diff --git a/.github/workflows/actions/test-monitor-process-results/action.yml b/.github/workflows/actions/test-monitor-process-results/action.yml index 7565e6ab20e..27bf377448f 100644 --- a/.github/workflows/actions/test-monitor-process-results/action.yml +++ b/.github/workflows/actions/test-monitor-process-results/action.yml @@ -42,13 +42,13 @@ runs: uses: 'google-github-actions/setup-gcloud@v2' - name: Upload results to BigQuery (skipped tests) - uses: nick-fields/retry@v3 + uses: nick-fields/retry@v4 with: timeout_minutes: 1 max_attempts: 3 command: bq load --source_format=NEWLINE_DELIMITED_JSON $BIGQUERY_DATASET.$BIGQUERY_TABLE $SKIPPED_TESTS_FILE tools/test_monitor/schemas/skipped_tests_schema.json - name: Upload results to BigQuery (test run) - uses: nick-fields/retry@v3 + uses: nick-fields/retry@v4 with: timeout_minutes: 2 max_attempts: 3 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 428168a4555..f86917bcdd0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,15 +8,18 @@ on: - trying - 'feature/**' - 'v[0-9]+.[0-9]+' + - 'v[0-9]+.[0-9]+-rc' pull_request: branches: - master* - 'auto-cadence-upgrade/**' - 'feature/**' - 'v[0-9]+.[0-9]+' + - 'v[0-9]+.[0-9]+-rc' merge_group: branches: - master + workflow_dispatch: env: GO_VERSION: "1.25" @@ -28,18 +31,18 @@ concurrency: jobs: build-linter: name: Build Custom Linter - runs-on: ubuntu-latest + runs-on: blacksmith-4vcpu-ubuntu-2404 steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} cache: true - name: Cache custom linter binary id: cache-linter - uses: actions/cache@v3 + uses: actions/cache@v5 with: # Key should change whenever implementation (tools/structwrite), or compilation config (.custom-gcl.yml) changes # When the key is different, it is a cache miss, and the custom linter binary is recompiled @@ -68,20 +71,25 @@ jobs: matrix: dir: [./, ./integration/, ./insecure/] name: Lint - runs-on: ubuntu-latest + runs-on: blacksmith-4vcpu-ubuntu-2404 needs: build-linter # must wait for custom linter binary to be available steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 + - name: Setup private build environment + if: ${{ vars.PRIVATE_BUILDS_SUPPORTED == 'true' }} + uses: ./actions/private-setup + with: + cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} cache: true - name: Restore custom linter binary from cache id: cache-linter - uses: actions/cache@v3 + uses: actions/cache@v5 with: # See "Cache custom linter binary" job for information about the key structure key: custom-linter-${{ env.GO_VERSION }}-${{ runner.os }}-${{ hashFiles('.custom-gcl.yml', 'tools/structwrite/**') }}-${{ github.sha }} @@ -114,10 +122,10 @@ jobs: tidy: name: Tidy - runs-on: ubuntu-latest + runs-on: blacksmith-4vcpu-ubuntu-2404 steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup private build environment if: ${{ vars.PRIVATE_BUILDS_SUPPORTED == 'true' }} @@ -126,7 +134,7 @@ jobs: cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} @@ -138,14 +146,14 @@ jobs: create-dynamic-test-matrix: name: Create Dynamic Test Matrix - runs-on: ubuntu-latest + runs-on: blacksmith-4vcpu-ubuntu-2404 outputs: dynamic-matrix: ${{ steps.set-test-matrix.outputs.dynamicMatrix }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} @@ -156,14 +164,14 @@ jobs: create-insecure-dynamic-test-matrix: name: Create Dynamic Unit Test Insecure Package Matrix - runs-on: ubuntu-latest + runs-on: blacksmith-4vcpu-ubuntu-2404 outputs: dynamic-matrix: ${{ steps.set-test-matrix.outputs.dynamicMatrix }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} @@ -174,14 +182,14 @@ jobs: create-integration-dynamic-test-matrix: name: Create Dynamic Integration Test Package Matrix - runs-on: ubuntu-latest + runs-on: blacksmith-4vcpu-ubuntu-2404 outputs: dynamic-matrix: ${{ steps.set-test-matrix.outputs.dynamicMatrix }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} @@ -201,7 +209,7 @@ jobs: runs-on: ${{ matrix.targets.runner }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup private build environment if: ${{ vars.PRIVATE_BUILDS_SUPPORTED == 'true' }} @@ -210,7 +218,7 @@ jobs: cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} @@ -218,7 +226,7 @@ jobs: - name: Setup tests (${{ matrix.targets.name }}) run: VERBOSE=1 make -e GO_TEST_PACKAGES="${{ matrix.targets.packages }}" install-tools - name: Run tests (${{ matrix.targets.name }}) - uses: nick-fields/retry@v3 + uses: nick-fields/retry@v4 with: timeout_minutes: 35 max_attempts: 5 @@ -247,7 +255,7 @@ jobs: runs-on: ${{ matrix.targets.runner }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup private build environment if: ${{ vars.PRIVATE_BUILDS_SUPPORTED == 'true' }} @@ -256,7 +264,7 @@ jobs: cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} @@ -264,7 +272,7 @@ jobs: - name: Setup tests (${{ matrix.targets.name }}) run: VERBOSE=1 make -e GO_TEST_PACKAGES="${{ matrix.targets.packages }}" install-tools - name: Run tests (${{ matrix.targets.name }}) - uses: nick-fields/retry@v3 + uses: nick-fields/retry@v4 with: timeout_minutes: 35 max_attempts: 5 @@ -284,12 +292,12 @@ jobs: docker-build: name: Docker Build - runs-on: buildjet-16vcpu-ubuntu-2204 + runs-on: blacksmith-16vcpu-ubuntu-2404 env: CADENCE_DEPLOY_KEY: ${{ secrets.CADENCE_DEPLOY_KEY }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: # all tags are needed for integration tests fetch-depth: 0 @@ -301,14 +309,14 @@ jobs: cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} cache: true - name: Login to Docker Hub - uses: docker/login-action@v3 + uses: docker/login-action@v4 with: username: ${{ vars.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} @@ -328,6 +336,7 @@ jobs: gcr.io/flow-container-registry/collection:latest \ gcr.io/flow-container-registry/consensus:latest \ gcr.io/flow-container-registry/execution:latest \ + gcr.io/flow-container-registry/execution-ledger:latest \ gcr.io/flow-container-registry/ghost:latest \ gcr.io/flow-container-registry/observer:latest \ gcr.io/flow-container-registry/verification:latest \ @@ -336,7 +345,7 @@ jobs: gcr.io/flow-container-registry/verification-corrupted:latest > flow-docker-images.tar - name: Cache Docker images - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: flow-docker-images.tar # use the workflow run id as part of the cache key to ensure these docker images will only be used for a single workflow run @@ -344,12 +353,12 @@ jobs: docker-build-cadence-vm: name: Docker Build (with Cadence VM) - runs-on: buildjet-16vcpu-ubuntu-2204 + runs-on: blacksmith-16vcpu-ubuntu-2404 env: CADENCE_DEPLOY_KEY: ${{ secrets.CADENCE_DEPLOY_KEY }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: # all tags are needed for integration tests fetch-depth: 0 @@ -361,14 +370,14 @@ jobs: cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} cache: true - name: Login to Docker Hub - uses: docker/login-action@v3 + uses: docker/login-action@v4 with: username: ${{ vars.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} @@ -388,6 +397,7 @@ jobs: gcr.io/flow-container-registry/collection:latest \ gcr.io/flow-container-registry/consensus:latest \ gcr.io/flow-container-registry/execution:latest \ + gcr.io/flow-container-registry/execution-ledger:latest \ gcr.io/flow-container-registry/ghost:latest \ gcr.io/flow-container-registry/observer:latest \ gcr.io/flow-container-registry/verification:latest \ @@ -396,7 +406,7 @@ jobs: gcr.io/flow-container-registry/verification-corrupted:latest > flow-docker-images.tar - name: Cache Docker images - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: flow-docker-images.tar # use the workflow run id as part of the cache key to ensure these docker images will only be used for a single workflow run @@ -414,7 +424,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup private build environment if: ${{ vars.PRIVATE_BUILDS_SUPPORTED == 'true' }} @@ -423,7 +433,7 @@ jobs: cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} @@ -431,7 +441,7 @@ jobs: - name: Setup tests (${{ matrix.targets.name }}) run: VERBOSE=1 make -e GO_TEST_PACKAGES="${{ matrix.targets.packages }}" install-tools - name: Run tests (${{ matrix.targets.name }}) - uses: nick-fields/retry@v3 + uses: nick-fields/retry@v4 with: timeout_minutes: 35 max_attempts: 5 @@ -460,92 +470,92 @@ jobs: include: - name: Access Cohort1 Integration Tests make: make -C integration access-cohort1-tests - runner: buildjet-4vcpu-ubuntu-2204 + runner: blacksmith-4vcpu-ubuntu-2404 - name: Access Cohort1 Integration Tests (Cadence VM) make: make -C integration access-cohort1-tests - runner: buildjet-4vcpu-ubuntu-2204 + runner: blacksmith-4vcpu-ubuntu-2404 cadence_vm: true - name: Access Cohort2 Integration Tests make: make -C integration access-cohort2-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Access Cohort3 Integration Tests make: make -C integration access-cohort3-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Access Cohort4 Integration Tests make: make -C integration access-cohort4-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 # test suite has single test which is flaky and needs to be fixed - reminder here to put it back when it's fixed # - name: BFT (Framework) Integration Tests # make: make -C integration bft-framework-tests -# runner: ubuntu-latest +# runner: blacksmith-4vcpu-ubuntu-2404 - name: BFT (Protocol) Integration Tests make: make -C integration bft-protocol-tests - runner: buildjet-8vcpu-ubuntu-2204 + runner: blacksmith-8vcpu-ubuntu-2404 - name: BFT (Gossipsub) Integration Tests make: make -C integration bft-gossipsub-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Collection Integration Tests make: make -C integration collection-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Consensus Integration Tests make: make -C integration consensus-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Epoch Cohort1 Integration Tests make: make -C integration epochs-cohort1-tests - runner: buildjet-8vcpu-ubuntu-2204 + runner: blacksmith-8vcpu-ubuntu-2404 - name: Epoch Cohort1 Integration Tests (Cadence VM) make: make -C integration epochs-cohort1-tests - runner: buildjet-8vcpu-ubuntu-2204 + runner: blacksmith-8vcpu-ubuntu-2404 cadence_vm: true - name: Epoch Cohort2 Integration Tests make: make -C integration epochs-cohort2-tests - runner: buildjet-4vcpu-ubuntu-2204 + runner: blacksmith-4vcpu-ubuntu-2404 - name: Epoch Cohort2 Integration Tests (Cadence VM) make: make -C integration epochs-cohort2-tests - runner: buildjet-4vcpu-ubuntu-2204 + runner: blacksmith-4vcpu-ubuntu-2404 cadence_vm: true - name: Execution Integration Tests make: make -C integration execution-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Execution Integration Tests (Cadence VM) make: make -C integration execution-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 cadence_vm: true - name: Ghost Integration Tests make: make -C integration ghost-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Ghost Integration Tests (Cadence VM) make: make -C integration ghost-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 cadence_vm: true - name: MVP Integration Tests make: make -C integration mvp-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: MVP Integration Tests (Cadence VM) make: make -C integration mvp-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 cadence_vm: true - name: Network Integration Tests make: make -C integration network-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Verification Integration Tests make: make -C integration verification-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Verification Integration Tests (Cadence VM) make: make -C integration verification-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 cadence_vm: true - name: Upgrade Integration Tests make: make -C integration upgrades-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 - name: Upgrade Integration Tests (Cadence VM) make: make -C integration upgrades-tests - runner: ubuntu-latest + runner: blacksmith-4vcpu-ubuntu-2404 cadence_vm: true runs-on: ${{ matrix.runner }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: # all tags are needed for integration tests fetch-depth: 0 @@ -557,13 +567,13 @@ jobs: cadence_deploy_key: ${{ secrets.CADENCE_DEPLOY_KEY }} - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 timeout-minutes: 10 # fail fast. sometimes this step takes an extremely long time with: go-version: ${{ env.GO_VERSION }} cache: true - name: Load cached Docker images - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: flow-docker-images.tar # use the same cache key as the docker-build / docker-build-cadence-vm job @@ -574,7 +584,7 @@ jobs: # TODO(rbtz): re-enable when we fix exisiting races. #env: # RACE_DETECTOR: 1 - uses: nick-fields/retry@v3 + uses: nick-fields/retry@v4 with: timeout_minutes: 35 max_attempts: 5 diff --git a/.github/workflows/code-analysis.yml b/.github/workflows/code-analysis.yml index 424d7c78e98..36ea098039f 100644 --- a/.github/workflows/code-analysis.yml +++ b/.github/workflows/code-analysis.yml @@ -28,10 +28,10 @@ jobs: languages: ['go'] steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v6 with: go-version-file: ./go.mod @@ -43,7 +43,7 @@ jobs: - name: Initialize CodeQL - uses: github/codeql-action/init@v3 + uses: github/codeql-action/init@v4 with: languages: ${{ matrix.languages}} queries: security-extended @@ -52,7 +52,7 @@ jobs: run: CGO_ENABLED=0 go build -mod=vendor -tags=no_cgo ./... - name: CodeQL Analyze - uses: github/codeql-action/analyze@v3 + uses: github/codeql-action/analyze@v4 with: category: "/language:${{ matrix.languages}}" - # need org username and pat to access private libraries \ No newline at end of file + # need org username and pat to access private libraries diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index e622aba1221..f1f369f7c40 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -10,6 +10,11 @@ on: pull_request: branches: ["master"] +# Until actions/dependency-review-action ships node24 in action.yml, opt in per GitHub guidance: +# https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/ +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + permissions: contents: read pull-requests: write # Required for PR comments @@ -21,7 +26,7 @@ jobs: vulnerable-changes: ${{ steps.review.outputs.vulnerable-changes }} steps: - name: "Checkout repository" - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: "Dependency Review" id: review uses: actions/dependency-review-action@v4 @@ -36,7 +41,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Add PR Comment - uses: actions/github-script@v7 + uses: actions/github-script@v8 env: VULN_OUTPUT: ${{ needs.dependency-review.outputs.vulnerable-changes }} with: @@ -72,4 +77,4 @@ jobs: } catch (error) { console.error('Error processing vulnerability data:', error); throw error; - } \ No newline at end of file + } diff --git a/.github/workflows/flaky-test-monitor.yml b/.github/workflows/flaky-test-monitor.yml index 627762e4395..329342608ae 100644 --- a/.github/workflows/flaky-test-monitor.yml +++ b/.github/workflows/flaky-test-monitor.yml @@ -37,9 +37,9 @@ jobs: dynamic-matrix: ${{ steps.set-test-matrix.outputs.dynamicMatrix }} steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} cache: true @@ -58,9 +58,9 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} cache: true @@ -100,9 +100,9 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} cache: true @@ -160,12 +160,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: # all tags are needed for integration tests fetch-depth: 0 - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} cache: true diff --git a/.github/workflows/image_builds.yml b/.github/workflows/image_builds.yml index 782d5d60976..e683caab46e 100644 --- a/.github/workflows/image_builds.yml +++ b/.github/workflows/image_builds.yml @@ -1,4 +1,4 @@ -name: Build & Promote Docker Images to Public Registry +name: Build & Promote Docker Images to Public Registry on: workflow_dispatch: inputs: @@ -25,69 +25,75 @@ jobs: # The environment is set to 'container builds' that provides the necessary secrets for pushing to the pirvate registry. public-build: if: ${{ github.event.inputs.secure-build == 'false' }} - name: Execute public repo build & push to private artifact registry + name: Execute public repo build & push to private artifact registry runs-on: ubuntu-latest strategy: fail-fast: false matrix: - # We specify all of the potential build commands for each role. + # We specify all of the potential build commands for each role. # This allows us to build and push all images in parallel, reducing the overall build time. # The matrix is defined to include all roles & image types that we want to build and push. # These commands are targets defined in the Makefile of the repository. build_command: # access Build Commands - - docker-build-access-with-adx docker-push-access-with-adx - - docker-build-access-without-adx docker-push-access-without-adx - - docker-build-access-without-netgo-without-adx docker-push-access-without-netgo-without-adx - - docker-cross-build-access-arm docker-push-access-arm + - docker-build-access-with-adx docker-push-access-with-adx + - docker-build-access-without-adx docker-push-access-without-adx + - docker-build-access-without-netgo-without-adx docker-push-access-without-netgo-without-adx + - docker-cross-build-access-arm docker-push-access-arm # collection Build Commands - - docker-build-collection-with-adx docker-push-collection-with-adx - - docker-build-collection-without-adx docker-push-collection-without-adx - - docker-build-collection-without-netgo-without-adx docker-push-collection-without-netgo-without-adx - - docker-cross-build-collection-arm docker-push-collection-arm + - docker-build-collection-with-adx docker-push-collection-with-adx + - docker-build-collection-without-adx docker-push-collection-without-adx + - docker-build-collection-without-netgo-without-adx docker-push-collection-without-netgo-without-adx + - docker-cross-build-collection-arm docker-push-collection-arm # consensus Build Commands - - docker-build-consensus-with-adx docker-push-consensus-with-adx - - docker-build-consensus-without-adx docker-push-consensus-without-adx - - docker-build-consensus-without-netgo-without-adx docker-push-consensus-without-netgo-without-adx - - docker-cross-build-consensus-arm docker-push-consensus-arm + - docker-build-consensus-with-adx docker-push-consensus-with-adx + - docker-build-consensus-without-adx docker-push-consensus-without-adx + - docker-build-consensus-without-netgo-without-adx docker-push-consensus-without-netgo-without-adx + - docker-cross-build-consensus-arm docker-push-consensus-arm # execution Build Commands - - docker-build-execution-with-adx docker-push-execution-with-adx - - docker-build-execution-without-adx docker-push-execution-without-adx - - docker-build-execution-without-netgo-without-adx docker-push-execution-without-netgo-without-adx - - docker-cross-build-execution-arm docker-push-execution-arm + - docker-build-execution-with-adx docker-push-execution-with-adx + - docker-build-execution-without-adx docker-push-execution-without-adx + - docker-build-execution-without-netgo-without-adx docker-push-execution-without-netgo-without-adx + - docker-cross-build-execution-arm docker-push-execution-arm - docker-build-execution-cadence-vm docker-push-execution-cadence-vm + # execution Ledger Service Build Commands + - docker-build-execution-ledger-with-adx docker-push-execution-ledger-with-adx + - docker-build-execution-ledger-without-adx docker-push-execution-ledger-without-adx + - docker-build-execution-ledger-without-netgo-without-adx docker-push-execution-ledger-without-netgo-without-adx + - docker-cross-build-execution-ledger-arm docker-push-execution-ledger-arm + # observer Build Commands - - docker-build-observer-with-adx docker-push-observer-with-adx - - docker-build-observer-without-adx docker-push-observer-without-adx - - docker-build-observer-without-netgo-without-adx docker-push-observer-without-netgo-without-adx - - docker-cross-build-observer-arm docker-push-observer-arm + - docker-build-observer-with-adx docker-push-observer-with-adx + - docker-build-observer-without-adx docker-push-observer-without-adx + - docker-build-observer-without-netgo-without-adx docker-push-observer-without-netgo-without-adx + - docker-cross-build-observer-arm docker-push-observer-arm # verification Build Commands - - docker-build-verification-with-adx docker-push-verification-with-adx - - docker-build-verification-without-adx docker-push-verification-without-adx - - docker-build-verification-without-netgo-without-adx docker-push-verification-without-netgo-without-adx - - docker-cross-build-verification-arm docker-push-verification-arm + - docker-build-verification-with-adx docker-push-verification-with-adx + - docker-build-verification-without-adx docker-push-verification-without-adx + - docker-build-verification-without-netgo-without-adx docker-push-verification-without-netgo-without-adx + - docker-cross-build-verification-arm docker-push-verification-arm - environment: container builds + environment: container builds steps: - name: Setup Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} - name: Checkout Public flow-go repo - uses: actions/checkout@v3 + uses: actions/checkout@v6 with: fetch-depth: 0 repository: onflow/flow-go ref: ${{ inputs.tag }} - name: Authenticate with Docker Registry - uses: google-github-actions/auth@v1 + uses: google-github-actions/auth@v3 with: credentials_json: ${{ secrets.GCP_CREDENTIALS_FOR_PRIVATE_REGISTRY }} @@ -95,7 +101,7 @@ jobs: run: gcloud auth configure-docker ${{ env.PRIVATE_REGISTRY_HOST }} - name: Login to Docker Hub - uses: docker/login-action@v3 + uses: docker/login-action@v4 with: username: ${{ vars.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} @@ -112,7 +118,8 @@ jobs: # It uses a matrix strategy to handle the builds for different roles in parallel. # The environment is set to 'secure builds' to ensure that the builds are gated and only approved images are deployed. # The job is triggered only if the 'secure-build' input is set to 'true'. - # The job uses an action to execute a cross-repo workflow that builds and pushes the images to the private registry. + # max-parallel: 1 ensures each role gets the correct run ID (avoids wrong run mapping when polling). + # Set vars.SECURE_BUILDS_REPO (e.g. flow-go-internal) for unmasked run links in logs. name: Execute secure build & push to private registry runs-on: ubuntu-latest if: ${{ github.event.inputs.secure-build == 'true' }} @@ -120,7 +127,7 @@ jobs: fail-fast: false matrix: role: [access, collection, consensus, execution, observer, verification] - environment: secure builds + environment: secure builds steps: - uses: actions/create-github-app-token@v2 id: app-token @@ -129,15 +136,21 @@ jobs: private-key: ${{ secrets.DEPLOYMENT_APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} - - uses: convictional/trigger-workflow-and-wait@v1.6.1 + - uses: convictional/trigger-workflow-and-wait@v1.6.5 + id: trigger-secure-build with: client_payload: '{"role": "${{ matrix.role }}", "tag": "${{ inputs.tag }}"}' github_token: ${{ steps.app-token.outputs.token }} owner: 'onflow' - repo: ${{ secrets.SECURE_BUILDS_REPO }} - ref: master-private + repo: ${{ secrets.SECURE_BUILDS_REPO }} + ref: master-private workflow_file_name: 'secure_build.yml' + - name: Print secure build run URL + run: | + REPO="${{ vars.SECURE_BUILDS_REPO || 'flow-go-internal' }}" + echo "Secure build for ${{ matrix.role }}: https://github.com/onflow/${REPO}/actions/runs/${{ steps.trigger-secure-build.outputs.workflow_id }}" + promote-to-partner-registry: # This job promotes container images from the private registry to the partner registry. # As of right now, the only role being promoted to the partner registry is 'access'. @@ -156,19 +169,19 @@ jobs: fail-fast: false matrix: role: [access] - environment: ${{ matrix.role }} image promotion to partner registry + environment: ${{ matrix.role }} image promotion to partner registry steps: - name: Checkout repo - uses: actions/checkout@v3 + uses: actions/checkout@v6 - - name: Promote ${{ matrix.role }} + - name: Promote ${{ matrix.role }} uses: ./actions/promote-images with: gcp_credentials: ${{ secrets.PARTNER_REGISTRY_PROMOTION_SECRET }} private_registry: ${{ vars.PRIVATE_REGISTRY }} private_registry_host: ${{ env.PRIVATE_REGISTRY_HOST }} promotion_registry: ${{ vars.PARTNER_REGISTRY }} - role: ${{ matrix.role }} + role: ${{ matrix.role }} tags: "${{ inputs.tag }},${{ inputs.tag }}-without-adx,${{ inputs.tag }}-without-netgo-without-adx,${{ inputs.tag }}-arm" promote-to-public-registry: @@ -188,18 +201,18 @@ jobs: fail-fast: false matrix: role: [access, collection, consensus, execution, observer, verification] - environment: ${{ matrix.role }} image promotion to public registry + environment: ${{ matrix.role }} image promotion to public registry steps: - name: Checkout repo - uses: actions/checkout@v3 + uses: actions/checkout@v6 - - name: Promote ${{ matrix.role }} + - name: Promote ${{ matrix.role }} uses: ./actions/promote-images with: gcp_credentials: ${{ secrets.PUBLIC_REGISTRY_PROMOTION_SECRET }} private_registry: ${{ vars.PRIVATE_REGISTRY }} private_registry_host: ${{ env.PRIVATE_REGISTRY_HOST }} promotion_registry: ${{ vars.PUBLIC_REGISTRY }} - role: ${{ matrix.role }} + role: ${{ matrix.role }} tags: "${{ inputs.tag }},${{ inputs.tag }}-without-adx,${{ inputs.tag }}-without-netgo-without-adx,${{ inputs.tag }}-arm" diff --git a/.github/workflows/tools.yml b/.github/workflows/tools.yml index 9bca236ceda..84e1d947224 100644 --- a/.github/workflows/tools.yml +++ b/.github/workflows/tools.yml @@ -24,19 +24,19 @@ jobs: - name: Print all input variables run: echo '${{ toJson(inputs) }}' | jq - id: auth - uses: google-github-actions/auth@v1 + uses: google-github-actions/auth@v3 with: credentials_json: ${{ secrets.GCR_SERVICE_KEY }} - name: Set up Google Cloud SDK - uses: google-github-actions/setup-gcloud@v1 + uses: google-github-actions/setup-gcloud@v3 with: project_id: flow - name: Setup Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version: ${{ env.GO_VERSION }} - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: # to accurately get the version tag fetch-depth: 0 diff --git a/.gitignore b/.gitignore index f1a940e2ecc..6dee1dfe72f 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,9 @@ flowdb .idea .vscode *.code-workspace +*.worktrees +.claude/ +.local/ # ignore all files in the .cursor directory, except for the rules directory .cursor/* !.cursor/rules/ @@ -81,3 +84,4 @@ tps-results*.json # Custom golangcilint build custom-gcl tools/custom-gcl +ai-notes/ diff --git a/.mockery.yaml b/.mockery.yaml index f72ddd9c450..cb63adb9d83 100644 --- a/.mockery.yaml +++ b/.mockery.yaml @@ -1,113 +1,91 @@ -dir: "{{.InterfaceDir}}/mock" -outpkg: "mock" -filename: "{{.InterfaceName | snakecase}}.go" -mockname: "{{.InterfaceName}}" - -all: True -with-expecter: False -include-auto-generated: False -disable-func-mocks: True -fail-on-missing: True - -# Suppress warnings -issue-845-fix: True -disable-version-string: True -resolve-type-alias: False - +all: true +dir: '{{.InterfaceDir}}/mock' +structname: '{{.InterfaceName}}' +pkgname: mock +filename: '{{.InterfaceName | snakecase}}.go' +template: testify +template-data: + unroll-variadic: true packages: + github.com/onflow/flow-go-sdk/access: + config: + dir: integration/benchmark/mock + interfaces: + Client: { } github.com/onflow/flow-go/access: + github.com/onflow/flow-go/access/backends/extended: github.com/onflow/flow-go/access/validator: - github.com/onflow/flow-go/cmd/util/ledger/reporters: + config: + all: true github.com/onflow/flow-go/consensus/hotstuff: config: - dir: "consensus/hotstuff/mocks" - outpkg: "mocks" - github.com/onflow/flow-go/engine/access/ingestion/collections: - github.com/onflow/flow-go/engine/access/ingestion/tx_error_messages: - github.com/onflow/flow-go/engine/access/rest/common/models: - github.com/onflow/flow-go/engine/access/rest/websockets: - github.com/onflow/flow-go/engine/access/rest/websockets/data_providers: - github.com/onflow/flow-go/engine/access/rpc/backend/accounts/provider: - github.com/onflow/flow-go/engine/access/rpc/backend/events/provider: - github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator: - github.com/onflow/flow-go/engine/access/rpc/backend/transactions/error_messages: - github.com/onflow/flow-go/engine/access/rpc/backend/transactions/provider: - github.com/onflow/flow-go/engine/access/rpc/connection: - github.com/onflow/flow-go/engine/access/state_stream: - github.com/onflow/flow-go/engine/access/subscription: - github.com/onflow/flow-go/engine/access/subscription/tracker: + dir: consensus/hotstuff/mocks + pkgname: mocks + github.com/onflow/flow-go/engine/access/ingestion/collections: { } + github.com/onflow/flow-go/engine/access/ingestion/tx_error_messages: { } + github.com/onflow/flow-go/engine/access/rest/common/models: { } + github.com/onflow/flow-go/engine/access/rest/websockets: { } + github.com/onflow/flow-go/engine/access/rest/websockets/data_providers: { } + github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator: { } + github.com/onflow/flow-go/engine/access/rpc/backend/transactions/provider: { } + github.com/onflow/flow-go/engine/access/state_stream: { } + github.com/onflow/flow-go/engine/access/subscription: { } + github.com/onflow/flow-go/engine/access/subscription/tracker: { } github.com/onflow/flow-go/engine/access/wrapper: config: - dir: "engine/access/mock" - github.com/onflow/flow-go/engine/collection: - github.com/onflow/flow-go/engine/collection/epochmgr: - github.com/onflow/flow-go/engine/collection/rpc: + dir: engine/access/mock + github.com/onflow/flow-go/engine/collection: { } + github.com/onflow/flow-go/engine/collection/epochmgr: { } + github.com/onflow/flow-go/engine/collection/rpc: { } github.com/onflow/flow-go/engine/common/follower: interfaces: complianceCore: config: - exported: true - mockname: "{{.InterfaceName | firstUpper}}" - github.com/onflow/flow-go/engine/common/follower/cache: - github.com/onflow/flow-go/engine/consensus: - github.com/onflow/flow-go/engine/consensus/approvals: - github.com/onflow/flow-go/engine/execution: - github.com/onflow/flow-go/engine/execution/computation: - github.com/onflow/flow-go/engine/execution/computation/computer: - github.com/onflow/flow-go/engine/execution/computation/query: - github.com/onflow/flow-go/engine/execution/ingestion/uploader: - github.com/onflow/flow-go/engine/execution/provider: - github.com/onflow/flow-go/engine/execution/state: - github.com/onflow/flow-go/engine/protocol: - github.com/onflow/flow-go/engine/verification/fetcher: - github.com/onflow/flow-go/fvm: - github.com/onflow/flow-go/fvm/environment: - github.com/onflow/flow-go/fvm/storage/snapshot: - github.com/onflow/flow-go/insecure: - github.com/onflow/flow-go/ledger: - github.com/onflow/flow-go/model/fingerprint: - github.com/onflow/flow-go/module: - github.com/onflow/flow-go/module/component: - github.com/onflow/flow-go/module/execution: - github.com/onflow/flow-go/module/executiondatasync/execution_data: + structname: '{{.InterfaceName | firstUpper}}' + github.com/onflow/flow-go/engine/common/follower/cache: { } + github.com/onflow/flow-go/engine/consensus: { } + github.com/onflow/flow-go/engine/execution: { } + github.com/onflow/flow-go/engine/execution/computation/computer: { } + github.com/onflow/flow-go/engine/execution/ingestion/uploader: { } + github.com/onflow/flow-go/engine/execution/state: { } + github.com/onflow/flow-go/engine/verification/fetcher: { } + github.com/onflow/flow-go/fvm: { } + github.com/onflow/flow-go/fvm/environment: { } + github.com/onflow/flow-go/fvm/storage/snapshot: { } + github.com/onflow/flow-go/ledger: { } + github.com/onflow/flow-go/model/fingerprint: { } + github.com/onflow/flow-go/module: { } + github.com/onflow/flow-go/module/component: { } + github.com/onflow/flow-go/module/execution: { } + github.com/onflow/flow-go/module/executiondatasync/execution_data: { } github.com/onflow/flow-go/module/executiondatasync/optimistic_sync: config: - all: False + all: false interfaces: - Core: - github.com/onflow/flow-go/module/executiondatasync/tracker: - github.com/onflow/flow-go/module/forest: - github.com/onflow/flow-go/module/mempool: + Core: { } + github.com/onflow/flow-go/module/executiondatasync/tracker: { } + github.com/onflow/flow-go/module/forest: { } + github.com/onflow/flow-go/module/mempool: { } github.com/onflow/flow-go/module/mempool/consensus/mock_interfaces: config: - dir: "module/mempool/consensus/mock" - github.com/onflow/flow-go/module/state_synchronization: - github.com/onflow/flow-go/module/state_synchronization/requester: - github.com/onflow/flow-go/network: - github.com/onflow/flow-go/network/alsp: - github.com/onflow/flow-go/network/p2p: - github.com/onflow/flow-go/state/cluster: - github.com/onflow/flow-go/state/protocol: - github.com/onflow/flow-go/state/protocol/events: - github.com/onflow/flow-go/state/protocol/protocol_state: - github.com/onflow/flow-go/state/protocol/protocol_state/mock_interfaces: - config: - dir: "state/protocol/protocol_state/mock" - github.com/onflow/flow-go/state/protocol/protocol_state/epochs: - github.com/onflow/flow-go/state/protocol/protocol_state/epochs/mock_interfaces: - config: - dir: "state/protocol/protocol_state/epochs/mock" - github.com/onflow/flow-go/storage: - - # external libraries - github.com/onflow/flow-go-sdk/access: - config: - dir: "integration/benchmark/mock" - interfaces: - Client: - + dir: module/mempool/consensus/mock + github.com/onflow/flow-go/module/state_synchronization: { } + github.com/onflow/flow-go/module/state_synchronization/indexer/extended: { } + github.com/onflow/flow-go/module/state_synchronization/requester: { } github.com/onflow/crypto: config: - dir: "module/mock" + dir: module/mock + filename: crypto_mocks.go interfaces: - PublicKey: + PublicKey: { } + github.com/onflow/flow-go/network: { } + github.com/onflow/flow-go/network/alsp: { } + github.com/onflow/flow-go/network/p2p: { } + github.com/onflow/flow-go/state/cluster: { } + github.com/onflow/flow-go/state/protocol: { } + github.com/onflow/flow-go/state/protocol/events: { } + github.com/onflow/flow-go/state/protocol/protocol_state: { } + github.com/onflow/flow-go/state/protocol/protocol_state/mock_interfaces: { } + github.com/onflow/flow-go/state/protocol/protocol_state/epochs: { } + github.com/onflow/flow-go/state/protocol/protocol_state/epochs/mock_interfaces: { } + github.com/onflow/flow-go/storage: { } diff --git a/AGENTS.md b/AGENTS.md index 466257e0103..8727f8850c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,8 +32,8 @@ This file provides guidance to AI Agents when working with code in this reposito - Include a note that the message was produced in collaboration with [your agent name - e.g. claude, gemini, cursor, etc]. ### Answering Questions -- When asked a question, consider the answer and perform any exploration of the codebase required to provide quality answer. -- DO NOT attempt to write or modify code. Simply answer the question. +- When asked a question, consider the answer and perform any exploration of the codebase required to provide a quality answer. +- When asked a question, do not write or modify code. Simply answer the question. ### Communication - Be direct and straight forward. @@ -74,6 +74,10 @@ This file provides guidance to AI Agents when working with code in this reposito Flow is a multi-node blockchain protocol implementing a byzantine fault-tolerant consensus mechanism. The architecture follows a data flow graph pattern where components are processing vertices connected by message-passing edges. +Note: this repo includes 2 go modules: +- `/`: this is the main module `github.com/onflow/flow-go` +- `integration/`: this is a separate module for integration tests `github.com/onflow/flow-go/integration` + ### Node Types - **Access Node** (`/cmd/access/`) - Public API gateway, transaction submission and execution - **Collection Node** (`/cmd/collection/`) - Transaction batching into collections @@ -82,6 +86,14 @@ Flow is a multi-node blockchain protocol implementing a byzantine fault-tolerant - **Verification Node** (`/cmd/verification/`) - Execution result verification - **Observer Node** (`/cmd/observer/`) - Read-only network participant +Abbreviations: +- **AN**: Access Node +- **LN**: Collection Node +- **SN**: Consensus Node +- **EN**: Execution Node +- **VN**: Verification Node +- **ON**: Observer Node + ### Core Components #### Consensus (HotStuff/Jolteon) @@ -166,4 +178,14 @@ Flow uses a high-assurance approach where: - Network messages must be authenticated and validated - State consistency is paramount - use proper synchronization primitives -This codebase implements a production blockchain protocol with high security and performance requirements. Changes should be made carefully with thorough testing and consideration of byzantine failure modes.z \ No newline at end of file +This codebase implements a production blockchain protocol with high security and performance requirements. Changes should be made carefully with thorough testing and consideration of byzantine failure modes. + +## Relevant External Repos + +Flow Protobuf: https://github.com/onflow/flow/protobuf/go/flow +OpenAPI Specs: https://github.com/onflow/flow/openapi +Flow SDK: https://github.com/onflow/flow-go-sdk +Flow Core Contracts: https://github.com/onflow/flow-core-contracts +FungibleToken Contracts: https://github.com/onflow/flow-ft +NonFungibleToken Contracts: https://github.com/onflow/flow-nft +Cadence: https://github.com/onflow/cadence diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000000..2450db7dcff --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +Release notes and version history for flow-go are tracked via GitHub Releases: + +- https://github.com/onflow/flow-go/releases + +For user-facing changes per version, see the Releases page. Each release page contains the tag, release notes, and links to the associated commits and milestones. diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 00000000000..7ffe41e5462 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,25 @@ +cff-version: 1.2.0 +message: "If you use flow-go in your research or reference it in a publication, please cite it as below." +title: "flow-go: Flow Network Reference Implementation in Go" +abstract: "flow-go is the Go reference implementation of the Flow network, a Layer 1 proof-of-stake blockchain. It implements HotStuff consensus, a multi-role node architecture (Access, Collection, Consensus, Execution, Verification), the Flow Virtual Machine, ledger, networking, and cryptography subsystems." +authors: + - name: "Flow Foundation" + website: "https://flow.com" +repository-code: "https://github.com/onflow/flow-go" +url: "https://flow.com" +license: AGPL-3.0-only +type: software +keywords: + - flow + - flow-network + - blockchain + - layer-1 + - proof-of-stake + - consensus + - hotstuff + - byzantine-fault-tolerance + - cadence + - smart-contracts + - reference-implementation + - distributed-systems + - go diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d7c51008df6..6aa00c5fcd3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -109,17 +109,11 @@ following when creating your pull request: A reviewer will be assigned automatically when your PR is created. -We use [bors](https://github.com/bors-ng/bors-ng) merge bot to ensure that the `master` branch never breaks. -Once a PR is approved, you can comment on it with the following to add your PR to the merge queue: +We use GitHub Actions to ensure that the `master` branch never breaks. +Once a PR is approved and CI passes, you can add it to the merge queue. +If the PR fails in the merge queue, you will need to fix it and try again. -``` -bors merge -``` - -If the PR passes CI, it will automatically be pushed to the `master` branch. If it fails, bors will comment -on the PR so you can fix it. - -See the [documentation](https://bors.tech/documentation/) for a more comprehensive list of bors commands. +See GitHub's [merge queue documentation](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-a-merge-queue) for more details. ## Style Guide diff --git a/Makefile b/Makefile index 5872a4244ad..727924d4dd2 100644 --- a/Makefile +++ b/Makefile @@ -34,9 +34,6 @@ UNAME := $(shell uname) # Used when building within docker GOARCH := $(shell go env GOARCH) -# The location of the k8s YAML files -K8S_YAMLS_LOCATION_STAGING=./k8s/staging - # docker container registry export CONTAINER_REGISTRY := gcr.io/flow-container-registry export DOCKER_BUILDKIT := 1 @@ -84,7 +81,7 @@ unittest-main: .PHONY: install-mock-generators install-mock-generators: cd ${GOPATH}; \ - go install github.com/vektra/mockery/v2@v2.53.5; + go install github.com/vektra/mockery/v3@v3.6.1; .PHONY: install-tools install-tools: check-go-version install-mock-generators @@ -112,8 +109,15 @@ go-math-rand-check: echo "[Error] Go production code should not use math/rand package"; exit 1; \ fi +.SILENT: go-fix +go-fix: + # fix go code style issues + go fix ./... + git diff --exit-code + + .PHONY: code-sanity-check -code-sanity-check: go-math-rand-check +code-sanity-check: go-fix go-math-rand-check .PHONY: fuzz-fvm fuzz-fvm: @@ -152,7 +156,7 @@ generate: generate-proto generate-mocks generate-fvm-env-wrappers .PHONY: generate-proto generate-proto: - prototool generate protobuf + cd ledger/protobuf && buf generate .PHONY: generate-fvm-env-wrappers generate-fvm-env-wrappers: @@ -160,8 +164,7 @@ generate-fvm-env-wrappers: .PHONY: generate-mocks generate-mocks: install-mock-generators - mockery --config .mockery.yaml - cd insecure; mockery --config .mockery.yaml + mockery --config .mockery.yaml --log-level warn # this ensures there is no unused dependency being added by accident .PHONY: tidy @@ -174,11 +177,10 @@ tidy: # Builds a custom version of the golangci-lint binary which includes custom plugins tools/custom-gcl: tools/structwrite .custom-gcl.yml - golangci-lint custom + $(shell go env GOPATH)/bin/golangci-lint custom .PHONY: lint lint: tools/custom-gcl - # revive -config revive.toml -exclude storage/ledger/trie ./... ./tools/custom-gcl run -v $(or $(LINT_PATH),./...) .PHONY: lint-new @@ -187,7 +189,6 @@ lint-new: tools/custom-gcl .PHONY: fix-lint fix-lint: tools/custom-gcl - # revive -config revive.toml -exclude storage/ledger/trie ./... ./tools/custom-gcl run -v --fix $(or $(LINT_PATH),./...) .PHONY: fix-lint-new @@ -387,6 +388,42 @@ docker-cross-build-execution-arm: --label "git_commit=${COMMIT}" --label "git_tag=${IMAGE_TAG_ARM}" \ -t "$(CONTAINER_REGISTRY)/execution:$(IMAGE_TAG_ARM)" . +.PHONY: docker-build-execution-ledger-with-adx +docker-build-execution-ledger-with-adx: + docker build -f cmd/Dockerfile --build-arg TARGET=./cmd/ledger --build-arg COMMIT=$(COMMIT) --build-arg VERSION=$(IMAGE_TAG) --build-arg GOARCH=amd64 --target production \ + --secret id=cadence_deploy_key,env=CADENCE_DEPLOY_KEY --build-arg GOPRIVATE=$(GOPRIVATE) \ + --label "git_commit=${COMMIT}" --label "git_tag=$(IMAGE_TAG)" \ + -t "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG)" . + +.PHONY: docker-build-execution-ledger-without-adx +docker-build-execution-ledger-without-adx: + docker build -f cmd/Dockerfile --build-arg TARGET=./cmd/ledger --build-arg COMMIT=$(COMMIT) --build-arg VERSION=$(IMAGE_TAG_NO_ADX) --build-arg GOARCH=amd64 --build-arg CGO_FLAG=$(DISABLE_ADX) --target production \ + --secret id=cadence_deploy_key,env=CADENCE_DEPLOY_KEY --build-arg GOPRIVATE=$(GOPRIVATE) \ + --label "git_commit=${COMMIT}" --label "git_tag=$(IMAGE_TAG_NO_ADX)" \ + -t "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG_NO_ADX)" . + +.PHONY: docker-build-execution-ledger-without-netgo-without-adx +docker-build-execution-ledger-without-netgo-without-adx: + docker build -f cmd/Dockerfile --build-arg TARGET=./cmd/ledger --build-arg COMMIT=$(COMMIT) --build-arg VERSION=$(IMAGE_TAG_NO_NETGO_NO_ADX) --build-arg GOARCH=amd64 --build-arg TAGS="" --build-arg CGO_FLAG=$(DISABLE_ADX) --target production \ + --secret id=cadence_deploy_key,env=CADENCE_DEPLOY_KEY --build-arg GOPRIVATE=$(GOPRIVATE) \ + --label "git_commit=${COMMIT}" --label "git_tag=$(IMAGE_TAG_NO_NETGO_NO_ADX)" \ + -t "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG_NO_NETGO_NO_ADX)" . + +.PHONY: docker-cross-build-execution-ledger-arm +docker-cross-build-execution-ledger-arm: + docker build -f cmd/Dockerfile --build-arg TARGET=./cmd/ledger --build-arg COMMIT=$(COMMIT) --build-arg VERSION=$(IMAGE_TAG_ARM) --build-arg GOARCH=arm64 --build-arg CC=aarch64-linux-gnu-gcc --target production \ + --secret id=cadence_deploy_key,env=CADENCE_DEPLOY_KEY --build-arg GOPRIVATE=$(GOPRIVATE) \ + --label "git_commit=${COMMIT}" --label "git_tag=${IMAGE_TAG_ARM}" \ + -t "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG_ARM)" . + +.PHONY: docker-native-build-execution-ledger +docker-native-build-execution-ledger: + docker build -f cmd/Dockerfile --build-arg TARGET=./cmd/ledger --build-arg COMMIT=$(COMMIT) --build-arg VERSION=$(IMAGE_TAG) --build-arg GOARCH=$(GOARCH) --build-arg CGO_FLAG=$(CRYPTO_FLAG) --target production \ + --secret id=cadence_deploy_key,env=CADENCE_DEPLOY_KEY --build-arg GOPRIVATE=$(GOPRIVATE) \ + --label "git_commit=${COMMIT}" --label "git_tag=${IMAGE_TAG}" \ + -t "$(CONTAINER_REGISTRY)/execution-ledger:latest" \ + -t "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG)" . + .PHONY: docker-native-build-execution-debug docker-native-build-execution-debug: docker build -f cmd/Dockerfile --build-arg TARGET=./cmd/execution --build-arg COMMIT=$(COMMIT) --build-arg CADENCE_VM_TAG=$(CADENCE_VM_TAG) --build-arg VERSION=$(IMAGE_TAG) --build-arg GOARCH=$(GOARCH) --build-arg CGO_FLAG=$(CRYPTO_FLAG) --target debug \ @@ -574,7 +611,7 @@ docker-native-build-ghost-debug: -t "$(CONTAINER_REGISTRY)/ghost-debug:latest" \ -t "$(CONTAINER_REGISTRY)/ghost-debug:$(IMAGE_TAG)" . -PHONY: docker-build-bootstrap +.PHONY: docker-build-bootstrap docker-build-bootstrap: docker build -f cmd/Dockerfile --build-arg TARGET=./cmd/bootstrap --build-arg GOARCH=$(GOARCH) --build-arg VERSION=$(IMAGE_TAG) --build-arg CGO_FLAG=$(CRYPTO_FLAG) --target production \ --secret id=cadence_deploy_key,env=CADENCE_DEPLOY_KEY \ @@ -606,7 +643,7 @@ docker-native-build-loader: -t "$(CONTAINER_REGISTRY)/loader:$(IMAGE_TAG)" . .PHONY: docker-native-build-flow -docker-native-build-flow: docker-native-build-collection docker-native-build-consensus docker-native-build-execution docker-native-build-verification docker-native-build-access docker-native-build-observer docker-native-build-ghost +docker-native-build-flow: docker-native-build-collection docker-native-build-consensus docker-native-build-execution docker-native-build-execution-ledger docker-native-build-verification docker-native-build-access docker-native-build-observer docker-native-build-ghost .PHONY: docker-build-flow-with-adx docker-build-flow-with-adx: docker-build-collection-with-adx docker-build-consensus-with-adx docker-build-execution-with-adx docker-build-verification-with-adx docker-build-access-with-adx docker-build-observer-with-adx @@ -696,6 +733,22 @@ docker-push-execution-arm: docker-push-execution-latest: docker-push-execution docker push "$(CONTAINER_REGISTRY)/execution:latest" +.PHONY: docker-push-execution-ledger-with-adx +docker-push-execution-ledger-with-adx: + docker push "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG)" + +.PHONY: docker-push-execution-ledger-without-adx +docker-push-execution-ledger-without-adx: + docker push "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG_NO_ADX)" + +.PHONY: docker-push-execution-ledger-without-netgo-without-adx +docker-push-execution-ledger-without-netgo-without-adx: + docker push "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG_NO_NETGO_NO_ADX)" + +.PHONY: docker-push-execution-ledger-arm +docker-push-execution-ledger-arm: + docker push "$(CONTAINER_REGISTRY)/execution-ledger:$(IMAGE_TAG_ARM)" + .PHONY: docker-push-verification-with-adx docker-push-verification-with-adx: docker push "$(CONTAINER_REGISTRY)/verification:$(IMAGE_TAG)" @@ -868,39 +921,3 @@ check-go-version: exit 1; \ fi; \ ' - -#---------------------------------------------------------------------- -# CD COMMANDS -#---------------------------------------------------------------------- - -.PHONY: deploy-staging -deploy-staging: update-deployment-image-name-staging apply-staging-files monitor-rollout - -# Staging YAMLs must have 'staging' in their name. -.PHONY: apply-staging-files -apply-staging-files: - kconfig=$$(uuidgen); \ - echo "$$KUBECONFIG_STAGING" > $$kconfig; \ - files=$$(find ${K8S_YAMLS_LOCATION_STAGING} -type f \( --name "*.yml" -or --name "*.yaml" \)); \ - echo "$$files" | xargs -I {} kubectl --kubeconfig=$$kconfig apply -f {} - -# Deployment YAMLs must have 'deployment' in their name. -.PHONY: update-deployment-image-name-staging -update-deployment-image-name-staging: CONTAINER=flow-test-net -update-deployment-image-name-staging: - @files=$$(find ${K8S_YAMLS_LOCATION_STAGING} -type f \( --name "*.yml" -or --name "*.yaml" \) | grep deployment); \ - for file in $$files; do \ - patched=`openssl rand -hex 8`; \ - node=`echo "$$file" | grep -oP 'flow-\K\w+(?=-node-deployment.yml)'`; \ - kubectl patch -f $$file -p '{"spec":{"template":{"spec":{"containers":[{"name":"${CONTAINER}","image":"$(CONTAINER_REGISTRY)/'"$$node"':${IMAGE_TAG}"}]}}}}`' --local -o yaml > $$patched; \ - mv -f $$patched $$file; \ - done - -.PHONY: monitor-rollout -monitor-rollout: - kconfig=$$(uuidgen); \ - echo "$$KUBECONFIG_STAGING" > $$kconfig; \ - kubectl --kubeconfig=$$kconfig rollout status statefulsets.apps flow-collection-node-v1; \ - kubectl --kubeconfig=$$kconfig rollout status statefulsets.apps flow-consensus-node-v1; \ - kubectl --kubeconfig=$$kconfig rollout status statefulsets.apps flow-execution-node-v1; \ - kubectl --kubeconfig=$$kconfig rollout status statefulsets.apps flow-verification-node-v1 diff --git a/README.md b/README.md index 333cbfc7bd2..1233ea9f153 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,22 @@ -# Flow [![GoDoc](https://godoc.org/github.com/onflow/flow-go?status.svg)](https://godoc.org/github.com/onflow/flow-go) +# flow-go — Flow Network Reference Implementation in Go -Flow is a fast, secure, and developer-friendly blockchain built to support the next generation of games, apps and the -digital assets that power them. Read more about it [here](https://github.com/onflow/flow). +[![GoDoc](https://godoc.org/github.com/onflow/flow-go?status.svg)](https://godoc.org/github.com/onflow/flow-go) +[![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) +[![Release](https://img.shields.io/github/v/release/onflow/flow-go)](https://github.com/onflow/flow-go/releases) +[![Discord](https://img.shields.io/badge/Discord-Flow-7289DA?logo=discord&logoColor=white)](https://discord.gg/flow) +[![Built on Flow](https://img.shields.io/badge/Built_on-Flow-00EF8B)](https://flow.com) + +Reference implementation of the [Flow network](https://flow.com) in Go. Flow is a Layer 1 proof-of-stake blockchain built for consumer apps, AI Agents, and DeFi at scale. This repo hosts the node software — consensus, execution, verification, access, and collection roles — and the Cadence VM integration used on mainnet, testnet, and local networks. + +## TL;DR + +- **What:** flow-go is the Go reference implementation of the Flow network, a Layer 1 proof-of-stake blockchain. +- **Who it's for:** protocol contributors, node operators, and teams building infrastructure on or adjacent to Flow. +- **Why use it:** canonical source of truth for Flow consensus (HotStuff), multi-role architecture, Cadence VM integration, and Flow EVM. +- **Status:** see [Releases](https://github.com/onflow/flow-go/releases) for the latest version. Live on mainnet. +- **License:** AGPL-3.0 +- **Related repos:** [cadence](https://github.com/onflow/cadence) (language) · [flow-cli](https://github.com/onflow/flow-cli) (CLI) · [fcl-js](https://github.com/onflow/fcl-js) (JS client) · [flow-go-sdk](https://github.com/onflow/flow-go-sdk) (Go client) +- The reference Go implementation for the Flow network, open-sourced since 2019. @@ -192,3 +207,35 @@ type StateMachineEventsTelemetryFactory interface { config: dir: "state/protocol/protocol_state/mock" ``` + +## FAQ + +### What is flow-go? +flow-go is the Go reference implementation of the Flow network — a Layer 1 proof-of-stake blockchain. It implements the node software (Access, Collection, Consensus, Execution, Verification roles), the HotStuff consensus algorithm, ledger, storage, networking, and cryptography subsystems. + +### How does flow-go differ from the Cadence repo? +flow-go is the **protocol / node** implementation. [`onflow/cadence`](https://github.com/onflow/cadence) is the **Cadence smart contract language** (compiler, interpreter, type system). flow-go embeds the Cadence VM to execute transactions, but the language itself is developed in the Cadence repo. + +### What are the five node roles in Flow? +Access, Collection, Consensus, Execution, and Verification. Each has its own entry point under `/cmd/`. There is also an Observer service for staking-free read-only access. + +### Which Go version does flow-go require? +Go 1.25 or later. See the [Installation](#installation) section for the full environment setup. + +### Where is the consensus algorithm implemented? +Under [`/consensus/hotstuff`](/consensus/hotstuff). HotStuff is the BFT consensus family used by Flow. + +### How do I run a local Flow network? +See the [Local Network Guide](/integration/localnet/README.md) for a full local multi-role network suitable for integration testing. + +### Where do I report a security issue? +See [SECURITY.md](/SECURITY.md) for the responsible disclosure policy. + +## About Flow + +This repo is the Go reference implementation of the [Flow network](https://flow.com), a Layer 1 blockchain built for consumer applications, AI Agents, and DeFi at scale. + +- Developer docs: https://developers.flow.com +- Cadence language: https://cadence-lang.org +- Community: [Flow Discord](https://discord.gg/flow) · [Flow Forum](https://forum.flow.com) +- Governance: [Flow Improvement Proposals](https://github.com/onflow/flips) diff --git a/access/api.go b/access/api.go index 30f55705e43..08669653e7c 100644 --- a/access/api.go +++ b/access/api.go @@ -99,6 +99,23 @@ type TransactionStreamAPI interface { ) subscription.Subscription } +// ReceiptsAPI provides access to execution receipts for blocks and execution results. +type ReceiptsAPI interface { + // GetExecutionReceiptsByBlockID retrieves all known execution receipts for the given block. + // + // Expected error returns during normal operation: + // - codes.NotFound: if no receipts are indexed for the given block ID. + GetExecutionReceiptsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.ExecutionReceipt, error) + + // GetExecutionReceiptsByResultID retrieves all known execution receipts that commit to the + // given execution result ID. It resolves the associated block ID from the result, then + // retrieves all receipts for that block, filtering to those matching the requested result. + // + // Expected error returns during normal operation: + // - codes.NotFound: if the execution result or its block's receipts are not found. + GetExecutionReceiptsByResultID(ctx context.Context, resultID flow.Identifier) ([]*flow.ExecutionReceipt, error) +} + // API provides all public-facing functionality of the Flow Access API. type API interface { AccountsAPI @@ -106,6 +123,7 @@ type API interface { ScriptsAPI TransactionsAPI TransactionStreamAPI + ReceiptsAPI Ping(ctx context.Context) error GetNetworkParameters(ctx context.Context) accessmodel.NetworkParameters diff --git a/access/backends/extended/api.go b/access/backends/extended/api.go new file mode 100644 index 00000000000..7d142952909 --- /dev/null +++ b/access/backends/extended/api.go @@ -0,0 +1,174 @@ +package extended + +import ( + "context" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// API defines the extended access API for querying account transaction and transfer history. +type API interface { + // GetAccountTransactions returns a paginated list of transactions for the given account address. + // Results are ordered descending by block height (newest first). + // + // If the account is found but has no transactions, the response will include an empty array and no error. + // + // Expected error returns during normal operations: + // - [codes.NotFound] if the account is not found + // - [codes.FailedPrecondition] if the account transaction index has not been initialized + // - [codes.OutOfRange] if the cursor references a height outside the indexed range + // - [codes.InvalidArgument] if the query parameters are invalid + GetAccountTransactions( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.AccountTransactionCursor, + filter AccountTransactionFilter, + expandOptions AccountTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.AccountTransactionsPage, error) + + // GetAccountFungibleTokenTransfers returns a paginated list of fungible token transfers for + // the given account address. Results are ordered descending by block height (newest first). + // + // If the account has no transfers, the response will include an empty array and no error. + // + // Expected error returns during normal operations: + // - [codes.NotFound] if the account is not found + // - [codes.FailedPrecondition] if the fungible token transfer index has not been initialized + // - [codes.OutOfRange] if the cursor references a height outside the indexed range + // - [codes.InvalidArgument] if the query parameters are invalid + GetAccountFungibleTokenTransfers( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.TransferCursor, + filter AccountTransferFilter, + expandOptions AccountTransferExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.FungibleTokenTransfersPage, error) + + // GetAccountNonFungibleTokenTransfers returns a paginated list of non-fungible token transfers + // for the given account address. Results are ordered descending by block height (newest first). + // + // If the account has no transfers, the response will include an empty array and no error. + // + // Expected error returns during normal operations: + // - [codes.NotFound] if the account is not found + // - [codes.FailedPrecondition] if the non-fungible token transfer index has not been initialized + // - [codes.OutOfRange] if the cursor references a height outside the indexed range + // - [codes.InvalidArgument] if the query parameters are invalid + GetAccountNonFungibleTokenTransfers( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.TransferCursor, + filter AccountTransferFilter, + expandOptions AccountTransferExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.NonFungibleTokenTransfersPage, error) + + // GetScheduledTransaction returns a single scheduled transaction by its scheduler-assigned ID. + // + // Expected error returns during normal operations: + // - [codes.NotFound]: if no transaction with the given ID exists + // - [codes.FailedPrecondition]: if the index has not been initialized + GetScheduledTransaction( + ctx context.Context, + id uint64, + expandOptions ScheduledTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.ScheduledTransaction, error) + + // GetScheduledTransactions returns a paginated list of scheduled transactions. + // + // Expected error returns during normal operations: + // - [codes.FailedPrecondition]: if the index has not been initialized + // - [codes.InvalidArgument]: if the query parameters are invalid + GetScheduledTransactions( + ctx context.Context, + limit uint32, + cursor *accessmodel.ScheduledTransactionCursor, + filter ScheduledTransactionFilter, + expandOptions ScheduledTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.ScheduledTransactionsPage, error) + + // GetScheduledTransactionsByAddress returns a paginated list of scheduled transactions for the given address. + // + // Expected error returns during normal operations: + // - [codes.FailedPrecondition]: if the index has not been initialized + // - [codes.InvalidArgument]: if the query parameters are invalid + GetScheduledTransactionsByAddress( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.ScheduledTransactionCursor, + filter ScheduledTransactionFilter, + expandOptions ScheduledTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.ScheduledTransactionsPage, error) + + // GetContract returns the most recent deployment of the given contract. + // + // Expected error returns during normal operations: + // - [codes.NotFound]: if no contract with the given identifier exists + // - [codes.FailedPrecondition]: if the index has not been initialized + GetContract( + ctx context.Context, + id string, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.ContractDeployment, error) + + // GetContractDeployments returns a paginated list of all deployments of the given contract, + // most recent first. + // + // Expected error returns during normal operations: + // - [codes.NotFound]: if no contract with the given identifier exists + // - [codes.FailedPrecondition]: if the index has not been initialized + // - [codes.InvalidArgument]: if query parameters are invalid + GetContractDeployments( + ctx context.Context, + id string, + limit uint32, + cursor *accessmodel.ContractDeploymentsCursor, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.ContractDeploymentPage, error) + + // GetContracts returns a paginated list of contracts at their latest deployment. + // + // Expected error returns during normal operations: + // - [codes.FailedPrecondition]: if the index has not been initialized + // - [codes.InvalidArgument]: if query parameters are invalid + GetContracts( + ctx context.Context, + limit uint32, + cursor *accessmodel.ContractDeploymentsCursor, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.ContractDeploymentPage, error) + + // GetContractsByAddress returns a paginated list of contracts at their latest deployment for + // the given address. + // + // Expected error returns during normal operations: + // - [codes.FailedPrecondition]: if the index has not been initialized + // - [codes.InvalidArgument]: if query parameters are invalid + GetContractsByAddress( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.ContractDeploymentsCursor, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, + ) (*accessmodel.ContractDeploymentPage, error) +} diff --git a/access/backends/extended/backend.go b/access/backends/extended/backend.go new file mode 100644 index 00000000000..a158c6d69f7 --- /dev/null +++ b/access/backends/extended/backend.go @@ -0,0 +1,127 @@ +package extended + +import ( + "context" + "errors" + "fmt" + + "github.com/rs/zerolog" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow-go/engine/access/index" + "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/error_messages" + "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/provider" + txstatus "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/status" + "github.com/onflow/flow-go/model/access/systemcollection" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/execution" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" +) + +// Config holds configuration for the extended API backend. +type Config struct { + DefaultPageSize uint32 // Page size used when limit is 0. + MaxPageSize uint32 // Maximum allowed page size. +} + +// DefaultConfig returns the default configuration for the extended API backend. +func DefaultConfig() Config { + return Config{ + DefaultPageSize: 50, + MaxPageSize: 200, + } +} + +// Backend implements the extended API for querying account transactions and token transfers. +type Backend struct { + *AccountTransactionsBackend + *AccountTransfersBackend + *ScheduledTransactionsBackend + *ContractsBackend + + log zerolog.Logger +} + +var _ API = (*Backend)(nil) + +// New creates a new Backend instance. +func New( + log zerolog.Logger, + config Config, + chainID flow.ChainID, + store storage.AccountTransactionsReader, + ftStore storage.FungibleTokenTransfersBootstrapper, + nftStore storage.NonFungibleTokenTransfersBootstrapper, + state protocol.State, + blocks storage.Blocks, + headers storage.Headers, + eventsIndex *index.EventsIndex, + txResultsIndex *index.TransactionResultsIndex, + txErrorMessageProvider error_messages.Provider, + collections storage.CollectionsReader, + transactions storage.TransactionsReader, + scheduledTransactions storage.ScheduledTransactionsReader, + scheduledTxIndex storage.ScheduledTransactionsIndexReader, + contractsIndex storage.ContractDeploymentsIndexReader, + txStatusDeriver *txstatus.TxStatusDeriver, + scriptExecutor execution.ScriptExecutor, +) (*Backend, error) { + log = log.With().Str("component", "extended_backend").Logger() + + systemCollections, err := systemcollection.NewVersioned(chainID.Chain(), systemcollection.Default(chainID)) + if err != nil { + return nil, fmt.Errorf("failed to create system collection set: %w", err) + } + + transactionsProvider := provider.NewLocalTransactionProvider( + state, + collections, + blocks, + eventsIndex, + txResultsIndex, + txErrorMessageProvider, + systemCollections, + txStatusDeriver, + chainID, + ) + + base := &backendBase{ + config: config, + headers: headers, + blocks: blocks, + collections: collections, + transactions: transactions, + scheduledTransactions: scheduledTransactions, + systemCollections: systemCollections, + transactionsProvider: transactionsProvider, + } + + chain := chainID.Chain() + return &Backend{ + log: log, + AccountTransactionsBackend: NewAccountTransactionsBackend(log, base, store, chain), + AccountTransfersBackend: NewAccountTransfersBackend(log, base, ftStore, nftStore, chain), + ScheduledTransactionsBackend: NewScheduledTransactionsBackend(log, base, chainID, scheduledTxIndex, contractsIndex, scheduledTransactions, state, scriptExecutor), + ContractsBackend: NewContractsBackend(log, base, contractsIndex), + }, nil +} + +// mapReadError converts storage read errors to appropriate gRPC status errors. +func mapReadError(ctx context.Context, label string, err error) error { + switch { + case errors.Is(err, storage.ErrNotBootstrapped): + return status.Errorf(codes.FailedPrecondition, "%s index not initialized: %v", label, err) + case errors.Is(err, storage.ErrHeightNotIndexed): + return status.Errorf(codes.OutOfRange, "requested height not indexed: %v", err) + case errors.Is(err, storage.ErrInvalidQuery): + return status.Errorf(codes.InvalidArgument, "invalid query: %v", err) + case errors.Is(err, storage.ErrNotFound): + return status.Errorf(codes.NotFound, "not found: %v", err) + default: + irrecoverable.Throw(ctx, fmt.Errorf("failed to get %s: %w", label, err)) + return err + } +} diff --git a/access/backends/extended/backend_account_transactions.go b/access/backends/extended/backend_account_transactions.go new file mode 100644 index 00000000000..2d520c5665a --- /dev/null +++ b/access/backends/extended/backend_account_transactions.go @@ -0,0 +1,179 @@ +package extended + +import ( + "context" + "fmt" + + "github.com/rs/zerolog" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" +) + +type AccountTransactionExpandOptions struct { + Result bool + Transaction bool +} + +func (o *AccountTransactionExpandOptions) HasExpand() bool { + return o.Result || o.Transaction +} + +type AccountTransactionFilter struct { + Roles []accessmodel.TransactionRole +} + +func (f *AccountTransactionFilter) Filter() storage.IndexFilter[*accessmodel.AccountTransaction] { + if len(f.Roles) == 0 { + return nil + } + + rolesMap := make(map[accessmodel.TransactionRole]bool, len(f.Roles)) + for _, role := range f.Roles { + rolesMap[role] = true + } + + return func(tx *accessmodel.AccountTransaction) bool { + for _, role := range tx.Roles { + if rolesMap[role] { + return true + } + } + return false + } +} + +// AccountTransactionsBackend implements the extended API for querying account transactions. +type AccountTransactionsBackend struct { + *backendBase + + log zerolog.Logger + store storage.AccountTransactionsReader + chain flow.Chain +} + +// NewAccountTransactionsBackend creates a new AccountTransactionsBackend instance. +func NewAccountTransactionsBackend( + log zerolog.Logger, + base *backendBase, + store storage.AccountTransactionsReader, + chain flow.Chain, +) *AccountTransactionsBackend { + return &AccountTransactionsBackend{ + backendBase: base, + log: log, + store: store, + chain: chain, + } +} + +// GetAccountTransactions returns a paginated list of transactions for the given account address. +// Results are ordered descending by block height (newest first). +// +// If the account is found but has no transactions, the response will include an empty array and no error. +// +// Expected error returns during normal operations: +// - [codes.NotFound] if the account is not found +// - [codes.FailedPrecondition] if the account transaction index has not been initialized +// - [codes.OutOfRange] if the cursor references a height outside the indexed range +// - [codes.InvalidArgument] if the query parameters are invalid +func (b *AccountTransactionsBackend) GetAccountTransactions( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.AccountTransactionCursor, + filter AccountTransactionFilter, + expandOptions AccountTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.AccountTransactionsPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + if !b.chain.IsValid(address) { + return nil, status.Errorf(codes.NotFound, "account %s is not valid on chain %s", address, b.chain.ChainID()) + } + // TODO: check if account exists for the chain + + iter, err := b.store.ByAddress(address, cursor) + if err != nil { + return nil, mapReadError(ctx, "account transactions", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.Filter()) + if err != nil { + err = fmt.Errorf("error collecting transactions: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := accessmodel.AccountTransactionsPage{ + Transactions: collected, + NextCursor: nextCursor, + } + + for i := range page.Transactions { + tx := &page.Transactions[i] + if err := b.expand(ctx, tx, expandOptions, encodingVersion); err != nil { + err = fmt.Errorf("unexpected error expanding transaction: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + } + + return &page, nil +} + +// expand adds additional details to the transaction. +// +// Since the extended indexer only indexes sealed data, all transaction and result data should exist +// in storage for the given height. +// +// No error returns are expected during normal operation. +func (b *AccountTransactionsBackend) expand( + ctx context.Context, + tx *accessmodel.AccountTransaction, + expandOptions AccountTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, +) error { + header, err := b.headers.ByHeight(tx.BlockHeight) + if err != nil { + return fmt.Errorf("could not retrieve block header: %w", err) + } + + // always add the block timestamp + tx.BlockTimestamp = header.Timestamp + + // only add the transaction body and result if requested + if !expandOptions.HasExpand() { + return nil + } + + var isSystemChunkTx bool + if expandOptions.Transaction { + var txBody *flow.TransactionBody + txBody, isSystemChunkTx, err = b.getTransactionBody(ctx, header, tx.TransactionID) + if err != nil { + return fmt.Errorf("could not retrieve transaction body: %w", err) + } + tx.Transaction = txBody + } + + if expandOptions.Result { + result, err := b.getTransactionResult(ctx, tx.TransactionID, header, isSystemChunkTx, expandOptions.Transaction, encodingVersion) + if err != nil { + return fmt.Errorf("could not retrieve transaction result: %w", err) + } + tx.Result = result + } + + return nil +} diff --git a/access/backends/extended/backend_account_transactions_test.go b/access/backends/extended/backend_account_transactions_test.go new file mode 100644 index 00000000000..b9bf78579dd --- /dev/null +++ b/access/backends/extended/backend_account_transactions_test.go @@ -0,0 +1,309 @@ +package extended + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + mocktestify "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + providermock "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/provider/mock" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/storage" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/utils/unittest" +) + +// txEntry is a test implementation of IteratorEntry for AccountTransaction. +type txEntry struct { + tx accessmodel.AccountTransaction +} + +func (e txEntry) Cursor() accessmodel.AccountTransactionCursor { + return accessmodel.AccountTransactionCursor{ + Address: e.tx.Address, + BlockHeight: e.tx.BlockHeight, + TransactionIndex: e.tx.TransactionIndex, + } +} + +func (e txEntry) Value() (accessmodel.AccountTransaction, error) { + return e.tx, nil +} + +func newSliceIter(txs []accessmodel.AccountTransaction) storage.AccountTransactionIterator { + return func(yield func(storage.IteratorEntry[accessmodel.AccountTransaction, accessmodel.AccountTransactionCursor], error) bool) { + for _, tx := range txs { + if !yield(txEntry{tx: tx}, nil) { + return + } + } + } +} + +func TestBackend_GetAccountTransactions(t *testing.T) { + t.Parallel() + + defaultEncoding := entities.EventEncodingVersion_JSON_CDC_V0 + + t.Run("happy path returns page from storage", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig(), headers: mockHeaders}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + blockHeader := unittest.BlockHeaderFixture() + + txs := []accessmodel.AccountTransaction{ + { + Address: addr, + BlockHeight: blockHeader.Height, + TransactionID: txID, + TransactionIndex: 0, + Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleAuthorizer}, + }, + } + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(newSliceIter(txs), nil) + mockHeaders.On("ByHeight", blockHeader.Height).Return(blockHeader, nil) + + page, err := backend.GetAccountTransactions(context.Background(), addr, 0, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + require.Len(t, page.Transactions, 1) + assert.Equal(t, txID, page.Transactions[0].TransactionID) + assert.Equal(t, blockHeader.Timestamp, page.Transactions[0].BlockTimestamp) + assert.Nil(t, page.NextCursor) + }) + + t.Run("default limit applied when limit is 0", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig(), headers: mockHeaders}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + blockHeader := unittest.BlockHeaderFixture() + + txs := []accessmodel.AccountTransaction{ + {Address: addr, BlockHeight: blockHeader.Height, TransactionID: unittest.IdentifierFixture()}, + } + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(newSliceIter(txs), nil) + mockHeaders.On("ByHeight", blockHeader.Height).Return(unittest.BlockHeaderFixture(), nil) + + _, err := backend.GetAccountTransactions(context.Background(), addr, 0, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + }) + + t.Run("limit exceeding max returns InvalidArgument", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + _, err := backend.GetAccountTransactions(context.Background(), addr, 500, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("cursor is forwarded to storage", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig(), headers: mockHeaders}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + cursor := &accessmodel.AccountTransactionCursor{BlockHeight: 50, TransactionIndex: 3} + blockHeader := unittest.BlockHeaderFixture(func(h *flow.Header) { h.Height = 50 }) + + txs := []accessmodel.AccountTransaction{ + {Address: addr, BlockHeight: 50, TransactionID: unittest.IdentifierFixture()}, + } + + mockStore.On("ByAddress", addr, cursor).Return(newSliceIter(txs), nil) + mockHeaders.On("ByHeight", uint64(50)).Return(blockHeader, nil) + + _, err := backend.GetAccountTransactions(context.Background(), addr, 10, cursor, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + }) + + t.Run("filter applied by backend: only matching transactions returned", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig(), headers: mockHeaders}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + blockHeader := unittest.BlockHeaderFixture() + filter := AccountTransactionFilter{Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleAuthorizer}} + + txID := unittest.IdentifierFixture() + // Iterator yields one authorizer and one payer tx; only the authorizer should be returned. + txs := []accessmodel.AccountTransaction{ + {Address: addr, BlockHeight: blockHeader.Height, TransactionID: txID, Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleAuthorizer}}, + {Address: addr, BlockHeight: blockHeader.Height, TransactionID: unittest.IdentifierFixture(), Roles: []accessmodel.TransactionRole{accessmodel.TransactionRolePayer}}, + } + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(newSliceIter(txs), nil) + mockHeaders.On("ByHeight", blockHeader.Height).Return(blockHeader, nil) + + page, err := backend.GetAccountTransactions(context.Background(), addr, 0, nil, filter, AccountTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + require.Len(t, page.Transactions, 1) + assert.Equal(t, txID, page.Transactions[0].TransactionID) + }) + + t.Run("next cursor set when iterator has more results than limit", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig(), headers: mockHeaders}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + blockHeader := unittest.BlockHeaderFixture() + + // Iterator yields limit+1 transactions; the extra one becomes the next cursor. + txs := []accessmodel.AccountTransaction{ + {Address: addr, BlockHeight: blockHeader.Height, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 0}, + {Address: addr, BlockHeight: 99, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 2}, + } + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(newSliceIter(txs), nil) + mockHeaders.On("ByHeight", blockHeader.Height).Return(blockHeader, nil) + + page, err := backend.GetAccountTransactions(context.Background(), addr, 1, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + require.Len(t, page.Transactions, 1) + require.NotNil(t, page.NextCursor) + assert.Equal(t, uint64(99), page.NextCursor.BlockHeight) + assert.Equal(t, uint32(2), page.NextCursor.TransactionIndex) + }) + + t.Run("ErrNotBootstrapped maps to FailedPrecondition", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore, flow.Testnet.Chain()) + + addr := unittest.InvalidAddressFixture() + + _, err := backend.GetAccountTransactions(context.Background(), addr, 0, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.NotFound, st.Code()) + }) + + t.Run("empty results with valid address returns empty page", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(newSliceIter(nil), nil) + + page, err := backend.GetAccountTransactions(context.Background(), addr, 0, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + assert.Empty(t, page.Transactions) + }) + + t.Run("ErrNotBootstrapped maps to FailedPrecondition", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(nil, storage.ErrNotBootstrapped) + + _, err := backend.GetAccountTransactions(context.Background(), addr, 0, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("ErrHeightNotIndexed maps to OutOfRange", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + cursor := &accessmodel.AccountTransactionCursor{BlockHeight: 999, TransactionIndex: 0} + + mockStore.On("ByAddress", addr, cursor).Return(nil, fmt.Errorf("wrapped: %w", storage.ErrHeightNotIndexed)) + + _, err := backend.GetAccountTransactions(context.Background(), addr, 10, cursor, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.OutOfRange, st.Code()) + }) + + t.Run("expand result without expand transaction succeeds when collection not indexed", func(t *testing.T) { + // Regression test: when expandOptions.Result=true and expandOptions.Transaction=false, + // getTransactionResult is called with isSystemChunkTx=false (since getTransactionBody is + // skipped). If LightByTransactionID returns ErrNotFound (e.g. asynchronous index not yet + // available), the old code called collection.ID() on a nil pointer, causing a panic. + // The fixed code skips the assignment and uses a zero collectionID instead. + mockStore := storagemock.NewAccountTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockProvider := providermock.NewTransactionProvider(t) + backend := NewAccountTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: DefaultConfig(), + headers: mockHeaders, + collections: mockCollections, + transactionsProvider: mockProvider, + }, + mockStore, + flow.Testnet.Chain(), + ) + + addr := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + blockHeader := unittest.BlockHeaderFixture() + expectedResult := &accessmodel.TransactionResult{} + + storedPage := accessmodel.AccountTransactionsPage{ + Transactions: []accessmodel.AccountTransaction{ + {Address: addr, BlockHeight: blockHeader.Height, TransactionID: txID}, + }, + } + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(newSliceIter(storedPage.Transactions), nil) + mockHeaders.On("ByHeight", blockHeader.Height).Return(blockHeader, nil) + // Collection is not yet indexed; LightByTransactionID returns ErrNotFound. + mockCollections.On("LightByTransactionID", txID).Return((*flow.LightCollection)(nil), storage.ErrNotFound).Once() + // Expects zero collectionID since the collection lookup returned ErrNotFound. + mockProvider.On("TransactionResult", mocktestify.Anything, blockHeader, txID, flow.ZeroID, defaultEncoding).Return(expectedResult, nil).Once() + + expandOptions := AccountTransactionExpandOptions{Result: true, Transaction: false} + page, err := backend.GetAccountTransactions(context.Background(), addr, 0, nil, AccountTransactionFilter{}, expandOptions, defaultEncoding) + require.NoError(t, err) + require.Len(t, page.Transactions, 1) + assert.Equal(t, expectedResult, page.Transactions[0].Result) + }) + + t.Run("unexpected error triggers irrecoverable", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsReader(t) + backend := NewAccountTransactionsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + storageErr := fmt.Errorf("unexpected storage failure") + + mockStore.On("ByAddress", addr, (*accessmodel.AccountTransactionCursor)(nil)).Return(nil, storageErr) + + expectedErr := fmt.Errorf("failed to get account transactions: %w", storageErr) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), + irrecoverable.NewMockSignalerContextExpectError(t, context.Background(), expectedErr)) + + _, err := backend.GetAccountTransactions(signalerCtx, addr, 0, nil, AccountTransactionFilter{}, AccountTransactionExpandOptions{}, defaultEncoding) + require.Error(t, err) + }) +} diff --git a/access/backends/extended/backend_account_transfers.go b/access/backends/extended/backend_account_transfers.go new file mode 100644 index 00000000000..3fcd835235d --- /dev/null +++ b/access/backends/extended/backend_account_transfers.go @@ -0,0 +1,301 @@ +package extended + +import ( + "context" + "fmt" + + "github.com/rs/zerolog" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" +) + +type AccountTransferExpandOptions struct { + Transaction bool + Result bool +} + +func (o *AccountTransferExpandOptions) HasExpand() bool { + return o.Transaction || o.Result +} + +type AccountTransferFilter struct { + TokenType string + SourceAddress flow.Address + RecipientAddress flow.Address +} + +func (f *AccountTransferFilter) isEmpty() bool { + return f == nil || + (f.TokenType == "" && + f.SourceAddress == flow.EmptyAddress && + f.RecipientAddress == flow.EmptyAddress) +} + +func (f *AccountTransferFilter) validate(account flow.Address) error { + // if both source and recipient addresses are set and neither are the account's address, then the + // filter will never match. + if f.SourceAddress != flow.EmptyAddress && f.RecipientAddress != flow.EmptyAddress { + if f.SourceAddress == account || f.RecipientAddress == account { + return nil + } + return fmt.Errorf("source and recipient addresses are set and neither are the account's address. filter will never match") + } + return nil +} + +// FTFilter returns a filter function for fungible token transfers based on the filter criteria. +// Returns nil when no filter criteria are set, indicating all transfers should be accepted. +func (f *AccountTransferFilter) FTFilter() storage.IndexFilter[*accessmodel.FungibleTokenTransfer] { + if f.isEmpty() { + return nil + } + return func(transfer *accessmodel.FungibleTokenTransfer) bool { + return f.filter(transfer.TokenType, transfer.SourceAddress, transfer.RecipientAddress) + } +} + +// NFTFilter returns a filter function for non-fungible token transfers based on the filter criteria. +// Returns nil when no filter criteria are set, indicating all transfers should be accepted. +func (f *AccountTransferFilter) NFTFilter() storage.IndexFilter[*accessmodel.NonFungibleTokenTransfer] { + if f.isEmpty() { + return nil + } + return func(transfer *accessmodel.NonFungibleTokenTransfer) bool { + return f.filter(transfer.TokenType, transfer.SourceAddress, transfer.RecipientAddress) + } +} + +func (f *AccountTransferFilter) filter(tokenType string, sourceAddress flow.Address, recipientAddress flow.Address) bool { + if f.TokenType != "" && tokenType != f.TokenType { + return false + } + if f.SourceAddress != flow.EmptyAddress && sourceAddress != f.SourceAddress { + return false + } + if f.RecipientAddress != flow.EmptyAddress && recipientAddress != f.RecipientAddress { + return false + } + return true +} + +// AccountTransfersBackend implements the extended API for querying account token transfers. +type AccountTransfersBackend struct { + *backendBase + + log zerolog.Logger + ftStore storage.FungibleTokenTransfersBootstrapper + nftStore storage.NonFungibleTokenTransfersBootstrapper + + chain flow.Chain +} + +// NewAccountTransfersBackend creates a new AccountTransfersBackend instance. +func NewAccountTransfersBackend( + log zerolog.Logger, + base *backendBase, + ftStore storage.FungibleTokenTransfersBootstrapper, + nftStore storage.NonFungibleTokenTransfersBootstrapper, + chain flow.Chain, +) *AccountTransfersBackend { + return &AccountTransfersBackend{ + backendBase: base, + log: log, + ftStore: ftStore, + nftStore: nftStore, + chain: chain, + } +} + +// GetAccountFungibleTokenTransfers returns a paginated list of fungible token transfers for the +// given account address. Results are ordered descending by block height (newest first). +// +// If the account has no transfers, the response will include an empty array and no error. +// +// Expected error returns during normal operations: +// - [codes.NotFound] if the account is not found +// - [codes.FailedPrecondition] if the fungible token transfer index has not been initialized +// - [codes.OutOfRange] if the cursor references a height outside the indexed range +// - [codes.InvalidArgument] if the query parameters are invalid +func (b *AccountTransfersBackend) GetAccountFungibleTokenTransfers( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.TransferCursor, + filter AccountTransferFilter, + expandOptions AccountTransferExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.FungibleTokenTransfersPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + if err := filter.validate(address); err != nil { + return nil, status.Errorf(codes.InvalidArgument, "filter is not valid for account: %v", err) + } + + if !b.chain.IsValid(address) { + return nil, status.Errorf(codes.NotFound, "account %s is not valid on chain %s", address, b.chain.ChainID()) + } + + iter, err := b.ftStore.ByAddress(address, cursor) + if err != nil { + return nil, mapReadError(ctx, "fungible token transfers", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.FTFilter()) + if err != nil { + err = fmt.Errorf("error collecting fungible token transfers: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := accessmodel.FungibleTokenTransfersPage{ + Transfers: collected, + NextCursor: nextCursor, + } + + // TODO: check if account exists for the chain + for i := range page.Transfers { + t := &page.Transfers[i] + + header, txBody, result, err := b.expand(ctx, t.BlockHeight, t.TransactionID, expandOptions, encodingVersion) + if err != nil { + err = fmt.Errorf("failed to populate details for transfer transaction %s: %w", t.TransactionID, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + // only the expanded options will be populated + t.BlockTimestamp = header.Timestamp + t.Transaction = txBody + t.Result = result + } + + return &page, nil +} + +// GetAccountNonFungibleTokenTransfers returns a paginated list of non-fungible token transfers for +// the given account address. Results are ordered descending by block height (newest first). +// +// If the account has no transfers, the response will include an empty array and no error. +// +// Expected error returns during normal operations: +// - [codes.NotFound] if the account is not found +// - [codes.FailedPrecondition] if the non-fungible token transfer index has not been initialized +// - [codes.OutOfRange] if the cursor references a height outside the indexed range +// - [codes.InvalidArgument] if the query parameters are invalid +func (b *AccountTransfersBackend) GetAccountNonFungibleTokenTransfers( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.TransferCursor, + filter AccountTransferFilter, + expandOptions AccountTransferExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.NonFungibleTokenTransfersPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + if err := filter.validate(address); err != nil { + return nil, status.Errorf(codes.InvalidArgument, "filter is not valid for account: %v", err) + } + + if !b.chain.IsValid(address) { + return nil, status.Errorf(codes.NotFound, "account %s is not valid on chain %s", address, b.chain.ChainID()) + } + + iter, err := b.nftStore.ByAddress(address, cursor) + if err != nil { + return nil, mapReadError(ctx, "non-fungible token transfers", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.NFTFilter()) + if err != nil { + err = fmt.Errorf("error collecting non-fungible token transfers: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := accessmodel.NonFungibleTokenTransfersPage{ + Transfers: collected, + NextCursor: nextCursor, + } + + // TODO: check if account exists for the chain + for i := range page.Transfers { + t := &page.Transfers[i] + + header, txBody, result, err := b.expand(ctx, t.BlockHeight, t.TransactionID, expandOptions, encodingVersion) + if err != nil { + err = fmt.Errorf("failed to populate details for transfer transaction %s: %w", t.TransactionID, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + // only the expanded options will be populated + t.BlockTimestamp = header.Timestamp + t.Transaction = txBody + t.Result = result + } + + return &page, nil +} + +// expand adds additional details to the transaction. +// +// Since the extended indexer only indexes sealed data, all transaction and result data should exist +// in storage for the given height. +// +// No error returns are expected during normal operation. +func (b *AccountTransfersBackend) expand( + ctx context.Context, + blockHeight uint64, + transactionID flow.Identifier, + expandOptions AccountTransferExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*flow.Header, *flow.TransactionBody, *accessmodel.TransactionResult, error) { + blockID, err := b.headers.BlockIDByHeight(blockHeight) + if err != nil { + return nil, nil, nil, fmt.Errorf("could not retrieve block ID: %w", err) + } + + header, err := b.headers.ByBlockID(blockID) + if err != nil { + return nil, nil, nil, fmt.Errorf("could not retrieve block header: %w", err) + } + + // only add the transaction body and result if requested + if !expandOptions.HasExpand() { + return header, nil, nil, nil + } + + var txBody *flow.TransactionBody + var isSystemChunkTx bool + if expandOptions.Transaction { + txBody, isSystemChunkTx, err = b.getTransactionBody(ctx, header, transactionID) + if err != nil { + return nil, nil, nil, fmt.Errorf("could not retrieve transaction body: %w", err) + } + } + + var result *accessmodel.TransactionResult + if expandOptions.Result { + result, err = b.getTransactionResult(ctx, transactionID, header, isSystemChunkTx, expandOptions.Transaction, encodingVersion) + if err != nil { + return nil, nil, nil, fmt.Errorf("could not retrieve transaction result: %w", err) + } + } + + return header, txBody, result, nil +} diff --git a/access/backends/extended/backend_account_transfers_test.go b/access/backends/extended/backend_account_transfers_test.go new file mode 100644 index 00000000000..d40eef61946 --- /dev/null +++ b/access/backends/extended/backend_account_transfers_test.go @@ -0,0 +1,787 @@ +package extended + +import ( + "context" + "fmt" + "math/big" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/storage" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/utils/unittest" +) + +// ftEntry is a test implementation of IteratorEntry for FungibleTokenTransfer. +type ftEntry struct { + transfer accessmodel.FungibleTokenTransfer +} + +func (e ftEntry) Cursor() accessmodel.TransferCursor { + return accessmodel.TransferCursor{ + BlockHeight: e.transfer.BlockHeight, + TransactionIndex: e.transfer.TransactionIndex, + } +} + +func (e ftEntry) Value() (accessmodel.FungibleTokenTransfer, error) { + return e.transfer, nil +} + +func newFTSliceIter(transfers []accessmodel.FungibleTokenTransfer) storage.FungibleTokenTransferIterator { + return func(yield func(storage.IteratorEntry[accessmodel.FungibleTokenTransfer, accessmodel.TransferCursor], error) bool) { + for _, t := range transfers { + if !yield(ftEntry{transfer: t}, nil) { + return + } + } + } +} + +// nftEntry is a test implementation of IteratorEntry for NonFungibleTokenTransfer. +type nftEntry struct { + transfer accessmodel.NonFungibleTokenTransfer +} + +func (e nftEntry) Cursor() accessmodel.TransferCursor { + return accessmodel.TransferCursor{ + BlockHeight: e.transfer.BlockHeight, + TransactionIndex: e.transfer.TransactionIndex, + } +} + +func (e nftEntry) Value() (accessmodel.NonFungibleTokenTransfer, error) { + return e.transfer, nil +} + +func newNFTSliceIter(transfers []accessmodel.NonFungibleTokenTransfer) storage.NonFungibleTokenTransferIterator { + return func(yield func(storage.IteratorEntry[accessmodel.NonFungibleTokenTransfer, accessmodel.TransferCursor], error) bool) { + for _, t := range transfers { + if !yield(nftEntry{transfer: t}, nil) { + return + } + } + } +} + +func TestBackend_GetAccountFungibleTokenTransfers(t *testing.T) { + t.Parallel() + + defaultEncoding := entities.EventEncodingVersion_JSON_CDC_V0 + defaultConfig := DefaultConfig() + + t.Run("happy path returns page from storage", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: DefaultConfig(), headers: mockHeaders}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + expectedPage := accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 100, + TransactionIndex: 0, + TokenType: "A.1654653399040a61.FlowToken", + Amount: big.NewInt(1000), + SourceAddress: addr, + RecipientAddress: unittest.RandomAddressFixture(), + }, + }, + } + + blockID := unittest.IdentifierFixture() + ftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(newFTSliceIter(expectedPage.Transfers), nil) + mockHeaders.On("BlockIDByHeight", uint64(100)).Return(blockID, nil) + mockHeaders.On("ByBlockID", blockID).Return(unittest.BlockHeaderFixture(), nil) + + page, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + require.Len(t, page.Transfers, 1) + assert.Equal(t, txID, page.Transfers[0].TransactionID) + assert.Nil(t, page.NextCursor) + }) + + t.Run("default limit applied when limit is 0", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig, headers: mockHeaders}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + nonEmptyPage := accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{ + {BlockHeight: 1, TransactionID: unittest.IdentifierFixture()}, + }, + } + + blockID := unittest.IdentifierFixture() + ftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(newFTSliceIter(nonEmptyPage.Transfers), nil) + mockHeaders.On("BlockIDByHeight", uint64(1)).Return(blockID, nil) + mockHeaders.On("ByBlockID", blockID).Return(unittest.BlockHeaderFixture(), nil) + + _, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("limit exceeding max returns InvalidArgument", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + _, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 500, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("cursor is forwarded to storage", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig, headers: mockHeaders}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + cursor := &accessmodel.TransferCursor{BlockHeight: 50, TransactionIndex: 3, EventIndex: 1} + + nonEmptyPage := accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{ + {BlockHeight: 50, TransactionID: unittest.IdentifierFixture()}, + }, + } + + blockID := unittest.IdentifierFixture() + ftStore.On("ByAddress", addr, cursor). + Return(newFTSliceIter(nonEmptyPage.Transfers), nil) + mockHeaders.On("BlockIDByHeight", uint64(50)).Return(blockID, nil) + mockHeaders.On("ByBlockID", blockID).Return(unittest.BlockHeaderFixture(), nil) + + _, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 10, cursor, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("invalid address returns NotFound", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.InvalidAddressFixture() + + _, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.NotFound, st.Code()) + }) + + t.Run("filter with both addresses neither matching account returns InvalidArgument", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + filter := AccountTransferFilter{ + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + } + + _, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 0, nil, filter, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("empty results with valid address returns empty page", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + ftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(newFTSliceIter(nil), nil) + + page, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + assert.Empty(t, page.Transfers) + }) + + t.Run("ErrNotBootstrapped maps to FailedPrecondition", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + ftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(nil, storage.ErrNotBootstrapped) + + _, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("ErrHeightNotIndexed maps to OutOfRange", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + cursor := &accessmodel.TransferCursor{BlockHeight: 999, TransactionIndex: 0, EventIndex: 0} + + ftStore.On("ByAddress", addr, cursor). + Return(nil, fmt.Errorf("wrapped: %w", storage.ErrHeightNotIndexed)) + + _, err := backend.GetAccountFungibleTokenTransfers( + context.Background(), addr, 10, cursor, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.OutOfRange, st.Code()) + }) + + t.Run("unexpected error triggers irrecoverable", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + storageErr := fmt.Errorf("unexpected storage failure") + + ftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(nil, storageErr) + + expectedErr := fmt.Errorf("failed to get fungible token transfers: %w", storageErr) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), + irrecoverable.NewMockSignalerContextExpectError(t, context.Background(), expectedErr)) + + _, err := backend.GetAccountFungibleTokenTransfers( + signalerCtx, addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + }) +} + +func TestBackend_GetAccountNonFungibleTokenTransfers(t *testing.T) { + t.Parallel() + + defaultEncoding := entities.EventEncodingVersion_JSON_CDC_V0 + defaultConfig := DefaultConfig() + + t.Run("happy path returns page from storage", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig, headers: mockHeaders}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + expectedPage := accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 100, + TransactionIndex: 0, + TokenType: "A.1654653399040a61.MyNFT", + ID: 42, + SourceAddress: addr, + RecipientAddress: unittest.RandomAddressFixture(), + }, + }, + } + + blockID := unittest.IdentifierFixture() + nftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(newNFTSliceIter(expectedPage.Transfers), nil) + mockHeaders.On("BlockIDByHeight", uint64(100)).Return(blockID, nil) + mockHeaders.On("ByBlockID", blockID).Return(unittest.BlockHeaderFixture(), nil) + + page, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + require.Len(t, page.Transfers, 1) + assert.Equal(t, txID, page.Transfers[0].TransactionID) + assert.Nil(t, page.NextCursor) + }) + + t.Run("default limit applied when limit is 0", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig, headers: mockHeaders}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + nonEmptyPage := accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{ + {BlockHeight: 1, TransactionID: unittest.IdentifierFixture()}, + }, + } + + blockID := unittest.IdentifierFixture() + nftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(newNFTSliceIter(nonEmptyPage.Transfers), nil) + mockHeaders.On("BlockIDByHeight", uint64(1)).Return(blockID, nil) + mockHeaders.On("ByBlockID", blockID).Return(unittest.BlockHeaderFixture(), nil) + + _, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("limit exceeding max returns InvalidArgument", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + _, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 500, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("cursor is forwarded to storage", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + mockHeaders := storagemock.NewHeaders(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig, headers: mockHeaders}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + cursor := &accessmodel.TransferCursor{BlockHeight: 50, TransactionIndex: 3, EventIndex: 1} + + nonEmptyPage := accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{ + {BlockHeight: 50, TransactionID: unittest.IdentifierFixture()}, + }, + } + + blockID := unittest.IdentifierFixture() + nftStore.On("ByAddress", addr, cursor). + Return(newNFTSliceIter(nonEmptyPage.Transfers), nil) + mockHeaders.On("BlockIDByHeight", uint64(50)).Return(blockID, nil) + mockHeaders.On("ByBlockID", blockID).Return(unittest.BlockHeaderFixture(), nil) + + _, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 10, cursor, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("invalid address returns NotFound", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.InvalidAddressFixture() + + _, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.NotFound, st.Code()) + }) + + t.Run("filter with both addresses neither matching account returns InvalidArgument", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + filter := AccountTransferFilter{ + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + } + + _, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 0, nil, filter, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("empty results with valid address returns empty page", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + nftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(newNFTSliceIter(nil), nil) + + page, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + assert.Empty(t, page.Transfers) + }) + + t.Run("ErrNotBootstrapped maps to FailedPrecondition", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + + nftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(nil, storage.ErrNotBootstrapped) + + _, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("ErrHeightNotIndexed maps to OutOfRange", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + cursor := &accessmodel.TransferCursor{BlockHeight: 999, TransactionIndex: 0, EventIndex: 0} + + nftStore.On("ByAddress", addr, cursor). + Return(nil, fmt.Errorf("wrapped: %w", storage.ErrHeightNotIndexed)) + + _, err := backend.GetAccountNonFungibleTokenTransfers( + context.Background(), addr, 10, cursor, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.OutOfRange, st.Code()) + }) + + t.Run("unexpected error triggers irrecoverable", func(t *testing.T) { + ftStore := storagemock.NewFungibleTokenTransfersBootstrapper(t) + nftStore := storagemock.NewNonFungibleTokenTransfersBootstrapper(t) + backend := NewAccountTransfersBackend(unittest.Logger(), &backendBase{config: defaultConfig}, ftStore, nftStore, flow.Testnet.Chain()) + + addr := unittest.RandomAddressFixture() + storageErr := fmt.Errorf("unexpected storage failure") + + nftStore.On("ByAddress", addr, (*accessmodel.TransferCursor)(nil)). + Return(nil, storageErr) + + expectedErr := fmt.Errorf("failed to get non-fungible token transfers: %w", storageErr) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), + irrecoverable.NewMockSignalerContextExpectError(t, context.Background(), expectedErr)) + + _, err := backend.GetAccountNonFungibleTokenTransfers( + signalerCtx, addr, 0, nil, AccountTransferFilter{}, AccountTransferExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + }) +} + +func TestAccountFTTransferFilter(t *testing.T) { + t.Parallel() + + senderAddr := unittest.RandomAddressFixture() + recipientAddr := unittest.RandomAddressFixture() + otherAddr := unittest.RandomAddressFixture() + + transfer := &accessmodel.FungibleTokenTransfer{ + TokenType: "A.1654653399040a61.FlowToken", + SourceAddress: senderAddr, + RecipientAddress: recipientAddr, + } + + t.Run("empty filter matches all", func(t *testing.T) { + filter := AccountTransferFilter{} + assert.Nil(t, filter.FTFilter(), "empty filter should return nil, indicating all transfers are accepted") + }) + + t.Run("token type filter matches", func(t *testing.T) { + filter := AccountTransferFilter{TokenType: "A.1654653399040a61.FlowToken"} + assert.True(t, filter.FTFilter()(transfer)) + }) + + t.Run("token type filter rejects mismatch", func(t *testing.T) { + filter := AccountTransferFilter{TokenType: "A.0xOther.USDC"} + assert.False(t, filter.FTFilter()(transfer)) + }) + + t.Run("source address filter matches", func(t *testing.T) { + filter := AccountTransferFilter{SourceAddress: senderAddr} + assert.True(t, filter.FTFilter()(transfer)) + }) + + t.Run("source address filter rejects mismatch", func(t *testing.T) { + filter := AccountTransferFilter{SourceAddress: otherAddr} + assert.False(t, filter.FTFilter()(transfer)) + }) + + t.Run("recipient address filter matches", func(t *testing.T) { + filter := AccountTransferFilter{RecipientAddress: recipientAddr} + assert.True(t, filter.FTFilter()(transfer)) + }) + + t.Run("recipient address filter rejects mismatch", func(t *testing.T) { + filter := AccountTransferFilter{RecipientAddress: otherAddr} + assert.False(t, filter.FTFilter()(transfer)) + }) + + t.Run("sender role matches when account is source", func(t *testing.T) { + filter := AccountTransferFilter{ + SourceAddress: senderAddr, + } + assert.True(t, filter.FTFilter()(transfer)) + }) + + t.Run("sender role rejects when account is not source", func(t *testing.T) { + filter := AccountTransferFilter{ + SourceAddress: recipientAddr, + } + assert.False(t, filter.FTFilter()(transfer)) + }) + + t.Run("recipient role matches when account is recipient", func(t *testing.T) { + filter := AccountTransferFilter{ + RecipientAddress: recipientAddr, + } + assert.True(t, filter.FTFilter()(transfer)) + }) + + t.Run("recipient role rejects when account is not recipient", func(t *testing.T) { + filter := AccountTransferFilter{ + RecipientAddress: senderAddr, + } + assert.False(t, filter.FTFilter()(transfer)) + }) + + t.Run("combined filters all match", func(t *testing.T) { + filter := AccountTransferFilter{ + TokenType: "A.1654653399040a61.FlowToken", + SourceAddress: senderAddr, + RecipientAddress: recipientAddr, + } + assert.True(t, filter.FTFilter()(transfer)) + }) + + t.Run("combined filters reject on first mismatch", func(t *testing.T) { + filter := AccountTransferFilter{ + TokenType: "A.0xOther.USDC", // mismatch + SourceAddress: senderAddr, // match + } + assert.False(t, filter.FTFilter()(transfer)) + }) + + t.Run("empty address fields are ignored", func(t *testing.T) { + filter := AccountTransferFilter{ + SourceAddress: flow.EmptyAddress, + RecipientAddress: flow.EmptyAddress, + } + assert.Nil(t, filter.FTFilter(), "filter with only empty addresses should return nil, indicating all transfers are accepted") + }) +} + +func TestAccountTransferFilter(t *testing.T) { + t.Parallel() + + senderAddr := unittest.RandomAddressFixture() + recipientAddr := unittest.RandomAddressFixture() + otherAddr := unittest.RandomAddressFixture() + + transfer := &accessmodel.NonFungibleTokenTransfer{ + TokenType: "A.1654653399040a61.MyNFT", + SourceAddress: senderAddr, + RecipientAddress: recipientAddr, + } + + t.Run("empty filter matches all", func(t *testing.T) { + filter := AccountTransferFilter{} + assert.Nil(t, filter.NFTFilter(), "empty filter should return nil, indicating all transfers are accepted") + }) + + t.Run("token type filter matches", func(t *testing.T) { + filter := AccountTransferFilter{TokenType: "A.1654653399040a61.MyNFT"} + assert.True(t, filter.NFTFilter()(transfer)) + }) + + t.Run("token type filter rejects mismatch", func(t *testing.T) { + filter := AccountTransferFilter{TokenType: "A.0xOther.OtherNFT"} + assert.False(t, filter.NFTFilter()(transfer)) + }) + + t.Run("source address filter matches", func(t *testing.T) { + filter := AccountTransferFilter{SourceAddress: senderAddr} + assert.True(t, filter.NFTFilter()(transfer)) + }) + + t.Run("source address filter rejects mismatch", func(t *testing.T) { + filter := AccountTransferFilter{SourceAddress: otherAddr} + assert.False(t, filter.NFTFilter()(transfer)) + }) + + t.Run("recipient address filter matches", func(t *testing.T) { + filter := AccountTransferFilter{RecipientAddress: recipientAddr} + assert.True(t, filter.NFTFilter()(transfer)) + }) + + t.Run("recipient address filter rejects mismatch", func(t *testing.T) { + filter := AccountTransferFilter{RecipientAddress: otherAddr} + assert.False(t, filter.NFTFilter()(transfer)) + }) + + t.Run("sender role matches when account is source", func(t *testing.T) { + filter := AccountTransferFilter{ + SourceAddress: senderAddr, + } + assert.True(t, filter.NFTFilter()(transfer)) + }) + + t.Run("sender role rejects when account is not source", func(t *testing.T) { + filter := AccountTransferFilter{ + SourceAddress: recipientAddr, + } + assert.False(t, filter.NFTFilter()(transfer)) + }) + + t.Run("recipient role matches when account is recipient", func(t *testing.T) { + filter := AccountTransferFilter{ + RecipientAddress: recipientAddr, + } + assert.True(t, filter.NFTFilter()(transfer)) + }) + + t.Run("recipient role rejects when account is not recipient", func(t *testing.T) { + filter := AccountTransferFilter{ + RecipientAddress: senderAddr, + } + assert.False(t, filter.NFTFilter()(transfer)) + }) + + t.Run("combined filters all match", func(t *testing.T) { + filter := AccountTransferFilter{ + TokenType: "A.1654653399040a61.MyNFT", + SourceAddress: senderAddr, + RecipientAddress: recipientAddr, + } + assert.True(t, filter.NFTFilter()(transfer)) + }) + + t.Run("combined filters reject on first mismatch", func(t *testing.T) { + filter := AccountTransferFilter{ + TokenType: "A.0xOther.OtherNFT", // mismatch + SourceAddress: senderAddr, // match + } + assert.False(t, filter.NFTFilter()(transfer)) + }) + + t.Run("empty address fields are ignored", func(t *testing.T) { + filter := AccountTransferFilter{ + SourceAddress: flow.EmptyAddress, + RecipientAddress: flow.EmptyAddress, + } + assert.Nil(t, filter.NFTFilter(), "filter with only empty addresses should return nil, indicating all transfers are accepted") + }) +} + +func TestAccountTransferFilter_Validate(t *testing.T) { + t.Parallel() + + account := unittest.RandomAddressFixture() + otherAddr1 := unittest.RandomAddressFixture() + otherAddr2 := unittest.RandomAddressFixture() + + tests := []struct { + name string + filter AccountTransferFilter + expectErr bool + }{ + { + name: "both addresses set and account is source", + filter: AccountTransferFilter{SourceAddress: account, RecipientAddress: otherAddr1}, + expectErr: false, + }, + { + name: "both addresses set and account is recipient", + filter: AccountTransferFilter{SourceAddress: otherAddr1, RecipientAddress: account}, + expectErr: false, + }, + { + name: "both addresses set and account is neither", + filter: AccountTransferFilter{SourceAddress: otherAddr1, RecipientAddress: otherAddr2}, + expectErr: true, + }, + { + name: "only source set", + filter: AccountTransferFilter{SourceAddress: otherAddr1}, + expectErr: false, + }, + { + name: "only recipient set", + filter: AccountTransferFilter{RecipientAddress: otherAddr1}, + expectErr: false, + }, + { + name: "empty filter", + filter: AccountTransferFilter{}, + expectErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.filter.validate(account) + if tt.expectErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} diff --git a/access/backends/extended/backend_base.go b/access/backends/extended/backend_base.go new file mode 100644 index 00000000000..a63e43aff4b --- /dev/null +++ b/access/backends/extended/backend_base.go @@ -0,0 +1,141 @@ +package extended + +import ( + "context" + "errors" + "fmt" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/provider" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/access/systemcollection" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// backendBase holds shared configuration, storage dependencies, and helper methods used by both +// the account transactions and account transfers backends. +type backendBase struct { + config Config + + headers storage.Headers + blocks storage.Blocks + collections storage.CollectionsReader + transactions storage.TransactionsReader + scheduledTransactions storage.ScheduledTransactionsReader + + transactionsProvider provider.TransactionProvider + systemCollections *systemcollection.Versioned +} + +// normalizeLimit applies default page size when limit is 0, and returns an error if the limit +// exceeds the configured maximum. +// +// Any error indicates the limit is invalid. +func (b *backendBase) normalizeLimit(limit uint32) (uint32, error) { + if limit == 0 { + return b.config.DefaultPageSize, nil + } + if limit > b.config.MaxPageSize { + return 0, fmt.Errorf("limit exceeds maximum: %d > %d", limit, b.config.MaxPageSize) + } + return limit, nil +} + +// getTransactionResult retrieves the transaction result for a given transaction. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound] if the transaction is not found +func (b *backendBase) getTransactionResult( + ctx context.Context, + txID flow.Identifier, + header *flow.Header, + isSystemChunkTx bool, + expandTransaction bool, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.TransactionResult, error) { + // the system collection is not indexed and uses the zero ID by convention. + var collectionID flow.Identifier + + if !isSystemChunkTx { + collection, err := b.collections.LightByTransactionID(txID) + if err != nil { + if !errors.Is(err, storage.ErrNotFound) { + return nil, fmt.Errorf("could not retrieve collection: %w", err) + } + // if we have already looked up the transaction and confirmed it is NOT a system chunk tx, + // then there should be an entry in the tx/collection index. however, the collection/tx + // index is built asynchronously with the extended indexer and may not be available yet. + // return an error, but don't throw an irrecoverable error. + if expandTransaction { + return nil, fmt.Errorf("could not retrieve collection for standard transaction: %w", err) + } + // if the collection is not found and we're not expanding the transaction, + // proceed with zero collectionID. + } else { + collectionID = collection.ID() + } + } + + result, err := b.transactionsProvider.TransactionResult(ctx, header, txID, collectionID, encodingVersion) + if err != nil { + return nil, fmt.Errorf("could not retrieve transaction result: %w", err) + } + + return result, nil +} + +// getTransactionBody retrieves the transaction body for the given transaction ID. +// It checks submitted transactions, system transactions, and scheduled transactions in order. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound] if the transaction is not found +func (b *backendBase) getTransactionBody(ctx context.Context, header *flow.Header, txID flow.Identifier) (*flow.TransactionBody, bool, error) { + // first, check if it's a submitted transaction since that's the most common + txBody, err := b.transactions.ByID(txID) + if err == nil { + return txBody, false, nil + } + if !errors.Is(err, storage.ErrNotFound) { + return nil, false, fmt.Errorf("failed to retrieve transaction body: %w", err) + } + + // next, check if the transaction is a system transaction because it's the cheapest lookup + systemTx, ok := b.systemCollections.SearchAll(txID) + if ok { + return systemTx, true, nil + } + + // finally, check if it's a scheduled transaction + blockID, err := b.scheduledTransactions.BlockIDByTransactionID(txID) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + return nil, false, fmt.Errorf("transaction not found: %w", err) + } + return nil, false, fmt.Errorf("could not retrieve scheduled transaction block ID: %w", err) + } + + // the provided header was looked up based on data stored in the db for the account transaction. + // if the transaction is a scheduled transaction, it must match the block ID indexed for the + // scheduled transaction, otherwise the node is in an inconsistent state. + if blockID != header.ID() { + return nil, false, fmt.Errorf("scheduled transaction found in block %s, but %s was provided", blockID, header.ID()) + } + + allScheduledTxs, err := b.transactionsProvider.ScheduledTransactionsByBlockID(ctx, header) + if err != nil { + return nil, false, fmt.Errorf("could not retrieve all scheduled transactions: %w", err) + } + + for _, scheduledTx := range allScheduledTxs { + if scheduledTx.ID() == txID { + return scheduledTx, true, nil + } + } + + // at this point, the transaction is not known to the node. + // this is unexpected. if the account transaction was indexed, then the transaction should be found + // somewhere in storage. + return nil, false, fmt.Errorf("indexed transaction not found: %w", storage.ErrNotFound) +} diff --git a/access/backends/extended/backend_contracts.go b/access/backends/extended/backend_contracts.go new file mode 100644 index 00000000000..8c6f739a8c4 --- /dev/null +++ b/access/backends/extended/backend_contracts.go @@ -0,0 +1,353 @@ +package extended + +import ( + "context" + "fmt" + + "github.com/onflow/flow/protobuf/go/flow/entities" + "github.com/rs/zerolog" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" +) + +type ContractDeploymentExpandOptions struct { + Code bool + Transaction bool + Result bool +} + +func (o *ContractDeploymentExpandOptions) HasExpand() bool { + return o.Transaction || o.Result +} + +// ContractDeploymentFilter specifies optional filter criteria for contract deployment queries. +// All fields are optional; nil/zero fields are ignored. +type ContractDeploymentFilter struct { + // ContractName is a partial match against the name component of the contract identifier + // (e.g. "A.{addr}.{name}"). + ContractName string + // StartBlock is an inclusive block height lower bound. + StartBlock *uint64 + // EndBlock is an inclusive block height upper bound. + EndBlock *uint64 +} + +// Filter builds a [storage.IndexFilter] from the non-nil filter fields. +func (f *ContractDeploymentFilter) Filter() storage.IndexFilter[*accessmodel.ContractDeployment] { + // No nil filters. Always filter out deleted contracts. + // When deleting contracts is eventually supported, make this a configurable option. for now, + // always remove deleted contracts from the results. + + return func(d *accessmodel.ContractDeployment) bool { + if d.IsDeleted { + return false + } + if f.ContractName != "" && d.ContractName != f.ContractName { + return false + } + if f.StartBlock != nil && d.BlockHeight < *f.StartBlock { + return false + } + if f.EndBlock != nil && d.BlockHeight > *f.EndBlock { + return false + } + return true + } +} + +// ContractsBackend implements the contracts portion of the extended API. +type ContractsBackend struct { + *backendBase + + log zerolog.Logger + store storage.ContractDeploymentsIndexReader +} + +// NewContractsBackend creates a new [ContractsBackend]. +func NewContractsBackend( + log zerolog.Logger, + base *backendBase, + store storage.ContractDeploymentsIndexReader, +) *ContractsBackend { + return &ContractsBackend{ + backendBase: base, + log: log, + store: store, + } +} + +// GetContract returns the most recent deployment of the contract with the given identifier. +// +// Expected error returns during normal operations: +// - [codes.NotFound]: if no contract with the given identifier exists +// - [codes.FailedPrecondition]: if the index has not been initialized +func (b *ContractsBackend) GetContract( + ctx context.Context, + id string, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.ContractDeployment, error) { + account, contractName, err := accessmodel.ParseContractID(id) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid contract identifier: %v", err) + } + + if filter.ContractName != "" && contractName != filter.ContractName { + return nil, status.Errorf(codes.InvalidArgument, "contract name filter is not supported for single contract requests") + } + + deployment, err := b.store.ByContract(account, contractName) + if err != nil { + return nil, mapReadError(ctx, "contract", err) + } + + if expandOptions.HasExpand() { + if err := b.expand(ctx, &deployment, expandOptions, encodingVersion); err != nil { + err = fmt.Errorf("failed to expand contract deployment %s: %w", id, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + } + + // code is always loaded from storage, so remove it if not requested + if !expandOptions.Code { + deployment.Code = nil + } + + return &deployment, nil +} + +// GetContractDeployments returns a paginated list of all deployments of the given contract, +// most recent first (descending by block height, then by TxIndex, then by EventIndex). +// +// Expected error returns during normal operations: +// - [codes.NotFound]: if no contract with the given identifier exists +// - [codes.FailedPrecondition]: if the index has not been initialized +// - [codes.InvalidArgument]: if query parameters are invalid +func (b *ContractsBackend) GetContractDeployments( + ctx context.Context, + id string, + limit uint32, + cursor *accessmodel.ContractDeploymentsCursor, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.ContractDeploymentPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + account, contractName, err := accessmodel.ParseContractID(id) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid contract identifier: %v", err) + } + + if filter.ContractName != "" && contractName != filter.ContractName { + return nil, status.Errorf(codes.InvalidArgument, "contract name filter is not supported for single contract requests") + } + + if cursor != nil { + // ignore address/contract name passed by the caller + cursor.Address = account + cursor.ContractName = contractName + } + + iter, err := b.store.DeploymentsByContract(account, contractName, cursor) + if err != nil { + return nil, mapReadError(ctx, "contract deployments", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.Filter()) + if err != nil { + err = fmt.Errorf("error collecting contract deployments: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := &accessmodel.ContractDeploymentPage{ + Deployments: collected, + NextCursor: nextCursor, + } + + if expandOptions.HasExpand() { + for i := range page.Deployments { + deployment := &page.Deployments[i] + if err := b.expand(ctx, deployment, expandOptions, encodingVersion); err != nil { + err = fmt.Errorf("failed to expand contract deployment at height %d: %w", deployment.BlockHeight, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + } + } + + // code is always loaded from storage, so remove it if not requested + if !expandOptions.Code { + for i := range page.Deployments { + page.Deployments[i].Code = nil + } + } + + return page, nil +} + +// GetContracts returns a paginated list of contracts at their latest deployment. +// +// Expected error returns during normal operations: +// - [codes.FailedPrecondition]: if the index has not been initialized +// - [codes.InvalidArgument]: if query parameters are invalid +func (b *ContractsBackend) GetContracts( + ctx context.Context, + limit uint32, + cursor *accessmodel.ContractDeploymentsCursor, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.ContractDeploymentPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + iter, err := b.store.All(cursor) + if err != nil { + return nil, mapReadError(ctx, "contracts", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.Filter()) + if err != nil { + err = fmt.Errorf("error collecting contracts: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := &accessmodel.ContractDeploymentPage{ + Deployments: collected, + NextCursor: nextCursor, + } + + if expandOptions.HasExpand() { + for i := range page.Deployments { + deployment := &page.Deployments[i] + if err := b.expand(ctx, deployment, expandOptions, encodingVersion); err != nil { + contractID := accessmodel.ContractID(deployment.Address, deployment.ContractName) + err = fmt.Errorf("failed to expand contract deployment %s: %w", contractID, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + } + } + + // code is always loaded from storage, so remove it if not requested + if !expandOptions.Code { + for i := range page.Deployments { + page.Deployments[i].Code = nil + } + } + + return page, nil +} + +// GetContractsByAddress returns a paginated list of contracts at their latest deployment for +// the given address. +// +// Expected error returns during normal operations: +// - [codes.FailedPrecondition]: if the index has not been initialized +// - [codes.InvalidArgument]: if query parameters are invalid +func (b *ContractsBackend) GetContractsByAddress( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.ContractDeploymentsCursor, + filter ContractDeploymentFilter, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.ContractDeploymentPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + if cursor != nil { + // ignore any address passed by the caller + cursor.Address = address + } + + iter, err := b.store.ByAddress(address, cursor) + if err != nil { + return nil, mapReadError(ctx, "contracts", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.Filter()) + if err != nil { + err = fmt.Errorf("error collecting contracts by address: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := &accessmodel.ContractDeploymentPage{ + Deployments: collected, + NextCursor: nextCursor, + } + + if expandOptions.HasExpand() { + for i := range page.Deployments { + deployment := &page.Deployments[i] + if err := b.expand(ctx, deployment, expandOptions, encodingVersion); err != nil { + contractID := accessmodel.ContractID(deployment.Address, deployment.ContractName) + err = fmt.Errorf("failed to expand contract deployment %s: %w", contractID, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + } + } + + // code is always loaded from storage, so remove it if not requested + if !expandOptions.Code { + for i := range page.Deployments { + page.Deployments[i].Code = nil + } + } + + return page, nil +} + +func (b *ContractsBackend) expand( + ctx context.Context, + deployment *accessmodel.ContractDeployment, + expandOptions ContractDeploymentExpandOptions, + encodingVersion entities.EventEncodingVersion, +) error { + header, err := b.headers.ByHeight(deployment.BlockHeight) + if err != nil { + return fmt.Errorf("could not retrieve block header: %w", err) + } + + var isSystemChunkTx bool + if expandOptions.Transaction { + var txBody *flow.TransactionBody + var err error + txBody, isSystemChunkTx, err = b.getTransactionBody(ctx, header, deployment.TransactionID) + if err != nil { + return fmt.Errorf("could not retrieve transaction body: %w", err) + } + deployment.Transaction = txBody + } + + if expandOptions.Result { + result, err := b.getTransactionResult(ctx, deployment.TransactionID, header, isSystemChunkTx, expandOptions.Transaction, encodingVersion) + if err != nil { + return fmt.Errorf("could not retrieve transaction result: %w", err) + } + deployment.Result = result + } + + return nil +} diff --git a/access/backends/extended/backend_contracts_test.go b/access/backends/extended/backend_contracts_test.go new file mode 100644 index 00000000000..6365edd753c --- /dev/null +++ b/access/backends/extended/backend_contracts_test.go @@ -0,0 +1,736 @@ +package extended + +import ( + "context" + "fmt" + "testing" + + "github.com/onflow/flow/protobuf/go/flow/entities" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/storage" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/utils/unittest" +) + +// makeContractDeployment builds a minimal ContractDeployment for use in backend tests. +// contractID must have the format "A.{16hex}.{name}". +func makeContractDeployment(tb testing.TB, contractID string, height uint64) accessmodel.ContractDeployment { + tb.Helper() + addr, name, err := accessmodel.ParseContractID(contractID) + require.NoError(tb, err) + return accessmodel.ContractDeployment{ + Address: addr, + ContractName: name, + BlockHeight: height, + TransactionID: unittest.IdentifierFixture(), + Code: []byte("access(all) contract Foo {}"), + CodeHash: make([]byte, 32), + } +} + +// testIterEntry is a storage.IteratorEntry used by both deployment-history and contracts iterators. +// The cursor is pre-computed at construction time via newDeploymentHistoryEntry or newContractsEntry. +type testIterEntry struct { + d accessmodel.ContractDeployment + cursor accessmodel.ContractDeploymentsCursor +} + +func (e testIterEntry) Cursor() accessmodel.ContractDeploymentsCursor { return e.cursor } +func (e testIterEntry) Value() (accessmodel.ContractDeployment, error) { return e.d, nil } + +// newDeploymentHistoryEntry builds a testIterEntry whose cursor is keyed by +// BlockHeight/TransactionIndex/EventIndex (used by DeploymentsByContract). +func newDeploymentHistoryEntry(d accessmodel.ContractDeployment) testIterEntry { + return testIterEntry{d: d, cursor: accessmodel.ContractDeploymentsCursor{ + BlockHeight: d.BlockHeight, + TransactionIndex: d.TransactionIndex, + EventIndex: d.EventIndex, + }} +} + +// newContractsEntry builds a testIterEntry whose cursor is keyed by Address/ContractName +// (used by All and ByAddress). +func newContractsEntry(d accessmodel.ContractDeployment) testIterEntry { + return testIterEntry{d: d, cursor: accessmodel.ContractDeploymentsCursor{ + Address: d.Address, + ContractName: d.ContractName, + }} +} + +// makeContractDeploymentIter builds a storage.ContractDeploymentIterator from a slice of deployments. +// Used for DeploymentsByContractID (cursor type: ContractDeploymentsCursor). +func makeContractDeploymentIter(deployments []accessmodel.ContractDeployment) storage.ContractDeploymentIterator { + return func(yield func(storage.IteratorEntry[accessmodel.ContractDeployment, accessmodel.ContractDeploymentsCursor], error) bool) { + for _, d := range deployments { + if !yield(newDeploymentHistoryEntry(d), nil) { + return + } + } + } +} + +// makeContractsIter builds a storage.ContractDeploymentIterator from a slice of deployments. +// Used for All and ByAddress (cursor type: ContractsCursor). +func makeContractsIter(deployments []accessmodel.ContractDeployment) storage.ContractDeploymentIterator { + return func(yield func(storage.IteratorEntry[accessmodel.ContractDeployment, accessmodel.ContractDeploymentsCursor], error) bool) { + for _, d := range deployments { + if !yield(newContractsEntry(d), nil) { + return + } + } + } +} + +// makeIterWithError returns an iterator that immediately yields the given error. +// Used to test error handling in CollectResults. +func makeIterWithError(err error) storage.ContractDeploymentIterator { + return func(yield func(storage.IteratorEntry[accessmodel.ContractDeployment, accessmodel.ContractDeploymentsCursor], error) bool) { + yield(nil, err) + } +} + +// contractSignalerCtxExpectingThrow returns a context and a verify function that asserts +// irrecoverable.Throw was called exactly once. The context is built with +// [irrecoverable.WithSignalerContext] so that [irrecoverable.Throw] can locate the signaler +// via the context value chain. +func contractSignalerCtxExpectingThrow(t *testing.T) (context.Context, func()) { + t.Helper() + thrown := make(chan error, 1) + m := irrecoverable.NewMockSignalerContextWithCallback(t, context.Background(), func(err error) { + thrown <- err + }) + ctx := irrecoverable.WithSignalerContext(context.Background(), m) + verify := func() { + t.Helper() + select { + case err := <-thrown: + require.Error(t, err) + default: + t.Fatal("expected irrecoverable.Throw to be called but it was not") + } + } + return ctx, verify +} + +// TestContractsBackend_GetContract tests all code paths for GetContract. +func TestContractsBackend_GetContract(t *testing.T) { + t.Parallel() + + contractID := "A.0000000000000001.FungibleToken" + contractAddr := flow.HexToAddress("0000000000000001") + contractName := "FungibleToken" + deployment := makeContractDeployment(t, contractID, 42) + + t.Run("happy path returns deployment", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + mockStore.On("ByContract", contractAddr, contractName).Return(deployment, nil).Once() + + result, err := backend.GetContract(context.Background(), contractID, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.NotNil(t, result) + assert.Equal(t, contractID, accessmodel.ContractID(result.Address, result.ContractName)) + assert.Equal(t, uint64(42), result.BlockHeight) + }) + + t.Run("ErrNotFound returns codes.NotFound", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + mockStore.On("ByContract", contractAddr, contractName).Return(accessmodel.ContractDeployment{}, storage.ErrNotFound).Once() + + _, err := backend.GetContract(context.Background(), contractID, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.NotFound, st.Code()) + }) + + t.Run("ErrNotBootstrapped returns codes.FailedPrecondition", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + mockStore.On("ByContract", contractAddr, contractName).Return(accessmodel.ContractDeployment{}, storage.ErrNotBootstrapped).Once() + + _, err := backend.GetContract(context.Background(), contractID, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("unexpected error triggers irrecoverable", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + unexpectedErr := fmt.Errorf("disk failure") + mockStore.On("ByContract", contractAddr, contractName).Return(accessmodel.ContractDeployment{}, unexpectedErr).Once() + + signalerCtx, verifyThrown := contractSignalerCtxExpectingThrow(t) + _, err := backend.GetContract(signalerCtx, contractID, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + verifyThrown() + }) + + t.Run("invalid contract ID returns codes.InvalidArgument", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + _, err := backend.GetContract(context.Background(), "notavalidid", ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("mismatched contract name filter returns codes.InvalidArgument", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + // contractID contains "FungibleToken" but filter specifies a different name + _, err := backend.GetContract(context.Background(), contractID, + ContractDeploymentFilter{ContractName: "FlowToken"}, + ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) +} + +// TestContractsBackend_GetContractDeployments tests all code paths for GetContractDeployments. +func TestContractsBackend_GetContractDeployments(t *testing.T) { + t.Parallel() + + contractID := "A.0000000000000001.FungibleToken" + contractAddr := flow.HexToAddress("0000000000000001") + contractName := "FungibleToken" + + t.Run("happy path returns page without next cursor", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, contractID, 50), + makeContractDeployment(t, contractID, 30), + } + mockStore.On("DeploymentsByContract", contractAddr, contractName, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractDeploymentIter(deployments), nil).Once() + + result, err := backend.GetContractDeployments(context.Background(), contractID, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.NotNil(t, result) + assert.Len(t, result.Deployments, 2) + assert.Nil(t, result.NextCursor) + }) + + t.Run("has more results sets NextCursor", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + // Provide 2 items for limit=1: first is returned, second becomes the cursor. + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, contractID, 50), + makeContractDeployment(t, contractID, 30), // cursor item (first of next page) + } + mockStore.On("DeploymentsByContract", contractAddr, contractName, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractDeploymentIter(deployments), nil).Once() + + result, err := backend.GetContractDeployments(context.Background(), contractID, 1, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.NotNil(t, result.NextCursor) + assert.Equal(t, uint64(30), result.NextCursor.BlockHeight) + }) + + t.Run("cursor forwarded to store", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + cursor := &accessmodel.ContractDeploymentsCursor{BlockHeight: 30, TransactionIndex: 1, EventIndex: 2} + mockStore.On("DeploymentsByContract", contractAddr, contractName, cursor). + Return(makeContractDeploymentIter(nil), nil).Once() + + _, err := backend.GetContractDeployments(context.Background(), contractID, 10, cursor, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + }) + + t.Run("limit exceeds max returns codes.InvalidArgument", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + _, err := backend.GetContractDeployments(context.Background(), contractID, DefaultConfig().MaxPageSize+1, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("ErrNotBootstrapped returns codes.FailedPrecondition", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + mockStore.On("DeploymentsByContract", contractAddr, contractName, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(nil, storage.ErrNotBootstrapped).Once() + + _, err := backend.GetContractDeployments(context.Background(), contractID, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("unexpected error triggers irrecoverable", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + unexpectedErr := fmt.Errorf("disk failure") + mockStore.On("DeploymentsByContract", contractAddr, contractName, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(nil, unexpectedErr).Once() + + signalerCtx, verifyThrown := contractSignalerCtxExpectingThrow(t) + _, err := backend.GetContractDeployments(signalerCtx, contractID, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + verifyThrown() + }) + + t.Run("iterator error triggers irrecoverable", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + iterErr := fmt.Errorf("storage read failure") + mockStore.On("DeploymentsByContract", contractAddr, contractName, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeIterWithError(iterErr), nil).Once() + + signalerCtx, verifyThrown := contractSignalerCtxExpectingThrow(t) + _, err := backend.GetContractDeployments(signalerCtx, contractID, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + verifyThrown() + }) + + t.Run("filter excludes out-of-range deployments", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, contractID, 50), + makeContractDeployment(t, contractID, 30), + makeContractDeployment(t, contractID, 10), + } + mockStore.On("DeploymentsByContract", contractAddr, contractName, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractDeploymentIter(deployments), nil).Once() + + start, end := uint64(20), uint64(40) + result, err := backend.GetContractDeployments(context.Background(), contractID, 0, nil, + ContractDeploymentFilter{StartBlock: &start, EndBlock: &end}, + ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.Len(t, result.Deployments, 1) + assert.Equal(t, uint64(30), result.Deployments[0].BlockHeight) + }) + + t.Run("invalid contract ID returns codes.InvalidArgument", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + _, err := backend.GetContractDeployments(context.Background(), "notavalidid", 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("mismatched contract name filter returns codes.InvalidArgument", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + // contractID contains "FungibleToken" but filter specifies a different name + _, err := backend.GetContractDeployments(context.Background(), contractID, 0, nil, + ContractDeploymentFilter{ContractName: "FlowToken"}, + ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) +} + +// TestContractsBackend_GetContracts tests all code paths for GetContracts. +func TestContractsBackend_GetContracts(t *testing.T) { + t.Parallel() + + t.Run("happy path returns page", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, "A.0000000000000001.FungibleToken", 10), + makeContractDeployment(t, "A.0000000000000002.FlowToken", 11), + } + mockStore.On("All", (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractsIter(deployments), nil).Once() + + result, err := backend.GetContracts(context.Background(), 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.NotNil(t, result) + assert.Len(t, result.Deployments, 2) + assert.Nil(t, result.NextCursor) + }) + + t.Run("has more results sets NextCursor", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + // Provide 2 items for limit=1: first is returned, second becomes the cursor. + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, "A.0000000000000001.FungibleToken", 10), + makeContractDeployment(t, "A.0000000000000002.FlowToken", 11), // cursor item + } + mockStore.On("All", (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractsIter(deployments), nil).Once() + + result, err := backend.GetContracts(context.Background(), 1, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.NotNil(t, result.NextCursor) + assert.Equal(t, flow.HexToAddress("0000000000000002"), result.NextCursor.Address) + assert.Equal(t, "FlowToken", result.NextCursor.ContractName) + }) + + t.Run("cursor forwarded to store", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + cursor := &accessmodel.ContractDeploymentsCursor{Address: flow.HexToAddress("0000000000000001"), ContractName: "FungibleToken"} + mockStore.On("All", cursor). + Return(makeContractsIter(nil), nil).Once() + + _, err := backend.GetContracts(context.Background(), 5, cursor, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + }) + + t.Run("limit exceeds max returns codes.InvalidArgument", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + _, err := backend.GetContracts(context.Background(), DefaultConfig().MaxPageSize+1, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("ErrNotBootstrapped returns codes.FailedPrecondition", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + mockStore.On("All", (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(nil, storage.ErrNotBootstrapped).Once() + + _, err := backend.GetContracts(context.Background(), 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("unexpected error triggers irrecoverable", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + unexpectedErr := fmt.Errorf("disk failure") + mockStore.On("All", (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(nil, unexpectedErr).Once() + + signalerCtx, verifyThrown := contractSignalerCtxExpectingThrow(t) + _, err := backend.GetContracts(signalerCtx, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + verifyThrown() + }) + + t.Run("iterator error triggers irrecoverable", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + iterErr := fmt.Errorf("storage read failure") + mockStore.On("All", (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeIterWithError(iterErr), nil).Once() + + signalerCtx, verifyThrown := contractSignalerCtxExpectingThrow(t) + _, err := backend.GetContracts(signalerCtx, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + verifyThrown() + }) + + t.Run("filter by contract name excludes non-matching contracts", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, "A.0000000000000001.FungibleToken", 10), + makeContractDeployment(t, "A.0000000000000002.FlowToken", 11), + } + mockStore.On("All", (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractsIter(deployments), nil).Once() + + result, err := backend.GetContracts(context.Background(), 0, nil, + ContractDeploymentFilter{ContractName: "FungibleToken"}, + ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.Len(t, result.Deployments, 1) + assert.Equal(t, "FungibleToken", result.Deployments[0].ContractName) + }) +} + +// TestContractsBackend_GetContractsByAddress tests all code paths for GetContractsByAddress. +func TestContractsBackend_GetContractsByAddress(t *testing.T) { + t.Parallel() + + addr := unittest.RandomAddressFixture() + + t.Run("happy path returns page for address", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + contractID := fmt.Sprintf("A.%s.Foo", addr.Hex()) + deployments := []accessmodel.ContractDeployment{makeContractDeployment(t, contractID, 15)} + mockStore.On("ByAddress", addr, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractsIter(deployments), nil).Once() + + result, err := backend.GetContractsByAddress(context.Background(), addr, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.NotNil(t, result) + require.Len(t, result.Deployments, 1) + assert.Equal(t, contractID, accessmodel.ContractID(result.Deployments[0].Address, result.Deployments[0].ContractName)) + }) + + t.Run("has more results sets NextCursor", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + contractID1 := fmt.Sprintf("A.%s.Bar", addr.Hex()) + contractID2 := fmt.Sprintf("A.%s.Foo", addr.Hex()) + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, contractID1, 10), + makeContractDeployment(t, contractID2, 11), // cursor item (first of next page) + } + mockStore.On("ByAddress", addr, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractsIter(deployments), nil).Once() + + result, err := backend.GetContractsByAddress(context.Background(), addr, 1, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.NotNil(t, result.NextCursor) + assert.Equal(t, addr, result.NextCursor.Address) + assert.Equal(t, "Foo", result.NextCursor.ContractName) + }) + + t.Run("cursor forwarded to store", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + cursor := &accessmodel.ContractDeploymentsCursor{Address: addr, ContractName: "Foo"} + mockStore.On("ByAddress", addr, cursor). + Return(makeContractsIter(nil), nil).Once() + + _, err := backend.GetContractsByAddress(context.Background(), addr, 10, cursor, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + }) + + t.Run("limit exceeds max returns codes.InvalidArgument", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + _, err := backend.GetContractsByAddress(context.Background(), addr, DefaultConfig().MaxPageSize+1, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("ErrNotBootstrapped returns codes.FailedPrecondition", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + mockStore.On("ByAddress", addr, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(nil, storage.ErrNotBootstrapped).Once() + + _, err := backend.GetContractsByAddress(context.Background(), addr, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("unexpected error triggers irrecoverable", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + unexpectedErr := fmt.Errorf("disk failure") + mockStore.On("ByAddress", addr, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(nil, unexpectedErr).Once() + + signalerCtx, verifyThrown := contractSignalerCtxExpectingThrow(t) + _, err := backend.GetContractsByAddress(signalerCtx, addr, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + verifyThrown() + }) + + t.Run("iterator error triggers irrecoverable", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + iterErr := fmt.Errorf("storage read failure") + mockStore.On("ByAddress", addr, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeIterWithError(iterErr), nil).Once() + + signalerCtx, verifyThrown := contractSignalerCtxExpectingThrow(t) + _, err := backend.GetContractsByAddress(signalerCtx, addr, 0, nil, ContractDeploymentFilter{}, ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.Error(t, err) + verifyThrown() + }) + + t.Run("filter excludes out-of-range contracts", func(t *testing.T) { + t.Parallel() + mockStore := storagemock.NewContractDeploymentsIndexReader(t) + backend := NewContractsBackend(unittest.Logger(), &backendBase{config: DefaultConfig()}, mockStore) + + contractID1 := fmt.Sprintf("A.%s.Bar", addr.Hex()) + contractID2 := fmt.Sprintf("A.%s.Foo", addr.Hex()) + deployments := []accessmodel.ContractDeployment{ + makeContractDeployment(t, contractID1, 10), + makeContractDeployment(t, contractID2, 50), + } + mockStore.On("ByAddress", addr, (*accessmodel.ContractDeploymentsCursor)(nil)). + Return(makeContractsIter(deployments), nil).Once() + + end := uint64(30) + result, err := backend.GetContractsByAddress(context.Background(), addr, 0, nil, + ContractDeploymentFilter{EndBlock: &end}, + ContractDeploymentExpandOptions{}, entities.EventEncodingVersion_JSON_CDC_V0) + require.NoError(t, err) + require.Len(t, result.Deployments, 1) + assert.Equal(t, "Bar", result.Deployments[0].ContractName) + }) +} + +// TestContractDeploymentFilter tests the Filter() predicate builder. +func TestContractDeploymentFilter(t *testing.T) { + t.Parallel() + + addr := unittest.RandomAddressFixture() + + foo := &accessmodel.ContractDeployment{Address: addr, ContractName: "FungibleToken", BlockHeight: 100} + bar := &accessmodel.ContractDeployment{Address: addr, ContractName: "FlowToken", BlockHeight: 200} + + t.Run("empty filter always filters deleted contracts", func(t *testing.T) { + t.Parallel() + f := ContractDeploymentFilter{} + filter := f.Filter() + require.NotNil(t, filter) + assert.True(t, filter(foo), "non-deleted contract passes empty filter") + deleted := &accessmodel.ContractDeployment{Address: addr, ContractName: "FungibleToken", BlockHeight: 100, IsDeleted: true} + assert.False(t, filter(deleted), "deleted contract is filtered out") + }) + + t.Run("ContractName exact match filters non-matching names", func(t *testing.T) { + t.Parallel() + // Filter{ContractName: "FungibleToken"}: matching name passes, non-matching name fails. + f := ContractDeploymentFilter{ContractName: "FungibleToken"} + filter := f.Filter() + assert.True(t, filter(foo), "FungibleToken matches → true") + assert.False(t, filter(bar), "FlowToken doesn't match FungibleToken → false") + }) + + t.Run("ContractName with block range excludes non-matching out-of-range contract", func(t *testing.T) { + t.Parallel() + // bar is at height 200; set EndBlock=150 so bar fails the block range check. + end := uint64(150) + f := ContractDeploymentFilter{ContractName: "FungibleToken", EndBlock: &end} + filter := f.Filter() + assert.True(t, filter(foo), "FungibleToken matches name → early true, block range ignored") + assert.False(t, filter(bar), "FlowToken fails name and height 200 > EndBlock 150 → false") + }) + + t.Run("StartBlock excludes deployments before the bound", func(t *testing.T) { + t.Parallel() + start := uint64(150) + f := ContractDeploymentFilter{StartBlock: &start} + filter := f.Filter() + assert.False(t, filter(foo), "height 100 < StartBlock 150 should be excluded") + assert.True(t, filter(bar), "height 200 >= StartBlock 150 should be included") + }) + + t.Run("EndBlock excludes deployments after the bound", func(t *testing.T) { + t.Parallel() + end := uint64(150) + f := ContractDeploymentFilter{EndBlock: &end} + filter := f.Filter() + assert.True(t, filter(foo), "height 100 <= EndBlock 150 should be included") + assert.False(t, filter(bar), "height 200 > EndBlock 150 should be excluded") + }) + + t.Run("StartBlock and EndBlock window", func(t *testing.T) { + t.Parallel() + start := uint64(50) + end := uint64(150) + f := ContractDeploymentFilter{StartBlock: &start, EndBlock: &end} + filter := f.Filter() + assert.True(t, filter(foo), "height 100 within [50, 150] should be included") + assert.False(t, filter(bar), "height 200 outside [50, 150] should be excluded") + }) + + t.Run("StartBlock boundary is inclusive", func(t *testing.T) { + t.Parallel() + start := uint64(100) // exactly foo's height + f := ContractDeploymentFilter{StartBlock: &start} + filter := f.Filter() + assert.True(t, filter(foo), "height 100 == StartBlock 100 should be included") + assert.True(t, filter(bar), "height 200 > StartBlock 100 should be included") + }) + + t.Run("EndBlock boundary is inclusive", func(t *testing.T) { + t.Parallel() + end := uint64(100) // exactly foo's height + f := ContractDeploymentFilter{EndBlock: &end} + filter := f.Filter() + assert.True(t, filter(foo), "height 100 == EndBlock 100 should be included") + assert.False(t, filter(bar), "height 200 > EndBlock 100 should be excluded") + }) +} diff --git a/access/backends/extended/backend_scheduled_transactions.go b/access/backends/extended/backend_scheduled_transactions.go new file mode 100644 index 00000000000..d04eb8b1e43 --- /dev/null +++ b/access/backends/extended/backend_scheduled_transactions.go @@ -0,0 +1,507 @@ +package extended + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/onflow/flow/protobuf/go/flow/entities" + "github.com/rs/zerolog" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/execution" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" +) + +type ScheduledTransactionExpandOptions struct { + Result bool + Transaction bool + HandlerContract bool +} + +func (o *ScheduledTransactionExpandOptions) HasExpand() bool { + return o.Result || o.Transaction || o.HandlerContract +} + +// ScheduledTransactionFilter specifies optional filter criteria for scheduled transaction queries. +// All fields are optional; nil/zero fields are ignored. +type ScheduledTransactionFilter struct { + Statuses []accessmodel.ScheduledTransactionStatus + Priority *accessmodel.ScheduledTransactionPriority + StartTime *uint64 // inclusive UFix64 timestamp lower bound + EndTime *uint64 // inclusive UFix64 timestamp upper bound + TransactionHandlerOwner *flow.Address + TransactionHandlerTypeID *string + TransactionHandlerUUID *uint64 +} + +func (f *ScheduledTransactionFilter) isEmpty() bool { + if f == nil { + return true + } + if len(f.Statuses) == 0 && + f.Priority == nil && + f.StartTime == nil && + f.EndTime == nil && + f.TransactionHandlerOwner == nil && + f.TransactionHandlerTypeID == nil && + f.TransactionHandlerUUID == nil { + return true + } + return false +} + +// Filter builds a [storage.IndexFilter] from the non-nil filter fields. +func (f *ScheduledTransactionFilter) Filter() storage.IndexFilter[*accessmodel.ScheduledTransaction] { + if f.isEmpty() { + return nil + } + + statuses := make(map[accessmodel.ScheduledTransactionStatus]bool) + for _, status := range f.Statuses { + statuses[status] = true + } + + return func(tx *accessmodel.ScheduledTransaction) bool { + if len(statuses) > 0 && !statuses[tx.Status] { + return false + } + + if f.Priority != nil && tx.Priority != *f.Priority { + return false + } + if f.StartTime != nil && tx.Timestamp < *f.StartTime { + return false + } + if f.EndTime != nil && tx.Timestamp > *f.EndTime { + return false + } + if f.TransactionHandlerOwner != nil && tx.TransactionHandlerOwner != *f.TransactionHandlerOwner { + return false + } + if f.TransactionHandlerTypeID != nil && tx.TransactionHandlerTypeIdentifier != *f.TransactionHandlerTypeID { + return false + } + if f.TransactionHandlerUUID != nil && tx.TransactionHandlerUUID != *f.TransactionHandlerUUID { + return false + } + return true + } +} + +// ScheduledTransactionsBackend implements the extended API for querying scheduled transactions. +type ScheduledTransactionsBackend struct { + *backendBase + + log zerolog.Logger + chainID flow.ChainID + state protocol.State + store storage.ScheduledTransactionsIndexReader + contracts storage.ContractDeploymentsIndexReader + scheduledTransactions storage.ScheduledTransactionsReader + scriptExecutor execution.ScriptExecutor +} + +// NewScheduledTransactionsBackend creates a new [ScheduledTransactionsBackend]. +func NewScheduledTransactionsBackend( + log zerolog.Logger, + base *backendBase, + chainID flow.ChainID, + store storage.ScheduledTransactionsIndexReader, + contracts storage.ContractDeploymentsIndexReader, + scheduledTransactions storage.ScheduledTransactionsReader, + state protocol.State, + scriptExecutor execution.ScriptExecutor, +) *ScheduledTransactionsBackend { + return &ScheduledTransactionsBackend{ + backendBase: base, + log: log, + chainID: chainID, + store: store, + contracts: contracts, + scheduledTransactions: scheduledTransactions, + state: state, + scriptExecutor: scriptExecutor, + } +} + +// GetScheduledTransaction returns a single scheduled transaction by its scheduler-assigned ID. +// +// Expected error returns during normal operations: +// - [codes.NotFound]: if no transaction with the given ID exists +// - [codes.FailedPrecondition]: if the index has not been initialized +func (b *ScheduledTransactionsBackend) GetScheduledTransaction( + ctx context.Context, + id uint64, + expandOptions ScheduledTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.ScheduledTransaction, error) { + tx, err := b.store.ByID(id) + if err != nil { + return nil, mapReadError(ctx, "scheduled transaction", err) + } + + if err := b.expand(ctx, &tx, expandOptions, encodingVersion); err != nil { + err = fmt.Errorf("failed to expand scheduled transaction %d: %w", tx.ID, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + return &tx, nil +} + +// GetScheduledTransactions returns a paginated list of scheduled transactions. +// +// Expected error returns during normal operations: +// - [codes.FailedPrecondition]: if the index has not been initialized +// - [codes.InvalidArgument]: if the query parameters are invalid +func (b *ScheduledTransactionsBackend) GetScheduledTransactions( + ctx context.Context, + limit uint32, + cursor *accessmodel.ScheduledTransactionCursor, + filter ScheduledTransactionFilter, + expandOptions ScheduledTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.ScheduledTransactionsPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + iter, err := b.store.All(cursor) + if err != nil { + return nil, mapReadError(ctx, "scheduled transactions", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.Filter()) + if err != nil { + err = fmt.Errorf("error collecting scheduled transactions: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: collected, + NextCursor: nextCursor, + } + + for i := range page.Transactions { + tx := &page.Transactions[i] + if err := b.expand(ctx, tx, expandOptions, encodingVersion); err != nil { + err = fmt.Errorf("failed to expand scheduled transaction %d: %w", tx.ID, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + } + + return page, nil +} + +// GetScheduledTransactionsByAddress returns a paginated list of scheduled transactions for the given address. +// +// Expected error returns during normal operations: +// - [codes.FailedPrecondition]: if the index has not been initialized +// - [codes.InvalidArgument]: if the query parameters are invalid +func (b *ScheduledTransactionsBackend) GetScheduledTransactionsByAddress( + ctx context.Context, + address flow.Address, + limit uint32, + cursor *accessmodel.ScheduledTransactionCursor, + filter ScheduledTransactionFilter, + expandOptions ScheduledTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, +) (*accessmodel.ScheduledTransactionsPage, error) { + limit, err := b.normalizeLimit(limit) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid limit: %v", err) + } + + iter, err := b.store.ByAddress(address, cursor) + if err != nil { + return nil, mapReadError(ctx, "scheduled transactions", err) + } + + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter.Filter()) + if err != nil { + err = fmt.Errorf("error collecting scheduled transactions: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: collected, + NextCursor: nextCursor, + } + + for i := range page.Transactions { + tx := &page.Transactions[i] + if err := b.expand(ctx, tx, expandOptions, encodingVersion); err != nil { + err = fmt.Errorf("failed to expand scheduled transaction %d: %w", tx.ID, err) + irrecoverable.Throw(ctx, err) + return nil, err + } + } + + return page, nil +} + +// populateBlockTimestamps looks up the block headers for the creation and completion +// transactions and sets CreatedAt and CompletedAt on the transaction. +// +// No error returns are expected during normal operation. +func (b *ScheduledTransactionsBackend) populateBlockTimestamps( + tx *accessmodel.ScheduledTransaction, +) (executedHeader *flow.Header, err error) { + // `CreatedTransactionID` may be empty if this scheduled transaction was backfilled + if tx.CreatedTransactionID != flow.ZeroID { + header, err := b.lookupAnyTransactionBlock(tx.CreatedTransactionID) + if err != nil && !errors.Is(err, storage.ErrNotFound) { + return nil, fmt.Errorf("failed to get creation block timestamp for scheduled tx %d: %w", tx.ID, err) + } + if err == nil { + tx.CreatedAt = header.Timestamp + } + // if the created transaction was not found, don't populate the timestamp, but continue to + // return a response. the created transaction ID will be populated, so it will be clear this + // information is not available yet. + } + + switch tx.Status { + case accessmodel.ScheduledTxStatusExecuted, accessmodel.ScheduledTxStatusFailed: + header, err := b.lookupScheduledTransactionBlock(tx.ExecutedTransactionID) + if err != nil { + // if the scheduled transaction record was found in the extended index, then the scheduled + // transaction to block ID mapping must exist in storage. + err = irrecoverable.NewException(fmt.Errorf("failed to get completion block timestamp for scheduled tx %d: %w", tx.ID, err)) + return nil, err + } + // Note: the executed transaction header must be found, so the method can guarantee a header + // is returned for all executed scheduled transactions if no error is encountered. + tx.CompletedAt = header.Timestamp + return header, nil + + case accessmodel.ScheduledTxStatusCancelled: + header, err := b.lookupAnyTransactionBlock(tx.CancelledTransactionID) + if err != nil && !errors.Is(err, storage.ErrNotFound) { + return nil, fmt.Errorf("failed to get creation block timestamp for scheduled tx %d: %w", tx.ID, err) + } + if err == nil { + tx.CompletedAt = header.Timestamp + } + return nil, nil + // if the cancelled transaction was not found, don't populate the timestamp, but continue to + // return a response. the cancelled transaction ID will be populated, so it will be clear this + // information is not available yet. + } + + return nil, nil +} + +// lookupAnyTransactionBlock looks up the block timestamp for a transaction by its ID. +// It supports both scheduled and standard transactions. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if the transaction's block could not be resolved. +func (b *ScheduledTransactionsBackend) lookupAnyTransactionBlock(txID flow.Identifier) (*flow.Header, error) { + header, err := b.lookupScheduledTransactionBlock(txID) + if err == nil { + return header, nil + } + if !errors.Is(err, storage.ErrNotFound) { + return nil, fmt.Errorf("failed to get block timestamp for scheduled tx %s: %w", txID, err) + } + // the transaction may not be a scheduled transaction, so try to look up the block for a + // standard transaction. + + header, err = b.lookupStandardTransactionBlock(txID) + if err != nil { + return nil, fmt.Errorf("failed to get block timestamp for standard tx %s: %w", txID, err) + } + + return header, nil +} + +// lookupStandardTransactionBlock looks up the block timestamp for a standard transaction by its ID. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if the transaction's block could not be resolved. +func (b *ScheduledTransactionsBackend) lookupStandardTransactionBlock(txID flow.Identifier) (*flow.Header, error) { + collection, err := b.collections.LightByTransactionID(txID) + if err != nil { + return nil, fmt.Errorf("failed to get collection for tx: %w", err) + } + collectionID := collection.ID() + + block, err := b.blocks.ByCollectionID(collectionID) + if err != nil { + // The txID → collectionID index (LightByTransactionID) and the collectionID → blockID index + // (checked here) are built by separate async components: the collection Indexer and + // the FinalizedBlockProcessor respectively. During catch-up or under load, the + // FinalizedBlockProcessor may lag behind, causing ErrNotFound here even though the + // collection is indexed. This is a transient state that resolves once finalization + // processing catches up. + // + // Note: this will also fail if the transaction is a system transaction. + return nil, fmt.Errorf("failed to get block ID for collection %s: %w", collectionID, err) + } + return block.ToHeader(), nil +} + +// lookupScheduledTransactionBlock looks up the block timestamp for a scheduled transaction by its ID. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if the scheduled transaction did not exist in storage. +func (b *ScheduledTransactionsBackend) lookupScheduledTransactionBlock(txID flow.Identifier) (*flow.Header, error) { + blockID, err := b.scheduledTransactions.BlockIDByTransactionID(txID) + if err != nil { + return nil, fmt.Errorf("failed to get block ID for scheduled tx: %w", err) + } + + header, err := b.headers.ByBlockID(blockID) + if err != nil { + // if the scheduled transaction was found, the block must exist in storage. + err = irrecoverable.NewException(fmt.Errorf("failed to get header for block %s: %w", blockID, err)) + return nil, err + } + return header, nil +} + +// expand enriches an executed scheduled transaction with its transaction result. +// For non-executed transactions, this is a no-op. +// +// No error returns are expected during normal operation. +func (b *ScheduledTransactionsBackend) expand( + ctx context.Context, + tx *accessmodel.ScheduledTransaction, + expandOptions ScheduledTransactionExpandOptions, + encodingVersion entities.EventEncodingVersion, +) error { + // always populate the block timestamps + executedHeader, err := b.populateBlockTimestamps(tx) + if err != nil { + return fmt.Errorf("failed to get block timestamp for scheduled tx %d: %w", tx.ID, err) + } + + if expandOptions.HandlerContract { + err := b.expandHandlerContract(ctx, tx) + if err != nil { + return fmt.Errorf("failed to expand handler contract for scheduled tx %d: %w", tx.ID, err) + } + } + + if !expandOptions.Transaction && !expandOptions.Result { + return nil + } + + // if the transaction was not executed, there's nothing to expand. + if tx.Status != accessmodel.ScheduledTxStatusExecuted && tx.Status != accessmodel.ScheduledTxStatusFailed { + return nil + } + + if expandOptions.Transaction { + txBody, err := b.systemCollections. + ByHeight(executedHeader.Height). + ExecuteCallbacksTransaction(b.chainID.Chain(), tx.ID, tx.ExecutionEffort) + if err != nil { + return fmt.Errorf("failed to construct scheduled transaction body: %w", err) + } + + if txBody.ID() != tx.ExecutedTransactionID { + return fmt.Errorf("scheduled transaction body ID %s does not match executed transaction ID %s", txBody.ID(), tx.ExecutedTransactionID) + } + tx.Transaction = txBody + } + + if expandOptions.Result { + result, err := b.getTransactionResult(ctx, tx.ExecutedTransactionID, executedHeader, true, expandOptions.Transaction, encodingVersion) + if err != nil { + return fmt.Errorf("failed to get transaction result for tx %s: %w", tx.ExecutedTransactionID, err) + } + tx.Result = result + } + + return nil +} + +// expandHandlerContract expands the handler contract for a scheduled transaction. +// +// No error returns are expected during normal operation. +func (b *ScheduledTransactionsBackend) expandHandlerContract( + ctx context.Context, + tx *accessmodel.ScheduledTransaction, +) error { + address, contractName, err := transactionHandlerContract(tx.TransactionHandlerTypeIdentifier) + if err != nil { + return fmt.Errorf("failed to get contract ID for tx handler %s: %w", tx.TransactionHandlerTypeIdentifier, err) + } + + contract, err := b.contracts.ByContract(address, contractName) + + if err == nil { + tx.HandlerContract = &contract + return nil + } + + if !errors.Is(err, storage.ErrNotFound) { + return fmt.Errorf("failed to get contract for tx handler %s: %w", tx.TransactionHandlerTypeIdentifier, err) + } + + // it's possible that the contracts index is backfilling and not caught up yet. in this case, + // fetch the code from the node's state. + + latest, err := b.state.Sealed().Head() + if err != nil { + return fmt.Errorf("failed to get latest sealed block: %w", err) + } + + code, err := b.getContractFromState(ctx, address, contractName, latest.Height) + if err != nil { + return fmt.Errorf("failed to get contract code for tx handler %s: %w", address, err) + } + + tx.HandlerContract = &accessmodel.ContractDeployment{ + Address: address, + ContractName: contractName, + Code: code, + CodeHash: accessmodel.CadenceCodeHash(code), + IsPlaceholder: true, + } + + return nil +} + +func (b *ScheduledTransactionsBackend) getContractFromState(ctx context.Context, address flow.Address, contractName string, height uint64) ([]byte, error) { + contract, err := b.scriptExecutor.GetAccountCode(ctx, address, contractName, height) + if err != nil { + return nil, fmt.Errorf("failed to get contract code for tx handler %s: %w", address, err) + } + return contract, nil +} + +// transactionHandlerContract extracts the contract ID from a transaction handler type identifier. +// The handler type identifier is a fully qualified Cadence type identifier of the transaction handler, +// e.g. +// +// A.1654653399040a61.MyScheduler.Handler -> A.1654653399040a61.MyScheduler +func transactionHandlerContract(handlerTypeIdentifier string) (address flow.Address, contractName string, err error) { + parts := strings.Split(handlerTypeIdentifier, ".") + if len(parts) < 3 { + return flow.Address{}, "", fmt.Errorf("invalid handler type identifier: %s", handlerTypeIdentifier) + } + + address, err = flow.StringToAddress(parts[1]) + if err != nil { + return flow.Address{}, "", fmt.Errorf("failed to parse address from handler type identifier: %w", err) + } + + contractName = parts[2] + + return address, contractName, nil +} diff --git a/access/backends/extended/backend_scheduled_transactions_test.go b/access/backends/extended/backend_scheduled_transactions_test.go new file mode 100644 index 00000000000..62de97e9d8f --- /dev/null +++ b/access/backends/extended/backend_scheduled_transactions_test.go @@ -0,0 +1,1729 @@ +package extended + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + mocktestify "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + providermock "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/provider/mock" + "github.com/onflow/flow-go/fvm/blueprints" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/access/systemcollection" + "github.com/onflow/flow-go/model/flow" + executionmock "github.com/onflow/flow-go/module/execution/mock" + "github.com/onflow/flow-go/module/irrecoverable" + protocolmock "github.com/onflow/flow-go/state/protocol/mock" + "github.com/onflow/flow-go/storage" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/utils/unittest" +) + +// testSchedTxEntry is a simple storage.IteratorEntry implementation for tests. +type testSchedTxEntry struct { + tx accessmodel.ScheduledTransaction +} + +func (e testSchedTxEntry) Cursor() accessmodel.ScheduledTransactionCursor { + return accessmodel.ScheduledTransactionCursor{ID: e.tx.ID} +} + +func (e testSchedTxEntry) Value() (accessmodel.ScheduledTransaction, error) { + return e.tx, nil +} + +// makeScheduledTxIter builds a storage.ScheduledTransactionIterator from a slice of transactions. +func makeScheduledTxIter(txs []accessmodel.ScheduledTransaction) storage.ScheduledTransactionIterator { + return func(yield func(storage.IteratorEntry[accessmodel.ScheduledTransaction, accessmodel.ScheduledTransactionCursor], error) bool) { + for _, tx := range txs { + if !yield(testSchedTxEntry{tx: tx}, nil) { + return + } + } + } +} + +// signalerCtxExpectingThrow creates a context that asserts irrecoverable.Throw is called +// with a non-nil error. Returns the context and a verification function that must be called +// after the operation under test to confirm Throw was invoked. +func signalerCtxExpectingThrow(t *testing.T) (context.Context, func()) { + t.Helper() + thrown := make(chan error, 1) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), + irrecoverable.NewMockSignalerContextWithCallback(t, context.Background(), func(err error) { + select { + case thrown <- err: + default: + } + })) + verify := func() { + t.Helper() + select { + case err := <-thrown: + require.Error(t, err, "irrecoverable.Throw must be called with a non-nil error") + default: + t.Fatal("expected irrecoverable.Throw to be called but it was not") + } + } + return signalerCtx, verify +} + +// TestTransactionHandlerContract tests the helper that extracts the contract ID from a +// transaction handler type identifier. +func TestTransactionHandlerContract(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + input string + expectedID string + expectedAddrHex string + expectedContract string + expectedErr bool + }{ + { + name: "standard type identifier", + input: "A.1654653399040a61.MyScheduler.Handler", + expectedID: "A.1654653399040a61.MyScheduler", + expectedAddrHex: "1654653399040a61", + expectedContract: "MyScheduler", + }, + { + name: "deeply nested type identifier returns A.address.Contract prefix only", + input: "A.1654653399040a61.MyScheduler.SubModule.Handler", + expectedID: "A.1654653399040a61.MyScheduler", + expectedAddrHex: "1654653399040a61", + expectedContract: "MyScheduler", + }, + { + name: "exactly three parts is valid", + input: "A.1654653399040a61.MyScheduler", + expectedID: "A.1654653399040a61.MyScheduler", + expectedAddrHex: "1654653399040a61", + expectedContract: "MyScheduler", + }, + { + name: "fewer than three parts returns error", + input: "SomeContract.Handler", + expectedErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + addr, contractName, err := transactionHandlerContract(tt.input) + if tt.expectedErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.expectedAddrHex, addr.Hex()) + assert.Equal(t, tt.expectedContract, contractName) + }) + } +} + +// TestScheduledTransactionFilter tests that ScheduledTransactionFilter.Filter produces a +// predicate that correctly matches or rejects scheduled transactions for each filter field, +// and for combined multi-field filters. +func TestScheduledTransactionFilter(t *testing.T) { + t.Parallel() + + ownerAddr := unittest.RandomAddressFixture() + otherAddr := unittest.RandomAddressFixture() + handlerTypeID := "A.1654653399040a61.MyScheduler.Handler" + otherTypeID := "A.0000000000000001.OtherScheduler.Handler" + + tx := &accessmodel.ScheduledTransaction{ + ID: 42, + Status: accessmodel.ScheduledTxStatusScheduled, + Priority: 5, + Timestamp: 1000, + TransactionHandlerOwner: ownerAddr, + TransactionHandlerTypeIdentifier: handlerTypeID, + TransactionHandlerUUID: 99, + } + + t.Run("empty filter returns nil", func(t *testing.T) { + filter := ScheduledTransactionFilter{} + assert.Nil(t, filter.Filter()) + }) + + t.Run("status filter matches", func(t *testing.T) { + filter := ScheduledTransactionFilter{ + Statuses: []accessmodel.ScheduledTransactionStatus{accessmodel.ScheduledTxStatusScheduled}, + } + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("status filter rejects mismatch", func(t *testing.T) { + filter := ScheduledTransactionFilter{ + Statuses: []accessmodel.ScheduledTransactionStatus{accessmodel.ScheduledTxStatusExecuted}, + } + assert.False(t, filter.Filter()(tx)) + }) + + t.Run("status filter matches when one of multiple statuses matches", func(t *testing.T) { + filter := ScheduledTransactionFilter{ + Statuses: []accessmodel.ScheduledTransactionStatus{ + accessmodel.ScheduledTxStatusExecuted, + accessmodel.ScheduledTxStatusScheduled, + }, + } + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("priority filter matches", func(t *testing.T) { + p := accessmodel.ScheduledTransactionPriority(5) + filter := ScheduledTransactionFilter{Priority: &p} + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("priority filter rejects mismatch", func(t *testing.T) { + p := accessmodel.ScheduledTransactionPriority(10) + filter := ScheduledTransactionFilter{Priority: &p} + assert.False(t, filter.Filter()(tx)) + }) + + t.Run("start time inclusive lower bound matches equal timestamp", func(t *testing.T) { + start := uint64(1000) + filter := ScheduledTransactionFilter{StartTime: &start} + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("start time rejects timestamp below bound", func(t *testing.T) { + start := uint64(1001) + filter := ScheduledTransactionFilter{StartTime: &start} + assert.False(t, filter.Filter()(tx)) + }) + + t.Run("end time inclusive upper bound matches equal timestamp", func(t *testing.T) { + end := uint64(1000) + filter := ScheduledTransactionFilter{EndTime: &end} + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("end time rejects timestamp above bound", func(t *testing.T) { + end := uint64(999) + filter := ScheduledTransactionFilter{EndTime: &end} + assert.False(t, filter.Filter()(tx)) + }) + + t.Run("start and end time window matches timestamp within range", func(t *testing.T) { + start := uint64(900) + end := uint64(1100) + filter := ScheduledTransactionFilter{StartTime: &start, EndTime: &end} + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("handler owner filter matches", func(t *testing.T) { + filter := ScheduledTransactionFilter{TransactionHandlerOwner: &ownerAddr} + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("handler owner filter rejects mismatch", func(t *testing.T) { + filter := ScheduledTransactionFilter{TransactionHandlerOwner: &otherAddr} + assert.False(t, filter.Filter()(tx)) + }) + + t.Run("handler type ID filter matches", func(t *testing.T) { + filter := ScheduledTransactionFilter{TransactionHandlerTypeID: &handlerTypeID} + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("handler type ID filter rejects mismatch", func(t *testing.T) { + filter := ScheduledTransactionFilter{TransactionHandlerTypeID: &otherTypeID} + assert.False(t, filter.Filter()(tx)) + }) + + t.Run("handler UUID filter matches", func(t *testing.T) { + uuid := uint64(99) + filter := ScheduledTransactionFilter{TransactionHandlerUUID: &uuid} + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("handler UUID filter rejects mismatch", func(t *testing.T) { + uuid := uint64(100) + filter := ScheduledTransactionFilter{TransactionHandlerUUID: &uuid} + assert.False(t, filter.Filter()(tx)) + }) + + t.Run("combined filters all match", func(t *testing.T) { + p := accessmodel.ScheduledTransactionPriority(5) + start := uint64(1000) + end := uint64(1000) + uuid := uint64(99) + filter := ScheduledTransactionFilter{ + Statuses: []accessmodel.ScheduledTransactionStatus{accessmodel.ScheduledTxStatusScheduled}, + Priority: &p, + StartTime: &start, + EndTime: &end, + TransactionHandlerOwner: &ownerAddr, + TransactionHandlerTypeID: &handlerTypeID, + TransactionHandlerUUID: &uuid, + } + assert.True(t, filter.Filter()(tx)) + }) + + t.Run("combined filters reject on single mismatch", func(t *testing.T) { + p := accessmodel.ScheduledTransactionPriority(5) + wrongUUID := uint64(100) // mismatch + filter := ScheduledTransactionFilter{ + Priority: &p, + TransactionHandlerUUID: &wrongUUID, + } + assert.False(t, filter.Filter()(tx)) + }) +} + +// TestScheduledTransactionsBackend_GetScheduledTransaction tests all code paths for the +// GetScheduledTransaction method, including storage error mappings and all expand combinations. +func TestScheduledTransactionsBackend_GetScheduledTransaction(t *testing.T) { + t.Parallel() + + defaultEncoding := entities.EventEncodingVersion_JSON_CDC_V0 + defaultConfig := DefaultConfig() + + t.Run("happy path: returns transaction without expand", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + expectedTx := accessmodel.ScheduledTransaction{ID: 1, Status: accessmodel.ScheduledTxStatusScheduled} + store.On("ByID", uint64(1)).Return(expectedTx, nil).Once() + + result, err := backend.GetScheduledTransaction( + context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding, + ) + require.NoError(t, err) + require.NotNil(t, result) + assert.Equal(t, expectedTx, *result) + assert.Nil(t, result.Transaction) + assert.Nil(t, result.Result) + assert.Nil(t, result.HandlerContract) + }) + + t.Run("ErrNotFound maps to codes.NotFound", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + store.On("ByID", uint64(99)).Return(accessmodel.ScheduledTransaction{}, storage.ErrNotFound).Once() + + _, err := backend.GetScheduledTransaction( + context.Background(), 99, ScheduledTransactionExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.NotFound, st.Code()) + }) + + t.Run("ErrNotBootstrapped maps to codes.FailedPrecondition", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + store.On("ByID", uint64(1)).Return(accessmodel.ScheduledTransaction{}, storage.ErrNotBootstrapped).Once() + + _, err := backend.GetScheduledTransaction( + context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("unexpected storage error triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + storageErr := fmt.Errorf("unexpected disk failure") + store.On("ByID", uint64(1)).Return(accessmodel.ScheduledTransaction{}, storageErr).Once() + + expectedErr := fmt.Errorf("failed to get scheduled transaction: %w", storageErr) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), + irrecoverable.NewMockSignalerContextExpectError(t, context.Background(), expectedErr)) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, ScheduledTransactionExpandOptions{}, defaultEncoding, + ) + require.Error(t, err) + }) + + // expand is no-op for scheduled status (no block lookups, no result/transaction populated) + t.Run("expand is no-op for scheduled status", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + tx := accessmodel.ScheduledTransaction{ID: 1, Status: accessmodel.ScheduledTxStatusScheduled} + store.On("ByID", uint64(1)).Return(tx, nil).Once() + + // expand options set but status is Scheduled: no storage lookups expected + result, err := backend.GetScheduledTransaction( + context.Background(), 1, + ScheduledTransactionExpandOptions{Result: true, Transaction: true}, + defaultEncoding, + ) + require.NoError(t, err) + assert.Nil(t, result.Transaction) + assert.Nil(t, result.Result) + }) + + // for cancelled status: block timestamps are looked up, but result/transaction are not expanded + t.Run("expand is no-op for result/transaction on cancelled status", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + + cancelledTxID := unittest.IdentifierFixture() + cancelledCollection := &flow.LightCollection{Transactions: []flow.Identifier{cancelledTxID}} + cancelledBlock := unittest.BlockFixture() + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + collections: mockCollections, + blocks: mockBlocks, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + tx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusCancelled, + CancelledTransactionID: cancelledTxID, + } + store.On("ByID", uint64(1)).Return(tx, nil).Once() + // CancelledTransactionID is a user tx: not in scheduled lookup, falls back to collection + scheduledTxLookup.On("BlockIDByTransactionID", cancelledTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", cancelledTxID).Return(cancelledCollection, nil).Once() + mockBlocks.On("ByCollectionID", cancelledCollection.ID()).Return(cancelledBlock, nil).Once() + + result, err := backend.GetScheduledTransaction( + context.Background(), 1, + ScheduledTransactionExpandOptions{Result: true, Transaction: true}, + defaultEncoding, + ) + require.NoError(t, err) + assert.Equal(t, cancelledBlock.Timestamp, result.CompletedAt) + assert.Nil(t, result.Transaction) + assert.Nil(t, result.Result) + }) + + // expand result works for executed and failed transactions + for _, status := range []accessmodel.ScheduledTransactionStatus{accessmodel.ScheduledTxStatusExecuted, accessmodel.ScheduledTxStatusFailed} { + t.Run(fmt.Sprintf("expand result on %s transaction", status), func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + mockProvider := providermock.NewTransactionProvider(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + headers: mockHeaders, + transactionsProvider: mockProvider, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + txID := unittest.IdentifierFixture() + blockHeader := unittest.BlockHeaderFixture() + blockID := blockHeader.ID() + + storedTx := accessmodel.ScheduledTransaction{ID: 1, Status: status, ExecutedTransactionID: txID} + expectedResult := &accessmodel.TransactionResult{ + TransactionID: txID, + BlockID: blockID, + Status: flow.TransactionStatusSealed, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(blockID, nil).Once() + mockHeaders.On("ByBlockID", blockID).Return(blockHeader, nil).Once() + mockProvider.On("TransactionResult", mocktestify.Anything, blockHeader, txID, mocktestify.Anything, defaultEncoding). + Return(expectedResult, nil).Once() + + result, err := backend.GetScheduledTransaction( + context.Background(), 1, + ScheduledTransactionExpandOptions{Result: true}, + defaultEncoding, + ) + require.NoError(t, err) + require.NotNil(t, result.Result) + assert.Equal(t, expectedResult, result.Result) + assert.Nil(t, result.Transaction) + }) + } + + // expand tx body works for executed and failed transactions + for _, status := range []accessmodel.ScheduledTransactionStatus{accessmodel.ScheduledTxStatusExecuted, accessmodel.ScheduledTxStatusFailed} { + t.Run(fmt.Sprintf("expand transaction body on %s transaction", status), func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + + sysCollections, err := systemcollection.NewVersioned( + flow.Mainnet.Chain(), systemcollection.Default(flow.Mainnet), + ) + require.NoError(t, err) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + headers: mockHeaders, + systemCollections: sysCollections, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + // construct the expected tx body using the same path the production code will use + const scheduledTxID = uint64(42) + const executionEffort = uint64(1000) + expectedTxBody, err := blueprints.ExecuteCallbacksTransaction(flow.Mainnet.Chain(), scheduledTxID, executionEffort) + require.NoError(t, err) + txID := expectedTxBody.ID() + + blockHeader := unittest.BlockHeaderFixture() + blockID := blockHeader.ID() + + storedTx := accessmodel.ScheduledTransaction{ + ID: scheduledTxID, Status: status, + ExecutedTransactionID: txID, ExecutionEffort: executionEffort, + } + + store.On("ByID", scheduledTxID).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(blockID, nil).Once() + mockHeaders.On("ByBlockID", blockID).Return(blockHeader, nil).Once() + + result, err := backend.GetScheduledTransaction( + context.Background(), scheduledTxID, + ScheduledTransactionExpandOptions{Transaction: true}, + defaultEncoding, + ) + require.NoError(t, err) + require.NotNil(t, result.Transaction) + assert.Equal(t, txID, result.Transaction.ID()) + assert.Nil(t, result.Result) + }) + } + + t.Run("expand handler contract", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + mockContracts := storagemock.NewContractDeploymentsIndexReader(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, mockContracts, nil, nil, nil, + ) + + handlerTypeID := "A.1654653399040a61.MyScheduler.Handler" + contractID := "A.1654653399040a61.MyScheduler" + contractBody := []byte("pub contract MyScheduler {}") + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + TransactionHandlerTypeIdentifier: handlerTypeID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + mockContracts.On("ByContract", flow.HexToAddress("1654653399040a61"), "MyScheduler").Return( + accessmodel.ContractDeployment{Address: flow.HexToAddress("1654653399040a61"), ContractName: "MyScheduler", Code: contractBody}, + nil, + ).Once() + + result, err := backend.GetScheduledTransaction( + context.Background(), 1, + ScheduledTransactionExpandOptions{HandlerContract: true}, + defaultEncoding, + ) + require.NoError(t, err) + require.NotNil(t, result.HandlerContract) + assert.Equal(t, contractID, accessmodel.ContractID(result.HandlerContract.Address, result.HandlerContract.ContractName)) + assert.Equal(t, contractBody, result.HandlerContract.Code) + }) + + t.Run("created tx block not yet available returns zero CreatedAt", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + collections: mockCollections, + blocks: mockBlocks, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + createdTxID := unittest.IdentifierFixture() + createdCollection := &flow.LightCollection{Transactions: []flow.Identifier{createdTxID}} + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + CreatedTransactionID: createdTxID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return(createdCollection, nil).Once() + // block not yet indexed by FinalizedBlockProcessor + mockBlocks.On("ByCollectionID", createdCollection.ID()).Return((*flow.Block)(nil), storage.ErrNotFound).Once() + + result, err := backend.GetScheduledTransaction(context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + assert.Zero(t, result.CreatedAt) + }) + + t.Run("cancelled tx block not yet available returns zero CompletedAt", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + collections: mockCollections, + blocks: mockBlocks, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + cancelledTxID := unittest.IdentifierFixture() + cancelledCollection := &flow.LightCollection{Transactions: []flow.Identifier{cancelledTxID}} + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusCancelled, + CancelledTransactionID: cancelledTxID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", cancelledTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", cancelledTxID).Return(cancelledCollection, nil).Once() + mockBlocks.On("ByCollectionID", cancelledCollection.ID()).Return((*flow.Block)(nil), storage.ErrNotFound).Once() + + result, err := backend.GetScheduledTransaction(context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + assert.Zero(t, result.CompletedAt) + }) + + t.Run("BlockIDByTransactionID error during populateBlockTimestamps triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + txID := unittest.IdentifierFixture() + storedTx := accessmodel.ScheduledTransaction{ID: 1, Status: accessmodel.ScheduledTxStatusExecuted, ExecutedTransactionID: txID} + lookupErr := fmt.Errorf("lookup error") + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(flow.Identifier{}, lookupErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, ScheduledTransactionExpandOptions{Result: true}, defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("BlockIDByTransactionID error during expand triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + txID := unittest.IdentifierFixture() + storedTx := accessmodel.ScheduledTransaction{ID: 1, Status: accessmodel.ScheduledTxStatusExecuted, ExecutedTransactionID: txID} + blockLookupErr := fmt.Errorf("block lookup error") + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(flow.Identifier{}, blockLookupErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, ScheduledTransactionExpandOptions{Result: true}, defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("ByBlockID error during expand triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig, headers: mockHeaders}, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + txID := unittest.IdentifierFixture() + blockID := unittest.IdentifierFixture() + storedTx := accessmodel.ScheduledTransaction{ID: 1, Status: accessmodel.ScheduledTxStatusExecuted, ExecutedTransactionID: txID} + headerErr := fmt.Errorf("header lookup error") + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(blockID, nil).Once() + mockHeaders.On("ByBlockID", blockID).Return((*flow.Header)(nil), headerErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, ScheduledTransactionExpandOptions{Result: true}, defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("transaction ID mismatch during expand triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + + sysCollections, err := systemcollection.NewVersioned( + flow.Mainnet.Chain(), systemcollection.Default(flow.Mainnet), + ) + require.NoError(t, err) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + headers: mockHeaders, + systemCollections: sysCollections, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + // ExecutedTransactionID does NOT match the tx body constructed by systemCollections + mismatchedTxID := unittest.IdentifierFixture() + blockHeader := unittest.BlockHeaderFixture() + blockID := blockHeader.ID() + storedTx := accessmodel.ScheduledTransaction{ + ID: 42, Status: accessmodel.ScheduledTxStatusExecuted, + ExecutedTransactionID: mismatchedTxID, ExecutionEffort: 1000, + } + + store.On("ByID", uint64(42)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", mismatchedTxID).Return(blockID, nil).Once() + mockHeaders.On("ByBlockID", blockID).Return(blockHeader, nil).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err = backend.GetScheduledTransaction( + signalerCtx, 42, ScheduledTransactionExpandOptions{Transaction: true}, defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("transaction not found in block during expand triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + + sysCollections, err := systemcollection.NewVersioned( + flow.Mainnet.Chain(), systemcollection.Default(flow.Mainnet), + ) + require.NoError(t, err) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + headers: mockHeaders, + systemCollections: sysCollections, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + // txID that does NOT match the tx body constructed by systemCollections. + txID := unittest.IdentifierFixture() + blockHeader := unittest.BlockHeaderFixture() + blockID := blockHeader.ID() + storedTx := accessmodel.ScheduledTransaction{ID: 1, Status: accessmodel.ScheduledTxStatusExecuted, ExecutedTransactionID: txID, ExecutionEffort: 1000} + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(blockID, nil).Once() + mockHeaders.On("ByBlockID", blockID).Return(blockHeader, nil).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err = backend.GetScheduledTransaction( + signalerCtx, 1, ScheduledTransactionExpandOptions{Transaction: true}, defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("TransactionResult error during expand triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + mockProvider := providermock.NewTransactionProvider(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + headers: mockHeaders, + transactionsProvider: mockProvider, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + txID := unittest.IdentifierFixture() + blockHeader := unittest.BlockHeaderFixture() + blockID := blockHeader.ID() + storedTx := accessmodel.ScheduledTransaction{ID: 1, Status: accessmodel.ScheduledTxStatusExecuted, ExecutedTransactionID: txID} + resultErr := fmt.Errorf("result lookup error") + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(blockID, nil).Once() + mockHeaders.On("ByBlockID", blockID).Return(blockHeader, nil).Once() + mockProvider.On("TransactionResult", mocktestify.Anything, blockHeader, txID, mocktestify.Anything, defaultEncoding). + Return(nil, resultErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, ScheduledTransactionExpandOptions{Result: true}, defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("expandHandlerContract: ByContract error triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + mockContracts := storagemock.NewContractDeploymentsIndexReader(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, mockContracts, nil, nil, nil, + ) + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + TransactionHandlerTypeIdentifier: "A.1654653399040a61.MyScheduler.Handler", + } + contractErr := fmt.Errorf("contract read error") + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + mockContracts.On("ByContract", flow.HexToAddress("1654653399040a61"), "MyScheduler").Return( + accessmodel.ContractDeployment{}, contractErr, + ).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, + ScheduledTransactionExpandOptions{HandlerContract: true}, + defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("expandHandlerContract: ErrNotFound falls back to state, returns contract", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + mockContracts := storagemock.NewContractDeploymentsIndexReader(t) + mockState := protocolmock.NewState(t) + mockSnapshot := protocolmock.NewSnapshot(t) + mockExecutor := executionmock.NewScriptExecutor(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, mockContracts, nil, mockState, mockExecutor, + ) + + sealedHeader := unittest.BlockHeaderFixture() + handlerAddr, err := flow.StringToAddress("1654653399040a61") + require.NoError(t, err) + contractCode := []byte("access(all) contract MyScheduler {}") + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + TransactionHandlerTypeIdentifier: "A.1654653399040a61.MyScheduler.Handler", + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + mockContracts.On("ByContract", flow.HexToAddress("1654653399040a61"), "MyScheduler").Return( + accessmodel.ContractDeployment{}, storage.ErrNotFound, + ).Once() + mockState.On("Sealed").Return(mockSnapshot).Once() + mockSnapshot.On("Head").Return(sealedHeader, nil).Once() + mockExecutor.On("GetAccountCode", mocktestify.Anything, handlerAddr, "MyScheduler", sealedHeader.Height). + Return(contractCode, nil).Once() + + signalerCtx, _ := irrecoverable.NewMockSignalerContextWithCancel(t, context.Background()) + + tx, err := backend.GetScheduledTransaction( + signalerCtx, 1, + ScheduledTransactionExpandOptions{HandlerContract: true}, + defaultEncoding, + ) + require.NoError(t, err) + require.NotNil(t, tx.HandlerContract) + assert.Equal(t, "A.1654653399040a61.MyScheduler", accessmodel.ContractID(tx.HandlerContract.Address, tx.HandlerContract.ContractName)) + assert.Equal(t, contractCode, tx.HandlerContract.Code) + }) + + t.Run("expandHandlerContract: ErrNotFound and state.Sealed fails triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + mockContracts := storagemock.NewContractDeploymentsIndexReader(t) + mockState := protocolmock.NewState(t) + mockSnapshot := protocolmock.NewSnapshot(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, mockContracts, nil, mockState, nil, + ) + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + TransactionHandlerTypeIdentifier: "A.1654653399040a61.MyScheduler.Handler", + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + mockContracts.On("ByContract", flow.HexToAddress("1654653399040a61"), "MyScheduler").Return( + accessmodel.ContractDeployment{}, storage.ErrNotFound, + ).Once() + mockState.On("Sealed").Return(mockSnapshot).Once() + mockSnapshot.On("Head").Return(nil, fmt.Errorf("state error")).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, + ScheduledTransactionExpandOptions{HandlerContract: true}, + defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("expandHandlerContract: ErrNotFound and GetAccountCode fails triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + mockContracts := storagemock.NewContractDeploymentsIndexReader(t) + mockState := protocolmock.NewState(t) + mockSnapshot := protocolmock.NewSnapshot(t) + mockExecutor := executionmock.NewScriptExecutor(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, mockContracts, nil, mockState, mockExecutor, + ) + + sealedHeader := unittest.BlockHeaderFixture() + handlerAddr, err := flow.StringToAddress("1654653399040a61") + require.NoError(t, err) + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + TransactionHandlerTypeIdentifier: "A.1654653399040a61.MyScheduler.Handler", + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + mockContracts.On("ByContract", flow.HexToAddress("1654653399040a61"), "MyScheduler").Return( + accessmodel.ContractDeployment{}, storage.ErrNotFound, + ).Once() + mockState.On("Sealed").Return(mockSnapshot).Once() + mockSnapshot.On("Head").Return(sealedHeader, nil).Once() + mockExecutor.On("GetAccountCode", mocktestify.Anything, handlerAddr, "MyScheduler", sealedHeader.Height). + Return(nil, fmt.Errorf("executor error")).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err = backend.GetScheduledTransaction( + signalerCtx, 1, + ScheduledTransactionExpandOptions{HandlerContract: true}, + defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("expandHandlerContract: invalid type identifier triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + // Too few parts to extract a contract ID (requires at least 3 dot-separated segments). + TransactionHandlerTypeIdentifier: "invalid", + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction( + signalerCtx, 1, + ScheduledTransactionExpandOptions{HandlerContract: true}, + defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) +} + +// TestScheduledTransactionsBackend_GetScheduledTransactions tests all code paths for the +// GetScheduledTransactions method, including pagination, filtering, and error handling. +func TestScheduledTransactionsBackend_GetScheduledTransactions(t *testing.T) { + t.Parallel() + + defaultEncoding := entities.EventEncodingVersion_JSON_CDC_V0 + defaultConfig := DefaultConfig() + + t.Run("happy path: returns transactions without next cursor when fewer than limit", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + txs := []accessmodel.ScheduledTransaction{ + {ID: 5, Status: accessmodel.ScheduledTxStatusScheduled}, + {ID: 3, Status: accessmodel.ScheduledTxStatusScheduled}, + } + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(txs), nil).Once() + + page, err := backend.GetScheduledTransactions( + context.Background(), 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + require.Len(t, page.Transactions, 2) + assert.Nil(t, page.NextCursor) + }) + + t.Run("next cursor set when iterator yields more than limit items", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + // limit=2, provide 3 items: CollectResults collects 2, then peeks at item 3 to build cursor + txs := []accessmodel.ScheduledTransaction{ + {ID: 5, Status: accessmodel.ScheduledTxStatusScheduled}, + {ID: 3, Status: accessmodel.ScheduledTxStatusScheduled}, + {ID: 1, Status: accessmodel.ScheduledTxStatusScheduled}, + } + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(txs), nil).Once() + + page, err := backend.GetScheduledTransactions( + context.Background(), 2, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + require.Len(t, page.Transactions, 2) + require.NotNil(t, page.NextCursor) + assert.Equal(t, uint64(1), page.NextCursor.ID) + }) + + t.Run("default limit applied when limit is 0", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(nil), nil).Once() + + _, err := backend.GetScheduledTransactions( + context.Background(), 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("explicit limit is respected", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(nil), nil).Once() + + _, err := backend.GetScheduledTransactions( + context.Background(), 10, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("limit exceeding max returns InvalidArgument", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + _, err := backend.GetScheduledTransactions( + context.Background(), 500, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("cursor is forwarded to storage", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + cursor := &accessmodel.ScheduledTransactionCursor{ID: 100} + store.On("All", cursor). + Return(makeScheduledTxIter(nil), nil).Once() + + _, err := backend.GetScheduledTransactions( + context.Background(), 20, cursor, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("empty result set returns empty page", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(nil), nil).Once() + + page, err := backend.GetScheduledTransactions( + context.Background(), 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + assert.Empty(t, page.Transactions) + assert.Nil(t, page.NextCursor) + }) + + t.Run("ErrNotBootstrapped maps to FailedPrecondition", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(nil, storage.ErrNotBootstrapped).Once() + + _, err := backend.GetScheduledTransactions( + context.Background(), 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("unexpected storage error triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + storageErr := fmt.Errorf("unexpected disk failure") + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(nil, storageErr).Once() + + expectedErr := fmt.Errorf("failed to get scheduled transactions: %w", storageErr) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), + irrecoverable.NewMockSignalerContextExpectError(t, context.Background(), expectedErr)) + + _, err := backend.GetScheduledTransactions( + signalerCtx, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.Error(t, err) + }) + + t.Run("expand error triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + txID := unittest.IdentifierFixture() + txs := []accessmodel.ScheduledTransaction{ + {ID: 1, Status: accessmodel.ScheduledTxStatusExecuted, ExecutedTransactionID: txID}, + } + lookupErr := fmt.Errorf("lookup failed") + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(txs), nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(flow.Identifier{}, lookupErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransactions( + signalerCtx, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{Result: true}, + defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("tx block not yet available returns zero timestamps", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + collections: mockCollections, + blocks: mockBlocks, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + createdTxID := unittest.IdentifierFixture() + createdCollection := &flow.LightCollection{Transactions: []flow.Identifier{createdTxID}} + txs := []accessmodel.ScheduledTransaction{ + {ID: 1, Status: accessmodel.ScheduledTxStatusScheduled, CreatedTransactionID: createdTxID}, + } + + store.On("All", (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(txs), nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return(createdCollection, nil).Once() + mockBlocks.On("ByCollectionID", createdCollection.ID()).Return((*flow.Block)(nil), storage.ErrNotFound).Once() + + page, err := backend.GetScheduledTransactions( + context.Background(), 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + require.Len(t, page.Transactions, 1) + assert.Zero(t, page.Transactions[0].CreatedAt) + }) +} + +// TestScheduledTransactionsBackend_GetScheduledTransactionsByAddress tests all code paths for the +// GetScheduledTransactionsByAddress method, including pagination, address scoping, and error handling. +func TestScheduledTransactionsBackend_GetScheduledTransactionsByAddress(t *testing.T) { + t.Parallel() + + defaultEncoding := entities.EventEncodingVersion_JSON_CDC_V0 + defaultConfig := DefaultConfig() + + t.Run("happy path: returns transactions for address without next cursor when fewer than limit", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + txs := []accessmodel.ScheduledTransaction{ + {ID: 7, Status: accessmodel.ScheduledTxStatusScheduled}, + } + + store.On("ByAddress", addr, (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(txs), nil).Once() + + page, err := backend.GetScheduledTransactionsByAddress( + context.Background(), addr, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + require.Len(t, page.Transactions, 1) + assert.Equal(t, uint64(7), page.Transactions[0].ID) + assert.Nil(t, page.NextCursor) + }) + + t.Run("default limit applied when limit is 0", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + store.On("ByAddress", addr, (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(nil), nil).Once() + + _, err := backend.GetScheduledTransactionsByAddress( + context.Background(), addr, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("limit exceeding max returns InvalidArgument", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + + _, err := backend.GetScheduledTransactionsByAddress( + context.Background(), addr, 500, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.InvalidArgument, st.Code()) + }) + + t.Run("cursor is forwarded to storage", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + cursor := &accessmodel.ScheduledTransactionCursor{ID: 50} + store.On("ByAddress", addr, cursor). + Return(makeScheduledTxIter(nil), nil).Once() + + _, err := backend.GetScheduledTransactionsByAddress( + context.Background(), addr, 15, cursor, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + }) + + t.Run("empty result set returns empty page", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + store.On("ByAddress", addr, (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(nil), nil).Once() + + page, err := backend.GetScheduledTransactionsByAddress( + context.Background(), addr, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + assert.Empty(t, page.Transactions) + assert.Nil(t, page.NextCursor) + }) + + t.Run("ErrNotBootstrapped maps to FailedPrecondition", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + store.On("ByAddress", addr, (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(nil, storage.ErrNotBootstrapped).Once() + + _, err := backend.GetScheduledTransactionsByAddress( + context.Background(), addr, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.Error(t, err) + st, ok := status.FromError(err) + require.True(t, ok) + assert.Equal(t, codes.FailedPrecondition, st.Code()) + }) + + t.Run("unexpected storage error triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, nil, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + storageErr := fmt.Errorf("unexpected disk failure") + store.On("ByAddress", addr, (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(nil, storageErr).Once() + + expectedErr := fmt.Errorf("failed to get scheduled transactions: %w", storageErr) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), + irrecoverable.NewMockSignalerContextExpectError(t, context.Background(), expectedErr)) + + _, err := backend.GetScheduledTransactionsByAddress( + signalerCtx, addr, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.Error(t, err) + }) + + t.Run("expand error triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), &backendBase{config: defaultConfig}, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + txs := []accessmodel.ScheduledTransaction{ + {ID: 1, Status: accessmodel.ScheduledTxStatusExecuted, ExecutedTransactionID: txID}, + } + lookupErr := fmt.Errorf("lookup failed") + + store.On("ByAddress", addr, (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(txs), nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", txID).Return(flow.Identifier{}, lookupErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransactionsByAddress( + signalerCtx, addr, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{Result: true}, + defaultEncoding, + ) + require.Error(t, err) + verifyThrown() + }) + + t.Run("tx block not yet available returns zero timestamps", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + + backend := NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + collections: mockCollections, + blocks: mockBlocks, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + + addr := unittest.RandomAddressFixture() + createdTxID := unittest.IdentifierFixture() + createdCollection := &flow.LightCollection{Transactions: []flow.Identifier{createdTxID}} + txs := []accessmodel.ScheduledTransaction{ + {ID: 1, Status: accessmodel.ScheduledTxStatusScheduled, CreatedTransactionID: createdTxID}, + } + + store.On("ByAddress", addr, (*accessmodel.ScheduledTransactionCursor)(nil)). + Return(makeScheduledTxIter(txs), nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return(createdCollection, nil).Once() + mockBlocks.On("ByCollectionID", createdCollection.ID()).Return((*flow.Block)(nil), storage.ErrNotFound).Once() + + page, err := backend.GetScheduledTransactionsByAddress( + context.Background(), addr, 0, nil, + ScheduledTransactionFilter{}, ScheduledTransactionExpandOptions{}, + defaultEncoding, + ) + require.NoError(t, err) + require.Len(t, page.Transactions, 1) + assert.Zero(t, page.Transactions[0].CreatedAt) + }) +} + +// TestScheduledTransactionsBackend_PopulateBlockTimestamps verifies that populateBlockTimestamps +// correctly resolves CreatedAt and CompletedAt from the stored transaction IDs. +func TestScheduledTransactionsBackend_PopulateBlockTimestamps(t *testing.T) { + t.Parallel() + + defaultConfig := DefaultConfig() + defaultEncoding := entities.EventEncodingVersion_JSON_CDC_V0 + + // helper builds a full backend with all mocks configured + makeBackend := func( + store *storagemock.ScheduledTransactionsIndexReader, + scheduledTxLookup *storagemock.ScheduledTransactionsReader, + mockHeaders *storagemock.Headers, + mockCollections *storagemock.CollectionsReader, + mockBlocks *storagemock.Blocks, + ) *ScheduledTransactionsBackend { + return NewScheduledTransactionsBackend( + unittest.Logger(), + &backendBase{ + config: defaultConfig, + headers: mockHeaders, + blocks: mockBlocks, + collections: mockCollections, + }, + flow.Mainnet, store, nil, scheduledTxLookup, nil, nil, + ) + } + + t.Run("created_at populated for non-placeholder tx with CreatedTransactionID", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + backend := makeBackend(store, scheduledTxLookup, nil, mockCollections, mockBlocks) + + createdTxID := unittest.IdentifierFixture() + collection := &flow.LightCollection{Transactions: []flow.Identifier{createdTxID}} + block := unittest.BlockFixture() + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + CreatedTransactionID: createdTxID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + // createdTxID is a user transaction: not in scheduled tx lookup, falls back to collection + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return(collection, nil).Once() + mockBlocks.On("ByCollectionID", collection.ID()).Return(block, nil).Once() + + result, err := backend.GetScheduledTransaction(context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + assert.Equal(t, block.Timestamp, result.CreatedAt) + assert.Zero(t, result.CompletedAt) + }) + + t.Run("created_at absent for placeholder tx", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + backend := makeBackend(store, scheduledTxLookup, nil, nil, nil) + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + IsPlaceholder: true, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + // no lookups expected: placeholder tx skips CreatedAt, Scheduled status skips CompletedAt + + result, err := backend.GetScheduledTransaction(context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + assert.Zero(t, result.CreatedAt) + assert.Zero(t, result.CompletedAt) + }) + + t.Run("completed_at populated for executed tx via scheduledTxLookup", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockHeaders := storagemock.NewHeaders(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + backend := makeBackend(store, scheduledTxLookup, mockHeaders, mockCollections, mockBlocks) + + createdTxID := unittest.IdentifierFixture() + executedTxID := unittest.IdentifierFixture() + createdCollection := &flow.LightCollection{Transactions: []flow.Identifier{createdTxID}} + createdBlock := unittest.BlockFixture() + executedBlockHeader := unittest.BlockHeaderFixture() + executedBlockID := executedBlockHeader.ID() + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusExecuted, + CreatedTransactionID: createdTxID, + ExecutedTransactionID: executedTxID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + // createdTxID is a user transaction: scheduledTxLookup returns ErrNotFound, falls back to collection + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return(createdCollection, nil).Once() + mockBlocks.On("ByCollectionID", createdCollection.ID()).Return(createdBlock, nil).Once() + // executedTxID is a system transaction: scheduledTxLookup succeeds + scheduledTxLookup.On("BlockIDByTransactionID", executedTxID).Return(executedBlockID, nil).Once() + mockHeaders.On("ByBlockID", executedBlockID).Return(executedBlockHeader, nil).Once() + + result, err := backend.GetScheduledTransaction(context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + assert.Equal(t, createdBlock.Timestamp, result.CreatedAt) + assert.Equal(t, executedBlockHeader.Timestamp, result.CompletedAt) + }) + + t.Run("completed_at populated for cancelled tx via collection lookup", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + backend := makeBackend(store, scheduledTxLookup, nil, mockCollections, mockBlocks) + + createdTxID := unittest.IdentifierFixture() + cancelledTxID := unittest.IdentifierFixture() + createdCollection := &flow.LightCollection{Transactions: []flow.Identifier{createdTxID}} + cancelledCollection := &flow.LightCollection{Transactions: []flow.Identifier{cancelledTxID}} + createdBlock := unittest.BlockFixture() + cancelledBlock := unittest.BlockFixture() + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusCancelled, + CreatedTransactionID: createdTxID, + CancelledTransactionID: cancelledTxID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + // both are user transactions: not in scheduled tx lookup, fall back to collection + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return(createdCollection, nil).Once() + mockBlocks.On("ByCollectionID", createdCollection.ID()).Return(createdBlock, nil).Once() + scheduledTxLookup.On("BlockIDByTransactionID", cancelledTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", cancelledTxID).Return(cancelledCollection, nil).Once() + mockBlocks.On("ByCollectionID", cancelledCollection.ID()).Return(cancelledBlock, nil).Once() + + result, err := backend.GetScheduledTransaction(context.Background(), 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.NoError(t, err) + assert.Equal(t, createdBlock.Timestamp, result.CreatedAt) + assert.Equal(t, cancelledBlock.Timestamp, result.CompletedAt) + }) + + t.Run("collection lookup error for created tx triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + backend := makeBackend(store, scheduledTxLookup, nil, mockCollections, nil) + + createdTxID := unittest.IdentifierFixture() + lookupErr := fmt.Errorf("collection lookup error") + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusScheduled, + CreatedTransactionID: createdTxID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + // not in scheduled lookup, falls back to collection which errors + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return((*flow.LightCollection)(nil), lookupErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction(signalerCtx, 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.Error(t, err) + verifyThrown() + }) + + t.Run("BlockIDByTransactionID error for executed tx triggers irrecoverable", func(t *testing.T) { + store := storagemock.NewScheduledTransactionsIndexReader(t) + scheduledTxLookup := storagemock.NewScheduledTransactionsReader(t) + mockCollections := storagemock.NewCollectionsReader(t) + mockBlocks := storagemock.NewBlocks(t) + mockHeaders := storagemock.NewHeaders(t) + backend := makeBackend(store, scheduledTxLookup, mockHeaders, mockCollections, mockBlocks) + + createdTxID := unittest.IdentifierFixture() + executedTxID := unittest.IdentifierFixture() + createdCollection := &flow.LightCollection{Transactions: []flow.Identifier{createdTxID}} + createdBlock := unittest.BlockFixture() + lookupErr := fmt.Errorf("block lookup error") + + storedTx := accessmodel.ScheduledTransaction{ + ID: 1, + Status: accessmodel.ScheduledTxStatusExecuted, + CreatedTransactionID: createdTxID, + ExecutedTransactionID: executedTxID, + } + + store.On("ByID", uint64(1)).Return(storedTx, nil).Once() + // createdTxID falls back to collection + scheduledTxLookup.On("BlockIDByTransactionID", createdTxID).Return(flow.Identifier{}, storage.ErrNotFound).Once() + mockCollections.On("LightByTransactionID", createdTxID).Return(createdCollection, nil).Once() + mockBlocks.On("ByCollectionID", createdCollection.ID()).Return(createdBlock, nil).Once() + // executedTxID lookup returns an unexpected error + scheduledTxLookup.On("BlockIDByTransactionID", executedTxID).Return(flow.Identifier{}, lookupErr).Once() + + signalerCtx, verifyThrown := signalerCtxExpectingThrow(t) + + _, err := backend.GetScheduledTransaction(signalerCtx, 1, ScheduledTransactionExpandOptions{}, defaultEncoding) + require.Error(t, err) + verifyThrown() + }) +} diff --git a/access/backends/extended/mock/api.go b/access/backends/extended/mock/api.go new file mode 100644 index 00000000000..38e3be4566a --- /dev/null +++ b/access/backends/extended/mock/api.go @@ -0,0 +1,980 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "context" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow/protobuf/go/flow/entities" + mock "github.com/stretchr/testify/mock" +) + +// NewAPI creates a new instance of API. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *API { + mock := &API{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// API is an autogenerated mock type for the API type +type API struct { + mock.Mock +} + +type API_Expecter struct { + mock *mock.Mock +} + +func (_m *API) EXPECT() *API_Expecter { + return &API_Expecter{mock: &_m.Mock} +} + +// GetAccountFungibleTokenTransfers provides a mock function for the type API +func (_mock *API) GetAccountFungibleTokenTransfers(ctx context.Context, address flow.Address, limit uint32, cursor *access.TransferCursor, filter extended.AccountTransferFilter, expandOptions extended.AccountTransferExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.FungibleTokenTransfersPage, error) { + ret := _mock.Called(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetAccountFungibleTokenTransfers") + } + + var r0 *access.FungibleTokenTransfersPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.TransferCursor, extended.AccountTransferFilter, extended.AccountTransferExpandOptions, entities.EventEncodingVersion) (*access.FungibleTokenTransfersPage, error)); ok { + return returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.TransferCursor, extended.AccountTransferFilter, extended.AccountTransferExpandOptions, entities.EventEncodingVersion) *access.FungibleTokenTransfersPage); ok { + r0 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.FungibleTokenTransfersPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, *access.TransferCursor, extended.AccountTransferFilter, extended.AccountTransferExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetAccountFungibleTokenTransfers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountFungibleTokenTransfers' +type API_GetAccountFungibleTokenTransfers_Call struct { + *mock.Call +} + +// GetAccountFungibleTokenTransfers is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - limit uint32 +// - cursor *access.TransferCursor +// - filter extended.AccountTransferFilter +// - expandOptions extended.AccountTransferExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetAccountFungibleTokenTransfers(ctx interface{}, address interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetAccountFungibleTokenTransfers_Call { + return &API_GetAccountFungibleTokenTransfers_Call{Call: _e.mock.On("GetAccountFungibleTokenTransfers", ctx, address, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetAccountFungibleTokenTransfers_Call) Run(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.TransferCursor, filter extended.AccountTransferFilter, expandOptions extended.AccountTransferExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetAccountFungibleTokenTransfers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 *access.TransferCursor + if args[3] != nil { + arg3 = args[3].(*access.TransferCursor) + } + var arg4 extended.AccountTransferFilter + if args[4] != nil { + arg4 = args[4].(extended.AccountTransferFilter) + } + var arg5 extended.AccountTransferExpandOptions + if args[5] != nil { + arg5 = args[5].(extended.AccountTransferExpandOptions) + } + var arg6 entities.EventEncodingVersion + if args[6] != nil { + arg6 = args[6].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + ) + }) + return _c +} + +func (_c *API_GetAccountFungibleTokenTransfers_Call) Return(fungibleTokenTransfersPage *access.FungibleTokenTransfersPage, err error) *API_GetAccountFungibleTokenTransfers_Call { + _c.Call.Return(fungibleTokenTransfersPage, err) + return _c +} + +func (_c *API_GetAccountFungibleTokenTransfers_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.TransferCursor, filter extended.AccountTransferFilter, expandOptions extended.AccountTransferExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.FungibleTokenTransfersPage, error)) *API_GetAccountFungibleTokenTransfers_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountNonFungibleTokenTransfers provides a mock function for the type API +func (_mock *API) GetAccountNonFungibleTokenTransfers(ctx context.Context, address flow.Address, limit uint32, cursor *access.TransferCursor, filter extended.AccountTransferFilter, expandOptions extended.AccountTransferExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.NonFungibleTokenTransfersPage, error) { + ret := _mock.Called(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetAccountNonFungibleTokenTransfers") + } + + var r0 *access.NonFungibleTokenTransfersPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.TransferCursor, extended.AccountTransferFilter, extended.AccountTransferExpandOptions, entities.EventEncodingVersion) (*access.NonFungibleTokenTransfersPage, error)); ok { + return returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.TransferCursor, extended.AccountTransferFilter, extended.AccountTransferExpandOptions, entities.EventEncodingVersion) *access.NonFungibleTokenTransfersPage); ok { + r0 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.NonFungibleTokenTransfersPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, *access.TransferCursor, extended.AccountTransferFilter, extended.AccountTransferExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetAccountNonFungibleTokenTransfers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountNonFungibleTokenTransfers' +type API_GetAccountNonFungibleTokenTransfers_Call struct { + *mock.Call +} + +// GetAccountNonFungibleTokenTransfers is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - limit uint32 +// - cursor *access.TransferCursor +// - filter extended.AccountTransferFilter +// - expandOptions extended.AccountTransferExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetAccountNonFungibleTokenTransfers(ctx interface{}, address interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetAccountNonFungibleTokenTransfers_Call { + return &API_GetAccountNonFungibleTokenTransfers_Call{Call: _e.mock.On("GetAccountNonFungibleTokenTransfers", ctx, address, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetAccountNonFungibleTokenTransfers_Call) Run(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.TransferCursor, filter extended.AccountTransferFilter, expandOptions extended.AccountTransferExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetAccountNonFungibleTokenTransfers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 *access.TransferCursor + if args[3] != nil { + arg3 = args[3].(*access.TransferCursor) + } + var arg4 extended.AccountTransferFilter + if args[4] != nil { + arg4 = args[4].(extended.AccountTransferFilter) + } + var arg5 extended.AccountTransferExpandOptions + if args[5] != nil { + arg5 = args[5].(extended.AccountTransferExpandOptions) + } + var arg6 entities.EventEncodingVersion + if args[6] != nil { + arg6 = args[6].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + ) + }) + return _c +} + +func (_c *API_GetAccountNonFungibleTokenTransfers_Call) Return(nonFungibleTokenTransfersPage *access.NonFungibleTokenTransfersPage, err error) *API_GetAccountNonFungibleTokenTransfers_Call { + _c.Call.Return(nonFungibleTokenTransfersPage, err) + return _c +} + +func (_c *API_GetAccountNonFungibleTokenTransfers_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.TransferCursor, filter extended.AccountTransferFilter, expandOptions extended.AccountTransferExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.NonFungibleTokenTransfersPage, error)) *API_GetAccountNonFungibleTokenTransfers_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountTransactions provides a mock function for the type API +func (_mock *API) GetAccountTransactions(ctx context.Context, address flow.Address, limit uint32, cursor *access.AccountTransactionCursor, filter extended.AccountTransactionFilter, expandOptions extended.AccountTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.AccountTransactionsPage, error) { + ret := _mock.Called(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetAccountTransactions") + } + + var r0 *access.AccountTransactionsPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.AccountTransactionCursor, extended.AccountTransactionFilter, extended.AccountTransactionExpandOptions, entities.EventEncodingVersion) (*access.AccountTransactionsPage, error)); ok { + return returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.AccountTransactionCursor, extended.AccountTransactionFilter, extended.AccountTransactionExpandOptions, entities.EventEncodingVersion) *access.AccountTransactionsPage); ok { + r0 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.AccountTransactionsPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, *access.AccountTransactionCursor, extended.AccountTransactionFilter, extended.AccountTransactionExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetAccountTransactions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountTransactions' +type API_GetAccountTransactions_Call struct { + *mock.Call +} + +// GetAccountTransactions is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - limit uint32 +// - cursor *access.AccountTransactionCursor +// - filter extended.AccountTransactionFilter +// - expandOptions extended.AccountTransactionExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetAccountTransactions(ctx interface{}, address interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetAccountTransactions_Call { + return &API_GetAccountTransactions_Call{Call: _e.mock.On("GetAccountTransactions", ctx, address, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetAccountTransactions_Call) Run(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.AccountTransactionCursor, filter extended.AccountTransactionFilter, expandOptions extended.AccountTransactionExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetAccountTransactions_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 *access.AccountTransactionCursor + if args[3] != nil { + arg3 = args[3].(*access.AccountTransactionCursor) + } + var arg4 extended.AccountTransactionFilter + if args[4] != nil { + arg4 = args[4].(extended.AccountTransactionFilter) + } + var arg5 extended.AccountTransactionExpandOptions + if args[5] != nil { + arg5 = args[5].(extended.AccountTransactionExpandOptions) + } + var arg6 entities.EventEncodingVersion + if args[6] != nil { + arg6 = args[6].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + ) + }) + return _c +} + +func (_c *API_GetAccountTransactions_Call) Return(accountTransactionsPage *access.AccountTransactionsPage, err error) *API_GetAccountTransactions_Call { + _c.Call.Return(accountTransactionsPage, err) + return _c +} + +func (_c *API_GetAccountTransactions_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.AccountTransactionCursor, filter extended.AccountTransactionFilter, expandOptions extended.AccountTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.AccountTransactionsPage, error)) *API_GetAccountTransactions_Call { + _c.Call.Return(run) + return _c +} + +// GetContract provides a mock function for the type API +func (_mock *API) GetContract(ctx context.Context, id string, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeployment, error) { + ret := _mock.Called(ctx, id, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetContract") + } + + var r0 *access.ContractDeployment + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, string, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) (*access.ContractDeployment, error)); ok { + return returnFunc(ctx, id, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, string, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) *access.ContractDeployment); ok { + r0 = returnFunc(ctx, id, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ContractDeployment) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, string, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, id, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContract' +type API_GetContract_Call struct { + *mock.Call +} + +// GetContract is a helper method to define mock.On call +// - ctx context.Context +// - id string +// - filter extended.ContractDeploymentFilter +// - expandOptions extended.ContractDeploymentExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetContract(ctx interface{}, id interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetContract_Call { + return &API_GetContract_Call{Call: _e.mock.On("GetContract", ctx, id, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetContract_Call) Run(run func(ctx context.Context, id string, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 extended.ContractDeploymentFilter + if args[2] != nil { + arg2 = args[2].(extended.ContractDeploymentFilter) + } + var arg3 extended.ContractDeploymentExpandOptions + if args[3] != nil { + arg3 = args[3].(extended.ContractDeploymentExpandOptions) + } + var arg4 entities.EventEncodingVersion + if args[4] != nil { + arg4 = args[4].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *API_GetContract_Call) Return(contractDeployment *access.ContractDeployment, err error) *API_GetContract_Call { + _c.Call.Return(contractDeployment, err) + return _c +} + +func (_c *API_GetContract_Call) RunAndReturn(run func(ctx context.Context, id string, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeployment, error)) *API_GetContract_Call { + _c.Call.Return(run) + return _c +} + +// GetContractDeployments provides a mock function for the type API +func (_mock *API) GetContractDeployments(ctx context.Context, id string, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeploymentPage, error) { + ret := _mock.Called(ctx, id, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetContractDeployments") + } + + var r0 *access.ContractDeploymentPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) (*access.ContractDeploymentPage, error)); ok { + return returnFunc(ctx, id, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) *access.ContractDeploymentPage); ok { + r0 = returnFunc(ctx, id, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ContractDeploymentPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, string, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, id, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetContractDeployments_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContractDeployments' +type API_GetContractDeployments_Call struct { + *mock.Call +} + +// GetContractDeployments is a helper method to define mock.On call +// - ctx context.Context +// - id string +// - limit uint32 +// - cursor *access.ContractDeploymentsCursor +// - filter extended.ContractDeploymentFilter +// - expandOptions extended.ContractDeploymentExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetContractDeployments(ctx interface{}, id interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetContractDeployments_Call { + return &API_GetContractDeployments_Call{Call: _e.mock.On("GetContractDeployments", ctx, id, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetContractDeployments_Call) Run(run func(ctx context.Context, id string, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetContractDeployments_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 *access.ContractDeploymentsCursor + if args[3] != nil { + arg3 = args[3].(*access.ContractDeploymentsCursor) + } + var arg4 extended.ContractDeploymentFilter + if args[4] != nil { + arg4 = args[4].(extended.ContractDeploymentFilter) + } + var arg5 extended.ContractDeploymentExpandOptions + if args[5] != nil { + arg5 = args[5].(extended.ContractDeploymentExpandOptions) + } + var arg6 entities.EventEncodingVersion + if args[6] != nil { + arg6 = args[6].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + ) + }) + return _c +} + +func (_c *API_GetContractDeployments_Call) Return(contractDeploymentPage *access.ContractDeploymentPage, err error) *API_GetContractDeployments_Call { + _c.Call.Return(contractDeploymentPage, err) + return _c +} + +func (_c *API_GetContractDeployments_Call) RunAndReturn(run func(ctx context.Context, id string, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeploymentPage, error)) *API_GetContractDeployments_Call { + _c.Call.Return(run) + return _c +} + +// GetContracts provides a mock function for the type API +func (_mock *API) GetContracts(ctx context.Context, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeploymentPage, error) { + ret := _mock.Called(ctx, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetContracts") + } + + var r0 *access.ContractDeploymentPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) (*access.ContractDeploymentPage, error)); ok { + return returnFunc(ctx, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) *access.ContractDeploymentPage); ok { + r0 = returnFunc(ctx, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ContractDeploymentPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetContracts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContracts' +type API_GetContracts_Call struct { + *mock.Call +} + +// GetContracts is a helper method to define mock.On call +// - ctx context.Context +// - limit uint32 +// - cursor *access.ContractDeploymentsCursor +// - filter extended.ContractDeploymentFilter +// - expandOptions extended.ContractDeploymentExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetContracts(ctx interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetContracts_Call { + return &API_GetContracts_Call{Call: _e.mock.On("GetContracts", ctx, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetContracts_Call) Run(run func(ctx context.Context, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetContracts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + var arg2 *access.ContractDeploymentsCursor + if args[2] != nil { + arg2 = args[2].(*access.ContractDeploymentsCursor) + } + var arg3 extended.ContractDeploymentFilter + if args[3] != nil { + arg3 = args[3].(extended.ContractDeploymentFilter) + } + var arg4 extended.ContractDeploymentExpandOptions + if args[4] != nil { + arg4 = args[4].(extended.ContractDeploymentExpandOptions) + } + var arg5 entities.EventEncodingVersion + if args[5] != nil { + arg5 = args[5].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + ) + }) + return _c +} + +func (_c *API_GetContracts_Call) Return(contractDeploymentPage *access.ContractDeploymentPage, err error) *API_GetContracts_Call { + _c.Call.Return(contractDeploymentPage, err) + return _c +} + +func (_c *API_GetContracts_Call) RunAndReturn(run func(ctx context.Context, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeploymentPage, error)) *API_GetContracts_Call { + _c.Call.Return(run) + return _c +} + +// GetContractsByAddress provides a mock function for the type API +func (_mock *API) GetContractsByAddress(ctx context.Context, address flow.Address, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeploymentPage, error) { + ret := _mock.Called(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetContractsByAddress") + } + + var r0 *access.ContractDeploymentPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) (*access.ContractDeploymentPage, error)); ok { + return returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) *access.ContractDeploymentPage); ok { + r0 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ContractDeploymentPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, *access.ContractDeploymentsCursor, extended.ContractDeploymentFilter, extended.ContractDeploymentExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetContractsByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContractsByAddress' +type API_GetContractsByAddress_Call struct { + *mock.Call +} + +// GetContractsByAddress is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - limit uint32 +// - cursor *access.ContractDeploymentsCursor +// - filter extended.ContractDeploymentFilter +// - expandOptions extended.ContractDeploymentExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetContractsByAddress(ctx interface{}, address interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetContractsByAddress_Call { + return &API_GetContractsByAddress_Call{Call: _e.mock.On("GetContractsByAddress", ctx, address, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetContractsByAddress_Call) Run(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetContractsByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 *access.ContractDeploymentsCursor + if args[3] != nil { + arg3 = args[3].(*access.ContractDeploymentsCursor) + } + var arg4 extended.ContractDeploymentFilter + if args[4] != nil { + arg4 = args[4].(extended.ContractDeploymentFilter) + } + var arg5 extended.ContractDeploymentExpandOptions + if args[5] != nil { + arg5 = args[5].(extended.ContractDeploymentExpandOptions) + } + var arg6 entities.EventEncodingVersion + if args[6] != nil { + arg6 = args[6].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + ) + }) + return _c +} + +func (_c *API_GetContractsByAddress_Call) Return(contractDeploymentPage *access.ContractDeploymentPage, err error) *API_GetContractsByAddress_Call { + _c.Call.Return(contractDeploymentPage, err) + return _c +} + +func (_c *API_GetContractsByAddress_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.ContractDeploymentsCursor, filter extended.ContractDeploymentFilter, expandOptions extended.ContractDeploymentExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ContractDeploymentPage, error)) *API_GetContractsByAddress_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransaction provides a mock function for the type API +func (_mock *API) GetScheduledTransaction(ctx context.Context, id uint64, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ScheduledTransaction, error) { + ret := _mock.Called(ctx, id, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetScheduledTransaction") + } + + var r0 *access.ScheduledTransaction + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) (*access.ScheduledTransaction, error)); ok { + return returnFunc(ctx, id, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) *access.ScheduledTransaction); ok { + r0 = returnFunc(ctx, id, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ScheduledTransaction) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, id, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetScheduledTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransaction' +type API_GetScheduledTransaction_Call struct { + *mock.Call +} + +// GetScheduledTransaction is a helper method to define mock.On call +// - ctx context.Context +// - id uint64 +// - expandOptions extended.ScheduledTransactionExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetScheduledTransaction(ctx interface{}, id interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetScheduledTransaction_Call { + return &API_GetScheduledTransaction_Call{Call: _e.mock.On("GetScheduledTransaction", ctx, id, expandOptions, encodingVersion)} +} + +func (_c *API_GetScheduledTransaction_Call) Run(run func(ctx context.Context, id uint64, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetScheduledTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 extended.ScheduledTransactionExpandOptions + if args[2] != nil { + arg2 = args[2].(extended.ScheduledTransactionExpandOptions) + } + var arg3 entities.EventEncodingVersion + if args[3] != nil { + arg3 = args[3].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_GetScheduledTransaction_Call) Return(scheduledTransaction *access.ScheduledTransaction, err error) *API_GetScheduledTransaction_Call { + _c.Call.Return(scheduledTransaction, err) + return _c +} + +func (_c *API_GetScheduledTransaction_Call) RunAndReturn(run func(ctx context.Context, id uint64, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ScheduledTransaction, error)) *API_GetScheduledTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransactions provides a mock function for the type API +func (_mock *API) GetScheduledTransactions(ctx context.Context, limit uint32, cursor *access.ScheduledTransactionCursor, filter extended.ScheduledTransactionFilter, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ScheduledTransactionsPage, error) { + ret := _mock.Called(ctx, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetScheduledTransactions") + } + + var r0 *access.ScheduledTransactionsPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, uint32, *access.ScheduledTransactionCursor, extended.ScheduledTransactionFilter, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) (*access.ScheduledTransactionsPage, error)); ok { + return returnFunc(ctx, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, uint32, *access.ScheduledTransactionCursor, extended.ScheduledTransactionFilter, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) *access.ScheduledTransactionsPage); ok { + r0 = returnFunc(ctx, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ScheduledTransactionsPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, uint32, *access.ScheduledTransactionCursor, extended.ScheduledTransactionFilter, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetScheduledTransactions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransactions' +type API_GetScheduledTransactions_Call struct { + *mock.Call +} + +// GetScheduledTransactions is a helper method to define mock.On call +// - ctx context.Context +// - limit uint32 +// - cursor *access.ScheduledTransactionCursor +// - filter extended.ScheduledTransactionFilter +// - expandOptions extended.ScheduledTransactionExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetScheduledTransactions(ctx interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetScheduledTransactions_Call { + return &API_GetScheduledTransactions_Call{Call: _e.mock.On("GetScheduledTransactions", ctx, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetScheduledTransactions_Call) Run(run func(ctx context.Context, limit uint32, cursor *access.ScheduledTransactionCursor, filter extended.ScheduledTransactionFilter, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetScheduledTransactions_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + var arg2 *access.ScheduledTransactionCursor + if args[2] != nil { + arg2 = args[2].(*access.ScheduledTransactionCursor) + } + var arg3 extended.ScheduledTransactionFilter + if args[3] != nil { + arg3 = args[3].(extended.ScheduledTransactionFilter) + } + var arg4 extended.ScheduledTransactionExpandOptions + if args[4] != nil { + arg4 = args[4].(extended.ScheduledTransactionExpandOptions) + } + var arg5 entities.EventEncodingVersion + if args[5] != nil { + arg5 = args[5].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + ) + }) + return _c +} + +func (_c *API_GetScheduledTransactions_Call) Return(scheduledTransactionsPage *access.ScheduledTransactionsPage, err error) *API_GetScheduledTransactions_Call { + _c.Call.Return(scheduledTransactionsPage, err) + return _c +} + +func (_c *API_GetScheduledTransactions_Call) RunAndReturn(run func(ctx context.Context, limit uint32, cursor *access.ScheduledTransactionCursor, filter extended.ScheduledTransactionFilter, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ScheduledTransactionsPage, error)) *API_GetScheduledTransactions_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransactionsByAddress provides a mock function for the type API +func (_mock *API) GetScheduledTransactionsByAddress(ctx context.Context, address flow.Address, limit uint32, cursor *access.ScheduledTransactionCursor, filter extended.ScheduledTransactionFilter, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ScheduledTransactionsPage, error) { + ret := _mock.Called(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + + if len(ret) == 0 { + panic("no return value specified for GetScheduledTransactionsByAddress") + } + + var r0 *access.ScheduledTransactionsPage + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.ScheduledTransactionCursor, extended.ScheduledTransactionFilter, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) (*access.ScheduledTransactionsPage, error)); ok { + return returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *access.ScheduledTransactionCursor, extended.ScheduledTransactionFilter, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) *access.ScheduledTransactionsPage); ok { + r0 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ScheduledTransactionsPage) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, *access.ScheduledTransactionCursor, extended.ScheduledTransactionFilter, extended.ScheduledTransactionExpandOptions, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, address, limit, cursor, filter, expandOptions, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetScheduledTransactionsByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransactionsByAddress' +type API_GetScheduledTransactionsByAddress_Call struct { + *mock.Call +} + +// GetScheduledTransactionsByAddress is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - limit uint32 +// - cursor *access.ScheduledTransactionCursor +// - filter extended.ScheduledTransactionFilter +// - expandOptions extended.ScheduledTransactionExpandOptions +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetScheduledTransactionsByAddress(ctx interface{}, address interface{}, limit interface{}, cursor interface{}, filter interface{}, expandOptions interface{}, encodingVersion interface{}) *API_GetScheduledTransactionsByAddress_Call { + return &API_GetScheduledTransactionsByAddress_Call{Call: _e.mock.On("GetScheduledTransactionsByAddress", ctx, address, limit, cursor, filter, expandOptions, encodingVersion)} +} + +func (_c *API_GetScheduledTransactionsByAddress_Call) Run(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.ScheduledTransactionCursor, filter extended.ScheduledTransactionFilter, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion)) *API_GetScheduledTransactionsByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 *access.ScheduledTransactionCursor + if args[3] != nil { + arg3 = args[3].(*access.ScheduledTransactionCursor) + } + var arg4 extended.ScheduledTransactionFilter + if args[4] != nil { + arg4 = args[4].(extended.ScheduledTransactionFilter) + } + var arg5 extended.ScheduledTransactionExpandOptions + if args[5] != nil { + arg5 = args[5].(extended.ScheduledTransactionExpandOptions) + } + var arg6 entities.EventEncodingVersion + if args[6] != nil { + arg6 = args[6].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + ) + }) + return _c +} + +func (_c *API_GetScheduledTransactionsByAddress_Call) Return(scheduledTransactionsPage *access.ScheduledTransactionsPage, err error) *API_GetScheduledTransactionsByAddress_Call { + _c.Call.Return(scheduledTransactionsPage, err) + return _c +} + +func (_c *API_GetScheduledTransactionsByAddress_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, limit uint32, cursor *access.ScheduledTransactionCursor, filter extended.ScheduledTransactionFilter, expandOptions extended.ScheduledTransactionExpandOptions, encodingVersion entities.EventEncodingVersion) (*access.ScheduledTransactionsPage, error)) *API_GetScheduledTransactionsByAddress_Call { + _c.Call.Return(run) + return _c +} diff --git a/access/legacy/handler.go b/access/legacy/handler.go index 8a504680d01..39ec3751a1f 100644 --- a/access/legacy/handler.go +++ b/access/legacy/handler.go @@ -35,7 +35,7 @@ func (h *Handler) GetNetworkParameters( context.Context, *accessproto.GetNetworkParametersRequest, ) (*accessproto.GetNetworkParametersResponse, error) { - panic("implement me") + return nil, status.Error(codes.Unimplemented, "not implemented") } // SendTransaction submits a transaction to the network. @@ -252,7 +252,7 @@ func (h *Handler) GetAccountAtBlockHeight( ctx context.Context, request *accessproto.GetAccountAtBlockHeightRequest, ) (*accessproto.AccountResponse, error) { - panic("implement me") + return nil, status.Error(codes.Unimplemented, "not implemented") } // ExecuteScriptAtLatestBlock executes a script at a the latest block diff --git a/access/mock/accounts_api.go b/access/mock/accounts_api.go index 8362f73238e..04033a58a37 100644 --- a/access/mock/accounts_api.go +++ b/access/mock/accounts_api.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewAccountsAPI creates a new instance of AccountsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountsAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountsAPI { + mock := &AccountsAPI{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccountsAPI is an autogenerated mock type for the AccountsAPI type type AccountsAPI struct { mock.Mock } -// GetAccount provides a mock function with given fields: ctx, address -func (_m *AccountsAPI) GetAccount(ctx context.Context, address flow.Address) (*flow.Account, error) { - ret := _m.Called(ctx, address) +type AccountsAPI_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountsAPI) EXPECT() *AccountsAPI_Expecter { + return &AccountsAPI_Expecter{mock: &_m.Mock} +} + +// GetAccount provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccount(ctx context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -24,29 +48,67 @@ func (_m *AccountsAPI) GetAccount(ctx context.Context, address flow.Address) (*f var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *AccountsAPI) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { - ret := _m.Called(ctx, address, height) +// AccountsAPI_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type AccountsAPI_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *AccountsAPI_Expecter) GetAccount(ctx interface{}, address interface{}) *AccountsAPI_GetAccount_Call { + return &AccountsAPI_GetAccount_Call{Call: _e.mock.On("GetAccount", ctx, address)} +} + +func (_c *AccountsAPI_GetAccount_Call) Run(run func(ctx context.Context, address flow.Address)) *AccountsAPI_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccount_Call) Return(account *flow.Account, err error) *AccountsAPI_GetAccount_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *AccountsAPI_GetAccount_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (*flow.Account, error)) *AccountsAPI_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockHeight provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockHeight") @@ -54,29 +116,73 @@ func (_m *AccountsAPI) GetAccountAtBlockHeight(ctx context.Context, address flow var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { + r0 = returnFunc(ctx, address, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *AccountsAPI) GetAccountAtLatestBlock(ctx context.Context, address flow.Address) (*flow.Account, error) { - ret := _m.Called(ctx, address) +// AccountsAPI_GetAccountAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockHeight' +type AccountsAPI_GetAccountAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *AccountsAPI_Expecter) GetAccountAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *AccountsAPI_GetAccountAtBlockHeight_Call { + return &AccountsAPI_GetAccountAtBlockHeight_Call{Call: _e.mock.On("GetAccountAtBlockHeight", ctx, address, height)} +} + +func (_c *AccountsAPI_GetAccountAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *AccountsAPI_GetAccountAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountAtBlockHeight_Call) Return(account *flow.Account, err error) *AccountsAPI_GetAccountAtBlockHeight_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *AccountsAPI_GetAccountAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error)) *AccountsAPI_GetAccountAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtLatestBlock provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountAtLatestBlock(ctx context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountAtLatestBlock") @@ -84,29 +190,67 @@ func (_m *AccountsAPI) GetAccountAtLatestBlock(ctx context.Context, address flow var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *AccountsAPI) GetAccountBalanceAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (uint64, error) { - ret := _m.Called(ctx, address, height) +// AccountsAPI_GetAccountAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtLatestBlock' +type AccountsAPI_GetAccountAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *AccountsAPI_Expecter) GetAccountAtLatestBlock(ctx interface{}, address interface{}) *AccountsAPI_GetAccountAtLatestBlock_Call { + return &AccountsAPI_GetAccountAtLatestBlock_Call{Call: _e.mock.On("GetAccountAtLatestBlock", ctx, address)} +} + +func (_c *AccountsAPI_GetAccountAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *AccountsAPI_GetAccountAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountAtLatestBlock_Call) Return(account *flow.Account, err error) *AccountsAPI_GetAccountAtLatestBlock_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *AccountsAPI_GetAccountAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (*flow.Account, error)) *AccountsAPI_GetAccountAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtBlockHeight provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountBalanceAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (uint64, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtBlockHeight") @@ -114,27 +258,71 @@ func (_m *AccountsAPI) GetAccountBalanceAtBlockHeight(ctx context.Context, addre var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { + r0 = returnFunc(ctx, address, height) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *AccountsAPI) GetAccountBalanceAtLatestBlock(ctx context.Context, address flow.Address) (uint64, error) { - ret := _m.Called(ctx, address) +// AccountsAPI_GetAccountBalanceAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtBlockHeight' +type AccountsAPI_GetAccountBalanceAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountBalanceAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *AccountsAPI_Expecter) GetAccountBalanceAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *AccountsAPI_GetAccountBalanceAtBlockHeight_Call { + return &AccountsAPI_GetAccountBalanceAtBlockHeight_Call{Call: _e.mock.On("GetAccountBalanceAtBlockHeight", ctx, address, height)} +} + +func (_c *AccountsAPI_GetAccountBalanceAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *AccountsAPI_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountBalanceAtBlockHeight_Call) Return(v uint64, err error) *AccountsAPI_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountsAPI_GetAccountBalanceAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (uint64, error)) *AccountsAPI_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtLatestBlock provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountBalanceAtLatestBlock(ctx context.Context, address flow.Address) (uint64, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtLatestBlock") @@ -142,27 +330,65 @@ func (_m *AccountsAPI) GetAccountBalanceAtLatestBlock(ctx context.Context, addre var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (uint64, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (uint64, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) uint64); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) uint64); ok { + r0 = returnFunc(ctx, address) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtBlockHeight provides a mock function with given fields: ctx, address, keyIndex, height -func (_m *AccountsAPI) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, keyIndex, height) +// AccountsAPI_GetAccountBalanceAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtLatestBlock' +type AccountsAPI_GetAccountBalanceAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountBalanceAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *AccountsAPI_Expecter) GetAccountBalanceAtLatestBlock(ctx interface{}, address interface{}) *AccountsAPI_GetAccountBalanceAtLatestBlock_Call { + return &AccountsAPI_GetAccountBalanceAtLatestBlock_Call{Call: _e.mock.On("GetAccountBalanceAtLatestBlock", ctx, address)} +} + +func (_c *AccountsAPI_GetAccountBalanceAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *AccountsAPI_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountBalanceAtLatestBlock_Call) Return(v uint64, err error) *AccountsAPI_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountsAPI_GetAccountBalanceAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (uint64, error)) *AccountsAPI_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtBlockHeight provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, keyIndex, height) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtBlockHeight") @@ -170,29 +396,79 @@ func (_m *AccountsAPI) GetAccountKeyAtBlockHeight(ctx context.Context, address f var r0 *flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountPublicKey, error)); ok { - return rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, keyIndex, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountPublicKey); ok { - r0 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, keyIndex, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { - r1 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { + r1 = returnFunc(ctx, address, keyIndex, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtLatestBlock provides a mock function with given fields: ctx, address, keyIndex -func (_m *AccountsAPI) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, keyIndex) +// AccountsAPI_GetAccountKeyAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtBlockHeight' +type AccountsAPI_GetAccountKeyAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeyAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - keyIndex uint32 +// - height uint64 +func (_e *AccountsAPI_Expecter) GetAccountKeyAtBlockHeight(ctx interface{}, address interface{}, keyIndex interface{}, height interface{}) *AccountsAPI_GetAccountKeyAtBlockHeight_Call { + return &AccountsAPI_GetAccountKeyAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeyAtBlockHeight", ctx, address, keyIndex, height)} +} + +func (_c *AccountsAPI_GetAccountKeyAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64)) *AccountsAPI_GetAccountKeyAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountKeyAtBlockHeight_Call) Return(accountPublicKey *flow.AccountPublicKey, err error) *AccountsAPI_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(accountPublicKey, err) + return _c +} + +func (_c *AccountsAPI_GetAccountKeyAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error)) *AccountsAPI_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtLatestBlock provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, keyIndex) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtLatestBlock") @@ -200,29 +476,73 @@ func (_m *AccountsAPI) GetAccountKeyAtLatestBlock(ctx context.Context, address f var r0 *flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) (*flow.AccountPublicKey, error)); ok { - return rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) (*flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, keyIndex) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) *flow.AccountPublicKey); ok { - r0 = rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) *flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, keyIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32) error); ok { - r1 = rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32) error); ok { + r1 = returnFunc(ctx, address, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *AccountsAPI) GetAccountKeysAtBlockHeight(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, height) +// AccountsAPI_GetAccountKeyAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtLatestBlock' +type AccountsAPI_GetAccountKeyAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeyAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - keyIndex uint32 +func (_e *AccountsAPI_Expecter) GetAccountKeyAtLatestBlock(ctx interface{}, address interface{}, keyIndex interface{}) *AccountsAPI_GetAccountKeyAtLatestBlock_Call { + return &AccountsAPI_GetAccountKeyAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeyAtLatestBlock", ctx, address, keyIndex)} +} + +func (_c *AccountsAPI_GetAccountKeyAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address, keyIndex uint32)) *AccountsAPI_GetAccountKeyAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountKeyAtLatestBlock_Call) Return(accountPublicKey *flow.AccountPublicKey, err error) *AccountsAPI_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(accountPublicKey, err) + return _c +} + +func (_c *AccountsAPI_GetAccountKeyAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountPublicKey, error)) *AccountsAPI_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtBlockHeight provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountKeysAtBlockHeight(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtBlockHeight") @@ -230,29 +550,73 @@ func (_m *AccountsAPI) GetAccountKeysAtBlockHeight(ctx context.Context, address var r0 []flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]flow.AccountPublicKey, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []flow.AccountPublicKey); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *AccountsAPI) GetAccountKeysAtLatestBlock(ctx context.Context, address flow.Address) ([]flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address) +// AccountsAPI_GetAccountKeysAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtBlockHeight' +type AccountsAPI_GetAccountKeysAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeysAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *AccountsAPI_Expecter) GetAccountKeysAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *AccountsAPI_GetAccountKeysAtBlockHeight_Call { + return &AccountsAPI_GetAccountKeysAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeysAtBlockHeight", ctx, address, height)} +} + +func (_c *AccountsAPI_GetAccountKeysAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *AccountsAPI_GetAccountKeysAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountKeysAtBlockHeight_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *AccountsAPI_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *AccountsAPI_GetAccountKeysAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error)) *AccountsAPI_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtLatestBlock provides a mock function for the type AccountsAPI +func (_mock *AccountsAPI) GetAccountKeysAtLatestBlock(ctx context.Context, address flow.Address) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtLatestBlock") @@ -260,36 +624,60 @@ func (_m *AccountsAPI) GetAccountKeysAtLatestBlock(ctx context.Context, address var r0 []flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) ([]flow.AccountPublicKey, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) []flow.AccountPublicKey); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) []flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAccountsAPI creates a new instance of AccountsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccountsAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *AccountsAPI { - mock := &AccountsAPI{} - mock.Mock.Test(t) +// AccountsAPI_GetAccountKeysAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtLatestBlock' +type AccountsAPI_GetAccountKeysAtLatestBlock_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetAccountKeysAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *AccountsAPI_Expecter) GetAccountKeysAtLatestBlock(ctx interface{}, address interface{}) *AccountsAPI_GetAccountKeysAtLatestBlock_Call { + return &AccountsAPI_GetAccountKeysAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeysAtLatestBlock", ctx, address)} +} - return mock +func (_c *AccountsAPI_GetAccountKeysAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *AccountsAPI_GetAccountKeysAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountsAPI_GetAccountKeysAtLatestBlock_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *AccountsAPI_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *AccountsAPI_GetAccountKeysAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) ([]flow.AccountPublicKey, error)) *AccountsAPI_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(run) + return _c } diff --git a/access/mock/api.go b/access/mock/api.go index cfbc16f4bd4..189992a8f62 100644 --- a/access/mock/api.go +++ b/access/mock/api.go @@ -1,28 +1,49 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - entities "github.com/onflow/flow/protobuf/go/flow/entities" + "context" + "github.com/onflow/flow-go/engine/access/subscription" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow/protobuf/go/flow/entities" mock "github.com/stretchr/testify/mock" +) + +// NewAPI creates a new instance of API. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *API { + mock := &API{} + mock.Mock.Test(t) - modelaccess "github.com/onflow/flow-go/model/access" + t.Cleanup(func() { mock.AssertExpectations(t) }) - subscription "github.com/onflow/flow-go/engine/access/subscription" -) + return mock +} // API is an autogenerated mock type for the API type type API struct { mock.Mock } -// ExecuteScriptAtBlockHeight provides a mock function with given fields: ctx, blockHeight, script, arguments -func (_m *API) ExecuteScriptAtBlockHeight(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte) ([]byte, error) { - ret := _m.Called(ctx, blockHeight, script, arguments) +type API_Expecter struct { + mock *mock.Mock +} + +func (_m *API) EXPECT() *API_Expecter { + return &API_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockHeight provides a mock function for the type API +func (_mock *API) ExecuteScriptAtBlockHeight(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte) ([]byte, error) { + ret := _mock.Called(ctx, blockHeight, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockHeight") @@ -30,29 +51,79 @@ func (_m *API) ExecuteScriptAtBlockHeight(ctx context.Context, blockHeight uint6 var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) ([]byte, error)); ok { - return rf(ctx, blockHeight, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) ([]byte, error)); ok { + return returnFunc(ctx, blockHeight, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) []byte); ok { - r0 = rf(ctx, blockHeight, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) []byte); ok { + r0 = returnFunc(ctx, blockHeight, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, []byte, [][]byte) error); ok { - r1 = rf(ctx, blockHeight, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, []byte, [][]byte) error); ok { + r1 = returnFunc(ctx, blockHeight, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtBlockID provides a mock function with given fields: ctx, blockID, script, arguments -func (_m *API) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte) ([]byte, error) { - ret := _m.Called(ctx, blockID, script, arguments) +// API_ExecuteScriptAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockHeight' +type API_ExecuteScriptAtBlockHeight_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - blockHeight uint64 +// - script []byte +// - arguments [][]byte +func (_e *API_Expecter) ExecuteScriptAtBlockHeight(ctx interface{}, blockHeight interface{}, script interface{}, arguments interface{}) *API_ExecuteScriptAtBlockHeight_Call { + return &API_ExecuteScriptAtBlockHeight_Call{Call: _e.mock.On("ExecuteScriptAtBlockHeight", ctx, blockHeight, script, arguments)} +} + +func (_c *API_ExecuteScriptAtBlockHeight_Call) Run(run func(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte)) *API_ExecuteScriptAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 [][]byte + if args[3] != nil { + arg3 = args[3].([][]byte) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_ExecuteScriptAtBlockHeight_Call) Return(bytes []byte, err error) *API_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *API_ExecuteScriptAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte) ([]byte, error)) *API_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtBlockID provides a mock function for the type API +func (_mock *API) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte) ([]byte, error) { + ret := _mock.Called(ctx, blockID, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -60,29 +131,79 @@ func (_m *API) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Identifi var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) ([]byte, error)); ok { - return rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) ([]byte, error)); ok { + return returnFunc(ctx, blockID, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) []byte); ok { - r0 = rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) []byte); ok { + r0 = returnFunc(ctx, blockID, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, [][]byte) error); ok { - r1 = rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, [][]byte) error); ok { + r1 = returnFunc(ctx, blockID, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtLatestBlock provides a mock function with given fields: ctx, script, arguments -func (_m *API) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, arguments [][]byte) ([]byte, error) { - ret := _m.Called(ctx, script, arguments) +// API_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type API_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - script []byte +// - arguments [][]byte +func (_e *API_Expecter) ExecuteScriptAtBlockID(ctx interface{}, blockID interface{}, script interface{}, arguments interface{}) *API_ExecuteScriptAtBlockID_Call { + return &API_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", ctx, blockID, script, arguments)} +} + +func (_c *API_ExecuteScriptAtBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte)) *API_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 [][]byte + if args[3] != nil { + arg3 = args[3].([][]byte) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_ExecuteScriptAtBlockID_Call) Return(bytes []byte, err error) *API_ExecuteScriptAtBlockID_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *API_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte) ([]byte, error)) *API_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtLatestBlock provides a mock function for the type API +func (_mock *API) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, arguments [][]byte) ([]byte, error) { + ret := _mock.Called(ctx, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtLatestBlock") @@ -90,29 +211,73 @@ func (_m *API) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, ar var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) ([]byte, error)); ok { - return rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) ([]byte, error)); ok { + return returnFunc(ctx, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) []byte); ok { - r0 = rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) []byte); ok { + r0 = returnFunc(ctx, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, [][]byte) error); ok { - r1 = rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, [][]byte) error); ok { + r1 = returnFunc(ctx, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccount provides a mock function with given fields: ctx, address -func (_m *API) GetAccount(ctx context.Context, address flow.Address) (*flow.Account, error) { - ret := _m.Called(ctx, address) +// API_ExecuteScriptAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtLatestBlock' +type API_ExecuteScriptAtLatestBlock_Call struct { + *mock.Call +} + +// ExecuteScriptAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - script []byte +// - arguments [][]byte +func (_e *API_Expecter) ExecuteScriptAtLatestBlock(ctx interface{}, script interface{}, arguments interface{}) *API_ExecuteScriptAtLatestBlock_Call { + return &API_ExecuteScriptAtLatestBlock_Call{Call: _e.mock.On("ExecuteScriptAtLatestBlock", ctx, script, arguments)} +} + +func (_c *API_ExecuteScriptAtLatestBlock_Call) Run(run func(ctx context.Context, script []byte, arguments [][]byte)) *API_ExecuteScriptAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 [][]byte + if args[2] != nil { + arg2 = args[2].([][]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_ExecuteScriptAtLatestBlock_Call) Return(bytes []byte, err error) *API_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *API_ExecuteScriptAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, script []byte, arguments [][]byte) ([]byte, error)) *API_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccount provides a mock function for the type API +func (_mock *API) GetAccount(ctx context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -120,29 +285,67 @@ func (_m *API) GetAccount(ctx context.Context, address flow.Address) (*flow.Acco var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *API) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { - ret := _m.Called(ctx, address, height) +// API_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type API_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *API_Expecter) GetAccount(ctx interface{}, address interface{}) *API_GetAccount_Call { + return &API_GetAccount_Call{Call: _e.mock.On("GetAccount", ctx, address)} +} + +func (_c *API_GetAccount_Call) Run(run func(ctx context.Context, address flow.Address)) *API_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetAccount_Call) Return(account *flow.Account, err error) *API_GetAccount_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *API_GetAccount_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (*flow.Account, error)) *API_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockHeight provides a mock function for the type API +func (_mock *API) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockHeight") @@ -150,29 +353,73 @@ func (_m *API) GetAccountAtBlockHeight(ctx context.Context, address flow.Address var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { + r0 = returnFunc(ctx, address, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *API) GetAccountAtLatestBlock(ctx context.Context, address flow.Address) (*flow.Account, error) { - ret := _m.Called(ctx, address) +// API_GetAccountAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockHeight' +type API_GetAccountAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *API_Expecter) GetAccountAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *API_GetAccountAtBlockHeight_Call { + return &API_GetAccountAtBlockHeight_Call{Call: _e.mock.On("GetAccountAtBlockHeight", ctx, address, height)} +} + +func (_c *API_GetAccountAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *API_GetAccountAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_GetAccountAtBlockHeight_Call) Return(account *flow.Account, err error) *API_GetAccountAtBlockHeight_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *API_GetAccountAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error)) *API_GetAccountAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtLatestBlock provides a mock function for the type API +func (_mock *API) GetAccountAtLatestBlock(ctx context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountAtLatestBlock") @@ -180,29 +427,67 @@ func (_m *API) GetAccountAtLatestBlock(ctx context.Context, address flow.Address var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *API) GetAccountBalanceAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (uint64, error) { - ret := _m.Called(ctx, address, height) +// API_GetAccountAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtLatestBlock' +type API_GetAccountAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *API_Expecter) GetAccountAtLatestBlock(ctx interface{}, address interface{}) *API_GetAccountAtLatestBlock_Call { + return &API_GetAccountAtLatestBlock_Call{Call: _e.mock.On("GetAccountAtLatestBlock", ctx, address)} +} + +func (_c *API_GetAccountAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *API_GetAccountAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetAccountAtLatestBlock_Call) Return(account *flow.Account, err error) *API_GetAccountAtLatestBlock_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *API_GetAccountAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (*flow.Account, error)) *API_GetAccountAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtBlockHeight provides a mock function for the type API +func (_mock *API) GetAccountBalanceAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (uint64, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtBlockHeight") @@ -210,27 +495,71 @@ func (_m *API) GetAccountBalanceAtBlockHeight(ctx context.Context, address flow. var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { + r0 = returnFunc(ctx, address, height) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *API) GetAccountBalanceAtLatestBlock(ctx context.Context, address flow.Address) (uint64, error) { - ret := _m.Called(ctx, address) +// API_GetAccountBalanceAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtBlockHeight' +type API_GetAccountBalanceAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountBalanceAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *API_Expecter) GetAccountBalanceAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *API_GetAccountBalanceAtBlockHeight_Call { + return &API_GetAccountBalanceAtBlockHeight_Call{Call: _e.mock.On("GetAccountBalanceAtBlockHeight", ctx, address, height)} +} + +func (_c *API_GetAccountBalanceAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *API_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_GetAccountBalanceAtBlockHeight_Call) Return(v uint64, err error) *API_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *API_GetAccountBalanceAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (uint64, error)) *API_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtLatestBlock provides a mock function for the type API +func (_mock *API) GetAccountBalanceAtLatestBlock(ctx context.Context, address flow.Address) (uint64, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtLatestBlock") @@ -238,27 +567,65 @@ func (_m *API) GetAccountBalanceAtLatestBlock(ctx context.Context, address flow. var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (uint64, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (uint64, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) uint64); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) uint64); ok { + r0 = returnFunc(ctx, address) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtBlockHeight provides a mock function with given fields: ctx, address, keyIndex, height -func (_m *API) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, keyIndex, height) +// API_GetAccountBalanceAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtLatestBlock' +type API_GetAccountBalanceAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountBalanceAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *API_Expecter) GetAccountBalanceAtLatestBlock(ctx interface{}, address interface{}) *API_GetAccountBalanceAtLatestBlock_Call { + return &API_GetAccountBalanceAtLatestBlock_Call{Call: _e.mock.On("GetAccountBalanceAtLatestBlock", ctx, address)} +} + +func (_c *API_GetAccountBalanceAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *API_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetAccountBalanceAtLatestBlock_Call) Return(v uint64, err error) *API_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *API_GetAccountBalanceAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (uint64, error)) *API_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtBlockHeight provides a mock function for the type API +func (_mock *API) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, keyIndex, height) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtBlockHeight") @@ -266,29 +633,79 @@ func (_m *API) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.Addr var r0 *flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountPublicKey, error)); ok { - return rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, keyIndex, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountPublicKey); ok { - r0 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, keyIndex, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { - r1 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { + r1 = returnFunc(ctx, address, keyIndex, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtLatestBlock provides a mock function with given fields: ctx, address, keyIndex -func (_m *API) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, keyIndex) +// API_GetAccountKeyAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtBlockHeight' +type API_GetAccountKeyAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeyAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - keyIndex uint32 +// - height uint64 +func (_e *API_Expecter) GetAccountKeyAtBlockHeight(ctx interface{}, address interface{}, keyIndex interface{}, height interface{}) *API_GetAccountKeyAtBlockHeight_Call { + return &API_GetAccountKeyAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeyAtBlockHeight", ctx, address, keyIndex, height)} +} + +func (_c *API_GetAccountKeyAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64)) *API_GetAccountKeyAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_GetAccountKeyAtBlockHeight_Call) Return(accountPublicKey *flow.AccountPublicKey, err error) *API_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(accountPublicKey, err) + return _c +} + +func (_c *API_GetAccountKeyAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error)) *API_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtLatestBlock provides a mock function for the type API +func (_mock *API) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, keyIndex) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtLatestBlock") @@ -296,29 +713,73 @@ func (_m *API) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.Addr var r0 *flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) (*flow.AccountPublicKey, error)); ok { - return rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) (*flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, keyIndex) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) *flow.AccountPublicKey); ok { - r0 = rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) *flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, keyIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32) error); ok { - r1 = rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32) error); ok { + r1 = returnFunc(ctx, address, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *API) GetAccountKeysAtBlockHeight(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, height) +// API_GetAccountKeyAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtLatestBlock' +type API_GetAccountKeyAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeyAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - keyIndex uint32 +func (_e *API_Expecter) GetAccountKeyAtLatestBlock(ctx interface{}, address interface{}, keyIndex interface{}) *API_GetAccountKeyAtLatestBlock_Call { + return &API_GetAccountKeyAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeyAtLatestBlock", ctx, address, keyIndex)} +} + +func (_c *API_GetAccountKeyAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address, keyIndex uint32)) *API_GetAccountKeyAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_GetAccountKeyAtLatestBlock_Call) Return(accountPublicKey *flow.AccountPublicKey, err error) *API_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(accountPublicKey, err) + return _c +} + +func (_c *API_GetAccountKeyAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountPublicKey, error)) *API_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtBlockHeight provides a mock function for the type API +func (_mock *API) GetAccountKeysAtBlockHeight(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtBlockHeight") @@ -326,29 +787,73 @@ func (_m *API) GetAccountKeysAtBlockHeight(ctx context.Context, address flow.Add var r0 []flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]flow.AccountPublicKey, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []flow.AccountPublicKey); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *API) GetAccountKeysAtLatestBlock(ctx context.Context, address flow.Address) ([]flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address) +// API_GetAccountKeysAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtBlockHeight' +type API_GetAccountKeysAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeysAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *API_Expecter) GetAccountKeysAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *API_GetAccountKeysAtBlockHeight_Call { + return &API_GetAccountKeysAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeysAtBlockHeight", ctx, address, height)} +} + +func (_c *API_GetAccountKeysAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *API_GetAccountKeysAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_GetAccountKeysAtBlockHeight_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *API_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *API_GetAccountKeysAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error)) *API_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtLatestBlock provides a mock function for the type API +func (_mock *API) GetAccountKeysAtLatestBlock(ctx context.Context, address flow.Address) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtLatestBlock") @@ -356,29 +861,67 @@ func (_m *API) GetAccountKeysAtLatestBlock(ctx context.Context, address flow.Add var r0 []flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) ([]flow.AccountPublicKey, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) []flow.AccountPublicKey); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) []flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockByHeight provides a mock function with given fields: ctx, height -func (_m *API) GetBlockByHeight(ctx context.Context, height uint64) (*flow.Block, flow.BlockStatus, error) { - ret := _m.Called(ctx, height) +// API_GetAccountKeysAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtLatestBlock' +type API_GetAccountKeysAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeysAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *API_Expecter) GetAccountKeysAtLatestBlock(ctx interface{}, address interface{}) *API_GetAccountKeysAtLatestBlock_Call { + return &API_GetAccountKeysAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeysAtLatestBlock", ctx, address)} +} + +func (_c *API_GetAccountKeysAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *API_GetAccountKeysAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetAccountKeysAtLatestBlock_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *API_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *API_GetAccountKeysAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) ([]flow.AccountPublicKey, error)) *API_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByHeight provides a mock function for the type API +func (_mock *API) GetBlockByHeight(ctx context.Context, height uint64) (*flow.Block, flow.BlockStatus, error) { + ret := _mock.Called(ctx, height) if len(ret) == 0 { panic("no return value specified for GetBlockByHeight") @@ -387,35 +930,72 @@ func (_m *API) GetBlockByHeight(ctx context.Context, height uint64) (*flow.Block var r0 *flow.Block var r1 flow.BlockStatus var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Block, flow.BlockStatus, error)); ok { - return rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Block, flow.BlockStatus, error)); ok { + return returnFunc(ctx, height) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.Block); ok { - r0 = rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.Block); ok { + r0 = returnFunc(ctx, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) flow.BlockStatus); ok { - r1 = rf(ctx, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) flow.BlockStatus); ok { + r1 = returnFunc(ctx, height) } else { r1 = ret.Get(1).(flow.BlockStatus) } - - if rf, ok := ret.Get(2).(func(context.Context, uint64) error); ok { - r2 = rf(ctx, height) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64) error); ok { + r2 = returnFunc(ctx, height) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetBlockByID provides a mock function with given fields: ctx, id -func (_m *API) GetBlockByID(ctx context.Context, id flow.Identifier) (*flow.Block, flow.BlockStatus, error) { - ret := _m.Called(ctx, id) +// API_GetBlockByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByHeight' +type API_GetBlockByHeight_Call struct { + *mock.Call +} + +// GetBlockByHeight is a helper method to define mock.On call +// - ctx context.Context +// - height uint64 +func (_e *API_Expecter) GetBlockByHeight(ctx interface{}, height interface{}) *API_GetBlockByHeight_Call { + return &API_GetBlockByHeight_Call{Call: _e.mock.On("GetBlockByHeight", ctx, height)} +} + +func (_c *API_GetBlockByHeight_Call) Run(run func(ctx context.Context, height uint64)) *API_GetBlockByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetBlockByHeight_Call) Return(v *flow.Block, blockStatus flow.BlockStatus, err error) *API_GetBlockByHeight_Call { + _c.Call.Return(v, blockStatus, err) + return _c +} + +func (_c *API_GetBlockByHeight_Call) RunAndReturn(run func(ctx context.Context, height uint64) (*flow.Block, flow.BlockStatus, error)) *API_GetBlockByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByID provides a mock function for the type API +func (_mock *API) GetBlockByID(ctx context.Context, id flow.Identifier) (*flow.Block, flow.BlockStatus, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetBlockByID") @@ -424,35 +1004,72 @@ func (_m *API) GetBlockByID(ctx context.Context, id flow.Identifier) (*flow.Bloc var r0 *flow.Block var r1 flow.BlockStatus var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Block, flow.BlockStatus, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Block, flow.BlockStatus, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Block); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Block); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) flow.BlockStatus); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) flow.BlockStatus); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Get(1).(flow.BlockStatus) } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier) error); ok { - r2 = rf(ctx, id) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier) error); ok { + r2 = returnFunc(ctx, id) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetBlockHeaderByHeight provides a mock function with given fields: ctx, height -func (_m *API) GetBlockHeaderByHeight(ctx context.Context, height uint64) (*flow.Header, flow.BlockStatus, error) { - ret := _m.Called(ctx, height) +// API_GetBlockByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByID' +type API_GetBlockByID_Call struct { + *mock.Call +} + +// GetBlockByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *API_Expecter) GetBlockByID(ctx interface{}, id interface{}) *API_GetBlockByID_Call { + return &API_GetBlockByID_Call{Call: _e.mock.On("GetBlockByID", ctx, id)} +} + +func (_c *API_GetBlockByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *API_GetBlockByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetBlockByID_Call) Return(v *flow.Block, blockStatus flow.BlockStatus, err error) *API_GetBlockByID_Call { + _c.Call.Return(v, blockStatus, err) + return _c +} + +func (_c *API_GetBlockByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.Block, flow.BlockStatus, error)) *API_GetBlockByID_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByHeight provides a mock function for the type API +func (_mock *API) GetBlockHeaderByHeight(ctx context.Context, height uint64) (*flow.Header, flow.BlockStatus, error) { + ret := _mock.Called(ctx, height) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByHeight") @@ -461,35 +1078,72 @@ func (_m *API) GetBlockHeaderByHeight(ctx context.Context, height uint64) (*flow var r0 *flow.Header var r1 flow.BlockStatus var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Header, flow.BlockStatus, error)); ok { - return rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Header, flow.BlockStatus, error)); ok { + return returnFunc(ctx, height) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.Header); ok { - r0 = rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.Header); ok { + r0 = returnFunc(ctx, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) flow.BlockStatus); ok { - r1 = rf(ctx, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) flow.BlockStatus); ok { + r1 = returnFunc(ctx, height) } else { r1 = ret.Get(1).(flow.BlockStatus) } - - if rf, ok := ret.Get(2).(func(context.Context, uint64) error); ok { - r2 = rf(ctx, height) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64) error); ok { + r2 = returnFunc(ctx, height) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetBlockHeaderByID provides a mock function with given fields: ctx, id -func (_m *API) GetBlockHeaderByID(ctx context.Context, id flow.Identifier) (*flow.Header, flow.BlockStatus, error) { - ret := _m.Called(ctx, id) +// API_GetBlockHeaderByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByHeight' +type API_GetBlockHeaderByHeight_Call struct { + *mock.Call +} + +// GetBlockHeaderByHeight is a helper method to define mock.On call +// - ctx context.Context +// - height uint64 +func (_e *API_Expecter) GetBlockHeaderByHeight(ctx interface{}, height interface{}) *API_GetBlockHeaderByHeight_Call { + return &API_GetBlockHeaderByHeight_Call{Call: _e.mock.On("GetBlockHeaderByHeight", ctx, height)} +} + +func (_c *API_GetBlockHeaderByHeight_Call) Run(run func(ctx context.Context, height uint64)) *API_GetBlockHeaderByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetBlockHeaderByHeight_Call) Return(header *flow.Header, blockStatus flow.BlockStatus, err error) *API_GetBlockHeaderByHeight_Call { + _c.Call.Return(header, blockStatus, err) + return _c +} + +func (_c *API_GetBlockHeaderByHeight_Call) RunAndReturn(run func(ctx context.Context, height uint64) (*flow.Header, flow.BlockStatus, error)) *API_GetBlockHeaderByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByID provides a mock function for the type API +func (_mock *API) GetBlockHeaderByID(ctx context.Context, id flow.Identifier) (*flow.Header, flow.BlockStatus, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByID") @@ -498,65 +1152,140 @@ func (_m *API) GetBlockHeaderByID(ctx context.Context, id flow.Identifier) (*flo var r0 *flow.Header var r1 flow.BlockStatus var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Header, flow.BlockStatus, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Header, flow.BlockStatus, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Header); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Header); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) flow.BlockStatus); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) flow.BlockStatus); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Get(1).(flow.BlockStatus) } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier) error); ok { - r2 = rf(ctx, id) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier) error); ok { + r2 = returnFunc(ctx, id) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetCollectionByID provides a mock function with given fields: ctx, id -func (_m *API) GetCollectionByID(ctx context.Context, id flow.Identifier) (*flow.LightCollection, error) { - ret := _m.Called(ctx, id) +// API_GetBlockHeaderByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByID' +type API_GetBlockHeaderByID_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetCollectionByID") - } +// GetBlockHeaderByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *API_Expecter) GetBlockHeaderByID(ctx interface{}, id interface{}) *API_GetBlockHeaderByID_Call { + return &API_GetBlockHeaderByID_Call{Call: _e.mock.On("GetBlockHeaderByID", ctx, id)} +} - var r0 *flow.LightCollection - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.LightCollection, error)); ok { - return rf(ctx, id) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.LightCollection); ok { - r0 = rf(ctx, id) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.LightCollection) +func (_c *API_GetBlockHeaderByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *API_GetBlockHeaderByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetBlockHeaderByID_Call) Return(header *flow.Header, blockStatus flow.BlockStatus, err error) *API_GetBlockHeaderByID_Call { + _c.Call.Return(header, blockStatus, err) + return _c +} + +func (_c *API_GetBlockHeaderByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.Header, flow.BlockStatus, error)) *API_GetBlockHeaderByID_Call { + _c.Call.Return(run) + return _c +} + +// GetCollectionByID provides a mock function for the type API +func (_mock *API) GetCollectionByID(ctx context.Context, id flow.Identifier) (*flow.LightCollection, error) { + ret := _mock.Called(ctx, id) + + if len(ret) == 0 { + panic("no return value specified for GetCollectionByID") } - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + var r0 *flow.LightCollection + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.LightCollection, error)); ok { + return returnFunc(ctx, id) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.LightCollection); ok { + r0 = returnFunc(ctx, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*flow.LightCollection) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForBlockIDs provides a mock function with given fields: ctx, eventType, blockIDs, requiredEventEncodingVersion -func (_m *API) GetEventsForBlockIDs(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { - ret := _m.Called(ctx, eventType, blockIDs, requiredEventEncodingVersion) +// API_GetCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCollectionByID' +type API_GetCollectionByID_Call struct { + *mock.Call +} + +// GetCollectionByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *API_Expecter) GetCollectionByID(ctx interface{}, id interface{}) *API_GetCollectionByID_Call { + return &API_GetCollectionByID_Call{Call: _e.mock.On("GetCollectionByID", ctx, id)} +} + +func (_c *API_GetCollectionByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *API_GetCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetCollectionByID_Call) Return(lightCollection *flow.LightCollection, err error) *API_GetCollectionByID_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *API_GetCollectionByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.LightCollection, error)) *API_GetCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForBlockIDs provides a mock function for the type API +func (_mock *API) GetEventsForBlockIDs(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { + ret := _mock.Called(ctx, eventType, blockIDs, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for GetEventsForBlockIDs") @@ -564,29 +1293,79 @@ func (_m *API) GetEventsForBlockIDs(ctx context.Context, eventType string, block var r0 []flow.BlockEvents var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { - return rf(ctx, eventType, blockIDs, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { + return returnFunc(ctx, eventType, blockIDs, requiredEventEncodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) []flow.BlockEvents); ok { - r0 = rf(ctx, eventType, blockIDs, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) []flow.BlockEvents); ok { + r0 = returnFunc(ctx, eventType, blockIDs, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.BlockEvents) } } - - if rf, ok := ret.Get(1).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, eventType, blockIDs, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, eventType, blockIDs, requiredEventEncodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForHeightRange provides a mock function with given fields: ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion -func (_m *API) GetEventsForHeightRange(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { - ret := _m.Called(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) +// API_GetEventsForBlockIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForBlockIDs' +type API_GetEventsForBlockIDs_Call struct { + *mock.Call +} + +// GetEventsForBlockIDs is a helper method to define mock.On call +// - ctx context.Context +// - eventType string +// - blockIDs []flow.Identifier +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetEventsForBlockIDs(ctx interface{}, eventType interface{}, blockIDs interface{}, requiredEventEncodingVersion interface{}) *API_GetEventsForBlockIDs_Call { + return &API_GetEventsForBlockIDs_Call{Call: _e.mock.On("GetEventsForBlockIDs", ctx, eventType, blockIDs, requiredEventEncodingVersion)} +} + +func (_c *API_GetEventsForBlockIDs_Call) Run(run func(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion)) *API_GetEventsForBlockIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 []flow.Identifier + if args[2] != nil { + arg2 = args[2].([]flow.Identifier) + } + var arg3 entities.EventEncodingVersion + if args[3] != nil { + arg3 = args[3].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_GetEventsForBlockIDs_Call) Return(blockEventss []flow.BlockEvents, err error) *API_GetEventsForBlockIDs_Call { + _c.Call.Return(blockEventss, err) + return _c +} + +func (_c *API_GetEventsForBlockIDs_Call) RunAndReturn(run func(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error)) *API_GetEventsForBlockIDs_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForHeightRange provides a mock function for the type API +func (_mock *API) GetEventsForHeightRange(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { + ret := _mock.Called(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for GetEventsForHeightRange") @@ -594,29 +1373,221 @@ func (_m *API) GetEventsForHeightRange(ctx context.Context, eventType string, st var r0 []flow.BlockEvents var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { - return rf(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { + return returnFunc(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) []flow.BlockEvents); ok { - r0 = rf(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) []flow.BlockEvents); ok { + r0 = returnFunc(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.BlockEvents) } } + if returnFunc, ok := ret.Get(1).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetEventsForHeightRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForHeightRange' +type API_GetEventsForHeightRange_Call struct { + *mock.Call +} + +// GetEventsForHeightRange is a helper method to define mock.On call +// - ctx context.Context +// - eventType string +// - startHeight uint64 +// - endHeight uint64 +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetEventsForHeightRange(ctx interface{}, eventType interface{}, startHeight interface{}, endHeight interface{}, requiredEventEncodingVersion interface{}) *API_GetEventsForHeightRange_Call { + return &API_GetEventsForHeightRange_Call{Call: _e.mock.On("GetEventsForHeightRange", ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion)} +} - if rf, ok := ret.Get(1).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) +func (_c *API_GetEventsForHeightRange_Call) Run(run func(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion)) *API_GetEventsForHeightRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + var arg4 entities.EventEncodingVersion + if args[4] != nil { + arg4 = args[4].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *API_GetEventsForHeightRange_Call) Return(blockEventss []flow.BlockEvents, err error) *API_GetEventsForHeightRange_Call { + _c.Call.Return(blockEventss, err) + return _c +} + +func (_c *API_GetEventsForHeightRange_Call) RunAndReturn(run func(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error)) *API_GetEventsForHeightRange_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionReceiptsByBlockID provides a mock function for the type API +func (_mock *API) GetExecutionReceiptsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + ret := _mock.Called(ctx, blockID) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByBlockID") + } + + var r0 []*flow.ExecutionReceipt + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.ExecutionReceipt, error)); ok { + return returnFunc(ctx, blockID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.ExecutionReceipt); ok { + r0 = returnFunc(ctx, blockID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*flow.ExecutionReceipt) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } + return r0, r1 +} + +// API_GetExecutionReceiptsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByBlockID' +type API_GetExecutionReceiptsByBlockID_Call struct { + *mock.Call +} + +// GetExecutionReceiptsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *API_Expecter) GetExecutionReceiptsByBlockID(ctx interface{}, blockID interface{}) *API_GetExecutionReceiptsByBlockID_Call { + return &API_GetExecutionReceiptsByBlockID_Call{Call: _e.mock.On("GetExecutionReceiptsByBlockID", ctx, blockID)} +} +func (_c *API_GetExecutionReceiptsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *API_GetExecutionReceiptsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetExecutionReceiptsByBlockID_Call) Return(executionReceipts []*flow.ExecutionReceipt, err error) *API_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(executionReceipts, err) + return _c +} + +func (_c *API_GetExecutionReceiptsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]*flow.ExecutionReceipt, error)) *API_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionReceiptsByResultID provides a mock function for the type API +func (_mock *API) GetExecutionReceiptsByResultID(ctx context.Context, resultID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + ret := _mock.Called(ctx, resultID) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByResultID") + } + + var r0 []*flow.ExecutionReceipt + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.ExecutionReceipt, error)); ok { + return returnFunc(ctx, resultID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.ExecutionReceipt); ok { + r0 = returnFunc(ctx, resultID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*flow.ExecutionReceipt) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, resultID) + } else { + r1 = ret.Error(1) + } return r0, r1 } -// GetExecutionResultByID provides a mock function with given fields: ctx, id -func (_m *API) GetExecutionResultByID(ctx context.Context, id flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(ctx, id) +// API_GetExecutionReceiptsByResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByResultID' +type API_GetExecutionReceiptsByResultID_Call struct { + *mock.Call +} + +// GetExecutionReceiptsByResultID is a helper method to define mock.On call +// - ctx context.Context +// - resultID flow.Identifier +func (_e *API_Expecter) GetExecutionReceiptsByResultID(ctx interface{}, resultID interface{}) *API_GetExecutionReceiptsByResultID_Call { + return &API_GetExecutionReceiptsByResultID_Call{Call: _e.mock.On("GetExecutionReceiptsByResultID", ctx, resultID)} +} + +func (_c *API_GetExecutionReceiptsByResultID_Call) Run(run func(ctx context.Context, resultID flow.Identifier)) *API_GetExecutionReceiptsByResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetExecutionReceiptsByResultID_Call) Return(executionReceipts []*flow.ExecutionReceipt, err error) *API_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(executionReceipts, err) + return _c +} + +func (_c *API_GetExecutionReceiptsByResultID_Call) RunAndReturn(run func(ctx context.Context, resultID flow.Identifier) ([]*flow.ExecutionReceipt, error)) *API_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultByID provides a mock function for the type API +func (_mock *API) GetExecutionResultByID(ctx context.Context, id flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetExecutionResultByID") @@ -624,29 +1595,67 @@ func (_m *API) GetExecutionResultByID(ctx context.Context, id flow.Identifier) ( var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionResultForBlockID provides a mock function with given fields: ctx, blockID -func (_m *API) GetExecutionResultForBlockID(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(ctx, blockID) +// API_GetExecutionResultByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultByID' +type API_GetExecutionResultByID_Call struct { + *mock.Call +} + +// GetExecutionResultByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *API_Expecter) GetExecutionResultByID(ctx interface{}, id interface{}) *API_GetExecutionResultByID_Call { + return &API_GetExecutionResultByID_Call{Call: _e.mock.On("GetExecutionResultByID", ctx, id)} +} + +func (_c *API_GetExecutionResultByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *API_GetExecutionResultByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetExecutionResultByID_Call) Return(executionResult *flow.ExecutionResult, err error) *API_GetExecutionResultByID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *API_GetExecutionResultByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.ExecutionResult, error)) *API_GetExecutionResultByID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultForBlockID provides a mock function for the type API +func (_mock *API) GetExecutionResultForBlockID(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetExecutionResultForBlockID") @@ -654,29 +1663,67 @@ func (_m *API) GetExecutionResultForBlockID(ctx context.Context, blockID flow.Id var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetFullCollectionByID provides a mock function with given fields: ctx, id -func (_m *API) GetFullCollectionByID(ctx context.Context, id flow.Identifier) (*flow.Collection, error) { - ret := _m.Called(ctx, id) +// API_GetExecutionResultForBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultForBlockID' +type API_GetExecutionResultForBlockID_Call struct { + *mock.Call +} + +// GetExecutionResultForBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *API_Expecter) GetExecutionResultForBlockID(ctx interface{}, blockID interface{}) *API_GetExecutionResultForBlockID_Call { + return &API_GetExecutionResultForBlockID_Call{Call: _e.mock.On("GetExecutionResultForBlockID", ctx, blockID)} +} + +func (_c *API_GetExecutionResultForBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *API_GetExecutionResultForBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetExecutionResultForBlockID_Call) Return(executionResult *flow.ExecutionResult, err error) *API_GetExecutionResultForBlockID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *API_GetExecutionResultForBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionResult, error)) *API_GetExecutionResultForBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetFullCollectionByID provides a mock function for the type API +func (_mock *API) GetFullCollectionByID(ctx context.Context, id flow.Identifier) (*flow.Collection, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetFullCollectionByID") @@ -684,29 +1731,67 @@ func (_m *API) GetFullCollectionByID(ctx context.Context, id flow.Identifier) (* var r0 *flow.Collection var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Collection, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Collection, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Collection); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Collection); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Collection) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlock provides a mock function with given fields: ctx, isSealed -func (_m *API) GetLatestBlock(ctx context.Context, isSealed bool) (*flow.Block, flow.BlockStatus, error) { - ret := _m.Called(ctx, isSealed) +// API_GetFullCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFullCollectionByID' +type API_GetFullCollectionByID_Call struct { + *mock.Call +} + +// GetFullCollectionByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *API_Expecter) GetFullCollectionByID(ctx interface{}, id interface{}) *API_GetFullCollectionByID_Call { + return &API_GetFullCollectionByID_Call{Call: _e.mock.On("GetFullCollectionByID", ctx, id)} +} + +func (_c *API_GetFullCollectionByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *API_GetFullCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetFullCollectionByID_Call) Return(collection *flow.Collection, err error) *API_GetFullCollectionByID_Call { + _c.Call.Return(collection, err) + return _c +} + +func (_c *API_GetFullCollectionByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.Collection, error)) *API_GetFullCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlock provides a mock function for the type API +func (_mock *API) GetLatestBlock(ctx context.Context, isSealed bool) (*flow.Block, flow.BlockStatus, error) { + ret := _mock.Called(ctx, isSealed) if len(ret) == 0 { panic("no return value specified for GetLatestBlock") @@ -715,35 +1800,72 @@ func (_m *API) GetLatestBlock(ctx context.Context, isSealed bool) (*flow.Block, var r0 *flow.Block var r1 flow.BlockStatus var r2 error - if rf, ok := ret.Get(0).(func(context.Context, bool) (*flow.Block, flow.BlockStatus, error)); ok { - return rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) (*flow.Block, flow.BlockStatus, error)); ok { + return returnFunc(ctx, isSealed) } - if rf, ok := ret.Get(0).(func(context.Context, bool) *flow.Block); ok { - r0 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) *flow.Block); ok { + r0 = returnFunc(ctx, isSealed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, bool) flow.BlockStatus); ok { - r1 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(1).(func(context.Context, bool) flow.BlockStatus); ok { + r1 = returnFunc(ctx, isSealed) } else { r1 = ret.Get(1).(flow.BlockStatus) } - - if rf, ok := ret.Get(2).(func(context.Context, bool) error); ok { - r2 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(2).(func(context.Context, bool) error); ok { + r2 = returnFunc(ctx, isSealed) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetLatestBlockHeader provides a mock function with given fields: ctx, isSealed -func (_m *API) GetLatestBlockHeader(ctx context.Context, isSealed bool) (*flow.Header, flow.BlockStatus, error) { - ret := _m.Called(ctx, isSealed) +// API_GetLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlock' +type API_GetLatestBlock_Call struct { + *mock.Call +} + +// GetLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - isSealed bool +func (_e *API_Expecter) GetLatestBlock(ctx interface{}, isSealed interface{}) *API_GetLatestBlock_Call { + return &API_GetLatestBlock_Call{Call: _e.mock.On("GetLatestBlock", ctx, isSealed)} +} + +func (_c *API_GetLatestBlock_Call) Run(run func(ctx context.Context, isSealed bool)) *API_GetLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetLatestBlock_Call) Return(v *flow.Block, blockStatus flow.BlockStatus, err error) *API_GetLatestBlock_Call { + _c.Call.Return(v, blockStatus, err) + return _c +} + +func (_c *API_GetLatestBlock_Call) RunAndReturn(run func(ctx context.Context, isSealed bool) (*flow.Block, flow.BlockStatus, error)) *API_GetLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlockHeader provides a mock function for the type API +func (_mock *API) GetLatestBlockHeader(ctx context.Context, isSealed bool) (*flow.Header, flow.BlockStatus, error) { + ret := _mock.Called(ctx, isSealed) if len(ret) == 0 { panic("no return value specified for GetLatestBlockHeader") @@ -752,35 +1874,72 @@ func (_m *API) GetLatestBlockHeader(ctx context.Context, isSealed bool) (*flow.H var r0 *flow.Header var r1 flow.BlockStatus var r2 error - if rf, ok := ret.Get(0).(func(context.Context, bool) (*flow.Header, flow.BlockStatus, error)); ok { - return rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) (*flow.Header, flow.BlockStatus, error)); ok { + return returnFunc(ctx, isSealed) } - if rf, ok := ret.Get(0).(func(context.Context, bool) *flow.Header); ok { - r0 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) *flow.Header); ok { + r0 = returnFunc(ctx, isSealed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(context.Context, bool) flow.BlockStatus); ok { - r1 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(1).(func(context.Context, bool) flow.BlockStatus); ok { + r1 = returnFunc(ctx, isSealed) } else { r1 = ret.Get(1).(flow.BlockStatus) } - - if rf, ok := ret.Get(2).(func(context.Context, bool) error); ok { - r2 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(2).(func(context.Context, bool) error); ok { + r2 = returnFunc(ctx, isSealed) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetLatestProtocolStateSnapshot provides a mock function with given fields: ctx -func (_m *API) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, error) { - ret := _m.Called(ctx) +// API_GetLatestBlockHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlockHeader' +type API_GetLatestBlockHeader_Call struct { + *mock.Call +} + +// GetLatestBlockHeader is a helper method to define mock.On call +// - ctx context.Context +// - isSealed bool +func (_e *API_Expecter) GetLatestBlockHeader(ctx interface{}, isSealed interface{}) *API_GetLatestBlockHeader_Call { + return &API_GetLatestBlockHeader_Call{Call: _e.mock.On("GetLatestBlockHeader", ctx, isSealed)} +} + +func (_c *API_GetLatestBlockHeader_Call) Run(run func(ctx context.Context, isSealed bool)) *API_GetLatestBlockHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetLatestBlockHeader_Call) Return(header *flow.Header, blockStatus flow.BlockStatus, err error) *API_GetLatestBlockHeader_Call { + _c.Call.Return(header, blockStatus, err) + return _c +} + +func (_c *API_GetLatestBlockHeader_Call) RunAndReturn(run func(ctx context.Context, isSealed bool) (*flow.Header, flow.BlockStatus, error)) *API_GetLatestBlockHeader_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestProtocolStateSnapshot provides a mock function for the type API +func (_mock *API) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for GetLatestProtocolStateSnapshot") @@ -788,77 +1947,174 @@ func (_m *API) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, erro var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context) ([]byte, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) ([]byte, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) []byte); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) []byte); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetNetworkParameters provides a mock function with given fields: ctx -func (_m *API) GetNetworkParameters(ctx context.Context) modelaccess.NetworkParameters { - ret := _m.Called(ctx) +// API_GetLatestProtocolStateSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestProtocolStateSnapshot' +type API_GetLatestProtocolStateSnapshot_Call struct { + *mock.Call +} + +// GetLatestProtocolStateSnapshot is a helper method to define mock.On call +// - ctx context.Context +func (_e *API_Expecter) GetLatestProtocolStateSnapshot(ctx interface{}) *API_GetLatestProtocolStateSnapshot_Call { + return &API_GetLatestProtocolStateSnapshot_Call{Call: _e.mock.On("GetLatestProtocolStateSnapshot", ctx)} +} + +func (_c *API_GetLatestProtocolStateSnapshot_Call) Run(run func(ctx context.Context)) *API_GetLatestProtocolStateSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *API_GetLatestProtocolStateSnapshot_Call) Return(bytes []byte, err error) *API_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *API_GetLatestProtocolStateSnapshot_Call) RunAndReturn(run func(ctx context.Context) ([]byte, error)) *API_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// GetNetworkParameters provides a mock function for the type API +func (_mock *API) GetNetworkParameters(ctx context.Context) access.NetworkParameters { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for GetNetworkParameters") } - var r0 modelaccess.NetworkParameters - if rf, ok := ret.Get(0).(func(context.Context) modelaccess.NetworkParameters); ok { - r0 = rf(ctx) + var r0 access.NetworkParameters + if returnFunc, ok := ret.Get(0).(func(context.Context) access.NetworkParameters); ok { + r0 = returnFunc(ctx) } else { - r0 = ret.Get(0).(modelaccess.NetworkParameters) + r0 = ret.Get(0).(access.NetworkParameters) } - return r0 } -// GetNodeVersionInfo provides a mock function with given fields: ctx -func (_m *API) GetNodeVersionInfo(ctx context.Context) (*modelaccess.NodeVersionInfo, error) { - ret := _m.Called(ctx) +// API_GetNetworkParameters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNetworkParameters' +type API_GetNetworkParameters_Call struct { + *mock.Call +} + +// GetNetworkParameters is a helper method to define mock.On call +// - ctx context.Context +func (_e *API_Expecter) GetNetworkParameters(ctx interface{}) *API_GetNetworkParameters_Call { + return &API_GetNetworkParameters_Call{Call: _e.mock.On("GetNetworkParameters", ctx)} +} + +func (_c *API_GetNetworkParameters_Call) Run(run func(ctx context.Context)) *API_GetNetworkParameters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *API_GetNetworkParameters_Call) Return(networkParameters access.NetworkParameters) *API_GetNetworkParameters_Call { + _c.Call.Return(networkParameters) + return _c +} + +func (_c *API_GetNetworkParameters_Call) RunAndReturn(run func(ctx context.Context) access.NetworkParameters) *API_GetNetworkParameters_Call { + _c.Call.Return(run) + return _c +} + +// GetNodeVersionInfo provides a mock function for the type API +func (_mock *API) GetNodeVersionInfo(ctx context.Context) (*access.NodeVersionInfo, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for GetNodeVersionInfo") } - var r0 *modelaccess.NodeVersionInfo + var r0 *access.NodeVersionInfo var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*modelaccess.NodeVersionInfo, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) (*access.NodeVersionInfo, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) *modelaccess.NodeVersionInfo); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) *access.NodeVersionInfo); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.NodeVersionInfo) + r0 = ret.Get(0).(*access.NodeVersionInfo) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByBlockID provides a mock function with given fields: ctx, blockID -func (_m *API) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID flow.Identifier) ([]byte, error) { - ret := _m.Called(ctx, blockID) +// API_GetNodeVersionInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNodeVersionInfo' +type API_GetNodeVersionInfo_Call struct { + *mock.Call +} + +// GetNodeVersionInfo is a helper method to define mock.On call +// - ctx context.Context +func (_e *API_Expecter) GetNodeVersionInfo(ctx interface{}) *API_GetNodeVersionInfo_Call { + return &API_GetNodeVersionInfo_Call{Call: _e.mock.On("GetNodeVersionInfo", ctx)} +} + +func (_c *API_GetNodeVersionInfo_Call) Run(run func(ctx context.Context)) *API_GetNodeVersionInfo_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *API_GetNodeVersionInfo_Call) Return(nodeVersionInfo *access.NodeVersionInfo, err error) *API_GetNodeVersionInfo_Call { + _c.Call.Return(nodeVersionInfo, err) + return _c +} + +func (_c *API_GetNodeVersionInfo_Call) RunAndReturn(run func(ctx context.Context) (*access.NodeVersionInfo, error)) *API_GetNodeVersionInfo_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByBlockID provides a mock function for the type API +func (_mock *API) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID flow.Identifier) ([]byte, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByBlockID") @@ -866,29 +2122,67 @@ func (_m *API) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID fl var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]byte, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]byte, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []byte); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []byte); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByHeight provides a mock function with given fields: ctx, blockHeight -func (_m *API) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHeight uint64) ([]byte, error) { - ret := _m.Called(ctx, blockHeight) +// API_GetProtocolStateSnapshotByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByBlockID' +type API_GetProtocolStateSnapshotByBlockID_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *API_Expecter) GetProtocolStateSnapshotByBlockID(ctx interface{}, blockID interface{}) *API_GetProtocolStateSnapshotByBlockID_Call { + return &API_GetProtocolStateSnapshotByBlockID_Call{Call: _e.mock.On("GetProtocolStateSnapshotByBlockID", ctx, blockID)} +} + +func (_c *API_GetProtocolStateSnapshotByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *API_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetProtocolStateSnapshotByBlockID_Call) Return(bytes []byte, err error) *API_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *API_GetProtocolStateSnapshotByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]byte, error)) *API_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByHeight provides a mock function for the type API +func (_mock *API) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHeight uint64) ([]byte, error) { + ret := _mock.Called(ctx, blockHeight) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByHeight") @@ -896,29 +2190,67 @@ func (_m *API) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHeight var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) ([]byte, error)); ok { - return rf(ctx, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) ([]byte, error)); ok { + return returnFunc(ctx, blockHeight) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) []byte); ok { - r0 = rf(ctx, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) []byte); ok { + r0 = returnFunc(ctx, blockHeight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, blockHeight) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, blockHeight) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetScheduledTransaction provides a mock function with given fields: ctx, scheduledTxID -func (_m *API) GetScheduledTransaction(ctx context.Context, scheduledTxID uint64) (*flow.TransactionBody, error) { - ret := _m.Called(ctx, scheduledTxID) +// API_GetProtocolStateSnapshotByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByHeight' +type API_GetProtocolStateSnapshotByHeight_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByHeight is a helper method to define mock.On call +// - ctx context.Context +// - blockHeight uint64 +func (_e *API_Expecter) GetProtocolStateSnapshotByHeight(ctx interface{}, blockHeight interface{}) *API_GetProtocolStateSnapshotByHeight_Call { + return &API_GetProtocolStateSnapshotByHeight_Call{Call: _e.mock.On("GetProtocolStateSnapshotByHeight", ctx, blockHeight)} +} + +func (_c *API_GetProtocolStateSnapshotByHeight_Call) Run(run func(ctx context.Context, blockHeight uint64)) *API_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetProtocolStateSnapshotByHeight_Call) Return(bytes []byte, err error) *API_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *API_GetProtocolStateSnapshotByHeight_Call) RunAndReturn(run func(ctx context.Context, blockHeight uint64) ([]byte, error)) *API_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransaction provides a mock function for the type API +func (_mock *API) GetScheduledTransaction(ctx context.Context, scheduledTxID uint64) (*flow.TransactionBody, error) { + ret := _mock.Called(ctx, scheduledTxID) if len(ret) == 0 { panic("no return value specified for GetScheduledTransaction") @@ -926,59 +2258,141 @@ func (_m *API) GetScheduledTransaction(ctx context.Context, scheduledTxID uint64 var r0 *flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.TransactionBody, error)); ok { - return rf(ctx, scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.TransactionBody, error)); ok { + return returnFunc(ctx, scheduledTxID) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.TransactionBody); ok { - r0 = rf(ctx, scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.TransactionBody); ok { + r0 = returnFunc(ctx, scheduledTxID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, scheduledTxID) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, scheduledTxID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetScheduledTransactionResult provides a mock function with given fields: ctx, scheduledTxID, encodingVersion -func (_m *API) GetScheduledTransactionResult(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, scheduledTxID, encodingVersion) +// API_GetScheduledTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransaction' +type API_GetScheduledTransaction_Call struct { + *mock.Call +} + +// GetScheduledTransaction is a helper method to define mock.On call +// - ctx context.Context +// - scheduledTxID uint64 +func (_e *API_Expecter) GetScheduledTransaction(ctx interface{}, scheduledTxID interface{}) *API_GetScheduledTransaction_Call { + return &API_GetScheduledTransaction_Call{Call: _e.mock.On("GetScheduledTransaction", ctx, scheduledTxID)} +} + +func (_c *API_GetScheduledTransaction_Call) Run(run func(ctx context.Context, scheduledTxID uint64)) *API_GetScheduledTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetScheduledTransaction_Call) Return(transactionBody *flow.TransactionBody, err error) *API_GetScheduledTransaction_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *API_GetScheduledTransaction_Call) RunAndReturn(run func(ctx context.Context, scheduledTxID uint64) (*flow.TransactionBody, error)) *API_GetScheduledTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransactionResult provides a mock function for the type API +func (_mock *API) GetScheduledTransactionResult(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, scheduledTxID, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetScheduledTransactionResult") } - var r0 *modelaccess.TransactionResult + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, scheduledTxID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, scheduledTxID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, scheduledTxID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, scheduledTxID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) + r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, scheduledTxID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, scheduledTxID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransaction provides a mock function with given fields: ctx, txID, blockID -func (_m *API) GetSystemTransaction(ctx context.Context, txID flow.Identifier, blockID flow.Identifier) (*flow.TransactionBody, error) { - ret := _m.Called(ctx, txID, blockID) +// API_GetScheduledTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransactionResult' +type API_GetScheduledTransactionResult_Call struct { + *mock.Call +} + +// GetScheduledTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - scheduledTxID uint64 +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetScheduledTransactionResult(ctx interface{}, scheduledTxID interface{}, encodingVersion interface{}) *API_GetScheduledTransactionResult_Call { + return &API_GetScheduledTransactionResult_Call{Call: _e.mock.On("GetScheduledTransactionResult", ctx, scheduledTxID, encodingVersion)} +} + +func (_c *API_GetScheduledTransactionResult_Call) Run(run func(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion)) *API_GetScheduledTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_GetScheduledTransactionResult_Call) Return(transactionResult *access.TransactionResult, err error) *API_GetScheduledTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *API_GetScheduledTransactionResult_Call) RunAndReturn(run func(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *API_GetScheduledTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransaction provides a mock function for the type API +func (_mock *API) GetSystemTransaction(ctx context.Context, txID flow.Identifier, blockID flow.Identifier) (*flow.TransactionBody, error) { + ret := _mock.Called(ctx, txID, blockID) if len(ret) == 0 { panic("no return value specified for GetSystemTransaction") @@ -986,179 +2400,461 @@ func (_m *API) GetSystemTransaction(ctx context.Context, txID flow.Identifier, b var r0 *flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.TransactionBody, error)); ok { - return rf(ctx, txID, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.TransactionBody, error)); ok { + return returnFunc(ctx, txID, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.TransactionBody); ok { - r0 = rf(ctx, txID, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.TransactionBody); ok { + r0 = returnFunc(ctx, txID, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { - r1 = rf(ctx, txID, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(ctx, txID, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransactionResult provides a mock function with given fields: ctx, txID, blockID, encodingVersion -func (_m *API) GetSystemTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, txID, blockID, encodingVersion) +// API_GetSystemTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransaction' +type API_GetSystemTransaction_Call struct { + *mock.Call +} + +// GetSystemTransaction is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - blockID flow.Identifier +func (_e *API_Expecter) GetSystemTransaction(ctx interface{}, txID interface{}, blockID interface{}) *API_GetSystemTransaction_Call { + return &API_GetSystemTransaction_Call{Call: _e.mock.On("GetSystemTransaction", ctx, txID, blockID)} +} + +func (_c *API_GetSystemTransaction_Call) Run(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier)) *API_GetSystemTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_GetSystemTransaction_Call) Return(transactionBody *flow.TransactionBody, err error) *API_GetSystemTransaction_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *API_GetSystemTransaction_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier) (*flow.TransactionBody, error)) *API_GetSystemTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransactionResult provides a mock function for the type API +func (_mock *API) GetSystemTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, txID, blockID, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetSystemTransactionResult") } - var r0 *modelaccess.TransactionResult + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, txID, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, txID, blockID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, txID, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, txID, blockID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) + r0 = ret.Get(0).(*access.TransactionResult) } } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, txID, blockID, encodingVersion) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// API_GetSystemTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransactionResult' +type API_GetSystemTransactionResult_Call struct { + *mock.Call +} + +// GetSystemTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - blockID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetSystemTransactionResult(ctx interface{}, txID interface{}, blockID interface{}, encodingVersion interface{}) *API_GetSystemTransactionResult_Call { + return &API_GetSystemTransactionResult_Call{Call: _e.mock.On("GetSystemTransactionResult", ctx, txID, blockID, encodingVersion)} +} + +func (_c *API_GetSystemTransactionResult_Call) Run(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *API_GetSystemTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 entities.EventEncodingVersion + if args[3] != nil { + arg3 = args[3].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_GetSystemTransactionResult_Call) Return(transactionResult *access.TransactionResult, err error) *API_GetSystemTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *API_GetSystemTransactionResult_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *API_GetSystemTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransaction provides a mock function for the type API +func (_mock *API) GetTransaction(ctx context.Context, id flow.Identifier) (*flow.TransactionBody, error) { + ret := _mock.Called(ctx, id) + + if len(ret) == 0 { + panic("no return value specified for GetTransaction") + } - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, txID, blockID, encodingVersion) + var r0 *flow.TransactionBody + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionBody, error)); ok { + return returnFunc(ctx, id) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionBody); ok { + r0 = returnFunc(ctx, id) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*flow.TransactionBody) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } + return r0, r1 +} + +// API_GetTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransaction' +type API_GetTransaction_Call struct { + *mock.Call +} + +// GetTransaction is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *API_Expecter) GetTransaction(ctx interface{}, id interface{}) *API_GetTransaction_Call { + return &API_GetTransaction_Call{Call: _e.mock.On("GetTransaction", ctx, id)} +} + +func (_c *API_GetTransaction_Call) Run(run func(ctx context.Context, id flow.Identifier)) *API_GetTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return r0, r1 +func (_c *API_GetTransaction_Call) Return(transactionBody *flow.TransactionBody, err error) *API_GetTransaction_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *API_GetTransaction_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.TransactionBody, error)) *API_GetTransaction_Call { + _c.Call.Return(run) + return _c } -// GetTransaction provides a mock function with given fields: ctx, id -func (_m *API) GetTransaction(ctx context.Context, id flow.Identifier) (*flow.TransactionBody, error) { - ret := _m.Called(ctx, id) +// GetTransactionResult provides a mock function for the type API +func (_mock *API) GetTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, txID, blockID, collectionID, encodingVersion) if len(ret) == 0 { - panic("no return value specified for GetTransaction") + panic("no return value specified for GetTransactionResult") } - var r0 *flow.TransactionBody + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionBody, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, txID, blockID, collectionID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionBody); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, txID, blockID, collectionID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.TransactionBody) + r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, txID, blockID, collectionID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResult provides a mock function with given fields: ctx, txID, blockID, collectionID, encodingVersion -func (_m *API) GetTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, txID, blockID, collectionID, encodingVersion) +// API_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type API_GetTransactionResult_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetTransactionResult") - } +// GetTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - blockID flow.Identifier +// - collectionID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetTransactionResult(ctx interface{}, txID interface{}, blockID interface{}, collectionID interface{}, encodingVersion interface{}) *API_GetTransactionResult_Call { + return &API_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", ctx, txID, blockID, collectionID, encodingVersion)} +} - var r0 *modelaccess.TransactionResult - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, txID, blockID, collectionID, encodingVersion) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, txID, blockID, collectionID, encodingVersion) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) +func (_c *API_GetTransactionResult_Call) Run(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *API_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) } - } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + var arg4 entities.EventEncodingVersion + if args[4] != nil { + arg4 = args[4].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, txID, blockID, collectionID, encodingVersion) - } else { - r1 = ret.Error(1) - } +func (_c *API_GetTransactionResult_Call) Return(transactionResult *access.TransactionResult, err error) *API_GetTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} - return r0, r1 +func (_c *API_GetTransactionResult_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *API_GetTransactionResult_Call { + _c.Call.Return(run) + return _c } -// GetTransactionResultByIndex provides a mock function with given fields: ctx, blockID, index, encodingVersion -func (_m *API) GetTransactionResultByIndex(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, blockID, index, encodingVersion) +// GetTransactionResultByIndex provides a mock function for the type API +func (_mock *API) GetTransactionResultByIndex(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, blockID, index, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetTransactionResultByIndex") } - var r0 *modelaccess.TransactionResult + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, blockID, index, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, blockID, index, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, blockID, index, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, blockID, index, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) + r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, blockID, index, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, blockID, index, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultsByBlockID provides a mock function with given fields: ctx, blockID, encodingVersion -func (_m *API) GetTransactionResultsByBlockID(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) ([]*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, blockID, encodingVersion) +// API_GetTransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultByIndex' +type API_GetTransactionResultByIndex_Call struct { + *mock.Call +} + +// GetTransactionResultByIndex is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - index uint32 +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetTransactionResultByIndex(ctx interface{}, blockID interface{}, index interface{}, encodingVersion interface{}) *API_GetTransactionResultByIndex_Call { + return &API_GetTransactionResultByIndex_Call{Call: _e.mock.On("GetTransactionResultByIndex", ctx, blockID, index, encodingVersion)} +} + +func (_c *API_GetTransactionResultByIndex_Call) Run(run func(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion)) *API_GetTransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 entities.EventEncodingVersion + if args[3] != nil { + arg3 = args[3].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_GetTransactionResultByIndex_Call) Return(transactionResult *access.TransactionResult, err error) *API_GetTransactionResultByIndex_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *API_GetTransactionResultByIndex_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *API_GetTransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultsByBlockID provides a mock function for the type API +func (_mock *API) GetTransactionResultsByBlockID(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) ([]*access.TransactionResult, error) { + ret := _mock.Called(ctx, blockID, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetTransactionResultsByBlockID") } - var r0 []*modelaccess.TransactionResult + var r0 []*access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) ([]*modelaccess.TransactionResult, error)); ok { - return rf(ctx, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) ([]*access.TransactionResult, error)); ok { + return returnFunc(ctx, blockID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) []*modelaccess.TransactionResult); ok { - r0 = rf(ctx, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) []*access.TransactionResult); ok { + r0 = returnFunc(ctx, blockID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*modelaccess.TransactionResult) + r0 = ret.Get(0).([]*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, blockID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, blockID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionsByBlockID provides a mock function with given fields: ctx, blockID -func (_m *API) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionBody, error) { - ret := _m.Called(ctx, blockID) +// API_GetTransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultsByBlockID' +type API_GetTransactionResultsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionResultsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) GetTransactionResultsByBlockID(ctx interface{}, blockID interface{}, encodingVersion interface{}) *API_GetTransactionResultsByBlockID_Call { + return &API_GetTransactionResultsByBlockID_Call{Call: _e.mock.On("GetTransactionResultsByBlockID", ctx, blockID, encodingVersion)} +} + +func (_c *API_GetTransactionResultsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *API_GetTransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_GetTransactionResultsByBlockID_Call) Return(transactionResults []*access.TransactionResult, err error) *API_GetTransactionResultsByBlockID_Call { + _c.Call.Return(transactionResults, err) + return _c +} + +func (_c *API_GetTransactionResultsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) ([]*access.TransactionResult, error)) *API_GetTransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionsByBlockID provides a mock function for the type API +func (_mock *API) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionBody, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetTransactionsByBlockID") @@ -1166,292 +2862,865 @@ func (_m *API) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identi var r0 []*flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.TransactionBody, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.TransactionBody, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.TransactionBody); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.TransactionBody); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Ping provides a mock function with given fields: ctx -func (_m *API) Ping(ctx context.Context) error { - ret := _m.Called(ctx) +// API_GetTransactionsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionsByBlockID' +type API_GetTransactionsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *API_Expecter) GetTransactionsByBlockID(ctx interface{}, blockID interface{}) *API_GetTransactionsByBlockID_Call { + return &API_GetTransactionsByBlockID_Call{Call: _e.mock.On("GetTransactionsByBlockID", ctx, blockID)} +} + +func (_c *API_GetTransactionsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *API_GetTransactionsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetTransactionsByBlockID_Call) Return(transactionBodys []*flow.TransactionBody, err error) *API_GetTransactionsByBlockID_Call { + _c.Call.Return(transactionBodys, err) + return _c +} + +func (_c *API_GetTransactionsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionBody, error)) *API_GetTransactionsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Ping provides a mock function for the type API +func (_mock *API) Ping(ctx context.Context) error { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for Ping") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Error(0) } - return r0 } -// SendAndSubscribeTransactionStatuses provides a mock function with given fields: ctx, tx, requiredEventEncodingVersion -func (_m *API) SendAndSubscribeTransactionStatuses(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { - ret := _m.Called(ctx, tx, requiredEventEncodingVersion) +// API_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping' +type API_Ping_Call struct { + *mock.Call +} + +// Ping is a helper method to define mock.On call +// - ctx context.Context +func (_e *API_Expecter) Ping(ctx interface{}) *API_Ping_Call { + return &API_Ping_Call{Call: _e.mock.On("Ping", ctx)} +} + +func (_c *API_Ping_Call) Run(run func(ctx context.Context)) *API_Ping_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *API_Ping_Call) Return(err error) *API_Ping_Call { + _c.Call.Return(err) + return _c +} + +func (_c *API_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *API_Ping_Call { + _c.Call.Return(run) + return _c +} + +// SendAndSubscribeTransactionStatuses provides a mock function for the type API +func (_mock *API) SendAndSubscribeTransactionStatuses(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { + ret := _mock.Called(ctx, tx, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for SendAndSubscribeTransactionStatuses") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody, entities.EventEncodingVersion) subscription.Subscription); ok { - r0 = rf(ctx, tx, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody, entities.EventEncodingVersion) subscription.Subscription); ok { + r0 = returnFunc(ctx, tx, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SendTransaction provides a mock function with given fields: ctx, tx -func (_m *API) SendTransaction(ctx context.Context, tx *flow.TransactionBody) error { - ret := _m.Called(ctx, tx) +// API_SendAndSubscribeTransactionStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendAndSubscribeTransactionStatuses' +type API_SendAndSubscribeTransactionStatuses_Call struct { + *mock.Call +} + +// SendAndSubscribeTransactionStatuses is a helper method to define mock.On call +// - ctx context.Context +// - tx *flow.TransactionBody +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) SendAndSubscribeTransactionStatuses(ctx interface{}, tx interface{}, requiredEventEncodingVersion interface{}) *API_SendAndSubscribeTransactionStatuses_Call { + return &API_SendAndSubscribeTransactionStatuses_Call{Call: _e.mock.On("SendAndSubscribeTransactionStatuses", ctx, tx, requiredEventEncodingVersion)} +} + +func (_c *API_SendAndSubscribeTransactionStatuses_Call) Run(run func(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion)) *API_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.TransactionBody + if args[1] != nil { + arg1 = args[1].(*flow.TransactionBody) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SendAndSubscribeTransactionStatuses_Call) Return(subscription1 subscription.Subscription) *API_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SendAndSubscribeTransactionStatuses_Call) RunAndReturn(run func(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription) *API_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(run) + return _c +} + +// SendTransaction provides a mock function for the type API +func (_mock *API) SendTransaction(ctx context.Context, tx *flow.TransactionBody) error { + ret := _mock.Called(ctx, tx) if len(ret) == 0 { panic("no return value specified for SendTransaction") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody) error); ok { - r0 = rf(ctx, tx) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody) error); ok { + r0 = returnFunc(ctx, tx) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlockDigestsFromLatest provides a mock function with given fields: ctx, blockStatus -func (_m *API) SubscribeBlockDigestsFromLatest(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, blockStatus) +// API_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' +type API_SendTransaction_Call struct { + *mock.Call +} + +// SendTransaction is a helper method to define mock.On call +// - ctx context.Context +// - tx *flow.TransactionBody +func (_e *API_Expecter) SendTransaction(ctx interface{}, tx interface{}) *API_SendTransaction_Call { + return &API_SendTransaction_Call{Call: _e.mock.On("SendTransaction", ctx, tx)} +} + +func (_c *API_SendTransaction_Call) Run(run func(ctx context.Context, tx *flow.TransactionBody)) *API_SendTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.TransactionBody + if args[1] != nil { + arg1 = args[1].(*flow.TransactionBody) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SendTransaction_Call) Return(err error) *API_SendTransaction_Call { + _c.Call.Return(err) + return _c +} + +func (_c *API_SendTransaction_Call) RunAndReturn(run func(ctx context.Context, tx *flow.TransactionBody) error) *API_SendTransaction_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromLatest provides a mock function for the type API +func (_mock *API) SubscribeBlockDigestsFromLatest(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromLatest") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlockDigestsFromStartBlockID provides a mock function with given fields: ctx, startBlockID, blockStatus -func (_m *API) SubscribeBlockDigestsFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, startBlockID, blockStatus) +// API_SubscribeBlockDigestsFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromLatest' +type API_SubscribeBlockDigestsFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlockDigestsFromLatest(ctx interface{}, blockStatus interface{}) *API_SubscribeBlockDigestsFromLatest_Call { + return &API_SubscribeBlockDigestsFromLatest_Call{Call: _e.mock.On("SubscribeBlockDigestsFromLatest", ctx, blockStatus)} +} + +func (_c *API_SubscribeBlockDigestsFromLatest_Call) Run(run func(ctx context.Context, blockStatus flow.BlockStatus)) *API_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.BlockStatus + if args[1] != nil { + arg1 = args[1].(flow.BlockStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SubscribeBlockDigestsFromLatest_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlockDigestsFromLatest_Call) RunAndReturn(run func(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartBlockID provides a mock function for the type API +func (_mock *API) SubscribeBlockDigestsFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartBlockID") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlockDigestsFromStartHeight provides a mock function with given fields: ctx, startHeight, blockStatus -func (_m *API) SubscribeBlockDigestsFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, startHeight, blockStatus) +// API_SubscribeBlockDigestsFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartBlockID' +type API_SubscribeBlockDigestsFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlockDigestsFromStartBlockID(ctx interface{}, startBlockID interface{}, blockStatus interface{}) *API_SubscribeBlockDigestsFromStartBlockID_Call { + return &API_SubscribeBlockDigestsFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartBlockID", ctx, startBlockID, blockStatus)} +} + +func (_c *API_SubscribeBlockDigestsFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus)) *API_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeBlockDigestsFromStartBlockID_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlockDigestsFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartHeight provides a mock function for the type API +func (_mock *API) SubscribeBlockDigestsFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, startHeight, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartHeight") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlockHeadersFromLatest provides a mock function with given fields: ctx, blockStatus -func (_m *API) SubscribeBlockHeadersFromLatest(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, blockStatus) +// API_SubscribeBlockDigestsFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartHeight' +type API_SubscribeBlockDigestsFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlockDigestsFromStartHeight(ctx interface{}, startHeight interface{}, blockStatus interface{}) *API_SubscribeBlockDigestsFromStartHeight_Call { + return &API_SubscribeBlockDigestsFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartHeight", ctx, startHeight, blockStatus)} +} + +func (_c *API_SubscribeBlockDigestsFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus)) *API_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeBlockDigestsFromStartHeight_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlockDigestsFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromLatest provides a mock function for the type API +func (_mock *API) SubscribeBlockHeadersFromLatest(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromLatest") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlockHeadersFromStartBlockID provides a mock function with given fields: ctx, startBlockID, blockStatus -func (_m *API) SubscribeBlockHeadersFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, startBlockID, blockStatus) +// API_SubscribeBlockHeadersFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromLatest' +type API_SubscribeBlockHeadersFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlockHeadersFromLatest(ctx interface{}, blockStatus interface{}) *API_SubscribeBlockHeadersFromLatest_Call { + return &API_SubscribeBlockHeadersFromLatest_Call{Call: _e.mock.On("SubscribeBlockHeadersFromLatest", ctx, blockStatus)} +} + +func (_c *API_SubscribeBlockHeadersFromLatest_Call) Run(run func(ctx context.Context, blockStatus flow.BlockStatus)) *API_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.BlockStatus + if args[1] != nil { + arg1 = args[1].(flow.BlockStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SubscribeBlockHeadersFromLatest_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlockHeadersFromLatest_Call) RunAndReturn(run func(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartBlockID provides a mock function for the type API +func (_mock *API) SubscribeBlockHeadersFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartBlockID") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlockHeadersFromStartHeight provides a mock function with given fields: ctx, startHeight, blockStatus -func (_m *API) SubscribeBlockHeadersFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, startHeight, blockStatus) +// API_SubscribeBlockHeadersFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartBlockID' +type API_SubscribeBlockHeadersFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlockHeadersFromStartBlockID(ctx interface{}, startBlockID interface{}, blockStatus interface{}) *API_SubscribeBlockHeadersFromStartBlockID_Call { + return &API_SubscribeBlockHeadersFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartBlockID", ctx, startBlockID, blockStatus)} +} + +func (_c *API_SubscribeBlockHeadersFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus)) *API_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeBlockHeadersFromStartBlockID_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlockHeadersFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartHeight provides a mock function for the type API +func (_mock *API) SubscribeBlockHeadersFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, startHeight, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartHeight") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlocksFromLatest provides a mock function with given fields: ctx, blockStatus -func (_m *API) SubscribeBlocksFromLatest(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, blockStatus) +// API_SubscribeBlockHeadersFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartHeight' +type API_SubscribeBlockHeadersFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlockHeadersFromStartHeight(ctx interface{}, startHeight interface{}, blockStatus interface{}) *API_SubscribeBlockHeadersFromStartHeight_Call { + return &API_SubscribeBlockHeadersFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartHeight", ctx, startHeight, blockStatus)} +} + +func (_c *API_SubscribeBlockHeadersFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus)) *API_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeBlockHeadersFromStartHeight_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlockHeadersFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromLatest provides a mock function for the type API +func (_mock *API) SubscribeBlocksFromLatest(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromLatest") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlocksFromStartBlockID provides a mock function with given fields: ctx, startBlockID, blockStatus -func (_m *API) SubscribeBlocksFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, startBlockID, blockStatus) +// API_SubscribeBlocksFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromLatest' +type API_SubscribeBlocksFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlocksFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlocksFromLatest(ctx interface{}, blockStatus interface{}) *API_SubscribeBlocksFromLatest_Call { + return &API_SubscribeBlocksFromLatest_Call{Call: _e.mock.On("SubscribeBlocksFromLatest", ctx, blockStatus)} +} + +func (_c *API_SubscribeBlocksFromLatest_Call) Run(run func(ctx context.Context, blockStatus flow.BlockStatus)) *API_SubscribeBlocksFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.BlockStatus + if args[1] != nil { + arg1 = args[1].(flow.BlockStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SubscribeBlocksFromLatest_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlocksFromLatest_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlocksFromLatest_Call) RunAndReturn(run func(ctx context.Context, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlocksFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartBlockID provides a mock function for the type API +func (_mock *API) SubscribeBlocksFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartBlockID") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeBlocksFromStartHeight provides a mock function with given fields: ctx, startHeight, blockStatus -func (_m *API) SubscribeBlocksFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription { - ret := _m.Called(ctx, startHeight, blockStatus) +// API_SubscribeBlocksFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartBlockID' +type API_SubscribeBlocksFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlocksFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlocksFromStartBlockID(ctx interface{}, startBlockID interface{}, blockStatus interface{}) *API_SubscribeBlocksFromStartBlockID_Call { + return &API_SubscribeBlocksFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlocksFromStartBlockID", ctx, startBlockID, blockStatus)} +} + +func (_c *API_SubscribeBlocksFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus)) *API_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeBlocksFromStartBlockID_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlocksFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartHeight provides a mock function for the type API +func (_mock *API) SubscribeBlocksFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription { + ret := _mock.Called(ctx, startHeight, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartHeight") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) subscription.Subscription); ok { - r0 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) subscription.Subscription); ok { + r0 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeTransactionStatuses provides a mock function with given fields: ctx, txID, requiredEventEncodingVersion -func (_m *API) SubscribeTransactionStatuses(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { - ret := _m.Called(ctx, txID, requiredEventEncodingVersion) +// API_SubscribeBlocksFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartHeight' +type API_SubscribeBlocksFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlocksFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - blockStatus flow.BlockStatus +func (_e *API_Expecter) SubscribeBlocksFromStartHeight(ctx interface{}, startHeight interface{}, blockStatus interface{}) *API_SubscribeBlocksFromStartHeight_Call { + return &API_SubscribeBlocksFromStartHeight_Call{Call: _e.mock.On("SubscribeBlocksFromStartHeight", ctx, startHeight, blockStatus)} +} + +func (_c *API_SubscribeBlocksFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus)) *API_SubscribeBlocksFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeBlocksFromStartHeight_Call) Return(subscription1 subscription.Subscription) *API_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeBlocksFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) subscription.Subscription) *API_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeTransactionStatuses provides a mock function for the type API +func (_mock *API) SubscribeTransactionStatuses(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { + ret := _mock.Called(ctx, txID, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for SubscribeTransactionStatuses") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) subscription.Subscription); ok { - r0 = rf(ctx, txID, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) subscription.Subscription); ok { + r0 = returnFunc(ctx, txID, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// NewAPI creates a new instance of API. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *API { - mock := &API{} - mock.Mock.Test(t) +// API_SubscribeTransactionStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeTransactionStatuses' +type API_SubscribeTransactionStatuses_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubscribeTransactionStatuses is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *API_Expecter) SubscribeTransactionStatuses(ctx interface{}, txID interface{}, requiredEventEncodingVersion interface{}) *API_SubscribeTransactionStatuses_Call { + return &API_SubscribeTransactionStatuses_Call{Call: _e.mock.On("SubscribeTransactionStatuses", ctx, txID, requiredEventEncodingVersion)} +} - return mock +func (_c *API_SubscribeTransactionStatuses_Call) Run(run func(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion)) *API_SubscribeTransactionStatuses_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeTransactionStatuses_Call) Return(subscription1 subscription.Subscription) *API_SubscribeTransactionStatuses_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeTransactionStatuses_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription) *API_SubscribeTransactionStatuses_Call { + _c.Call.Return(run) + return _c } diff --git a/access/mock/events_api.go b/access/mock/events_api.go index 010a35a8910..24c1e67fee9 100644 --- a/access/mock/events_api.go +++ b/access/mock/events_api.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - entities "github.com/onflow/flow/protobuf/go/flow/entities" + "context" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow/protobuf/go/flow/entities" mock "github.com/stretchr/testify/mock" ) +// NewEventsAPI creates a new instance of EventsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEventsAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *EventsAPI { + mock := &EventsAPI{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EventsAPI is an autogenerated mock type for the EventsAPI type type EventsAPI struct { mock.Mock } -// GetEventsForBlockIDs provides a mock function with given fields: ctx, eventType, blockIDs, requiredEventEncodingVersion -func (_m *EventsAPI) GetEventsForBlockIDs(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { - ret := _m.Called(ctx, eventType, blockIDs, requiredEventEncodingVersion) +type EventsAPI_Expecter struct { + mock *mock.Mock +} + +func (_m *EventsAPI) EXPECT() *EventsAPI_Expecter { + return &EventsAPI_Expecter{mock: &_m.Mock} +} + +// GetEventsForBlockIDs provides a mock function for the type EventsAPI +func (_mock *EventsAPI) GetEventsForBlockIDs(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { + ret := _mock.Called(ctx, eventType, blockIDs, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for GetEventsForBlockIDs") @@ -26,29 +49,79 @@ func (_m *EventsAPI) GetEventsForBlockIDs(ctx context.Context, eventType string, var r0 []flow.BlockEvents var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { - return rf(ctx, eventType, blockIDs, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { + return returnFunc(ctx, eventType, blockIDs, requiredEventEncodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) []flow.BlockEvents); ok { - r0 = rf(ctx, eventType, blockIDs, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) []flow.BlockEvents); ok { + r0 = returnFunc(ctx, eventType, blockIDs, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.BlockEvents) } } - - if rf, ok := ret.Get(1).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, eventType, blockIDs, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, string, []flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, eventType, blockIDs, requiredEventEncodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForHeightRange provides a mock function with given fields: ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion -func (_m *EventsAPI) GetEventsForHeightRange(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { - ret := _m.Called(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) +// EventsAPI_GetEventsForBlockIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForBlockIDs' +type EventsAPI_GetEventsForBlockIDs_Call struct { + *mock.Call +} + +// GetEventsForBlockIDs is a helper method to define mock.On call +// - ctx context.Context +// - eventType string +// - blockIDs []flow.Identifier +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *EventsAPI_Expecter) GetEventsForBlockIDs(ctx interface{}, eventType interface{}, blockIDs interface{}, requiredEventEncodingVersion interface{}) *EventsAPI_GetEventsForBlockIDs_Call { + return &EventsAPI_GetEventsForBlockIDs_Call{Call: _e.mock.On("GetEventsForBlockIDs", ctx, eventType, blockIDs, requiredEventEncodingVersion)} +} + +func (_c *EventsAPI_GetEventsForBlockIDs_Call) Run(run func(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion)) *EventsAPI_GetEventsForBlockIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 []flow.Identifier + if args[2] != nil { + arg2 = args[2].([]flow.Identifier) + } + var arg3 entities.EventEncodingVersion + if args[3] != nil { + arg3 = args[3].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *EventsAPI_GetEventsForBlockIDs_Call) Return(blockEventss []flow.BlockEvents, err error) *EventsAPI_GetEventsForBlockIDs_Call { + _c.Call.Return(blockEventss, err) + return _c +} + +func (_c *EventsAPI_GetEventsForBlockIDs_Call) RunAndReturn(run func(ctx context.Context, eventType string, blockIDs []flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error)) *EventsAPI_GetEventsForBlockIDs_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForHeightRange provides a mock function for the type EventsAPI +func (_mock *EventsAPI) GetEventsForHeightRange(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error) { + ret := _mock.Called(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for GetEventsForHeightRange") @@ -56,36 +129,78 @@ func (_m *EventsAPI) GetEventsForHeightRange(ctx context.Context, eventType stri var r0 []flow.BlockEvents var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { - return rf(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) ([]flow.BlockEvents, error)); ok { + return returnFunc(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) []flow.BlockEvents); ok { - r0 = rf(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) []flow.BlockEvents); ok { + r0 = returnFunc(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.BlockEvents) } } - - if rf, ok := ret.Get(1).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, string, uint64, uint64, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEventsAPI creates a new instance of EventsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEventsAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *EventsAPI { - mock := &EventsAPI{} - mock.Mock.Test(t) +// EventsAPI_GetEventsForHeightRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForHeightRange' +type EventsAPI_GetEventsForHeightRange_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetEventsForHeightRange is a helper method to define mock.On call +// - ctx context.Context +// - eventType string +// - startHeight uint64 +// - endHeight uint64 +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *EventsAPI_Expecter) GetEventsForHeightRange(ctx interface{}, eventType interface{}, startHeight interface{}, endHeight interface{}, requiredEventEncodingVersion interface{}) *EventsAPI_GetEventsForHeightRange_Call { + return &EventsAPI_GetEventsForHeightRange_Call{Call: _e.mock.On("GetEventsForHeightRange", ctx, eventType, startHeight, endHeight, requiredEventEncodingVersion)} +} - return mock +func (_c *EventsAPI_GetEventsForHeightRange_Call) Run(run func(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion)) *EventsAPI_GetEventsForHeightRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + var arg4 entities.EventEncodingVersion + if args[4] != nil { + arg4 = args[4].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *EventsAPI_GetEventsForHeightRange_Call) Return(blockEventss []flow.BlockEvents, err error) *EventsAPI_GetEventsForHeightRange_Call { + _c.Call.Return(blockEventss, err) + return _c +} + +func (_c *EventsAPI_GetEventsForHeightRange_Call) RunAndReturn(run func(ctx context.Context, eventType string, startHeight uint64, endHeight uint64, requiredEventEncodingVersion entities.EventEncodingVersion) ([]flow.BlockEvents, error)) *EventsAPI_GetEventsForHeightRange_Call { + _c.Call.Return(run) + return _c } diff --git a/access/mock/receipts_api.go b/access/mock/receipts_api.go new file mode 100644 index 00000000000..e14556e9b92 --- /dev/null +++ b/access/mock/receipts_api.go @@ -0,0 +1,175 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "context" + + "github.com/onflow/flow-go/model/flow" + mock "github.com/stretchr/testify/mock" +) + +// NewReceiptsAPI creates a new instance of ReceiptsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReceiptsAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *ReceiptsAPI { + mock := &ReceiptsAPI{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ReceiptsAPI is an autogenerated mock type for the ReceiptsAPI type +type ReceiptsAPI struct { + mock.Mock +} + +type ReceiptsAPI_Expecter struct { + mock *mock.Mock +} + +func (_m *ReceiptsAPI) EXPECT() *ReceiptsAPI_Expecter { + return &ReceiptsAPI_Expecter{mock: &_m.Mock} +} + +// GetExecutionReceiptsByBlockID provides a mock function for the type ReceiptsAPI +func (_mock *ReceiptsAPI) GetExecutionReceiptsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + ret := _mock.Called(ctx, blockID) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByBlockID") + } + + var r0 []*flow.ExecutionReceipt + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.ExecutionReceipt, error)); ok { + return returnFunc(ctx, blockID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.ExecutionReceipt); ok { + r0 = returnFunc(ctx, blockID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*flow.ExecutionReceipt) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ReceiptsAPI_GetExecutionReceiptsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByBlockID' +type ReceiptsAPI_GetExecutionReceiptsByBlockID_Call struct { + *mock.Call +} + +// GetExecutionReceiptsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *ReceiptsAPI_Expecter) GetExecutionReceiptsByBlockID(ctx interface{}, blockID interface{}) *ReceiptsAPI_GetExecutionReceiptsByBlockID_Call { + return &ReceiptsAPI_GetExecutionReceiptsByBlockID_Call{Call: _e.mock.On("GetExecutionReceiptsByBlockID", ctx, blockID)} +} + +func (_c *ReceiptsAPI_GetExecutionReceiptsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *ReceiptsAPI_GetExecutionReceiptsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReceiptsAPI_GetExecutionReceiptsByBlockID_Call) Return(executionReceipts []*flow.ExecutionReceipt, err error) *ReceiptsAPI_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(executionReceipts, err) + return _c +} + +func (_c *ReceiptsAPI_GetExecutionReceiptsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]*flow.ExecutionReceipt, error)) *ReceiptsAPI_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionReceiptsByResultID provides a mock function for the type ReceiptsAPI +func (_mock *ReceiptsAPI) GetExecutionReceiptsByResultID(ctx context.Context, resultID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + ret := _mock.Called(ctx, resultID) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByResultID") + } + + var r0 []*flow.ExecutionReceipt + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.ExecutionReceipt, error)); ok { + return returnFunc(ctx, resultID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.ExecutionReceipt); ok { + r0 = returnFunc(ctx, resultID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*flow.ExecutionReceipt) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, resultID) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ReceiptsAPI_GetExecutionReceiptsByResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByResultID' +type ReceiptsAPI_GetExecutionReceiptsByResultID_Call struct { + *mock.Call +} + +// GetExecutionReceiptsByResultID is a helper method to define mock.On call +// - ctx context.Context +// - resultID flow.Identifier +func (_e *ReceiptsAPI_Expecter) GetExecutionReceiptsByResultID(ctx interface{}, resultID interface{}) *ReceiptsAPI_GetExecutionReceiptsByResultID_Call { + return &ReceiptsAPI_GetExecutionReceiptsByResultID_Call{Call: _e.mock.On("GetExecutionReceiptsByResultID", ctx, resultID)} +} + +func (_c *ReceiptsAPI_GetExecutionReceiptsByResultID_Call) Run(run func(ctx context.Context, resultID flow.Identifier)) *ReceiptsAPI_GetExecutionReceiptsByResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReceiptsAPI_GetExecutionReceiptsByResultID_Call) Return(executionReceipts []*flow.ExecutionReceipt, err error) *ReceiptsAPI_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(executionReceipts, err) + return _c +} + +func (_c *ReceiptsAPI_GetExecutionReceiptsByResultID_Call) RunAndReturn(run func(ctx context.Context, resultID flow.Identifier) ([]*flow.ExecutionReceipt, error)) *ReceiptsAPI_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(run) + return _c +} diff --git a/access/mock/scripts_api.go b/access/mock/scripts_api.go index 9c7b113c73b..fca4f9023da 100644 --- a/access/mock/scripts_api.go +++ b/access/mock/scripts_api.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewScriptsAPI creates a new instance of ScriptsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScriptsAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *ScriptsAPI { + mock := &ScriptsAPI{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ScriptsAPI is an autogenerated mock type for the ScriptsAPI type type ScriptsAPI struct { mock.Mock } -// ExecuteScriptAtBlockHeight provides a mock function with given fields: ctx, blockHeight, script, arguments -func (_m *ScriptsAPI) ExecuteScriptAtBlockHeight(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte) ([]byte, error) { - ret := _m.Called(ctx, blockHeight, script, arguments) +type ScriptsAPI_Expecter struct { + mock *mock.Mock +} + +func (_m *ScriptsAPI) EXPECT() *ScriptsAPI_Expecter { + return &ScriptsAPI_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockHeight provides a mock function for the type ScriptsAPI +func (_mock *ScriptsAPI) ExecuteScriptAtBlockHeight(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte) ([]byte, error) { + ret := _mock.Called(ctx, blockHeight, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockHeight") @@ -24,29 +48,79 @@ func (_m *ScriptsAPI) ExecuteScriptAtBlockHeight(ctx context.Context, blockHeigh var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) ([]byte, error)); ok { - return rf(ctx, blockHeight, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) ([]byte, error)); ok { + return returnFunc(ctx, blockHeight, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) []byte); ok { - r0 = rf(ctx, blockHeight, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, []byte, [][]byte) []byte); ok { + r0 = returnFunc(ctx, blockHeight, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, []byte, [][]byte) error); ok { - r1 = rf(ctx, blockHeight, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, []byte, [][]byte) error); ok { + r1 = returnFunc(ctx, blockHeight, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtBlockID provides a mock function with given fields: ctx, blockID, script, arguments -func (_m *ScriptsAPI) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte) ([]byte, error) { - ret := _m.Called(ctx, blockID, script, arguments) +// ScriptsAPI_ExecuteScriptAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockHeight' +type ScriptsAPI_ExecuteScriptAtBlockHeight_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - blockHeight uint64 +// - script []byte +// - arguments [][]byte +func (_e *ScriptsAPI_Expecter) ExecuteScriptAtBlockHeight(ctx interface{}, blockHeight interface{}, script interface{}, arguments interface{}) *ScriptsAPI_ExecuteScriptAtBlockHeight_Call { + return &ScriptsAPI_ExecuteScriptAtBlockHeight_Call{Call: _e.mock.On("ExecuteScriptAtBlockHeight", ctx, blockHeight, script, arguments)} +} + +func (_c *ScriptsAPI_ExecuteScriptAtBlockHeight_Call) Run(run func(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte)) *ScriptsAPI_ExecuteScriptAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 [][]byte + if args[3] != nil { + arg3 = args[3].([][]byte) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScriptsAPI_ExecuteScriptAtBlockHeight_Call) Return(bytes []byte, err error) *ScriptsAPI_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ScriptsAPI_ExecuteScriptAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, blockHeight uint64, script []byte, arguments [][]byte) ([]byte, error)) *ScriptsAPI_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtBlockID provides a mock function for the type ScriptsAPI +func (_mock *ScriptsAPI) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte) ([]byte, error) { + ret := _mock.Called(ctx, blockID, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -54,29 +128,79 @@ func (_m *ScriptsAPI) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.I var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) ([]byte, error)); ok { - return rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) ([]byte, error)); ok { + return returnFunc(ctx, blockID, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) []byte); ok { - r0 = rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, [][]byte) []byte); ok { + r0 = returnFunc(ctx, blockID, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, [][]byte) error); ok { - r1 = rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, [][]byte) error); ok { + r1 = returnFunc(ctx, blockID, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtLatestBlock provides a mock function with given fields: ctx, script, arguments -func (_m *ScriptsAPI) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, arguments [][]byte) ([]byte, error) { - ret := _m.Called(ctx, script, arguments) +// ScriptsAPI_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type ScriptsAPI_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - script []byte +// - arguments [][]byte +func (_e *ScriptsAPI_Expecter) ExecuteScriptAtBlockID(ctx interface{}, blockID interface{}, script interface{}, arguments interface{}) *ScriptsAPI_ExecuteScriptAtBlockID_Call { + return &ScriptsAPI_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", ctx, blockID, script, arguments)} +} + +func (_c *ScriptsAPI_ExecuteScriptAtBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte)) *ScriptsAPI_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 [][]byte + if args[3] != nil { + arg3 = args[3].([][]byte) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScriptsAPI_ExecuteScriptAtBlockID_Call) Return(bytes []byte, err error) *ScriptsAPI_ExecuteScriptAtBlockID_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ScriptsAPI_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, script []byte, arguments [][]byte) ([]byte, error)) *ScriptsAPI_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtLatestBlock provides a mock function for the type ScriptsAPI +func (_mock *ScriptsAPI) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, arguments [][]byte) ([]byte, error) { + ret := _mock.Called(ctx, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtLatestBlock") @@ -84,36 +208,66 @@ func (_m *ScriptsAPI) ExecuteScriptAtLatestBlock(ctx context.Context, script []b var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) ([]byte, error)); ok { - return rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) ([]byte, error)); ok { + return returnFunc(ctx, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) []byte); ok { - r0 = rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte) []byte); ok { + r0 = returnFunc(ctx, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, [][]byte) error); ok { - r1 = rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, [][]byte) error); ok { + r1 = returnFunc(ctx, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewScriptsAPI creates a new instance of ScriptsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewScriptsAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *ScriptsAPI { - mock := &ScriptsAPI{} - mock.Mock.Test(t) +// ScriptsAPI_ExecuteScriptAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtLatestBlock' +type ScriptsAPI_ExecuteScriptAtLatestBlock_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ExecuteScriptAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - script []byte +// - arguments [][]byte +func (_e *ScriptsAPI_Expecter) ExecuteScriptAtLatestBlock(ctx interface{}, script interface{}, arguments interface{}) *ScriptsAPI_ExecuteScriptAtLatestBlock_Call { + return &ScriptsAPI_ExecuteScriptAtLatestBlock_Call{Call: _e.mock.On("ExecuteScriptAtLatestBlock", ctx, script, arguments)} +} - return mock +func (_c *ScriptsAPI_ExecuteScriptAtLatestBlock_Call) Run(run func(ctx context.Context, script []byte, arguments [][]byte)) *ScriptsAPI_ExecuteScriptAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 [][]byte + if args[2] != nil { + arg2 = args[2].([][]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ScriptsAPI_ExecuteScriptAtLatestBlock_Call) Return(bytes []byte, err error) *ScriptsAPI_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ScriptsAPI_ExecuteScriptAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, script []byte, arguments [][]byte) ([]byte, error)) *ScriptsAPI_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(run) + return _c } diff --git a/access/mock/transaction_stream_api.go b/access/mock/transaction_stream_api.go index 9968f9b71f8..d643223df6e 100644 --- a/access/mock/transaction_stream_api.go +++ b/access/mock/transaction_stream_api.go @@ -1,73 +1,171 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - entities "github.com/onflow/flow/protobuf/go/flow/entities" + "context" + "github.com/onflow/flow-go/engine/access/subscription" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow/protobuf/go/flow/entities" mock "github.com/stretchr/testify/mock" - - subscription "github.com/onflow/flow-go/engine/access/subscription" ) +// NewTransactionStreamAPI creates a new instance of TransactionStreamAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionStreamAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionStreamAPI { + mock := &TransactionStreamAPI{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionStreamAPI is an autogenerated mock type for the TransactionStreamAPI type type TransactionStreamAPI struct { mock.Mock } -// SendAndSubscribeTransactionStatuses provides a mock function with given fields: ctx, tx, requiredEventEncodingVersion -func (_m *TransactionStreamAPI) SendAndSubscribeTransactionStatuses(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { - ret := _m.Called(ctx, tx, requiredEventEncodingVersion) +type TransactionStreamAPI_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionStreamAPI) EXPECT() *TransactionStreamAPI_Expecter { + return &TransactionStreamAPI_Expecter{mock: &_m.Mock} +} + +// SendAndSubscribeTransactionStatuses provides a mock function for the type TransactionStreamAPI +func (_mock *TransactionStreamAPI) SendAndSubscribeTransactionStatuses(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { + ret := _mock.Called(ctx, tx, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for SendAndSubscribeTransactionStatuses") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody, entities.EventEncodingVersion) subscription.Subscription); ok { - r0 = rf(ctx, tx, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody, entities.EventEncodingVersion) subscription.Subscription); ok { + r0 = returnFunc(ctx, tx, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeTransactionStatuses provides a mock function with given fields: ctx, txID, requiredEventEncodingVersion -func (_m *TransactionStreamAPI) SubscribeTransactionStatuses(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { - ret := _m.Called(ctx, txID, requiredEventEncodingVersion) +// TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendAndSubscribeTransactionStatuses' +type TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call struct { + *mock.Call +} + +// SendAndSubscribeTransactionStatuses is a helper method to define mock.On call +// - ctx context.Context +// - tx *flow.TransactionBody +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *TransactionStreamAPI_Expecter) SendAndSubscribeTransactionStatuses(ctx interface{}, tx interface{}, requiredEventEncodingVersion interface{}) *TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call { + return &TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call{Call: _e.mock.On("SendAndSubscribeTransactionStatuses", ctx, tx, requiredEventEncodingVersion)} +} + +func (_c *TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call) Run(run func(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion)) *TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.TransactionBody + if args[1] != nil { + arg1 = args[1].(*flow.TransactionBody) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call) Return(subscription1 subscription.Subscription) *TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call) RunAndReturn(run func(ctx context.Context, tx *flow.TransactionBody, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription) *TransactionStreamAPI_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeTransactionStatuses provides a mock function for the type TransactionStreamAPI +func (_mock *TransactionStreamAPI) SubscribeTransactionStatuses(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription { + ret := _mock.Called(ctx, txID, requiredEventEncodingVersion) if len(ret) == 0 { panic("no return value specified for SubscribeTransactionStatuses") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) subscription.Subscription); ok { - r0 = rf(ctx, txID, requiredEventEncodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) subscription.Subscription); ok { + r0 = returnFunc(ctx, txID, requiredEventEncodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// NewTransactionStreamAPI creates a new instance of TransactionStreamAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionStreamAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionStreamAPI { - mock := &TransactionStreamAPI{} - mock.Mock.Test(t) +// TransactionStreamAPI_SubscribeTransactionStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeTransactionStatuses' +type TransactionStreamAPI_SubscribeTransactionStatuses_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubscribeTransactionStatuses is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - requiredEventEncodingVersion entities.EventEncodingVersion +func (_e *TransactionStreamAPI_Expecter) SubscribeTransactionStatuses(ctx interface{}, txID interface{}, requiredEventEncodingVersion interface{}) *TransactionStreamAPI_SubscribeTransactionStatuses_Call { + return &TransactionStreamAPI_SubscribeTransactionStatuses_Call{Call: _e.mock.On("SubscribeTransactionStatuses", ctx, txID, requiredEventEncodingVersion)} +} - return mock +func (_c *TransactionStreamAPI_SubscribeTransactionStatuses_Call) Run(run func(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion)) *TransactionStreamAPI_SubscribeTransactionStatuses_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TransactionStreamAPI_SubscribeTransactionStatuses_Call) Return(subscription1 subscription.Subscription) *TransactionStreamAPI_SubscribeTransactionStatuses_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *TransactionStreamAPI_SubscribeTransactionStatuses_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) subscription.Subscription) *TransactionStreamAPI_SubscribeTransactionStatuses_Call { + _c.Call.Return(run) + return _c } diff --git a/access/mock/transactions_api.go b/access/mock/transactions_api.go index 957bcd51be1..fe59e3c5c6f 100644 --- a/access/mock/transactions_api.go +++ b/access/mock/transactions_api.go @@ -1,26 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - entities "github.com/onflow/flow/protobuf/go/flow/entities" + "context" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow/protobuf/go/flow/entities" mock "github.com/stretchr/testify/mock" - - modelaccess "github.com/onflow/flow-go/model/access" ) +// NewTransactionsAPI creates a new instance of TransactionsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionsAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionsAPI { + mock := &TransactionsAPI{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionsAPI is an autogenerated mock type for the TransactionsAPI type type TransactionsAPI struct { mock.Mock } -// GetScheduledTransaction provides a mock function with given fields: ctx, scheduledTxID -func (_m *TransactionsAPI) GetScheduledTransaction(ctx context.Context, scheduledTxID uint64) (*flow.TransactionBody, error) { - ret := _m.Called(ctx, scheduledTxID) +type TransactionsAPI_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionsAPI) EXPECT() *TransactionsAPI_Expecter { + return &TransactionsAPI_Expecter{mock: &_m.Mock} +} + +// GetScheduledTransaction provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetScheduledTransaction(ctx context.Context, scheduledTxID uint64) (*flow.TransactionBody, error) { + ret := _mock.Called(ctx, scheduledTxID) if len(ret) == 0 { panic("no return value specified for GetScheduledTransaction") @@ -28,59 +50,141 @@ func (_m *TransactionsAPI) GetScheduledTransaction(ctx context.Context, schedule var r0 *flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.TransactionBody, error)); ok { - return rf(ctx, scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.TransactionBody, error)); ok { + return returnFunc(ctx, scheduledTxID) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.TransactionBody); ok { - r0 = rf(ctx, scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.TransactionBody); ok { + r0 = returnFunc(ctx, scheduledTxID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, scheduledTxID) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, scheduledTxID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetScheduledTransactionResult provides a mock function with given fields: ctx, scheduledTxID, encodingVersion -func (_m *TransactionsAPI) GetScheduledTransactionResult(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, scheduledTxID, encodingVersion) +// TransactionsAPI_GetScheduledTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransaction' +type TransactionsAPI_GetScheduledTransaction_Call struct { + *mock.Call +} + +// GetScheduledTransaction is a helper method to define mock.On call +// - ctx context.Context +// - scheduledTxID uint64 +func (_e *TransactionsAPI_Expecter) GetScheduledTransaction(ctx interface{}, scheduledTxID interface{}) *TransactionsAPI_GetScheduledTransaction_Call { + return &TransactionsAPI_GetScheduledTransaction_Call{Call: _e.mock.On("GetScheduledTransaction", ctx, scheduledTxID)} +} + +func (_c *TransactionsAPI_GetScheduledTransaction_Call) Run(run func(ctx context.Context, scheduledTxID uint64)) *TransactionsAPI_GetScheduledTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetScheduledTransaction_Call) Return(transactionBody *flow.TransactionBody, err error) *TransactionsAPI_GetScheduledTransaction_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *TransactionsAPI_GetScheduledTransaction_Call) RunAndReturn(run func(ctx context.Context, scheduledTxID uint64) (*flow.TransactionBody, error)) *TransactionsAPI_GetScheduledTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransactionResult provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetScheduledTransactionResult(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, scheduledTxID, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetScheduledTransactionResult") } - var r0 *modelaccess.TransactionResult + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, scheduledTxID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, scheduledTxID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, scheduledTxID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, scheduledTxID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) + r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, scheduledTxID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, scheduledTxID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransaction provides a mock function with given fields: ctx, txID, blockID -func (_m *TransactionsAPI) GetSystemTransaction(ctx context.Context, txID flow.Identifier, blockID flow.Identifier) (*flow.TransactionBody, error) { - ret := _m.Called(ctx, txID, blockID) +// TransactionsAPI_GetScheduledTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransactionResult' +type TransactionsAPI_GetScheduledTransactionResult_Call struct { + *mock.Call +} + +// GetScheduledTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - scheduledTxID uint64 +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionsAPI_Expecter) GetScheduledTransactionResult(ctx interface{}, scheduledTxID interface{}, encodingVersion interface{}) *TransactionsAPI_GetScheduledTransactionResult_Call { + return &TransactionsAPI_GetScheduledTransactionResult_Call{Call: _e.mock.On("GetScheduledTransactionResult", ctx, scheduledTxID, encodingVersion)} +} + +func (_c *TransactionsAPI_GetScheduledTransactionResult_Call) Run(run func(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion)) *TransactionsAPI_GetScheduledTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetScheduledTransactionResult_Call) Return(transactionResult *access.TransactionResult, err error) *TransactionsAPI_GetScheduledTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionsAPI_GetScheduledTransactionResult_Call) RunAndReturn(run func(ctx context.Context, scheduledTxID uint64, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *TransactionsAPI_GetScheduledTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransaction provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetSystemTransaction(ctx context.Context, txID flow.Identifier, blockID flow.Identifier) (*flow.TransactionBody, error) { + ret := _mock.Called(ctx, txID, blockID) if len(ret) == 0 { panic("no return value specified for GetSystemTransaction") @@ -88,59 +192,153 @@ func (_m *TransactionsAPI) GetSystemTransaction(ctx context.Context, txID flow.I var r0 *flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.TransactionBody, error)); ok { - return rf(ctx, txID, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.TransactionBody, error)); ok { + return returnFunc(ctx, txID, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.TransactionBody); ok { - r0 = rf(ctx, txID, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.TransactionBody); ok { + r0 = returnFunc(ctx, txID, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { - r1 = rf(ctx, txID, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(ctx, txID, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransactionResult provides a mock function with given fields: ctx, txID, blockID, encodingVersion -func (_m *TransactionsAPI) GetSystemTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, txID, blockID, encodingVersion) +// TransactionsAPI_GetSystemTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransaction' +type TransactionsAPI_GetSystemTransaction_Call struct { + *mock.Call +} + +// GetSystemTransaction is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - blockID flow.Identifier +func (_e *TransactionsAPI_Expecter) GetSystemTransaction(ctx interface{}, txID interface{}, blockID interface{}) *TransactionsAPI_GetSystemTransaction_Call { + return &TransactionsAPI_GetSystemTransaction_Call{Call: _e.mock.On("GetSystemTransaction", ctx, txID, blockID)} +} + +func (_c *TransactionsAPI_GetSystemTransaction_Call) Run(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier)) *TransactionsAPI_GetSystemTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetSystemTransaction_Call) Return(transactionBody *flow.TransactionBody, err error) *TransactionsAPI_GetSystemTransaction_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *TransactionsAPI_GetSystemTransaction_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier) (*flow.TransactionBody, error)) *TransactionsAPI_GetSystemTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransactionResult provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetSystemTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, txID, blockID, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetSystemTransactionResult") } - var r0 *modelaccess.TransactionResult + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, txID, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, txID, blockID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, txID, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, txID, blockID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) + r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, txID, blockID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, txID, blockID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransaction provides a mock function with given fields: ctx, id -func (_m *TransactionsAPI) GetTransaction(ctx context.Context, id flow.Identifier) (*flow.TransactionBody, error) { - ret := _m.Called(ctx, id) +// TransactionsAPI_GetSystemTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransactionResult' +type TransactionsAPI_GetSystemTransactionResult_Call struct { + *mock.Call +} + +// GetSystemTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - blockID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionsAPI_Expecter) GetSystemTransactionResult(ctx interface{}, txID interface{}, blockID interface{}, encodingVersion interface{}) *TransactionsAPI_GetSystemTransactionResult_Call { + return &TransactionsAPI_GetSystemTransactionResult_Call{Call: _e.mock.On("GetSystemTransactionResult", ctx, txID, blockID, encodingVersion)} +} + +func (_c *TransactionsAPI_GetSystemTransactionResult_Call) Run(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *TransactionsAPI_GetSystemTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 entities.EventEncodingVersion + if args[3] != nil { + arg3 = args[3].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetSystemTransactionResult_Call) Return(transactionResult *access.TransactionResult, err error) *TransactionsAPI_GetSystemTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionsAPI_GetSystemTransactionResult_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *TransactionsAPI_GetSystemTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransaction provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetTransaction(ctx context.Context, id flow.Identifier) (*flow.TransactionBody, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetTransaction") @@ -148,119 +346,307 @@ func (_m *TransactionsAPI) GetTransaction(ctx context.Context, id flow.Identifie var r0 *flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionBody, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionBody, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionBody); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionBody); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResult provides a mock function with given fields: ctx, txID, blockID, collectionID, encodingVersion -func (_m *TransactionsAPI) GetTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, txID, blockID, collectionID, encodingVersion) +// TransactionsAPI_GetTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransaction' +type TransactionsAPI_GetTransaction_Call struct { + *mock.Call +} + +// GetTransaction is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *TransactionsAPI_Expecter) GetTransaction(ctx interface{}, id interface{}) *TransactionsAPI_GetTransaction_Call { + return &TransactionsAPI_GetTransaction_Call{Call: _e.mock.On("GetTransaction", ctx, id)} +} + +func (_c *TransactionsAPI_GetTransaction_Call) Run(run func(ctx context.Context, id flow.Identifier)) *TransactionsAPI_GetTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetTransaction_Call) Return(transactionBody *flow.TransactionBody, err error) *TransactionsAPI_GetTransaction_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *TransactionsAPI_GetTransaction_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.TransactionBody, error)) *TransactionsAPI_GetTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResult provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetTransactionResult(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, txID, blockID, collectionID, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetTransactionResult") } - var r0 *modelaccess.TransactionResult + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, txID, blockID, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, txID, blockID, collectionID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, txID, blockID, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, txID, blockID, collectionID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) + r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, txID, blockID, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, txID, blockID, collectionID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultByIndex provides a mock function with given fields: ctx, blockID, index, encodingVersion -func (_m *TransactionsAPI) GetTransactionResultByIndex(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion) (*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, blockID, index, encodingVersion) +// TransactionsAPI_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type TransactionsAPI_GetTransactionResult_Call struct { + *mock.Call +} + +// GetTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +// - blockID flow.Identifier +// - collectionID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionsAPI_Expecter) GetTransactionResult(ctx interface{}, txID interface{}, blockID interface{}, collectionID interface{}, encodingVersion interface{}) *TransactionsAPI_GetTransactionResult_Call { + return &TransactionsAPI_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", ctx, txID, blockID, collectionID, encodingVersion)} +} + +func (_c *TransactionsAPI_GetTransactionResult_Call) Run(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *TransactionsAPI_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + var arg4 entities.EventEncodingVersion + if args[4] != nil { + arg4 = args[4].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetTransactionResult_Call) Return(transactionResult *access.TransactionResult, err error) *TransactionsAPI_GetTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionsAPI_GetTransactionResult_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier, blockID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *TransactionsAPI_GetTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultByIndex provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetTransactionResultByIndex(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, blockID, index, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetTransactionResultByIndex") } - var r0 *modelaccess.TransactionResult + var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) (*modelaccess.TransactionResult, error)); ok { - return rf(ctx, blockID, index, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, blockID, index, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) *modelaccess.TransactionResult); ok { - r0 = rf(ctx, blockID, index, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, blockID, index, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*modelaccess.TransactionResult) + r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, blockID, index, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint32, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, blockID, index, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultsByBlockID provides a mock function with given fields: ctx, blockID, encodingVersion -func (_m *TransactionsAPI) GetTransactionResultsByBlockID(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) ([]*modelaccess.TransactionResult, error) { - ret := _m.Called(ctx, blockID, encodingVersion) +// TransactionsAPI_GetTransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultByIndex' +type TransactionsAPI_GetTransactionResultByIndex_Call struct { + *mock.Call +} + +// GetTransactionResultByIndex is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - index uint32 +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionsAPI_Expecter) GetTransactionResultByIndex(ctx interface{}, blockID interface{}, index interface{}, encodingVersion interface{}) *TransactionsAPI_GetTransactionResultByIndex_Call { + return &TransactionsAPI_GetTransactionResultByIndex_Call{Call: _e.mock.On("GetTransactionResultByIndex", ctx, blockID, index, encodingVersion)} +} + +func (_c *TransactionsAPI_GetTransactionResultByIndex_Call) Run(run func(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion)) *TransactionsAPI_GetTransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 entities.EventEncodingVersion + if args[3] != nil { + arg3 = args[3].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetTransactionResultByIndex_Call) Return(transactionResult *access.TransactionResult, err error) *TransactionsAPI_GetTransactionResultByIndex_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionsAPI_GetTransactionResultByIndex_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, index uint32, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *TransactionsAPI_GetTransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultsByBlockID provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetTransactionResultsByBlockID(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) ([]*access.TransactionResult, error) { + ret := _mock.Called(ctx, blockID, encodingVersion) if len(ret) == 0 { panic("no return value specified for GetTransactionResultsByBlockID") } - var r0 []*modelaccess.TransactionResult + var r0 []*access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) ([]*modelaccess.TransactionResult, error)); ok { - return rf(ctx, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) ([]*access.TransactionResult, error)); ok { + return returnFunc(ctx, blockID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) []*modelaccess.TransactionResult); ok { - r0 = rf(ctx, blockID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) []*access.TransactionResult); ok { + r0 = returnFunc(ctx, blockID, encodingVersion) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*modelaccess.TransactionResult) + r0 = ret.Get(0).([]*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, blockID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, blockID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionsByBlockID provides a mock function with given fields: ctx, blockID -func (_m *TransactionsAPI) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionBody, error) { - ret := _m.Called(ctx, blockID) +// TransactionsAPI_GetTransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultsByBlockID' +type TransactionsAPI_GetTransactionResultsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionResultsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionsAPI_Expecter) GetTransactionResultsByBlockID(ctx interface{}, blockID interface{}, encodingVersion interface{}) *TransactionsAPI_GetTransactionResultsByBlockID_Call { + return &TransactionsAPI_GetTransactionResultsByBlockID_Call{Call: _e.mock.On("GetTransactionResultsByBlockID", ctx, blockID, encodingVersion)} +} + +func (_c *TransactionsAPI_GetTransactionResultsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *TransactionsAPI_GetTransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetTransactionResultsByBlockID_Call) Return(transactionResults []*access.TransactionResult, err error) *TransactionsAPI_GetTransactionResultsByBlockID_Call { + _c.Call.Return(transactionResults, err) + return _c +} + +func (_c *TransactionsAPI_GetTransactionResultsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, encodingVersion entities.EventEncodingVersion) ([]*access.TransactionResult, error)) *TransactionsAPI_GetTransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionsByBlockID provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionBody, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetTransactionsByBlockID") @@ -268,54 +654,117 @@ func (_m *TransactionsAPI) GetTransactionsByBlockID(ctx context.Context, blockID var r0 []*flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.TransactionBody, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.TransactionBody, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.TransactionBody); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.TransactionBody); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// SendTransaction provides a mock function with given fields: ctx, tx -func (_m *TransactionsAPI) SendTransaction(ctx context.Context, tx *flow.TransactionBody) error { - ret := _m.Called(ctx, tx) +// TransactionsAPI_GetTransactionsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionsByBlockID' +type TransactionsAPI_GetTransactionsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *TransactionsAPI_Expecter) GetTransactionsByBlockID(ctx interface{}, blockID interface{}) *TransactionsAPI_GetTransactionsByBlockID_Call { + return &TransactionsAPI_GetTransactionsByBlockID_Call{Call: _e.mock.On("GetTransactionsByBlockID", ctx, blockID)} +} + +func (_c *TransactionsAPI_GetTransactionsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *TransactionsAPI_GetTransactionsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionsAPI_GetTransactionsByBlockID_Call) Return(transactionBodys []*flow.TransactionBody, err error) *TransactionsAPI_GetTransactionsByBlockID_Call { + _c.Call.Return(transactionBodys, err) + return _c +} + +func (_c *TransactionsAPI_GetTransactionsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionBody, error)) *TransactionsAPI_GetTransactionsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SendTransaction provides a mock function for the type TransactionsAPI +func (_mock *TransactionsAPI) SendTransaction(ctx context.Context, tx *flow.TransactionBody) error { + ret := _mock.Called(ctx, tx) if len(ret) == 0 { panic("no return value specified for SendTransaction") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody) error); ok { - r0 = rf(ctx, tx) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.TransactionBody) error); ok { + r0 = returnFunc(ctx, tx) } else { r0 = ret.Error(0) } - return r0 } -// NewTransactionsAPI creates a new instance of TransactionsAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionsAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionsAPI { - mock := &TransactionsAPI{} - mock.Mock.Test(t) +// TransactionsAPI_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' +type TransactionsAPI_SendTransaction_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SendTransaction is a helper method to define mock.On call +// - ctx context.Context +// - tx *flow.TransactionBody +func (_e *TransactionsAPI_Expecter) SendTransaction(ctx interface{}, tx interface{}) *TransactionsAPI_SendTransaction_Call { + return &TransactionsAPI_SendTransaction_Call{Call: _e.mock.On("SendTransaction", ctx, tx)} +} - return mock +func (_c *TransactionsAPI_SendTransaction_Call) Run(run func(ctx context.Context, tx *flow.TransactionBody)) *TransactionsAPI_SendTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.TransactionBody + if args[1] != nil { + arg1 = args[1].(*flow.TransactionBody) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionsAPI_SendTransaction_Call) Return(err error) *TransactionsAPI_SendTransaction_Call { + _c.Call.Return(err) + return _c +} + +func (_c *TransactionsAPI_SendTransaction_Call) RunAndReturn(run func(ctx context.Context, tx *flow.TransactionBody) error) *TransactionsAPI_SendTransaction_Call { + _c.Call.Return(run) + return _c } diff --git a/access/unimplemented.go b/access/unimplemented.go index 309eebb3f81..a12dbcdd06b 100644 --- a/access/unimplemented.go +++ b/access/unimplemented.go @@ -255,6 +255,16 @@ func (u *UnimplementedAPI) GetExecutionResultByID(ctx context.Context, id flow.I return nil, status.Error(codes.Unimplemented, "method GetExecutionResultByID not implemented") } +// GetExecutionReceiptsByBlockID returns an unimplemented error. +func (u *UnimplementedAPI) GetExecutionReceiptsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + return nil, status.Error(codes.Unimplemented, "method GetExecutionReceiptsByBlockID not implemented") +} + +// GetExecutionReceiptsByResultID returns an unimplemented error. +func (u *UnimplementedAPI) GetExecutionReceiptsByResultID(ctx context.Context, resultID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + return nil, status.Error(codes.Unimplemented, "method GetExecutionReceiptsByResultID not implemented") +} + // SubscribeBlocksFromStartBlockID returns a failed subscription. func (u *UnimplementedAPI) SubscribeBlocksFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) subscription.Subscription { msg := "method SubscribeBlocksFromStartBlockID not implemented" diff --git a/access/validator/errors.go b/access/validator/errors.go index 5542f275ac3..725844eb4dc 100644 --- a/access/validator/errors.go +++ b/access/validator/errors.go @@ -77,6 +77,26 @@ func (e DuplicatedSignatureError) Error() string { return fmt.Sprintf("duplicated signature for key (address: %s, index: %d)", e.Address.String(), e.KeyIndex) } +// MissingSignatureError indicates that a signature is missing for a payer, proposer, or authorizer. +type MissingSignatureError struct { + Address flow.Address + Message string +} + +func (e MissingSignatureError) Error() string { + return fmt.Sprintf("%s: missing signature is from account %s", e.Message, e.Address) +} + +// UnrelatedAccountSignatureError indicates that a signature has been provided by an account +// that is neither the proposer, payer, nor an authorizer of the transaction. +type UnrelatedAccountSignatureError struct { + Address flow.Address +} + +func (e UnrelatedAccountSignatureError) Error() string { + return fmt.Sprintf("unrelated account signature from address: %s", e.Address.String()) +} + // InvalidRawSignatureError indicates that a transaction contains a cryptographic raw signature // with a wrong format. type InvalidRawSignatureError struct { diff --git a/access/validator/mock/blocks.go b/access/validator/mock/blocks.go index 358938db0ba..35dfca3e013 100644 --- a/access/validator/mock/blocks.go +++ b/access/validator/mock/blocks.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBlocks creates a new instance of Blocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlocks(t interface { + mock.TestingT + Cleanup(func()) +}) *Blocks { + mock := &Blocks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Blocks is an autogenerated mock type for the Blocks type type Blocks struct { mock.Mock } -// FinalizedHeader provides a mock function with no fields -func (_m *Blocks) FinalizedHeader() (*flow.Header, error) { - ret := _m.Called() +type Blocks_Expecter struct { + mock *mock.Mock +} + +func (_m *Blocks) EXPECT() *Blocks_Expecter { + return &Blocks_Expecter{mock: &_m.Mock} +} + +// FinalizedHeader provides a mock function for the type Blocks +func (_mock *Blocks) FinalizedHeader() (*flow.Header, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalizedHeader") @@ -22,29 +46,54 @@ func (_m *Blocks) FinalizedHeader() (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func() (*flow.Header, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.Header, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// HeaderByID provides a mock function with given fields: id -func (_m *Blocks) HeaderByID(id flow.Identifier) (*flow.Header, error) { - ret := _m.Called(id) +// Blocks_FinalizedHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedHeader' +type Blocks_FinalizedHeader_Call struct { + *mock.Call +} + +// FinalizedHeader is a helper method to define mock.On call +func (_e *Blocks_Expecter) FinalizedHeader() *Blocks_FinalizedHeader_Call { + return &Blocks_FinalizedHeader_Call{Call: _e.mock.On("FinalizedHeader")} +} + +func (_c *Blocks_FinalizedHeader_Call) Run(run func()) *Blocks_FinalizedHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Blocks_FinalizedHeader_Call) Return(header *flow.Header, err error) *Blocks_FinalizedHeader_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Blocks_FinalizedHeader_Call) RunAndReturn(run func() (*flow.Header, error)) *Blocks_FinalizedHeader_Call { + _c.Call.Return(run) + return _c +} + +// HeaderByID provides a mock function for the type Blocks +func (_mock *Blocks) HeaderByID(id flow.Identifier) (*flow.Header, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for HeaderByID") @@ -52,29 +101,61 @@ func (_m *Blocks) HeaderByID(id flow.Identifier) (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Header, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Header, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Header); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Header); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// IndexedHeight provides a mock function with no fields -func (_m *Blocks) IndexedHeight() (uint64, error) { - ret := _m.Called() +// Blocks_HeaderByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByID' +type Blocks_HeaderByID_Call struct { + *mock.Call +} + +// HeaderByID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *Blocks_Expecter) HeaderByID(id interface{}) *Blocks_HeaderByID_Call { + return &Blocks_HeaderByID_Call{Call: _e.mock.On("HeaderByID", id)} +} + +func (_c *Blocks_HeaderByID_Call) Run(run func(id flow.Identifier)) *Blocks_HeaderByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_HeaderByID_Call) Return(header *flow.Header, err error) *Blocks_HeaderByID_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Blocks_HeaderByID_Call) RunAndReturn(run func(id flow.Identifier) (*flow.Header, error)) *Blocks_HeaderByID_Call { + _c.Call.Return(run) + return _c +} + +// IndexedHeight provides a mock function for the type Blocks +func (_mock *Blocks) IndexedHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for IndexedHeight") @@ -82,27 +163,52 @@ func (_m *Blocks) IndexedHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// SealedHeader provides a mock function with no fields -func (_m *Blocks) SealedHeader() (*flow.Header, error) { - ret := _m.Called() +// Blocks_IndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IndexedHeight' +type Blocks_IndexedHeight_Call struct { + *mock.Call +} + +// IndexedHeight is a helper method to define mock.On call +func (_e *Blocks_Expecter) IndexedHeight() *Blocks_IndexedHeight_Call { + return &Blocks_IndexedHeight_Call{Call: _e.mock.On("IndexedHeight")} +} + +func (_c *Blocks_IndexedHeight_Call) Run(run func()) *Blocks_IndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Blocks_IndexedHeight_Call) Return(v uint64, err error) *Blocks_IndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Blocks_IndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *Blocks_IndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// SealedHeader provides a mock function for the type Blocks +func (_mock *Blocks) SealedHeader() (*flow.Header, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SealedHeader") @@ -110,36 +216,47 @@ func (_m *Blocks) SealedHeader() (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func() (*flow.Header, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.Header, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBlocks creates a new instance of Blocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlocks(t interface { - mock.TestingT - Cleanup(func()) -}) *Blocks { - mock := &Blocks{} - mock.Mock.Test(t) +// Blocks_SealedHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SealedHeader' +type Blocks_SealedHeader_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SealedHeader is a helper method to define mock.On call +func (_e *Blocks_Expecter) SealedHeader() *Blocks_SealedHeader_Call { + return &Blocks_SealedHeader_Call{Call: _e.mock.On("SealedHeader")} +} - return mock +func (_c *Blocks_SealedHeader_Call) Run(run func()) *Blocks_SealedHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Blocks_SealedHeader_Call) Return(header *flow.Header, err error) *Blocks_SealedHeader_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Blocks_SealedHeader_Call) RunAndReturn(run func() (*flow.Header, error)) *Blocks_SealedHeader_Call { + _c.Call.Return(run) + return _c } diff --git a/access/validator/validator.go b/access/validator/validator.go index 3e3368ce3d4..91a1589f412 100644 --- a/access/validator/validator.go +++ b/access/validator/validator.go @@ -233,7 +233,7 @@ func (v *TransactionValidator) initValidationSteps() { {v.checkCanBeParsed, metrics.InvalidScript}, {v.checkAddresses, metrics.InvalidAddresses}, {v.checkSignatureFormat, metrics.InvalidSignature}, - {v.checkSignatureDuplications, metrics.DuplicatedSignature}, + {v.checkAccounts, metrics.DuplicatedSignature}, } } @@ -264,9 +264,6 @@ func (v *TransactionValidator) Validate(ctx context.Context, tx *flow.Transactio v.transactionValidationMetrics.TransactionValidationSkipped() log.Info().Err(err).Msg("check payer validation skipped due to error") } - - // TODO replace checkSignatureFormat by verifying the account/payer signatures - v.transactionValidationMetrics.TransactionValidated() return nil @@ -415,8 +412,14 @@ func (v *TransactionValidator) checkAddresses(tx *flow.TransactionBody) error { return nil } -// every key (account, key index combination) can only be used once for signing -func (v *TransactionValidator) checkSignatureDuplications(tx *flow.TransactionBody) error { +// Checks related to the accounts used in the transaction: +// - no duplicate account keys signing +// - no unrelated account signatures (from accounts that are neither proposer, payer, nor authorizers) +// - at least one payer envelope signature +// - at least one proposer signature +// - at least one signature per authorizer +func (v *TransactionValidator) checkAccounts(tx *flow.TransactionBody) error { + // check for duplicate account key type uniqueKey struct { address flow.Address index uint32 @@ -428,9 +431,56 @@ func (v *TransactionValidator) checkSignatureDuplications(tx *flow.TransactionBo } observedSigs[uniqueKey{sig.Address, sig.KeyIndex}] = true } + // check for minimum account signatures + observedEnvelopeSig := make(map[flow.Address]bool) + observedPayloadSig := make(map[flow.Address]bool) + for _, sig := range tx.EnvelopeSignatures { + observedEnvelopeSig[sig.Address] = true + } + for _, sig := range tx.PayloadSignatures { + observedPayloadSig[sig.Address] = true + } + + if !observedEnvelopeSig[tx.Payer] { + return MissingSignatureError{Address: tx.Payer, Message: "payer envelope signature is missing"} + } + + if !observedEnvelopeSig[tx.ProposalKey.Address] && !observedPayloadSig[tx.ProposalKey.Address] { + return MissingSignatureError{Address: tx.ProposalKey.Address, Message: "proposer signature on either payload or envelope is missing"} + } + + for _, authorizer := range tx.Authorizers { + if authorizer == tx.Payer || authorizer == tx.ProposalKey.Address { + // at this point, payer and proposer are guaranteed to have signatures + continue + } + if !observedEnvelopeSig[authorizer] && !observedPayloadSig[authorizer] { + return MissingSignatureError{Address: authorizer, Message: "authorizer signature on either payload or envelope is missing"} + } + } + + // check for unrelated account signatures + relatedAccounts := make(map[flow.Address]struct{}) + relatedAccounts[tx.Payer] = struct{}{} + relatedAccounts[tx.ProposalKey.Address] = struct{}{} + for _, authorizer := range tx.Authorizers { + relatedAccounts[authorizer] = struct{}{} + } + for _, sig := range append(tx.PayloadSignatures, tx.EnvelopeSignatures...) { + if _, ok := relatedAccounts[sig.Address]; !ok { + return UnrelatedAccountSignatureError{Address: sig.Address} + } + } return nil } +// checkSignatureFormat checks the format of each transaction signature independently. +// The current checks are: +// - the format is correct with regards to the authentication scheme +// - sanity check that the cryptographic signature can be an ECDSA signature of either P-256 or secp256k1 curve +// +// TODO replace checkSignatureFormat with verifying the account/payer signatures when +// collection nodes can access the account public keys. func (v *TransactionValidator) checkSignatureFormat(tx *flow.TransactionBody) error { for _, signature := range tx.PayloadSignatures { valid, _ := signature.ValidateExtensionDataAndReconstructMessage(tx.PayloadMessage()) diff --git a/admin/buf.lock b/admin/buf.lock index 7d3579dcf64..188ba61c36c 100644 --- a/admin/buf.lock +++ b/admin/buf.lock @@ -1,9 +1,8 @@ # Generated by buf. DO NOT EDIT. +version: v1beta1 deps: - remote: buf.build owner: googleapis repository: googleapis - branch: main - commit: 04ad98c82478417784639b43e71c6b4c - digest: b1-8nhYmpcJRqI1lyfXpbPH_nQjQfzgGoVHXq_gA7E4mjg= - create_time: 2021-09-07T16:08:38.569839Z + commit: 004180b77378443887d3b55cabc00384 + digest: shake256:d26c7c2fd95f0873761af33ca4a0c0d92c8577122b6feb74eb3b0a57ebe47a98ab24a209a0e91945ac4c77204e9da0c2de0020b2cedc27bdbcdea6c431eec69b diff --git a/admin/command_runner.go b/admin/command_runner.go index a16c0085ff0..cd296b010f1 100644 --- a/admin/command_runner.go +++ b/admin/command_runner.go @@ -28,7 +28,7 @@ var _ component.Component = (*CommandRunner)(nil) const CommandRunnerShutdownTimeout = 5 * time.Second -type CommandHandler func(ctx context.Context, request *CommandRequest) (interface{}, error) +type CommandHandler func(ctx context.Context, request *CommandRequest) (any, error) type CommandValidator func(request *CommandRequest) error type CommandRunnerOption func(*CommandRunner) @@ -37,10 +37,10 @@ type CommandRequest struct { // Data is the payload of the request, generated by the request initiator. // This is populated by the admin command framework and is available to both // Validator and Handler functions. - Data interface{} + Data any // ValidatorData may be optionally set by the Validator function, and will // then be available for use in the Handler function. - ValidatorData interface{} + ValidatorData any } func WithTLS(config *tls.Config) CommandRunnerOption { @@ -75,13 +75,13 @@ func NewCommandRunnerBootstrapper() *CommandRunnerBootstrapper { func (r *CommandRunnerBootstrapper) Bootstrap(logger zerolog.Logger, bindAddress string, opts ...CommandRunnerOption) *CommandRunner { handlers := make(map[string]CommandHandler) - commands := make([]interface{}, 0, len(r.handlers)) + commands := make([]any, 0, len(r.handlers)) - r.RegisterHandler("ping", func(ctx context.Context, req *CommandRequest) (interface{}, error) { + r.RegisterHandler("ping", func(ctx context.Context, req *CommandRequest) (any, error) { return "pong", nil }) - r.RegisterHandler("list-commands", func(ctx context.Context, req *CommandRequest) (interface{}, error) { + r.RegisterHandler("list-commands", func(ctx context.Context, req *CommandRequest) (any, error) { return commands, nil }) @@ -195,6 +195,13 @@ func (r *CommandRunner) runAdminServer(ctx irrecoverable.SignalerContext) error r.logger.Info().Msg("admin server starting up") + // Remove stale socket file from previous run (e.g. after container/process restart) + if _, err := os.Stat(r.grpcAddress); err == nil { + if removeErr := os.Remove(r.grpcAddress); removeErr != nil { + r.logger.Warn().Err(removeErr).Str("socket", r.grpcAddress).Msg("failed to remove stale admin socket") + } + } + listener, err := net.Listen("unix", r.grpcAddress) if err != nil { return fmt.Errorf("failed to listen on admin server address: %w", err) @@ -209,16 +216,14 @@ func (r *CommandRunner) runAdminServer(ctx irrecoverable.SignalerContext) error pb.RegisterAdminServer(grpcServer, NewAdminServer(r)) r.workersStarted.Add(1) - r.workersFinished.Add(1) - go func() { - defer r.workersFinished.Done() + r.workersFinished.Go(func() { r.workersStarted.Done() if err := grpcServer.Serve(listener); err != nil { r.logger.Err(err).Msg("gRPC server encountered fatal error") ctx.Throw(err) } - }() + }) // Initialize gRPC and HTTP muxers gwmux := runtime.NewServeMux() @@ -249,9 +254,7 @@ func (r *CommandRunner) runAdminServer(ctx irrecoverable.SignalerContext) error } r.workersStarted.Add(1) - r.workersFinished.Add(1) - go func() { - defer r.workersFinished.Done() + r.workersFinished.Go(func() { r.workersStarted.Done() // Start HTTP server (and proxy calls to gRPC server endpoint) @@ -266,12 +269,10 @@ func (r *CommandRunner) runAdminServer(ctx irrecoverable.SignalerContext) error r.logger.Err(err).Msg("HTTP server encountered error") ctx.Throw(err) } - }() + }) r.workersStarted.Add(1) - r.workersFinished.Add(1) - go func() { - defer r.workersFinished.Done() + r.workersFinished.Go(func() { r.workersStarted.Done() <-ctx.Done() @@ -296,12 +297,12 @@ func (r *CommandRunner) runAdminServer(ctx irrecoverable.SignalerContext) error } } } - }() + }) return nil } -func (r *CommandRunner) runCommand(ctx context.Context, command string, data interface{}) (interface{}, error) { +func (r *CommandRunner) runCommand(ctx context.Context, command string, data any) (any, error) { r.logger.Info().Str("command", command).Msg("received new command") req := &CommandRequest{Data: data} @@ -318,7 +319,7 @@ func (r *CommandRunner) runCommand(ctx context.Context, command string, data int } } - var handleResult interface{} + var handleResult any var handleErr error if handler := r.getHandler(command); handler != nil { diff --git a/admin/commands/execution/checkpoint_trigger.go b/admin/commands/execution/checkpoint_trigger.go index 481b3fa3199..0a396ec23e4 100644 --- a/admin/commands/execution/checkpoint_trigger.go +++ b/admin/commands/execution/checkpoint_trigger.go @@ -13,14 +13,25 @@ import ( var _ commands.AdminCommand = (*TriggerCheckpointCommand)(nil) // TriggerCheckpointCommand will send a signal to compactor to trigger checkpoint -// once finishing writing the current WAL segment file +// once finishing writing the current WAL segment file. +// When running in remote ledger mode (ledgerServiceAddr is non-empty), this command +// returns an error directing users to the ledger service's admin endpoint. type TriggerCheckpointCommand struct { - trigger *atomic.Bool + trigger *atomic.Bool + ledgerServiceAddr string // non-empty when using remote ledger service + ledgerServiceAdminAddr string // admin HTTP address for remote ledger service } -func NewTriggerCheckpointCommand(trigger *atomic.Bool) *TriggerCheckpointCommand { +// NewTriggerCheckpointCommand creates a new TriggerCheckpointCommand. +// Parameters: +// - trigger: atomic bool to signal the compactor (used only in local ledger mode) +// - ledgerServiceAddr: gRPC address of the remote ledger service (empty string for local mode) +// - ledgerServiceAdminAddr: admin HTTP address of the remote ledger service (for error messages) +func NewTriggerCheckpointCommand(trigger *atomic.Bool, ledgerServiceAddr, ledgerServiceAdminAddr string) *TriggerCheckpointCommand { return &TriggerCheckpointCommand{ - trigger: trigger, + trigger: trigger, + ledgerServiceAddr: ledgerServiceAddr, + ledgerServiceAdminAddr: ledgerServiceAdminAddr, } } @@ -35,5 +46,23 @@ func (s *TriggerCheckpointCommand) Handler(_ context.Context, _ *admin.CommandRe } func (s *TriggerCheckpointCommand) Validator(_ *admin.CommandRequest) error { + // When using remote ledger service, checkpointing is handled by the ledger service + if s.ledgerServiceAddr != "" { + if s.ledgerServiceAdminAddr == "" { + return admin.NewInvalidAdminReqErrorf( + "trigger-checkpoint is not available when using remote ledger service (connected to %s). "+ + "Please use the ledger service's admin endpoint instead. "+ + "The admin address was not configured - check if the ledger service was started with --admin-addr", + s.ledgerServiceAddr, + ) + } + return admin.NewInvalidAdminReqErrorf( + "trigger-checkpoint is not available when using remote ledger service (connected to %s). "+ + "Please use the ledger service's admin endpoint instead: "+ + "curl -X POST http://%s/admin/run_command -H 'Content-Type: application/json' -d '{\"commandName\": \"trigger-checkpoint\", \"data\": {}}'", + s.ledgerServiceAddr, + s.ledgerServiceAdminAddr, + ) + } return nil } diff --git a/admin/commands/helper.go b/admin/commands/helper.go index f12b0899048..18135ad9507 100644 --- a/admin/commands/helper.go +++ b/admin/commands/helper.go @@ -4,8 +4,8 @@ import ( "encoding/json" ) -func ConvertToInterfaceList(list interface{}) ([]interface{}, error) { - var resultList []interface{} +func ConvertToInterfaceList(list any) ([]any, error) { + var resultList []any bytes, err := json.Marshal(list) if err != nil { return nil, err @@ -14,8 +14,8 @@ func ConvertToInterfaceList(list interface{}) ([]interface{}, error) { return resultList, err } -func ConvertToMap(object interface{}) (map[string]interface{}, error) { - var result map[string]interface{} +func ConvertToMap(object any) (map[string]any, error) { + var result map[string]any bytes, err := json.Marshal(object) if err != nil { return nil, err diff --git a/admin/tools.go b/admin/tools.go index 709bd37825d..61fa90246f4 100644 --- a/admin/tools.go +++ b/admin/tools.go @@ -1,5 +1,4 @@ //go:build tools -// +build tools package tools diff --git a/bors.toml b/bors.toml deleted file mode 100644 index 4366b20e275..00000000000 --- a/bors.toml +++ /dev/null @@ -1,36 +0,0 @@ -# See https://forum.bors.tech/t/bug-wildcard-status-ignores-1-match/438 -# for why we need to explicitly list all statuses - -status = [ - "Lint (./)", - "Lint (./integration/)", - "Lint (./crypto/)", - "Unit Tests (access)", - "Unit Tests (admin)", - "Unit Tests (cmd)", - "Unit Tests (consensus)", - "Unit Tests (engine)", - "Unit Tests (fvm)", - "Unit Tests (ledger)", - "Unit Tests (module)", - "Unit Tests (network)", - "Unit Tests (utils)", - "Unit Tests (others)", - "Integration Tests (make -C integration access-tests)", - "Integration Tests (make -C integration bft-framework-tests)", - "Integration Tests (make -C integration bft-gossipsub-tests)", - "Integration Tests (make -C integration bft-protocol-tests)", - "Integration Tests (make -C integration collection-tests)", - "Integration Tests (make -C integration consensus-tests)", - "Integration Tests (make -C integration epochs-cohort1-tests)", - "Integration Tests (make -C integration epochs-cohort2-tests)", - "Integration Tests (make -C integration execution-tests)", - "Integration Tests (make -C integration ghost-tests)", - "Integration Tests (make -C integration mvp-tests)", - "Integration Tests (make -C integration network-tests)", - "Integration Tests (make -C integration verification-tests)", - -] - -delete_merged_branches = true -required_approvals = 2 diff --git a/cmd/access/node_builder/access_node_builder.go b/cmd/access/node_builder/access_node_builder.go index 5ac66c3d726..5c3a42fafaa 100644 --- a/cmd/access/node_builder/access_node_builder.go +++ b/cmd/access/node_builder/access_node_builder.go @@ -15,14 +15,16 @@ import ( "github.com/ipfs/go-cid" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/routing" - "github.com/onflow/crypto" - "github.com/onflow/flow/protobuf/go/flow/access" "github.com/rs/zerolog" "github.com/spf13/pflag" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" + "github.com/onflow/crypto" + "github.com/onflow/flow/protobuf/go/flow/access" + + extendedbackend "github.com/onflow/flow-go/access/backends/extended" txvalidator "github.com/onflow/flow-go/access/validator" "github.com/onflow/flow-go/admin/commands" stateSyncCommands "github.com/onflow/flow-go/admin/commands/state_synchronization" @@ -53,6 +55,7 @@ import ( "github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator" "github.com/onflow/flow-go/engine/access/rpc/backend/query_mode" "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/error_messages" + txstatus "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/status" rpcConnection "github.com/onflow/flow-go/engine/access/rpc/connection" "github.com/onflow/flow-go/engine/access/state_stream" statestreambackend "github.com/onflow/flow-go/engine/access/state_stream/backend" @@ -85,18 +88,22 @@ import ( finalizer "github.com/onflow/flow-go/module/finalizer/consensus" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/id" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/mempool/herocache" "github.com/onflow/flow-go/module/mempool/stdmap" "github.com/onflow/flow-go/module/metrics" "github.com/onflow/flow-go/module/metrics/unstaked" "github.com/onflow/flow-go/module/state_synchronization" "github.com/onflow/flow-go/module/state_synchronization/indexer" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" + extendedbootstrap "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/bootstrap" edrequester "github.com/onflow/flow-go/module/state_synchronization/requester" "github.com/onflow/flow-go/network" alspmgr "github.com/onflow/flow-go/network/alsp/manager" netcache "github.com/onflow/flow-go/network/cache" "github.com/onflow/flow-go/network/channels" cborcodec "github.com/onflow/flow-go/network/codec/cbor" + "github.com/onflow/flow-go/network/message" "github.com/onflow/flow-go/network/p2p" "github.com/onflow/flow-go/network/p2p/blob" p2pbuilder "github.com/onflow/flow-go/network/p2p/builder" @@ -121,6 +128,7 @@ import ( bstorage "github.com/onflow/flow-go/storage/badger" pstorage "github.com/onflow/flow-go/storage/pebble" "github.com/onflow/flow-go/storage/store" + "github.com/onflow/flow-go/utils" "github.com/onflow/flow-go/utils/grpcutils" ) @@ -169,6 +177,9 @@ type AccessNodeConfig struct { PublicNetworkConfig PublicNetworkConfig TxResultCacheSize uint executionDataIndexingEnabled bool + extendedIndexingEnabled bool + extendedIndexingDBPath string + extendedIndexingBackfillDelay time.Duration registersDBPath string checkpointFile string scriptExecutorConfig query.QueryConfig @@ -194,6 +205,7 @@ type PublicNetworkConfig struct { // DefaultAccessNodeConfig defines all the default values for the AccessNodeConfig func DefaultAccessNodeConfig() *AccessNodeConfig { homedir, _ := os.UserHomeDir() + defaultDatadir := filepath.Join(homedir, ".flow") return &AccessNodeConfig{ supportsObserver: false, rpcConf: rpc.Config{ @@ -262,7 +274,7 @@ func DefaultAccessNodeConfig() *AccessNodeConfig { }, executionDataSyncEnabled: true, publicNetworkExecutionDataEnabled: false, - executionDataDir: filepath.Join(homedir, ".flow", "execution_data"), + executionDataDir: filepath.Join(defaultDatadir, "execution_data"), executionDataStartHeight: 0, executionDataConfig: edrequester.ExecutionDataConfig{ InitialBlockHeight: 0, @@ -273,10 +285,13 @@ func DefaultAccessNodeConfig() *AccessNodeConfig { MaxRetryDelay: edrequester.DefaultMaxRetryDelay, }, executionDataIndexingEnabled: false, + extendedIndexingEnabled: false, + extendedIndexingBackfillDelay: extended.DefaultBackfillDelay, executionDataPrunerHeightRangeTarget: 0, executionDataPrunerThreshold: pruner.DefaultThreshold, executionDataPruningInterval: pruner.DefaultPruningInterval, - registersDBPath: filepath.Join(homedir, ".flow", "execution_state"), + registersDBPath: filepath.Join(defaultDatadir, "execution_state"), + extendedIndexingDBPath: filepath.Join(defaultDatadir, "indexer"), checkpointFile: cmd.NotSet, scriptExecutorConfig: query.NewDefaultConfig(), scriptExecMinBlock: 0, @@ -328,6 +343,9 @@ type FlowAccessNodeBuilder struct { ExecutionDataCache *execdatacache.ExecutionDataCache ExecutionIndexer *indexer.Indexer ExecutionIndexerCore *indexer.IndexerCore + ExtendedIndexer *extended.ExtendedIndexer + ExtendedBackend *extendedbackend.Backend + ExtendedStorage extendedbootstrap.Storage CollectionIndexer *collections.Indexer CollectionSyncer *collections.Syncer ScriptExecutor *backend.ScriptExecutor @@ -370,6 +388,7 @@ type FlowAccessNodeBuilder struct { stateStreamBackend *statestreambackend.StateStreamBackend nodeBackend *backend.Backend + streamLimiter *limiters.ConcurrencyLimiter ExecNodeIdentitiesProvider *commonrpc.ExecutionNodeIdentitiesProvider TxResultErrorMessagesCore *tx_error_messages.TxErrorMessagesCore @@ -560,8 +579,8 @@ func (builder *FlowAccessNodeBuilder) BuildConsensusFollower() *FlowAccessNodeBu func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccessNodeBuilder { var bs network.BlobService - var processedBlockHeight storage.ConsumerProgressInitializer - var processedNotifications storage.ConsumerProgressInitializer + var processedBlockHeightInitializer storage.ConsumerProgressInitializer + var processedNotificationsInitializer storage.ConsumerProgressInitializer var bsDependable *module.ProxiedReadyDoneAware var execDataDistributor *edrequester.ExecutionDataDistributor var execDataCacheBackend *herocache.BlockExecutionData @@ -570,6 +589,9 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess requesterDependable := module.NewProxiedReadyDoneAware() builder.IndexerDependencies.Add(requesterDependable) + registerStorageDependable := module.NewProxiedReadyDoneAware() + builder.IndexerDependencies.Add(registerStorageDependable) + executionDataPrunerEnabled := builder.executionDataPrunerHeightRangeTarget != 0 builder. @@ -601,14 +623,14 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess // writes execution data to. db := builder.ExecutionDatastoreManager.DB() - processedBlockHeight = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterBlockHeight) + processedBlockHeightInitializer = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterBlockHeight) return nil }). Module("processed notifications consumer progress", func(node *cmd.NodeConfig) error { // Note: progress is stored in the datastore's DB since that is where the jobqueue // writes execution data to. db := builder.ExecutionDatastoreManager.DB() - processedNotifications = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterNotification) + processedNotificationsInitializer = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterNotification) return nil }). Module("blobservice peer manager dependencies", func(node *cmd.NodeConfig) error { @@ -744,6 +766,16 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess execDataCacheBackend, ) + // start processing from the initial block height resolved from the execution data config + processedBlockHeight, err := processedBlockHeightInitializer.Initialize(builder.executionDataConfig.InitialBlockHeight) + if err != nil { + return nil, fmt.Errorf("could not initialize processed block height: %w", err) + } + processedNotifications, err := processedNotificationsInitializer.Initialize(builder.executionDataConfig.InitialBlockHeight) + if err != nil { + return nil, fmt.Errorf("could not initialize processed notifications: %w", err) + } + r, err := edrequester.New( builder.Logger, metrics.NewExecutionDataRequesterCollector(), @@ -817,6 +849,10 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess blob.WithParentBlobService(bs), } + if !builder.BitswapReprovideEnabled { + opts = append(opts, blob.WithReprovideInterval(-1)) + } + net := builder.AccessNodeConfig.PublicNetworkConfig.Network var err error @@ -833,8 +869,32 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess }) } - if builder.executionDataIndexingEnabled { - var indexedBlockHeight storage.ConsumerProgressInitializer + if !builder.executionDataIndexingEnabled { + builder.IndexerDependencies.Add(&module.NoopReadyDoneAware{}) + } else { + var indexedBlockHeightInitializer storage.ConsumerProgressInitializer + + scriptExecutorDependendable := module.NewProxiedReadyDoneAware() + extendedIndexerDependable := module.NewProxiedReadyDoneAware() + + // Script executor: + // -> registers storage + scriptExecutorDependencies := cmd.NewDependencyList() + scriptExecutorDependencies.Add(registerStorageDependable) + + // Extended indexer: + // -> script executor + extendedIndexerDependencies := cmd.NewDependencyList() + extendedIndexerDependencies.Add(scriptExecutorDependendable) + + // Regular indexer: + // -> script executor + // -> extended indexer + builder.IndexerDependencies.Add(scriptExecutorDependendable) + builder.IndexerDependencies.Add(extendedIndexerDependable) + + var indexerDerivedChainData *derived.DerivedChainData + var queryDerivedChainData *derived.DerivedChainData builder. AdminCommand("execute-script", func(config *cmd.NodeConfig) commands.AdminCommand { @@ -842,7 +902,7 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess }). Module("indexed block height consumer progress", func(node *cmd.NodeConfig) error { // Note: progress is stored in the MAIN db since that is where indexed execution data is stored. - indexedBlockHeight = store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressExecutionDataIndexerBlockHeight) + indexedBlockHeightInitializer = store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressExecutionDataIndexerBlockHeight) return nil }). Module("transaction results storage", func(node *cmd.NodeConfig) error { @@ -853,10 +913,35 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess builder.scheduledTransactions = store.NewScheduledTransactions(node.Metrics.Cache, node.ProtocolDB, bstorage.DefaultCacheSize) return nil }). - DependableComponent("execution data indexer", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + Module("extended index database", func(node *cmd.NodeConfig) error { + if !builder.extendedIndexingEnabled { + return nil + } + + extendedStorage, err := extendedbootstrap.OpenExtendedIndexDB( + node.Logger, + builder.extendedIndexingDBPath, + builder.SealedRootBlock.Height, + ) + if err != nil { + return fmt.Errorf("could not open extended index database: %w", err) + } + builder.ExtendedStorage = extendedStorage + + builder.ShutdownFunc(func() error { + if err := extendedStorage.DB.Close(); err != nil { + return fmt.Errorf("error closing extended indexer db: %w", err) + } + return nil + }) + + return nil + }). + DependableComponent("registers storage", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { // Note: using a DependableComponent here to ensure that the indexer does not block // other components from starting while bootstrapping the register db since it may - // take hours to complete. + // take hours to complete. The registers storage is not actually a component, but it + // cannot be started as a Module without blocking startup. pdb, err := pstorage.OpenRegisterPebbleDB( node.Logger.With().Str("pebbledb", "registers").Logger(), @@ -933,36 +1018,84 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess builder.Storage.RegisterIndex = registers } - indexerDerivedChainData, queryDerivedChainData, err := builder.buildDerivedChainData() + rda := &module.NoopReadyDoneAware{} + registerStorageDependable.Init(rda) + return rda, nil + }, nil). + DependableComponent("script executor", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + var err error + indexerDerivedChainData, queryDerivedChainData, err = builder.buildDerivedChainData() if err != nil { return nil, fmt.Errorf("could not create derived chain data: %w", err) } + // create script execution module, this depends on the indexer being initialized and the + // having the register storage bootstrapped + scripts := execution.NewScripts( + builder.Logger, + metrics.NewExecutionCollector(builder.Tracer), + builder.RootChainID, + computation.NewProtocolStateWrapper(builder.State), + builder.Storage.Headers, + builder.Storage.RegisterIndex.Get, + builder.scriptExecutorConfig, + queryDerivedChainData, + builder.programCacheSize > 0, + ) + + err = builder.ScriptExecutor.Initialize(builder.Storage.RegisterIndex, scripts, builder.VersionControl) + if err != nil { + return nil, fmt.Errorf("could not initialize script executor: %w", err) + } + + err = builder.RegistersAsyncStore.Initialize(builder.Storage.RegisterIndex) + if err != nil { + return nil, fmt.Errorf("could not initialize registers async store: %w", err) + } + scriptExecutorDependendable.Init(&module.NoopReadyDoneAware{}) + + // the script executor is not a component. it is being started as a DependableComponent + // to ensure dependencies are setup in the correct order. + return &module.NoopReadyDoneAware{}, nil + }, scriptExecutorDependencies). + DependableComponent("execution data indexer", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + // Note: using a DependableComponent here to ensure that the indexer does not block + // other components from starting while bootstrapping the register db since it may + // take hours to complete. + builder.ExecutionIndexerCore = indexer.New( builder.Logger, metrics.NewExecutionStateIndexerCollector(), - notNil(builder.ProtocolDB), - notNil(builder.Storage.RegisterIndex), - notNil(builder.Storage.Headers), - notNil(builder.events), - notNil(builder.collections), - notNil(builder.transactions), - notNil(builder.lightTransactionResults), - notNil(builder.scheduledTransactions), + utils.NotNil(builder.ProtocolDB), + utils.NotNil(builder.Storage.RegisterIndex), + utils.NotNil(builder.Storage.Headers), + utils.NotNil(builder.events), + utils.NotNil(builder.collections), + utils.NotNil(builder.transactions), + utils.NotNil(builder.lightTransactionResults), + utils.NotNil(builder.scheduledTransactions), builder.RootChainID, - indexerDerivedChainData, - notNil(builder.CollectionIndexer), - notNil(builder.collectionExecutedMetric), + indexerDerivedChainData, // might be nil if program caching is disabled + utils.NotNil(builder.CollectionIndexer), + utils.NotNil(builder.collectionExecutedMetric), node.StorageLockMgr, + builder.ExtendedIndexer, ) + // start processing from the first height of the registers db, which is initialized from + // the checkpoint. this ensures a consistent starting point for the indexed data. + indexedBlockHeight, err := indexedBlockHeightInitializer.Initialize(builder.Storage.RegisterIndex.FirstHeight()) + if err != nil { + return nil, fmt.Errorf("could not initialize indexed block height: %w", err) + } + // execution state worker uses a jobqueue to process new execution data and indexes it by using the indexer. builder.ExecutionIndexer, err = indexer.NewIndexer( builder.Logger, - registers.FirstHeight(), - registers, + builder.Storage.RegisterIndex.FirstHeight(), + builder.Storage.RegisterIndex, builder.ExecutionIndexerCore, - notNil(builder.ExecutionDataCache), + utils.NotNil(builder.ExecutionDataCache), builder.ExecutionDataRequester.HighestConsecutiveHeight, indexedBlockHeight, ) @@ -977,41 +1110,48 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess // setup requester to notify indexer when new execution data is received execDataDistributor.AddOnExecutionDataReceivedConsumer(builder.ExecutionIndexer.OnExecutionData) - // create script execution module, this depends on the indexer being initialized and the - // having the register storage bootstrapped - scripts := execution.NewScripts( - builder.Logger, - metrics.NewExecutionCollector(builder.Tracer), - builder.RootChainID, - computation.NewProtocolStateWrapper(builder.State), - builder.Storage.Headers, - builder.ExecutionIndexerCore.RegisterValue, - builder.scriptExecutorConfig, - queryDerivedChainData, - builder.programCacheSize > 0, - ) - - err = builder.ScriptExecutor.Initialize(builder.ExecutionIndexer, scripts, builder.VersionControl) - if err != nil { - return nil, err - } - err = builder.Reporter.Initialize(builder.ExecutionIndexer) if err != nil { return nil, err } - err = builder.RegistersAsyncStore.Initialize(registers) - if err != nil { - return nil, err - } - if builder.stopControlEnabled { builder.StopControl.RegisterHeightRecorder(builder.ExecutionIndexer) } return builder.ExecutionIndexer, nil }, builder.IndexerDependencies) + + if !builder.extendedIndexingEnabled { + extendedIndexerDependable.Init(&module.NoopReadyDoneAware{}) + } else { + builder.DependableComponent("extended indexer", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + extendedIndexer, err := extendedbootstrap.BootstrapIndexers( + node.Logger, + node.RootChainID, + utils.NotNil(builder.ExtendedStorage), + utils.NotNil(builder.StorageLockMgr), + utils.NotNil(node.State), + utils.NotNil(builder.Storage.Index), + utils.NotNil(builder.Storage.Headers), + utils.NotNil(builder.Storage.Guarantees), + utils.NotNil(builder.Storage.Collections), + utils.NotNil(builder.events), + utils.NotNil(builder.lightTransactionResults), + utils.NotNil(builder.ScriptExecutor), + utils.NotNil(builder.Storage.RegisterIndex), + builder.extendedIndexingBackfillDelay, + ) + if err != nil { + return nil, fmt.Errorf("could not create extended indexer: %w", err) + } + + builder.ExtendedIndexer = extendedIndexer + extendedIndexerDependable.Init(builder.ExtendedIndexer) + + return builder.ExtendedIndexer, nil + }, extendedIndexerDependencies) + } } if builder.stateStreamConf.ListenAddr != "" { @@ -1064,7 +1204,7 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess node.Storage.Seals, node.Storage.Results, builder.ExecutionDataStore, - notNil(builder.ExecutionDataCache), + utils.NotNil(builder.ExecutionDataCache), builder.RegistersAsyncStore, builder.EventsIndex, useIndex, @@ -1085,11 +1225,12 @@ func (builder *FlowAccessNodeBuilder) BuildExecutionSyncComponents() *FlowAccess stateStreamEng, err := statestreambackend.NewEng( node.Logger, builder.stateStreamConf, - notNil(builder.ExecutionDataCache), + utils.NotNil(builder.ExecutionDataCache), node.Storage.Headers, node.RootChainID, builder.stateStreamGrpcServer, builder.stateStreamBackend, + utils.NotNil(builder.streamLimiter), ) if err != nil { return nil, fmt.Errorf("could not create state stream engine: %w", err) @@ -1408,6 +1549,21 @@ func (builder *FlowAccessNodeBuilder) extraFlags() { flags.StringVar(&builder.registersDBPath, "execution-state-dir", defaultConfig.registersDBPath, "directory to use for execution-state database") flags.StringVar(&builder.checkpointFile, "execution-state-checkpoint", defaultConfig.checkpointFile, "execution-state checkpoint file") + // Extended Indexing + flags.BoolVar(&builder.extendedIndexingEnabled, + "extended-indexing-enabled", + defaultConfig.extendedIndexingEnabled, + "whether to enable account data indexing") + flags.DurationVar(&builder.extendedIndexingBackfillDelay, + "extended-indexing-backfill-delay", + defaultConfig.extendedIndexingBackfillDelay, + "minimum delay between backfilled heights per extended indexer") + flags.StringVar(&builder.extendedIndexingDBPath, + "extended-indexing-db-dir", + defaultConfig.extendedIndexingDBPath, + "directory to use for extended indexing database", + ) + flags.StringVar(&builder.rpcConf.BackendConfig.EventQueryMode, "event-query-mode", defaultConfig.rpcConf.BackendConfig.EventQueryMode, @@ -1607,6 +1763,10 @@ func (builder *FlowAccessNodeBuilder) extraFlags() { return errors.New("execution-data-indexing-enabled must be set if store-tx-result-error-messages is enabled") } + if builder.stateStreamConf.MaxGlobalStreams == 0 { + return errors.New("state-stream-global-max-streams must be greater than 0") + } + return nil }) } @@ -1678,7 +1838,7 @@ func (builder *FlowAccessNodeBuilder) Initialize() error { builder.EnqueueNetworkInit() builder.AdminCommand("get-transactions", func(conf *cmd.NodeConfig) commands.AdminCommand { - return storageCommands.NewGetTransactionsCommand(conf.State, conf.Storage.Payloads, notNil(builder.collections)) + return storageCommands.NewGetTransactionsCommand(conf.State, conf.Storage.Payloads, utils.NotNil(builder.collections)) }) // if this is an access node that supports public followers, enqueue the public network @@ -1718,8 +1878,8 @@ func (builder *FlowAccessNodeBuilder) enqueueRelayNetwork() { } func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { - var processedFinalizedBlockHeight storage.ConsumerProgressInitializer - var processedTxErrorMessagesBlockHeight storage.ConsumerProgressInitializer + var processedFinalizedBlockHeightInitializer storage.ConsumerProgressInitializer + var processedTxErrorMessagesBlockHeightInitializer storage.ConsumerProgressInitializer if builder.executionDataSyncEnabled { builder.BuildExecutionSyncComponents() @@ -1836,7 +1996,7 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { return nil }). Module("rest metrics", func(node *cmd.NodeConfig) error { - m, err := metrics.NewRestCollector(router.URLToRoute, node.MetricsRegisterer) + m, err := metrics.NewRestCollector(router.MethodURLToRoute, node.MetricsRegisterer) if err != nil { return err } @@ -1944,7 +2104,7 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { return nil }). Module("processed finalized block height consumer progress", func(node *cmd.NodeConfig) error { - processedFinalizedBlockHeight = store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressIngestionEngineBlockHeight) + processedFinalizedBlockHeightInitializer = store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressIngestionEngineBlockHeight) return nil }). Module("processed last full block height monotonic consumer progress", func(node *cmd.NodeConfig) error { @@ -2012,6 +2172,16 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { return stopControl, nil }). + Module("stream limiter", func(node *cmd.NodeConfig) error { + // Initialize stream limiter for RPC server - must be done unconditionally + // since the RPC server always uses it for stream concurrency limiting. + var err error + builder.streamLimiter, err = limiters.NewConcurrencyLimiter(builder.stateStreamConf.MaxGlobalStreams) + if err != nil { + return fmt.Errorf("could not create stream limiter: %w", err) + } + return nil + }). Component("RPC engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { config := builder.rpcConf backendConfig := config.BackendConfig @@ -2109,34 +2279,34 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { builder.txResultErrorMessageProvider = error_messages.NewTxErrorMessageProvider( node.Logger, builder.transactionResultErrorMessages, // might be nil - notNil(builder.TxResultsIndex), + utils.NotNil(builder.TxResultsIndex), connFactory, nodeCommunicator, - notNil(builder.ExecNodeIdentitiesProvider), + utils.NotNil(builder.ExecNodeIdentitiesProvider), ) builder.nodeBackend, err = backend.New(backend.Params{ State: node.State, - CollectionRPC: builder.CollectionRPC, // might be nil - HistoricalAccessNodes: notNil(builder.HistoricalAccessRPCs), + CollectionRPC: builder.CollectionRPC, // might be nil + HistoricalAccessNodes: builder.HistoricalAccessRPCs, // might be nil Blocks: node.Storage.Blocks, Headers: node.Storage.Headers, - Collections: notNil(builder.collections), - Transactions: notNil(builder.transactions), + Collections: utils.NotNil(builder.collections), + Transactions: utils.NotNil(builder.transactions), ExecutionReceipts: node.Storage.Receipts, ExecutionResults: node.Storage.Results, Seals: node.Storage.Seals, TxResultErrorMessages: builder.transactionResultErrorMessages, // might be nil ScheduledTransactions: builder.scheduledTransactions, // might be nil ChainID: node.RootChainID, - AccessMetrics: notNil(builder.AccessMetrics), + AccessMetrics: utils.NotNil(builder.AccessMetrics), ConnFactory: connFactory, MaxHeightRange: backendConfig.MaxHeightRange, Log: node.Logger, SnapshotHistoryLimit: backend.DefaultSnapshotHistoryLimit, Communicator: nodeCommunicator, TxResultCacheSize: builder.TxResultCacheSize, - ScriptExecutor: notNil(builder.ScriptExecutor), + ScriptExecutor: utils.NotNil(builder.ScriptExecutor), ScriptExecutionMode: scriptExecMode, CheckPayerBalanceMode: checkPayerBalanceMode, EventQueryMode: eventQueryMode, @@ -2148,36 +2318,65 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { builder.stateStreamConf.ResponseLimit, builder.stateStreamConf.ClientSendBufferSize, ), - EventsIndex: notNil(builder.EventsIndex), + EventsIndex: utils.NotNil(builder.EventsIndex), TxResultQueryMode: txResultQueryMode, - TxResultsIndex: notNil(builder.TxResultsIndex), + TxResultsIndex: utils.NotNil(builder.TxResultsIndex), LastFullBlockHeight: lastFullBlockHeight, IndexReporter: indexReporter, - VersionControl: notNil(builder.VersionControl), - ExecNodeIdentitiesProvider: notNil(builder.ExecNodeIdentitiesProvider), - TxErrorMessageProvider: notNil(builder.txResultErrorMessageProvider), + VersionControl: utils.NotNil(builder.VersionControl), + ExecNodeIdentitiesProvider: utils.NotNil(builder.ExecNodeIdentitiesProvider), + TxErrorMessageProvider: utils.NotNil(builder.txResultErrorMessageProvider), MaxScriptAndArgumentSize: config.BackendConfig.AccessConfig.MaxRequestMsgSize, }) if err != nil { return nil, fmt.Errorf("could not initialize backend: %w", err) } + if builder.extendedIndexingEnabled { + builder.ExtendedBackend, err = extendedbackend.New( + node.Logger, + extendedbackend.DefaultConfig(), + node.RootChainID, + builder.ExtendedStorage.AccountTransactionsBootstrapper, + builder.ExtendedStorage.FungibleTokenTransfersBootstrapper, + builder.ExtendedStorage.NonFungibleTokenTransfersBootstrapper, + utils.NotNil(node.State), + utils.NotNil(node.Storage.Blocks), + utils.NotNil(node.Storage.Headers), + utils.NotNil(builder.EventsIndex), + utils.NotNil(builder.TxResultsIndex), + utils.NotNil(builder.txResultErrorMessageProvider), + utils.NotNil(node.Storage.Collections), + utils.NotNil(node.Storage.Transactions), + builder.scheduledTransactions, + builder.ExtendedStorage.ScheduledTransactionsBootstrapper, + builder.ExtendedStorage.ContractDeploymentsBootstrapper, + txstatus.NewTxStatusDeriver(node.State, lastFullBlockHeight), + utils.NotNil(builder.ScriptExecutor), + ) + if err != nil { + return nil, fmt.Errorf("could not initialize extended backend: %w", err) + } + } + engineBuilder, err := rpc.NewBuilder( node.Logger, node.State, config, node.RootChainID, - notNil(builder.AccessMetrics), + utils.NotNil(builder.AccessMetrics), builder.rpcMetricsEnabled, - notNil(builder.Me), - notNil(builder.nodeBackend), - notNil(builder.nodeBackend), - notNil(builder.secureGrpcServer), - notNil(builder.unsecureGrpcServer), - notNil(builder.stateStreamBackend), + utils.NotNil(builder.Me), + utils.NotNil(builder.nodeBackend), + utils.NotNil(builder.nodeBackend), + utils.NotNil(builder.secureGrpcServer), + utils.NotNil(builder.unsecureGrpcServer), + builder.stateStreamBackend, // might be nil builder.stateStreamConf, indexReporter, builder.FollowerDistributor, + builder.ExtendedBackend, + utils.NotNil(builder.streamLimiter), ) if err != nil { return nil, err @@ -2194,12 +2393,17 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { return builder.RpcEng, nil }). Component("requester engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + fifoStore, err := engine.NewFifoMessageStore(requester.DefaultEntityRequestCacheSize) + if err != nil { + return nil, fmt.Errorf("could not create requester store: %w", err) + } requestEng, err := requester.New( node.Logger.With().Str("entity", "collection").Logger(), node.Metrics.Engine, node.EngineRegistry, node.Me, node.State, + fifoStore, channels.RequestCollections, filter.HasRole[flow.Identity](flow.RoleCollection), func() flow.Entity { return new(flow.Collection) }, @@ -2212,10 +2416,10 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { collectionIndexer, err := collections.NewIndexer( node.Logger, builder.ProtocolDB, - notNil(builder.collectionExecutedMetric), + utils.NotNil(builder.collectionExecutedMetric), node.State, node.Storage.Blocks, - notNil(builder.collections), + utils.NotNil(builder.collections), lastFullBlockHeight, node.StorageLockMgr, ) @@ -2231,7 +2435,7 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { if builder.executionDataSyncEnabled && !builder.executionDataIndexingEnabled { executionDataSyncer = collections.NewExecutionDataSyncer( node.Logger, - notNil(builder.ExecutionDataCache), + utils.NotNil(builder.ExecutionDataCache), collectionIndexer, ) } @@ -2240,7 +2444,7 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { node.Logger, builder.RequestEng, node.State, - notNil(builder.collections), + utils.NotNil(builder.collections), lastFullBlockHeight, collectionIndexer, executionDataSyncer, @@ -2255,13 +2459,19 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { if builder.storeTxResultErrorMessages { builder.TxResultErrorMessagesCore = tx_error_messages.NewTxErrorMessagesCore( node.Logger, - notNil(builder.txResultErrorMessageProvider), + utils.NotNil(builder.txResultErrorMessageProvider), builder.transactionResultErrorMessages, - notNil(builder.ExecNodeIdentitiesProvider), + utils.NotNil(builder.ExecNodeIdentitiesProvider), node.StorageLockMgr, ) } + // start ingesting finalized block from the earliest block in storage (sealed root block height) + processedFinalizedBlockHeight, err := processedFinalizedBlockHeightInitializer.Initialize(node.SealedRootBlock.Height) + if err != nil { + return nil, fmt.Errorf("could not initialize processed finalized block height: %w", err) + } + ingestEng, err := ingestion.New( node.Logger, node.EngineRegistry, @@ -2273,10 +2483,11 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { node.Storage.Results, node.Storage.Receipts, processedFinalizedBlockHeight, - notNil(builder.CollectionSyncer), - notNil(builder.CollectionIndexer), - notNil(builder.collectionExecutedMetric), - notNil(builder.TxResultErrorMessagesCore), + utils.NotNil(builder.CollectionSyncer), + utils.NotNil(builder.CollectionIndexer), + utils.NotNil(builder.collectionExecutedMetric), + builder.AccessMetrics, + builder.TxResultErrorMessagesCore, // will be nil if `storeTxResultErrorMessages` is false builder.FollowerDistributor, ) if err != nil { @@ -2307,13 +2518,19 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) { return nil }). Module("processed error messages block height consumer progress", func(node *cmd.NodeConfig) error { - processedTxErrorMessagesBlockHeight = store.NewConsumerProgress( + processedTxErrorMessagesBlockHeightInitializer = store.NewConsumerProgress( builder.ProtocolDB, module.ConsumeProgressEngineTxErrorMessagesBlockHeight, ) return nil }). Component("transaction result error messages engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + // start processing from the earliest block in storage (sealed root block height) + processedTxErrorMessagesBlockHeight, err := processedTxErrorMessagesBlockHeightInitializer.Initialize(node.SealedRootBlock.Height) + if err != nil { + return nil, fmt.Errorf("could not initialize processed tx error messages block height: %w", err) + } + engine, err := tx_error_messages.New( node.Logger, metrics.NewTransactionErrorMessagesCollector(), @@ -2445,6 +2662,7 @@ func (builder *FlowAccessNodeBuilder) enqueuePublicNetworkInit() { SlashingViolationConsumerFactory: func(adapter network.ConduitAdapter) network.ViolationsConsumer { return slashing.NewSlashingViolationsConsumer(builder.Logger, builder.Metrics.Network, adapter) }, + UnicastStreamAuthorizer: message.AlwaysAuthorizedUnicastSenderRole, }, underlay.WithMessageValidators(msgValidators...)) if err != nil { return nil, fmt.Errorf("could not initialize network: %w", err) @@ -2522,15 +2740,3 @@ func (builder *FlowAccessNodeBuilder) initPublicLibp2pNode(networkKey crypto.Pri return libp2pNode, nil } - -// notNil ensures that the input is not nil and returns it -// the usage is to ensure the dependencies are initialized before initializing a module. -// for instance, the IngestionEngine depends on storage.Collections, which is initialized in a -// different function, so we need to ensure that the storage.Collections is initialized before -// creating the IngestionEngine. -func notNil[T any](dep T) T { - if any(dep) == nil { - panic("dependency is nil") - } - return dep -} diff --git a/cmd/bootstrap/cmd/finalize.go b/cmd/bootstrap/cmd/finalize.go index 4de0a5f167a..5f3acd5211c 100644 --- a/cmd/bootstrap/cmd/finalize.go +++ b/cmd/bootstrap/cmd/finalize.go @@ -19,7 +19,6 @@ import ( hotstuff "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/model/bootstrap" - model "github.com/onflow/flow-go/model/bootstrap" "github.com/onflow/flow-go/model/dkg" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/epochs" @@ -148,8 +147,8 @@ func finalize(cmd *cobra.Command, args []string) { rootQC := constructRootQC( block, votes, - model.FilterByRole(stakingNodes, flow.RoleConsensus), - model.FilterByRole(internalNodes, flow.RoleConsensus), + bootstrap.FilterByRole(stakingNodes, flow.RoleConsensus), + bootstrap.FilterByRole(internalNodes, flow.RoleConsensus), dkgData, ) log.Info().Msg("") @@ -200,15 +199,15 @@ func finalize(cmd *cobra.Command, args []string) { } // write snapshot to disk - err = common.WriteJSON(model.PathRootProtocolStateSnapshot, flagOutdir, snapshot.Encodable()) + err = common.WriteJSON(bootstrap.PathRootProtocolStateSnapshot, flagOutdir, snapshot.Encodable()) if err != nil { log.Fatal().Err(err).Msg("failed to write json") } - log.Info().Msgf("wrote file %s/%s", flagOutdir, model.PathRootProtocolStateSnapshot) + log.Info().Msgf("wrote file %s/%s", flagOutdir, bootstrap.PathRootProtocolStateSnapshot) log.Info().Msg("") // read snapshot and verify consistency - rootSnapshot, err := loadRootProtocolSnapshot(model.PathRootProtocolStateSnapshot) + rootSnapshot, err := loadRootProtocolSnapshot(bootstrap.PathRootProtocolStateSnapshot) if err != nil { log.Fatal().Err(err).Msg("unable to load serialized root protocol") } @@ -249,7 +248,7 @@ func finalize(cmd *cobra.Command, args []string) { log.Info().Str("private_dir", flagInternalNodePrivInfoDir).Str("output_dir", flagOutdir).Msg("attempting to copy private key files") if flagInternalNodePrivInfoDir != flagOutdir { log.Info().Msg("copying internal private keys to output folder") - err := io.CopyDirectory(flagInternalNodePrivInfoDir, filepath.Join(flagOutdir, model.DirPrivateRoot)) + err := io.CopyDirectory(flagInternalNodePrivInfoDir, filepath.Join(flagOutdir, bootstrap.DirPrivateRoot)) if err != nil { log.Error().Err(err).Msg("could not copy private key files") } @@ -278,7 +277,7 @@ func readRootBlockVotes() []*hotstuff.Vote { } for _, f := range files { // skip files that do not include node-infos - if !strings.Contains(f, model.FilenameRootBlockVotePrefix) { + if !strings.Contains(f, bootstrap.FilenameRootBlockVotePrefix) { continue } @@ -300,7 +299,7 @@ func readRootBlockVotes() []*hotstuff.Vote { // // IMPORTANT: node infos are returned in the canonical ordering, meaning this // is safe to use as the input to the DKG and protocol state. -func mergeNodeInfos(internalNodes, partnerNodes []model.NodeInfo) ([]model.NodeInfo, error) { +func mergeNodeInfos(internalNodes, partnerNodes []bootstrap.NodeInfo) ([]bootstrap.NodeInfo, error) { nodes := append(internalNodes, partnerNodes...) // test for duplicate Addresses @@ -322,7 +321,7 @@ func mergeNodeInfos(internalNodes, partnerNodes []model.NodeInfo) ([]model.NodeI } // sort nodes using the canonical ordering - nodes = model.Sort(nodes, flow.Canonical[flow.Identity]) + nodes = bootstrap.Sort(nodes, flow.Canonical[flow.Identity]) return nodes, nil } @@ -410,7 +409,7 @@ func generateEmptyExecutionState( } commit, err = run.GenerateExecutionState( - filepath.Join(flagOutdir, model.DirnameExecutionState), + filepath.Join(flagOutdir, bootstrap.DirnameExecutionState), serviceAccountPublicKey, rootBlock.ChainID.Chain(), fvm.WithRootBlock(rootBlock), diff --git a/cmd/bootstrap/cmd/machine_account_key_test.go b/cmd/bootstrap/cmd/machine_account_key_test.go index dfd93fcd5f6..b7c14f18384 100644 --- a/cmd/bootstrap/cmd/machine_account_key_test.go +++ b/cmd/bootstrap/cmd/machine_account_key_test.go @@ -13,7 +13,6 @@ import ( "github.com/onflow/flow-go/cmd/util/cmd/common" "github.com/onflow/flow-go/model/bootstrap" - model "github.com/onflow/flow-go/model/bootstrap" ioutils "github.com/onflow/flow-go/utils/io" "github.com/onflow/flow-go/utils/unittest" ) @@ -45,11 +44,11 @@ func TestMachineAccountKeyFileExists(t *testing.T) { nodeID := strings.TrimSpace(string(b)) // make sure file exists - machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountPrivateKey, nodeID)) + machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountPrivateKey, nodeID)) require.FileExists(t, machineKeyFilePath) // read file priv key file before command - var machineAccountPrivBefore model.NodeMachineAccountKey + var machineAccountPrivBefore bootstrap.NodeMachineAccountKey require.NoError(t, common.ReadJSON(machineKeyFilePath, &machineAccountPrivBefore)) // run command with flags @@ -59,7 +58,7 @@ func TestMachineAccountKeyFileExists(t *testing.T) { require.Regexp(t, keyFileExistsRegex, hook.logs.String()) // read machine account key file again - var machineAccountPrivAfter model.NodeMachineAccountKey + var machineAccountPrivAfter bootstrap.NodeMachineAccountKey require.NoError(t, common.ReadJSON(machineKeyFilePath, &machineAccountPrivAfter)) // check if key was modified @@ -99,7 +98,7 @@ func TestMachineAccountKeyFileCreated(t *testing.T) { nodeID := strings.TrimSpace(string(b)) // delete machine account key file - machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountPrivateKey, nodeID)) + machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountPrivateKey, nodeID)) err = os.Remove(machineKeyFilePath) require.NoError(t, err) diff --git a/cmd/bootstrap/cmd/machine_account_test.go b/cmd/bootstrap/cmd/machine_account_test.go index 27631a3bddc..ff97e73064f 100644 --- a/cmd/bootstrap/cmd/machine_account_test.go +++ b/cmd/bootstrap/cmd/machine_account_test.go @@ -13,7 +13,6 @@ import ( "github.com/onflow/flow-go/cmd/util/cmd/common" "github.com/onflow/flow-go/model/bootstrap" - model "github.com/onflow/flow-go/model/bootstrap" "github.com/onflow/flow-go/model/flow" ioutils "github.com/onflow/flow-go/utils/io" "github.com/onflow/flow-go/utils/unittest" @@ -55,11 +54,11 @@ func TestMachineAccountHappyPath(t *testing.T) { nodeID := strings.TrimSpace(string(b)) // make sure key file exists (sanity check) - machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountPrivateKey, nodeID)) + machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountPrivateKey, nodeID)) require.FileExists(t, machineKeyFilePath) // sanity check if machine account info file exists - machineInfoFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountInfoPriv, nodeID)) + machineInfoFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountInfoPriv, nodeID)) require.NoFileExists(t, machineInfoFilePath) // make sure regex matches and file was created @@ -102,11 +101,11 @@ func TestMachineAccountInfoFileExists(t *testing.T) { nodeID := strings.TrimSpace(string(b)) // make sure key file exists (sanity check) - machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountPrivateKey, nodeID)) + machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountPrivateKey, nodeID)) require.FileExists(t, machineKeyFilePath) // sanity check if machine account info file exists - machineInfoFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountInfoPriv, nodeID)) + machineInfoFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountInfoPriv, nodeID)) require.NoFileExists(t, machineInfoFilePath) // run machine account to create info file @@ -115,14 +114,14 @@ func TestMachineAccountInfoFileExists(t *testing.T) { hook.logs.Reset() // read in info file - var machineAccountInfoBefore model.NodeMachineAccountInfo + var machineAccountInfoBefore bootstrap.NodeMachineAccountInfo require.NoError(t, common.ReadJSON(machineInfoFilePath, &machineAccountInfoBefore)) // run again and make sure info file was not changed machineAccountRun(nil, nil) require.Regexp(t, regex, hook.logs.String()) - var machineAccountInfoAfter model.NodeMachineAccountInfo + var machineAccountInfoAfter bootstrap.NodeMachineAccountInfo require.NoError(t, common.ReadJSON(machineInfoFilePath, &machineAccountInfoAfter)) assert.Equal(t, machineAccountInfoBefore, machineAccountInfoAfter) @@ -160,11 +159,11 @@ func TestMachineAccountWrongFlowAddressFormat(t *testing.T) { nodeID := strings.TrimSpace(string(b)) // make sure key file exists (sanity check) - machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountPrivateKey, nodeID)) + machineKeyFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountPrivateKey, nodeID)) require.FileExists(t, machineKeyFilePath) // sanity check if machine account info file exists - machineInfoFilePath := filepath.Join(flagOutdir, fmt.Sprintf(model.PathNodeMachineAccountInfoPriv, nodeID)) + machineInfoFilePath := filepath.Join(flagOutdir, fmt.Sprintf(bootstrap.PathNodeMachineAccountInfoPriv, nodeID)) require.NoFileExists(t, machineInfoFilePath) // run machine account command diff --git a/cmd/bootstrap/run/epochs.go b/cmd/bootstrap/run/epochs.go index ed695af2b07..4dad518d71b 100644 --- a/cmd/bootstrap/run/epochs.go +++ b/cmd/bootstrap/run/epochs.go @@ -13,7 +13,6 @@ import ( hotstuff "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/fvm/systemcontracts" "github.com/onflow/flow-go/model/bootstrap" - model "github.com/onflow/flow-go/model/bootstrap" "github.com/onflow/flow-go/model/cluster" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/flow/filter" @@ -163,7 +162,7 @@ func GenerateRecoverTxArgsWithDKG( // Filter internalNodes so it only contains nodes which are valid for inclusion in the epoch // This is a safety measure: just in case subsequent functions don't properly account for additional nodes, // we proactively remove them from consideration here. - internalNodes = slices.DeleteFunc(slices.Clone(internalNodes), func(info model.NodeInfo) bool { + internalNodes = slices.DeleteFunc(slices.Clone(internalNodes), func(info bootstrap.NodeInfo) bool { _, isCurrentEligibleEpochParticipant := internalNodesMap[info.NodeID] return !isCurrentEligibleEpochParticipant }) @@ -364,11 +363,11 @@ func ConstructClusterRootQCsFromVotes(log zerolog.Logger, clusterList flow.Clust // Filters a list of nodes to include only nodes that will sign the QC for the // given cluster. The resulting list of nodes is only nodes that are in the // given cluster AND are not partner nodes (ie. we have the private keys). -func filterClusterSigners(cluster flow.IdentitySkeletonList, nodeInfos []model.NodeInfo) []model.NodeInfo { - var filtered []model.NodeInfo +func filterClusterSigners(cluster flow.IdentitySkeletonList, nodeInfos []bootstrap.NodeInfo) []bootstrap.NodeInfo { + var filtered []bootstrap.NodeInfo for _, node := range nodeInfos { _, isInCluster := cluster.ByNodeID(node.NodeID) - isPrivateKeyAvailable := node.Type() == model.NodeInfoTypePrivate + isPrivateKeyAvailable := node.Type() == bootstrap.NodeInfoTypePrivate if isInCluster && isPrivateKeyAvailable { filtered = append(filtered, node) diff --git a/cmd/bootstrap/run/execution_state.go b/cmd/bootstrap/run/execution_state.go index c1896668c38..257f088f8f6 100644 --- a/cmd/bootstrap/run/execution_state.go +++ b/cmd/bootstrap/run/execution_state.go @@ -11,7 +11,6 @@ import ( "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/ledger/common/pathfinder" "github.com/onflow/flow-go/ledger/complete" - ledger "github.com/onflow/flow-go/ledger/complete" "github.com/onflow/flow-go/ledger/complete/mtrie/trie" "github.com/onflow/flow-go/ledger/complete/wal" bootstrapFilenames "github.com/onflow/flow-go/model/bootstrap" @@ -38,7 +37,7 @@ func GenerateExecutionState( return flow.DummyStateCommitment, err } - ledgerStorage, err := ledger.NewLedger(diskWal, capacity, metricsCollector, zerolog.Nop(), ledger.DefaultPathFinderVersion) + ledgerStorage, err := complete.NewLedger(diskWal, capacity, metricsCollector, zerolog.Nop(), complete.DefaultPathFinderVersion) if err != nil { return flow.DummyStateCommitment, err } diff --git a/cmd/bootstrap/transit/cmd/pull.go b/cmd/bootstrap/transit/cmd/pull.go index 9eb0a9861b5..6ccd0fbf1a7 100644 --- a/cmd/bootstrap/transit/cmd/pull.go +++ b/cmd/bootstrap/transit/cmd/pull.go @@ -16,7 +16,6 @@ import ( "github.com/onflow/flow-go/cmd/bootstrap/gcs" "github.com/onflow/flow-go/cmd/bootstrap/utils" "github.com/onflow/flow-go/model/bootstrap" - model "github.com/onflow/flow-go/model/bootstrap" "github.com/onflow/flow-go/model/flow" ) @@ -130,7 +129,7 @@ func pull(cmd *cobra.Command, args []string) { if role == flow.RoleExecution { // root.checkpoint* is downloaded to /public-root-information after a pull - localPublicRootInfoDir := filepath.Join(flagBootDir, model.DirnamePublicBootstrap) + localPublicRootInfoDir := filepath.Join(flagBootDir, bootstrap.DirnamePublicBootstrap) // move the root.checkpoint, root.checkpoint.0, root.checkpoint.1 etc. files to the bootstrap/execution-state dir err = filepath.WalkDir(localPublicRootInfoDir, func(srcPath string, rootCheckpointFile fs.DirEntry, err error) error { @@ -139,9 +138,9 @@ func pull(cmd *cobra.Command, args []string) { } // if rootCheckpointFile is a file whose name starts with "root.checkpoint", then move it - if !rootCheckpointFile.IsDir() && strings.HasPrefix(rootCheckpointFile.Name(), model.FilenameWALRootCheckpoint) { + if !rootCheckpointFile.IsDir() && strings.HasPrefix(rootCheckpointFile.Name(), bootstrap.FilenameWALRootCheckpoint) { - dstPath := filepath.Join(flagBootDir, model.DirnameExecutionState, rootCheckpointFile.Name()) + dstPath := filepath.Join(flagBootDir, bootstrap.DirnameExecutionState, rootCheckpointFile.Name()) log.Info().Str("src", srcPath).Str("destination", dstPath).Msgf("moving file") err = moveFile(srcPath, dstPath) if err != nil { @@ -165,7 +164,7 @@ func pull(cmd *cobra.Command, args []string) { } // calculate SHA256 of rootsnapshot - rootFile := filepath.Join(flagBootDir, model.PathRootProtocolStateSnapshot) + rootFile := filepath.Join(flagBootDir, bootstrap.PathRootProtocolStateSnapshot) rootSHA256, err := getFileSHA256(rootFile) if err != nil { log.Fatal().Err(err).Str("file", rootFile).Msg("failed to calculate SHA256 of root file") diff --git a/cmd/bootstrap/utils/key_generation.go b/cmd/bootstrap/utils/key_generation.go index 7d82109309d..658656b9222 100644 --- a/cmd/bootstrap/utils/key_generation.go +++ b/cmd/bootstrap/utils/key_generation.go @@ -16,7 +16,6 @@ import ( "github.com/onflow/flow-go/fvm/systemcontracts" "github.com/onflow/flow-go/model/bootstrap" - model "github.com/onflow/flow-go/model/bootstrap" "github.com/onflow/flow-go/model/encodable" "github.com/onflow/flow-go/model/flow" ) @@ -310,9 +309,9 @@ func WriteStakingNetworkingKeyFiles(nodeInfos []bootstrap.NodeInfo, write WriteJ // WriteNodeInternalPubInfos writes the `node-internal-infos.pub.json` file. // In a nutshell, this file contains the Role, address and weight for all authorized nodes. func WriteNodeInternalPubInfos(nodeInfos []bootstrap.NodeInfo, write WriteJSONFileFunc) error { - configs := make([]model.NodeConfig, len(nodeInfos)) + configs := make([]bootstrap.NodeConfig, len(nodeInfos)) for i, nodeInfo := range nodeInfos { - configs[i] = model.NodeConfig{ + configs[i] = bootstrap.NodeConfig{ Role: nodeInfo.Role, Address: nodeInfo.Address, Weight: nodeInfo.Weight, diff --git a/cmd/consensus/main.go b/cmd/consensus/main.go index cf22c928e2d..85eb9d8e4af 100644 --- a/cmd/consensus/main.go +++ b/cmd/consensus/main.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "os" "path/filepath" "time" @@ -30,6 +31,7 @@ import ( "github.com/onflow/flow-go/consensus/hotstuff/verification" "github.com/onflow/flow-go/consensus/hotstuff/votecollector" recovery "github.com/onflow/flow-go/consensus/recovery/protocol" + "github.com/onflow/flow-go/engine" "github.com/onflow/flow-go/engine/common/requester" synceng "github.com/onflow/flow-go/engine/common/synchronization" "github.com/onflow/flow-go/engine/consensus/approvals/tracker" @@ -101,10 +103,11 @@ func main() { startupTime time.Time // DKG contract client - machineAccountInfo *bootstrap.NodeMachineAccountInfo - flowClientConfigs []*grpcclient.FlowClientConfig - insecureAccessAPI bool - accessNodeIDS []string + machineAccountInfo *bootstrap.NodeMachineAccountInfo + flowClientConfigs []*grpcclient.FlowClientConfig + insecureAccessAPI bool + accessNodeIDS []string + requireBeaconKeyOnStartup bool err error mutableState protocol.ParticipantState @@ -160,6 +163,7 @@ func main() { flags.BoolVar(&emergencySealing, "emergency-sealing-active", flow.DefaultEmergencySealingActive, "(de)activation of emergency sealing") flags.BoolVar(&insecureAccessAPI, "insecure-access-api", false, "required if insecure GRPC connection should be used") flags.StringSliceVar(&accessNodeIDS, "access-node-ids", []string{}, fmt.Sprintf("array of access node IDs sorted in priority order where the first ID in this array will get the first connection attempt and each subsequent ID after serves as a fallback. Minimum length %d. Use '*' for all IDs in protocol state.", common.DefaultAccessNodeIDSMinimum)) + flags.BoolVar(&requireBeaconKeyOnStartup, "require-beacon-key", true, "if true, the node will fail to start if the beacon key for the current epoch is missing or invalid. The purpose of this flag is to notify an operator if they start a node with expected keys missing (typically if they are using Dynamic Bootstrap to reclaim disk space). ") flags.DurationVar(&dkgMessagingEngineConfig.RetryBaseWait, "dkg-messaging-engine-retry-base-wait", dkgMessagingEngineConfig.RetryBaseWait, "the inter-attempt wait time for the first attempt (base of exponential retry)") flags.Uint64Var(&dkgMessagingEngineConfig.RetryMax, "dkg-messaging-engine-retry-max", dkgMessagingEngineConfig.RetryMax, "the maximum number of retry attempts for an outbound DKG message") flags.Uint64Var(&dkgMessagingEngineConfig.RetryJitterPercent, "dkg-messaging-engine-retry-jitter-percent", dkgMessagingEngineConfig.RetryJitterPercent, "the percentage of jitter to apply to each inter-attempt wait time") @@ -373,6 +377,16 @@ func main() { node.ProtocolEvents.AddConsumer(myBeaconKeyRecovery) return nil }). + Module("beacon key verification", func(node *cmd.NodeConfig) error { + err := dkgmodule.VerifyBeaconKeyForEpoch(node.Logger, node.NodeID, node.State, myBeaconKeyStateMachine, requireBeaconKeyOnStartup) + if err != nil { + log.Fatal("This node is configured with --require-beacon-key=true (default), but failed to find a valid beacon key for the " + + "current epoch on startup. This default check is used as a safety precaution to prevent many Consensus nodes from being " + + "started up, all without valid beacon keys, as this can compromise liveness on the network. If you operate more than one " + + "Flow Consensus node, contact Flow Foundation operator support for guidance on how to proceed.") + } + return nil + }). Module("collection guarantees mempool", func(node *cmd.NodeConfig) error { guarantees = stdmap.NewGuarantees(guaranteeLimit) return nil @@ -487,12 +501,17 @@ func main() { return e, err }). Component("matching engine", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + fifoStore, err := engine.NewFifoMessageStore(requester.DefaultEntityRequestCacheSize) + if err != nil { + return nil, fmt.Errorf("could not create requester store: %w", err) + } receiptRequester, err = requester.New( node.Logger.With().Str("entity", "receipt").Logger(), node.Metrics.Engine, node.EngineRegistry, node.Me, node.State, + fifoStore, channels.RequestReceiptsByBlockID, filter.HasRole[flow.Identity](flow.RoleExecution), func() flow.Entity { return new(flow.ExecutionReceipt) }, diff --git a/cmd/execution_builder.go b/cmd/execution_builder.go index e79a8a4aea8..470345f8834 100644 --- a/cmd/execution_builder.go +++ b/cmd/execution_builder.go @@ -63,11 +63,9 @@ import ( "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/storage/snapshot" "github.com/onflow/flow-go/fvm/systemcontracts" - ledgerpkg "github.com/onflow/flow-go/ledger" - "github.com/onflow/flow-go/ledger/common/pathfinder" - ledger "github.com/onflow/flow-go/ledger/complete" + "github.com/onflow/flow-go/ledger" "github.com/onflow/flow-go/ledger/complete/wal" - bootstrapFilenames "github.com/onflow/flow-go/model/bootstrap" + ledgerfactory "github.com/onflow/flow-go/ledger/factory" modelbootstrap "github.com/onflow/flow-go/model/bootstrap" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/flow/filter" @@ -78,9 +76,7 @@ import ( exedataprovider "github.com/onflow/flow-go/module/executiondatasync/provider" "github.com/onflow/flow-go/module/executiondatasync/pruner" edstorage "github.com/onflow/flow-go/module/executiondatasync/storage" - execdatastorage "github.com/onflow/flow-go/module/executiondatasync/storage" "github.com/onflow/flow-go/module/executiondatasync/tracker" - "github.com/onflow/flow-go/module/finalizedreader" finalizer "github.com/onflow/flow-go/module/finalizer/consensus" "github.com/onflow/flow-go/module/mempool/queue" "github.com/onflow/flow-go/module/metrics" @@ -133,7 +129,7 @@ type ExecutionNode struct { executionState state.ExecutionState followerState protocol.FollowerState committee hotstuff.DynamicCommittee - ledgerStorage *ledger.Ledger + ledgerStorage ledger.Ledger registerStore *storehouse.RegisterStore // storage @@ -163,18 +159,24 @@ type ExecutionNode struct { scriptsEng *scripts.Engine followerDistributor *pubsub.FollowerDistributor checkAuthorizedAtBlock func(blockID flow.Identifier) (bool, error) - diskWAL *wal.DiskWAL blockDataUploader *uploader.Manager executionDataStore execution_data.ExecutionDataStore toTriggerCheckpoint *atomic.Bool // create the checkpoint trigger to be controlled by admin tool, and listened by the compactor stopControl *stop.StopControl // stop the node at given block height - executionDataDatastore execdatastorage.DatastoreManager + executionDataDatastore edstorage.DatastoreManager executionDataPruner *pruner.Pruner executionDataBlobstore blobs.Blobstore executionDataTracker tracker.Storage blobService network.BlobService blobserviceDependable *module.ProxiedReadyDoneAware metricsProvider txmetrics.TransactionExecutionMetricsProvider + + // used by ingestion engine to notify executed block, and + // used by background indexer engine to trigger indexing + blockExecutedNotifier *ingestion.BlockExecutedNotifier + + // save register updates in storehouse when it is not enabled + backgroundIndexerEngine *storehouse.BackgroundIndexerEngine } func (builder *ExecutionNodeBuilder) LoadComponentsAndModules() { @@ -191,7 +193,7 @@ func (builder *ExecutionNodeBuilder) LoadComponentsAndModules() { return stateSyncCommands.NewReadExecutionDataCommand(exeNode.executionDataStore) }). AdminCommand("trigger-checkpoint", func(config *NodeConfig) commands.AdminCommand { - return executionCommands.NewTriggerCheckpointCommand(exeNode.toTriggerCheckpoint) + return executionCommands.NewTriggerCheckpointCommand(exeNode.toTriggerCheckpoint, exeNode.exeConf.ledgerServiceAddr, exeNode.exeConf.ledgerServiceAdminAddr) }). AdminCommand("stop-at-height", func(config *NodeConfig) commands.AdminCommand { return executionCommands.NewStopAtHeightCommand(exeNode.stopControl) @@ -215,6 +217,7 @@ func (builder *ExecutionNodeBuilder) LoadComponentsAndModules() { Module("sync core", exeNode.LoadSyncCore). Module("execution storage", exeNode.LoadExecutionStorage). Module("follower distributor", exeNode.LoadFollowerDistributor). + Module("block executed notifier", exeNode.LoadBlockExecutedNotifier). Module("authorization checking function", exeNode.LoadAuthorizationCheckingFunction). Module("execution data datastore", exeNode.LoadExecutionDataDatastore). Module("execution data getter", exeNode.LoadExecutionDataGetter). @@ -239,7 +242,6 @@ func (builder *ExecutionNodeBuilder) LoadComponentsAndModules() { "chunk_data_pack", exeNode.chunkDataPackDB) }). Component("stop control", exeNode.LoadStopControl). - Component("execution state ledger WAL compactor", exeNode.LoadExecutionStateLedgerWALCompactor). // disable execution data pruner for now, since storehouse is going to need the execution data // for recovery, // TODO: will re-visit this once storehouse has implemented new WAL for checkpoint file of @@ -262,6 +264,11 @@ func (builder *ExecutionNodeBuilder) LoadComponentsAndModules() { Component("receipt provider engine", exeNode.LoadReceiptProviderEngine). Component("synchronization engine", exeNode.LoadSynchronizationEngine). Component("grpc server", exeNode.LoadGrpcServer) + + // Only load background indexer engine when both flags indicate it should be enabled + if !exeNode.exeConf.enableStorehouse && exeNode.exeConf.enableBackgroundStorehouseIndexing { + builder.FlowNodeBuilder.Component("background indexer engine", exeNode.LoadBackgroundIndexerEngine) + } } func (exeNode *ExecutionNode) LoadCollections(node *NodeConfig) error { @@ -360,6 +367,18 @@ func (exeNode *ExecutionNode) LoadFollowerDistributor(node *NodeConfig) error { return nil } +func (exeNode *ExecutionNode) LoadBlockExecutedNotifier(node *NodeConfig) error { + // background storehouse indexing is the only consumer of this notifier, + // only create the notifier when background storehouse indexing is enabled + if !exeNode.exeConf.enableBackgroundStorehouseIndexing { + return nil + } + + exeNode.blockExecutedNotifier = ingestion.NewBlockExecutedNotifier() + + return nil +} + func (exeNode *ExecutionNode) LoadBlobService( node *NodeConfig, ) ( @@ -580,10 +599,15 @@ func (exeNode *ExecutionNode) LoadProviderEngine( node.RootChainID, exeNode.exeConf.computationConfig.ExtensiveTracing, exeNode.exeConf.scheduleCallbacksEnabled, + exeNode.exeConf.tokenTrackingEnabled, )..., ) - vmCtx := fvm.NewContext(opts...) + if exeNode.exeConf.tokenTrackingEnabled { + node.Logger.Info().Str("module", "transaction-inspection").Msg("transaction inspection enabled") + } + + vmCtx := fvm.NewContext(node.RootChainID.Chain(), opts...) var collector module.ExecutionMetrics collector = exeNode.collector @@ -603,6 +627,7 @@ func (exeNode *ExecutionNode) LoadProviderEngine( } ledgerViewCommitter := committer.NewLedgerViewCommitter(exeNode.ledgerStorage, node.Tracer) + exeNode.exeConf.computationConfig.TokenTrackingEnabled = exeNode.exeConf.tokenTrackingEnabled manager, err := computation.New( node.Logger, collector, @@ -656,14 +681,8 @@ func (exeNode *ExecutionNode) LoadProviderEngine( blockSnapshot, _, err := exeNode.executionState.CreateStorageSnapshot(blockID) if err != nil { - tries, _ := exeNode.ledgerStorage.Tries() - trieInfo := "empty" - if len(tries) > 0 { - trieInfo = fmt.Sprintf("length: %v, 1st: %v, last: %v", len(tries), tries[0].RootHash(), tries[len(tries)-1].RootHash()) - } - - return nil, fmt.Errorf("cannot create a storage snapshot at block %v at height %v, trie: %s: %w", blockID, - height, trieInfo, err) + return nil, fmt.Errorf("cannot create a storage snapshot at block %v at height %v : %w", blockID, + height, err) } // Get the epoch counter from the smart contract at the last executed block. @@ -863,77 +882,30 @@ func (exeNode *ExecutionNode) LoadRegisterStore( ) error { if !exeNode.exeConf.enableStorehouse { node.Logger.Info().Msg("register store disabled") + exeNode.registerStore = nil return nil } - node.Logger.Info(). - Str("pebble_db_path", exeNode.exeConf.registerDir). - Msg("register store enabled") - pebbledb, err := storagepebble.OpenRegisterPebbleDB( - node.Logger.With().Str("pebbledb", "registers").Logger(), - exeNode.exeConf.registerDir) - - if err != nil { - return fmt.Errorf("could not create disk register store: %w", err) - } - - // close pebble db on shut down - exeNode.builder.ShutdownFunc(func() error { - err := pebbledb.Close() - if err != nil { - return fmt.Errorf("could not close register store: %w", err) - } - return nil - }) - - bootstrapped, err := storagepebble.IsBootstrapped(pebbledb) - if err != nil { - return fmt.Errorf("could not check if registers db is bootstrapped: %w", err) - } - - node.Logger.Info().Msgf("register store bootstrapped: %v", bootstrapped) - - if !bootstrapped { - checkpointFile := path.Join(exeNode.exeConf.triedir, modelbootstrap.FilenameWALRootCheckpoint) - sealedRoot := node.State.Params().SealedRoot() - - rootSeal := node.State.Params().Seal() - - if sealedRoot.ID() != rootSeal.BlockID { - return fmt.Errorf("mismatching root seal and sealed root: %v != %v", sealedRoot.ID(), rootSeal.BlockID) - } - - checkpointHeight := sealedRoot.Height - rootHash := ledgerpkg.RootHash(rootSeal.FinalState) - - err = bootstrap.ImportRegistersFromCheckpoint(node.Logger, checkpointFile, checkpointHeight, rootHash, pebbledb, exeNode.exeConf.importCheckpointWorkerCount) - if err != nil { - return fmt.Errorf("could not import registers from checkpoint: %w", err) - } - } - diskStore, err := storagepebble.NewRegisters(pebbledb, storagepebble.PruningDisabled) - if err != nil { - return fmt.Errorf("could not create registers storage: %w", err) - } - - reader := finalizedreader.NewFinalizedReader(node.Storage.Headers, node.LastFinalizedHeader.Height) - node.ProtocolEvents.AddConsumer(reader) - notifier := storehouse.NewRegisterStoreMetrics(exeNode.collector) - - // report latest finalized and executed height as metrics - notifier.OnFinalizedAndExecutedHeightUpdated(diskStore.LatestHeight()) - - registerStore, err := storehouse.NewRegisterStore( - diskStore, - nil, // TODO: replace with real WAL - reader, + registerStore, closer, err := storehouse.LoadRegisterStore( node.Logger, - notifier, + node.State, + node.Storage.Headers, + node.ProtocolEvents, + node.LastFinalizedHeader.Height, + exeNode.collector, + exeNode.exeConf.registerDir, + exeNode.exeConf.triedir, + exeNode.exeConf.importCheckpointWorkerCount, + bootstrap.ImportRegistersFromCheckpoint, ) if err != nil { return err } + if closer != nil { + exeNode.builder.ShutdownFunc(closer.Close) + } + exeNode.registerStore = registerStore return nil } @@ -944,36 +916,27 @@ func (exeNode *ExecutionNode) LoadExecutionStateLedger( module.ReadyDoneAware, error, ) { - // DiskWal is a dependent component because we need to ensure - // that all WAL updates are completed before closing opened WAL segment. - var err error - exeNode.diskWAL, err = wal.NewDiskWAL(node.Logger.With().Str("subcomponent", "wal").Logger(), - node.MetricsRegisterer, exeNode.collector, exeNode.exeConf.triedir, int(exeNode.exeConf.mTrieCacheSize), pathfinder.PathByteSize, wal.SegmentSize) + // Create ledger using factory + ledgerStorage, err := ledgerfactory.NewLedger(ledgerfactory.Config{ + LedgerServiceAddr: exeNode.exeConf.ledgerServiceAddr, + LedgerMaxRequestSize: exeNode.exeConf.ledgerMaxRequestSize, + LedgerMaxResponseSize: exeNode.exeConf.ledgerMaxResponseSize, + Triedir: exeNode.exeConf.triedir, + MTrieCacheSize: exeNode.exeConf.mTrieCacheSize, + CheckpointDistance: exeNode.exeConf.checkpointDistance, + CheckpointsToKeep: exeNode.exeConf.checkpointsToKeep, + MetricsRegisterer: node.MetricsRegisterer, + WALMetrics: exeNode.collector, + LedgerMetrics: exeNode.collector, + Logger: node.Logger, + }, exeNode.toTriggerCheckpoint) if err != nil { - return nil, fmt.Errorf("failed to initialize wal: %w", err) + return nil, err } - exeNode.ledgerStorage, err = ledger.NewLedger(exeNode.diskWAL, int(exeNode.exeConf.mTrieCacheSize), exeNode.collector, node.Logger.With().Str("subcomponent", - "ledger").Logger(), ledger.DefaultPathFinderVersion) - return exeNode.ledgerStorage, err -} + exeNode.ledgerStorage = ledgerStorage -func (exeNode *ExecutionNode) LoadExecutionStateLedgerWALCompactor( - node *NodeConfig, -) ( - module.ReadyDoneAware, - error, -) { - return ledger.NewCompactor( - exeNode.ledgerStorage, - exeNode.diskWAL, - node.Logger.With().Str("subcomponent", "checkpointer").Logger(), - uint(exeNode.exeConf.mTrieCacheSize), - exeNode.exeConf.checkpointDistance, - exeNode.exeConf.checkpointsToKeep, - exeNode.toTriggerCheckpoint, // compactor will listen to the signal from admin tool for force triggering checkpointing - exeNode.collector, - ) + return exeNode.ledgerStorage, nil } func (exeNode *ExecutionNode) LoadExecutionDataPruner( @@ -1102,15 +1065,17 @@ func (exeNode *ExecutionNode) LoadIngestionEngine( colFetcher = accessFetcher exeNode.collectionRequester = accessFetcher } else { + fifoStore, err := engine.NewFifoMessageStore(requester.DefaultEntityRequestCacheSize) + if err != nil { + return nil, fmt.Errorf("could not create requester store: %w", err) + } reqEng, err := requester.New(node.Logger.With().Str("entity", "collection").Logger(), node.Metrics.Engine, node.EngineRegistry, node.Me, node.State, + fifoStore, channels.RequestCollections, filter.Any, func() flow.Entity { return new(flow.Collection) }, // we are manually triggering batches in execution, but lets still send off a batch once a minute, as a safety net for the sake of retries requester.WithBatchInterval(exeNode.exeConf.requestInterval), - // consistency of collection can be checked by checking hash, and hash comes from trusted source (blocks from consensus follower) - // hence we not need to check origin - requester.WithValidateStaking(false), // we have observed execution nodes occasionally fail to retrieve collections using this engine, which can cause temporary execution halts // setting a retry maximum of 10s results in a much faster recovery from these faults (default is 2m) requester.WithRetryMaximum(10*time.Second), @@ -1124,6 +1089,11 @@ func (exeNode *ExecutionNode) LoadIngestionEngine( exeNode.collectionRequester = reqEng } + var blockExecutedCallback ingestion.BlockExecutedCallback + if exeNode.blockExecutedNotifier != nil { + blockExecutedCallback = exeNode.blockExecutedNotifier.OnExecuted + } + _, core, err := ingestion.NewMachine( node.Logger, node.ProtocolEvents, @@ -1139,6 +1109,7 @@ func (exeNode *ExecutionNode) LoadIngestionEngine( exeNode.providerEngine, exeNode.blockDataUploader, exeNode.stopControl, + blockExecutedCallback, ) return core, err @@ -1389,6 +1360,42 @@ func (exeNode *ExecutionNode) LoadGrpcServer( ), nil } +func (exeNode *ExecutionNode) LoadBackgroundIndexerEngine( + node *NodeConfig, +) ( + module.ReadyDoneAware, + error, +) { + engine, created, err := storehouse.LoadBackgroundIndexerEngine( + node.Logger, + exeNode.exeConf.enableBackgroundStorehouseIndexing, + node.State, + node.Storage.Headers, + node.ProtocolEvents, + node.LastFinalizedHeader.Height, + exeNode.collector, + exeNode.exeConf.registerDir, + exeNode.exeConf.triedir, + exeNode.exeConf.importCheckpointWorkerCount, + bootstrap.ImportRegistersFromCheckpoint, + exeNode.executionDataStore, + exeNode.resultsReader, + exeNode.blockExecutedNotifier, + exeNode.followerDistributor, + exeNode.exeConf.backgroundIndexerHeightsPerSecond, + ) + if err != nil { + return nil, err + } + + if !created { + return &module.NoopReadyDoneAware{}, nil + } + + exeNode.backgroundIndexerEngine = engine + return engine, nil +} + func (exeNode *ExecutionNode) LoadBootstrapper(node *NodeConfig) error { // check if the execution database already exists @@ -1409,9 +1416,9 @@ func (exeNode *ExecutionNode) LoadBootstrapper(node *NodeConfig) error { err := wal.CheckpointHasRootHash( node.Logger, - path.Join(node.BootstrapDir, bootstrapFilenames.DirnameExecutionState), - bootstrapFilenames.FilenameWALRootCheckpoint, - ledgerpkg.RootHash(node.RootSeal.FinalState), + path.Join(node.BootstrapDir, modelbootstrap.DirnameExecutionState), + modelbootstrap.FilenameWALRootCheckpoint, + ledger.RootHash(node.RootSeal.FinalState), ) if err != nil { return err @@ -1488,18 +1495,18 @@ func copyBootstrapState(dir, trie string) error { firstCheckpointFilename := "00000000" fileExists := func(fileName string) bool { - _, err := os.Stat(filepath.Join(dir, bootstrapFilenames.DirnameExecutionState, fileName)) + _, err := os.Stat(filepath.Join(dir, modelbootstrap.DirnameExecutionState, fileName)) return err == nil } // if there is a root checkpoint file, then copy that file over - if fileExists(bootstrapFilenames.FilenameWALRootCheckpoint) { - filename = bootstrapFilenames.FilenameWALRootCheckpoint + if fileExists(modelbootstrap.FilenameWALRootCheckpoint) { + filename = modelbootstrap.FilenameWALRootCheckpoint } else if fileExists(firstCheckpointFilename) { // else if there is a checkpoint file, then copy that file over filename = firstCheckpointFilename } else { - filePath := filepath.Join(dir, bootstrapFilenames.DirnameExecutionState, firstCheckpointFilename) + filePath := filepath.Join(dir, modelbootstrap.DirnameExecutionState, firstCheckpointFilename) // include absolute path of the missing file in the error message absPath, err := filepath.Abs(filePath) @@ -1511,7 +1518,7 @@ func copyBootstrapState(dir, trie string) error { } // copy from the bootstrap folder to the execution state folder - from, to := path.Join(dir, bootstrapFilenames.DirnameExecutionState), trie + from, to := path.Join(dir, modelbootstrap.DirnameExecutionState), trie log.Info().Str("dir", dir).Str("trie", trie). Msgf("linking checkpoint file %v from directory: %v, to: %v", filename, from, to) diff --git a/cmd/execution_config.go b/cmd/execution_config.go index 1ce7427f9ec..00ddf2d1bc6 100644 --- a/cmd/execution_config.go +++ b/cmd/execution_config.go @@ -17,8 +17,10 @@ import ( exeprovider "github.com/onflow/flow-go/engine/execution/provider" exepruner "github.com/onflow/flow-go/engine/execution/pruner" "github.com/onflow/flow-go/engine/execution/rpc" + "github.com/onflow/flow-go/engine/execution/storehouse" "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/storage/derived" + "github.com/onflow/flow-go/ledger" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/executiondatasync/execution_data" "github.com/onflow/flow-go/module/mempool" @@ -60,6 +62,7 @@ type ExecutionConfig struct { transactionExecutionMetricsEnabled bool transactionExecutionMetricsBufferSize uint scheduleCallbacksEnabled bool + tokenTrackingEnabled bool computationConfig computation.ComputationConfig receiptRequestWorkers uint // common provider engine workers @@ -69,15 +72,22 @@ type ExecutionConfig struct { // It works around an issue where some collection nodes are not configured with enough // this works around an issue where some collection nodes are not configured with enough // file descriptors causing connection failures. - onflowOnlyLNs bool - enableStorehouse bool - enableChecker bool - publicAccessID string + onflowOnlyLNs bool + enableStorehouse bool + enableBackgroundStorehouseIndexing bool + backgroundIndexerHeightsPerSecond uint64 + enableChecker bool + publicAccessID string pruningConfigThreshold uint64 pruningConfigBatchSize uint pruningConfigSleepAfterCommit time.Duration pruningConfigSleepAfterIteration time.Duration + + ledgerServiceAddr string // gRPC address for remote ledger service (empty means use local ledger) + ledgerServiceAdminAddr string // Admin HTTP address for remote ledger service (for trigger-checkpoint command) + ledgerMaxRequestSize uint // Maximum request message size in bytes for remote ledger client (0 = default 1 GiB) + ledgerMaxResponseSize uint // Maximum response message size in bytes for remote ledger client (0 = default 1 GiB) } func (exeConf *ExecutionConfig) SetupFlags(flags *pflag.FlagSet) { @@ -94,9 +104,9 @@ func (exeConf *ExecutionConfig) SetupFlags(flags *pflag.FlagSet) { flags.StringVar(&exeConf.triedir, "triedir", filepath.Join(datadir, "trie"), "directory to store the execution State") flags.StringVar(&exeConf.executionDataDir, "execution-data-dir", filepath.Join(datadir, "execution_data"), "directory to use for storing Execution Data") flags.StringVar(&exeConf.registerDir, "register-dir", filepath.Join(datadir, "register"), "directory to use for storing registers Data") - flags.Uint32Var(&exeConf.mTrieCacheSize, "mtrie-cache-size", 500, "cache size for MTrie") - flags.UintVar(&exeConf.checkpointDistance, "checkpoint-distance", 20, "number of WAL segments between checkpoints") - flags.UintVar(&exeConf.checkpointsToKeep, "checkpoints-to-keep", 5, "number of recent checkpoints to keep (0 to keep all)") + flags.Uint32Var(&exeConf.mTrieCacheSize, "mtrie-cache-size", ledger.DefaultMTrieCacheSize, "cache size for MTrie") + flags.UintVar(&exeConf.checkpointDistance, "checkpoint-distance", ledger.DefaultCheckpointDistance, "number of WAL segments between checkpoints") + flags.UintVar(&exeConf.checkpointsToKeep, "checkpoints-to-keep", ledger.DefaultCheckpointsToKeep, "number of recent checkpoints to keep (0 to keep all)") flags.UintVar(&exeConf.computationConfig.DerivedDataCacheSize, "cadence-execution-cache", derived.DefaultDerivedDataCacheSize, "cache size for Cadence execution") flags.BoolVar(&exeConf.computationConfig.ExtensiveTracing, "extensive-tracing", false, "adds high-overhead tracing to execution") @@ -144,8 +154,11 @@ func (exeConf *ExecutionConfig) SetupFlags(flags *pflag.FlagSet) { flags.BoolVar(&exeConf.onflowOnlyLNs, "temp-onflow-only-lns", false, "do not use unless required. forces node to only request collections from onflow collection nodes") flags.BoolVar(&exeConf.enableStorehouse, "enable-storehouse", false, "enable storehouse to store registers on disk, default is false") + flags.BoolVar(&exeConf.enableBackgroundStorehouseIndexing, "enable-background-storehouse-indexing", false, "enable background indexing of storehouse data while storehouse is disabled to eliminate downtime when enabling it. default: false.") + flags.Uint64Var(&exeConf.backgroundIndexerHeightsPerSecond, "background-indexer-heights-per-second", storehouse.DefaultHeightsPerSecond, fmt.Sprintf("rate limit for background indexer in heights per second. 0 means no rate limiting. default: %v", storehouse.DefaultHeightsPerSecond)) flags.BoolVar(&exeConf.enableChecker, "enable-checker", true, "enable checker to check the correctness of the execution result, default is true") flags.BoolVar(&exeConf.scheduleCallbacksEnabled, "scheduled-callbacks-enabled", fvm.DefaultScheduledTransactionsEnabled, "[deprecated] enable execution of scheduled transactions") + flags.BoolVar(&exeConf.tokenTrackingEnabled, "token-tracking-enabled", false, "enable tracking and logging of token moves on transactions") // deprecated. Retain it to prevent nodes that previously had this configuration from crashing. var deprecatedEnableNewIngestionEngine bool flags.BoolVar(&deprecatedEnableNewIngestionEngine, "enable-new-ingestion-engine", true, "enable new ingestion engine, default is true") @@ -155,6 +168,10 @@ func (exeConf *ExecutionConfig) SetupFlags(flags *pflag.FlagSet) { flags.UintVar(&exeConf.pruningConfigBatchSize, "pruning-config-batch-size", exepruner.DefaultConfig.BatchSize, "the batch size is the number of blocks that we want to delete in one batch, default 1200") flags.DurationVar(&exeConf.pruningConfigSleepAfterCommit, "pruning-config-sleep-after-commit", exepruner.DefaultConfig.SleepAfterEachBatchCommit, "sleep time after each batch commit, default 1s") flags.DurationVar(&exeConf.pruningConfigSleepAfterIteration, "pruning-config-sleep-after-iteration", exepruner.DefaultConfig.SleepAfterEachIteration, "sleep time after each iteration, default max int64") + flags.StringVar(&exeConf.ledgerServiceAddr, "ledger-service-addr", "", "gRPC address for remote ledger service (TCP: e.g., localhost:9000, or Unix socket: unix:///path/to/socket). If empty, uses local ledger") + flags.StringVar(&exeConf.ledgerServiceAdminAddr, "ledger-service-admin-addr", "", "admin HTTP address for remote ledger service (e.g., localhost:9003). Used to provide helpful error messages when trigger-checkpoint is called in remote mode") + flags.UintVar(&exeConf.ledgerMaxRequestSize, "ledger-max-request-size", 0, "maximum request message size in bytes for remote ledger client (0 = default 1 GiB)") + flags.UintVar(&exeConf.ledgerMaxResponseSize, "ledger-max-response-size", 0, "maximum response message size in bytes for remote ledger client (0 = default 1 GiB)") } func (exeConf *ExecutionConfig) ValidateFlags() error { @@ -177,5 +194,9 @@ func (exeConf *ExecutionConfig) ValidateFlags() error { if exeConf.rpcConf.MaxResponseMsgSize == 0 { return errors.New("rpc-max-response-message-size must be greater than 0") } + // Explicitly turn off background storehouse indexing when storehouse is enabled + if exeConf.enableStorehouse { + exeConf.enableBackgroundStorehouseIndexing = false + } return nil } diff --git a/cmd/ledger/README.md b/cmd/ledger/README.md new file mode 100644 index 00000000000..b71e7573c14 --- /dev/null +++ b/cmd/ledger/README.md @@ -0,0 +1,103 @@ +# Ledger Service + +A standalone gRPC service that provides remote access to ledger operations. + +## Building + +The protobuf code must be generated first: + +```bash +cd ledger/protobuf +buf generate +``` + +Then build the service: + +```bash +go build -o flow-ledger-service ./cmd/ledger +``` + +## Running + +```bash +# Listen on TCP only +./flow-ledger-service \ + -triedir /path/to/trie \ + -ledger-service-tcp 0.0.0.0:9000 + +# Listen on Unix socket only +./flow-ledger-service \ + -triedir /path/to/trie \ + -ledger-service-socket /sockets/ledger.sock + +# Listen on both TCP and Unix socket +./flow-ledger-service \ + -triedir /path/to/trie \ + -ledger-service-tcp 0.0.0.0:9000 \ + -ledger-service-socket /sockets/ledger.sock \ + -mtrie-cache-size 500 \ + -checkpoint-distance 100 \ + -checkpoints-to-keep 3 + +# With admin server enabled (use port 9003 to avoid conflict with execution node's 9002) +./flow-ledger-service \ + -triedir /path/to/trie \ + -ledger-service-tcp 0.0.0.0:9000 \ + -admin-addr 0.0.0.0:9003 +``` + +## Flags + +- `-triedir`: Directory for trie files (required) +- `-ledger-service-tcp`: TCP listen address (e.g., 0.0.0.0:9000). If provided, server accepts TCP connections. +- `-ledger-service-socket`: Unix socket path (e.g., /sockets/ledger.sock). If provided, server accepts Unix socket connections. Can specify multiple sockets separated by comma. +- **Note**: At least one of `-ledger-service-tcp` or `-ledger-service-socket` must be provided. +- `-admin-addr`: Address to bind on for admin HTTP server (e.g., 0.0.0.0:9003). If provided, enables admin commands. Use a different port than the execution node's admin server (default 9002). Optional. +- `-mtrie-cache-size`: MTrie cache size - number of tries (default: 500) +- `-checkpoint-distance`: Checkpoint distance (default: 100) +- `-checkpoints-to-keep`: Number of checkpoints to keep (default: 3) +- `-max-request-size`: Maximum request message size in bytes (default: 1 GiB) +- `-max-response-size`: Maximum response message size in bytes (default: 1 GiB) +- `-loglevel`: Log level (panic, fatal, error, warn, info, debug) (default: info) + +## Admin Commands + +When `-admin-addr` is provided, the service exposes an HTTP admin API for managing the ledger service. + +### Available Commands + +- `trigger-checkpoint`: Triggers a checkpoint to be created as soon as the current WAL segment file is finished writing. This is useful for manually creating checkpoints without waiting for the automatic checkpoint distance. +- `ping`: Simple health check command to verify the admin server is responsive. +- `list-commands`: Lists all available admin commands. + +**Examples:** +```bash +# Trigger a checkpoint +curl -X POST http://localhost:9003/admin/run_command \ + -H "Content-Type: application/json" \ + -d '{"commandName": "trigger-checkpoint", "data": {}}' + +# Ping the admin server +curl -X POST http://localhost:9003/admin/run_command \ + -H "Content-Type: application/json" \ + -d '{"commandName": "ping", "data": {}}' + +# List all available commands +curl -X POST http://localhost:9003/admin/run_command \ + -H "Content-Type: application/json" \ + -d '{"commandName": "list-commands", "data": {}}' +``` + +**Note:** When running an execution node with a remote ledger service (using `--ledger-service-addr`), the `trigger-checkpoint` command on the execution node is disabled. You must use the ledger service's admin endpoint to trigger checkpoints. + +## API + +The service implements the `LedgerService` gRPC interface defined in `ledger/protobuf/ledger.proto`: + +- `InitialState()` - Returns the initial state of the ledger +- `HasState()` - Checks if a state exists +- `GetSingleValue()` - Gets a single value for a key +- `Get()` - Gets multiple values for keys +- `Set()` - Updates keys with new values +- `Prove()` - Generates proofs for keys + diff --git a/cmd/ledger/admin.go b/cmd/ledger/admin.go new file mode 100644 index 00000000000..607d9968b7a --- /dev/null +++ b/cmd/ledger/admin.go @@ -0,0 +1,96 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/rs/zerolog" + "go.uber.org/atomic" +) + +// adminRequest represents the JSON request body for admin commands. +// This matches the format used by the execution node's admin framework. +type adminRequest struct { + CommandName string `json:"commandName"` + Data json.RawMessage `json:"data,omitempty"` +} + +// adminResponse represents the JSON response for admin commands. +// This matches the format used by the execution node's admin framework. +type adminResponse struct { + Output any `json:"output,omitempty"` + Error string `json:"error,omitempty"` +} + +// adminHandler is a simple HTTP-only admin server for the ledger service. +// Unlike the execution node's admin framework (which uses gRPC + HTTP gateway), +// this directly handles HTTP requests without the gRPC proxy layer. +type adminHandler struct { + logger zerolog.Logger + triggerCheckpoint *atomic.Bool + commands []string +} + +// newAdminHandler creates a new admin HTTP handler. +func newAdminHandler(logger zerolog.Logger, triggerCheckpoint *atomic.Bool) http.Handler { + h := &adminHandler{ + logger: logger.With().Str("component", "admin").Logger(), + triggerCheckpoint: triggerCheckpoint, + commands: []string{"ping", "list-commands", "trigger-checkpoint"}, + } + + mux := http.NewServeMux() + mux.HandleFunc("/admin/run_command", h.handleCommand) + return mux +} + +func (h *adminHandler) handleCommand(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + + if r.Method != http.MethodPost { + h.writeError(w, http.StatusMethodNotAllowed, "method not allowed, use POST") + return + } + + var req adminRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + h.writeError(w, http.StatusBadRequest, fmt.Sprintf("invalid JSON: %v", err)) + return + } + + h.logger.Info().Str("command", req.CommandName).Msg("received admin command") + + var result any + + switch req.CommandName { + case "ping": + result = "pong" + + case "list-commands": + result = h.commands + + case "trigger-checkpoint": + if h.triggerCheckpoint.CompareAndSwap(false, true) { + h.logger.Info().Msg("trigger checkpoint as soon as finishing writing the current segment file") + result = "ok" + } else { + result = "checkpoint already triggered" + } + + default: + h.writeError(w, http.StatusBadRequest, fmt.Sprintf("unknown command: %s", req.CommandName)) + return + } + + h.writeSuccess(w, result) +} + +func (h *adminHandler) writeError(w http.ResponseWriter, status int, msg string) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(adminResponse{Error: msg}) +} + +func (h *adminHandler) writeSuccess(w http.ResponseWriter, output any) { + _ = json.NewEncoder(w).Encode(adminResponse{Output: output}) +} diff --git a/cmd/ledger/main.go b/cmd/ledger/main.go new file mode 100644 index 00000000000..0dd48ca6b98 --- /dev/null +++ b/cmd/ledger/main.go @@ -0,0 +1,305 @@ +package main + +import ( + "context" + "flag" + "fmt" + "net" + "net/http" + "os" + "os/signal" + "path/filepath" + "strings" + "syscall" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/zerolog" + "go.uber.org/atomic" + "google.golang.org/grpc" + + ledgerfactory "github.com/onflow/flow-go/ledger/factory" + ledgerpb "github.com/onflow/flow-go/ledger/protobuf" + "github.com/onflow/flow-go/ledger/remote" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/metrics" +) + +var ( + triedir = flag.String("triedir", "", "Directory for trie files (required)") + ledgerServiceTCP = flag.String("ledger-service-tcp", "", "Ledger service TCP listen address (e.g., 0.0.0.0:9000). If provided, server accepts TCP connections.") + ledgerServiceSocket = flag.String("ledger-service-socket", "", "Ledger service Unix socket path (e.g., /sockets/ledger.sock). If provided, server accepts Unix socket connections. Can specify multiple sockets separated by comma.") + adminAddr = flag.String("admin-addr", "", "Address to bind on for admin HTTP server (e.g., 0.0.0.0:9003). If provided, enables admin commands. Use a different port than the execution node's admin server (default 9002).") + metricsPort = flag.Uint("metrics-port", 0, "Port for Prometheus metrics server (e.g., 8080). If 0, metrics server is disabled.") + mtrieCacheSize = flag.Int("mtrie-cache-size", 500, "MTrie cache size (number of tries)") + checkpointDist = flag.Uint("checkpoint-distance", 100, "Checkpoint distance") + checkpointsToKeep = flag.Uint("checkpoints-to-keep", 3, "Number of checkpoints to keep") + logLevel = flag.String("loglevel", "info", "Log level (panic, fatal, error, warn, info, debug)") + maxRequestSize = flag.Uint("max-request-size", 1<<30, "Maximum request message size in bytes (default: 1 GiB)") + maxResponseSize = flag.Uint("max-response-size", 1<<30, "Maximum response message size in bytes (default: 1 GiB)") +) + +func main() { + flag.Parse() + + if *triedir == "" { + fmt.Fprintf(os.Stderr, "error: --triedir is required\n") + os.Exit(1) + } + + // Parse and set log level + lvl, err := zerolog.ParseLevel(strings.ToLower(*logLevel)) + if err != nil { + fmt.Fprintf(os.Stderr, "error: invalid log level %q: %v\n", *logLevel, err) + os.Exit(1) + } + zerolog.SetGlobalLevel(lvl) + + logger := zerolog.New(os.Stderr).With(). + Timestamp(). + Str("service", "ledger"). + Logger() + + // Validate that at least one address is provided + if *ledgerServiceTCP == "" && *ledgerServiceSocket == "" { + logger.Fatal().Msg("at least one of --ledger-service-tcp or --ledger-service-socket must be provided") + } + + logger.Info(). + Str("triedir", *triedir). + Str("ledger_service_tcp", *ledgerServiceTCP). + Str("ledger_service_socket", *ledgerServiceSocket). + Str("admin_addr", *adminAddr). + Uint("metrics_port", *metricsPort). + Int("mtrie_cache_size", *mtrieCacheSize). + Msg("starting ledger service") + + // Create trigger for manual checkpointing (used by admin command) + triggerCheckpointOnNextSegmentFinish := atomic.NewBool(false) + + // Create ledger using factory + metricsCollector := metrics.NewLedgerCollector("ledger", "wal") + ledgerStorage, err := ledgerfactory.NewLedger(ledgerfactory.Config{ + Triedir: *triedir, + MTrieCacheSize: uint32(*mtrieCacheSize), + CheckpointDistance: *checkpointDist, + CheckpointsToKeep: *checkpointsToKeep, + MetricsRegisterer: prometheus.DefaultRegisterer, + WALMetrics: metricsCollector, + LedgerMetrics: metricsCollector, + Logger: logger, + }, triggerCheckpointOnNextSegmentFinish) + if err != nil { + logger.Fatal().Err(err).Msg("failed to create ledger") + } + + // Wait for ledger to be ready (WAL replay) + logger.Info().Msg("waiting for ledger initialization...") + <-ledgerStorage.Ready() + logger.Info().Msg("ledger ready") + + // Check if any trie is loaded after startup + stateCount := ledgerStorage.StateCount() + if stateCount == 0 { + logger.Fatal().Msg("no trie loaded after startup - no states available") + } + + // Get the last trie state for logging + lastState, err := ledgerStorage.StateByIndex(-1) + if err != nil { + logger.Fatal().Err(err).Msg("failed to get last state for logging") + } + logger.Info(). + Int("state_count", stateCount). + Str("last_state", lastState.String()). + Msg("ledger health check passed") + + // Create gRPC server with max message size configuration. + // Default to 1 GiB for responses (instead of standard 4 MiB) to handle large proofs that can exceed 4MB. + // This was increased to fix "grpc: received message larger than max" errors when generating + // proofs for blocks with many state changes. + grpcServer := grpc.NewServer( + grpc.MaxRecvMsgSize(int(*maxRequestSize)), + grpc.MaxSendMsgSize(int(*maxResponseSize)), + ) + + // Create and register ledger service + ledgerService := remote.NewService(ledgerStorage, logger) + ledgerpb.RegisterLedgerServiceServer(grpcServer, ledgerService) + + // Create listeners based on provided flags + type listenerInfo struct { + listener net.Listener + address string + socketPath string + isUnixSocket bool + } + var listeners []listenerInfo + var socketPaths []string + + // Create TCP listener if TCP address is provided + if *ledgerServiceTCP != "" { + lis, err := net.Listen("tcp", *ledgerServiceTCP) + if err != nil { + logger.Fatal().Err(err).Str("address", *ledgerServiceTCP).Msg("failed to listen on TCP") + } + + logger.Info().Str("address", *ledgerServiceTCP).Msg("gRPC server listening on TCP") + listeners = append(listeners, listenerInfo{ + listener: lis, + address: *ledgerServiceTCP, + socketPath: "", + isUnixSocket: false, + }) + } + + // Create Unix socket listeners if socket path(s) are provided + if *ledgerServiceSocket != "" { + // Support multiple socket paths separated by comma + socketPathsList := strings.Split(*ledgerServiceSocket, ",") + for _, socketPath := range socketPathsList { + socketPath = strings.TrimSpace(socketPath) + if socketPath == "" { + continue + } + + // Ensure the socket directory exists + socketDir := filepath.Dir(socketPath) + if socketDir != "" && socketDir != "." { + if err := os.MkdirAll(socketDir, 0755); err != nil { + logger.Fatal().Err(err).Str("socket_dir", socketDir).Msg("failed to create socket directory") + } + } + + // Clean up any existing socket file + if _, err := os.Stat(socketPath); err == nil { + logger.Info().Str("socket_path", socketPath).Msg("removing existing socket file") + if err := os.Remove(socketPath); err != nil { + logger.Warn().Err(err).Str("socket_path", socketPath).Msg("failed to remove existing socket file") + } + } + + lis, err := net.Listen("unix", socketPath) + if err != nil { + logger.Fatal().Err(err).Str("socket_path", socketPath).Msg("failed to listen on Unix socket") + } + + // Set socket file permissions (readable/writable by owner and group) + if err := os.Chmod(socketPath, 0660); err != nil { + logger.Warn().Err(err).Str("socket_path", socketPath).Msg("failed to set socket file permissions") + } + + logger.Info().Str("socket_path", socketPath).Msg("gRPC server listening on Unix domain socket") + socketPaths = append(socketPaths, socketPath) + listeners = append(listeners, listenerInfo{ + listener: lis, + address: socketPath, + socketPath: socketPath, + isUnixSocket: true, + }) + } + } + + // Set up metrics server if metrics port is provided + var metricsServer *metrics.Server + var metricsCancel context.CancelFunc + if *metricsPort > 0 { + metricsServer = metrics.NewServer(logger, *metricsPort) + + metricsCtx, cancel := context.WithCancel(context.Background()) + metricsCancel = cancel + + signalerCtx, errChan := irrecoverable.WithSignaler(metricsCtx) + go func() { + metricsServer.Start(signalerCtx) + select { + case err := <-errChan: + if err != nil { + logger.Error().Err(err).Msg("metrics server encountered irrecoverable error") + } + case <-metricsCtx.Done(): + } + }() + + <-metricsServer.Ready() + logger.Info().Uint("metrics_port", *metricsPort).Msg("metrics server started") + } + + // Set up simple HTTP admin server if admin address is provided + // This is a lightweight HTTP-only server (no gRPC proxy layer) + var adminServer *http.Server + if *adminAddr != "" { + adminHandler := newAdminHandler(logger, triggerCheckpointOnNextSegmentFinish) + adminServer = &http.Server{ + Addr: *adminAddr, + Handler: adminHandler, + } + + go func() { + logger.Info().Str("admin_addr", *adminAddr).Msg("starting admin HTTP server") + if err := adminServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + logger.Error().Err(err).Msg("admin HTTP server error") + } + }() + } + + // Start server on all listeners in separate goroutines + errCh := make(chan error, len(listeners)) + for _, info := range listeners { + go func() { + if err := grpcServer.Serve(info.listener); err != nil { + errCh <- fmt.Errorf("gRPC server error on %s: %w", info.address, err) + } + }() + } + + // Wait for interrupt signal or error + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) + + select { + case sig := <-sigCh: + logger.Info().Str("signal", sig.String()).Msg("received signal, shutting down") + case err := <-errCh: + logger.Error().Err(err).Msg("server error") + } + + // Graceful shutdown + logger.Info().Msg("shutting down gRPC server...") + grpcServer.GracefulStop() + + // Clean up Unix socket files + for _, socketPath := range socketPaths { + if socketPath != "" { + if err := os.Remove(socketPath); err != nil { + logger.Warn().Err(err).Str("socket_path", socketPath).Msg("failed to remove socket file") + } else { + logger.Info().Str("socket_path", socketPath).Msg("removed socket file") + } + } + } + + // Shutdown admin server if it was started + if adminServer != nil { + logger.Info().Msg("shutting down admin server...") + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer shutdownCancel() + if err := adminServer.Shutdown(shutdownCtx); err != nil { + logger.Warn().Err(err).Msg("admin server shutdown error") + } + logger.Info().Msg("admin server stopped") + } + + // Shutdown metrics server if it was started + if metricsServer != nil && metricsCancel != nil { + logger.Info().Msg("shutting down metrics server...") + metricsCancel() + <-metricsServer.Done() + logger.Info().Msg("metrics server stopped") + } + + logger.Info().Msg("waiting for ledger to stop...") + <-ledgerStorage.Done() + + logger.Info().Msg("ledger service stopped") +} diff --git a/cmd/node_builder.go b/cmd/node_builder.go index 2721552642c..bd1626cb627 100644 --- a/cmd/node_builder.go +++ b/cmd/node_builder.go @@ -5,7 +5,6 @@ import ( "time" "github.com/dgraph-io/badger/v2" - "github.com/jordanschalm/lockctx" madns "github.com/multiformats/go-multiaddr-dns" "github.com/onflow/crypto" "github.com/prometheus/client_golang/prometheus" @@ -205,7 +204,7 @@ type NodeConfig struct { ProtocolDB storage.DB SecretsDB *badger.DB Storage Storage - StorageLockMgr lockctx.Manager + StorageLockMgr storage.LockManager ProtocolEvents *events.Distributor State protocol.State Resolver madns.BasicResolver diff --git a/cmd/observer/node_builder/observer_builder.go b/cmd/observer/node_builder/observer_builder.go index 6cbaafbbda7..62a797ee62a 100644 --- a/cmd/observer/node_builder/observer_builder.go +++ b/cmd/observer/node_builder/observer_builder.go @@ -17,11 +17,13 @@ import ( "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" "github.com/libp2p/go-libp2p/core/peer" - "github.com/onflow/crypto" "github.com/rs/zerolog" "github.com/spf13/pflag" "google.golang.org/grpc/credentials" + "github.com/onflow/crypto" + + extendedbackend "github.com/onflow/flow-go/access/backends/extended" "github.com/onflow/flow-go/admin/commands" stateSyncCommands "github.com/onflow/flow-go/admin/commands/state_synchronization" "github.com/onflow/flow-go/cmd" @@ -48,6 +50,7 @@ import ( "github.com/onflow/flow-go/engine/access/rpc/backend/events" "github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator" "github.com/onflow/flow-go/engine/access/rpc/backend/query_mode" + txstatus "github.com/onflow/flow-go/engine/access/rpc/backend/transactions/status" rpcConnection "github.com/onflow/flow-go/engine/access/rpc/connection" "github.com/onflow/flow-go/engine/access/state_stream" statestreambackend "github.com/onflow/flow-go/engine/access/state_stream/backend" @@ -80,12 +83,15 @@ import ( finalizer "github.com/onflow/flow-go/module/finalizer/consensus" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/id" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/local" "github.com/onflow/flow-go/module/mempool/herocache" "github.com/onflow/flow-go/module/mempool/stdmap" "github.com/onflow/flow-go/module/metrics" "github.com/onflow/flow-go/module/state_synchronization" "github.com/onflow/flow-go/module/state_synchronization/indexer" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" + extendedbootstrap "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/bootstrap" edrequester "github.com/onflow/flow-go/module/state_synchronization/requester" consensus_follower "github.com/onflow/flow-go/module/upstream" "github.com/onflow/flow-go/network" @@ -93,6 +99,7 @@ import ( netcache "github.com/onflow/flow-go/network/cache" "github.com/onflow/flow-go/network/channels" "github.com/onflow/flow-go/network/converter" + "github.com/onflow/flow-go/network/message" "github.com/onflow/flow-go/network/p2p" "github.com/onflow/flow-go/network/p2p/blob" "github.com/onflow/flow-go/network/p2p/cache" @@ -112,6 +119,7 @@ import ( bstorage "github.com/onflow/flow-go/storage/badger" pstorage "github.com/onflow/flow-go/storage/pebble" "github.com/onflow/flow-go/storage/store" + "github.com/onflow/flow-go/utils" "github.com/onflow/flow-go/utils/grpcutils" "github.com/onflow/flow-go/utils/io" ) @@ -156,6 +164,9 @@ type ObserverServiceConfig struct { logTxTimeToSealed bool executionDataSyncEnabled bool executionDataIndexingEnabled bool + extendedIndexingEnabled bool + extendedIndexingBackfillDelay time.Duration + extendedIndexingDBPath string executionDataPrunerHeightRangeTarget uint64 executionDataPrunerThreshold uint64 executionDataPruningInterval time.Duration @@ -235,6 +246,8 @@ func DefaultObserverServiceConfig() *ObserverServiceConfig { logTxTimeToSealed: false, executionDataSyncEnabled: false, executionDataIndexingEnabled: false, + extendedIndexingEnabled: false, + extendedIndexingBackfillDelay: extended.DefaultBackfillDelay, executionDataPrunerHeightRangeTarget: 0, executionDataPrunerThreshold: pruner.DefaultThreshold, executionDataPruningInterval: pruner.DefaultPruningInterval, @@ -242,6 +255,7 @@ func DefaultObserverServiceConfig() *ObserverServiceConfig { versionControlEnabled: true, stopControlEnabled: false, executionDataDir: filepath.Join(homedir, ".flow", "execution_data"), + extendedIndexingDBPath: filepath.Join(homedir, ".flow", "indexer"), executionDataStartHeight: 0, executionDataConfig: edrequester.ExecutionDataConfig{ InitialBlockHeight: 0, @@ -280,6 +294,9 @@ type ObserverServiceBuilder struct { FollowerCore module.HotStuffFollower ExecutionIndexer *indexer.Indexer ExecutionIndexerCore *indexer.IndexerCore + ExtendedIndexer *extended.ExtendedIndexer + ExtendedBackend *extendedbackend.Backend + ExtendedStorage extendedbootstrap.Storage TxResultsIndex *index.TransactionResultsIndex IndexerDependencies *cmd.DependencyList VersionControl *version.VersionControl @@ -302,6 +319,7 @@ type ObserverServiceBuilder struct { events storage.Events lightTransactionResults storage.LightTransactionResults scheduledTransactions storage.ScheduledTransactions + lastFullBlockHeight *counters.PersistentStrictMonotonicCounter // available until after the network has started. Hence, a factory function that needs to be called just before // creating the sync engine @@ -325,6 +343,7 @@ type ObserverServiceBuilder struct { stateStreamGrpcServer *grpcserver.GrpcServer stateStreamBackend *statestreambackend.StateStreamBackend + streamLimiter *limiters.ConcurrencyLimiter } // deriveBootstrapPeerIdentities derives the Flow Identity of the bootstrap peers from the parameters. @@ -716,6 +735,21 @@ func (builder *ObserverServiceBuilder) extraFlags() { var builderExecutionDataDBMode string flags.StringVar(&builderExecutionDataDBMode, "execution-data-db", "pebble", "[deprecated] the DB type for execution datastore.") + // Extended Indexing + flags.BoolVar(&builder.extendedIndexingEnabled, + "extended-indexing-enabled", + defaultConfig.extendedIndexingEnabled, + "whether to enable account data indexing") + flags.DurationVar(&builder.extendedIndexingBackfillDelay, + "extended-indexing-backfill-delay", + defaultConfig.extendedIndexingBackfillDelay, + "minimum delay between backfilled heights per extended indexer") + flags.StringVar(&builder.extendedIndexingDBPath, + "extended-indexing-db-dir", + defaultConfig.extendedIndexingDBPath, + "directory to use for extended indexing database", + ) + // Execution data pruner flags.Uint64Var(&builder.executionDataPrunerHeightRangeTarget, "execution-data-height-range-target", @@ -911,6 +945,10 @@ func (builder *ObserverServiceBuilder) extraFlags() { return errors.New("rest-max-request-size must be greater than 0") } + if builder.stateStreamConf.MaxGlobalStreams == 0 { + return errors.New("state-stream-global-max-streams must be greater than 0") + } + return nil }) } @@ -1096,6 +1134,17 @@ func (builder *ObserverServiceBuilder) Build() (cmd.Node, error) { builder.BuildExecutionSyncComponents() } + // Initialize stream limiter for RPC server - must be done unconditionally + // since the RPC server always uses it for stream concurrency limiting. + builder.Module("stream limiter", func(node *cmd.NodeConfig) error { + var err error + builder.streamLimiter, err = limiters.NewConcurrencyLimiter(builder.stateStreamConf.MaxGlobalStreams) + if err != nil { + return fmt.Errorf("could not create stream limiter: %w", err) + } + return nil + }) + builder.enqueueRPCServer() return builder.FlowNodeBuilder.Build() } @@ -1103,17 +1152,19 @@ func (builder *ObserverServiceBuilder) Build() (cmd.Node, error) { func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverServiceBuilder { var ds datastore.Batching var bs network.BlobService - var processedBlockHeight storage.ConsumerProgressInitializer - var processedNotifications storage.ConsumerProgressInitializer + var processedBlockHeightInitializer storage.ConsumerProgressInitializer + var processedNotificationsInitializer storage.ConsumerProgressInitializer var publicBsDependable *module.ProxiedReadyDoneAware var execDataDistributor *edrequester.ExecutionDataDistributor var execDataCacheBackend *herocache.BlockExecutionData var executionDataStoreCache *execdatacache.ExecutionDataCache - // setup dependency chain to ensure indexer starts after the requester requesterDependable := module.NewProxiedReadyDoneAware() builder.IndexerDependencies.Add(requesterDependable) + registerStorageDependable := module.NewProxiedReadyDoneAware() + builder.IndexerDependencies.Add(registerStorageDependable) + executionDataPrunerEnabled := builder.executionDataPrunerHeightRangeTarget != 0 builder. @@ -1149,7 +1200,7 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS // writes execution data to. db := builder.ExecutionDatastoreManager.DB() - processedBlockHeight = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterBlockHeight) + processedBlockHeightInitializer = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterBlockHeight) return nil }). Module("processed notifications consumer progress", func(node *cmd.NodeConfig) error { @@ -1157,7 +1208,7 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS // writes execution data to. db := builder.ExecutionDatastoreManager.DB() - processedNotifications = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterNotification) + processedNotificationsInitializer = store.NewConsumerProgress(db, module.ConsumeProgressExecutionDataRequesterNotification) return nil }). Module("blobservice peer manager dependencies", func(node *cmd.NodeConfig) error { @@ -1286,6 +1337,16 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS execDataCacheBackend, ) + // start processing from the initial block height resolved from the execution data config + processedBlockHeight, err := processedBlockHeightInitializer.Initialize(builder.executionDataConfig.InitialBlockHeight) + if err != nil { + return nil, fmt.Errorf("could not initialize processed block height: %w", err) + } + processedNotifications, err := processedNotificationsInitializer.Initialize(builder.executionDataConfig.InitialBlockHeight) + if err != nil { + return nil, fmt.Errorf("could not initialize processed notifications: %w", err) + } + r, err := edrequester.New( builder.Logger, metrics.NewExecutionDataRequesterCollector(), @@ -1341,11 +1402,33 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS return builder.ExecutionDataPruner, nil }) if builder.executionDataIndexingEnabled { - var indexedBlockHeight storage.ConsumerProgressInitializer + var indexedBlockHeightInitializer storage.ConsumerProgressInitializer + + scriptExecutorDependendable := module.NewProxiedReadyDoneAware() + extendedIndexerDependable := module.NewProxiedReadyDoneAware() + + // Script executor: + // -> registers storage + scriptExecutorDependencies := cmd.NewDependencyList() + scriptExecutorDependencies.Add(registerStorageDependable) + + // Extended indexer: + // -> script executor + extendedIndexerDependencies := cmd.NewDependencyList() + extendedIndexerDependencies.Add(scriptExecutorDependendable) + + // Regular indexer: + // -> script executor + // -> extended indexer + builder.IndexerDependencies.Add(scriptExecutorDependendable) + builder.IndexerDependencies.Add(extendedIndexerDependable) + + var indexerDerivedChainData *derived.DerivedChainData + var queryDerivedChainData *derived.DerivedChainData builder.Module("indexed block height consumer progress", func(node *cmd.NodeConfig) error { // Note: progress is stored in the MAIN db since that is where indexed execution data is stored. - indexedBlockHeight = store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressExecutionDataIndexerBlockHeight) + indexedBlockHeightInitializer = store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressExecutionDataIndexerBlockHeight) return nil }).Module("transaction results storage", func(node *cmd.NodeConfig) error { builder.lightTransactionResults = store.NewLightTransactionResults(node.Metrics.Cache, node.ProtocolDB, bstorage.DefaultCacheSize) @@ -1353,10 +1436,48 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS }).Module("scheduled transactions storage", func(node *cmd.NodeConfig) error { builder.scheduledTransactions = store.NewScheduledTransactions(node.Metrics.Cache, node.ProtocolDB, bstorage.DefaultCacheSize) return nil - }).DependableComponent("execution data indexer", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + }).Module("extended index database", func(node *cmd.NodeConfig) error { + if !builder.extendedIndexingEnabled { + return nil + } + + extendedStorage, err := extendedbootstrap.OpenExtendedIndexDB( + node.Logger, + builder.extendedIndexingDBPath, + builder.State.Params().SealedRoot().Height, + ) + if err != nil { + return fmt.Errorf("could not open extended index database: %w", err) + } + builder.ExtendedStorage = extendedStorage + + builder.ShutdownFunc(func() error { + if err := builder.ExtendedStorage.DB.Close(); err != nil { + return fmt.Errorf("error closing extended indexer db: %w", err) + } + return nil + }) + + return nil + }).Module("last full block height consumer progress", func(node *cmd.NodeConfig) error { + rootBlockHeight := node.State.Params().FinalizedRoot().Height + progress, err := store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressLastFullBlockHeight).Initialize(rootBlockHeight) + if err != nil { + return fmt.Errorf("could not create last full block height consumer progress: %w", err) + } + + lastFullBlockHeight, err := counters.NewPersistentStrictMonotonicCounter(progress) + if err != nil { + return fmt.Errorf("could not create last full block height counter: %w", err) + } + builder.lastFullBlockHeight = lastFullBlockHeight + + return nil + }).DependableComponent("registers storage", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { // Note: using a DependableComponent here to ensure that the indexer does not block // other components from starting while bootstrapping the register db since it may - // take hours to complete. + // take hours to complete. The registers storage is not actually a component, but it + // cannot be started as a Module without blocking startup. pdb, err := pstorage.OpenRegisterPebbleDB( node.Logger.With().Str("pebbledb", "registers").Logger(), @@ -1433,81 +1554,16 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS builder.Storage.RegisterIndex = registers } - indexerDerivedChainData, queryDerivedChainData, err := builder.buildDerivedChainData() + rda := &module.NoopReadyDoneAware{} + registerStorageDependable.Init(rda) + return rda, nil + }, nil).DependableComponent("script executor", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + var err error + indexerDerivedChainData, queryDerivedChainData, err = builder.buildDerivedChainData() if err != nil { return nil, fmt.Errorf("could not create derived chain data: %w", err) } - rootBlockHeight := node.State.Params().FinalizedRoot().Height - progress, err := store.NewConsumerProgress(builder.ProtocolDB, module.ConsumeProgressLastFullBlockHeight).Initialize(rootBlockHeight) - if err != nil { - return nil, fmt.Errorf("could not create last full block height consumer progress: %w", err) - } - - lastFullBlockHeight, err := counters.NewPersistentStrictMonotonicCounter(progress) - if err != nil { - return nil, fmt.Errorf("could not create last full block height counter: %w", err) - } - - var collectionExecutedMetric module.CollectionExecutedMetric = metrics.NewNoopCollector() - collectionIndexer, err := collections.NewIndexer( - builder.Logger, - builder.ProtocolDB, - collectionExecutedMetric, - builder.State, - builder.Storage.Blocks, - builder.Storage.Collections, - lastFullBlockHeight, - builder.StorageLockMgr, - ) - if err != nil { - return nil, fmt.Errorf("could not create collection indexer: %w", err) - } - - builder.ExecutionIndexerCore = indexer.New( - builder.Logger, - metrics.NewExecutionStateIndexerCollector(), - builder.ProtocolDB, - builder.Storage.RegisterIndex, - builder.Storage.Headers, - builder.events, - builder.Storage.Collections, - builder.Storage.Transactions, - builder.lightTransactionResults, - builder.scheduledTransactions, - builder.RootChainID, - indexerDerivedChainData, - collectionIndexer, - collectionExecutedMetric, - node.StorageLockMgr, - ) - - // execution state worker uses a jobqueue to process new execution data and indexes it by using the indexer. - builder.ExecutionIndexer, err = indexer.NewIndexer( - builder.Logger, - registers.FirstHeight(), - registers, - builder.ExecutionIndexerCore, - executionDataStoreCache, - builder.ExecutionDataRequester.HighestConsecutiveHeight, - indexedBlockHeight, - ) - if err != nil { - return nil, err - } - - if executionDataPrunerEnabled { - builder.ExecutionDataPruner.RegisterHeightRecorder(builder.ExecutionIndexer) - } - - // setup requester to notify indexer when new execution data is received - execDataDistributor.AddOnExecutionDataReceivedConsumer(builder.ExecutionIndexer.OnExecutionData) - - err = builder.Reporter.Initialize(builder.ExecutionIndexer) - if err != nil { - return nil, err - } - // create script execution module, this depends on the indexer being initialized and the // having the register storage bootstrapped scripts := execution.NewScripts( @@ -1516,28 +1572,136 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS builder.RootChainID, computation.NewProtocolStateWrapper(builder.State), builder.Storage.Headers, - builder.ExecutionIndexerCore.RegisterValue, + builder.Storage.RegisterIndex.Get, builder.scriptExecutorConfig, queryDerivedChainData, builder.programCacheSize > 0, ) - err = builder.ScriptExecutor.Initialize(builder.ExecutionIndexer, scripts, builder.VersionControl) + err = builder.ScriptExecutor.Initialize(builder.Storage.RegisterIndex, scripts, builder.VersionControl) if err != nil { - return nil, err + return nil, fmt.Errorf("could not initialize script executor: %w", err) } - err = builder.RegistersAsyncStore.Initialize(registers) + err = builder.RegistersAsyncStore.Initialize(builder.Storage.RegisterIndex) if err != nil { - return nil, err + return nil, fmt.Errorf("could not initialize registers async store: %w", err) } + scriptExecutorDependendable.Init(&module.NoopReadyDoneAware{}) + + // the script executor is not a component. it is being started as a DependableComponent + // to ensure dependencies are setup in the correct order. + return &module.NoopReadyDoneAware{}, nil + }, scriptExecutorDependencies). + DependableComponent("execution data indexer", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + // Note: using a DependableComponent here to ensure that the indexer does not block + // other components from starting while bootstrapping the register db since it may + // take hours to complete. + + var collectionExecutedMetric module.CollectionExecutedMetric = metrics.NewNoopCollector() + collectionIndexer, err := collections.NewIndexer( + builder.Logger, + builder.ProtocolDB, + collectionExecutedMetric, + builder.State, + builder.Storage.Blocks, + builder.Storage.Collections, + builder.lastFullBlockHeight, + builder.StorageLockMgr, + ) + if err != nil { + return nil, fmt.Errorf("could not create collection indexer: %w", err) + } - if builder.stopControlEnabled { - builder.StopControl.RegisterHeightRecorder(builder.ExecutionIndexer) - } + builder.ExecutionIndexerCore = indexer.New( + builder.Logger, + metrics.NewExecutionStateIndexerCollector(), + builder.ProtocolDB, + builder.Storage.RegisterIndex, + builder.Storage.Headers, + builder.events, + builder.Storage.Collections, + builder.Storage.Transactions, + builder.lightTransactionResults, + builder.scheduledTransactions, + builder.RootChainID, + indexerDerivedChainData, // might be nil if program caching is disabled + collectionIndexer, + collectionExecutedMetric, + node.StorageLockMgr, + builder.ExtendedIndexer, + ) + + // start processing from the first height of the registers db, which is initialized from + // the checkpoint. this ensures a consistent starting point for the indexed data. + indexedBlockHeight, err := indexedBlockHeightInitializer.Initialize(builder.Storage.RegisterIndex.FirstHeight()) + if err != nil { + return nil, fmt.Errorf("could not initialize indexed block height: %w", err) + } + + // execution state worker uses a jobqueue to process new execution data and indexes it by using the indexer. + builder.ExecutionIndexer, err = indexer.NewIndexer( + builder.Logger, + builder.Storage.RegisterIndex.FirstHeight(), + builder.Storage.RegisterIndex, + builder.ExecutionIndexerCore, + executionDataStoreCache, + builder.ExecutionDataRequester.HighestConsecutiveHeight, + indexedBlockHeight, + ) + if err != nil { + return nil, err + } + + if executionDataPrunerEnabled { + builder.ExecutionDataPruner.RegisterHeightRecorder(builder.ExecutionIndexer) + } - return builder.ExecutionIndexer, nil - }, builder.IndexerDependencies) + // setup requester to notify indexer when new execution data is received + execDataDistributor.AddOnExecutionDataReceivedConsumer(builder.ExecutionIndexer.OnExecutionData) + + err = builder.Reporter.Initialize(builder.ExecutionIndexer) + if err != nil { + return nil, err + } + + if builder.stopControlEnabled { + builder.StopControl.RegisterHeightRecorder(builder.ExecutionIndexer) + } + + return builder.ExecutionIndexer, nil + }, builder.IndexerDependencies) + + if !builder.extendedIndexingEnabled { + extendedIndexerDependable.Init(&module.NoopReadyDoneAware{}) + } else { + builder.DependableComponent("extended indexer", func(node *cmd.NodeConfig) (module.ReadyDoneAware, error) { + extendedIndexer, err := extendedbootstrap.BootstrapIndexers( + node.Logger, + node.RootChainID, + utils.NotNil(builder.ExtendedStorage), + utils.NotNil(builder.StorageLockMgr), + utils.NotNil(node.State), + utils.NotNil(builder.Storage.Index), + utils.NotNil(builder.Storage.Headers), + utils.NotNil(builder.Storage.Guarantees), + utils.NotNil(builder.Storage.Collections), + utils.NotNil(builder.events), + utils.NotNil(builder.lightTransactionResults), + utils.NotNil(builder.ScriptExecutor), + utils.NotNil(builder.Storage.RegisterIndex), + builder.extendedIndexingBackfillDelay, + ) + if err != nil { + return nil, fmt.Errorf("could not create extended indexer: %w", err) + } + + builder.ExtendedIndexer = extendedIndexer + extendedIndexerDependable.Init(builder.ExtendedIndexer) + + return builder.ExtendedIndexer, nil + }, extendedIndexerDependencies) + } } if builder.stateStreamConf.ListenAddr != "" { @@ -1616,6 +1780,7 @@ func (builder *ObserverServiceBuilder) BuildExecutionSyncComponents() *ObserverS node.RootChainID, builder.stateStreamGrpcServer, builder.stateStreamBackend, + utils.NotNil(builder.streamLimiter), ) if err != nil { return nil, fmt.Errorf("could not create state stream engine: %w", err) @@ -1711,6 +1876,7 @@ func (builder *ObserverServiceBuilder) enqueuePublicNetworkInit() { SlashingViolationConsumerFactory: func(adapter network.ConduitAdapter) network.ViolationsConsumer { return slashing.NewSlashingViolationsConsumer(builder.Logger, builder.Metrics.Network, adapter) }, + UnicastStreamAuthorizer: message.AlwaysAuthorizedUnicastSenderRole, }, underlay.WithMessageValidators(publicNetworkMsgValidators(node.Logger, node.IdentityProvider, node.NodeID)...)) if err != nil { return nil, fmt.Errorf("could not initialize network: %w", err) @@ -1754,7 +1920,7 @@ func (builder *ObserverServiceBuilder) enqueueRPCServer() { return nil }) builder.Module("rest metrics", func(node *cmd.NodeConfig) error { - m, err := metrics.NewRestCollector(router.URLToRoute, node.MetricsRegisterer) + m, err := metrics.NewRestCollector(router.MethodURLToRoute, node.MetricsRegisterer) if err != nil { return err } @@ -2047,6 +2213,33 @@ func (builder *ObserverServiceBuilder) enqueueRPCServer() { return nil, err } + if builder.extendedIndexingEnabled { + builder.ExtendedBackend, err = extendedbackend.New( + node.Logger, + extendedbackend.DefaultConfig(), + node.RootChainID, + builder.ExtendedStorage.AccountTransactionsBootstrapper, + builder.ExtendedStorage.FungibleTokenTransfersBootstrapper, + builder.ExtendedStorage.NonFungibleTokenTransfersBootstrapper, + utils.NotNil(node.State), + utils.NotNil(node.Storage.Blocks), + utils.NotNil(node.Storage.Headers), + utils.NotNil(builder.EventsIndex), + utils.NotNil(builder.TxResultsIndex), + nil, // tx error message provider is not currently supported on observer nodes + utils.NotNil(node.Storage.Collections), + utils.NotNil(node.Storage.Transactions), + builder.scheduledTransactions, + builder.ExtendedStorage.ScheduledTransactionsBootstrapper, + builder.ExtendedStorage.ContractDeploymentsBootstrapper, + txstatus.NewTxStatusDeriver(node.State, builder.lastFullBlockHeight), + builder.ScriptExecutor, + ) + if err != nil { + return nil, fmt.Errorf("could not initialize extended backend: %w", err) + } + } + engineBuilder, err := rpc.NewBuilder( node.Logger, node.State, @@ -2063,6 +2256,8 @@ func (builder *ObserverServiceBuilder) enqueueRPCServer() { builder.stateStreamConf, indexReporter, builder.FollowerDistributor, + builder.ExtendedBackend, + utils.NotNil(builder.streamLimiter), ) if err != nil { return nil, err diff --git a/cmd/scaffold.go b/cmd/scaffold.go index a1374a2e03c..e812399486f 100644 --- a/cmd/scaffold.go +++ b/cmd/scaffold.go @@ -56,6 +56,7 @@ import ( netcache "github.com/onflow/flow-go/network/cache" "github.com/onflow/flow-go/network/channels" "github.com/onflow/flow-go/network/converter" + "github.com/onflow/flow-go/network/message" "github.com/onflow/flow-go/network/p2p" p2pbuilder "github.com/onflow/flow-go/network/p2p/builder" p2pbuilderconfig "github.com/onflow/flow-go/network/p2p/builder/config" @@ -692,6 +693,13 @@ func (fnb *FlowNodeBuilder) InitFlowNetworkWithConduitFactory( SlashingViolationConsumerFactory: func(adapter network.ConduitAdapter) network.ViolationsConsumer { return slashing.NewSlashingViolationsConsumer(fnb.Logger, fnb.Metrics.Network, adapter) }, + UnicastStreamAuthorizer: func() func(flow.Role, flow.Role) bool { + if fnb.ObserverMode { + // observer mode uses public network where peers are not authorized based on role + return message.AlwaysAuthorizedUnicastSenderRole + } + return nil // use default (IsAuthorizedUnicastSenderRole) + }(), }, networkOptions...) if err != nil { return nil, fmt.Errorf("could not initialize network: %w", err) diff --git a/cmd/util/cmd/atree_inlined_status/atree_inlined_status_test.go b/cmd/util/cmd/atree_inlined_status/atree_inlined_status_test.go index 3a73ab5c212..37c3605124e 100644 --- a/cmd/util/cmd/atree_inlined_status/atree_inlined_status_test.go +++ b/cmd/util/cmd/atree_inlined_status/atree_inlined_status_test.go @@ -39,12 +39,12 @@ func testCheckAtreeInlinedStatus(t *testing.T, payloadCount int, nWorkers int) { atreeInlinedPayloadCount := payloadCount - atreeNoninlinedPayloadCount payloads := make([]*ledger.Payload, 0, payloadCount) - for i := 0; i < atreeInlinedPayloadCount; i++ { + for range atreeInlinedPayloadCount { key := getRandomKey() value := getAtreeInlinedPayload(t) payloads = append(payloads, ledger.NewPayload(key, value)) } - for i := 0; i < atreeNoninlinedPayloadCount; i++ { + for range atreeNoninlinedPayloadCount { key := getRandomKey() value := getAtreeNoninlinedPayload(t) payloads = append(payloads, ledger.NewPayload(key, value)) diff --git a/cmd/util/cmd/bootstrap-execution-state-payloads/cmd.go b/cmd/util/cmd/bootstrap-execution-state-payloads/cmd.go index 6d76bc5b408..d1f997c50df 100644 --- a/cmd/util/cmd/bootstrap-execution-state-payloads/cmd.go +++ b/cmd/util/cmd/bootstrap-execution-state-payloads/cmd.go @@ -43,9 +43,7 @@ func run(*cobra.Command, []string) { log.Info().Msgf("creating payloads for chain %s", chain) - ctx := fvm.NewContext( - fvm.WithChain(chain), - ) + ctx := fvm.NewContext(chain) vm := fvm.NewVirtualMachine() diff --git a/cmd/util/ledger/migrations/account_key_deduplication_migration_validation.go b/cmd/util/cmd/check-storage/account_key_validation.go similarity index 91% rename from cmd/util/ledger/migrations/account_key_deduplication_migration_validation.go rename to cmd/util/cmd/check-storage/account_key_validation.go index 0cd8a9cc627..24a02f4dea3 100644 --- a/cmd/util/ledger/migrations/account_key_deduplication_migration_validation.go +++ b/cmd/util/cmd/check-storage/account_key_validation.go @@ -1,4 +1,4 @@ -package migrations +package check_storage import ( "fmt" @@ -10,10 +10,11 @@ import ( "github.com/onflow/flow-go/cmd/util/ledger/util/registers" "github.com/onflow/flow-go/fvm/environment" + accountkeymetadata "github.com/onflow/flow-go/fvm/environment/account-key-metadata" "github.com/onflow/flow-go/model/flow" ) -func ValidateAccountPublicKeyV4( +func validateAccountPublicKey( address common.Address, accountRegisters *registers.AccountRegisters, ) error { @@ -23,7 +24,7 @@ func ValidateAccountPublicKeyV4( } // Validate account status register - accountPublicKeyCount, storedKeyCount, deduplicated, err := validateAccountStatusV4Register(address, accountRegisters) + accountPublicKeyCount, storedKeyCount, deduplicated, err := validateAccountStatusRegister(address, accountRegisters) if err != nil { return err } @@ -42,9 +43,7 @@ func ValidateAccountPublicKeyV4( batchPublicKeyRegisters := make(map[string][]byte) err = accountRegisters.ForEach(func(_ string, key string, value []byte) error { - if strings.HasPrefix(key, legacyAccountPublicKeyRegisterKeyPrefix) { - return fmt.Errorf("found legacy account public key register %s", key) - } else if key == flow.AccountPublicKey0RegisterKey { + if key == flow.AccountPublicKey0RegisterKey { foundAccountPublicKey0 = true } else if strings.HasPrefix(key, flow.BatchPublicKeyRegisterKeyPrefix) { batchPublicKeyRegisters[key] = value @@ -85,7 +84,7 @@ func ValidateAccountPublicKeyV4( return validateBatchPublicKeyRegisters(storedKeyCount, batchPublicKeyRegisters) } -func validateAccountStatusV4Register( +func validateAccountStatusRegister( address common.Address, accountRegisters *registers.AccountRegisters, ) ( @@ -123,20 +122,20 @@ func validateAccountStatusV4Register( accountPublicKeyCount = accountStatus.AccountPublicKeyCount() if accountPublicKeyCount <= 1 { - if len(encodedAccountStatus) != environment.AccountStatusMinSizeV4 { - err = fmt.Errorf("account status register size is %d, expect %d bytes", len(encodedAccountStatus), environment.AccountStatusMinSizeV4) + if len(encodedAccountStatus) != environment.AccountStatusMinSize { + err = fmt.Errorf("account status register size is %d, expect %d bytes", len(encodedAccountStatus), environment.AccountStatusMinSize) return } storedKeyCount = accountPublicKeyCount return } - weightAndRevokedStatus, startKeyIndexForMapping, accountPublicKeyMappings, startKeyIndexForDigests, digests, err := decodeAccountStatusKeyMetadata( - encodedAccountStatus[environment.AccountStatusMinSizeV4:], + weightAndRevokedStatus, startKeyIndexForMapping, accountPublicKeyMappings, startKeyIndexForDigests, digests, err := accountkeymetadata.DecodeKeyMetadata( + encodedAccountStatus[environment.AccountStatusMinSize:], deduplicated, ) if err != nil { - err = fmt.Errorf("failed to parse key metadata %x: %s", encodedAccountStatus[environment.AccountStatusMinSizeV4:], err) + err = fmt.Errorf("failed to parse key metadata %x: %s", encodedAccountStatus[environment.AccountStatusMinSize:], err) return } @@ -214,7 +213,7 @@ func validateBatchPublicKeyRegisters( return fmt.Errorf("failed to find batch public key %s", key) } - encodedKeys, err := decodeBatchPublicKey(encoded) + encodedKeys, err := environment.DecodeBatchPublicKeys(encoded) if err != nil { return fmt.Errorf("failed to decode batch public key register %s, %x: %s", key, encoded, err) } @@ -245,7 +244,7 @@ func validateBatchPublicKeyRegisters( } } - if batchCount < maxPublicKeyCountInBatch && batchNum != len(batchPublicKeyRegisters)-1 { + if batchCount < environment.MaxPublicKeyCountInBatch && batchNum != len(batchPublicKeyRegisters)-1 { return fmt.Errorf("batch public key %s has less than max count in a batch: got %d keys, %d batches in total", key, batchCount, len(batchPublicKeyRegisters)) } } @@ -260,7 +259,7 @@ func validateBatchPublicKeyRegisters( func validateKeyMetadata( deduplicated bool, accountPublicKeyCount uint32, - weightAndRevokedStatus []accountPublicKeyWeightAndRevokedStatus, + weightAndRevokedStatus []accountkeymetadata.WeightAndRevokedStatus, startKeyIndexForDigests uint32, digests []uint64, startKeyIndexForMapping uint32, @@ -270,8 +269,8 @@ func validateKeyMetadata( return fmt.Errorf("found %d weight and revoked status, expect %d", len(weightAndRevokedStatus), accountPublicKeyCount-1) } - if len(digests) > maxStoredDigests { - return fmt.Errorf("found %d digests, expect max %d digests", len(digests), maxStoredDigests) + if len(digests) > environment.MaxStoredDigests { + return fmt.Errorf("found %d digests, expect max %d digests", len(digests), environment.MaxStoredDigests) } if len(digests) > int(accountPublicKeyCount) { diff --git a/cmd/util/cmd/check-storage/cmd.go b/cmd/util/cmd/check-storage/cmd.go index e0a72109d22..043e2cd9e1e 100644 --- a/cmd/util/cmd/check-storage/cmd.go +++ b/cmd/util/cmd/check-storage/cmd.go @@ -15,7 +15,6 @@ import ( "github.com/onflow/cadence/common" "github.com/onflow/cadence/runtime" - "github.com/onflow/flow-go/cmd/util/ledger/migrations" "github.com/onflow/flow-go/cmd/util/ledger/reporters" "github.com/onflow/flow-go/cmd/util/ledger/util" "github.com/onflow/flow-go/cmd/util/ledger/util/registers" @@ -420,7 +419,7 @@ func checkAccountStorageHealth(accountRegisters *registers.AccountRegisters, nWo if flagIsAccountStatusV4 { // Validate account public key storage - err = migrations.ValidateAccountPublicKeyV4(address, accountRegisters) + err = validateAccountPublicKey(address, accountRegisters) if err != nil { issues = append( issues, @@ -575,7 +574,7 @@ func checkAccountPublicKeys( } } - // NOTE: don't need to check unreachable keys because it is checked in ValidateAccountPublicKeyV4(). + // NOTE: don't need to check unreachable keys because it is checked in validateAccountPublicKey(). return nil } diff --git a/cmd/util/cmd/checkpoint-collect-stats/cmd.go b/cmd/util/cmd/checkpoint-collect-stats/cmd.go index b5fa913e76e..3269f4914cf 100644 --- a/cmd/util/cmd/checkpoint-collect-stats/cmd.go +++ b/cmd/util/cmd/checkpoint-collect-stats/cmd.go @@ -19,8 +19,8 @@ import ( "github.com/onflow/flow-go/cmd/util/ledger/reporters" "github.com/onflow/flow-go/cmd/util/ledger/util" + "github.com/onflow/flow-go/fvm/environment" "github.com/onflow/flow-go/fvm/evm/emulator/state" - "github.com/onflow/flow-go/fvm/evm/handler" "github.com/onflow/flow-go/ledger" "github.com/onflow/flow-go/ledger/common/pathfinder" "github.com/onflow/flow-go/ledger/complete" @@ -410,7 +410,7 @@ func getRegisterStats(valueSizesByType sizesByType) []RegisterStatsByTypes { return statsByTypes } -func writeStats(reportName string, stats interface{}) { +func writeStats(reportName string, stats any) { rw := reporters.NewReportFileWriterFactory(flagOutputDir, log.Logger). ReportWriter(reportName) defer rw.Close() @@ -465,9 +465,9 @@ func getRegisterType(key ledger.Key) string { return "account storage ID" case state.CodesStorageIDKey: return "code storage ID" - case handler.BlockStoreLatestBlockKey: + case environment.BlockStoreLatestBlockKey: return "latest block" - case handler.BlockStoreLatestBlockProposalKey: + case environment.BlockStoreLatestBlockProposalKey: return "latest block proposal" } diff --git a/cmd/util/cmd/compare-debug-tx/cmd.go b/cmd/util/cmd/compare-debug-tx/cmd.go new file mode 100644 index 00000000000..e6174e80c11 --- /dev/null +++ b/cmd/util/cmd/compare-debug-tx/cmd.go @@ -0,0 +1,475 @@ +package compare_debug_tx + +import ( + "bytes" + "context" + "fmt" + "io" + "os" + "os/exec" + "strings" + + "github.com/rs/zerolog/log" + "github.com/spf13/cobra" + "golang.org/x/sync/errgroup" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/grpcclient" + "github.com/onflow/flow-go/utils/debug" +) + +var ( + flagBranch1 string + flagBranch2 string + flagChain string + flagAccessAddress string + flagExecutionAddress string + flagComputeLimit uint64 + flagUseExecutionDataAPI bool + flagBlockID string + flagBlockCount int + flagParallel int + flagLogCadenceTraces bool + flagOnlyTraceCadence bool + flagEntropyProvider string + flagShowTraceDiff bool +) + +var Cmd = &cobra.Command{ + Use: "compare-debug-tx", + Short: "compare transaction execution between two git branches", + Run: run, +} + +func init() { + Cmd.Flags().StringVar(&flagBranch1, "branch1", "", "first git branch (required)") + _ = Cmd.MarkFlagRequired("branch1") + + Cmd.Flags().StringVar(&flagBranch2, "branch2", "", "second git branch (required)") + _ = Cmd.MarkFlagRequired("branch2") + + Cmd.Flags().StringVar(&flagChain, "chain", "", "Chain name") + _ = Cmd.MarkFlagRequired("chain") + + Cmd.Flags().StringVar(&flagAccessAddress, "access-address", "", "address of the access node") + _ = Cmd.MarkFlagRequired("access-address") + + Cmd.Flags().StringVar(&flagExecutionAddress, "execution-address", "", "address of the execution node (required if --use-execution-data-api is false)") + + Cmd.Flags().Uint64Var(&flagComputeLimit, "compute-limit", flow.DefaultMaxTransactionGasLimit, "transaction compute limit") + + Cmd.Flags().BoolVar(&flagUseExecutionDataAPI, "use-execution-data-api", true, "use the execution data API (default: true)") + + Cmd.Flags().StringVar(&flagBlockID, "block-id", "", "block ID") + + Cmd.Flags().IntVar(&flagBlockCount, "block-count", 1, "number of consecutive blocks to process (default: 1); if > 1, requires --block-id and no positional transaction IDs") + + Cmd.Flags().IntVar(&flagParallel, "parallel", 1, "number of blocks to process in parallel (default: 1)") + + Cmd.Flags().BoolVar(&flagLogCadenceTraces, "log-cadence-traces", false, "log Cadence traces (default: false)") + + Cmd.Flags().BoolVar(&flagOnlyTraceCadence, "only-trace-cadence", false, "when tracing, only include spans related to Cadence execution (default: false)") + + Cmd.Flags().StringVar(&flagEntropyProvider, "entropy-provider", "none", "entropy provider to use (default: none; options: none, block-hash)") + + Cmd.Flags().BoolVar(&flagShowTraceDiff, "show-trace-diff", false, "show trace diff output (default: false)") +} + +// closeFile closes the file and fatals on failure. +func closeFile(f *os.File) { + if err := f.Close(); err != nil { + log.Fatal().Err(err).Str("file", f.Name()).Msg("failed to close temp file") + } +} + +// removeFile removes the file at path and fatals on failure. +func removeFile(path string) { + if err := os.Remove(path); err != nil { + log.Fatal().Err(err).Str("file", path).Msg("failed to remove temp file") + } +} + +func run(_ *cobra.Command, args []string) { + repoRoot := findRepoRoot() + checkCleanWorkingTree(repoRoot) + + // Resolve block IDs before git checkouts when --block-count > 0. + var blockIDs []string + if flagBlockCount > 0 { + if flagBlockID == "" { + log.Fatal().Msg("--block-count requires --block-id to be set") + } + if len(args) > 0 { + log.Fatal().Msg("--block-count cannot be used with positional transaction IDs") + } + blockIDs = resolveBlockChain(flagBlockID, flagBlockCount) + } + + result1, err := os.CreateTemp("", "compare-debug-tx-result1-*") + if err != nil { + log.Fatal().Err(err).Msg("failed to create temp file for result1") + } + defer removeFile(result1.Name()) + defer closeFile(result1) + + result2, err := os.CreateTemp("", "compare-debug-tx-result2-*") + if err != nil { + log.Fatal().Err(err).Msg("failed to create temp file for result2") + } + defer removeFile(result2.Name()) + defer closeFile(result2) + + trace1, err := os.CreateTemp("", "compare-debug-tx-trace1-*") + if err != nil { + log.Fatal().Err(err).Msg("failed to create temp file for trace1") + } + defer removeFile(trace1.Name()) + defer closeFile(trace1) + + trace2, err := os.CreateTemp("", "compare-debug-tx-trace2-*") + if err != nil { + log.Fatal().Err(err).Msg("failed to create temp file for trace2") + } + defer removeFile(trace2.Name()) + defer closeFile(trace2) + + checkoutBranch(repoRoot, flagBranch1) + binary1 := buildUtil(repoRoot) + defer removeFile(binary1) + perBlock1 := runAllBlocks(binary1, args, blockIDs, result1, trace1) + defer cleanupPerBlockFiles(perBlock1) + + checkoutBranch(repoRoot, flagBranch2) + binary2 := buildUtil(repoRoot) + defer removeFile(binary2) + perBlock2 := runAllBlocks(binary2, args, blockIDs, result2, trace2) + defer cleanupPerBlockFiles(perBlock2) + + if len(blockIDs) == 1 { + fmt.Printf("=== Result diff (%s vs %s) ===\n", flagBranch1, flagBranch2) + diffFiles(result1.Name(), result2.Name(), flagBranch1, flagBranch2) + + if flagShowTraceDiff { + fmt.Printf("=== Trace diff (%s vs %s) ===\n", flagBranch1, flagBranch2) + diffFiles(trace1.Name(), trace2.Name(), flagBranch1, flagBranch2) + } + } + + printMismatchStats(blockIDs, perBlock1, perBlock2) +} + +// perBlockFiles holds per-block result and trace temp files. +type perBlockFiles struct { + result *os.File + trace *os.File +} + +// cleanupPerBlockFiles closes and removes all per-block temp files. +func cleanupPerBlockFiles(files []perBlockFiles) { + for _, f := range files { + closeFile(f.result) + removeFile(f.result.Name()) + closeFile(f.trace) + removeFile(f.trace.Name()) + } +} + +// runAllBlocks runs debug-tx for each block ID in blockIDs (or a single invocation when +// blockIDs is empty), up to flagParallel blocks concurrently. Results and traces from each +// block are collected into per-block temp files and concatenated into resultDst and traceDst +// in deterministic order after all blocks complete. +// +// When blockIDs has entries, the per-block files are returned and the caller is responsible +// for cleanup via cleanupPerBlockFiles. When blockIDs is empty, nil is returned. +func runAllBlocks(binaryPath string, txIDs []string, blockIDs []string, resultDst *os.File, traceDst *os.File) []perBlockFiles { + if len(blockIDs) == 0 { + if err := runDebugTx(binaryPath, buildDebugTxArgs(txIDs, traceDst.Name(), ""), resultDst); err != nil { + log.Fatal().Err(err).Msg("failed to run debug-tx") + } + return nil + } + + files := make([]perBlockFiles, len(blockIDs)) + for i := range blockIDs { + result, err := os.CreateTemp("", "compare-debug-tx-block-result-*") + if err != nil { + log.Fatal().Err(err).Msg("failed to create per-block result temp file") + } + trace, err := os.CreateTemp("", "compare-debug-tx-block-trace-*") + if err != nil { + log.Fatal().Err(err).Msg("failed to create per-block trace temp file") + } + files[i] = perBlockFiles{result: result, trace: trace} + } + + g, _ := errgroup.WithContext(context.Background()) + g.SetLimit(flagParallel) + + for i, blockID := range blockIDs { + g.Go(func() error { + return runDebugTx(binaryPath, buildDebugTxArgs(txIDs, files[i].trace.Name(), blockID), files[i].result) + }) + } + if err := g.Wait(); err != nil { + log.Fatal().Err(err).Msg("failed to run debug-tx") + } + + for _, f := range files { + if _, err := f.result.Seek(0, io.SeekStart); err != nil { + log.Fatal().Err(err).Msg("failed to seek per-block result file") + } + if _, err := io.Copy(resultDst, f.result); err != nil { + log.Fatal().Err(err).Msg("failed to append per-block result") + } + if _, err := f.trace.Seek(0, io.SeekStart); err != nil { + log.Fatal().Err(err).Msg("failed to seek per-block trace file") + } + if _, err := io.Copy(traceDst, f.trace); err != nil { + log.Fatal().Err(err).Msg("failed to append per-block trace") + } + } + + return files +} + +// resolveBlockChain fetches count consecutive block IDs starting from startBlockID, +// following parent IDs, and returns them as hex strings. +func resolveBlockChain(startBlockID string, count int) []string { + blockID, err := flow.HexStringToIdentifier(startBlockID) + if err != nil { + log.Fatal().Err(err).Str("ID", startBlockID).Msg("failed to parse block ID") + } + + config, err := grpcclient.NewFlowClientConfig(flagAccessAddress, "", flow.ZeroID, true) + if err != nil { + log.Fatal().Err(err).Msg("failed to create flow client config") + } + + flowClient, err := grpcclient.FlowClient(config) + if err != nil { + log.Fatal().Err(err).Msg("failed to create flow client") + } + + ctx := context.Background() + + var blockIDs []string + for range count { + header, err := debug.GetAccessAPIBlockHeader(ctx, flowClient.RPCClient(), blockID) + if err != nil { + log.Fatal().Err(err).Str("blockID", blockID.String()).Msg("failed to fetch block header") + } + + log.Info().Msgf("Resolved block %s at height %d", blockID, header.Height) + blockIDs = append(blockIDs, blockID.String()) + blockID = header.ParentID + } + + return blockIDs +} + +// findRepoRoot returns the absolute path to the root of the git repository. +// +// No error returns are expected during normal operation. +func findRepoRoot() string { + out, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() + if err != nil { + log.Fatal().Err(err).Msg("failed to find repo root") + } + return strings.TrimSpace(string(out)) +} + +// checkCleanWorkingTree fatals if the working tree has uncommitted changes (excluding untracked files). +// +// No error returns are expected during normal operation. +func checkCleanWorkingTree(repoRoot string) { + cmd := exec.Command("git", "status", "--porcelain", "--untracked-files=no") + cmd.Dir = repoRoot + out, err := cmd.Output() + if err != nil { + log.Fatal().Err(err).Msg("failed to check working tree status") + } + if len(bytes.TrimSpace(out)) > 0 { + log.Fatal().Msg("working tree has uncommitted changes; stash or commit before comparing branches") + } +} + +// checkoutBranch checks out the given branch in the repo at repoRoot. +// +// No error returns are expected during normal operation. +func checkoutBranch(repoRoot, branch string) { + cmd := exec.Command("git", "checkout", branch) + cmd.Dir = repoRoot + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + log.Fatal().Err(err).Str("branch", branch).Msg("failed to checkout branch") + } +} + +// buildUtil compiles `./cmd/util` with the cadence_tracing build tag in repoRoot, +// writes the binary to a temp file, and returns its path. The caller is responsible +// for removing the file when done. +func buildUtil(repoRoot string) string { + binary, err := os.CreateTemp("", "compare-debug-tx-util-*") + if err != nil { + log.Fatal().Err(err).Msg("failed to create temp file for util binary") + } + closeFile(binary) + + cmd := exec.Command("go", "build", "-tags", "cadence_tracing", "-o", binary.Name(), "./cmd/util") + cmd.Dir = repoRoot + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + log.Fatal().Err(err).Msg("failed to build util binary") + } + + return binary.Name() +} + +// runDebugTx runs the `debug-tx` subcommand of the prebuilt binaryPath with fwdArgs, +// directing stdout to resultDst and stderr to os.Stderr. +func runDebugTx(binaryPath string, fwdArgs []string, resultDst *os.File) error { + cmd := exec.Command(binaryPath, append([]string{"debug-tx"}, fwdArgs...)...) + cmd.Stdout = resultDst + cmd.Stderr = os.Stderr + return cmd.Run() +} + +// buildDebugTxArgs assembles the flag arguments for the debug-tx command, appending +// --show-result=true, --trace=, and the given tx IDs. +// blockIDOverride, when non-empty, overrides --block-id instead of using flagBlockID. +func buildDebugTxArgs(txIDs []string, tracePath string, blockIDOverride string) []string { + args := []string{ + "--chain=" + flagChain, + "--access-address=" + flagAccessAddress, + fmt.Sprintf("--compute-limit=%d", flagComputeLimit), + fmt.Sprintf("--use-execution-data-api=%t", flagUseExecutionDataAPI), + fmt.Sprintf("--log-cadence-traces=%t", flagLogCadenceTraces), + fmt.Sprintf("--only-trace-cadence=%t", flagOnlyTraceCadence), + "--entropy-provider=" + flagEntropyProvider, + "--show-result=true", + "--trace=" + tracePath, + } + + if flagExecutionAddress != "" { + args = append(args, "--execution-address="+flagExecutionAddress) + } + + blockID := flagBlockID + if blockIDOverride != "" { + blockID = blockIDOverride + } + if blockID != "" { + args = append(args, "--block-id="+blockID) + } + + args = append(args, txIDs...) + return args +} + +// printMismatchStats compares per-block result files from two branches and prints +// statistics on how many blocks and transactions had result mismatches. +func printMismatchStats(blockIDs []string, files1, files2 []perBlockFiles) { + blocksWithMismatch := 0 + totalTxs := 0 + txsWithMismatch := 0 + + fmt.Printf("\n=== Result Mismatch Summary ===\n") + + for i, blockID := range blockIDs { + data1 := readFileFromStart(files1[i].result) + data2 := readFileFromStart(files2[i].result) + + sections1 := splitTxSections(data1) + sections2 := splitTxSections(data2) + + blockTxMismatches := 0 + txCount := max(len(sections1), len(sections2)) + totalTxs += txCount + + for j := range txCount { + var s1, s2 []byte + if j < len(sections1) { + s1 = sections1[j] + } + if j < len(sections2) { + s2 = sections2[j] + } + if !bytes.Equal(s1, s2) { + txsWithMismatch++ + blockTxMismatches++ + } + } + + if blockTxMismatches > 0 { + blocksWithMismatch++ + log.Error().Msgf("Block %s: %d/%d transactions differ", blockID, blockTxMismatches, txCount) + } + } + + log.Info().Msgf("Blocks with result mismatches: %d/%d", blocksWithMismatch, len(blockIDs)) + log.Info().Msgf("Transactions with result mismatches: %d/%d", txsWithMismatch, totalTxs) +} + +// readFileFromStart seeks to the beginning of the file and reads all content. +func readFileFromStart(f *os.File) []byte { + if _, err := f.Seek(0, io.SeekStart); err != nil { + log.Fatal().Err(err).Msg("failed to seek file") + } + data, err := io.ReadAll(f) + if err != nil { + log.Fatal().Err(err).Msg("failed to read file") + } + return data +} + +// splitTxSections splits result data into per-transaction sections. +// Each section starts with a "# ID: " line and includes all content up to the next such line. +func splitTxSections(data []byte) [][]byte { + prefix := []byte("# ID: ") + var sections [][]byte + sectionStart := -1 + + for i := 0; i < len(data); { + lineEnd := bytes.IndexByte(data[i:], '\n') + var line []byte + if lineEnd < 0 { + line = data[i:] + } else { + line = data[i : i+lineEnd] + } + + if bytes.HasPrefix(line, prefix) { + if sectionStart >= 0 { + sections = append(sections, data[sectionStart:i]) + } + sectionStart = i + } + + if lineEnd < 0 { + break + } + i += lineEnd + 1 + } + if sectionStart >= 0 { + sections = append(sections, data[sectionStart:]) + } + return sections +} + +// diffFiles runs `diff -u --label label1 --label label2 file1 file2` and prints the output. +// A diff exit code of 1 (files differ) is not treated as an error. +// +// No error returns are expected during normal operation. +func diffFiles(file1, file2, label1, label2 string) { + cmd := exec.Command("diff", "-u", "--label", label1, "--label", label2, file1, file2) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + err := cmd.Run() + if err != nil { + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 { + // exit code 1 means files differ, which is expected + return + } + log.Fatal().Err(err).Msg("failed to diff files") + } +} diff --git a/cmd/util/cmd/debug-script/cmd.go b/cmd/util/cmd/debug-script/cmd.go index 6b62f7fefbf..4d58f6f8c03 100644 --- a/cmd/util/cmd/debug-script/cmd.go +++ b/cmd/util/cmd/debug-script/cmd.go @@ -1,7 +1,6 @@ package debug_tx import ( - "context" "os" "github.com/onflow/flow/protobuf/go/flow/access" @@ -61,14 +60,15 @@ func init() { Cmd.Flags().BoolVar(&flagUseVM, "use-vm", false, "use the VM for script execution (default: false)") } -func run(*cobra.Command, []string) { +func run(cmd *cobra.Command, _ []string) { + ctx := cmd.Context() chainID := flow.ChainID(flagChain) chain := chainID.Chain() code, err := os.ReadFile(flagScript) if err != nil { - log.Fatal().Err(err).Msgf("failed to read script from file %s", flagScript) + log.Fatal().Err(err).Msgf("Failed to read script from file %s", flagScript) } accessConn, err := grpc.NewClient( @@ -76,7 +76,7 @@ func run(*cobra.Command, []string) { grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { - log.Fatal().Err(err).Msg("failed to create access connection") + log.Fatal().Err(err).Msg("Failed to create access connection") } defer accessConn.Close() @@ -84,14 +84,14 @@ func run(*cobra.Command, []string) { blockID, err := flow.HexStringToIdentifier(flagBlockID) if err != nil { - log.Fatal().Err(err).Msg("failed to parse block ID") + log.Fatal().Err(err).Msg("Failed to parse block ID") } log.Info().Msgf("Fetching block header for %s ...", blockID) - blockHeader, err := debug.GetAccessAPIBlockHeader(context.Background(), accessClient, blockID) + blockHeader, err := debug.GetAccessAPIBlockHeader(ctx, accessClient, blockID) if err != nil { - log.Fatal().Err(err).Msg("failed to fetch block header") + log.Fatal().Err(err).Msg("Failed to fetch block header") } log.Info().Msgf( @@ -106,16 +106,16 @@ func run(*cobra.Command, []string) { } else if flagExecutionAddress != "" { remoteClient, err = debug.NewExecutionNodeRemoteClient(flagExecutionAddress) } else { - log.Fatal().Msg("either --use-execution-data-api or --execution-address must be provided") + log.Fatal().Msg("Either --use-execution-data-api or --execution-address must be provided") } if err != nil { - log.Fatal().Err(err).Msg("failed to remote client") + log.Fatal().Err(err).Msg("Failed to create remote client") } defer remoteClient.Close() remoteSnapshot, err := remoteClient.StorageSnapshot(blockHeader.Height, blockID) if err != nil { - log.Fatal().Err(err).Msg("failed to create storage snapshot") + log.Fatal().Err(err).Msg("Failed to create storage snapshot") } blockSnapshot := debug.NewCachingStorageSnapshot(remoteSnapshot) @@ -131,11 +131,13 @@ func run(*cobra.Command, []string) { result, err := debugger.RunScript(code, arguments, blockSnapshot, blockHeader) if err != nil { - log.Fatal().Err(err).Msg("failed to run script") + log.Fatal().Err(err).Msg("Failed to run script") } if result.Output.Err != nil { - log.Fatal().Err(result.Output.Err).Msg("script execution failed") + log.Fatal().Err(result.Output.Err).Msg("Script execution failed") + } else { + log.Info().Msg("Script executed successfully") } log.Info().Msgf("Result: %s", result.Output.Value) diff --git a/cmd/util/cmd/debug-tx/cmd.go b/cmd/util/cmd/debug-tx/cmd.go index 0725dd01380..83a9fdf0a7e 100644 --- a/cmd/util/cmd/debug-tx/cmd.go +++ b/cmd/util/cmd/debug-tx/cmd.go @@ -31,7 +31,7 @@ var ( flagBlockID string flagUseVM bool flagTracePath string - flagLogTraces bool + flagLogCadenceTraces bool flagOnlyTraceCadence bool flagEntropyProvider string ) @@ -69,7 +69,7 @@ func init() { Cmd.Flags().StringVar(&flagTracePath, "trace", "", "enable tracing to given path") - Cmd.Flags().BoolVar(&flagLogTraces, "log-cadence-traces", false, "log Cadence traces. requires --trace and --only-trace-cadence to be set (default: false)") + Cmd.Flags().BoolVar(&flagLogCadenceTraces, "log-cadence-traces", false, "log Cadence traces. requires --trace and --only-trace-cadence to be set (default: false)") Cmd.Flags().BoolVar(&flagOnlyTraceCadence, "only-trace-cadence", false, "when tracing, only include spans related to Cadence execution (default: false)") @@ -83,12 +83,12 @@ func run(_ *cobra.Command, args []string) { config, err := grpcclient.NewFlowClientConfig(flagAccessAddress, "", flow.ZeroID, true) if err != nil { - log.Fatal().Err(err).Msg("failed to create flow client config") + log.Fatal().Err(err).Msg("Failed to create flow client config") } flowClient, err := grpcclient.FlowClient(config) if err != nil { - log.Fatal().Err(err).Msg("failed to create client") + log.Fatal().Err(err).Msg("Failed to create client") } var remoteClient debug.RemoteClient @@ -97,10 +97,10 @@ func run(_ *cobra.Command, args []string) { } else if flagExecutionAddress != "" { remoteClient, err = debug.NewExecutionNodeRemoteClient(flagExecutionAddress) } else { - log.Fatal().Msg("either --use-execution-data-api or --execution-address must be provided") + log.Fatal().Msg("Either --use-execution-data-api or --execution-address must be provided") } if err != nil { - log.Fatal().Err(err).Msg("failed to remote client") + log.Fatal().Err(err).Msg("Failed to create remote client") } defer remoteClient.Close() @@ -110,21 +110,25 @@ func run(_ *cobra.Command, args []string) { } else if flagTracePath != "" { traceFile, err = os.Create(flagTracePath) if err != nil { - log.Fatal().Err(err).Msg("failed to create trace file") + log.Fatal().Err(err).Msg("Failed to create trace file") } defer traceFile.Close() } + if flagLogCadenceTraces && (flagTracePath == "" || !flagOnlyTraceCadence) { + log.Fatal().Msg("--log-cadence-traces requires both --trace and --only-trace-cadence") + } + var spanExporter otelTrace.SpanExporter if traceFile != nil { if flagOnlyTraceCadence { cadenceSpanExporter := &debug.InterestingCadenceSpanExporter{ - Log: flagLogTraces, + Log: flagLogCadenceTraces, } defer func() { err = cadenceSpanExporter.WriteSpans(traceFile) if err != nil { - log.Fatal().Err(err).Msg("failed to write spans") + log.Fatal().Err(err).Msg("Failed to write spans") } }() spanExporter = cadenceSpanExporter @@ -134,22 +138,26 @@ func run(_ *cobra.Command, args []string) { stdouttrace.WithoutTimestamps(), ) if err != nil { - log.Fatal().Err(err).Msg("failed to create trace exporter") + log.Fatal().Err(err).Msg("Failed to create trace exporter") } } } + if flagBlockID == "" && len(args) == 0 { + log.Fatal().Msg("Must provide either --block-id or one or more transaction IDs") + } + if flagBlockID != "" { if len(args) != 0 { - log.Fatal().Msg("cannot provide both block ID and transaction IDs") + log.Fatal().Msg("Cannot provide both block ID and transaction IDs") } // Block ID provided, fetch the block and its transaction IDs blockID, err := flow.HexStringToIdentifier(flagBlockID) if err != nil { - log.Fatal().Err(err).Str("ID", flagBlockID).Msg("failed to parse block ID") + log.Fatal().Err(err).Str("ID", flagBlockID).Msg("Failed to parse block ID") } header := FetchBlockHeader(blockID, flowClient) @@ -201,7 +209,7 @@ func run(_ *cobra.Command, args []string) { for _, rawTxID := range args { txID, err := flow.HexStringToIdentifier(rawTxID) if err != nil { - log.Fatal().Err(err).Str("ID", rawTxID).Msg("failed to parse transaction ID") + log.Fatal().Err(err).Str("ID", rawTxID).Msg("Failed to parse transaction ID") } result := RunSingleTransaction( @@ -228,6 +236,8 @@ func fvmOptions(blockID flow.Identifier) []fvm.Option { var options []fvm.Option switch flagEntropyProvider { + case "none": + // no entropy provider case "block-hash": options = append( options, @@ -235,6 +245,10 @@ func fvmOptions(blockID flow.Identifier) []fvm.Option { BlockHash: blockID, }), ) + default: + log.Fatal(). + Str("entropy-provider", flagEntropyProvider). + Msg("Invalid --entropy-provider value, must be one of: none, block-hash") } return options @@ -253,7 +267,7 @@ func RunSingleTransaction( txResult, err := flowClient.GetTransactionResult(context.Background(), sdk.Identifier(txID)) if err != nil { - log.Fatal().Err(err).Msg("failed to fetch transaction result") + log.Fatal().Err(err).Msg("Failed to fetch transaction result") } blockID := flow.Identifier(txResult.BlockID) @@ -302,7 +316,7 @@ func RunSingleTransaction( } } - log.Fatal().Msg("transaction not found in block transactions") + log.Fatal().Msg("Transaction not found in block transactions") return debug.Result{} } @@ -314,7 +328,7 @@ func NewBlockSnapshot( remoteSnapshot, err := remoteClient.StorageSnapshot(blockHeader.Height, blockHeader.ID()) if err != nil { - log.Fatal().Err(err).Msg("failed to create storage snapshot") + log.Fatal().Err(err).Msg("Failed to create storage snapshot") } return debug.NewCachingStorageSnapshot(remoteSnapshot) @@ -329,7 +343,7 @@ func FetchBlockHeader( var err error header, err = debug.GetAccessAPIBlockHeader(context.Background(), flowClient.RPCClient(), blockID) if err != nil { - log.Fatal().Err(err).Msg("failed to fetch block header") + log.Fatal().Err(err).Msg("Failed to fetch block header") } log.Info().Msgf( @@ -356,7 +370,7 @@ func SubscribeBlockHeadersFromStartBlockID( blockStatus, ) if err != nil { - log.Fatal().Err(err).Msg("failed to subscribe to block headers") + log.Fatal().Err(err).Msg("Failed to subscribe to block headers") } log.Info().Msg("Subscribed to block headers") @@ -377,7 +391,7 @@ func SubscribeBlockHeadersFromLatest( blockStatus, ) if err != nil { - log.Fatal().Err(err).Msg("failed to subscribe to block headers") + log.Fatal().Err(err).Msg("Failed to subscribe to block headers") } log.Info().Msg("Subscribed to block headers") @@ -398,7 +412,7 @@ func FetchBlockTransactions( blockTransactions, err = flowClient.GetTransactionsByBlockID(context.Background(), sdk.Identifier(blockID)) if err != nil { - log.Fatal().Err(err).Msg("failed to fetch transactions of block") + log.Fatal().Err(err).Msg("Failed to fetch transactions of block") } for _, blockTx := range blockTransactions { @@ -515,7 +529,7 @@ func RunTransaction( sync, ) if err != nil { - log.Fatal().Err(err).Msg("failed to create tracer") + log.Fatal().Err(err).Msg("Failed to create tracer") } span, _ := tracer.StartTransactionSpan(context.TODO(), flow.Identifier(tx.ID()), "") @@ -550,6 +564,8 @@ func RunTransaction( // TransactionInvoker already logs error if result.Output.Err == nil { log.Info().Msg("Transaction succeeded") + } else { + log.Err(result.Output.Err).Msgf("Transaction failed") } return result diff --git a/cmd/util/cmd/diffkeys/cmd.go b/cmd/util/cmd/diffkeys/cmd.go deleted file mode 100644 index e79c09ac948..00000000000 --- a/cmd/util/cmd/diffkeys/cmd.go +++ /dev/null @@ -1,507 +0,0 @@ -package diffkeys - -import ( - "context" - "encoding/hex" - "encoding/json" - "fmt" - - "github.com/onflow/cadence/common" - "github.com/rs/zerolog/log" - "github.com/spf13/cobra" - "golang.org/x/sync/errgroup" - - "github.com/onflow/flow-go/cmd/util/ledger/migrations" - "github.com/onflow/flow-go/cmd/util/ledger/reporters" - "github.com/onflow/flow-go/cmd/util/ledger/util" - "github.com/onflow/flow-go/cmd/util/ledger/util/registers" - "github.com/onflow/flow-go/ledger" - "github.com/onflow/flow-go/model/flow" - moduleUtil "github.com/onflow/flow-go/module/util" -) - -var ( - flagOutputDirectory string - flagPayloadsV3 string - flagPayloadsV4 string - flagStateV3 string - flagStateV4 string - flagStateCommitmentV3 string - flagStateCommitmentV4 string - flagNWorker int - flagChain string -) - -var Cmd = &cobra.Command{ - Use: "diff-keys", - Short: "Compare account public keys in the given state-v3 with state-v4 and output to JSONL file (empty file if no difference)", - Run: run, -} - -const ReporterName = "key-diff" - -type stateType uint8 - -const ( - oldState stateType = 1 - newState stateType = 2 -) - -func init() { - - // Input with account public keys in v3 format - - Cmd.Flags().StringVar( - &flagPayloadsV3, - "payloads-v3", - "", - "Input payload file name with account public keys in v3 format", - ) - - Cmd.Flags().StringVar( - &flagStateV3, - "state-v3", - "", - "Input state file name with account public keys in v3 format", - ) - Cmd.Flags().StringVar( - &flagStateCommitmentV3, - "state-commitment-v3", - "", - "Input state commitment for state-v3", - ) - - // Input with account public keys in v4 format - - Cmd.Flags().StringVar( - &flagPayloadsV4, - "payloads-v4", - "", - "Input payload file name with account public keys in v4 format", - ) - - Cmd.Flags().StringVar( - &flagStateV4, - "state-v4", - "", - "Input state file name with account public keys in v4 format", - ) - - Cmd.Flags().StringVar( - &flagStateCommitmentV4, - "state-commitment-v4", - "", - "Input state commitment for state-v4", - ) - - // Other - - Cmd.Flags().StringVar( - &flagOutputDirectory, - "output-directory", - "", - "Output directory", - ) - _ = Cmd.MarkFlagRequired("output-directory") - - Cmd.Flags().IntVar( - &flagNWorker, - "n-worker", - 10, - "number of workers to use", - ) - - Cmd.Flags().StringVar( - &flagChain, - "chain", - "", - "Chain name", - ) - _ = Cmd.MarkFlagRequired("chain") -} - -func run(*cobra.Command, []string) { - - chainID := flow.ChainID(flagChain) - // Validate chain ID - _ = chainID.Chain() - - if flagPayloadsV3 == "" && flagStateV3 == "" { - log.Fatal().Msg("Either --payloads-v3 or --state-v3 must be provided") - } else if flagPayloadsV3 != "" && flagStateV3 != "" { - log.Fatal().Msg("Only one of --payloads-v4 or --state-v4 must be provided") - } - if flagStateV3 != "" && flagStateCommitmentV3 == "" { - log.Fatal().Msg("--state-commitment-v3 must be provided when --state-v3 is provided") - } - - if flagPayloadsV4 == "" && flagStateV4 == "" { - log.Fatal().Msg("Either --payloads-v4 or --state-v4 must be provided") - } else if flagPayloadsV4 != "" && flagStateV4 != "" { - log.Fatal().Msg("Only one of --payloads-v4 or --state-v4 must be provided") - } - if flagStateV4 != "" && flagStateCommitmentV4 == "" { - log.Fatal().Msg("--state-commitment-v4 must be provided when --state-v4 is provided") - } - - rw := reporters.NewReportFileWriterFactoryWithFormat(flagOutputDirectory, log.Logger, reporters.ReportFormatJSONL). - ReportWriter(ReporterName) - defer rw.Close() - - var registersV3, registersV4 *registers.ByAccount - { - // Load payloads and create registers. - // Define in a block, so that the memory is released after the registers are created. - payloadsV3, payloadsV4 := loadPayloads() - - registersV3, registersV4 = payloadsToRegisters(payloadsV3, payloadsV4) - - accountCountV3 := registersV3.AccountCount() - accountCountV4 := registersV4.AccountCount() - if accountCountV3 != accountCountV4 { - log.Warn().Msgf( - "Registers have different number of accounts: %d vs %d", - accountCountV3, - accountCountV4, - ) - } - } - - err := diff(registersV3, registersV4, chainID, rw, flagNWorker) - if err != nil { - log.Warn().Err(err).Msgf("failed to diff registers") - } -} - -func loadPayloads() (payloads1, payloads2 []*ledger.Payload) { - - log.Info().Msg("Loading payloads") - - var group errgroup.Group - - group.Go(func() (err error) { - if flagPayloadsV3 != "" { - log.Info().Msgf("Loading v3 payloads from file at %v", flagPayloadsV3) - - _, payloads1, err = util.ReadPayloadFile(log.Logger, flagPayloadsV3) - if err != nil { - err = fmt.Errorf("failed to load v3 payload file: %w", err) - } - } else { - log.Info().Msgf("Reading v3 trie with state commitement %s", flagStateCommitmentV3) - - stateCommitment := util.ParseStateCommitment(flagStateCommitmentV3) - payloads1, err = util.ReadTrieForPayloads(flagStateV3, stateCommitment) - if err != nil { - err = fmt.Errorf("failed to load v3 trie: %w", err) - } - } - return - }) - - group.Go(func() (err error) { - if flagPayloadsV4 != "" { - log.Info().Msgf("Loading v4 payloads from file at %v", flagPayloadsV4) - - _, payloads2, err = util.ReadPayloadFile(log.Logger, flagPayloadsV4) - if err != nil { - err = fmt.Errorf("failed to load v4 payload file: %w", err) - } - } else { - log.Info().Msgf("Reading v4 trie with state commitment %s", flagStateCommitmentV4) - - stateCommitment := util.ParseStateCommitment(flagStateCommitmentV4) - payloads2, err = util.ReadTrieForPayloads(flagStateV4, stateCommitment) - if err != nil { - err = fmt.Errorf("failed to load v4 trie: %w", err) - } - } - return - }) - - err := group.Wait() - if err != nil { - log.Fatal().Err(err).Msg("failed to read payloads") - } - - log.Info().Msg("Finished loading payloads") - - return -} - -func payloadsToRegisters(payloads1, payloads2 []*ledger.Payload) (registers1, registers2 *registers.ByAccount) { - - log.Info().Msg("Creating registers from payloads") - - var group errgroup.Group - - group.Go(func() (err error) { - log.Info().Msgf("Creating registers from v3 payloads (%d)", len(payloads1)) - - registers1, err = registers.NewByAccountFromPayloads(payloads1) - if err != nil { - return fmt.Errorf("failed to create registers from v3 payloads: %w", err) - } - - log.Info().Msgf( - "Created %d registers from payloads (%d accounts)", - registers1.Count(), - registers1.AccountCount(), - ) - - return - }) - - group.Go(func() (err error) { - log.Info().Msgf("Creating registers from v4 payloads (%d)", len(payloads2)) - - registers2, err = registers.NewByAccountFromPayloads(payloads2) - if err != nil { - return fmt.Errorf("failed to create registers from v4 payloads: %w", err) - } - - log.Info().Msgf( - "Created %d registers from payloads (%d accounts)", - registers2.Count(), - registers2.AccountCount(), - ) - - return - }) - - err := group.Wait() - if err != nil { - log.Fatal().Err(err).Msg("failed to create registers from payloads") - } - - log.Info().Msg("Finished creating registers from payloads") - - return -} - -func diff( - registersV3 *registers.ByAccount, - registersV4 *registers.ByAccount, - chainID flow.ChainID, - rw reporters.ReportWriter, - nWorkers int, -) error { - log.Info().Msgf("Diffing accounts: v3 count %d, v4 count %d", registersV3.AccountCount(), registersV4.AccountCount()) - - if registersV3.AccountCount() < nWorkers { - nWorkers = registersV3.AccountCount() - } - - logAccount := moduleUtil.LogProgress( - log.Logger, - moduleUtil.DefaultLogProgressConfig( - "processing account group", - registersV3.AccountCount(), - ), - ) - - if nWorkers <= 1 { - foundAccountCountInRegistersV4 := 0 - - _ = registersV3.ForEachAccount(func(accountRegistersV3 *registers.AccountRegisters) (err error) { - owner := accountRegistersV3.Owner() - - if !registersV4.HasAccountOwner(owner) { - rw.Write(accountMissing{ - Owner: owner, - State: int(newState), - }) - - return nil - } - - foundAccountCountInRegistersV4++ - - accountRegistersV4 := registersV4.AccountRegisters(owner) - - err = diffAccount( - owner, - accountRegistersV3, - accountRegistersV4, - chainID, - rw, - ) - if err != nil { - log.Warn().Err(err).Msgf("failed to diff account %x", []byte(owner)) - } - - logAccount(1) - - return nil - }) - - if foundAccountCountInRegistersV4 < registersV4.AccountCount() { - - log.Warn().Msgf("finding missing accounts that exist in v4, but are missing in v3, count: %v", registersV4.AccountCount()-foundAccountCountInRegistersV4) - - _ = registersV4.ForEachAccount(func(accountRegistersV4 *registers.AccountRegisters) error { - owner := accountRegistersV4.Owner() - if !registersV3.HasAccountOwner(owner) { - rw.Write(accountMissing{ - Owner: owner, - State: int(oldState), - }) - } - return nil - }) - } - - return nil - } - - type job struct { - owner string - accountRegistersV3 *registers.AccountRegisters - accountRegistersV4 *registers.AccountRegisters - } - - type result struct { - owner string - err error - } - - jobs := make(chan job, nWorkers) - - results := make(chan result, nWorkers) - - g, ctx := errgroup.WithContext(context.Background()) - - // Launch goroutines to diff accounts - for i := 0; i < nWorkers; i++ { - g.Go(func() (err error) { - for job := range jobs { - err := diffAccount( - job.owner, - job.accountRegistersV3, - job.accountRegistersV4, - chainID, - rw, - ) - - select { - case results <- result{owner: job.owner, err: err}: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - }) - } - - // Launch goroutine to wait for workers and close result channel - go func() { - _ = g.Wait() - close(results) - }() - - // Launch goroutine to send account registers to jobs channel - go func() { - defer close(jobs) - - foundAccountCountInRegistersV4 := 0 - - _ = registersV3.ForEachAccount(func(accountRegistersV3 *registers.AccountRegisters) (err error) { - owner := accountRegistersV3.Owner() - if !registersV4.HasAccountOwner(owner) { - rw.Write(accountMissing{ - Owner: owner, - State: int(newState), - }) - - return nil - } - - foundAccountCountInRegistersV4++ - - accountRegistersV4 := registersV4.AccountRegisters(owner) - - jobs <- job{ - owner: owner, - accountRegistersV3: accountRegistersV3, - accountRegistersV4: accountRegistersV4, - } - - return nil - }) - - if foundAccountCountInRegistersV4 < registersV4.AccountCount() { - - log.Warn().Msgf("finding missing accounts that exist in v4, but are missing in v3, count: %v", registersV4.AccountCount()-foundAccountCountInRegistersV4) - - _ = registersV4.ForEachAccount(func(accountRegistersV4 *registers.AccountRegisters) (err error) { - owner := accountRegistersV4.Owner() - if !registersV3.HasAccountOwner(owner) { - rw.Write(accountMissing{ - Owner: owner, - State: int(oldState), - }) - } - return nil - }) - } - }() - - // Gather results - for result := range results { - logAccount(1) - if result.err != nil { - log.Warn().Err(result.err).Msgf("failed to diff account %x", []byte(result.owner)) - } - } - - if err := g.Wait(); err != nil { - return err - } - - log.Info().Msgf("Finished diffing accounts") - - return nil -} - -func diffAccount( - owner string, - accountRegistersV3 *registers.AccountRegisters, - accountRegistersV4 *registers.AccountRegisters, - chainID flow.ChainID, - rw reporters.ReportWriter, -) (err error) { - address, err := common.BytesToAddress([]byte(owner)) - if err != nil { - return err - } - - migrations.NewAccountKeyDiffReporter( - address, - chainID, - rw, - ).DiffKeys( - accountRegistersV3, - accountRegistersV4, - ) - - return nil -} - -type accountMissing struct { - Owner string - State int -} - -var _ json.Marshaler = accountMissing{} - -func (e accountMissing) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Kind string `json:"kind"` - Owner string `json:"owner"` - State int `json:"state"` - }{ - Kind: "account-missing", - Owner: hex.EncodeToString([]byte(e.Owner)), - State: e.State, - }) -} diff --git a/cmd/util/cmd/epochs/utils/encode.go b/cmd/util/cmd/epochs/utils/encode.go index a92ba6f2556..2be7ecd979d 100644 --- a/cmd/util/cmd/epochs/utils/encode.go +++ b/cmd/util/cmd/epochs/utils/encode.go @@ -14,7 +14,7 @@ import ( func EncodeArgs(args []cadence.Value) ([]byte, error) { // will hold unmarshalled cadence JSON - parsedArgs := make([]interface{}, len(args)) + parsedArgs := make([]any, len(args)) for index, cdcVal := range args { @@ -25,7 +25,7 @@ func EncodeArgs(args []cadence.Value) ([]byte, error) { } // unmarshal json to interface and append to array - var arg interface{} + var arg any err = json.Unmarshal(encoded, &arg) if err != nil { return nil, fmt.Errorf("failed to unmarshal cadence arguments: %w", err) diff --git a/cmd/util/cmd/execution-state-extract/cmd.go b/cmd/util/cmd/execution-state-extract/cmd.go index 34375a1c025..76a7d4721e3 100644 --- a/cmd/util/cmd/execution-state-extract/cmd.go +++ b/cmd/util/cmd/execution-state-extract/cmd.go @@ -370,28 +370,6 @@ func runE(*cobra.Command, []string) error { } } - migs = append( - migs, - migrations.NamedMigration{ - Name: "account-public-key-deduplication", - Migrate: migrations.NewAccountBasedMigration( - log.Logger, - flagNWorker, - []migrations.AccountBasedMigration{ - migrations.NewAccountPublicKeyDeduplicationMigration( - chain.ChainID(), - flagOutputDir, - flagValidate, - reporters.NewReportFileWriterFactory(flagOutputDir, log.Logger), - ), - migrations.NewAccountUsageMigration( - reporters.NewReportFileWriterFactoryWithFormat(flagOutputDir, log.Logger, reporters.ReportFormatCSV), - ), - }, - ), - }, - ) - migration := newMigration(log.Logger, migs, flagNWorker) payloads, err = migration(payloads) diff --git a/cmd/util/cmd/generate-authorization-fixes/cmd_test.go b/cmd/util/cmd/generate-authorization-fixes/cmd_test.go index 00d6b62d594..6d1bf83e1d6 100644 --- a/cmd/util/cmd/generate-authorization-fixes/cmd_test.go +++ b/cmd/util/cmd/generate-authorization-fixes/cmd_test.go @@ -29,9 +29,7 @@ func newBootstrapPayloads( bootstrapProcedureOptions ...fvm.BootstrapProcedureOption, ) ([]*ledger.Payload, error) { - ctx := fvm.NewContext( - fvm.WithChain(chainID.Chain()), - ) + ctx := fvm.NewContext(chainID.Chain()) vm := fvm.NewVirtualMachine() diff --git a/cmd/util/cmd/inspect-token-movements/cmd.go b/cmd/util/cmd/inspect-token-movements/cmd.go new file mode 100644 index 00000000000..fc236e996a0 --- /dev/null +++ b/cmd/util/cmd/inspect-token-movements/cmd.go @@ -0,0 +1,231 @@ +package inspect + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/spf13/cobra" + + "github.com/onflow/flow-go/cmd/util/cmd/common" + "github.com/onflow/flow-go/fvm/inspection" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" +) + +var ( + flagDatadir string + flagChunkDataPackDir string + flagChain string + flagFromTo string + flagLastK uint64 +) + +// Cmd is the command for inspecting token movements in executed blocks +// by reading chunk data packs and running the token changes inspector. +// +// # inspect the last 100 sealed blocks +// ./util inspect-token-movements --chain flow-mainnet --datadir /var/flow/data/protocol --chunk_data_pack_dir /var/flow/data/chunk_data_packs --lastk 100 +// # inspect the blocks from height 2000 to 3000 +// ./util inspect-token-movements --chain flow-mainnet --datadir /var/flow/data/protocol --chunk_data_pack_dir /var/flow/data/chunk_data_packs --from_to 2000_3000 +var Cmd = &cobra.Command{ + Use: "inspect-token-movements", + Short: "inspect token movements by analyzing chunk data packs for unaccounted token mints/burns", + Run: run, +} + +func init() { + Cmd.Flags().StringVar(&flagChain, "chain", "", "Chain name") + _ = Cmd.MarkFlagRequired("chain") + + common.InitDataDirFlag(Cmd, &flagDatadir) + + Cmd.Flags().StringVar(&flagChunkDataPackDir, "chunk_data_pack_dir", "/var/flow/data/chunk_data_packs", + "directory that stores the chunk data packs") + _ = Cmd.MarkFlagRequired("chunk_data_pack_dir") + + Cmd.Flags().Uint64Var(&flagLastK, "lastk", 1, + "last k sealed blocks to inspect") + + Cmd.Flags().StringVar(&flagFromTo, "from_to", "", + "the height range to inspect blocks (inclusive), i.e, 1_1000, 1000_2000, 2000_3000, etc.") +} + +func run(*cobra.Command, []string) { + lockManager := storage.MakeSingletonLockManager() + chainID := flow.ChainID(flagChain) + chain := chainID.Chain() + + lg := log.With(). + Str("chain", string(chainID)). + Str("datadir", flagDatadir). + Str("chunk_data_pack_dir", flagChunkDataPackDir). + Uint64("lastk", flagLastK). + Str("from_to", flagFromTo). + Logger() + + lg.Info().Msg("initializing token movements inspector") + + closer, storages, chunkDataPacks, state, err := initStorages(lockManager, flagDatadir, flagChunkDataPackDir) + if err != nil { + lg.Fatal().Err(err).Msg("could not init storages") + } + defer func() { + if closeErr := closer(); closeErr != nil { + lg.Warn().Err(closeErr).Msg("error closing storages") + } + }() + + // Create the token changes inspector with default search tokens for this chain + inspector := inspection.NewTokenChangesInspector(inspection.DefaultTokenDiffSearchTokens(chain), chainID) + + var from, to uint64 + + lastSealed, err := state.Sealed().Head() + if err != nil { + lg.Fatal().Err(err).Msg("could not get last sealed height") + } + + if flagFromTo != "" { + from, to, err = parseFromTo(flagFromTo) + if err != nil { + lg.Fatal().Err(err).Msg("could not parse from_to") + } + + if to > lastSealed.Height { + lg.Fatal().Msgf("'to' height (%d) exceeds last sealed block height (%d)", to, lastSealed.Height) + } + } else { + root := state.Params().SealedRoot().Height + + // preventing overflow + if flagLastK > lastSealed.Height+1 { + lg.Fatal().Msgf("k is greater than the number of sealed blocks, k: %d, last sealed height: %d", flagLastK, lastSealed.Height) + } + + from = lastSealed.Height - flagLastK + 1 + + // root block is not verifiable, because it's sealed already. + // the first verifiable is the next block of the root block + firstVerifiable := root + 1 + + if from < firstVerifiable { + from = firstVerifiable + } + to = lastSealed.Height + } + + root := state.Params().SealedRoot().Height + if from <= root { + lg.Fatal().Msgf("cannot inspect blocks before the root block, from: %d, root: %d", from, root) + } + + lg.Info().Msgf("inspecting token movements for blocks from %d to %d", from, to) + + for height := from; height <= to; height++ { + err := inspectHeight( + lg, + chainID, + height, + storages.Headers, + chunkDataPacks, + storages.Results, + state, + inspector, + ) + if err != nil { + lg.Error().Err(err).Uint64("height", height).Msg("error inspecting height") + } + } + + lg.Info().Msgf("finished inspecting token movements for blocks from %d to %d", from, to) +} + +func inspectHeight( + lg zerolog.Logger, + chainID flow.ChainID, + height uint64, + headers storage.Headers, + chunkDataPacks storage.ChunkDataPacks, + results storage.ExecutionResults, + protocolState protocol.State, + inspector *inspection.TokenChanges, +) error { + header, err := headers.ByHeight(height) + if err != nil { + return fmt.Errorf("could not get block header by height %d: %w", height, err) + } + + blockID := header.ID() + + result, err := results.ByBlockID(blockID) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + lg.Warn().Uint64("height", height).Hex("block_id", blockID[:]).Msg("execution result not found") + return nil + } + return fmt.Errorf("could not get execution result by block ID %s: %w", blockID, err) + } + + heightLg := lg.With(). + Uint64("height", height). + Hex("block_id", blockID[:]). + Logger() + + heightLg.Info().Int("num_chunks", len(result.Chunks)).Msg("inspecting block") + + for _, chunk := range result.Chunks { + chunkDataPack, err := chunkDataPacks.ByChunkID(chunk.ID()) + if err != nil { + return fmt.Errorf("could not get chunk data pack by chunk ID %s: %w", chunk.ID(), err) + } + + chunkLg := heightLg.With(). + Uint64("chunk_index", chunk.Index). + Logger() + + err = inspectChunkFromDataPack( + chunkLg, + chainID, + header, + chunk, + chunkDataPack, + result, + protocolState, + headers, + inspector, + ) + if err != nil { + chunkLg.Error().Err(err).Msg("error inspecting chunk") + } + } + + return nil +} + +func parseFromTo(fromTo string) (from, to uint64, err error) { + parts := strings.Split(fromTo, "_") + if len(parts) != 2 { + return 0, 0, fmt.Errorf("invalid format: expected 'from_to', got '%s'", fromTo) + } + + from, err = strconv.ParseUint(strings.TrimSpace(parts[0]), 10, 64) + if err != nil { + return 0, 0, fmt.Errorf("invalid 'from' value: %w", err) + } + + to, err = strconv.ParseUint(strings.TrimSpace(parts[1]), 10, 64) + if err != nil { + return 0, 0, fmt.Errorf("invalid 'to' value: %w", err) + } + + if from > to { + return 0, 0, fmt.Errorf("'from' value (%d) must be less than or equal to 'to' value (%d)", from, to) + } + + return from, to, nil +} diff --git a/cmd/util/cmd/inspect-token-movements/storage.go b/cmd/util/cmd/inspect-token-movements/storage.go new file mode 100644 index 00000000000..ae498db48ff --- /dev/null +++ b/cmd/util/cmd/inspect-token-movements/storage.go @@ -0,0 +1,395 @@ +package inspect + +import ( + "errors" + "fmt" + + "github.com/jordanschalm/lockctx" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + + "github.com/onflow/flow-go/cmd/util/cmd/common" + "github.com/onflow/flow-go/engine/execution/computation" + "github.com/onflow/flow-go/engine/execution/computation/computer" + executionState "github.com/onflow/flow-go/engine/execution/state" + "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm/blueprints" + "github.com/onflow/flow-go/fvm/initialize" + "github.com/onflow/flow-go/fvm/inspection" + "github.com/onflow/flow-go/fvm/storage/derived" + "github.com/onflow/flow-go/fvm/storage/logical" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger/partial" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/verification" + "github.com/onflow/flow-go/model/verification/convert" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + storagepebble "github.com/onflow/flow-go/storage/pebble" + "github.com/onflow/flow-go/storage/store" +) + +func initStorages( + lockManager lockctx.Manager, + dataDir string, + chunkDataPackDir string, +) ( + func() error, + *store.All, + storage.ChunkDataPacks, + protocol.State, + error, +) { + db, err := common.InitStorage(dataDir) + if err != nil { + return nil, nil, nil, nil, fmt.Errorf("could not init storage database: %w", err) + } + + storages := common.InitStorages(db) + state, err := common.OpenProtocolState(lockManager, db, storages) + if err != nil { + _ = db.Close() + return nil, nil, nil, nil, fmt.Errorf("could not open protocol state: %w", err) + } + + // require the chunk data pack data must exist before returning the storage module + chunkDataPackDB, err := storagepebble.ShouldOpenDefaultPebbleDB( + log.Logger.With().Str("pebbledb", "cdp").Logger(), chunkDataPackDir) + if err != nil { + _ = db.Close() + return nil, nil, nil, nil, fmt.Errorf("could not open chunk data pack DB: %w", err) + } + storedChunkDataPacks := store.NewStoredChunkDataPacks(metrics.NewNoopCollector(), pebbleimpl.ToDB(chunkDataPackDB), 1000) + chunkDataPacks := store.NewChunkDataPacks(metrics.NewNoopCollector(), + db, storedChunkDataPacks, storages.Collections, 1000) + + closer := func() error { + var dbErr, chunkDataPackDBErr error + + if err := db.Close(); err != nil { + dbErr = fmt.Errorf("failed to close protocol db: %w", err) + } + + if err := chunkDataPackDB.Close(); err != nil { + chunkDataPackDBErr = fmt.Errorf("failed to close chunk data pack db: %w", err) + } + return errors.Join(dbErr, chunkDataPackDBErr) + } + + return closer, storages, chunkDataPacks, state, nil +} + +// partialLedgerStorageSnapshot wraps a storage snapshot and tracks unknown register touches +type partialLedgerStorageSnapshot struct { + snapshot snapshot.StorageSnapshot + + unknownRegTouch map[flow.RegisterID]struct{} +} + +func (storage *partialLedgerStorageSnapshot) Get( + id flow.RegisterID, +) ( + flow.RegisterValue, + error, +) { + value, err := storage.snapshot.Get(id) + if err != nil && errors.Is(err, ledger.ErrMissingKeys{}) { + storage.unknownRegTouch[id] = struct{}{} + return flow.RegisterValue{}, nil + } + + return value, err +} + +// chunkInspector handles the inspection of chunks by re-executing transactions +type chunkInspector struct { + vm fvm.VM + vmCtx fvm.Context + systemChunkCtx fvm.Context + callbackCtx fvm.Context + logger zerolog.Logger + inspector *inspection.TokenChanges +} + +func newChunkInspector( + logger zerolog.Logger, + chainID flow.ChainID, + headers storage.Headers, + inspector *inspection.TokenChanges, +) *chunkInspector { + vm := fvm.NewVirtualMachine() + fvmOptions := initialize.InitFvmOptions( + chainID, + headers, + false, // transaction fees not disabled + ) + fvmOptions = append( + []fvm.Option{fvm.WithLogger(logger)}, + fvmOptions..., + ) + + fvmOptions = append( + fvmOptions, + computation.DefaultFVMOptions( + chainID, + false, + false, + false, + )..., + ) + vmCtx := fvm.NewContext(chainID.Chain(), fvmOptions...) + + return &chunkInspector{ + vm: vm, + vmCtx: vmCtx, + systemChunkCtx: computer.SystemChunkContext(vmCtx, metrics.NewNoopCollector()), + callbackCtx: computer.ScheduledTransactionContext(vmCtx, metrics.NewNoopCollector()), + logger: logger, + inspector: inspector, + } +} + +// inspectChunk re-executes transactions in the chunk and runs the token inspector. +// For system chunks, this mirrors the verification node's behavior by using the proper +// system chunk FVM context and handling scheduled callback transactions. +func (ci *chunkInspector) inspectChunk( + vc *verification.VerifiableChunkData, +) error { + var transactions []*fvm.TransactionProcedure + derivedBlockData := derived.NewEmptyDerivedBlockData(logical.Time(vc.TransactionOffset)) + + // Construct partial trie from chunk data pack + psmt, err := partial.NewLedger( + vc.ChunkDataPack.Proof, + ledger.State(vc.ChunkDataPack.StartState), + partial.DefaultPathFinderVersion, + ) + if err != nil { + return fmt.Errorf("could not construct partial trie: %w", err) + } + + // Create storage snapshot + unknownRegTouch := make(map[flow.RegisterID]struct{}) + snapshotTree := snapshot.NewSnapshotTree( + &partialLedgerStorageSnapshot{ + snapshot: executionState.NewLedgerStorageSnapshot( + psmt, + vc.ChunkDataPack.StartState), + unknownRegTouch: unknownRegTouch, + }) + + // Set up the appropriate FVM context and transactions based on chunk type + var ctx fvm.Context + var callbackCtx fvm.Context + var processAlreadyExecuted bool + + if vc.IsSystemChunk { + ctx = fvm.NewContextFromParent( + ci.systemChunkCtx, + fvm.WithBlockHeader(vc.Header), + fvm.WithProtocolStateSnapshot(vc.Snapshot), + fvm.WithDerivedBlockData(derivedBlockData), + ) + callbackCtx = fvm.NewContextFromParent( + ci.callbackCtx, + fvm.WithBlockHeader(vc.Header), + fvm.WithProtocolStateSnapshot(vc.Snapshot), + fvm.WithDerivedBlockData(derivedBlockData), + ) + + transactions, processAlreadyExecuted, err = ci.createSystemChunkTransactions( + callbackCtx, &snapshotTree, vc.TransactionOffset) + if err != nil { + return fmt.Errorf("could not create system chunk transactions: %w", err) + } + } else { + ctx = fvm.NewContextFromParent( + ci.vmCtx, + fvm.WithBlockHeader(vc.Header), + fvm.WithProtocolStateSnapshot(vc.Snapshot), + fvm.WithDerivedBlockData(derivedBlockData), + ) + + transactions = make( + []*fvm.TransactionProcedure, + 0, + len(vc.ChunkDataPack.Collection.Transactions)) + for i, txBody := range vc.ChunkDataPack.Collection.Transactions { + tx := fvm.Transaction(txBody, vc.TransactionOffset+uint32(i)) + transactions = append(transactions, tx) + } + } + + // Execute each transaction and inspect. + // For system chunks with scheduled transactions enabled, the process callback + // transaction (index 0) was already executed by createSystemChunkTransactions, + // so we start from index 1. + txStartIndex := 0 + if processAlreadyExecuted { + txStartIndex = 1 + } + + for i := txStartIndex; i < len(transactions); i++ { + tx := transactions[i] + txCtx := ctx + + // For system chunks with scheduled transactions, use callbackCtx for all + // transactions except the last (the system transaction itself). + if vc.IsSystemChunk && ci.vmCtx.ScheduledTransactionsEnabled && i < len(transactions)-1 { + txCtx = callbackCtx + } + + ci.logger.Info(). + Int("tx_index", i). + Hex("tx_id", tx.ID[:]). + Msg("executing transaction") + + executionSnapshot, output, err := ci.vm.Run( + txCtx, + tx, + snapshotTree) + if err != nil { + ci.logger.Warn(). + Err(err). + Int("tx_index", i). + Hex("tx_id", tx.ID[:]). + Msg("failed to execute transaction") + continue + } + + // Collect events for inspection + events := make([]flow.Event, 0, len(output.Events)+len(output.ServiceEvents)) + events = append(events, output.Events...) + events = append(events, output.ServiceEvents...) + + // Run the inspector + result, err := ci.inspector.Inspect(ci.logger, snapshotTree, executionSnapshot, events) + if err != nil { + ci.logger.Warn(). + Err(err). + Int("tx_index", i). + Hex("tx_id", tx.ID[:]). + Msg("failed to inspect transaction") + } else { + ci.logInspectionResult(tx.ID, i, result) + } + + // Update snapshot tree for next transaction + snapshotTree = snapshotTree.Append(executionSnapshot) + } + + return nil +} + +// createSystemChunkTransactions builds the transaction list for a system chunk, +// mirroring the verification node's ChunkVerifier.createSystemChunk logic. +// If scheduled transactions are disabled, returns only the system transaction. +// If enabled, executes the process callback transaction, generates execute callback +// transactions from its events, and appends the system transaction last. +// Returns the transaction list and whether the process callback was already executed +// (requiring the caller to skip it in the execution loop). +func (ci *chunkInspector) createSystemChunkTransactions( + callbackCtx fvm.Context, + snapshotTree *snapshot.SnapshotTree, + transactionOffset uint32, +) ([]*fvm.TransactionProcedure, bool, error) { + txIndex := transactionOffset + + // If scheduled transactions are disabled, only the system transaction is in the chunk + if !ci.vmCtx.ScheduledTransactionsEnabled { + txBody, err := blueprints.SystemChunkTransaction(ci.vmCtx.Chain) + if err != nil { + return nil, false, fmt.Errorf("could not get system chunk transaction: %w", err) + } + return []*fvm.TransactionProcedure{ + fvm.Transaction(txBody, txIndex), + }, false, nil + } + + // Execute process callback transaction to discover scheduled transactions + processBody, err := blueprints.ProcessCallbacksTransaction(ci.vmCtx.Chain) + if err != nil { + return nil, false, fmt.Errorf("could not get process callback transaction: %w", err) + } + processTx := fvm.Transaction(processBody, txIndex) + + executionSnapshot, processOutput, err := ci.vm.Run(callbackCtx, processTx, *snapshotTree) + if err != nil { + return nil, false, fmt.Errorf("failed to execute process callback transaction: %w", err) + } + + // Generate callback execution transactions from the events + callbackTxs, err := blueprints.ExecuteCallbacksTransactions(ci.vmCtx.Chain, processOutput.Events) + if err != nil { + return nil, false, fmt.Errorf("failed to generate callback execution transactions: %w", err) + } + + // Build the final transaction list: [processCallback, ...callbackExecutions, systemTx] + transactions := make([]*fvm.TransactionProcedure, 0, len(callbackTxs)+2) + transactions = append(transactions, processTx) + + for _, c := range callbackTxs { + txIndex++ + transactions = append(transactions, fvm.Transaction(c, txIndex)) + } + + systemTx, err := blueprints.SystemChunkTransaction(ci.vmCtx.Chain) + if err != nil { + return nil, false, fmt.Errorf("could not get system chunk transaction: %w", err) + } + txIndex++ + transactions = append(transactions, fvm.Transaction(systemTx, txIndex)) + + // Update snapshot tree with the process callback execution + *snapshotTree = snapshotTree.Append(executionSnapshot) + + return transactions, true, nil +} + +func (ci *chunkInspector) logInspectionResult(txID flow.Identifier, txIndex int, result inspection.Result) { + if result == nil { + ci.logger.Info().Msgf("no result from inspection, transaction did not trigger any token movements") + return + } + + lvl, evt := result.AsLogEvent() + if evt == nil { + ci.logger.Info().Msgf("transaction did not trigger any token movements") + return + } + + e := ci.logger.WithLevel(lvl). + Hex("tx_id", txID[:]). + Int("tx_index", txIndex) + evt(e) + e.Msg("Token inspection result") +} + +// inspectChunkFromDataPack creates a VerifiableChunkData and inspects it +func inspectChunkFromDataPack( + logger zerolog.Logger, + chainID flow.ChainID, + header *flow.Header, + chunk *flow.Chunk, + chunkDataPack *flow.ChunkDataPack, + result *flow.ExecutionResult, + protocolState protocol.State, + headers storage.Headers, + inspector *inspection.TokenChanges, +) error { + // Get protocol snapshot at the block + ps := protocolState.AtBlockID(header.ID()) + + // Convert to verifiable chunk data + vcd, err := convert.FromChunkDataPack(chunk, chunkDataPack, header, ps, result) + if err != nil { + return fmt.Errorf("could not convert chunk data pack: %w", err) + } + + // Create chunk inspector and run inspection + chunkInspector := newChunkInspector(logger, chainID, headers, inspector) + return chunkInspector.inspectChunk(vcd) +} diff --git a/cmd/util/cmd/pebble-checkpoint/cmd.go b/cmd/util/cmd/pebble-checkpoint/cmd.go index 247caa2612b..e054cf337bd 100644 --- a/cmd/util/cmd/pebble-checkpoint/cmd.go +++ b/cmd/util/cmd/pebble-checkpoint/cmd.go @@ -3,15 +3,17 @@ package cmd import ( "fmt" + "github.com/cockroachdb/pebble/v2" "github.com/rs/zerolog/log" "github.com/spf13/cobra" - "github.com/onflow/flow-go/storage/pebble" + flowpebble "github.com/onflow/flow-go/storage/pebble" ) var ( flagPebbleDir string flagOutput string + flagDBType string ) // Note: Although checkpoint is fast to create, it is not free. When creating a checkpoint, the @@ -32,16 +34,30 @@ func init() { Cmd.Flags().StringVar(&flagOutput, "output", "", "output directory for the checkpoint") _ = Cmd.MarkFlagRequired("output") + + Cmd.Flags().StringVar(&flagDBType, "db-type", "register", + "type of pebble database: 'register' (uses MVCCComparer) or 'protocol' (uses default comparer)") } func runE(*cobra.Command, []string) error { log.Info().Msgf("creating checkpoint from Pebble database at %v to %v", flagPebbleDir, flagOutput) - // Initialize Pebble DB - db, err := pebble.ShouldOpenDefaultPebbleDB(log.Logger, flagPebbleDir) + var db *pebble.DB + var err error + + switch flagDBType { + case "register": + db, err = flowpebble.OpenRegisterPebbleDB(log.Logger, flagPebbleDir) + case "protocol": + db, err = flowpebble.ShouldOpenDefaultPebbleDB(log.Logger, flagPebbleDir) + default: + return fmt.Errorf("unknown db-type %q, must be 'register' or 'protocol'", flagDBType) + } + if err != nil { return fmt.Errorf("failed to initialize Pebble database %v: %w", flagPebbleDir, err) } + defer db.Close() // Create checkpoint err = db.Checkpoint(flagOutput) diff --git a/cmd/util/cmd/root.go b/cmd/util/cmd/root.go index 342dd0d6838..7d8d80c81b1 100644 --- a/cmd/util/cmd/root.go +++ b/cmd/util/cmd/root.go @@ -18,11 +18,11 @@ import ( checkpoint_list_tries "github.com/onflow/flow-go/cmd/util/cmd/checkpoint-list-tries" checkpoint_trie_stats "github.com/onflow/flow-go/cmd/util/cmd/checkpoint-trie-stats" compare_cadence_vm "github.com/onflow/flow-go/cmd/util/cmd/compare-cadence-vm" + compare_debug_tx "github.com/onflow/flow-go/cmd/util/cmd/compare-debug-tx" db_migration "github.com/onflow/flow-go/cmd/util/cmd/db-migration" debug_script "github.com/onflow/flow-go/cmd/util/cmd/debug-script" debug_tx "github.com/onflow/flow-go/cmd/util/cmd/debug-tx" diff_states "github.com/onflow/flow-go/cmd/util/cmd/diff-states" - "github.com/onflow/flow-go/cmd/util/cmd/diffkeys" epochs "github.com/onflow/flow-go/cmd/util/cmd/epochs/cmd" export "github.com/onflow/flow-go/cmd/util/cmd/exec-data-json-export" edbs "github.com/onflow/flow-go/cmd/util/cmd/execution-data-blobstore/cmd" @@ -34,15 +34,18 @@ import ( find_inconsistent_result "github.com/onflow/flow-go/cmd/util/cmd/find-inconsistent-result" find_trie_root "github.com/onflow/flow-go/cmd/util/cmd/find-trie-root" generate_authorization_fixes "github.com/onflow/flow-go/cmd/util/cmd/generate-authorization-fixes" + inspect_token_movements "github.com/onflow/flow-go/cmd/util/cmd/inspect-token-movements" "github.com/onflow/flow-go/cmd/util/cmd/leaders" pebble_checkpoint "github.com/onflow/flow-go/cmd/util/cmd/pebble-checkpoint" read_badger "github.com/onflow/flow-go/cmd/util/cmd/read-badger/cmd" read_execution_state "github.com/onflow/flow-go/cmd/util/cmd/read-execution-state" read_hotstuff "github.com/onflow/flow-go/cmd/util/cmd/read-hotstuff/cmd" read_protocol_state "github.com/onflow/flow-go/cmd/util/cmd/read-protocol-state/cmd" + remove_execution_fork "github.com/onflow/flow-go/cmd/util/cmd/remove-execution-fork/cmd" rollback_executed_height "github.com/onflow/flow-go/cmd/util/cmd/rollback-executed-height/cmd" run_script "github.com/onflow/flow-go/cmd/util/cmd/run-script" "github.com/onflow/flow-go/cmd/util/cmd/snapshot" + storehouse_checkpoint_validator "github.com/onflow/flow-go/cmd/util/cmd/storehouse-checkpoint-validator" system_addresses "github.com/onflow/flow-go/cmd/util/cmd/system-addresses" verify_evm_offchain_replay "github.com/onflow/flow-go/cmd/util/cmd/verify-evm-offchain-replay" verify_execution_result "github.com/onflow/flow-go/cmd/util/cmd/verify_execution_result" @@ -127,6 +130,7 @@ func addCommands() { rootCmd.AddCommand(system_addresses.Cmd) rootCmd.AddCommand(check_storage.Cmd) rootCmd.AddCommand(debug_tx.Cmd) + rootCmd.AddCommand(compare_debug_tx.Cmd) rootCmd.AddCommand(debug_script.Cmd) rootCmd.AddCommand(generate_authorization_fixes.Cmd) rootCmd.AddCommand(evm_state_exporter.Cmd) @@ -134,8 +138,10 @@ func addCommands() { rootCmd.AddCommand(verify_evm_offchain_replay.Cmd) rootCmd.AddCommand(pebble_checkpoint.Cmd) rootCmd.AddCommand(db_migration.Cmd) - rootCmd.AddCommand(diffkeys.Cmd) rootCmd.AddCommand(compare_cadence_vm.Cmd) + rootCmd.AddCommand(storehouse_checkpoint_validator.Cmd) + rootCmd.AddCommand(remove_execution_fork.RootCmd) + rootCmd.AddCommand(inspect_token_movements.Cmd) } func initConfig() { diff --git a/cmd/util/cmd/run-script/cmd.go b/cmd/util/cmd/run-script/cmd.go index 31a1f1f2fc4..dd50ac41b66 100644 --- a/cmd/util/cmd/run-script/cmd.go +++ b/cmd/util/cmd/run-script/cmd.go @@ -134,7 +134,7 @@ func run(*cobra.Command, []string) { registersByAccount.AccountCount(), ) - options := computation.DefaultFVMOptions(chainID, false, false) + options := computation.DefaultFVMOptions(chainID, false, false, false) options = append( options, fvm.WithContractDeploymentRestricted(false), @@ -143,7 +143,7 @@ func run(*cobra.Command, []string) { fvm.WithSequenceNumberCheckAndIncrementEnabled(false), fvm.WithTransactionFeesEnabled(false), ) - ctx := fvm.NewContext(options...) + ctx := fvm.NewContext(chain, options...) storageSnapshot := registers.StorageSnapshot{ Registers: registersByAccount, @@ -183,6 +183,8 @@ func run(*cobra.Command, []string) { backend.Config{}, false, websockets.NewDefaultWebsocketConfig(), + nil, + nil, ) if err != nil { log.Fatal().Err(err).Msg("failed to create server") diff --git a/cmd/util/cmd/storehouse-checkpoint-validator/cmd.go b/cmd/util/cmd/storehouse-checkpoint-validator/cmd.go new file mode 100644 index 00000000000..c92455f4303 --- /dev/null +++ b/cmd/util/cmd/storehouse-checkpoint-validator/cmd.go @@ -0,0 +1,117 @@ +package storehouse_checkpoint_validator + +import ( + "context" + "fmt" + + "github.com/rs/zerolog/log" + "github.com/spf13/cobra" + + "github.com/onflow/flow-go/engine/execution/storehouse" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + pebblestorage "github.com/onflow/flow-go/storage/pebble" + "github.com/onflow/flow-go/storage/store" +) + +var ( + flagPebbleDir string + flagDataDir string + flagCheckpointDir string + flagBlockHeight uint64 + flagWorkerCount int +) + +var Cmd = &cobra.Command{ + Use: "storehouse-checkpoint-validator", + Short: "Validate registers in storehouse against checkpoint file", + Long: `Validate registers in storehouse against checkpoint file. +This command validates that all registers in the checkpoint file match the registers stored in the pebble database. +The checkpoint directory must contain a root.checkpoint file with a single trie.`, + RunE: runE, +} + +func init() { + Cmd.Flags().StringVar(&flagPebbleDir, "pebble-dir", "", + "directory containing the Pebble database with register store") + _ = Cmd.MarkFlagRequired("pebble-dir") + + Cmd.Flags().StringVar(&flagDataDir, "datadir", "/var/flow/data/protocol", + "directory containing the protocol database") + + Cmd.Flags().StringVar(&flagCheckpointDir, "checkpoint-dir", "", + "directory containing the checkpoint file (must have root.checkpoint)") + _ = Cmd.MarkFlagRequired("checkpoint-dir") + + Cmd.Flags().Uint64Var(&flagBlockHeight, "block-height", 0, + "block height to validate against") + _ = Cmd.MarkFlagRequired("block-height") + + Cmd.Flags().IntVar(&flagWorkerCount, "worker-count", 4, + "number of worker goroutines for validation") +} + +func runE(*cobra.Command, []string) error { + log.Info(). + Str("pebble-dir", flagPebbleDir). + Str("datadir", flagDataDir). + Str("checkpoint-dir", flagCheckpointDir). + Uint64("block-height", flagBlockHeight). + Int("worker-count", flagWorkerCount). + Msg("starting storehouse checkpoint validation") + + // Open pebble DB for register store + // Note: Register store uses a special comparer, so we use OpenRegisterPebbleDB + pebbleDB, err := pebblestorage.OpenRegisterPebbleDB(log.Logger, flagPebbleDir) + if err != nil { + return fmt.Errorf("failed to open pebble database at %s: %w", flagPebbleDir, err) + } + defer func() { + if closeErr := pebbleDB.Close(); closeErr != nil { + log.Error().Err(closeErr).Msg("failed to close pebble database") + } + }() + + // Initialize register store + // Using PruningDisabled to ensure we can access all registers + registerStore, err := pebblestorage.NewRegisters(pebbleDB, pebblestorage.PruningDisabled) + if err != nil { + return fmt.Errorf("failed to initialize register store: %w", err) + } + + // Open protocol database from datadir + protocolPebbleDB, err := pebblestorage.ShouldOpenDefaultPebbleDB(log.Logger, flagDataDir) + if err != nil { + return fmt.Errorf("failed to open protocol database at %s: %w", flagDataDir, err) + } + defer func() { + if closeErr := protocolPebbleDB.Close(); closeErr != nil { + log.Error().Err(closeErr).Msg("failed to close protocol database") + } + }() + + protocolDB := pebbleimpl.ToDB(protocolPebbleDB) + + // Initialize storage components + metricsCollector := &metrics.NoopCollector{} + storages := store.InitAll(metricsCollector, protocolDB) + + // Validate checkpoint + ctx := context.Background() + err = storehouse.ValidateWithCheckpoint( + log.Logger, + ctx, + registerStore, + storages.Results, + storages.Headers, + flagCheckpointDir, + flagBlockHeight, + flagWorkerCount, + ) + if err != nil { + return fmt.Errorf("validation failed: %w", err) + } + + log.Info().Msg("validation completed successfully") + return nil +} diff --git a/cmd/util/cmd/verify_execution_result/cmd.go b/cmd/util/cmd/verify_execution_result/cmd.go index c5c1c111ebd..42e9eabbf76 100644 --- a/cmd/util/cmd/verify_execution_result/cmd.go +++ b/cmd/util/cmd/verify_execution_result/cmd.go @@ -88,6 +88,8 @@ func run(*cobra.Command, []string) { lg.Info().Msgf("look for 'could not verify' in the log for any mismatch, or try again with --stop_on_mismatch true to stop on first mismatch") } + var totalStats verifier.BlockVerificationStats + if flagFromTo != "" { from, to, err := parseFromTo(flagFromTo) if err != nil { @@ -95,8 +97,7 @@ func run(*cobra.Command, []string) { } lg.Info().Msgf("verifying range from %d to %d", from, to) - - err = verifier.VerifyRange( + totalStats, err = verifier.VerifyRange( lockManager, from, to, @@ -111,10 +112,11 @@ func run(*cobra.Command, []string) { if err != nil { lg.Fatal().Err(err).Msgf("could not verify range from %d to %d", from, to) } - lg.Info().Msgf("finished verified range from %d to %d", from, to) + lg.Info().Msgf("finished verifying range from %d to %d", from, to) } else { lg.Info().Msgf("verifying last %d sealed blocks", flagLastK) - err := verifier.VerifyLastKHeight( + var err error + totalStats, err = verifier.VerifyLastKHeight( lockManager, flagLastK, chainID, @@ -129,8 +131,15 @@ func run(*cobra.Command, []string) { lg.Fatal().Err(err).Msg("could not verify last k height") } - lg.Info().Msgf("finished verified last %d sealed blocks", flagLastK) + lg.Info().Msgf("finished verifying last %d sealed blocks", flagLastK) } + + lg.Info().Msgf("matching chunks: %d/%d. matching transactions: %d/%d", + totalStats.MatchedChunkCount, + totalStats.MatchedChunkCount+totalStats.MismatchedChunkCount, + totalStats.MatchedTransactionCount, + totalStats.MatchedTransactionCount+totalStats.MismatchedTransactionCount, + ) } func parseFromTo(fromTo string) (from, to uint64, err error) { diff --git a/cmd/util/ledger/migrations/account_based_migration_test.go b/cmd/util/ledger/migrations/account_based_migration_test.go index c06a6a7f090..0a6cbaf19f2 100644 --- a/cmd/util/ledger/migrations/account_based_migration_test.go +++ b/cmd/util/ledger/migrations/account_based_migration_test.go @@ -21,7 +21,7 @@ func accountStatusPayload(address common.Address) *ledger.Payload { return ledger.NewPayload( convert.RegisterIDToLedgerKey( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), ), accountStatus.ToBytes(), ) diff --git a/cmd/util/ledger/migrations/account_key_deduplication_encoder.go b/cmd/util/ledger/migrations/account_key_deduplication_encoder.go deleted file mode 100644 index 9944d0a301d..00000000000 --- a/cmd/util/ledger/migrations/account_key_deduplication_encoder.go +++ /dev/null @@ -1,535 +0,0 @@ -package migrations - -import ( - "encoding/binary" - "fmt" - "math" - - accountkeymetadata "github.com/onflow/flow-go/fvm/environment/account-key-metadata" - "github.com/onflow/flow-go/model/flow" -) - -const ( - lengthPrefixSize = 4 - runLengthSize = 2 -) - -// Account Public Key Weight and Revoked Status - -const ( - // maxRunLengthInEncodedStatusGroup (65535) is the max run length that - // can be stored in each RLE encoded status group. - maxRunLengthInEncodedStatusGroup = math.MaxUint16 - - // weightAndRevokedStatusSize (2) is the number of bytes used to store - // the weight and status together as a uint16: - // - the high bit is the revoked status - // - the remaining 15 bits is the weight (more than enough for its 0..1000 range) - weightAndRevokedStatusSize = 2 - - // weightAndRevokedStatusGroupSize (4) is the number of bytes used to store - // the uint16 run length and the uint16 representing weight and revoked status. - weightAndRevokedStatusGroupSize = runLengthSize + weightAndRevokedStatusSize - - // revokedMask is the bitmask for setting or getting the revoked flag stored - // as the high bit of a uint16. - revokedMask = 0x8000 - - // weightMask is the bitmask for getting the weight from the low 15 bits (fifteen bits) of - // the uint16 containing the unsigned 15-bit weight. - weightMask = 0x7fff -) - -type accountPublicKeyWeightAndRevokedStatus struct { - weight uint16 // Weight is 0-1000 - revoked bool -} - -// accountPublicKeyWeightAndRevokedStatus is encoded using RLE: -// - run length (2 bytes) -// - value (2 bytes): revoked status is the high bit and weight is the remaining 15 bits. -// NOTE: if number of elements in a run-length group exceeds maxRunLengthInEncodedStatusGroup, -// a new group is created with remaining run-length and the same weight and revoked status. -func encodeAccountPublicKeyWeightsAndRevokedStatus(weightsAndRevoked []accountPublicKeyWeightAndRevokedStatus) ([]byte, error) { - if len(weightsAndRevoked) == 0 { - return nil, nil - } - - buf := make([]byte, 0, len(weightsAndRevoked)*(weightAndRevokedStatusGroupSize)) - - off := 0 - for i := 0; i < len(weightsAndRevoked); { - runLength := 1 - value := weightsAndRevoked[i] - i++ - - // Find group boundary - for i < len(weightsAndRevoked) && runLength < maxRunLengthInEncodedStatusGroup && weightsAndRevoked[i] == value { - runLength++ - i++ - } - - // Encode weight and revoked status group - - buf = buf[:off+weightAndRevokedStatusGroupSize] - - binary.BigEndian.PutUint16(buf[off:], uint16(runLength)) - off += runLengthSize - - weightAndRevoked := value.weight - if value.revoked { - weightAndRevoked |= revokedMask // Turn on high bit for revoked status - } - - binary.BigEndian.PutUint16(buf[off:], weightAndRevoked) - off += weightAndRevokedStatusSize - } - - return buf, nil -} - -func decodeAccountPublicKeyWeightAndRevokedStatusGroups(b []byte) ([]accountPublicKeyWeightAndRevokedStatus, error) { - if len(b)%weightAndRevokedStatusGroupSize != 0 { - return nil, fmt.Errorf("failed to decode weight and revoked status: expect multiple of %d bytes, got %d", weightAndRevokedStatusGroupSize, len(b)) - } - - statuses := make([]accountPublicKeyWeightAndRevokedStatus, 0, len(b)/weightAndRevokedStatusGroupSize) - - for i := 0; i < len(b); i += weightAndRevokedStatusGroupSize { - runLength := uint32(binary.BigEndian.Uint16(b[i:])) - weightAndRevoked := binary.BigEndian.Uint16(b[i+2 : i+4]) - - status := accountPublicKeyWeightAndRevokedStatus{ - weight: weightAndRevoked & weightMask, - revoked: (weightAndRevoked & revokedMask) > 0, - } - - for range runLength { - statuses = append(statuses, status) - } - } - - return statuses, nil -} - -// Account Public Key Index to Stored Public Key Index Mappings -const ( - storedKeyIndexSize = 4 - mappingGroupSize = runLengthSize + storedKeyIndexSize - consecutiveGroupFlagMask = 0x8000 - lengthMask = 0x7fff -) - -// encodeAccountPublicKeyMapping encodes keyIndexMappings into concatenated run-length groups. -// Each run-length group is encoded as: -// - length in the low 15 bits of uint16 (2 bytes) -// - stored key index as uint32 (4 bytes) -// For example, account has 8 account keys with 5 unique keys. -// Unique key index mapping is {Key0, Key1, Key1, Key1, Key1, Key2, Key3, Key4}. -// The example's encoded mapping would be: -// { {run-length 1, value 0}, {run-length 4, value 1}, {consecutive-run-length 3, start-value 2}} -func encodeAccountPublicKeyMapping(mapping []uint32) ([]byte, error) { - if len(mapping) == 0 { - return nil, nil - } - - firstGroup := accountkeymetadata.NewMappingGroup(1, mapping[0], false) - - if len(mapping) == 1 { - return firstGroup.Encode(), nil - } - - groups := make([]*accountkeymetadata.MappingGroup, 0, len(mapping)) - groups = append(groups, firstGroup) - - lastGroup := firstGroup - for _, storedKeyIndex := range mapping[1:] { - if !lastGroup.TryMerge(storedKeyIndex) { - // Create and append new group - lastGroup = accountkeymetadata.NewMappingGroup(1, storedKeyIndex, false) - groups = append(groups, lastGroup) - } - } - - return accountkeymetadata.MappingGroups(groups).Encode(), nil -} - -func decodeAccountPublicKeyMapping(b []byte) ([]uint32, error) { - if len(b)%mappingGroupSize != 0 { - return nil, fmt.Errorf("failed to decode mappings: expect multiple of %d bytes, got %d", mappingGroupSize, len(b)) - } - - mapping := make([]uint32, 0, len(b)/mappingGroupSize) - - for i := 0; i < len(b); i += mappingGroupSize { - runLength := binary.BigEndian.Uint16(b[i:]) - storedKeyIndex := binary.BigEndian.Uint32(b[i+runLengthSize:]) - - if consecutiveBit := (runLength & consecutiveGroupFlagMask) >> 15; consecutiveBit == 1 { - runLength &= lengthMask - - for i := range runLength { - mapping = append(mapping, storedKeyIndex+uint32(i)) - } - } else { - for range runLength { - mapping = append(mapping, storedKeyIndex) - } - } - } - - return mapping, nil -} - -// Digest list - -const digestSize = 8 - -// encodeDigestList encodes digests into concatenated uint64. -func encodeDigestList(digests []uint64) []byte { - if len(digests) == 0 { - return nil - } - encodedDigestList := make([]byte, digestSize*len(digests)) - off := 0 - for _, digest := range digests { - binary.BigEndian.PutUint64(encodedDigestList[off:], digest) - off += digestSize - } - return encodedDigestList -} - -func decodeDigestList(b []byte) ([]uint64, error) { - if len(b)%digestSize != 0 { - return nil, fmt.Errorf("failed to decode digest list: expect multiple of %d byte, got %d", digestSize, len(b)) - } - - storedDigestCount := len(b) / digestSize - - digests := make([]uint64, 0, storedDigestCount) - - for i := 0; i < len(b); i += digestSize { - digests = append(digests, binary.BigEndian.Uint64(b[i:])) - } - - return digests, nil -} - -// Public Key Batch Register - -const ( - maxEncodedKeySize = math.MaxUint8 // Encoded public key size is ~70 bytes -) - -// PublicKeyBatch register contains up to maxBatchPublicKeyCount number of encoded public keys. -// Each public key is encoded as: -// - length prefixed encoded public key -func encodePublicKeysInBatches(encodedPublicKey [][]byte, maxPublicKeyCountInBatch int) ([][]byte, error) { - // Return early if there is only one encoded public key (first public key). - // First public key is stored in its own register, not in batch public key register. - if len(encodedPublicKey) <= 1 { - return nil, nil - } - - // Reset first encoded public key to nil during encoding - // to avoid encoding first account public key in batch public key. - - firstEncodedPublicKey := encodedPublicKey[0] - defer func() { - encodedPublicKey[0] = firstEncodedPublicKey - }() - - encodedPublicKey[0] = nil - - values := make([][]byte, 0, len(encodedPublicKey)/maxPublicKeyCountInBatch+1) - - for i := 0; i < len(encodedPublicKey); { - batchCount := min(maxPublicKeyCountInBatch, len(encodedPublicKey)-i) - - encodedBatchPublicKey, err := encodeBatchPublicKey(encodedPublicKey[i : i+batchCount]) - if err != nil { - return nil, err - } - - values = append(values, encodedBatchPublicKey) - - i += batchCount - } - - return values, nil -} - -func encodeBatchPublicKey(encodedPublicKey [][]byte) ([]byte, error) { - - size := 0 - for _, encoded := range encodedPublicKey { - if len(encoded) > maxEncodedKeySize { - return nil, fmt.Errorf("encoded key size is %d bytes, exceeded max size %d", len(encoded), maxEncodedKeySize) - } - size += 1 + len(encoded) - } - - buf := make([]byte, size) - off := 0 - for _, encoded := range encodedPublicKey { - buf[off] = byte(len(encoded)) - off++ - - n := copy(buf[off:], encoded) - off += n - } - - return buf, nil -} - -func decodeBatchPublicKey(b []byte) ([][]byte, error) { - if len(b) == 0 { - return nil, nil - } - - encodedPublicKeys := make([][]byte, 0, maxPublicKeyCountInBatch) - - off := 0 - for off < len(b) { - size := int(b[off]) - off++ - - if off+size > len(b) { - return nil, fmt.Errorf("failed to decode batch public key: off %d + size %d out of bounds %d: %x", off, size, len(b), b) - } - - encodedPublicKey := b[off : off+size] - off += size - - encodedPublicKeys = append(encodedPublicKeys, encodedPublicKey) - } - - if off != len(b) { - return nil, fmt.Errorf("failed to decode batch public key: trailing data (%d bytes): %x", len(b)-off, b) - } - - return encodedPublicKeys, nil -} - -// Account Status register - -const ( - versionMask = 0xf0 - flagMask = 0x0f - deduplicatedAccountStatusV4VerionAndFlagByte = 0x41 - nondeduplicatedAccountStatusV4VerionAndFlagByte = 0x40 - accountStatusV4MinimumSize = 29 // Same size as account status v3 -) - -// encodeAccountStatusV4WithPublicKeyMetadata encodes public key metadata section -// in "a.s" register depending on deduplicated flag. -// -// With deduplicated flag, account status is encoded as: -// - account status v3 (29 bytes) -// - length prefixed list of account public key weight and revoked status starting from key index 1 -// - startKeyIndex (4 bytes) + length prefixed list of account public key index mappings to stored key index -// - startStoredKeyIndex (4 bytes) + length prefixed list of last N stored key digests -// -// Without deduplicated flag, account status is encoded as: -// - account status v3 (29 bytes) -// - length prefixed list of account public key weight and revoked status starting from key index 1 -// - startStoredKeyIndex (4 bytes) + length prefixed list of last N stored key digests -func encodeAccountStatusV4WithPublicKeyMetadata( - original []byte, - weightAndRevokedStatus []accountPublicKeyWeightAndRevokedStatus, - startKeyIndexForDigests uint32, - keyDigests []uint64, - startKeyIndexForMappings uint32, - accountPublicKeyMappings []uint32, - deduplicated bool, -) ([]byte, error) { - - // Return early if the original account status payload contains any optional fields. - if len(original) != accountStatusV4MinimumSize { - return nil, fmt.Errorf("failed to encode account status payload: original payload has %d bytes, expect %d bytes", len(original), accountStatusV4MinimumSize) - } - - // Encode list of account public key weight and revoked status - encodedAccountPublicKeyWeightAndRevokedStatus, err := encodeAccountPublicKeyWeightsAndRevokedStatus(weightAndRevokedStatus) - if err != nil { - return nil, err - } - - // Encode list of key digests - encodedKeyDigests := encodeDigestList(keyDigests) - - // Encode mappings for deduplicated account public keys - var encodedAccountPublicKeyMapping []byte - if deduplicated { - encodedAccountPublicKeyMapping, err = encodeAccountPublicKeyMapping(accountPublicKeyMappings) - if err != nil { - return nil, err - } - } - - newAccountStatusPayloadSize := len(original) + - lengthPrefixSize + len(encodedAccountPublicKeyWeightAndRevokedStatus) + // length prefixed account public key weight and revoked status - 4 + // start stored key index for digests - lengthPrefixSize + len(encodedKeyDigests) // length prefixed digests - - if deduplicated { - newAccountStatusPayloadSize += 4 + // start key index for mapping - lengthPrefixSize + len(encodedAccountPublicKeyMapping) // used to retrieve account public key - } - - buf := make([]byte, newAccountStatusPayloadSize) - off := 0 - - // Append account status v4 version and flag - if deduplicated { - buf[0] = deduplicatedAccountStatusV4VerionAndFlagByte - } else { - buf[0] = nondeduplicatedAccountStatusV4VerionAndFlagByte - } - off++ - - // Append original content, except for the flag byte - n := copy(buf[off:], original[1:]) - off += n - - // Append length prefixed encoded revoked status - binary.BigEndian.PutUint32(buf[off:], uint32(len(encodedAccountPublicKeyWeightAndRevokedStatus))) - off += 4 - - n = copy(buf[off:], encodedAccountPublicKeyWeightAndRevokedStatus) - off += n - - if deduplicated { - // Append start key index for mapping - binary.BigEndian.PutUint32(buf[off:], startKeyIndexForMappings) - off += 4 - - // Append length prefixed account public key mapping - binary.BigEndian.PutUint32(buf[off:], uint32(len(encodedAccountPublicKeyMapping))) - off += 4 - - n = copy(buf[off:], encodedAccountPublicKeyMapping) - off += n - } - - // Append start key index for digests - binary.BigEndian.PutUint32(buf[off:], startKeyIndexForDigests) - off += 4 - - // Append length prefixed key digests - binary.BigEndian.PutUint32(buf[off:], uint32(len(encodedKeyDigests))) - off += 4 - - n = copy(buf[off:], encodedKeyDigests) - off += n - - return buf[:off], nil -} - -func decodeAccountStatusKeyMetadata(b []byte, deduplicated bool) ( - weightAndRevokedStatus []accountPublicKeyWeightAndRevokedStatus, - startKeyIndexForMapping uint32, - accountPublicKeyMappings []uint32, - startKeyIndexForDigests uint32, - digests []uint64, - err error, -) { - // Decode weight and revoked list - - var weightAndRevokedGroupsData []byte - weightAndRevokedGroupsData, b, err = parseNextLengthPrefixedData(b) - if err != nil { - err = fmt.Errorf("failed to decode AccountStatusV4: %w", err) - return - } - - weightAndRevokedStatus, err = decodeAccountPublicKeyWeightAndRevokedStatusGroups(weightAndRevokedGroupsData) - if err != nil { - err = fmt.Errorf("failed to decode weight and revoked status list: %w", err) - return - } - - // Decode account public key mapping if deduplication is on - - if deduplicated { - if len(b) < 4 { - err = fmt.Errorf("failed to decode AccountStatusV4: expect 4 bytes of start key index for mapping, got %d bytes", len(b)) - return - } - - startKeyIndexForMapping = binary.BigEndian.Uint32(b) - - b = b[4:] - - var mappingData []byte - mappingData, b, err = parseNextLengthPrefixedData(b) - if err != nil { - err = fmt.Errorf("failed to decode AccountStatusV4: %w", err) - return - } - - accountPublicKeyMappings, err = decodeAccountPublicKeyMapping(mappingData) - if err != nil { - err = fmt.Errorf("failed to decode account public key mappings: %w", err) - return - } - } - - // Decode digests list - - if len(b) < 4 { - err = fmt.Errorf("failed to decode AccountStatusV4: expect 4 bytes of start stored key index for digests, got %d bytes", len(b)) - return - } - - startKeyIndexForDigests = binary.BigEndian.Uint32(b) - b = b[4:] - - var digestsData []byte - digestsData, b, err = parseNextLengthPrefixedData(b) - if err != nil { - err = fmt.Errorf("failed to decode AccountStatusV4: %w", err) - return - } - - digests, err = decodeDigestList(digestsData) - if err != nil { - err = fmt.Errorf("failed to decode digests: %w", err) - return - } - - // Check trailing data - - if len(b) != 0 { - err = fmt.Errorf("failed to decode AccountStatusV4: got %d extra bytes", len(b)) - return - } - - return -} - -func parseNextLengthPrefixedData(b []byte) (next []byte, rest []byte, err error) { - if len(b) < lengthPrefixSize { - return nil, nil, fmt.Errorf("failed to decode data: expect at least 4 bytes, got %d bytes", len(b)) - } - - length := binary.BigEndian.Uint32(b[:lengthPrefixSize]) - - if len(b) < lengthPrefixSize+int(length) { - return nil, nil, fmt.Errorf("failed to decode data: expect at least %d bytes, got %d bytes", lengthPrefixSize+int(length), len(b)) - } - - b = b[lengthPrefixSize:] - return b[:length], b[length:], nil -} - -// Stored Public Key - -func encodeStoredPublicKeyFromAccountPublicKey(a flow.AccountPublicKey) ([]byte, error) { - storedPublicKey := flow.StoredPublicKey{ - PublicKey: a.PublicKey, - SignAlgo: a.SignAlgo, - HashAlgo: a.HashAlgo, - } - return flow.EncodeStoredPublicKey(storedPublicKey) -} diff --git a/cmd/util/ledger/migrations/account_key_deduplication_encoder_test.go b/cmd/util/ledger/migrations/account_key_deduplication_encoder_test.go deleted file mode 100644 index 84f9a8b1d95..00000000000 --- a/cmd/util/ledger/migrations/account_key_deduplication_encoder_test.go +++ /dev/null @@ -1,553 +0,0 @@ -package migrations - -import ( - "crypto/rand" - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/onflow/flow-go/fvm/environment" -) - -func TestAccountPublicKeyWeightsAndRevokedStatusSerizliation(t *testing.T) { - testcases := []struct { - name string - status []accountPublicKeyWeightAndRevokedStatus - expected []byte - }{ - { - name: "empty", - status: nil, - expected: nil, - }, - { - name: "one status", - status: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1000, revoked: false}, - }, - expected: []byte{0, 1, 0x03, 0xe8}, - }, - { - name: "multiple identical status", - status: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - }, - expected: []byte{0, 3, 0x83, 0xe8}, - }, - { - name: "different status", - status: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 2, revoked: false}, - {weight: 2, revoked: true}, - }, - expected: []byte{ - 0, 1, 0, 1, - 0, 1, 0, 2, - 0, 1, 0x80, 2, - }, - }, - { - name: "different status", - status: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 2, revoked: true}, - }, - expected: []byte{ - 0, 2, 0, 1, - 0, 1, 0x80, 2, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - b, err := encodeAccountPublicKeyWeightsAndRevokedStatus(tc.status) - require.NoError(t, err) - require.Equal(t, tc.expected, b) - - decodedStatus, err := decodeAccountPublicKeyWeightAndRevokedStatusGroups(b) - require.NoError(t, err) - require.ElementsMatch(t, tc.status, decodedStatus) - }) - } - - t.Run("run length around max group count", func(t *testing.T) { - testcases := []struct { - name string - status accountPublicKeyWeightAndRevokedStatus - count uint32 - expected []byte - }{ - { - name: "run length maxRunLengthInEncodedStatusGroup - 1", - status: accountPublicKeyWeightAndRevokedStatus{weight: 1000, revoked: true}, - count: maxRunLengthInEncodedStatusGroup - 1, - expected: []byte{ - 0xff, 0xfe, 0x83, 0xe8, - }, - }, - { - name: "run length maxRunLengthInEncodedStatusGroup ", - status: accountPublicKeyWeightAndRevokedStatus{weight: 1000, revoked: true}, - count: maxRunLengthInEncodedStatusGroup, - expected: []byte{ - 0xff, 0xff, 0x83, 0xe8, - }, - }, - { - name: "run length maxRunLengthInEncodedStatusGroup + 1", - status: accountPublicKeyWeightAndRevokedStatus{weight: 1000, revoked: true}, - count: maxRunLengthInEncodedStatusGroup + 1, - expected: []byte{ - 0xff, 0xff, 0x83, 0xe8, - 0x00, 0x01, 0x83, 0xe8, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - status := make([]accountPublicKeyWeightAndRevokedStatus, tc.count) - for i := range len(status) { - status[i] = tc.status - } - - b, err := encodeAccountPublicKeyWeightsAndRevokedStatus(status) - require.NoError(t, err) - require.Equal(t, tc.expected, b) - - decodedStatus, err := decodeAccountPublicKeyWeightAndRevokedStatusGroups(b) - require.NoError(t, err) - require.ElementsMatch(t, status, decodedStatus) - }) - } - }) -} - -func TestMappingGroupSerialization(t *testing.T) { - testcases := []struct { - name string - mappings []uint32 - expected []byte - }{ - { - name: "1 group with run length 1", - mappings: []uint32{1}, - expected: []byte{ - 0, 1, 0, 0, 0, 1, - }, - }, - { - name: "2 groups with different run length", - mappings: []uint32{1, 1, 2}, - expected: []byte{ - 0, 2, 0, 0, 0, 1, - 0, 1, 0, 0, 0, 2, - }, - }, - { - name: "consecutive group count followed by regular group", - mappings: []uint32{1, 2, 2}, - expected: []byte{ - 0x80, 2, 0, 0, 0, 1, - 0, 1, 0, 0, 0, 2, - }, - }, - { - name: "group value not consecutive", - mappings: []uint32{1, 3}, - expected: []byte{ - 0, 1, 0, 0, 0, 1, - 0, 1, 0, 0, 0, 3, - }, - }, - { - name: "consecutive group with run length 2", - mappings: []uint32{1, 2}, - expected: []byte{ - 0x80, 2, 0, 0, 0, 1, - }, - }, - { - name: "consecutive group with run length 3", - mappings: []uint32{1, 2, 3}, - expected: []byte{ - 0x80, 3, 0, 0, 0, 1, - }, - }, - { - name: "consecutive group followed by non-consecutive group", - mappings: []uint32{1, 2, 2}, - expected: []byte{ - 0x80, 2, 0, 0, 0, 1, - 0, 1, 0, 0, 0, 2, - }, - }, - { - name: "consecutive group followed by consecutive group", - mappings: []uint32{1, 2, 2, 3}, - expected: []byte{ - 0x80, 2, 0, 0, 0, 1, - 0x80, 2, 0, 0, 0, 2, - }, - }, - { - name: "consecutive groups mixed with non-consecutive groups", - mappings: []uint32{1, 3, 4, 5, 5, 5, 5, 6, 7, 7}, - expected: []byte{ - 0, 1, 0, 0, 0, 1, - 0x80, 3, 0, 0, 0, 3, - 0, 3, 0, 0, 0, 5, - 0x80, 2, 0, 0, 0, 6, - 0, 1, 0, 0, 0, 7, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - b, err := encodeAccountPublicKeyMapping(tc.mappings) - require.NoError(t, err) - require.Equal(t, tc.expected, b) - - decodedMappings, err := decodeAccountPublicKeyMapping(b) - require.NoError(t, err) - require.ElementsMatch(t, tc.mappings, decodedMappings) - }) - } -} - -func TestDigestListSerialization(t *testing.T) { - testcases := []struct { - name string - digests []uint64 - expected []byte - }{ - { - name: "empty", - digests: nil, - expected: nil, - }, - { - name: "1 digest", - digests: []uint64{1}, - expected: []byte{ - 0, 0, 0, 0, 0, 0, 0, 1, - }, - }, - { - name: "2 digests", - digests: []uint64{1, 2}, - expected: []byte{ - 0, 0, 0, 0, 0, 0, 0, 1, - 0, 0, 0, 0, 0, 0, 0, 2, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - b := encodeDigestList(tc.digests) - require.Equal(t, tc.expected, b) - - decodedDigests, err := decodeDigestList(b) - require.NoError(t, err) - require.ElementsMatch(t, tc.digests, decodedDigests) - }) - } -} - -func TestBatchPublicKeySerialization(t *testing.T) { - t.Run("empty", func(t *testing.T) { - b, err := encodePublicKeysInBatches(nil, maxPublicKeyCountInBatch) - require.NoError(t, err) - require.Empty(t, b) - - decodedPublicKeys, err := decodeBatchPublicKey(nil) - require.NoError(t, err) - require.Empty(t, decodedPublicKeys) - }) - - t.Run("1 public key", func(t *testing.T) { - encodedPublicKey := make([]byte, 73) - _, _ = rand.Read(encodedPublicKey) - - b, err := encodePublicKeysInBatches([][]byte{encodedPublicKey}, maxPublicKeyCountInBatch) - require.NoError(t, err) - require.Empty(t, b) - }) - - t.Run("2 public key", func(t *testing.T) { - encodedPublicKey1 := make([]byte, 73) - _, _ = rand.Read(encodedPublicKey1) - - encodedPublicKey2 := make([]byte, 80) - _, _ = rand.Read(encodedPublicKey2) - - encodedPublicKeys := [][]byte{encodedPublicKey1, encodedPublicKey2} - - b, err := encodePublicKeysInBatches(encodedPublicKeys, maxPublicKeyCountInBatch) - require.NoError(t, err) - require.True(t, len(b) == 1) - - decodedPublicKeys, err := decodeBatchPublicKey(b[0]) - require.NoError(t, err) - require.True(t, len(decodedPublicKeys) == 2) - require.Empty(t, decodedPublicKeys[0]) - require.Equal(t, encodedPublicKey2, decodedPublicKeys[1]) - }) - - t.Run("2 batches of public key", func(t *testing.T) { - encodedPublicKeys := make([][]byte, maxPublicKeyCountInBatch*1.5) - - for i := range len(encodedPublicKeys) { - encodedPublicKeys[i] = make([]byte, 70+i) - _, _ = rand.Read(encodedPublicKeys[i]) - } - - b, err := encodePublicKeysInBatches(encodedPublicKeys, maxPublicKeyCountInBatch) - require.NoError(t, err) - require.True(t, len(b) == 2) - - // Decode first batch - decodedPublicKeys, err := decodeBatchPublicKey(b[0]) - require.NoError(t, err) - require.True(t, len(decodedPublicKeys) == maxPublicKeyCountInBatch) - require.Empty(t, decodedPublicKeys[0]) - for i := 1; i < maxPublicKeyCountInBatch; i++ { - require.Equal(t, encodedPublicKeys[i], decodedPublicKeys[i]) - } - - // Decode second batch - decodedPublicKeys, err = decodeBatchPublicKey(b[1]) - require.NoError(t, err) - require.True(t, len(decodedPublicKeys) == len(encodedPublicKeys)-maxPublicKeyCountInBatch) - for i := range len(decodedPublicKeys) { - require.Equal(t, encodedPublicKeys[i+maxPublicKeyCountInBatch], decodedPublicKeys[i]) - } - }) -} - -func TestAccountStatusV4Serialization(t *testing.T) { - // NOTE: account status only contains key metadata - // if there are at least 2 account public keys. - - testcases := []struct { - name string - deduplicated bool - accountPublicKeyCount uint32 - weightAndRevokedStatus []accountPublicKeyWeightAndRevokedStatus - startIndexForDigests uint32 - digests []uint64 - startIndexForMappings uint32 - accountPublicKeyMappings []uint32 - expected []byte - }{ - { - name: "not deduplicated with 2 account public key", - deduplicated: false, - accountPublicKeyCount: uint32(2), - weightAndRevokedStatus: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1000, revoked: false}, - }, - startIndexForDigests: uint32(0), - digests: []uint64{1, 2}, - expected: []byte{ - // Required Fields - 0x40, // version + flag - 0, 0, 0, 0, 0, 0, 0, 0, // init value for storage used - 0, 0, 0, 0, 0, 0, 0, 1, // init value for storage index - 0, 0, 0, 2, // init value for public key counts - 0, 0, 0, 0, 0, 0, 0, 0, // init value for address id counter - // Optional Fields - 0, 0, 0, 4, // length prefix for weight and revoked list - 0, 1, 3, 0xe8, // weight and revoked group - 0, 0, 0, 0, // start index for digests - 0, 0, 0, 0x10, // length prefix for digests - 0, 0, 0, 0, 0, 0, 0, 1, // digest 1 - 0, 0, 0, 0, 0, 0, 0, 2, // digest 2 - }, - }, - { - name: "not deduplicated with 3 account public key", - deduplicated: false, - accountPublicKeyCount: uint32(3), - weightAndRevokedStatus: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - }, - startIndexForDigests: uint32(1), - digests: []uint64{2, 3}, - expected: []byte{ - // Required Fields - 0x40, // version + flag - 0, 0, 0, 0, 0, 0, 0, 0, // init value for storage used - 0, 0, 0, 0, 0, 0, 0, 1, // init value for storage index - 0, 0, 0, 3, // init value for public key counts - 0, 0, 0, 0, 0, 0, 0, 0, // init value for address id counter - // Optional Fields - 0, 0, 0, 4, // length prefix for weight and revoked list - 0, 2, 3, 0xe8, // weight and revoked group - 0, 0, 0, 1, // start index for digests - 0, 0, 0, 0x10, // length prefix for digests - 0, 0, 0, 0, 0, 0, 0, 2, // digest 2 - 0, 0, 0, 0, 0, 0, 0, 3, // digest 3 - }, - }, - { - name: "deduplicated with 2 account public key (1 stored key)", - deduplicated: true, - accountPublicKeyCount: uint32(2), - weightAndRevokedStatus: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1000, revoked: false}, - }, - startIndexForDigests: uint32(0), - digests: []uint64{1}, - startIndexForMappings: uint32(1), - accountPublicKeyMappings: []uint32{0}, - expected: []byte{ - // Required Fields - 0x41, // version + flag - 0, 0, 0, 0, 0, 0, 0, 0, // init value for storage used - 0, 0, 0, 0, 0, 0, 0, 1, // init value for storage index - 0, 0, 0, 2, // init value for public key counts - 0, 0, 0, 0, 0, 0, 0, 0, // init value for address id counter - // Optional Fields - 0, 0, 0, 4, // length prefix for weight and revoked list - 0, 1, 3, 0xe8, // weight and revoked group - 0, 0, 0, 1, // start index for mapping - 0, 0, 0, 6, // length prefix for mapping - 0, 1, 0, 0, 0, 0, // mapping group 1 - 0, 0, 0, 0, // start index for digests - 0, 0, 0, 8, // length prefix for digests - 0, 0, 0, 0, 0, 0, 0, 1, // digest 1 - }, - }, - { - name: "deduplicated with 3 account public key (2 stored keys)", - deduplicated: true, - accountPublicKeyCount: uint32(3), - weightAndRevokedStatus: []accountPublicKeyWeightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - }, - startIndexForDigests: uint32(0), - digests: []uint64{1, 2}, - startIndexForMappings: uint32(1), - accountPublicKeyMappings: []uint32{0, 1}, - expected: []byte{ - // Required Fields - 0x41, // version + flag - 0, 0, 0, 0, 0, 0, 0, 0, // init value for storage used - 0, 0, 0, 0, 0, 0, 0, 1, // init value for storage index - 0, 0, 0, 3, // init value for public key counts - 0, 0, 0, 0, 0, 0, 0, 0, // init value for address id counter - // Optional Fields - 0, 0, 0, 4, // length prefix for weight and revoked list - 0, 2, 3, 0xe8, // weight and revoked group - 0, 0, 0, 1, // start index for mapping - 0, 0, 0, 6, // length prefix for mapping - 0x80, 2, 0, 0, 0, 0, // mapping group 1 - 0, 0, 0, 0, // start index for digests - 0, 0, 0, 0x10, // length prefix for digests - 0, 0, 0, 0, 0, 0, 0, 1, // digest 1 - 0, 0, 0, 0, 0, 0, 0, 2, // digest 2 - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - - s := environment.NewAccountStatus() - s.SetAccountPublicKeyCount(tc.accountPublicKeyCount) - - b, err := encodeAccountStatusV4WithPublicKeyMetadata( - s.ToBytes(), - tc.weightAndRevokedStatus, - tc.startIndexForDigests, - tc.digests, - tc.startIndexForMappings, - tc.accountPublicKeyMappings, - tc.deduplicated, - ) - require.NoError(t, err) - require.Equal(t, tc.expected, b) - - _, decodedWeightAndRevokedStatus, decodedStartIndexForDigests, decodedDigests, decodedStartIndexForMappings, decodedAccountPublicKeyMappings, err := decodeAccountStatusV4(b) - require.NoError(t, err) - require.ElementsMatch(t, tc.weightAndRevokedStatus, decodedWeightAndRevokedStatus) - require.Equal(t, tc.startIndexForDigests, decodedStartIndexForDigests) - require.ElementsMatch(t, tc.digests, decodedDigests) - require.Equal(t, tc.startIndexForMappings, decodedStartIndexForMappings) - require.ElementsMatch(t, tc.accountPublicKeyMappings, decodedAccountPublicKeyMappings) - - err = validateKeyMetadata( - tc.deduplicated, - tc.accountPublicKeyCount, - decodedWeightAndRevokedStatus, - decodedStartIndexForDigests, - decodedDigests, - decodedStartIndexForMappings, - decodedAccountPublicKeyMappings) - require.NoError(t, err) - }) - } -} - -func decodeAccountStatusV4(b []byte) ( - requiredFields []byte, - weightAndRevokedStatus []accountPublicKeyWeightAndRevokedStatus, - startKeyIndexForDigests uint32, - digests []uint64, - startKeyIndexForMapping uint32, - accountPublicKeyMappings []uint32, - err error, -) { - if len(b) < accountStatusV4MinimumSize { - return nil, nil, 0, nil, 0, nil, fmt.Errorf("failed to decode AccountStatusV4: expect at least %d byte, got %d bytes", accountStatusV4MinimumSize, len(b)) - } - - version, flag := b[0]&versionMask>>4, b[0]&flagMask - - if version != 4 { - return nil, nil, 0, nil, 0, nil, fmt.Errorf("failed to decode AccountStatusV4: expect version 4, got %d", version) - } - - if flag != 0 && flag != 1 { - return nil, nil, 0, nil, 0, nil, fmt.Errorf("failed to decode AccountStatusV4: expect flag 0 or 1, got %d", flag) - } - - deduplicated := flag == 1 - - requiredFields = append([]byte(nil), b[:accountStatusV4MinimumSize]...) - optionalFields := append([]byte(nil), b[accountStatusV4MinimumSize:]...) - - accountStatus, err := environment.AccountStatusFromBytes(requiredFields) - if err != nil { - return nil, nil, 0, nil, 0, nil, err - } - - accountPublicKeyCount := accountStatus.AccountPublicKeyCount() - - if accountPublicKeyCount <= 1 { - if len(optionalFields) > 0 { - return nil, nil, 0, nil, 0, nil, fmt.Errorf("failed to decode AccountStatusV4: found optional fields when account public key count is %d", accountPublicKeyCount) - } - - if deduplicated { - return nil, nil, 0, nil, 0, nil, fmt.Errorf("failed to create AccountStatusV4: deduplication flag should be off when account public key is less than 2") - } - - return requiredFields, nil, 0, nil, 0, nil, err - } - - weightAndRevokedStatus, startKeyIndexForMapping, accountPublicKeyMappings, startKeyIndexForDigests, digests, err = decodeAccountStatusKeyMetadata(optionalFields, deduplicated) - - return -} diff --git a/cmd/util/ledger/migrations/account_key_deduplication_migration.go b/cmd/util/ledger/migrations/account_key_deduplication_migration.go deleted file mode 100644 index 0ab3edca023..00000000000 --- a/cmd/util/ledger/migrations/account_key_deduplication_migration.go +++ /dev/null @@ -1,455 +0,0 @@ -package migrations - -import ( - "context" - "encoding/binary" - "encoding/hex" - "fmt" - "path" - "sync" - "time" - - "github.com/fxamacker/circlehash" - "github.com/rs/zerolog" - - "github.com/onflow/cadence/common" - - "github.com/onflow/flow-go/cmd/util/ledger/reporters" - "github.com/onflow/flow-go/cmd/util/ledger/util/registers" - "github.com/onflow/flow-go/fvm/environment" - "github.com/onflow/flow-go/model/flow" -) - -// NOTE: The term "payload" and "register" are used interchangeably here. - -// Public key deduplication migration deduplicates public keys and migrates related payloads. -// Migration includes: -// - Optionally appending account public key metadata in "a.s" (account status) payload. -// - Weight and revoked status of each account public key, encoded using RLE to save space. -// The weight cannot be modified and revoke status is infrequently modified. -// - Key index mapping to stored key index mapping (only for accounts with duplication flag) -// encoded in RLE to save space. -// - Last N digests to detect duplicate keys being added at runtime (after migration and spork). -// - Renaming the payload key from "public_key_0" to "apk_0" without changing the payload value. -// - Migrating public keys from individual payloads to batch deduplicated public key payloads, -// starting from the second unique public key. -// - Migrating non-zero sequence number of account public key to its own payload. -// NOTE: We store and update the sequence number of each account public key in a separate payload -// to avoid blocking some use cases of concurrent execution. -// -// Using a data format (account public key metadata) that can detect duplicates and store deduplication data -// requires storing some related information (overhead) but in most cases the overhead is more than offset -// by deduplication. -// To avoid or reduce overhead, -// - migration only adds key metadata section to "a.s" payload for accounts with at least two keys. -// - migration only stores digests of the last N unique public keys (N=2 is good, using more wasn't always better). -// - migration only stores account public keys to stored public keys mappings if key deduplication occurred. -// -// More specifically: -// - For accounts with 0 public keys, migration skips them -// - For accounts with 1 public key, migration only renames the "public_key_0" payload to "apk_0" (no other changes) -// - For accounts with at least two keys, migration: -// * renames the "public_key_0" payload to "apk_0" -// * stores unique keys in batch public key payload, starting from public key 1 -// * stores non-zero sequence numbers in sequence number payloads -// * adds account key weights and revoked statuses to the key metadata section in key metadata section -// * adds digests of only the last N unique public keys in key metadata section (N=2 is the default) -// * adds account public key to unique key mappings if any key is deduplicated - -const ( - legacyAccountPublicKeyRegisterKeyPrefix = "public_key_" - legacyAccountPublicKeyRegisterKeyPattern = "public_key_%d" - legacyAccountPublicKey0RegisterKey = "public_key_0" -) - -const ( - maxPublicKeyCountInBatch = 20 // 20 public key payload is ~1420 bytes - maxStoredDigests = 2 // Account status payload stores up to 2 digests from last 2 stored keys. -) - -const ( - dummyDigest = uint64(0) -) - -// AccountPublicKeyDeduplicationMigration deduplicates account public keys, -// and migrates account status and account public key related payloads. -type AccountPublicKeyDeduplicationMigration struct { - log zerolog.Logger - chainID flow.ChainID - outputDir string - reporter reporters.ReportWriter - validationReporter reporters.ReportWriter - migrationResult migrationResult - accountMigrationResults []accountMigrationResult - resultLock sync.Mutex - validate bool -} - -var _ AccountBasedMigration = (*AccountPublicKeyDeduplicationMigration)(nil) - -func NewAccountPublicKeyDeduplicationMigration( - chainID flow.ChainID, - outputDir string, - validate bool, - rwf reporters.ReportWriterFactory, -) *AccountPublicKeyDeduplicationMigration { - - m := &AccountPublicKeyDeduplicationMigration{ - chainID: chainID, - reporter: rwf.ReportWriter("account-public-key-deduplication-migration_summary"), - outputDir: outputDir, - validate: validate, - } - - if validate { - m.validationReporter = rwf.ReportWriter("account-public-key-deduplication-validation") - } - - return m -} - -func (m *AccountPublicKeyDeduplicationMigration) InitMigration( - log zerolog.Logger, - registersByAccount *registers.ByAccount, - _ int, -) error { - m.log = log.With().Str("component", "DeduplicateAccountPublicKey").Logger() - m.accountMigrationResults = make([]accountMigrationResult, 0, registersByAccount.AccountCount()) - return nil -} - -func (m *AccountPublicKeyDeduplicationMigration) MigrateAccount( - _ context.Context, - address common.Address, - accountRegisters *registers.AccountRegisters, -) error { - beforeCount := accountRegisters.Count() - beforeSize := accountRegisters.PayloadSize() - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys(m.log, accountRegisters) - if err != nil { - return fmt.Errorf("failed to migrate and deduplicate account public keys for account %x: %w", accountRegisters.Owner(), err) - } - - if m.validate { - err := ValidateAccountPublicKeyV4(address, accountRegisters) - if err != nil { - m.validationReporter.Write(validationError{ - Address: address.Hex(), - Msg: err.Error(), - }) - } - } - - afterCount := accountRegisters.Count() - afterSize := accountRegisters.PayloadSize() - - migrationResult := accountMigrationResult{ - address: hex.EncodeToString([]byte(accountRegisters.Owner())), - beforeCount: beforeCount, - beforeSize: beforeSize, - afterCount: afterCount, - afterSize: afterSize, - deduplicated: deduplicated, - } - - m.resultLock.Lock() - defer m.resultLock.Unlock() - - m.accountMigrationResults = append(m.accountMigrationResults, migrationResult) - - if deduplicated { - m.migrationResult.TotalDeduplicatedAccountCount++ - } else { - m.migrationResult.TotalUndeduplicatedAccountCount++ - } - - m.migrationResult.TotalSizeDelta += afterSize - beforeSize - m.migrationResult.TotalCountDelta += afterCount - beforeCount - - return nil -} - -func (m *AccountPublicKeyDeduplicationMigration) Close() error { - // Write migration summary - m.reporter.Write(m.migrationResult) - defer m.reporter.Close() - - // Write account migration results - fileName := path.Join(m.outputDir, fmt.Sprintf("%s_%d.csv", "account_public_key_deduplication_account_migration_results", int32(time.Now().Unix()))) - return writeAccountMigrationResults(fileName, m.accountMigrationResults) -} - -func migrateAndDeduplicateAccountPublicKeys( - log zerolog.Logger, - accountRegisters *registers.AccountRegisters, -) (deduplicated bool, _ error) { - - owner := accountRegisters.Owner() - - encodedAccountStatusV4, err := migrateAccountStatusToV4(log, accountRegisters, owner) - if err != nil { - return false, fmt.Errorf("failed to migrate account status from v3 to v4 for %x: %w", owner, err) - } - - accountStatusV4, err := environment.AccountStatusFromBytes(encodedAccountStatusV4) - if err != nil { - return false, fmt.Errorf("failed to create AccountStatus from migrated payload for %x: %w", owner, err) - } - - accountPublicKeyCount := accountStatusV4.AccountPublicKeyCount() - - if accountPublicKeyCount == 0 { - return false, nil - } - - if accountPublicKeyCount == 1 { - _, err := migrateAccountPublicKey0(accountRegisters, owner) - if err != nil { - return false, fmt.Errorf("failed to migrate account public key 0 for %x: %w", owner, err) - } - return false, nil - } - - encodedAccountPublicKey0, err := migrateAccountPublicKey0(accountRegisters, owner) - if err != nil { - return false, fmt.Errorf("failed to migrate account public key 0 for %x: %w", owner, err) - } - - return migrateAndDeduplicateAccountPublicKeysIfNeeded( - log, - accountRegisters, - owner, - accountPublicKeyCount, - encodedAccountPublicKey0, - ) -} - -func migrateAndDeduplicateAccountPublicKeysIfNeeded( - log zerolog.Logger, - accountRegisters *registers.AccountRegisters, - owner string, - accountPublicKeyCount uint32, - encodedAccountPublicKey0 []byte, -) ( - deduplicated bool, - err error, -) { - // TODO: maybe special case migration for accounts with 2 account public keys (16% of accounts) - - // accountPublicKeyWeightAndRevokedStatuses is ordered by account public key index, - // starting from account public key at index 1. - accountPublicKeyWeightAndRevokedStatuses := make([]accountPublicKeyWeightAndRevokedStatus, 0, accountPublicKeyCount-1) - - // Account public key deduplicator deduplicates keys. - deduplicator := newAccountPublicKeyDeduplicator(owner, accountPublicKeyCount) - - // Add account public key 0 to deduplicator - err = deduplicator.addEncodedAccountPublicKey(0, encodedAccountPublicKey0) - if err != nil { - return false, fmt.Errorf("failed to add account public key at index %d for owner %x to deduplicator: %w", 0, owner, err) - } - - for keyIndex := uint32(1); keyIndex < accountPublicKeyCount; keyIndex++ { - - decodedAccountPublicKey, err := getAccountPublicKeyOrError(accountRegisters, owner, keyIndex) - if err != nil { - return false, fmt.Errorf("failed to decode public key at index %d for owner %x: %w", keyIndex, owner, err) - } - - err = deduplicator.addAccountPublicKey(keyIndex, decodedAccountPublicKey) - if err != nil { - return false, fmt.Errorf("failed to add account public key at index %d for owner %x to deduplicator: %w", keyIndex, owner, err) - } - - // Save weight and revoked status for account public key - accountPublicKeyWeightAndRevokedStatuses = append( - accountPublicKeyWeightAndRevokedStatuses, - accountPublicKeyWeightAndRevokedStatus{ - weight: uint16(decodedAccountPublicKey.Weight), - revoked: decodedAccountPublicKey.Revoked, - }, - ) - - // Migrate sequence number for account public key - // NOTE: sequence number is stored in its own payload, decoupled from public key. - err = migrateSeqNumberIfNeeded(accountRegisters, owner, keyIndex, decodedAccountPublicKey.SeqNumber) - if err != nil { - return false, fmt.Errorf("failed to migrate sequence number at index %d for owner %x: %w", keyIndex, owner, err) - } - - // Remove account public key from storage - // NOTE: account public key starting from key index 1 stores in batch. - err = removeAccountPublicKey(accountRegisters, owner, keyIndex) - if err != nil { - return false, fmt.Errorf("failed to remove public key at index %d for owner %x: %w", keyIndex, owner, err) - } - } - - shouldDeduplicate := deduplicator.hasDuplicateKey() - - encodedPublicKeys := deduplicator.uniqueKeys() - - // Migrate account status with account public key metadata - err = migrateAccountStatusWithPublicKeyMetadata( - log, - accountRegisters, - owner, - accountPublicKeyWeightAndRevokedStatuses, - encodedPublicKeys, - deduplicator.keyIndexMapping(), - shouldDeduplicate, - ) - if err != nil { - return false, fmt.Errorf("failed to migrate account status with key metadata for account %x: %w", owner, err) - } - - // Migrate account public key at index >= 1 - err = migrateAccountPublicKeysIfNeeded(accountRegisters, owner, encodedPublicKeys) - if err != nil { - return false, fmt.Errorf("failed to migrate account public keys in batches for account %x: %w", owner, err) - } - - return shouldDeduplicate, nil -} - -// accountPublicKeyDeduplicator deduplicates all account public keys (including account public key 0). -type accountPublicKeyDeduplicator struct { - owner string - - accountPublicKeyCount uint32 - - // uniqEncodedPublicKeysMap is used to deduplicate encoded public key. - uniqEncodedPublicKeysMap map[string]uint32 // key: encoded public key, value: index of uniqEncodedPublicKeys - - // uniqEncodedPublicKeys contains unique encoded public key. - // NOTE: First element is always encoded account public key 0. - uniqEncodedPublicKeys [][]byte - - // accountPublicKeyIndexMappings contains mapping of account public key index to unique public key index. - // NOTE: First mapping is always 0 (account public key index 0) to 0 (unique key index 0). - accountPublicKeyIndexMappings []uint32 // index: account public key index, element: uniqEncodedPublicKeys index -} - -func newAccountPublicKeyDeduplicator(owner string, accountPublicKeyCount uint32) *accountPublicKeyDeduplicator { - return &accountPublicKeyDeduplicator{ - owner: owner, - accountPublicKeyCount: accountPublicKeyCount, - uniqEncodedPublicKeysMap: make(map[string]uint32), - uniqEncodedPublicKeys: make([][]byte, 0, accountPublicKeyCount), - accountPublicKeyIndexMappings: make([]uint32, accountPublicKeyCount), - } -} - -func (d *accountPublicKeyDeduplicator) addEncodedAccountPublicKey( - keyIndex uint32, - encodedAccountPublicKey []byte, -) error { - accountPublicKey0, err := flow.DecodeAccountPublicKey(encodedAccountPublicKey, keyIndex) - if err != nil { - return fmt.Errorf("failed to decode account public key %d for owner %x: %w", keyIndex, d.owner, err) - } - return d.addAccountPublicKey(keyIndex, accountPublicKey0) -} - -func (d *accountPublicKeyDeduplicator) addAccountPublicKey( - keyIndex uint32, - accountPublicKey flow.AccountPublicKey, -) error { - encodedPublicKey, err := encodeStoredPublicKeyFromAccountPublicKey(accountPublicKey) - if err != nil { - return fmt.Errorf("failed to encode stored public key at index %d for owner %x: %w", keyIndex, d.owner, err) - } - - if uniqKeyIndex, exists := d.uniqEncodedPublicKeysMap[string(encodedPublicKey)]; !exists { - // New key is unique - - // Append key to unique key list - d.uniqEncodedPublicKeys = append(d.uniqEncodedPublicKeys, encodedPublicKey) - - // Unique key index is the last key index in uniqEncodedPublicKeys. - uniqKeyIndex = uint32(len(d.uniqEncodedPublicKeys) - 1) - - // Append unique key index to account public key mappings - d.accountPublicKeyIndexMappings[keyIndex] = uniqKeyIndex - - d.uniqEncodedPublicKeysMap[string(encodedPublicKey)] = uniqKeyIndex - } else { - // New key is duplicate - d.accountPublicKeyIndexMappings[keyIndex] = uniqKeyIndex - } - - return nil -} - -func (d *accountPublicKeyDeduplicator) hasDuplicateKey() bool { - return d.accountPublicKeyCount > uint32(len(d.uniqEncodedPublicKeys)) -} - -func (d *accountPublicKeyDeduplicator) keyIndexMapping() []uint32 { - return d.accountPublicKeyIndexMappings -} - -func (d *accountPublicKeyDeduplicator) uniqueKeys() [][]byte { - return d.uniqEncodedPublicKeys -} - -func generateLastNPublicKeyDigests( - log zerolog.Logger, - owner string, - encodedPublicKeys [][]byte, - n int, - hashFunc func(b []byte, seed uint64) uint64, -) (int, []uint64) { - digestCount := min(len(encodedPublicKeys), n) - startIndex := len(encodedPublicKeys) - digestCount - digests := generatePublicKeyDigests(log, owner, encodedPublicKeys[startIndex:], hashFunc) - return startIndex, digests -} - -// generatePublicKeyDigests returns digests of encodedPublicKeys. -func generatePublicKeyDigests( - log zerolog.Logger, - owner string, - encodedPublicKeys [][]byte, - hashFunc func(b []byte, seed uint64) uint64, -) (digests []uint64) { - if hashFunc == nil { - hashFunc = circlehash.Hash64 - } - - seed := binary.BigEndian.Uint64([]byte(owner)) - - digests = make([]uint64, len(encodedPublicKeys)) - - collisions := make(map[uint64][]int) - hasCollision := false - - for i, encodedPublicKey := range encodedPublicKeys { - digest := hashFunc(encodedPublicKey, seed) - - if _, exists := collisions[digest]; exists { - hasCollision = true - digests[i] = dummyDigest - } else { - digests[i] = digest - } - - collisions[digest] = append(collisions[digest], i) - } - - if hasCollision { - for digest, encodedPublicKeyIndexes := range collisions { - if len(encodedPublicKeyIndexes) > 1 { - log.Warn().Msgf("found digest collisions for account %x: digest %d, encoded public key indexes %v", owner, digest, encodedPublicKeyIndexes) - } - } - } - - return digests -} - -type validationError struct { - Address string - Msg string -} diff --git a/cmd/util/ledger/migrations/account_key_deduplication_migration_results.go b/cmd/util/ledger/migrations/account_key_deduplication_migration_results.go deleted file mode 100644 index f3ec9656b85..00000000000 --- a/cmd/util/ledger/migrations/account_key_deduplication_migration_results.go +++ /dev/null @@ -1,78 +0,0 @@ -package migrations - -import ( - "cmp" - "encoding/csv" - "fmt" - "os" - "slices" - "strconv" -) - -type accountMigrationResult struct { - address string - beforeCount int - beforeSize int - afterCount int - afterSize int - deduplicated bool -} - -type migrationResult struct { - TotalDeduplicatedAccountCount int `json:"deduplicated_account"` - TotalUndeduplicatedAccountCount int `json:"undeduplicated_account"` - TotalCountDelta int `json:"register_count_delta"` - TotalSizeDelta int `json:"register_size_delta"` -} - -func writeAccountMigrationResults( - fileName string, - migrationResults []accountMigrationResult, -) error { - slices.SortFunc(migrationResults, func(a, b accountMigrationResult) int { - r := cmp.Compare(a.beforeCount, b.beforeCount) - if r != 0 { - return r - } - return cmp.Compare(a.address, b.address) - }) - - file, err := os.Create(fileName) - if err != nil { - return fmt.Errorf("failed to create account migration result file %s: %w", fileName, err) - } - defer file.Close() - - w := csv.NewWriter(file) - defer w.Flush() - - header := []string{ - "address", - "before_count", - "before_size", - "after_count", - "after_size", - "deduplicated", - } - - // Write header - err = w.Write(header) - if err != nil { - return fmt.Errorf("failed to write header to %s: %w", fileName, err) - } - - for _, migrationStats := range migrationResults { - data := []string{ - migrationStats.address, - strconv.Itoa(migrationStats.beforeCount), - strconv.Itoa(migrationStats.beforeSize), - strconv.Itoa(migrationStats.afterCount), - strconv.Itoa(migrationStats.afterSize), - strconv.FormatBool(migrationStats.deduplicated), - } - if err := w.Write(data); err != nil { - return fmt.Errorf("failed to write migration result for %s: %w", migrationStats.address, err) - } - } - return nil -} diff --git a/cmd/util/ledger/migrations/account_key_deduplication_migration_test.go b/cmd/util/ledger/migrations/account_key_deduplication_migration_test.go deleted file mode 100644 index 86c40fdc66c..00000000000 --- a/cmd/util/ledger/migrations/account_key_deduplication_migration_test.go +++ /dev/null @@ -1,648 +0,0 @@ -package migrations - -import ( - "crypto/rand" - "encoding/binary" - "fmt" - "testing" - - "github.com/fxamacker/circlehash" - "github.com/onflow/cadence/common" - "github.com/rs/zerolog" - "github.com/stretchr/testify/require" - - "github.com/onflow/flow-go/cmd/util/ledger/util/registers" - "github.com/onflow/flow-go/model/flow" - "github.com/onflow/flow-go/utils/unittest" -) - -func TestAccountPublicKeyDeduplicator(t *testing.T) { - pk1 := newAccountPublicKey(t, 1000) - pkb1, err := encodeStoredPublicKeyFromAccountPublicKey(pk1) - require.NoError(t, err) - - pk2 := newAccountPublicKey(t, 1000) - pkb2, err := encodeStoredPublicKeyFromAccountPublicKey(pk2) - require.NoError(t, err) - - pk3 := newAccountPublicKey(t, 1000) - pkb3, err := encodeStoredPublicKeyFromAccountPublicKey(pk3) - require.NoError(t, err) - - pk4 := newAccountPublicKey(t, 1000) - pkb4, err := encodeStoredPublicKeyFromAccountPublicKey(pk4) - require.NoError(t, err) - - pk5 := newAccountPublicKey(t, 1000) - pkb5, err := encodeStoredPublicKeyFromAccountPublicKey(pk5) - require.NoError(t, err) - - testcases := []struct { - name string - keys []flow.AccountPublicKey - encodedUniqueKeys [][]byte - mappings []uint32 - hasDeduplicate bool - }{ - { - name: "empty", - }, - { - name: "1 key", - keys: []flow.AccountPublicKey{pk1}, - encodedUniqueKeys: [][]byte{pkb1}, - mappings: []uint32{0}, - }, - { - name: "2 unique key", - keys: []flow.AccountPublicKey{pk1, pk2}, - encodedUniqueKeys: [][]byte{pkb1, pkb2}, - mappings: []uint32{0, 1}, - }, - { - name: "2 duplicate key", - keys: []flow.AccountPublicKey{pk1, pk1}, - encodedUniqueKeys: [][]byte{pkb1}, - mappings: []uint32{0, 0}, - hasDeduplicate: true, - }, - { - name: "5 keys with 1 unique keys", - keys: []flow.AccountPublicKey{pk1, pk1, pk1, pk1, pk1}, - encodedUniqueKeys: [][]byte{pkb1}, - mappings: []uint32{0, 0, 0, 0, 0}, - hasDeduplicate: true, - }, - { - name: "5 keys with 4 unique keys", - keys: []flow.AccountPublicKey{pk1, pk2, pk1, pk3, pk4}, - encodedUniqueKeys: [][]byte{pkb1, pkb2, pkb3, pkb4}, - mappings: []uint32{0, 1, 0, 2, 3}, - hasDeduplicate: true, - }, - { - name: "5 keys with 5 unique keys", - keys: []flow.AccountPublicKey{pk1, pk2, pk3, pk4, pk5}, - encodedUniqueKeys: [][]byte{pkb1, pkb2, pkb3, pkb4, pkb5}, - mappings: []uint32{0, 1, 2, 3, 4}, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - deduplicator := newAccountPublicKeyDeduplicator("a", uint32(len(tc.keys))) - - for i, pk := range tc.keys { - err = deduplicator.addAccountPublicKey(uint32(i), pk) - require.NoError(t, err) - } - - require.Equal(t, tc.hasDeduplicate, deduplicator.hasDuplicateKey()) - - keys := deduplicator.uniqueKeys() - require.ElementsMatch(t, tc.encodedUniqueKeys, keys) - - mapping := deduplicator.keyIndexMapping() - require.ElementsMatch(t, tc.mappings, mapping) - }) - } -} - -func TestDigestForLastNEncodedPublicKeys(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - seed := binary.BigEndian.Uint64(owner[:]) - - type pkData struct { - pk flow.AccountPublicKey - pkb []byte - digest uint64 - } - - pks := make([]pkData, 3) - - for { - digestsMap := make(map[uint64]struct{}) - - for i := range len(pks) { - pk := newAccountPublicKey(t, 1000) - - pkb, err := encodeStoredPublicKeyFromAccountPublicKey(pk) - require.NoError(t, err) - - digest := circlehash.Hash64(pkb, seed) - - pks[i] = pkData{pk, pkb, digest} - digestsMap[digest] = struct{}{} - } - - if len(digestsMap) == len(pks) { - break - } - } - - testcases := []struct { - name string - encodedPublicKeys [][]byte - hashFunc func(b []byte, seed uint64) uint64 - n int - expectedStartIndex int - expectedDigests []uint64 - }{ - { - name: "empty", - n: 2, - }, - { - name: "1 key, min 2 keys", - n: 2, - encodedPublicKeys: [][]byte{pks[0].pkb}, - expectedStartIndex: 0, - expectedDigests: []uint64{pks[0].digest}, - }, - { - name: "2 key, min 2 keys", - n: 2, - encodedPublicKeys: [][]byte{pks[0].pkb, pks[1].pkb}, - expectedStartIndex: 0, - expectedDigests: []uint64{pks[0].digest, pks[1].digest}, - }, - { - name: "3 key, min 2 keys", - n: 2, - encodedPublicKeys: [][]byte{pks[0].pkb, pks[1].pkb, pks[2].pkb}, - expectedStartIndex: 1, - expectedDigests: []uint64{pks[1].digest, pks[2].digest}, - }, - { - name: "3 key, min 2 keys, collision", - n: 2, - hashFunc: func([]byte, uint64) uint64 { - return 0 - }, - encodedPublicKeys: [][]byte{pks[0].pkb, pks[1].pkb, pks[2].pkb}, - expectedStartIndex: 1, - expectedDigests: []uint64{0, dummyDigest}, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - startIndex, digests := generateLastNPublicKeyDigests( - zerolog.Nop(), - string(owner[:]), - tc.encodedPublicKeys, - tc.n, - tc.hashFunc, - ) - require.Equal(t, tc.expectedStartIndex, startIndex) - require.ElementsMatch(t, tc.expectedDigests, digests) - }) - } -} - -func TestMigration(t *testing.T) { - const accountStatusMinSize = 29 - - t.Run("no account public key", func(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - - encodedAccountStatusV3 := newEncodedAccountStatusV3(0) - - accountRegisters := registers.NewAccountRegisters(string(owner[:])) - err := accountRegisters.Set(string(owner[:]), flow.AccountStatusKey, encodedAccountStatusV3) - require.NoError(t, err) - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys( - zerolog.Nop(), - accountRegisters, - ) - require.NoError(t, err) - require.False(t, deduplicated) - - // Register after migration: - // - "a.s" - require.Equal(t, 1, accountRegisters.Count()) - - // Test "a.s" register - encodedAccountStatusV4, err := accountRegisters.Get(string(owner[:]), flow.AccountStatusKey) - require.NoError(t, err) - require.Equal(t, len(encodedAccountStatusV3), len(encodedAccountStatusV4)) - require.Equal(t, byte(0x40), encodedAccountStatusV4[0]) - require.Equal(t, encodedAccountStatusV3[1:], encodedAccountStatusV4[1:]) - - err = ValidateAccountPublicKeyV4(common.Address(owner), accountRegisters) - require.NoError(t, err) - }) - - t.Run("1 account public key without sequence number", func(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - - pk1 := newAccountPublicKey(t, 1000) - encodedPk1, err := flow.EncodeAccountPublicKey(pk1) - require.NoError(t, err) - - encodedAccountStatusV3 := newEncodedAccountStatusV3(1) - - accountRegisters := registers.NewAccountRegisters(string(owner[:])) - err = accountRegisters.Set(string(owner[:]), flow.AccountStatusKey, encodedAccountStatusV3) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), legacyAccountPublicKey0RegisterKey, encodedPk1) - require.NoError(t, err) - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys( - zerolog.Nop(), - accountRegisters, - ) - require.NoError(t, err) - require.False(t, deduplicated) - - // Registers after migration: - // - "a.s" - // - "apk_0" - require.Equal(t, 2, accountRegisters.Count()) - - // Test "a.s" register - encodedAccountStatusV4, err := accountRegisters.Get(string(owner[:]), flow.AccountStatusKey) - require.NoError(t, err) - require.Equal(t, len(encodedAccountStatusV3), len(encodedAccountStatusV4)) - require.Equal(t, byte(0x40), encodedAccountStatusV4[0]) - require.Equal(t, encodedAccountStatusV3[1:], encodedAccountStatusV4[1:]) - - // Test "apk_0" register - encodedAccountPublicKey0, err := accountRegisters.Get(string(owner[:]), flow.AccountPublicKey0RegisterKey) - require.NoError(t, err) - require.Equal(t, encodedPk1, encodedAccountPublicKey0) - - err = ValidateAccountPublicKeyV4(common.Address(owner), accountRegisters) - require.NoError(t, err) - }) - - t.Run("1 account public key with sequence number", func(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - - pk1 := newAccountPublicKey(t, 1000) - pk1.SeqNumber = 1 - encodedPk1, err := flow.EncodeAccountPublicKey(pk1) - require.NoError(t, err) - - encodedAccountStatusV3 := newEncodedAccountStatusV3(1) - - accountRegisters := registers.NewAccountRegisters(string(owner[:])) - err = accountRegisters.Set(string(owner[:]), flow.AccountStatusKey, encodedAccountStatusV3) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), legacyAccountPublicKey0RegisterKey, encodedPk1) - require.NoError(t, err) - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys( - zerolog.Nop(), - accountRegisters, - ) - require.NoError(t, err) - require.False(t, deduplicated) - - // Registers after migration: - // - "a.s" - // - "apk_0" - require.Equal(t, 2, accountRegisters.Count()) - - // Test "a.s" register - encodedAccountStatusV4, err := accountRegisters.Get(string(owner[:]), flow.AccountStatusKey) - require.NoError(t, err) - require.Equal(t, len(encodedAccountStatusV3), len(encodedAccountStatusV4)) - require.Equal(t, byte(0x40), encodedAccountStatusV4[0]) - require.Equal(t, encodedAccountStatusV3[1:], encodedAccountStatusV4[1:]) - - // Test "apk_0" register - encodedAccountPublicKey0, err := accountRegisters.Get(string(owner[:]), flow.AccountPublicKey0RegisterKey) - require.NoError(t, err) - require.Equal(t, encodedPk1, encodedAccountPublicKey0) - - err = ValidateAccountPublicKeyV4(common.Address(owner), accountRegisters) - require.NoError(t, err) - }) - - t.Run("2 unique account public key without sequence number", func(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - seed := binary.BigEndian.Uint64(owner[:]) - - pk1 := newAccountPublicKey(t, 1000) - encodedPk1, err := flow.EncodeAccountPublicKey(pk1) - require.NoError(t, err) - - encodedSpk1, err := encodeStoredPublicKeyFromAccountPublicKey(pk1) - require.NoError(t, err) - - digest1 := circlehash.Hash64(encodedSpk1, seed) - - pk2 := newAccountPublicKey(t, 1000) - encodedPk2, err := flow.EncodeAccountPublicKey(pk2) - require.NoError(t, err) - - encodedSpk2, err := encodeStoredPublicKeyFromAccountPublicKey(pk2) - require.NoError(t, err) - - digest2 := circlehash.Hash64(encodedSpk2, seed) - - encodedAccountStatusV3 := newEncodedAccountStatusV3(2) - - accountRegisters := registers.NewAccountRegisters(string(owner[:])) - err = accountRegisters.Set(string(owner[:]), flow.AccountStatusKey, encodedAccountStatusV3) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), legacyAccountPublicKey0RegisterKey, encodedPk1) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedPk2) - require.NoError(t, err) - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys( - zerolog.Nop(), - accountRegisters, - ) - require.NoError(t, err) - require.False(t, deduplicated) - - // Registers after migration: - // - "a.s" - // - "apk_0" - // - "pk_b0" - require.Equal(t, 3, accountRegisters.Count()) - - // Test "a.s" register - encodedAccountStatusV4, err := accountRegisters.Get(string(owner[:]), flow.AccountStatusKey) - require.NoError(t, err) - require.True(t, len(encodedAccountStatusV3) < len(encodedAccountStatusV4)) - require.Equal(t, byte(0x40), encodedAccountStatusV4[0]) - require.Equal(t, encodedAccountStatusV3[1:], encodedAccountStatusV4[1:len(encodedAccountStatusV3)]) - - _, weightAndRevokedStatus, startKeyIndexForDigests, digests, startKeyIndexForMapping, accountPublicKeyMappings, err := decodeAccountStatusV4(encodedAccountStatusV4) - require.NoError(t, err) - require.ElementsMatch(t, []accountPublicKeyWeightAndRevokedStatus{{1000, false}}, weightAndRevokedStatus) - require.Equal(t, uint32(0), startKeyIndexForDigests) - require.ElementsMatch(t, []uint64{digest1, digest2}, digests) - require.Equal(t, uint32(0), startKeyIndexForMapping) - require.Nil(t, accountPublicKeyMappings) - - // Test "apk_0" register - encodedAccountPublicKey0, err := accountRegisters.Get(string(owner[:]), flow.AccountPublicKey0RegisterKey) - require.NoError(t, err) - require.Equal(t, encodedPk1, encodedAccountPublicKey0) - - // Test "pk_b0" register - encodedBatchPublicKey0, err := accountRegisters.Get(string(owner[:]), fmt.Sprintf(flow.BatchPublicKeyRegisterKeyPattern, 0)) - require.NoError(t, err) - - encodedPks, err := decodeBatchPublicKey(encodedBatchPublicKey0) - require.NoError(t, err) - require.ElementsMatch(t, [][]byte{{}, encodedSpk2}, encodedPks) - - err = ValidateAccountPublicKeyV4(common.Address(owner), accountRegisters) - require.NoError(t, err) - }) - - t.Run("2 unique account public key with sequence number", func(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - seed := binary.BigEndian.Uint64(owner[:]) - - pk1 := newAccountPublicKey(t, 1000) - pk1.SeqNumber = 1 - encodedPk1, err := flow.EncodeAccountPublicKey(pk1) - require.NoError(t, err) - - encodedSpk1, err := encodeStoredPublicKeyFromAccountPublicKey(pk1) - require.NoError(t, err) - - digest1 := circlehash.Hash64(encodedSpk1, seed) - - pk2 := newAccountPublicKey(t, 1000) - pk2.SeqNumber = 2 - encodedPk2, err := flow.EncodeAccountPublicKey(pk2) - require.NoError(t, err) - - encodedSpk2, err := encodeStoredPublicKeyFromAccountPublicKey(pk2) - require.NoError(t, err) - - digest2 := circlehash.Hash64(encodedSpk2, seed) - - encodedAccountStatusV3 := newEncodedAccountStatusV3(2) - - accountRegisters := registers.NewAccountRegisters(string(owner[:])) - err = accountRegisters.Set(string(owner[:]), flow.AccountStatusKey, encodedAccountStatusV3) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), legacyAccountPublicKey0RegisterKey, encodedPk1) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedPk2) - require.NoError(t, err) - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys( - zerolog.Nop(), - accountRegisters, - ) - require.NoError(t, err) - require.False(t, deduplicated) - - // Registers after migration: - // - "a.s" - // - "apk_0" - // - "pk_b0" - // - "sn_1" - require.Equal(t, 4, accountRegisters.Count()) - - // Test "a.s" register - encodedAccountStatusV4, err := accountRegisters.Get(string(owner[:]), flow.AccountStatusKey) - require.NoError(t, err) - require.True(t, len(encodedAccountStatusV3) < len(encodedAccountStatusV4)) - require.Equal(t, byte(0x40), encodedAccountStatusV4[0]) - require.Equal(t, encodedAccountStatusV3[1:], encodedAccountStatusV4[1:len(encodedAccountStatusV3)]) - - _, weightAndRevokedStatus, startKeyIndexForDigests, digests, startKeyIndexForMapping, accountPublicKeyMappings, err := decodeAccountStatusV4(encodedAccountStatusV4) - require.NoError(t, err) - require.ElementsMatch(t, []accountPublicKeyWeightAndRevokedStatus{{1000, false}}, weightAndRevokedStatus) - require.Equal(t, uint32(0), startKeyIndexForDigests) - require.ElementsMatch(t, []uint64{digest1, digest2}, digests) - require.Equal(t, uint32(0), startKeyIndexForMapping) - require.Nil(t, accountPublicKeyMappings) - - // Test "apk_0" register - encodedAccountPublicKey0, err := accountRegisters.Get(string(owner[:]), flow.AccountPublicKey0RegisterKey) - require.NoError(t, err) - require.Equal(t, encodedPk1, encodedAccountPublicKey0) - - // Test "pk_b0" register - encodedBatchPublicKey0, err := accountRegisters.Get(string(owner[:]), fmt.Sprintf(flow.BatchPublicKeyRegisterKeyPattern, 0)) - require.NoError(t, err) - - encodedPks, err := decodeBatchPublicKey(encodedBatchPublicKey0) - require.NoError(t, err) - require.ElementsMatch(t, [][]byte{{}, encodedSpk2}, encodedPks) - - // Test "sn_0" register - encodedSequenceNumber, err := accountRegisters.Get(string(owner[:]), fmt.Sprintf(flow.SequenceNumberRegisterKeyPattern, 1)) - require.NoError(t, err) - - seqNum, err := flow.DecodeSequenceNumber(encodedSequenceNumber) - require.NoError(t, err) - require.Equal(t, uint64(2), seqNum) - - err = ValidateAccountPublicKeyV4(common.Address(owner), accountRegisters) - require.NoError(t, err) - }) - - t.Run("2 account public key (1 unique key) without sequence number", func(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - seed := binary.BigEndian.Uint64(owner[:]) - - pk1 := newAccountPublicKey(t, 1000) - encodedPk1, err := flow.EncodeAccountPublicKey(pk1) - require.NoError(t, err) - - encodedSpk1, err := encodeStoredPublicKeyFromAccountPublicKey(pk1) - require.NoError(t, err) - - digest1 := circlehash.Hash64(encodedSpk1, seed) - - encodedAccountStatusV3 := newEncodedAccountStatusV3(2) - - accountRegisters := registers.NewAccountRegisters(string(owner[:])) - err = accountRegisters.Set(string(owner[:]), flow.AccountStatusKey, encodedAccountStatusV3) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), legacyAccountPublicKey0RegisterKey, encodedPk1) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedPk1) - require.NoError(t, err) - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys( - zerolog.Nop(), - accountRegisters, - ) - require.NoError(t, err) - require.True(t, deduplicated) - - // Registers after migration: - // - "a.s" - // - "apk_0" - require.Equal(t, 2, accountRegisters.Count()) - - // Test "a.s" register - encodedAccountStatusV4, err := accountRegisters.Get(string(owner[:]), flow.AccountStatusKey) - require.NoError(t, err) - require.True(t, len(encodedAccountStatusV3) < len(encodedAccountStatusV4)) - require.Equal(t, byte(0x41), encodedAccountStatusV4[0]) - require.Equal(t, encodedAccountStatusV3[1:], encodedAccountStatusV4[1:len(encodedAccountStatusV3)]) - - _, weightAndRevokedStatus, startKeyIndexForDigests, digests, startKeyIndexForMapping, accountPublicKeyMappings, err := decodeAccountStatusV4(encodedAccountStatusV4) - require.NoError(t, err) - require.ElementsMatch(t, []accountPublicKeyWeightAndRevokedStatus{{1000, false}}, weightAndRevokedStatus) - require.Equal(t, uint32(0), startKeyIndexForDigests) - require.ElementsMatch(t, []uint64{digest1}, digests) - require.Equal(t, uint32(1), startKeyIndexForMapping) - require.ElementsMatch(t, []uint32{0}, accountPublicKeyMappings) - - // Test "apk_0" register - encodedAccountPublicKey0, err := accountRegisters.Get(string(owner[:]), flow.AccountPublicKey0RegisterKey) - require.NoError(t, err) - require.Equal(t, encodedPk1, encodedAccountPublicKey0) - - err = ValidateAccountPublicKeyV4(common.Address(owner), accountRegisters) - require.NoError(t, err) - }) - - t.Run("2 account public key (1 unique key) with sequence number", func(t *testing.T) { - var owner [8]byte - _, _ = rand.Read(owner[:]) - seed := binary.BigEndian.Uint64(owner[:]) - - pk1 := newAccountPublicKey(t, 1000) - pk1.SeqNumber = 1 - encodedPk1, err := flow.EncodeAccountPublicKey(pk1) - require.NoError(t, err) - - encodedSpk1, err := encodeStoredPublicKeyFromAccountPublicKey(pk1) - require.NoError(t, err) - - digest1 := circlehash.Hash64(encodedSpk1, seed) - - encodedAccountStatusV3 := newEncodedAccountStatusV3(2) - - accountRegisters := registers.NewAccountRegisters(string(owner[:])) - err = accountRegisters.Set(string(owner[:]), flow.AccountStatusKey, encodedAccountStatusV3) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), legacyAccountPublicKey0RegisterKey, encodedPk1) - require.NoError(t, err) - err = accountRegisters.Set(string(owner[:]), fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedPk1) - require.NoError(t, err) - - deduplicated, err := migrateAndDeduplicateAccountPublicKeys( - zerolog.Nop(), - accountRegisters, - ) - require.NoError(t, err) - require.True(t, deduplicated) - - // Registers after migration: - // - "a.s" - // - "apk_0" - // - "sn_1" - require.Equal(t, 3, accountRegisters.Count()) - - // Test "a.s" register - encodedAccountStatusV4, err := accountRegisters.Get(string(owner[:]), flow.AccountStatusKey) - require.NoError(t, err) - require.True(t, len(encodedAccountStatusV3) < len(encodedAccountStatusV4)) - require.Equal(t, byte(0x41), encodedAccountStatusV4[0]) - require.Equal(t, encodedAccountStatusV3[1:], encodedAccountStatusV4[1:len(encodedAccountStatusV3)]) - - _, weightAndRevokedStatus, startKeyIndexForDigests, digests, startKeyIndexForMapping, accountPublicKeyMappings, err := decodeAccountStatusV4(encodedAccountStatusV4) - require.NoError(t, err) - require.ElementsMatch(t, []accountPublicKeyWeightAndRevokedStatus{{1000, false}}, weightAndRevokedStatus) - require.Equal(t, uint32(0), startKeyIndexForDigests) - require.ElementsMatch(t, []uint64{digest1}, digests) - require.Equal(t, uint32(1), startKeyIndexForMapping) - require.ElementsMatch(t, []uint32{0}, accountPublicKeyMappings) - - // Test "apk_0" register - encodedAccountPublicKey0, err := accountRegisters.Get(string(owner[:]), flow.AccountPublicKey0RegisterKey) - require.NoError(t, err) - require.Equal(t, encodedPk1, encodedAccountPublicKey0) - - // Test "sn_0" register - encodedSequenceNumber, err := accountRegisters.Get(string(owner[:]), fmt.Sprintf(flow.SequenceNumberRegisterKeyPattern, 1)) - require.NoError(t, err) - - seqNum, err := flow.DecodeSequenceNumber(encodedSequenceNumber) - require.NoError(t, err) - require.Equal(t, uint64(1), seqNum) - - err = ValidateAccountPublicKeyV4(common.Address(owner), accountRegisters) - require.NoError(t, err) - }) -} - -func newAccountPublicKey(t *testing.T, weight int) flow.AccountPublicKey { - privateKey, err := unittest.AccountKeyDefaultFixture() - require.NoError(t, err) - - return privateKey.PublicKey(weight) -} - -func newEncodedAccountStatusV3(accountPublicKeyCount uint32) []byte { - b := []byte{ - 0, // initial empty flags - 0, 0, 0, 0, 0, 0, 0, 0, // init value for storage used - 0, 0, 0, 0, 0, 0, 0, 1, // init value for storage index - 0, 0, 0, 0, // init value for public key counts - 0, 0, 0, 0, 0, 0, 0, 0, // init value for address id counter - } - - var encodedAccountPublicKeyCount [4]byte - binary.BigEndian.PutUint32(encodedAccountPublicKeyCount[:], accountPublicKeyCount) - - copy(b[17:], encodedAccountPublicKeyCount[:]) - - return b -} diff --git a/cmd/util/ledger/migrations/account_key_deduplication_migration_utils.go b/cmd/util/ledger/migrations/account_key_deduplication_migration_utils.go deleted file mode 100644 index bcefd0b75d1..00000000000 --- a/cmd/util/ledger/migrations/account_key_deduplication_migration_utils.go +++ /dev/null @@ -1,223 +0,0 @@ -package migrations - -import ( - "fmt" - - "github.com/rs/zerolog" - - "github.com/onflow/flow-go/cmd/util/ledger/util/registers" - "github.com/onflow/flow-go/model/flow" -) - -const ( - accountStatusV4WithNoDeduplicationFlag = 0x40 -) - -func getAccountRegisterOrError( - accountRegisters *registers.AccountRegisters, - owner string, - key string, -) ([]byte, error) { - value, err := accountRegisters.Get(owner, key) - if err != nil { - return nil, err - } - if len(value) == 0 { - return nil, fmt.Errorf("owner %x key %s register not found", owner, key) - } - return value, nil -} - -func getAccountPublicKeyOrError( - accountRegisters *registers.AccountRegisters, - owner string, - keyIndex uint32, -) (flow.AccountPublicKey, error) { - publicKeyRegisterKey := fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, keyIndex) - - encodedAccountPublicKey, err := getAccountRegisterOrError(accountRegisters, owner, publicKeyRegisterKey) - if err != nil { - return flow.AccountPublicKey{}, err - } - - decodedAccountPublicKey, err := flow.DecodeAccountPublicKey(encodedAccountPublicKey, keyIndex) - if err != nil { - return flow.AccountPublicKey{}, err - } - - return decodedAccountPublicKey, nil -} - -func removeAccountPublicKey( - accountRegisters *registers.AccountRegisters, - owner string, - keyIndex uint32, -) error { - publicKeyRegisterKey := fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, keyIndex) - return accountRegisters.Set(owner, publicKeyRegisterKey, nil) -} - -// migrateAccountStatusToV4 sets account status version to v4, stores account status -// in account status register, and returns updated account status. -func migrateAccountStatusToV4( - log zerolog.Logger, - accountRegisters *registers.AccountRegisters, - owner string, -) ([]byte, error) { - encodedAccountStatus, err := getAccountRegisterOrError(accountRegisters, owner, flow.AccountStatusKey) - if err != nil { - return nil, err - } - - if encodedAccountStatus[0] != 0 { - log.Warn().Msgf("%x account status flag is %d, flag will be reset during migration", owner, encodedAccountStatus[0]) - } - - // Update account status version and flag in place. - encodedAccountStatus[0] = accountStatusV4WithNoDeduplicationFlag - - // Set account status register - err = accountRegisters.Set(owner, flow.AccountStatusKey, encodedAccountStatus) - if err != nil { - return nil, err - } - - return encodedAccountStatus, nil -} - -// migrateAccountPublicKey0 renames public_key_0 to apk_0, stores renamed -// account public key, and returns raw data of account public key 0. -func migrateAccountPublicKey0( - accountRegisters *registers.AccountRegisters, - owner string, -) ([]byte, error) { - encodedAccountPublicKey0, err := getAccountRegisterOrError(accountRegisters, owner, legacyAccountPublicKey0RegisterKey) - if err != nil { - return nil, err - } - - // Rename public_key_0 register key to apk_0 - err = accountRegisters.Set(owner, legacyAccountPublicKey0RegisterKey, nil) - if err != nil { - return nil, err - } - err = accountRegisters.Set(owner, flow.AccountPublicKey0RegisterKey, encodedAccountPublicKey0) - if err != nil { - return nil, err - } - - return encodedAccountPublicKey0, nil -} - -// migrateSeqNumberIfNeeded creates sequence number register for the given -// account public key if sequence number is > 0. -func migrateSeqNumberIfNeeded( - accountRegisters *registers.AccountRegisters, - owner string, - keyIndex uint32, - seqNumber uint64, -) error { - if seqNumber == 0 { - return nil - } - - seqNumberRegisterKey := fmt.Sprintf(flow.SequenceNumberRegisterKeyPattern, keyIndex) - - encodedSeqNumber, err := flow.EncodeSequenceNumber(seqNumber) - if err != nil { - return err - } - - return accountRegisters.Set(owner, seqNumberRegisterKey, encodedSeqNumber) -} - -// migrateAccountStatusWithPublicKeyMetadata appends accounts public key metadata -// to account status register. -func migrateAccountStatusWithPublicKeyMetadata( - log zerolog.Logger, - accountRegisters *registers.AccountRegisters, - owner string, - accountPublicKeyWeightAndRevokedStatus []accountPublicKeyWeightAndRevokedStatus, - encodedPublicKeys [][]byte, - keyIndexMappings []uint32, - deduplicated bool, -) error { - encodedAccountStatus, err := getAccountRegisterOrError(accountRegisters, owner, flow.AccountStatusKey) - if err != nil { - return err - } - - // After the migration and spork, the runtime needs to detect duplicate public keys - // being added and store them efficiently. Detection rate doesn't need to be 100% - // to be effective and we don't want to read all existing keys or store all digests. - // We only need to compute and store the hash digest of the last N public keys added. - // For example, N=2 showed good balance of tradeoffs in tests using mainnet snapshot. - startIndexForDigests, digests := generateLastNPublicKeyDigests(log, owner, encodedPublicKeys, maxStoredDigests, nil) - - // startIndexForMapping stores the start index of the first deduplicated public key. - // This is used to avoid unnecessary key index mapping overhead (both speed & storage). - startIndexForMapping := firstIndexOfDuplicateKeyInMappings(keyIndexMappings) - - // keyIndexMappings is a slice containing stored key index where the slice index is - // the account key index starting from startIndexForMapping. - keyIndexMappings = keyIndexMappings[startIndexForMapping:] - - newAccountStatus, err := encodeAccountStatusV4WithPublicKeyMetadata( - encodedAccountStatus, - accountPublicKeyWeightAndRevokedStatus, - uint32(startIndexForDigests), - digests, - uint32(startIndexForMapping), - keyIndexMappings, - deduplicated, - ) - if err != nil { - return err - } - - return accountRegisters.Set(owner, flow.AccountStatusKey, newAccountStatus) -} - -// migrateAccountPublicKeysIfNeeded migrates account public key from index >= 1 to batched public key register. -// NOTE: -// - Key 0 in batch 0 is always empty since it corresponds to account public key 0, which is stored in its own register. -func migrateAccountPublicKeysIfNeeded( - accountRegisters *registers.AccountRegisters, - owner string, - encodedUniquePublicKeys [][]byte, -) error { - // Return early if encodedPublicKeys only contains public key 0 (which always stores in register apk_0) - if len(encodedUniquePublicKeys) == 1 { - return nil - } - - // Storing public keys in batch reduces payload count and reduces number of reads for multiple public keys. - // About 65% of accounts have 1 public key so the first public key is not deduplicated to avoid overhead. - // About 90% of accounts have fewer than 10 account public keys, so with batching 90% of accounts have at - // most 2 payloads for public keys (since the first key is always by itself to avoid overhead). - // - apk_0 payload for account public key 0, and - // - pb_b0 payload for rest of deduplicated public keys - encodedBatchPublicKeys, err := encodePublicKeysInBatches(encodedUniquePublicKeys, maxPublicKeyCountInBatch) - if err != nil { - return err - } - - for batchIndex, encodedBatchPublicKey := range encodedBatchPublicKeys { - batchPublicKeyRegisterKey := fmt.Sprintf(flow.BatchPublicKeyRegisterKeyPattern, batchIndex) - err = accountRegisters.Set(owner, batchPublicKeyRegisterKey, encodedBatchPublicKey) - if err != nil { - return err - } - } - - return nil -} - -func firstIndexOfDuplicateKeyInMappings(accountPublicKeyMappings []uint32) int { - for keyIndex, storedKeyIndex := range accountPublicKeyMappings { - if uint32(keyIndex) != storedKeyIndex { - return keyIndex - } - } - return len(accountPublicKeyMappings) -} diff --git a/cmd/util/ledger/migrations/account_key_diff.go b/cmd/util/ledger/migrations/account_key_diff.go deleted file mode 100644 index 63a16eaebe7..00000000000 --- a/cmd/util/ledger/migrations/account_key_diff.go +++ /dev/null @@ -1,273 +0,0 @@ -package migrations - -import ( - "encoding/json" - "fmt" - - "github.com/onflow/cadence/common" - - "github.com/onflow/crypto/hash" - - "github.com/onflow/flow-go/cmd/util/ledger/reporters" - "github.com/onflow/flow-go/cmd/util/ledger/util/registers" - "github.com/onflow/flow-go/fvm/environment" - "github.com/onflow/flow-go/fvm/storage/state" - "github.com/onflow/flow-go/model/flow" -) - -type accountKeyDiffKind int - -const ( - accountKeyCountDiff accountKeyDiffKind = iota - accountKeyDiff -) - -var accountKeyDiffKindString = map[accountKeyDiffKind]string{ - accountKeyCountDiff: "key_count_diff", - accountKeyDiff: "key_diff", -} - -type accountKeyDiffProblem struct { - Address string - KeyIndex uint32 - Kind string - Msg string -} - -type accountKeyDiffErrorKind int - -const ( - accountKeyCountErrorKind accountKeyDiffErrorKind = iota - accountKeyErrorKind -) - -var accountKeyDiffErrorKindString = map[accountKeyDiffErrorKind]string{ - accountKeyCountErrorKind: "error_get_key_count_failed", - accountKeyErrorKind: "error_get_key_failed", -} - -type accountKeyDiffError struct { - Address string - Kind string - Msg string -} - -type AccountKeyDiffReporter struct { - address common.Address - chainID flow.ChainID - reportWriter reporters.ReportWriter -} - -func NewAccountKeyDiffReporter( - address common.Address, - chainID flow.ChainID, - rw reporters.ReportWriter, -) *AccountKeyDiffReporter { - return &AccountKeyDiffReporter{ - address: address, - chainID: chainID, - reportWriter: rw, - } -} - -func (akd *AccountKeyDiffReporter) DiffKeys( - accountRegistersV3, accountRegistersV4 registers.Registers, -) { - if akd.address == common.ZeroAddress { - return - } - - accountsV3 := newAccountsWithAccountKeyV3(accountRegistersV3) - - accountsV4 := newAccountsWithAccountKeyV4(accountRegistersV4) - - countV3, err := accountsV3.getAccountPublicKeyCount(flow.Address(akd.address)) - if err != nil { - akd.reportWriter.Write( - accountKeyDiffError{ - Address: akd.address.Hex(), - Kind: accountKeyDiffErrorKindString[accountKeyCountErrorKind], - Msg: fmt.Sprintf("failed to get account public key count v3: %s", err), - }) - return - } - - countV4, err := accountsV4.getAccountPublicKeyCount(flow.Address(akd.address)) - if err != nil { - akd.reportWriter.Write( - accountKeyDiffError{ - Address: akd.address.Hex(), - Kind: accountKeyDiffErrorKindString[accountKeyCountErrorKind], - Msg: fmt.Sprintf("failed to get account public key count v4: %s", err), - }) - return - } - - if countV3 != countV4 { - akd.reportWriter.Write( - accountKeyDiffProblem{ - Address: akd.address.Hex(), - Kind: accountKeyDiffKindString[accountKeyCountDiff], - Msg: fmt.Sprintf("%d keys in v3, %d keys in v4", countV3, countV4), - }) - return - } - - for keyIndex := range countV3 { - keyV3, err := accountsV3.getAccountPublicKey(flow.Address(akd.address), keyIndex) - if err != nil { - akd.reportWriter.Write( - accountKeyDiffError{ - Address: akd.address.Hex(), - Kind: accountKeyDiffErrorKindString[accountKeyErrorKind], - Msg: fmt.Sprintf("failed to get account public key v3 at key index %d: %s", keyIndex, err), - }) - continue - } - - keyV4, err := accountsV4.getAccountPublicKey(flow.Address(akd.address), keyIndex) - if err != nil { - akd.reportWriter.Write( - accountKeyDiffError{ - Address: akd.address.Hex(), - Kind: accountKeyDiffErrorKindString[accountKeyErrorKind], - Msg: fmt.Sprintf("failed to get account public key v4 at key index %d: %s", keyIndex, err), - }) - continue - } - - err = equal(keyV3, keyV4) - if err != nil { - encodedKeyV3, _ := json.Marshal(keyV3) - encodedKeyV4, _ := json.Marshal(keyV4) - - akd.reportWriter.Write( - accountKeyDiffProblem{ - Address: akd.address.Hex(), - KeyIndex: keyIndex, - Kind: accountKeyDiffKindString[accountKeyDiff], - Msg: fmt.Sprintf("v3: %s, v4 %s: %s", encodedKeyV3, encodedKeyV4, err.Error()), - }) - } - } -} - -type accountsWithAccountKeysV3 struct { - a *environment.StatefulAccounts -} - -func newAccountsWithAccountKeyV3(regs registers.Registers) *accountsWithAccountKeysV3 { - return &accountsWithAccountKeysV3{ - a: newStatefulAccounts(regs), - } -} - -func (akv3 *accountsWithAccountKeysV3) getAccountPublicKeyCount(address flow.Address) (uint32, error) { - id := flow.AccountStatusRegisterID(address) - - statusBytes, err := akv3.a.GetValue(id) - if err != nil { - return 0, fmt.Errorf("failed to load account status for account %s: %w", address, err) - } - if len(statusBytes) == 0 { - return 0, fmt.Errorf("account status register is empty for account %s", address) - } - - as, err := environment.AccountStatusFromBytes(statusBytes) - if err != nil { - return 0, fmt.Errorf("failed to create account status from bytes for account %s: %w", address, err) - } - - return as.AccountPublicKeyCount(), nil -} - -func (akv3 *accountsWithAccountKeysV3) getAccountPublicKey(address flow.Address, keyIndex uint32) (flow.AccountPublicKey, error) { - id := flow.RegisterID{ - Owner: string(address.Bytes()), - Key: fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, keyIndex), - } - - publicKeyBytes, err := akv3.a.GetValue(id) - if err != nil { - return flow.AccountPublicKey{}, fmt.Errorf("failed to load account public key %d for account %s: %w", keyIndex, address, err) - } - if len(publicKeyBytes) == 0 { - return flow.AccountPublicKey{}, fmt.Errorf("account public key %d is empty for account %s", keyIndex, address) - } - - key, err := flow.DecodeAccountPublicKey(publicKeyBytes, keyIndex) - if err != nil { - return flow.AccountPublicKey{}, fmt.Errorf("failed to decode account public key %d for account %s", keyIndex, address) - } - - return key, nil -} - -type accountsWithAccountKeysV4 struct { - a *environment.StatefulAccounts -} - -func newAccountsWithAccountKeyV4(regs registers.Registers) *accountsWithAccountKeysV4 { - return &accountsWithAccountKeysV4{ - a: newStatefulAccounts(regs), - } -} - -func (akv4 *accountsWithAccountKeysV4) getAccountPublicKeyCount(address flow.Address) (uint32, error) { - return akv4.a.GetAccountPublicKeyCount(address) -} - -func (akv4 *accountsWithAccountKeysV4) getAccountPublicKey(address flow.Address, keyIndex uint32) (flow.AccountPublicKey, error) { - return akv4.a.GetAccountPublicKey(address, keyIndex) -} - -func newStatefulAccounts( - regs registers.Registers, -) *environment.StatefulAccounts { - // Create a new transaction state with a dummy hasher - // because we do not need spock proofs for migrations. - transactionState := state.NewTransactionStateFromExecutionState( - state.NewExecutionStateWithSpockStateHasher( - registers.StorageSnapshot{ - Registers: regs, - }, - state.DefaultParameters(), - func() hash.Hasher { - return dummyHasher{} - }, - ), - ) - return environment.NewAccounts(transactionState) -} - -func equal(keyV3, keyV4 flow.AccountPublicKey) error { - if keyV3.Index != keyV4.Index { - return fmt.Errorf("account public key index differ: v3 %v, v4 %v", keyV3.Index, keyV4.Index) - } - - if !keyV3.PublicKey.Equals(keyV4.PublicKey) { - return fmt.Errorf("account public key differ: v3 %v, v4 %v", keyV3.PublicKey, keyV4.PublicKey) - } - - if keyV3.SignAlgo != keyV4.SignAlgo { - return fmt.Errorf("account public key sign algo differ: v3 %v, v4 %v", keyV3.SignAlgo, keyV4.SignAlgo) - } - - if keyV3.HashAlgo != keyV4.HashAlgo { - return fmt.Errorf("account public key hash algo differ: v3 %v, v4 %v", keyV3.HashAlgo, keyV4.HashAlgo) - } - - if keyV3.SeqNumber != keyV4.SeqNumber { - return fmt.Errorf("account public key sequence number differ: v3 %v, v4 %v", keyV3.SeqNumber, keyV4.SeqNumber) - } - - if keyV3.Weight != keyV4.Weight { - return fmt.Errorf("account public key weight differ: v3 %v, v4 %v", keyV3.Weight, keyV4.Weight) - } - - if keyV3.Revoked != keyV4.Revoked { - return fmt.Errorf("account public key revoked status differ: v3 %v, v4 %v", keyV3.Revoked, keyV4.Revoked) - } - - return nil -} diff --git a/cmd/util/ledger/migrations/account_key_diff_test.go b/cmd/util/ledger/migrations/account_key_diff_test.go deleted file mode 100644 index 45ae3444bf8..00000000000 --- a/cmd/util/ledger/migrations/account_key_diff_test.go +++ /dev/null @@ -1,715 +0,0 @@ -package migrations - -import ( - "fmt" - "math" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/onflow/cadence/common" - "github.com/onflow/flow-go-sdk/crypto" - - "github.com/onflow/flow-go/cmd/util/ledger/util/registers" - "github.com/onflow/flow-go/fvm/environment" - accountkeymetadata "github.com/onflow/flow-go/fvm/environment/account-key-metadata" - "github.com/onflow/flow-go/ledger" - "github.com/onflow/flow-go/ledger/common/convert" - "github.com/onflow/flow-go/model/flow" -) - -func TestAccountPublicKeyDiff(t *testing.T) { - address := flow.BytesToAddress([]byte{0x01}) - chainID := flow.Testnet - - t.Run("0 key", func(t *testing.T) { - accountStatusV3Bytes := environment.NewAccountStatus().ToBytes() - accountStatusV3Bytes[0] = 0 - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - }) - require.NoError(t, err) - - accountStatusV4Bytes := environment.NewAccountStatus().ToBytes() - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4Bytes), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - // No diff - require.Equal(t, 0, len(reportWriter.data)) - }) - - t.Run("1 key", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(1) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, legacyAccountPublicKey0RegisterKey, encodedKey0), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - // No diff - require.Equal(t, 0, len(reportWriter.data)) - }) - - t.Run("2 keys", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - key1 := newAccountPublicKey(t, 1) - storedKey1 := accountPublicKeyToStoredKey(key1) - - encodedKey1, err := flow.EncodeAccountPublicKey(key1) - require.NoError(t, err) - - encodedStoredKey1, err := flow.EncodeStoredPublicKey(storedKey1) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(2) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, legacyAccountPublicKey0RegisterKey, encodedKey0), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedKey1), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - // Append key 1 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key1.Revoked, - uint16(key1.Weight), - encodedStoredKey1, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - if i == 0 { - return encodedStoredKey0, nil - } - return nil, fmt.Errorf("expect getStoredKey for key index 0, got %d", i) - }, - ) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - newPayload(address, "pk_b0", newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &storedKey1})), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - // No diff - require.Equal(t, 0, len(reportWriter.data)) - }) - - t.Run("2 keys, diff for public key", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - key1a := newAccountPublicKey(t, 1) - - encodedKey1a, err := flow.EncodeAccountPublicKey(key1a) - require.NoError(t, err) - - key1b := newAccountPublicKey(t, 1) - storedKey1b := accountPublicKeyToStoredKey(key1b) - - encodedStoredKey1b, err := flow.EncodeStoredPublicKey(storedKey1b) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(2) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, legacyAccountPublicKey0RegisterKey, encodedKey0), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedKey1a), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - // Append key 1 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key1b.Revoked, - uint16(key1b.Weight), - encodedStoredKey1b, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - if i == 0 { - return encodedStoredKey0, nil - } - return nil, fmt.Errorf("expect getStoredKey for key index 0, got %d", i) - }, - ) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - newPayload(address, "pk_b0", newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &storedKey1b})), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - require.Equal(t, 1, len(reportWriter.data)) - require.Contains(t, reportWriter.data[0].(accountKeyDiffProblem).Msg, "account public key diff") - }) - - t.Run("2 keys, diff for weight", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - key1 := newAccountPublicKey(t, 1) - storedKey1 := accountPublicKeyToStoredKey(key1) - - encodedKey1, err := flow.EncodeAccountPublicKey(key1) - require.NoError(t, err) - - encodedStoredKey1, err := flow.EncodeStoredPublicKey(storedKey1) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(2) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, legacyAccountPublicKey0RegisterKey, encodedKey0), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedKey1), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - // Append key 1 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key1.Revoked, - uint16(key1.Weight+1), - encodedStoredKey1, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - if i == 0 { - return encodedStoredKey0, nil - } - return nil, fmt.Errorf("expect getStoredKey for key index 0, got %d", i) - }, - ) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - newPayload(address, "pk_b0", newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &storedKey1})), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - require.Equal(t, 1, len(reportWriter.data)) - require.Contains(t, reportWriter.data[0].(accountKeyDiffProblem).Msg, "weight") - }) - - t.Run("2 keys, diff for revoked status", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - key1 := newAccountPublicKey(t, 1) - storedKey1 := accountPublicKeyToStoredKey(key1) - - encodedKey1, err := flow.EncodeAccountPublicKey(key1) - require.NoError(t, err) - - encodedStoredKey1, err := flow.EncodeStoredPublicKey(storedKey1) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(2) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, legacyAccountPublicKey0RegisterKey, encodedKey0), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedKey1), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - // Append key 1 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - !key1.Revoked, - uint16(key1.Weight), - encodedStoredKey1, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - if i == 0 { - return encodedStoredKey0, nil - } - return nil, fmt.Errorf("expect getStoredKey for key index 0, got %d", i) - }, - ) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - newPayload(address, "pk_b0", newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &storedKey1})), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - require.Equal(t, 1, len(reportWriter.data)) - require.Contains(t, reportWriter.data[0].(accountKeyDiffProblem).Msg, "revoked status") - }) - - t.Run("2 keys, diff for sequence number", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - key1 := newAccountPublicKey(t, 1) - key1.SeqNumber = 1 - storedKey1 := accountPublicKeyToStoredKey(key1) - - encodedKey1, err := flow.EncodeAccountPublicKey(key1) - require.NoError(t, err) - - encodedStoredKey1, err := flow.EncodeStoredPublicKey(storedKey1) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(2) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, legacyAccountPublicKey0RegisterKey, encodedKey0), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedKey1), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - // Append key 1 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key1.Revoked, - uint16(key1.Weight), - encodedStoredKey1, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - if i == 0 { - return encodedStoredKey0, nil - } - return nil, fmt.Errorf("expect getStoredKey for key index 0, got %d", i) - }, - ) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - newPayload(address, "pk_b0", newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &storedKey1})), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - require.Equal(t, 1, len(reportWriter.data)) - require.Contains(t, reportWriter.data[0].(accountKeyDiffProblem).Msg, "sequence number") - }) - - t.Run("2 keys, diff for hash algo", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - key1 := newAccountPublicKey(t, 1) - storedKey1 := accountPublicKeyToStoredKey(key1) - storedKey1.HashAlgo = crypto.SHA3_384 - - encodedKey1, err := flow.EncodeAccountPublicKey(key1) - require.NoError(t, err) - - encodedStoredKey1, err := flow.EncodeStoredPublicKey(storedKey1) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(2) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, legacyAccountPublicKey0RegisterKey, encodedKey0), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedKey1), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - // Append key 1 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key1.Revoked, - uint16(key1.Weight), - encodedStoredKey1, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - if i == 0 { - return encodedStoredKey0, nil - } - return nil, fmt.Errorf("expect getStoredKey for key index 0, got %d", i) - }, - ) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - newPayload(address, "pk_b0", newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &storedKey1})), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - require.Equal(t, 1, len(reportWriter.data)) - require.Contains(t, reportWriter.data[0].(accountKeyDiffProblem).Msg, "hash algo") - }) - - t.Run("2 duplicate keys", func(t *testing.T) { - key0 := newAccountPublicKey(t, 1000) - storedKey0 := accountPublicKeyToStoredKey(key0) - - encodedKey0, err := flow.EncodeAccountPublicKey(key0) - require.NoError(t, err) - - encodedStoredKey0, err := flow.EncodeStoredPublicKey(storedKey0) - require.NoError(t, err) - - key1 := key0 - key1.SeqNumber = 1 - storedKey1 := accountPublicKeyToStoredKey(key1) - - encodedKey1, err := flow.EncodeAccountPublicKey(key1) - require.NoError(t, err) - - encodedStoredKey1, err := flow.EncodeStoredPublicKey(storedKey1) - require.NoError(t, err) - - accountStatusV3 := environment.NewAccountStatus() - accountStatusV3.SetAccountPublicKeyCount(2) - accountStatusV3Bytes := accountStatusV3.ToBytes() - accountStatusV3Bytes[0] = 0 - - registersV3, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV3Bytes), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 0), encodedKey0), - newPayload(address, fmt.Sprintf(legacyAccountPublicKeyRegisterKeyPattern, 1), encodedKey1), - }) - require.NoError(t, err) - - accountStatusV4 := environment.NewAccountStatus() - // Append key 0 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key0.Revoked, - uint16(key0.Weight), - encodedStoredKey0, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - return nil, fmt.Errorf("don't expect getStoredKey called, got %d", i) - }, - ) - require.NoError(t, err) - // Append key 1 - _, _, err = accountStatusV4.AppendAccountPublicKeyMetadata( - key1.Revoked, - uint16(key1.Weight), - encodedStoredKey1, - func(b []byte) uint64 { - return accountkeymetadata.GetPublicKeyDigest(address, b) - }, - func(i uint32) ([]byte, error) { - if i == 0 { - return encodedStoredKey0, nil - } - return nil, fmt.Errorf("expect getStoredKey for key index 0, got %d", i) - }, - ) - require.NoError(t, err) - - encodedSeqNumber, err := flow.EncodeSequenceNumber(key1.SeqNumber) - require.NoError(t, err) - - registersV4, err := registers.NewByAccountFromPayloads([]*ledger.Payload{ - newPayload(address, flow.AccountStatusKey, accountStatusV4.ToBytes()), - newPayload(address, "apk_0", encodedKey0), - newPayload(address, "sn_1", encodedSeqNumber), - }) - require.NoError(t, err) - - reportWriter := newMemoryReportWriter() - - diffReporter := NewAccountKeyDiffReporter(common.Address(address), chainID, reportWriter) - diffReporter.DiffKeys(registersV3, registersV4) - - // No diff - require.Equal(t, 0, len(reportWriter.data)) - }) -} - -func newPayload(owner flow.Address, key string, value []byte) *ledger.Payload { - registerID := flow.NewRegisterID(owner, key) - ledgerKey := convert.RegisterIDToLedgerKey(registerID) - return ledger.NewPayload(ledgerKey, value) -} - -type memoryReportWriter struct { - data []any -} - -func newMemoryReportWriter() *memoryReportWriter { - return &memoryReportWriter{} -} - -func (w *memoryReportWriter) Write(dataPoint interface{}) { - w.data = append(w.data, dataPoint) -} - -func (w *memoryReportWriter) Close() { -} - -func accountPublicKeyToStoredKey(apk flow.AccountPublicKey) flow.StoredPublicKey { - return flow.StoredPublicKey{ - PublicKey: apk.PublicKey, - SignAlgo: apk.SignAlgo, - HashAlgo: apk.HashAlgo, - } -} - -func newBatchPublicKey(t *testing.T, storedPublicKeys []*flow.StoredPublicKey) []byte { - var buf []byte - var err error - - for _, k := range storedPublicKeys { - var encodedKey []byte - - if k != nil { - encodedKey, err = flow.EncodeStoredPublicKey(*k) - require.NoError(t, err) - } - - b, err := encodeBatchedPublicKey(encodedKey) - require.NoError(t, err) - - buf = append(buf, b...) - } - return buf -} - -func encodeBatchedPublicKey(encodedPublicKey []byte) ([]byte, error) { - const maxEncodedKeySize = math.MaxUint8 - - if len(encodedPublicKey) > maxEncodedKeySize { - return nil, fmt.Errorf("failed to encode batched public key: encoded key size is %d bytes, exceeded max size %d", len(encodedPublicKey), maxEncodedKeySize) - } - - buf := make([]byte, 1+len(encodedPublicKey)) - buf[0] = byte(len(encodedPublicKey)) - copy(buf[1:], encodedPublicKey) - - return buf, nil -} diff --git a/cmd/util/ledger/migrations/add_key_migration.go b/cmd/util/ledger/migrations/add_key_migration.go index 2fcca8db493..e8ae71d2c59 100644 --- a/cmd/util/ledger/migrations/add_key_migration.go +++ b/cmd/util/ledger/migrations/add_key_migration.go @@ -128,7 +128,7 @@ func (m *AddKeyMigration) MigrateAccount( return err } - account, err := migrationRuntime.Accounts.Get(flow.ConvertAddress(address)) + account, err := migrationRuntime.Accounts.Get(flow.Address(address)) if err != nil { return fmt.Errorf("could not find account at address %s", address) } @@ -147,7 +147,7 @@ func (m *AddKeyMigration) MigrateAccount( Weight: fvm.AccountKeyWeightThreshold, } - flowAddress := flow.ConvertAddress(address) + flowAddress := flow.Address(address) keyIndex, err := migrationRuntime.Accounts.GetAccountPublicKeyCount(flowAddress) if err != nil { diff --git a/cmd/util/ledger/migrations/cadence_value_diff.go b/cmd/util/ledger/migrations/cadence_value_diff.go index 3341c12b737..a45139c0cbb 100644 --- a/cmd/util/ledger/migrations/cadence_value_diff.go +++ b/cmd/util/ledger/migrations/cadence_value_diff.go @@ -306,9 +306,8 @@ func (dr *CadenceValueDiffReporter) diffDomain( return nil, nil, nil, false } - oldValue := oldStorageMap.ReadValue(nil, mapKey) - - newValue := newStorageMap.ReadValue(nil, mapKey) + oldValue := oldStorageMap.ReadValue(oldRuntime.Interpreter, mapKey) + newValue := newStorageMap.ReadValue(newRuntime.Interpreter, mapKey) return oldValue, newValue, trace, true } @@ -863,6 +862,7 @@ func (dr *CadenceValueDiffReporter) diffCadenceDictionaryValue( oldKeys = append(oldKeys, key) return true }, + false, ) newKeys := make([]interpreter.Value, 0, otherDictionary.Count()) @@ -872,6 +872,7 @@ func (dr *CadenceValueDiffReporter) diffCadenceDictionaryValue( newKeys = append(newKeys, key) return true }, + false, ) onlyOldKeys := make([]interpreter.Value, 0, len(oldKeys)) diff --git a/cmd/util/ledger/migrations/cadence_value_diff_test.go b/cmd/util/ledger/migrations/cadence_value_diff_test.go index 35efbf1b14f..4f9f73b9d85 100644 --- a/cmd/util/ledger/migrations/cadence_value_diff_test.go +++ b/cmd/util/ledger/migrations/cadence_value_diff_test.go @@ -193,7 +193,7 @@ func TestDiffCadenceValues(t *testing.T) { accountStatus := environment.NewAccountStatus() accountStatusPayload := ledger.NewPayload( convert.RegisterIDToLedgerKey( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), ), accountStatus.ToBytes(), ) @@ -313,7 +313,7 @@ func TestDiffCadenceValues(t *testing.T) { accountStatus := environment.NewAccountStatus() accountStatusPayload := ledger.NewPayload( convert.RegisterIDToLedgerKey( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), ), accountStatus.ToBytes(), ) @@ -432,7 +432,7 @@ func TestDiffCadenceValues(t *testing.T) { accountStatus := environment.NewAccountStatus() accountStatusPayload := ledger.NewPayload( convert.RegisterIDToLedgerKey( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), ), accountStatus.ToBytes(), ) @@ -562,7 +562,7 @@ func TestDiffCadenceValues(t *testing.T) { accountStatus := environment.NewAccountStatus() accountStatusPayload := ledger.NewPayload( convert.RegisterIDToLedgerKey( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), ), accountStatus.ToBytes(), ) @@ -703,7 +703,7 @@ func createStorageMapRegisters( accountStatus := environment.NewAccountStatus() accountStatusPayload := ledger.NewPayload( convert.RegisterIDToLedgerKey( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), ), accountStatus.ToBytes(), ) @@ -759,7 +759,7 @@ func createTestRegisters(t *testing.T, address common.Address, domain common.Sto accountStatus := environment.NewAccountStatus() accountStatusPayload := ledger.NewPayload( convert.RegisterIDToLedgerKey( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), ), accountStatus.ToBytes(), ) diff --git a/cmd/util/ledger/migrations/deploy_migration_test.go b/cmd/util/ledger/migrations/deploy_migration_test.go index c867eee5d71..5465aaed672 100644 --- a/cmd/util/ledger/migrations/deploy_migration_test.go +++ b/cmd/util/ledger/migrations/deploy_migration_test.go @@ -22,9 +22,7 @@ func newBootstrapPayloads( bootstrapProcedureOptions ...fvm.BootstrapProcedureOption, ) ([]*ledger.Payload, error) { - ctx := fvm.NewContext( - fvm.WithChain(chainID.Chain()), - ) + ctx := fvm.NewContext(chainID.Chain()) vm := fvm.NewVirtualMachine() @@ -159,7 +157,7 @@ func TestDeploy(t *testing.T) { } ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), fvm.WithCadenceLogging(true), diff --git a/cmd/util/ledger/migrations/storage_used_migration_test.go b/cmd/util/ledger/migrations/storage_used_migration_test.go index cd4ebb3ba4e..d1486406ac1 100644 --- a/cmd/util/ledger/migrations/storage_used_migration_test.go +++ b/cmd/util/ledger/migrations/storage_used_migration_test.go @@ -32,7 +32,7 @@ func TestAccountStatusMigration(t *testing.T) { sizeOfTheStatusPayload := uint64( environment.RegisterSize( - flow.AccountStatusRegisterID(flow.ConvertAddress(address)), + flow.AccountStatusRegisterID(flow.Address(address)), environment.NewAccountStatus().ToBytes(), ), ) @@ -71,70 +71,6 @@ func TestAccountStatusMigration(t *testing.T) { require.Error(t, err) }) - t.Run("status register v1", func(t *testing.T) { - t.Parallel() - - accountPublicKeyCount := uint32(5) - statusPayloadAndSequenceNubmerSize := sizeOfTheStatusPayload + - predefinedSequenceNumberPayloadSizes(string(address[:]), 1, accountPublicKeyCount) - - payloads := []*ledger.Payload{ - ledger.NewPayload( - ledger.NewKey([]ledger.KeyPart{ownerKey, {Type: 2, Value: []byte(flow.AccountStatusKey)}}), - []byte{ - 0, // flags - 0, 0, 0, 0, 0, 0, 0, 7, // storage used - 0, 0, 0, 0, 0, 0, 0, 6, // storage index - 0, 0, 0, 0, 0, 0, 0, 5, // public key counts - }, - ), - } - - migrated, err := migrate(payloads) - require.NoError(t, err) - require.Len(t, migrated, 1) - - accountStatus, err := environment.AccountStatusFromBytes(migrated[0].Value()) - require.NoError(t, err) - - require.Equal(t, statusPayloadAndSequenceNubmerSize, accountStatus.StorageUsed()) - require.Equal(t, atree.SlabIndex{0, 0, 0, 0, 0, 0, 0, 6}, accountStatus.SlabIndex()) - require.Equal(t, accountPublicKeyCount, accountStatus.AccountPublicKeyCount()) - require.Equal(t, uint64(0), accountStatus.AccountIdCounter()) - }) - t.Run("status register v2", func(t *testing.T) { - t.Parallel() - - accountPublicKeyCount := uint32(5) - statusPayloadAndSequenceNubmerSize := sizeOfTheStatusPayload + - predefinedSequenceNumberPayloadSizes(string(address[:]), 1, accountPublicKeyCount) - - payloads := []*ledger.Payload{ - ledger.NewPayload( - ledger.NewKey([]ledger.KeyPart{ownerKey, {Type: 2, Value: []byte(flow.AccountStatusKey)}}), - []byte{ - 0, // flags - 0, 0, 0, 0, 0, 0, 0, 100, // storage used - 0, 0, 0, 0, 0, 0, 0, 6, // storage index - 0, 0, 0, 0, 0, 0, 0, 5, // public key counts - 0, 0, 0, 0, 0, 0, 0, 3, // account id counter - }, - ), - } - - migrated, err := migrate(payloads) - require.NoError(t, err) - require.Len(t, migrated, 1) - - accountStatus, err := environment.AccountStatusFromBytes(migrated[0].Value()) - require.NoError(t, err) - - require.Equal(t, statusPayloadAndSequenceNubmerSize, accountStatus.StorageUsed()) - require.Equal(t, atree.SlabIndex{0, 0, 0, 0, 0, 0, 0, 6}, accountStatus.SlabIndex()) - require.Equal(t, accountPublicKeyCount, accountStatus.AccountPublicKeyCount()) - require.Equal(t, uint64(3), accountStatus.AccountIdCounter()) - }) - t.Run("status register v3", func(t *testing.T) { t.Parallel() @@ -210,7 +146,7 @@ func TestAccountStatusMigration(t *testing.T) { dataRegisterSize := uint64(environment.RegisterSize( flow.RegisterID{ - Owner: string(flow.ConvertAddress(address).Bytes()), + Owner: string(flow.Address(address).Bytes()), Key: "1", }, make([]byte, 100), diff --git a/cmd/util/ledger/migrations/transaction_migration.go b/cmd/util/ledger/migrations/transaction_migration.go index 488ce1aeb63..2ecb86e7ba4 100644 --- a/cmd/util/ledger/migrations/transaction_migration.go +++ b/cmd/util/ledger/migrations/transaction_migration.go @@ -19,14 +19,14 @@ func NewTransactionBasedMigration( ) RegistersMigration { return func(registersByAccount *registers.ByAccount) error { - options := computation.DefaultFVMOptions(chainID, false, false) + options := computation.DefaultFVMOptions(chainID, false, false, false) options = append(options, fvm.WithContractDeploymentRestricted(false), fvm.WithContractRemovalRestricted(false), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), fvm.WithTransactionFeesEnabled(false)) - ctx := fvm.NewContext(options...) + ctx := fvm.NewContext(chainID.Chain(), options...) storageSnapshot := registers.StorageSnapshot{ Registers: registersByAccount, diff --git a/cmd/util/ledger/reporters/account_reporter.go b/cmd/util/ledger/reporters/account_reporter.go index 859bb32ca83..c92eb1a52ce 100644 --- a/cmd/util/ledger/reporters/account_reporter.go +++ b/cmd/util/ledger/reporters/account_reporter.go @@ -143,7 +143,7 @@ func NewBalanceReporter( ) *balanceProcessor { vm := fvm.NewVirtualMachine() ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithMemoryAndInteractionLimitsDisabled()) env := environment.NewScriptEnvironmentFromStorageSnapshot( @@ -217,7 +217,7 @@ func (c *balanceProcessor) reportAccountData(indx uint64) { return } - runtimeAddress := common.MustBytesToAddress(address.Bytes()) + runtimeAddress := common.Address(address) u, err := c.env.GetStorageUsed(runtimeAddress) if err != nil { diff --git a/cmd/util/ledger/reporters/atree_decode.go b/cmd/util/ledger/reporters/atree_decode.go index 96720afd5c5..2e99ef12970 100644 --- a/cmd/util/ledger/reporters/atree_decode.go +++ b/cmd/util/ledger/reporters/atree_decode.go @@ -153,7 +153,7 @@ func skipMapExtraData(data []byte, decMode cbor.DecMode) ([]byte, error) { r := bytes.NewReader(data[versionAndFlagSize:]) dec := decMode.NewDecoder(r) - var v []interface{} + var v []any err := dec.Decode(&v) if err != nil { return data, errors.New("failed to decode map extra data") diff --git a/cmd/util/ledger/reporters/atree_reporter.go b/cmd/util/ledger/reporters/atree_reporter.go index 39c005dbc55..2e4e1a2e5d6 100644 --- a/cmd/util/ledger/reporters/atree_reporter.go +++ b/cmd/util/ledger/reporters/atree_reporter.go @@ -68,7 +68,7 @@ func (r *AtreeReporter) Report(payloads []ledger.Payload, commit ledger.State) e } // produce jobs for workers to process - for i := 0; i < len(payloads); i++ { + for i := range payloads { jobs <- &payloads[i] err := progress.Add(1) diff --git a/cmd/util/ledger/reporters/fungible_token_tracker.go b/cmd/util/ledger/reporters/fungible_token_tracker.go index 555cf90df9e..6d93288e2e0 100644 --- a/cmd/util/ledger/reporters/fungible_token_tracker.go +++ b/cmd/util/ledger/reporters/fungible_token_tracker.go @@ -122,7 +122,7 @@ func (r *FungibleTokenTracker) Report(payloads []ledger.Payload, commit ledger.S close(jobs) workerCount := runtime.NumCPU() - for i := 0; i < workerCount; i++ { + for range workerCount { wg.Add(1) go r.worker(jobs, wg) } diff --git a/cmd/util/ledger/reporters/fungible_token_tracker_test.go b/cmd/util/ledger/reporters/fungible_token_tracker_test.go index 253b147a0af..8183216dbff 100644 --- a/cmd/util/ledger/reporters/fungible_token_tracker_test.go +++ b/cmd/util/ledger/reporters/fungible_token_tracker_test.go @@ -50,11 +50,10 @@ func TestFungibleTokenTracker(t *testing.T) { vm := fvm.NewVirtualMachine() opts := []fvm.Option{ - fvm.WithChain(chain), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), } - ctx := fvm.NewContext(opts...) + ctx := fvm.NewContext(chain, opts...) bootstrapOptions := []fvm.BootstrapProcedureOption{ fvm.WithTransactionFee(fvm.DefaultTransactionFees), fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), diff --git a/cmd/util/ledger/reporters/mock/report_writer.go b/cmd/util/ledger/reporters/mock/report_writer.go deleted file mode 100644 index 4f601f06d08..00000000000 --- a/cmd/util/ledger/reporters/mock/report_writer.go +++ /dev/null @@ -1,34 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import mock "github.com/stretchr/testify/mock" - -// ReportWriter is an autogenerated mock type for the ReportWriter type -type ReportWriter struct { - mock.Mock -} - -// Close provides a mock function with no fields -func (_m *ReportWriter) Close() { - _m.Called() -} - -// Write provides a mock function with given fields: dataPoint -func (_m *ReportWriter) Write(dataPoint interface{}) { - _m.Called(dataPoint) -} - -// NewReportWriter creates a new instance of ReportWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReportWriter(t interface { - mock.TestingT - Cleanup(func()) -}) *ReportWriter { - mock := &ReportWriter{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/cmd/util/ledger/reporters/mock/report_writer_factory.go b/cmd/util/ledger/reporters/mock/report_writer_factory.go deleted file mode 100644 index 2177d4d3306..00000000000 --- a/cmd/util/ledger/reporters/mock/report_writer_factory.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - reporters "github.com/onflow/flow-go/cmd/util/ledger/reporters" - mock "github.com/stretchr/testify/mock" -) - -// ReportWriterFactory is an autogenerated mock type for the ReportWriterFactory type -type ReportWriterFactory struct { - mock.Mock -} - -// ReportWriter provides a mock function with given fields: dataNamespace -func (_m *ReportWriterFactory) ReportWriter(dataNamespace string) reporters.ReportWriter { - ret := _m.Called(dataNamespace) - - if len(ret) == 0 { - panic("no return value specified for ReportWriter") - } - - var r0 reporters.ReportWriter - if rf, ok := ret.Get(0).(func(string) reporters.ReportWriter); ok { - r0 = rf(dataNamespace) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(reporters.ReportWriter) - } - } - - return r0 -} - -// NewReportWriterFactory creates a new instance of ReportWriterFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReportWriterFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *ReportWriterFactory { - mock := &ReportWriterFactory{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/cmd/util/ledger/reporters/reporter_output.go b/cmd/util/ledger/reporters/reporter_output.go index 22d529c8d46..5088b92a7aa 100644 --- a/cmd/util/ledger/reporters/reporter_output.go +++ b/cmd/util/ledger/reporters/reporter_output.go @@ -91,7 +91,7 @@ func NewReportFileWriter(fileName string, log zerolog.Logger, format ReportForma // ReportWriter writes data from reports type ReportWriter interface { - Write(dataPoint interface{}) + Write(dataPoint any) Close() } @@ -103,7 +103,7 @@ type ReportNilWriter struct { var _ ReportWriter = &ReportNilWriter{} -func (r ReportNilWriter) Write(_ interface{}) { +func (r ReportNilWriter) Write(_ any) { } func (r ReportNilWriter) Close() { @@ -115,7 +115,7 @@ type JSONReportFileWriter struct { f *os.File fileName string wg *sync.WaitGroup - writeChan chan interface{} + writeChan chan any writer *bufio.Writer log zerolog.Logger format ReportFormat @@ -162,28 +162,26 @@ func NewJSONReportFileWriter(fileName string, log zerolog.Logger, format ReportF writer: writer, log: log, firstWrite: true, - writeChan: make(chan interface{}, reportFileWriteBufferSize), + writeChan: make(chan any, reportFileWriteBufferSize), wg: &sync.WaitGroup{}, format: format, } - fw.wg.Add(1) - go func() { + fw.wg.Go(func() { for d := range fw.writeChan { fw.write(d) } - fw.wg.Done() - }() + }) return fw } -func (r *JSONReportFileWriter) Write(dataPoint interface{}) { +func (r *JSONReportFileWriter) Write(dataPoint any) { r.writeChan <- dataPoint } -func (r *JSONReportFileWriter) write(dataPoint interface{}) { +func (r *JSONReportFileWriter) write(dataPoint any) { if r.faulty { return } @@ -282,19 +280,17 @@ func NewCSVReportFileWriter(fileName string, log zerolog.Logger) ReportWriter { wg: &sync.WaitGroup{}, } - fw.wg.Add(1) - go func() { + fw.wg.Go(func() { for d := range fw.writeChan { fw.write(d) } - fw.wg.Done() - }() + }) return fw } -func (r *CSVReportFileWriter) Write(dataPoint interface{}) { +func (r *CSVReportFileWriter) Write(dataPoint any) { record, ok := dataPoint.([]string) if !ok { r.log.Warn().Msgf("cannot write %T to csv, skip this record", dataPoint) diff --git a/cmd/util/ledger/util/payload_file.go b/cmd/util/ledger/util/payload_file.go index 4b419d19736..7ad8f0a02d9 100644 --- a/cmd/util/ledger/util/payload_file.go +++ b/cmd/util/ledger/util/payload_file.go @@ -307,7 +307,7 @@ func ReadPayloadFile(logger zerolog.Logger, payloadFile string) (bool, []*ledger payloads := make([]*ledger.Payload, payloadCount) - for i := 0; i < payloadCount; i++ { + for i := range payloadCount { var rawPayload []byte err := dec.Decode(&rawPayload) if err != nil { diff --git a/cmd/util/ledger/util/registers/registers.go b/cmd/util/ledger/util/registers/registers.go index c16abefe5f9..faaa8285a6f 100644 --- a/cmd/util/ledger/util/registers/registers.go +++ b/cmd/util/ledger/util/registers/registers.go @@ -105,7 +105,7 @@ func (b *ByAccount) DestructIntoPayloads(nWorker int) []*ledger.Payload { } } - for i := 0; i < nWorker; i++ { + for range nWorker { wg.Add(1) go worker() } diff --git a/cmd/util/ledger/util/topn.go b/cmd/util/ledger/util/topn.go index 25031974477..3278ee2c7b0 100644 --- a/cmd/util/ledger/util/topn.go +++ b/cmd/util/ledger/util/topn.go @@ -35,11 +35,11 @@ func (h *TopN[T]) Swap(i, j int) { h.Tree[j], h.Tree[i] } -func (h *TopN[T]) Push(x interface{}) { +func (h *TopN[T]) Push(x any) { h.Tree = append(h.Tree, x.(T)) } -func (h *TopN[T]) Pop() interface{} { +func (h *TopN[T]) Pop() any { tree := h.Tree count := len(tree) lastIndex := count - 1 diff --git a/cmd/verification_builder.go b/cmd/verification_builder.go index 976814b1e06..7bf2939647a 100644 --- a/cmd/verification_builder.go +++ b/cmd/verification_builder.go @@ -16,7 +16,6 @@ import ( "github.com/onflow/flow-go/consensus/hotstuff/verification" recoveryprotocol "github.com/onflow/flow-go/consensus/recovery/protocol" "github.com/onflow/flow-go/engine/common/follower" - followereng "github.com/onflow/flow-go/engine/common/follower" commonsync "github.com/onflow/flow-go/engine/common/synchronization" "github.com/onflow/flow-go/engine/execution/computation" "github.com/onflow/flow-go/engine/verification/assigner" @@ -91,11 +90,11 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { var ( followerState protocol.FollowerState - chunkStatuses *stdmap.ChunkStatuses // used in fetcher engine - chunkRequests *stdmap.ChunkRequests // used in requester engine - processedChunkIndex storage.ConsumerProgressInitializer // used in chunk consumer - processedBlockHeight storage.ConsumerProgressInitializer // used in block consumer - chunkQueue storage.ChunksQueue // used in chunk consumer + chunkStatuses *stdmap.ChunkStatuses // used in fetcher engine + chunkRequests *stdmap.ChunkRequests // used in requester engine + processedChunkIndexInitializer storage.ConsumerProgressInitializer // used in chunk consumer + processedBlockHeightInitializer storage.ConsumerProgressInitializer // used in block consumer + chunkQueue storage.ChunksQueue // used in chunk consumer syncCore *chainsync.Core // used in follower engine assignerEngine *assigner.Engine // the assigner engine @@ -158,11 +157,11 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { return nil }). Module("processed chunk index consumer progress", func(node *NodeConfig) error { - processedChunkIndex = store.NewConsumerProgress(node.ProtocolDB, module.ConsumeProgressVerificationChunkIndex) + processedChunkIndexInitializer = store.NewConsumerProgress(node.ProtocolDB, module.ConsumeProgressVerificationChunkIndex) return nil }). Module("processed block height consumer progress", func(node *NodeConfig) error { - processedBlockHeight = store.NewConsumerProgress(node.ProtocolDB, module.ConsumeProgressVerificationBlockHeight) + processedBlockHeightInitializer = store.NewConsumerProgress(node.ProtocolDB, module.ConsumeProgressVerificationBlockHeight) return nil }). Module("chunks queue", func(node *NodeConfig) error { @@ -212,9 +211,10 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { node.RootChainID, false, v.verConf.scheduledTransactionsEnabled, + false, )..., ) - vmCtx := fvm.NewContext(fvmOptions...) + vmCtx := fvm.NewContext(node.RootChainID.Chain(), fvmOptions...) chunkVerifier := chunks.NewChunkVerifier(vm, vmCtx, node.Logger) @@ -269,6 +269,11 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { requesterEngine, v.verConf.stopAtHeight) + processedChunkIndex, err := processedChunkIndexInitializer.Initialize(chunkconsumer.DefaultJobIndex) + if err != nil { + return nil, fmt.Errorf("could not initialize processed index: %w", err) + } + // requester and fetcher engines are started by chunk consumer chunkConsumer, err = chunkconsumer.NewChunkConsumer( node.Logger, @@ -312,10 +317,17 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { return assignerEngine, nil }). Component("block consumer", func(node *NodeConfig) (module.ReadyDoneAware, error) { - var initBlockHeight uint64 - var err error + sealedHead, err := node.State.Sealed().Head() + if err != nil { + return nil, fmt.Errorf("could not get sealed head: %w", err) + } + + processedBlockHeight, err := processedBlockHeightInitializer.Initialize(sealedHead.Height) + if err != nil { + return nil, fmt.Errorf("could not initialize processed block height index: %w", err) + } - blockConsumer, initBlockHeight, err = blockconsumer.NewBlockConsumer( + blockConsumer, err = blockconsumer.NewBlockConsumer( node.Logger, collector, processedBlockHeight, @@ -336,7 +348,7 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { node.Logger.Info(). Str("component", "node-builder"). - Uint64("init_height", initBlockHeight). + Uint64("init_height", sealedHead.Height). Msg("block consumer initialized") return blockConsumer, nil @@ -390,7 +402,7 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { heroCacheCollector = metrics.FollowerCacheMetrics(node.MetricsRegisterer) } - core, err := followereng.NewComplianceCore( + core, err := follower.NewComplianceCore( node.Logger, node.Metrics.Mempool, heroCacheCollector, @@ -405,7 +417,7 @@ func (v *VerificationNodeBuilder) LoadComponentsAndModules() { return nil, fmt.Errorf("could not create follower core: %w", err) } - followerEng, err = followereng.NewComplianceLayer( + followerEng, err = follower.NewComplianceLayer( node.Logger, node.EngineRegistry, node.Me, diff --git a/config/default-config.yml b/config/default-config.yml index 0d338492ab9..218c6bd8e36 100644 --- a/config/default-config.yml +++ b/config/default-config.yml @@ -16,14 +16,16 @@ network-config: dns-cache-ttl: 5m # The size of the queue for notifications about new peers in the disallow list. disallow-list-notification-cache-size: 100 + # Maximum number of messages in the inbound message queue. Limits memory growth from message flooding. + message-queue-size: 100_000 unicast: rate-limiter: # Setting this to true will disable connection disconnects and gating when unicast rate limiters are configured - dry-run: true + dry-run: false # The number of seconds a peer will be forced to wait before being allowed to successfully reconnect to the node after being rate limited lockout-duration: 10s # Amount of unicast messages that can be sent by a peer per second - message-rate-limit: 0 + message-rate-limit: 500 # Bandwidth size in bytes a peer is allowed to send via unicast streams per second bandwidth-rate-limit: 0 # Bandwidth size in bytes a peer is allowed to send via unicast streams at once diff --git a/consensus/hotstuff/mocks/block_producer.go b/consensus/hotstuff/mocks/block_producer.go index af340b10071..baede21ca11 100644 --- a/consensus/hotstuff/mocks/block_producer.go +++ b/consensus/hotstuff/mocks/block_producer.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBlockProducer creates a new instance of BlockProducer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockProducer(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockProducer { + mock := &BlockProducer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BlockProducer is an autogenerated mock type for the BlockProducer type type BlockProducer struct { mock.Mock } -// MakeBlockProposal provides a mock function with given fields: view, qc, lastViewTC -func (_m *BlockProducer) MakeBlockProposal(view uint64, qc *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*flow.ProposalHeader, error) { - ret := _m.Called(view, qc, lastViewTC) +type BlockProducer_Expecter struct { + mock *mock.Mock +} + +func (_m *BlockProducer) EXPECT() *BlockProducer_Expecter { + return &BlockProducer_Expecter{mock: &_m.Mock} +} + +// MakeBlockProposal provides a mock function for the type BlockProducer +func (_mock *BlockProducer) MakeBlockProposal(view uint64, qc *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*flow.ProposalHeader, error) { + ret := _mock.Called(view, qc, lastViewTC) if len(ret) == 0 { panic("no return value specified for MakeBlockProposal") @@ -23,36 +46,66 @@ func (_m *BlockProducer) MakeBlockProposal(view uint64, qc *flow.QuorumCertifica var r0 *flow.ProposalHeader var r1 error - if rf, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) (*flow.ProposalHeader, error)); ok { - return rf(view, qc, lastViewTC) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) (*flow.ProposalHeader, error)); ok { + return returnFunc(view, qc, lastViewTC) } - if rf, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) *flow.ProposalHeader); ok { - r0 = rf(view, qc, lastViewTC) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) *flow.ProposalHeader); ok { + r0 = returnFunc(view, qc, lastViewTC) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ProposalHeader) } } - - if rf, ok := ret.Get(1).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) error); ok { - r1 = rf(view, qc, lastViewTC) + if returnFunc, ok := ret.Get(1).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) error); ok { + r1 = returnFunc(view, qc, lastViewTC) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBlockProducer creates a new instance of BlockProducer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockProducer(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockProducer { - mock := &BlockProducer{} - mock.Mock.Test(t) +// BlockProducer_MakeBlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MakeBlockProposal' +type BlockProducer_MakeBlockProposal_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// MakeBlockProposal is a helper method to define mock.On call +// - view uint64 +// - qc *flow.QuorumCertificate +// - lastViewTC *flow.TimeoutCertificate +func (_e *BlockProducer_Expecter) MakeBlockProposal(view interface{}, qc interface{}, lastViewTC interface{}) *BlockProducer_MakeBlockProposal_Call { + return &BlockProducer_MakeBlockProposal_Call{Call: _e.mock.On("MakeBlockProposal", view, qc, lastViewTC)} +} - return mock +func (_c *BlockProducer_MakeBlockProposal_Call) Run(run func(view uint64, qc *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *BlockProducer_MakeBlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *BlockProducer_MakeBlockProposal_Call) Return(proposalHeader *flow.ProposalHeader, err error) *BlockProducer_MakeBlockProposal_Call { + _c.Call.Return(proposalHeader, err) + return _c +} + +func (_c *BlockProducer_MakeBlockProposal_Call) RunAndReturn(run func(view uint64, qc *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*flow.ProposalHeader, error)) *BlockProducer_MakeBlockProposal_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/block_signer_decoder.go b/consensus/hotstuff/mocks/block_signer_decoder.go index 518cfe567fb..6f119a49969 100644 --- a/consensus/hotstuff/mocks/block_signer_decoder.go +++ b/consensus/hotstuff/mocks/block_signer_decoder.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBlockSignerDecoder creates a new instance of BlockSignerDecoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockSignerDecoder(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockSignerDecoder { + mock := &BlockSignerDecoder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BlockSignerDecoder is an autogenerated mock type for the BlockSignerDecoder type type BlockSignerDecoder struct { mock.Mock } -// DecodeSignerIDs provides a mock function with given fields: header -func (_m *BlockSignerDecoder) DecodeSignerIDs(header *flow.Header) (flow.IdentifierList, error) { - ret := _m.Called(header) +type BlockSignerDecoder_Expecter struct { + mock *mock.Mock +} + +func (_m *BlockSignerDecoder) EXPECT() *BlockSignerDecoder_Expecter { + return &BlockSignerDecoder_Expecter{mock: &_m.Mock} +} + +// DecodeSignerIDs provides a mock function for the type BlockSignerDecoder +func (_mock *BlockSignerDecoder) DecodeSignerIDs(header *flow.Header) (flow.IdentifierList, error) { + ret := _mock.Called(header) if len(ret) == 0 { panic("no return value specified for DecodeSignerIDs") @@ -23,36 +46,54 @@ func (_m *BlockSignerDecoder) DecodeSignerIDs(header *flow.Header) (flow.Identif var r0 flow.IdentifierList var r1 error - if rf, ok := ret.Get(0).(func(*flow.Header) (flow.IdentifierList, error)); ok { - return rf(header) + if returnFunc, ok := ret.Get(0).(func(*flow.Header) (flow.IdentifierList, error)); ok { + return returnFunc(header) } - if rf, ok := ret.Get(0).(func(*flow.Header) flow.IdentifierList); ok { - r0 = rf(header) + if returnFunc, ok := ret.Get(0).(func(*flow.Header) flow.IdentifierList); ok { + r0 = returnFunc(header) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentifierList) } } - - if rf, ok := ret.Get(1).(func(*flow.Header) error); ok { - r1 = rf(header) + if returnFunc, ok := ret.Get(1).(func(*flow.Header) error); ok { + r1 = returnFunc(header) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBlockSignerDecoder creates a new instance of BlockSignerDecoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockSignerDecoder(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockSignerDecoder { - mock := &BlockSignerDecoder{} - mock.Mock.Test(t) +// BlockSignerDecoder_DecodeSignerIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DecodeSignerIDs' +type BlockSignerDecoder_DecodeSignerIDs_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// DecodeSignerIDs is a helper method to define mock.On call +// - header *flow.Header +func (_e *BlockSignerDecoder_Expecter) DecodeSignerIDs(header interface{}) *BlockSignerDecoder_DecodeSignerIDs_Call { + return &BlockSignerDecoder_DecodeSignerIDs_Call{Call: _e.mock.On("DecodeSignerIDs", header)} +} - return mock +func (_c *BlockSignerDecoder_DecodeSignerIDs_Call) Run(run func(header *flow.Header)) *BlockSignerDecoder_DecodeSignerIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockSignerDecoder_DecodeSignerIDs_Call) Return(identifierList flow.IdentifierList, err error) *BlockSignerDecoder_DecodeSignerIDs_Call { + _c.Call.Return(identifierList, err) + return _c +} + +func (_c *BlockSignerDecoder_DecodeSignerIDs_Call) RunAndReturn(run func(header *flow.Header) (flow.IdentifierList, error)) *BlockSignerDecoder_DecodeSignerIDs_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/communicator_consumer.go b/consensus/hotstuff/mocks/communicator_consumer.go index bda84f4661e..48a9a0bff0c 100644 --- a/consensus/hotstuff/mocks/communicator_consumer.go +++ b/consensus/hotstuff/mocks/communicator_consumer.go @@ -1,47 +1,172 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" + "time" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" +) + +// NewCommunicatorConsumer creates a new instance of CommunicatorConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCommunicatorConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *CommunicatorConsumer { + mock := &CommunicatorConsumer{} + mock.Mock.Test(t) - model "github.com/onflow/flow-go/consensus/hotstuff/model" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // CommunicatorConsumer is an autogenerated mock type for the CommunicatorConsumer type type CommunicatorConsumer struct { mock.Mock } -// OnOwnProposal provides a mock function with given fields: proposal, targetPublicationTime -func (_m *CommunicatorConsumer) OnOwnProposal(proposal *flow.ProposalHeader, targetPublicationTime time.Time) { - _m.Called(proposal, targetPublicationTime) +type CommunicatorConsumer_Expecter struct { + mock *mock.Mock } -// OnOwnTimeout provides a mock function with given fields: timeout -func (_m *CommunicatorConsumer) OnOwnTimeout(timeout *model.TimeoutObject) { - _m.Called(timeout) +func (_m *CommunicatorConsumer) EXPECT() *CommunicatorConsumer_Expecter { + return &CommunicatorConsumer_Expecter{mock: &_m.Mock} } -// OnOwnVote provides a mock function with given fields: vote, recipientID -func (_m *CommunicatorConsumer) OnOwnVote(vote *model.Vote, recipientID flow.Identifier) { - _m.Called(vote, recipientID) +// OnOwnProposal provides a mock function for the type CommunicatorConsumer +func (_mock *CommunicatorConsumer) OnOwnProposal(proposal *flow.ProposalHeader, targetPublicationTime time.Time) { + _mock.Called(proposal, targetPublicationTime) + return } -// NewCommunicatorConsumer creates a new instance of CommunicatorConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCommunicatorConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *CommunicatorConsumer { - mock := &CommunicatorConsumer{} - mock.Mock.Test(t) +// CommunicatorConsumer_OnOwnProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOwnProposal' +type CommunicatorConsumer_OnOwnProposal_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnOwnProposal is a helper method to define mock.On call +// - proposal *flow.ProposalHeader +// - targetPublicationTime time.Time +func (_e *CommunicatorConsumer_Expecter) OnOwnProposal(proposal interface{}, targetPublicationTime interface{}) *CommunicatorConsumer_OnOwnProposal_Call { + return &CommunicatorConsumer_OnOwnProposal_Call{Call: _e.mock.On("OnOwnProposal", proposal, targetPublicationTime)} +} - return mock +func (_c *CommunicatorConsumer_OnOwnProposal_Call) Run(run func(proposal *flow.ProposalHeader, targetPublicationTime time.Time)) *CommunicatorConsumer_OnOwnProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ProposalHeader + if args[0] != nil { + arg0 = args[0].(*flow.ProposalHeader) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *CommunicatorConsumer_OnOwnProposal_Call) Return() *CommunicatorConsumer_OnOwnProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *CommunicatorConsumer_OnOwnProposal_Call) RunAndReturn(run func(proposal *flow.ProposalHeader, targetPublicationTime time.Time)) *CommunicatorConsumer_OnOwnProposal_Call { + _c.Run(run) + return _c +} + +// OnOwnTimeout provides a mock function for the type CommunicatorConsumer +func (_mock *CommunicatorConsumer) OnOwnTimeout(timeout *model.TimeoutObject) { + _mock.Called(timeout) + return +} + +// CommunicatorConsumer_OnOwnTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOwnTimeout' +type CommunicatorConsumer_OnOwnTimeout_Call struct { + *mock.Call +} + +// OnOwnTimeout is a helper method to define mock.On call +// - timeout *model.TimeoutObject +func (_e *CommunicatorConsumer_Expecter) OnOwnTimeout(timeout interface{}) *CommunicatorConsumer_OnOwnTimeout_Call { + return &CommunicatorConsumer_OnOwnTimeout_Call{Call: _e.mock.On("OnOwnTimeout", timeout)} +} + +func (_c *CommunicatorConsumer_OnOwnTimeout_Call) Run(run func(timeout *model.TimeoutObject)) *CommunicatorConsumer_OnOwnTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CommunicatorConsumer_OnOwnTimeout_Call) Return() *CommunicatorConsumer_OnOwnTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *CommunicatorConsumer_OnOwnTimeout_Call) RunAndReturn(run func(timeout *model.TimeoutObject)) *CommunicatorConsumer_OnOwnTimeout_Call { + _c.Run(run) + return _c +} + +// OnOwnVote provides a mock function for the type CommunicatorConsumer +func (_mock *CommunicatorConsumer) OnOwnVote(vote *model.Vote, recipientID flow.Identifier) { + _mock.Called(vote, recipientID) + return +} + +// CommunicatorConsumer_OnOwnVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOwnVote' +type CommunicatorConsumer_OnOwnVote_Call struct { + *mock.Call +} + +// OnOwnVote is a helper method to define mock.On call +// - vote *model.Vote +// - recipientID flow.Identifier +func (_e *CommunicatorConsumer_Expecter) OnOwnVote(vote interface{}, recipientID interface{}) *CommunicatorConsumer_OnOwnVote_Call { + return &CommunicatorConsumer_OnOwnVote_Call{Call: _e.mock.On("OnOwnVote", vote, recipientID)} +} + +func (_c *CommunicatorConsumer_OnOwnVote_Call) Run(run func(vote *model.Vote, recipientID flow.Identifier)) *CommunicatorConsumer_OnOwnVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *CommunicatorConsumer_OnOwnVote_Call) Return() *CommunicatorConsumer_OnOwnVote_Call { + _c.Call.Return() + return _c +} + +func (_c *CommunicatorConsumer_OnOwnVote_Call) RunAndReturn(run func(vote *model.Vote, recipientID flow.Identifier)) *CommunicatorConsumer_OnOwnVote_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/consumer.go b/consensus/hotstuff/mocks/consumer.go index e4efa650e95..2988a3ee467 100644 --- a/consensus/hotstuff/mocks/consumer.go +++ b/consensus/hotstuff/mocks/consumer.go @@ -1,128 +1,878 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - flow "github.com/onflow/flow-go/model/flow" + "time" + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" +) + +// NewConsumer creates a new instance of Consumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *Consumer { + mock := &Consumer{} + mock.Mock.Test(t) - model "github.com/onflow/flow-go/consensus/hotstuff/model" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // Consumer is an autogenerated mock type for the Consumer type type Consumer struct { mock.Mock } -// OnBlockIncorporated provides a mock function with given fields: _a0 -func (_m *Consumer) OnBlockIncorporated(_a0 *model.Block) { - _m.Called(_a0) +type Consumer_Expecter struct { + mock *mock.Mock } -// OnCurrentViewDetails provides a mock function with given fields: currentView, finalizedView, currentLeader -func (_m *Consumer) OnCurrentViewDetails(currentView uint64, finalizedView uint64, currentLeader flow.Identifier) { - _m.Called(currentView, finalizedView, currentLeader) +func (_m *Consumer) EXPECT() *Consumer_Expecter { + return &Consumer_Expecter{mock: &_m.Mock} } -// OnDoubleProposeDetected provides a mock function with given fields: _a0, _a1 -func (_m *Consumer) OnDoubleProposeDetected(_a0 *model.Block, _a1 *model.Block) { - _m.Called(_a0, _a1) +// OnBlockIncorporated provides a mock function for the type Consumer +func (_mock *Consumer) OnBlockIncorporated(block *model.Block) { + _mock.Called(block) + return } -// OnEventProcessed provides a mock function with no fields -func (_m *Consumer) OnEventProcessed() { - _m.Called() +// Consumer_OnBlockIncorporated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockIncorporated' +type Consumer_OnBlockIncorporated_Call struct { + *mock.Call } -// OnFinalizedBlock provides a mock function with given fields: _a0 -func (_m *Consumer) OnFinalizedBlock(_a0 *model.Block) { - _m.Called(_a0) +// OnBlockIncorporated is a helper method to define mock.On call +// - block *model.Block +func (_e *Consumer_Expecter) OnBlockIncorporated(block interface{}) *Consumer_OnBlockIncorporated_Call { + return &Consumer_OnBlockIncorporated_Call{Call: _e.mock.On("OnBlockIncorporated", block)} } -// OnInvalidBlockDetected provides a mock function with given fields: err -func (_m *Consumer) OnInvalidBlockDetected(err flow.Slashable[model.InvalidProposalError]) { - _m.Called(err) +func (_c *Consumer_OnBlockIncorporated_Call) Run(run func(block *model.Block)) *Consumer_OnBlockIncorporated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c } -// OnLocalTimeout provides a mock function with given fields: currentView -func (_m *Consumer) OnLocalTimeout(currentView uint64) { - _m.Called(currentView) +func (_c *Consumer_OnBlockIncorporated_Call) Return() *Consumer_OnBlockIncorporated_Call { + _c.Call.Return() + return _c } -// OnOwnProposal provides a mock function with given fields: proposal, targetPublicationTime -func (_m *Consumer) OnOwnProposal(proposal *flow.ProposalHeader, targetPublicationTime time.Time) { - _m.Called(proposal, targetPublicationTime) +func (_c *Consumer_OnBlockIncorporated_Call) RunAndReturn(run func(block *model.Block)) *Consumer_OnBlockIncorporated_Call { + _c.Run(run) + return _c } -// OnOwnTimeout provides a mock function with given fields: timeout -func (_m *Consumer) OnOwnTimeout(timeout *model.TimeoutObject) { - _m.Called(timeout) +// OnCurrentViewDetails provides a mock function for the type Consumer +func (_mock *Consumer) OnCurrentViewDetails(currentView uint64, finalizedView uint64, currentLeader flow.Identifier) { + _mock.Called(currentView, finalizedView, currentLeader) + return } -// OnOwnVote provides a mock function with given fields: vote, recipientID -func (_m *Consumer) OnOwnVote(vote *model.Vote, recipientID flow.Identifier) { - _m.Called(vote, recipientID) +// Consumer_OnCurrentViewDetails_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnCurrentViewDetails' +type Consumer_OnCurrentViewDetails_Call struct { + *mock.Call } -// OnPartialTc provides a mock function with given fields: currentView, partialTc -func (_m *Consumer) OnPartialTc(currentView uint64, partialTc *hotstuff.PartialTcCreated) { - _m.Called(currentView, partialTc) +// OnCurrentViewDetails is a helper method to define mock.On call +// - currentView uint64 +// - finalizedView uint64 +// - currentLeader flow.Identifier +func (_e *Consumer_Expecter) OnCurrentViewDetails(currentView interface{}, finalizedView interface{}, currentLeader interface{}) *Consumer_OnCurrentViewDetails_Call { + return &Consumer_OnCurrentViewDetails_Call{Call: _e.mock.On("OnCurrentViewDetails", currentView, finalizedView, currentLeader)} } -// OnQcTriggeredViewChange provides a mock function with given fields: oldView, newView, qc -func (_m *Consumer) OnQcTriggeredViewChange(oldView uint64, newView uint64, qc *flow.QuorumCertificate) { - _m.Called(oldView, newView, qc) +func (_c *Consumer_OnCurrentViewDetails_Call) Run(run func(currentView uint64, finalizedView uint64, currentLeader flow.Identifier)) *Consumer_OnCurrentViewDetails_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// OnReceiveProposal provides a mock function with given fields: currentView, proposal -func (_m *Consumer) OnReceiveProposal(currentView uint64, proposal *model.SignedProposal) { - _m.Called(currentView, proposal) +func (_c *Consumer_OnCurrentViewDetails_Call) Return() *Consumer_OnCurrentViewDetails_Call { + _c.Call.Return() + return _c } -// OnReceiveQc provides a mock function with given fields: currentView, qc -func (_m *Consumer) OnReceiveQc(currentView uint64, qc *flow.QuorumCertificate) { - _m.Called(currentView, qc) +func (_c *Consumer_OnCurrentViewDetails_Call) RunAndReturn(run func(currentView uint64, finalizedView uint64, currentLeader flow.Identifier)) *Consumer_OnCurrentViewDetails_Call { + _c.Run(run) + return _c } -// OnReceiveTc provides a mock function with given fields: currentView, tc -func (_m *Consumer) OnReceiveTc(currentView uint64, tc *flow.TimeoutCertificate) { - _m.Called(currentView, tc) +// OnDoubleProposeDetected provides a mock function for the type Consumer +func (_mock *Consumer) OnDoubleProposeDetected(block *model.Block, block1 *model.Block) { + _mock.Called(block, block1) + return } -// OnStart provides a mock function with given fields: currentView -func (_m *Consumer) OnStart(currentView uint64) { - _m.Called(currentView) +// Consumer_OnDoubleProposeDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDoubleProposeDetected' +type Consumer_OnDoubleProposeDetected_Call struct { + *mock.Call } -// OnStartingTimeout provides a mock function with given fields: _a0 -func (_m *Consumer) OnStartingTimeout(_a0 model.TimerInfo) { - _m.Called(_a0) +// OnDoubleProposeDetected is a helper method to define mock.On call +// - block *model.Block +// - block1 *model.Block +func (_e *Consumer_Expecter) OnDoubleProposeDetected(block interface{}, block1 interface{}) *Consumer_OnDoubleProposeDetected_Call { + return &Consumer_OnDoubleProposeDetected_Call{Call: _e.mock.On("OnDoubleProposeDetected", block, block1)} } -// OnTcTriggeredViewChange provides a mock function with given fields: oldView, newView, tc -func (_m *Consumer) OnTcTriggeredViewChange(oldView uint64, newView uint64, tc *flow.TimeoutCertificate) { - _m.Called(oldView, newView, tc) +func (_c *Consumer_OnDoubleProposeDetected_Call) Run(run func(block *model.Block, block1 *model.Block)) *Consumer_OnDoubleProposeDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + var arg1 *model.Block + if args[1] != nil { + arg1 = args[1].(*model.Block) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnViewChange provides a mock function with given fields: oldView, newView -func (_m *Consumer) OnViewChange(oldView uint64, newView uint64) { - _m.Called(oldView, newView) +func (_c *Consumer_OnDoubleProposeDetected_Call) Return() *Consumer_OnDoubleProposeDetected_Call { + _c.Call.Return() + return _c } -// NewConsumer creates a new instance of Consumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *Consumer { - mock := &Consumer{} - mock.Mock.Test(t) +func (_c *Consumer_OnDoubleProposeDetected_Call) RunAndReturn(run func(block *model.Block, block1 *model.Block)) *Consumer_OnDoubleProposeDetected_Call { + _c.Run(run) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnEventProcessed provides a mock function for the type Consumer +func (_mock *Consumer) OnEventProcessed() { + _mock.Called() + return +} - return mock +// Consumer_OnEventProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnEventProcessed' +type Consumer_OnEventProcessed_Call struct { + *mock.Call +} + +// OnEventProcessed is a helper method to define mock.On call +func (_e *Consumer_Expecter) OnEventProcessed() *Consumer_OnEventProcessed_Call { + return &Consumer_OnEventProcessed_Call{Call: _e.mock.On("OnEventProcessed")} +} + +func (_c *Consumer_OnEventProcessed_Call) Run(run func()) *Consumer_OnEventProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Consumer_OnEventProcessed_Call) Return() *Consumer_OnEventProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnEventProcessed_Call) RunAndReturn(run func()) *Consumer_OnEventProcessed_Call { + _c.Run(run) + return _c +} + +// OnFinalizedBlock provides a mock function for the type Consumer +func (_mock *Consumer) OnFinalizedBlock(block *model.Block) { + _mock.Called(block) + return +} + +// Consumer_OnFinalizedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFinalizedBlock' +type Consumer_OnFinalizedBlock_Call struct { + *mock.Call +} + +// OnFinalizedBlock is a helper method to define mock.On call +// - block *model.Block +func (_e *Consumer_Expecter) OnFinalizedBlock(block interface{}) *Consumer_OnFinalizedBlock_Call { + return &Consumer_OnFinalizedBlock_Call{Call: _e.mock.On("OnFinalizedBlock", block)} +} + +func (_c *Consumer_OnFinalizedBlock_Call) Run(run func(block *model.Block)) *Consumer_OnFinalizedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Consumer_OnFinalizedBlock_Call) Return() *Consumer_OnFinalizedBlock_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnFinalizedBlock_Call) RunAndReturn(run func(block *model.Block)) *Consumer_OnFinalizedBlock_Call { + _c.Run(run) + return _c +} + +// OnInvalidBlockDetected provides a mock function for the type Consumer +func (_mock *Consumer) OnInvalidBlockDetected(err flow.Slashable[model.InvalidProposalError]) { + _mock.Called(err) + return +} + +// Consumer_OnInvalidBlockDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidBlockDetected' +type Consumer_OnInvalidBlockDetected_Call struct { + *mock.Call +} + +// OnInvalidBlockDetected is a helper method to define mock.On call +// - err flow.Slashable[model.InvalidProposalError] +func (_e *Consumer_Expecter) OnInvalidBlockDetected(err interface{}) *Consumer_OnInvalidBlockDetected_Call { + return &Consumer_OnInvalidBlockDetected_Call{Call: _e.mock.On("OnInvalidBlockDetected", err)} +} + +func (_c *Consumer_OnInvalidBlockDetected_Call) Run(run func(err flow.Slashable[model.InvalidProposalError])) *Consumer_OnInvalidBlockDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[model.InvalidProposalError] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[model.InvalidProposalError]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Consumer_OnInvalidBlockDetected_Call) Return() *Consumer_OnInvalidBlockDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnInvalidBlockDetected_Call) RunAndReturn(run func(err flow.Slashable[model.InvalidProposalError])) *Consumer_OnInvalidBlockDetected_Call { + _c.Run(run) + return _c +} + +// OnLocalTimeout provides a mock function for the type Consumer +func (_mock *Consumer) OnLocalTimeout(currentView uint64) { + _mock.Called(currentView) + return +} + +// Consumer_OnLocalTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalTimeout' +type Consumer_OnLocalTimeout_Call struct { + *mock.Call +} + +// OnLocalTimeout is a helper method to define mock.On call +// - currentView uint64 +func (_e *Consumer_Expecter) OnLocalTimeout(currentView interface{}) *Consumer_OnLocalTimeout_Call { + return &Consumer_OnLocalTimeout_Call{Call: _e.mock.On("OnLocalTimeout", currentView)} +} + +func (_c *Consumer_OnLocalTimeout_Call) Run(run func(currentView uint64)) *Consumer_OnLocalTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Consumer_OnLocalTimeout_Call) Return() *Consumer_OnLocalTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnLocalTimeout_Call) RunAndReturn(run func(currentView uint64)) *Consumer_OnLocalTimeout_Call { + _c.Run(run) + return _c +} + +// OnOwnProposal provides a mock function for the type Consumer +func (_mock *Consumer) OnOwnProposal(proposal *flow.ProposalHeader, targetPublicationTime time.Time) { + _mock.Called(proposal, targetPublicationTime) + return +} + +// Consumer_OnOwnProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOwnProposal' +type Consumer_OnOwnProposal_Call struct { + *mock.Call +} + +// OnOwnProposal is a helper method to define mock.On call +// - proposal *flow.ProposalHeader +// - targetPublicationTime time.Time +func (_e *Consumer_Expecter) OnOwnProposal(proposal interface{}, targetPublicationTime interface{}) *Consumer_OnOwnProposal_Call { + return &Consumer_OnOwnProposal_Call{Call: _e.mock.On("OnOwnProposal", proposal, targetPublicationTime)} +} + +func (_c *Consumer_OnOwnProposal_Call) Run(run func(proposal *flow.ProposalHeader, targetPublicationTime time.Time)) *Consumer_OnOwnProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ProposalHeader + if args[0] != nil { + arg0 = args[0].(*flow.ProposalHeader) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_OnOwnProposal_Call) Return() *Consumer_OnOwnProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnOwnProposal_Call) RunAndReturn(run func(proposal *flow.ProposalHeader, targetPublicationTime time.Time)) *Consumer_OnOwnProposal_Call { + _c.Run(run) + return _c +} + +// OnOwnTimeout provides a mock function for the type Consumer +func (_mock *Consumer) OnOwnTimeout(timeout *model.TimeoutObject) { + _mock.Called(timeout) + return +} + +// Consumer_OnOwnTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOwnTimeout' +type Consumer_OnOwnTimeout_Call struct { + *mock.Call +} + +// OnOwnTimeout is a helper method to define mock.On call +// - timeout *model.TimeoutObject +func (_e *Consumer_Expecter) OnOwnTimeout(timeout interface{}) *Consumer_OnOwnTimeout_Call { + return &Consumer_OnOwnTimeout_Call{Call: _e.mock.On("OnOwnTimeout", timeout)} +} + +func (_c *Consumer_OnOwnTimeout_Call) Run(run func(timeout *model.TimeoutObject)) *Consumer_OnOwnTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Consumer_OnOwnTimeout_Call) Return() *Consumer_OnOwnTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnOwnTimeout_Call) RunAndReturn(run func(timeout *model.TimeoutObject)) *Consumer_OnOwnTimeout_Call { + _c.Run(run) + return _c +} + +// OnOwnVote provides a mock function for the type Consumer +func (_mock *Consumer) OnOwnVote(vote *model.Vote, recipientID flow.Identifier) { + _mock.Called(vote, recipientID) + return +} + +// Consumer_OnOwnVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOwnVote' +type Consumer_OnOwnVote_Call struct { + *mock.Call +} + +// OnOwnVote is a helper method to define mock.On call +// - vote *model.Vote +// - recipientID flow.Identifier +func (_e *Consumer_Expecter) OnOwnVote(vote interface{}, recipientID interface{}) *Consumer_OnOwnVote_Call { + return &Consumer_OnOwnVote_Call{Call: _e.mock.On("OnOwnVote", vote, recipientID)} +} + +func (_c *Consumer_OnOwnVote_Call) Run(run func(vote *model.Vote, recipientID flow.Identifier)) *Consumer_OnOwnVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_OnOwnVote_Call) Return() *Consumer_OnOwnVote_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnOwnVote_Call) RunAndReturn(run func(vote *model.Vote, recipientID flow.Identifier)) *Consumer_OnOwnVote_Call { + _c.Run(run) + return _c +} + +// OnPartialTc provides a mock function for the type Consumer +func (_mock *Consumer) OnPartialTc(currentView uint64, partialTc *hotstuff.PartialTcCreated) { + _mock.Called(currentView, partialTc) + return +} + +// Consumer_OnPartialTc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPartialTc' +type Consumer_OnPartialTc_Call struct { + *mock.Call +} + +// OnPartialTc is a helper method to define mock.On call +// - currentView uint64 +// - partialTc *hotstuff.PartialTcCreated +func (_e *Consumer_Expecter) OnPartialTc(currentView interface{}, partialTc interface{}) *Consumer_OnPartialTc_Call { + return &Consumer_OnPartialTc_Call{Call: _e.mock.On("OnPartialTc", currentView, partialTc)} +} + +func (_c *Consumer_OnPartialTc_Call) Run(run func(currentView uint64, partialTc *hotstuff.PartialTcCreated)) *Consumer_OnPartialTc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *hotstuff.PartialTcCreated + if args[1] != nil { + arg1 = args[1].(*hotstuff.PartialTcCreated) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_OnPartialTc_Call) Return() *Consumer_OnPartialTc_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnPartialTc_Call) RunAndReturn(run func(currentView uint64, partialTc *hotstuff.PartialTcCreated)) *Consumer_OnPartialTc_Call { + _c.Run(run) + return _c +} + +// OnQcTriggeredViewChange provides a mock function for the type Consumer +func (_mock *Consumer) OnQcTriggeredViewChange(oldView uint64, newView uint64, qc *flow.QuorumCertificate) { + _mock.Called(oldView, newView, qc) + return +} + +// Consumer_OnQcTriggeredViewChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnQcTriggeredViewChange' +type Consumer_OnQcTriggeredViewChange_Call struct { + *mock.Call +} + +// OnQcTriggeredViewChange is a helper method to define mock.On call +// - oldView uint64 +// - newView uint64 +// - qc *flow.QuorumCertificate +func (_e *Consumer_Expecter) OnQcTriggeredViewChange(oldView interface{}, newView interface{}, qc interface{}) *Consumer_OnQcTriggeredViewChange_Call { + return &Consumer_OnQcTriggeredViewChange_Call{Call: _e.mock.On("OnQcTriggeredViewChange", oldView, newView, qc)} +} + +func (_c *Consumer_OnQcTriggeredViewChange_Call) Run(run func(oldView uint64, newView uint64, qc *flow.QuorumCertificate)) *Consumer_OnQcTriggeredViewChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.QuorumCertificate + if args[2] != nil { + arg2 = args[2].(*flow.QuorumCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Consumer_OnQcTriggeredViewChange_Call) Return() *Consumer_OnQcTriggeredViewChange_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnQcTriggeredViewChange_Call) RunAndReturn(run func(oldView uint64, newView uint64, qc *flow.QuorumCertificate)) *Consumer_OnQcTriggeredViewChange_Call { + _c.Run(run) + return _c +} + +// OnReceiveProposal provides a mock function for the type Consumer +func (_mock *Consumer) OnReceiveProposal(currentView uint64, proposal *model.SignedProposal) { + _mock.Called(currentView, proposal) + return +} + +// Consumer_OnReceiveProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveProposal' +type Consumer_OnReceiveProposal_Call struct { + *mock.Call +} + +// OnReceiveProposal is a helper method to define mock.On call +// - currentView uint64 +// - proposal *model.SignedProposal +func (_e *Consumer_Expecter) OnReceiveProposal(currentView interface{}, proposal interface{}) *Consumer_OnReceiveProposal_Call { + return &Consumer_OnReceiveProposal_Call{Call: _e.mock.On("OnReceiveProposal", currentView, proposal)} +} + +func (_c *Consumer_OnReceiveProposal_Call) Run(run func(currentView uint64, proposal *model.SignedProposal)) *Consumer_OnReceiveProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *model.SignedProposal + if args[1] != nil { + arg1 = args[1].(*model.SignedProposal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_OnReceiveProposal_Call) Return() *Consumer_OnReceiveProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnReceiveProposal_Call) RunAndReturn(run func(currentView uint64, proposal *model.SignedProposal)) *Consumer_OnReceiveProposal_Call { + _c.Run(run) + return _c +} + +// OnReceiveQc provides a mock function for the type Consumer +func (_mock *Consumer) OnReceiveQc(currentView uint64, qc *flow.QuorumCertificate) { + _mock.Called(currentView, qc) + return +} + +// Consumer_OnReceiveQc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveQc' +type Consumer_OnReceiveQc_Call struct { + *mock.Call +} + +// OnReceiveQc is a helper method to define mock.On call +// - currentView uint64 +// - qc *flow.QuorumCertificate +func (_e *Consumer_Expecter) OnReceiveQc(currentView interface{}, qc interface{}) *Consumer_OnReceiveQc_Call { + return &Consumer_OnReceiveQc_Call{Call: _e.mock.On("OnReceiveQc", currentView, qc)} +} + +func (_c *Consumer_OnReceiveQc_Call) Run(run func(currentView uint64, qc *flow.QuorumCertificate)) *Consumer_OnReceiveQc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_OnReceiveQc_Call) Return() *Consumer_OnReceiveQc_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnReceiveQc_Call) RunAndReturn(run func(currentView uint64, qc *flow.QuorumCertificate)) *Consumer_OnReceiveQc_Call { + _c.Run(run) + return _c +} + +// OnReceiveTc provides a mock function for the type Consumer +func (_mock *Consumer) OnReceiveTc(currentView uint64, tc *flow.TimeoutCertificate) { + _mock.Called(currentView, tc) + return +} + +// Consumer_OnReceiveTc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveTc' +type Consumer_OnReceiveTc_Call struct { + *mock.Call +} + +// OnReceiveTc is a helper method to define mock.On call +// - currentView uint64 +// - tc *flow.TimeoutCertificate +func (_e *Consumer_Expecter) OnReceiveTc(currentView interface{}, tc interface{}) *Consumer_OnReceiveTc_Call { + return &Consumer_OnReceiveTc_Call{Call: _e.mock.On("OnReceiveTc", currentView, tc)} +} + +func (_c *Consumer_OnReceiveTc_Call) Run(run func(currentView uint64, tc *flow.TimeoutCertificate)) *Consumer_OnReceiveTc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.TimeoutCertificate + if args[1] != nil { + arg1 = args[1].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_OnReceiveTc_Call) Return() *Consumer_OnReceiveTc_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnReceiveTc_Call) RunAndReturn(run func(currentView uint64, tc *flow.TimeoutCertificate)) *Consumer_OnReceiveTc_Call { + _c.Run(run) + return _c +} + +// OnStart provides a mock function for the type Consumer +func (_mock *Consumer) OnStart(currentView uint64) { + _mock.Called(currentView) + return +} + +// Consumer_OnStart_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStart' +type Consumer_OnStart_Call struct { + *mock.Call +} + +// OnStart is a helper method to define mock.On call +// - currentView uint64 +func (_e *Consumer_Expecter) OnStart(currentView interface{}) *Consumer_OnStart_Call { + return &Consumer_OnStart_Call{Call: _e.mock.On("OnStart", currentView)} +} + +func (_c *Consumer_OnStart_Call) Run(run func(currentView uint64)) *Consumer_OnStart_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Consumer_OnStart_Call) Return() *Consumer_OnStart_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnStart_Call) RunAndReturn(run func(currentView uint64)) *Consumer_OnStart_Call { + _c.Run(run) + return _c +} + +// OnStartingTimeout provides a mock function for the type Consumer +func (_mock *Consumer) OnStartingTimeout(timerInfo model.TimerInfo) { + _mock.Called(timerInfo) + return +} + +// Consumer_OnStartingTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStartingTimeout' +type Consumer_OnStartingTimeout_Call struct { + *mock.Call +} + +// OnStartingTimeout is a helper method to define mock.On call +// - timerInfo model.TimerInfo +func (_e *Consumer_Expecter) OnStartingTimeout(timerInfo interface{}) *Consumer_OnStartingTimeout_Call { + return &Consumer_OnStartingTimeout_Call{Call: _e.mock.On("OnStartingTimeout", timerInfo)} +} + +func (_c *Consumer_OnStartingTimeout_Call) Run(run func(timerInfo model.TimerInfo)) *Consumer_OnStartingTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 model.TimerInfo + if args[0] != nil { + arg0 = args[0].(model.TimerInfo) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Consumer_OnStartingTimeout_Call) Return() *Consumer_OnStartingTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnStartingTimeout_Call) RunAndReturn(run func(timerInfo model.TimerInfo)) *Consumer_OnStartingTimeout_Call { + _c.Run(run) + return _c +} + +// OnTcTriggeredViewChange provides a mock function for the type Consumer +func (_mock *Consumer) OnTcTriggeredViewChange(oldView uint64, newView uint64, tc *flow.TimeoutCertificate) { + _mock.Called(oldView, newView, tc) + return +} + +// Consumer_OnTcTriggeredViewChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTcTriggeredViewChange' +type Consumer_OnTcTriggeredViewChange_Call struct { + *mock.Call +} + +// OnTcTriggeredViewChange is a helper method to define mock.On call +// - oldView uint64 +// - newView uint64 +// - tc *flow.TimeoutCertificate +func (_e *Consumer_Expecter) OnTcTriggeredViewChange(oldView interface{}, newView interface{}, tc interface{}) *Consumer_OnTcTriggeredViewChange_Call { + return &Consumer_OnTcTriggeredViewChange_Call{Call: _e.mock.On("OnTcTriggeredViewChange", oldView, newView, tc)} +} + +func (_c *Consumer_OnTcTriggeredViewChange_Call) Run(run func(oldView uint64, newView uint64, tc *flow.TimeoutCertificate)) *Consumer_OnTcTriggeredViewChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Consumer_OnTcTriggeredViewChange_Call) Return() *Consumer_OnTcTriggeredViewChange_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnTcTriggeredViewChange_Call) RunAndReturn(run func(oldView uint64, newView uint64, tc *flow.TimeoutCertificate)) *Consumer_OnTcTriggeredViewChange_Call { + _c.Run(run) + return _c +} + +// OnViewChange provides a mock function for the type Consumer +func (_mock *Consumer) OnViewChange(oldView uint64, newView uint64) { + _mock.Called(oldView, newView) + return +} + +// Consumer_OnViewChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnViewChange' +type Consumer_OnViewChange_Call struct { + *mock.Call +} + +// OnViewChange is a helper method to define mock.On call +// - oldView uint64 +// - newView uint64 +func (_e *Consumer_Expecter) OnViewChange(oldView interface{}, newView interface{}) *Consumer_OnViewChange_Call { + return &Consumer_OnViewChange_Call{Call: _e.mock.On("OnViewChange", oldView, newView)} +} + +func (_c *Consumer_OnViewChange_Call) Run(run func(oldView uint64, newView uint64)) *Consumer_OnViewChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_OnViewChange_Call) Return() *Consumer_OnViewChange_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_OnViewChange_Call) RunAndReturn(run func(oldView uint64, newView uint64)) *Consumer_OnViewChange_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/dkg.go b/consensus/hotstuff/mocks/dkg.go index e39fc77f1c1..036ffbd0508 100644 --- a/consensus/hotstuff/mocks/dkg.go +++ b/consensus/hotstuff/mocks/dkg.go @@ -1,42 +1,91 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewDKG creates a new instance of DKG. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKG(t interface { + mock.TestingT + Cleanup(func()) +}) *DKG { + mock := &DKG{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKG is an autogenerated mock type for the DKG type type DKG struct { mock.Mock } -// GroupKey provides a mock function with no fields -func (_m *DKG) GroupKey() crypto.PublicKey { - ret := _m.Called() +type DKG_Expecter struct { + mock *mock.Mock +} + +func (_m *DKG) EXPECT() *DKG_Expecter { + return &DKG_Expecter{mock: &_m.Mock} +} + +// GroupKey provides a mock function for the type DKG +func (_mock *DKG) GroupKey() crypto.PublicKey { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GroupKey") } var r0 crypto.PublicKey - if rf, ok := ret.Get(0).(func() crypto.PublicKey); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() crypto.PublicKey); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PublicKey) } } - return r0 } -// Index provides a mock function with given fields: nodeID -func (_m *DKG) Index(nodeID flow.Identifier) (uint, error) { - ret := _m.Called(nodeID) +// DKG_GroupKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GroupKey' +type DKG_GroupKey_Call struct { + *mock.Call +} + +// GroupKey is a helper method to define mock.On call +func (_e *DKG_Expecter) GroupKey() *DKG_GroupKey_Call { + return &DKG_GroupKey_Call{Call: _e.mock.On("GroupKey")} +} + +func (_c *DKG_GroupKey_Call) Run(run func()) *DKG_GroupKey_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKG_GroupKey_Call) Return(publicKey crypto.PublicKey) *DKG_GroupKey_Call { + _c.Call.Return(publicKey) + return _c +} + +func (_c *DKG_GroupKey_Call) RunAndReturn(run func() crypto.PublicKey) *DKG_GroupKey_Call { + _c.Call.Return(run) + return _c +} + +// Index provides a mock function for the type DKG +func (_mock *DKG) Index(nodeID flow.Identifier) (uint, error) { + ret := _mock.Called(nodeID) if len(ret) == 0 { panic("no return value specified for Index") @@ -44,27 +93,59 @@ func (_m *DKG) Index(nodeID flow.Identifier) (uint, error) { var r0 uint var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (uint, error)); ok { - return rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (uint, error)); ok { + return returnFunc(nodeID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) uint); ok { - r0 = rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) uint); ok { + r0 = returnFunc(nodeID) } else { r0 = ret.Get(0).(uint) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(nodeID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(nodeID) } else { r1 = ret.Error(1) } - return r0, r1 } -// KeyShare provides a mock function with given fields: nodeID -func (_m *DKG) KeyShare(nodeID flow.Identifier) (crypto.PublicKey, error) { - ret := _m.Called(nodeID) +// DKG_Index_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Index' +type DKG_Index_Call struct { + *mock.Call +} + +// Index is a helper method to define mock.On call +// - nodeID flow.Identifier +func (_e *DKG_Expecter) Index(nodeID interface{}) *DKG_Index_Call { + return &DKG_Index_Call{Call: _e.mock.On("Index", nodeID)} +} + +func (_c *DKG_Index_Call) Run(run func(nodeID flow.Identifier)) *DKG_Index_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKG_Index_Call) Return(v uint, err error) *DKG_Index_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *DKG_Index_Call) RunAndReturn(run func(nodeID flow.Identifier) (uint, error)) *DKG_Index_Call { + _c.Call.Return(run) + return _c +} + +// KeyShare provides a mock function for the type DKG +func (_mock *DKG) KeyShare(nodeID flow.Identifier) (crypto.PublicKey, error) { + ret := _mock.Called(nodeID) if len(ret) == 0 { panic("no return value specified for KeyShare") @@ -72,49 +153,107 @@ func (_m *DKG) KeyShare(nodeID flow.Identifier) (crypto.PublicKey, error) { var r0 crypto.PublicKey var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (crypto.PublicKey, error)); ok { - return rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (crypto.PublicKey, error)); ok { + return returnFunc(nodeID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) crypto.PublicKey); ok { - r0 = rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) crypto.PublicKey); ok { + r0 = returnFunc(nodeID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PublicKey) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(nodeID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(nodeID) } else { r1 = ret.Error(1) } - return r0, r1 } -// KeyShares provides a mock function with no fields -func (_m *DKG) KeyShares() []crypto.PublicKey { - ret := _m.Called() +// DKG_KeyShare_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'KeyShare' +type DKG_KeyShare_Call struct { + *mock.Call +} + +// KeyShare is a helper method to define mock.On call +// - nodeID flow.Identifier +func (_e *DKG_Expecter) KeyShare(nodeID interface{}) *DKG_KeyShare_Call { + return &DKG_KeyShare_Call{Call: _e.mock.On("KeyShare", nodeID)} +} + +func (_c *DKG_KeyShare_Call) Run(run func(nodeID flow.Identifier)) *DKG_KeyShare_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKG_KeyShare_Call) Return(publicKey crypto.PublicKey, err error) *DKG_KeyShare_Call { + _c.Call.Return(publicKey, err) + return _c +} + +func (_c *DKG_KeyShare_Call) RunAndReturn(run func(nodeID flow.Identifier) (crypto.PublicKey, error)) *DKG_KeyShare_Call { + _c.Call.Return(run) + return _c +} + +// KeyShares provides a mock function for the type DKG +func (_mock *DKG) KeyShares() []crypto.PublicKey { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for KeyShares") } var r0 []crypto.PublicKey - if rf, ok := ret.Get(0).(func() []crypto.PublicKey); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []crypto.PublicKey); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]crypto.PublicKey) } } - return r0 } -// NodeID provides a mock function with given fields: index -func (_m *DKG) NodeID(index uint) (flow.Identifier, error) { - ret := _m.Called(index) +// DKG_KeyShares_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'KeyShares' +type DKG_KeyShares_Call struct { + *mock.Call +} + +// KeyShares is a helper method to define mock.On call +func (_e *DKG_Expecter) KeyShares() *DKG_KeyShares_Call { + return &DKG_KeyShares_Call{Call: _e.mock.On("KeyShares")} +} + +func (_c *DKG_KeyShares_Call) Run(run func()) *DKG_KeyShares_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKG_KeyShares_Call) Return(publicKeys []crypto.PublicKey) *DKG_KeyShares_Call { + _c.Call.Return(publicKeys) + return _c +} + +func (_c *DKG_KeyShares_Call) RunAndReturn(run func() []crypto.PublicKey) *DKG_KeyShares_Call { + _c.Call.Return(run) + return _c +} + +// NodeID provides a mock function for the type DKG +func (_mock *DKG) NodeID(index uint) (flow.Identifier, error) { + ret := _mock.Called(index) if len(ret) == 0 { panic("no return value specified for NodeID") @@ -122,54 +261,98 @@ func (_m *DKG) NodeID(index uint) (flow.Identifier, error) { var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint) (flow.Identifier, error)); ok { - return rf(index) + if returnFunc, ok := ret.Get(0).(func(uint) (flow.Identifier, error)); ok { + return returnFunc(index) } - if rf, ok := ret.Get(0).(func(uint) flow.Identifier); ok { - r0 = rf(index) + if returnFunc, ok := ret.Get(0).(func(uint) flow.Identifier); ok { + r0 = returnFunc(index) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint) error); ok { - r1 = rf(index) + if returnFunc, ok := ret.Get(1).(func(uint) error); ok { + r1 = returnFunc(index) } else { r1 = ret.Error(1) } - return r0, r1 } -// Size provides a mock function with no fields -func (_m *DKG) Size() uint { - ret := _m.Called() +// DKG_NodeID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NodeID' +type DKG_NodeID_Call struct { + *mock.Call +} + +// NodeID is a helper method to define mock.On call +// - index uint +func (_e *DKG_Expecter) NodeID(index interface{}) *DKG_NodeID_Call { + return &DKG_NodeID_Call{Call: _e.mock.On("NodeID", index)} +} + +func (_c *DKG_NodeID_Call) Run(run func(index uint)) *DKG_NodeID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKG_NodeID_Call) Return(identifier flow.Identifier, err error) *DKG_NodeID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *DKG_NodeID_Call) RunAndReturn(run func(index uint) (flow.Identifier, error)) *DKG_NodeID_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type DKG +func (_mock *DKG) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewDKG creates a new instance of DKG. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKG(t interface { - mock.TestingT - Cleanup(func()) -}) *DKG { - mock := &DKG{} - mock.Mock.Test(t) +// DKG_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type DKG_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *DKG_Expecter) Size() *DKG_Size_Call { + return &DKG_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *DKG_Size_Call) Run(run func()) *DKG_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKG_Size_Call) Return(v uint) *DKG_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *DKG_Size_Call) RunAndReturn(run func() uint) *DKG_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/dynamic_committee.go b/consensus/hotstuff/mocks/dynamic_committee.go index c2cb50f7da1..727f7717ddf 100644 --- a/consensus/hotstuff/mocks/dynamic_committee.go +++ b/consensus/hotstuff/mocks/dynamic_committee.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewDynamicCommittee creates a new instance of DynamicCommittee. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDynamicCommittee(t interface { + mock.TestingT + Cleanup(func()) +}) *DynamicCommittee { + mock := &DynamicCommittee{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DynamicCommittee is an autogenerated mock type for the DynamicCommittee type type DynamicCommittee struct { mock.Mock } -// DKG provides a mock function with given fields: view -func (_m *DynamicCommittee) DKG(view uint64) (hotstuff.DKG, error) { - ret := _m.Called(view) +type DynamicCommittee_Expecter struct { + mock *mock.Mock +} + +func (_m *DynamicCommittee) EXPECT() *DynamicCommittee_Expecter { + return &DynamicCommittee_Expecter{mock: &_m.Mock} +} + +// DKG provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) DKG(view uint64) (hotstuff.DKG, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for DKG") @@ -24,29 +47,61 @@ func (_m *DynamicCommittee) DKG(view uint64) (hotstuff.DKG, error) { var r0 hotstuff.DKG var r1 error - if rf, ok := ret.Get(0).(func(uint64) (hotstuff.DKG, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (hotstuff.DKG, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) hotstuff.DKG); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) hotstuff.DKG); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(hotstuff.DKG) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// IdentitiesByBlock provides a mock function with given fields: blockID -func (_m *DynamicCommittee) IdentitiesByBlock(blockID flow.Identifier) (flow.IdentityList, error) { - ret := _m.Called(blockID) +// DynamicCommittee_DKG_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DKG' +type DynamicCommittee_DKG_Call struct { + *mock.Call +} + +// DKG is a helper method to define mock.On call +// - view uint64 +func (_e *DynamicCommittee_Expecter) DKG(view interface{}) *DynamicCommittee_DKG_Call { + return &DynamicCommittee_DKG_Call{Call: _e.mock.On("DKG", view)} +} + +func (_c *DynamicCommittee_DKG_Call) Run(run func(view uint64)) *DynamicCommittee_DKG_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DynamicCommittee_DKG_Call) Return(dKG hotstuff.DKG, err error) *DynamicCommittee_DKG_Call { + _c.Call.Return(dKG, err) + return _c +} + +func (_c *DynamicCommittee_DKG_Call) RunAndReturn(run func(view uint64) (hotstuff.DKG, error)) *DynamicCommittee_DKG_Call { + _c.Call.Return(run) + return _c +} + +// IdentitiesByBlock provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) IdentitiesByBlock(blockID flow.Identifier) (flow.IdentityList, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for IdentitiesByBlock") @@ -54,29 +109,61 @@ func (_m *DynamicCommittee) IdentitiesByBlock(blockID flow.Identifier) (flow.Ide var r0 flow.IdentityList var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.IdentityList, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.IdentityList, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.IdentityList); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.IdentityList); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentityList) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// IdentitiesByEpoch provides a mock function with given fields: view -func (_m *DynamicCommittee) IdentitiesByEpoch(view uint64) (flow.IdentitySkeletonList, error) { - ret := _m.Called(view) +// DynamicCommittee_IdentitiesByBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IdentitiesByBlock' +type DynamicCommittee_IdentitiesByBlock_Call struct { + *mock.Call +} + +// IdentitiesByBlock is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *DynamicCommittee_Expecter) IdentitiesByBlock(blockID interface{}) *DynamicCommittee_IdentitiesByBlock_Call { + return &DynamicCommittee_IdentitiesByBlock_Call{Call: _e.mock.On("IdentitiesByBlock", blockID)} +} + +func (_c *DynamicCommittee_IdentitiesByBlock_Call) Run(run func(blockID flow.Identifier)) *DynamicCommittee_IdentitiesByBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DynamicCommittee_IdentitiesByBlock_Call) Return(v flow.IdentityList, err error) *DynamicCommittee_IdentitiesByBlock_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *DynamicCommittee_IdentitiesByBlock_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.IdentityList, error)) *DynamicCommittee_IdentitiesByBlock_Call { + _c.Call.Return(run) + return _c +} + +// IdentitiesByEpoch provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) IdentitiesByEpoch(view uint64) (flow.IdentitySkeletonList, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for IdentitiesByEpoch") @@ -84,29 +171,61 @@ func (_m *DynamicCommittee) IdentitiesByEpoch(view uint64) (flow.IdentitySkeleto var r0 flow.IdentitySkeletonList var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.IdentitySkeletonList, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.IdentitySkeletonList, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) flow.IdentitySkeletonList); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.IdentitySkeletonList); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentitySkeletonList) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// IdentityByBlock provides a mock function with given fields: blockID, participantID -func (_m *DynamicCommittee) IdentityByBlock(blockID flow.Identifier, participantID flow.Identifier) (*flow.Identity, error) { - ret := _m.Called(blockID, participantID) +// DynamicCommittee_IdentitiesByEpoch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IdentitiesByEpoch' +type DynamicCommittee_IdentitiesByEpoch_Call struct { + *mock.Call +} + +// IdentitiesByEpoch is a helper method to define mock.On call +// - view uint64 +func (_e *DynamicCommittee_Expecter) IdentitiesByEpoch(view interface{}) *DynamicCommittee_IdentitiesByEpoch_Call { + return &DynamicCommittee_IdentitiesByEpoch_Call{Call: _e.mock.On("IdentitiesByEpoch", view)} +} + +func (_c *DynamicCommittee_IdentitiesByEpoch_Call) Run(run func(view uint64)) *DynamicCommittee_IdentitiesByEpoch_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DynamicCommittee_IdentitiesByEpoch_Call) Return(v flow.IdentitySkeletonList, err error) *DynamicCommittee_IdentitiesByEpoch_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *DynamicCommittee_IdentitiesByEpoch_Call) RunAndReturn(run func(view uint64) (flow.IdentitySkeletonList, error)) *DynamicCommittee_IdentitiesByEpoch_Call { + _c.Call.Return(run) + return _c +} + +// IdentityByBlock provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) IdentityByBlock(blockID flow.Identifier, participantID flow.Identifier) (*flow.Identity, error) { + ret := _mock.Called(blockID, participantID) if len(ret) == 0 { panic("no return value specified for IdentityByBlock") @@ -114,29 +233,67 @@ func (_m *DynamicCommittee) IdentityByBlock(blockID flow.Identifier, participant var r0 *flow.Identity var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.Identity, error)); ok { - return rf(blockID, participantID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.Identity, error)); ok { + return returnFunc(blockID, participantID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.Identity); ok { - r0 = rf(blockID, participantID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.Identity); ok { + r0 = returnFunc(blockID, participantID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Identity) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, participantID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, participantID) } else { r1 = ret.Error(1) } - return r0, r1 } -// IdentityByEpoch provides a mock function with given fields: view, participantID -func (_m *DynamicCommittee) IdentityByEpoch(view uint64, participantID flow.Identifier) (*flow.IdentitySkeleton, error) { - ret := _m.Called(view, participantID) +// DynamicCommittee_IdentityByBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IdentityByBlock' +type DynamicCommittee_IdentityByBlock_Call struct { + *mock.Call +} + +// IdentityByBlock is a helper method to define mock.On call +// - blockID flow.Identifier +// - participantID flow.Identifier +func (_e *DynamicCommittee_Expecter) IdentityByBlock(blockID interface{}, participantID interface{}) *DynamicCommittee_IdentityByBlock_Call { + return &DynamicCommittee_IdentityByBlock_Call{Call: _e.mock.On("IdentityByBlock", blockID, participantID)} +} + +func (_c *DynamicCommittee_IdentityByBlock_Call) Run(run func(blockID flow.Identifier, participantID flow.Identifier)) *DynamicCommittee_IdentityByBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DynamicCommittee_IdentityByBlock_Call) Return(identity *flow.Identity, err error) *DynamicCommittee_IdentityByBlock_Call { + _c.Call.Return(identity, err) + return _c +} + +func (_c *DynamicCommittee_IdentityByBlock_Call) RunAndReturn(run func(blockID flow.Identifier, participantID flow.Identifier) (*flow.Identity, error)) *DynamicCommittee_IdentityByBlock_Call { + _c.Call.Return(run) + return _c +} + +// IdentityByEpoch provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) IdentityByEpoch(view uint64, participantID flow.Identifier) (*flow.IdentitySkeleton, error) { + ret := _mock.Called(view, participantID) if len(ret) == 0 { panic("no return value specified for IdentityByEpoch") @@ -144,29 +301,67 @@ func (_m *DynamicCommittee) IdentityByEpoch(view uint64, participantID flow.Iden var r0 *flow.IdentitySkeleton var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (*flow.IdentitySkeleton, error)); ok { - return rf(view, participantID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (*flow.IdentitySkeleton, error)); ok { + return returnFunc(view, participantID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) *flow.IdentitySkeleton); ok { - r0 = rf(view, participantID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) *flow.IdentitySkeleton); ok { + r0 = returnFunc(view, participantID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.IdentitySkeleton) } } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(view, participantID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(view, participantID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LeaderForView provides a mock function with given fields: view -func (_m *DynamicCommittee) LeaderForView(view uint64) (flow.Identifier, error) { - ret := _m.Called(view) +// DynamicCommittee_IdentityByEpoch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IdentityByEpoch' +type DynamicCommittee_IdentityByEpoch_Call struct { + *mock.Call +} + +// IdentityByEpoch is a helper method to define mock.On call +// - view uint64 +// - participantID flow.Identifier +func (_e *DynamicCommittee_Expecter) IdentityByEpoch(view interface{}, participantID interface{}) *DynamicCommittee_IdentityByEpoch_Call { + return &DynamicCommittee_IdentityByEpoch_Call{Call: _e.mock.On("IdentityByEpoch", view, participantID)} +} + +func (_c *DynamicCommittee_IdentityByEpoch_Call) Run(run func(view uint64, participantID flow.Identifier)) *DynamicCommittee_IdentityByEpoch_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DynamicCommittee_IdentityByEpoch_Call) Return(identitySkeleton *flow.IdentitySkeleton, err error) *DynamicCommittee_IdentityByEpoch_Call { + _c.Call.Return(identitySkeleton, err) + return _c +} + +func (_c *DynamicCommittee_IdentityByEpoch_Call) RunAndReturn(run func(view uint64, participantID flow.Identifier) (*flow.IdentitySkeleton, error)) *DynamicCommittee_IdentityByEpoch_Call { + _c.Call.Return(run) + return _c +} + +// LeaderForView provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) LeaderForView(view uint64) (flow.Identifier, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for LeaderForView") @@ -174,29 +369,61 @@ func (_m *DynamicCommittee) LeaderForView(view uint64) (flow.Identifier, error) var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// QuorumThresholdForView provides a mock function with given fields: view -func (_m *DynamicCommittee) QuorumThresholdForView(view uint64) (uint64, error) { - ret := _m.Called(view) +// DynamicCommittee_LeaderForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LeaderForView' +type DynamicCommittee_LeaderForView_Call struct { + *mock.Call +} + +// LeaderForView is a helper method to define mock.On call +// - view uint64 +func (_e *DynamicCommittee_Expecter) LeaderForView(view interface{}) *DynamicCommittee_LeaderForView_Call { + return &DynamicCommittee_LeaderForView_Call{Call: _e.mock.On("LeaderForView", view)} +} + +func (_c *DynamicCommittee_LeaderForView_Call) Run(run func(view uint64)) *DynamicCommittee_LeaderForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DynamicCommittee_LeaderForView_Call) Return(identifier flow.Identifier, err error) *DynamicCommittee_LeaderForView_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *DynamicCommittee_LeaderForView_Call) RunAndReturn(run func(view uint64) (flow.Identifier, error)) *DynamicCommittee_LeaderForView_Call { + _c.Call.Return(run) + return _c +} + +// QuorumThresholdForView provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) QuorumThresholdForView(view uint64) (uint64, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for QuorumThresholdForView") @@ -204,47 +431,105 @@ func (_m *DynamicCommittee) QuorumThresholdForView(view uint64) (uint64, error) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(view) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// Self provides a mock function with no fields -func (_m *DynamicCommittee) Self() flow.Identifier { - ret := _m.Called() +// DynamicCommittee_QuorumThresholdForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QuorumThresholdForView' +type DynamicCommittee_QuorumThresholdForView_Call struct { + *mock.Call +} + +// QuorumThresholdForView is a helper method to define mock.On call +// - view uint64 +func (_e *DynamicCommittee_Expecter) QuorumThresholdForView(view interface{}) *DynamicCommittee_QuorumThresholdForView_Call { + return &DynamicCommittee_QuorumThresholdForView_Call{Call: _e.mock.On("QuorumThresholdForView", view)} +} + +func (_c *DynamicCommittee_QuorumThresholdForView_Call) Run(run func(view uint64)) *DynamicCommittee_QuorumThresholdForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DynamicCommittee_QuorumThresholdForView_Call) Return(v uint64, err error) *DynamicCommittee_QuorumThresholdForView_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *DynamicCommittee_QuorumThresholdForView_Call) RunAndReturn(run func(view uint64) (uint64, error)) *DynamicCommittee_QuorumThresholdForView_Call { + _c.Call.Return(run) + return _c +} + +// Self provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) Self() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Self") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// TimeoutThresholdForView provides a mock function with given fields: view -func (_m *DynamicCommittee) TimeoutThresholdForView(view uint64) (uint64, error) { - ret := _m.Called(view) +// DynamicCommittee_Self_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Self' +type DynamicCommittee_Self_Call struct { + *mock.Call +} + +// Self is a helper method to define mock.On call +func (_e *DynamicCommittee_Expecter) Self() *DynamicCommittee_Self_Call { + return &DynamicCommittee_Self_Call{Call: _e.mock.On("Self")} +} + +func (_c *DynamicCommittee_Self_Call) Run(run func()) *DynamicCommittee_Self_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DynamicCommittee_Self_Call) Return(identifier flow.Identifier) *DynamicCommittee_Self_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *DynamicCommittee_Self_Call) RunAndReturn(run func() flow.Identifier) *DynamicCommittee_Self_Call { + _c.Call.Return(run) + return _c +} + +// TimeoutThresholdForView provides a mock function for the type DynamicCommittee +func (_mock *DynamicCommittee) TimeoutThresholdForView(view uint64) (uint64, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for TimeoutThresholdForView") @@ -252,34 +537,52 @@ func (_m *DynamicCommittee) TimeoutThresholdForView(view uint64) (uint64, error) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(view) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewDynamicCommittee creates a new instance of DynamicCommittee. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDynamicCommittee(t interface { - mock.TestingT - Cleanup(func()) -}) *DynamicCommittee { - mock := &DynamicCommittee{} - mock.Mock.Test(t) +// DynamicCommittee_TimeoutThresholdForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TimeoutThresholdForView' +type DynamicCommittee_TimeoutThresholdForView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TimeoutThresholdForView is a helper method to define mock.On call +// - view uint64 +func (_e *DynamicCommittee_Expecter) TimeoutThresholdForView(view interface{}) *DynamicCommittee_TimeoutThresholdForView_Call { + return &DynamicCommittee_TimeoutThresholdForView_Call{Call: _e.mock.On("TimeoutThresholdForView", view)} +} - return mock +func (_c *DynamicCommittee_TimeoutThresholdForView_Call) Run(run func(view uint64)) *DynamicCommittee_TimeoutThresholdForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DynamicCommittee_TimeoutThresholdForView_Call) Return(v uint64, err error) *DynamicCommittee_TimeoutThresholdForView_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *DynamicCommittee_TimeoutThresholdForView_Call) RunAndReturn(run func(view uint64) (uint64, error)) *DynamicCommittee_TimeoutThresholdForView_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/event_handler.go b/consensus/hotstuff/mocks/event_handler.go index 2784ff3628a..604be065174 100644 --- a/consensus/hotstuff/mocks/event_handler.go +++ b/consensus/hotstuff/mocks/event_handler.go @@ -1,163 +1,387 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - context "context" - - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - flow "github.com/onflow/flow-go/model/flow" + "context" + "time" + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" +) - model "github.com/onflow/flow-go/consensus/hotstuff/model" +// NewEventHandler creates a new instance of EventHandler. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEventHandler(t interface { + mock.TestingT + Cleanup(func()) +}) *EventHandler { + mock := &EventHandler{} + mock.Mock.Test(t) - time "time" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EventHandler is an autogenerated mock type for the EventHandler type type EventHandler struct { mock.Mock } -// OnLocalTimeout provides a mock function with no fields -func (_m *EventHandler) OnLocalTimeout() error { - ret := _m.Called() +type EventHandler_Expecter struct { + mock *mock.Mock +} + +func (_m *EventHandler) EXPECT() *EventHandler_Expecter { + return &EventHandler_Expecter{mock: &_m.Mock} +} + +// OnLocalTimeout provides a mock function for the type EventHandler +func (_mock *EventHandler) OnLocalTimeout() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for OnLocalTimeout") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// OnPartialTcCreated provides a mock function with given fields: partialTC -func (_m *EventHandler) OnPartialTcCreated(partialTC *hotstuff.PartialTcCreated) error { - ret := _m.Called(partialTC) +// EventHandler_OnLocalTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalTimeout' +type EventHandler_OnLocalTimeout_Call struct { + *mock.Call +} + +// OnLocalTimeout is a helper method to define mock.On call +func (_e *EventHandler_Expecter) OnLocalTimeout() *EventHandler_OnLocalTimeout_Call { + return &EventHandler_OnLocalTimeout_Call{Call: _e.mock.On("OnLocalTimeout")} +} + +func (_c *EventHandler_OnLocalTimeout_Call) Run(run func()) *EventHandler_OnLocalTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EventHandler_OnLocalTimeout_Call) Return(err error) *EventHandler_OnLocalTimeout_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EventHandler_OnLocalTimeout_Call) RunAndReturn(run func() error) *EventHandler_OnLocalTimeout_Call { + _c.Call.Return(run) + return _c +} + +// OnPartialTcCreated provides a mock function for the type EventHandler +func (_mock *EventHandler) OnPartialTcCreated(partialTC *hotstuff.PartialTcCreated) error { + ret := _mock.Called(partialTC) if len(ret) == 0 { panic("no return value specified for OnPartialTcCreated") } var r0 error - if rf, ok := ret.Get(0).(func(*hotstuff.PartialTcCreated) error); ok { - r0 = rf(partialTC) + if returnFunc, ok := ret.Get(0).(func(*hotstuff.PartialTcCreated) error); ok { + r0 = returnFunc(partialTC) } else { r0 = ret.Error(0) } - return r0 } -// OnReceiveProposal provides a mock function with given fields: proposal -func (_m *EventHandler) OnReceiveProposal(proposal *model.SignedProposal) error { - ret := _m.Called(proposal) +// EventHandler_OnPartialTcCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPartialTcCreated' +type EventHandler_OnPartialTcCreated_Call struct { + *mock.Call +} + +// OnPartialTcCreated is a helper method to define mock.On call +// - partialTC *hotstuff.PartialTcCreated +func (_e *EventHandler_Expecter) OnPartialTcCreated(partialTC interface{}) *EventHandler_OnPartialTcCreated_Call { + return &EventHandler_OnPartialTcCreated_Call{Call: _e.mock.On("OnPartialTcCreated", partialTC)} +} + +func (_c *EventHandler_OnPartialTcCreated_Call) Run(run func(partialTC *hotstuff.PartialTcCreated)) *EventHandler_OnPartialTcCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *hotstuff.PartialTcCreated + if args[0] != nil { + arg0 = args[0].(*hotstuff.PartialTcCreated) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventHandler_OnPartialTcCreated_Call) Return(err error) *EventHandler_OnPartialTcCreated_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EventHandler_OnPartialTcCreated_Call) RunAndReturn(run func(partialTC *hotstuff.PartialTcCreated) error) *EventHandler_OnPartialTcCreated_Call { + _c.Call.Return(run) + return _c +} + +// OnReceiveProposal provides a mock function for the type EventHandler +func (_mock *EventHandler) OnReceiveProposal(proposal *model.SignedProposal) error { + ret := _mock.Called(proposal) if len(ret) == 0 { panic("no return value specified for OnReceiveProposal") } var r0 error - if rf, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { - r0 = rf(proposal) + if returnFunc, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { + r0 = returnFunc(proposal) } else { r0 = ret.Error(0) } - return r0 } -// OnReceiveQc provides a mock function with given fields: qc -func (_m *EventHandler) OnReceiveQc(qc *flow.QuorumCertificate) error { - ret := _m.Called(qc) +// EventHandler_OnReceiveProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveProposal' +type EventHandler_OnReceiveProposal_Call struct { + *mock.Call +} + +// OnReceiveProposal is a helper method to define mock.On call +// - proposal *model.SignedProposal +func (_e *EventHandler_Expecter) OnReceiveProposal(proposal interface{}) *EventHandler_OnReceiveProposal_Call { + return &EventHandler_OnReceiveProposal_Call{Call: _e.mock.On("OnReceiveProposal", proposal)} +} + +func (_c *EventHandler_OnReceiveProposal_Call) Run(run func(proposal *model.SignedProposal)) *EventHandler_OnReceiveProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventHandler_OnReceiveProposal_Call) Return(err error) *EventHandler_OnReceiveProposal_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EventHandler_OnReceiveProposal_Call) RunAndReturn(run func(proposal *model.SignedProposal) error) *EventHandler_OnReceiveProposal_Call { + _c.Call.Return(run) + return _c +} + +// OnReceiveQc provides a mock function for the type EventHandler +func (_mock *EventHandler) OnReceiveQc(qc *flow.QuorumCertificate) error { + ret := _mock.Called(qc) if len(ret) == 0 { panic("no return value specified for OnReceiveQc") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.QuorumCertificate) error); ok { - r0 = rf(qc) + if returnFunc, ok := ret.Get(0).(func(*flow.QuorumCertificate) error); ok { + r0 = returnFunc(qc) } else { r0 = ret.Error(0) } - return r0 } -// OnReceiveTc provides a mock function with given fields: tc -func (_m *EventHandler) OnReceiveTc(tc *flow.TimeoutCertificate) error { - ret := _m.Called(tc) +// EventHandler_OnReceiveQc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveQc' +type EventHandler_OnReceiveQc_Call struct { + *mock.Call +} + +// OnReceiveQc is a helper method to define mock.On call +// - qc *flow.QuorumCertificate +func (_e *EventHandler_Expecter) OnReceiveQc(qc interface{}) *EventHandler_OnReceiveQc_Call { + return &EventHandler_OnReceiveQc_Call{Call: _e.mock.On("OnReceiveQc", qc)} +} + +func (_c *EventHandler_OnReceiveQc_Call) Run(run func(qc *flow.QuorumCertificate)) *EventHandler_OnReceiveQc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventHandler_OnReceiveQc_Call) Return(err error) *EventHandler_OnReceiveQc_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EventHandler_OnReceiveQc_Call) RunAndReturn(run func(qc *flow.QuorumCertificate) error) *EventHandler_OnReceiveQc_Call { + _c.Call.Return(run) + return _c +} + +// OnReceiveTc provides a mock function for the type EventHandler +func (_mock *EventHandler) OnReceiveTc(tc *flow.TimeoutCertificate) error { + ret := _mock.Called(tc) if len(ret) == 0 { panic("no return value specified for OnReceiveTc") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.TimeoutCertificate) error); ok { - r0 = rf(tc) + if returnFunc, ok := ret.Get(0).(func(*flow.TimeoutCertificate) error); ok { + r0 = returnFunc(tc) } else { r0 = ret.Error(0) } - return r0 } -// Start provides a mock function with given fields: ctx -func (_m *EventHandler) Start(ctx context.Context) error { - ret := _m.Called(ctx) +// EventHandler_OnReceiveTc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveTc' +type EventHandler_OnReceiveTc_Call struct { + *mock.Call +} + +// OnReceiveTc is a helper method to define mock.On call +// - tc *flow.TimeoutCertificate +func (_e *EventHandler_Expecter) OnReceiveTc(tc interface{}) *EventHandler_OnReceiveTc_Call { + return &EventHandler_OnReceiveTc_Call{Call: _e.mock.On("OnReceiveTc", tc)} +} + +func (_c *EventHandler_OnReceiveTc_Call) Run(run func(tc *flow.TimeoutCertificate)) *EventHandler_OnReceiveTc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventHandler_OnReceiveTc_Call) Return(err error) *EventHandler_OnReceiveTc_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EventHandler_OnReceiveTc_Call) RunAndReturn(run func(tc *flow.TimeoutCertificate) error) *EventHandler_OnReceiveTc_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type EventHandler +func (_mock *EventHandler) Start(ctx context.Context) error { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for Start") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Error(0) } - return r0 } -// TimeoutChannel provides a mock function with no fields -func (_m *EventHandler) TimeoutChannel() <-chan time.Time { - ret := _m.Called() +// EventHandler_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type EventHandler_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - ctx context.Context +func (_e *EventHandler_Expecter) Start(ctx interface{}) *EventHandler_Start_Call { + return &EventHandler_Start_Call{Call: _e.mock.On("Start", ctx)} +} + +func (_c *EventHandler_Start_Call) Run(run func(ctx context.Context)) *EventHandler_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventHandler_Start_Call) Return(err error) *EventHandler_Start_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EventHandler_Start_Call) RunAndReturn(run func(ctx context.Context) error) *EventHandler_Start_Call { + _c.Call.Return(run) + return _c +} + +// TimeoutChannel provides a mock function for the type EventHandler +func (_mock *EventHandler) TimeoutChannel() <-chan time.Time { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TimeoutChannel") } var r0 <-chan time.Time - if rf, ok := ret.Get(0).(func() <-chan time.Time); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan time.Time); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan time.Time) } } - return r0 } -// NewEventHandler creates a new instance of EventHandler. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEventHandler(t interface { - mock.TestingT - Cleanup(func()) -}) *EventHandler { - mock := &EventHandler{} - mock.Mock.Test(t) +// EventHandler_TimeoutChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TimeoutChannel' +type EventHandler_TimeoutChannel_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TimeoutChannel is a helper method to define mock.On call +func (_e *EventHandler_Expecter) TimeoutChannel() *EventHandler_TimeoutChannel_Call { + return &EventHandler_TimeoutChannel_Call{Call: _e.mock.On("TimeoutChannel")} +} - return mock +func (_c *EventHandler_TimeoutChannel_Call) Run(run func()) *EventHandler_TimeoutChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EventHandler_TimeoutChannel_Call) Return(timeCh <-chan time.Time) *EventHandler_TimeoutChannel_Call { + _c.Call.Return(timeCh) + return _c +} + +func (_c *EventHandler_TimeoutChannel_Call) RunAndReturn(run func() <-chan time.Time) *EventHandler_TimeoutChannel_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/event_loop.go b/consensus/hotstuff/mocks/event_loop.go index fd1fea6bd9e..151c1f45b69 100644 --- a/consensus/hotstuff/mocks/event_loop.go +++ b/consensus/hotstuff/mocks/event_loop.go @@ -1,117 +1,503 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + mock "github.com/stretchr/testify/mock" +) - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" +// NewEventLoop creates a new instance of EventLoop. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEventLoop(t interface { + mock.TestingT + Cleanup(func()) +}) *EventLoop { + mock := &EventLoop{} + mock.Mock.Test(t) - mock "github.com/stretchr/testify/mock" + t.Cleanup(func() { mock.AssertExpectations(t) }) - model "github.com/onflow/flow-go/consensus/hotstuff/model" -) + return mock +} // EventLoop is an autogenerated mock type for the EventLoop type type EventLoop struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *EventLoop) Done() <-chan struct{} { - ret := _m.Called() +type EventLoop_Expecter struct { + mock *mock.Mock +} + +func (_m *EventLoop) EXPECT() *EventLoop_Expecter { + return &EventLoop_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type EventLoop +func (_mock *EventLoop) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// OnNewQcDiscovered provides a mock function with given fields: certificate -func (_m *EventLoop) OnNewQcDiscovered(certificate *flow.QuorumCertificate) { - _m.Called(certificate) +// EventLoop_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type EventLoop_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *EventLoop_Expecter) Done() *EventLoop_Done_Call { + return &EventLoop_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *EventLoop_Done_Call) Run(run func()) *EventLoop_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EventLoop_Done_Call) Return(valCh <-chan struct{}) *EventLoop_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *EventLoop_Done_Call) RunAndReturn(run func() <-chan struct{}) *EventLoop_Done_Call { + _c.Call.Return(run) + return _c +} + +// OnNewQcDiscovered provides a mock function for the type EventLoop +func (_mock *EventLoop) OnNewQcDiscovered(certificate *flow.QuorumCertificate) { + _mock.Called(certificate) + return +} + +// EventLoop_OnNewQcDiscovered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnNewQcDiscovered' +type EventLoop_OnNewQcDiscovered_Call struct { + *mock.Call +} + +// OnNewQcDiscovered is a helper method to define mock.On call +// - certificate *flow.QuorumCertificate +func (_e *EventLoop_Expecter) OnNewQcDiscovered(certificate interface{}) *EventLoop_OnNewQcDiscovered_Call { + return &EventLoop_OnNewQcDiscovered_Call{Call: _e.mock.On("OnNewQcDiscovered", certificate)} +} + +func (_c *EventLoop_OnNewQcDiscovered_Call) Run(run func(certificate *flow.QuorumCertificate)) *EventLoop_OnNewQcDiscovered_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventLoop_OnNewQcDiscovered_Call) Return() *EventLoop_OnNewQcDiscovered_Call { + _c.Call.Return() + return _c +} + +func (_c *EventLoop_OnNewQcDiscovered_Call) RunAndReturn(run func(certificate *flow.QuorumCertificate)) *EventLoop_OnNewQcDiscovered_Call { + _c.Run(run) + return _c +} + +// OnNewTcDiscovered provides a mock function for the type EventLoop +func (_mock *EventLoop) OnNewTcDiscovered(certificate *flow.TimeoutCertificate) { + _mock.Called(certificate) + return +} + +// EventLoop_OnNewTcDiscovered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnNewTcDiscovered' +type EventLoop_OnNewTcDiscovered_Call struct { + *mock.Call +} + +// OnNewTcDiscovered is a helper method to define mock.On call +// - certificate *flow.TimeoutCertificate +func (_e *EventLoop_Expecter) OnNewTcDiscovered(certificate interface{}) *EventLoop_OnNewTcDiscovered_Call { + return &EventLoop_OnNewTcDiscovered_Call{Call: _e.mock.On("OnNewTcDiscovered", certificate)} +} + +func (_c *EventLoop_OnNewTcDiscovered_Call) Run(run func(certificate *flow.TimeoutCertificate)) *EventLoop_OnNewTcDiscovered_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventLoop_OnNewTcDiscovered_Call) Return() *EventLoop_OnNewTcDiscovered_Call { + _c.Call.Return() + return _c +} + +func (_c *EventLoop_OnNewTcDiscovered_Call) RunAndReturn(run func(certificate *flow.TimeoutCertificate)) *EventLoop_OnNewTcDiscovered_Call { + _c.Run(run) + return _c +} + +// OnPartialTcCreated provides a mock function for the type EventLoop +func (_mock *EventLoop) OnPartialTcCreated(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) { + _mock.Called(view, newestQC, lastViewTC) + return +} + +// EventLoop_OnPartialTcCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPartialTcCreated' +type EventLoop_OnPartialTcCreated_Call struct { + *mock.Call +} + +// OnPartialTcCreated is a helper method to define mock.On call +// - view uint64 +// - newestQC *flow.QuorumCertificate +// - lastViewTC *flow.TimeoutCertificate +func (_e *EventLoop_Expecter) OnPartialTcCreated(view interface{}, newestQC interface{}, lastViewTC interface{}) *EventLoop_OnPartialTcCreated_Call { + return &EventLoop_OnPartialTcCreated_Call{Call: _e.mock.On("OnPartialTcCreated", view, newestQC, lastViewTC)} +} + +func (_c *EventLoop_OnPartialTcCreated_Call) Run(run func(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *EventLoop_OnPartialTcCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *EventLoop_OnPartialTcCreated_Call) Return() *EventLoop_OnPartialTcCreated_Call { + _c.Call.Return() + return _c +} + +func (_c *EventLoop_OnPartialTcCreated_Call) RunAndReturn(run func(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *EventLoop_OnPartialTcCreated_Call { + _c.Run(run) + return _c +} + +// OnQcConstructedFromVotes provides a mock function for the type EventLoop +func (_mock *EventLoop) OnQcConstructedFromVotes(quorumCertificate *flow.QuorumCertificate) { + _mock.Called(quorumCertificate) + return +} + +// EventLoop_OnQcConstructedFromVotes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnQcConstructedFromVotes' +type EventLoop_OnQcConstructedFromVotes_Call struct { + *mock.Call +} + +// OnQcConstructedFromVotes is a helper method to define mock.On call +// - quorumCertificate *flow.QuorumCertificate +func (_e *EventLoop_Expecter) OnQcConstructedFromVotes(quorumCertificate interface{}) *EventLoop_OnQcConstructedFromVotes_Call { + return &EventLoop_OnQcConstructedFromVotes_Call{Call: _e.mock.On("OnQcConstructedFromVotes", quorumCertificate)} +} + +func (_c *EventLoop_OnQcConstructedFromVotes_Call) Run(run func(quorumCertificate *flow.QuorumCertificate)) *EventLoop_OnQcConstructedFromVotes_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventLoop_OnQcConstructedFromVotes_Call) Return() *EventLoop_OnQcConstructedFromVotes_Call { + _c.Call.Return() + return _c } -// OnNewTcDiscovered provides a mock function with given fields: certificate -func (_m *EventLoop) OnNewTcDiscovered(certificate *flow.TimeoutCertificate) { - _m.Called(certificate) +func (_c *EventLoop_OnQcConstructedFromVotes_Call) RunAndReturn(run func(quorumCertificate *flow.QuorumCertificate)) *EventLoop_OnQcConstructedFromVotes_Call { + _c.Run(run) + return _c } -// OnPartialTcCreated provides a mock function with given fields: view, newestQC, lastViewTC -func (_m *EventLoop) OnPartialTcCreated(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) { - _m.Called(view, newestQC, lastViewTC) +// OnTcConstructedFromTimeouts provides a mock function for the type EventLoop +func (_mock *EventLoop) OnTcConstructedFromTimeouts(certificate *flow.TimeoutCertificate) { + _mock.Called(certificate) + return } -// OnQcConstructedFromVotes provides a mock function with given fields: _a0 -func (_m *EventLoop) OnQcConstructedFromVotes(_a0 *flow.QuorumCertificate) { - _m.Called(_a0) +// EventLoop_OnTcConstructedFromTimeouts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTcConstructedFromTimeouts' +type EventLoop_OnTcConstructedFromTimeouts_Call struct { + *mock.Call } -// OnTcConstructedFromTimeouts provides a mock function with given fields: certificate -func (_m *EventLoop) OnTcConstructedFromTimeouts(certificate *flow.TimeoutCertificate) { - _m.Called(certificate) +// OnTcConstructedFromTimeouts is a helper method to define mock.On call +// - certificate *flow.TimeoutCertificate +func (_e *EventLoop_Expecter) OnTcConstructedFromTimeouts(certificate interface{}) *EventLoop_OnTcConstructedFromTimeouts_Call { + return &EventLoop_OnTcConstructedFromTimeouts_Call{Call: _e.mock.On("OnTcConstructedFromTimeouts", certificate)} } -// OnTimeoutProcessed provides a mock function with given fields: timeout -func (_m *EventLoop) OnTimeoutProcessed(timeout *model.TimeoutObject) { - _m.Called(timeout) +func (_c *EventLoop_OnTcConstructedFromTimeouts_Call) Run(run func(certificate *flow.TimeoutCertificate)) *EventLoop_OnTcConstructedFromTimeouts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c } -// OnVoteProcessed provides a mock function with given fields: vote -func (_m *EventLoop) OnVoteProcessed(vote *model.Vote) { - _m.Called(vote) +func (_c *EventLoop_OnTcConstructedFromTimeouts_Call) Return() *EventLoop_OnTcConstructedFromTimeouts_Call { + _c.Call.Return() + return _c } -// Ready provides a mock function with no fields -func (_m *EventLoop) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *EventLoop_OnTcConstructedFromTimeouts_Call) RunAndReturn(run func(certificate *flow.TimeoutCertificate)) *EventLoop_OnTcConstructedFromTimeouts_Call { + _c.Run(run) + return _c +} + +// OnTimeoutProcessed provides a mock function for the type EventLoop +func (_mock *EventLoop) OnTimeoutProcessed(timeout *model.TimeoutObject) { + _mock.Called(timeout) + return +} + +// EventLoop_OnTimeoutProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTimeoutProcessed' +type EventLoop_OnTimeoutProcessed_Call struct { + *mock.Call +} + +// OnTimeoutProcessed is a helper method to define mock.On call +// - timeout *model.TimeoutObject +func (_e *EventLoop_Expecter) OnTimeoutProcessed(timeout interface{}) *EventLoop_OnTimeoutProcessed_Call { + return &EventLoop_OnTimeoutProcessed_Call{Call: _e.mock.On("OnTimeoutProcessed", timeout)} +} + +func (_c *EventLoop_OnTimeoutProcessed_Call) Run(run func(timeout *model.TimeoutObject)) *EventLoop_OnTimeoutProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventLoop_OnTimeoutProcessed_Call) Return() *EventLoop_OnTimeoutProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *EventLoop_OnTimeoutProcessed_Call) RunAndReturn(run func(timeout *model.TimeoutObject)) *EventLoop_OnTimeoutProcessed_Call { + _c.Run(run) + return _c +} + +// OnVoteProcessed provides a mock function for the type EventLoop +func (_mock *EventLoop) OnVoteProcessed(vote *model.Vote) { + _mock.Called(vote) + return +} + +// EventLoop_OnVoteProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnVoteProcessed' +type EventLoop_OnVoteProcessed_Call struct { + *mock.Call +} + +// OnVoteProcessed is a helper method to define mock.On call +// - vote *model.Vote +func (_e *EventLoop_Expecter) OnVoteProcessed(vote interface{}) *EventLoop_OnVoteProcessed_Call { + return &EventLoop_OnVoteProcessed_Call{Call: _e.mock.On("OnVoteProcessed", vote)} +} + +func (_c *EventLoop_OnVoteProcessed_Call) Run(run func(vote *model.Vote)) *EventLoop_OnVoteProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventLoop_OnVoteProcessed_Call) Return() *EventLoop_OnVoteProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *EventLoop_OnVoteProcessed_Call) RunAndReturn(run func(vote *model.Vote)) *EventLoop_OnVoteProcessed_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type EventLoop +func (_mock *EventLoop) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *EventLoop) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// EventLoop_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type EventLoop_Ready_Call struct { + *mock.Call } -// SubmitProposal provides a mock function with given fields: proposal -func (_m *EventLoop) SubmitProposal(proposal *model.SignedProposal) { - _m.Called(proposal) +// Ready is a helper method to define mock.On call +func (_e *EventLoop_Expecter) Ready() *EventLoop_Ready_Call { + return &EventLoop_Ready_Call{Call: _e.mock.On("Ready")} } -// NewEventLoop creates a new instance of EventLoop. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEventLoop(t interface { - mock.TestingT - Cleanup(func()) -}) *EventLoop { - mock := &EventLoop{} - mock.Mock.Test(t) +func (_c *EventLoop_Ready_Call) Run(run func()) *EventLoop_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *EventLoop_Ready_Call) Return(valCh <-chan struct{}) *EventLoop_Ready_Call { + _c.Call.Return(valCh) + return _c +} - return mock +func (_c *EventLoop_Ready_Call) RunAndReturn(run func() <-chan struct{}) *EventLoop_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type EventLoop +func (_mock *EventLoop) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// EventLoop_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type EventLoop_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *EventLoop_Expecter) Start(signalerContext interface{}) *EventLoop_Start_Call { + return &EventLoop_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *EventLoop_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *EventLoop_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventLoop_Start_Call) Return() *EventLoop_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *EventLoop_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *EventLoop_Start_Call { + _c.Run(run) + return _c +} + +// SubmitProposal provides a mock function for the type EventLoop +func (_mock *EventLoop) SubmitProposal(proposal *model.SignedProposal) { + _mock.Called(proposal) + return +} + +// EventLoop_SubmitProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitProposal' +type EventLoop_SubmitProposal_Call struct { + *mock.Call +} + +// SubmitProposal is a helper method to define mock.On call +// - proposal *model.SignedProposal +func (_e *EventLoop_Expecter) SubmitProposal(proposal interface{}) *EventLoop_SubmitProposal_Call { + return &EventLoop_SubmitProposal_Call{Call: _e.mock.On("SubmitProposal", proposal)} +} + +func (_c *EventLoop_SubmitProposal_Call) Run(run func(proposal *model.SignedProposal)) *EventLoop_SubmitProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventLoop_SubmitProposal_Call) Return() *EventLoop_SubmitProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *EventLoop_SubmitProposal_Call) RunAndReturn(run func(proposal *model.SignedProposal)) *EventLoop_SubmitProposal_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/finalization_consumer.go b/consensus/hotstuff/mocks/finalization_consumer.go index 9855d8c5fa5..d7492076dc0 100644 --- a/consensus/hotstuff/mocks/finalization_consumer.go +++ b/consensus/hotstuff/mocks/finalization_consumer.go @@ -1,27 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - model "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" ) -// FinalizationConsumer is an autogenerated mock type for the FinalizationConsumer type -type FinalizationConsumer struct { - mock.Mock -} - -// OnBlockIncorporated provides a mock function with given fields: _a0 -func (_m *FinalizationConsumer) OnBlockIncorporated(_a0 *model.Block) { - _m.Called(_a0) -} - -// OnFinalizedBlock provides a mock function with given fields: _a0 -func (_m *FinalizationConsumer) OnFinalizedBlock(_a0 *model.Block) { - _m.Called(_a0) -} - // NewFinalizationConsumer creates a new instance of FinalizationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewFinalizationConsumer(t interface { @@ -35,3 +22,96 @@ func NewFinalizationConsumer(t interface { return mock } + +// FinalizationConsumer is an autogenerated mock type for the FinalizationConsumer type +type FinalizationConsumer struct { + mock.Mock +} + +type FinalizationConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *FinalizationConsumer) EXPECT() *FinalizationConsumer_Expecter { + return &FinalizationConsumer_Expecter{mock: &_m.Mock} +} + +// OnBlockIncorporated provides a mock function for the type FinalizationConsumer +func (_mock *FinalizationConsumer) OnBlockIncorporated(block *model.Block) { + _mock.Called(block) + return +} + +// FinalizationConsumer_OnBlockIncorporated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockIncorporated' +type FinalizationConsumer_OnBlockIncorporated_Call struct { + *mock.Call +} + +// OnBlockIncorporated is a helper method to define mock.On call +// - block *model.Block +func (_e *FinalizationConsumer_Expecter) OnBlockIncorporated(block interface{}) *FinalizationConsumer_OnBlockIncorporated_Call { + return &FinalizationConsumer_OnBlockIncorporated_Call{Call: _e.mock.On("OnBlockIncorporated", block)} +} + +func (_c *FinalizationConsumer_OnBlockIncorporated_Call) Run(run func(block *model.Block)) *FinalizationConsumer_OnBlockIncorporated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FinalizationConsumer_OnBlockIncorporated_Call) Return() *FinalizationConsumer_OnBlockIncorporated_Call { + _c.Call.Return() + return _c +} + +func (_c *FinalizationConsumer_OnBlockIncorporated_Call) RunAndReturn(run func(block *model.Block)) *FinalizationConsumer_OnBlockIncorporated_Call { + _c.Run(run) + return _c +} + +// OnFinalizedBlock provides a mock function for the type FinalizationConsumer +func (_mock *FinalizationConsumer) OnFinalizedBlock(block *model.Block) { + _mock.Called(block) + return +} + +// FinalizationConsumer_OnFinalizedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFinalizedBlock' +type FinalizationConsumer_OnFinalizedBlock_Call struct { + *mock.Call +} + +// OnFinalizedBlock is a helper method to define mock.On call +// - block *model.Block +func (_e *FinalizationConsumer_Expecter) OnFinalizedBlock(block interface{}) *FinalizationConsumer_OnFinalizedBlock_Call { + return &FinalizationConsumer_OnFinalizedBlock_Call{Call: _e.mock.On("OnFinalizedBlock", block)} +} + +func (_c *FinalizationConsumer_OnFinalizedBlock_Call) Run(run func(block *model.Block)) *FinalizationConsumer_OnFinalizedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FinalizationConsumer_OnFinalizedBlock_Call) Return() *FinalizationConsumer_OnFinalizedBlock_Call { + _c.Call.Return() + return _c +} + +func (_c *FinalizationConsumer_OnFinalizedBlock_Call) RunAndReturn(run func(block *model.Block)) *FinalizationConsumer_OnFinalizedBlock_Call { + _c.Run(run) + return _c +} diff --git a/consensus/hotstuff/mocks/finalization_registrar.go b/consensus/hotstuff/mocks/finalization_registrar.go index 481086d00cd..e179ad93c78 100644 --- a/consensus/hotstuff/mocks/finalization_registrar.go +++ b/consensus/hotstuff/mocks/finalization_registrar.go @@ -1,27 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - model "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" ) -// FinalizationRegistrar is an autogenerated mock type for the FinalizationRegistrar type -type FinalizationRegistrar struct { - mock.Mock -} - -// AddOnBlockFinalizedConsumer provides a mock function with given fields: consumer -func (_m *FinalizationRegistrar) AddOnBlockFinalizedConsumer(consumer func(*model.Block)) { - _m.Called(consumer) -} - -// AddOnBlockIncorporatedConsumer provides a mock function with given fields: consumer -func (_m *FinalizationRegistrar) AddOnBlockIncorporatedConsumer(consumer func(*model.Block)) { - _m.Called(consumer) -} - // NewFinalizationRegistrar creates a new instance of FinalizationRegistrar. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewFinalizationRegistrar(t interface { @@ -35,3 +22,96 @@ func NewFinalizationRegistrar(t interface { return mock } + +// FinalizationRegistrar is an autogenerated mock type for the FinalizationRegistrar type +type FinalizationRegistrar struct { + mock.Mock +} + +type FinalizationRegistrar_Expecter struct { + mock *mock.Mock +} + +func (_m *FinalizationRegistrar) EXPECT() *FinalizationRegistrar_Expecter { + return &FinalizationRegistrar_Expecter{mock: &_m.Mock} +} + +// AddOnBlockFinalizedConsumer provides a mock function for the type FinalizationRegistrar +func (_mock *FinalizationRegistrar) AddOnBlockFinalizedConsumer(consumer func(block *model.Block)) { + _mock.Called(consumer) + return +} + +// FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddOnBlockFinalizedConsumer' +type FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call struct { + *mock.Call +} + +// AddOnBlockFinalizedConsumer is a helper method to define mock.On call +// - consumer func(block *model.Block) +func (_e *FinalizationRegistrar_Expecter) AddOnBlockFinalizedConsumer(consumer interface{}) *FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call { + return &FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call{Call: _e.mock.On("AddOnBlockFinalizedConsumer", consumer)} +} + +func (_c *FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call) Run(run func(consumer func(block *model.Block))) *FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(block *model.Block) + if args[0] != nil { + arg0 = args[0].(func(block *model.Block)) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call) Return() *FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call { + _c.Call.Return() + return _c +} + +func (_c *FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call) RunAndReturn(run func(consumer func(block *model.Block))) *FinalizationRegistrar_AddOnBlockFinalizedConsumer_Call { + _c.Run(run) + return _c +} + +// AddOnBlockIncorporatedConsumer provides a mock function for the type FinalizationRegistrar +func (_mock *FinalizationRegistrar) AddOnBlockIncorporatedConsumer(consumer func(block *model.Block)) { + _mock.Called(consumer) + return +} + +// FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddOnBlockIncorporatedConsumer' +type FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call struct { + *mock.Call +} + +// AddOnBlockIncorporatedConsumer is a helper method to define mock.On call +// - consumer func(block *model.Block) +func (_e *FinalizationRegistrar_Expecter) AddOnBlockIncorporatedConsumer(consumer interface{}) *FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call { + return &FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call{Call: _e.mock.On("AddOnBlockIncorporatedConsumer", consumer)} +} + +func (_c *FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call) Run(run func(consumer func(block *model.Block))) *FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(block *model.Block) + if args[0] != nil { + arg0 = args[0].(func(block *model.Block)) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call) Return() *FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call { + _c.Call.Return() + return _c +} + +func (_c *FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call) RunAndReturn(run func(consumer func(block *model.Block))) *FinalizationRegistrar_AddOnBlockIncorporatedConsumer_Call { + _c.Run(run) + return _c +} diff --git a/consensus/hotstuff/mocks/follower_consumer.go b/consensus/hotstuff/mocks/follower_consumer.go index 307004cc8e1..66f1249010f 100644 --- a/consensus/hotstuff/mocks/follower_consumer.go +++ b/consensus/hotstuff/mocks/follower_consumer.go @@ -1,50 +1,204 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewFollowerConsumer creates a new instance of FollowerConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFollowerConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *FollowerConsumer { + mock := &FollowerConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // FollowerConsumer is an autogenerated mock type for the FollowerConsumer type type FollowerConsumer struct { mock.Mock } -// OnBlockIncorporated provides a mock function with given fields: _a0 -func (_m *FollowerConsumer) OnBlockIncorporated(_a0 *model.Block) { - _m.Called(_a0) +type FollowerConsumer_Expecter struct { + mock *mock.Mock } -// OnDoubleProposeDetected provides a mock function with given fields: _a0, _a1 -func (_m *FollowerConsumer) OnDoubleProposeDetected(_a0 *model.Block, _a1 *model.Block) { - _m.Called(_a0, _a1) +func (_m *FollowerConsumer) EXPECT() *FollowerConsumer_Expecter { + return &FollowerConsumer_Expecter{mock: &_m.Mock} } -// OnFinalizedBlock provides a mock function with given fields: _a0 -func (_m *FollowerConsumer) OnFinalizedBlock(_a0 *model.Block) { - _m.Called(_a0) +// OnBlockIncorporated provides a mock function for the type FollowerConsumer +func (_mock *FollowerConsumer) OnBlockIncorporated(block *model.Block) { + _mock.Called(block) + return } -// OnInvalidBlockDetected provides a mock function with given fields: err -func (_m *FollowerConsumer) OnInvalidBlockDetected(err flow.Slashable[model.InvalidProposalError]) { - _m.Called(err) +// FollowerConsumer_OnBlockIncorporated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockIncorporated' +type FollowerConsumer_OnBlockIncorporated_Call struct { + *mock.Call } -// NewFollowerConsumer creates a new instance of FollowerConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewFollowerConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *FollowerConsumer { - mock := &FollowerConsumer{} - mock.Mock.Test(t) +// OnBlockIncorporated is a helper method to define mock.On call +// - block *model.Block +func (_e *FollowerConsumer_Expecter) OnBlockIncorporated(block interface{}) *FollowerConsumer_OnBlockIncorporated_Call { + return &FollowerConsumer_OnBlockIncorporated_Call{Call: _e.mock.On("OnBlockIncorporated", block)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *FollowerConsumer_OnBlockIncorporated_Call) Run(run func(block *model.Block)) *FollowerConsumer_OnBlockIncorporated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *FollowerConsumer_OnBlockIncorporated_Call) Return() *FollowerConsumer_OnBlockIncorporated_Call { + _c.Call.Return() + return _c +} + +func (_c *FollowerConsumer_OnBlockIncorporated_Call) RunAndReturn(run func(block *model.Block)) *FollowerConsumer_OnBlockIncorporated_Call { + _c.Run(run) + return _c +} + +// OnDoubleProposeDetected provides a mock function for the type FollowerConsumer +func (_mock *FollowerConsumer) OnDoubleProposeDetected(block *model.Block, block1 *model.Block) { + _mock.Called(block, block1) + return +} + +// FollowerConsumer_OnDoubleProposeDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDoubleProposeDetected' +type FollowerConsumer_OnDoubleProposeDetected_Call struct { + *mock.Call +} + +// OnDoubleProposeDetected is a helper method to define mock.On call +// - block *model.Block +// - block1 *model.Block +func (_e *FollowerConsumer_Expecter) OnDoubleProposeDetected(block interface{}, block1 interface{}) *FollowerConsumer_OnDoubleProposeDetected_Call { + return &FollowerConsumer_OnDoubleProposeDetected_Call{Call: _e.mock.On("OnDoubleProposeDetected", block, block1)} +} + +func (_c *FollowerConsumer_OnDoubleProposeDetected_Call) Run(run func(block *model.Block, block1 *model.Block)) *FollowerConsumer_OnDoubleProposeDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + var arg1 *model.Block + if args[1] != nil { + arg1 = args[1].(*model.Block) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *FollowerConsumer_OnDoubleProposeDetected_Call) Return() *FollowerConsumer_OnDoubleProposeDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *FollowerConsumer_OnDoubleProposeDetected_Call) RunAndReturn(run func(block *model.Block, block1 *model.Block)) *FollowerConsumer_OnDoubleProposeDetected_Call { + _c.Run(run) + return _c +} + +// OnFinalizedBlock provides a mock function for the type FollowerConsumer +func (_mock *FollowerConsumer) OnFinalizedBlock(block *model.Block) { + _mock.Called(block) + return +} + +// FollowerConsumer_OnFinalizedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFinalizedBlock' +type FollowerConsumer_OnFinalizedBlock_Call struct { + *mock.Call +} + +// OnFinalizedBlock is a helper method to define mock.On call +// - block *model.Block +func (_e *FollowerConsumer_Expecter) OnFinalizedBlock(block interface{}) *FollowerConsumer_OnFinalizedBlock_Call { + return &FollowerConsumer_OnFinalizedBlock_Call{Call: _e.mock.On("OnFinalizedBlock", block)} +} + +func (_c *FollowerConsumer_OnFinalizedBlock_Call) Run(run func(block *model.Block)) *FollowerConsumer_OnFinalizedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FollowerConsumer_OnFinalizedBlock_Call) Return() *FollowerConsumer_OnFinalizedBlock_Call { + _c.Call.Return() + return _c +} + +func (_c *FollowerConsumer_OnFinalizedBlock_Call) RunAndReturn(run func(block *model.Block)) *FollowerConsumer_OnFinalizedBlock_Call { + _c.Run(run) + return _c +} + +// OnInvalidBlockDetected provides a mock function for the type FollowerConsumer +func (_mock *FollowerConsumer) OnInvalidBlockDetected(err flow.Slashable[model.InvalidProposalError]) { + _mock.Called(err) + return +} + +// FollowerConsumer_OnInvalidBlockDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidBlockDetected' +type FollowerConsumer_OnInvalidBlockDetected_Call struct { + *mock.Call +} + +// OnInvalidBlockDetected is a helper method to define mock.On call +// - err flow.Slashable[model.InvalidProposalError] +func (_e *FollowerConsumer_Expecter) OnInvalidBlockDetected(err interface{}) *FollowerConsumer_OnInvalidBlockDetected_Call { + return &FollowerConsumer_OnInvalidBlockDetected_Call{Call: _e.mock.On("OnInvalidBlockDetected", err)} +} + +func (_c *FollowerConsumer_OnInvalidBlockDetected_Call) Run(run func(err flow.Slashable[model.InvalidProposalError])) *FollowerConsumer_OnInvalidBlockDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[model.InvalidProposalError] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[model.InvalidProposalError]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FollowerConsumer_OnInvalidBlockDetected_Call) Return() *FollowerConsumer_OnInvalidBlockDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *FollowerConsumer_OnInvalidBlockDetected_Call) RunAndReturn(run func(err flow.Slashable[model.InvalidProposalError])) *FollowerConsumer_OnInvalidBlockDetected_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/forks.go b/consensus/hotstuff/mocks/forks.go index 1da09ab462e..0d7bc3c914e 100644 --- a/consensus/hotstuff/mocks/forks.go +++ b/consensus/hotstuff/mocks/forks.go @@ -1,60 +1,148 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewForks creates a new instance of Forks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewForks(t interface { + mock.TestingT + Cleanup(func()) +}) *Forks { + mock := &Forks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Forks is an autogenerated mock type for the Forks type type Forks struct { mock.Mock } -// AddCertifiedBlock provides a mock function with given fields: certifiedBlock -func (_m *Forks) AddCertifiedBlock(certifiedBlock *model.CertifiedBlock) error { - ret := _m.Called(certifiedBlock) +type Forks_Expecter struct { + mock *mock.Mock +} + +func (_m *Forks) EXPECT() *Forks_Expecter { + return &Forks_Expecter{mock: &_m.Mock} +} + +// AddCertifiedBlock provides a mock function for the type Forks +func (_mock *Forks) AddCertifiedBlock(certifiedBlock *model.CertifiedBlock) error { + ret := _mock.Called(certifiedBlock) if len(ret) == 0 { panic("no return value specified for AddCertifiedBlock") } var r0 error - if rf, ok := ret.Get(0).(func(*model.CertifiedBlock) error); ok { - r0 = rf(certifiedBlock) + if returnFunc, ok := ret.Get(0).(func(*model.CertifiedBlock) error); ok { + r0 = returnFunc(certifiedBlock) } else { r0 = ret.Error(0) } - return r0 } -// AddValidatedBlock provides a mock function with given fields: proposal -func (_m *Forks) AddValidatedBlock(proposal *model.Block) error { - ret := _m.Called(proposal) +// Forks_AddCertifiedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddCertifiedBlock' +type Forks_AddCertifiedBlock_Call struct { + *mock.Call +} + +// AddCertifiedBlock is a helper method to define mock.On call +// - certifiedBlock *model.CertifiedBlock +func (_e *Forks_Expecter) AddCertifiedBlock(certifiedBlock interface{}) *Forks_AddCertifiedBlock_Call { + return &Forks_AddCertifiedBlock_Call{Call: _e.mock.On("AddCertifiedBlock", certifiedBlock)} +} + +func (_c *Forks_AddCertifiedBlock_Call) Run(run func(certifiedBlock *model.CertifiedBlock)) *Forks_AddCertifiedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.CertifiedBlock + if args[0] != nil { + arg0 = args[0].(*model.CertifiedBlock) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Forks_AddCertifiedBlock_Call) Return(err error) *Forks_AddCertifiedBlock_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Forks_AddCertifiedBlock_Call) RunAndReturn(run func(certifiedBlock *model.CertifiedBlock) error) *Forks_AddCertifiedBlock_Call { + _c.Call.Return(run) + return _c +} + +// AddValidatedBlock provides a mock function for the type Forks +func (_mock *Forks) AddValidatedBlock(proposal *model.Block) error { + ret := _mock.Called(proposal) if len(ret) == 0 { panic("no return value specified for AddValidatedBlock") } var r0 error - if rf, ok := ret.Get(0).(func(*model.Block) error); ok { - r0 = rf(proposal) + if returnFunc, ok := ret.Get(0).(func(*model.Block) error); ok { + r0 = returnFunc(proposal) } else { r0 = ret.Error(0) } - return r0 } -// FinalityProof provides a mock function with no fields -func (_m *Forks) FinalityProof() (*hotstuff.FinalityProof, bool) { - ret := _m.Called() +// Forks_AddValidatedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddValidatedBlock' +type Forks_AddValidatedBlock_Call struct { + *mock.Call +} + +// AddValidatedBlock is a helper method to define mock.On call +// - proposal *model.Block +func (_e *Forks_Expecter) AddValidatedBlock(proposal interface{}) *Forks_AddValidatedBlock_Call { + return &Forks_AddValidatedBlock_Call{Call: _e.mock.On("AddValidatedBlock", proposal)} +} + +func (_c *Forks_AddValidatedBlock_Call) Run(run func(proposal *model.Block)) *Forks_AddValidatedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Forks_AddValidatedBlock_Call) Return(err error) *Forks_AddValidatedBlock_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Forks_AddValidatedBlock_Call) RunAndReturn(run func(proposal *model.Block) error) *Forks_AddValidatedBlock_Call { + _c.Call.Return(run) + return _c +} + +// FinalityProof provides a mock function for the type Forks +func (_mock *Forks) FinalityProof() (*hotstuff.FinalityProof, bool) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalityProof") @@ -62,67 +150,144 @@ func (_m *Forks) FinalityProof() (*hotstuff.FinalityProof, bool) { var r0 *hotstuff.FinalityProof var r1 bool - if rf, ok := ret.Get(0).(func() (*hotstuff.FinalityProof, bool)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*hotstuff.FinalityProof, bool)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *hotstuff.FinalityProof); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *hotstuff.FinalityProof); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*hotstuff.FinalityProof) } } - - if rf, ok := ret.Get(1).(func() bool); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// FinalizedBlock provides a mock function with no fields -func (_m *Forks) FinalizedBlock() *model.Block { - ret := _m.Called() +// Forks_FinalityProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalityProof' +type Forks_FinalityProof_Call struct { + *mock.Call +} + +// FinalityProof is a helper method to define mock.On call +func (_e *Forks_Expecter) FinalityProof() *Forks_FinalityProof_Call { + return &Forks_FinalityProof_Call{Call: _e.mock.On("FinalityProof")} +} + +func (_c *Forks_FinalityProof_Call) Run(run func()) *Forks_FinalityProof_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Forks_FinalityProof_Call) Return(finalityProof *hotstuff.FinalityProof, b bool) *Forks_FinalityProof_Call { + _c.Call.Return(finalityProof, b) + return _c +} + +func (_c *Forks_FinalityProof_Call) RunAndReturn(run func() (*hotstuff.FinalityProof, bool)) *Forks_FinalityProof_Call { + _c.Call.Return(run) + return _c +} + +// FinalizedBlock provides a mock function for the type Forks +func (_mock *Forks) FinalizedBlock() *model.Block { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalizedBlock") } var r0 *model.Block - if rf, ok := ret.Get(0).(func() *model.Block); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *model.Block); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Block) } } - return r0 } -// FinalizedView provides a mock function with no fields -func (_m *Forks) FinalizedView() uint64 { - ret := _m.Called() +// Forks_FinalizedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedBlock' +type Forks_FinalizedBlock_Call struct { + *mock.Call +} + +// FinalizedBlock is a helper method to define mock.On call +func (_e *Forks_Expecter) FinalizedBlock() *Forks_FinalizedBlock_Call { + return &Forks_FinalizedBlock_Call{Call: _e.mock.On("FinalizedBlock")} +} + +func (_c *Forks_FinalizedBlock_Call) Run(run func()) *Forks_FinalizedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Forks_FinalizedBlock_Call) Return(block *model.Block) *Forks_FinalizedBlock_Call { + _c.Call.Return(block) + return _c +} + +func (_c *Forks_FinalizedBlock_Call) RunAndReturn(run func() *model.Block) *Forks_FinalizedBlock_Call { + _c.Call.Return(run) + return _c +} + +// FinalizedView provides a mock function for the type Forks +func (_mock *Forks) FinalizedView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalizedView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetBlock provides a mock function with given fields: blockID -func (_m *Forks) GetBlock(blockID flow.Identifier) (*model.Block, bool) { - ret := _m.Called(blockID) +// Forks_FinalizedView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedView' +type Forks_FinalizedView_Call struct { + *mock.Call +} + +// FinalizedView is a helper method to define mock.On call +func (_e *Forks_Expecter) FinalizedView() *Forks_FinalizedView_Call { + return &Forks_FinalizedView_Call{Call: _e.mock.On("FinalizedView")} +} + +func (_c *Forks_FinalizedView_Call) Run(run func()) *Forks_FinalizedView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Forks_FinalizedView_Call) Return(v uint64) *Forks_FinalizedView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Forks_FinalizedView_Call) RunAndReturn(run func() uint64) *Forks_FinalizedView_Call { + _c.Call.Return(run) + return _c +} + +// GetBlock provides a mock function for the type Forks +func (_mock *Forks) GetBlock(blockID flow.Identifier) (*model.Block, bool) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for GetBlock") @@ -130,56 +295,107 @@ func (_m *Forks) GetBlock(blockID flow.Identifier) (*model.Block, bool) { var r0 *model.Block var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*model.Block, bool)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*model.Block, bool)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *model.Block); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *model.Block); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Block) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetBlocksForView provides a mock function with given fields: view -func (_m *Forks) GetBlocksForView(view uint64) []*model.Block { - ret := _m.Called(view) +// Forks_GetBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlock' +type Forks_GetBlock_Call struct { + *mock.Call +} + +// GetBlock is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Forks_Expecter) GetBlock(blockID interface{}) *Forks_GetBlock_Call { + return &Forks_GetBlock_Call{Call: _e.mock.On("GetBlock", blockID)} +} + +func (_c *Forks_GetBlock_Call) Run(run func(blockID flow.Identifier)) *Forks_GetBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Forks_GetBlock_Call) Return(block *model.Block, b bool) *Forks_GetBlock_Call { + _c.Call.Return(block, b) + return _c +} + +func (_c *Forks_GetBlock_Call) RunAndReturn(run func(blockID flow.Identifier) (*model.Block, bool)) *Forks_GetBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetBlocksForView provides a mock function for the type Forks +func (_mock *Forks) GetBlocksForView(view uint64) []*model.Block { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for GetBlocksForView") } var r0 []*model.Block - if rf, ok := ret.Get(0).(func(uint64) []*model.Block); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) []*model.Block); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*model.Block) } } - return r0 } -// NewForks creates a new instance of Forks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewForks(t interface { - mock.TestingT - Cleanup(func()) -}) *Forks { - mock := &Forks{} - mock.Mock.Test(t) +// Forks_GetBlocksForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlocksForView' +type Forks_GetBlocksForView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetBlocksForView is a helper method to define mock.On call +// - view uint64 +func (_e *Forks_Expecter) GetBlocksForView(view interface{}) *Forks_GetBlocksForView_Call { + return &Forks_GetBlocksForView_Call{Call: _e.mock.On("GetBlocksForView", view)} +} - return mock +func (_c *Forks_GetBlocksForView_Call) Run(run func(view uint64)) *Forks_GetBlocksForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Forks_GetBlocksForView_Call) Return(blocks []*model.Block) *Forks_GetBlocksForView_Call { + _c.Call.Return(blocks) + return _c +} + +func (_c *Forks_GetBlocksForView_Call) RunAndReturn(run func(view uint64) []*model.Block) *Forks_GetBlocksForView_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/pace_maker.go b/consensus/hotstuff/mocks/pace_maker.go index ca28c361a90..7e25d54482a 100644 --- a/consensus/hotstuff/mocks/pace_maker.go +++ b/consensus/hotstuff/mocks/pace_maker.go @@ -1,85 +1,184 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" + "context" + "time" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" +) - model "github.com/onflow/flow-go/consensus/hotstuff/model" +// NewPaceMaker creates a new instance of PaceMaker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPaceMaker(t interface { + mock.TestingT + Cleanup(func()) +}) *PaceMaker { + mock := &PaceMaker{} + mock.Mock.Test(t) - time "time" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // PaceMaker is an autogenerated mock type for the PaceMaker type type PaceMaker struct { mock.Mock } -// CurView provides a mock function with no fields -func (_m *PaceMaker) CurView() uint64 { - ret := _m.Called() +type PaceMaker_Expecter struct { + mock *mock.Mock +} + +func (_m *PaceMaker) EXPECT() *PaceMaker_Expecter { + return &PaceMaker_Expecter{mock: &_m.Mock} +} + +// CurView provides a mock function for the type PaceMaker +func (_mock *PaceMaker) CurView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for CurView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// LastViewTC provides a mock function with no fields -func (_m *PaceMaker) LastViewTC() *flow.TimeoutCertificate { - ret := _m.Called() +// PaceMaker_CurView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CurView' +type PaceMaker_CurView_Call struct { + *mock.Call +} + +// CurView is a helper method to define mock.On call +func (_e *PaceMaker_Expecter) CurView() *PaceMaker_CurView_Call { + return &PaceMaker_CurView_Call{Call: _e.mock.On("CurView")} +} + +func (_c *PaceMaker_CurView_Call) Run(run func()) *PaceMaker_CurView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PaceMaker_CurView_Call) Return(v uint64) *PaceMaker_CurView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *PaceMaker_CurView_Call) RunAndReturn(run func() uint64) *PaceMaker_CurView_Call { + _c.Call.Return(run) + return _c +} + +// LastViewTC provides a mock function for the type PaceMaker +func (_mock *PaceMaker) LastViewTC() *flow.TimeoutCertificate { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LastViewTC") } var r0 *flow.TimeoutCertificate - if rf, ok := ret.Get(0).(func() *flow.TimeoutCertificate); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.TimeoutCertificate); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TimeoutCertificate) } } - return r0 } -// NewestQC provides a mock function with no fields -func (_m *PaceMaker) NewestQC() *flow.QuorumCertificate { - ret := _m.Called() +// PaceMaker_LastViewTC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LastViewTC' +type PaceMaker_LastViewTC_Call struct { + *mock.Call +} + +// LastViewTC is a helper method to define mock.On call +func (_e *PaceMaker_Expecter) LastViewTC() *PaceMaker_LastViewTC_Call { + return &PaceMaker_LastViewTC_Call{Call: _e.mock.On("LastViewTC")} +} + +func (_c *PaceMaker_LastViewTC_Call) Run(run func()) *PaceMaker_LastViewTC_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PaceMaker_LastViewTC_Call) Return(timeoutCertificate *flow.TimeoutCertificate) *PaceMaker_LastViewTC_Call { + _c.Call.Return(timeoutCertificate) + return _c +} + +func (_c *PaceMaker_LastViewTC_Call) RunAndReturn(run func() *flow.TimeoutCertificate) *PaceMaker_LastViewTC_Call { + _c.Call.Return(run) + return _c +} + +// NewestQC provides a mock function for the type PaceMaker +func (_mock *PaceMaker) NewestQC() *flow.QuorumCertificate { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NewestQC") } var r0 *flow.QuorumCertificate - if rf, ok := ret.Get(0).(func() *flow.QuorumCertificate); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.QuorumCertificate); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.QuorumCertificate) } } - return r0 } -// ProcessQC provides a mock function with given fields: qc -func (_m *PaceMaker) ProcessQC(qc *flow.QuorumCertificate) (*model.NewViewEvent, error) { - ret := _m.Called(qc) +// PaceMaker_NewestQC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewestQC' +type PaceMaker_NewestQC_Call struct { + *mock.Call +} + +// NewestQC is a helper method to define mock.On call +func (_e *PaceMaker_Expecter) NewestQC() *PaceMaker_NewestQC_Call { + return &PaceMaker_NewestQC_Call{Call: _e.mock.On("NewestQC")} +} + +func (_c *PaceMaker_NewestQC_Call) Run(run func()) *PaceMaker_NewestQC_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PaceMaker_NewestQC_Call) Return(quorumCertificate *flow.QuorumCertificate) *PaceMaker_NewestQC_Call { + _c.Call.Return(quorumCertificate) + return _c +} + +func (_c *PaceMaker_NewestQC_Call) RunAndReturn(run func() *flow.QuorumCertificate) *PaceMaker_NewestQC_Call { + _c.Call.Return(run) + return _c +} + +// ProcessQC provides a mock function for the type PaceMaker +func (_mock *PaceMaker) ProcessQC(qc *flow.QuorumCertificate) (*model.NewViewEvent, error) { + ret := _mock.Called(qc) if len(ret) == 0 { panic("no return value specified for ProcessQC") @@ -87,29 +186,61 @@ func (_m *PaceMaker) ProcessQC(qc *flow.QuorumCertificate) (*model.NewViewEvent, var r0 *model.NewViewEvent var r1 error - if rf, ok := ret.Get(0).(func(*flow.QuorumCertificate) (*model.NewViewEvent, error)); ok { - return rf(qc) + if returnFunc, ok := ret.Get(0).(func(*flow.QuorumCertificate) (*model.NewViewEvent, error)); ok { + return returnFunc(qc) } - if rf, ok := ret.Get(0).(func(*flow.QuorumCertificate) *model.NewViewEvent); ok { - r0 = rf(qc) + if returnFunc, ok := ret.Get(0).(func(*flow.QuorumCertificate) *model.NewViewEvent); ok { + r0 = returnFunc(qc) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.NewViewEvent) } } - - if rf, ok := ret.Get(1).(func(*flow.QuorumCertificate) error); ok { - r1 = rf(qc) + if returnFunc, ok := ret.Get(1).(func(*flow.QuorumCertificate) error); ok { + r1 = returnFunc(qc) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProcessTC provides a mock function with given fields: tc -func (_m *PaceMaker) ProcessTC(tc *flow.TimeoutCertificate) (*model.NewViewEvent, error) { - ret := _m.Called(tc) +// PaceMaker_ProcessQC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessQC' +type PaceMaker_ProcessQC_Call struct { + *mock.Call +} + +// ProcessQC is a helper method to define mock.On call +// - qc *flow.QuorumCertificate +func (_e *PaceMaker_Expecter) ProcessQC(qc interface{}) *PaceMaker_ProcessQC_Call { + return &PaceMaker_ProcessQC_Call{Call: _e.mock.On("ProcessQC", qc)} +} + +func (_c *PaceMaker_ProcessQC_Call) Run(run func(qc *flow.QuorumCertificate)) *PaceMaker_ProcessQC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PaceMaker_ProcessQC_Call) Return(newViewEvent *model.NewViewEvent, err error) *PaceMaker_ProcessQC_Call { + _c.Call.Return(newViewEvent, err) + return _c +} + +func (_c *PaceMaker_ProcessQC_Call) RunAndReturn(run func(qc *flow.QuorumCertificate) (*model.NewViewEvent, error)) *PaceMaker_ProcessQC_Call { + _c.Call.Return(run) + return _c +} + +// ProcessTC provides a mock function for the type PaceMaker +func (_mock *PaceMaker) ProcessTC(tc *flow.TimeoutCertificate) (*model.NewViewEvent, error) { + ret := _mock.Called(tc) if len(ret) == 0 { panic("no return value specified for ProcessTC") @@ -117,79 +248,203 @@ func (_m *PaceMaker) ProcessTC(tc *flow.TimeoutCertificate) (*model.NewViewEvent var r0 *model.NewViewEvent var r1 error - if rf, ok := ret.Get(0).(func(*flow.TimeoutCertificate) (*model.NewViewEvent, error)); ok { - return rf(tc) + if returnFunc, ok := ret.Get(0).(func(*flow.TimeoutCertificate) (*model.NewViewEvent, error)); ok { + return returnFunc(tc) } - if rf, ok := ret.Get(0).(func(*flow.TimeoutCertificate) *model.NewViewEvent); ok { - r0 = rf(tc) + if returnFunc, ok := ret.Get(0).(func(*flow.TimeoutCertificate) *model.NewViewEvent); ok { + r0 = returnFunc(tc) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.NewViewEvent) } } - - if rf, ok := ret.Get(1).(func(*flow.TimeoutCertificate) error); ok { - r1 = rf(tc) + if returnFunc, ok := ret.Get(1).(func(*flow.TimeoutCertificate) error); ok { + r1 = returnFunc(tc) } else { r1 = ret.Error(1) } - return r0, r1 } -// Start provides a mock function with given fields: ctx -func (_m *PaceMaker) Start(ctx context.Context) { - _m.Called(ctx) +// PaceMaker_ProcessTC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessTC' +type PaceMaker_ProcessTC_Call struct { + *mock.Call +} + +// ProcessTC is a helper method to define mock.On call +// - tc *flow.TimeoutCertificate +func (_e *PaceMaker_Expecter) ProcessTC(tc interface{}) *PaceMaker_ProcessTC_Call { + return &PaceMaker_ProcessTC_Call{Call: _e.mock.On("ProcessTC", tc)} +} + +func (_c *PaceMaker_ProcessTC_Call) Run(run func(tc *flow.TimeoutCertificate)) *PaceMaker_ProcessTC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PaceMaker_ProcessTC_Call) Return(newViewEvent *model.NewViewEvent, err error) *PaceMaker_ProcessTC_Call { + _c.Call.Return(newViewEvent, err) + return _c +} + +func (_c *PaceMaker_ProcessTC_Call) RunAndReturn(run func(tc *flow.TimeoutCertificate) (*model.NewViewEvent, error)) *PaceMaker_ProcessTC_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type PaceMaker +func (_mock *PaceMaker) Start(ctx context.Context) { + _mock.Called(ctx) + return +} + +// PaceMaker_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type PaceMaker_Start_Call struct { + *mock.Call } -// TargetPublicationTime provides a mock function with given fields: proposalView, timeViewEntered, parentBlockId -func (_m *PaceMaker) TargetPublicationTime(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier) time.Time { - ret := _m.Called(proposalView, timeViewEntered, parentBlockId) +// Start is a helper method to define mock.On call +// - ctx context.Context +func (_e *PaceMaker_Expecter) Start(ctx interface{}) *PaceMaker_Start_Call { + return &PaceMaker_Start_Call{Call: _e.mock.On("Start", ctx)} +} + +func (_c *PaceMaker_Start_Call) Run(run func(ctx context.Context)) *PaceMaker_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PaceMaker_Start_Call) Return() *PaceMaker_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *PaceMaker_Start_Call) RunAndReturn(run func(ctx context.Context)) *PaceMaker_Start_Call { + _c.Run(run) + return _c +} + +// TargetPublicationTime provides a mock function for the type PaceMaker +func (_mock *PaceMaker) TargetPublicationTime(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier) time.Time { + ret := _mock.Called(proposalView, timeViewEntered, parentBlockId) if len(ret) == 0 { panic("no return value specified for TargetPublicationTime") } var r0 time.Time - if rf, ok := ret.Get(0).(func(uint64, time.Time, flow.Identifier) time.Time); ok { - r0 = rf(proposalView, timeViewEntered, parentBlockId) + if returnFunc, ok := ret.Get(0).(func(uint64, time.Time, flow.Identifier) time.Time); ok { + r0 = returnFunc(proposalView, timeViewEntered, parentBlockId) } else { r0 = ret.Get(0).(time.Time) } - return r0 } -// TimeoutChannel provides a mock function with no fields -func (_m *PaceMaker) TimeoutChannel() <-chan time.Time { - ret := _m.Called() +// PaceMaker_TargetPublicationTime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TargetPublicationTime' +type PaceMaker_TargetPublicationTime_Call struct { + *mock.Call +} + +// TargetPublicationTime is a helper method to define mock.On call +// - proposalView uint64 +// - timeViewEntered time.Time +// - parentBlockId flow.Identifier +func (_e *PaceMaker_Expecter) TargetPublicationTime(proposalView interface{}, timeViewEntered interface{}, parentBlockId interface{}) *PaceMaker_TargetPublicationTime_Call { + return &PaceMaker_TargetPublicationTime_Call{Call: _e.mock.On("TargetPublicationTime", proposalView, timeViewEntered, parentBlockId)} +} + +func (_c *PaceMaker_TargetPublicationTime_Call) Run(run func(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier)) *PaceMaker_TargetPublicationTime_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *PaceMaker_TargetPublicationTime_Call) Return(time1 time.Time) *PaceMaker_TargetPublicationTime_Call { + _c.Call.Return(time1) + return _c +} + +func (_c *PaceMaker_TargetPublicationTime_Call) RunAndReturn(run func(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier) time.Time) *PaceMaker_TargetPublicationTime_Call { + _c.Call.Return(run) + return _c +} + +// TimeoutChannel provides a mock function for the type PaceMaker +func (_mock *PaceMaker) TimeoutChannel() <-chan time.Time { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TimeoutChannel") } var r0 <-chan time.Time - if rf, ok := ret.Get(0).(func() <-chan time.Time); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan time.Time); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan time.Time) } } - return r0 } -// NewPaceMaker creates a new instance of PaceMaker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPaceMaker(t interface { - mock.TestingT - Cleanup(func()) -}) *PaceMaker { - mock := &PaceMaker{} - mock.Mock.Test(t) +// PaceMaker_TimeoutChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TimeoutChannel' +type PaceMaker_TimeoutChannel_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TimeoutChannel is a helper method to define mock.On call +func (_e *PaceMaker_Expecter) TimeoutChannel() *PaceMaker_TimeoutChannel_Call { + return &PaceMaker_TimeoutChannel_Call{Call: _e.mock.On("TimeoutChannel")} +} - return mock +func (_c *PaceMaker_TimeoutChannel_Call) Run(run func()) *PaceMaker_TimeoutChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PaceMaker_TimeoutChannel_Call) Return(timeCh <-chan time.Time) *PaceMaker_TimeoutChannel_Call { + _c.Call.Return(timeCh) + return _c +} + +func (_c *PaceMaker_TimeoutChannel_Call) RunAndReturn(run func() <-chan time.Time) *PaceMaker_TimeoutChannel_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/packer.go b/consensus/hotstuff/mocks/packer.go index 6adb8d9c701..2e3597f5949 100644 --- a/consensus/hotstuff/mocks/packer.go +++ b/consensus/hotstuff/mocks/packer.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewPacker creates a new instance of Packer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPacker(t interface { + mock.TestingT + Cleanup(func()) +}) *Packer { + mock := &Packer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Packer is an autogenerated mock type for the Packer type type Packer struct { mock.Mock } -// Pack provides a mock function with given fields: view, sig -func (_m *Packer) Pack(view uint64, sig *hotstuff.BlockSignatureData) ([]byte, []byte, error) { - ret := _m.Called(view, sig) +type Packer_Expecter struct { + mock *mock.Mock +} + +func (_m *Packer) EXPECT() *Packer_Expecter { + return &Packer_Expecter{mock: &_m.Mock} +} + +// Pack provides a mock function for the type Packer +func (_mock *Packer) Pack(view uint64, sig *hotstuff.BlockSignatureData) ([]byte, []byte, error) { + ret := _mock.Called(view, sig) if len(ret) == 0 { panic("no return value specified for Pack") @@ -25,37 +48,74 @@ func (_m *Packer) Pack(view uint64, sig *hotstuff.BlockSignatureData) ([]byte, [ var r0 []byte var r1 []byte var r2 error - if rf, ok := ret.Get(0).(func(uint64, *hotstuff.BlockSignatureData) ([]byte, []byte, error)); ok { - return rf(view, sig) + if returnFunc, ok := ret.Get(0).(func(uint64, *hotstuff.BlockSignatureData) ([]byte, []byte, error)); ok { + return returnFunc(view, sig) } - if rf, ok := ret.Get(0).(func(uint64, *hotstuff.BlockSignatureData) []byte); ok { - r0 = rf(view, sig) + if returnFunc, ok := ret.Get(0).(func(uint64, *hotstuff.BlockSignatureData) []byte); ok { + r0 = returnFunc(view, sig) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(uint64, *hotstuff.BlockSignatureData) []byte); ok { - r1 = rf(view, sig) + if returnFunc, ok := ret.Get(1).(func(uint64, *hotstuff.BlockSignatureData) []byte); ok { + r1 = returnFunc(view, sig) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]byte) } } - - if rf, ok := ret.Get(2).(func(uint64, *hotstuff.BlockSignatureData) error); ok { - r2 = rf(view, sig) + if returnFunc, ok := ret.Get(2).(func(uint64, *hotstuff.BlockSignatureData) error); ok { + r2 = returnFunc(view, sig) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// Unpack provides a mock function with given fields: signerIdentities, sigData -func (_m *Packer) Unpack(signerIdentities flow.IdentitySkeletonList, sigData []byte) (*hotstuff.BlockSignatureData, error) { - ret := _m.Called(signerIdentities, sigData) +// Packer_Pack_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Pack' +type Packer_Pack_Call struct { + *mock.Call +} + +// Pack is a helper method to define mock.On call +// - view uint64 +// - sig *hotstuff.BlockSignatureData +func (_e *Packer_Expecter) Pack(view interface{}, sig interface{}) *Packer_Pack_Call { + return &Packer_Pack_Call{Call: _e.mock.On("Pack", view, sig)} +} + +func (_c *Packer_Pack_Call) Run(run func(view uint64, sig *hotstuff.BlockSignatureData)) *Packer_Pack_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *hotstuff.BlockSignatureData + if args[1] != nil { + arg1 = args[1].(*hotstuff.BlockSignatureData) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Packer_Pack_Call) Return(signerIndices []byte, sigData []byte, err error) *Packer_Pack_Call { + _c.Call.Return(signerIndices, sigData, err) + return _c +} + +func (_c *Packer_Pack_Call) RunAndReturn(run func(view uint64, sig *hotstuff.BlockSignatureData) ([]byte, []byte, error)) *Packer_Pack_Call { + _c.Call.Return(run) + return _c +} + +// Unpack provides a mock function for the type Packer +func (_mock *Packer) Unpack(signerIdentities flow.IdentitySkeletonList, sigData []byte) (*hotstuff.BlockSignatureData, error) { + ret := _mock.Called(signerIdentities, sigData) if len(ret) == 0 { panic("no return value specified for Unpack") @@ -63,36 +123,60 @@ func (_m *Packer) Unpack(signerIdentities flow.IdentitySkeletonList, sigData []b var r0 *hotstuff.BlockSignatureData var r1 error - if rf, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte) (*hotstuff.BlockSignatureData, error)); ok { - return rf(signerIdentities, sigData) + if returnFunc, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte) (*hotstuff.BlockSignatureData, error)); ok { + return returnFunc(signerIdentities, sigData) } - if rf, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte) *hotstuff.BlockSignatureData); ok { - r0 = rf(signerIdentities, sigData) + if returnFunc, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte) *hotstuff.BlockSignatureData); ok { + r0 = returnFunc(signerIdentities, sigData) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*hotstuff.BlockSignatureData) } } - - if rf, ok := ret.Get(1).(func(flow.IdentitySkeletonList, []byte) error); ok { - r1 = rf(signerIdentities, sigData) + if returnFunc, ok := ret.Get(1).(func(flow.IdentitySkeletonList, []byte) error); ok { + r1 = returnFunc(signerIdentities, sigData) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewPacker creates a new instance of Packer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPacker(t interface { - mock.TestingT - Cleanup(func()) -}) *Packer { - mock := &Packer{} - mock.Mock.Test(t) +// Packer_Unpack_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Unpack' +type Packer_Unpack_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Unpack is a helper method to define mock.On call +// - signerIdentities flow.IdentitySkeletonList +// - sigData []byte +func (_e *Packer_Expecter) Unpack(signerIdentities interface{}, sigData interface{}) *Packer_Unpack_Call { + return &Packer_Unpack_Call{Call: _e.mock.On("Unpack", signerIdentities, sigData)} +} - return mock +func (_c *Packer_Unpack_Call) Run(run func(signerIdentities flow.IdentitySkeletonList, sigData []byte)) *Packer_Unpack_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.IdentitySkeletonList + if args[0] != nil { + arg0 = args[0].(flow.IdentitySkeletonList) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Packer_Unpack_Call) Return(blockSignatureData *hotstuff.BlockSignatureData, err error) *Packer_Unpack_Call { + _c.Call.Return(blockSignatureData, err) + return _c +} + +func (_c *Packer_Unpack_Call) RunAndReturn(run func(signerIdentities flow.IdentitySkeletonList, sigData []byte) (*hotstuff.BlockSignatureData, error)) *Packer_Unpack_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/participant_consumer.go b/consensus/hotstuff/mocks/participant_consumer.go index cfe7a4d4134..9dac02453b4 100644 --- a/consensus/hotstuff/mocks/participant_consumer.go +++ b/consensus/hotstuff/mocks/participant_consumer.go @@ -1,91 +1,578 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewParticipantConsumer creates a new instance of ParticipantConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewParticipantConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *ParticipantConsumer { + mock := &ParticipantConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ParticipantConsumer is an autogenerated mock type for the ParticipantConsumer type type ParticipantConsumer struct { mock.Mock } -// OnCurrentViewDetails provides a mock function with given fields: currentView, finalizedView, currentLeader -func (_m *ParticipantConsumer) OnCurrentViewDetails(currentView uint64, finalizedView uint64, currentLeader flow.Identifier) { - _m.Called(currentView, finalizedView, currentLeader) +type ParticipantConsumer_Expecter struct { + mock *mock.Mock } -// OnEventProcessed provides a mock function with no fields -func (_m *ParticipantConsumer) OnEventProcessed() { - _m.Called() +func (_m *ParticipantConsumer) EXPECT() *ParticipantConsumer_Expecter { + return &ParticipantConsumer_Expecter{mock: &_m.Mock} } -// OnLocalTimeout provides a mock function with given fields: currentView -func (_m *ParticipantConsumer) OnLocalTimeout(currentView uint64) { - _m.Called(currentView) +// OnCurrentViewDetails provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnCurrentViewDetails(currentView uint64, finalizedView uint64, currentLeader flow.Identifier) { + _mock.Called(currentView, finalizedView, currentLeader) + return } -// OnPartialTc provides a mock function with given fields: currentView, partialTc -func (_m *ParticipantConsumer) OnPartialTc(currentView uint64, partialTc *hotstuff.PartialTcCreated) { - _m.Called(currentView, partialTc) +// ParticipantConsumer_OnCurrentViewDetails_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnCurrentViewDetails' +type ParticipantConsumer_OnCurrentViewDetails_Call struct { + *mock.Call } -// OnQcTriggeredViewChange provides a mock function with given fields: oldView, newView, qc -func (_m *ParticipantConsumer) OnQcTriggeredViewChange(oldView uint64, newView uint64, qc *flow.QuorumCertificate) { - _m.Called(oldView, newView, qc) +// OnCurrentViewDetails is a helper method to define mock.On call +// - currentView uint64 +// - finalizedView uint64 +// - currentLeader flow.Identifier +func (_e *ParticipantConsumer_Expecter) OnCurrentViewDetails(currentView interface{}, finalizedView interface{}, currentLeader interface{}) *ParticipantConsumer_OnCurrentViewDetails_Call { + return &ParticipantConsumer_OnCurrentViewDetails_Call{Call: _e.mock.On("OnCurrentViewDetails", currentView, finalizedView, currentLeader)} } -// OnReceiveProposal provides a mock function with given fields: currentView, proposal -func (_m *ParticipantConsumer) OnReceiveProposal(currentView uint64, proposal *model.SignedProposal) { - _m.Called(currentView, proposal) +func (_c *ParticipantConsumer_OnCurrentViewDetails_Call) Run(run func(currentView uint64, finalizedView uint64, currentLeader flow.Identifier)) *ParticipantConsumer_OnCurrentViewDetails_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// OnReceiveQc provides a mock function with given fields: currentView, qc -func (_m *ParticipantConsumer) OnReceiveQc(currentView uint64, qc *flow.QuorumCertificate) { - _m.Called(currentView, qc) +func (_c *ParticipantConsumer_OnCurrentViewDetails_Call) Return() *ParticipantConsumer_OnCurrentViewDetails_Call { + _c.Call.Return() + return _c } -// OnReceiveTc provides a mock function with given fields: currentView, tc -func (_m *ParticipantConsumer) OnReceiveTc(currentView uint64, tc *flow.TimeoutCertificate) { - _m.Called(currentView, tc) +func (_c *ParticipantConsumer_OnCurrentViewDetails_Call) RunAndReturn(run func(currentView uint64, finalizedView uint64, currentLeader flow.Identifier)) *ParticipantConsumer_OnCurrentViewDetails_Call { + _c.Run(run) + return _c } -// OnStart provides a mock function with given fields: currentView -func (_m *ParticipantConsumer) OnStart(currentView uint64) { - _m.Called(currentView) +// OnEventProcessed provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnEventProcessed() { + _mock.Called() + return } -// OnStartingTimeout provides a mock function with given fields: _a0 -func (_m *ParticipantConsumer) OnStartingTimeout(_a0 model.TimerInfo) { - _m.Called(_a0) +// ParticipantConsumer_OnEventProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnEventProcessed' +type ParticipantConsumer_OnEventProcessed_Call struct { + *mock.Call } -// OnTcTriggeredViewChange provides a mock function with given fields: oldView, newView, tc -func (_m *ParticipantConsumer) OnTcTriggeredViewChange(oldView uint64, newView uint64, tc *flow.TimeoutCertificate) { - _m.Called(oldView, newView, tc) +// OnEventProcessed is a helper method to define mock.On call +func (_e *ParticipantConsumer_Expecter) OnEventProcessed() *ParticipantConsumer_OnEventProcessed_Call { + return &ParticipantConsumer_OnEventProcessed_Call{Call: _e.mock.On("OnEventProcessed")} } -// OnViewChange provides a mock function with given fields: oldView, newView -func (_m *ParticipantConsumer) OnViewChange(oldView uint64, newView uint64) { - _m.Called(oldView, newView) +func (_c *ParticipantConsumer_OnEventProcessed_Call) Run(run func()) *ParticipantConsumer_OnEventProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// NewParticipantConsumer creates a new instance of ParticipantConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewParticipantConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *ParticipantConsumer { - mock := &ParticipantConsumer{} - mock.Mock.Test(t) +func (_c *ParticipantConsumer_OnEventProcessed_Call) Return() *ParticipantConsumer_OnEventProcessed_Call { + _c.Call.Return() + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ParticipantConsumer_OnEventProcessed_Call) RunAndReturn(run func()) *ParticipantConsumer_OnEventProcessed_Call { + _c.Run(run) + return _c +} - return mock +// OnLocalTimeout provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnLocalTimeout(currentView uint64) { + _mock.Called(currentView) + return +} + +// ParticipantConsumer_OnLocalTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalTimeout' +type ParticipantConsumer_OnLocalTimeout_Call struct { + *mock.Call +} + +// OnLocalTimeout is a helper method to define mock.On call +// - currentView uint64 +func (_e *ParticipantConsumer_Expecter) OnLocalTimeout(currentView interface{}) *ParticipantConsumer_OnLocalTimeout_Call { + return &ParticipantConsumer_OnLocalTimeout_Call{Call: _e.mock.On("OnLocalTimeout", currentView)} +} + +func (_c *ParticipantConsumer_OnLocalTimeout_Call) Run(run func(currentView uint64)) *ParticipantConsumer_OnLocalTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnLocalTimeout_Call) Return() *ParticipantConsumer_OnLocalTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnLocalTimeout_Call) RunAndReturn(run func(currentView uint64)) *ParticipantConsumer_OnLocalTimeout_Call { + _c.Run(run) + return _c +} + +// OnPartialTc provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnPartialTc(currentView uint64, partialTc *hotstuff.PartialTcCreated) { + _mock.Called(currentView, partialTc) + return +} + +// ParticipantConsumer_OnPartialTc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPartialTc' +type ParticipantConsumer_OnPartialTc_Call struct { + *mock.Call +} + +// OnPartialTc is a helper method to define mock.On call +// - currentView uint64 +// - partialTc *hotstuff.PartialTcCreated +func (_e *ParticipantConsumer_Expecter) OnPartialTc(currentView interface{}, partialTc interface{}) *ParticipantConsumer_OnPartialTc_Call { + return &ParticipantConsumer_OnPartialTc_Call{Call: _e.mock.On("OnPartialTc", currentView, partialTc)} +} + +func (_c *ParticipantConsumer_OnPartialTc_Call) Run(run func(currentView uint64, partialTc *hotstuff.PartialTcCreated)) *ParticipantConsumer_OnPartialTc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *hotstuff.PartialTcCreated + if args[1] != nil { + arg1 = args[1].(*hotstuff.PartialTcCreated) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnPartialTc_Call) Return() *ParticipantConsumer_OnPartialTc_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnPartialTc_Call) RunAndReturn(run func(currentView uint64, partialTc *hotstuff.PartialTcCreated)) *ParticipantConsumer_OnPartialTc_Call { + _c.Run(run) + return _c +} + +// OnQcTriggeredViewChange provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnQcTriggeredViewChange(oldView uint64, newView uint64, qc *flow.QuorumCertificate) { + _mock.Called(oldView, newView, qc) + return +} + +// ParticipantConsumer_OnQcTriggeredViewChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnQcTriggeredViewChange' +type ParticipantConsumer_OnQcTriggeredViewChange_Call struct { + *mock.Call +} + +// OnQcTriggeredViewChange is a helper method to define mock.On call +// - oldView uint64 +// - newView uint64 +// - qc *flow.QuorumCertificate +func (_e *ParticipantConsumer_Expecter) OnQcTriggeredViewChange(oldView interface{}, newView interface{}, qc interface{}) *ParticipantConsumer_OnQcTriggeredViewChange_Call { + return &ParticipantConsumer_OnQcTriggeredViewChange_Call{Call: _e.mock.On("OnQcTriggeredViewChange", oldView, newView, qc)} +} + +func (_c *ParticipantConsumer_OnQcTriggeredViewChange_Call) Run(run func(oldView uint64, newView uint64, qc *flow.QuorumCertificate)) *ParticipantConsumer_OnQcTriggeredViewChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.QuorumCertificate + if args[2] != nil { + arg2 = args[2].(*flow.QuorumCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnQcTriggeredViewChange_Call) Return() *ParticipantConsumer_OnQcTriggeredViewChange_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnQcTriggeredViewChange_Call) RunAndReturn(run func(oldView uint64, newView uint64, qc *flow.QuorumCertificate)) *ParticipantConsumer_OnQcTriggeredViewChange_Call { + _c.Run(run) + return _c +} + +// OnReceiveProposal provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnReceiveProposal(currentView uint64, proposal *model.SignedProposal) { + _mock.Called(currentView, proposal) + return +} + +// ParticipantConsumer_OnReceiveProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveProposal' +type ParticipantConsumer_OnReceiveProposal_Call struct { + *mock.Call +} + +// OnReceiveProposal is a helper method to define mock.On call +// - currentView uint64 +// - proposal *model.SignedProposal +func (_e *ParticipantConsumer_Expecter) OnReceiveProposal(currentView interface{}, proposal interface{}) *ParticipantConsumer_OnReceiveProposal_Call { + return &ParticipantConsumer_OnReceiveProposal_Call{Call: _e.mock.On("OnReceiveProposal", currentView, proposal)} +} + +func (_c *ParticipantConsumer_OnReceiveProposal_Call) Run(run func(currentView uint64, proposal *model.SignedProposal)) *ParticipantConsumer_OnReceiveProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *model.SignedProposal + if args[1] != nil { + arg1 = args[1].(*model.SignedProposal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnReceiveProposal_Call) Return() *ParticipantConsumer_OnReceiveProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnReceiveProposal_Call) RunAndReturn(run func(currentView uint64, proposal *model.SignedProposal)) *ParticipantConsumer_OnReceiveProposal_Call { + _c.Run(run) + return _c +} + +// OnReceiveQc provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnReceiveQc(currentView uint64, qc *flow.QuorumCertificate) { + _mock.Called(currentView, qc) + return +} + +// ParticipantConsumer_OnReceiveQc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveQc' +type ParticipantConsumer_OnReceiveQc_Call struct { + *mock.Call +} + +// OnReceiveQc is a helper method to define mock.On call +// - currentView uint64 +// - qc *flow.QuorumCertificate +func (_e *ParticipantConsumer_Expecter) OnReceiveQc(currentView interface{}, qc interface{}) *ParticipantConsumer_OnReceiveQc_Call { + return &ParticipantConsumer_OnReceiveQc_Call{Call: _e.mock.On("OnReceiveQc", currentView, qc)} +} + +func (_c *ParticipantConsumer_OnReceiveQc_Call) Run(run func(currentView uint64, qc *flow.QuorumCertificate)) *ParticipantConsumer_OnReceiveQc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnReceiveQc_Call) Return() *ParticipantConsumer_OnReceiveQc_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnReceiveQc_Call) RunAndReturn(run func(currentView uint64, qc *flow.QuorumCertificate)) *ParticipantConsumer_OnReceiveQc_Call { + _c.Run(run) + return _c +} + +// OnReceiveTc provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnReceiveTc(currentView uint64, tc *flow.TimeoutCertificate) { + _mock.Called(currentView, tc) + return +} + +// ParticipantConsumer_OnReceiveTc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiveTc' +type ParticipantConsumer_OnReceiveTc_Call struct { + *mock.Call +} + +// OnReceiveTc is a helper method to define mock.On call +// - currentView uint64 +// - tc *flow.TimeoutCertificate +func (_e *ParticipantConsumer_Expecter) OnReceiveTc(currentView interface{}, tc interface{}) *ParticipantConsumer_OnReceiveTc_Call { + return &ParticipantConsumer_OnReceiveTc_Call{Call: _e.mock.On("OnReceiveTc", currentView, tc)} +} + +func (_c *ParticipantConsumer_OnReceiveTc_Call) Run(run func(currentView uint64, tc *flow.TimeoutCertificate)) *ParticipantConsumer_OnReceiveTc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.TimeoutCertificate + if args[1] != nil { + arg1 = args[1].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnReceiveTc_Call) Return() *ParticipantConsumer_OnReceiveTc_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnReceiveTc_Call) RunAndReturn(run func(currentView uint64, tc *flow.TimeoutCertificate)) *ParticipantConsumer_OnReceiveTc_Call { + _c.Run(run) + return _c +} + +// OnStart provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnStart(currentView uint64) { + _mock.Called(currentView) + return +} + +// ParticipantConsumer_OnStart_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStart' +type ParticipantConsumer_OnStart_Call struct { + *mock.Call +} + +// OnStart is a helper method to define mock.On call +// - currentView uint64 +func (_e *ParticipantConsumer_Expecter) OnStart(currentView interface{}) *ParticipantConsumer_OnStart_Call { + return &ParticipantConsumer_OnStart_Call{Call: _e.mock.On("OnStart", currentView)} +} + +func (_c *ParticipantConsumer_OnStart_Call) Run(run func(currentView uint64)) *ParticipantConsumer_OnStart_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnStart_Call) Return() *ParticipantConsumer_OnStart_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnStart_Call) RunAndReturn(run func(currentView uint64)) *ParticipantConsumer_OnStart_Call { + _c.Run(run) + return _c +} + +// OnStartingTimeout provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnStartingTimeout(timerInfo model.TimerInfo) { + _mock.Called(timerInfo) + return +} + +// ParticipantConsumer_OnStartingTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStartingTimeout' +type ParticipantConsumer_OnStartingTimeout_Call struct { + *mock.Call +} + +// OnStartingTimeout is a helper method to define mock.On call +// - timerInfo model.TimerInfo +func (_e *ParticipantConsumer_Expecter) OnStartingTimeout(timerInfo interface{}) *ParticipantConsumer_OnStartingTimeout_Call { + return &ParticipantConsumer_OnStartingTimeout_Call{Call: _e.mock.On("OnStartingTimeout", timerInfo)} +} + +func (_c *ParticipantConsumer_OnStartingTimeout_Call) Run(run func(timerInfo model.TimerInfo)) *ParticipantConsumer_OnStartingTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 model.TimerInfo + if args[0] != nil { + arg0 = args[0].(model.TimerInfo) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnStartingTimeout_Call) Return() *ParticipantConsumer_OnStartingTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnStartingTimeout_Call) RunAndReturn(run func(timerInfo model.TimerInfo)) *ParticipantConsumer_OnStartingTimeout_Call { + _c.Run(run) + return _c +} + +// OnTcTriggeredViewChange provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnTcTriggeredViewChange(oldView uint64, newView uint64, tc *flow.TimeoutCertificate) { + _mock.Called(oldView, newView, tc) + return +} + +// ParticipantConsumer_OnTcTriggeredViewChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTcTriggeredViewChange' +type ParticipantConsumer_OnTcTriggeredViewChange_Call struct { + *mock.Call +} + +// OnTcTriggeredViewChange is a helper method to define mock.On call +// - oldView uint64 +// - newView uint64 +// - tc *flow.TimeoutCertificate +func (_e *ParticipantConsumer_Expecter) OnTcTriggeredViewChange(oldView interface{}, newView interface{}, tc interface{}) *ParticipantConsumer_OnTcTriggeredViewChange_Call { + return &ParticipantConsumer_OnTcTriggeredViewChange_Call{Call: _e.mock.On("OnTcTriggeredViewChange", oldView, newView, tc)} +} + +func (_c *ParticipantConsumer_OnTcTriggeredViewChange_Call) Run(run func(oldView uint64, newView uint64, tc *flow.TimeoutCertificate)) *ParticipantConsumer_OnTcTriggeredViewChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnTcTriggeredViewChange_Call) Return() *ParticipantConsumer_OnTcTriggeredViewChange_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnTcTriggeredViewChange_Call) RunAndReturn(run func(oldView uint64, newView uint64, tc *flow.TimeoutCertificate)) *ParticipantConsumer_OnTcTriggeredViewChange_Call { + _c.Run(run) + return _c +} + +// OnViewChange provides a mock function for the type ParticipantConsumer +func (_mock *ParticipantConsumer) OnViewChange(oldView uint64, newView uint64) { + _mock.Called(oldView, newView) + return +} + +// ParticipantConsumer_OnViewChange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnViewChange' +type ParticipantConsumer_OnViewChange_Call struct { + *mock.Call +} + +// OnViewChange is a helper method to define mock.On call +// - oldView uint64 +// - newView uint64 +func (_e *ParticipantConsumer_Expecter) OnViewChange(oldView interface{}, newView interface{}) *ParticipantConsumer_OnViewChange_Call { + return &ParticipantConsumer_OnViewChange_Call{Call: _e.mock.On("OnViewChange", oldView, newView)} +} + +func (_c *ParticipantConsumer_OnViewChange_Call) Run(run func(oldView uint64, newView uint64)) *ParticipantConsumer_OnViewChange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantConsumer_OnViewChange_Call) Return() *ParticipantConsumer_OnViewChange_Call { + _c.Call.Return() + return _c +} + +func (_c *ParticipantConsumer_OnViewChange_Call) RunAndReturn(run func(oldView uint64, newView uint64)) *ParticipantConsumer_OnViewChange_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/persister.go b/consensus/hotstuff/mocks/persister.go index 49e3a4ca5f9..7c02bc05d57 100644 --- a/consensus/hotstuff/mocks/persister.go +++ b/consensus/hotstuff/mocks/persister.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" mock "github.com/stretchr/testify/mock" ) +// NewPersister creates a new instance of Persister. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPersister(t interface { + mock.TestingT + Cleanup(func()) +}) *Persister { + mock := &Persister{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Persister is an autogenerated mock type for the Persister type type Persister struct { mock.Mock } -// GetLivenessData provides a mock function with no fields -func (_m *Persister) GetLivenessData() (*hotstuff.LivenessData, error) { - ret := _m.Called() +type Persister_Expecter struct { + mock *mock.Mock +} + +func (_m *Persister) EXPECT() *Persister_Expecter { + return &Persister_Expecter{mock: &_m.Mock} +} + +// GetLivenessData provides a mock function for the type Persister +func (_mock *Persister) GetLivenessData() (*hotstuff.LivenessData, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetLivenessData") @@ -22,29 +46,54 @@ func (_m *Persister) GetLivenessData() (*hotstuff.LivenessData, error) { var r0 *hotstuff.LivenessData var r1 error - if rf, ok := ret.Get(0).(func() (*hotstuff.LivenessData, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*hotstuff.LivenessData, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *hotstuff.LivenessData); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *hotstuff.LivenessData); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*hotstuff.LivenessData) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSafetyData provides a mock function with no fields -func (_m *Persister) GetSafetyData() (*hotstuff.SafetyData, error) { - ret := _m.Called() +// Persister_GetLivenessData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLivenessData' +type Persister_GetLivenessData_Call struct { + *mock.Call +} + +// GetLivenessData is a helper method to define mock.On call +func (_e *Persister_Expecter) GetLivenessData() *Persister_GetLivenessData_Call { + return &Persister_GetLivenessData_Call{Call: _e.mock.On("GetLivenessData")} +} + +func (_c *Persister_GetLivenessData_Call) Run(run func()) *Persister_GetLivenessData_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Persister_GetLivenessData_Call) Return(livenessData *hotstuff.LivenessData, err error) *Persister_GetLivenessData_Call { + _c.Call.Return(livenessData, err) + return _c +} + +func (_c *Persister_GetLivenessData_Call) RunAndReturn(run func() (*hotstuff.LivenessData, error)) *Persister_GetLivenessData_Call { + _c.Call.Return(run) + return _c +} + +// GetSafetyData provides a mock function for the type Persister +func (_mock *Persister) GetSafetyData() (*hotstuff.SafetyData, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetSafetyData") @@ -52,72 +101,149 @@ func (_m *Persister) GetSafetyData() (*hotstuff.SafetyData, error) { var r0 *hotstuff.SafetyData var r1 error - if rf, ok := ret.Get(0).(func() (*hotstuff.SafetyData, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*hotstuff.SafetyData, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *hotstuff.SafetyData); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *hotstuff.SafetyData); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*hotstuff.SafetyData) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// PutLivenessData provides a mock function with given fields: livenessData -func (_m *Persister) PutLivenessData(livenessData *hotstuff.LivenessData) error { - ret := _m.Called(livenessData) +// Persister_GetSafetyData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSafetyData' +type Persister_GetSafetyData_Call struct { + *mock.Call +} + +// GetSafetyData is a helper method to define mock.On call +func (_e *Persister_Expecter) GetSafetyData() *Persister_GetSafetyData_Call { + return &Persister_GetSafetyData_Call{Call: _e.mock.On("GetSafetyData")} +} + +func (_c *Persister_GetSafetyData_Call) Run(run func()) *Persister_GetSafetyData_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Persister_GetSafetyData_Call) Return(safetyData *hotstuff.SafetyData, err error) *Persister_GetSafetyData_Call { + _c.Call.Return(safetyData, err) + return _c +} + +func (_c *Persister_GetSafetyData_Call) RunAndReturn(run func() (*hotstuff.SafetyData, error)) *Persister_GetSafetyData_Call { + _c.Call.Return(run) + return _c +} + +// PutLivenessData provides a mock function for the type Persister +func (_mock *Persister) PutLivenessData(livenessData *hotstuff.LivenessData) error { + ret := _mock.Called(livenessData) if len(ret) == 0 { panic("no return value specified for PutLivenessData") } var r0 error - if rf, ok := ret.Get(0).(func(*hotstuff.LivenessData) error); ok { - r0 = rf(livenessData) + if returnFunc, ok := ret.Get(0).(func(*hotstuff.LivenessData) error); ok { + r0 = returnFunc(livenessData) } else { r0 = ret.Error(0) } - return r0 } -// PutSafetyData provides a mock function with given fields: safetyData -func (_m *Persister) PutSafetyData(safetyData *hotstuff.SafetyData) error { - ret := _m.Called(safetyData) +// Persister_PutLivenessData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PutLivenessData' +type Persister_PutLivenessData_Call struct { + *mock.Call +} + +// PutLivenessData is a helper method to define mock.On call +// - livenessData *hotstuff.LivenessData +func (_e *Persister_Expecter) PutLivenessData(livenessData interface{}) *Persister_PutLivenessData_Call { + return &Persister_PutLivenessData_Call{Call: _e.mock.On("PutLivenessData", livenessData)} +} + +func (_c *Persister_PutLivenessData_Call) Run(run func(livenessData *hotstuff.LivenessData)) *Persister_PutLivenessData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *hotstuff.LivenessData + if args[0] != nil { + arg0 = args[0].(*hotstuff.LivenessData) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Persister_PutLivenessData_Call) Return(err error) *Persister_PutLivenessData_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Persister_PutLivenessData_Call) RunAndReturn(run func(livenessData *hotstuff.LivenessData) error) *Persister_PutLivenessData_Call { + _c.Call.Return(run) + return _c +} + +// PutSafetyData provides a mock function for the type Persister +func (_mock *Persister) PutSafetyData(safetyData *hotstuff.SafetyData) error { + ret := _mock.Called(safetyData) if len(ret) == 0 { panic("no return value specified for PutSafetyData") } var r0 error - if rf, ok := ret.Get(0).(func(*hotstuff.SafetyData) error); ok { - r0 = rf(safetyData) + if returnFunc, ok := ret.Get(0).(func(*hotstuff.SafetyData) error); ok { + r0 = returnFunc(safetyData) } else { r0 = ret.Error(0) } - return r0 } -// NewPersister creates a new instance of Persister. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPersister(t interface { - mock.TestingT - Cleanup(func()) -}) *Persister { - mock := &Persister{} - mock.Mock.Test(t) +// Persister_PutSafetyData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PutSafetyData' +type Persister_PutSafetyData_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// PutSafetyData is a helper method to define mock.On call +// - safetyData *hotstuff.SafetyData +func (_e *Persister_Expecter) PutSafetyData(safetyData interface{}) *Persister_PutSafetyData_Call { + return &Persister_PutSafetyData_Call{Call: _e.mock.On("PutSafetyData", safetyData)} +} - return mock +func (_c *Persister_PutSafetyData_Call) Run(run func(safetyData *hotstuff.SafetyData)) *Persister_PutSafetyData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *hotstuff.SafetyData + if args[0] != nil { + arg0 = args[0].(*hotstuff.SafetyData) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Persister_PutSafetyData_Call) Return(err error) *Persister_PutSafetyData_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Persister_PutSafetyData_Call) RunAndReturn(run func(safetyData *hotstuff.SafetyData) error) *Persister_PutSafetyData_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/persister_reader.go b/consensus/hotstuff/mocks/persister_reader.go index 54146f89594..0a097254c7d 100644 --- a/consensus/hotstuff/mocks/persister_reader.go +++ b/consensus/hotstuff/mocks/persister_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" mock "github.com/stretchr/testify/mock" ) +// NewPersisterReader creates a new instance of PersisterReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPersisterReader(t interface { + mock.TestingT + Cleanup(func()) +}) *PersisterReader { + mock := &PersisterReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // PersisterReader is an autogenerated mock type for the PersisterReader type type PersisterReader struct { mock.Mock } -// GetLivenessData provides a mock function with no fields -func (_m *PersisterReader) GetLivenessData() (*hotstuff.LivenessData, error) { - ret := _m.Called() +type PersisterReader_Expecter struct { + mock *mock.Mock +} + +func (_m *PersisterReader) EXPECT() *PersisterReader_Expecter { + return &PersisterReader_Expecter{mock: &_m.Mock} +} + +// GetLivenessData provides a mock function for the type PersisterReader +func (_mock *PersisterReader) GetLivenessData() (*hotstuff.LivenessData, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetLivenessData") @@ -22,29 +46,54 @@ func (_m *PersisterReader) GetLivenessData() (*hotstuff.LivenessData, error) { var r0 *hotstuff.LivenessData var r1 error - if rf, ok := ret.Get(0).(func() (*hotstuff.LivenessData, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*hotstuff.LivenessData, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *hotstuff.LivenessData); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *hotstuff.LivenessData); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*hotstuff.LivenessData) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSafetyData provides a mock function with no fields -func (_m *PersisterReader) GetSafetyData() (*hotstuff.SafetyData, error) { - ret := _m.Called() +// PersisterReader_GetLivenessData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLivenessData' +type PersisterReader_GetLivenessData_Call struct { + *mock.Call +} + +// GetLivenessData is a helper method to define mock.On call +func (_e *PersisterReader_Expecter) GetLivenessData() *PersisterReader_GetLivenessData_Call { + return &PersisterReader_GetLivenessData_Call{Call: _e.mock.On("GetLivenessData")} +} + +func (_c *PersisterReader_GetLivenessData_Call) Run(run func()) *PersisterReader_GetLivenessData_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PersisterReader_GetLivenessData_Call) Return(livenessData *hotstuff.LivenessData, err error) *PersisterReader_GetLivenessData_Call { + _c.Call.Return(livenessData, err) + return _c +} + +func (_c *PersisterReader_GetLivenessData_Call) RunAndReturn(run func() (*hotstuff.LivenessData, error)) *PersisterReader_GetLivenessData_Call { + _c.Call.Return(run) + return _c +} + +// GetSafetyData provides a mock function for the type PersisterReader +func (_mock *PersisterReader) GetSafetyData() (*hotstuff.SafetyData, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetSafetyData") @@ -52,36 +101,47 @@ func (_m *PersisterReader) GetSafetyData() (*hotstuff.SafetyData, error) { var r0 *hotstuff.SafetyData var r1 error - if rf, ok := ret.Get(0).(func() (*hotstuff.SafetyData, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*hotstuff.SafetyData, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *hotstuff.SafetyData); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *hotstuff.SafetyData); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*hotstuff.SafetyData) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewPersisterReader creates a new instance of PersisterReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPersisterReader(t interface { - mock.TestingT - Cleanup(func()) -}) *PersisterReader { - mock := &PersisterReader{} - mock.Mock.Test(t) +// PersisterReader_GetSafetyData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSafetyData' +type PersisterReader_GetSafetyData_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetSafetyData is a helper method to define mock.On call +func (_e *PersisterReader_Expecter) GetSafetyData() *PersisterReader_GetSafetyData_Call { + return &PersisterReader_GetSafetyData_Call{Call: _e.mock.On("GetSafetyData")} +} - return mock +func (_c *PersisterReader_GetSafetyData_Call) Run(run func()) *PersisterReader_GetSafetyData_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PersisterReader_GetSafetyData_Call) Return(safetyData *hotstuff.SafetyData, err error) *PersisterReader_GetSafetyData_Call { + _c.Call.Return(safetyData, err) + return _c +} + +func (_c *PersisterReader_GetSafetyData_Call) RunAndReturn(run func() (*hotstuff.SafetyData, error)) *PersisterReader_GetSafetyData_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/proposal_duration_provider.go b/consensus/hotstuff/mocks/proposal_duration_provider.go index f1f5a4b6e2e..8e258aa303c 100644 --- a/consensus/hotstuff/mocks/proposal_duration_provider.go +++ b/consensus/hotstuff/mocks/proposal_duration_provider.go @@ -1,48 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" + "time" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - time "time" ) +// NewProposalDurationProvider creates a new instance of ProposalDurationProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProposalDurationProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *ProposalDurationProvider { + mock := &ProposalDurationProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ProposalDurationProvider is an autogenerated mock type for the ProposalDurationProvider type type ProposalDurationProvider struct { mock.Mock } -// TargetPublicationTime provides a mock function with given fields: proposalView, timeViewEntered, parentBlockId -func (_m *ProposalDurationProvider) TargetPublicationTime(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier) time.Time { - ret := _m.Called(proposalView, timeViewEntered, parentBlockId) +type ProposalDurationProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *ProposalDurationProvider) EXPECT() *ProposalDurationProvider_Expecter { + return &ProposalDurationProvider_Expecter{mock: &_m.Mock} +} + +// TargetPublicationTime provides a mock function for the type ProposalDurationProvider +func (_mock *ProposalDurationProvider) TargetPublicationTime(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier) time.Time { + ret := _mock.Called(proposalView, timeViewEntered, parentBlockId) if len(ret) == 0 { panic("no return value specified for TargetPublicationTime") } var r0 time.Time - if rf, ok := ret.Get(0).(func(uint64, time.Time, flow.Identifier) time.Time); ok { - r0 = rf(proposalView, timeViewEntered, parentBlockId) + if returnFunc, ok := ret.Get(0).(func(uint64, time.Time, flow.Identifier) time.Time); ok { + r0 = returnFunc(proposalView, timeViewEntered, parentBlockId) } else { r0 = ret.Get(0).(time.Time) } - return r0 } -// NewProposalDurationProvider creates a new instance of ProposalDurationProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProposalDurationProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *ProposalDurationProvider { - mock := &ProposalDurationProvider{} - mock.Mock.Test(t) +// ProposalDurationProvider_TargetPublicationTime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TargetPublicationTime' +type ProposalDurationProvider_TargetPublicationTime_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TargetPublicationTime is a helper method to define mock.On call +// - proposalView uint64 +// - timeViewEntered time.Time +// - parentBlockId flow.Identifier +func (_e *ProposalDurationProvider_Expecter) TargetPublicationTime(proposalView interface{}, timeViewEntered interface{}, parentBlockId interface{}) *ProposalDurationProvider_TargetPublicationTime_Call { + return &ProposalDurationProvider_TargetPublicationTime_Call{Call: _e.mock.On("TargetPublicationTime", proposalView, timeViewEntered, parentBlockId)} +} - return mock +func (_c *ProposalDurationProvider_TargetPublicationTime_Call) Run(run func(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier)) *ProposalDurationProvider_TargetPublicationTime_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ProposalDurationProvider_TargetPublicationTime_Call) Return(time1 time.Time) *ProposalDurationProvider_TargetPublicationTime_Call { + _c.Call.Return(time1) + return _c +} + +func (_c *ProposalDurationProvider_TargetPublicationTime_Call) RunAndReturn(run func(proposalView uint64, timeViewEntered time.Time, parentBlockId flow.Identifier) time.Time) *ProposalDurationProvider_TargetPublicationTime_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/proposal_violation_consumer.go b/consensus/hotstuff/mocks/proposal_violation_consumer.go index 597b860eb08..d30af118c9c 100644 --- a/consensus/hotstuff/mocks/proposal_violation_consumer.go +++ b/consensus/hotstuff/mocks/proposal_violation_consumer.go @@ -1,30 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) -// ProposalViolationConsumer is an autogenerated mock type for the ProposalViolationConsumer type -type ProposalViolationConsumer struct { - mock.Mock -} - -// OnDoubleProposeDetected provides a mock function with given fields: _a0, _a1 -func (_m *ProposalViolationConsumer) OnDoubleProposeDetected(_a0 *model.Block, _a1 *model.Block) { - _m.Called(_a0, _a1) -} - -// OnInvalidBlockDetected provides a mock function with given fields: err -func (_m *ProposalViolationConsumer) OnInvalidBlockDetected(err flow.Slashable[model.InvalidProposalError]) { - _m.Called(err) -} - // NewProposalViolationConsumer creates a new instance of ProposalViolationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewProposalViolationConsumer(t interface { @@ -38,3 +23,102 @@ func NewProposalViolationConsumer(t interface { return mock } + +// ProposalViolationConsumer is an autogenerated mock type for the ProposalViolationConsumer type +type ProposalViolationConsumer struct { + mock.Mock +} + +type ProposalViolationConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *ProposalViolationConsumer) EXPECT() *ProposalViolationConsumer_Expecter { + return &ProposalViolationConsumer_Expecter{mock: &_m.Mock} +} + +// OnDoubleProposeDetected provides a mock function for the type ProposalViolationConsumer +func (_mock *ProposalViolationConsumer) OnDoubleProposeDetected(block *model.Block, block1 *model.Block) { + _mock.Called(block, block1) + return +} + +// ProposalViolationConsumer_OnDoubleProposeDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDoubleProposeDetected' +type ProposalViolationConsumer_OnDoubleProposeDetected_Call struct { + *mock.Call +} + +// OnDoubleProposeDetected is a helper method to define mock.On call +// - block *model.Block +// - block1 *model.Block +func (_e *ProposalViolationConsumer_Expecter) OnDoubleProposeDetected(block interface{}, block1 interface{}) *ProposalViolationConsumer_OnDoubleProposeDetected_Call { + return &ProposalViolationConsumer_OnDoubleProposeDetected_Call{Call: _e.mock.On("OnDoubleProposeDetected", block, block1)} +} + +func (_c *ProposalViolationConsumer_OnDoubleProposeDetected_Call) Run(run func(block *model.Block, block1 *model.Block)) *ProposalViolationConsumer_OnDoubleProposeDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + var arg1 *model.Block + if args[1] != nil { + arg1 = args[1].(*model.Block) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ProposalViolationConsumer_OnDoubleProposeDetected_Call) Return() *ProposalViolationConsumer_OnDoubleProposeDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *ProposalViolationConsumer_OnDoubleProposeDetected_Call) RunAndReturn(run func(block *model.Block, block1 *model.Block)) *ProposalViolationConsumer_OnDoubleProposeDetected_Call { + _c.Run(run) + return _c +} + +// OnInvalidBlockDetected provides a mock function for the type ProposalViolationConsumer +func (_mock *ProposalViolationConsumer) OnInvalidBlockDetected(err flow.Slashable[model.InvalidProposalError]) { + _mock.Called(err) + return +} + +// ProposalViolationConsumer_OnInvalidBlockDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidBlockDetected' +type ProposalViolationConsumer_OnInvalidBlockDetected_Call struct { + *mock.Call +} + +// OnInvalidBlockDetected is a helper method to define mock.On call +// - err flow.Slashable[model.InvalidProposalError] +func (_e *ProposalViolationConsumer_Expecter) OnInvalidBlockDetected(err interface{}) *ProposalViolationConsumer_OnInvalidBlockDetected_Call { + return &ProposalViolationConsumer_OnInvalidBlockDetected_Call{Call: _e.mock.On("OnInvalidBlockDetected", err)} +} + +func (_c *ProposalViolationConsumer_OnInvalidBlockDetected_Call) Run(run func(err flow.Slashable[model.InvalidProposalError])) *ProposalViolationConsumer_OnInvalidBlockDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[model.InvalidProposalError] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[model.InvalidProposalError]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProposalViolationConsumer_OnInvalidBlockDetected_Call) Return() *ProposalViolationConsumer_OnInvalidBlockDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *ProposalViolationConsumer_OnInvalidBlockDetected_Call) RunAndReturn(run func(err flow.Slashable[model.InvalidProposalError])) *ProposalViolationConsumer_OnInvalidBlockDetected_Call { + _c.Run(run) + return _c +} diff --git a/consensus/hotstuff/mocks/random_beacon_inspector.go b/consensus/hotstuff/mocks/random_beacon_inspector.go index 1c08aab162c..da8d6a4676c 100644 --- a/consensus/hotstuff/mocks/random_beacon_inspector.go +++ b/consensus/hotstuff/mocks/random_beacon_inspector.go @@ -1,39 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - crypto "github.com/onflow/crypto" - + "github.com/onflow/crypto" mock "github.com/stretchr/testify/mock" ) +// NewRandomBeaconInspector creates a new instance of RandomBeaconInspector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRandomBeaconInspector(t interface { + mock.TestingT + Cleanup(func()) +}) *RandomBeaconInspector { + mock := &RandomBeaconInspector{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RandomBeaconInspector is an autogenerated mock type for the RandomBeaconInspector type type RandomBeaconInspector struct { mock.Mock } -// EnoughShares provides a mock function with no fields -func (_m *RandomBeaconInspector) EnoughShares() bool { - ret := _m.Called() +type RandomBeaconInspector_Expecter struct { + mock *mock.Mock +} + +func (_m *RandomBeaconInspector) EXPECT() *RandomBeaconInspector_Expecter { + return &RandomBeaconInspector_Expecter{mock: &_m.Mock} +} + +// EnoughShares provides a mock function for the type RandomBeaconInspector +func (_mock *RandomBeaconInspector) EnoughShares() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EnoughShares") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// Reconstruct provides a mock function with no fields -func (_m *RandomBeaconInspector) Reconstruct() (crypto.Signature, error) { - ret := _m.Called() +// RandomBeaconInspector_EnoughShares_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EnoughShares' +type RandomBeaconInspector_EnoughShares_Call struct { + *mock.Call +} + +// EnoughShares is a helper method to define mock.On call +func (_e *RandomBeaconInspector_Expecter) EnoughShares() *RandomBeaconInspector_EnoughShares_Call { + return &RandomBeaconInspector_EnoughShares_Call{Call: _e.mock.On("EnoughShares")} +} + +func (_c *RandomBeaconInspector_EnoughShares_Call) Run(run func()) *RandomBeaconInspector_EnoughShares_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RandomBeaconInspector_EnoughShares_Call) Return(b bool) *RandomBeaconInspector_EnoughShares_Call { + _c.Call.Return(b) + return _c +} + +func (_c *RandomBeaconInspector_EnoughShares_Call) RunAndReturn(run func() bool) *RandomBeaconInspector_EnoughShares_Call { + _c.Call.Return(run) + return _c +} + +// Reconstruct provides a mock function for the type RandomBeaconInspector +func (_mock *RandomBeaconInspector) Reconstruct() (crypto.Signature, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Reconstruct") @@ -41,29 +90,54 @@ func (_m *RandomBeaconInspector) Reconstruct() (crypto.Signature, error) { var r0 crypto.Signature var r1 error - if rf, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() crypto.Signature); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() crypto.Signature); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.Signature) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// TrustedAdd provides a mock function with given fields: signerIndex, share -func (_m *RandomBeaconInspector) TrustedAdd(signerIndex int, share crypto.Signature) (bool, error) { - ret := _m.Called(signerIndex, share) +// RandomBeaconInspector_Reconstruct_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reconstruct' +type RandomBeaconInspector_Reconstruct_Call struct { + *mock.Call +} + +// Reconstruct is a helper method to define mock.On call +func (_e *RandomBeaconInspector_Expecter) Reconstruct() *RandomBeaconInspector_Reconstruct_Call { + return &RandomBeaconInspector_Reconstruct_Call{Call: _e.mock.On("Reconstruct")} +} + +func (_c *RandomBeaconInspector_Reconstruct_Call) Run(run func()) *RandomBeaconInspector_Reconstruct_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RandomBeaconInspector_Reconstruct_Call) Return(signature crypto.Signature, err error) *RandomBeaconInspector_Reconstruct_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *RandomBeaconInspector_Reconstruct_Call) RunAndReturn(run func() (crypto.Signature, error)) *RandomBeaconInspector_Reconstruct_Call { + _c.Call.Return(run) + return _c +} + +// TrustedAdd provides a mock function for the type RandomBeaconInspector +func (_mock *RandomBeaconInspector) TrustedAdd(signerIndex int, share crypto.Signature) (bool, error) { + ret := _mock.Called(signerIndex, share) if len(ret) == 0 { panic("no return value specified for TrustedAdd") @@ -71,52 +145,115 @@ func (_m *RandomBeaconInspector) TrustedAdd(signerIndex int, share crypto.Signat var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { - return rf(signerIndex, share) + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { + return returnFunc(signerIndex, share) } - if rf, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { - r0 = rf(signerIndex, share) + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { + r0 = returnFunc(signerIndex, share) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { - r1 = rf(signerIndex, share) + if returnFunc, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { + r1 = returnFunc(signerIndex, share) } else { r1 = ret.Error(1) } - return r0, r1 } -// Verify provides a mock function with given fields: signerIndex, share -func (_m *RandomBeaconInspector) Verify(signerIndex int, share crypto.Signature) error { - ret := _m.Called(signerIndex, share) +// RandomBeaconInspector_TrustedAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TrustedAdd' +type RandomBeaconInspector_TrustedAdd_Call struct { + *mock.Call +} + +// TrustedAdd is a helper method to define mock.On call +// - signerIndex int +// - share crypto.Signature +func (_e *RandomBeaconInspector_Expecter) TrustedAdd(signerIndex interface{}, share interface{}) *RandomBeaconInspector_TrustedAdd_Call { + return &RandomBeaconInspector_TrustedAdd_Call{Call: _e.mock.On("TrustedAdd", signerIndex, share)} +} + +func (_c *RandomBeaconInspector_TrustedAdd_Call) Run(run func(signerIndex int, share crypto.Signature)) *RandomBeaconInspector_TrustedAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RandomBeaconInspector_TrustedAdd_Call) Return(enoughshares bool, exception error) *RandomBeaconInspector_TrustedAdd_Call { + _c.Call.Return(enoughshares, exception) + return _c +} + +func (_c *RandomBeaconInspector_TrustedAdd_Call) RunAndReturn(run func(signerIndex int, share crypto.Signature) (bool, error)) *RandomBeaconInspector_TrustedAdd_Call { + _c.Call.Return(run) + return _c +} + +// Verify provides a mock function for the type RandomBeaconInspector +func (_mock *RandomBeaconInspector) Verify(signerIndex int, share crypto.Signature) error { + ret := _mock.Called(signerIndex, share) if len(ret) == 0 { panic("no return value specified for Verify") } var r0 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) error); ok { - r0 = rf(signerIndex, share) + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) error); ok { + r0 = returnFunc(signerIndex, share) } else { r0 = ret.Error(0) } - return r0 } -// NewRandomBeaconInspector creates a new instance of RandomBeaconInspector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRandomBeaconInspector(t interface { - mock.TestingT - Cleanup(func()) -}) *RandomBeaconInspector { - mock := &RandomBeaconInspector{} - mock.Mock.Test(t) +// RandomBeaconInspector_Verify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Verify' +type RandomBeaconInspector_Verify_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Verify is a helper method to define mock.On call +// - signerIndex int +// - share crypto.Signature +func (_e *RandomBeaconInspector_Expecter) Verify(signerIndex interface{}, share interface{}) *RandomBeaconInspector_Verify_Call { + return &RandomBeaconInspector_Verify_Call{Call: _e.mock.On("Verify", signerIndex, share)} +} - return mock +func (_c *RandomBeaconInspector_Verify_Call) Run(run func(signerIndex int, share crypto.Signature)) *RandomBeaconInspector_Verify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RandomBeaconInspector_Verify_Call) Return(err error) *RandomBeaconInspector_Verify_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RandomBeaconInspector_Verify_Call) RunAndReturn(run func(signerIndex int, share crypto.Signature) error) *RandomBeaconInspector_Verify_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/random_beacon_reconstructor.go b/consensus/hotstuff/mocks/random_beacon_reconstructor.go index 579c60aa510..11ece48c187 100644 --- a/consensus/hotstuff/mocks/random_beacon_reconstructor.go +++ b/consensus/hotstuff/mocks/random_beacon_reconstructor.go @@ -1,40 +1,89 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewRandomBeaconReconstructor creates a new instance of RandomBeaconReconstructor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRandomBeaconReconstructor(t interface { + mock.TestingT + Cleanup(func()) +}) *RandomBeaconReconstructor { + mock := &RandomBeaconReconstructor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RandomBeaconReconstructor is an autogenerated mock type for the RandomBeaconReconstructor type type RandomBeaconReconstructor struct { mock.Mock } -// EnoughShares provides a mock function with no fields -func (_m *RandomBeaconReconstructor) EnoughShares() bool { - ret := _m.Called() +type RandomBeaconReconstructor_Expecter struct { + mock *mock.Mock +} + +func (_m *RandomBeaconReconstructor) EXPECT() *RandomBeaconReconstructor_Expecter { + return &RandomBeaconReconstructor_Expecter{mock: &_m.Mock} +} + +// EnoughShares provides a mock function for the type RandomBeaconReconstructor +func (_mock *RandomBeaconReconstructor) EnoughShares() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EnoughShares") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// Reconstruct provides a mock function with no fields -func (_m *RandomBeaconReconstructor) Reconstruct() (crypto.Signature, error) { - ret := _m.Called() +// RandomBeaconReconstructor_EnoughShares_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EnoughShares' +type RandomBeaconReconstructor_EnoughShares_Call struct { + *mock.Call +} + +// EnoughShares is a helper method to define mock.On call +func (_e *RandomBeaconReconstructor_Expecter) EnoughShares() *RandomBeaconReconstructor_EnoughShares_Call { + return &RandomBeaconReconstructor_EnoughShares_Call{Call: _e.mock.On("EnoughShares")} +} + +func (_c *RandomBeaconReconstructor_EnoughShares_Call) Run(run func()) *RandomBeaconReconstructor_EnoughShares_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RandomBeaconReconstructor_EnoughShares_Call) Return(b bool) *RandomBeaconReconstructor_EnoughShares_Call { + _c.Call.Return(b) + return _c +} + +func (_c *RandomBeaconReconstructor_EnoughShares_Call) RunAndReturn(run func() bool) *RandomBeaconReconstructor_EnoughShares_Call { + _c.Call.Return(run) + return _c +} + +// Reconstruct provides a mock function for the type RandomBeaconReconstructor +func (_mock *RandomBeaconReconstructor) Reconstruct() (crypto.Signature, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Reconstruct") @@ -42,29 +91,54 @@ func (_m *RandomBeaconReconstructor) Reconstruct() (crypto.Signature, error) { var r0 crypto.Signature var r1 error - if rf, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() crypto.Signature); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() crypto.Signature); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.Signature) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// TrustedAdd provides a mock function with given fields: signerID, sig -func (_m *RandomBeaconReconstructor) TrustedAdd(signerID flow.Identifier, sig crypto.Signature) (bool, error) { - ret := _m.Called(signerID, sig) +// RandomBeaconReconstructor_Reconstruct_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reconstruct' +type RandomBeaconReconstructor_Reconstruct_Call struct { + *mock.Call +} + +// Reconstruct is a helper method to define mock.On call +func (_e *RandomBeaconReconstructor_Expecter) Reconstruct() *RandomBeaconReconstructor_Reconstruct_Call { + return &RandomBeaconReconstructor_Reconstruct_Call{Call: _e.mock.On("Reconstruct")} +} + +func (_c *RandomBeaconReconstructor_Reconstruct_Call) Run(run func()) *RandomBeaconReconstructor_Reconstruct_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RandomBeaconReconstructor_Reconstruct_Call) Return(signature crypto.Signature, err error) *RandomBeaconReconstructor_Reconstruct_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *RandomBeaconReconstructor_Reconstruct_Call) RunAndReturn(run func() (crypto.Signature, error)) *RandomBeaconReconstructor_Reconstruct_Call { + _c.Call.Return(run) + return _c +} + +// TrustedAdd provides a mock function for the type RandomBeaconReconstructor +func (_mock *RandomBeaconReconstructor) TrustedAdd(signerID flow.Identifier, sig crypto.Signature) (bool, error) { + ret := _mock.Called(signerID, sig) if len(ret) == 0 { panic("no return value specified for TrustedAdd") @@ -72,52 +146,115 @@ func (_m *RandomBeaconReconstructor) TrustedAdd(signerID flow.Identifier, sig cr var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) (bool, error)); ok { - return rf(signerID, sig) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) (bool, error)); ok { + return returnFunc(signerID, sig) } - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) bool); ok { - r0 = rf(signerID, sig) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) bool); ok { + r0 = returnFunc(signerID, sig) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(flow.Identifier, crypto.Signature) error); ok { - r1 = rf(signerID, sig) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, crypto.Signature) error); ok { + r1 = returnFunc(signerID, sig) } else { r1 = ret.Error(1) } - return r0, r1 } -// Verify provides a mock function with given fields: signerID, sig -func (_m *RandomBeaconReconstructor) Verify(signerID flow.Identifier, sig crypto.Signature) error { - ret := _m.Called(signerID, sig) +// RandomBeaconReconstructor_TrustedAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TrustedAdd' +type RandomBeaconReconstructor_TrustedAdd_Call struct { + *mock.Call +} + +// TrustedAdd is a helper method to define mock.On call +// - signerID flow.Identifier +// - sig crypto.Signature +func (_e *RandomBeaconReconstructor_Expecter) TrustedAdd(signerID interface{}, sig interface{}) *RandomBeaconReconstructor_TrustedAdd_Call { + return &RandomBeaconReconstructor_TrustedAdd_Call{Call: _e.mock.On("TrustedAdd", signerID, sig)} +} + +func (_c *RandomBeaconReconstructor_TrustedAdd_Call) Run(run func(signerID flow.Identifier, sig crypto.Signature)) *RandomBeaconReconstructor_TrustedAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RandomBeaconReconstructor_TrustedAdd_Call) Return(EnoughShares bool, err error) *RandomBeaconReconstructor_TrustedAdd_Call { + _c.Call.Return(EnoughShares, err) + return _c +} + +func (_c *RandomBeaconReconstructor_TrustedAdd_Call) RunAndReturn(run func(signerID flow.Identifier, sig crypto.Signature) (bool, error)) *RandomBeaconReconstructor_TrustedAdd_Call { + _c.Call.Return(run) + return _c +} + +// Verify provides a mock function for the type RandomBeaconReconstructor +func (_mock *RandomBeaconReconstructor) Verify(signerID flow.Identifier, sig crypto.Signature) error { + ret := _mock.Called(signerID, sig) if len(ret) == 0 { panic("no return value specified for Verify") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) error); ok { - r0 = rf(signerID, sig) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) error); ok { + r0 = returnFunc(signerID, sig) } else { r0 = ret.Error(0) } - return r0 } -// NewRandomBeaconReconstructor creates a new instance of RandomBeaconReconstructor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRandomBeaconReconstructor(t interface { - mock.TestingT - Cleanup(func()) -}) *RandomBeaconReconstructor { - mock := &RandomBeaconReconstructor{} - mock.Mock.Test(t) +// RandomBeaconReconstructor_Verify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Verify' +type RandomBeaconReconstructor_Verify_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Verify is a helper method to define mock.On call +// - signerID flow.Identifier +// - sig crypto.Signature +func (_e *RandomBeaconReconstructor_Expecter) Verify(signerID interface{}, sig interface{}) *RandomBeaconReconstructor_Verify_Call { + return &RandomBeaconReconstructor_Verify_Call{Call: _e.mock.On("Verify", signerID, sig)} +} - return mock +func (_c *RandomBeaconReconstructor_Verify_Call) Run(run func(signerID flow.Identifier, sig crypto.Signature)) *RandomBeaconReconstructor_Verify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RandomBeaconReconstructor_Verify_Call) Return(err error) *RandomBeaconReconstructor_Verify_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RandomBeaconReconstructor_Verify_Call) RunAndReturn(run func(signerID flow.Identifier, sig crypto.Signature) error) *RandomBeaconReconstructor_Verify_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/replicas.go b/consensus/hotstuff/mocks/replicas.go index 37d946d69c9..28b915b4a1c 100644 --- a/consensus/hotstuff/mocks/replicas.go +++ b/consensus/hotstuff/mocks/replicas.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewReplicas creates a new instance of Replicas. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReplicas(t interface { + mock.TestingT + Cleanup(func()) +}) *Replicas { + mock := &Replicas{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Replicas is an autogenerated mock type for the Replicas type type Replicas struct { mock.Mock } -// DKG provides a mock function with given fields: view -func (_m *Replicas) DKG(view uint64) (hotstuff.DKG, error) { - ret := _m.Called(view) +type Replicas_Expecter struct { + mock *mock.Mock +} + +func (_m *Replicas) EXPECT() *Replicas_Expecter { + return &Replicas_Expecter{mock: &_m.Mock} +} + +// DKG provides a mock function for the type Replicas +func (_mock *Replicas) DKG(view uint64) (hotstuff.DKG, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for DKG") @@ -24,29 +47,61 @@ func (_m *Replicas) DKG(view uint64) (hotstuff.DKG, error) { var r0 hotstuff.DKG var r1 error - if rf, ok := ret.Get(0).(func(uint64) (hotstuff.DKG, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (hotstuff.DKG, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) hotstuff.DKG); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) hotstuff.DKG); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(hotstuff.DKG) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// IdentitiesByEpoch provides a mock function with given fields: view -func (_m *Replicas) IdentitiesByEpoch(view uint64) (flow.IdentitySkeletonList, error) { - ret := _m.Called(view) +// Replicas_DKG_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DKG' +type Replicas_DKG_Call struct { + *mock.Call +} + +// DKG is a helper method to define mock.On call +// - view uint64 +func (_e *Replicas_Expecter) DKG(view interface{}) *Replicas_DKG_Call { + return &Replicas_DKG_Call{Call: _e.mock.On("DKG", view)} +} + +func (_c *Replicas_DKG_Call) Run(run func(view uint64)) *Replicas_DKG_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Replicas_DKG_Call) Return(dKG hotstuff.DKG, err error) *Replicas_DKG_Call { + _c.Call.Return(dKG, err) + return _c +} + +func (_c *Replicas_DKG_Call) RunAndReturn(run func(view uint64) (hotstuff.DKG, error)) *Replicas_DKG_Call { + _c.Call.Return(run) + return _c +} + +// IdentitiesByEpoch provides a mock function for the type Replicas +func (_mock *Replicas) IdentitiesByEpoch(view uint64) (flow.IdentitySkeletonList, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for IdentitiesByEpoch") @@ -54,29 +109,61 @@ func (_m *Replicas) IdentitiesByEpoch(view uint64) (flow.IdentitySkeletonList, e var r0 flow.IdentitySkeletonList var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.IdentitySkeletonList, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.IdentitySkeletonList, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) flow.IdentitySkeletonList); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.IdentitySkeletonList); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentitySkeletonList) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// IdentityByEpoch provides a mock function with given fields: view, participantID -func (_m *Replicas) IdentityByEpoch(view uint64, participantID flow.Identifier) (*flow.IdentitySkeleton, error) { - ret := _m.Called(view, participantID) +// Replicas_IdentitiesByEpoch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IdentitiesByEpoch' +type Replicas_IdentitiesByEpoch_Call struct { + *mock.Call +} + +// IdentitiesByEpoch is a helper method to define mock.On call +// - view uint64 +func (_e *Replicas_Expecter) IdentitiesByEpoch(view interface{}) *Replicas_IdentitiesByEpoch_Call { + return &Replicas_IdentitiesByEpoch_Call{Call: _e.mock.On("IdentitiesByEpoch", view)} +} + +func (_c *Replicas_IdentitiesByEpoch_Call) Run(run func(view uint64)) *Replicas_IdentitiesByEpoch_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Replicas_IdentitiesByEpoch_Call) Return(v flow.IdentitySkeletonList, err error) *Replicas_IdentitiesByEpoch_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Replicas_IdentitiesByEpoch_Call) RunAndReturn(run func(view uint64) (flow.IdentitySkeletonList, error)) *Replicas_IdentitiesByEpoch_Call { + _c.Call.Return(run) + return _c +} + +// IdentityByEpoch provides a mock function for the type Replicas +func (_mock *Replicas) IdentityByEpoch(view uint64, participantID flow.Identifier) (*flow.IdentitySkeleton, error) { + ret := _mock.Called(view, participantID) if len(ret) == 0 { panic("no return value specified for IdentityByEpoch") @@ -84,29 +171,67 @@ func (_m *Replicas) IdentityByEpoch(view uint64, participantID flow.Identifier) var r0 *flow.IdentitySkeleton var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (*flow.IdentitySkeleton, error)); ok { - return rf(view, participantID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (*flow.IdentitySkeleton, error)); ok { + return returnFunc(view, participantID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) *flow.IdentitySkeleton); ok { - r0 = rf(view, participantID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) *flow.IdentitySkeleton); ok { + r0 = returnFunc(view, participantID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.IdentitySkeleton) } } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(view, participantID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(view, participantID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LeaderForView provides a mock function with given fields: view -func (_m *Replicas) LeaderForView(view uint64) (flow.Identifier, error) { - ret := _m.Called(view) +// Replicas_IdentityByEpoch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IdentityByEpoch' +type Replicas_IdentityByEpoch_Call struct { + *mock.Call +} + +// IdentityByEpoch is a helper method to define mock.On call +// - view uint64 +// - participantID flow.Identifier +func (_e *Replicas_Expecter) IdentityByEpoch(view interface{}, participantID interface{}) *Replicas_IdentityByEpoch_Call { + return &Replicas_IdentityByEpoch_Call{Call: _e.mock.On("IdentityByEpoch", view, participantID)} +} + +func (_c *Replicas_IdentityByEpoch_Call) Run(run func(view uint64, participantID flow.Identifier)) *Replicas_IdentityByEpoch_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Replicas_IdentityByEpoch_Call) Return(identitySkeleton *flow.IdentitySkeleton, err error) *Replicas_IdentityByEpoch_Call { + _c.Call.Return(identitySkeleton, err) + return _c +} + +func (_c *Replicas_IdentityByEpoch_Call) RunAndReturn(run func(view uint64, participantID flow.Identifier) (*flow.IdentitySkeleton, error)) *Replicas_IdentityByEpoch_Call { + _c.Call.Return(run) + return _c +} + +// LeaderForView provides a mock function for the type Replicas +func (_mock *Replicas) LeaderForView(view uint64) (flow.Identifier, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for LeaderForView") @@ -114,29 +239,61 @@ func (_m *Replicas) LeaderForView(view uint64) (flow.Identifier, error) { var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// QuorumThresholdForView provides a mock function with given fields: view -func (_m *Replicas) QuorumThresholdForView(view uint64) (uint64, error) { - ret := _m.Called(view) +// Replicas_LeaderForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LeaderForView' +type Replicas_LeaderForView_Call struct { + *mock.Call +} + +// LeaderForView is a helper method to define mock.On call +// - view uint64 +func (_e *Replicas_Expecter) LeaderForView(view interface{}) *Replicas_LeaderForView_Call { + return &Replicas_LeaderForView_Call{Call: _e.mock.On("LeaderForView", view)} +} + +func (_c *Replicas_LeaderForView_Call) Run(run func(view uint64)) *Replicas_LeaderForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Replicas_LeaderForView_Call) Return(identifier flow.Identifier, err error) *Replicas_LeaderForView_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *Replicas_LeaderForView_Call) RunAndReturn(run func(view uint64) (flow.Identifier, error)) *Replicas_LeaderForView_Call { + _c.Call.Return(run) + return _c +} + +// QuorumThresholdForView provides a mock function for the type Replicas +func (_mock *Replicas) QuorumThresholdForView(view uint64) (uint64, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for QuorumThresholdForView") @@ -144,47 +301,105 @@ func (_m *Replicas) QuorumThresholdForView(view uint64) (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(view) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// Self provides a mock function with no fields -func (_m *Replicas) Self() flow.Identifier { - ret := _m.Called() +// Replicas_QuorumThresholdForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QuorumThresholdForView' +type Replicas_QuorumThresholdForView_Call struct { + *mock.Call +} + +// QuorumThresholdForView is a helper method to define mock.On call +// - view uint64 +func (_e *Replicas_Expecter) QuorumThresholdForView(view interface{}) *Replicas_QuorumThresholdForView_Call { + return &Replicas_QuorumThresholdForView_Call{Call: _e.mock.On("QuorumThresholdForView", view)} +} + +func (_c *Replicas_QuorumThresholdForView_Call) Run(run func(view uint64)) *Replicas_QuorumThresholdForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Replicas_QuorumThresholdForView_Call) Return(v uint64, err error) *Replicas_QuorumThresholdForView_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Replicas_QuorumThresholdForView_Call) RunAndReturn(run func(view uint64) (uint64, error)) *Replicas_QuorumThresholdForView_Call { + _c.Call.Return(run) + return _c +} + +// Self provides a mock function for the type Replicas +func (_mock *Replicas) Self() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Self") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// TimeoutThresholdForView provides a mock function with given fields: view -func (_m *Replicas) TimeoutThresholdForView(view uint64) (uint64, error) { - ret := _m.Called(view) +// Replicas_Self_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Self' +type Replicas_Self_Call struct { + *mock.Call +} + +// Self is a helper method to define mock.On call +func (_e *Replicas_Expecter) Self() *Replicas_Self_Call { + return &Replicas_Self_Call{Call: _e.mock.On("Self")} +} + +func (_c *Replicas_Self_Call) Run(run func()) *Replicas_Self_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Replicas_Self_Call) Return(identifier flow.Identifier) *Replicas_Self_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *Replicas_Self_Call) RunAndReturn(run func() flow.Identifier) *Replicas_Self_Call { + _c.Call.Return(run) + return _c +} + +// TimeoutThresholdForView provides a mock function for the type Replicas +func (_mock *Replicas) TimeoutThresholdForView(view uint64) (uint64, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for TimeoutThresholdForView") @@ -192,34 +407,52 @@ func (_m *Replicas) TimeoutThresholdForView(view uint64) (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(view) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewReplicas creates a new instance of Replicas. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReplicas(t interface { - mock.TestingT - Cleanup(func()) -}) *Replicas { - mock := &Replicas{} - mock.Mock.Test(t) +// Replicas_TimeoutThresholdForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TimeoutThresholdForView' +type Replicas_TimeoutThresholdForView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TimeoutThresholdForView is a helper method to define mock.On call +// - view uint64 +func (_e *Replicas_Expecter) TimeoutThresholdForView(view interface{}) *Replicas_TimeoutThresholdForView_Call { + return &Replicas_TimeoutThresholdForView_Call{Call: _e.mock.On("TimeoutThresholdForView", view)} +} - return mock +func (_c *Replicas_TimeoutThresholdForView_Call) Run(run func(view uint64)) *Replicas_TimeoutThresholdForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Replicas_TimeoutThresholdForView_Call) Return(v uint64, err error) *Replicas_TimeoutThresholdForView_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Replicas_TimeoutThresholdForView_Call) RunAndReturn(run func(view uint64) (uint64, error)) *Replicas_TimeoutThresholdForView_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/safety_rules.go b/consensus/hotstuff/mocks/safety_rules.go index 1c76ba1d956..b4f4ba2018d 100644 --- a/consensus/hotstuff/mocks/safety_rules.go +++ b/consensus/hotstuff/mocks/safety_rules.go @@ -1,23 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewSafetyRules creates a new instance of SafetyRules. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSafetyRules(t interface { + mock.TestingT + Cleanup(func()) +}) *SafetyRules { + mock := &SafetyRules{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SafetyRules is an autogenerated mock type for the SafetyRules type type SafetyRules struct { mock.Mock } -// ProduceTimeout provides a mock function with given fields: curView, newestQC, lastViewTC -func (_m *SafetyRules) ProduceTimeout(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*model.TimeoutObject, error) { - ret := _m.Called(curView, newestQC, lastViewTC) +type SafetyRules_Expecter struct { + mock *mock.Mock +} + +func (_m *SafetyRules) EXPECT() *SafetyRules_Expecter { + return &SafetyRules_Expecter{mock: &_m.Mock} +} + +// ProduceTimeout provides a mock function for the type SafetyRules +func (_mock *SafetyRules) ProduceTimeout(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*model.TimeoutObject, error) { + ret := _mock.Called(curView, newestQC, lastViewTC) if len(ret) == 0 { panic("no return value specified for ProduceTimeout") @@ -25,29 +47,73 @@ func (_m *SafetyRules) ProduceTimeout(curView uint64, newestQC *flow.QuorumCerti var r0 *model.TimeoutObject var r1 error - if rf, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) (*model.TimeoutObject, error)); ok { - return rf(curView, newestQC, lastViewTC) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) (*model.TimeoutObject, error)); ok { + return returnFunc(curView, newestQC, lastViewTC) } - if rf, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) *model.TimeoutObject); ok { - r0 = rf(curView, newestQC, lastViewTC) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) *model.TimeoutObject); ok { + r0 = returnFunc(curView, newestQC, lastViewTC) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.TimeoutObject) } } - - if rf, ok := ret.Get(1).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) error); ok { - r1 = rf(curView, newestQC, lastViewTC) + if returnFunc, ok := ret.Get(1).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) error); ok { + r1 = returnFunc(curView, newestQC, lastViewTC) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProduceVote provides a mock function with given fields: proposal, curView -func (_m *SafetyRules) ProduceVote(proposal *model.SignedProposal, curView uint64) (*model.Vote, error) { - ret := _m.Called(proposal, curView) +// SafetyRules_ProduceTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProduceTimeout' +type SafetyRules_ProduceTimeout_Call struct { + *mock.Call +} + +// ProduceTimeout is a helper method to define mock.On call +// - curView uint64 +// - newestQC *flow.QuorumCertificate +// - lastViewTC *flow.TimeoutCertificate +func (_e *SafetyRules_Expecter) ProduceTimeout(curView interface{}, newestQC interface{}, lastViewTC interface{}) *SafetyRules_ProduceTimeout_Call { + return &SafetyRules_ProduceTimeout_Call{Call: _e.mock.On("ProduceTimeout", curView, newestQC, lastViewTC)} +} + +func (_c *SafetyRules_ProduceTimeout_Call) Run(run func(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *SafetyRules_ProduceTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *SafetyRules_ProduceTimeout_Call) Return(timeoutObject *model.TimeoutObject, err error) *SafetyRules_ProduceTimeout_Call { + _c.Call.Return(timeoutObject, err) + return _c +} + +func (_c *SafetyRules_ProduceTimeout_Call) RunAndReturn(run func(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*model.TimeoutObject, error)) *SafetyRules_ProduceTimeout_Call { + _c.Call.Return(run) + return _c +} + +// ProduceVote provides a mock function for the type SafetyRules +func (_mock *SafetyRules) ProduceVote(proposal *model.SignedProposal, curView uint64) (*model.Vote, error) { + ret := _mock.Called(proposal, curView) if len(ret) == 0 { panic("no return value specified for ProduceVote") @@ -55,29 +121,67 @@ func (_m *SafetyRules) ProduceVote(proposal *model.SignedProposal, curView uint6 var r0 *model.Vote var r1 error - if rf, ok := ret.Get(0).(func(*model.SignedProposal, uint64) (*model.Vote, error)); ok { - return rf(proposal, curView) + if returnFunc, ok := ret.Get(0).(func(*model.SignedProposal, uint64) (*model.Vote, error)); ok { + return returnFunc(proposal, curView) } - if rf, ok := ret.Get(0).(func(*model.SignedProposal, uint64) *model.Vote); ok { - r0 = rf(proposal, curView) + if returnFunc, ok := ret.Get(0).(func(*model.SignedProposal, uint64) *model.Vote); ok { + r0 = returnFunc(proposal, curView) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Vote) } } - - if rf, ok := ret.Get(1).(func(*model.SignedProposal, uint64) error); ok { - r1 = rf(proposal, curView) + if returnFunc, ok := ret.Get(1).(func(*model.SignedProposal, uint64) error); ok { + r1 = returnFunc(proposal, curView) } else { r1 = ret.Error(1) } - return r0, r1 } -// SignOwnProposal provides a mock function with given fields: unsignedProposal -func (_m *SafetyRules) SignOwnProposal(unsignedProposal *model.Proposal) (*model.Vote, error) { - ret := _m.Called(unsignedProposal) +// SafetyRules_ProduceVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProduceVote' +type SafetyRules_ProduceVote_Call struct { + *mock.Call +} + +// ProduceVote is a helper method to define mock.On call +// - proposal *model.SignedProposal +// - curView uint64 +func (_e *SafetyRules_Expecter) ProduceVote(proposal interface{}, curView interface{}) *SafetyRules_ProduceVote_Call { + return &SafetyRules_ProduceVote_Call{Call: _e.mock.On("ProduceVote", proposal, curView)} +} + +func (_c *SafetyRules_ProduceVote_Call) Run(run func(proposal *model.SignedProposal, curView uint64)) *SafetyRules_ProduceVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SafetyRules_ProduceVote_Call) Return(vote *model.Vote, err error) *SafetyRules_ProduceVote_Call { + _c.Call.Return(vote, err) + return _c +} + +func (_c *SafetyRules_ProduceVote_Call) RunAndReturn(run func(proposal *model.SignedProposal, curView uint64) (*model.Vote, error)) *SafetyRules_ProduceVote_Call { + _c.Call.Return(run) + return _c +} + +// SignOwnProposal provides a mock function for the type SafetyRules +func (_mock *SafetyRules) SignOwnProposal(unsignedProposal *model.Proposal) (*model.Vote, error) { + ret := _mock.Called(unsignedProposal) if len(ret) == 0 { panic("no return value specified for SignOwnProposal") @@ -85,36 +189,54 @@ func (_m *SafetyRules) SignOwnProposal(unsignedProposal *model.Proposal) (*model var r0 *model.Vote var r1 error - if rf, ok := ret.Get(0).(func(*model.Proposal) (*model.Vote, error)); ok { - return rf(unsignedProposal) + if returnFunc, ok := ret.Get(0).(func(*model.Proposal) (*model.Vote, error)); ok { + return returnFunc(unsignedProposal) } - if rf, ok := ret.Get(0).(func(*model.Proposal) *model.Vote); ok { - r0 = rf(unsignedProposal) + if returnFunc, ok := ret.Get(0).(func(*model.Proposal) *model.Vote); ok { + r0 = returnFunc(unsignedProposal) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Vote) } } - - if rf, ok := ret.Get(1).(func(*model.Proposal) error); ok { - r1 = rf(unsignedProposal) + if returnFunc, ok := ret.Get(1).(func(*model.Proposal) error); ok { + r1 = returnFunc(unsignedProposal) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSafetyRules creates a new instance of SafetyRules. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSafetyRules(t interface { - mock.TestingT - Cleanup(func()) -}) *SafetyRules { - mock := &SafetyRules{} - mock.Mock.Test(t) +// SafetyRules_SignOwnProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SignOwnProposal' +type SafetyRules_SignOwnProposal_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SignOwnProposal is a helper method to define mock.On call +// - unsignedProposal *model.Proposal +func (_e *SafetyRules_Expecter) SignOwnProposal(unsignedProposal interface{}) *SafetyRules_SignOwnProposal_Call { + return &SafetyRules_SignOwnProposal_Call{Call: _e.mock.On("SignOwnProposal", unsignedProposal)} +} - return mock +func (_c *SafetyRules_SignOwnProposal_Call) Run(run func(unsignedProposal *model.Proposal)) *SafetyRules_SignOwnProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Proposal + if args[0] != nil { + arg0 = args[0].(*model.Proposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SafetyRules_SignOwnProposal_Call) Return(vote *model.Vote, err error) *SafetyRules_SignOwnProposal_Call { + _c.Call.Return(vote, err) + return _c +} + +func (_c *SafetyRules_SignOwnProposal_Call) RunAndReturn(run func(unsignedProposal *model.Proposal) (*model.Vote, error)) *SafetyRules_SignOwnProposal_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/signer.go b/consensus/hotstuff/mocks/signer.go index dd6588feb91..6aa336a8eec 100644 --- a/consensus/hotstuff/mocks/signer.go +++ b/consensus/hotstuff/mocks/signer.go @@ -1,23 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewSigner creates a new instance of Signer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSigner(t interface { + mock.TestingT + Cleanup(func()) +}) *Signer { + mock := &Signer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Signer is an autogenerated mock type for the Signer type type Signer struct { mock.Mock } -// CreateTimeout provides a mock function with given fields: curView, newestQC, lastViewTC -func (_m *Signer) CreateTimeout(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*model.TimeoutObject, error) { - ret := _m.Called(curView, newestQC, lastViewTC) +type Signer_Expecter struct { + mock *mock.Mock +} + +func (_m *Signer) EXPECT() *Signer_Expecter { + return &Signer_Expecter{mock: &_m.Mock} +} + +// CreateTimeout provides a mock function for the type Signer +func (_mock *Signer) CreateTimeout(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*model.TimeoutObject, error) { + ret := _mock.Called(curView, newestQC, lastViewTC) if len(ret) == 0 { panic("no return value specified for CreateTimeout") @@ -25,29 +47,73 @@ func (_m *Signer) CreateTimeout(curView uint64, newestQC *flow.QuorumCertificate var r0 *model.TimeoutObject var r1 error - if rf, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) (*model.TimeoutObject, error)); ok { - return rf(curView, newestQC, lastViewTC) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) (*model.TimeoutObject, error)); ok { + return returnFunc(curView, newestQC, lastViewTC) } - if rf, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) *model.TimeoutObject); ok { - r0 = rf(curView, newestQC, lastViewTC) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) *model.TimeoutObject); ok { + r0 = returnFunc(curView, newestQC, lastViewTC) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.TimeoutObject) } } - - if rf, ok := ret.Get(1).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) error); ok { - r1 = rf(curView, newestQC, lastViewTC) + if returnFunc, ok := ret.Get(1).(func(uint64, *flow.QuorumCertificate, *flow.TimeoutCertificate) error); ok { + r1 = returnFunc(curView, newestQC, lastViewTC) } else { r1 = ret.Error(1) } - return r0, r1 } -// CreateVote provides a mock function with given fields: block -func (_m *Signer) CreateVote(block *model.Block) (*model.Vote, error) { - ret := _m.Called(block) +// Signer_CreateTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateTimeout' +type Signer_CreateTimeout_Call struct { + *mock.Call +} + +// CreateTimeout is a helper method to define mock.On call +// - curView uint64 +// - newestQC *flow.QuorumCertificate +// - lastViewTC *flow.TimeoutCertificate +func (_e *Signer_Expecter) CreateTimeout(curView interface{}, newestQC interface{}, lastViewTC interface{}) *Signer_CreateTimeout_Call { + return &Signer_CreateTimeout_Call{Call: _e.mock.On("CreateTimeout", curView, newestQC, lastViewTC)} +} + +func (_c *Signer_CreateTimeout_Call) Run(run func(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *Signer_CreateTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Signer_CreateTimeout_Call) Return(timeoutObject *model.TimeoutObject, err error) *Signer_CreateTimeout_Call { + _c.Call.Return(timeoutObject, err) + return _c +} + +func (_c *Signer_CreateTimeout_Call) RunAndReturn(run func(curView uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) (*model.TimeoutObject, error)) *Signer_CreateTimeout_Call { + _c.Call.Return(run) + return _c +} + +// CreateVote provides a mock function for the type Signer +func (_mock *Signer) CreateVote(block *model.Block) (*model.Vote, error) { + ret := _mock.Called(block) if len(ret) == 0 { panic("no return value specified for CreateVote") @@ -55,36 +121,54 @@ func (_m *Signer) CreateVote(block *model.Block) (*model.Vote, error) { var r0 *model.Vote var r1 error - if rf, ok := ret.Get(0).(func(*model.Block) (*model.Vote, error)); ok { - return rf(block) + if returnFunc, ok := ret.Get(0).(func(*model.Block) (*model.Vote, error)); ok { + return returnFunc(block) } - if rf, ok := ret.Get(0).(func(*model.Block) *model.Vote); ok { - r0 = rf(block) + if returnFunc, ok := ret.Get(0).(func(*model.Block) *model.Vote); ok { + r0 = returnFunc(block) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Vote) } } - - if rf, ok := ret.Get(1).(func(*model.Block) error); ok { - r1 = rf(block) + if returnFunc, ok := ret.Get(1).(func(*model.Block) error); ok { + r1 = returnFunc(block) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSigner creates a new instance of Signer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSigner(t interface { - mock.TestingT - Cleanup(func()) -}) *Signer { - mock := &Signer{} - mock.Mock.Test(t) +// Signer_CreateVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateVote' +type Signer_CreateVote_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// CreateVote is a helper method to define mock.On call +// - block *model.Block +func (_e *Signer_Expecter) CreateVote(block interface{}) *Signer_CreateVote_Call { + return &Signer_CreateVote_Call{Call: _e.mock.On("CreateVote", block)} +} - return mock +func (_c *Signer_CreateVote_Call) Run(run func(block *model.Block)) *Signer_CreateVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Block + if args[0] != nil { + arg0 = args[0].(*model.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Signer_CreateVote_Call) Return(vote *model.Vote, err error) *Signer_CreateVote_Call { + _c.Call.Return(vote, err) + return _c +} + +func (_c *Signer_CreateVote_Call) RunAndReturn(run func(block *model.Block) (*model.Vote, error)) *Signer_CreateVote_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_aggregation_consumer.go b/consensus/hotstuff/mocks/timeout_aggregation_consumer.go index 75e16a933f3..72677d463f8 100644 --- a/consensus/hotstuff/mocks/timeout_aggregation_consumer.go +++ b/consensus/hotstuff/mocks/timeout_aggregation_consumer.go @@ -1,65 +1,336 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewTimeoutAggregationConsumer creates a new instance of TimeoutAggregationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutAggregationConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutAggregationConsumer { + mock := &TimeoutAggregationConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutAggregationConsumer is an autogenerated mock type for the TimeoutAggregationConsumer type type TimeoutAggregationConsumer struct { mock.Mock } -// OnDoubleTimeoutDetected provides a mock function with given fields: _a0, _a1 -func (_m *TimeoutAggregationConsumer) OnDoubleTimeoutDetected(_a0 *model.TimeoutObject, _a1 *model.TimeoutObject) { - _m.Called(_a0, _a1) +type TimeoutAggregationConsumer_Expecter struct { + mock *mock.Mock } -// OnInvalidTimeoutDetected provides a mock function with given fields: err -func (_m *TimeoutAggregationConsumer) OnInvalidTimeoutDetected(err model.InvalidTimeoutError) { - _m.Called(err) +func (_m *TimeoutAggregationConsumer) EXPECT() *TimeoutAggregationConsumer_Expecter { + return &TimeoutAggregationConsumer_Expecter{mock: &_m.Mock} } -// OnNewQcDiscovered provides a mock function with given fields: certificate -func (_m *TimeoutAggregationConsumer) OnNewQcDiscovered(certificate *flow.QuorumCertificate) { - _m.Called(certificate) +// OnDoubleTimeoutDetected provides a mock function for the type TimeoutAggregationConsumer +func (_mock *TimeoutAggregationConsumer) OnDoubleTimeoutDetected(timeoutObject *model.TimeoutObject, timeoutObject1 *model.TimeoutObject) { + _mock.Called(timeoutObject, timeoutObject1) + return } -// OnNewTcDiscovered provides a mock function with given fields: certificate -func (_m *TimeoutAggregationConsumer) OnNewTcDiscovered(certificate *flow.TimeoutCertificate) { - _m.Called(certificate) +// TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDoubleTimeoutDetected' +type TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call struct { + *mock.Call } -// OnPartialTcCreated provides a mock function with given fields: view, newestQC, lastViewTC -func (_m *TimeoutAggregationConsumer) OnPartialTcCreated(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) { - _m.Called(view, newestQC, lastViewTC) +// OnDoubleTimeoutDetected is a helper method to define mock.On call +// - timeoutObject *model.TimeoutObject +// - timeoutObject1 *model.TimeoutObject +func (_e *TimeoutAggregationConsumer_Expecter) OnDoubleTimeoutDetected(timeoutObject interface{}, timeoutObject1 interface{}) *TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call { + return &TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call{Call: _e.mock.On("OnDoubleTimeoutDetected", timeoutObject, timeoutObject1)} } -// OnTcConstructedFromTimeouts provides a mock function with given fields: certificate -func (_m *TimeoutAggregationConsumer) OnTcConstructedFromTimeouts(certificate *flow.TimeoutCertificate) { - _m.Called(certificate) +func (_c *TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call) Run(run func(timeoutObject *model.TimeoutObject, timeoutObject1 *model.TimeoutObject)) *TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + var arg1 *model.TimeoutObject + if args[1] != nil { + arg1 = args[1].(*model.TimeoutObject) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnTimeoutProcessed provides a mock function with given fields: timeout -func (_m *TimeoutAggregationConsumer) OnTimeoutProcessed(timeout *model.TimeoutObject) { - _m.Called(timeout) +func (_c *TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call) Return() *TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call { + _c.Call.Return() + return _c } -// NewTimeoutAggregationConsumer creates a new instance of TimeoutAggregationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutAggregationConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutAggregationConsumer { - mock := &TimeoutAggregationConsumer{} - mock.Mock.Test(t) +func (_c *TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call) RunAndReturn(run func(timeoutObject *model.TimeoutObject, timeoutObject1 *model.TimeoutObject)) *TimeoutAggregationConsumer_OnDoubleTimeoutDetected_Call { + _c.Run(run) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnInvalidTimeoutDetected provides a mock function for the type TimeoutAggregationConsumer +func (_mock *TimeoutAggregationConsumer) OnInvalidTimeoutDetected(err model.InvalidTimeoutError) { + _mock.Called(err) + return +} - return mock +// TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidTimeoutDetected' +type TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call struct { + *mock.Call +} + +// OnInvalidTimeoutDetected is a helper method to define mock.On call +// - err model.InvalidTimeoutError +func (_e *TimeoutAggregationConsumer_Expecter) OnInvalidTimeoutDetected(err interface{}) *TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call { + return &TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call{Call: _e.mock.On("OnInvalidTimeoutDetected", err)} +} + +func (_c *TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call) Run(run func(err model.InvalidTimeoutError)) *TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 model.InvalidTimeoutError + if args[0] != nil { + arg0 = args[0].(model.InvalidTimeoutError) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call) Return() *TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call) RunAndReturn(run func(err model.InvalidTimeoutError)) *TimeoutAggregationConsumer_OnInvalidTimeoutDetected_Call { + _c.Run(run) + return _c +} + +// OnNewQcDiscovered provides a mock function for the type TimeoutAggregationConsumer +func (_mock *TimeoutAggregationConsumer) OnNewQcDiscovered(certificate *flow.QuorumCertificate) { + _mock.Called(certificate) + return +} + +// TimeoutAggregationConsumer_OnNewQcDiscovered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnNewQcDiscovered' +type TimeoutAggregationConsumer_OnNewQcDiscovered_Call struct { + *mock.Call +} + +// OnNewQcDiscovered is a helper method to define mock.On call +// - certificate *flow.QuorumCertificate +func (_e *TimeoutAggregationConsumer_Expecter) OnNewQcDiscovered(certificate interface{}) *TimeoutAggregationConsumer_OnNewQcDiscovered_Call { + return &TimeoutAggregationConsumer_OnNewQcDiscovered_Call{Call: _e.mock.On("OnNewQcDiscovered", certificate)} +} + +func (_c *TimeoutAggregationConsumer_OnNewQcDiscovered_Call) Run(run func(certificate *flow.QuorumCertificate)) *TimeoutAggregationConsumer_OnNewQcDiscovered_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregationConsumer_OnNewQcDiscovered_Call) Return() *TimeoutAggregationConsumer_OnNewQcDiscovered_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationConsumer_OnNewQcDiscovered_Call) RunAndReturn(run func(certificate *flow.QuorumCertificate)) *TimeoutAggregationConsumer_OnNewQcDiscovered_Call { + _c.Run(run) + return _c +} + +// OnNewTcDiscovered provides a mock function for the type TimeoutAggregationConsumer +func (_mock *TimeoutAggregationConsumer) OnNewTcDiscovered(certificate *flow.TimeoutCertificate) { + _mock.Called(certificate) + return +} + +// TimeoutAggregationConsumer_OnNewTcDiscovered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnNewTcDiscovered' +type TimeoutAggregationConsumer_OnNewTcDiscovered_Call struct { + *mock.Call +} + +// OnNewTcDiscovered is a helper method to define mock.On call +// - certificate *flow.TimeoutCertificate +func (_e *TimeoutAggregationConsumer_Expecter) OnNewTcDiscovered(certificate interface{}) *TimeoutAggregationConsumer_OnNewTcDiscovered_Call { + return &TimeoutAggregationConsumer_OnNewTcDiscovered_Call{Call: _e.mock.On("OnNewTcDiscovered", certificate)} +} + +func (_c *TimeoutAggregationConsumer_OnNewTcDiscovered_Call) Run(run func(certificate *flow.TimeoutCertificate)) *TimeoutAggregationConsumer_OnNewTcDiscovered_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregationConsumer_OnNewTcDiscovered_Call) Return() *TimeoutAggregationConsumer_OnNewTcDiscovered_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationConsumer_OnNewTcDiscovered_Call) RunAndReturn(run func(certificate *flow.TimeoutCertificate)) *TimeoutAggregationConsumer_OnNewTcDiscovered_Call { + _c.Run(run) + return _c +} + +// OnPartialTcCreated provides a mock function for the type TimeoutAggregationConsumer +func (_mock *TimeoutAggregationConsumer) OnPartialTcCreated(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) { + _mock.Called(view, newestQC, lastViewTC) + return +} + +// TimeoutAggregationConsumer_OnPartialTcCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPartialTcCreated' +type TimeoutAggregationConsumer_OnPartialTcCreated_Call struct { + *mock.Call +} + +// OnPartialTcCreated is a helper method to define mock.On call +// - view uint64 +// - newestQC *flow.QuorumCertificate +// - lastViewTC *flow.TimeoutCertificate +func (_e *TimeoutAggregationConsumer_Expecter) OnPartialTcCreated(view interface{}, newestQC interface{}, lastViewTC interface{}) *TimeoutAggregationConsumer_OnPartialTcCreated_Call { + return &TimeoutAggregationConsumer_OnPartialTcCreated_Call{Call: _e.mock.On("OnPartialTcCreated", view, newestQC, lastViewTC)} +} + +func (_c *TimeoutAggregationConsumer_OnPartialTcCreated_Call) Run(run func(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *TimeoutAggregationConsumer_OnPartialTcCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TimeoutAggregationConsumer_OnPartialTcCreated_Call) Return() *TimeoutAggregationConsumer_OnPartialTcCreated_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationConsumer_OnPartialTcCreated_Call) RunAndReturn(run func(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *TimeoutAggregationConsumer_OnPartialTcCreated_Call { + _c.Run(run) + return _c +} + +// OnTcConstructedFromTimeouts provides a mock function for the type TimeoutAggregationConsumer +func (_mock *TimeoutAggregationConsumer) OnTcConstructedFromTimeouts(certificate *flow.TimeoutCertificate) { + _mock.Called(certificate) + return +} + +// TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTcConstructedFromTimeouts' +type TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call struct { + *mock.Call +} + +// OnTcConstructedFromTimeouts is a helper method to define mock.On call +// - certificate *flow.TimeoutCertificate +func (_e *TimeoutAggregationConsumer_Expecter) OnTcConstructedFromTimeouts(certificate interface{}) *TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call { + return &TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call{Call: _e.mock.On("OnTcConstructedFromTimeouts", certificate)} +} + +func (_c *TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call) Run(run func(certificate *flow.TimeoutCertificate)) *TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call) Return() *TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call) RunAndReturn(run func(certificate *flow.TimeoutCertificate)) *TimeoutAggregationConsumer_OnTcConstructedFromTimeouts_Call { + _c.Run(run) + return _c +} + +// OnTimeoutProcessed provides a mock function for the type TimeoutAggregationConsumer +func (_mock *TimeoutAggregationConsumer) OnTimeoutProcessed(timeout *model.TimeoutObject) { + _mock.Called(timeout) + return +} + +// TimeoutAggregationConsumer_OnTimeoutProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTimeoutProcessed' +type TimeoutAggregationConsumer_OnTimeoutProcessed_Call struct { + *mock.Call +} + +// OnTimeoutProcessed is a helper method to define mock.On call +// - timeout *model.TimeoutObject +func (_e *TimeoutAggregationConsumer_Expecter) OnTimeoutProcessed(timeout interface{}) *TimeoutAggregationConsumer_OnTimeoutProcessed_Call { + return &TimeoutAggregationConsumer_OnTimeoutProcessed_Call{Call: _e.mock.On("OnTimeoutProcessed", timeout)} +} + +func (_c *TimeoutAggregationConsumer_OnTimeoutProcessed_Call) Run(run func(timeout *model.TimeoutObject)) *TimeoutAggregationConsumer_OnTimeoutProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregationConsumer_OnTimeoutProcessed_Call) Return() *TimeoutAggregationConsumer_OnTimeoutProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationConsumer_OnTimeoutProcessed_Call) RunAndReturn(run func(timeout *model.TimeoutObject)) *TimeoutAggregationConsumer_OnTimeoutProcessed_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_aggregation_violation_consumer.go b/consensus/hotstuff/mocks/timeout_aggregation_violation_consumer.go index 71509a764d9..7bd7dc7ebf7 100644 --- a/consensus/hotstuff/mocks/timeout_aggregation_violation_consumer.go +++ b/consensus/hotstuff/mocks/timeout_aggregation_violation_consumer.go @@ -1,27 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - model "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" ) -// TimeoutAggregationViolationConsumer is an autogenerated mock type for the TimeoutAggregationViolationConsumer type -type TimeoutAggregationViolationConsumer struct { - mock.Mock -} - -// OnDoubleTimeoutDetected provides a mock function with given fields: _a0, _a1 -func (_m *TimeoutAggregationViolationConsumer) OnDoubleTimeoutDetected(_a0 *model.TimeoutObject, _a1 *model.TimeoutObject) { - _m.Called(_a0, _a1) -} - -// OnInvalidTimeoutDetected provides a mock function with given fields: err -func (_m *TimeoutAggregationViolationConsumer) OnInvalidTimeoutDetected(err model.InvalidTimeoutError) { - _m.Called(err) -} - // NewTimeoutAggregationViolationConsumer creates a new instance of TimeoutAggregationViolationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewTimeoutAggregationViolationConsumer(t interface { @@ -35,3 +22,102 @@ func NewTimeoutAggregationViolationConsumer(t interface { return mock } + +// TimeoutAggregationViolationConsumer is an autogenerated mock type for the TimeoutAggregationViolationConsumer type +type TimeoutAggregationViolationConsumer struct { + mock.Mock +} + +type TimeoutAggregationViolationConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutAggregationViolationConsumer) EXPECT() *TimeoutAggregationViolationConsumer_Expecter { + return &TimeoutAggregationViolationConsumer_Expecter{mock: &_m.Mock} +} + +// OnDoubleTimeoutDetected provides a mock function for the type TimeoutAggregationViolationConsumer +func (_mock *TimeoutAggregationViolationConsumer) OnDoubleTimeoutDetected(timeoutObject *model.TimeoutObject, timeoutObject1 *model.TimeoutObject) { + _mock.Called(timeoutObject, timeoutObject1) + return +} + +// TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDoubleTimeoutDetected' +type TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call struct { + *mock.Call +} + +// OnDoubleTimeoutDetected is a helper method to define mock.On call +// - timeoutObject *model.TimeoutObject +// - timeoutObject1 *model.TimeoutObject +func (_e *TimeoutAggregationViolationConsumer_Expecter) OnDoubleTimeoutDetected(timeoutObject interface{}, timeoutObject1 interface{}) *TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call { + return &TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call{Call: _e.mock.On("OnDoubleTimeoutDetected", timeoutObject, timeoutObject1)} +} + +func (_c *TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call) Run(run func(timeoutObject *model.TimeoutObject, timeoutObject1 *model.TimeoutObject)) *TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + var arg1 *model.TimeoutObject + if args[1] != nil { + arg1 = args[1].(*model.TimeoutObject) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call) Return() *TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call) RunAndReturn(run func(timeoutObject *model.TimeoutObject, timeoutObject1 *model.TimeoutObject)) *TimeoutAggregationViolationConsumer_OnDoubleTimeoutDetected_Call { + _c.Run(run) + return _c +} + +// OnInvalidTimeoutDetected provides a mock function for the type TimeoutAggregationViolationConsumer +func (_mock *TimeoutAggregationViolationConsumer) OnInvalidTimeoutDetected(err model.InvalidTimeoutError) { + _mock.Called(err) + return +} + +// TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidTimeoutDetected' +type TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call struct { + *mock.Call +} + +// OnInvalidTimeoutDetected is a helper method to define mock.On call +// - err model.InvalidTimeoutError +func (_e *TimeoutAggregationViolationConsumer_Expecter) OnInvalidTimeoutDetected(err interface{}) *TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call { + return &TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call{Call: _e.mock.On("OnInvalidTimeoutDetected", err)} +} + +func (_c *TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call) Run(run func(err model.InvalidTimeoutError)) *TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 model.InvalidTimeoutError + if args[0] != nil { + arg0 = args[0].(model.InvalidTimeoutError) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call) Return() *TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call) RunAndReturn(run func(err model.InvalidTimeoutError)) *TimeoutAggregationViolationConsumer_OnInvalidTimeoutDetected_Call { + _c.Run(run) + return _c +} diff --git a/consensus/hotstuff/mocks/timeout_aggregator.go b/consensus/hotstuff/mocks/timeout_aggregator.go index 2273f157baf..7bcec3a12c8 100644 --- a/consensus/hotstuff/mocks/timeout_aggregator.go +++ b/consensus/hotstuff/mocks/timeout_aggregator.go @@ -1,84 +1,250 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewTimeoutAggregator creates a new instance of TimeoutAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutAggregator(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutAggregator { + mock := &TimeoutAggregator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutAggregator is an autogenerated mock type for the TimeoutAggregator type type TimeoutAggregator struct { mock.Mock } -// AddTimeout provides a mock function with given fields: timeoutObject -func (_m *TimeoutAggregator) AddTimeout(timeoutObject *model.TimeoutObject) { - _m.Called(timeoutObject) +type TimeoutAggregator_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutAggregator) EXPECT() *TimeoutAggregator_Expecter { + return &TimeoutAggregator_Expecter{mock: &_m.Mock} +} + +// AddTimeout provides a mock function for the type TimeoutAggregator +func (_mock *TimeoutAggregator) AddTimeout(timeoutObject *model.TimeoutObject) { + _mock.Called(timeoutObject) + return +} + +// TimeoutAggregator_AddTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddTimeout' +type TimeoutAggregator_AddTimeout_Call struct { + *mock.Call +} + +// AddTimeout is a helper method to define mock.On call +// - timeoutObject *model.TimeoutObject +func (_e *TimeoutAggregator_Expecter) AddTimeout(timeoutObject interface{}) *TimeoutAggregator_AddTimeout_Call { + return &TimeoutAggregator_AddTimeout_Call{Call: _e.mock.On("AddTimeout", timeoutObject)} +} + +func (_c *TimeoutAggregator_AddTimeout_Call) Run(run func(timeoutObject *model.TimeoutObject)) *TimeoutAggregator_AddTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregator_AddTimeout_Call) Return() *TimeoutAggregator_AddTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregator_AddTimeout_Call) RunAndReturn(run func(timeoutObject *model.TimeoutObject)) *TimeoutAggregator_AddTimeout_Call { + _c.Run(run) + return _c } -// Done provides a mock function with no fields -func (_m *TimeoutAggregator) Done() <-chan struct{} { - ret := _m.Called() +// Done provides a mock function for the type TimeoutAggregator +func (_mock *TimeoutAggregator) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// PruneUpToView provides a mock function with given fields: lowestRetainedView -func (_m *TimeoutAggregator) PruneUpToView(lowestRetainedView uint64) { - _m.Called(lowestRetainedView) +// TimeoutAggregator_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type TimeoutAggregator_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *TimeoutAggregator_Expecter) Done() *TimeoutAggregator_Done_Call { + return &TimeoutAggregator_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *TimeoutAggregator_Done_Call) Run(run func()) *TimeoutAggregator_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TimeoutAggregator_Done_Call) Return(valCh <-chan struct{}) *TimeoutAggregator_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *TimeoutAggregator_Done_Call) RunAndReturn(run func() <-chan struct{}) *TimeoutAggregator_Done_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToView provides a mock function for the type TimeoutAggregator +func (_mock *TimeoutAggregator) PruneUpToView(lowestRetainedView uint64) { + _mock.Called(lowestRetainedView) + return +} + +// TimeoutAggregator_PruneUpToView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToView' +type TimeoutAggregator_PruneUpToView_Call struct { + *mock.Call +} + +// PruneUpToView is a helper method to define mock.On call +// - lowestRetainedView uint64 +func (_e *TimeoutAggregator_Expecter) PruneUpToView(lowestRetainedView interface{}) *TimeoutAggregator_PruneUpToView_Call { + return &TimeoutAggregator_PruneUpToView_Call{Call: _e.mock.On("PruneUpToView", lowestRetainedView)} +} + +func (_c *TimeoutAggregator_PruneUpToView_Call) Run(run func(lowestRetainedView uint64)) *TimeoutAggregator_PruneUpToView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregator_PruneUpToView_Call) Return() *TimeoutAggregator_PruneUpToView_Call { + _c.Call.Return() + return _c } -// Ready provides a mock function with no fields -func (_m *TimeoutAggregator) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *TimeoutAggregator_PruneUpToView_Call) RunAndReturn(run func(lowestRetainedView uint64)) *TimeoutAggregator_PruneUpToView_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type TimeoutAggregator +func (_mock *TimeoutAggregator) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *TimeoutAggregator) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// TimeoutAggregator_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type TimeoutAggregator_Ready_Call struct { + *mock.Call } -// NewTimeoutAggregator creates a new instance of TimeoutAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutAggregator(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutAggregator { - mock := &TimeoutAggregator{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *TimeoutAggregator_Expecter) Ready() *TimeoutAggregator_Ready_Call { + return &TimeoutAggregator_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *TimeoutAggregator_Ready_Call) Run(run func()) *TimeoutAggregator_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *TimeoutAggregator_Ready_Call) Return(valCh <-chan struct{}) *TimeoutAggregator_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *TimeoutAggregator_Ready_Call) RunAndReturn(run func() <-chan struct{}) *TimeoutAggregator_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type TimeoutAggregator +func (_mock *TimeoutAggregator) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// TimeoutAggregator_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type TimeoutAggregator_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *TimeoutAggregator_Expecter) Start(signalerContext interface{}) *TimeoutAggregator_Start_Call { + return &TimeoutAggregator_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *TimeoutAggregator_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *TimeoutAggregator_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutAggregator_Start_Call) Return() *TimeoutAggregator_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutAggregator_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *TimeoutAggregator_Start_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_collector.go b/consensus/hotstuff/mocks/timeout_collector.go index 399d8a33c95..9a8cda8078b 100644 --- a/consensus/hotstuff/mocks/timeout_collector.go +++ b/consensus/hotstuff/mocks/timeout_collector.go @@ -1,63 +1,132 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - model "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" ) +// NewTimeoutCollector creates a new instance of TimeoutCollector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutCollector(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutCollector { + mock := &TimeoutCollector{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutCollector is an autogenerated mock type for the TimeoutCollector type type TimeoutCollector struct { mock.Mock } -// AddTimeout provides a mock function with given fields: timeoutObject -func (_m *TimeoutCollector) AddTimeout(timeoutObject *model.TimeoutObject) error { - ret := _m.Called(timeoutObject) +type TimeoutCollector_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutCollector) EXPECT() *TimeoutCollector_Expecter { + return &TimeoutCollector_Expecter{mock: &_m.Mock} +} + +// AddTimeout provides a mock function for the type TimeoutCollector +func (_mock *TimeoutCollector) AddTimeout(timeoutObject *model.TimeoutObject) error { + ret := _mock.Called(timeoutObject) if len(ret) == 0 { panic("no return value specified for AddTimeout") } var r0 error - if rf, ok := ret.Get(0).(func(*model.TimeoutObject) error); ok { - r0 = rf(timeoutObject) + if returnFunc, ok := ret.Get(0).(func(*model.TimeoutObject) error); ok { + r0 = returnFunc(timeoutObject) } else { r0 = ret.Error(0) } - return r0 } -// View provides a mock function with no fields -func (_m *TimeoutCollector) View() uint64 { - ret := _m.Called() +// TimeoutCollector_AddTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddTimeout' +type TimeoutCollector_AddTimeout_Call struct { + *mock.Call +} + +// AddTimeout is a helper method to define mock.On call +// - timeoutObject *model.TimeoutObject +func (_e *TimeoutCollector_Expecter) AddTimeout(timeoutObject interface{}) *TimeoutCollector_AddTimeout_Call { + return &TimeoutCollector_AddTimeout_Call{Call: _e.mock.On("AddTimeout", timeoutObject)} +} + +func (_c *TimeoutCollector_AddTimeout_Call) Run(run func(timeoutObject *model.TimeoutObject)) *TimeoutCollector_AddTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutCollector_AddTimeout_Call) Return(err error) *TimeoutCollector_AddTimeout_Call { + _c.Call.Return(err) + return _c +} + +func (_c *TimeoutCollector_AddTimeout_Call) RunAndReturn(run func(timeoutObject *model.TimeoutObject) error) *TimeoutCollector_AddTimeout_Call { + _c.Call.Return(run) + return _c +} + +// View provides a mock function for the type TimeoutCollector +func (_mock *TimeoutCollector) View() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for View") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewTimeoutCollector creates a new instance of TimeoutCollector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutCollector(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutCollector { - mock := &TimeoutCollector{} - mock.Mock.Test(t) +// TimeoutCollector_View_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'View' +type TimeoutCollector_View_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// View is a helper method to define mock.On call +func (_e *TimeoutCollector_Expecter) View() *TimeoutCollector_View_Call { + return &TimeoutCollector_View_Call{Call: _e.mock.On("View")} +} - return mock +func (_c *TimeoutCollector_View_Call) Run(run func()) *TimeoutCollector_View_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TimeoutCollector_View_Call) Return(v uint64) *TimeoutCollector_View_Call { + _c.Call.Return(v) + return _c +} + +func (_c *TimeoutCollector_View_Call) RunAndReturn(run func() uint64) *TimeoutCollector_View_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_collector_consumer.go b/consensus/hotstuff/mocks/timeout_collector_consumer.go index 48fb7c25404..cb190c073ad 100644 --- a/consensus/hotstuff/mocks/timeout_collector_consumer.go +++ b/consensus/hotstuff/mocks/timeout_collector_consumer.go @@ -1,55 +1,250 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewTimeoutCollectorConsumer creates a new instance of TimeoutCollectorConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutCollectorConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutCollectorConsumer { + mock := &TimeoutCollectorConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutCollectorConsumer is an autogenerated mock type for the TimeoutCollectorConsumer type type TimeoutCollectorConsumer struct { mock.Mock } -// OnNewQcDiscovered provides a mock function with given fields: certificate -func (_m *TimeoutCollectorConsumer) OnNewQcDiscovered(certificate *flow.QuorumCertificate) { - _m.Called(certificate) +type TimeoutCollectorConsumer_Expecter struct { + mock *mock.Mock } -// OnNewTcDiscovered provides a mock function with given fields: certificate -func (_m *TimeoutCollectorConsumer) OnNewTcDiscovered(certificate *flow.TimeoutCertificate) { - _m.Called(certificate) +func (_m *TimeoutCollectorConsumer) EXPECT() *TimeoutCollectorConsumer_Expecter { + return &TimeoutCollectorConsumer_Expecter{mock: &_m.Mock} } -// OnPartialTcCreated provides a mock function with given fields: view, newestQC, lastViewTC -func (_m *TimeoutCollectorConsumer) OnPartialTcCreated(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) { - _m.Called(view, newestQC, lastViewTC) +// OnNewQcDiscovered provides a mock function for the type TimeoutCollectorConsumer +func (_mock *TimeoutCollectorConsumer) OnNewQcDiscovered(certificate *flow.QuorumCertificate) { + _mock.Called(certificate) + return } -// OnTcConstructedFromTimeouts provides a mock function with given fields: certificate -func (_m *TimeoutCollectorConsumer) OnTcConstructedFromTimeouts(certificate *flow.TimeoutCertificate) { - _m.Called(certificate) +// TimeoutCollectorConsumer_OnNewQcDiscovered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnNewQcDiscovered' +type TimeoutCollectorConsumer_OnNewQcDiscovered_Call struct { + *mock.Call } -// OnTimeoutProcessed provides a mock function with given fields: timeout -func (_m *TimeoutCollectorConsumer) OnTimeoutProcessed(timeout *model.TimeoutObject) { - _m.Called(timeout) +// OnNewQcDiscovered is a helper method to define mock.On call +// - certificate *flow.QuorumCertificate +func (_e *TimeoutCollectorConsumer_Expecter) OnNewQcDiscovered(certificate interface{}) *TimeoutCollectorConsumer_OnNewQcDiscovered_Call { + return &TimeoutCollectorConsumer_OnNewQcDiscovered_Call{Call: _e.mock.On("OnNewQcDiscovered", certificate)} } -// NewTimeoutCollectorConsumer creates a new instance of TimeoutCollectorConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutCollectorConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutCollectorConsumer { - mock := &TimeoutCollectorConsumer{} - mock.Mock.Test(t) +func (_c *TimeoutCollectorConsumer_OnNewQcDiscovered_Call) Run(run func(certificate *flow.QuorumCertificate)) *TimeoutCollectorConsumer_OnNewQcDiscovered_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *TimeoutCollectorConsumer_OnNewQcDiscovered_Call) Return() *TimeoutCollectorConsumer_OnNewQcDiscovered_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *TimeoutCollectorConsumer_OnNewQcDiscovered_Call) RunAndReturn(run func(certificate *flow.QuorumCertificate)) *TimeoutCollectorConsumer_OnNewQcDiscovered_Call { + _c.Run(run) + return _c +} + +// OnNewTcDiscovered provides a mock function for the type TimeoutCollectorConsumer +func (_mock *TimeoutCollectorConsumer) OnNewTcDiscovered(certificate *flow.TimeoutCertificate) { + _mock.Called(certificate) + return +} + +// TimeoutCollectorConsumer_OnNewTcDiscovered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnNewTcDiscovered' +type TimeoutCollectorConsumer_OnNewTcDiscovered_Call struct { + *mock.Call +} + +// OnNewTcDiscovered is a helper method to define mock.On call +// - certificate *flow.TimeoutCertificate +func (_e *TimeoutCollectorConsumer_Expecter) OnNewTcDiscovered(certificate interface{}) *TimeoutCollectorConsumer_OnNewTcDiscovered_Call { + return &TimeoutCollectorConsumer_OnNewTcDiscovered_Call{Call: _e.mock.On("OnNewTcDiscovered", certificate)} +} + +func (_c *TimeoutCollectorConsumer_OnNewTcDiscovered_Call) Run(run func(certificate *flow.TimeoutCertificate)) *TimeoutCollectorConsumer_OnNewTcDiscovered_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutCollectorConsumer_OnNewTcDiscovered_Call) Return() *TimeoutCollectorConsumer_OnNewTcDiscovered_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutCollectorConsumer_OnNewTcDiscovered_Call) RunAndReturn(run func(certificate *flow.TimeoutCertificate)) *TimeoutCollectorConsumer_OnNewTcDiscovered_Call { + _c.Run(run) + return _c +} + +// OnPartialTcCreated provides a mock function for the type TimeoutCollectorConsumer +func (_mock *TimeoutCollectorConsumer) OnPartialTcCreated(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate) { + _mock.Called(view, newestQC, lastViewTC) + return +} + +// TimeoutCollectorConsumer_OnPartialTcCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPartialTcCreated' +type TimeoutCollectorConsumer_OnPartialTcCreated_Call struct { + *mock.Call +} + +// OnPartialTcCreated is a helper method to define mock.On call +// - view uint64 +// - newestQC *flow.QuorumCertificate +// - lastViewTC *flow.TimeoutCertificate +func (_e *TimeoutCollectorConsumer_Expecter) OnPartialTcCreated(view interface{}, newestQC interface{}, lastViewTC interface{}) *TimeoutCollectorConsumer_OnPartialTcCreated_Call { + return &TimeoutCollectorConsumer_OnPartialTcCreated_Call{Call: _e.mock.On("OnPartialTcCreated", view, newestQC, lastViewTC)} +} + +func (_c *TimeoutCollectorConsumer_OnPartialTcCreated_Call) Run(run func(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *TimeoutCollectorConsumer_OnPartialTcCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + var arg2 *flow.TimeoutCertificate + if args[2] != nil { + arg2 = args[2].(*flow.TimeoutCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TimeoutCollectorConsumer_OnPartialTcCreated_Call) Return() *TimeoutCollectorConsumer_OnPartialTcCreated_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutCollectorConsumer_OnPartialTcCreated_Call) RunAndReturn(run func(view uint64, newestQC *flow.QuorumCertificate, lastViewTC *flow.TimeoutCertificate)) *TimeoutCollectorConsumer_OnPartialTcCreated_Call { + _c.Run(run) + return _c +} + +// OnTcConstructedFromTimeouts provides a mock function for the type TimeoutCollectorConsumer +func (_mock *TimeoutCollectorConsumer) OnTcConstructedFromTimeouts(certificate *flow.TimeoutCertificate) { + _mock.Called(certificate) + return +} + +// TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTcConstructedFromTimeouts' +type TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call struct { + *mock.Call +} + +// OnTcConstructedFromTimeouts is a helper method to define mock.On call +// - certificate *flow.TimeoutCertificate +func (_e *TimeoutCollectorConsumer_Expecter) OnTcConstructedFromTimeouts(certificate interface{}) *TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call { + return &TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call{Call: _e.mock.On("OnTcConstructedFromTimeouts", certificate)} +} + +func (_c *TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call) Run(run func(certificate *flow.TimeoutCertificate)) *TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call) Return() *TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call) RunAndReturn(run func(certificate *flow.TimeoutCertificate)) *TimeoutCollectorConsumer_OnTcConstructedFromTimeouts_Call { + _c.Run(run) + return _c +} + +// OnTimeoutProcessed provides a mock function for the type TimeoutCollectorConsumer +func (_mock *TimeoutCollectorConsumer) OnTimeoutProcessed(timeout *model.TimeoutObject) { + _mock.Called(timeout) + return +} + +// TimeoutCollectorConsumer_OnTimeoutProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTimeoutProcessed' +type TimeoutCollectorConsumer_OnTimeoutProcessed_Call struct { + *mock.Call +} + +// OnTimeoutProcessed is a helper method to define mock.On call +// - timeout *model.TimeoutObject +func (_e *TimeoutCollectorConsumer_Expecter) OnTimeoutProcessed(timeout interface{}) *TimeoutCollectorConsumer_OnTimeoutProcessed_Call { + return &TimeoutCollectorConsumer_OnTimeoutProcessed_Call{Call: _e.mock.On("OnTimeoutProcessed", timeout)} +} + +func (_c *TimeoutCollectorConsumer_OnTimeoutProcessed_Call) Run(run func(timeout *model.TimeoutObject)) *TimeoutCollectorConsumer_OnTimeoutProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutCollectorConsumer_OnTimeoutProcessed_Call) Return() *TimeoutCollectorConsumer_OnTimeoutProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutCollectorConsumer_OnTimeoutProcessed_Call) RunAndReturn(run func(timeout *model.TimeoutObject)) *TimeoutCollectorConsumer_OnTimeoutProcessed_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_collector_factory.go b/consensus/hotstuff/mocks/timeout_collector_factory.go index 9eac542523d..071cc192eb6 100644 --- a/consensus/hotstuff/mocks/timeout_collector_factory.go +++ b/consensus/hotstuff/mocks/timeout_collector_factory.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" mock "github.com/stretchr/testify/mock" ) +// NewTimeoutCollectorFactory creates a new instance of TimeoutCollectorFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutCollectorFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutCollectorFactory { + mock := &TimeoutCollectorFactory{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutCollectorFactory is an autogenerated mock type for the TimeoutCollectorFactory type type TimeoutCollectorFactory struct { mock.Mock } -// Create provides a mock function with given fields: view -func (_m *TimeoutCollectorFactory) Create(view uint64) (hotstuff.TimeoutCollector, error) { - ret := _m.Called(view) +type TimeoutCollectorFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutCollectorFactory) EXPECT() *TimeoutCollectorFactory_Expecter { + return &TimeoutCollectorFactory_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type TimeoutCollectorFactory +func (_mock *TimeoutCollectorFactory) Create(view uint64) (hotstuff.TimeoutCollector, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for Create") @@ -22,36 +46,54 @@ func (_m *TimeoutCollectorFactory) Create(view uint64) (hotstuff.TimeoutCollecto var r0 hotstuff.TimeoutCollector var r1 error - if rf, ok := ret.Get(0).(func(uint64) (hotstuff.TimeoutCollector, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (hotstuff.TimeoutCollector, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) hotstuff.TimeoutCollector); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) hotstuff.TimeoutCollector); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(hotstuff.TimeoutCollector) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTimeoutCollectorFactory creates a new instance of TimeoutCollectorFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutCollectorFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutCollectorFactory { - mock := &TimeoutCollectorFactory{} - mock.Mock.Test(t) +// TimeoutCollectorFactory_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type TimeoutCollectorFactory_Create_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Create is a helper method to define mock.On call +// - view uint64 +func (_e *TimeoutCollectorFactory_Expecter) Create(view interface{}) *TimeoutCollectorFactory_Create_Call { + return &TimeoutCollectorFactory_Create_Call{Call: _e.mock.On("Create", view)} +} - return mock +func (_c *TimeoutCollectorFactory_Create_Call) Run(run func(view uint64)) *TimeoutCollectorFactory_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutCollectorFactory_Create_Call) Return(timeoutCollector hotstuff.TimeoutCollector, err error) *TimeoutCollectorFactory_Create_Call { + _c.Call.Return(timeoutCollector, err) + return _c +} + +func (_c *TimeoutCollectorFactory_Create_Call) RunAndReturn(run func(view uint64) (hotstuff.TimeoutCollector, error)) *TimeoutCollectorFactory_Create_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_collectors.go b/consensus/hotstuff/mocks/timeout_collectors.go index c2f15d5b294..a92028000bc 100644 --- a/consensus/hotstuff/mocks/timeout_collectors.go +++ b/consensus/hotstuff/mocks/timeout_collectors.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" mock "github.com/stretchr/testify/mock" ) +// NewTimeoutCollectors creates a new instance of TimeoutCollectors. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutCollectors(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutCollectors { + mock := &TimeoutCollectors{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutCollectors is an autogenerated mock type for the TimeoutCollectors type type TimeoutCollectors struct { mock.Mock } -// GetOrCreateCollector provides a mock function with given fields: view -func (_m *TimeoutCollectors) GetOrCreateCollector(view uint64) (hotstuff.TimeoutCollector, bool, error) { - ret := _m.Called(view) +type TimeoutCollectors_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutCollectors) EXPECT() *TimeoutCollectors_Expecter { + return &TimeoutCollectors_Expecter{mock: &_m.Mock} +} + +// GetOrCreateCollector provides a mock function for the type TimeoutCollectors +func (_mock *TimeoutCollectors) GetOrCreateCollector(view uint64) (hotstuff.TimeoutCollector, bool, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for GetOrCreateCollector") @@ -23,47 +47,99 @@ func (_m *TimeoutCollectors) GetOrCreateCollector(view uint64) (hotstuff.Timeout var r0 hotstuff.TimeoutCollector var r1 bool var r2 error - if rf, ok := ret.Get(0).(func(uint64) (hotstuff.TimeoutCollector, bool, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (hotstuff.TimeoutCollector, bool, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) hotstuff.TimeoutCollector); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) hotstuff.TimeoutCollector); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(hotstuff.TimeoutCollector) } } - - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(view) } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(view) + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(view) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// PruneUpToView provides a mock function with given fields: lowestRetainedView -func (_m *TimeoutCollectors) PruneUpToView(lowestRetainedView uint64) { - _m.Called(lowestRetainedView) +// TimeoutCollectors_GetOrCreateCollector_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOrCreateCollector' +type TimeoutCollectors_GetOrCreateCollector_Call struct { + *mock.Call } -// NewTimeoutCollectors creates a new instance of TimeoutCollectors. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutCollectors(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutCollectors { - mock := &TimeoutCollectors{} - mock.Mock.Test(t) +// GetOrCreateCollector is a helper method to define mock.On call +// - view uint64 +func (_e *TimeoutCollectors_Expecter) GetOrCreateCollector(view interface{}) *TimeoutCollectors_GetOrCreateCollector_Call { + return &TimeoutCollectors_GetOrCreateCollector_Call{Call: _e.mock.On("GetOrCreateCollector", view)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *TimeoutCollectors_GetOrCreateCollector_Call) Run(run func(view uint64)) *TimeoutCollectors_GetOrCreateCollector_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *TimeoutCollectors_GetOrCreateCollector_Call) Return(collector hotstuff.TimeoutCollector, created bool, err error) *TimeoutCollectors_GetOrCreateCollector_Call { + _c.Call.Return(collector, created, err) + return _c +} + +func (_c *TimeoutCollectors_GetOrCreateCollector_Call) RunAndReturn(run func(view uint64) (hotstuff.TimeoutCollector, bool, error)) *TimeoutCollectors_GetOrCreateCollector_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToView provides a mock function for the type TimeoutCollectors +func (_mock *TimeoutCollectors) PruneUpToView(lowestRetainedView uint64) { + _mock.Called(lowestRetainedView) + return +} + +// TimeoutCollectors_PruneUpToView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToView' +type TimeoutCollectors_PruneUpToView_Call struct { + *mock.Call +} + +// PruneUpToView is a helper method to define mock.On call +// - lowestRetainedView uint64 +func (_e *TimeoutCollectors_Expecter) PruneUpToView(lowestRetainedView interface{}) *TimeoutCollectors_PruneUpToView_Call { + return &TimeoutCollectors_PruneUpToView_Call{Call: _e.mock.On("PruneUpToView", lowestRetainedView)} +} + +func (_c *TimeoutCollectors_PruneUpToView_Call) Run(run func(lowestRetainedView uint64)) *TimeoutCollectors_PruneUpToView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutCollectors_PruneUpToView_Call) Return() *TimeoutCollectors_PruneUpToView_Call { + _c.Call.Return() + return _c +} + +func (_c *TimeoutCollectors_PruneUpToView_Call) RunAndReturn(run func(lowestRetainedView uint64)) *TimeoutCollectors_PruneUpToView_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_processor.go b/consensus/hotstuff/mocks/timeout_processor.go index c2c42a3b99b..1d8c4860228 100644 --- a/consensus/hotstuff/mocks/timeout_processor.go +++ b/consensus/hotstuff/mocks/timeout_processor.go @@ -1,45 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - model "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" ) +// NewTimeoutProcessor creates a new instance of TimeoutProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutProcessor(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutProcessor { + mock := &TimeoutProcessor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutProcessor is an autogenerated mock type for the TimeoutProcessor type type TimeoutProcessor struct { mock.Mock } -// Process provides a mock function with given fields: timeout -func (_m *TimeoutProcessor) Process(timeout *model.TimeoutObject) error { - ret := _m.Called(timeout) +type TimeoutProcessor_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutProcessor) EXPECT() *TimeoutProcessor_Expecter { + return &TimeoutProcessor_Expecter{mock: &_m.Mock} +} + +// Process provides a mock function for the type TimeoutProcessor +func (_mock *TimeoutProcessor) Process(timeout *model.TimeoutObject) error { + ret := _mock.Called(timeout) if len(ret) == 0 { panic("no return value specified for Process") } var r0 error - if rf, ok := ret.Get(0).(func(*model.TimeoutObject) error); ok { - r0 = rf(timeout) + if returnFunc, ok := ret.Get(0).(func(*model.TimeoutObject) error); ok { + r0 = returnFunc(timeout) } else { r0 = ret.Error(0) } - return r0 } -// NewTimeoutProcessor creates a new instance of TimeoutProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutProcessor(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutProcessor { - mock := &TimeoutProcessor{} - mock.Mock.Test(t) +// TimeoutProcessor_Process_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Process' +type TimeoutProcessor_Process_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Process is a helper method to define mock.On call +// - timeout *model.TimeoutObject +func (_e *TimeoutProcessor_Expecter) Process(timeout interface{}) *TimeoutProcessor_Process_Call { + return &TimeoutProcessor_Process_Call{Call: _e.mock.On("Process", timeout)} +} - return mock +func (_c *TimeoutProcessor_Process_Call) Run(run func(timeout *model.TimeoutObject)) *TimeoutProcessor_Process_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.TimeoutObject + if args[0] != nil { + arg0 = args[0].(*model.TimeoutObject) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutProcessor_Process_Call) Return(err error) *TimeoutProcessor_Process_Call { + _c.Call.Return(err) + return _c +} + +func (_c *TimeoutProcessor_Process_Call) RunAndReturn(run func(timeout *model.TimeoutObject) error) *TimeoutProcessor_Process_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_processor_factory.go b/consensus/hotstuff/mocks/timeout_processor_factory.go index 074112dcc88..f7b763f30e8 100644 --- a/consensus/hotstuff/mocks/timeout_processor_factory.go +++ b/consensus/hotstuff/mocks/timeout_processor_factory.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" mock "github.com/stretchr/testify/mock" ) +// NewTimeoutProcessorFactory creates a new instance of TimeoutProcessorFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutProcessorFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutProcessorFactory { + mock := &TimeoutProcessorFactory{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutProcessorFactory is an autogenerated mock type for the TimeoutProcessorFactory type type TimeoutProcessorFactory struct { mock.Mock } -// Create provides a mock function with given fields: view -func (_m *TimeoutProcessorFactory) Create(view uint64) (hotstuff.TimeoutProcessor, error) { - ret := _m.Called(view) +type TimeoutProcessorFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutProcessorFactory) EXPECT() *TimeoutProcessorFactory_Expecter { + return &TimeoutProcessorFactory_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type TimeoutProcessorFactory +func (_mock *TimeoutProcessorFactory) Create(view uint64) (hotstuff.TimeoutProcessor, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for Create") @@ -22,36 +46,54 @@ func (_m *TimeoutProcessorFactory) Create(view uint64) (hotstuff.TimeoutProcesso var r0 hotstuff.TimeoutProcessor var r1 error - if rf, ok := ret.Get(0).(func(uint64) (hotstuff.TimeoutProcessor, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (hotstuff.TimeoutProcessor, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) hotstuff.TimeoutProcessor); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) hotstuff.TimeoutProcessor); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(hotstuff.TimeoutProcessor) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTimeoutProcessorFactory creates a new instance of TimeoutProcessorFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutProcessorFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutProcessorFactory { - mock := &TimeoutProcessorFactory{} - mock.Mock.Test(t) +// TimeoutProcessorFactory_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type TimeoutProcessorFactory_Create_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Create is a helper method to define mock.On call +// - view uint64 +func (_e *TimeoutProcessorFactory_Expecter) Create(view interface{}) *TimeoutProcessorFactory_Create_Call { + return &TimeoutProcessorFactory_Create_Call{Call: _e.mock.On("Create", view)} +} - return mock +func (_c *TimeoutProcessorFactory_Create_Call) Run(run func(view uint64)) *TimeoutProcessorFactory_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TimeoutProcessorFactory_Create_Call) Return(timeoutProcessor hotstuff.TimeoutProcessor, err error) *TimeoutProcessorFactory_Create_Call { + _c.Call.Return(timeoutProcessor, err) + return _c +} + +func (_c *TimeoutProcessorFactory_Create_Call) RunAndReturn(run func(view uint64) (hotstuff.TimeoutProcessor, error)) *TimeoutProcessorFactory_Create_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/timeout_signature_aggregator.go b/consensus/hotstuff/mocks/timeout_signature_aggregator.go index 3c39fe843a9..785fbdbdcd2 100644 --- a/consensus/hotstuff/mocks/timeout_signature_aggregator.go +++ b/consensus/hotstuff/mocks/timeout_signature_aggregator.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTimeoutSignatureAggregator creates a new instance of TimeoutSignatureAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeoutSignatureAggregator(t interface { + mock.TestingT + Cleanup(func()) +}) *TimeoutSignatureAggregator { + mock := &TimeoutSignatureAggregator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TimeoutSignatureAggregator is an autogenerated mock type for the TimeoutSignatureAggregator type type TimeoutSignatureAggregator struct { mock.Mock } -// Aggregate provides a mock function with no fields -func (_m *TimeoutSignatureAggregator) Aggregate() ([]hotstuff.TimeoutSignerInfo, crypto.Signature, error) { - ret := _m.Called() +type TimeoutSignatureAggregator_Expecter struct { + mock *mock.Mock +} + +func (_m *TimeoutSignatureAggregator) EXPECT() *TimeoutSignatureAggregator_Expecter { + return &TimeoutSignatureAggregator_Expecter{mock: &_m.Mock} +} + +// Aggregate provides a mock function for the type TimeoutSignatureAggregator +func (_mock *TimeoutSignatureAggregator) Aggregate() ([]hotstuff.TimeoutSignerInfo, crypto.Signature, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Aggregate") @@ -27,55 +49,105 @@ func (_m *TimeoutSignatureAggregator) Aggregate() ([]hotstuff.TimeoutSignerInfo, var r0 []hotstuff.TimeoutSignerInfo var r1 crypto.Signature var r2 error - if rf, ok := ret.Get(0).(func() ([]hotstuff.TimeoutSignerInfo, crypto.Signature, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]hotstuff.TimeoutSignerInfo, crypto.Signature, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []hotstuff.TimeoutSignerInfo); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []hotstuff.TimeoutSignerInfo); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]hotstuff.TimeoutSignerInfo) } } - - if rf, ok := ret.Get(1).(func() crypto.Signature); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() crypto.Signature); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).(crypto.Signature) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// TotalWeight provides a mock function with no fields -func (_m *TimeoutSignatureAggregator) TotalWeight() uint64 { - ret := _m.Called() +// TimeoutSignatureAggregator_Aggregate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Aggregate' +type TimeoutSignatureAggregator_Aggregate_Call struct { + *mock.Call +} + +// Aggregate is a helper method to define mock.On call +func (_e *TimeoutSignatureAggregator_Expecter) Aggregate() *TimeoutSignatureAggregator_Aggregate_Call { + return &TimeoutSignatureAggregator_Aggregate_Call{Call: _e.mock.On("Aggregate")} +} + +func (_c *TimeoutSignatureAggregator_Aggregate_Call) Run(run func()) *TimeoutSignatureAggregator_Aggregate_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TimeoutSignatureAggregator_Aggregate_Call) Return(signersInfo []hotstuff.TimeoutSignerInfo, aggregatedSig crypto.Signature, exception error) *TimeoutSignatureAggregator_Aggregate_Call { + _c.Call.Return(signersInfo, aggregatedSig, exception) + return _c +} + +func (_c *TimeoutSignatureAggregator_Aggregate_Call) RunAndReturn(run func() ([]hotstuff.TimeoutSignerInfo, crypto.Signature, error)) *TimeoutSignatureAggregator_Aggregate_Call { + _c.Call.Return(run) + return _c +} + +// TotalWeight provides a mock function for the type TimeoutSignatureAggregator +func (_mock *TimeoutSignatureAggregator) TotalWeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TotalWeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// VerifyAndAdd provides a mock function with given fields: signerID, sig, newestQCView -func (_m *TimeoutSignatureAggregator) VerifyAndAdd(signerID flow.Identifier, sig crypto.Signature, newestQCView uint64) (uint64, error) { - ret := _m.Called(signerID, sig, newestQCView) +// TimeoutSignatureAggregator_TotalWeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TotalWeight' +type TimeoutSignatureAggregator_TotalWeight_Call struct { + *mock.Call +} + +// TotalWeight is a helper method to define mock.On call +func (_e *TimeoutSignatureAggregator_Expecter) TotalWeight() *TimeoutSignatureAggregator_TotalWeight_Call { + return &TimeoutSignatureAggregator_TotalWeight_Call{Call: _e.mock.On("TotalWeight")} +} + +func (_c *TimeoutSignatureAggregator_TotalWeight_Call) Run(run func()) *TimeoutSignatureAggregator_TotalWeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TimeoutSignatureAggregator_TotalWeight_Call) Return(v uint64) *TimeoutSignatureAggregator_TotalWeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *TimeoutSignatureAggregator_TotalWeight_Call) RunAndReturn(run func() uint64) *TimeoutSignatureAggregator_TotalWeight_Call { + _c.Call.Return(run) + return _c +} + +// VerifyAndAdd provides a mock function for the type TimeoutSignatureAggregator +func (_mock *TimeoutSignatureAggregator) VerifyAndAdd(signerID flow.Identifier, sig crypto.Signature, newestQCView uint64) (uint64, error) { + ret := _mock.Called(signerID, sig, newestQCView) if len(ret) == 0 { panic("no return value specified for VerifyAndAdd") @@ -83,52 +155,108 @@ func (_m *TimeoutSignatureAggregator) VerifyAndAdd(signerID flow.Identifier, sig var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature, uint64) (uint64, error)); ok { - return rf(signerID, sig, newestQCView) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature, uint64) (uint64, error)); ok { + return returnFunc(signerID, sig, newestQCView) } - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature, uint64) uint64); ok { - r0 = rf(signerID, sig, newestQCView) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature, uint64) uint64); ok { + r0 = returnFunc(signerID, sig, newestQCView) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier, crypto.Signature, uint64) error); ok { - r1 = rf(signerID, sig, newestQCView) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, crypto.Signature, uint64) error); ok { + r1 = returnFunc(signerID, sig, newestQCView) } else { r1 = ret.Error(1) } - return r0, r1 } -// View provides a mock function with no fields -func (_m *TimeoutSignatureAggregator) View() uint64 { - ret := _m.Called() +// TimeoutSignatureAggregator_VerifyAndAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyAndAdd' +type TimeoutSignatureAggregator_VerifyAndAdd_Call struct { + *mock.Call +} + +// VerifyAndAdd is a helper method to define mock.On call +// - signerID flow.Identifier +// - sig crypto.Signature +// - newestQCView uint64 +func (_e *TimeoutSignatureAggregator_Expecter) VerifyAndAdd(signerID interface{}, sig interface{}, newestQCView interface{}) *TimeoutSignatureAggregator_VerifyAndAdd_Call { + return &TimeoutSignatureAggregator_VerifyAndAdd_Call{Call: _e.mock.On("VerifyAndAdd", signerID, sig, newestQCView)} +} + +func (_c *TimeoutSignatureAggregator_VerifyAndAdd_Call) Run(run func(signerID flow.Identifier, sig crypto.Signature, newestQCView uint64)) *TimeoutSignatureAggregator_VerifyAndAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TimeoutSignatureAggregator_VerifyAndAdd_Call) Return(totalWeight uint64, exception error) *TimeoutSignatureAggregator_VerifyAndAdd_Call { + _c.Call.Return(totalWeight, exception) + return _c +} + +func (_c *TimeoutSignatureAggregator_VerifyAndAdd_Call) RunAndReturn(run func(signerID flow.Identifier, sig crypto.Signature, newestQCView uint64) (uint64, error)) *TimeoutSignatureAggregator_VerifyAndAdd_Call { + _c.Call.Return(run) + return _c +} + +// View provides a mock function for the type TimeoutSignatureAggregator +func (_mock *TimeoutSignatureAggregator) View() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for View") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewTimeoutSignatureAggregator creates a new instance of TimeoutSignatureAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTimeoutSignatureAggregator(t interface { - mock.TestingT - Cleanup(func()) -}) *TimeoutSignatureAggregator { - mock := &TimeoutSignatureAggregator{} - mock.Mock.Test(t) +// TimeoutSignatureAggregator_View_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'View' +type TimeoutSignatureAggregator_View_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// View is a helper method to define mock.On call +func (_e *TimeoutSignatureAggregator_Expecter) View() *TimeoutSignatureAggregator_View_Call { + return &TimeoutSignatureAggregator_View_Call{Call: _e.mock.On("View")} +} - return mock +func (_c *TimeoutSignatureAggregator_View_Call) Run(run func()) *TimeoutSignatureAggregator_View_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TimeoutSignatureAggregator_View_Call) Return(v uint64) *TimeoutSignatureAggregator_View_Call { + _c.Call.Return(v) + return _c +} + +func (_c *TimeoutSignatureAggregator_View_Call) RunAndReturn(run func() uint64) *TimeoutSignatureAggregator_View_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/validator.go b/consensus/hotstuff/mocks/validator.go index 18f60590d0e..4aac815f646 100644 --- a/consensus/hotstuff/mocks/validator.go +++ b/consensus/hotstuff/mocks/validator.go @@ -1,77 +1,198 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewValidator creates a new instance of Validator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewValidator(t interface { + mock.TestingT + Cleanup(func()) +}) *Validator { + mock := &Validator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Validator is an autogenerated mock type for the Validator type type Validator struct { mock.Mock } -// ValidateProposal provides a mock function with given fields: proposal -func (_m *Validator) ValidateProposal(proposal *model.SignedProposal) error { - ret := _m.Called(proposal) +type Validator_Expecter struct { + mock *mock.Mock +} + +func (_m *Validator) EXPECT() *Validator_Expecter { + return &Validator_Expecter{mock: &_m.Mock} +} + +// ValidateProposal provides a mock function for the type Validator +func (_mock *Validator) ValidateProposal(proposal *model.SignedProposal) error { + ret := _mock.Called(proposal) if len(ret) == 0 { panic("no return value specified for ValidateProposal") } var r0 error - if rf, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { - r0 = rf(proposal) + if returnFunc, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { + r0 = returnFunc(proposal) } else { r0 = ret.Error(0) } - return r0 } -// ValidateQC provides a mock function with given fields: qc -func (_m *Validator) ValidateQC(qc *flow.QuorumCertificate) error { - ret := _m.Called(qc) +// Validator_ValidateProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidateProposal' +type Validator_ValidateProposal_Call struct { + *mock.Call +} + +// ValidateProposal is a helper method to define mock.On call +// - proposal *model.SignedProposal +func (_e *Validator_Expecter) ValidateProposal(proposal interface{}) *Validator_ValidateProposal_Call { + return &Validator_ValidateProposal_Call{Call: _e.mock.On("ValidateProposal", proposal)} +} + +func (_c *Validator_ValidateProposal_Call) Run(run func(proposal *model.SignedProposal)) *Validator_ValidateProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Validator_ValidateProposal_Call) Return(err error) *Validator_ValidateProposal_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Validator_ValidateProposal_Call) RunAndReturn(run func(proposal *model.SignedProposal) error) *Validator_ValidateProposal_Call { + _c.Call.Return(run) + return _c +} + +// ValidateQC provides a mock function for the type Validator +func (_mock *Validator) ValidateQC(qc *flow.QuorumCertificate) error { + ret := _mock.Called(qc) if len(ret) == 0 { panic("no return value specified for ValidateQC") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.QuorumCertificate) error); ok { - r0 = rf(qc) + if returnFunc, ok := ret.Get(0).(func(*flow.QuorumCertificate) error); ok { + r0 = returnFunc(qc) } else { r0 = ret.Error(0) } - return r0 } -// ValidateTC provides a mock function with given fields: tc -func (_m *Validator) ValidateTC(tc *flow.TimeoutCertificate) error { - ret := _m.Called(tc) +// Validator_ValidateQC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidateQC' +type Validator_ValidateQC_Call struct { + *mock.Call +} + +// ValidateQC is a helper method to define mock.On call +// - qc *flow.QuorumCertificate +func (_e *Validator_Expecter) ValidateQC(qc interface{}) *Validator_ValidateQC_Call { + return &Validator_ValidateQC_Call{Call: _e.mock.On("ValidateQC", qc)} +} + +func (_c *Validator_ValidateQC_Call) Run(run func(qc *flow.QuorumCertificate)) *Validator_ValidateQC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Validator_ValidateQC_Call) Return(err error) *Validator_ValidateQC_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Validator_ValidateQC_Call) RunAndReturn(run func(qc *flow.QuorumCertificate) error) *Validator_ValidateQC_Call { + _c.Call.Return(run) + return _c +} + +// ValidateTC provides a mock function for the type Validator +func (_mock *Validator) ValidateTC(tc *flow.TimeoutCertificate) error { + ret := _mock.Called(tc) if len(ret) == 0 { panic("no return value specified for ValidateTC") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.TimeoutCertificate) error); ok { - r0 = rf(tc) + if returnFunc, ok := ret.Get(0).(func(*flow.TimeoutCertificate) error); ok { + r0 = returnFunc(tc) } else { r0 = ret.Error(0) } - return r0 } -// ValidateVote provides a mock function with given fields: vote -func (_m *Validator) ValidateVote(vote *model.Vote) (*flow.IdentitySkeleton, error) { - ret := _m.Called(vote) +// Validator_ValidateTC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidateTC' +type Validator_ValidateTC_Call struct { + *mock.Call +} + +// ValidateTC is a helper method to define mock.On call +// - tc *flow.TimeoutCertificate +func (_e *Validator_Expecter) ValidateTC(tc interface{}) *Validator_ValidateTC_Call { + return &Validator_ValidateTC_Call{Call: _e.mock.On("ValidateTC", tc)} +} + +func (_c *Validator_ValidateTC_Call) Run(run func(tc *flow.TimeoutCertificate)) *Validator_ValidateTC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TimeoutCertificate + if args[0] != nil { + arg0 = args[0].(*flow.TimeoutCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Validator_ValidateTC_Call) Return(err error) *Validator_ValidateTC_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Validator_ValidateTC_Call) RunAndReturn(run func(tc *flow.TimeoutCertificate) error) *Validator_ValidateTC_Call { + _c.Call.Return(run) + return _c +} + +// ValidateVote provides a mock function for the type Validator +func (_mock *Validator) ValidateVote(vote *model.Vote) (*flow.IdentitySkeleton, error) { + ret := _mock.Called(vote) if len(ret) == 0 { panic("no return value specified for ValidateVote") @@ -79,36 +200,54 @@ func (_m *Validator) ValidateVote(vote *model.Vote) (*flow.IdentitySkeleton, err var r0 *flow.IdentitySkeleton var r1 error - if rf, ok := ret.Get(0).(func(*model.Vote) (*flow.IdentitySkeleton, error)); ok { - return rf(vote) + if returnFunc, ok := ret.Get(0).(func(*model.Vote) (*flow.IdentitySkeleton, error)); ok { + return returnFunc(vote) } - if rf, ok := ret.Get(0).(func(*model.Vote) *flow.IdentitySkeleton); ok { - r0 = rf(vote) + if returnFunc, ok := ret.Get(0).(func(*model.Vote) *flow.IdentitySkeleton); ok { + r0 = returnFunc(vote) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.IdentitySkeleton) } } - - if rf, ok := ret.Get(1).(func(*model.Vote) error); ok { - r1 = rf(vote) + if returnFunc, ok := ret.Get(1).(func(*model.Vote) error); ok { + r1 = returnFunc(vote) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewValidator creates a new instance of Validator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewValidator(t interface { - mock.TestingT - Cleanup(func()) -}) *Validator { - mock := &Validator{} - mock.Mock.Test(t) +// Validator_ValidateVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidateVote' +type Validator_ValidateVote_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ValidateVote is a helper method to define mock.On call +// - vote *model.Vote +func (_e *Validator_Expecter) ValidateVote(vote interface{}) *Validator_ValidateVote_Call { + return &Validator_ValidateVote_Call{Call: _e.mock.On("ValidateVote", vote)} +} - return mock +func (_c *Validator_ValidateVote_Call) Run(run func(vote *model.Vote)) *Validator_ValidateVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Validator_ValidateVote_Call) Return(identitySkeleton *flow.IdentitySkeleton, err error) *Validator_ValidateVote_Call { + _c.Call.Return(identitySkeleton, err) + return _c +} + +func (_c *Validator_ValidateVote_Call) RunAndReturn(run func(vote *model.Vote) (*flow.IdentitySkeleton, error)) *Validator_ValidateVote_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/verifier.go b/consensus/hotstuff/mocks/verifier.go index 38c1fa81ee7..f153a0b7218 100644 --- a/consensus/hotstuff/mocks/verifier.go +++ b/consensus/hotstuff/mocks/verifier.go @@ -1,82 +1,244 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewVerifier creates a new instance of Verifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVerifier(t interface { + mock.TestingT + Cleanup(func()) +}) *Verifier { + mock := &Verifier{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Verifier is an autogenerated mock type for the Verifier type type Verifier struct { mock.Mock } -// VerifyQC provides a mock function with given fields: signers, sigData, view, blockID -func (_m *Verifier) VerifyQC(signers flow.IdentitySkeletonList, sigData []byte, view uint64, blockID flow.Identifier) error { - ret := _m.Called(signers, sigData, view, blockID) +type Verifier_Expecter struct { + mock *mock.Mock +} + +func (_m *Verifier) EXPECT() *Verifier_Expecter { + return &Verifier_Expecter{mock: &_m.Mock} +} + +// VerifyQC provides a mock function for the type Verifier +func (_mock *Verifier) VerifyQC(signers flow.IdentitySkeletonList, sigData []byte, view uint64, blockID flow.Identifier) error { + ret := _mock.Called(signers, sigData, view, blockID) if len(ret) == 0 { panic("no return value specified for VerifyQC") } var r0 error - if rf, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte, uint64, flow.Identifier) error); ok { - r0 = rf(signers, sigData, view, blockID) + if returnFunc, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte, uint64, flow.Identifier) error); ok { + r0 = returnFunc(signers, sigData, view, blockID) } else { r0 = ret.Error(0) } - return r0 } -// VerifyTC provides a mock function with given fields: signers, sigData, view, highQCViews -func (_m *Verifier) VerifyTC(signers flow.IdentitySkeletonList, sigData []byte, view uint64, highQCViews []uint64) error { - ret := _m.Called(signers, sigData, view, highQCViews) +// Verifier_VerifyQC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyQC' +type Verifier_VerifyQC_Call struct { + *mock.Call +} + +// VerifyQC is a helper method to define mock.On call +// - signers flow.IdentitySkeletonList +// - sigData []byte +// - view uint64 +// - blockID flow.Identifier +func (_e *Verifier_Expecter) VerifyQC(signers interface{}, sigData interface{}, view interface{}, blockID interface{}) *Verifier_VerifyQC_Call { + return &Verifier_VerifyQC_Call{Call: _e.mock.On("VerifyQC", signers, sigData, view, blockID)} +} + +func (_c *Verifier_VerifyQC_Call) Run(run func(signers flow.IdentitySkeletonList, sigData []byte, view uint64, blockID flow.Identifier)) *Verifier_VerifyQC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.IdentitySkeletonList + if args[0] != nil { + arg0 = args[0].(flow.IdentitySkeletonList) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Verifier_VerifyQC_Call) Return(err error) *Verifier_VerifyQC_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Verifier_VerifyQC_Call) RunAndReturn(run func(signers flow.IdentitySkeletonList, sigData []byte, view uint64, blockID flow.Identifier) error) *Verifier_VerifyQC_Call { + _c.Call.Return(run) + return _c +} + +// VerifyTC provides a mock function for the type Verifier +func (_mock *Verifier) VerifyTC(signers flow.IdentitySkeletonList, sigData []byte, view uint64, highQCViews []uint64) error { + ret := _mock.Called(signers, sigData, view, highQCViews) if len(ret) == 0 { panic("no return value specified for VerifyTC") } var r0 error - if rf, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte, uint64, []uint64) error); ok { - r0 = rf(signers, sigData, view, highQCViews) + if returnFunc, ok := ret.Get(0).(func(flow.IdentitySkeletonList, []byte, uint64, []uint64) error); ok { + r0 = returnFunc(signers, sigData, view, highQCViews) } else { r0 = ret.Error(0) } - return r0 } -// VerifyVote provides a mock function with given fields: voter, sigData, view, blockID -func (_m *Verifier) VerifyVote(voter *flow.IdentitySkeleton, sigData []byte, view uint64, blockID flow.Identifier) error { - ret := _m.Called(voter, sigData, view, blockID) +// Verifier_VerifyTC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyTC' +type Verifier_VerifyTC_Call struct { + *mock.Call +} + +// VerifyTC is a helper method to define mock.On call +// - signers flow.IdentitySkeletonList +// - sigData []byte +// - view uint64 +// - highQCViews []uint64 +func (_e *Verifier_Expecter) VerifyTC(signers interface{}, sigData interface{}, view interface{}, highQCViews interface{}) *Verifier_VerifyTC_Call { + return &Verifier_VerifyTC_Call{Call: _e.mock.On("VerifyTC", signers, sigData, view, highQCViews)} +} + +func (_c *Verifier_VerifyTC_Call) Run(run func(signers flow.IdentitySkeletonList, sigData []byte, view uint64, highQCViews []uint64)) *Verifier_VerifyTC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.IdentitySkeletonList + if args[0] != nil { + arg0 = args[0].(flow.IdentitySkeletonList) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []uint64 + if args[3] != nil { + arg3 = args[3].([]uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Verifier_VerifyTC_Call) Return(err error) *Verifier_VerifyTC_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Verifier_VerifyTC_Call) RunAndReturn(run func(signers flow.IdentitySkeletonList, sigData []byte, view uint64, highQCViews []uint64) error) *Verifier_VerifyTC_Call { + _c.Call.Return(run) + return _c +} + +// VerifyVote provides a mock function for the type Verifier +func (_mock *Verifier) VerifyVote(voter *flow.IdentitySkeleton, sigData []byte, view uint64, blockID flow.Identifier) error { + ret := _mock.Called(voter, sigData, view, blockID) if len(ret) == 0 { panic("no return value specified for VerifyVote") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.IdentitySkeleton, []byte, uint64, flow.Identifier) error); ok { - r0 = rf(voter, sigData, view, blockID) + if returnFunc, ok := ret.Get(0).(func(*flow.IdentitySkeleton, []byte, uint64, flow.Identifier) error); ok { + r0 = returnFunc(voter, sigData, view, blockID) } else { r0 = ret.Error(0) } - return r0 } -// NewVerifier creates a new instance of Verifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVerifier(t interface { - mock.TestingT - Cleanup(func()) -}) *Verifier { - mock := &Verifier{} - mock.Mock.Test(t) +// Verifier_VerifyVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyVote' +type Verifier_VerifyVote_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VerifyVote is a helper method to define mock.On call +// - voter *flow.IdentitySkeleton +// - sigData []byte +// - view uint64 +// - blockID flow.Identifier +func (_e *Verifier_Expecter) VerifyVote(voter interface{}, sigData interface{}, view interface{}, blockID interface{}) *Verifier_VerifyVote_Call { + return &Verifier_VerifyVote_Call{Call: _e.mock.On("VerifyVote", voter, sigData, view, blockID)} +} - return mock +func (_c *Verifier_VerifyVote_Call) Run(run func(voter *flow.IdentitySkeleton, sigData []byte, view uint64, blockID flow.Identifier)) *Verifier_VerifyVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IdentitySkeleton + if args[0] != nil { + arg0 = args[0].(*flow.IdentitySkeleton) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Verifier_VerifyVote_Call) Return(err error) *Verifier_VerifyVote_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Verifier_VerifyVote_Call) RunAndReturn(run func(voter *flow.IdentitySkeleton, sigData []byte, view uint64, blockID flow.Identifier) error) *Verifier_VerifyVote_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/verifying_vote_processor.go b/consensus/hotstuff/mocks/verifying_vote_processor.go index 105346f3a3e..9639d57b8f9 100644 --- a/consensus/hotstuff/mocks/verifying_vote_processor.go +++ b/consensus/hotstuff/mocks/verifying_vote_processor.go @@ -1,85 +1,179 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewVerifyingVoteProcessor creates a new instance of VerifyingVoteProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVerifyingVoteProcessor(t interface { + mock.TestingT + Cleanup(func()) +}) *VerifyingVoteProcessor { + mock := &VerifyingVoteProcessor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VerifyingVoteProcessor is an autogenerated mock type for the VerifyingVoteProcessor type type VerifyingVoteProcessor struct { mock.Mock } -// Block provides a mock function with no fields -func (_m *VerifyingVoteProcessor) Block() *model.Block { - ret := _m.Called() +type VerifyingVoteProcessor_Expecter struct { + mock *mock.Mock +} + +func (_m *VerifyingVoteProcessor) EXPECT() *VerifyingVoteProcessor_Expecter { + return &VerifyingVoteProcessor_Expecter{mock: &_m.Mock} +} + +// Block provides a mock function for the type VerifyingVoteProcessor +func (_mock *VerifyingVoteProcessor) Block() *model.Block { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Block") } var r0 *model.Block - if rf, ok := ret.Get(0).(func() *model.Block); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *model.Block); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Block) } } - return r0 } -// Process provides a mock function with given fields: vote -func (_m *VerifyingVoteProcessor) Process(vote *model.Vote) error { - ret := _m.Called(vote) +// VerifyingVoteProcessor_Block_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Block' +type VerifyingVoteProcessor_Block_Call struct { + *mock.Call +} + +// Block is a helper method to define mock.On call +func (_e *VerifyingVoteProcessor_Expecter) Block() *VerifyingVoteProcessor_Block_Call { + return &VerifyingVoteProcessor_Block_Call{Call: _e.mock.On("Block")} +} + +func (_c *VerifyingVoteProcessor_Block_Call) Run(run func()) *VerifyingVoteProcessor_Block_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerifyingVoteProcessor_Block_Call) Return(block *model.Block) *VerifyingVoteProcessor_Block_Call { + _c.Call.Return(block) + return _c +} + +func (_c *VerifyingVoteProcessor_Block_Call) RunAndReturn(run func() *model.Block) *VerifyingVoteProcessor_Block_Call { + _c.Call.Return(run) + return _c +} + +// Process provides a mock function for the type VerifyingVoteProcessor +func (_mock *VerifyingVoteProcessor) Process(vote *model.Vote) error { + ret := _mock.Called(vote) if len(ret) == 0 { panic("no return value specified for Process") } var r0 error - if rf, ok := ret.Get(0).(func(*model.Vote) error); ok { - r0 = rf(vote) + if returnFunc, ok := ret.Get(0).(func(*model.Vote) error); ok { + r0 = returnFunc(vote) } else { r0 = ret.Error(0) } - return r0 } -// Status provides a mock function with no fields -func (_m *VerifyingVoteProcessor) Status() hotstuff.VoteCollectorStatus { - ret := _m.Called() +// VerifyingVoteProcessor_Process_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Process' +type VerifyingVoteProcessor_Process_Call struct { + *mock.Call +} + +// Process is a helper method to define mock.On call +// - vote *model.Vote +func (_e *VerifyingVoteProcessor_Expecter) Process(vote interface{}) *VerifyingVoteProcessor_Process_Call { + return &VerifyingVoteProcessor_Process_Call{Call: _e.mock.On("Process", vote)} +} + +func (_c *VerifyingVoteProcessor_Process_Call) Run(run func(vote *model.Vote)) *VerifyingVoteProcessor_Process_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VerifyingVoteProcessor_Process_Call) Return(err error) *VerifyingVoteProcessor_Process_Call { + _c.Call.Return(err) + return _c +} + +func (_c *VerifyingVoteProcessor_Process_Call) RunAndReturn(run func(vote *model.Vote) error) *VerifyingVoteProcessor_Process_Call { + _c.Call.Return(run) + return _c +} + +// Status provides a mock function for the type VerifyingVoteProcessor +func (_mock *VerifyingVoteProcessor) Status() hotstuff.VoteCollectorStatus { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Status") } var r0 hotstuff.VoteCollectorStatus - if rf, ok := ret.Get(0).(func() hotstuff.VoteCollectorStatus); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() hotstuff.VoteCollectorStatus); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(hotstuff.VoteCollectorStatus) } - return r0 } -// NewVerifyingVoteProcessor creates a new instance of VerifyingVoteProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVerifyingVoteProcessor(t interface { - mock.TestingT - Cleanup(func()) -}) *VerifyingVoteProcessor { - mock := &VerifyingVoteProcessor{} - mock.Mock.Test(t) +// VerifyingVoteProcessor_Status_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Status' +type VerifyingVoteProcessor_Status_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Status is a helper method to define mock.On call +func (_e *VerifyingVoteProcessor_Expecter) Status() *VerifyingVoteProcessor_Status_Call { + return &VerifyingVoteProcessor_Status_Call{Call: _e.mock.On("Status")} +} - return mock +func (_c *VerifyingVoteProcessor_Status_Call) Run(run func()) *VerifyingVoteProcessor_Status_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerifyingVoteProcessor_Status_Call) Return(voteCollectorStatus hotstuff.VoteCollectorStatus) *VerifyingVoteProcessor_Status_Call { + _c.Call.Return(voteCollectorStatus) + return _c +} + +func (_c *VerifyingVoteProcessor_Status_Call) RunAndReturn(run func() hotstuff.VoteCollectorStatus) *VerifyingVoteProcessor_Status_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/vote_aggregation_consumer.go b/consensus/hotstuff/mocks/vote_aggregation_consumer.go index 23693e11797..aa256992a87 100644 --- a/consensus/hotstuff/mocks/vote_aggregation_consumer.go +++ b/consensus/hotstuff/mocks/vote_aggregation_consumer.go @@ -1,55 +1,250 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewVoteAggregationConsumer creates a new instance of VoteAggregationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteAggregationConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *VoteAggregationConsumer { + mock := &VoteAggregationConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VoteAggregationConsumer is an autogenerated mock type for the VoteAggregationConsumer type type VoteAggregationConsumer struct { mock.Mock } -// OnDoubleVotingDetected provides a mock function with given fields: _a0, _a1 -func (_m *VoteAggregationConsumer) OnDoubleVotingDetected(_a0 *model.Vote, _a1 *model.Vote) { - _m.Called(_a0, _a1) +type VoteAggregationConsumer_Expecter struct { + mock *mock.Mock } -// OnInvalidVoteDetected provides a mock function with given fields: err -func (_m *VoteAggregationConsumer) OnInvalidVoteDetected(err model.InvalidVoteError) { - _m.Called(err) +func (_m *VoteAggregationConsumer) EXPECT() *VoteAggregationConsumer_Expecter { + return &VoteAggregationConsumer_Expecter{mock: &_m.Mock} } -// OnQcConstructedFromVotes provides a mock function with given fields: _a0 -func (_m *VoteAggregationConsumer) OnQcConstructedFromVotes(_a0 *flow.QuorumCertificate) { - _m.Called(_a0) +// OnDoubleVotingDetected provides a mock function for the type VoteAggregationConsumer +func (_mock *VoteAggregationConsumer) OnDoubleVotingDetected(vote *model.Vote, vote1 *model.Vote) { + _mock.Called(vote, vote1) + return } -// OnVoteForInvalidBlockDetected provides a mock function with given fields: vote, invalidProposal -func (_m *VoteAggregationConsumer) OnVoteForInvalidBlockDetected(vote *model.Vote, invalidProposal *model.SignedProposal) { - _m.Called(vote, invalidProposal) +// VoteAggregationConsumer_OnDoubleVotingDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDoubleVotingDetected' +type VoteAggregationConsumer_OnDoubleVotingDetected_Call struct { + *mock.Call } -// OnVoteProcessed provides a mock function with given fields: vote -func (_m *VoteAggregationConsumer) OnVoteProcessed(vote *model.Vote) { - _m.Called(vote) +// OnDoubleVotingDetected is a helper method to define mock.On call +// - vote *model.Vote +// - vote1 *model.Vote +func (_e *VoteAggregationConsumer_Expecter) OnDoubleVotingDetected(vote interface{}, vote1 interface{}) *VoteAggregationConsumer_OnDoubleVotingDetected_Call { + return &VoteAggregationConsumer_OnDoubleVotingDetected_Call{Call: _e.mock.On("OnDoubleVotingDetected", vote, vote1)} } -// NewVoteAggregationConsumer creates a new instance of VoteAggregationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVoteAggregationConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *VoteAggregationConsumer { - mock := &VoteAggregationConsumer{} - mock.Mock.Test(t) +func (_c *VoteAggregationConsumer_OnDoubleVotingDetected_Call) Run(run func(vote *model.Vote, vote1 *model.Vote)) *VoteAggregationConsumer_OnDoubleVotingDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + var arg1 *model.Vote + if args[1] != nil { + arg1 = args[1].(*model.Vote) + } + run( + arg0, + arg1, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *VoteAggregationConsumer_OnDoubleVotingDetected_Call) Return() *VoteAggregationConsumer_OnDoubleVotingDetected_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *VoteAggregationConsumer_OnDoubleVotingDetected_Call) RunAndReturn(run func(vote *model.Vote, vote1 *model.Vote)) *VoteAggregationConsumer_OnDoubleVotingDetected_Call { + _c.Run(run) + return _c +} + +// OnInvalidVoteDetected provides a mock function for the type VoteAggregationConsumer +func (_mock *VoteAggregationConsumer) OnInvalidVoteDetected(err model.InvalidVoteError) { + _mock.Called(err) + return +} + +// VoteAggregationConsumer_OnInvalidVoteDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidVoteDetected' +type VoteAggregationConsumer_OnInvalidVoteDetected_Call struct { + *mock.Call +} + +// OnInvalidVoteDetected is a helper method to define mock.On call +// - err model.InvalidVoteError +func (_e *VoteAggregationConsumer_Expecter) OnInvalidVoteDetected(err interface{}) *VoteAggregationConsumer_OnInvalidVoteDetected_Call { + return &VoteAggregationConsumer_OnInvalidVoteDetected_Call{Call: _e.mock.On("OnInvalidVoteDetected", err)} +} + +func (_c *VoteAggregationConsumer_OnInvalidVoteDetected_Call) Run(run func(err model.InvalidVoteError)) *VoteAggregationConsumer_OnInvalidVoteDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 model.InvalidVoteError + if args[0] != nil { + arg0 = args[0].(model.InvalidVoteError) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregationConsumer_OnInvalidVoteDetected_Call) Return() *VoteAggregationConsumer_OnInvalidVoteDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregationConsumer_OnInvalidVoteDetected_Call) RunAndReturn(run func(err model.InvalidVoteError)) *VoteAggregationConsumer_OnInvalidVoteDetected_Call { + _c.Run(run) + return _c +} + +// OnQcConstructedFromVotes provides a mock function for the type VoteAggregationConsumer +func (_mock *VoteAggregationConsumer) OnQcConstructedFromVotes(quorumCertificate *flow.QuorumCertificate) { + _mock.Called(quorumCertificate) + return +} + +// VoteAggregationConsumer_OnQcConstructedFromVotes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnQcConstructedFromVotes' +type VoteAggregationConsumer_OnQcConstructedFromVotes_Call struct { + *mock.Call +} + +// OnQcConstructedFromVotes is a helper method to define mock.On call +// - quorumCertificate *flow.QuorumCertificate +func (_e *VoteAggregationConsumer_Expecter) OnQcConstructedFromVotes(quorumCertificate interface{}) *VoteAggregationConsumer_OnQcConstructedFromVotes_Call { + return &VoteAggregationConsumer_OnQcConstructedFromVotes_Call{Call: _e.mock.On("OnQcConstructedFromVotes", quorumCertificate)} +} + +func (_c *VoteAggregationConsumer_OnQcConstructedFromVotes_Call) Run(run func(quorumCertificate *flow.QuorumCertificate)) *VoteAggregationConsumer_OnQcConstructedFromVotes_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregationConsumer_OnQcConstructedFromVotes_Call) Return() *VoteAggregationConsumer_OnQcConstructedFromVotes_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregationConsumer_OnQcConstructedFromVotes_Call) RunAndReturn(run func(quorumCertificate *flow.QuorumCertificate)) *VoteAggregationConsumer_OnQcConstructedFromVotes_Call { + _c.Run(run) + return _c +} + +// OnVoteForInvalidBlockDetected provides a mock function for the type VoteAggregationConsumer +func (_mock *VoteAggregationConsumer) OnVoteForInvalidBlockDetected(vote *model.Vote, invalidProposal *model.SignedProposal) { + _mock.Called(vote, invalidProposal) + return +} + +// VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnVoteForInvalidBlockDetected' +type VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call struct { + *mock.Call +} + +// OnVoteForInvalidBlockDetected is a helper method to define mock.On call +// - vote *model.Vote +// - invalidProposal *model.SignedProposal +func (_e *VoteAggregationConsumer_Expecter) OnVoteForInvalidBlockDetected(vote interface{}, invalidProposal interface{}) *VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call { + return &VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call{Call: _e.mock.On("OnVoteForInvalidBlockDetected", vote, invalidProposal)} +} + +func (_c *VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call) Run(run func(vote *model.Vote, invalidProposal *model.SignedProposal)) *VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + var arg1 *model.SignedProposal + if args[1] != nil { + arg1 = args[1].(*model.SignedProposal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call) Return() *VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call) RunAndReturn(run func(vote *model.Vote, invalidProposal *model.SignedProposal)) *VoteAggregationConsumer_OnVoteForInvalidBlockDetected_Call { + _c.Run(run) + return _c +} + +// OnVoteProcessed provides a mock function for the type VoteAggregationConsumer +func (_mock *VoteAggregationConsumer) OnVoteProcessed(vote *model.Vote) { + _mock.Called(vote) + return +} + +// VoteAggregationConsumer_OnVoteProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnVoteProcessed' +type VoteAggregationConsumer_OnVoteProcessed_Call struct { + *mock.Call +} + +// OnVoteProcessed is a helper method to define mock.On call +// - vote *model.Vote +func (_e *VoteAggregationConsumer_Expecter) OnVoteProcessed(vote interface{}) *VoteAggregationConsumer_OnVoteProcessed_Call { + return &VoteAggregationConsumer_OnVoteProcessed_Call{Call: _e.mock.On("OnVoteProcessed", vote)} +} + +func (_c *VoteAggregationConsumer_OnVoteProcessed_Call) Run(run func(vote *model.Vote)) *VoteAggregationConsumer_OnVoteProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregationConsumer_OnVoteProcessed_Call) Return() *VoteAggregationConsumer_OnVoteProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregationConsumer_OnVoteProcessed_Call) RunAndReturn(run func(vote *model.Vote)) *VoteAggregationConsumer_OnVoteProcessed_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/vote_aggregation_violation_consumer.go b/consensus/hotstuff/mocks/vote_aggregation_violation_consumer.go index 9fb0ec4b1f3..377317055e5 100644 --- a/consensus/hotstuff/mocks/vote_aggregation_violation_consumer.go +++ b/consensus/hotstuff/mocks/vote_aggregation_violation_consumer.go @@ -1,42 +1,169 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - model "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" ) +// NewVoteAggregationViolationConsumer creates a new instance of VoteAggregationViolationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteAggregationViolationConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *VoteAggregationViolationConsumer { + mock := &VoteAggregationViolationConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VoteAggregationViolationConsumer is an autogenerated mock type for the VoteAggregationViolationConsumer type type VoteAggregationViolationConsumer struct { mock.Mock } -// OnDoubleVotingDetected provides a mock function with given fields: _a0, _a1 -func (_m *VoteAggregationViolationConsumer) OnDoubleVotingDetected(_a0 *model.Vote, _a1 *model.Vote) { - _m.Called(_a0, _a1) +type VoteAggregationViolationConsumer_Expecter struct { + mock *mock.Mock } -// OnInvalidVoteDetected provides a mock function with given fields: err -func (_m *VoteAggregationViolationConsumer) OnInvalidVoteDetected(err model.InvalidVoteError) { - _m.Called(err) +func (_m *VoteAggregationViolationConsumer) EXPECT() *VoteAggregationViolationConsumer_Expecter { + return &VoteAggregationViolationConsumer_Expecter{mock: &_m.Mock} } -// OnVoteForInvalidBlockDetected provides a mock function with given fields: vote, invalidProposal -func (_m *VoteAggregationViolationConsumer) OnVoteForInvalidBlockDetected(vote *model.Vote, invalidProposal *model.SignedProposal) { - _m.Called(vote, invalidProposal) +// OnDoubleVotingDetected provides a mock function for the type VoteAggregationViolationConsumer +func (_mock *VoteAggregationViolationConsumer) OnDoubleVotingDetected(vote *model.Vote, vote1 *model.Vote) { + _mock.Called(vote, vote1) + return } -// NewVoteAggregationViolationConsumer creates a new instance of VoteAggregationViolationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVoteAggregationViolationConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *VoteAggregationViolationConsumer { - mock := &VoteAggregationViolationConsumer{} - mock.Mock.Test(t) +// VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDoubleVotingDetected' +type VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnDoubleVotingDetected is a helper method to define mock.On call +// - vote *model.Vote +// - vote1 *model.Vote +func (_e *VoteAggregationViolationConsumer_Expecter) OnDoubleVotingDetected(vote interface{}, vote1 interface{}) *VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call { + return &VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call{Call: _e.mock.On("OnDoubleVotingDetected", vote, vote1)} +} - return mock +func (_c *VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call) Run(run func(vote *model.Vote, vote1 *model.Vote)) *VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + var arg1 *model.Vote + if args[1] != nil { + arg1 = args[1].(*model.Vote) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call) Return() *VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call) RunAndReturn(run func(vote *model.Vote, vote1 *model.Vote)) *VoteAggregationViolationConsumer_OnDoubleVotingDetected_Call { + _c.Run(run) + return _c +} + +// OnInvalidVoteDetected provides a mock function for the type VoteAggregationViolationConsumer +func (_mock *VoteAggregationViolationConsumer) OnInvalidVoteDetected(err model.InvalidVoteError) { + _mock.Called(err) + return +} + +// VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidVoteDetected' +type VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call struct { + *mock.Call +} + +// OnInvalidVoteDetected is a helper method to define mock.On call +// - err model.InvalidVoteError +func (_e *VoteAggregationViolationConsumer_Expecter) OnInvalidVoteDetected(err interface{}) *VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call { + return &VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call{Call: _e.mock.On("OnInvalidVoteDetected", err)} +} + +func (_c *VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call) Run(run func(err model.InvalidVoteError)) *VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 model.InvalidVoteError + if args[0] != nil { + arg0 = args[0].(model.InvalidVoteError) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call) Return() *VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call) RunAndReturn(run func(err model.InvalidVoteError)) *VoteAggregationViolationConsumer_OnInvalidVoteDetected_Call { + _c.Run(run) + return _c +} + +// OnVoteForInvalidBlockDetected provides a mock function for the type VoteAggregationViolationConsumer +func (_mock *VoteAggregationViolationConsumer) OnVoteForInvalidBlockDetected(vote *model.Vote, invalidProposal *model.SignedProposal) { + _mock.Called(vote, invalidProposal) + return +} + +// VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnVoteForInvalidBlockDetected' +type VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call struct { + *mock.Call +} + +// OnVoteForInvalidBlockDetected is a helper method to define mock.On call +// - vote *model.Vote +// - invalidProposal *model.SignedProposal +func (_e *VoteAggregationViolationConsumer_Expecter) OnVoteForInvalidBlockDetected(vote interface{}, invalidProposal interface{}) *VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call { + return &VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call{Call: _e.mock.On("OnVoteForInvalidBlockDetected", vote, invalidProposal)} +} + +func (_c *VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call) Run(run func(vote *model.Vote, invalidProposal *model.SignedProposal)) *VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + var arg1 *model.SignedProposal + if args[1] != nil { + arg1 = args[1].(*model.SignedProposal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call) Return() *VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call) RunAndReturn(run func(vote *model.Vote, invalidProposal *model.SignedProposal)) *VoteAggregationViolationConsumer_OnVoteForInvalidBlockDetected_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/vote_aggregator.go b/consensus/hotstuff/mocks/vote_aggregator.go index ae9cf3a7000..9eda446ad82 100644 --- a/consensus/hotstuff/mocks/vote_aggregator.go +++ b/consensus/hotstuff/mocks/vote_aggregator.go @@ -1,107 +1,341 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewVoteAggregator creates a new instance of VoteAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteAggregator(t interface { + mock.TestingT + Cleanup(func()) +}) *VoteAggregator { + mock := &VoteAggregator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VoteAggregator is an autogenerated mock type for the VoteAggregator type type VoteAggregator struct { mock.Mock } -// AddBlock provides a mock function with given fields: block -func (_m *VoteAggregator) AddBlock(block *model.SignedProposal) { - _m.Called(block) +type VoteAggregator_Expecter struct { + mock *mock.Mock +} + +func (_m *VoteAggregator) EXPECT() *VoteAggregator_Expecter { + return &VoteAggregator_Expecter{mock: &_m.Mock} +} + +// AddBlock provides a mock function for the type VoteAggregator +func (_mock *VoteAggregator) AddBlock(block *model.SignedProposal) { + _mock.Called(block) + return +} + +// VoteAggregator_AddBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlock' +type VoteAggregator_AddBlock_Call struct { + *mock.Call +} + +// AddBlock is a helper method to define mock.On call +// - block *model.SignedProposal +func (_e *VoteAggregator_Expecter) AddBlock(block interface{}) *VoteAggregator_AddBlock_Call { + return &VoteAggregator_AddBlock_Call{Call: _e.mock.On("AddBlock", block)} +} + +func (_c *VoteAggregator_AddBlock_Call) Run(run func(block *model.SignedProposal)) *VoteAggregator_AddBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregator_AddBlock_Call) Return() *VoteAggregator_AddBlock_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregator_AddBlock_Call) RunAndReturn(run func(block *model.SignedProposal)) *VoteAggregator_AddBlock_Call { + _c.Run(run) + return _c +} + +// AddVote provides a mock function for the type VoteAggregator +func (_mock *VoteAggregator) AddVote(vote *model.Vote) { + _mock.Called(vote) + return +} + +// VoteAggregator_AddVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddVote' +type VoteAggregator_AddVote_Call struct { + *mock.Call +} + +// AddVote is a helper method to define mock.On call +// - vote *model.Vote +func (_e *VoteAggregator_Expecter) AddVote(vote interface{}) *VoteAggregator_AddVote_Call { + return &VoteAggregator_AddVote_Call{Call: _e.mock.On("AddVote", vote)} +} + +func (_c *VoteAggregator_AddVote_Call) Run(run func(vote *model.Vote)) *VoteAggregator_AddVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregator_AddVote_Call) Return() *VoteAggregator_AddVote_Call { + _c.Call.Return() + return _c } -// AddVote provides a mock function with given fields: vote -func (_m *VoteAggregator) AddVote(vote *model.Vote) { - _m.Called(vote) +func (_c *VoteAggregator_AddVote_Call) RunAndReturn(run func(vote *model.Vote)) *VoteAggregator_AddVote_Call { + _c.Run(run) + return _c } -// Done provides a mock function with no fields -func (_m *VoteAggregator) Done() <-chan struct{} { - ret := _m.Called() +// Done provides a mock function for the type VoteAggregator +func (_mock *VoteAggregator) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// InvalidBlock provides a mock function with given fields: block -func (_m *VoteAggregator) InvalidBlock(block *model.SignedProposal) error { - ret := _m.Called(block) +// VoteAggregator_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type VoteAggregator_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *VoteAggregator_Expecter) Done() *VoteAggregator_Done_Call { + return &VoteAggregator_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *VoteAggregator_Done_Call) Run(run func()) *VoteAggregator_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VoteAggregator_Done_Call) Return(valCh <-chan struct{}) *VoteAggregator_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *VoteAggregator_Done_Call) RunAndReturn(run func() <-chan struct{}) *VoteAggregator_Done_Call { + _c.Call.Return(run) + return _c +} + +// InvalidBlock provides a mock function for the type VoteAggregator +func (_mock *VoteAggregator) InvalidBlock(block *model.SignedProposal) error { + ret := _mock.Called(block) if len(ret) == 0 { panic("no return value specified for InvalidBlock") } var r0 error - if rf, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { - r0 = rf(block) + if returnFunc, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { + r0 = returnFunc(block) } else { r0 = ret.Error(0) } - return r0 } -// PruneUpToView provides a mock function with given fields: view -func (_m *VoteAggregator) PruneUpToView(view uint64) { - _m.Called(view) +// VoteAggregator_InvalidBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InvalidBlock' +type VoteAggregator_InvalidBlock_Call struct { + *mock.Call +} + +// InvalidBlock is a helper method to define mock.On call +// - block *model.SignedProposal +func (_e *VoteAggregator_Expecter) InvalidBlock(block interface{}) *VoteAggregator_InvalidBlock_Call { + return &VoteAggregator_InvalidBlock_Call{Call: _e.mock.On("InvalidBlock", block)} +} + +func (_c *VoteAggregator_InvalidBlock_Call) Run(run func(block *model.SignedProposal)) *VoteAggregator_InvalidBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregator_InvalidBlock_Call) Return(err error) *VoteAggregator_InvalidBlock_Call { + _c.Call.Return(err) + return _c +} + +func (_c *VoteAggregator_InvalidBlock_Call) RunAndReturn(run func(block *model.SignedProposal) error) *VoteAggregator_InvalidBlock_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToView provides a mock function for the type VoteAggregator +func (_mock *VoteAggregator) PruneUpToView(view uint64) { + _mock.Called(view) + return +} + +// VoteAggregator_PruneUpToView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToView' +type VoteAggregator_PruneUpToView_Call struct { + *mock.Call +} + +// PruneUpToView is a helper method to define mock.On call +// - view uint64 +func (_e *VoteAggregator_Expecter) PruneUpToView(view interface{}) *VoteAggregator_PruneUpToView_Call { + return &VoteAggregator_PruneUpToView_Call{Call: _e.mock.On("PruneUpToView", view)} } -// Ready provides a mock function with no fields -func (_m *VoteAggregator) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *VoteAggregator_PruneUpToView_Call) Run(run func(view uint64)) *VoteAggregator_PruneUpToView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregator_PruneUpToView_Call) Return() *VoteAggregator_PruneUpToView_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregator_PruneUpToView_Call) RunAndReturn(run func(view uint64)) *VoteAggregator_PruneUpToView_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type VoteAggregator +func (_mock *VoteAggregator) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *VoteAggregator) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// VoteAggregator_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type VoteAggregator_Ready_Call struct { + *mock.Call } -// NewVoteAggregator creates a new instance of VoteAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVoteAggregator(t interface { - mock.TestingT - Cleanup(func()) -}) *VoteAggregator { - mock := &VoteAggregator{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *VoteAggregator_Expecter) Ready() *VoteAggregator_Ready_Call { + return &VoteAggregator_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *VoteAggregator_Ready_Call) Run(run func()) *VoteAggregator_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *VoteAggregator_Ready_Call) Return(valCh <-chan struct{}) *VoteAggregator_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *VoteAggregator_Ready_Call) RunAndReturn(run func() <-chan struct{}) *VoteAggregator_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type VoteAggregator +func (_mock *VoteAggregator) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// VoteAggregator_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type VoteAggregator_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *VoteAggregator_Expecter) Start(signalerContext interface{}) *VoteAggregator_Start_Call { + return &VoteAggregator_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *VoteAggregator_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *VoteAggregator_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteAggregator_Start_Call) Return() *VoteAggregator_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteAggregator_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *VoteAggregator_Start_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/vote_collector.go b/consensus/hotstuff/mocks/vote_collector.go index 651dd1197ef..e7f4dcd0dff 100644 --- a/consensus/hotstuff/mocks/vote_collector.go +++ b/consensus/hotstuff/mocks/vote_collector.go @@ -1,106 +1,268 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewVoteCollector creates a new instance of VoteCollector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteCollector(t interface { + mock.TestingT + Cleanup(func()) +}) *VoteCollector { + mock := &VoteCollector{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VoteCollector is an autogenerated mock type for the VoteCollector type type VoteCollector struct { mock.Mock } -// AddVote provides a mock function with given fields: vote -func (_m *VoteCollector) AddVote(vote *model.Vote) error { - ret := _m.Called(vote) +type VoteCollector_Expecter struct { + mock *mock.Mock +} + +func (_m *VoteCollector) EXPECT() *VoteCollector_Expecter { + return &VoteCollector_Expecter{mock: &_m.Mock} +} + +// AddVote provides a mock function for the type VoteCollector +func (_mock *VoteCollector) AddVote(vote *model.Vote) error { + ret := _mock.Called(vote) if len(ret) == 0 { panic("no return value specified for AddVote") } var r0 error - if rf, ok := ret.Get(0).(func(*model.Vote) error); ok { - r0 = rf(vote) + if returnFunc, ok := ret.Get(0).(func(*model.Vote) error); ok { + r0 = returnFunc(vote) } else { r0 = ret.Error(0) } - return r0 } -// ProcessBlock provides a mock function with given fields: block -func (_m *VoteCollector) ProcessBlock(block *model.SignedProposal) error { - ret := _m.Called(block) +// VoteCollector_AddVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddVote' +type VoteCollector_AddVote_Call struct { + *mock.Call +} + +// AddVote is a helper method to define mock.On call +// - vote *model.Vote +func (_e *VoteCollector_Expecter) AddVote(vote interface{}) *VoteCollector_AddVote_Call { + return &VoteCollector_AddVote_Call{Call: _e.mock.On("AddVote", vote)} +} + +func (_c *VoteCollector_AddVote_Call) Run(run func(vote *model.Vote)) *VoteCollector_AddVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteCollector_AddVote_Call) Return(err error) *VoteCollector_AddVote_Call { + _c.Call.Return(err) + return _c +} + +func (_c *VoteCollector_AddVote_Call) RunAndReturn(run func(vote *model.Vote) error) *VoteCollector_AddVote_Call { + _c.Call.Return(run) + return _c +} + +// ProcessBlock provides a mock function for the type VoteCollector +func (_mock *VoteCollector) ProcessBlock(block *model.SignedProposal) error { + ret := _mock.Called(block) if len(ret) == 0 { panic("no return value specified for ProcessBlock") } var r0 error - if rf, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { - r0 = rf(block) + if returnFunc, ok := ret.Get(0).(func(*model.SignedProposal) error); ok { + r0 = returnFunc(block) } else { r0 = ret.Error(0) } - return r0 } -// RegisterVoteConsumer provides a mock function with given fields: consumer -func (_m *VoteCollector) RegisterVoteConsumer(consumer hotstuff.VoteConsumer) { - _m.Called(consumer) +// VoteCollector_ProcessBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessBlock' +type VoteCollector_ProcessBlock_Call struct { + *mock.Call +} + +// ProcessBlock is a helper method to define mock.On call +// - block *model.SignedProposal +func (_e *VoteCollector_Expecter) ProcessBlock(block interface{}) *VoteCollector_ProcessBlock_Call { + return &VoteCollector_ProcessBlock_Call{Call: _e.mock.On("ProcessBlock", block)} +} + +func (_c *VoteCollector_ProcessBlock_Call) Run(run func(block *model.SignedProposal)) *VoteCollector_ProcessBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + run( + arg0, + ) + }) + return _c } -// Status provides a mock function with no fields -func (_m *VoteCollector) Status() hotstuff.VoteCollectorStatus { - ret := _m.Called() +func (_c *VoteCollector_ProcessBlock_Call) Return(err error) *VoteCollector_ProcessBlock_Call { + _c.Call.Return(err) + return _c +} + +func (_c *VoteCollector_ProcessBlock_Call) RunAndReturn(run func(block *model.SignedProposal) error) *VoteCollector_ProcessBlock_Call { + _c.Call.Return(run) + return _c +} + +// RegisterVoteConsumer provides a mock function for the type VoteCollector +func (_mock *VoteCollector) RegisterVoteConsumer(consumer hotstuff.VoteConsumer) { + _mock.Called(consumer) + return +} + +// VoteCollector_RegisterVoteConsumer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterVoteConsumer' +type VoteCollector_RegisterVoteConsumer_Call struct { + *mock.Call +} + +// RegisterVoteConsumer is a helper method to define mock.On call +// - consumer hotstuff.VoteConsumer +func (_e *VoteCollector_Expecter) RegisterVoteConsumer(consumer interface{}) *VoteCollector_RegisterVoteConsumer_Call { + return &VoteCollector_RegisterVoteConsumer_Call{Call: _e.mock.On("RegisterVoteConsumer", consumer)} +} + +func (_c *VoteCollector_RegisterVoteConsumer_Call) Run(run func(consumer hotstuff.VoteConsumer)) *VoteCollector_RegisterVoteConsumer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 hotstuff.VoteConsumer + if args[0] != nil { + arg0 = args[0].(hotstuff.VoteConsumer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteCollector_RegisterVoteConsumer_Call) Return() *VoteCollector_RegisterVoteConsumer_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteCollector_RegisterVoteConsumer_Call) RunAndReturn(run func(consumer hotstuff.VoteConsumer)) *VoteCollector_RegisterVoteConsumer_Call { + _c.Run(run) + return _c +} + +// Status provides a mock function for the type VoteCollector +func (_mock *VoteCollector) Status() hotstuff.VoteCollectorStatus { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Status") } var r0 hotstuff.VoteCollectorStatus - if rf, ok := ret.Get(0).(func() hotstuff.VoteCollectorStatus); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() hotstuff.VoteCollectorStatus); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(hotstuff.VoteCollectorStatus) } - return r0 } -// View provides a mock function with no fields -func (_m *VoteCollector) View() uint64 { - ret := _m.Called() +// VoteCollector_Status_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Status' +type VoteCollector_Status_Call struct { + *mock.Call +} + +// Status is a helper method to define mock.On call +func (_e *VoteCollector_Expecter) Status() *VoteCollector_Status_Call { + return &VoteCollector_Status_Call{Call: _e.mock.On("Status")} +} + +func (_c *VoteCollector_Status_Call) Run(run func()) *VoteCollector_Status_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VoteCollector_Status_Call) Return(voteCollectorStatus hotstuff.VoteCollectorStatus) *VoteCollector_Status_Call { + _c.Call.Return(voteCollectorStatus) + return _c +} + +func (_c *VoteCollector_Status_Call) RunAndReturn(run func() hotstuff.VoteCollectorStatus) *VoteCollector_Status_Call { + _c.Call.Return(run) + return _c +} + +// View provides a mock function for the type VoteCollector +func (_mock *VoteCollector) View() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for View") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewVoteCollector creates a new instance of VoteCollector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVoteCollector(t interface { - mock.TestingT - Cleanup(func()) -}) *VoteCollector { - mock := &VoteCollector{} - mock.Mock.Test(t) +// VoteCollector_View_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'View' +type VoteCollector_View_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// View is a helper method to define mock.On call +func (_e *VoteCollector_Expecter) View() *VoteCollector_View_Call { + return &VoteCollector_View_Call{Call: _e.mock.On("View")} +} - return mock +func (_c *VoteCollector_View_Call) Run(run func()) *VoteCollector_View_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VoteCollector_View_Call) Return(v uint64) *VoteCollector_View_Call { + _c.Call.Return(v) + return _c +} + +func (_c *VoteCollector_View_Call) RunAndReturn(run func() uint64) *VoteCollector_View_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/vote_collector_consumer.go b/consensus/hotstuff/mocks/vote_collector_consumer.go index 25357617118..1dbde1b0387 100644 --- a/consensus/hotstuff/mocks/vote_collector_consumer.go +++ b/consensus/hotstuff/mocks/vote_collector_consumer.go @@ -1,30 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) -// VoteCollectorConsumer is an autogenerated mock type for the VoteCollectorConsumer type -type VoteCollectorConsumer struct { - mock.Mock -} - -// OnQcConstructedFromVotes provides a mock function with given fields: _a0 -func (_m *VoteCollectorConsumer) OnQcConstructedFromVotes(_a0 *flow.QuorumCertificate) { - _m.Called(_a0) -} - -// OnVoteProcessed provides a mock function with given fields: vote -func (_m *VoteCollectorConsumer) OnVoteProcessed(vote *model.Vote) { - _m.Called(vote) -} - // NewVoteCollectorConsumer creates a new instance of VoteCollectorConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewVoteCollectorConsumer(t interface { @@ -38,3 +23,96 @@ func NewVoteCollectorConsumer(t interface { return mock } + +// VoteCollectorConsumer is an autogenerated mock type for the VoteCollectorConsumer type +type VoteCollectorConsumer struct { + mock.Mock +} + +type VoteCollectorConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *VoteCollectorConsumer) EXPECT() *VoteCollectorConsumer_Expecter { + return &VoteCollectorConsumer_Expecter{mock: &_m.Mock} +} + +// OnQcConstructedFromVotes provides a mock function for the type VoteCollectorConsumer +func (_mock *VoteCollectorConsumer) OnQcConstructedFromVotes(quorumCertificate *flow.QuorumCertificate) { + _mock.Called(quorumCertificate) + return +} + +// VoteCollectorConsumer_OnQcConstructedFromVotes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnQcConstructedFromVotes' +type VoteCollectorConsumer_OnQcConstructedFromVotes_Call struct { + *mock.Call +} + +// OnQcConstructedFromVotes is a helper method to define mock.On call +// - quorumCertificate *flow.QuorumCertificate +func (_e *VoteCollectorConsumer_Expecter) OnQcConstructedFromVotes(quorumCertificate interface{}) *VoteCollectorConsumer_OnQcConstructedFromVotes_Call { + return &VoteCollectorConsumer_OnQcConstructedFromVotes_Call{Call: _e.mock.On("OnQcConstructedFromVotes", quorumCertificate)} +} + +func (_c *VoteCollectorConsumer_OnQcConstructedFromVotes_Call) Run(run func(quorumCertificate *flow.QuorumCertificate)) *VoteCollectorConsumer_OnQcConstructedFromVotes_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.QuorumCertificate + if args[0] != nil { + arg0 = args[0].(*flow.QuorumCertificate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteCollectorConsumer_OnQcConstructedFromVotes_Call) Return() *VoteCollectorConsumer_OnQcConstructedFromVotes_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteCollectorConsumer_OnQcConstructedFromVotes_Call) RunAndReturn(run func(quorumCertificate *flow.QuorumCertificate)) *VoteCollectorConsumer_OnQcConstructedFromVotes_Call { + _c.Run(run) + return _c +} + +// OnVoteProcessed provides a mock function for the type VoteCollectorConsumer +func (_mock *VoteCollectorConsumer) OnVoteProcessed(vote *model.Vote) { + _mock.Called(vote) + return +} + +// VoteCollectorConsumer_OnVoteProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnVoteProcessed' +type VoteCollectorConsumer_OnVoteProcessed_Call struct { + *mock.Call +} + +// OnVoteProcessed is a helper method to define mock.On call +// - vote *model.Vote +func (_e *VoteCollectorConsumer_Expecter) OnVoteProcessed(vote interface{}) *VoteCollectorConsumer_OnVoteProcessed_Call { + return &VoteCollectorConsumer_OnVoteProcessed_Call{Call: _e.mock.On("OnVoteProcessed", vote)} +} + +func (_c *VoteCollectorConsumer_OnVoteProcessed_Call) Run(run func(vote *model.Vote)) *VoteCollectorConsumer_OnVoteProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteCollectorConsumer_OnVoteProcessed_Call) Return() *VoteCollectorConsumer_OnVoteProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteCollectorConsumer_OnVoteProcessed_Call) RunAndReturn(run func(vote *model.Vote)) *VoteCollectorConsumer_OnVoteProcessed_Call { + _c.Run(run) + return _c +} diff --git a/consensus/hotstuff/mocks/vote_collectors.go b/consensus/hotstuff/mocks/vote_collectors.go index e7be4957fa0..2f7d5d5d632 100644 --- a/consensus/hotstuff/mocks/vote_collectors.go +++ b/consensus/hotstuff/mocks/vote_collectors.go @@ -1,42 +1,91 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewVoteCollectors creates a new instance of VoteCollectors. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteCollectors(t interface { + mock.TestingT + Cleanup(func()) +}) *VoteCollectors { + mock := &VoteCollectors{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VoteCollectors is an autogenerated mock type for the VoteCollectors type type VoteCollectors struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *VoteCollectors) Done() <-chan struct{} { - ret := _m.Called() +type VoteCollectors_Expecter struct { + mock *mock.Mock +} + +func (_m *VoteCollectors) EXPECT() *VoteCollectors_Expecter { + return &VoteCollectors_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type VoteCollectors +func (_mock *VoteCollectors) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// GetOrCreateCollector provides a mock function with given fields: view -func (_m *VoteCollectors) GetOrCreateCollector(view uint64) (hotstuff.VoteCollector, bool, error) { - ret := _m.Called(view) +// VoteCollectors_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type VoteCollectors_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *VoteCollectors_Expecter) Done() *VoteCollectors_Done_Call { + return &VoteCollectors_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *VoteCollectors_Done_Call) Run(run func()) *VoteCollectors_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VoteCollectors_Done_Call) Return(valCh <-chan struct{}) *VoteCollectors_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *VoteCollectors_Done_Call) RunAndReturn(run func() <-chan struct{}) *VoteCollectors_Done_Call { + _c.Call.Return(run) + return _c +} + +// GetOrCreateCollector provides a mock function for the type VoteCollectors +func (_mock *VoteCollectors) GetOrCreateCollector(view uint64) (hotstuff.VoteCollector, bool, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for GetOrCreateCollector") @@ -45,72 +94,185 @@ func (_m *VoteCollectors) GetOrCreateCollector(view uint64) (hotstuff.VoteCollec var r0 hotstuff.VoteCollector var r1 bool var r2 error - if rf, ok := ret.Get(0).(func(uint64) (hotstuff.VoteCollector, bool, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (hotstuff.VoteCollector, bool, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) hotstuff.VoteCollector); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) hotstuff.VoteCollector); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(hotstuff.VoteCollector) } } - - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(view) } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(view) + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(view) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// PruneUpToView provides a mock function with given fields: lowestRetainedView -func (_m *VoteCollectors) PruneUpToView(lowestRetainedView uint64) { - _m.Called(lowestRetainedView) +// VoteCollectors_GetOrCreateCollector_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOrCreateCollector' +type VoteCollectors_GetOrCreateCollector_Call struct { + *mock.Call +} + +// GetOrCreateCollector is a helper method to define mock.On call +// - view uint64 +func (_e *VoteCollectors_Expecter) GetOrCreateCollector(view interface{}) *VoteCollectors_GetOrCreateCollector_Call { + return &VoteCollectors_GetOrCreateCollector_Call{Call: _e.mock.On("GetOrCreateCollector", view)} +} + +func (_c *VoteCollectors_GetOrCreateCollector_Call) Run(run func(view uint64)) *VoteCollectors_GetOrCreateCollector_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c } -// Ready provides a mock function with no fields -func (_m *VoteCollectors) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *VoteCollectors_GetOrCreateCollector_Call) Return(collector hotstuff.VoteCollector, created bool, err error) *VoteCollectors_GetOrCreateCollector_Call { + _c.Call.Return(collector, created, err) + return _c +} + +func (_c *VoteCollectors_GetOrCreateCollector_Call) RunAndReturn(run func(view uint64) (hotstuff.VoteCollector, bool, error)) *VoteCollectors_GetOrCreateCollector_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToView provides a mock function for the type VoteCollectors +func (_mock *VoteCollectors) PruneUpToView(lowestRetainedView uint64) { + _mock.Called(lowestRetainedView) + return +} + +// VoteCollectors_PruneUpToView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToView' +type VoteCollectors_PruneUpToView_Call struct { + *mock.Call +} + +// PruneUpToView is a helper method to define mock.On call +// - lowestRetainedView uint64 +func (_e *VoteCollectors_Expecter) PruneUpToView(lowestRetainedView interface{}) *VoteCollectors_PruneUpToView_Call { + return &VoteCollectors_PruneUpToView_Call{Call: _e.mock.On("PruneUpToView", lowestRetainedView)} +} + +func (_c *VoteCollectors_PruneUpToView_Call) Run(run func(lowestRetainedView uint64)) *VoteCollectors_PruneUpToView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteCollectors_PruneUpToView_Call) Return() *VoteCollectors_PruneUpToView_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteCollectors_PruneUpToView_Call) RunAndReturn(run func(lowestRetainedView uint64)) *VoteCollectors_PruneUpToView_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type VoteCollectors +func (_mock *VoteCollectors) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *VoteCollectors) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// VoteCollectors_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type VoteCollectors_Ready_Call struct { + *mock.Call } -// NewVoteCollectors creates a new instance of VoteCollectors. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVoteCollectors(t interface { - mock.TestingT - Cleanup(func()) -}) *VoteCollectors { - mock := &VoteCollectors{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *VoteCollectors_Expecter) Ready() *VoteCollectors_Ready_Call { + return &VoteCollectors_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *VoteCollectors_Ready_Call) Run(run func()) *VoteCollectors_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *VoteCollectors_Ready_Call) Return(valCh <-chan struct{}) *VoteCollectors_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *VoteCollectors_Ready_Call) RunAndReturn(run func() <-chan struct{}) *VoteCollectors_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type VoteCollectors +func (_mock *VoteCollectors) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// VoteCollectors_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type VoteCollectors_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *VoteCollectors_Expecter) Start(signalerContext interface{}) *VoteCollectors_Start_Call { + return &VoteCollectors_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *VoteCollectors_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *VoteCollectors_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteCollectors_Start_Call) Return() *VoteCollectors_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *VoteCollectors_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *VoteCollectors_Start_Call { + _c.Run(run) + return _c } diff --git a/consensus/hotstuff/mocks/vote_processor.go b/consensus/hotstuff/mocks/vote_processor.go index bcd9cc2377e..b15226f3caa 100644 --- a/consensus/hotstuff/mocks/vote_processor.go +++ b/consensus/hotstuff/mocks/vote_processor.go @@ -1,65 +1,133 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewVoteProcessor creates a new instance of VoteProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteProcessor(t interface { + mock.TestingT + Cleanup(func()) +}) *VoteProcessor { + mock := &VoteProcessor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VoteProcessor is an autogenerated mock type for the VoteProcessor type type VoteProcessor struct { mock.Mock } -// Process provides a mock function with given fields: vote -func (_m *VoteProcessor) Process(vote *model.Vote) error { - ret := _m.Called(vote) +type VoteProcessor_Expecter struct { + mock *mock.Mock +} + +func (_m *VoteProcessor) EXPECT() *VoteProcessor_Expecter { + return &VoteProcessor_Expecter{mock: &_m.Mock} +} + +// Process provides a mock function for the type VoteProcessor +func (_mock *VoteProcessor) Process(vote *model.Vote) error { + ret := _mock.Called(vote) if len(ret) == 0 { panic("no return value specified for Process") } var r0 error - if rf, ok := ret.Get(0).(func(*model.Vote) error); ok { - r0 = rf(vote) + if returnFunc, ok := ret.Get(0).(func(*model.Vote) error); ok { + r0 = returnFunc(vote) } else { r0 = ret.Error(0) } - return r0 } -// Status provides a mock function with no fields -func (_m *VoteProcessor) Status() hotstuff.VoteCollectorStatus { - ret := _m.Called() +// VoteProcessor_Process_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Process' +type VoteProcessor_Process_Call struct { + *mock.Call +} + +// Process is a helper method to define mock.On call +// - vote *model.Vote +func (_e *VoteProcessor_Expecter) Process(vote interface{}) *VoteProcessor_Process_Call { + return &VoteProcessor_Process_Call{Call: _e.mock.On("Process", vote)} +} + +func (_c *VoteProcessor_Process_Call) Run(run func(vote *model.Vote)) *VoteProcessor_Process_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.Vote + if args[0] != nil { + arg0 = args[0].(*model.Vote) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VoteProcessor_Process_Call) Return(err error) *VoteProcessor_Process_Call { + _c.Call.Return(err) + return _c +} + +func (_c *VoteProcessor_Process_Call) RunAndReturn(run func(vote *model.Vote) error) *VoteProcessor_Process_Call { + _c.Call.Return(run) + return _c +} + +// Status provides a mock function for the type VoteProcessor +func (_mock *VoteProcessor) Status() hotstuff.VoteCollectorStatus { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Status") } var r0 hotstuff.VoteCollectorStatus - if rf, ok := ret.Get(0).(func() hotstuff.VoteCollectorStatus); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() hotstuff.VoteCollectorStatus); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(hotstuff.VoteCollectorStatus) } - return r0 } -// NewVoteProcessor creates a new instance of VoteProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVoteProcessor(t interface { - mock.TestingT - Cleanup(func()) -}) *VoteProcessor { - mock := &VoteProcessor{} - mock.Mock.Test(t) +// VoteProcessor_Status_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Status' +type VoteProcessor_Status_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Status is a helper method to define mock.On call +func (_e *VoteProcessor_Expecter) Status() *VoteProcessor_Status_Call { + return &VoteProcessor_Status_Call{Call: _e.mock.On("Status")} +} - return mock +func (_c *VoteProcessor_Status_Call) Run(run func()) *VoteProcessor_Status_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VoteProcessor_Status_Call) Return(voteCollectorStatus hotstuff.VoteCollectorStatus) *VoteProcessor_Status_Call { + _c.Call.Return(voteCollectorStatus) + return _c +} + +func (_c *VoteProcessor_Status_Call) RunAndReturn(run func() hotstuff.VoteCollectorStatus) *VoteProcessor_Status_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/vote_processor_factory.go b/consensus/hotstuff/mocks/vote_processor_factory.go index 7f7807272ec..290b066c5c0 100644 --- a/consensus/hotstuff/mocks/vote_processor_factory.go +++ b/consensus/hotstuff/mocks/vote_processor_factory.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/rs/zerolog" mock "github.com/stretchr/testify/mock" +) - model "github.com/onflow/flow-go/consensus/hotstuff/model" +// NewVoteProcessorFactory creates a new instance of VoteProcessorFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteProcessorFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *VoteProcessorFactory { + mock := &VoteProcessorFactory{} + mock.Mock.Test(t) - zerolog "github.com/rs/zerolog" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // VoteProcessorFactory is an autogenerated mock type for the VoteProcessorFactory type type VoteProcessorFactory struct { mock.Mock } -// Create provides a mock function with given fields: log, proposal -func (_m *VoteProcessorFactory) Create(log zerolog.Logger, proposal *model.SignedProposal) (hotstuff.VerifyingVoteProcessor, error) { - ret := _m.Called(log, proposal) +type VoteProcessorFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *VoteProcessorFactory) EXPECT() *VoteProcessorFactory_Expecter { + return &VoteProcessorFactory_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type VoteProcessorFactory +func (_mock *VoteProcessorFactory) Create(log zerolog.Logger, proposal *model.SignedProposal) (hotstuff.VerifyingVoteProcessor, error) { + ret := _mock.Called(log, proposal) if len(ret) == 0 { panic("no return value specified for Create") @@ -26,36 +48,60 @@ func (_m *VoteProcessorFactory) Create(log zerolog.Logger, proposal *model.Signe var r0 hotstuff.VerifyingVoteProcessor var r1 error - if rf, ok := ret.Get(0).(func(zerolog.Logger, *model.SignedProposal) (hotstuff.VerifyingVoteProcessor, error)); ok { - return rf(log, proposal) + if returnFunc, ok := ret.Get(0).(func(zerolog.Logger, *model.SignedProposal) (hotstuff.VerifyingVoteProcessor, error)); ok { + return returnFunc(log, proposal) } - if rf, ok := ret.Get(0).(func(zerolog.Logger, *model.SignedProposal) hotstuff.VerifyingVoteProcessor); ok { - r0 = rf(log, proposal) + if returnFunc, ok := ret.Get(0).(func(zerolog.Logger, *model.SignedProposal) hotstuff.VerifyingVoteProcessor); ok { + r0 = returnFunc(log, proposal) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(hotstuff.VerifyingVoteProcessor) } } - - if rf, ok := ret.Get(1).(func(zerolog.Logger, *model.SignedProposal) error); ok { - r1 = rf(log, proposal) + if returnFunc, ok := ret.Get(1).(func(zerolog.Logger, *model.SignedProposal) error); ok { + r1 = returnFunc(log, proposal) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewVoteProcessorFactory creates a new instance of VoteProcessorFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVoteProcessorFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *VoteProcessorFactory { - mock := &VoteProcessorFactory{} - mock.Mock.Test(t) +// VoteProcessorFactory_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type VoteProcessorFactory_Create_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Create is a helper method to define mock.On call +// - log zerolog.Logger +// - proposal *model.SignedProposal +func (_e *VoteProcessorFactory_Expecter) Create(log interface{}, proposal interface{}) *VoteProcessorFactory_Create_Call { + return &VoteProcessorFactory_Create_Call{Call: _e.mock.On("Create", log, proposal)} +} - return mock +func (_c *VoteProcessorFactory_Create_Call) Run(run func(log zerolog.Logger, proposal *model.SignedProposal)) *VoteProcessorFactory_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 zerolog.Logger + if args[0] != nil { + arg0 = args[0].(zerolog.Logger) + } + var arg1 *model.SignedProposal + if args[1] != nil { + arg1 = args[1].(*model.SignedProposal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *VoteProcessorFactory_Create_Call) Return(verifyingVoteProcessor hotstuff.VerifyingVoteProcessor, err error) *VoteProcessorFactory_Create_Call { + _c.Call.Return(verifyingVoteProcessor, err) + return _c +} + +func (_c *VoteProcessorFactory_Create_Call) RunAndReturn(run func(log zerolog.Logger, proposal *model.SignedProposal) (hotstuff.VerifyingVoteProcessor, error)) *VoteProcessorFactory_Create_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/weighted_signature_aggregator.go b/consensus/hotstuff/mocks/weighted_signature_aggregator.go index 106914d8ad5..ab753859f9d 100644 --- a/consensus/hotstuff/mocks/weighted_signature_aggregator.go +++ b/consensus/hotstuff/mocks/weighted_signature_aggregator.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewWeightedSignatureAggregator creates a new instance of WeightedSignatureAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewWeightedSignatureAggregator(t interface { + mock.TestingT + Cleanup(func()) +}) *WeightedSignatureAggregator { + mock := &WeightedSignatureAggregator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // WeightedSignatureAggregator is an autogenerated mock type for the WeightedSignatureAggregator type type WeightedSignatureAggregator struct { mock.Mock } -// Aggregate provides a mock function with no fields -func (_m *WeightedSignatureAggregator) Aggregate() (flow.IdentifierList, []byte, error) { - ret := _m.Called() +type WeightedSignatureAggregator_Expecter struct { + mock *mock.Mock +} + +func (_m *WeightedSignatureAggregator) EXPECT() *WeightedSignatureAggregator_Expecter { + return &WeightedSignatureAggregator_Expecter{mock: &_m.Mock} +} + +// Aggregate provides a mock function for the type WeightedSignatureAggregator +func (_mock *WeightedSignatureAggregator) Aggregate() (flow.IdentifierList, []byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Aggregate") @@ -25,55 +48,105 @@ func (_m *WeightedSignatureAggregator) Aggregate() (flow.IdentifierList, []byte, var r0 flow.IdentifierList var r1 []byte var r2 error - if rf, ok := ret.Get(0).(func() (flow.IdentifierList, []byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.IdentifierList, []byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.IdentifierList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentifierList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentifierList) } } - - if rf, ok := ret.Get(1).(func() []byte); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() []byte); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]byte) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// TotalWeight provides a mock function with no fields -func (_m *WeightedSignatureAggregator) TotalWeight() uint64 { - ret := _m.Called() +// WeightedSignatureAggregator_Aggregate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Aggregate' +type WeightedSignatureAggregator_Aggregate_Call struct { + *mock.Call +} + +// Aggregate is a helper method to define mock.On call +func (_e *WeightedSignatureAggregator_Expecter) Aggregate() *WeightedSignatureAggregator_Aggregate_Call { + return &WeightedSignatureAggregator_Aggregate_Call{Call: _e.mock.On("Aggregate")} +} + +func (_c *WeightedSignatureAggregator_Aggregate_Call) Run(run func()) *WeightedSignatureAggregator_Aggregate_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *WeightedSignatureAggregator_Aggregate_Call) Return(identifierList flow.IdentifierList, bytes []byte, err error) *WeightedSignatureAggregator_Aggregate_Call { + _c.Call.Return(identifierList, bytes, err) + return _c +} + +func (_c *WeightedSignatureAggregator_Aggregate_Call) RunAndReturn(run func() (flow.IdentifierList, []byte, error)) *WeightedSignatureAggregator_Aggregate_Call { + _c.Call.Return(run) + return _c +} + +// TotalWeight provides a mock function for the type WeightedSignatureAggregator +func (_mock *WeightedSignatureAggregator) TotalWeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TotalWeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// TrustedAdd provides a mock function with given fields: signerID, sig -func (_m *WeightedSignatureAggregator) TrustedAdd(signerID flow.Identifier, sig crypto.Signature) (uint64, error) { - ret := _m.Called(signerID, sig) +// WeightedSignatureAggregator_TotalWeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TotalWeight' +type WeightedSignatureAggregator_TotalWeight_Call struct { + *mock.Call +} + +// TotalWeight is a helper method to define mock.On call +func (_e *WeightedSignatureAggregator_Expecter) TotalWeight() *WeightedSignatureAggregator_TotalWeight_Call { + return &WeightedSignatureAggregator_TotalWeight_Call{Call: _e.mock.On("TotalWeight")} +} + +func (_c *WeightedSignatureAggregator_TotalWeight_Call) Run(run func()) *WeightedSignatureAggregator_TotalWeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *WeightedSignatureAggregator_TotalWeight_Call) Return(v uint64) *WeightedSignatureAggregator_TotalWeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *WeightedSignatureAggregator_TotalWeight_Call) RunAndReturn(run func() uint64) *WeightedSignatureAggregator_TotalWeight_Call { + _c.Call.Return(run) + return _c +} + +// TrustedAdd provides a mock function for the type WeightedSignatureAggregator +func (_mock *WeightedSignatureAggregator) TrustedAdd(signerID flow.Identifier, sig crypto.Signature) (uint64, error) { + ret := _mock.Called(signerID, sig) if len(ret) == 0 { panic("no return value specified for TrustedAdd") @@ -81,52 +154,115 @@ func (_m *WeightedSignatureAggregator) TrustedAdd(signerID flow.Identifier, sig var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) (uint64, error)); ok { - return rf(signerID, sig) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) (uint64, error)); ok { + return returnFunc(signerID, sig) } - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) uint64); ok { - r0 = rf(signerID, sig) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) uint64); ok { + r0 = returnFunc(signerID, sig) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier, crypto.Signature) error); ok { - r1 = rf(signerID, sig) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, crypto.Signature) error); ok { + r1 = returnFunc(signerID, sig) } else { r1 = ret.Error(1) } - return r0, r1 } -// Verify provides a mock function with given fields: signerID, sig -func (_m *WeightedSignatureAggregator) Verify(signerID flow.Identifier, sig crypto.Signature) error { - ret := _m.Called(signerID, sig) +// WeightedSignatureAggregator_TrustedAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TrustedAdd' +type WeightedSignatureAggregator_TrustedAdd_Call struct { + *mock.Call +} + +// TrustedAdd is a helper method to define mock.On call +// - signerID flow.Identifier +// - sig crypto.Signature +func (_e *WeightedSignatureAggregator_Expecter) TrustedAdd(signerID interface{}, sig interface{}) *WeightedSignatureAggregator_TrustedAdd_Call { + return &WeightedSignatureAggregator_TrustedAdd_Call{Call: _e.mock.On("TrustedAdd", signerID, sig)} +} + +func (_c *WeightedSignatureAggregator_TrustedAdd_Call) Run(run func(signerID flow.Identifier, sig crypto.Signature)) *WeightedSignatureAggregator_TrustedAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *WeightedSignatureAggregator_TrustedAdd_Call) Return(totalWeight uint64, exception error) *WeightedSignatureAggregator_TrustedAdd_Call { + _c.Call.Return(totalWeight, exception) + return _c +} + +func (_c *WeightedSignatureAggregator_TrustedAdd_Call) RunAndReturn(run func(signerID flow.Identifier, sig crypto.Signature) (uint64, error)) *WeightedSignatureAggregator_TrustedAdd_Call { + _c.Call.Return(run) + return _c +} + +// Verify provides a mock function for the type WeightedSignatureAggregator +func (_mock *WeightedSignatureAggregator) Verify(signerID flow.Identifier, sig crypto.Signature) error { + ret := _mock.Called(signerID, sig) if len(ret) == 0 { panic("no return value specified for Verify") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) error); ok { - r0 = rf(signerID, sig) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, crypto.Signature) error); ok { + r0 = returnFunc(signerID, sig) } else { r0 = ret.Error(0) } - return r0 } -// NewWeightedSignatureAggregator creates a new instance of WeightedSignatureAggregator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewWeightedSignatureAggregator(t interface { - mock.TestingT - Cleanup(func()) -}) *WeightedSignatureAggregator { - mock := &WeightedSignatureAggregator{} - mock.Mock.Test(t) +// WeightedSignatureAggregator_Verify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Verify' +type WeightedSignatureAggregator_Verify_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Verify is a helper method to define mock.On call +// - signerID flow.Identifier +// - sig crypto.Signature +func (_e *WeightedSignatureAggregator_Expecter) Verify(signerID interface{}, sig interface{}) *WeightedSignatureAggregator_Verify_Call { + return &WeightedSignatureAggregator_Verify_Call{Call: _e.mock.On("Verify", signerID, sig)} +} - return mock +func (_c *WeightedSignatureAggregator_Verify_Call) Run(run func(signerID flow.Identifier, sig crypto.Signature)) *WeightedSignatureAggregator_Verify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *WeightedSignatureAggregator_Verify_Call) Return(err error) *WeightedSignatureAggregator_Verify_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WeightedSignatureAggregator_Verify_Call) RunAndReturn(run func(signerID flow.Identifier, sig crypto.Signature) error) *WeightedSignatureAggregator_Verify_Call { + _c.Call.Return(run) + return _c } diff --git a/consensus/hotstuff/mocks/workerpool.go b/consensus/hotstuff/mocks/workerpool.go index 447fc39bd43..073b2c7cb26 100644 --- a/consensus/hotstuff/mocks/workerpool.go +++ b/consensus/hotstuff/mocks/workerpool.go @@ -1,23 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks -import mock "github.com/stretchr/testify/mock" - -// Workerpool is an autogenerated mock type for the Workerpool type -type Workerpool struct { - mock.Mock -} - -// StopWait provides a mock function with no fields -func (_m *Workerpool) StopWait() { - _m.Called() -} - -// Submit provides a mock function with given fields: task -func (_m *Workerpool) Submit(task func()) { - _m.Called(task) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewWorkerpool creates a new instance of Workerpool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -32,3 +21,89 @@ func NewWorkerpool(t interface { return mock } + +// Workerpool is an autogenerated mock type for the Workerpool type +type Workerpool struct { + mock.Mock +} + +type Workerpool_Expecter struct { + mock *mock.Mock +} + +func (_m *Workerpool) EXPECT() *Workerpool_Expecter { + return &Workerpool_Expecter{mock: &_m.Mock} +} + +// StopWait provides a mock function for the type Workerpool +func (_mock *Workerpool) StopWait() { + _mock.Called() + return +} + +// Workerpool_StopWait_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StopWait' +type Workerpool_StopWait_Call struct { + *mock.Call +} + +// StopWait is a helper method to define mock.On call +func (_e *Workerpool_Expecter) StopWait() *Workerpool_StopWait_Call { + return &Workerpool_StopWait_Call{Call: _e.mock.On("StopWait")} +} + +func (_c *Workerpool_StopWait_Call) Run(run func()) *Workerpool_StopWait_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Workerpool_StopWait_Call) Return() *Workerpool_StopWait_Call { + _c.Call.Return() + return _c +} + +func (_c *Workerpool_StopWait_Call) RunAndReturn(run func()) *Workerpool_StopWait_Call { + _c.Run(run) + return _c +} + +// Submit provides a mock function for the type Workerpool +func (_mock *Workerpool) Submit(task func()) { + _mock.Called(task) + return +} + +// Workerpool_Submit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Submit' +type Workerpool_Submit_Call struct { + *mock.Call +} + +// Submit is a helper method to define mock.On call +// - task func() +func (_e *Workerpool_Expecter) Submit(task interface{}) *Workerpool_Submit_Call { + return &Workerpool_Submit_Call{Call: _e.mock.On("Submit", task)} +} + +func (_c *Workerpool_Submit_Call) Run(run func(task func())) *Workerpool_Submit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func() + if args[0] != nil { + arg0 = args[0].(func()) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Workerpool_Submit_Call) Return() *Workerpool_Submit_Call { + _c.Call.Return() + return _c +} + +func (_c *Workerpool_Submit_Call) RunAndReturn(run func(task func())) *Workerpool_Submit_Call { + _c.Run(run) + return _c +} diff --git a/consensus/hotstuff/mocks/workers.go b/consensus/hotstuff/mocks/workers.go index 3d0a4b91696..2977a0a839d 100644 --- a/consensus/hotstuff/mocks/workers.go +++ b/consensus/hotstuff/mocks/workers.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mocks -import mock "github.com/stretchr/testify/mock" - -// Workers is an autogenerated mock type for the Workers type -type Workers struct { - mock.Mock -} - -// Submit provides a mock function with given fields: task -func (_m *Workers) Submit(task func()) { - _m.Called(task) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewWorkers creates a new instance of Workers. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,56 @@ func NewWorkers(t interface { return mock } + +// Workers is an autogenerated mock type for the Workers type +type Workers struct { + mock.Mock +} + +type Workers_Expecter struct { + mock *mock.Mock +} + +func (_m *Workers) EXPECT() *Workers_Expecter { + return &Workers_Expecter{mock: &_m.Mock} +} + +// Submit provides a mock function for the type Workers +func (_mock *Workers) Submit(task func()) { + _mock.Called(task) + return +} + +// Workers_Submit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Submit' +type Workers_Submit_Call struct { + *mock.Call +} + +// Submit is a helper method to define mock.On call +// - task func() +func (_e *Workers_Expecter) Submit(task interface{}) *Workers_Submit_Call { + return &Workers_Submit_Call{Call: _e.mock.On("Submit", task)} +} + +func (_c *Workers_Submit_Call) Run(run func(task func())) *Workers_Submit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func() + if args[0] != nil { + arg0 = args[0].(func()) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Workers_Submit_Call) Return() *Workers_Submit_Call { + _c.Call.Return() + return _c +} + +func (_c *Workers_Submit_Call) RunAndReturn(run func(task func())) *Workers_Submit_Call { + _c.Run(run) + return _c +} diff --git a/consensus/hotstuff/model/errors.go b/consensus/hotstuff/model/errors.go index 047e827090f..960a165ca30 100644 --- a/consensus/hotstuff/model/errors.go +++ b/consensus/hotstuff/model/errors.go @@ -34,7 +34,7 @@ func IsNoVoteError(err error) bool { return errors.As(err, &e) } -func NewNoVoteErrorf(msg string, args ...interface{}) error { +func NewNoVoteErrorf(msg string, args ...any) error { return NoVoteError{Err: fmt.Errorf(msg, args...)} } @@ -57,7 +57,7 @@ func IsNoTimeoutError(err error) bool { return errors.As(err, &e) } -func NewNoTimeoutErrorf(msg string, args ...interface{}) error { +func NewNoTimeoutErrorf(msg string, args ...any) error { return NoTimeoutError{Err: fmt.Errorf(msg, args...)} } @@ -70,7 +70,7 @@ func NewInvalidFormatError(err error) error { return InvalidFormatError{err} } -func NewInvalidFormatErrorf(msg string, args ...interface{}) error { +func NewInvalidFormatErrorf(msg string, args ...any) error { return InvalidFormatError{fmt.Errorf(msg, args...)} } @@ -93,7 +93,7 @@ func NewConfigurationError(err error) error { return ConfigurationError{err} } -func NewConfigurationErrorf(msg string, args ...interface{}) error { +func NewConfigurationErrorf(msg string, args ...any) error { return ConfigurationError{fmt.Errorf(msg, args...)} } @@ -169,7 +169,7 @@ type InvalidProposalError struct { Err error } -func NewInvalidProposalErrorf(proposal *SignedProposal, msg string, args ...interface{}) error { +func NewInvalidProposalErrorf(proposal *SignedProposal, msg string, args ...any) error { return InvalidProposalError{ InvalidProposal: proposal, Err: fmt.Errorf(msg, args...), @@ -212,7 +212,7 @@ type InvalidBlockError struct { Err error } -func NewInvalidBlockErrorf(block *Block, msg string, args ...interface{}) error { +func NewInvalidBlockErrorf(block *Block, msg string, args ...any) error { return InvalidBlockError{ InvalidBlock: block, Err: fmt.Errorf(msg, args...), @@ -255,7 +255,7 @@ type InvalidVoteError struct { Err error } -func NewInvalidVoteErrorf(vote *Vote, msg string, args ...interface{}) error { +func NewInvalidVoteErrorf(vote *Vote, msg string, args ...any) error { return InvalidVoteError{ Vote: vote, Err: fmt.Errorf(msg, args...), @@ -307,8 +307,9 @@ func IsByzantineThresholdExceededError(err error) bool { return errors.As(err, &target) } -// DoubleVoteError indicates that a consensus replica has voted for two different -// blocks, or has provided two semantically different votes for the same block. +// DoubleVoteError indicates that a consensus replica has voted for two different blocks +// in the same view, or has provided two semantically different votes for the same block. +// This is a PROTOCOL VIOLATION (slashable equivocation attack). type DoubleVoteError struct { FirstVote *Vote ConflictingVote *Vote @@ -340,7 +341,10 @@ func (e DoubleVoteError) Unwrap() error { return e.err } -func NewDoubleVoteErrorf(firstVote, conflictingVote *Vote, msg string, args ...interface{}) error { +// NewDoubleVoteErrorf creates an error signalling that a consensus replica has voted for two different +// blocks in the same view, or has provided two semantically different votes for the same block. +// This is a PROTOCOL VIOLATION (slashable equivocation attack). +func NewDoubleVoteErrorf(firstVote, conflictingVote *Vote, msg string, args ...any) error { return DoubleVoteError{ FirstVote: firstVote, ConflictingVote: conflictingVote, @@ -357,7 +361,7 @@ func NewDuplicatedSignerError(err error) error { return DuplicatedSignerError{err} } -func NewDuplicatedSignerErrorf(msg string, args ...interface{}) error { +func NewDuplicatedSignerErrorf(msg string, args ...any) error { return DuplicatedSignerError{err: fmt.Errorf(msg, args...)} } @@ -370,7 +374,7 @@ func IsDuplicatedSignerError(err error) bool { return errors.As(err, &e) } -// InvalidSignatureIncludedError indicates that some signatures, included via TrustedAdd, are invalid +// InvalidSignatureIncludedError indicates that some signatures are invalid type InvalidSignatureIncludedError struct { err error } @@ -379,7 +383,7 @@ func NewInvalidSignatureIncludedError(err error) error { return InvalidSignatureIncludedError{err} } -func NewInvalidSignatureIncludedErrorf(msg string, args ...interface{}) error { +func NewInvalidSignatureIncludedErrorf(msg string, args ...any) error { return InvalidSignatureIncludedError{fmt.Errorf(msg, args...)} } @@ -402,7 +406,7 @@ func NewInvalidAggregatedKeyError(err error) error { return InvalidAggregatedKeyError{err} } -func NewInvalidAggregatedKeyErrorf(msg string, args ...interface{}) error { +func NewInvalidAggregatedKeyErrorf(msg string, args ...any) error { return InvalidAggregatedKeyError{fmt.Errorf(msg, args...)} } @@ -423,7 +427,7 @@ func NewInsufficientSignaturesError(err error) error { return InsufficientSignaturesError{err} } -func NewInsufficientSignaturesErrorf(msg string, args ...interface{}) error { +func NewInsufficientSignaturesErrorf(msg string, args ...any) error { return InsufficientSignaturesError{fmt.Errorf(msg, args...)} } @@ -445,7 +449,7 @@ func NewInvalidSignerError(err error) error { return InvalidSignerError{err} } -func NewInvalidSignerErrorf(msg string, args ...interface{}) error { +func NewInvalidSignerErrorf(msg string, args ...any) error { return InvalidSignerError{fmt.Errorf(msg, args...)} } @@ -491,7 +495,7 @@ func (e DoubleTimeoutError) Unwrap() error { return e.err } -func NewDoubleTimeoutErrorf(firstTimeout, conflictingTimeout *TimeoutObject, msg string, args ...interface{}) error { +func NewDoubleTimeoutErrorf(firstTimeout, conflictingTimeout *TimeoutObject, msg string, args ...any) error { return DoubleTimeoutError{ FirstTimeout: firstTimeout, ConflictingTimeout: conflictingTimeout, @@ -505,7 +509,7 @@ type InvalidTimeoutError struct { Err error } -func NewInvalidTimeoutErrorf(timeout *TimeoutObject, msg string, args ...interface{}) error { +func NewInvalidTimeoutErrorf(timeout *TimeoutObject, msg string, args ...any) error { return InvalidTimeoutError{ Timeout: timeout, Err: fmt.Errorf(msg, args...), diff --git a/consensus/hotstuff/pacemaker/timeout/controller_test.go b/consensus/hotstuff/pacemaker/timeout/controller_test.go index be2b367f774..643a91f8d42 100644 --- a/consensus/hotstuff/pacemaker/timeout/controller_test.go +++ b/consensus/hotstuff/pacemaker/timeout/controller_test.go @@ -44,7 +44,7 @@ func Test_TimeoutIncrease(t *testing.T) { tc := initTimeoutController(t) // advance failed rounds beyond `happyPathMaxRoundFailures`; - for r := uint64(0); r < happyPathMaxRoundFailures; r++ { + for range happyPathMaxRoundFailures { tc.OnTimeout() } @@ -81,7 +81,7 @@ func Test_TimeoutDecrease(t *testing.T) { func Test_MinCutoff(t *testing.T) { tc := initTimeoutController(t) - for r := uint64(0); r < happyPathMaxRoundFailures; r++ { + for range happyPathMaxRoundFailures { tc.OnTimeout() // replica timeout doesn't increase since r < happyPathMaxRoundFailures. } diff --git a/consensus/hotstuff/signature/randombeacon_inspector.go b/consensus/hotstuff/signature/randombeacon_inspector.go index e6fa3a1bf0e..6ffdae58ce4 100644 --- a/consensus/hotstuff/signature/randombeacon_inspector.go +++ b/consensus/hotstuff/signature/randombeacon_inspector.go @@ -5,16 +5,19 @@ import ( "github.com/onflow/crypto" + "github.com/onflow/flow-go/consensus/hotstuff" "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/module/signature" ) -// randomBeaconInspector implements hotstuff.RandomBeaconInspector interface. +// randomBeaconInspector implements [hotstuff.RandomBeaconInspector] interface. // All methods of this structure are concurrency-safe. type randomBeaconInspector struct { inspector crypto.ThresholdSignatureInspector } +var _ hotstuff.RandomBeaconInspector = (*randomBeaconInspector)(nil) + // NewRandomBeaconInspector instantiates a new randomBeaconInspector. // The constructor errors with a `model.ConfigurationError` in any of the following cases // - n is not between `ThresholdSignMinSize` and `ThresholdSignMaxSize`, @@ -50,8 +53,8 @@ func NewRandomBeaconInspector( // execute the business logic, without interfering with each other). // It allows concurrent verification of the given signature. // Returns : -// - model.InvalidSignerError if signerIndex is invalid -// - model.ErrInvalidSignature if signerID is valid but signature is cryptographically invalid +// - [model.InvalidSignerError] if signerIndex is invalid +// - [model.ErrInvalidSignature] if signerID is valid but signature is cryptographically invalid // - other error if there is an unexpected exception. func (r *randomBeaconInspector) Verify(signerIndex int, share crypto.Signature) error { valid, err := r.inspector.VerifyShare(signerIndex, share) @@ -75,14 +78,14 @@ func (r *randomBeaconInspector) Verify(signerIndex int, share crypto.Signature) // are returned) through a post-check (verifying the threshold signature // _after_ reconstruction before returning it). // The function is thread-safe but locks its internal state, thereby permitting only -// one routine at a time to add a signature. +// one routine at a time to add a signature (inherited from the underlying inspector). // Returns: // - (true, nil) if the signature has been added, and enough shares have been collected. // - (false, nil) if the signature has been added, but not enough shares were collected. // // The following errors are expected during normal operations: -// - model.InvalidSignerError if signerIndex is invalid (out of the valid range) -// - model.DuplicatedSignerError if the signer has been already added +// - [model.InvalidSignerError] if signerIndex is invalid (out of the valid range) +// - [model.DuplicatedSignerError] if the signer has been already added // - other error if there is an unexpected exception. func (r *randomBeaconInspector) TrustedAdd(signerIndex int, share crypto.Signature) (bool, error) { // Trusted add to the crypto layer @@ -112,8 +115,8 @@ func (r *randomBeaconInspector) EnoughShares() bool { // // Returns: // - (signature, nil) if no error occurred -// - (nil, model.InsufficientSignaturesError) if not enough shares were collected -// - (nil, model.InvalidSignatureIncluded) if at least one collected share does not serialize to a valid BLS signature, +// - (nil, [model.InsufficientSignaturesError]) if not enough shares were collected +// - (nil, [model.InvalidSignatureIncluded]) if at least one collected share does not serialize to a valid BLS signature, // or if the constructed signature failed to verify against the group public key and stored message. This post-verification // is required for safety, as `TrustedAdd` allows adding invalid signatures. // - (nil, error) for any other unexpected error. diff --git a/consensus/hotstuff/signature/randombeacon_reconstructor.go b/consensus/hotstuff/signature/randombeacon_reconstructor.go index 205657bb80e..8f0617cbb09 100644 --- a/consensus/hotstuff/signature/randombeacon_reconstructor.go +++ b/consensus/hotstuff/signature/randombeacon_reconstructor.go @@ -11,8 +11,8 @@ import ( "github.com/onflow/flow-go/state/protocol" ) -// RandomBeaconReconstructor implements hotstuff.RandomBeaconReconstructor. -// The implementation wraps the hotstuff.RandomBeaconInspector and translates the signer identity into signer index. +// RandomBeaconReconstructor implements [hotstuff.RandomBeaconReconstructor]. +// The implementation wraps the [hotstuff.RandomBeaconInspector] and translates the signer identity into signer index. // It has knowledge about DKG to be able to map signerID to signerIndex type RandomBeaconReconstructor struct { hotstuff.RandomBeaconInspector // a stateful object for this epoch. It's used for both verifying all sig shares and reconstructing the threshold signature. @@ -33,8 +33,8 @@ func NewRandomBeaconReconstructor(dkg hotstuff.DKG, randomBeaconInspector hotstu // execute the business logic, without interfering with each other). // It allows concurrent verification of the given signature. // Returns : -// - model.InvalidSignerError if signerID is invalid -// - model.ErrInvalidSignature if signerID is valid but signature is cryptographically invalid +// - [model.InvalidSignerError] if signerID is invalid +// - [model.ErrInvalidSignature] if signerID is valid but signature is cryptographically invalid // - other error if there is an unexpected exception. func (r *RandomBeaconReconstructor) Verify(signerID flow.Identifier, sig crypto.Signature) error { signerIndex, err := r.dkg.Index(signerID) @@ -60,8 +60,8 @@ func (r *RandomBeaconReconstructor) Verify(signerID flow.Identifier, sig crypto. // - (false, nil) if the signature has been added, but not enough shares were collected. // // The following errors are expected during normal operations: -// - model.InvalidSignerError if signerIndex is invalid (out of the valid range) -// - model.DuplicatedSignerError if the signer has been already added +// - [model.InvalidSignerError] if signerIndex is invalid (out of the valid range) +// - [model.DuplicatedSignerError] if the signer has been already added // - other error if there is an unexpected exception. func (r *RandomBeaconReconstructor) TrustedAdd(signerID flow.Identifier, sig crypto.Signature) (bool, error) { signerIndex, err := r.dkg.Index(signerID) diff --git a/consensus/hotstuff/signature/weighted_signature_aggregator.go b/consensus/hotstuff/signature/weighted_signature_aggregator.go index 7e111cff870..f1e6f9e57b1 100644 --- a/consensus/hotstuff/signature/weighted_signature_aggregator.go +++ b/consensus/hotstuff/signature/weighted_signature_aggregator.go @@ -19,26 +19,24 @@ type signerInfo struct { index int } -// WeightedSignatureAggregator implements consensus/hotstuff.WeightedSignatureAggregator. -// It is a wrapper around module/signature.SignatureAggregatorSameMessage, which implements a +// WeightedSignatureAggregator implements [hotstuff.WeightedSignatureAggregator]. +// It is a wrapper around [signature.SignatureAggregatorSameMessage], implementing a // mapping from node IDs (as used by HotStuff) to index-based addressing of authorized -// signers (as used by SignatureAggregatorSameMessage). +// signers (as used by [signature.SignatureAggregatorSameMessage]). // -// Similarly to module/signature.SignatureAggregatorSameMessage, this module assumes proofs of possession (PoP) -// of all identity public keys are valid. +// We delegate the handling of duplicate signatures to the underlying [signature.SignatureAggregatorSameMessage]. +// NOTE: This is possible, because [signature.SignatureAggregatorSameMessage] does not support signatures with +// multiplicity higher than 1, i.e. each signer is allowed to sign at most once. Should this constraint every be +// changed in [signature.SignatureAggregatorSameMessage], this module would need to be updated accordingly. +// +// Similarly to [signature.SignatureAggregatorSameMessage], this module assumes proofs +// of possession (PoP) of all identity public keys are valid. type WeightedSignatureAggregator struct { aggregator *signature.SignatureAggregatorSameMessage // low level crypto BLS aggregator, agnostic of weights and flow IDs ids flow.IdentityList // all possible ids (only gets updated by constructor) idToInfo map[flow.Identifier]signerInfo // auxiliary map to lookup signer weight and index by ID (only gets updated by constructor) totalWeight uint64 // weight collected (gets updated) lock sync.RWMutex // lock for atomic updates to totalWeight and collectedIDs - - // collectedIDs tracks the Identities of all nodes whose signatures have been collected so far. - // The reason for tracking the duplicate signers at this module level is that having no duplicates - // is a Hotstuff constraint, rather than a cryptographic aggregation constraint. We are planning to - // extend the cryptographic primitives to support multiplicity higher than 1 in the future. - // Therefore, we already add the logic for identifying duplicates here. - collectedIDs map[flow.Identifier]struct{} // map of collected IDs (gets updated) } var _ hotstuff.WeightedSignatureAggregator = (*WeightedSignatureAggregator)(nil) @@ -81,17 +79,16 @@ func NewWeightedSignatureAggregator( } return &WeightedSignatureAggregator{ - aggregator: agg, - ids: ids, - idToInfo: idToInfo, - collectedIDs: make(map[flow.Identifier]struct{}), + aggregator: agg, + ids: ids, + idToInfo: idToInfo, }, nil } // Verify verifies the signature under the stored public keys and message. // Expected errors during normal operations: -// - model.InvalidSignerError if signerID is invalid (not a consensus participant) -// - model.ErrInvalidSignature if signerID is valid but signature is cryptographically invalid +// - [model.InvalidSignerError] if signerID is invalid (not a consensus participant) +// - [model.ErrInvalidSignature] if signerID is valid but signature is cryptographically invalid // // The function is thread-safe. func (w *WeightedSignatureAggregator) Verify(signerID flow.Identifier, sig crypto.Signature) error { @@ -116,8 +113,8 @@ func (w *WeightedSignatureAggregator) Verify(signerID flow.Identifier, sig crypt // The total weight of all collected signatures (excluding duplicates) is returned regardless // of any returned error. // The function errors with: -// - model.InvalidSignerError if signerID is invalid (not a consensus participant) -// - model.DuplicatedSignerError if the signer has been already added +// - [model.InvalidSignerError] if signerID is invalid (not a consensus participant) +// - [model.DuplicatedSignerError] if the signer has been already added // // The function is thread-safe. func (w *WeightedSignatureAggregator) TrustedAdd(signerID flow.Identifier, sig crypto.Signature) (uint64, error) { @@ -130,19 +127,20 @@ func (w *WeightedSignatureAggregator) TrustedAdd(signerID flow.Identifier, sig c w.lock.Lock() defer w.lock.Unlock() - // check for repeated occurrence of signerID (in anticipation of aggregator supporting multiplicities larger than 1 in the future) - if _, duplicate := w.collectedIDs[signerID]; duplicate { - return w.totalWeight, model.NewDuplicatedSignerErrorf("signature from %v was already added", signerID) - } - + // NOTE: We delegate the handling of duplicate signatures to the underlying [signature.SignatureAggregatorSameMessage]. + // This is valid only because [signature.SignatureAggregatorSameMessage] does not support signatures with multiplicity + // higher than 1, i.e. each signer is allowed to sign at most once. Should this constraint every be relaxed in + // [signature.SignatureAggregatorSameMessage], we need to implement it here in the `WeightedSignatureAggregator`, + // because in the context of HotStuff each consensus replica is allowed to vote at most once. err := w.aggregator.TrustedAdd(info.index, sig) if err != nil { - // During normal operations, signature.InvalidSignerIdxError or signature.DuplicatedSignerIdxError should never occur. + if signature.IsDuplicatedSignerIdxError(err) { + return w.totalWeight, model.NewDuplicatedSignerErrorf("signature from %v was already added", signerID) + } + // During normal operations, signature.InvalidSignerIdxError should never occur. return w.totalWeight, fmt.Errorf("unexpected exception while trusted add of signature from %v: %w", signerID, err) } w.totalWeight += info.weight - w.collectedIDs[signerID] = struct{}{} - return w.totalWeight, nil } @@ -158,12 +156,12 @@ func (w *WeightedSignatureAggregator) TotalWeight() uint64 { // The function performs a final verification and errors if the aggregated signature is invalid. This is // required for the function safety since `TrustedAdd` allows adding invalid signatures. // The function errors with: -// - model.InsufficientSignaturesError if no signatures have been added yet -// - model.InvalidSignatureIncludedError if: +// - [model.InsufficientSignaturesError] if no signatures have been added yet +// - [model.InvalidSignatureIncludedError] if: // - some signature(s), included via TrustedAdd, fail to deserialize (regardless of the aggregated public key) // -- or all signatures deserialize correctly but some signature(s), included via TrustedAdd, are // invalid (while aggregated public key is valid) -// -- model.InvalidAggregatedKeyError if all signatures deserialize correctly but the signer's +// -- [model.InvalidAggregatedKeyError] if all signatures deserialize correctly but the signer's // staking public keys sum up to an invalid key (BLS identity public key). // Any aggregated signature would fail the cryptographic verification under the identity public // key and therefore such signature is considered invalid. Such scenario can only happen if diff --git a/consensus/hotstuff/vote_collector.go b/consensus/hotstuff/vote_collector.go index 3a259808dc4..15e99156dd9 100644 --- a/consensus/hotstuff/vote_collector.go +++ b/consensus/hotstuff/vote_collector.go @@ -59,14 +59,15 @@ type VoteCollector interface { // ProcessBlock performs validation of block signature and processes block with respected collector. // Calling this function will mark conflicting collector as stale and change state of valid collectors // It returns nil if the block is valid. - // It returns model.InvalidProposalError if block is invalid. + // It returns [model.InvalidProposalError] if block is invalid. // It returns other error if there is exception processing the block. ProcessBlock(block *model.SignedProposal) error - // AddVote adds a vote to the collector - // When enough votes have been added to produce a QC, the QC will be created asynchronously, and - // passed to EventLoop through a callback. - // No errors are expected during normal operations. + // AddVote adds a vote to the vote collector. The vote must be for the `VoteCollector`'s view (otherwise, + // an exception is returned). When enough votes have been added to produce a QC, the QC will be created + // asynchronously, and passed to EventLoop through a callback. + // All byzantine edge cases are handled internally via callbacks to notifier. + // Under normal execution only exceptions are propagated to caller. AddVote(vote *model.Vote) error // RegisterVoteConsumer registers a VoteConsumer. Upon registration, the collector @@ -88,11 +89,13 @@ type VoteCollector interface { // Depending on their implementation, a VoteProcessor might drop votes or attempt to construct a QC. type VoteProcessor interface { // Process performs processing of single vote. This function is safe to call from multiple goroutines. + // // Expected error returns during normal operations: - // * VoteForIncompatibleBlockError - submitted vote for incompatible block - // * VoteForIncompatibleViewError - submitted vote for incompatible view - // * model.InvalidVoteError - submitted vote with invalid signature - // * model.DuplicatedSignerError - vote from a signer whose vote was previously already processed + // - [VoteForIncompatibleBlockError] if vote is for incompatible block + // - [VoteForIncompatibleViewError] if vote is for incompatible view + // - [model.InvalidVoteError] if vote has invalid signature + // - [model.DuplicatedSignerError] if the same vote from the same signer has been already added + // // All other errors should be treated as exceptions. Process(vote *model.Vote) error @@ -100,7 +103,13 @@ type VoteProcessor interface { Status() VoteCollectorStatus } -// VerifyingVoteProcessor is a VoteProcessor that attempts to construct a QC for the given block. +// VerifyingVoteProcessor is a VoteProcessor that attempts to construct a QC for a specific block +// (provided at construction time). +// +// IMPORTANT: The VerifyingVoteProcessor provides the final defense against any vote-equivocation attacks +// for its specific block. These attacks typically aim at multiple votes from the same node being counted +// towards the supermajority threshold. The VerifyingVoteProcessor must withstand attacks by the +// leader concurrently utilizing stand-alone votes and votes embedded into the proposal. type VerifyingVoteProcessor interface { VoteProcessor @@ -115,6 +124,6 @@ type VoteProcessorFactory interface { // Create instantiates a VerifyingVoteProcessor for processing votes for a specific proposal. // Caller can be sure that proposal vote was successfully verified and processed. // Expected error returns during normal operations: - // * model.InvalidProposalError - proposal has invalid proposer vote + // * [model.InvalidProposalError] - proposal has invalid proposer vote Create(log zerolog.Logger, proposal *model.SignedProposal) (VerifyingVoteProcessor, error) } diff --git a/consensus/hotstuff/voteaggregator/vote_collectors_test.go b/consensus/hotstuff/voteaggregator/vote_collectors_test.go index ee721ea1521..f1851c03538 100644 --- a/consensus/hotstuff/voteaggregator/vote_collectors_test.go +++ b/consensus/hotstuff/voteaggregator/vote_collectors_test.go @@ -5,6 +5,7 @@ import ( "fmt" "sync" "testing" + "time" "github.com/gammazero/workerpool" "github.com/stretchr/testify/require" @@ -49,7 +50,7 @@ func (s *VoteCollectorsTestSuite) SetupTest() { } func (s *VoteCollectorsTestSuite) TearDownTest() { - s.workerPool.StopWait() + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) } // prepareMockedCollector prepares a mocked collector and stores it in map, later it will be used diff --git a/consensus/hotstuff/votecollector/combined_vote_processor_v2.go b/consensus/hotstuff/votecollector/combined_vote_processor_v2.go index c1b4edececa..5e756c35def 100644 --- a/consensus/hotstuff/votecollector/combined_vote_processor_v2.go +++ b/consensus/hotstuff/votecollector/combined_vote_processor_v2.go @@ -100,6 +100,7 @@ type CombinedVoteProcessorV2 struct { rbRector hotstuff.RandomBeaconReconstructor onQCCreated hotstuff.OnQCCreated packer hotstuff.Packer + votesCache *AppendOnlyIdentifierSet minRequiredWeight uint64 done atomic.Bool } @@ -121,6 +122,7 @@ func NewCombinedVoteProcessor(log zerolog.Logger, rbRector: rbRector, onQCCreated: onQCCreated, packer: packer, + votesCache: NewConcurrentIdentifierSet(), minRequiredWeight: minRequiredWeight, done: *atomic.NewBool(false), } @@ -136,27 +138,45 @@ func (p *CombinedVoteProcessorV2) Status() hotstuff.VoteCollectorStatus { return hotstuff.VoteCollectorStatusVerifying } -// Process performs processing of single vote in concurrent safe way. This function is implemented to be -// called by multiple goroutines at the same time. Supports processing of both staking and random beacon signatures. -// Design of this function is event driven: as soon as we collect enough signatures to create a QC we will immediately do so -// and submit it via callback for further processing. +// Process ingests a single vote. It can be called by multiple goroutines at the same time. While all valid +// votes must carry a staking signature, most nodes should also include their random beacon signatures as +// part of their vote (but technically it's optional). +// Design of this function is event driven: as soon as we collect enough signatures to create a QC, we will +// immediately do so and submit it via callback for further processing. However, due to concurrency, a few +// more than the minimum required signatures might be container in the QC (permitted by the protocol). +// +// IMPORTANT: The VerifyingVoteProcessor provides the final defense against any vote-equivocation attacks +// for its specific block. These attacks typically aim at multiple votes from the same node being counted +// towards the supermajority threshold. This must cover attacks by the leader concurrently utilizing +// stand-alone votes and votes embedded into the proposal. +// // Expected error returns during normal operations: -// * VoteForIncompatibleBlockError - submitted vote for incompatible block -// * VoteForIncompatibleViewError - submitted vote for incompatible view -// * model.InvalidVoteError - submitted vote with invalid signature -// * model.DuplicatedSignerError if the signer has been already added -// All other errors should be treated as exceptions. +// - [VoteForIncompatibleBlockError] if vote is for incompatible block +// - [VoteForIncompatibleViewError] if vote is for incompatible view +// - [model.InvalidVoteError] if vote has invalid signature +// - [model.DuplicatedSignerError] if the same vote from the same signer has been already added // -// Impossibility of vote double-counting: Our signature scheme requires _every_ vote to supply a -// staking signature. Therefore, the `stakingSigAggtor` has the set of _all_ signerIDs that have -// provided a valid vote. Hence, the `stakingSigAggtor` guarantees that only a single vote can -// be successfully added for each `signerID`, i.e. double-counting votes is impossible. +// All other errors should be treated as exceptions. func (p *CombinedVoteProcessorV2) Process(vote *model.Vote) error { err := EnsureVoteForBlock(vote, p.block) if err != nil { return fmt.Errorf("received incompatible vote %v: %w", vote.ID(), err) } + // Impossibility of vote double-counting: Our signature scheme requires _every_ vote to include a staking signature. + // Therefore, the `stakingSigAggtor` has the set of _all_ signerIDs that have provided a valid vote. Only a single + // competing thread for any specific voter can pass through `stakingSigAggtor` and succeed in adding a vote (validation + // front-loaded). Only threads that pass the `stakingSigAggtor` can reach the random beacon reconstructor. Therefore, + // the `stakingSigAggtor` acts like a trapdoor for competing threads, guaranteeing that only a single vote per signerID + // is accepted by the CombinedVoteProcessorV2. + // However, note that we *must prevalidate votes* to avoid detecting ann invalid vote only after having added its + // staking signature to the `stakingSigAggtor`. This performance overhead makes the `CombinedVoteProcessorV2` vulnerable + // to resource exhaustion attacks. We therefore include a dedicated `votesCache` to reject all votes beyond the first + // before we run the expensive cryptographic validation. + if !p.votesCache.Add(vote.SignerID) { + return model.NewDuplicatedSignerErrorf("vote from %s has been already added", vote.SignerID) + } + // Vote Processing state machine if p.done.Load() { return nil diff --git a/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go b/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go index cbb2b488d9e..8a4d67b375e 100644 --- a/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go +++ b/consensus/hotstuff/votecollector/combined_vote_processor_v2_test.go @@ -22,11 +22,11 @@ import ( "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/consensus/hotstuff/safetyrules" "github.com/onflow/flow-go/consensus/hotstuff/signature" - hsig "github.com/onflow/flow-go/consensus/hotstuff/signature" hotstuffvalidator "github.com/onflow/flow-go/consensus/hotstuff/validator" "github.com/onflow/flow-go/consensus/hotstuff/verification" "github.com/onflow/flow-go/model/encodable" "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/local" modulemock "github.com/onflow/flow-go/module/mock" msig "github.com/onflow/flow-go/module/signature" @@ -83,6 +83,7 @@ func (s *CombinedVoteProcessorV2TestSuite) SetupTest() { onQCCreated: s.onQCCreated, packer: s.packer, minRequiredWeight: s.minRequiredWeight, + votesCache: NewConcurrentIdentifierSet(), done: *atomic.NewBool(false), } } @@ -302,6 +303,7 @@ func (s *CombinedVoteProcessorV2TestSuite) TestProcess_BuildQCError() { rbRector: rbReconstructor, onQCCreated: s.onQCCreated, packer: packer, + votesCache: NewConcurrentIdentifierSet(), minRequiredWeight: s.minRequiredWeight, done: *atomic.NewBool(false), } @@ -415,7 +417,9 @@ func (s *CombinedVoteProcessorV2TestSuite) TestProcess_ConcurrentCreatingQC() { defer shutdownWg.Done() startupWg.Wait() err := s.processor.Process(vote) - require.NoError(s.T(), err) + if err != nil { + require.True(s.T(), model.IsDuplicatedSignerError(err)) + } }() } @@ -558,6 +562,7 @@ func TestCombinedVoteProcessorV2_PropertyCreatingQCCorrectness(testifyT *testing rbRector: reconstructor, onQCCreated: onQCCreated, packer: pcker, + votesCache: NewConcurrentIdentifierSet(), minRequiredWeight: minRequiredWeight, done: *atomic.NewBool(false), } @@ -710,6 +715,7 @@ func TestCombinedVoteProcessorV2_PropertyCreatingQCLiveness(testifyT *testing.T) rbRector: reconstructor, onQCCreated: onQCCreated, packer: pcker, + votesCache: NewConcurrentIdentifierSet(), minRequiredWeight: minRequiredWeight, done: *atomic.NewBool(false), } @@ -817,7 +823,7 @@ func TestCombinedVoteProcessorV2_BuildVerifyQC(t *testing.T) { // there is no Random Beacon key for this epoch keys.On("RetrieveMyBeaconPrivateKey", epochCounter).Return(nil, false, nil) - beaconSignerStore := hsig.NewEpochAwareRandomBeaconKeyStore(epochLookup, keys) + beaconSignerStore := signature.NewEpochAwareRandomBeaconKeyStore(epochLookup, keys) me, err := local.New(identity.IdentitySkeleton, stakingPriv) require.NoError(t, err) @@ -840,7 +846,7 @@ func TestCombinedVoteProcessorV2_BuildVerifyQC(t *testing.T) { // there is Random Beacon key for this epoch keys.On("RetrieveMyBeaconPrivateKey", epochCounter).Return(dkgKey, true, nil) - beaconSignerStore := hsig.NewEpochAwareRandomBeaconKeyStore(epochLookup, keys) + beaconSignerStore := signature.NewEpochAwareRandomBeaconKeyStore(epochLookup, keys) me, err := local.New(identity.IdentitySkeleton, stakingPriv) require.NoError(t, err) @@ -898,7 +904,7 @@ func TestCombinedVoteProcessorV2_BuildVerifyQC(t *testing.T) { qcCreated := false onQCCreated := func(qc *flow.QuorumCertificate) { - packer := hsig.NewConsensusSigDataPacker(committee) + packer := signature.NewConsensusSigDataPacker(committee) // create verifier that will do crypto checks of created QC verifier := verification.NewCombinedVerifier(committee, packer) @@ -972,3 +978,106 @@ func TestReadRandomSourceFromPackedQCV2(t *testing.T) { // verify the random source is deterministic require.Equal(t, randomSource, randomSourceAgain) } + +// TestCombinedVoteProcessorV2_DoubleVoting tests that CombinedVoteProcessorV2 is able to +// detect a situation where a consensus participant is sending two different votes: +// first vote is signed with the staking key only and the other one is signed with the random beacon key. +// This is a form of vote equivocation where a node sends a different vote from the one it has submitted previously. +// CombinedVoteProcessorV2 has to detect that the vote from given participant has been already processed and return a respective error. +// +// There are two conceptually different attack scenarios we are testing here: +// - Leader-based attacks: +// (a) The leader might send block proposal and equivocate by sending a different conflicting vote. +// (b) The leader might send a block proposal and (repeatedly) send the same vote again as an independent message. +// - Any byzantine node (replicas and leader alike) might send multiple individual vote messages (repeated identical votes, or equivocating with different votes). +func TestCombinedVoteProcessorV2_DoubleVoting(t *testing.T) { + proposerView := uint64(20) + + dkgData, err := bootstrapDKG.RandomBeaconKG(4, unittest.RandomBytes(32)) + require.NoError(t, err) + + // prepare a minimal consensus committee with all nodes participating in the RandomBeacon KG + allIdentities := unittest.IdentityListFixture(len(dkgData.PubKeyShares)).Sort(flow.Canonical[flow.Identity]) + dkgParticipants := make(map[flow.Identifier]flow.DKGParticipant) + for index, identity := range allIdentities { + dkgParticipants[identity.NodeID] = flow.DKGParticipant{ + Index: uint(index), + KeyShare: dkgData.PubKeyShares[index], + } + } + + leader := allIdentities[0] + + stakingPriv := unittest.StakingPrivKeyFixture() + leader.StakingPubKey = stakingPriv.PublicKey() + + leaderParticipantData := dkgParticipants[leader.NodeID] + dkgKey := encodable.RandomBeaconPrivKey{ + PrivateKey: dkgData.PrivKeyShares[leaderParticipantData.Index], + } + + me, err := local.New(leader.IdentitySkeleton, stakingPriv) + require.NoError(t, err) + + beaconSignerStore := modulemock.NewRandomBeaconKeyStore(t) + beaconSignerStore.On("ByView", proposerView).Return(dkgKey, nil) + rbSigner := verification.NewCombinedSigner(me, beaconSignerStore) + + stakingSignerStore := modulemock.NewRandomBeaconKeyStore(t) + stakingSignerStore.On("ByView", proposerView).Return(nil, module.ErrNoBeaconKeyForEpoch) + stakingSigner := verification.NewCombinedSigner(me, stakingSignerStore) + + block := helper.MakeBlock(helper.WithBlockView(proposerView), helper.WithBlockProposer(leader.NodeID)) + + // create and sign proposal + leaderVote, err := rbSigner.CreateVote(block) + require.Equal(t, 2*msig.SigLen, len(leaderVote.SigData), "sanity check failed: need a compound staking + beacon signature in the vote for this test") + require.NoError(t, err) + proposal := helper.MakeSignedProposal(helper.WithProposal(helper.MakeProposal(helper.WithBlock(block))), helper.WithSigData(leaderVote.SigData)) + + // construct another vote for this block but using staking key this time. + // this will result in inconsistent voting. + leaderDifferentVote, err := stakingSigner.CreateVote(block) // this vote has only staking sig; while individually valid, it is different from `leaderVote` + require.NoError(t, err) + + // construct an equivocating vote, same view, but different block ID + otherBlock := helper.MakeBlock(helper.WithBlockView(block.View)) + leaderDifferentBlockVote, err := rbSigner.CreateVote(otherBlock) + require.NoError(t, err) + + onQCCreated := func(qc *flow.QuorumCertificate) { + require.Fail(t, "qc is not expected to be created in this test scenario") + } + + committee, err := committees.NewStaticCommittee(allIdentities, flow.ZeroID, dkgParticipants, dkgData.PubGroupKey) + require.NoError(t, err) + + baseFactory := &combinedVoteProcessorFactoryBaseV2{ + committee: committee, + onQCCreated: onQCCreated, + packer: signature.NewConsensusSigDataPacker(committee), + } + voteProcessorFactory := &VoteProcessorFactory{ + baseFactory: baseFactory.Create, + } + voteProcessor, err := voteProcessorFactory.Create(unittest.Logger(), proposal) + require.NoError(t, err) + + t.Run("duplicated-vote", func(t *testing.T) { + // process the same vote again + err = voteProcessor.Process(leaderVote) + require.Error(t, err) + require.True(t, model.IsDuplicatedSignerError(err)) + }) + t.Run("vote for different block", func(t *testing.T) { + // process the double vote, this has to result in an error. + err = voteProcessor.Process(leaderDifferentBlockVote) + require.ErrorAs(t, err, &VoteForIncompatibleBlockError) + }) + t.Run("vote for same block with different signature scheme", func(t *testing.T) { + // process the double vote, this has to result in an error. + err = voteProcessor.Process(leaderDifferentVote) + require.Error(t, err) + require.True(t, model.IsDuplicatedSignerError(err)) + }) +} diff --git a/consensus/hotstuff/votecollector/combined_vote_processor_v3.go b/consensus/hotstuff/votecollector/combined_vote_processor_v3.go index e47234421be..dc2aaa26adb 100644 --- a/consensus/hotstuff/votecollector/combined_vote_processor_v3.go +++ b/consensus/hotstuff/votecollector/combined_vote_processor_v3.go @@ -109,6 +109,7 @@ func (f *combinedVoteProcessorFactoryBaseV3) Create(log zerolog.Logger, block *m rbRector: rbRector, onQCCreated: f.onQCCreated, packer: f.packer, + votesCache: NewConcurrentIdentifierSet(), minRequiredWeight: minRequiredWeight, done: *atomic.NewBool(false), }, nil @@ -130,6 +131,7 @@ type CombinedVoteProcessorV3 struct { rbRector hotstuff.RandomBeaconReconstructor onQCCreated hotstuff.OnQCCreated packer hotstuff.Packer + votesCache *AppendOnlyIdentifierSet minRequiredWeight uint64 done atomic.Bool } @@ -146,39 +148,65 @@ func (p *CombinedVoteProcessorV3) Status() hotstuff.VoteCollectorStatus { return hotstuff.VoteCollectorStatusVerifying } -// Process performs processing of single vote in concurrent safe way. This function is implemented to be -// called by multiple goroutines at the same time. Supports processing of both staking and random beacon signatures. -// Design of this function is event driven: as soon as we collect enough signatures to create a QC we will immediately do so -// and submit it via callback for further processing. +// Process ingests a single vote. It can be called by multiple goroutines at the same time. While all valid +// votes must carry a staking signature, most nodes should solely provide their random beacon signatures but +// nodes can fall back to voting with their staking signature (e.g. node did not succeed the DKG). +// Design of this function is event driven: as soon as we collect enough signatures to create a QC, we will +// immediately do so and submit it via callback for further processing. However, due to concurrency, a few +// more than the minimum required signatures might be container in the QC (permitted by the protocol). +// +// IMPORTANT: The VerifyingVoteProcessor provides the final defense against any vote-equivocation attacks +// for its specific block. These attacks typically aim at multiple votes from the same node being counted +// towards the supermajority threshold. This must cover attacks by the leader concurrently utilizing +// stand-alone votes and votes embedded into the proposal. +// // Expected error returns during normal operations: -// * VoteForIncompatibleBlockError - submitted vote for incompatible block -// * VoteForIncompatibleViewError - submitted vote for incompatible view -// * model.InvalidVoteError - submitted vote with invalid signature -// * model.DuplicatedSignerError - vote from a signer whose vote was previously already processed -// All other errors should be treated as exceptions. +// - [VoteForIncompatibleBlockError] if vote is for incompatible block +// - [VoteForIncompatibleViewError] if vote is for incompatible view +// - [model.InvalidVoteError] if vote has invalid signature +// - [model.DuplicatedSignerError] if the same vote from the same signer has been already added // -// CAUTION: implementation is NOT (yet) BFT -// Explanation: for correctness, we require that no voter can be counted repeatedly. However, -// CombinedVoteProcessorV3 relies on the `VoteCollector`'s `votesCache` filter out all votes but the first for -// every signerID. However, we have the edge case, where we still feed the proposers vote twice into the -// `VerifyingVoteProcessor` (once as part of a cached vote, once as an individual vote). This can be exploited -// by a byzantine proposer to be erroneously counted twice, which would lead to a safety fault. +// All other errors should be treated as exceptions. // -// TODO (suggestion): I think it would be worth-while to include a second `votesCache` into the `CombinedVoteProcessorV3`. -// Thereby, `CombinedVoteProcessorV3` inherently guarantees correctness of the QCs it produces without relying on -// external conditions (making the code more modular, less interdependent and thereby easier to maintain). The -// runtime overhead is marginal: For `votesCache` to add 500 votes (concurrently with 20 threads) takes about -// 0.25ms. This runtime overhead is neglectable and a good tradeoff for the gain in maintainability and code clarity. +// Impossibility of vote double-counting: All votes before being counted by the aggregator are first deduplicated using +// a dedicated votesCache which tracks votes by signerID this ensures that at most one vote will be processed from given +// signer. This means that [CombinedVoteProcessorV3] guarantees to process at most one vote per signer, everything else +// will be discarded as duplicate. We rely on the external components to detect and slash equivocation cases. func (p *CombinedVoteProcessorV3) Process(vote *model.Vote) error { err := EnsureVoteForBlock(vote, p.block) if err != nil { return fmt.Errorf("received incompatible vote %v: %w", vote.ID(), err) } + // Add vote to a local cache to track repeated and double votes before processing them by specific aggregators. + // Consensus committee member can provide vote in two forms: a staking signature and a random beacon signature. + // Therefore, we might receive two votes from one node, where the first vote gets processed by the StakingSigAggregator and + // second one by RBSigAggregator. Since each of the aggregators tracks votes by signer ID, they cannot detect duplicated or + // repeated votes if they were provided only one to each aggregator. It's impossible to deduplicate votes without relying on + // external components to do the job. To increase modularity and BFT resilience of this component we are introducing a + // votesCache which tracks votes by signer ID. Using votesCache we can guarantee that we will process at most one vote per + // signer, which guarantees correctness of the QCs we produce without relying on external conditions. + // + // The way votesCache is used introduces some weak consistency between cache and aggregators; on happy path it's completely + // straightforward approach. Adding a vote to the votesCache acts like a trapdoor for competing threads: only a single competing + // thread for a specific voter will pass through and succeed in adding a vote to the aggregator(s). + // It gets more interesting when any of the operations fail after we add the vote to the cache. The way this logic is structured, + // it results in the following rule: + // ▷ Only the very first vote that was added to the votesCache from the same signer will be processed by the component. ◁ + // It means that if the vote was invalid by any reason from the point of view of the aggregator, a second vote + // won't be processed at all even if it might be correct from the point of view of the aggregator. + // Formally: Let n denote the total state of the consensus committee. If we receive invalid votes from participants with a + // combined state ≥ n/3, then we won't be able to produce a QC for this particular view. Otherwise, this component must eventually + // always produce a QC, provided enough valid votes arrive. + if !p.votesCache.Add(vote.SignerID) { + return model.NewDuplicatedSignerErrorf("vote from %s has been already added", vote.SignerID) + } + // Vote Processing state machine if p.done.Load() { return nil } + sigType, sig, err := msig.DecodeSingleSig(vote.SigData) if err != nil { if errors.Is(err, msig.ErrInvalidSignatureFormat) { diff --git a/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go b/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go index 6afcf56392a..aca9120ded1 100644 --- a/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go +++ b/consensus/hotstuff/votecollector/combined_vote_processor_v3_test.go @@ -26,6 +26,7 @@ import ( "github.com/onflow/flow-go/model/encodable" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/flow/filter" + "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/local" modulemock "github.com/onflow/flow-go/module/mock" "github.com/onflow/flow-go/module/signature" @@ -97,6 +98,7 @@ func (s *CombinedVoteProcessorV3TestSuite) SetupTest() { onQCCreated: s.onQCCreated, packer: s.packer, minRequiredWeight: s.minRequiredWeight, + votesCache: NewConcurrentIdentifierSet(), done: *atomic.NewBool(false), } } @@ -227,19 +229,23 @@ func (s *CombinedVoteProcessorV3TestSuite) TestProcess_TrustedAdd_Exception() { require.ErrorIs(s.T(), err, exception) require.False(s.T(), model.IsInvalidVoteError(err)) }) - s.Run("threshold-sig", func() { + s.Run("threshold-sig-aggregator", func() { thresholdVote := unittest.VoteForBlockFixture(s.proposal.Block, unittest.VoteWithBeaconSig()) *s.rbSigAggregator = mockhotstuff.WeightedSignatureAggregator{} - *s.reconstructor = mockhotstuff.RandomBeaconReconstructor{} s.rbSigAggregator.On("Verify", thresholdVote.SignerID, mock.Anything).Return(nil) s.rbSigAggregator.On("TrustedAdd", thresholdVote.SignerID, mock.Anything).Return(uint64(0), exception).Once() err := s.processor.Process(thresholdVote) require.ErrorIs(s.T(), err, exception) require.False(s.T(), model.IsInvalidVoteError(err)) - // test also if reconstructor failed to add it + }) + s.Run("threshold-sig-reconstructor", func() { + thresholdVote := unittest.VoteForBlockFixture(s.proposal.Block, unittest.VoteWithBeaconSig()) + *s.rbSigAggregator = mockhotstuff.WeightedSignatureAggregator{} + *s.reconstructor = mockhotstuff.RandomBeaconReconstructor{} + s.rbSigAggregator.On("Verify", thresholdVote.SignerID, mock.Anything).Return(nil).Once() s.rbSigAggregator.On("TrustedAdd", thresholdVote.SignerID, mock.Anything).Return(s.sigWeight, nil).Once() s.reconstructor.On("TrustedAdd", thresholdVote.SignerID, mock.Anything).Return(false, exception).Once() - err = s.processor.Process(thresholdVote) + err := s.processor.Process(thresholdVote) require.ErrorIs(s.T(), err, exception) require.False(s.T(), model.IsInvalidVoteError(err)) }) @@ -291,6 +297,7 @@ func (s *CombinedVoteProcessorV3TestSuite) TestProcess_BuildQCError() { onQCCreated: s.onQCCreated, packer: packer, minRequiredWeight: s.minRequiredWeight, + votesCache: NewConcurrentIdentifierSet(), done: *atomic.NewBool(false), } } @@ -414,7 +421,9 @@ func (s *CombinedVoteProcessorV3TestSuite) TestProcess_ConcurrentCreatingQC() { defer shutdownWg.Done() startupWg.Wait() err := s.processor.Process(vote) - require.NoError(s.T(), err) + if err != nil { + require.True(s.T(), model.IsDuplicatedSignerError(err)) + } }() } @@ -606,6 +615,7 @@ func TestCombinedVoteProcessorV3_PropertyCreatingQCCorrectness(testifyT *testing onQCCreated: onQCCreated, packer: pcker, minRequiredWeight: minRequiredWeight, + votesCache: NewConcurrentIdentifierSet(), done: *atomic.NewBool(false), } @@ -706,6 +716,7 @@ func TestCombinedVoteProcessorV3_OnlyRandomBeaconSigners(testifyT *testing.T) { onQCCreated: func(qc *flow.QuorumCertificate) { /* no op */ }, packer: packer, minRequiredWeight: 70, + votesCache: NewConcurrentIdentifierSet(), done: *atomic.NewBool(false), } @@ -846,6 +857,7 @@ func TestCombinedVoteProcessorV3_PropertyCreatingQCLiveness(testifyT *testing.T) onQCCreated: onQCCreated, packer: pcker, minRequiredWeight: minRequiredWeight, + votesCache: NewConcurrentIdentifierSet(), done: *atomic.NewBool(false), } @@ -1045,3 +1057,105 @@ func TestCombinedVoteProcessorV3_BuildVerifyQC(t *testing.T) { require.True(t, qcCreated) } + +// TestCombinedVoteProcessorV3_DoubleVoting tests that CombinedVoteProcessorV3 is able to +// detect a situation where a consensus participant is sending two different votes, first vote is +// signed with the staking key only and the other one is signed with the random beacon key. +// This is a form of vote equivocation where a node sends a different vote from the one it has submitted previously. +// CombinedVoteProcessorV3 has to detect that the vote from given participant has been already processed and return a respective error. +// +// There are two conceptually different attack scenarios we are testing here: +// - Leader-based attacks: +// (a) The leader might send block proposal and equivocate by sending a different conflicting vote. +// (b) The leader might send a block proposal and (repeatedly) send the same vote again as an independent message. +// - Any byzantine node (replicas and leader alike) might send multiple individual vote messages (repeated identical votes, or equivocating with different votes). +func TestCombinedVoteProcessorV3_DoubleVoting(t *testing.T) { + proposerView := uint64(20) + + dkgData, err := bootstrapDKG.RandomBeaconKG(4, unittest.RandomBytes(32)) + require.NoError(t, err) + + // prepare a minimal consensus committee with all nodes participating in the RandomBeacon KG + allIdentities := unittest.IdentityListFixture(len(dkgData.PubKeyShares)).Sort(flow.Canonical[flow.Identity]) + dkgParticipants := make(map[flow.Identifier]flow.DKGParticipant) + for index, identity := range allIdentities { + dkgParticipants[identity.NodeID] = flow.DKGParticipant{ + Index: uint(index), + KeyShare: dkgData.PubKeyShares[index], + } + } + + leader := allIdentities[0] + + stakingPriv := unittest.StakingPrivKeyFixture() + leader.StakingPubKey = stakingPriv.PublicKey() + + leaderParticipantData := dkgParticipants[leader.NodeID] + dkgKey := encodable.RandomBeaconPrivKey{ + PrivateKey: dkgData.PrivKeyShares[leaderParticipantData.Index], + } + + me, err := local.New(leader.IdentitySkeleton, stakingPriv) + require.NoError(t, err) + + beaconSignerStore := modulemock.NewRandomBeaconKeyStore(t) + beaconSignerStore.On("ByView", proposerView).Return(dkgKey, nil) + rbSigner := verification.NewCombinedSignerV3(me, beaconSignerStore) + + stakingSignerStore := modulemock.NewRandomBeaconKeyStore(t) + stakingSignerStore.On("ByView", proposerView).Return(nil, module.ErrNoBeaconKeyForEpoch) + stakingSigner := verification.NewCombinedSignerV3(me, stakingSignerStore) + + block := helper.MakeBlock(helper.WithBlockView(proposerView), helper.WithBlockProposer(leader.NodeID)) + + // create and sign proposal + leaderVote, err := rbSigner.CreateVote(block) + require.NoError(t, err) + proposal := helper.MakeSignedProposal(helper.WithProposal(helper.MakeProposal(helper.WithBlock(block))), helper.WithSigData(leaderVote.SigData)) + + // construct another vote for this block but using staking key this time. + // While both votes are individually valid, the voter violates the protocol by publishing inconsistent votes. + leaderDifferentVote, err := stakingSigner.CreateVote(block) + require.NoError(t, err) + + // construct an equivocating vote, same view, but different block ID + otherBlock := helper.MakeBlock(helper.WithBlockView(block.View)) + leaderDifferentBlockVote, err := rbSigner.CreateVote(otherBlock) + require.NoError(t, err) + + onQCCreated := func(qc *flow.QuorumCertificate) { + require.Fail(t, "qc is not expected to be created in this test scenario") + } + + committee, err := committees.NewStaticCommittee(allIdentities, flow.ZeroID, dkgParticipants, dkgData.PubGroupKey) + require.NoError(t, err) + + baseFactory := &combinedVoteProcessorFactoryBaseV3{ + committee: committee, + onQCCreated: onQCCreated, + packer: hsig.NewConsensusSigDataPacker(committee), + } + voteProcessorFactory := &VoteProcessorFactory{ + baseFactory: baseFactory.Create, + } + voteProcessor, err := voteProcessorFactory.Create(unittest.Logger(), proposal) + require.NoError(t, err) + + t.Run("duplicated-vote", func(t *testing.T) { + // process the same vote again + err = voteProcessor.Process(leaderVote) + require.Error(t, err) + require.True(t, model.IsDuplicatedSignerError(err)) + }) + t.Run("vote for different block", func(t *testing.T) { + // process the double vote, this has to result in an error. + err = voteProcessor.Process(leaderDifferentBlockVote) + require.ErrorAs(t, err, &VoteForIncompatibleBlockError) + }) + t.Run("vote for same block with different signature scheme", func(t *testing.T) { + // process the double vote, this has to result in an error. + err = voteProcessor.Process(leaderDifferentVote) + require.Error(t, err) + require.True(t, model.IsDuplicatedSignerError(err)) + }) +} diff --git a/consensus/hotstuff/votecollector/common.go b/consensus/hotstuff/votecollector/common.go index 6ce2ebc2a3b..064497865dc 100644 --- a/consensus/hotstuff/votecollector/common.go +++ b/consensus/hotstuff/votecollector/common.go @@ -3,9 +3,11 @@ package votecollector import ( "errors" "fmt" + "sync" "github.com/onflow/flow-go/consensus/hotstuff" "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/model/flow" ) var ( @@ -31,8 +33,8 @@ func (c *NoopProcessor) Status() hotstuff.VoteCollectorStatus { return c.status // EnsureVoteForBlock verifies that the vote is for the given block. // Returns nil on success and sentinel errors: -// - model.VoteForIncompatibleViewError if the vote is from a different view than block -// - model.VoteForIncompatibleBlockError if the vote is from the same view as block +// - [VoteForIncompatibleViewError] if the vote is from a different view than the block +// - [VoteForIncompatibleBlockError] if the vote is from the same view as the block // but for a different blockID func EnsureVoteForBlock(vote *model.Vote, block *model.Block) error { if vote.View != block.View { @@ -43,3 +45,29 @@ func EnsureVoteForBlock(vote *model.Vote, block *model.Block) error { } return nil } + +// AppendOnlyIdentifierSet implements a simple set for tracking unique entries by identifier. +// Removal of set elements is not supported, we want to provide append-only guarantees. +// Concurrency safe. +type AppendOnlyIdentifierSet struct { + set map[flow.Identifier]struct{} + lock sync.Mutex +} + +// NewConcurrentIdentifierSet creates new identifier set, with strict append-only characteristics. +func NewConcurrentIdentifierSet() *AppendOnlyIdentifierSet { + return &AppendOnlyIdentifierSet{ + set: make(map[flow.Identifier]struct{}), + } +} + +// Add adds identifier to the internal set, returns true when added, otherwise returns false. +func (s *AppendOnlyIdentifierSet) Add(identifier flow.Identifier) bool { + s.lock.Lock() + defer s.lock.Unlock() + _, exists := s.set[identifier] + if !exists { + s.set[identifier] = struct{}{} + } + return !exists +} diff --git a/consensus/hotstuff/votecollector/factory.go b/consensus/hotstuff/votecollector/factory.go index 29a5ef00abe..eac77a8d26c 100644 --- a/consensus/hotstuff/votecollector/factory.go +++ b/consensus/hotstuff/votecollector/factory.go @@ -61,7 +61,7 @@ func (f *VoteProcessorFactory) Create(log zerolog.Logger, proposal *model.Signed return processor, nil } -// NewStakingVoteProcessorFactory implements hotstuff.VoteProcessorFactory for +// NewStakingVoteProcessorFactory implements [hotstuff.VoteProcessorFactory] for // members of a collector cluster. For their cluster-local hotstuff, collectors // only sign with their staking key. func NewStakingVoteProcessorFactory(committee hotstuff.DynamicCommittee, onQCCreated hotstuff.OnQCCreated) *VoteProcessorFactory { @@ -74,7 +74,7 @@ func NewStakingVoteProcessorFactory(committee hotstuff.DynamicCommittee, onQCCre } } -// NewCombinedVoteProcessorFactory implements hotstuff.VoteProcessorFactory fo +// NewCombinedVoteProcessorFactory implements [hotstuff.VoteProcessorFactory] for // participants of the Main Consensus committee. // // With their vote, members of the main consensus committee can contribute to hotstuff and @@ -96,10 +96,12 @@ func NewCombinedVoteProcessorFactory(committee hotstuff.DynamicCommittee, onQCCr /* ***************************** VerifyingVoteProcessor constructors for bootstrapping ***************************** */ -// NewBootstrapCombinedVoteProcessor directly creates a CombinedVoteProcessorV2, -// suitable for the collector's local cluster consensus. -// Intended use: only for bootstrapping. -// UNSAFE: the proposer vote for `block` is _not_ validated or included +// NewBootstrapCombinedVoteProcessor directly creates a [CombinedVoteProcessorV2], +// suitable for the Main Consensus committee. +// Intended use: only for BOOTSTRAPPING. During bootstrapping, we aggregate votes for the genesis/root block, +// which does not have a proposer signature/vote. Therefore, we can't use the regular factories, which require +// a full [model.SignedProposal] (including proposer vote) to instantiate the [hotstuff.VerifyingVoteProcessor]. +// UNSAFE: a proposer vote for `block` is _not_ included here func NewBootstrapCombinedVoteProcessor(log zerolog.Logger, committee hotstuff.DynamicCommittee, block *model.Block, onQCCreated hotstuff.OnQCCreated) (hotstuff.VerifyingVoteProcessor, error) { factory := &combinedVoteProcessorFactoryBaseV2{ committee: committee, @@ -109,10 +111,12 @@ func NewBootstrapCombinedVoteProcessor(log zerolog.Logger, committee hotstuff.Dy return factory.Create(log, block) } -// NewBootstrapStakingVoteProcessor directly creates a `StakingVoteProcessor`, +// NewBootstrapStakingVoteProcessor directly creates a [StakingVoteProcessor], // suitable for the collector's local cluster consensus. -// Intended use: only for bootstrapping. -// UNSAFE: the proposer vote for `block` is _not_ validated or included +// Intended use: only for BOOTSTRAPPING. During bootstrapping, we aggregate votes for the genesis/root block, +// which does not have a proposer signature/vote. Therefore, we can't use the regular factories, which require +// a full [model.SignedProposal] (including proposer vote) to instantiate the [hotstuff.VerifyingVoteProcessor]. +// UNSAFE: the proposer vote for `block` is _not_ included here func NewBootstrapStakingVoteProcessor(log zerolog.Logger, committee hotstuff.DynamicCommittee, block *model.Block, onQCCreated hotstuff.OnQCCreated) (hotstuff.VerifyingVoteProcessor, error) { factory := &stakingVoteProcessorFactoryBase{ committee: committee, diff --git a/consensus/hotstuff/votecollector/staking_vote_processor.go b/consensus/hotstuff/votecollector/staking_vote_processor.go index cd9814a6d96..6886da23430 100644 --- a/consensus/hotstuff/votecollector/staking_vote_processor.go +++ b/consensus/hotstuff/votecollector/staking_vote_processor.go @@ -72,7 +72,7 @@ func (f *stakingVoteProcessorFactoryBase) Create(log zerolog.Logger, block *mode /* ****************** StakingVoteProcessor Implementation ******************* */ -// StakingVoteProcessor implements the hotstuff.VerifyingVoteProcessor interface. +// StakingVoteProcessor implements the [hotstuff.VerifyingVoteProcessor] interface. // It processes hotstuff votes from a collector cluster, where participants vote // in favour of a block by proving their staking key signature. // Concurrency safe. @@ -86,6 +86,8 @@ type StakingVoteProcessor struct { allParticipants flow.IdentityList } +var _ hotstuff.VerifyingVoteProcessor = (*StakingVoteProcessor)(nil) + // Block returns block that is part of proposal that we are processing votes for. func (p *StakingVoteProcessor) Block() *model.Block { return p.block @@ -101,10 +103,16 @@ func (p *StakingVoteProcessor) Status() hotstuff.VoteCollectorStatus { // Supports processing of both staking and threshold signatures. Design of this // function is event driven, as soon as we collect enough weight to create a QC // we will immediately do this and submit it via callback for further processing. +// +// IMPORTANT: The VerifyingVoteProcessor provides the final defense against any vote-equivocation attacks +// for its specific block. These attacks typically aim at multiple votes from the same node being counted +// towards the supermajority threshold. This must cover attacks by the leader concurrently utilizing +// stand-alone votes and votes embedded into the proposal. +// // Expected error returns during normal operations: -// * VoteForIncompatibleBlockError - submitted vote for incompatible block -// * VoteForIncompatibleViewError - submitted vote for incompatible view -// * model.InvalidVoteError - submitted vote with invalid signature +// * [VoteForIncompatibleBlockError] if vote is for incompatible block +// * [VoteForIncompatibleViewError] if vote is for incompatible view +// * [model.InvalidVoteError] if vote has invalid signature // All other errors should be treated as exceptions. func (p *StakingVoteProcessor) Process(vote *model.Vote) error { err := EnsureVoteForBlock(vote, p.block) diff --git a/consensus/hotstuff/votecollector/statemachine.go b/consensus/hotstuff/votecollector/statemachine.go index 60558cf2aaf..d909af108c0 100644 --- a/consensus/hotstuff/votecollector/statemachine.go +++ b/consensus/hotstuff/votecollector/statemachine.go @@ -3,7 +3,6 @@ package votecollector import ( "errors" "fmt" - "sync" "github.com/rs/zerolog" "go.uber.org/atomic" @@ -11,23 +10,52 @@ import ( "github.com/onflow/flow-go/consensus/hotstuff" "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/consensus/hotstuff/voteaggregator" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/utils/logging" ) var ( ErrDifferentCollectorState = errors.New("different state") ) -// VerifyingVoteProcessorFactory generates hotstuff.VerifyingVoteCollector instances +// VerifyingVoteProcessorFactory generates [hotstuff.VerifyingVoteProcessor] instances type VerifyingVoteProcessorFactory = func(log zerolog.Logger, proposal *model.SignedProposal) (hotstuff.VerifyingVoteProcessor, error) -// VoteCollector implements a state machine for transition between different states of vote collector +// VoteCollector implements a state machine for transition between different states of vote processor. +// It ingests *all* votes for a specified view and consolidates the handling of all byzantine edge cases +// related to voting (including byzantine leaders publishing conflicting proposals and/or votes). +// On the happy path, the VoteCollector generates a QC when enough votes have been ingested. +// We internally delegate the vote-format specific processing to the VoteProcessor. type VoteCollector struct { - sync.Mutex log zerolog.Logger workers hotstuff.Workers notifier hotstuff.VoteAggregationConsumer createVerifyingProcessor VerifyingVoteProcessorFactory + // Byzantine nodes might mount the following attacks on the vote-processing logic: + // 1. The leader might send block proposal and equivocate by sending a different conflicting vote as an independent message. + // 2. The leader might send a block proposal and (repeatedly) send the same vote again as an independent message. + // 3. Any byzantine replica might send multiple individual vote messages (repeated identical votes, or equivocating with different votes). + // These are resource exhaustion attacks (if frequent), but can also be attempts by byzantine nodes to have their votes repeatedly + // counted (producing an invalid QC if repeatedly counted and thereby disrupting the certification and finalization process). + // + // Replicas that are not the leader might also attempt to submit proposals, but these are already caught earlier by the compliance layer. + // Hence, attacks 1. and 2. are only available to the leader, because these attacks specifically utilize the fact that the leader signs + // their proposal, with the signature authenticating the proposal as well as serving as the leader's vote. Attack 3. can be mounted by + // replicas and the leader alike. + // + // ATTENTION: Detecting vote equivocation is a collaborative effort of the VoteCollector's `votesCache` and the `VoteProcessor`. + // * Stand-alone votes always hit the `votesCache`, which checks the vote against all previously cached votes for + // equivocation (protocol violation) or exact duplicates (non-slashable, potential spamming). This mitigates attack 3. + // * In the current implementation, the `votesCache` does not catch leader attacks 1. and 2., which exploit the fact that stand-alone + // votes and votes embedded in proposals are processed concurrently through different code paths. We emphasize that attack vectors + // 1. and 2. are only available to a byzantine leader as long as the leader has not (yet) equivocated for the current view. Once + // the VoteCollector notices that the _leader_ equivocates, it immediately stops accepting proposals for the view, thereby closing + // attack vectors 1. and 2. Hence, it is sufficient for the [VerifyingVoteProcessor] to catch _all_ equivocation attacks, + // including attacks 1. and 2. + // + // The VoteProcessor provides the final defense against any double-counting attacks, because this attack vector is only open as long + // as we are ingesting votes with the goal of producing a QC, in other words as along as we are still following the happy path. votesCache VotesCache votesProcessor atomic.Value } @@ -81,49 +109,71 @@ func NewStateMachine( return sm } -// AddVote adds a vote to current vote collector -// All expected errors are handled via callbacks to notifier. -// Under normal execution only exceptions are propagated to caller. +// AddVote adds a vote to the vote collector. The vote must be for the `VoteCollector`'s view (otherwise, +// an exception is returned). When enough votes have been added to produce a QC, the QC will be created +// asynchronously, and passed to EventLoop through a callback. +// All byzantine edge cases are handled internally via callbacks to notifier. +// Under normal execution, only exceptions are propagated to caller. func (m *VoteCollector) AddVote(vote *model.Vote) error { - // Cache vote + // Cache vote; only the first vote from any specific signer will pass this step + unique, err := m.ensureVoteUnique(vote) + if err != nil { + return err + } + if !unique { + return nil + } + + err = m.processVote(vote) // handles all byzantine edge cases internally + if err != nil { + return fmt.Errorf("internal error processing vote %v for block %v: %w", + vote.ID(), vote.BlockID, err) + } + return nil +} + +// ensureVoteUnique caches the vote in the votesCache (or rejects it) - implemented as a concurrency safe, atomic operation. +// This function is responsible for reporting byzantine behavior when byzantine leader or replica has sent an equivocating vote. +// All votes that are different from the original one(by same signer) are reported as equivocation attempts. +// +// ATTENTION: In order to guarantee that all equivocation attempts will be caught, this function needs to be +// called consistently before processing individual votes _and_ block proposals. +// +// Possible return values: +// - (true, nil) if vote is first from given signer ID +// - (false, nil) if there is another vote in the cache that was previously added by given signer ID +// - (false, error) if exception during processing. +// +// No errors are expected during normal operations. +func (m *VoteCollector) ensureVoteUnique(vote *model.Vote) (bool, error) { err := m.votesCache.AddVote(vote) if err != nil { if errors.Is(err, RepeatedVoteErr) { - return nil + return false, nil } if doubleVoteErr, isDoubleVoteErr := model.AsDoubleVoteError(err); isDoubleVoteErr { m.notifier.OnDoubleVotingDetected(doubleVoteErr.FirstVote, doubleVoteErr.ConflictingVote) - return nil + return false, nil } - return fmt.Errorf("internal error adding vote %v to cache for block %v: %w", + return false, fmt.Errorf("internal error adding vote %v to cache for block %v: %w", vote.ID(), vote.BlockID, err) } - - err = m.processVote(vote) - if err != nil { - if errors.Is(err, VoteForIncompatibleBlockError) { - // For honest nodes, there should be only a single proposal per view and all votes should - // be for this proposal. However, byzantine nodes might deviate from this happy path: - // * A malicious leader might create multiple (individually valid) conflicting proposals for the - // same view. Honest replicas will send correct votes for whatever proposal they see first. - // We only accept the first valid block and reject any other conflicting blocks that show up later. - // * Alternatively, malicious replicas might send votes with the expected view, but for blocks that - // don't exist. - // In either case, receiving votes for the same view but for different block IDs is a symptom - // of malicious consensus participants. Hence, we log it here as a warning: - m.log.Warn(). - Err(err). - Msg("received vote for incompatible block") - - return nil - } - return fmt.Errorf("internal error processing vote %v for block %v: %w", - vote.ID(), vote.BlockID, err) - } - return nil + return true, nil } -// processVote uses compare-and-repeat pattern to process vote with underlying vote processor +// processVote uses compare-and-repeat pattern to process vote with underlying vote processor. +// This compare-and-repeat pattern is crucial to ensure all valid votes make it to the +// [hotstuff.VerifyingVoteProcessor], i.e. liveness, despite the vote processor possibly being +// swapped concurrently when the block is arriving (see implementation for detailed reasoning). +// +// PREREQUISITE: This method should only be called for votes that were successfully added to +// `votesCache` (identical duplicates are ok). Therefore, we don't have to deal here with +// equivocation (same replica voting for different blocks) or inconsistent votes (replica +// emitting votes with inconsistent signatures for the same block), because such votes were +// already filtered out by the cache. +// +// All byzantine edge cases are handled internally via callbacks to notifier. Under normal +// execution, only exceptions are propagated to caller. func (m *VoteCollector) processVote(vote *model.Vote) error { for { processor := m.atomicLoadProcessor() @@ -131,19 +181,79 @@ func (m *VoteCollector) processVote(vote *model.Vote) error { err := processor.Process(vote) if err != nil { if invalidVoteErr, ok := model.AsInvalidVoteError(err); ok { + // vote is invalid, which we only notice once we try to add it to the [VerifyingVoteProcessor] m.notifier.OnInvalidVoteDetected(*invalidVoteErr) return nil } - // ATTENTION: due to how our logic is designed this situation is only possible - // where we receive the same vote twice, this is not a case of double voting. - // This scenario is possible if leader submits his vote additionally to the vote in proposal. if model.IsDuplicatedSignerError(err) { + // This error is returned for repetitions of exactly the same vote. Such repetitions can occur (as race + // condition) in our concurrent implementation. When the block proposal for the view arrives: + // (A1) `votesProcessor` transitions from [VoteCollectorStatusCaching] to [VoteCollectorStatusVerifying] + // (A2) the cached votes are fed into the [VerifyingVoteProcessor] + // However, to increase concurrency, step (A1) and (A2) are _not_ atomically happening together. + // Therefore, the following event (B) might happen _in between_: + // (B) A newly-arriving vote V is first cached and then processed by the [VerifyingVoteProcessor]. + // In this scenario, vote V is already included in the [VerifyingVoteProcessor]. Nevertheless, step (A2) + // will attempt to add V again to the [VerifyingVoteProcessor], because the vote is in the cache. m.log.Debug().Msgf("duplicated signer %x", vote.SignerID) return nil } - return err + if errors.Is(err, VoteForIncompatibleBlockError) { + // For honest nodes, there should be only a single proposal per view and all votes should + // be for this proposal. However, byzantine nodes might deviate from this happy path: + // * A malicious leader might create multiple (individually valid) conflicting proposals for the + // same view. Honest replicas will send correct votes for whatever proposal they see first. + // We only accept the first valid block and reject any other conflicting blocks that show up later. + // * Alternatively, malicious replicas might send votes with the expected view, but for blocks that + // don't exist. + // In either case, receiving votes for the same view but for different block IDs is a symptom + // of malicious consensus participants. Hence, we log it here as a warning: + m.log.Warn(). + Str(logging.KeySuspicious, "true"). + Err(err). + Msg("received vote for incompatible block") + + return nil + } + return irrecoverable.NewException(err) } + // ATTENTION: repeating the processing if the processor changed concurrently is REQUIRED for LIVENESS on the + // happy path (honest proposer and a supermajority of votes arriving in time). + // Liveness Proof for the happy path (utilizing the Go Memory Model https://go.dev/ref/mem, 'happens before' relation): + // * We only care about the Vote Processor's state transition `CachingVotes` → `VerifyingVotes`, because all other state transitions + // are leaving the happy path. The state transition is effectively an atomic write to the variable `votesProcessor` (see method + // `VoteCollector.ProcessBlock` below for details). + // * Case (a): `currentState` = [VoteCollectorStatusVerifying] = `m.Status()` + // Then, the `vote` is added directly to the [VerifyingVoteProcessor]. Informally, the state transition has happened before we retrieved + // the Vote Processor via `m.atomicLoadProcessor()` above. + // * Case (b): `currentState` = [VoteCollectorStatusCaching] = `m.Status()` + // We note the following 'happens before' relations (i) and (ii), which are guaranteed by sequential execution _within_ a goroutine: + // In goroutine A1 performing the state transition, (i) we write to `votesProcessor` before we read all cached votes from `votesCache` + // (acquiring `votesCache`s lock). In goroutine A2, (ii) we have added the vote to the `votesCache` (also acquiring `votesCache`s lock) + // before we read `votesProcessor`s status below and confirm its status still being [VoteCollectorStatusCaching]. + // We prove by contradiction that it is impossible for thread A1 to read the cached votes before thread A2 adds its vote to `votesCache` + // (if that was possible, the verifying vote processor would not see the vote). By the time A1 reads the `votesCache`, it has already + // completed updating the status of the `votesProcessor` to [VoteCollectorStatusVerifying] (per (i)). We assumed that A1 reading the + // `votesCache` happens before A2 writing to it (`votesCache` uses locks, which establish a happens before relation). With (ii), we infer + // that the `votesProcessor` reaching status [VoteCollectorStatusVerifying] happens before A2 reading the `votesProcessor` status below. + // Therefore, A2 would read the status [VoteCollectorStatusVerifying], which contradicts our assumption. + // Hence, we conclude that thread A2 always caches its vote before A1 reads the `votesCache`. As A1 is the thread that performs the + // state transition, it will include A1's vote when feeding the cached votes into the [VerifyingVoteProcessor]. + // Informally, the state transition will happen _after_ we cached the vote. + // * Case (c): `currentState` = [VoteCollectorStatusCaching] while `m.Status()` = [VoteCollectorStatusVerifying]. + // In this scenario, the vote is being fed into the [NoopProcessor] first, before we realize that the state has changed. However, + // since the status has changed, the check below will trigger a repeat of the processing, which will then enter case (a) + // (or leave the happy path by transitioning to [VoteCollectorStatusInvalid], implying we are dealing with a byzantine proposer, in which + // case we may drop all votes anyway). + // We have shown that all votes will reach the [VerifyingVoteProcessor] on the happy path. + // + // CAUTION: In the proof, we utilized that reading the `votesCache` happens before writing to it (case b). It is important to emphasize that + // only locks are agnostic to the performed operation being a read or a write. In contrast, atomic variables only establish a 'happens before' + // relation when a preceding write is observed by a subsequent read (consult go memory model https://go.dev/ref/mem, specifically the + //'synchronized before', and its generalized "happens before" relation). However, in our case, we first read and then write - an order of + // operations which does not induce any synchronization guarantees according to Go Memory Model. Hence, the `votesCache` utilizing locks is + // critical for the correctness of the `VoteCollector`. if currentState != m.Status() { continue } @@ -163,7 +273,7 @@ func (m *VoteCollector) View() uint64 { return m.votesCache.View() } -// ProcessBlock performs validation of block signature and processes block with respected collector. +// ProcessBlock validates the block signature, and adds it as the proposer's vote. // In case we have received double proposal, we will stop attempting to build a QC for this view, // because we don't want to build on any proposal from an equivocating primary. Note: slashing challenges // for proposal equivocation are triggered by hotstuff.Forks, so we don't have to do anything else here. @@ -172,10 +282,26 @@ func (m *VoteCollector) View() uint64 { // the state transition is only executed if VoteCollector's internal state is // equal to `expectedValue`. The implementation only allows the transitions // -// CachingVotes -> VerifyingVotes -// CachingVotes -> Invalid -// VerifyingVotes -> Invalid +// CachingVotes → VerifyingVotes +// CachingVotes → Invalid +// VerifyingVotes → Invalid +// +// No errors are expected during normal operation (Byzantine edge cases handled via notifications internally). func (m *VoteCollector) ProcessBlock(proposal *model.SignedProposal) error { + proposerVote, err := proposal.ProposerVote() + if err != nil { + return model.NewInvalidProposalErrorf(proposal, "invalid proposer vote") + } + // We only abort here in case of an exception. No matter whether the vote is the first from the voter, an exact + // duplicate or an equivocation, we still proceed as long as the vote is individually valid. This is fine, because + // the VoteProcessor is robust against all byzantine edge cases. The VoteCollector's responsibility is to detect + // equivocation attempts and report them via the notifier, which is done inside `ensureVoteUnique`. + // We could additionally abort the vote collection here in case of equivocation, but this is not necessary for + // safety, as long as the offending proposer is eventually slashed, which only requires notifying about the equivocation. + _, err = m.ensureVoteUnique(proposerVote) + if err != nil { + return err + } if proposal.Block.View != m.View() { return fmt.Errorf("this VoteCollector requires a proposal for view %d but received block %v with view %d", @@ -238,7 +364,7 @@ func (m *VoteCollector) RegisterVoteConsumer(consumer hotstuff.VoteConsumer) { m.votesCache.RegisterVoteConsumer(consumer) } -// caching2Verifying ensures that the VoteProcessor is currently in state `VoteCollectorStatusCaching` +// caching2Verifying ensures that the VoteProcessor is currently in state [VoteCollectorStatusCaching] // and replaces it by a newly-created VerifyingVoteProcessor. // Error returns: // * ErrDifferentCollectorState if the VoteCollector's state is _not_ `CachingVotes` @@ -251,27 +377,66 @@ func (m *VoteCollector) caching2Verifying(proposal *model.SignedProposal) error } newProcWrapper := &atomicValueWrapper{processor: newProc} - m.Lock() - defer m.Unlock() - proc := m.atomicLoadProcessor() - if proc.Status() != hotstuff.VoteCollectorStatusCaching { - return fmt.Errorf("processors's current state is %s: %w", proc.Status().String(), ErrDifferentCollectorState) + // We now have an optimistically-constructed `newProcWrapper` that represents the desired new state (happy path). We must ensure + // that writing the `newProcWrapper` to `m.votesProcessor` happens ATOMICALLY if and only if the current state is `CachingVotes`. + // The "Compare-And-Swap Loop" (CAS LOOP) is an efficient pattern to implement this logic: + // (i) We first retrieve the current state and check whether it is `CachingVotes`. + // (ii) If so, we attempt to compare-and-swap the current with the new state. + // Note that (i) and (ii) are separate operations. However, the CAS in (ii) ensures that the write only happens if the current state + // is still the same as what we observed in (i). If another thread changed the state in between (i) and (ii), we have worked with + // an outdated view of the current state, and should repeat the attempt to update the state (hence the "loop" in CAS LOOP). + // + // On our specific application here, putting (i) and (ii) in a loop is not necessary for the following reason: The state transition + // to `VoteCollectorStatusVerifying` is possible only if the current state is `VoteCollectorStatusCaching`. Once the state changed + // away from `VoteCollectorStatusCaching` it can never return to this state. I.e. if condition (i) failed once, it can never be + // satisfied later. Step (ii) failing implies that condition (i) was previously true, but no longer holds. + // Since we are storing a pointer in the atomic.Value the value compared will be the reference to the object. + currentProcWrapper := m.votesProcessor.Load().(*atomicValueWrapper) + currentState := currentProcWrapper.processor.Status() // must use same object here as in CAS below (_not_ a fresh load from `m.Status()`) + if currentState != hotstuff.VoteCollectorStatusCaching { + return fmt.Errorf("processors's current state is %s: %w", currentState.String(), ErrDifferentCollectorState) + } + stateUpdateSuccessful := m.votesProcessor.CompareAndSwap(currentProcWrapper, newProcWrapper) + if !stateUpdateSuccessful { + return fmt.Errorf("CAS failed in between, processors's current state is %s: %w", m.Status(), ErrDifferentCollectorState) } - m.votesProcessor.Store(newProcWrapper) + return nil } +// terminateVoteProcessing atomically transitions the VoteCollector into state +// `VoteCollectorStatusInvalid`. if it wasn't already in this state. func (m *VoteCollector) terminateVoteProcessing() { - if m.Status() == hotstuff.VoteCollectorStatusInvalid { + currentProcWrapper := m.votesProcessor.Load().(*atomicValueWrapper) + if currentProcWrapper.processor.Status() == hotstuff.VoteCollectorStatusInvalid { return } + newProcWrapper := &atomicValueWrapper{ processor: NewNoopCollector(hotstuff.VoteCollectorStatusInvalid), } - m.Lock() - defer m.Unlock() - m.votesProcessor.Store(newProcWrapper) + // We now have an optimistically-constructed `newProcWrapper` that represents the desired new state (happy path). We must ensure + // that writing the `newProcWrapper` to `m.votesProcessor` happens ATOMICALLY if and only if the current state is not + // `VoteCollectorStatusInvalid`. The "Compare-And-Swap Loop" (CAS LOOP) is an efficient pattern to implement this: + // (i) We first retrieved the current state (above) and checked whether it is different from `VoteCollectorStatusInvalid`. + // (ii) If so, we attempt to compare-and-swap the current with the new state. + // Note that (i) and (ii) are separate operations. However, the CAS in (ii) ensures that the write only happens if the current state + // is still the same as what we observed in (i). If another thread changed the state in between (i) and (ii), we have worked with + // an outdated view of the current state, and should repeat the attempt to update the state (hence the "loop" in CAS LOOP). + // Since we are storing a pointer in the atomic.Value the value compared will be the reference to the object. + for { + stateUpdateSuccessful := m.votesProcessor.CompareAndSwap(currentProcWrapper, newProcWrapper) + if stateUpdateSuccessful { + return + } + // the `currentProcWrapper` we worked with was stale: + // reload, check if invalid target state has already been reached, and repeat if not + currentProcWrapper = m.votesProcessor.Load().(*atomicValueWrapper) + if currentProcWrapper.processor.Status() == hotstuff.VoteCollectorStatusInvalid { + return + } + } } // processCachedVotes feeds all cached votes into the VoteProcessor diff --git a/consensus/hotstuff/votecollector/statemachine_test.go b/consensus/hotstuff/votecollector/statemachine_test.go index 1f6409c3136..ce0933acd73 100644 --- a/consensus/hotstuff/votecollector/statemachine_test.go +++ b/consensus/hotstuff/votecollector/statemachine_test.go @@ -43,7 +43,7 @@ func (s *StateMachineTestSuite) TearDownTest() { // Without this line we are risking running into weird situations where one test has finished but there are active workers // that are executing some work on the shared pool. Need to ensure that all pending work has been executed before // starting next test. - s.workerPool.StopWait() + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) } func (s *StateMachineTestSuite) SetupTest() { @@ -64,12 +64,20 @@ func (s *StateMachineTestSuite) SetupTest() { // prepareMockedProcessor prepares a mocked processor and stores it in map, later it will be used // to mock behavior of verifying vote processor. +// Additionally, it setups mocks on the processor assuming the proposer vote will be passed into the processing pipeline. func (s *StateMachineTestSuite) prepareMockedProcessor(proposal *model.SignedProposal) *mocks.VerifyingVoteProcessor { - processor := &mocks.VerifyingVoteProcessor{} + processor := mocks.NewVerifyingVoteProcessor(s.T()) processor.On("Block").Return(func() *model.Block { return proposal.Block }).Maybe() processor.On("Status").Return(hotstuff.VoteCollectorStatusVerifying) + + proposerVote, err := proposal.ProposerVote() + require.NoError(s.T(), err) + processor.On("Process", proposerVote).Run(func(_ mock.Arguments) { + s.notifier.On("OnVoteProcessed", proposerVote).Once() + }).Return(nil).Maybe() + s.mockedProcessors[proposal.Block.BlockID] = processor return processor } @@ -152,7 +160,8 @@ func (s *StateMachineTestSuite) TestAddVote_VerifyingState() { vote := unittest.VoteForBlockFixture(block, unittest.WithVoteView(s.view)) processor.On("Process", vote).Return(model.NewInvalidVoteErrorf(vote, "")).Once() s.notifier.On("OnInvalidVoteDetected", mock.Anything).Run(func(args mock.Arguments) { - invalidVoteErr := args.Get(0).(model.InvalidVoteError) + invalidVoteErr, ok := model.AsInvalidVoteError(args.Get(0).(error)) + require.True(s.T(), ok) require.Equal(s.T(), vote, invalidVoteErr.Vote) }).Return(nil).Once() err := s.collector.AddVote(vote) @@ -194,7 +203,7 @@ func (s *StateMachineTestSuite) TestAddVote_VerifyingState() { vote := unittest.VoteForBlockFixture(block, unittest.WithVoteView(s.view)) processor.On("Process", vote).Return(unexpectedError).Once() err := s.collector.AddVote(vote) - require.ErrorIs(t, err, unexpectedError) + require.ErrorAs(t, err, &unexpectedError) }) } @@ -217,11 +226,202 @@ func (s *StateMachineTestSuite) TestProcessBlock_ProcessingOfCachedVotes() { err := s.collector.ProcessBlock(proposal) require.NoError(s.T(), err) - time.Sleep(100 * time.Millisecond) - + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) processor.AssertExpectations(s.T()) } +/* ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + * CONTEXT: Byzantine Leader might mount the following attacks: + * 1. Vote-equivocation attack: send block proposal and equivocate by sending a different conflicting vote. + * 2. Spamming attack: send a block proposal and (repeatedly) send the same vote again as an independent message. + * 3. Leader might send multiple individual vote messages (repeated identical votes, or equivocating with different votes) + * Attacks 1. and 2. are only available to the leader, because these attacks exploit the fact that stand-alone votes and + * proposals are processed through different code paths: while stand-alone votes always hit the cache in the VoteCollector, + * the vote embedded into the proposal is processed with priority (potentially concurrently to other incoming stand-alone votes). + * Attack 3. can be mounted also by replicas + * In following section of tests, we verify correct handling of those scenarios. + * ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */ + +// TestProcessBlock_ByzantineLeaderEquivocation_ProposalBeforeVote tests a specific attack scenario mounted by byzantine leader: +// Attack 1. send block proposal and equivocate by sending a different conflicting vote. We test both orders of arrival: +// Case (1.a): proposal arriving first, stand-alone vote arriving later. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineLeaderEquivocation_ProposalBeforeVote() { + proposal := makeSignedProposalWithView(s.view) + block := proposal.Block + proposalVote, err := proposal.ProposerVote() + require.NoError(s.T(), err) + _ = s.prepareMockedProcessor(proposal) + + err = s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + equivocatingVote := unittest.VoteForBlockFixture(block, unittest.WithVoteSignerID(proposalVote.SignerID)) + s.notifier.On("OnDoubleVotingDetected", proposalVote, equivocatingVote).Once() + err = s.collector.AddVote(equivocatingVote) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + +// TestProcessBlock_ByzantineLeaderEquivocation_ProposalAfterVote tests a specific attack scenario mounted by byzantine leader: +// Attack 1. send block proposal and equivocate by sending a different conflicting vote. We test both orders of arrival: +// Case (1.b): stand-alone vote arriving first, proposal arriving second. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineLeaderEquivocation_ProposalAfterVote() { + proposal := makeSignedProposalWithView(s.view) + block := proposal.Block + // in this case proposer vote comes in second and acts as equivocated vote + equivocatingVote, err := proposal.ProposerVote() + require.NoError(s.T(), err) + processor := s.prepareMockedProcessor(proposal) + + firstVote := unittest.VoteForBlockFixture(block, unittest.WithVoteSignerID(equivocatingVote.SignerID)) + s.notifier.On("OnVoteProcessed", firstVote).Twice() + err = s.collector.AddVote(firstVote) + require.NoError(s.T(), err) + + processor.On("Process", firstVote).Return(nil).Once() + s.notifier.On("OnDoubleVotingDetected", firstVote, equivocatingVote).Once() + err = s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + +// TestProcessBlock_ByzantineLeaderSpamming_ProposalBeforeVote tests a specific attack scenario mounted by byzantine leader: +// Attack 2. send block proposal and try to spam with the same vote. We test both orders of arrival: +// Case (2.a): proposal arriving first, stand-alone vote arriving later. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineLeaderSpamming_ProposalBeforeVote() { + proposal := makeSignedProposalWithView(s.view) + _ = s.prepareMockedProcessor(proposal) + proposalVote, err := proposal.ProposerVote() + require.NoError(s.T(), err) + + err = s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + err = s.collector.AddVote(proposalVote) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + +// TestProcessBlock_ByzantineLeaderSpamming_ProposalAfterVote tests a specific attack scenario mounted by byzantine leader: +// Attack 2. send block proposal and try to spam with the same vote. We test both orders of arrival: +// Case (2.b): stand-alone vote arriving first, proposal arriving second. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineLeaderSpamming_ProposalAfterVote() { + proposal := makeSignedProposalWithView(s.view) + _ = s.prepareMockedProcessor(proposal) + proposalVote, err := proposal.ProposerVote() + require.NoError(s.T(), err) + + s.notifier.On("OnVoteProcessed", proposalVote).Once() + err = s.collector.AddVote(proposalVote) + require.NoError(s.T(), err) + + err = s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + +// TestProcessBlock_ByzantineReplicaEquivocation_BeforeProposal tests a specific attack scenario mounted by byzantine replica: +// Attack 3. send multiple votes trying to spam the leader or equivocate. We test both orders of arrival: +// Case (3.a): equivocating votes arrive before receiving a proposal. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineReplicaEquivocation_BeforeProposal() { + proposal := makeSignedProposalWithView(s.view) + block := proposal.Block + processor := s.prepareMockedProcessor(proposal) + + vote := unittest.VoteForBlockFixture(block) + equivocatingVote := unittest.VoteForBlockFixture(block, unittest.WithVoteSignerID(vote.SignerID)) + + processor.On("Process", vote).Return(nil).Once() + s.notifier.On("OnVoteProcessed", vote).Twice() + err := s.collector.AddVote(vote) + require.NoError(s.T(), err) + + s.notifier.On("OnDoubleVotingDetected", vote, equivocatingVote).Once() + err = s.collector.AddVote(equivocatingVote) + require.NoError(s.T(), err) + + err = s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + +// TestProcessBlock_ByzantineReplicaEquivocation_AfterProposal tests a specific attack scenario mounted by byzantine replica: +// Attack 3. send multiple votes trying to spam the leader or equivocate. We test both orders of arrival: +// Case (3.b): equivocating votes arrive after receiving a proposal. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineReplicaEquivocation_AfterProposal() { + proposal := makeSignedProposalWithView(s.view) + block := proposal.Block + processor := s.prepareMockedProcessor(proposal) + + vote := unittest.VoteForBlockFixture(block) + equivocatingVote := unittest.VoteForBlockFixture(block, unittest.WithVoteSignerID(vote.SignerID)) + err := s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + processor.On("Process", vote).Return(nil).Once() + s.notifier.On("OnVoteProcessed", vote).Once() + err = s.collector.AddVote(vote) + require.NoError(s.T(), err) + + s.notifier.On("OnDoubleVotingDetected", vote, equivocatingVote).Once() + err = s.collector.AddVote(equivocatingVote) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + +// TestProcessBlock_ByzantineReplicaEquivocation_BeforeProposal tests a specific attack scenario mounted by byzantine replica: +// Attack 3. send multiple votes trying to spam the leader or equivocate. We test both orders of arrival: +// Case (3.c): spamming: identical votes arrive before receiving a proposal. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineReplicaSpamming_BeforeProposal() { + proposal := makeSignedProposalWithView(s.view) + block := proposal.Block + processor := s.prepareMockedProcessor(proposal) + + vote := unittest.VoteForBlockFixture(block) + + processor.On("Process", vote).Return(nil).Once() + s.notifier.On("OnVoteProcessed", vote).Twice() + err := s.collector.AddVote(vote) + require.NoError(s.T(), err) + + err = s.collector.AddVote(vote) + require.NoError(s.T(), err) + + err = s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + +// TestProcessBlock_ByzantineReplicaEquivocation_BeforeProposal tests a specific attack scenario mounted by byzantine replica: +// Attack 3. send multiple votes trying to spam the leader or equivocate. We test both orders of arrival: +// Case (3.d): spamming: identical votes arrive after receiving a proposal. +func (s *StateMachineTestSuite) TestProcessBlock_ByzantineReplicaSpamming_AfterProposal() { + proposal := makeSignedProposalWithView(s.view) + block := proposal.Block + processor := s.prepareMockedProcessor(proposal) + + vote := unittest.VoteForBlockFixture(block) + err := s.collector.ProcessBlock(proposal) + require.NoError(s.T(), err) + + processor.On("Process", vote).Return(nil).Once() + s.notifier.On("OnVoteProcessed", vote).Once() + err = s.collector.AddVote(vote) + require.NoError(s.T(), err) + + err = s.collector.AddVote(vote) + require.NoError(s.T(), err) + + unittest.AssertReturnsBefore(s.T(), s.workerPool.StopWait, time.Second) +} + // Test_VoteProcessorErrorPropagation verifies that unexpected errors from the `VoteProcessor` // are propagated up the call stack (potentially wrapped), but are not replaced. func (s *StateMachineTestSuite) Test_VoteProcessorErrorPropagation() { @@ -229,15 +429,14 @@ func (s *StateMachineTestSuite) Test_VoteProcessorErrorPropagation() { block := proposal.Block processor := s.prepareMockedProcessor(proposal) - err := s.collector.ProcessBlock(helper.MakeSignedProposal( - helper.WithProposal(helper.MakeProposal(helper.WithBlock(block))))) + err := s.collector.ProcessBlock(proposal) require.NoError(s.T(), err) unexpectedError := errors.New("some unexpected error") vote := unittest.VoteForBlockFixture(block, unittest.WithVoteView(s.view)) processor.On("Process", vote).Return(unexpectedError).Once() err = s.collector.AddVote(vote) - require.ErrorIs(s.T(), err, unexpectedError) + require.ErrorAs(s.T(), err, &unexpectedError) } // RegisterVoteConsumer verifies that after registering vote consumer we are receiving all new and past votes diff --git a/consensus/hotstuff/votecollector/vote_cache.go b/consensus/hotstuff/votecollector/vote_cache.go index 98d06ee7197..05e161fab18 100644 --- a/consensus/hotstuff/votecollector/vote_cache.go +++ b/consensus/hotstuff/votecollector/vote_cache.go @@ -2,6 +2,7 @@ package votecollector import ( "errors" + "fmt" "sync" "github.com/onflow/flow-go/consensus/hotstuff" @@ -10,13 +11,13 @@ import ( ) var ( - // RepeatedVoteErr is emitted, when we receive a vote for the same block + // RepeatedVoteErr is emitted, when we receive the _same_ vote for the same block // from the same voter multiple times. This error does _not_ indicate // equivocation. RepeatedVoteErr = errors.New("duplicated vote") ) -// voteContainer container stores the vote and in index representing +// voteContainer container stores the vote and an index representing // the order in which the votes were received type voteContainer struct { *model.Vote @@ -26,13 +27,27 @@ type voteContainer struct { // VotesCache maintains a _concurrency safe_ cache of votes for one particular // view. The cache memorizes the order in which the votes were received. Votes // are de-duplicated based on the following rules: -// - Vor each voter (i.e. SignerID), we store the _first_ vote v0. -// - For any subsequent vote v, we check whether v.BlockID == v0.BlockID. -// If this is the case, we consider the vote a duplicate and drop it. -// If v and v0 have different BlockIDs, the voter is equivocating and -// we return a model.DoubleVoteError +// +// 1. The cache only ingests votes for the pre-configured view. Votes +// for other views are rejected with an [VoteForIncompatibleViewError]. +// +// 2. For each voter (i.e. SignerID), we store the _first_ vote `v0`. For any subsequent +// vote `v1` from the _same_ replica, we check: +// 2a. v1.ID() == v0.ID(): +// Votes with the same ID are identical. No protocol violation. We reject `v1` with a [RepeatedVoteErr] +// 2b. v1.ID() ≠ v0.ID(): +// The consensus replica has emitted inconsistent votes within the same view, which +// is generally a protocol violation. This is a sign of vote equivocation which happen if +// replica is voting for different blocks at the same view or using different signing information. +// We reject `v1` with a [model.DoubleVoteError]. type VotesCache struct { - lock sync.RWMutex + // CAUTION: In the VoteCollector's liveness proof, we utilized that reading the `VotesCache` happens before writing to it. It is important to + // emphasize that only locks are agnostic to the performed operation being a read or a write. In contrast, atomic variables only establish a + // 'synchronized before' relation when a preceding write is observed by a subsequent read. However, the VoteProcessor first reads and then + // writes. For atomic variables, this order of operations does not induce any synchronization guarantees according to Go Memory Model + // ( https://go.dev/ref/mem ). Hence, the VotesCache utilizing locks is critical for the correctness of the `VoteCollector`. + lock sync.RWMutex + view uint64 votes map[flow.Identifier]voteContainer // signerID -> first vote voteConsumers []hotstuff.VoteConsumer @@ -48,19 +63,30 @@ func NewVotesCache(view uint64) *VotesCache { func (vc *VotesCache) View() uint64 { return vc.view } -// AddVote stores a vote in the cache. The following errors are expected during -// normal operations: -// - nil: if the vote was successfully added -// - model.DoubleVoteError is returned if the voter is equivocating -// (i.e. voting in the same view for different blocks). -// - RepeatedVoteErr is returned when adding a vote for the same block from -// the same voter multiple times. -// - IncompatibleViewErr is returned if the vote is for a different view. -// -// When AddVote returns an error, the vote is _not_ stored. +// AddVote stores a vote in the cache. The method returns `nil`, if the vote was +// successfully stored. When AddVote returns an error, the vote is _not_ stored. +// Expected error returns during normal operations: +// - [VoteForIncompatibleViewError] is returned if the vote is for a different view. +// - [model.DoubleVoteError] indicates that the voter has emitted inconsistent +// votes within the same view. We consider two votes as inconsistent, if they +// are from the same signer for the same view, but have different IDs. Potential +// causes could be: +// (i) The signer voted for different blocks in the same view. +// (ii) The signer emitted votes for the same block, but included different +// signatures. This is only relevant for voting schemes where the signer has +// different options how to sign (e.g. sign with staking key and/or random +// beacon key). For such voting schemes, byzantine replicas could try to +// submit different votes for the same block, to exhaust the vote collector's +// resources or have multiple of their votes counted to undermine consensus +// safety (aka double-counting attack). +// Both (i) and (ii) are protocol violations and belong to the family of equivocation +// attacks. As part of the error, we return the internally-cached vote, which is +// conflicting with the input `vote`. +// - [RepeatedVoteErr] is returned when adding a vote that is _identical_ (same ID) +// to a previously added vote. This is not a slashable protocol violation. func (vc *VotesCache) AddVote(vote *model.Vote) error { if vote.View != vc.view { - return VoteForIncompatibleViewError + return fmt.Errorf("expected vote for view %d but vote's view is %d: %w", vc.view, vote.View, VoteForIncompatibleViewError) } vc.lock.Lock() defer vc.lock.Unlock() @@ -73,10 +99,16 @@ func (vc *VotesCache) AddVote(vote *model.Vote) error { // we return a model.DoubleVoteError firstVote, exists := vc.votes[vote.SignerID] if exists { + if firstVote.ID() == vote.ID() { + return RepeatedVoteErr + } if firstVote.BlockID != vote.BlockID { - return model.NewDoubleVoteErrorf(firstVote.Vote, vote, "detected vote equivocation at view: %d", vc.view) + // voting in the same view for different blocks => vote equivocation + return model.NewDoubleVoteErrorf(firstVote.Vote, vote, "replica %v voted for different blocks in view %d", vote.SignerID, vc.view) } - return RepeatedVoteErr + // Intentionally votes to not contain any auxiliary information that the voter can vary. Hence, the + // sender is voting for the same block but supplying different signatures => vote equivocation + return model.NewDoubleVoteErrorf(firstVote.Vote, vote, "detected vote equivocation at view: %d", vc.view) } // previously unknown vote: (1) store and (2) forward to consumers diff --git a/context7.json b/context7.json new file mode 100644 index 00000000000..586f4515ad4 --- /dev/null +++ b/context7.json @@ -0,0 +1,4 @@ +{ + "url": "https://context7.com/onflow/flow-go", + "public_key": "pk_EZ8p3YOFzJRKvdNkXGanl" +} diff --git a/crypto_adx_flag.mk b/crypto_adx_flag.mk index 0d0d5ac7467..e088f6cf6c6 100644 --- a/crypto_adx_flag.mk +++ b/crypto_adx_flag.mk @@ -16,14 +16,15 @@ else ADX_SUPPORT := 1 endif +# Flags to disable ADX instructions for older CPUs DISABLE_ADX := "-O2 -D__BLST_PORTABLE__" # Then, set `CRYPTO_FLAG` # the crypto package uses BLST source files underneath which may use ADX instructions. ifeq ($(ADX_SUPPORT), 1) -# if ADX instructions are supported on the current machine, default is to use a fast ADX implementation +# if ADX instructions are supported on the current machine, default is to use a fast ADX implementation CRYPTO_FLAG := "" else -# if ADX instructions aren't supported, this CGO flags uses a slower non-ADX implementation +# if ADX instructions aren't supported, this CGO flags uses a slower non-ADX implementation CRYPTO_FLAG := $(DISABLE_ADX) -endif \ No newline at end of file +endif diff --git a/docs/agents/GoDocs.md b/docs/agents/GoDocs.md index 387893b0455..46faca3748a 100644 --- a/docs/agents/GoDocs.md +++ b/docs/agents/GoDocs.md @@ -1,292 +1,319 @@ # Go Documentation Rule +## CRITICAL REQUIREMENTS +- **NEVER** modify logic. All changes must be documentation only. +- **NEVER** change existing documentation that states no errors are expected. ONLY formatting changes are permitted. + ## General Guidance - Add godocs comments for all types, variables, constants, functions, and interfaces. - Begin with the name of the entity. - Use complete sentences. +- Wrap comment lines that exceed 100 characters. - **ALL** methods that return an error **MUST** document expected error conditions! -- When updating existing code, if godocs exist, keep the existing content and improve formating/expand with additional details to conform with these rules. +- When updating existing code, if godocs exist, keep the existing content and improve formatting/expand with additional details to conform with these rules. - If any details are unclear, **DO NOT make something up**. Add a TODO to fill in the missing details or ask the user for clarification. +- Include an empty comment line with no trailing spaces between each section. +- Wrap types mentioned within comments within brackets (e.g. `[storage.ErrNotFound] if no block header with the given ID exists`) +- Wrap variable or method names within ticks (e.g. ```Update the `View` field```) ## Method Rules +Structure +```go +// [Method name and description - REQUIRED] +// +// [Additional context - optional] +// +// [Concurrency safety - REQUIRED if not concurrency safe] +// +// [Expected errors - REQUIRED] +``` + +Example ```go // MethodName performs a specific action or returns specific information. // -// Returns: (only if additional interpretation of return values is needed beyond the method / function signature) -// - return1: description of non-obvious aspects -// - return2: description of non-obvious aspects +// Additional important details about the method. // -// Expected errors during normal operations: -// - ErrType1: when and why this error occurs -// - ErrType2: when and why this error occurs -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +// NOT CONCURRENCY SAFE! // -// Safe for concurrent access (default, may be omitted) -// CAUTION: not concurrency safe! (if applicable, documentation is obligatory) +// Expected error returns during normal operation: +// - [ErrType1]: when and why this error occurs +// - [ErrType2]: when and why this error occurs ``` ### Method Description - - First line must be a complete sentence describing what the method does - - Use present tense - - Start with the method name - - End with a period - - Prefer a concise description that naturally incorporates the meaning of parameters - - Example: - ```go - // ByBlockID returns the header with the given ID. It is available for finalized and ambiguous blocks. - // Error returns: - // - ErrNotFound if no block header with the given ID exists - ByBlockID(blockID flow.Identifier) (*flow.Header, error) - ``` +- First line must be a complete sentence describing what the method does. +- Use present tense. +- Start with the method name. +- End with a period. +- Prefer a concise description that naturally incorporates the meaning of parameters +- Example: + ```go + // ByBlockID returns the header with the given ID. It is available for finalized and ambiguous blocks. + // + // Expected error returns during normal operation: + // - [ErrNotFound] if no block header with the given ID exists + ByBlockID(blockID flow.Identifier) (*flow.Header, error) + ``` ### Parameters - - Only document parameters separately when they have non-obvious aspects: - - Complex constraints or requirements - - Special relationships with other parameters - - Formatting or validation rules - - Example: - ```go - // ValidateTransaction validates the transaction against the current state. - // - // Parameters: - // - script: must be valid BPL-encoded script with max size of 64KB - // - accounts: must contain at least one account with signing capability - ``` +- Document parameters as part of the main description block. +- Only document parameters separately when they have non-obvious aspects: + - Complex constraints or requirements + - Special relationships with other parameters + - Formatting or validation rules + - Example: + ```go + // ValidateTransaction validates the transaction against the current state. + // `script` must be valid BPL-encoded script with max size of 64KB + // `accounts` must contain at least one account with signing capability + ``` ### Returns - - Only document return values if there is **additional information** necessary to interpret the function's or method's return values, which is not apparent from the method signature's return values - - When documenting non-error returns, be concise and focus only on non-obvious aspects: - ```go - // Example 1 - No return docs needed (self-explanatory): - // GetHeight returns the block's height. +- Document parameters as part of the main description block. +- Only document return values if there is **additional information** necessary to interpret the function's or method's return values, which is not apparent from the method signature's return values +- When documenting non-error returns, be concise and focus only on non-obvious aspects: + Example 1 - No return docs needed (self-explanatory): + ```go + // GetHeight returns the block's height. + ``` + + Example 2 - Additional context needed within method description: + ```go + // GetPipeline returns the execution pipeline, or nil if not configured. + ``` + + Example 3 - Complex return value needs explanation: + ```go + // GetBlockStatus returns the block's current status. + // Returns `PENDING` if still processing, `FINALIZED` if complete, or `INVALID` if failed validation. + ``` +- Expected errors documentation is mandatory (see section `Error Documentation` below) - // Example 2 - Additional context needed: - // GetPipeline returns the execution pipeline, or nil if not configured. +### Error Documentation +There are 2 categories of returned errors: + - Expected benign errors + - Exceptions (unexpected errors) + +Expected errors are benign sentinel errors returned by the function. +Exceptions are unexpected errors returned by the function. These include all errors that are not benign within the context of the method. + +IMPORTANT: For high-assurance software systems such as Flow, anything _outside_ of the paths explicitly specified as safe must be treated as critical failures. +- Hence, we tend to not explicitly specify this over and over again for the sake of brevity. Applying this rule entails that we only document sentinel errors. +- It is implicit that _any_ function or method that has an error return might return an exception, unless explicitly stated otherwise. + +- Error classification is context-dependent - the same error type can be benign in one context but an exception in another +- **ALL** methods that return an error **MUST** document exhaustively all expected benign errors that can be returned (if any) +- ONLY include expected errors documentation if the function returns an error. +- ONLY document benign errors that are expected during normal operations +- Exceptions (unexpected errors) are NOT individually documented in the error section. +- If no errors are expected (all return errors are exceptions), use the catch-all statement: `No error returns are expected during normal operations.` +- NEVER document individual exceptions. +- Error documentation should be the last part of a method's documentation + +Before documenting any error, verify: +- [ ] The error type exists in the codebase (for sentinel errors) +- [ ] The error is actually returned by the method +- [ ] The error handling matches the documented behavior +- [ ] The error is benign in this specific context +- [ ] If wrapping a sentinel error with fmt.Errorf, document the original sentinel error type +- [ ] The error documentation follows the standard format + +Common mistakes to avoid: +- DO NOT document errors that aren't returned +- DO NOT document generic fmt.Errorf errors unless they wrap a sentinel error +- DO NOT document exceptions (unexpected errors that may indicate bugs) +- DO NOT document exceptional errors. Instead, it is implicitly understood that any function or method with an error return might throw exceptions. We categorically exclude repetitive statements about exceptions, because they bloat the documentation. +- DO NOT document implementation details that might change + +#### Required Format + +Error documentation must follow one of these 2 formats: + +For methods with expected benign errors: +```go +// Expected error returns during normal operation: +// - [ErrTypeName]: when and why this error occurs (for sentinel errors) +``` - // Example 3 - Complex return value needs explanation: - // GetBlockStatus returns the block's current status. - // Returns: - // - status: PENDING if still processing, FINALIZED if complete, INVALID if failed validation - ``` - - Error returns documentation is mandatory (see section `Error Returns` below) +For methods where all errors are exceptions: +```go +// No error returns are expected during normal operation. +``` +#### Examples -### Error Documentation - - Error classification is context-dependent - the same error type can be benign in one context but an exception in another - - **ALL** methods that return an error **MUST** document exhaustively all benign errors that can be returned (if there are any) - - Error documentation should be the last part of a method's or function's documentation - - Only document benign errors that are expected during normal operations - - Exceptions (unexpected errors) are not individually documented in the error section. Instead, we include the catch-all statement: `All other errors are potential indicators of bugs or corrupted internal state (continuation impossible)` - - Before documenting any error, verify: - - [ ] The error type exists in the codebase (for sentinel errors) - - [ ] The error is actually returned by the method - - [ ] The error handling matches the documented behavior - - [ ] The error is benign in this specific context - - [ ] If wrapping a sentinel error with fmt.Errorf, document the original sentinel error type - - [ ] The error documentation follows the standard format - - Error documentation must follow this format: - ```go - // Expected errors during normal operations: - // - ErrTypeName: when and why this error occurs (for sentinel errors) - // - ErrWrapped: when wrapped via fmt.Errorf, document the original sentinel error - // - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) - ``` - - For methods where all errors are exceptions: - ```go - // No errors are expected during normal operation. - ``` - - Common mistakes to avoid: - - Don't document errors that aren't returned - - Don't document generic fmt.Errorf errors unless they wrap a sentinel error - - Don't document exceptions (unexpected errors that may indicate bugs) - - Don't mix benign and exceptional errors without clear distinction - - Don't omit the catch-all statement about other errors - - Don't document implementation details that might change - - Examples: - ```go - // Example 1: Method with sentinel errors - // GetBlock returns the block with the given ID. - // Expected errors during normal operations: - // - ErrNotFound: when the block doesn't exist - // - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) - - // Example 2: Method wrapping a sentinel error - // ValidateTransaction validates the transaction against the current state. - // Expected errors during normal operations: - // - ErrInvalidSignature: when the transaction signature is invalid (wrapped) - // - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) - - // Example 3: Method with only exceptional errors - // ProcessFinalizedBlock processes a block that is known to be finalized. - // No errors are expected during normal operation. - - // Example 4: Method with context-dependent error handling - // ByBlockID returns the block with the given ID. - // Expected errors during normal operations: - // - ErrNotFound: when requesting non-finalized blocks that don't exist - // - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) - // Note: ErrNotFound is NOT expected when requesting finalized blocks - ``` +Example 1: Method with sentinel errors +```go +// GetBlock returns the block with the given ID. +// +// Expected error returns during normal operation: +// - [ErrNotFound]: when the block doesn't exist +``` + +Example 2: Method wrapping a sentinel error +```go +// ValidateTransaction validates the transaction against the current state. +// +// Expected error returns during normal operation: +// - [ErrInvalidSignature]: when the transaction signature is invalid (wrapped) +``` + +Example 3: Method with only exceptional errors +```go +// ProcessFinalizedBlock processes a block that is known to be finalized. +// +// No error returns are expected during normal operation. +``` + +Example 4: Method with context-dependent error handling +```go +// ByBlockID returns the block with the given ID. +// +// Expected error returns during normal operation: +// - [ErrNotFound]: when requesting non-finalized blocks that don't exist +// Note: [ErrNotFound] is NOT expected when requesting finalized blocks +``` ### Concurrency Safety - - By default, we assume methods and functions to be concurrency safe. - - Every struct and interface must explicitly state whether it is safe for concurrent access - - If not thread-safe, explain why - - For methods or functions that are not concurrency safe (deviating from the default), it is **mandatory** to diligently document this by including the following call-out: - ```go - // CAUTION: not concurrency safe! - ``` - - If **all methods** of a struct or interface are thread-safe, only document this in the struct's or interface's godoc and mention that all methods are thread-safe. Do not include the line in each method: - ```go - // Safe for concurrent access - ``` - -### Special Cases - - For getters/setters, use simplified format: - ```go - // GetterName returns the value of the field. - // Returns: - // - value: description of the returned value - ``` - - For constructors, use: - ```go - // NewTypeName creates a new instance of TypeName. - // Parameters: - // - param1: description of param1 - // Returns: - // - *TypeName: the newly created instance - // - error: any error that occurred during creation - ``` +- By default, we assume methods and functions to be concurrency safe. +- Every struct and interface must explicitly state whether it is safe for concurrent access. +- For methods or functions that are not concurrency safe (deviating from the default), it **MUST** be explicitly documented by including the following call-out: + ```go + // NOT CONCURRENCY SAFE! + ``` +- If **ALL** methods of a struct or interface are thread-safe, only document this in the struct's or interface's godoc and mention that all methods are thread-safe. Do NOT include the line in each method: + ```go + // Safe for concurrent access + ``` ### Private Methods - - Private methods should still be documented - - Can use more technical language - - Focus on implementation details - - Must include error documention for any method that returns an error +- Private methods should still be documented +- Can use more technical language +- Focus on implementation details +- MUST include error documentation for any method that returns an error ## Examples ### Standard Method Example ```go // AddReceipt adds the given execution receipt to the container and associates it with the block. -// Returns true if the receipt was added, false if it already existed. Safe for concurrent access. +// Returns true if the receipt was added, false if it already existed. // -// Expected errors during normal operations: -// - ErrInvalidReceipt: when the receipt is malformed -// - ErrDuplicateReceipt: when the receipt already exists -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +// Safe for concurrent access. +// +// Expected error returns during normal operation: +// - [ErrInvalidReceipt]: when the receipt is malformed +// - [ErrDuplicateReceipt]: when the receipt already exists ``` ### Getter Method Example ```go -// Pipeline returns the pipeline associated with this execution result container. -// Returns nil if no pipeline is set. Safe for concurrent access +// pipeline returns the pipeline associated with this execution result container. +// Returns nil if no pipeline is set. +// +// NOT CONCURRENCY SAFE! Caller must hold the lock. ``` ### Constructor Example ```go -// NewExecutionResultContainer creates a new instance of ExecutionResultContainer with the given result and pipeline. +// NewExecutionResultContainer creates a new instance of ExecutionResultContainer with the given +// result and pipeline. // -// Expected Errors: -// - ErrInvalidBlock: when the block ID doesn't match the result's block ID -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +// Expected error returns during normal operation: +// - [ErrInvalidBlock]: when the block ID doesn't match the result's block ID ``` ## Interface Documentation 1. **Interface Description** - - Start with the interface name - - Describe the purpose and behavior of the interface - - Explain any invariants or guarantees the interface provides - - Explicitly state whether it is safe for concurrent access - - Example: - ```go - // Executor defines the interface for executing transactions. - // Implementations must guarantee thread-safety and handle byzantine inputs gracefully. - type Executor interface { - // ... methods ... - } - ``` +- Start with the interface name +- Describe the purpose and behavior of the interface +- Explain any invariants or guarantees the interface provides +- Explicitly state whether it is safe for concurrent access +- Example: + ```go + // Executor defines the interface for executing transactions. + // Implementations must guarantee thread-safety and handle byzantine inputs gracefully. + type Executor interface { + // ... methods ... + } + ``` 2. **Interface Methods** - - Document each method in the interface - - Focus on the contract/behavior rather than implementation details - - Include error documentation for methods that return errors - - Ensure that the interface documentation is consistent with the structs' documentations implementing this interface - - Every sentinel error that can be returned by any of the implementations must also be documented by the interface. - - Example: - ```go - // Execute processes the given transaction and returns its execution result. - // The method must be idempotent and handle byzantine inputs gracefully. - // - // Expected Errors: - // - ErrInvalidTransaction: when the transaction is malformed - // - ErrExecutionFailed: when the transaction execution fails - Execute(tx *Transaction) (*Result, error) - ``` +- Document each method in the interface +- Focus on the contract/behavior rather than implementation details +- Include error documentation for methods that return errors +- Ensure that the interface documentation is consistent with the structs' documentations implementing this interface + - Every sentinel error that can be returned by any of the implementations must also be documented by the interface. +- Example: + ```go + // Execute processes the given transaction and returns its execution result. + // The method must be idempotent and handle byzantine inputs gracefully. + // + // Expected error returns during normal operation: + // - [ErrInvalidTransaction]: when the transaction is malformed + // - [ErrExecutionFailed]: when the transaction execution fails + Execute(tx *Transaction) (*Result, error) + ``` ## Constants and Variables 1. **Constants** - - Document the purpose and usage of each constant - - Include any constraints or invariants - - Example: - ```go - // MaxBlockSize defines the maximum size of a block in bytes. - // This value must be a power of 2 and cannot be changed after initialization. - const MaxBlockSize = 1024 * 1024 - ``` + - Document the purpose and usage of each constant + - Include any constraints or invariants + - Example: + ```go + // MaxBlockSize defines the maximum size of a block in bytes. + // This value must be a power of 2 and cannot be changed after initialization. + const MaxBlockSize = 1024 * 1024 + ``` 2. **Variables** - - Document the purpose and lifecycle of each variable - - Include any thread-safety considerations - - Example: - ```go - // defaultConfig holds the default configuration for the system. - // This variable is read-only after initialization and safe for concurrent access. - var defaultConfig = &Config{ - // ... fields ... - } - ``` + - Document the purpose and lifecycle of each variable + - Include any thread-safety considerations + - Example: + ```go + // defaultConfig holds the default configuration for the system. + // This variable is read-only after initialization and safe for concurrent access. + var defaultConfig = &Config{ + // ... fields ... + } + ``` ## Type Documentation 1. **Type Description** - - Start with the type name - - Describe the purpose and behavior of the type - - Include any invariants or guarantees - - Example: - ```go - // Block represents a block in the Flow blockchain. - // Blocks are immutable once created and contain a list of transactions. - // All exported methods are safe for concurrent access. - type Block struct { - // ... fields ... - } - ``` + - Start with the type name + - Describe the purpose and behavior of the type + - Include any invariants or guarantees + - Example: + ```go + // Block represents a block in the Flow blockchain. + // Blocks are immutable once created and contain a list of transactions. + // All exported methods are safe for concurrent access. + type Block struct { + // ... fields ... + } + ``` 2. **Type Fields** - - Document each field with its purpose and constraints - - Include any thread-safety considerations - - Example: - ```go - type Block struct { - // Header contains the block's metadata and cryptographic commitments. - // This field is immutable after block creation. - Header *BlockHeader - - // Payload contains the block's transactions and execution results. - // This field is immutable after block creation. - Payload *BlockPayload - - // Signature is the cryptographic signature of the block proposer. - // This field must be set before the block is considered valid. - Signature []byte - } - ``` + - Document each field with its purpose and constraints + - Include any thread-safety considerations + - Example: + ```go + type Block struct { + // Header contains the block's metadata and cryptographic commitments. + // This field is immutable after block creation. + Header *BlockHeader + + // Payload contains the block's transactions and execution results. + // This field is immutable after block creation. + Payload *BlockPayload + + // Signature is the cryptographic signature of the block proposer. + // This field must be set before the block is considered valid. + Signature []byte + } + ``` 3. **Type Methods** - Document each method following the method documentation rules diff --git a/docs/agents/OperationalDoctrine.md b/docs/agents/OperationalDoctrine.md index fc25b1bd299..6f817bfe93f 100644 --- a/docs/agents/OperationalDoctrine.md +++ b/docs/agents/OperationalDoctrine.md @@ -37,4 +37,3 @@ Don't invent changes other than what's explicitly requested. - Don't remove unrelated code or functionalities. - Don't suggest updates or changes to files when there are no actual modifications needed. - Don't suggest whitespace changes. - diff --git a/engine/access/access_test.go b/engine/access/access_test.go index 1b77dc19518..ce22a417a29 100644 --- a/engine/access/access_test.go +++ b/engine/access/access_test.go @@ -44,6 +44,7 @@ import ( "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/counters" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/mempool/stdmap" "github.com/onflow/flow-go/module/metrics" mockmodule "github.com/onflow/flow-go/module/mock" @@ -187,12 +188,15 @@ func (suite *Suite) RunTest( }) require.NoError(suite.T(), err) + limiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + require.NoError(suite.T(), err) + handler := rpc.NewHandler( suite.backend, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, - subscription.DefaultMaxGlobalStreams, + limiter, rpc.WithBlockSignerDecoder(suite.signerIndicesDecoder), ) f(handler, db, all) @@ -358,7 +362,10 @@ func (suite *Suite) TestSendTransactionToRandomCollectionNode() { }) require.NoError(suite.T(), err) - handler := rpc.NewHandler(bnd, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, subscription.DefaultMaxGlobalStreams) + limiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + require.NoError(suite.T(), err) + + handler := rpc.NewHandler(bnd, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, limiter) // Send transaction 1 resp, err := handler.SendTransaction(context.Background(), sendReq1) @@ -728,7 +735,10 @@ func (suite *Suite) TestGetSealedTransaction() { }) require.NoError(suite.T(), err) - handler := rpc.NewHandler(bnd, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, subscription.DefaultMaxGlobalStreams) + limiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + require.NoError(suite.T(), err) + + handler := rpc.NewHandler(bnd, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, limiter) collectionExecutedMetric, err := indexer.NewCollectionExecutedMetricImpl( suite.log, @@ -742,13 +752,14 @@ func (suite *Suite) TestGetSealedTransaction() { ) require.NoError(suite.T(), err) - progress, err := store.NewConsumerProgress(db, module.ConsumeProgressLastFullBlockHeight).Initialize(suite.rootBlock.Height) + progress, err := store.NewConsumerProgress(db, module.ConsumeProgressLastFullBlockHeight).Initialize(suite.finalizedBlock.Height) require.NoError(suite.T(), err) lastFullBlockHeight, err := counters.NewPersistentStrictMonotonicCounter(progress) require.NoError(suite.T(), err) // create the ingest engine - processedHeight := store.NewConsumerProgress(db, module.ConsumeProgressIngestionEngineBlockHeight) + processedHeight, err := store.NewConsumerProgress(db, module.ConsumeProgressIngestionEngineBlockHeight).Initialize(suite.finalizedBlock.Height) + require.NoError(suite.T(), err) collectionIndexer, err := ingestioncollections.NewIndexer( suite.log, @@ -787,6 +798,7 @@ func (suite *Suite) TestGetSealedTransaction() { collectionSyncer, collectionIndexer, collectionExecutedMetric, + suite.metrics, nil, followerDistributor, ) @@ -992,7 +1004,10 @@ func (suite *Suite) TestGetTransactionResult() { }) require.NoError(suite.T(), err) - handler := rpc.NewHandler(bnd, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, subscription.DefaultMaxGlobalStreams) + limiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + require.NoError(suite.T(), err) + + handler := rpc.NewHandler(bnd, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, limiter) collectionExecutedMetric, err := indexer.NewCollectionExecutedMetricImpl( suite.log, @@ -1006,10 +1021,12 @@ func (suite *Suite) TestGetTransactionResult() { ) require.NoError(suite.T(), err) - processedHeightInitializer := store.NewConsumerProgress(db, module.ConsumeProgressIngestionEngineBlockHeight) + processedHeight, err := store.NewConsumerProgress(db, module.ConsumeProgressIngestionEngineBlockHeight). + Initialize(suite.finalizedBlock.Height) + require.NoError(suite.T(), err) lastFullBlockHeightProgress, err := store.NewConsumerProgress(db, module.ConsumeProgressLastFullBlockHeight). - Initialize(suite.rootBlock.Height) + Initialize(suite.finalizedBlock.Height) require.NoError(suite.T(), err) lastFullBlockHeight, err := counters.NewPersistentStrictMonotonicCounter(lastFullBlockHeightProgress) @@ -1048,10 +1065,11 @@ func (suite *Suite) TestGetTransactionResult() { all.Blocks, all.Results, all.Receipts, - processedHeightInitializer, + processedHeight, collectionSyncer, collectionIndexer, collectionExecutedMetric, + suite.metrics, nil, followerDistributor, ) @@ -1253,7 +1271,10 @@ func (suite *Suite) TestExecuteScript() { }) require.NoError(suite.T(), err) - handler := rpc.NewHandler(suite.backend, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, subscription.DefaultMaxGlobalStreams) + limiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + require.NoError(suite.T(), err) + + handler := rpc.NewHandler(suite.backend, suite.chainID.Chain(), suite.finalizedHeaderCache, suite.me, limiter) // initialize metrics related storage metrics := metrics.NewNoopCollector() @@ -1279,9 +1300,11 @@ func (suite *Suite) TestExecuteScript() { Once() processedHeightInitializer := store.NewConsumerProgress(db, module.ConsumeProgressIngestionEngineBlockHeight) + processedHeight, err := processedHeightInitializer.Initialize(suite.finalizedBlock.Height) + require.NoError(suite.T(), err) lastFullBlockHeightInitializer := store.NewConsumerProgress(db, module.ConsumeProgressLastFullBlockHeight) - lastFullBlockHeightProgress, err := lastFullBlockHeightInitializer.Initialize(suite.rootBlock.Height) + lastFullBlockHeightProgress, err := lastFullBlockHeightInitializer.Initialize(suite.finalizedBlock.Height) require.NoError(suite.T(), err) lastFullBlockHeight, err := counters.NewPersistentStrictMonotonicCounter(lastFullBlockHeightProgress) @@ -1320,10 +1343,11 @@ func (suite *Suite) TestExecuteScript() { all.Blocks, all.Results, all.Receipts, - processedHeightInitializer, + processedHeight, collectionSyncer, collectionIndexer, collectionExecutedMetric, + suite.metrics, nil, followerDistributor, ) diff --git a/engine/access/apiproxy/access_api_proxy.go b/engine/access/apiproxy/access_api_proxy.go index b57ff64fa63..01e08599e1a 100644 --- a/engine/access/apiproxy/access_api_proxy.go +++ b/engine/access/apiproxy/access_api_proxy.go @@ -450,6 +450,30 @@ func (h *FlowAccessAPIRouter) GetExecutionResultByID(context context.Context, re return res, err } +func (h *FlowAccessAPIRouter) GetExecutionReceiptsByBlockID(context context.Context, req *access.GetExecutionReceiptsByBlockIDRequest) (*access.ExecutionReceiptsResponse, error) { + if h.useIndex { + res, err := h.local.GetExecutionReceiptsByBlockID(context, req) + h.log(LocalApiService, "GetExecutionReceiptsByBlockID", err) + return res, err + } + + res, err := h.upstream.GetExecutionReceiptsByBlockID(context, req) + h.log(UpstreamApiService, "GetExecutionReceiptsByBlockID", err) + return res, err +} + +func (h *FlowAccessAPIRouter) GetExecutionReceiptsByResultID(context context.Context, req *access.GetExecutionReceiptsByResultIDRequest) (*access.ExecutionReceiptsResponse, error) { + if h.useIndex { + res, err := h.local.GetExecutionReceiptsByResultID(context, req) + h.log(LocalApiService, "GetExecutionReceiptsByResultID", err) + return res, err + } + + res, err := h.upstream.GetExecutionReceiptsByResultID(context, req) + h.log(UpstreamApiService, "GetExecutionReceiptsByResultID", err) + return res, err +} + func (h *FlowAccessAPIRouter) SubscribeBlocksFromStartBlockID(req *access.SubscribeBlocksFromStartBlockIDRequest, server access.AccessAPI_SubscribeBlocksFromStartBlockIDServer) error { err := h.local.SubscribeBlocksFromStartBlockID(req, server) h.log(LocalApiService, "SubscribeBlocksFromStartBlockID", err) @@ -928,6 +952,26 @@ func (h *FlowAccessAPIForwarder) GetExecutionResultByID(context context.Context, return upstream.GetExecutionResultByID(context, req) } +func (h *FlowAccessAPIForwarder) GetExecutionReceiptsByBlockID(context context.Context, req *access.GetExecutionReceiptsByBlockIDRequest) (*access.ExecutionReceiptsResponse, error) { + // This is a passthrough request + upstream, closer, err := h.FaultTolerantClient() + if err != nil { + return nil, err + } + defer closer.Close() + return upstream.GetExecutionReceiptsByBlockID(context, req) +} + +func (h *FlowAccessAPIForwarder) GetExecutionReceiptsByResultID(context context.Context, req *access.GetExecutionReceiptsByResultIDRequest) (*access.ExecutionReceiptsResponse, error) { + // This is a passthrough request + upstream, closer, err := h.FaultTolerantClient() + if err != nil { + return nil, err + } + defer closer.Close() + return upstream.GetExecutionReceiptsByResultID(context, req) +} + func (h *FlowAccessAPIForwarder) SendAndSubscribeTransactionStatuses(req *access.SendAndSubscribeTransactionStatusesRequest, server access.AccessAPI_SendAndSubscribeTransactionStatusesServer) error { return status.Errorf(codes.Unimplemented, "method SendAndSubscribeTransactionStatuses not implemented") } diff --git a/engine/access/handle_irrecoverable_state_test.go b/engine/access/handle_irrecoverable_state_test.go index c51dc8c7fd1..d46a7ef0000 100644 --- a/engine/access/handle_irrecoverable_state_test.go +++ b/engine/access/handle_irrecoverable_state_test.go @@ -29,10 +29,12 @@ import ( "github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator" "github.com/onflow/flow-go/engine/access/rpc/backend/query_mode" statestreambackend "github.com/onflow/flow-go/engine/access/state_stream/backend" + "github.com/onflow/flow-go/engine/access/subscription" commonrpc "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/metrics" module "github.com/onflow/flow-go/module/mock" mocknetwork "github.com/onflow/flow-go/network/mock" @@ -171,6 +173,8 @@ func (suite *IrrecoverableStateTestSuite) SetupTest() { stateStreamConfig := statestreambackend.Config{} followerDistributor := pubsub.NewFollowerDistributor() + streamLimiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + suite.Require().NoError(err) rpcEngBuilder, err := rpc.NewBuilder( suite.log, suite.state, @@ -187,6 +191,8 @@ func (suite *IrrecoverableStateTestSuite) SetupTest() { stateStreamConfig, nil, followerDistributor, + nil, + streamLimiter, ) assert.NoError(suite.T(), err) suite.rpcEng, err = rpcEngBuilder.WithLegacy().Build() diff --git a/engine/access/index/event_index_test.go b/engine/access/index/event_index_test.go index e86e9594c65..94b521d6046 100644 --- a/engine/access/index/event_index_test.go +++ b/engine/access/index/event_index_test.go @@ -1,9 +1,7 @@ package index import ( - "bytes" "math" - "sort" "testing" "github.com/stretchr/testify/assert" @@ -25,18 +23,6 @@ func TestGetEvents(t *testing.T) { storedEvents := make([]flow.Event, len(expectedEvents)) copy(storedEvents, expectedEvents) - // sort events in storage order (by tx ID) - sort.Slice(storedEvents, func(i, j int) bool { - cmp := bytes.Compare(storedEvents[i].TransactionID[:], storedEvents[j].TransactionID[:]) - if cmp == 0 { - if storedEvents[i].TransactionIndex == storedEvents[j].TransactionIndex { - return storedEvents[i].EventIndex < storedEvents[j].EventIndex - } - return storedEvents[i].TransactionIndex < storedEvents[j].TransactionIndex - } - return cmp < 0 - }) - events := storagemock.NewEvents(t) header := unittest.BlockHeaderFixture() diff --git a/engine/access/index/events_index.go b/engine/access/index/events_index.go index bc669c79fb1..50c2c797955 100644 --- a/engine/access/index/events_index.go +++ b/engine/access/index/events_index.go @@ -1,8 +1,6 @@ package index import ( - "sort" - "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/storage" ) @@ -36,15 +34,6 @@ func (e *EventsIndex) ByBlockID(blockID flow.Identifier, height uint64) ([]flow. return nil, err } - // events are keyed/sorted by [blockID, txID, txIndex, eventIndex] - // we need to resort them by tx index then event index so the output is in execution order - sort.Slice(events, func(i, j int) bool { - if events[i].TransactionIndex == events[j].TransactionIndex { - return events[i].EventIndex < events[j].EventIndex - } - return events[i].TransactionIndex < events[j].TransactionIndex - }) - return events, nil } diff --git a/engine/access/ingestion/collections/mock/collection_indexer.go b/engine/access/ingestion/collections/mock/collection_indexer.go index 9d2f174cfee..a473efd618f 100644 --- a/engine/access/ingestion/collections/mock/collection_indexer.go +++ b/engine/access/ingestion/collections/mock/collection_indexer.go @@ -1,38 +1,95 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewCollectionIndexer creates a new instance of CollectionIndexer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCollectionIndexer(t interface { + mock.TestingT + Cleanup(func()) +}) *CollectionIndexer { + mock := &CollectionIndexer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CollectionIndexer is an autogenerated mock type for the CollectionIndexer type type CollectionIndexer struct { mock.Mock } -// IndexCollections provides a mock function with given fields: _a0 -func (_m *CollectionIndexer) IndexCollections(_a0 []*flow.Collection) error { - ret := _m.Called(_a0) +type CollectionIndexer_Expecter struct { + mock *mock.Mock +} + +func (_m *CollectionIndexer) EXPECT() *CollectionIndexer_Expecter { + return &CollectionIndexer_Expecter{mock: &_m.Mock} +} + +// IndexCollections provides a mock function for the type CollectionIndexer +func (_mock *CollectionIndexer) IndexCollections(collections []*flow.Collection) error { + ret := _mock.Called(collections) if len(ret) == 0 { panic("no return value specified for IndexCollections") } var r0 error - if rf, ok := ret.Get(0).(func([]*flow.Collection) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func([]*flow.Collection) error); ok { + r0 = returnFunc(collections) } else { r0 = ret.Error(0) } - return r0 } -// MissingCollectionsAtHeight provides a mock function with given fields: height -func (_m *CollectionIndexer) MissingCollectionsAtHeight(height uint64) ([]*flow.CollectionGuarantee, error) { - ret := _m.Called(height) +// CollectionIndexer_IndexCollections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IndexCollections' +type CollectionIndexer_IndexCollections_Call struct { + *mock.Call +} + +// IndexCollections is a helper method to define mock.On call +// - collections []*flow.Collection +func (_e *CollectionIndexer_Expecter) IndexCollections(collections interface{}) *CollectionIndexer_IndexCollections_Call { + return &CollectionIndexer_IndexCollections_Call{Call: _e.mock.On("IndexCollections", collections)} +} + +func (_c *CollectionIndexer_IndexCollections_Call) Run(run func(collections []*flow.Collection)) *CollectionIndexer_IndexCollections_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []*flow.Collection + if args[0] != nil { + arg0 = args[0].([]*flow.Collection) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionIndexer_IndexCollections_Call) Return(err error) *CollectionIndexer_IndexCollections_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CollectionIndexer_IndexCollections_Call) RunAndReturn(run func(collections []*flow.Collection) error) *CollectionIndexer_IndexCollections_Call { + _c.Call.Return(run) + return _c +} + +// MissingCollectionsAtHeight provides a mock function for the type CollectionIndexer +func (_mock *CollectionIndexer) MissingCollectionsAtHeight(height uint64) ([]*flow.CollectionGuarantee, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for MissingCollectionsAtHeight") @@ -40,41 +97,94 @@ func (_m *CollectionIndexer) MissingCollectionsAtHeight(height uint64) ([]*flow. var r0 []*flow.CollectionGuarantee var r1 error - if rf, ok := ret.Get(0).(func(uint64) ([]*flow.CollectionGuarantee, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) ([]*flow.CollectionGuarantee, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) []*flow.CollectionGuarantee); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) []*flow.CollectionGuarantee); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.CollectionGuarantee) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// OnCollectionReceived provides a mock function with given fields: collection -func (_m *CollectionIndexer) OnCollectionReceived(collection *flow.Collection) { - _m.Called(collection) +// CollectionIndexer_MissingCollectionsAtHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MissingCollectionsAtHeight' +type CollectionIndexer_MissingCollectionsAtHeight_Call struct { + *mock.Call } -// NewCollectionIndexer creates a new instance of CollectionIndexer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCollectionIndexer(t interface { - mock.TestingT - Cleanup(func()) -}) *CollectionIndexer { - mock := &CollectionIndexer{} - mock.Mock.Test(t) +// MissingCollectionsAtHeight is a helper method to define mock.On call +// - height uint64 +func (_e *CollectionIndexer_Expecter) MissingCollectionsAtHeight(height interface{}) *CollectionIndexer_MissingCollectionsAtHeight_Call { + return &CollectionIndexer_MissingCollectionsAtHeight_Call{Call: _e.mock.On("MissingCollectionsAtHeight", height)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *CollectionIndexer_MissingCollectionsAtHeight_Call) Run(run func(height uint64)) *CollectionIndexer_MissingCollectionsAtHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *CollectionIndexer_MissingCollectionsAtHeight_Call) Return(collectionGuarantees []*flow.CollectionGuarantee, err error) *CollectionIndexer_MissingCollectionsAtHeight_Call { + _c.Call.Return(collectionGuarantees, err) + return _c +} + +func (_c *CollectionIndexer_MissingCollectionsAtHeight_Call) RunAndReturn(run func(height uint64) ([]*flow.CollectionGuarantee, error)) *CollectionIndexer_MissingCollectionsAtHeight_Call { + _c.Call.Return(run) + return _c +} + +// OnCollectionReceived provides a mock function for the type CollectionIndexer +func (_mock *CollectionIndexer) OnCollectionReceived(collection *flow.Collection) { + _mock.Called(collection) + return +} + +// CollectionIndexer_OnCollectionReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnCollectionReceived' +type CollectionIndexer_OnCollectionReceived_Call struct { + *mock.Call +} + +// OnCollectionReceived is a helper method to define mock.On call +// - collection *flow.Collection +func (_e *CollectionIndexer_Expecter) OnCollectionReceived(collection interface{}) *CollectionIndexer_OnCollectionReceived_Call { + return &CollectionIndexer_OnCollectionReceived_Call{Call: _e.mock.On("OnCollectionReceived", collection)} +} + +func (_c *CollectionIndexer_OnCollectionReceived_Call) Run(run func(collection *flow.Collection)) *CollectionIndexer_OnCollectionReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Collection + if args[0] != nil { + arg0 = args[0].(*flow.Collection) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionIndexer_OnCollectionReceived_Call) Return() *CollectionIndexer_OnCollectionReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionIndexer_OnCollectionReceived_Call) RunAndReturn(run func(collection *flow.Collection)) *CollectionIndexer_OnCollectionReceived_Call { + _c.Run(run) + return _c } diff --git a/engine/access/ingestion/engine.go b/engine/access/ingestion/engine.go index e078283da5b..8bc8e802aca 100644 --- a/engine/access/ingestion/engine.go +++ b/engine/access/ingestion/engine.go @@ -2,6 +2,7 @@ package ingestion import ( "context" + "errors" "fmt" "github.com/jordanschalm/lockctx" @@ -73,6 +74,7 @@ type Engine struct { // TODO: There's still a need for this metric to be in the ingestion engine rather than collection syncer. // Maybe it is a good idea to split it up? collectionExecutedMetric module.CollectionExecutedMetric + accessMetrics module.AccessMetrics txErrorMessagesCore *tx_error_messages.TxErrorMessagesCore } @@ -92,10 +94,11 @@ func New( blocks storage.Blocks, executionResults storage.ExecutionResults, executionReceipts storage.ExecutionReceipts, - finalizedProcessedHeight storage.ConsumerProgressInitializer, + finalizedProcessedHeight storage.ConsumerProgress, collectionSyncer *collections.Syncer, collectionIndexer *collections.Indexer, collectionExecutedMetric module.CollectionExecutedMetric, + accessMetrics module.AccessMetrics, txErrorMessagesCore *tx_error_messages.TxErrorMessagesCore, registrar hotstuff.FinalizationRegistrar, ) (*Engine, error) { @@ -130,6 +133,7 @@ func New( executionReceipts: executionReceipts, maxReceiptHeight: 0, collectionExecutedMetric: collectionExecutedMetric, + accessMetrics: accessMetrics, finalizedBlockNotifier: engine.NewNotifier(), // queue / notifier for execution receipts @@ -146,11 +150,6 @@ func New( // to get a sequential list of finalized blocks. finalizedBlockReader := jobqueue.NewFinalizedBlockReader(state, blocks) - defaultIndex, err := e.defaultProcessedIndex() - if err != nil { - return nil, fmt.Errorf("could not read default finalized processed index: %w", err) - } - // create a jobqueue that will process new available finalized block. The `finalizedBlockNotifier` is used to // signal new work, which is being triggered on the `processFinalizedBlockJob` handler. e.finalizedBlockConsumer, err = jobqueue.NewComponentConsumer( @@ -158,7 +157,6 @@ func New( e.finalizedBlockNotifier.Channel(), finalizedProcessedHeight, finalizedBlockReader, - defaultIndex, e.processFinalizedBlockJob, processFinalizedBlocksWorkersCount, searchAhead, @@ -195,20 +193,6 @@ func New( return e, nil } -// defaultProcessedIndex returns the last finalized block height from the protocol state. -// -// The finalizedBlockConsumer utilizes this return height to fetch and consume block jobs from -// jobs queue the first time it initializes. -// -// No errors are expected during normal operation. -func (e *Engine) defaultProcessedIndex() (uint64, error) { - final, err := e.state.Final().Head() - if err != nil { - return 0, fmt.Errorf("could not get finalized height: %w", err) - } - return final.Height, nil -} - // runFinalizedBlockConsumer runs the finalizedBlockConsumer component func (e *Engine) runFinalizedBlockConsumer(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { e.finalizedBlockConsumer.Start(ctx) @@ -230,12 +214,15 @@ func (e *Engine) processFinalizedBlockJob(ctx irrecoverable.SignalerContext, job } err = e.processFinalizedBlock(block) - if err == nil { - done() + if err != nil { + ctx.Throw( + fmt.Errorf( + "fatal error when ingestion building col->block index for finalized block (job: %s, height: %v): %w", + job.ID(), block.Height, err)) return } - e.log.Error().Err(err).Str("job_id", string(job.ID())).Msg("error during finalized block processing job") + done() } // processExecutionReceipts is responsible for processing the execution receipts. @@ -353,10 +340,10 @@ func (e *Engine) onFinalizedBlock(*model.Block) { // processFinalizedBlock handles an incoming finalized block. // It processes the block, indexes it for further processing, and requests missing collections if necessary. +// If the block is already indexed (storage.ErrAlreadyExists), it logs a warning and continues processing. // // Expected errors during normal operation: // - storage.ErrNotFound - if last full block height does not exist in the database. -// - storage.ErrAlreadyExists - if the collection within block or an execution result ID already exists in the database. // - generic error in case of unexpected failure from the database layer, or failure // to decode an existing database value. func (e *Engine) processFinalizedBlock(block *flow.Block) error { @@ -386,7 +373,15 @@ func (e *Engine) processFinalizedBlock(block *flow.Block) error { }) }) if err != nil { - return fmt.Errorf("could not index block for collections: %w", err) + if !errors.Is(err, storage.ErrAlreadyExists) { + return fmt.Errorf("could not index block for collections: %w", err) + } + // the job queue processed index is updated in a separate db update, so it's possible that the above index + // has been built, but the jobqueue index has not been updated yet. In this case, we can safely skip processing. + e.log.Warn(). + Uint64("height", block.Height). + Str("block_id", block.ID().String()). + Msg("block already indexed, skipping indexing") } err = e.collectionSyncer.RequestCollectionsForBlock(block.Height, block.Payload.Guarantees) @@ -394,6 +389,7 @@ func (e *Engine) processFinalizedBlock(block *flow.Block) error { return fmt.Errorf("could not request collections for block: %w", err) } e.collectionExecutedMetric.BlockFinalized(block) + e.accessMetrics.UpdateIngestionFinalizedBlockHeight(block.Height) return nil } diff --git a/engine/access/ingestion/engine_test.go b/engine/access/ingestion/engine_test.go index 49102f72f0e..59adbcaa937 100644 --- a/engine/access/ingestion/engine_test.go +++ b/engine/access/ingestion/engine_test.go @@ -177,7 +177,8 @@ func (s *Suite) SetupTest() { // initEngineAndSyncer create new instance of ingestion engine and collection syncer. // It waits until the ingestion engine starts. func (s *Suite) initEngineAndSyncer() (*Engine, *collections.Syncer, *collections.Indexer) { - processedHeightInitializer := store.NewConsumerProgress(s.db, module.ConsumeProgressIngestionEngineBlockHeight) + processedHeight, err := store.NewConsumerProgress(s.db, module.ConsumeProgressIngestionEngineBlockHeight).Initialize(s.finalizedBlock.Height) + require.NoError(s.T(), err) lastFullBlockHeight, err := store.NewConsumerProgress(s.db, module.ConsumeProgressLastFullBlockHeight).Initialize(s.finalizedBlock.Height) require.NoError(s.T(), err) @@ -217,10 +218,11 @@ func (s *Suite) initEngineAndSyncer() (*Engine, *collections.Syncer, *collection s.blocks, s.results, s.receipts, - processedHeightInitializer, + processedHeight, syncer, indexer, s.collectionExecutedMetric, + metrics.NewNoopCollector(), nil, s.distributor, ) @@ -272,8 +274,8 @@ func (s *Suite) TestOnFinalizedBlockSingle() { snap := new(protocolmock.Snapshot) finalSnapshot := protocolmock.NewSnapshot(s.T()) - finalSnapshot.On("Head").Return(s.finalizedBlock, nil).Twice() - s.proto.state.On("Final").Return(finalSnapshot, nil).Twice() + finalSnapshot.On("Head").Return(s.finalizedBlock, nil).Once() + s.proto.state.On("Final").Return(finalSnapshot, nil).Once() epoch.On("ClusterByChainID", mock.Anything).Return(cluster, nil) epochs.On("Current").Return(epoch, nil) @@ -338,8 +340,8 @@ func (s *Suite) TestOnFinalizedBlockSeveralBlocksAhead() { snap := new(protocolmock.Snapshot) finalSnapshot := protocolmock.NewSnapshot(s.T()) - finalSnapshot.On("Head").Return(s.finalizedBlock, nil).Twice() - s.proto.state.On("Final").Return(finalSnapshot, nil).Twice() + finalSnapshot.On("Head").Return(s.finalizedBlock, nil).Once() + s.proto.state.On("Final").Return(finalSnapshot, nil).Once() epoch.On("ClusterByChainID", mock.Anything).Return(cluster, nil) epochs.On("Current").Return(epoch, nil) @@ -415,10 +417,6 @@ func (s *Suite) TestOnFinalizedBlockSeveralBlocksAhead() { // TestExecutionReceiptsAreIndexed checks that execution receipts are properly indexed func (s *Suite) TestExecutionReceiptsAreIndexed() { - finalSnapshot := protocolmock.NewSnapshot(s.T()) - finalSnapshot.On("Head").Return(s.finalizedBlock, nil).Once() - s.proto.state.On("Final").Return(finalSnapshot, nil).Once() - eng, _, _ := s.initEngineAndSyncer() originID := unittest.IdentifierFixture() @@ -567,6 +565,77 @@ func (s *Suite) TestCollectionSyncing() { }, 2*time.Second, 100*time.Millisecond, "last full block height never updated") } +// TestOnFinalizedBlockAlreadyIndexed checks that when a block has already been indexed +// (storage.ErrAlreadyExists), the engine logs a warning and continues processing by +// requesting collections and updating metrics. This can happen when the job queue processed +// index hasn't been updated yet after a previous indexing operation. +func (s *Suite) TestOnFinalizedBlockAlreadyIndexed() { + cluster := new(protocolmock.Cluster) + epoch := new(protocolmock.CommittedEpoch) + epochs := new(protocolmock.EpochQuery) + snap := new(protocolmock.Snapshot) + + finalSnapshot := protocolmock.NewSnapshot(s.T()) + finalSnapshot.On("Head").Return(s.finalizedBlock, nil).Once() + s.proto.state.On("Final").Return(finalSnapshot, nil).Once() + + epoch.On("ClusterByChainID", mock.Anything).Return(cluster, nil) + epochs.On("Current").Return(epoch, nil) + snap.On("Epochs").Return(epochs) + + // prepare cluster committee members + clusterCommittee := unittest.IdentityListFixture(32 * 4).Filter(filter.HasRole[flow.Identity](flow.RoleCollection)).ToSkeleton() + cluster.On("Members").Return(clusterCommittee, nil) + + eng, _, _ := s.initEngineAndSyncer() + + irrecoverableCtx, cancel := irrecoverable.NewMockSignalerContextWithCancel(s.T(), s.ctx) + eng.ComponentManager.Start(irrecoverableCtx) + unittest.RequireCloseBefore(s.T(), eng.Ready(), 100*time.Millisecond, "could not start worker") + defer func() { + cancel() + unittest.RequireCloseBefore(s.T(), eng.Done(), 100*time.Millisecond, "could not stop worker") + }() + + block := s.generateBlock(clusterCommittee, snap) + block.Height = s.finalizedBlock.Height + 1 + s.blockMap[block.Height] = block + s.mockCollectionsForBlock(block) + s.finalizedBlock = block.ToHeader() + + hotstuffBlock := hotmodel.Block{ + BlockID: block.ID(), + } + + // simulate that the block has already been indexed (e.g., by a previous job queue run) + // by returning storage.ErrAlreadyExists + s.blocks.On("BatchIndexBlockContainingCollectionGuarantees", mock.Anything, mock.Anything, block.ID(), []flow.Identifier(flow.GetIDs(block.Payload.Guarantees))). + Return(storage.ErrAlreadyExists).Once() + + missingCollectionCount := 4 + wg := sync.WaitGroup{} + wg.Add(missingCollectionCount) + + // even though block is already indexed, collections should still be requested + for _, cg := range block.Payload.Guarantees { + s.request.On("EntityByID", cg.CollectionID, mock.Anything).Return().Run(func(args mock.Arguments) { + wg.Done() + }).Once() + } + + // force should be called once + s.request.On("Force").Return().Once() + + // process the block through the finalized callback + s.distributor.OnFinalizedBlock(&hotstuffBlock) + + unittest.RequireReturnsBefore(s.T(), wg.Wait, 100*time.Millisecond, "expect to process new block before timeout") + + // assert that collections were still requested despite the block being already indexed + s.headers.AssertExpectations(s.T()) + s.request.AssertNumberOfCalls(s.T(), "EntityByID", len(block.Payload.Guarantees)) +} + func (s *Suite) mockGuarantorsForCollection(guarantee *flow.CollectionGuarantee, members flow.IdentitySkeletonList) { cluster := protocolmock.NewCluster(s.T()) cluster.On("Members").Return(members, nil).Once() diff --git a/engine/access/ingestion/tx_error_messages/mock/requester.go b/engine/access/ingestion/tx_error_messages/mock/requester.go index a486cbf9b3e..8c81569a370 100644 --- a/engine/access/ingestion/tx_error_messages/mock/requester.go +++ b/engine/access/ingestion/tx_error_messages/mock/requester.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewRequester creates a new instance of Requester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRequester(t interface { + mock.TestingT + Cleanup(func()) +}) *Requester { + mock := &Requester{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Requester is an autogenerated mock type for the Requester type type Requester struct { mock.Mock } -// Request provides a mock function with given fields: ctx -func (_m *Requester) Request(ctx context.Context) ([]flow.TransactionResultErrorMessage, error) { - ret := _m.Called(ctx) +type Requester_Expecter struct { + mock *mock.Mock +} + +func (_m *Requester) EXPECT() *Requester_Expecter { + return &Requester_Expecter{mock: &_m.Mock} +} + +// Request provides a mock function for the type Requester +func (_mock *Requester) Request(ctx context.Context) ([]flow.TransactionResultErrorMessage, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for Request") @@ -24,36 +48,54 @@ func (_m *Requester) Request(ctx context.Context) ([]flow.TransactionResultError var r0 []flow.TransactionResultErrorMessage var r1 error - if rf, ok := ret.Get(0).(func(context.Context) ([]flow.TransactionResultErrorMessage, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) ([]flow.TransactionResultErrorMessage, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) []flow.TransactionResultErrorMessage); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) []flow.TransactionResultErrorMessage); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.TransactionResultErrorMessage) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewRequester creates a new instance of Requester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRequester(t interface { - mock.TestingT - Cleanup(func()) -}) *Requester { - mock := &Requester{} - mock.Mock.Test(t) +// Requester_Request_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Request' +type Requester_Request_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Request is a helper method to define mock.On call +// - ctx context.Context +func (_e *Requester_Expecter) Request(ctx interface{}) *Requester_Request_Call { + return &Requester_Request_Call{Call: _e.mock.On("Request", ctx)} +} - return mock +func (_c *Requester_Request_Call) Run(run func(ctx context.Context)) *Requester_Request_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Requester_Request_Call) Return(transactionResultErrorMessages []flow.TransactionResultErrorMessage, err error) *Requester_Request_Call { + _c.Call.Return(transactionResultErrorMessages, err) + return _c +} + +func (_c *Requester_Request_Call) RunAndReturn(run func(ctx context.Context) ([]flow.TransactionResultErrorMessage, error)) *Requester_Request_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/ingestion/tx_error_messages/tx_error_messages_core.go b/engine/access/ingestion/tx_error_messages/tx_error_messages_core.go index b08a9ae907f..50456be3b14 100644 --- a/engine/access/ingestion/tx_error_messages/tx_error_messages_core.go +++ b/engine/access/ingestion/tx_error_messages/tx_error_messages_core.go @@ -2,6 +2,7 @@ package tx_error_messages import ( "context" + "errors" "fmt" "github.com/jordanschalm/lockctx" @@ -51,15 +52,13 @@ func NewTxErrorMessagesCore( // The function first checks if error messages for the given block ID are already present in storage. // If they are not, it fetches the messages from execution nodes and stores them. // -// Parameters: -// - ctx: The context for managing cancellation and deadlines during the operation. -// - blockID: The identifier of the block for which transaction result error messages need to be processed. -// -// No errors are expected during normal operation. +// Expected error returns during normal operation: +// - [status.Error] if the GRPC call failed +// - [rpc.ErrNoENsFoundForExecutionResult] - if no execution nodes were found that produced the provided +// execution result and matched the operators criteria func (c *TxErrorMessagesCore) FetchErrorMessages(ctx context.Context, blockID flow.Identifier) error { execNodes, err := c.execNodeIdentitiesProvider.ExecutionNodesForBlockID(ctx, blockID) if err != nil { - c.log.Error().Err(err).Msg(fmt.Sprintf("failed to find execution nodes for block id: %s", blockID)) return fmt.Errorf("could not find execution nodes for block: %w", err) } @@ -74,7 +73,8 @@ func (c *TxErrorMessagesCore) FetchErrorMessages(ctx context.Context, blockID fl // not protected by the protocol. Execution Error messages might be non-deterministic, i.e. potentially different // for different execution nodes. Hence, we also persist which execution node (`execNode) provided the error message. // -// It returns [storage.ErrAlreadyExists] if tx result error messages for the block already exist. +// Expected error returns during normal operation: +// - [status.Error] if the GRPC call failed func (c *TxErrorMessagesCore) FetchErrorMessagesByENs( ctx context.Context, blockID flow.Identifier, @@ -105,6 +105,10 @@ func (c *TxErrorMessagesCore) FetchErrorMessagesByENs( if len(resp) > 0 { err = c.storeTransactionResultErrorMessages(blockID, resp, execNode) if err != nil { + if errors.Is(err, storage.ErrAlreadyExists) { + // data for the block already exists. nothing to do. + return nil + } return fmt.Errorf("could not store error messages (block: %s): %w", blockID, err) } } @@ -115,7 +119,8 @@ func (c *TxErrorMessagesCore) FetchErrorMessagesByENs( // storeTransactionResultErrorMessages persists and indexes all transaction result error messages for the given blockID. // The caller must acquire [storage.LockInsertTransactionResultErrMessage] and hold it until the write batch has been committed. // -// It returns [storage.ErrAlreadyExists] if tx result error messages for the block already exist. +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists] if tx result error messages for the block already exist. func (c *TxErrorMessagesCore) storeTransactionResultErrorMessages( blockID flow.Identifier, errorMessagesResponses []*execproto.GetTransactionErrorMessagesResponse_Result, diff --git a/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go b/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go index 431aa215a69..62c11353cbf 100644 --- a/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go +++ b/engine/access/ingestion/tx_error_messages/tx_error_messages_core_test.go @@ -219,6 +219,30 @@ func (s *TxErrorMessagesCoreSuite) TestHandleTransactionResultErrorMessages_Erro s.txErrorMessages.AssertNotCalled(s.T(), "Store", mock.Anything, mock.Anything) }) + s.Run("ErrAlreadyExists from Store is treated as success", func() { + // Simulate successful fetching but Store returns ErrAlreadyExists + + s.txErrorMessages.On("Exists", blockId).Return(false, nil).Once() + + resultsByBlockID := mockTransactionResultsByBlock(5) + exeEventReq := &execproto.GetTransactionErrorMessagesByBlockIDRequest{ + BlockId: blockId[:], + } + s.execClient.On("GetTransactionErrorMessagesByBlockID", mock.Anything, exeEventReq). + Return(createTransactionErrorMessagesResponse(resultsByBlockID), nil).Once() + + expectedStoreTxErrorMessages := createExpectedTxErrorMessages(resultsByBlockID, s.enNodeIDs.NodeIDs()[0]) + s.txErrorMessages.On("Store", mock.Anything, blockId, expectedStoreTxErrorMessages). + Return(func(lctx lockctx.Proof, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage) error { + require.True(s.T(), lctx.HoldsLock(storage.LockInsertTransactionResultErrMessage)) + return storage.ErrAlreadyExists + }).Once() + + core := s.initCore() + err := core.FetchErrorMessages(irrecoverableCtx, blockId) + require.NoError(s.T(), err) + }) + s.Run("Storage error after fetching results", func() { // Simulate successful fetching of transaction error messages but error in storing them. diff --git a/engine/access/ingestion/tx_error_messages/tx_error_messages_engine.go b/engine/access/ingestion/tx_error_messages/tx_error_messages_engine.go index f20f014d6c5..472cd3c1070 100644 --- a/engine/access/ingestion/tx_error_messages/tx_error_messages_engine.go +++ b/engine/access/ingestion/tx_error_messages/tx_error_messages_engine.go @@ -2,15 +2,18 @@ package tx_error_messages import ( "context" + "errors" "fmt" "time" "github.com/rs/zerolog" "github.com/sethvargo/go-retry" + "google.golang.org/grpc/status" "github.com/onflow/flow-go/consensus/hotstuff" "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/engine" + commonrpc "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/component" @@ -72,7 +75,7 @@ func New( metrics module.TransactionErrorMessagesMetrics, state protocol.State, headers storage.Headers, - txErrorMessagesProcessedHeight storage.ConsumerProgressInitializer, + txErrorMessagesProcessedHeight storage.ConsumerProgress, txErrorMessagesCore *TxErrorMessagesCore, finalizationRegistrar hotstuff.FinalizationRegistrar, ) (*Engine, error) { @@ -104,7 +107,6 @@ func New( e.txErrorMessagesNotifier.Channel(), txErrorMessagesProcessedHeight, sealedBlockReader, - e.state.Params().SealedRoot().Height, e.processTxResultErrorMessagesJob, processTxErrorMessagesWorkersCount, 0, @@ -139,20 +141,18 @@ func (e *Engine) processTxResultErrorMessagesJob(ctx irrecoverable.SignalerConte e.metrics.TxErrorsFetchStarted() err = e.processErrorMessagesForBlock(ctx, header.ID()) + if err != nil { + if !errors.Is(err, context.Canceled) { + ctx.Throw(fmt.Errorf("failed to process transaction result error messages for block: %w", err)) + } + return + } // use the last processed index to ensure the metrics reflect the highest _consecutive_ height. // this makes it easier to see when downloading gets stuck at a height. e.metrics.TxErrorsFetchFinished(time.Since(start), err == nil, e.txErrorMessagesConsumer.LastProcessedIndex()) - if err == nil { - done() - return - } - - e.log.Error(). - Err(err). - Str("job_id", string(job.ID())). - Msg("error encountered while processing transaction result error messages job") + done() } // runTxResultErrorMessagesConsumer runs the txErrorMessagesConsumer component @@ -178,8 +178,9 @@ func (e *Engine) onFinalizedBlock(*model.Block) { e.txErrorMessagesNotifier.Notify() } -// processErrorMessagesForBlock processes transaction result error messages for block. -// If the process fails, it will retry, using exponential backoff. +// processErrorMessagesForBlock processes transaction result error messages for the provided block. +// This method will retry indefinitely using exponential backoff until it encounters an exception +// or the error messages are successfully fetched. // // No errors are expected during normal operation. func (e *Engine) processErrorMessagesForBlock(ctx context.Context, blockID flow.Identifier) error { @@ -195,14 +196,41 @@ func (e *Engine) processErrorMessagesForBlock(ctx context.Context, blockID flow. err := e.txErrorMessagesCore.FetchErrorMessages(ctx, blockID) if err != nil { - e.log.Debug(). - Err(err). - Str("block_id", blockID.String()). - Uint64("attempt", uint64(attempt)). - Msgf("failed to fetch transaction result error messages. will retry") + if errors.Is(err, context.Canceled) { + return err + } + if !isRetryableError(err) { + return fmt.Errorf("failed to fetch transaction result error messages: %w", err) + } + + // throttle logging to once every 20 attempts + if attempt%20 == 0 { + e.log.Warn(). + Err(err). + Str("block_id", blockID.String()). + Uint64("attempt", uint64(attempt)). + Msgf("failed to fetch transaction result error messages. will retry") + } + + attempt++ + return retry.RetryableError(err) } - attempt++ - return retry.RetryableError(err) + return nil }) } + +// isRetryableError returns true if the error is retryable. +// If this method returns false, the error is an exception and it should not be retried. +func isRetryableError(err error) bool { + // this is permissive in that it will allow any grpc status error, including those that are not + // retryable. This is OK here since the backend will send requests across multiple execution nodes + // so retrying will generally result in a new set of nodes to try. + if _, ok := status.FromError(err); ok { + return true + } + if errors.Is(err, commonrpc.ErrNoENsFoundForExecutionResult) { + return true + } + return false +} diff --git a/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go b/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go index 58ce38a3769..b01988b4846 100644 --- a/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go +++ b/engine/access/ingestion/tx_error_messages/tx_error_messages_engine_test.go @@ -2,6 +2,7 @@ package tx_error_messages import ( "context" + "fmt" "os" "sync" "testing" @@ -136,10 +137,7 @@ func (s *TxErrorMessagesEngineSuite) SetupTest() { ).Maybe() s.proto.state.On("Params").Return(s.proto.params) - - // Mock the finalized and sealed root block header with height 0. s.proto.params.On("FinalizedRoot").Return(s.rootBlock.ToHeader(), nil) - s.proto.params.On("SealedRoot").Return(s.rootBlock.ToHeader(), nil) s.proto.snapshot.On("Head").Return( func() *flow.Header { @@ -158,10 +156,8 @@ func (s *TxErrorMessagesEngineSuite) SetupTest() { // initEngine creates a new instance of the transaction error messages engine // and waits for it to start. It initializes the engine with mocked components and state. func (s *TxErrorMessagesEngineSuite) initEngine(ctx irrecoverable.SignalerContext) *Engine { - processedTxErrorMessagesBlockHeight := store.NewConsumerProgress( - s.db, - module.ConsumeProgressEngineTxErrorMessagesBlockHeight, - ) + processedTxErrorMessagesBlockHeight, err := store.NewConsumerProgress(s.db, module.ConsumeProgressEngineTxErrorMessagesBlockHeight).Initialize(s.rootBlock.Height) + require.NoError(s.T(), err) execNodeIdentitiesProvider := commonrpc.NewExecutionNodeIdentitiesProvider( s.log, @@ -209,6 +205,119 @@ func (s *TxErrorMessagesEngineSuite) initEngine(ctx irrecoverable.SignalerContex return eng } +// TestOnFinalizedBlock_NonRetryableError_Throws verifies that when the engine receives a +// non-retryable error (not a GRPC status error and not ErrNoENsFoundForExecutionResult) while +// fetching transaction result error messages, it escalates the failure via ctx.Throw rather +// than retrying indefinitely. +func (s *TxErrorMessagesEngineSuite) TestOnFinalizedBlock_NonRetryableError_Throws() { + ctx, cancel := context.WithCancel(s.ctx) + defer cancel() + + // Capture the first thrown error and cancel the engine context so it can shut down. + errCh := make(chan error, 1) + irrecoverableCtx := irrecoverable.NewMockSignalerContextWithCallback(s.T(), ctx, func(err error) { + select { + case errCh <- err: + default: + } + cancel() + }) + + s.connFactory.On("GetExecutionAPIClient", mock.Anything).Return(s.execClient, &mockCloser{}, nil).Maybe() + s.proto.snapshot.On("Identities", mock.Anything).Return(s.enNodeIDs, nil).Maybe() + s.proto.state.On("AtBlockID", mock.Anything).Return(s.proto.snapshot).Maybe() + + // Return a plain (non-GRPC) error from the EN so that isRetryableError returns false. + nonRetryableErr := fmt.Errorf("unexpected storage corruption") + + for _, b := range s.blockMap { + // Use .Maybe() on all per-block mocks since some blocks may not be processed + // before the context is cancelled after the first Throw. + receipt1 := unittest.ReceiptForBlockFixture(b) + receipt1.ExecutorID = s.enNodeIDs.NodeIDs()[0] + receipt2 := unittest.ReceiptForBlockFixture(b) + receipt2.ExecutorID = s.enNodeIDs.NodeIDs()[0] + receipt1.ExecutionResult = receipt2.ExecutionResult + receipts := flow.ExecutionReceiptList{receipt1, receipt2} + s.receipts.On("ByBlockID", b.ID()).Return( + func(flow.Identifier) flow.ExecutionReceiptList { return receipts }, nil, + ).Maybe() + + s.txErrorMessages.On("Exists", b.ID()).Return(false, nil).Maybe() + blockID := b.ID() + exeEventReq := &execproto.GetTransactionErrorMessagesByBlockIDRequest{ + BlockId: blockID[:], + } + s.execClient.On("GetTransactionErrorMessagesByBlockID", mock.Anything, exeEventReq). + Return(nil, nonRetryableErr).Maybe() + } + + _ = s.initEngine(irrecoverableCtx) + + select { + case err := <-errCh: + require.ErrorContains(s.T(), err, "failed to process transaction result error messages for block") + case <-time.After(2 * time.Second): + s.T().Fatal("expected ctx.Throw to be called within timeout") + } +} + +// TestOnFinalizedBlock_ContextCancelled_NoThrow verifies that when the context is cancelled +// during the processing of transaction error messages, the engine does NOT escalate the +// cancellation via ctx.Throw and instead shuts down gracefully. +func (s *TxErrorMessagesEngineSuite) TestOnFinalizedBlock_ContextCancelled_NoThrow() { + irrecoverableCtx, cancel := irrecoverable.NewMockSignalerContextWithCancel(s.T(), context.Background()) + + s.connFactory.On("GetExecutionAPIClient", mock.Anything).Return(s.execClient, &mockCloser{}, nil) + s.proto.snapshot.On("Identities", mock.Anything).Return(s.enNodeIDs, nil) + s.proto.state.On("AtBlockID", mock.Anything).Return(s.proto.snapshot) + + // execClientCalled is closed when the exec client is first called, + // signaling that processing is underway and context.Canceled will be returned. + execClientCalled := make(chan struct{}) + var once sync.Once + for _, b := range s.blockMap { + receipt1 := unittest.ReceiptForBlockFixture(b) + receipt1.ExecutorID = s.enNodeIDs.NodeIDs()[0] + receipt2 := unittest.ReceiptForBlockFixture(b) + receipt2.ExecutorID = s.enNodeIDs.NodeIDs()[0] + receipt1.ExecutionResult = receipt2.ExecutionResult + receipts := flow.ExecutionReceiptList{receipt1, receipt2} + + // .Maybe() is required on per-block mocks: with processTxErrorMessagesWorkersCount + // concurrent workers and the context cancelled after the first exec client call, + // not all blocks are guaranteed to be reached before shutdown. + s.receipts.On("ByBlockID", b.ID()). + Return(func(flow.Identifier) (flow.ExecutionReceiptList, error) { + return receipts, nil + }). + Maybe() + + s.txErrorMessages.On("Exists", b.ID()).Return(false, nil).Maybe() + blockID := b.ID() + exeEventReq := &execproto.GetTransactionErrorMessagesByBlockIDRequest{ + BlockId: blockID[:], + } + s.execClient.On("GetTransactionErrorMessagesByBlockID", mock.Anything, exeEventReq). + Run(func(args mock.Arguments) { + once.Do(func() { close(execClientCalled) }) + }). + Return(nil, context.Canceled). + Maybe() + } + + eng := s.initEngine(irrecoverableCtx) + + // Wait until processing has started (exec client was called at least once). + unittest.RequireCloseBefore(s.T(), execClientCalled, 2*time.Second, "expected processing to start before timeout") + + // Cancel the context to trigger graceful shutdown. + cancel() + + // Verify the engine shuts down cleanly. + unittest.RequireCloseBefore(s.T(), eng.Done(), 2*time.Second, "expected engine to stop before timeout") +} + // TestOnFinalizedBlockHandleTxErrorMessages tests the handling of transaction error messages // when a new finalized block is processed. It verifies that the engine fetches transaction // error messages from execution nodes and stores them in the database. diff --git a/engine/access/ingestion2/engine_test.go b/engine/access/ingestion2/engine_test.go index 169f8476012..78c0541f220 100644 --- a/engine/access/ingestion2/engine_test.go +++ b/engine/access/ingestion2/engine_test.go @@ -202,7 +202,8 @@ func (s *Suite) TestComponentShutdown() { // initEngineAndSyncer create new instance of ingestion engine and collection collectionSyncer. // It waits until the ingestion engine starts. func (s *Suite) initEngineAndSyncer(ctx irrecoverable.SignalerContext) (*Engine, *collections.Syncer) { - processedHeightInitializer := store.NewConsumerProgress(s.db, module.ConsumeProgressIngestionEngineBlockHeight) + processedHeight, err := store.NewConsumerProgress(s.db, module.ConsumeProgressIngestionEngineBlockHeight).Initialize(s.finalizedBlock.Height) + require.NoError(s.T(), err) lastFullBlockHeight, err := store.NewConsumerProgress(s.db, module.ConsumeProgressLastFullBlockHeight).Initialize(s.finalizedBlock.Height) require.NoError(s.T(), err) @@ -240,7 +241,7 @@ func (s *Suite) initEngineAndSyncer(ctx irrecoverable.SignalerContext) (*Engine, s.db, s.blocks, s.results, - processedHeightInitializer, + processedHeight, syncer, s.collectionExecutedMetric, ) diff --git a/engine/access/ingestion2/finalized_block_processor.go b/engine/access/ingestion2/finalized_block_processor.go index 6ae7e3da9a1..27b3dad36de 100644 --- a/engine/access/ingestion2/finalized_block_processor.go +++ b/engine/access/ingestion2/finalized_block_processor.go @@ -68,15 +68,11 @@ func NewFinalizedBlockProcessor( db storage.DB, blocks storage.Blocks, executionResults storage.ExecutionResults, - finalizedProcessedHeight storage.ConsumerProgressInitializer, + finalizedProcessedHeight storage.ConsumerProgress, syncer *collections.Syncer, collectionExecutedMetric module.CollectionExecutedMetric, ) (*FinalizedBlockProcessor, error) { reader := jobqueue.NewFinalizedBlockReader(state, blocks) - finalizedBlock, err := state.Final().Head() - if err != nil { - return nil, fmt.Errorf("could not get finalized block header: %w", err) - } consumerNotifier := engine.NewNotifier() processor := &FinalizedBlockProcessor{ @@ -90,12 +86,12 @@ func NewFinalizedBlockProcessor( collectionExecutedMetric: collectionExecutedMetric, } + var err error processor.consumer, err = jobqueue.NewComponentConsumer( log.With().Str("module", "ingestion_block_consumer").Logger(), consumerNotifier.Channel(), finalizedProcessedHeight, reader, - finalizedBlock.Height, processor.processFinalizedBlockJobCallback, finalizedBlockProcessorWorkerCount, searchAhead, diff --git a/engine/access/integration_unsecure_grpc_server_test.go b/engine/access/integration_unsecure_grpc_server_test.go index edd0c9f2f9b..847d0b50655 100644 --- a/engine/access/integration_unsecure_grpc_server_test.go +++ b/engine/access/integration_unsecure_grpc_server_test.go @@ -38,6 +38,7 @@ import ( "github.com/onflow/flow-go/module/executiondatasync/execution_data/cache" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/mempool/herocache" "github.com/onflow/flow-go/module/metrics" module "github.com/onflow/flow-go/module/mock" @@ -211,6 +212,8 @@ func (suite *SameGRPCPortTestSuite) SetupTest() { stateStreamConfig := statestreambackend.Config{} followerDistributor := pubsub.NewFollowerDistributor() + streamLimiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + suite.Require().NoError(err) // create rpc engine builder rpcEngBuilder, err := rpc.NewBuilder( suite.log, @@ -228,6 +231,8 @@ func (suite *SameGRPCPortTestSuite) SetupTest() { stateStreamConfig, nil, followerDistributor, + nil, + streamLimiter, ) assert.NoError(suite.T(), err) suite.rpcEng, err = rpcEngBuilder.WithLegacy().Build() @@ -301,6 +306,7 @@ func (suite *SameGRPCPortTestSuite) SetupTest() { suite.chainID, suite.unsecureGrpcServer, stateStreamBackend, + streamLimiter, ) assert.NoError(suite.T(), err) diff --git a/engine/access/mock/access_api_client.go b/engine/access/mock/access_api_client.go index e0365a924cf..54ed6ea8f88 100644 --- a/engine/access/mock/access_api_client.go +++ b/engine/access/mock/access_api_client.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - access "github.com/onflow/flow/protobuf/go/flow/access" - - grpc "google.golang.org/grpc" + "context" + "github.com/onflow/flow/protobuf/go/flow/access" mock "github.com/stretchr/testify/mock" + "google.golang.org/grpc" ) +// NewAccessAPIClient creates a new instance of AccessAPIClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccessAPIClient(t interface { + mock.TestingT + Cleanup(func()) +}) *AccessAPIClient { + mock := &AccessAPIClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccessAPIClient is an autogenerated mock type for the AccessAPIClient type type AccessAPIClient struct { mock.Mock } -// ExecuteScriptAtBlockHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) ExecuteScriptAtBlockHeight(ctx context.Context, in *access.ExecuteScriptAtBlockHeightRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error) { +type AccessAPIClient_Expecter struct { + mock *mock.Mock +} + +func (_m *AccessAPIClient) EXPECT() *AccessAPIClient_Expecter { + return &AccessAPIClient_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) ExecuteScriptAtBlockHeight(ctx context.Context, in *access.ExecuteScriptAtBlockHeightRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -26,7 +49,7 @@ func (_m *AccessAPIClient) ExecuteScriptAtBlockHeight(ctx context.Context, in *a var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockHeight") @@ -34,28 +57,78 @@ func (_m *AccessAPIClient) ExecuteScriptAtBlockHeight(ctx context.Context, in *a var r0 *access.ExecuteScriptResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest, ...grpc.CallOption) (*access.ExecuteScriptResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest, ...grpc.CallOption) (*access.ExecuteScriptResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest, ...grpc.CallOption) *access.ExecuteScriptResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest, ...grpc.CallOption) *access.ExecuteScriptResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecuteScriptResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *access.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error) { +// AccessAPIClient_ExecuteScriptAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockHeight' +type AccessAPIClient_ExecuteScriptAtBlockHeight_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.ExecuteScriptAtBlockHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) ExecuteScriptAtBlockHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_ExecuteScriptAtBlockHeight_Call { + return &AccessAPIClient_ExecuteScriptAtBlockHeight_Call{Call: _e.mock.On("ExecuteScriptAtBlockHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_ExecuteScriptAtBlockHeight_Call) Run(run func(ctx context.Context, in *access.ExecuteScriptAtBlockHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_ExecuteScriptAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.ExecuteScriptAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.ExecuteScriptAtBlockHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_ExecuteScriptAtBlockHeight_Call) Return(executeScriptResponse *access.ExecuteScriptResponse, err error) *AccessAPIClient_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(executeScriptResponse, err) + return _c +} + +func (_c *AccessAPIClient_ExecuteScriptAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.ExecuteScriptAtBlockHeightRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error)) *AccessAPIClient_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *access.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -63,7 +136,7 @@ func (_m *AccessAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *acces var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -71,28 +144,78 @@ func (_m *AccessAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *acces var r0 *access.ExecuteScriptResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) (*access.ExecuteScriptResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) (*access.ExecuteScriptResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) *access.ExecuteScriptResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) *access.ExecuteScriptResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecuteScriptResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtLatestBlock provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) ExecuteScriptAtLatestBlock(ctx context.Context, in *access.ExecuteScriptAtLatestBlockRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error) { +// AccessAPIClient_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type AccessAPIClient_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.ExecuteScriptAtBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) ExecuteScriptAtBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_ExecuteScriptAtBlockID_Call { + return &AccessAPIClient_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_ExecuteScriptAtBlockID_Call) Run(run func(ctx context.Context, in *access.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.ExecuteScriptAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.ExecuteScriptAtBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_ExecuteScriptAtBlockID_Call) Return(executeScriptResponse *access.ExecuteScriptResponse, err error) *AccessAPIClient_ExecuteScriptAtBlockID_Call { + _c.Call.Return(executeScriptResponse, err) + return _c +} + +func (_c *AccessAPIClient_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error)) *AccessAPIClient_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtLatestBlock provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) ExecuteScriptAtLatestBlock(ctx context.Context, in *access.ExecuteScriptAtLatestBlockRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -100,7 +223,7 @@ func (_m *AccessAPIClient) ExecuteScriptAtLatestBlock(ctx context.Context, in *a var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtLatestBlock") @@ -108,28 +231,78 @@ func (_m *AccessAPIClient) ExecuteScriptAtLatestBlock(ctx context.Context, in *a var r0 *access.ExecuteScriptResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest, ...grpc.CallOption) (*access.ExecuteScriptResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest, ...grpc.CallOption) (*access.ExecuteScriptResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest, ...grpc.CallOption) *access.ExecuteScriptResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest, ...grpc.CallOption) *access.ExecuteScriptResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecuteScriptResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccount provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccount(ctx context.Context, in *access.GetAccountRequest, opts ...grpc.CallOption) (*access.GetAccountResponse, error) { +// AccessAPIClient_ExecuteScriptAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtLatestBlock' +type AccessAPIClient_ExecuteScriptAtLatestBlock_Call struct { + *mock.Call +} + +// ExecuteScriptAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - in *access.ExecuteScriptAtLatestBlockRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) ExecuteScriptAtLatestBlock(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_ExecuteScriptAtLatestBlock_Call { + return &AccessAPIClient_ExecuteScriptAtLatestBlock_Call{Call: _e.mock.On("ExecuteScriptAtLatestBlock", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_ExecuteScriptAtLatestBlock_Call) Run(run func(ctx context.Context, in *access.ExecuteScriptAtLatestBlockRequest, opts ...grpc.CallOption)) *AccessAPIClient_ExecuteScriptAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.ExecuteScriptAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.ExecuteScriptAtLatestBlockRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_ExecuteScriptAtLatestBlock_Call) Return(executeScriptResponse *access.ExecuteScriptResponse, err error) *AccessAPIClient_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(executeScriptResponse, err) + return _c +} + +func (_c *AccessAPIClient_ExecuteScriptAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, in *access.ExecuteScriptAtLatestBlockRequest, opts ...grpc.CallOption) (*access.ExecuteScriptResponse, error)) *AccessAPIClient_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccount provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccount(ctx context.Context, in *access.GetAccountRequest, opts ...grpc.CallOption) (*access.GetAccountResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -137,7 +310,7 @@ func (_m *AccessAPIClient) GetAccount(ctx context.Context, in *access.GetAccount var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -145,28 +318,78 @@ func (_m *AccessAPIClient) GetAccount(ctx context.Context, in *access.GetAccount var r0 *access.GetAccountResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest, ...grpc.CallOption) (*access.GetAccountResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest, ...grpc.CallOption) (*access.GetAccountResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest, ...grpc.CallOption) *access.GetAccountResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest, ...grpc.CallOption) *access.GetAccountResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.GetAccountResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountAtBlockHeight(ctx context.Context, in *access.GetAccountAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountResponse, error) { +// AccessAPIClient_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type AccessAPIClient_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccount(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccount_Call { + return &AccessAPIClient_GetAccount_Call{Call: _e.mock.On("GetAccount", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccount_Call) Run(run func(ctx context.Context, in *access.GetAccountRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccount_Call) Return(getAccountResponse *access.GetAccountResponse, err error) *AccessAPIClient_GetAccount_Call { + _c.Call.Return(getAccountResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccount_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountRequest, opts ...grpc.CallOption) (*access.GetAccountResponse, error)) *AccessAPIClient_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountAtBlockHeight(ctx context.Context, in *access.GetAccountAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -174,7 +397,7 @@ func (_m *AccessAPIClient) GetAccountAtBlockHeight(ctx context.Context, in *acce var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockHeight") @@ -182,28 +405,78 @@ func (_m *AccessAPIClient) GetAccountAtBlockHeight(ctx context.Context, in *acce var r0 *access.AccountResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest, ...grpc.CallOption) *access.AccountResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest, ...grpc.CallOption) *access.AccountResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtBlockHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtBlockHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtLatestBlock provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountAtLatestBlock(ctx context.Context, in *access.GetAccountAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountResponse, error) { +// AccessAPIClient_GetAccountAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockHeight' +type AccessAPIClient_GetAccountAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountAtBlockHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountAtBlockHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountAtBlockHeight_Call { + return &AccessAPIClient_GetAccountAtBlockHeight_Call{Call: _e.mock.On("GetAccountAtBlockHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountAtBlockHeight_Call) Run(run func(ctx context.Context, in *access.GetAccountAtBlockHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountAtBlockHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountAtBlockHeight_Call) Return(accountResponse *access.AccountResponse, err error) *AccessAPIClient_GetAccountAtBlockHeight_Call { + _c.Call.Return(accountResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountResponse, error)) *AccessAPIClient_GetAccountAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtLatestBlock provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountAtLatestBlock(ctx context.Context, in *access.GetAccountAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -211,7 +484,7 @@ func (_m *AccessAPIClient) GetAccountAtLatestBlock(ctx context.Context, in *acce var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountAtLatestBlock") @@ -219,28 +492,78 @@ func (_m *AccessAPIClient) GetAccountAtLatestBlock(ctx context.Context, in *acce var r0 *access.AccountResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest, ...grpc.CallOption) *access.AccountResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest, ...grpc.CallOption) *access.AccountResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtLatestBlockRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtLatestBlockRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtBlockHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountBalanceAtBlockHeight(ctx context.Context, in *access.GetAccountBalanceAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountBalanceResponse, error) { +// AccessAPIClient_GetAccountAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtLatestBlock' +type AccessAPIClient_GetAccountAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountAtLatestBlockRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountAtLatestBlock(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountAtLatestBlock_Call { + return &AccessAPIClient_GetAccountAtLatestBlock_Call{Call: _e.mock.On("GetAccountAtLatestBlock", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountAtLatestBlock_Call) Run(run func(ctx context.Context, in *access.GetAccountAtLatestBlockRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountAtLatestBlockRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountAtLatestBlock_Call) Return(accountResponse *access.AccountResponse, err error) *AccessAPIClient_GetAccountAtLatestBlock_Call { + _c.Call.Return(accountResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountResponse, error)) *AccessAPIClient_GetAccountAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtBlockHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountBalanceAtBlockHeight(ctx context.Context, in *access.GetAccountBalanceAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountBalanceResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -248,7 +571,7 @@ func (_m *AccessAPIClient) GetAccountBalanceAtBlockHeight(ctx context.Context, i var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtBlockHeight") @@ -256,28 +579,78 @@ func (_m *AccessAPIClient) GetAccountBalanceAtBlockHeight(ctx context.Context, i var r0 *access.AccountBalanceResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountBalanceResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountBalanceResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest, ...grpc.CallOption) *access.AccountBalanceResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest, ...grpc.CallOption) *access.AccountBalanceResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountBalanceResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtLatestBlock provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountBalanceAtLatestBlock(ctx context.Context, in *access.GetAccountBalanceAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountBalanceResponse, error) { +// AccessAPIClient_GetAccountBalanceAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtBlockHeight' +type AccessAPIClient_GetAccountBalanceAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountBalanceAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountBalanceAtBlockHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountBalanceAtBlockHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountBalanceAtBlockHeight_Call { + return &AccessAPIClient_GetAccountBalanceAtBlockHeight_Call{Call: _e.mock.On("GetAccountBalanceAtBlockHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountBalanceAtBlockHeight_Call) Run(run func(ctx context.Context, in *access.GetAccountBalanceAtBlockHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountBalanceAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountBalanceAtBlockHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountBalanceAtBlockHeight_Call) Return(accountBalanceResponse *access.AccountBalanceResponse, err error) *AccessAPIClient_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(accountBalanceResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountBalanceAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountBalanceAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountBalanceResponse, error)) *AccessAPIClient_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtLatestBlock provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountBalanceAtLatestBlock(ctx context.Context, in *access.GetAccountBalanceAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountBalanceResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -285,7 +658,7 @@ func (_m *AccessAPIClient) GetAccountBalanceAtLatestBlock(ctx context.Context, i var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtLatestBlock") @@ -293,28 +666,78 @@ func (_m *AccessAPIClient) GetAccountBalanceAtLatestBlock(ctx context.Context, i var r0 *access.AccountBalanceResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountBalanceResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountBalanceResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest, ...grpc.CallOption) *access.AccountBalanceResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest, ...grpc.CallOption) *access.AccountBalanceResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountBalanceResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtBlockHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountKeyAtBlockHeight(ctx context.Context, in *access.GetAccountKeyAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountKeyResponse, error) { +// AccessAPIClient_GetAccountBalanceAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtLatestBlock' +type AccessAPIClient_GetAccountBalanceAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountBalanceAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountBalanceAtLatestBlockRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountBalanceAtLatestBlock(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountBalanceAtLatestBlock_Call { + return &AccessAPIClient_GetAccountBalanceAtLatestBlock_Call{Call: _e.mock.On("GetAccountBalanceAtLatestBlock", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountBalanceAtLatestBlock_Call) Run(run func(ctx context.Context, in *access.GetAccountBalanceAtLatestBlockRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountBalanceAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountBalanceAtLatestBlockRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountBalanceAtLatestBlock_Call) Return(accountBalanceResponse *access.AccountBalanceResponse, err error) *AccessAPIClient_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(accountBalanceResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountBalanceAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountBalanceAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountBalanceResponse, error)) *AccessAPIClient_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtBlockHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountKeyAtBlockHeight(ctx context.Context, in *access.GetAccountKeyAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountKeyResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -322,7 +745,7 @@ func (_m *AccessAPIClient) GetAccountKeyAtBlockHeight(ctx context.Context, in *a var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtBlockHeight") @@ -330,28 +753,78 @@ func (_m *AccessAPIClient) GetAccountKeyAtBlockHeight(ctx context.Context, in *a var r0 *access.AccountKeyResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountKeyResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountKeyResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest, ...grpc.CallOption) *access.AccountKeyResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest, ...grpc.CallOption) *access.AccountKeyResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeyResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtLatestBlock provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountKeyAtLatestBlock(ctx context.Context, in *access.GetAccountKeyAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountKeyResponse, error) { +// AccessAPIClient_GetAccountKeyAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtBlockHeight' +type AccessAPIClient_GetAccountKeyAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeyAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountKeyAtBlockHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountKeyAtBlockHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountKeyAtBlockHeight_Call { + return &AccessAPIClient_GetAccountKeyAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeyAtBlockHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountKeyAtBlockHeight_Call) Run(run func(ctx context.Context, in *access.GetAccountKeyAtBlockHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountKeyAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeyAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeyAtBlockHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeyAtBlockHeight_Call) Return(accountKeyResponse *access.AccountKeyResponse, err error) *AccessAPIClient_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(accountKeyResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeyAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountKeyAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountKeyResponse, error)) *AccessAPIClient_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtLatestBlock provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountKeyAtLatestBlock(ctx context.Context, in *access.GetAccountKeyAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountKeyResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -359,7 +832,7 @@ func (_m *AccessAPIClient) GetAccountKeyAtLatestBlock(ctx context.Context, in *a var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtLatestBlock") @@ -367,28 +840,78 @@ func (_m *AccessAPIClient) GetAccountKeyAtLatestBlock(ctx context.Context, in *a var r0 *access.AccountKeyResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountKeyResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountKeyResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest, ...grpc.CallOption) *access.AccountKeyResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest, ...grpc.CallOption) *access.AccountKeyResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeyResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtBlockHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountKeysAtBlockHeight(ctx context.Context, in *access.GetAccountKeysAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountKeysResponse, error) { +// AccessAPIClient_GetAccountKeyAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtLatestBlock' +type AccessAPIClient_GetAccountKeyAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeyAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountKeyAtLatestBlockRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountKeyAtLatestBlock(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountKeyAtLatestBlock_Call { + return &AccessAPIClient_GetAccountKeyAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeyAtLatestBlock", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountKeyAtLatestBlock_Call) Run(run func(ctx context.Context, in *access.GetAccountKeyAtLatestBlockRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountKeyAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeyAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeyAtLatestBlockRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeyAtLatestBlock_Call) Return(accountKeyResponse *access.AccountKeyResponse, err error) *AccessAPIClient_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(accountKeyResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeyAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountKeyAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountKeyResponse, error)) *AccessAPIClient_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtBlockHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountKeysAtBlockHeight(ctx context.Context, in *access.GetAccountKeysAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountKeysResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -396,7 +919,7 @@ func (_m *AccessAPIClient) GetAccountKeysAtBlockHeight(ctx context.Context, in * var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtBlockHeight") @@ -404,28 +927,78 @@ func (_m *AccessAPIClient) GetAccountKeysAtBlockHeight(ctx context.Context, in * var r0 *access.AccountKeysResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountKeysResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest, ...grpc.CallOption) (*access.AccountKeysResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest, ...grpc.CallOption) *access.AccountKeysResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest, ...grpc.CallOption) *access.AccountKeysResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeysResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtLatestBlock provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetAccountKeysAtLatestBlock(ctx context.Context, in *access.GetAccountKeysAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountKeysResponse, error) { +// AccessAPIClient_GetAccountKeysAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtBlockHeight' +type AccessAPIClient_GetAccountKeysAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeysAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountKeysAtBlockHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountKeysAtBlockHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountKeysAtBlockHeight_Call { + return &AccessAPIClient_GetAccountKeysAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeysAtBlockHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountKeysAtBlockHeight_Call) Run(run func(ctx context.Context, in *access.GetAccountKeysAtBlockHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountKeysAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeysAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeysAtBlockHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeysAtBlockHeight_Call) Return(accountKeysResponse *access.AccountKeysResponse, err error) *AccessAPIClient_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(accountKeysResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeysAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountKeysAtBlockHeightRequest, opts ...grpc.CallOption) (*access.AccountKeysResponse, error)) *AccessAPIClient_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtLatestBlock provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetAccountKeysAtLatestBlock(ctx context.Context, in *access.GetAccountKeysAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountKeysResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -433,7 +1006,7 @@ func (_m *AccessAPIClient) GetAccountKeysAtLatestBlock(ctx context.Context, in * var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtLatestBlock") @@ -441,28 +1014,78 @@ func (_m *AccessAPIClient) GetAccountKeysAtLatestBlock(ctx context.Context, in * var r0 *access.AccountKeysResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountKeysResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest, ...grpc.CallOption) (*access.AccountKeysResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest, ...grpc.CallOption) *access.AccountKeysResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest, ...grpc.CallOption) *access.AccountKeysResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeysResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockByHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetBlockByHeight(ctx context.Context, in *access.GetBlockByHeightRequest, opts ...grpc.CallOption) (*access.BlockResponse, error) { +// AccessAPIClient_GetAccountKeysAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtLatestBlock' +type AccessAPIClient_GetAccountKeysAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeysAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetAccountKeysAtLatestBlockRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetAccountKeysAtLatestBlock(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetAccountKeysAtLatestBlock_Call { + return &AccessAPIClient_GetAccountKeysAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeysAtLatestBlock", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetAccountKeysAtLatestBlock_Call) Run(run func(ctx context.Context, in *access.GetAccountKeysAtLatestBlockRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetAccountKeysAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeysAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeysAtLatestBlockRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeysAtLatestBlock_Call) Return(accountKeysResponse *access.AccountKeysResponse, err error) *AccessAPIClient_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(accountKeysResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetAccountKeysAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, in *access.GetAccountKeysAtLatestBlockRequest, opts ...grpc.CallOption) (*access.AccountKeysResponse, error)) *AccessAPIClient_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetBlockByHeight(ctx context.Context, in *access.GetBlockByHeightRequest, opts ...grpc.CallOption) (*access.BlockResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -470,7 +1093,7 @@ func (_m *AccessAPIClient) GetBlockByHeight(ctx context.Context, in *access.GetB var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetBlockByHeight") @@ -478,28 +1101,78 @@ func (_m *AccessAPIClient) GetBlockByHeight(ctx context.Context, in *access.GetB var r0 *access.BlockResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest, ...grpc.CallOption) (*access.BlockResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest, ...grpc.CallOption) (*access.BlockResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest, ...grpc.CallOption) *access.BlockResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest, ...grpc.CallOption) *access.BlockResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockByHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockByHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockByID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetBlockByID(ctx context.Context, in *access.GetBlockByIDRequest, opts ...grpc.CallOption) (*access.BlockResponse, error) { +// AccessAPIClient_GetBlockByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByHeight' +type AccessAPIClient_GetBlockByHeight_Call struct { + *mock.Call +} + +// GetBlockByHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetBlockByHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetBlockByHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetBlockByHeight_Call { + return &AccessAPIClient_GetBlockByHeight_Call{Call: _e.mock.On("GetBlockByHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetBlockByHeight_Call) Run(run func(ctx context.Context, in *access.GetBlockByHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetBlockByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockByHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockByHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetBlockByHeight_Call) Return(blockResponse *access.BlockResponse, err error) *AccessAPIClient_GetBlockByHeight_Call { + _c.Call.Return(blockResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetBlockByHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.GetBlockByHeightRequest, opts ...grpc.CallOption) (*access.BlockResponse, error)) *AccessAPIClient_GetBlockByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetBlockByID(ctx context.Context, in *access.GetBlockByIDRequest, opts ...grpc.CallOption) (*access.BlockResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -507,7 +1180,7 @@ func (_m *AccessAPIClient) GetBlockByID(ctx context.Context, in *access.GetBlock var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetBlockByID") @@ -515,28 +1188,78 @@ func (_m *AccessAPIClient) GetBlockByID(ctx context.Context, in *access.GetBlock var r0 *access.BlockResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest, ...grpc.CallOption) (*access.BlockResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest, ...grpc.CallOption) (*access.BlockResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest, ...grpc.CallOption) *access.BlockResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest, ...grpc.CallOption) *access.BlockResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockByIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockByIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetBlockHeaderByHeight(ctx context.Context, in *access.GetBlockHeaderByHeightRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error) { +// AccessAPIClient_GetBlockByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByID' +type AccessAPIClient_GetBlockByID_Call struct { + *mock.Call +} + +// GetBlockByID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetBlockByIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetBlockByID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetBlockByID_Call { + return &AccessAPIClient_GetBlockByID_Call{Call: _e.mock.On("GetBlockByID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetBlockByID_Call) Run(run func(ctx context.Context, in *access.GetBlockByIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetBlockByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockByIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetBlockByID_Call) Return(blockResponse *access.BlockResponse, err error) *AccessAPIClient_GetBlockByID_Call { + _c.Call.Return(blockResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetBlockByID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetBlockByIDRequest, opts ...grpc.CallOption) (*access.BlockResponse, error)) *AccessAPIClient_GetBlockByID_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetBlockHeaderByHeight(ctx context.Context, in *access.GetBlockHeaderByHeightRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -544,7 +1267,7 @@ func (_m *AccessAPIClient) GetBlockHeaderByHeight(ctx context.Context, in *acces var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByHeight") @@ -552,28 +1275,78 @@ func (_m *AccessAPIClient) GetBlockHeaderByHeight(ctx context.Context, in *acces var r0 *access.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest, ...grpc.CallOption) (*access.BlockHeaderResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest, ...grpc.CallOption) (*access.BlockHeaderResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest, ...grpc.CallOption) *access.BlockHeaderResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest, ...grpc.CallOption) *access.BlockHeaderResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetBlockHeaderByID(ctx context.Context, in *access.GetBlockHeaderByIDRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error) { +// AccessAPIClient_GetBlockHeaderByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByHeight' +type AccessAPIClient_GetBlockHeaderByHeight_Call struct { + *mock.Call +} + +// GetBlockHeaderByHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetBlockHeaderByHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetBlockHeaderByHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetBlockHeaderByHeight_Call { + return &AccessAPIClient_GetBlockHeaderByHeight_Call{Call: _e.mock.On("GetBlockHeaderByHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetBlockHeaderByHeight_Call) Run(run func(ctx context.Context, in *access.GetBlockHeaderByHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetBlockHeaderByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockHeaderByHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockHeaderByHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetBlockHeaderByHeight_Call) Return(blockHeaderResponse *access.BlockHeaderResponse, err error) *AccessAPIClient_GetBlockHeaderByHeight_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetBlockHeaderByHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.GetBlockHeaderByHeightRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error)) *AccessAPIClient_GetBlockHeaderByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetBlockHeaderByID(ctx context.Context, in *access.GetBlockHeaderByIDRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -581,7 +1354,7 @@ func (_m *AccessAPIClient) GetBlockHeaderByID(ctx context.Context, in *access.Ge var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByID") @@ -589,65 +1362,165 @@ func (_m *AccessAPIClient) GetBlockHeaderByID(ctx context.Context, in *access.Ge var r0 *access.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest, ...grpc.CallOption) (*access.BlockHeaderResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest, ...grpc.CallOption) (*access.BlockHeaderResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest, ...grpc.CallOption) *access.BlockHeaderResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest, ...grpc.CallOption) *access.BlockHeaderResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCollectionByID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetCollectionByID(ctx context.Context, in *access.GetCollectionByIDRequest, opts ...grpc.CallOption) (*access.CollectionResponse, error) { - _va := make([]interface{}, len(opts)) - for _i := range opts { - _va[_i] = opts[_i] - } - var _ca []interface{} - _ca = append(_ca, ctx, in) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) +// AccessAPIClient_GetBlockHeaderByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByID' +type AccessAPIClient_GetBlockHeaderByID_Call struct { + *mock.Call +} - if len(ret) == 0 { +// GetBlockHeaderByID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetBlockHeaderByIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetBlockHeaderByID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetBlockHeaderByID_Call { + return &AccessAPIClient_GetBlockHeaderByID_Call{Call: _e.mock.On("GetBlockHeaderByID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetBlockHeaderByID_Call) Run(run func(ctx context.Context, in *access.GetBlockHeaderByIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetBlockHeaderByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockHeaderByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockHeaderByIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetBlockHeaderByID_Call) Return(blockHeaderResponse *access.BlockHeaderResponse, err error) *AccessAPIClient_GetBlockHeaderByID_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetBlockHeaderByID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetBlockHeaderByIDRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error)) *AccessAPIClient_GetBlockHeaderByID_Call { + _c.Call.Return(run) + return _c +} + +// GetCollectionByID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetCollectionByID(ctx context.Context, in *access.GetCollectionByIDRequest, opts ...grpc.CallOption) (*access.CollectionResponse, error) { + // grpc.CallOption + _va := make([]interface{}, len(opts)) + for _i := range opts { + _va[_i] = opts[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, in) + _ca = append(_ca, _va...) + ret := _mock.Called(_ca...) + + if len(ret) == 0 { panic("no return value specified for GetCollectionByID") } var r0 *access.CollectionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest, ...grpc.CallOption) (*access.CollectionResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest, ...grpc.CallOption) (*access.CollectionResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest, ...grpc.CallOption) *access.CollectionResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest, ...grpc.CallOption) *access.CollectionResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.CollectionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetCollectionByIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetCollectionByIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForBlockIDs provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetEventsForBlockIDs(ctx context.Context, in *access.GetEventsForBlockIDsRequest, opts ...grpc.CallOption) (*access.EventsResponse, error) { +// AccessAPIClient_GetCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCollectionByID' +type AccessAPIClient_GetCollectionByID_Call struct { + *mock.Call +} + +// GetCollectionByID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetCollectionByIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetCollectionByID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetCollectionByID_Call { + return &AccessAPIClient_GetCollectionByID_Call{Call: _e.mock.On("GetCollectionByID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetCollectionByID_Call) Run(run func(ctx context.Context, in *access.GetCollectionByIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetCollectionByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetCollectionByIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetCollectionByID_Call) Return(collectionResponse *access.CollectionResponse, err error) *AccessAPIClient_GetCollectionByID_Call { + _c.Call.Return(collectionResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetCollectionByID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetCollectionByIDRequest, opts ...grpc.CallOption) (*access.CollectionResponse, error)) *AccessAPIClient_GetCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForBlockIDs provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetEventsForBlockIDs(ctx context.Context, in *access.GetEventsForBlockIDsRequest, opts ...grpc.CallOption) (*access.EventsResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -655,7 +1528,7 @@ func (_m *AccessAPIClient) GetEventsForBlockIDs(ctx context.Context, in *access. var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetEventsForBlockIDs") @@ -663,28 +1536,78 @@ func (_m *AccessAPIClient) GetEventsForBlockIDs(ctx context.Context, in *access. var r0 *access.EventsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest, ...grpc.CallOption) (*access.EventsResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest, ...grpc.CallOption) (*access.EventsResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest, ...grpc.CallOption) *access.EventsResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest, ...grpc.CallOption) *access.EventsResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.EventsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetEventsForBlockIDsRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetEventsForBlockIDsRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForHeightRange provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetEventsForHeightRange(ctx context.Context, in *access.GetEventsForHeightRangeRequest, opts ...grpc.CallOption) (*access.EventsResponse, error) { +// AccessAPIClient_GetEventsForBlockIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForBlockIDs' +type AccessAPIClient_GetEventsForBlockIDs_Call struct { + *mock.Call +} + +// GetEventsForBlockIDs is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetEventsForBlockIDsRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetEventsForBlockIDs(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetEventsForBlockIDs_Call { + return &AccessAPIClient_GetEventsForBlockIDs_Call{Call: _e.mock.On("GetEventsForBlockIDs", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetEventsForBlockIDs_Call) Run(run func(ctx context.Context, in *access.GetEventsForBlockIDsRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetEventsForBlockIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetEventsForBlockIDsRequest + if args[1] != nil { + arg1 = args[1].(*access.GetEventsForBlockIDsRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetEventsForBlockIDs_Call) Return(eventsResponse *access.EventsResponse, err error) *AccessAPIClient_GetEventsForBlockIDs_Call { + _c.Call.Return(eventsResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetEventsForBlockIDs_Call) RunAndReturn(run func(ctx context.Context, in *access.GetEventsForBlockIDsRequest, opts ...grpc.CallOption) (*access.EventsResponse, error)) *AccessAPIClient_GetEventsForBlockIDs_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForHeightRange provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetEventsForHeightRange(ctx context.Context, in *access.GetEventsForHeightRangeRequest, opts ...grpc.CallOption) (*access.EventsResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -692,7 +1615,7 @@ func (_m *AccessAPIClient) GetEventsForHeightRange(ctx context.Context, in *acce var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetEventsForHeightRange") @@ -700,28 +1623,252 @@ func (_m *AccessAPIClient) GetEventsForHeightRange(ctx context.Context, in *acce var r0 *access.EventsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest, ...grpc.CallOption) (*access.EventsResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest, ...grpc.CallOption) (*access.EventsResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest, ...grpc.CallOption) *access.EventsResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest, ...grpc.CallOption) *access.EventsResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.EventsResponse) } } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetEventsForHeightRangeRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccessAPIClient_GetEventsForHeightRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForHeightRange' +type AccessAPIClient_GetEventsForHeightRange_Call struct { + *mock.Call +} + +// GetEventsForHeightRange is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetEventsForHeightRangeRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetEventsForHeightRange(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetEventsForHeightRange_Call { + return &AccessAPIClient_GetEventsForHeightRange_Call{Call: _e.mock.On("GetEventsForHeightRange", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetEventsForHeightRange_Call) Run(run func(ctx context.Context, in *access.GetEventsForHeightRangeRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetEventsForHeightRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetEventsForHeightRangeRequest + if args[1] != nil { + arg1 = args[1].(*access.GetEventsForHeightRangeRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetEventsForHeightRange_Call) Return(eventsResponse *access.EventsResponse, err error) *AccessAPIClient_GetEventsForHeightRange_Call { + _c.Call.Return(eventsResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetEventsForHeightRange_Call) RunAndReturn(run func(ctx context.Context, in *access.GetEventsForHeightRangeRequest, opts ...grpc.CallOption) (*access.EventsResponse, error)) *AccessAPIClient_GetEventsForHeightRange_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionReceiptsByBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetExecutionReceiptsByBlockID(ctx context.Context, in *access.GetExecutionReceiptsByBlockIDRequest, opts ...grpc.CallOption) (*access.ExecutionReceiptsResponse, error) { + // grpc.CallOption + _va := make([]interface{}, len(opts)) + for _i := range opts { + _va[_i] = opts[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, in) + _ca = append(_ca, _va...) + ret := _mock.Called(_ca...) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByBlockID") + } - if rf, ok := ret.Get(1).(func(context.Context, *access.GetEventsForHeightRangeRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + var r0 *access.ExecutionReceiptsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByBlockIDRequest, ...grpc.CallOption) (*access.ExecutionReceiptsResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByBlockIDRequest, ...grpc.CallOption) *access.ExecutionReceiptsResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ExecutionReceiptsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionReceiptsByBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } + return r0, r1 +} + +// AccessAPIClient_GetExecutionReceiptsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByBlockID' +type AccessAPIClient_GetExecutionReceiptsByBlockID_Call struct { + *mock.Call +} +// GetExecutionReceiptsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetExecutionReceiptsByBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetExecutionReceiptsByBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetExecutionReceiptsByBlockID_Call { + return &AccessAPIClient_GetExecutionReceiptsByBlockID_Call{Call: _e.mock.On("GetExecutionReceiptsByBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetExecutionReceiptsByBlockID_Call) Run(run func(ctx context.Context, in *access.GetExecutionReceiptsByBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetExecutionReceiptsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionReceiptsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionReceiptsByBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetExecutionReceiptsByBlockID_Call) Return(executionReceiptsResponse *access.ExecutionReceiptsResponse, err error) *AccessAPIClient_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(executionReceiptsResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetExecutionReceiptsByBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetExecutionReceiptsByBlockIDRequest, opts ...grpc.CallOption) (*access.ExecutionReceiptsResponse, error)) *AccessAPIClient_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionReceiptsByResultID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetExecutionReceiptsByResultID(ctx context.Context, in *access.GetExecutionReceiptsByResultIDRequest, opts ...grpc.CallOption) (*access.ExecutionReceiptsResponse, error) { + // grpc.CallOption + _va := make([]interface{}, len(opts)) + for _i := range opts { + _va[_i] = opts[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, in) + _ca = append(_ca, _va...) + ret := _mock.Called(_ca...) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByResultID") + } + + var r0 *access.ExecutionReceiptsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByResultIDRequest, ...grpc.CallOption) (*access.ExecutionReceiptsResponse, error)); ok { + return returnFunc(ctx, in, opts...) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByResultIDRequest, ...grpc.CallOption) *access.ExecutionReceiptsResponse); ok { + r0 = returnFunc(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ExecutionReceiptsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionReceiptsByResultIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } return r0, r1 } -// GetExecutionResultByID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetExecutionResultByID(ctx context.Context, in *access.GetExecutionResultByIDRequest, opts ...grpc.CallOption) (*access.ExecutionResultByIDResponse, error) { +// AccessAPIClient_GetExecutionReceiptsByResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByResultID' +type AccessAPIClient_GetExecutionReceiptsByResultID_Call struct { + *mock.Call +} + +// GetExecutionReceiptsByResultID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetExecutionReceiptsByResultIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetExecutionReceiptsByResultID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetExecutionReceiptsByResultID_Call { + return &AccessAPIClient_GetExecutionReceiptsByResultID_Call{Call: _e.mock.On("GetExecutionReceiptsByResultID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetExecutionReceiptsByResultID_Call) Run(run func(ctx context.Context, in *access.GetExecutionReceiptsByResultIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetExecutionReceiptsByResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionReceiptsByResultIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionReceiptsByResultIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetExecutionReceiptsByResultID_Call) Return(executionReceiptsResponse *access.ExecutionReceiptsResponse, err error) *AccessAPIClient_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(executionReceiptsResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetExecutionReceiptsByResultID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetExecutionReceiptsByResultIDRequest, opts ...grpc.CallOption) (*access.ExecutionReceiptsResponse, error)) *AccessAPIClient_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultByID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetExecutionResultByID(ctx context.Context, in *access.GetExecutionResultByIDRequest, opts ...grpc.CallOption) (*access.ExecutionResultByIDResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -729,7 +1876,7 @@ func (_m *AccessAPIClient) GetExecutionResultByID(ctx context.Context, in *acces var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetExecutionResultByID") @@ -737,28 +1884,78 @@ func (_m *AccessAPIClient) GetExecutionResultByID(ctx context.Context, in *acces var r0 *access.ExecutionResultByIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest, ...grpc.CallOption) (*access.ExecutionResultByIDResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest, ...grpc.CallOption) (*access.ExecutionResultByIDResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest, ...grpc.CallOption) *access.ExecutionResultByIDResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest, ...grpc.CallOption) *access.ExecutionResultByIDResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecutionResultByIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultByIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultByIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionResultForBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetExecutionResultForBlockID(ctx context.Context, in *access.GetExecutionResultForBlockIDRequest, opts ...grpc.CallOption) (*access.ExecutionResultForBlockIDResponse, error) { +// AccessAPIClient_GetExecutionResultByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultByID' +type AccessAPIClient_GetExecutionResultByID_Call struct { + *mock.Call +} + +// GetExecutionResultByID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetExecutionResultByIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetExecutionResultByID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetExecutionResultByID_Call { + return &AccessAPIClient_GetExecutionResultByID_Call{Call: _e.mock.On("GetExecutionResultByID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetExecutionResultByID_Call) Run(run func(ctx context.Context, in *access.GetExecutionResultByIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetExecutionResultByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionResultByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionResultByIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetExecutionResultByID_Call) Return(executionResultByIDResponse *access.ExecutionResultByIDResponse, err error) *AccessAPIClient_GetExecutionResultByID_Call { + _c.Call.Return(executionResultByIDResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetExecutionResultByID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetExecutionResultByIDRequest, opts ...grpc.CallOption) (*access.ExecutionResultByIDResponse, error)) *AccessAPIClient_GetExecutionResultByID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultForBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetExecutionResultForBlockID(ctx context.Context, in *access.GetExecutionResultForBlockIDRequest, opts ...grpc.CallOption) (*access.ExecutionResultForBlockIDResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -766,7 +1963,7 @@ func (_m *AccessAPIClient) GetExecutionResultForBlockID(ctx context.Context, in var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetExecutionResultForBlockID") @@ -774,28 +1971,78 @@ func (_m *AccessAPIClient) GetExecutionResultForBlockID(ctx context.Context, in var r0 *access.ExecutionResultForBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest, ...grpc.CallOption) (*access.ExecutionResultForBlockIDResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest, ...grpc.CallOption) (*access.ExecutionResultForBlockIDResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest, ...grpc.CallOption) *access.ExecutionResultForBlockIDResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest, ...grpc.CallOption) *access.ExecutionResultForBlockIDResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecutionResultForBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultForBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultForBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetFullCollectionByID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetFullCollectionByID(ctx context.Context, in *access.GetFullCollectionByIDRequest, opts ...grpc.CallOption) (*access.FullCollectionResponse, error) { +// AccessAPIClient_GetExecutionResultForBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultForBlockID' +type AccessAPIClient_GetExecutionResultForBlockID_Call struct { + *mock.Call +} + +// GetExecutionResultForBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetExecutionResultForBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetExecutionResultForBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetExecutionResultForBlockID_Call { + return &AccessAPIClient_GetExecutionResultForBlockID_Call{Call: _e.mock.On("GetExecutionResultForBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetExecutionResultForBlockID_Call) Run(run func(ctx context.Context, in *access.GetExecutionResultForBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetExecutionResultForBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionResultForBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionResultForBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetExecutionResultForBlockID_Call) Return(executionResultForBlockIDResponse *access.ExecutionResultForBlockIDResponse, err error) *AccessAPIClient_GetExecutionResultForBlockID_Call { + _c.Call.Return(executionResultForBlockIDResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetExecutionResultForBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetExecutionResultForBlockIDRequest, opts ...grpc.CallOption) (*access.ExecutionResultForBlockIDResponse, error)) *AccessAPIClient_GetExecutionResultForBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetFullCollectionByID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetFullCollectionByID(ctx context.Context, in *access.GetFullCollectionByIDRequest, opts ...grpc.CallOption) (*access.FullCollectionResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -803,7 +2050,7 @@ func (_m *AccessAPIClient) GetFullCollectionByID(ctx context.Context, in *access var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetFullCollectionByID") @@ -811,28 +2058,78 @@ func (_m *AccessAPIClient) GetFullCollectionByID(ctx context.Context, in *access var r0 *access.FullCollectionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest, ...grpc.CallOption) (*access.FullCollectionResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest, ...grpc.CallOption) (*access.FullCollectionResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest, ...grpc.CallOption) *access.FullCollectionResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest, ...grpc.CallOption) *access.FullCollectionResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.FullCollectionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetFullCollectionByIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetFullCollectionByIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlock provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetLatestBlock(ctx context.Context, in *access.GetLatestBlockRequest, opts ...grpc.CallOption) (*access.BlockResponse, error) { +// AccessAPIClient_GetFullCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFullCollectionByID' +type AccessAPIClient_GetFullCollectionByID_Call struct { + *mock.Call +} + +// GetFullCollectionByID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetFullCollectionByIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetFullCollectionByID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetFullCollectionByID_Call { + return &AccessAPIClient_GetFullCollectionByID_Call{Call: _e.mock.On("GetFullCollectionByID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetFullCollectionByID_Call) Run(run func(ctx context.Context, in *access.GetFullCollectionByIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetFullCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetFullCollectionByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetFullCollectionByIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetFullCollectionByID_Call) Return(fullCollectionResponse *access.FullCollectionResponse, err error) *AccessAPIClient_GetFullCollectionByID_Call { + _c.Call.Return(fullCollectionResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetFullCollectionByID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetFullCollectionByIDRequest, opts ...grpc.CallOption) (*access.FullCollectionResponse, error)) *AccessAPIClient_GetFullCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlock provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetLatestBlock(ctx context.Context, in *access.GetLatestBlockRequest, opts ...grpc.CallOption) (*access.BlockResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -840,7 +2137,7 @@ func (_m *AccessAPIClient) GetLatestBlock(ctx context.Context, in *access.GetLat var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetLatestBlock") @@ -848,28 +2145,78 @@ func (_m *AccessAPIClient) GetLatestBlock(ctx context.Context, in *access.GetLat var r0 *access.BlockResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest, ...grpc.CallOption) (*access.BlockResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest, ...grpc.CallOption) (*access.BlockResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest, ...grpc.CallOption) *access.BlockResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest, ...grpc.CallOption) *access.BlockResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlockHeader provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetLatestBlockHeader(ctx context.Context, in *access.GetLatestBlockHeaderRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error) { +// AccessAPIClient_GetLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlock' +type AccessAPIClient_GetLatestBlock_Call struct { + *mock.Call +} + +// GetLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetLatestBlockRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetLatestBlock(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetLatestBlock_Call { + return &AccessAPIClient_GetLatestBlock_Call{Call: _e.mock.On("GetLatestBlock", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetLatestBlock_Call) Run(run func(ctx context.Context, in *access.GetLatestBlockRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetLatestBlockRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetLatestBlock_Call) Return(blockResponse *access.BlockResponse, err error) *AccessAPIClient_GetLatestBlock_Call { + _c.Call.Return(blockResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetLatestBlock_Call) RunAndReturn(run func(ctx context.Context, in *access.GetLatestBlockRequest, opts ...grpc.CallOption) (*access.BlockResponse, error)) *AccessAPIClient_GetLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlockHeader provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetLatestBlockHeader(ctx context.Context, in *access.GetLatestBlockHeaderRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -877,7 +2224,7 @@ func (_m *AccessAPIClient) GetLatestBlockHeader(ctx context.Context, in *access. var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetLatestBlockHeader") @@ -885,28 +2232,78 @@ func (_m *AccessAPIClient) GetLatestBlockHeader(ctx context.Context, in *access. var r0 *access.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest, ...grpc.CallOption) (*access.BlockHeaderResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest, ...grpc.CallOption) (*access.BlockHeaderResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest, ...grpc.CallOption) *access.BlockHeaderResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest, ...grpc.CallOption) *access.BlockHeaderResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockHeaderRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockHeaderRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestProtocolStateSnapshot provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetLatestProtocolStateSnapshot(ctx context.Context, in *access.GetLatestProtocolStateSnapshotRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error) { +// AccessAPIClient_GetLatestBlockHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlockHeader' +type AccessAPIClient_GetLatestBlockHeader_Call struct { + *mock.Call +} + +// GetLatestBlockHeader is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetLatestBlockHeaderRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetLatestBlockHeader(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetLatestBlockHeader_Call { + return &AccessAPIClient_GetLatestBlockHeader_Call{Call: _e.mock.On("GetLatestBlockHeader", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetLatestBlockHeader_Call) Run(run func(ctx context.Context, in *access.GetLatestBlockHeaderRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetLatestBlockHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetLatestBlockHeaderRequest + if args[1] != nil { + arg1 = args[1].(*access.GetLatestBlockHeaderRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetLatestBlockHeader_Call) Return(blockHeaderResponse *access.BlockHeaderResponse, err error) *AccessAPIClient_GetLatestBlockHeader_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetLatestBlockHeader_Call) RunAndReturn(run func(ctx context.Context, in *access.GetLatestBlockHeaderRequest, opts ...grpc.CallOption) (*access.BlockHeaderResponse, error)) *AccessAPIClient_GetLatestBlockHeader_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestProtocolStateSnapshot provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetLatestProtocolStateSnapshot(ctx context.Context, in *access.GetLatestProtocolStateSnapshotRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -914,7 +2311,7 @@ func (_m *AccessAPIClient) GetLatestProtocolStateSnapshot(ctx context.Context, i var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetLatestProtocolStateSnapshot") @@ -922,28 +2319,78 @@ func (_m *AccessAPIClient) GetLatestProtocolStateSnapshot(ctx context.Context, i var r0 *access.ProtocolStateSnapshotResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest, ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest, ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest, ...grpc.CallOption) *access.ProtocolStateSnapshotResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest, ...grpc.CallOption) *access.ProtocolStateSnapshotResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ProtocolStateSnapshotResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetNetworkParameters provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetNetworkParameters(ctx context.Context, in *access.GetNetworkParametersRequest, opts ...grpc.CallOption) (*access.GetNetworkParametersResponse, error) { +// AccessAPIClient_GetLatestProtocolStateSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestProtocolStateSnapshot' +type AccessAPIClient_GetLatestProtocolStateSnapshot_Call struct { + *mock.Call +} + +// GetLatestProtocolStateSnapshot is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetLatestProtocolStateSnapshotRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetLatestProtocolStateSnapshot(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetLatestProtocolStateSnapshot_Call { + return &AccessAPIClient_GetLatestProtocolStateSnapshot_Call{Call: _e.mock.On("GetLatestProtocolStateSnapshot", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetLatestProtocolStateSnapshot_Call) Run(run func(ctx context.Context, in *access.GetLatestProtocolStateSnapshotRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetLatestProtocolStateSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetLatestProtocolStateSnapshotRequest + if args[1] != nil { + arg1 = args[1].(*access.GetLatestProtocolStateSnapshotRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetLatestProtocolStateSnapshot_Call) Return(protocolStateSnapshotResponse *access.ProtocolStateSnapshotResponse, err error) *AccessAPIClient_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(protocolStateSnapshotResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetLatestProtocolStateSnapshot_Call) RunAndReturn(run func(ctx context.Context, in *access.GetLatestProtocolStateSnapshotRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)) *AccessAPIClient_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// GetNetworkParameters provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetNetworkParameters(ctx context.Context, in *access.GetNetworkParametersRequest, opts ...grpc.CallOption) (*access.GetNetworkParametersResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -951,7 +2398,7 @@ func (_m *AccessAPIClient) GetNetworkParameters(ctx context.Context, in *access. var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetNetworkParameters") @@ -959,28 +2406,78 @@ func (_m *AccessAPIClient) GetNetworkParameters(ctx context.Context, in *access. var r0 *access.GetNetworkParametersResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest, ...grpc.CallOption) (*access.GetNetworkParametersResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest, ...grpc.CallOption) (*access.GetNetworkParametersResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest, ...grpc.CallOption) *access.GetNetworkParametersResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest, ...grpc.CallOption) *access.GetNetworkParametersResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.GetNetworkParametersResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetNetworkParametersRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetNetworkParametersRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetNodeVersionInfo provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetNodeVersionInfo(ctx context.Context, in *access.GetNodeVersionInfoRequest, opts ...grpc.CallOption) (*access.GetNodeVersionInfoResponse, error) { +// AccessAPIClient_GetNetworkParameters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNetworkParameters' +type AccessAPIClient_GetNetworkParameters_Call struct { + *mock.Call +} + +// GetNetworkParameters is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetNetworkParametersRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetNetworkParameters(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetNetworkParameters_Call { + return &AccessAPIClient_GetNetworkParameters_Call{Call: _e.mock.On("GetNetworkParameters", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetNetworkParameters_Call) Run(run func(ctx context.Context, in *access.GetNetworkParametersRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetNetworkParameters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetNetworkParametersRequest + if args[1] != nil { + arg1 = args[1].(*access.GetNetworkParametersRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetNetworkParameters_Call) Return(getNetworkParametersResponse *access.GetNetworkParametersResponse, err error) *AccessAPIClient_GetNetworkParameters_Call { + _c.Call.Return(getNetworkParametersResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetNetworkParameters_Call) RunAndReturn(run func(ctx context.Context, in *access.GetNetworkParametersRequest, opts ...grpc.CallOption) (*access.GetNetworkParametersResponse, error)) *AccessAPIClient_GetNetworkParameters_Call { + _c.Call.Return(run) + return _c +} + +// GetNodeVersionInfo provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetNodeVersionInfo(ctx context.Context, in *access.GetNodeVersionInfoRequest, opts ...grpc.CallOption) (*access.GetNodeVersionInfoResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -988,7 +2485,7 @@ func (_m *AccessAPIClient) GetNodeVersionInfo(ctx context.Context, in *access.Ge var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetNodeVersionInfo") @@ -996,28 +2493,78 @@ func (_m *AccessAPIClient) GetNodeVersionInfo(ctx context.Context, in *access.Ge var r0 *access.GetNodeVersionInfoResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest, ...grpc.CallOption) (*access.GetNodeVersionInfoResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest, ...grpc.CallOption) (*access.GetNodeVersionInfoResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest, ...grpc.CallOption) *access.GetNodeVersionInfoResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest, ...grpc.CallOption) *access.GetNodeVersionInfoResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.GetNodeVersionInfoResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetNodeVersionInfoRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetNodeVersionInfoRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetProtocolStateSnapshotByBlockID(ctx context.Context, in *access.GetProtocolStateSnapshotByBlockIDRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error) { +// AccessAPIClient_GetNodeVersionInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNodeVersionInfo' +type AccessAPIClient_GetNodeVersionInfo_Call struct { + *mock.Call +} + +// GetNodeVersionInfo is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetNodeVersionInfoRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetNodeVersionInfo(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetNodeVersionInfo_Call { + return &AccessAPIClient_GetNodeVersionInfo_Call{Call: _e.mock.On("GetNodeVersionInfo", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetNodeVersionInfo_Call) Run(run func(ctx context.Context, in *access.GetNodeVersionInfoRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetNodeVersionInfo_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetNodeVersionInfoRequest + if args[1] != nil { + arg1 = args[1].(*access.GetNodeVersionInfoRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetNodeVersionInfo_Call) Return(getNodeVersionInfoResponse *access.GetNodeVersionInfoResponse, err error) *AccessAPIClient_GetNodeVersionInfo_Call { + _c.Call.Return(getNodeVersionInfoResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetNodeVersionInfo_Call) RunAndReturn(run func(ctx context.Context, in *access.GetNodeVersionInfoRequest, opts ...grpc.CallOption) (*access.GetNodeVersionInfoResponse, error)) *AccessAPIClient_GetNodeVersionInfo_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetProtocolStateSnapshotByBlockID(ctx context.Context, in *access.GetProtocolStateSnapshotByBlockIDRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1025,7 +2572,7 @@ func (_m *AccessAPIClient) GetProtocolStateSnapshotByBlockID(ctx context.Context var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByBlockID") @@ -1033,28 +2580,78 @@ func (_m *AccessAPIClient) GetProtocolStateSnapshotByBlockID(ctx context.Context var r0 *access.ProtocolStateSnapshotResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest, ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest, ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest, ...grpc.CallOption) *access.ProtocolStateSnapshotResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest, ...grpc.CallOption) *access.ProtocolStateSnapshotResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ProtocolStateSnapshotResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetProtocolStateSnapshotByHeight(ctx context.Context, in *access.GetProtocolStateSnapshotByHeightRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error) { +// AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByBlockID' +type AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetProtocolStateSnapshotByBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetProtocolStateSnapshotByBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call { + return &AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call{Call: _e.mock.On("GetProtocolStateSnapshotByBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call) Run(run func(ctx context.Context, in *access.GetProtocolStateSnapshotByBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetProtocolStateSnapshotByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetProtocolStateSnapshotByBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call) Return(protocolStateSnapshotResponse *access.ProtocolStateSnapshotResponse, err error) *AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(protocolStateSnapshotResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetProtocolStateSnapshotByBlockIDRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)) *AccessAPIClient_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetProtocolStateSnapshotByHeight(ctx context.Context, in *access.GetProtocolStateSnapshotByHeightRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1062,7 +2659,7 @@ func (_m *AccessAPIClient) GetProtocolStateSnapshotByHeight(ctx context.Context, var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByHeight") @@ -1070,28 +2667,78 @@ func (_m *AccessAPIClient) GetProtocolStateSnapshotByHeight(ctx context.Context, var r0 *access.ProtocolStateSnapshotResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest, ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest, ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest, ...grpc.CallOption) *access.ProtocolStateSnapshotResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest, ...grpc.CallOption) *access.ProtocolStateSnapshotResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ProtocolStateSnapshotResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetScheduledTransaction provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetScheduledTransaction(ctx context.Context, in *access.GetScheduledTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error) { +// AccessAPIClient_GetProtocolStateSnapshotByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByHeight' +type AccessAPIClient_GetProtocolStateSnapshotByHeight_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetProtocolStateSnapshotByHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetProtocolStateSnapshotByHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetProtocolStateSnapshotByHeight_Call { + return &AccessAPIClient_GetProtocolStateSnapshotByHeight_Call{Call: _e.mock.On("GetProtocolStateSnapshotByHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetProtocolStateSnapshotByHeight_Call) Run(run func(ctx context.Context, in *access.GetProtocolStateSnapshotByHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetProtocolStateSnapshotByHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetProtocolStateSnapshotByHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetProtocolStateSnapshotByHeight_Call) Return(protocolStateSnapshotResponse *access.ProtocolStateSnapshotResponse, err error) *AccessAPIClient_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(protocolStateSnapshotResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetProtocolStateSnapshotByHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.GetProtocolStateSnapshotByHeightRequest, opts ...grpc.CallOption) (*access.ProtocolStateSnapshotResponse, error)) *AccessAPIClient_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransaction provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetScheduledTransaction(ctx context.Context, in *access.GetScheduledTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1099,7 +2746,7 @@ func (_m *AccessAPIClient) GetScheduledTransaction(ctx context.Context, in *acce var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetScheduledTransaction") @@ -1107,28 +2754,78 @@ func (_m *AccessAPIClient) GetScheduledTransaction(ctx context.Context, in *acce var r0 *access.TransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest, ...grpc.CallOption) (*access.TransactionResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest, ...grpc.CallOption) (*access.TransactionResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest, ...grpc.CallOption) *access.TransactionResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest, ...grpc.CallOption) *access.TransactionResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetScheduledTransactionResult provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetScheduledTransactionResult(ctx context.Context, in *access.GetScheduledTransactionResultRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { +// AccessAPIClient_GetScheduledTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransaction' +type AccessAPIClient_GetScheduledTransaction_Call struct { + *mock.Call +} + +// GetScheduledTransaction is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetScheduledTransactionRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetScheduledTransaction(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetScheduledTransaction_Call { + return &AccessAPIClient_GetScheduledTransaction_Call{Call: _e.mock.On("GetScheduledTransaction", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetScheduledTransaction_Call) Run(run func(ctx context.Context, in *access.GetScheduledTransactionRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetScheduledTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetScheduledTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetScheduledTransactionRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetScheduledTransaction_Call) Return(transactionResponse *access.TransactionResponse, err error) *AccessAPIClient_GetScheduledTransaction_Call { + _c.Call.Return(transactionResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetScheduledTransaction_Call) RunAndReturn(run func(ctx context.Context, in *access.GetScheduledTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error)) *AccessAPIClient_GetScheduledTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransactionResult provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetScheduledTransactionResult(ctx context.Context, in *access.GetScheduledTransactionResultRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1136,7 +2833,7 @@ func (_m *AccessAPIClient) GetScheduledTransactionResult(ctx context.Context, in var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetScheduledTransactionResult") @@ -1144,28 +2841,78 @@ func (_m *AccessAPIClient) GetScheduledTransactionResult(ctx context.Context, in var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionResultRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionResultRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransaction provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetSystemTransaction(ctx context.Context, in *access.GetSystemTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error) { +// AccessAPIClient_GetScheduledTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransactionResult' +type AccessAPIClient_GetScheduledTransactionResult_Call struct { + *mock.Call +} + +// GetScheduledTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetScheduledTransactionResultRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetScheduledTransactionResult(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetScheduledTransactionResult_Call { + return &AccessAPIClient_GetScheduledTransactionResult_Call{Call: _e.mock.On("GetScheduledTransactionResult", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetScheduledTransactionResult_Call) Run(run func(ctx context.Context, in *access.GetScheduledTransactionResultRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetScheduledTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetScheduledTransactionResultRequest + if args[1] != nil { + arg1 = args[1].(*access.GetScheduledTransactionResultRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetScheduledTransactionResult_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIClient_GetScheduledTransactionResult_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetScheduledTransactionResult_Call) RunAndReturn(run func(ctx context.Context, in *access.GetScheduledTransactionResultRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error)) *AccessAPIClient_GetScheduledTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransaction provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetSystemTransaction(ctx context.Context, in *access.GetSystemTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1173,7 +2920,7 @@ func (_m *AccessAPIClient) GetSystemTransaction(ctx context.Context, in *access. var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetSystemTransaction") @@ -1181,28 +2928,78 @@ func (_m *AccessAPIClient) GetSystemTransaction(ctx context.Context, in *access. var r0 *access.TransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest, ...grpc.CallOption) (*access.TransactionResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest, ...grpc.CallOption) (*access.TransactionResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest, ...grpc.CallOption) *access.TransactionResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest, ...grpc.CallOption) *access.TransactionResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransactionResult provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetSystemTransactionResult(ctx context.Context, in *access.GetSystemTransactionResultRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { +// AccessAPIClient_GetSystemTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransaction' +type AccessAPIClient_GetSystemTransaction_Call struct { + *mock.Call +} + +// GetSystemTransaction is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetSystemTransactionRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetSystemTransaction(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetSystemTransaction_Call { + return &AccessAPIClient_GetSystemTransaction_Call{Call: _e.mock.On("GetSystemTransaction", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetSystemTransaction_Call) Run(run func(ctx context.Context, in *access.GetSystemTransactionRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetSystemTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetSystemTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetSystemTransactionRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetSystemTransaction_Call) Return(transactionResponse *access.TransactionResponse, err error) *AccessAPIClient_GetSystemTransaction_Call { + _c.Call.Return(transactionResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetSystemTransaction_Call) RunAndReturn(run func(ctx context.Context, in *access.GetSystemTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error)) *AccessAPIClient_GetSystemTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransactionResult provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetSystemTransactionResult(ctx context.Context, in *access.GetSystemTransactionResultRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1210,7 +3007,7 @@ func (_m *AccessAPIClient) GetSystemTransactionResult(ctx context.Context, in *a var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetSystemTransactionResult") @@ -1218,28 +3015,78 @@ func (_m *AccessAPIClient) GetSystemTransactionResult(ctx context.Context, in *a var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionResultRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionResultRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransaction provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetTransaction(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error) { +// AccessAPIClient_GetSystemTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransactionResult' +type AccessAPIClient_GetSystemTransactionResult_Call struct { + *mock.Call +} + +// GetSystemTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetSystemTransactionResultRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetSystemTransactionResult(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetSystemTransactionResult_Call { + return &AccessAPIClient_GetSystemTransactionResult_Call{Call: _e.mock.On("GetSystemTransactionResult", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetSystemTransactionResult_Call) Run(run func(ctx context.Context, in *access.GetSystemTransactionResultRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetSystemTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetSystemTransactionResultRequest + if args[1] != nil { + arg1 = args[1].(*access.GetSystemTransactionResultRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetSystemTransactionResult_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIClient_GetSystemTransactionResult_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetSystemTransactionResult_Call) RunAndReturn(run func(ctx context.Context, in *access.GetSystemTransactionResultRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error)) *AccessAPIClient_GetSystemTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransaction provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetTransaction(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1247,7 +3094,7 @@ func (_m *AccessAPIClient) GetTransaction(ctx context.Context, in *access.GetTra var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransaction") @@ -1255,28 +3102,78 @@ func (_m *AccessAPIClient) GetTransaction(ctx context.Context, in *access.GetTra var r0 *access.TransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) (*access.TransactionResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) (*access.TransactionResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) *access.TransactionResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) *access.TransactionResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResponse) } - } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccessAPIClient_GetTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransaction' +type AccessAPIClient_GetTransaction_Call struct { + *mock.Call +} + +// GetTransaction is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetTransactionRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetTransaction(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetTransaction_Call { + return &AccessAPIClient_GetTransaction_Call{Call: _e.mock.On("GetTransaction", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetTransaction_Call) Run(run func(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) - } else { - r1 = ret.Error(1) - } +func (_c *AccessAPIClient_GetTransaction_Call) Return(transactionResponse *access.TransactionResponse, err error) *AccessAPIClient_GetTransaction_Call { + _c.Call.Return(transactionResponse, err) + return _c +} - return r0, r1 +func (_c *AccessAPIClient_GetTransaction_Call) RunAndReturn(run func(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResponse, error)) *AccessAPIClient_GetTransaction_Call { + _c.Call.Return(run) + return _c } -// GetTransactionResult provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetTransactionResult(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { +// GetTransactionResult provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetTransactionResult(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1284,7 +3181,7 @@ func (_m *AccessAPIClient) GetTransactionResult(ctx context.Context, in *access. var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionResult") @@ -1292,28 +3189,78 @@ func (_m *AccessAPIClient) GetTransactionResult(ctx context.Context, in *access. var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultByIndex provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetTransactionResultByIndex(ctx context.Context, in *access.GetTransactionByIndexRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { +// AccessAPIClient_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type AccessAPIClient_GetTransactionResult_Call struct { + *mock.Call +} + +// GetTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetTransactionRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetTransactionResult(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetTransactionResult_Call { + return &AccessAPIClient_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetTransactionResult_Call) Run(run func(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetTransactionResult_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIClient_GetTransactionResult_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetTransactionResult_Call) RunAndReturn(run func(ctx context.Context, in *access.GetTransactionRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error)) *AccessAPIClient_GetTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultByIndex provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetTransactionResultByIndex(ctx context.Context, in *access.GetTransactionByIndexRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1321,7 +3268,7 @@ func (_m *AccessAPIClient) GetTransactionResultByIndex(ctx context.Context, in * var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionResultByIndex") @@ -1329,28 +3276,78 @@ func (_m *AccessAPIClient) GetTransactionResultByIndex(ctx context.Context, in * var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest, ...grpc.CallOption) (*access.TransactionResultResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest, ...grpc.CallOption) *access.TransactionResultResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionByIndexRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionByIndexRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultsByBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetTransactionResultsByBlockID(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*access.TransactionResultsResponse, error) { +// AccessAPIClient_GetTransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultByIndex' +type AccessAPIClient_GetTransactionResultByIndex_Call struct { + *mock.Call +} + +// GetTransactionResultByIndex is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetTransactionByIndexRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetTransactionResultByIndex(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetTransactionResultByIndex_Call { + return &AccessAPIClient_GetTransactionResultByIndex_Call{Call: _e.mock.On("GetTransactionResultByIndex", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetTransactionResultByIndex_Call) Run(run func(ctx context.Context, in *access.GetTransactionByIndexRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetTransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionByIndexRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionByIndexRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetTransactionResultByIndex_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIClient_GetTransactionResultByIndex_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetTransactionResultByIndex_Call) RunAndReturn(run func(ctx context.Context, in *access.GetTransactionByIndexRequest, opts ...grpc.CallOption) (*access.TransactionResultResponse, error)) *AccessAPIClient_GetTransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultsByBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetTransactionResultsByBlockID(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*access.TransactionResultsResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1358,7 +3355,7 @@ func (_m *AccessAPIClient) GetTransactionResultsByBlockID(ctx context.Context, i var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionResultsByBlockID") @@ -1366,28 +3363,78 @@ func (_m *AccessAPIClient) GetTransactionResultsByBlockID(ctx context.Context, i var r0 *access.TransactionResultsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) (*access.TransactionResultsResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) (*access.TransactionResultsResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) *access.TransactionResultsResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) *access.TransactionResultsResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionsByBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) GetTransactionsByBlockID(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*access.TransactionsResponse, error) { +// AccessAPIClient_GetTransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultsByBlockID' +type AccessAPIClient_GetTransactionResultsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionResultsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetTransactionsByBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetTransactionResultsByBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetTransactionResultsByBlockID_Call { + return &AccessAPIClient_GetTransactionResultsByBlockID_Call{Call: _e.mock.On("GetTransactionResultsByBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetTransactionResultsByBlockID_Call) Run(run func(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetTransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionsByBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetTransactionResultsByBlockID_Call) Return(transactionResultsResponse *access.TransactionResultsResponse, err error) *AccessAPIClient_GetTransactionResultsByBlockID_Call { + _c.Call.Return(transactionResultsResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetTransactionResultsByBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*access.TransactionResultsResponse, error)) *AccessAPIClient_GetTransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionsByBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) GetTransactionsByBlockID(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*access.TransactionsResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1395,7 +3442,7 @@ func (_m *AccessAPIClient) GetTransactionsByBlockID(ctx context.Context, in *acc var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionsByBlockID") @@ -1403,28 +3450,78 @@ func (_m *AccessAPIClient) GetTransactionsByBlockID(ctx context.Context, in *acc var r0 *access.TransactionsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) (*access.TransactionsResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) (*access.TransactionsResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) *access.TransactionsResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) *access.TransactionsResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// Ping provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) Ping(ctx context.Context, in *access.PingRequest, opts ...grpc.CallOption) (*access.PingResponse, error) { +// AccessAPIClient_GetTransactionsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionsByBlockID' +type AccessAPIClient_GetTransactionsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.GetTransactionsByBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) GetTransactionsByBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_GetTransactionsByBlockID_Call { + return &AccessAPIClient_GetTransactionsByBlockID_Call{Call: _e.mock.On("GetTransactionsByBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_GetTransactionsByBlockID_Call) Run(run func(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_GetTransactionsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionsByBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_GetTransactionsByBlockID_Call) Return(transactionsResponse *access.TransactionsResponse, err error) *AccessAPIClient_GetTransactionsByBlockID_Call { + _c.Call.Return(transactionsResponse, err) + return _c +} + +func (_c *AccessAPIClient_GetTransactionsByBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*access.TransactionsResponse, error)) *AccessAPIClient_GetTransactionsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Ping provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) Ping(ctx context.Context, in *access.PingRequest, opts ...grpc.CallOption) (*access.PingResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1432,7 +3529,7 @@ func (_m *AccessAPIClient) Ping(ctx context.Context, in *access.PingRequest, opt var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for Ping") @@ -1440,28 +3537,78 @@ func (_m *AccessAPIClient) Ping(ctx context.Context, in *access.PingRequest, opt var r0 *access.PingResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.PingRequest, ...grpc.CallOption) (*access.PingResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.PingRequest, ...grpc.CallOption) (*access.PingResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.PingRequest, ...grpc.CallOption) *access.PingResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.PingRequest, ...grpc.CallOption) *access.PingResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.PingResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.PingRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.PingRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SendAndSubscribeTransactionStatuses provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SendAndSubscribeTransactionStatuses(ctx context.Context, in *access.SendAndSubscribeTransactionStatusesRequest, opts ...grpc.CallOption) (access.AccessAPI_SendAndSubscribeTransactionStatusesClient, error) { +// AccessAPIClient_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping' +type AccessAPIClient_Ping_Call struct { + *mock.Call +} + +// Ping is a helper method to define mock.On call +// - ctx context.Context +// - in *access.PingRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) Ping(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_Ping_Call { + return &AccessAPIClient_Ping_Call{Call: _e.mock.On("Ping", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_Ping_Call) Run(run func(ctx context.Context, in *access.PingRequest, opts ...grpc.CallOption)) *AccessAPIClient_Ping_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.PingRequest + if args[1] != nil { + arg1 = args[1].(*access.PingRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_Ping_Call) Return(pingResponse *access.PingResponse, err error) *AccessAPIClient_Ping_Call { + _c.Call.Return(pingResponse, err) + return _c +} + +func (_c *AccessAPIClient_Ping_Call) RunAndReturn(run func(ctx context.Context, in *access.PingRequest, opts ...grpc.CallOption) (*access.PingResponse, error)) *AccessAPIClient_Ping_Call { + _c.Call.Return(run) + return _c +} + +// SendAndSubscribeTransactionStatuses provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SendAndSubscribeTransactionStatuses(ctx context.Context, in *access.SendAndSubscribeTransactionStatusesRequest, opts ...grpc.CallOption) (access.AccessAPI_SendAndSubscribeTransactionStatusesClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1469,7 +3616,7 @@ func (_m *AccessAPIClient) SendAndSubscribeTransactionStatuses(ctx context.Conte var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SendAndSubscribeTransactionStatuses") @@ -1477,28 +3624,78 @@ func (_m *AccessAPIClient) SendAndSubscribeTransactionStatuses(ctx context.Conte var r0 access.AccessAPI_SendAndSubscribeTransactionStatusesClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SendAndSubscribeTransactionStatusesRequest, ...grpc.CallOption) (access.AccessAPI_SendAndSubscribeTransactionStatusesClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SendAndSubscribeTransactionStatusesRequest, ...grpc.CallOption) (access.AccessAPI_SendAndSubscribeTransactionStatusesClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SendAndSubscribeTransactionStatusesRequest, ...grpc.CallOption) access.AccessAPI_SendAndSubscribeTransactionStatusesClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SendAndSubscribeTransactionStatusesRequest, ...grpc.CallOption) access.AccessAPI_SendAndSubscribeTransactionStatusesClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SendAndSubscribeTransactionStatusesClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SendAndSubscribeTransactionStatusesRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SendAndSubscribeTransactionStatusesRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SendTransaction provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SendTransaction(ctx context.Context, in *access.SendTransactionRequest, opts ...grpc.CallOption) (*access.SendTransactionResponse, error) { +// AccessAPIClient_SendAndSubscribeTransactionStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendAndSubscribeTransactionStatuses' +type AccessAPIClient_SendAndSubscribeTransactionStatuses_Call struct { + *mock.Call +} + +// SendAndSubscribeTransactionStatuses is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SendAndSubscribeTransactionStatusesRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SendAndSubscribeTransactionStatuses(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SendAndSubscribeTransactionStatuses_Call { + return &AccessAPIClient_SendAndSubscribeTransactionStatuses_Call{Call: _e.mock.On("SendAndSubscribeTransactionStatuses", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SendAndSubscribeTransactionStatuses_Call) Run(run func(ctx context.Context, in *access.SendAndSubscribeTransactionStatusesRequest, opts ...grpc.CallOption)) *AccessAPIClient_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SendAndSubscribeTransactionStatusesRequest + if args[1] != nil { + arg1 = args[1].(*access.SendAndSubscribeTransactionStatusesRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SendAndSubscribeTransactionStatuses_Call) Return(accessAPI_SendAndSubscribeTransactionStatusesClient access.AccessAPI_SendAndSubscribeTransactionStatusesClient, err error) *AccessAPIClient_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(accessAPI_SendAndSubscribeTransactionStatusesClient, err) + return _c +} + +func (_c *AccessAPIClient_SendAndSubscribeTransactionStatuses_Call) RunAndReturn(run func(ctx context.Context, in *access.SendAndSubscribeTransactionStatusesRequest, opts ...grpc.CallOption) (access.AccessAPI_SendAndSubscribeTransactionStatusesClient, error)) *AccessAPIClient_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(run) + return _c +} + +// SendTransaction provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SendTransaction(ctx context.Context, in *access.SendTransactionRequest, opts ...grpc.CallOption) (*access.SendTransactionResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1506,7 +3703,7 @@ func (_m *AccessAPIClient) SendTransaction(ctx context.Context, in *access.SendT var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SendTransaction") @@ -1514,28 +3711,78 @@ func (_m *AccessAPIClient) SendTransaction(ctx context.Context, in *access.SendT var r0 *access.SendTransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest, ...grpc.CallOption) (*access.SendTransactionResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest, ...grpc.CallOption) (*access.SendTransactionResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest, ...grpc.CallOption) *access.SendTransactionResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest, ...grpc.CallOption) *access.SendTransactionResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.SendTransactionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SendTransactionRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SendTransactionRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlockDigestsFromLatest provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlockDigestsFromLatest(ctx context.Context, in *access.SubscribeBlockDigestsFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromLatestClient, error) { +// AccessAPIClient_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' +type AccessAPIClient_SendTransaction_Call struct { + *mock.Call +} + +// SendTransaction is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SendTransactionRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SendTransaction(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SendTransaction_Call { + return &AccessAPIClient_SendTransaction_Call{Call: _e.mock.On("SendTransaction", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SendTransaction_Call) Run(run func(ctx context.Context, in *access.SendTransactionRequest, opts ...grpc.CallOption)) *AccessAPIClient_SendTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SendTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.SendTransactionRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SendTransaction_Call) Return(sendTransactionResponse *access.SendTransactionResponse, err error) *AccessAPIClient_SendTransaction_Call { + _c.Call.Return(sendTransactionResponse, err) + return _c +} + +func (_c *AccessAPIClient_SendTransaction_Call) RunAndReturn(run func(ctx context.Context, in *access.SendTransactionRequest, opts ...grpc.CallOption) (*access.SendTransactionResponse, error)) *AccessAPIClient_SendTransaction_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromLatest provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlockDigestsFromLatest(ctx context.Context, in *access.SubscribeBlockDigestsFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromLatestClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1543,7 +3790,7 @@ func (_m *AccessAPIClient) SubscribeBlockDigestsFromLatest(ctx context.Context, var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromLatest") @@ -1551,28 +3798,78 @@ func (_m *AccessAPIClient) SubscribeBlockDigestsFromLatest(ctx context.Context, var r0 access.AccessAPI_SubscribeBlockDigestsFromLatestClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromLatestRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromLatestClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromLatestRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromLatestClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromLatestRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockDigestsFromLatestClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromLatestRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockDigestsFromLatestClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlockDigestsFromLatestClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockDigestsFromLatestRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockDigestsFromLatestRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlockDigestsFromStartBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlockDigestsFromStartBlockID(ctx context.Context, in *access.SubscribeBlockDigestsFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient, error) { +// AccessAPIClient_SubscribeBlockDigestsFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromLatest' +type AccessAPIClient_SubscribeBlockDigestsFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlockDigestsFromLatestRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlockDigestsFromLatest(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlockDigestsFromLatest_Call { + return &AccessAPIClient_SubscribeBlockDigestsFromLatest_Call{Call: _e.mock.On("SubscribeBlockDigestsFromLatest", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromLatest_Call) Run(run func(ctx context.Context, in *access.SubscribeBlockDigestsFromLatestRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlockDigestsFromLatestRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlockDigestsFromLatestRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromLatest_Call) Return(accessAPI_SubscribeBlockDigestsFromLatestClient access.AccessAPI_SubscribeBlockDigestsFromLatestClient, err error) *AccessAPIClient_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(accessAPI_SubscribeBlockDigestsFromLatestClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromLatest_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlockDigestsFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromLatestClient, error)) *AccessAPIClient_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlockDigestsFromStartBlockID(ctx context.Context, in *access.SubscribeBlockDigestsFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1580,7 +3877,7 @@ func (_m *AccessAPIClient) SubscribeBlockDigestsFromStartBlockID(ctx context.Con var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartBlockID") @@ -1588,28 +3885,78 @@ func (_m *AccessAPIClient) SubscribeBlockDigestsFromStartBlockID(ctx context.Con var r0 access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartBlockIDRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartBlockIDRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartBlockIDRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartBlockIDRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockDigestsFromStartBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockDigestsFromStartBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlockDigestsFromStartHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlockDigestsFromStartHeight(ctx context.Context, in *access.SubscribeBlockDigestsFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient, error) { +// AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartBlockID' +type AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlockDigestsFromStartBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlockDigestsFromStartBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call { + return &AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call) Run(run func(ctx context.Context, in *access.SubscribeBlockDigestsFromStartBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlockDigestsFromStartBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlockDigestsFromStartBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call) Return(accessAPI_SubscribeBlockDigestsFromStartBlockIDClient access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient, err error) *AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(accessAPI_SubscribeBlockDigestsFromStartBlockIDClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlockDigestsFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDClient, error)) *AccessAPIClient_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlockDigestsFromStartHeight(ctx context.Context, in *access.SubscribeBlockDigestsFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1617,7 +3964,7 @@ func (_m *AccessAPIClient) SubscribeBlockDigestsFromStartHeight(ctx context.Cont var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartHeight") @@ -1625,28 +3972,78 @@ func (_m *AccessAPIClient) SubscribeBlockDigestsFromStartHeight(ctx context.Cont var r0 access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartHeightRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartHeightRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartHeightRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockDigestsFromStartHeightRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockDigestsFromStartHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockDigestsFromStartHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlockHeadersFromLatest provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlockHeadersFromLatest(ctx context.Context, in *access.SubscribeBlockHeadersFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromLatestClient, error) { +// AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartHeight' +type AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlockDigestsFromStartHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlockDigestsFromStartHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call { + return &AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call) Run(run func(ctx context.Context, in *access.SubscribeBlockDigestsFromStartHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlockDigestsFromStartHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlockDigestsFromStartHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call) Return(accessAPI_SubscribeBlockDigestsFromStartHeightClient access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient, err error) *AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(accessAPI_SubscribeBlockDigestsFromStartHeightClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlockDigestsFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockDigestsFromStartHeightClient, error)) *AccessAPIClient_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromLatest provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlockHeadersFromLatest(ctx context.Context, in *access.SubscribeBlockHeadersFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromLatestClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1654,7 +4051,7 @@ func (_m *AccessAPIClient) SubscribeBlockHeadersFromLatest(ctx context.Context, var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromLatest") @@ -1662,28 +4059,78 @@ func (_m *AccessAPIClient) SubscribeBlockHeadersFromLatest(ctx context.Context, var r0 access.AccessAPI_SubscribeBlockHeadersFromLatestClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromLatestRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromLatestClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromLatestRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromLatestClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromLatestRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockHeadersFromLatestClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromLatestRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockHeadersFromLatestClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlockHeadersFromLatestClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockHeadersFromLatestRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockHeadersFromLatestRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlockHeadersFromStartBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlockHeadersFromStartBlockID(ctx context.Context, in *access.SubscribeBlockHeadersFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient, error) { +// AccessAPIClient_SubscribeBlockHeadersFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromLatest' +type AccessAPIClient_SubscribeBlockHeadersFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlockHeadersFromLatestRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlockHeadersFromLatest(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlockHeadersFromLatest_Call { + return &AccessAPIClient_SubscribeBlockHeadersFromLatest_Call{Call: _e.mock.On("SubscribeBlockHeadersFromLatest", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromLatest_Call) Run(run func(ctx context.Context, in *access.SubscribeBlockHeadersFromLatestRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlockHeadersFromLatestRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlockHeadersFromLatestRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromLatest_Call) Return(accessAPI_SubscribeBlockHeadersFromLatestClient access.AccessAPI_SubscribeBlockHeadersFromLatestClient, err error) *AccessAPIClient_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(accessAPI_SubscribeBlockHeadersFromLatestClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromLatest_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlockHeadersFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromLatestClient, error)) *AccessAPIClient_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlockHeadersFromStartBlockID(ctx context.Context, in *access.SubscribeBlockHeadersFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1691,7 +4138,7 @@ func (_m *AccessAPIClient) SubscribeBlockHeadersFromStartBlockID(ctx context.Con var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartBlockID") @@ -1699,28 +4146,78 @@ func (_m *AccessAPIClient) SubscribeBlockHeadersFromStartBlockID(ctx context.Con var r0 access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartBlockIDRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartBlockIDRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartBlockIDRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartBlockIDRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockHeadersFromStartBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockHeadersFromStartBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlockHeadersFromStartHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlockHeadersFromStartHeight(ctx context.Context, in *access.SubscribeBlockHeadersFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient, error) { +// AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartBlockID' +type AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlockHeadersFromStartBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlockHeadersFromStartBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call { + return &AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call) Run(run func(ctx context.Context, in *access.SubscribeBlockHeadersFromStartBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlockHeadersFromStartBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlockHeadersFromStartBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call) Return(accessAPI_SubscribeBlockHeadersFromStartBlockIDClient access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient, err error) *AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(accessAPI_SubscribeBlockHeadersFromStartBlockIDClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlockHeadersFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDClient, error)) *AccessAPIClient_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlockHeadersFromStartHeight(ctx context.Context, in *access.SubscribeBlockHeadersFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1728,7 +4225,7 @@ func (_m *AccessAPIClient) SubscribeBlockHeadersFromStartHeight(ctx context.Cont var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartHeight") @@ -1736,28 +4233,78 @@ func (_m *AccessAPIClient) SubscribeBlockHeadersFromStartHeight(ctx context.Cont var r0 access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartHeightRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartHeightRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartHeightRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlockHeadersFromStartHeightRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockHeadersFromStartHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlockHeadersFromStartHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlocksFromLatest provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlocksFromLatest(ctx context.Context, in *access.SubscribeBlocksFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromLatestClient, error) { +// AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartHeight' +type AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlockHeadersFromStartHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlockHeadersFromStartHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call { + return &AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartHeight", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call) Run(run func(ctx context.Context, in *access.SubscribeBlockHeadersFromStartHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlockHeadersFromStartHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlockHeadersFromStartHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call) Return(accessAPI_SubscribeBlockHeadersFromStartHeightClient access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient, err error) *AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(accessAPI_SubscribeBlockHeadersFromStartHeightClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlockHeadersFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlockHeadersFromStartHeightClient, error)) *AccessAPIClient_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromLatest provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlocksFromLatest(ctx context.Context, in *access.SubscribeBlocksFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromLatestClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1765,7 +4312,7 @@ func (_m *AccessAPIClient) SubscribeBlocksFromLatest(ctx context.Context, in *ac var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromLatest") @@ -1773,28 +4320,78 @@ func (_m *AccessAPIClient) SubscribeBlocksFromLatest(ctx context.Context, in *ac var r0 access.AccessAPI_SubscribeBlocksFromLatestClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromLatestRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromLatestClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromLatestRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromLatestClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromLatestRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlocksFromLatestClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromLatestRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlocksFromLatestClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlocksFromLatestClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlocksFromLatestRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlocksFromLatestRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlocksFromStartBlockID provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlocksFromStartBlockID(ctx context.Context, in *access.SubscribeBlocksFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartBlockIDClient, error) { +// AccessAPIClient_SubscribeBlocksFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromLatest' +type AccessAPIClient_SubscribeBlocksFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlocksFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlocksFromLatestRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlocksFromLatest(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlocksFromLatest_Call { + return &AccessAPIClient_SubscribeBlocksFromLatest_Call{Call: _e.mock.On("SubscribeBlocksFromLatest", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlocksFromLatest_Call) Run(run func(ctx context.Context, in *access.SubscribeBlocksFromLatestRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlocksFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlocksFromLatestRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlocksFromLatestRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlocksFromLatest_Call) Return(accessAPI_SubscribeBlocksFromLatestClient access.AccessAPI_SubscribeBlocksFromLatestClient, err error) *AccessAPIClient_SubscribeBlocksFromLatest_Call { + _c.Call.Return(accessAPI_SubscribeBlocksFromLatestClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlocksFromLatest_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlocksFromLatestRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromLatestClient, error)) *AccessAPIClient_SubscribeBlocksFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartBlockID provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlocksFromStartBlockID(ctx context.Context, in *access.SubscribeBlocksFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartBlockIDClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1802,7 +4399,7 @@ func (_m *AccessAPIClient) SubscribeBlocksFromStartBlockID(ctx context.Context, var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartBlockID") @@ -1810,28 +4407,78 @@ func (_m *AccessAPIClient) SubscribeBlocksFromStartBlockID(ctx context.Context, var r0 access.AccessAPI_SubscribeBlocksFromStartBlockIDClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartBlockIDRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartBlockIDClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartBlockIDRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartBlockIDClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartBlockIDRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlocksFromStartBlockIDClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartBlockIDRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlocksFromStartBlockIDClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlocksFromStartBlockIDClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlocksFromStartBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlocksFromStartBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlocksFromStartHeight provides a mock function with given fields: ctx, in, opts -func (_m *AccessAPIClient) SubscribeBlocksFromStartHeight(ctx context.Context, in *access.SubscribeBlocksFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartHeightClient, error) { +// AccessAPIClient_SubscribeBlocksFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartBlockID' +type AccessAPIClient_SubscribeBlocksFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlocksFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlocksFromStartBlockIDRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlocksFromStartBlockID(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlocksFromStartBlockID_Call { + return &AccessAPIClient_SubscribeBlocksFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlocksFromStartBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *AccessAPIClient_SubscribeBlocksFromStartBlockID_Call) Run(run func(ctx context.Context, in *access.SubscribeBlocksFromStartBlockIDRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlocksFromStartBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlocksFromStartBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlocksFromStartBlockID_Call) Return(accessAPI_SubscribeBlocksFromStartBlockIDClient access.AccessAPI_SubscribeBlocksFromStartBlockIDClient, err error) *AccessAPIClient_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(accessAPI_SubscribeBlocksFromStartBlockIDClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlocksFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlocksFromStartBlockIDRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartBlockIDClient, error)) *AccessAPIClient_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartHeight provides a mock function for the type AccessAPIClient +func (_mock *AccessAPIClient) SubscribeBlocksFromStartHeight(ctx context.Context, in *access.SubscribeBlocksFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartHeightClient, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1839,7 +4486,7 @@ func (_m *AccessAPIClient) SubscribeBlocksFromStartHeight(ctx context.Context, i var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartHeight") @@ -1847,36 +4494,71 @@ func (_m *AccessAPIClient) SubscribeBlocksFromStartHeight(ctx context.Context, i var r0 access.AccessAPI_SubscribeBlocksFromStartHeightClient var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartHeightRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartHeightClient, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartHeightRequest, ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartHeightClient, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartHeightRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlocksFromStartHeightClient); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SubscribeBlocksFromStartHeightRequest, ...grpc.CallOption) access.AccessAPI_SubscribeBlocksFromStartHeightClient); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPI_SubscribeBlocksFromStartHeightClient) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlocksFromStartHeightRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SubscribeBlocksFromStartHeightRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAccessAPIClient creates a new instance of AccessAPIClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccessAPIClient(t interface { - mock.TestingT - Cleanup(func()) -}) *AccessAPIClient { - mock := &AccessAPIClient{} - mock.Mock.Test(t) +// AccessAPIClient_SubscribeBlocksFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartHeight' +type AccessAPIClient_SubscribeBlocksFromStartHeight_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubscribeBlocksFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - in *access.SubscribeBlocksFromStartHeightRequest +// - opts ...grpc.CallOption +func (_e *AccessAPIClient_Expecter) SubscribeBlocksFromStartHeight(ctx interface{}, in interface{}, opts ...interface{}) *AccessAPIClient_SubscribeBlocksFromStartHeight_Call { + return &AccessAPIClient_SubscribeBlocksFromStartHeight_Call{Call: _e.mock.On("SubscribeBlocksFromStartHeight", + append([]interface{}{ctx, in}, opts...)...)} +} - return mock +func (_c *AccessAPIClient_SubscribeBlocksFromStartHeight_Call) Run(run func(ctx context.Context, in *access.SubscribeBlocksFromStartHeightRequest, opts ...grpc.CallOption)) *AccessAPIClient_SubscribeBlocksFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SubscribeBlocksFromStartHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.SubscribeBlocksFromStartHeightRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlocksFromStartHeight_Call) Return(accessAPI_SubscribeBlocksFromStartHeightClient access.AccessAPI_SubscribeBlocksFromStartHeightClient, err error) *AccessAPIClient_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(accessAPI_SubscribeBlocksFromStartHeightClient, err) + return _c +} + +func (_c *AccessAPIClient_SubscribeBlocksFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, in *access.SubscribeBlocksFromStartHeightRequest, opts ...grpc.CallOption) (access.AccessAPI_SubscribeBlocksFromStartHeightClient, error)) *AccessAPIClient_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/mock/access_api_server.go b/engine/access/mock/access_api_server.go index e77f00374bc..a84ca8da62b 100644 --- a/engine/access/mock/access_api_server.go +++ b/engine/access/mock/access_api_server.go @@ -1,23 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - access "github.com/onflow/flow/protobuf/go/flow/access" + "context" + "github.com/onflow/flow/protobuf/go/flow/access" mock "github.com/stretchr/testify/mock" ) +// NewAccessAPIServer creates a new instance of AccessAPIServer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccessAPIServer(t interface { + mock.TestingT + Cleanup(func()) +}) *AccessAPIServer { + mock := &AccessAPIServer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccessAPIServer is an autogenerated mock type for the AccessAPIServer type type AccessAPIServer struct { mock.Mock } -// ExecuteScriptAtBlockHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) ExecuteScriptAtBlockHeight(_a0 context.Context, _a1 *access.ExecuteScriptAtBlockHeightRequest) (*access.ExecuteScriptResponse, error) { - ret := _m.Called(_a0, _a1) +type AccessAPIServer_Expecter struct { + mock *mock.Mock +} + +func (_m *AccessAPIServer) EXPECT() *AccessAPIServer_Expecter { + return &AccessAPIServer_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) ExecuteScriptAtBlockHeight(context1 context.Context, executeScriptAtBlockHeightRequest *access.ExecuteScriptAtBlockHeightRequest) (*access.ExecuteScriptResponse, error) { + ret := _mock.Called(context1, executeScriptAtBlockHeightRequest) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockHeight") @@ -25,29 +48,67 @@ func (_m *AccessAPIServer) ExecuteScriptAtBlockHeight(_a0 context.Context, _a1 * var r0 *access.ExecuteScriptResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest) (*access.ExecuteScriptResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest) (*access.ExecuteScriptResponse, error)); ok { + return returnFunc(context1, executeScriptAtBlockHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest) *access.ExecuteScriptResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest) *access.ExecuteScriptResponse); ok { + r0 = returnFunc(context1, executeScriptAtBlockHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecuteScriptResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockHeightRequest) error); ok { + r1 = returnFunc(context1, executeScriptAtBlockHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) ExecuteScriptAtBlockID(_a0 context.Context, _a1 *access.ExecuteScriptAtBlockIDRequest) (*access.ExecuteScriptResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_ExecuteScriptAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockHeight' +type AccessAPIServer_ExecuteScriptAtBlockHeight_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockHeight is a helper method to define mock.On call +// - context1 context.Context +// - executeScriptAtBlockHeightRequest *access.ExecuteScriptAtBlockHeightRequest +func (_e *AccessAPIServer_Expecter) ExecuteScriptAtBlockHeight(context1 interface{}, executeScriptAtBlockHeightRequest interface{}) *AccessAPIServer_ExecuteScriptAtBlockHeight_Call { + return &AccessAPIServer_ExecuteScriptAtBlockHeight_Call{Call: _e.mock.On("ExecuteScriptAtBlockHeight", context1, executeScriptAtBlockHeightRequest)} +} + +func (_c *AccessAPIServer_ExecuteScriptAtBlockHeight_Call) Run(run func(context1 context.Context, executeScriptAtBlockHeightRequest *access.ExecuteScriptAtBlockHeightRequest)) *AccessAPIServer_ExecuteScriptAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.ExecuteScriptAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.ExecuteScriptAtBlockHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_ExecuteScriptAtBlockHeight_Call) Return(executeScriptResponse *access.ExecuteScriptResponse, err error) *AccessAPIServer_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(executeScriptResponse, err) + return _c +} + +func (_c *AccessAPIServer_ExecuteScriptAtBlockHeight_Call) RunAndReturn(run func(context1 context.Context, executeScriptAtBlockHeightRequest *access.ExecuteScriptAtBlockHeightRequest) (*access.ExecuteScriptResponse, error)) *AccessAPIServer_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) ExecuteScriptAtBlockID(context1 context.Context, executeScriptAtBlockIDRequest *access.ExecuteScriptAtBlockIDRequest) (*access.ExecuteScriptResponse, error) { + ret := _mock.Called(context1, executeScriptAtBlockIDRequest) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -55,29 +116,67 @@ func (_m *AccessAPIServer) ExecuteScriptAtBlockID(_a0 context.Context, _a1 *acce var r0 *access.ExecuteScriptResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest) (*access.ExecuteScriptResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest) (*access.ExecuteScriptResponse, error)); ok { + return returnFunc(context1, executeScriptAtBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest) *access.ExecuteScriptResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest) *access.ExecuteScriptResponse); ok { + r0 = returnFunc(context1, executeScriptAtBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecuteScriptResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtBlockIDRequest) error); ok { + r1 = returnFunc(context1, executeScriptAtBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) ExecuteScriptAtLatestBlock(_a0 context.Context, _a1 *access.ExecuteScriptAtLatestBlockRequest) (*access.ExecuteScriptResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type AccessAPIServer_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - context1 context.Context +// - executeScriptAtBlockIDRequest *access.ExecuteScriptAtBlockIDRequest +func (_e *AccessAPIServer_Expecter) ExecuteScriptAtBlockID(context1 interface{}, executeScriptAtBlockIDRequest interface{}) *AccessAPIServer_ExecuteScriptAtBlockID_Call { + return &AccessAPIServer_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", context1, executeScriptAtBlockIDRequest)} +} + +func (_c *AccessAPIServer_ExecuteScriptAtBlockID_Call) Run(run func(context1 context.Context, executeScriptAtBlockIDRequest *access.ExecuteScriptAtBlockIDRequest)) *AccessAPIServer_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.ExecuteScriptAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.ExecuteScriptAtBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_ExecuteScriptAtBlockID_Call) Return(executeScriptResponse *access.ExecuteScriptResponse, err error) *AccessAPIServer_ExecuteScriptAtBlockID_Call { + _c.Call.Return(executeScriptResponse, err) + return _c +} + +func (_c *AccessAPIServer_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(context1 context.Context, executeScriptAtBlockIDRequest *access.ExecuteScriptAtBlockIDRequest) (*access.ExecuteScriptResponse, error)) *AccessAPIServer_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtLatestBlock provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) ExecuteScriptAtLatestBlock(context1 context.Context, executeScriptAtLatestBlockRequest *access.ExecuteScriptAtLatestBlockRequest) (*access.ExecuteScriptResponse, error) { + ret := _mock.Called(context1, executeScriptAtLatestBlockRequest) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtLatestBlock") @@ -85,29 +184,67 @@ func (_m *AccessAPIServer) ExecuteScriptAtLatestBlock(_a0 context.Context, _a1 * var r0 *access.ExecuteScriptResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest) (*access.ExecuteScriptResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest) (*access.ExecuteScriptResponse, error)); ok { + return returnFunc(context1, executeScriptAtLatestBlockRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest) *access.ExecuteScriptResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest) *access.ExecuteScriptResponse); ok { + r0 = returnFunc(context1, executeScriptAtLatestBlockRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecuteScriptResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.ExecuteScriptAtLatestBlockRequest) error); ok { + r1 = returnFunc(context1, executeScriptAtLatestBlockRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccount provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccount(_a0 context.Context, _a1 *access.GetAccountRequest) (*access.GetAccountResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_ExecuteScriptAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtLatestBlock' +type AccessAPIServer_ExecuteScriptAtLatestBlock_Call struct { + *mock.Call +} + +// ExecuteScriptAtLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - executeScriptAtLatestBlockRequest *access.ExecuteScriptAtLatestBlockRequest +func (_e *AccessAPIServer_Expecter) ExecuteScriptAtLatestBlock(context1 interface{}, executeScriptAtLatestBlockRequest interface{}) *AccessAPIServer_ExecuteScriptAtLatestBlock_Call { + return &AccessAPIServer_ExecuteScriptAtLatestBlock_Call{Call: _e.mock.On("ExecuteScriptAtLatestBlock", context1, executeScriptAtLatestBlockRequest)} +} + +func (_c *AccessAPIServer_ExecuteScriptAtLatestBlock_Call) Run(run func(context1 context.Context, executeScriptAtLatestBlockRequest *access.ExecuteScriptAtLatestBlockRequest)) *AccessAPIServer_ExecuteScriptAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.ExecuteScriptAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.ExecuteScriptAtLatestBlockRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_ExecuteScriptAtLatestBlock_Call) Return(executeScriptResponse *access.ExecuteScriptResponse, err error) *AccessAPIServer_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(executeScriptResponse, err) + return _c +} + +func (_c *AccessAPIServer_ExecuteScriptAtLatestBlock_Call) RunAndReturn(run func(context1 context.Context, executeScriptAtLatestBlockRequest *access.ExecuteScriptAtLatestBlockRequest) (*access.ExecuteScriptResponse, error)) *AccessAPIServer_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccount provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccount(context1 context.Context, getAccountRequest *access.GetAccountRequest) (*access.GetAccountResponse, error) { + ret := _mock.Called(context1, getAccountRequest) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -115,29 +252,67 @@ func (_m *AccessAPIServer) GetAccount(_a0 context.Context, _a1 *access.GetAccoun var r0 *access.GetAccountResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest) (*access.GetAccountResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest) (*access.GetAccountResponse, error)); ok { + return returnFunc(context1, getAccountRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest) *access.GetAccountResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountRequest) *access.GetAccountResponse); ok { + r0 = returnFunc(context1, getAccountRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.GetAccountResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountRequest) error); ok { + r1 = returnFunc(context1, getAccountRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountAtBlockHeight(_a0 context.Context, _a1 *access.GetAccountAtBlockHeightRequest) (*access.AccountResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type AccessAPIServer_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - context1 context.Context +// - getAccountRequest *access.GetAccountRequest +func (_e *AccessAPIServer_Expecter) GetAccount(context1 interface{}, getAccountRequest interface{}) *AccessAPIServer_GetAccount_Call { + return &AccessAPIServer_GetAccount_Call{Call: _e.mock.On("GetAccount", context1, getAccountRequest)} +} + +func (_c *AccessAPIServer_GetAccount_Call) Run(run func(context1 context.Context, getAccountRequest *access.GetAccountRequest)) *AccessAPIServer_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccount_Call) Return(getAccountResponse *access.GetAccountResponse, err error) *AccessAPIServer_GetAccount_Call { + _c.Call.Return(getAccountResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccount_Call) RunAndReturn(run func(context1 context.Context, getAccountRequest *access.GetAccountRequest) (*access.GetAccountResponse, error)) *AccessAPIServer_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountAtBlockHeight(context1 context.Context, getAccountAtBlockHeightRequest *access.GetAccountAtBlockHeightRequest) (*access.AccountResponse, error) { + ret := _mock.Called(context1, getAccountAtBlockHeightRequest) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockHeight") @@ -145,29 +320,67 @@ func (_m *AccessAPIServer) GetAccountAtBlockHeight(_a0 context.Context, _a1 *acc var r0 *access.AccountResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest) (*access.AccountResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest) (*access.AccountResponse, error)); ok { + return returnFunc(context1, getAccountAtBlockHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest) *access.AccountResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtBlockHeightRequest) *access.AccountResponse); ok { + r0 = returnFunc(context1, getAccountAtBlockHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtBlockHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtBlockHeightRequest) error); ok { + r1 = returnFunc(context1, getAccountAtBlockHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountAtLatestBlock(_a0 context.Context, _a1 *access.GetAccountAtLatestBlockRequest) (*access.AccountResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockHeight' +type AccessAPIServer_GetAccountAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountAtBlockHeight is a helper method to define mock.On call +// - context1 context.Context +// - getAccountAtBlockHeightRequest *access.GetAccountAtBlockHeightRequest +func (_e *AccessAPIServer_Expecter) GetAccountAtBlockHeight(context1 interface{}, getAccountAtBlockHeightRequest interface{}) *AccessAPIServer_GetAccountAtBlockHeight_Call { + return &AccessAPIServer_GetAccountAtBlockHeight_Call{Call: _e.mock.On("GetAccountAtBlockHeight", context1, getAccountAtBlockHeightRequest)} +} + +func (_c *AccessAPIServer_GetAccountAtBlockHeight_Call) Run(run func(context1 context.Context, getAccountAtBlockHeightRequest *access.GetAccountAtBlockHeightRequest)) *AccessAPIServer_GetAccountAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountAtBlockHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountAtBlockHeight_Call) Return(accountResponse *access.AccountResponse, err error) *AccessAPIServer_GetAccountAtBlockHeight_Call { + _c.Call.Return(accountResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountAtBlockHeight_Call) RunAndReturn(run func(context1 context.Context, getAccountAtBlockHeightRequest *access.GetAccountAtBlockHeightRequest) (*access.AccountResponse, error)) *AccessAPIServer_GetAccountAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtLatestBlock provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountAtLatestBlock(context1 context.Context, getAccountAtLatestBlockRequest *access.GetAccountAtLatestBlockRequest) (*access.AccountResponse, error) { + ret := _mock.Called(context1, getAccountAtLatestBlockRequest) if len(ret) == 0 { panic("no return value specified for GetAccountAtLatestBlock") @@ -175,29 +388,67 @@ func (_m *AccessAPIServer) GetAccountAtLatestBlock(_a0 context.Context, _a1 *acc var r0 *access.AccountResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest) (*access.AccountResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest) (*access.AccountResponse, error)); ok { + return returnFunc(context1, getAccountAtLatestBlockRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest) *access.AccountResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountAtLatestBlockRequest) *access.AccountResponse); ok { + r0 = returnFunc(context1, getAccountAtLatestBlockRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtLatestBlockRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountAtLatestBlockRequest) error); ok { + r1 = returnFunc(context1, getAccountAtLatestBlockRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtBlockHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountBalanceAtBlockHeight(_a0 context.Context, _a1 *access.GetAccountBalanceAtBlockHeightRequest) (*access.AccountBalanceResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtLatestBlock' +type AccessAPIServer_GetAccountAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountAtLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - getAccountAtLatestBlockRequest *access.GetAccountAtLatestBlockRequest +func (_e *AccessAPIServer_Expecter) GetAccountAtLatestBlock(context1 interface{}, getAccountAtLatestBlockRequest interface{}) *AccessAPIServer_GetAccountAtLatestBlock_Call { + return &AccessAPIServer_GetAccountAtLatestBlock_Call{Call: _e.mock.On("GetAccountAtLatestBlock", context1, getAccountAtLatestBlockRequest)} +} + +func (_c *AccessAPIServer_GetAccountAtLatestBlock_Call) Run(run func(context1 context.Context, getAccountAtLatestBlockRequest *access.GetAccountAtLatestBlockRequest)) *AccessAPIServer_GetAccountAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountAtLatestBlockRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountAtLatestBlock_Call) Return(accountResponse *access.AccountResponse, err error) *AccessAPIServer_GetAccountAtLatestBlock_Call { + _c.Call.Return(accountResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountAtLatestBlock_Call) RunAndReturn(run func(context1 context.Context, getAccountAtLatestBlockRequest *access.GetAccountAtLatestBlockRequest) (*access.AccountResponse, error)) *AccessAPIServer_GetAccountAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtBlockHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountBalanceAtBlockHeight(context1 context.Context, getAccountBalanceAtBlockHeightRequest *access.GetAccountBalanceAtBlockHeightRequest) (*access.AccountBalanceResponse, error) { + ret := _mock.Called(context1, getAccountBalanceAtBlockHeightRequest) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtBlockHeight") @@ -205,29 +456,67 @@ func (_m *AccessAPIServer) GetAccountBalanceAtBlockHeight(_a0 context.Context, _ var r0 *access.AccountBalanceResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest) (*access.AccountBalanceResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest) (*access.AccountBalanceResponse, error)); ok { + return returnFunc(context1, getAccountBalanceAtBlockHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest) *access.AccountBalanceResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest) *access.AccountBalanceResponse); ok { + r0 = returnFunc(context1, getAccountBalanceAtBlockHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountBalanceResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtBlockHeightRequest) error); ok { + r1 = returnFunc(context1, getAccountBalanceAtBlockHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountBalanceAtLatestBlock(_a0 context.Context, _a1 *access.GetAccountBalanceAtLatestBlockRequest) (*access.AccountBalanceResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountBalanceAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtBlockHeight' +type AccessAPIServer_GetAccountBalanceAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountBalanceAtBlockHeight is a helper method to define mock.On call +// - context1 context.Context +// - getAccountBalanceAtBlockHeightRequest *access.GetAccountBalanceAtBlockHeightRequest +func (_e *AccessAPIServer_Expecter) GetAccountBalanceAtBlockHeight(context1 interface{}, getAccountBalanceAtBlockHeightRequest interface{}) *AccessAPIServer_GetAccountBalanceAtBlockHeight_Call { + return &AccessAPIServer_GetAccountBalanceAtBlockHeight_Call{Call: _e.mock.On("GetAccountBalanceAtBlockHeight", context1, getAccountBalanceAtBlockHeightRequest)} +} + +func (_c *AccessAPIServer_GetAccountBalanceAtBlockHeight_Call) Run(run func(context1 context.Context, getAccountBalanceAtBlockHeightRequest *access.GetAccountBalanceAtBlockHeightRequest)) *AccessAPIServer_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountBalanceAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountBalanceAtBlockHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountBalanceAtBlockHeight_Call) Return(accountBalanceResponse *access.AccountBalanceResponse, err error) *AccessAPIServer_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(accountBalanceResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountBalanceAtBlockHeight_Call) RunAndReturn(run func(context1 context.Context, getAccountBalanceAtBlockHeightRequest *access.GetAccountBalanceAtBlockHeightRequest) (*access.AccountBalanceResponse, error)) *AccessAPIServer_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtLatestBlock provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountBalanceAtLatestBlock(context1 context.Context, getAccountBalanceAtLatestBlockRequest *access.GetAccountBalanceAtLatestBlockRequest) (*access.AccountBalanceResponse, error) { + ret := _mock.Called(context1, getAccountBalanceAtLatestBlockRequest) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtLatestBlock") @@ -235,29 +524,67 @@ func (_m *AccessAPIServer) GetAccountBalanceAtLatestBlock(_a0 context.Context, _ var r0 *access.AccountBalanceResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest) (*access.AccountBalanceResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest) (*access.AccountBalanceResponse, error)); ok { + return returnFunc(context1, getAccountBalanceAtLatestBlockRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest) *access.AccountBalanceResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest) *access.AccountBalanceResponse); ok { + r0 = returnFunc(context1, getAccountBalanceAtLatestBlockRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountBalanceResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountBalanceAtLatestBlockRequest) error); ok { + r1 = returnFunc(context1, getAccountBalanceAtLatestBlockRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtBlockHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountKeyAtBlockHeight(_a0 context.Context, _a1 *access.GetAccountKeyAtBlockHeightRequest) (*access.AccountKeyResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountBalanceAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtLatestBlock' +type AccessAPIServer_GetAccountBalanceAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountBalanceAtLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - getAccountBalanceAtLatestBlockRequest *access.GetAccountBalanceAtLatestBlockRequest +func (_e *AccessAPIServer_Expecter) GetAccountBalanceAtLatestBlock(context1 interface{}, getAccountBalanceAtLatestBlockRequest interface{}) *AccessAPIServer_GetAccountBalanceAtLatestBlock_Call { + return &AccessAPIServer_GetAccountBalanceAtLatestBlock_Call{Call: _e.mock.On("GetAccountBalanceAtLatestBlock", context1, getAccountBalanceAtLatestBlockRequest)} +} + +func (_c *AccessAPIServer_GetAccountBalanceAtLatestBlock_Call) Run(run func(context1 context.Context, getAccountBalanceAtLatestBlockRequest *access.GetAccountBalanceAtLatestBlockRequest)) *AccessAPIServer_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountBalanceAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountBalanceAtLatestBlockRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountBalanceAtLatestBlock_Call) Return(accountBalanceResponse *access.AccountBalanceResponse, err error) *AccessAPIServer_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(accountBalanceResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountBalanceAtLatestBlock_Call) RunAndReturn(run func(context1 context.Context, getAccountBalanceAtLatestBlockRequest *access.GetAccountBalanceAtLatestBlockRequest) (*access.AccountBalanceResponse, error)) *AccessAPIServer_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtBlockHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountKeyAtBlockHeight(context1 context.Context, getAccountKeyAtBlockHeightRequest *access.GetAccountKeyAtBlockHeightRequest) (*access.AccountKeyResponse, error) { + ret := _mock.Called(context1, getAccountKeyAtBlockHeightRequest) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtBlockHeight") @@ -265,29 +592,67 @@ func (_m *AccessAPIServer) GetAccountKeyAtBlockHeight(_a0 context.Context, _a1 * var r0 *access.AccountKeyResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest) (*access.AccountKeyResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest) (*access.AccountKeyResponse, error)); ok { + return returnFunc(context1, getAccountKeyAtBlockHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest) *access.AccountKeyResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest) *access.AccountKeyResponse); ok { + r0 = returnFunc(context1, getAccountKeyAtBlockHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeyResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtBlockHeightRequest) error); ok { + r1 = returnFunc(context1, getAccountKeyAtBlockHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountKeyAtLatestBlock(_a0 context.Context, _a1 *access.GetAccountKeyAtLatestBlockRequest) (*access.AccountKeyResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountKeyAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtBlockHeight' +type AccessAPIServer_GetAccountKeyAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeyAtBlockHeight is a helper method to define mock.On call +// - context1 context.Context +// - getAccountKeyAtBlockHeightRequest *access.GetAccountKeyAtBlockHeightRequest +func (_e *AccessAPIServer_Expecter) GetAccountKeyAtBlockHeight(context1 interface{}, getAccountKeyAtBlockHeightRequest interface{}) *AccessAPIServer_GetAccountKeyAtBlockHeight_Call { + return &AccessAPIServer_GetAccountKeyAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeyAtBlockHeight", context1, getAccountKeyAtBlockHeightRequest)} +} + +func (_c *AccessAPIServer_GetAccountKeyAtBlockHeight_Call) Run(run func(context1 context.Context, getAccountKeyAtBlockHeightRequest *access.GetAccountKeyAtBlockHeightRequest)) *AccessAPIServer_GetAccountKeyAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeyAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeyAtBlockHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeyAtBlockHeight_Call) Return(accountKeyResponse *access.AccountKeyResponse, err error) *AccessAPIServer_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(accountKeyResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeyAtBlockHeight_Call) RunAndReturn(run func(context1 context.Context, getAccountKeyAtBlockHeightRequest *access.GetAccountKeyAtBlockHeightRequest) (*access.AccountKeyResponse, error)) *AccessAPIServer_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtLatestBlock provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountKeyAtLatestBlock(context1 context.Context, getAccountKeyAtLatestBlockRequest *access.GetAccountKeyAtLatestBlockRequest) (*access.AccountKeyResponse, error) { + ret := _mock.Called(context1, getAccountKeyAtLatestBlockRequest) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtLatestBlock") @@ -295,29 +660,67 @@ func (_m *AccessAPIServer) GetAccountKeyAtLatestBlock(_a0 context.Context, _a1 * var r0 *access.AccountKeyResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest) (*access.AccountKeyResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest) (*access.AccountKeyResponse, error)); ok { + return returnFunc(context1, getAccountKeyAtLatestBlockRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest) *access.AccountKeyResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest) *access.AccountKeyResponse); ok { + r0 = returnFunc(context1, getAccountKeyAtLatestBlockRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeyResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeyAtLatestBlockRequest) error); ok { + r1 = returnFunc(context1, getAccountKeyAtLatestBlockRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtBlockHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountKeysAtBlockHeight(_a0 context.Context, _a1 *access.GetAccountKeysAtBlockHeightRequest) (*access.AccountKeysResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountKeyAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtLatestBlock' +type AccessAPIServer_GetAccountKeyAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeyAtLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - getAccountKeyAtLatestBlockRequest *access.GetAccountKeyAtLatestBlockRequest +func (_e *AccessAPIServer_Expecter) GetAccountKeyAtLatestBlock(context1 interface{}, getAccountKeyAtLatestBlockRequest interface{}) *AccessAPIServer_GetAccountKeyAtLatestBlock_Call { + return &AccessAPIServer_GetAccountKeyAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeyAtLatestBlock", context1, getAccountKeyAtLatestBlockRequest)} +} + +func (_c *AccessAPIServer_GetAccountKeyAtLatestBlock_Call) Run(run func(context1 context.Context, getAccountKeyAtLatestBlockRequest *access.GetAccountKeyAtLatestBlockRequest)) *AccessAPIServer_GetAccountKeyAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeyAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeyAtLatestBlockRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeyAtLatestBlock_Call) Return(accountKeyResponse *access.AccountKeyResponse, err error) *AccessAPIServer_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(accountKeyResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeyAtLatestBlock_Call) RunAndReturn(run func(context1 context.Context, getAccountKeyAtLatestBlockRequest *access.GetAccountKeyAtLatestBlockRequest) (*access.AccountKeyResponse, error)) *AccessAPIServer_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtBlockHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountKeysAtBlockHeight(context1 context.Context, getAccountKeysAtBlockHeightRequest *access.GetAccountKeysAtBlockHeightRequest) (*access.AccountKeysResponse, error) { + ret := _mock.Called(context1, getAccountKeysAtBlockHeightRequest) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtBlockHeight") @@ -325,29 +728,67 @@ func (_m *AccessAPIServer) GetAccountKeysAtBlockHeight(_a0 context.Context, _a1 var r0 *access.AccountKeysResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest) (*access.AccountKeysResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest) (*access.AccountKeysResponse, error)); ok { + return returnFunc(context1, getAccountKeysAtBlockHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest) *access.AccountKeysResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest) *access.AccountKeysResponse); ok { + r0 = returnFunc(context1, getAccountKeysAtBlockHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeysResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtBlockHeightRequest) error); ok { + r1 = returnFunc(context1, getAccountKeysAtBlockHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetAccountKeysAtLatestBlock(_a0 context.Context, _a1 *access.GetAccountKeysAtLatestBlockRequest) (*access.AccountKeysResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountKeysAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtBlockHeight' +type AccessAPIServer_GetAccountKeysAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeysAtBlockHeight is a helper method to define mock.On call +// - context1 context.Context +// - getAccountKeysAtBlockHeightRequest *access.GetAccountKeysAtBlockHeightRequest +func (_e *AccessAPIServer_Expecter) GetAccountKeysAtBlockHeight(context1 interface{}, getAccountKeysAtBlockHeightRequest interface{}) *AccessAPIServer_GetAccountKeysAtBlockHeight_Call { + return &AccessAPIServer_GetAccountKeysAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeysAtBlockHeight", context1, getAccountKeysAtBlockHeightRequest)} +} + +func (_c *AccessAPIServer_GetAccountKeysAtBlockHeight_Call) Run(run func(context1 context.Context, getAccountKeysAtBlockHeightRequest *access.GetAccountKeysAtBlockHeightRequest)) *AccessAPIServer_GetAccountKeysAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeysAtBlockHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeysAtBlockHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeysAtBlockHeight_Call) Return(accountKeysResponse *access.AccountKeysResponse, err error) *AccessAPIServer_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(accountKeysResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeysAtBlockHeight_Call) RunAndReturn(run func(context1 context.Context, getAccountKeysAtBlockHeightRequest *access.GetAccountKeysAtBlockHeightRequest) (*access.AccountKeysResponse, error)) *AccessAPIServer_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtLatestBlock provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetAccountKeysAtLatestBlock(context1 context.Context, getAccountKeysAtLatestBlockRequest *access.GetAccountKeysAtLatestBlockRequest) (*access.AccountKeysResponse, error) { + ret := _mock.Called(context1, getAccountKeysAtLatestBlockRequest) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtLatestBlock") @@ -355,29 +796,67 @@ func (_m *AccessAPIServer) GetAccountKeysAtLatestBlock(_a0 context.Context, _a1 var r0 *access.AccountKeysResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest) (*access.AccountKeysResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest) (*access.AccountKeysResponse, error)); ok { + return returnFunc(context1, getAccountKeysAtLatestBlockRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest) *access.AccountKeysResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest) *access.AccountKeysResponse); ok { + r0 = returnFunc(context1, getAccountKeysAtLatestBlockRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.AccountKeysResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetAccountKeysAtLatestBlockRequest) error); ok { + r1 = returnFunc(context1, getAccountKeysAtLatestBlockRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockByHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetBlockByHeight(_a0 context.Context, _a1 *access.GetBlockByHeightRequest) (*access.BlockResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetAccountKeysAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtLatestBlock' +type AccessAPIServer_GetAccountKeysAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeysAtLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - getAccountKeysAtLatestBlockRequest *access.GetAccountKeysAtLatestBlockRequest +func (_e *AccessAPIServer_Expecter) GetAccountKeysAtLatestBlock(context1 interface{}, getAccountKeysAtLatestBlockRequest interface{}) *AccessAPIServer_GetAccountKeysAtLatestBlock_Call { + return &AccessAPIServer_GetAccountKeysAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeysAtLatestBlock", context1, getAccountKeysAtLatestBlockRequest)} +} + +func (_c *AccessAPIServer_GetAccountKeysAtLatestBlock_Call) Run(run func(context1 context.Context, getAccountKeysAtLatestBlockRequest *access.GetAccountKeysAtLatestBlockRequest)) *AccessAPIServer_GetAccountKeysAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetAccountKeysAtLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetAccountKeysAtLatestBlockRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeysAtLatestBlock_Call) Return(accountKeysResponse *access.AccountKeysResponse, err error) *AccessAPIServer_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(accountKeysResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetAccountKeysAtLatestBlock_Call) RunAndReturn(run func(context1 context.Context, getAccountKeysAtLatestBlockRequest *access.GetAccountKeysAtLatestBlockRequest) (*access.AccountKeysResponse, error)) *AccessAPIServer_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetBlockByHeight(context1 context.Context, getBlockByHeightRequest *access.GetBlockByHeightRequest) (*access.BlockResponse, error) { + ret := _mock.Called(context1, getBlockByHeightRequest) if len(ret) == 0 { panic("no return value specified for GetBlockByHeight") @@ -385,29 +864,67 @@ func (_m *AccessAPIServer) GetBlockByHeight(_a0 context.Context, _a1 *access.Get var r0 *access.BlockResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest) (*access.BlockResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest) (*access.BlockResponse, error)); ok { + return returnFunc(context1, getBlockByHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest) *access.BlockResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByHeightRequest) *access.BlockResponse); ok { + r0 = returnFunc(context1, getBlockByHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockByHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockByHeightRequest) error); ok { + r1 = returnFunc(context1, getBlockByHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockByID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetBlockByID(_a0 context.Context, _a1 *access.GetBlockByIDRequest) (*access.BlockResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetBlockByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByHeight' +type AccessAPIServer_GetBlockByHeight_Call struct { + *mock.Call +} + +// GetBlockByHeight is a helper method to define mock.On call +// - context1 context.Context +// - getBlockByHeightRequest *access.GetBlockByHeightRequest +func (_e *AccessAPIServer_Expecter) GetBlockByHeight(context1 interface{}, getBlockByHeightRequest interface{}) *AccessAPIServer_GetBlockByHeight_Call { + return &AccessAPIServer_GetBlockByHeight_Call{Call: _e.mock.On("GetBlockByHeight", context1, getBlockByHeightRequest)} +} + +func (_c *AccessAPIServer_GetBlockByHeight_Call) Run(run func(context1 context.Context, getBlockByHeightRequest *access.GetBlockByHeightRequest)) *AccessAPIServer_GetBlockByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockByHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockByHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetBlockByHeight_Call) Return(blockResponse *access.BlockResponse, err error) *AccessAPIServer_GetBlockByHeight_Call { + _c.Call.Return(blockResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetBlockByHeight_Call) RunAndReturn(run func(context1 context.Context, getBlockByHeightRequest *access.GetBlockByHeightRequest) (*access.BlockResponse, error)) *AccessAPIServer_GetBlockByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetBlockByID(context1 context.Context, getBlockByIDRequest *access.GetBlockByIDRequest) (*access.BlockResponse, error) { + ret := _mock.Called(context1, getBlockByIDRequest) if len(ret) == 0 { panic("no return value specified for GetBlockByID") @@ -415,29 +932,67 @@ func (_m *AccessAPIServer) GetBlockByID(_a0 context.Context, _a1 *access.GetBloc var r0 *access.BlockResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest) (*access.BlockResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest) (*access.BlockResponse, error)); ok { + return returnFunc(context1, getBlockByIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest) *access.BlockResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockByIDRequest) *access.BlockResponse); ok { + r0 = returnFunc(context1, getBlockByIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockByIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockByIDRequest) error); ok { + r1 = returnFunc(context1, getBlockByIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetBlockHeaderByHeight(_a0 context.Context, _a1 *access.GetBlockHeaderByHeightRequest) (*access.BlockHeaderResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetBlockByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByID' +type AccessAPIServer_GetBlockByID_Call struct { + *mock.Call +} + +// GetBlockByID is a helper method to define mock.On call +// - context1 context.Context +// - getBlockByIDRequest *access.GetBlockByIDRequest +func (_e *AccessAPIServer_Expecter) GetBlockByID(context1 interface{}, getBlockByIDRequest interface{}) *AccessAPIServer_GetBlockByID_Call { + return &AccessAPIServer_GetBlockByID_Call{Call: _e.mock.On("GetBlockByID", context1, getBlockByIDRequest)} +} + +func (_c *AccessAPIServer_GetBlockByID_Call) Run(run func(context1 context.Context, getBlockByIDRequest *access.GetBlockByIDRequest)) *AccessAPIServer_GetBlockByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockByIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetBlockByID_Call) Return(blockResponse *access.BlockResponse, err error) *AccessAPIServer_GetBlockByID_Call { + _c.Call.Return(blockResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetBlockByID_Call) RunAndReturn(run func(context1 context.Context, getBlockByIDRequest *access.GetBlockByIDRequest) (*access.BlockResponse, error)) *AccessAPIServer_GetBlockByID_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetBlockHeaderByHeight(context1 context.Context, getBlockHeaderByHeightRequest *access.GetBlockHeaderByHeightRequest) (*access.BlockHeaderResponse, error) { + ret := _mock.Called(context1, getBlockHeaderByHeightRequest) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByHeight") @@ -445,29 +1000,67 @@ func (_m *AccessAPIServer) GetBlockHeaderByHeight(_a0 context.Context, _a1 *acce var r0 *access.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest) (*access.BlockHeaderResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest) (*access.BlockHeaderResponse, error)); ok { + return returnFunc(context1, getBlockHeaderByHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest) *access.BlockHeaderResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByHeightRequest) *access.BlockHeaderResponse); ok { + r0 = returnFunc(context1, getBlockHeaderByHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByHeightRequest) error); ok { + r1 = returnFunc(context1, getBlockHeaderByHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetBlockHeaderByID(_a0 context.Context, _a1 *access.GetBlockHeaderByIDRequest) (*access.BlockHeaderResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetBlockHeaderByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByHeight' +type AccessAPIServer_GetBlockHeaderByHeight_Call struct { + *mock.Call +} + +// GetBlockHeaderByHeight is a helper method to define mock.On call +// - context1 context.Context +// - getBlockHeaderByHeightRequest *access.GetBlockHeaderByHeightRequest +func (_e *AccessAPIServer_Expecter) GetBlockHeaderByHeight(context1 interface{}, getBlockHeaderByHeightRequest interface{}) *AccessAPIServer_GetBlockHeaderByHeight_Call { + return &AccessAPIServer_GetBlockHeaderByHeight_Call{Call: _e.mock.On("GetBlockHeaderByHeight", context1, getBlockHeaderByHeightRequest)} +} + +func (_c *AccessAPIServer_GetBlockHeaderByHeight_Call) Run(run func(context1 context.Context, getBlockHeaderByHeightRequest *access.GetBlockHeaderByHeightRequest)) *AccessAPIServer_GetBlockHeaderByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockHeaderByHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockHeaderByHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetBlockHeaderByHeight_Call) Return(blockHeaderResponse *access.BlockHeaderResponse, err error) *AccessAPIServer_GetBlockHeaderByHeight_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetBlockHeaderByHeight_Call) RunAndReturn(run func(context1 context.Context, getBlockHeaderByHeightRequest *access.GetBlockHeaderByHeightRequest) (*access.BlockHeaderResponse, error)) *AccessAPIServer_GetBlockHeaderByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetBlockHeaderByID(context1 context.Context, getBlockHeaderByIDRequest *access.GetBlockHeaderByIDRequest) (*access.BlockHeaderResponse, error) { + ret := _mock.Called(context1, getBlockHeaderByIDRequest) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByID") @@ -475,29 +1068,67 @@ func (_m *AccessAPIServer) GetBlockHeaderByID(_a0 context.Context, _a1 *access.G var r0 *access.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest) (*access.BlockHeaderResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest) (*access.BlockHeaderResponse, error)); ok { + return returnFunc(context1, getBlockHeaderByIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest) *access.BlockHeaderResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetBlockHeaderByIDRequest) *access.BlockHeaderResponse); ok { + r0 = returnFunc(context1, getBlockHeaderByIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetBlockHeaderByIDRequest) error); ok { + r1 = returnFunc(context1, getBlockHeaderByIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCollectionByID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetCollectionByID(_a0 context.Context, _a1 *access.GetCollectionByIDRequest) (*access.CollectionResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetBlockHeaderByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByID' +type AccessAPIServer_GetBlockHeaderByID_Call struct { + *mock.Call +} + +// GetBlockHeaderByID is a helper method to define mock.On call +// - context1 context.Context +// - getBlockHeaderByIDRequest *access.GetBlockHeaderByIDRequest +func (_e *AccessAPIServer_Expecter) GetBlockHeaderByID(context1 interface{}, getBlockHeaderByIDRequest interface{}) *AccessAPIServer_GetBlockHeaderByID_Call { + return &AccessAPIServer_GetBlockHeaderByID_Call{Call: _e.mock.On("GetBlockHeaderByID", context1, getBlockHeaderByIDRequest)} +} + +func (_c *AccessAPIServer_GetBlockHeaderByID_Call) Run(run func(context1 context.Context, getBlockHeaderByIDRequest *access.GetBlockHeaderByIDRequest)) *AccessAPIServer_GetBlockHeaderByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetBlockHeaderByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetBlockHeaderByIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetBlockHeaderByID_Call) Return(blockHeaderResponse *access.BlockHeaderResponse, err error) *AccessAPIServer_GetBlockHeaderByID_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetBlockHeaderByID_Call) RunAndReturn(run func(context1 context.Context, getBlockHeaderByIDRequest *access.GetBlockHeaderByIDRequest) (*access.BlockHeaderResponse, error)) *AccessAPIServer_GetBlockHeaderByID_Call { + _c.Call.Return(run) + return _c +} + +// GetCollectionByID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetCollectionByID(context1 context.Context, getCollectionByIDRequest *access.GetCollectionByIDRequest) (*access.CollectionResponse, error) { + ret := _mock.Called(context1, getCollectionByIDRequest) if len(ret) == 0 { panic("no return value specified for GetCollectionByID") @@ -505,59 +1136,135 @@ func (_m *AccessAPIServer) GetCollectionByID(_a0 context.Context, _a1 *access.Ge var r0 *access.CollectionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest) (*access.CollectionResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest) (*access.CollectionResponse, error)); ok { + return returnFunc(context1, getCollectionByIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest) *access.CollectionResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetCollectionByIDRequest) *access.CollectionResponse); ok { + r0 = returnFunc(context1, getCollectionByIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.CollectionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetCollectionByIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetCollectionByIDRequest) error); ok { + r1 = returnFunc(context1, getCollectionByIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForBlockIDs provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetEventsForBlockIDs(_a0 context.Context, _a1 *access.GetEventsForBlockIDsRequest) (*access.EventsResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCollectionByID' +type AccessAPIServer_GetCollectionByID_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetEventsForBlockIDs") - } +// GetCollectionByID is a helper method to define mock.On call +// - context1 context.Context +// - getCollectionByIDRequest *access.GetCollectionByIDRequest +func (_e *AccessAPIServer_Expecter) GetCollectionByID(context1 interface{}, getCollectionByIDRequest interface{}) *AccessAPIServer_GetCollectionByID_Call { + return &AccessAPIServer_GetCollectionByID_Call{Call: _e.mock.On("GetCollectionByID", context1, getCollectionByIDRequest)} +} - var r0 *access.EventsResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest) (*access.EventsResponse, error)); ok { - return rf(_a0, _a1) - } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest) *access.EventsResponse); ok { - r0 = rf(_a0, _a1) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*access.EventsResponse) +func (_c *AccessAPIServer_GetCollectionByID_Call) Run(run func(context1 context.Context, getCollectionByIDRequest *access.GetCollectionByIDRequest)) *AccessAPIServer_GetCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) } + var arg1 *access.GetCollectionByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetCollectionByIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetCollectionByID_Call) Return(collectionResponse *access.CollectionResponse, err error) *AccessAPIServer_GetCollectionByID_Call { + _c.Call.Return(collectionResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetCollectionByID_Call) RunAndReturn(run func(context1 context.Context, getCollectionByIDRequest *access.GetCollectionByIDRequest) (*access.CollectionResponse, error)) *AccessAPIServer_GetCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForBlockIDs provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetEventsForBlockIDs(context1 context.Context, getEventsForBlockIDsRequest *access.GetEventsForBlockIDsRequest) (*access.EventsResponse, error) { + ret := _mock.Called(context1, getEventsForBlockIDsRequest) + + if len(ret) == 0 { + panic("no return value specified for GetEventsForBlockIDs") } - if rf, ok := ret.Get(1).(func(context.Context, *access.GetEventsForBlockIDsRequest) error); ok { - r1 = rf(_a0, _a1) + var r0 *access.EventsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest) (*access.EventsResponse, error)); ok { + return returnFunc(context1, getEventsForBlockIDsRequest) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForBlockIDsRequest) *access.EventsResponse); ok { + r0 = returnFunc(context1, getEventsForBlockIDsRequest) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.EventsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetEventsForBlockIDsRequest) error); ok { + r1 = returnFunc(context1, getEventsForBlockIDsRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForHeightRange provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetEventsForHeightRange(_a0 context.Context, _a1 *access.GetEventsForHeightRangeRequest) (*access.EventsResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetEventsForBlockIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForBlockIDs' +type AccessAPIServer_GetEventsForBlockIDs_Call struct { + *mock.Call +} + +// GetEventsForBlockIDs is a helper method to define mock.On call +// - context1 context.Context +// - getEventsForBlockIDsRequest *access.GetEventsForBlockIDsRequest +func (_e *AccessAPIServer_Expecter) GetEventsForBlockIDs(context1 interface{}, getEventsForBlockIDsRequest interface{}) *AccessAPIServer_GetEventsForBlockIDs_Call { + return &AccessAPIServer_GetEventsForBlockIDs_Call{Call: _e.mock.On("GetEventsForBlockIDs", context1, getEventsForBlockIDsRequest)} +} + +func (_c *AccessAPIServer_GetEventsForBlockIDs_Call) Run(run func(context1 context.Context, getEventsForBlockIDsRequest *access.GetEventsForBlockIDsRequest)) *AccessAPIServer_GetEventsForBlockIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetEventsForBlockIDsRequest + if args[1] != nil { + arg1 = args[1].(*access.GetEventsForBlockIDsRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetEventsForBlockIDs_Call) Return(eventsResponse *access.EventsResponse, err error) *AccessAPIServer_GetEventsForBlockIDs_Call { + _c.Call.Return(eventsResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetEventsForBlockIDs_Call) RunAndReturn(run func(context1 context.Context, getEventsForBlockIDsRequest *access.GetEventsForBlockIDsRequest) (*access.EventsResponse, error)) *AccessAPIServer_GetEventsForBlockIDs_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForHeightRange provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetEventsForHeightRange(context1 context.Context, getEventsForHeightRangeRequest *access.GetEventsForHeightRangeRequest) (*access.EventsResponse, error) { + ret := _mock.Called(context1, getEventsForHeightRangeRequest) if len(ret) == 0 { panic("no return value specified for GetEventsForHeightRange") @@ -565,29 +1272,203 @@ func (_m *AccessAPIServer) GetEventsForHeightRange(_a0 context.Context, _a1 *acc var r0 *access.EventsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest) (*access.EventsResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest) (*access.EventsResponse, error)); ok { + return returnFunc(context1, getEventsForHeightRangeRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest) *access.EventsResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetEventsForHeightRangeRequest) *access.EventsResponse); ok { + r0 = returnFunc(context1, getEventsForHeightRangeRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.EventsResponse) } } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetEventsForHeightRangeRequest) error); ok { + r1 = returnFunc(context1, getEventsForHeightRangeRequest) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccessAPIServer_GetEventsForHeightRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForHeightRange' +type AccessAPIServer_GetEventsForHeightRange_Call struct { + *mock.Call +} + +// GetEventsForHeightRange is a helper method to define mock.On call +// - context1 context.Context +// - getEventsForHeightRangeRequest *access.GetEventsForHeightRangeRequest +func (_e *AccessAPIServer_Expecter) GetEventsForHeightRange(context1 interface{}, getEventsForHeightRangeRequest interface{}) *AccessAPIServer_GetEventsForHeightRange_Call { + return &AccessAPIServer_GetEventsForHeightRange_Call{Call: _e.mock.On("GetEventsForHeightRange", context1, getEventsForHeightRangeRequest)} +} + +func (_c *AccessAPIServer_GetEventsForHeightRange_Call) Run(run func(context1 context.Context, getEventsForHeightRangeRequest *access.GetEventsForHeightRangeRequest)) *AccessAPIServer_GetEventsForHeightRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetEventsForHeightRangeRequest + if args[1] != nil { + arg1 = args[1].(*access.GetEventsForHeightRangeRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetEventsForHeightRange_Call) Return(eventsResponse *access.EventsResponse, err error) *AccessAPIServer_GetEventsForHeightRange_Call { + _c.Call.Return(eventsResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetEventsForHeightRange_Call) RunAndReturn(run func(context1 context.Context, getEventsForHeightRangeRequest *access.GetEventsForHeightRangeRequest) (*access.EventsResponse, error)) *AccessAPIServer_GetEventsForHeightRange_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionReceiptsByBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetExecutionReceiptsByBlockID(context1 context.Context, getExecutionReceiptsByBlockIDRequest *access.GetExecutionReceiptsByBlockIDRequest) (*access.ExecutionReceiptsResponse, error) { + ret := _mock.Called(context1, getExecutionReceiptsByBlockIDRequest) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByBlockID") + } - if rf, ok := ret.Get(1).(func(context.Context, *access.GetEventsForHeightRangeRequest) error); ok { - r1 = rf(_a0, _a1) + var r0 *access.ExecutionReceiptsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByBlockIDRequest) (*access.ExecutionReceiptsResponse, error)); ok { + return returnFunc(context1, getExecutionReceiptsByBlockIDRequest) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByBlockIDRequest) *access.ExecutionReceiptsResponse); ok { + r0 = returnFunc(context1, getExecutionReceiptsByBlockIDRequest) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ExecutionReceiptsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionReceiptsByBlockIDRequest) error); ok { + r1 = returnFunc(context1, getExecutionReceiptsByBlockIDRequest) } else { r1 = ret.Error(1) } + return r0, r1 +} + +// AccessAPIServer_GetExecutionReceiptsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByBlockID' +type AccessAPIServer_GetExecutionReceiptsByBlockID_Call struct { + *mock.Call +} + +// GetExecutionReceiptsByBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getExecutionReceiptsByBlockIDRequest *access.GetExecutionReceiptsByBlockIDRequest +func (_e *AccessAPIServer_Expecter) GetExecutionReceiptsByBlockID(context1 interface{}, getExecutionReceiptsByBlockIDRequest interface{}) *AccessAPIServer_GetExecutionReceiptsByBlockID_Call { + return &AccessAPIServer_GetExecutionReceiptsByBlockID_Call{Call: _e.mock.On("GetExecutionReceiptsByBlockID", context1, getExecutionReceiptsByBlockIDRequest)} +} + +func (_c *AccessAPIServer_GetExecutionReceiptsByBlockID_Call) Run(run func(context1 context.Context, getExecutionReceiptsByBlockIDRequest *access.GetExecutionReceiptsByBlockIDRequest)) *AccessAPIServer_GetExecutionReceiptsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionReceiptsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionReceiptsByBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetExecutionReceiptsByBlockID_Call) Return(executionReceiptsResponse *access.ExecutionReceiptsResponse, err error) *AccessAPIServer_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(executionReceiptsResponse, err) + return _c +} +func (_c *AccessAPIServer_GetExecutionReceiptsByBlockID_Call) RunAndReturn(run func(context1 context.Context, getExecutionReceiptsByBlockIDRequest *access.GetExecutionReceiptsByBlockIDRequest) (*access.ExecutionReceiptsResponse, error)) *AccessAPIServer_GetExecutionReceiptsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionReceiptsByResultID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetExecutionReceiptsByResultID(context1 context.Context, getExecutionReceiptsByResultIDRequest *access.GetExecutionReceiptsByResultIDRequest) (*access.ExecutionReceiptsResponse, error) { + ret := _mock.Called(context1, getExecutionReceiptsByResultIDRequest) + + if len(ret) == 0 { + panic("no return value specified for GetExecutionReceiptsByResultID") + } + + var r0 *access.ExecutionReceiptsResponse + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByResultIDRequest) (*access.ExecutionReceiptsResponse, error)); ok { + return returnFunc(context1, getExecutionReceiptsByResultIDRequest) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionReceiptsByResultIDRequest) *access.ExecutionReceiptsResponse); ok { + r0 = returnFunc(context1, getExecutionReceiptsByResultIDRequest) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*access.ExecutionReceiptsResponse) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionReceiptsByResultIDRequest) error); ok { + r1 = returnFunc(context1, getExecutionReceiptsByResultIDRequest) + } else { + r1 = ret.Error(1) + } return r0, r1 } -// GetExecutionResultByID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetExecutionResultByID(_a0 context.Context, _a1 *access.GetExecutionResultByIDRequest) (*access.ExecutionResultByIDResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetExecutionReceiptsByResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionReceiptsByResultID' +type AccessAPIServer_GetExecutionReceiptsByResultID_Call struct { + *mock.Call +} + +// GetExecutionReceiptsByResultID is a helper method to define mock.On call +// - context1 context.Context +// - getExecutionReceiptsByResultIDRequest *access.GetExecutionReceiptsByResultIDRequest +func (_e *AccessAPIServer_Expecter) GetExecutionReceiptsByResultID(context1 interface{}, getExecutionReceiptsByResultIDRequest interface{}) *AccessAPIServer_GetExecutionReceiptsByResultID_Call { + return &AccessAPIServer_GetExecutionReceiptsByResultID_Call{Call: _e.mock.On("GetExecutionReceiptsByResultID", context1, getExecutionReceiptsByResultIDRequest)} +} + +func (_c *AccessAPIServer_GetExecutionReceiptsByResultID_Call) Run(run func(context1 context.Context, getExecutionReceiptsByResultIDRequest *access.GetExecutionReceiptsByResultIDRequest)) *AccessAPIServer_GetExecutionReceiptsByResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionReceiptsByResultIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionReceiptsByResultIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetExecutionReceiptsByResultID_Call) Return(executionReceiptsResponse *access.ExecutionReceiptsResponse, err error) *AccessAPIServer_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(executionReceiptsResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetExecutionReceiptsByResultID_Call) RunAndReturn(run func(context1 context.Context, getExecutionReceiptsByResultIDRequest *access.GetExecutionReceiptsByResultIDRequest) (*access.ExecutionReceiptsResponse, error)) *AccessAPIServer_GetExecutionReceiptsByResultID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultByID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetExecutionResultByID(context1 context.Context, getExecutionResultByIDRequest *access.GetExecutionResultByIDRequest) (*access.ExecutionResultByIDResponse, error) { + ret := _mock.Called(context1, getExecutionResultByIDRequest) if len(ret) == 0 { panic("no return value specified for GetExecutionResultByID") @@ -595,29 +1476,67 @@ func (_m *AccessAPIServer) GetExecutionResultByID(_a0 context.Context, _a1 *acce var r0 *access.ExecutionResultByIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest) (*access.ExecutionResultByIDResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest) (*access.ExecutionResultByIDResponse, error)); ok { + return returnFunc(context1, getExecutionResultByIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest) *access.ExecutionResultByIDResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultByIDRequest) *access.ExecutionResultByIDResponse); ok { + r0 = returnFunc(context1, getExecutionResultByIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecutionResultByIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultByIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultByIDRequest) error); ok { + r1 = returnFunc(context1, getExecutionResultByIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionResultForBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetExecutionResultForBlockID(_a0 context.Context, _a1 *access.GetExecutionResultForBlockIDRequest) (*access.ExecutionResultForBlockIDResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetExecutionResultByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultByID' +type AccessAPIServer_GetExecutionResultByID_Call struct { + *mock.Call +} + +// GetExecutionResultByID is a helper method to define mock.On call +// - context1 context.Context +// - getExecutionResultByIDRequest *access.GetExecutionResultByIDRequest +func (_e *AccessAPIServer_Expecter) GetExecutionResultByID(context1 interface{}, getExecutionResultByIDRequest interface{}) *AccessAPIServer_GetExecutionResultByID_Call { + return &AccessAPIServer_GetExecutionResultByID_Call{Call: _e.mock.On("GetExecutionResultByID", context1, getExecutionResultByIDRequest)} +} + +func (_c *AccessAPIServer_GetExecutionResultByID_Call) Run(run func(context1 context.Context, getExecutionResultByIDRequest *access.GetExecutionResultByIDRequest)) *AccessAPIServer_GetExecutionResultByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionResultByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionResultByIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetExecutionResultByID_Call) Return(executionResultByIDResponse *access.ExecutionResultByIDResponse, err error) *AccessAPIServer_GetExecutionResultByID_Call { + _c.Call.Return(executionResultByIDResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetExecutionResultByID_Call) RunAndReturn(run func(context1 context.Context, getExecutionResultByIDRequest *access.GetExecutionResultByIDRequest) (*access.ExecutionResultByIDResponse, error)) *AccessAPIServer_GetExecutionResultByID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultForBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetExecutionResultForBlockID(context1 context.Context, getExecutionResultForBlockIDRequest *access.GetExecutionResultForBlockIDRequest) (*access.ExecutionResultForBlockIDResponse, error) { + ret := _mock.Called(context1, getExecutionResultForBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetExecutionResultForBlockID") @@ -625,29 +1544,67 @@ func (_m *AccessAPIServer) GetExecutionResultForBlockID(_a0 context.Context, _a1 var r0 *access.ExecutionResultForBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest) (*access.ExecutionResultForBlockIDResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest) (*access.ExecutionResultForBlockIDResponse, error)); ok { + return returnFunc(context1, getExecutionResultForBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest) *access.ExecutionResultForBlockIDResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetExecutionResultForBlockIDRequest) *access.ExecutionResultForBlockIDResponse); ok { + r0 = returnFunc(context1, getExecutionResultForBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ExecutionResultForBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultForBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetExecutionResultForBlockIDRequest) error); ok { + r1 = returnFunc(context1, getExecutionResultForBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetFullCollectionByID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetFullCollectionByID(_a0 context.Context, _a1 *access.GetFullCollectionByIDRequest) (*access.FullCollectionResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetExecutionResultForBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultForBlockID' +type AccessAPIServer_GetExecutionResultForBlockID_Call struct { + *mock.Call +} + +// GetExecutionResultForBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getExecutionResultForBlockIDRequest *access.GetExecutionResultForBlockIDRequest +func (_e *AccessAPIServer_Expecter) GetExecutionResultForBlockID(context1 interface{}, getExecutionResultForBlockIDRequest interface{}) *AccessAPIServer_GetExecutionResultForBlockID_Call { + return &AccessAPIServer_GetExecutionResultForBlockID_Call{Call: _e.mock.On("GetExecutionResultForBlockID", context1, getExecutionResultForBlockIDRequest)} +} + +func (_c *AccessAPIServer_GetExecutionResultForBlockID_Call) Run(run func(context1 context.Context, getExecutionResultForBlockIDRequest *access.GetExecutionResultForBlockIDRequest)) *AccessAPIServer_GetExecutionResultForBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetExecutionResultForBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetExecutionResultForBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetExecutionResultForBlockID_Call) Return(executionResultForBlockIDResponse *access.ExecutionResultForBlockIDResponse, err error) *AccessAPIServer_GetExecutionResultForBlockID_Call { + _c.Call.Return(executionResultForBlockIDResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetExecutionResultForBlockID_Call) RunAndReturn(run func(context1 context.Context, getExecutionResultForBlockIDRequest *access.GetExecutionResultForBlockIDRequest) (*access.ExecutionResultForBlockIDResponse, error)) *AccessAPIServer_GetExecutionResultForBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetFullCollectionByID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetFullCollectionByID(context1 context.Context, getFullCollectionByIDRequest *access.GetFullCollectionByIDRequest) (*access.FullCollectionResponse, error) { + ret := _mock.Called(context1, getFullCollectionByIDRequest) if len(ret) == 0 { panic("no return value specified for GetFullCollectionByID") @@ -655,29 +1612,67 @@ func (_m *AccessAPIServer) GetFullCollectionByID(_a0 context.Context, _a1 *acces var r0 *access.FullCollectionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest) (*access.FullCollectionResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest) (*access.FullCollectionResponse, error)); ok { + return returnFunc(context1, getFullCollectionByIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest) *access.FullCollectionResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetFullCollectionByIDRequest) *access.FullCollectionResponse); ok { + r0 = returnFunc(context1, getFullCollectionByIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.FullCollectionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetFullCollectionByIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetFullCollectionByIDRequest) error); ok { + r1 = returnFunc(context1, getFullCollectionByIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetLatestBlock(_a0 context.Context, _a1 *access.GetLatestBlockRequest) (*access.BlockResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetFullCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFullCollectionByID' +type AccessAPIServer_GetFullCollectionByID_Call struct { + *mock.Call +} + +// GetFullCollectionByID is a helper method to define mock.On call +// - context1 context.Context +// - getFullCollectionByIDRequest *access.GetFullCollectionByIDRequest +func (_e *AccessAPIServer_Expecter) GetFullCollectionByID(context1 interface{}, getFullCollectionByIDRequest interface{}) *AccessAPIServer_GetFullCollectionByID_Call { + return &AccessAPIServer_GetFullCollectionByID_Call{Call: _e.mock.On("GetFullCollectionByID", context1, getFullCollectionByIDRequest)} +} + +func (_c *AccessAPIServer_GetFullCollectionByID_Call) Run(run func(context1 context.Context, getFullCollectionByIDRequest *access.GetFullCollectionByIDRequest)) *AccessAPIServer_GetFullCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetFullCollectionByIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetFullCollectionByIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetFullCollectionByID_Call) Return(fullCollectionResponse *access.FullCollectionResponse, err error) *AccessAPIServer_GetFullCollectionByID_Call { + _c.Call.Return(fullCollectionResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetFullCollectionByID_Call) RunAndReturn(run func(context1 context.Context, getFullCollectionByIDRequest *access.GetFullCollectionByIDRequest) (*access.FullCollectionResponse, error)) *AccessAPIServer_GetFullCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlock provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetLatestBlock(context1 context.Context, getLatestBlockRequest *access.GetLatestBlockRequest) (*access.BlockResponse, error) { + ret := _mock.Called(context1, getLatestBlockRequest) if len(ret) == 0 { panic("no return value specified for GetLatestBlock") @@ -685,29 +1680,67 @@ func (_m *AccessAPIServer) GetLatestBlock(_a0 context.Context, _a1 *access.GetLa var r0 *access.BlockResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest) (*access.BlockResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest) (*access.BlockResponse, error)); ok { + return returnFunc(context1, getLatestBlockRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest) *access.BlockResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockRequest) *access.BlockResponse); ok { + r0 = returnFunc(context1, getLatestBlockRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockRequest) error); ok { + r1 = returnFunc(context1, getLatestBlockRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlockHeader provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetLatestBlockHeader(_a0 context.Context, _a1 *access.GetLatestBlockHeaderRequest) (*access.BlockHeaderResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlock' +type AccessAPIServer_GetLatestBlock_Call struct { + *mock.Call +} + +// GetLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - getLatestBlockRequest *access.GetLatestBlockRequest +func (_e *AccessAPIServer_Expecter) GetLatestBlock(context1 interface{}, getLatestBlockRequest interface{}) *AccessAPIServer_GetLatestBlock_Call { + return &AccessAPIServer_GetLatestBlock_Call{Call: _e.mock.On("GetLatestBlock", context1, getLatestBlockRequest)} +} + +func (_c *AccessAPIServer_GetLatestBlock_Call) Run(run func(context1 context.Context, getLatestBlockRequest *access.GetLatestBlockRequest)) *AccessAPIServer_GetLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetLatestBlockRequest + if args[1] != nil { + arg1 = args[1].(*access.GetLatestBlockRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetLatestBlock_Call) Return(blockResponse *access.BlockResponse, err error) *AccessAPIServer_GetLatestBlock_Call { + _c.Call.Return(blockResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetLatestBlock_Call) RunAndReturn(run func(context1 context.Context, getLatestBlockRequest *access.GetLatestBlockRequest) (*access.BlockResponse, error)) *AccessAPIServer_GetLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlockHeader provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetLatestBlockHeader(context1 context.Context, getLatestBlockHeaderRequest *access.GetLatestBlockHeaderRequest) (*access.BlockHeaderResponse, error) { + ret := _mock.Called(context1, getLatestBlockHeaderRequest) if len(ret) == 0 { panic("no return value specified for GetLatestBlockHeader") @@ -715,29 +1748,67 @@ func (_m *AccessAPIServer) GetLatestBlockHeader(_a0 context.Context, _a1 *access var r0 *access.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest) (*access.BlockHeaderResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest) (*access.BlockHeaderResponse, error)); ok { + return returnFunc(context1, getLatestBlockHeaderRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest) *access.BlockHeaderResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestBlockHeaderRequest) *access.BlockHeaderResponse); ok { + r0 = returnFunc(context1, getLatestBlockHeaderRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockHeaderRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetLatestBlockHeaderRequest) error); ok { + r1 = returnFunc(context1, getLatestBlockHeaderRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestProtocolStateSnapshot provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetLatestProtocolStateSnapshot(_a0 context.Context, _a1 *access.GetLatestProtocolStateSnapshotRequest) (*access.ProtocolStateSnapshotResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetLatestBlockHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlockHeader' +type AccessAPIServer_GetLatestBlockHeader_Call struct { + *mock.Call +} + +// GetLatestBlockHeader is a helper method to define mock.On call +// - context1 context.Context +// - getLatestBlockHeaderRequest *access.GetLatestBlockHeaderRequest +func (_e *AccessAPIServer_Expecter) GetLatestBlockHeader(context1 interface{}, getLatestBlockHeaderRequest interface{}) *AccessAPIServer_GetLatestBlockHeader_Call { + return &AccessAPIServer_GetLatestBlockHeader_Call{Call: _e.mock.On("GetLatestBlockHeader", context1, getLatestBlockHeaderRequest)} +} + +func (_c *AccessAPIServer_GetLatestBlockHeader_Call) Run(run func(context1 context.Context, getLatestBlockHeaderRequest *access.GetLatestBlockHeaderRequest)) *AccessAPIServer_GetLatestBlockHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetLatestBlockHeaderRequest + if args[1] != nil { + arg1 = args[1].(*access.GetLatestBlockHeaderRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetLatestBlockHeader_Call) Return(blockHeaderResponse *access.BlockHeaderResponse, err error) *AccessAPIServer_GetLatestBlockHeader_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetLatestBlockHeader_Call) RunAndReturn(run func(context1 context.Context, getLatestBlockHeaderRequest *access.GetLatestBlockHeaderRequest) (*access.BlockHeaderResponse, error)) *AccessAPIServer_GetLatestBlockHeader_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestProtocolStateSnapshot provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetLatestProtocolStateSnapshot(context1 context.Context, getLatestProtocolStateSnapshotRequest *access.GetLatestProtocolStateSnapshotRequest) (*access.ProtocolStateSnapshotResponse, error) { + ret := _mock.Called(context1, getLatestProtocolStateSnapshotRequest) if len(ret) == 0 { panic("no return value specified for GetLatestProtocolStateSnapshot") @@ -745,29 +1816,67 @@ func (_m *AccessAPIServer) GetLatestProtocolStateSnapshot(_a0 context.Context, _ var r0 *access.ProtocolStateSnapshotResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest) (*access.ProtocolStateSnapshotResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest) (*access.ProtocolStateSnapshotResponse, error)); ok { + return returnFunc(context1, getLatestProtocolStateSnapshotRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest) *access.ProtocolStateSnapshotResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest) *access.ProtocolStateSnapshotResponse); ok { + r0 = returnFunc(context1, getLatestProtocolStateSnapshotRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ProtocolStateSnapshotResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetLatestProtocolStateSnapshotRequest) error); ok { + r1 = returnFunc(context1, getLatestProtocolStateSnapshotRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetNetworkParameters provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetNetworkParameters(_a0 context.Context, _a1 *access.GetNetworkParametersRequest) (*access.GetNetworkParametersResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetLatestProtocolStateSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestProtocolStateSnapshot' +type AccessAPIServer_GetLatestProtocolStateSnapshot_Call struct { + *mock.Call +} + +// GetLatestProtocolStateSnapshot is a helper method to define mock.On call +// - context1 context.Context +// - getLatestProtocolStateSnapshotRequest *access.GetLatestProtocolStateSnapshotRequest +func (_e *AccessAPIServer_Expecter) GetLatestProtocolStateSnapshot(context1 interface{}, getLatestProtocolStateSnapshotRequest interface{}) *AccessAPIServer_GetLatestProtocolStateSnapshot_Call { + return &AccessAPIServer_GetLatestProtocolStateSnapshot_Call{Call: _e.mock.On("GetLatestProtocolStateSnapshot", context1, getLatestProtocolStateSnapshotRequest)} +} + +func (_c *AccessAPIServer_GetLatestProtocolStateSnapshot_Call) Run(run func(context1 context.Context, getLatestProtocolStateSnapshotRequest *access.GetLatestProtocolStateSnapshotRequest)) *AccessAPIServer_GetLatestProtocolStateSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetLatestProtocolStateSnapshotRequest + if args[1] != nil { + arg1 = args[1].(*access.GetLatestProtocolStateSnapshotRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetLatestProtocolStateSnapshot_Call) Return(protocolStateSnapshotResponse *access.ProtocolStateSnapshotResponse, err error) *AccessAPIServer_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(protocolStateSnapshotResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetLatestProtocolStateSnapshot_Call) RunAndReturn(run func(context1 context.Context, getLatestProtocolStateSnapshotRequest *access.GetLatestProtocolStateSnapshotRequest) (*access.ProtocolStateSnapshotResponse, error)) *AccessAPIServer_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// GetNetworkParameters provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetNetworkParameters(context1 context.Context, getNetworkParametersRequest *access.GetNetworkParametersRequest) (*access.GetNetworkParametersResponse, error) { + ret := _mock.Called(context1, getNetworkParametersRequest) if len(ret) == 0 { panic("no return value specified for GetNetworkParameters") @@ -775,29 +1884,67 @@ func (_m *AccessAPIServer) GetNetworkParameters(_a0 context.Context, _a1 *access var r0 *access.GetNetworkParametersResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest) (*access.GetNetworkParametersResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest) (*access.GetNetworkParametersResponse, error)); ok { + return returnFunc(context1, getNetworkParametersRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest) *access.GetNetworkParametersResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNetworkParametersRequest) *access.GetNetworkParametersResponse); ok { + r0 = returnFunc(context1, getNetworkParametersRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.GetNetworkParametersResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetNetworkParametersRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetNetworkParametersRequest) error); ok { + r1 = returnFunc(context1, getNetworkParametersRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetNodeVersionInfo provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetNodeVersionInfo(_a0 context.Context, _a1 *access.GetNodeVersionInfoRequest) (*access.GetNodeVersionInfoResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetNetworkParameters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNetworkParameters' +type AccessAPIServer_GetNetworkParameters_Call struct { + *mock.Call +} + +// GetNetworkParameters is a helper method to define mock.On call +// - context1 context.Context +// - getNetworkParametersRequest *access.GetNetworkParametersRequest +func (_e *AccessAPIServer_Expecter) GetNetworkParameters(context1 interface{}, getNetworkParametersRequest interface{}) *AccessAPIServer_GetNetworkParameters_Call { + return &AccessAPIServer_GetNetworkParameters_Call{Call: _e.mock.On("GetNetworkParameters", context1, getNetworkParametersRequest)} +} + +func (_c *AccessAPIServer_GetNetworkParameters_Call) Run(run func(context1 context.Context, getNetworkParametersRequest *access.GetNetworkParametersRequest)) *AccessAPIServer_GetNetworkParameters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetNetworkParametersRequest + if args[1] != nil { + arg1 = args[1].(*access.GetNetworkParametersRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetNetworkParameters_Call) Return(getNetworkParametersResponse *access.GetNetworkParametersResponse, err error) *AccessAPIServer_GetNetworkParameters_Call { + _c.Call.Return(getNetworkParametersResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetNetworkParameters_Call) RunAndReturn(run func(context1 context.Context, getNetworkParametersRequest *access.GetNetworkParametersRequest) (*access.GetNetworkParametersResponse, error)) *AccessAPIServer_GetNetworkParameters_Call { + _c.Call.Return(run) + return _c +} + +// GetNodeVersionInfo provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetNodeVersionInfo(context1 context.Context, getNodeVersionInfoRequest *access.GetNodeVersionInfoRequest) (*access.GetNodeVersionInfoResponse, error) { + ret := _mock.Called(context1, getNodeVersionInfoRequest) if len(ret) == 0 { panic("no return value specified for GetNodeVersionInfo") @@ -805,29 +1952,67 @@ func (_m *AccessAPIServer) GetNodeVersionInfo(_a0 context.Context, _a1 *access.G var r0 *access.GetNodeVersionInfoResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest) (*access.GetNodeVersionInfoResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest) (*access.GetNodeVersionInfoResponse, error)); ok { + return returnFunc(context1, getNodeVersionInfoRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest) *access.GetNodeVersionInfoResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetNodeVersionInfoRequest) *access.GetNodeVersionInfoResponse); ok { + r0 = returnFunc(context1, getNodeVersionInfoRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.GetNodeVersionInfoResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetNodeVersionInfoRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetNodeVersionInfoRequest) error); ok { + r1 = returnFunc(context1, getNodeVersionInfoRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetProtocolStateSnapshotByBlockID(_a0 context.Context, _a1 *access.GetProtocolStateSnapshotByBlockIDRequest) (*access.ProtocolStateSnapshotResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetNodeVersionInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNodeVersionInfo' +type AccessAPIServer_GetNodeVersionInfo_Call struct { + *mock.Call +} + +// GetNodeVersionInfo is a helper method to define mock.On call +// - context1 context.Context +// - getNodeVersionInfoRequest *access.GetNodeVersionInfoRequest +func (_e *AccessAPIServer_Expecter) GetNodeVersionInfo(context1 interface{}, getNodeVersionInfoRequest interface{}) *AccessAPIServer_GetNodeVersionInfo_Call { + return &AccessAPIServer_GetNodeVersionInfo_Call{Call: _e.mock.On("GetNodeVersionInfo", context1, getNodeVersionInfoRequest)} +} + +func (_c *AccessAPIServer_GetNodeVersionInfo_Call) Run(run func(context1 context.Context, getNodeVersionInfoRequest *access.GetNodeVersionInfoRequest)) *AccessAPIServer_GetNodeVersionInfo_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetNodeVersionInfoRequest + if args[1] != nil { + arg1 = args[1].(*access.GetNodeVersionInfoRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetNodeVersionInfo_Call) Return(getNodeVersionInfoResponse *access.GetNodeVersionInfoResponse, err error) *AccessAPIServer_GetNodeVersionInfo_Call { + _c.Call.Return(getNodeVersionInfoResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetNodeVersionInfo_Call) RunAndReturn(run func(context1 context.Context, getNodeVersionInfoRequest *access.GetNodeVersionInfoRequest) (*access.GetNodeVersionInfoResponse, error)) *AccessAPIServer_GetNodeVersionInfo_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetProtocolStateSnapshotByBlockID(context1 context.Context, getProtocolStateSnapshotByBlockIDRequest *access.GetProtocolStateSnapshotByBlockIDRequest) (*access.ProtocolStateSnapshotResponse, error) { + ret := _mock.Called(context1, getProtocolStateSnapshotByBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByBlockID") @@ -835,29 +2020,67 @@ func (_m *AccessAPIServer) GetProtocolStateSnapshotByBlockID(_a0 context.Context var r0 *access.ProtocolStateSnapshotResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest) (*access.ProtocolStateSnapshotResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest) (*access.ProtocolStateSnapshotResponse, error)); ok { + return returnFunc(context1, getProtocolStateSnapshotByBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest) *access.ProtocolStateSnapshotResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest) *access.ProtocolStateSnapshotResponse); ok { + r0 = returnFunc(context1, getProtocolStateSnapshotByBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ProtocolStateSnapshotResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByBlockIDRequest) error); ok { + r1 = returnFunc(context1, getProtocolStateSnapshotByBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetProtocolStateSnapshotByHeight(_a0 context.Context, _a1 *access.GetProtocolStateSnapshotByHeightRequest) (*access.ProtocolStateSnapshotResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByBlockID' +type AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getProtocolStateSnapshotByBlockIDRequest *access.GetProtocolStateSnapshotByBlockIDRequest +func (_e *AccessAPIServer_Expecter) GetProtocolStateSnapshotByBlockID(context1 interface{}, getProtocolStateSnapshotByBlockIDRequest interface{}) *AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call { + return &AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call{Call: _e.mock.On("GetProtocolStateSnapshotByBlockID", context1, getProtocolStateSnapshotByBlockIDRequest)} +} + +func (_c *AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call) Run(run func(context1 context.Context, getProtocolStateSnapshotByBlockIDRequest *access.GetProtocolStateSnapshotByBlockIDRequest)) *AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetProtocolStateSnapshotByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetProtocolStateSnapshotByBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call) Return(protocolStateSnapshotResponse *access.ProtocolStateSnapshotResponse, err error) *AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(protocolStateSnapshotResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call) RunAndReturn(run func(context1 context.Context, getProtocolStateSnapshotByBlockIDRequest *access.GetProtocolStateSnapshotByBlockIDRequest) (*access.ProtocolStateSnapshotResponse, error)) *AccessAPIServer_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetProtocolStateSnapshotByHeight(context1 context.Context, getProtocolStateSnapshotByHeightRequest *access.GetProtocolStateSnapshotByHeightRequest) (*access.ProtocolStateSnapshotResponse, error) { + ret := _mock.Called(context1, getProtocolStateSnapshotByHeightRequest) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByHeight") @@ -865,29 +2088,67 @@ func (_m *AccessAPIServer) GetProtocolStateSnapshotByHeight(_a0 context.Context, var r0 *access.ProtocolStateSnapshotResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest) (*access.ProtocolStateSnapshotResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest) (*access.ProtocolStateSnapshotResponse, error)); ok { + return returnFunc(context1, getProtocolStateSnapshotByHeightRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest) *access.ProtocolStateSnapshotResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest) *access.ProtocolStateSnapshotResponse); ok { + r0 = returnFunc(context1, getProtocolStateSnapshotByHeightRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.ProtocolStateSnapshotResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetProtocolStateSnapshotByHeightRequest) error); ok { + r1 = returnFunc(context1, getProtocolStateSnapshotByHeightRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetScheduledTransaction provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetScheduledTransaction(_a0 context.Context, _a1 *access.GetScheduledTransactionRequest) (*access.TransactionResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetProtocolStateSnapshotByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByHeight' +type AccessAPIServer_GetProtocolStateSnapshotByHeight_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByHeight is a helper method to define mock.On call +// - context1 context.Context +// - getProtocolStateSnapshotByHeightRequest *access.GetProtocolStateSnapshotByHeightRequest +func (_e *AccessAPIServer_Expecter) GetProtocolStateSnapshotByHeight(context1 interface{}, getProtocolStateSnapshotByHeightRequest interface{}) *AccessAPIServer_GetProtocolStateSnapshotByHeight_Call { + return &AccessAPIServer_GetProtocolStateSnapshotByHeight_Call{Call: _e.mock.On("GetProtocolStateSnapshotByHeight", context1, getProtocolStateSnapshotByHeightRequest)} +} + +func (_c *AccessAPIServer_GetProtocolStateSnapshotByHeight_Call) Run(run func(context1 context.Context, getProtocolStateSnapshotByHeightRequest *access.GetProtocolStateSnapshotByHeightRequest)) *AccessAPIServer_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetProtocolStateSnapshotByHeightRequest + if args[1] != nil { + arg1 = args[1].(*access.GetProtocolStateSnapshotByHeightRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetProtocolStateSnapshotByHeight_Call) Return(protocolStateSnapshotResponse *access.ProtocolStateSnapshotResponse, err error) *AccessAPIServer_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(protocolStateSnapshotResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetProtocolStateSnapshotByHeight_Call) RunAndReturn(run func(context1 context.Context, getProtocolStateSnapshotByHeightRequest *access.GetProtocolStateSnapshotByHeightRequest) (*access.ProtocolStateSnapshotResponse, error)) *AccessAPIServer_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransaction provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetScheduledTransaction(context1 context.Context, getScheduledTransactionRequest *access.GetScheduledTransactionRequest) (*access.TransactionResponse, error) { + ret := _mock.Called(context1, getScheduledTransactionRequest) if len(ret) == 0 { panic("no return value specified for GetScheduledTransaction") @@ -895,29 +2156,67 @@ func (_m *AccessAPIServer) GetScheduledTransaction(_a0 context.Context, _a1 *acc var r0 *access.TransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest) (*access.TransactionResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest) (*access.TransactionResponse, error)); ok { + return returnFunc(context1, getScheduledTransactionRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest) *access.TransactionResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionRequest) *access.TransactionResponse); ok { + r0 = returnFunc(context1, getScheduledTransactionRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionRequest) error); ok { + r1 = returnFunc(context1, getScheduledTransactionRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetScheduledTransactionResult provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetScheduledTransactionResult(_a0 context.Context, _a1 *access.GetScheduledTransactionResultRequest) (*access.TransactionResultResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetScheduledTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransaction' +type AccessAPIServer_GetScheduledTransaction_Call struct { + *mock.Call +} + +// GetScheduledTransaction is a helper method to define mock.On call +// - context1 context.Context +// - getScheduledTransactionRequest *access.GetScheduledTransactionRequest +func (_e *AccessAPIServer_Expecter) GetScheduledTransaction(context1 interface{}, getScheduledTransactionRequest interface{}) *AccessAPIServer_GetScheduledTransaction_Call { + return &AccessAPIServer_GetScheduledTransaction_Call{Call: _e.mock.On("GetScheduledTransaction", context1, getScheduledTransactionRequest)} +} + +func (_c *AccessAPIServer_GetScheduledTransaction_Call) Run(run func(context1 context.Context, getScheduledTransactionRequest *access.GetScheduledTransactionRequest)) *AccessAPIServer_GetScheduledTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetScheduledTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetScheduledTransactionRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetScheduledTransaction_Call) Return(transactionResponse *access.TransactionResponse, err error) *AccessAPIServer_GetScheduledTransaction_Call { + _c.Call.Return(transactionResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetScheduledTransaction_Call) RunAndReturn(run func(context1 context.Context, getScheduledTransactionRequest *access.GetScheduledTransactionRequest) (*access.TransactionResponse, error)) *AccessAPIServer_GetScheduledTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransactionResult provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetScheduledTransactionResult(context1 context.Context, getScheduledTransactionResultRequest *access.GetScheduledTransactionResultRequest) (*access.TransactionResultResponse, error) { + ret := _mock.Called(context1, getScheduledTransactionResultRequest) if len(ret) == 0 { panic("no return value specified for GetScheduledTransactionResult") @@ -925,29 +2224,67 @@ func (_m *AccessAPIServer) GetScheduledTransactionResult(_a0 context.Context, _a var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest) (*access.TransactionResultResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest) (*access.TransactionResultResponse, error)); ok { + return returnFunc(context1, getScheduledTransactionResultRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest) *access.TransactionResultResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetScheduledTransactionResultRequest) *access.TransactionResultResponse); ok { + r0 = returnFunc(context1, getScheduledTransactionResultRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionResultRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetScheduledTransactionResultRequest) error); ok { + r1 = returnFunc(context1, getScheduledTransactionResultRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransaction provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetSystemTransaction(_a0 context.Context, _a1 *access.GetSystemTransactionRequest) (*access.TransactionResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetScheduledTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransactionResult' +type AccessAPIServer_GetScheduledTransactionResult_Call struct { + *mock.Call +} + +// GetScheduledTransactionResult is a helper method to define mock.On call +// - context1 context.Context +// - getScheduledTransactionResultRequest *access.GetScheduledTransactionResultRequest +func (_e *AccessAPIServer_Expecter) GetScheduledTransactionResult(context1 interface{}, getScheduledTransactionResultRequest interface{}) *AccessAPIServer_GetScheduledTransactionResult_Call { + return &AccessAPIServer_GetScheduledTransactionResult_Call{Call: _e.mock.On("GetScheduledTransactionResult", context1, getScheduledTransactionResultRequest)} +} + +func (_c *AccessAPIServer_GetScheduledTransactionResult_Call) Run(run func(context1 context.Context, getScheduledTransactionResultRequest *access.GetScheduledTransactionResultRequest)) *AccessAPIServer_GetScheduledTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetScheduledTransactionResultRequest + if args[1] != nil { + arg1 = args[1].(*access.GetScheduledTransactionResultRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetScheduledTransactionResult_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIServer_GetScheduledTransactionResult_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetScheduledTransactionResult_Call) RunAndReturn(run func(context1 context.Context, getScheduledTransactionResultRequest *access.GetScheduledTransactionResultRequest) (*access.TransactionResultResponse, error)) *AccessAPIServer_GetScheduledTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransaction provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetSystemTransaction(context1 context.Context, getSystemTransactionRequest *access.GetSystemTransactionRequest) (*access.TransactionResponse, error) { + ret := _mock.Called(context1, getSystemTransactionRequest) if len(ret) == 0 { panic("no return value specified for GetSystemTransaction") @@ -955,29 +2292,67 @@ func (_m *AccessAPIServer) GetSystemTransaction(_a0 context.Context, _a1 *access var r0 *access.TransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest) (*access.TransactionResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest) (*access.TransactionResponse, error)); ok { + return returnFunc(context1, getSystemTransactionRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest) *access.TransactionResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionRequest) *access.TransactionResponse); ok { + r0 = returnFunc(context1, getSystemTransactionRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResponse) } - } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionRequest) error); ok { + r1 = returnFunc(context1, getSystemTransactionRequest) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccessAPIServer_GetSystemTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransaction' +type AccessAPIServer_GetSystemTransaction_Call struct { + *mock.Call +} + +// GetSystemTransaction is a helper method to define mock.On call +// - context1 context.Context +// - getSystemTransactionRequest *access.GetSystemTransactionRequest +func (_e *AccessAPIServer_Expecter) GetSystemTransaction(context1 interface{}, getSystemTransactionRequest interface{}) *AccessAPIServer_GetSystemTransaction_Call { + return &AccessAPIServer_GetSystemTransaction_Call{Call: _e.mock.On("GetSystemTransaction", context1, getSystemTransactionRequest)} +} + +func (_c *AccessAPIServer_GetSystemTransaction_Call) Run(run func(context1 context.Context, getSystemTransactionRequest *access.GetSystemTransactionRequest)) *AccessAPIServer_GetSystemTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetSystemTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetSystemTransactionRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionRequest) error); ok { - r1 = rf(_a0, _a1) - } else { - r1 = ret.Error(1) - } +func (_c *AccessAPIServer_GetSystemTransaction_Call) Return(transactionResponse *access.TransactionResponse, err error) *AccessAPIServer_GetSystemTransaction_Call { + _c.Call.Return(transactionResponse, err) + return _c +} - return r0, r1 +func (_c *AccessAPIServer_GetSystemTransaction_Call) RunAndReturn(run func(context1 context.Context, getSystemTransactionRequest *access.GetSystemTransactionRequest) (*access.TransactionResponse, error)) *AccessAPIServer_GetSystemTransaction_Call { + _c.Call.Return(run) + return _c } -// GetSystemTransactionResult provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetSystemTransactionResult(_a0 context.Context, _a1 *access.GetSystemTransactionResultRequest) (*access.TransactionResultResponse, error) { - ret := _m.Called(_a0, _a1) +// GetSystemTransactionResult provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetSystemTransactionResult(context1 context.Context, getSystemTransactionResultRequest *access.GetSystemTransactionResultRequest) (*access.TransactionResultResponse, error) { + ret := _mock.Called(context1, getSystemTransactionResultRequest) if len(ret) == 0 { panic("no return value specified for GetSystemTransactionResult") @@ -985,29 +2360,67 @@ func (_m *AccessAPIServer) GetSystemTransactionResult(_a0 context.Context, _a1 * var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest) (*access.TransactionResultResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest) (*access.TransactionResultResponse, error)); ok { + return returnFunc(context1, getSystemTransactionResultRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest) *access.TransactionResultResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetSystemTransactionResultRequest) *access.TransactionResultResponse); ok { + r0 = returnFunc(context1, getSystemTransactionResultRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionResultRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetSystemTransactionResultRequest) error); ok { + r1 = returnFunc(context1, getSystemTransactionResultRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransaction provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetTransaction(_a0 context.Context, _a1 *access.GetTransactionRequest) (*access.TransactionResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetSystemTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransactionResult' +type AccessAPIServer_GetSystemTransactionResult_Call struct { + *mock.Call +} + +// GetSystemTransactionResult is a helper method to define mock.On call +// - context1 context.Context +// - getSystemTransactionResultRequest *access.GetSystemTransactionResultRequest +func (_e *AccessAPIServer_Expecter) GetSystemTransactionResult(context1 interface{}, getSystemTransactionResultRequest interface{}) *AccessAPIServer_GetSystemTransactionResult_Call { + return &AccessAPIServer_GetSystemTransactionResult_Call{Call: _e.mock.On("GetSystemTransactionResult", context1, getSystemTransactionResultRequest)} +} + +func (_c *AccessAPIServer_GetSystemTransactionResult_Call) Run(run func(context1 context.Context, getSystemTransactionResultRequest *access.GetSystemTransactionResultRequest)) *AccessAPIServer_GetSystemTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetSystemTransactionResultRequest + if args[1] != nil { + arg1 = args[1].(*access.GetSystemTransactionResultRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetSystemTransactionResult_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIServer_GetSystemTransactionResult_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetSystemTransactionResult_Call) RunAndReturn(run func(context1 context.Context, getSystemTransactionResultRequest *access.GetSystemTransactionResultRequest) (*access.TransactionResultResponse, error)) *AccessAPIServer_GetSystemTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransaction provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetTransaction(context1 context.Context, getTransactionRequest *access.GetTransactionRequest) (*access.TransactionResponse, error) { + ret := _mock.Called(context1, getTransactionRequest) if len(ret) == 0 { panic("no return value specified for GetTransaction") @@ -1015,29 +2428,67 @@ func (_m *AccessAPIServer) GetTransaction(_a0 context.Context, _a1 *access.GetTr var r0 *access.TransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) (*access.TransactionResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) (*access.TransactionResponse, error)); ok { + return returnFunc(context1, getTransactionRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) *access.TransactionResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) *access.TransactionResponse); ok { + r0 = returnFunc(context1, getTransactionRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest) error); ok { + r1 = returnFunc(context1, getTransactionRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResult provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetTransactionResult(_a0 context.Context, _a1 *access.GetTransactionRequest) (*access.TransactionResultResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransaction' +type AccessAPIServer_GetTransaction_Call struct { + *mock.Call +} + +// GetTransaction is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionRequest *access.GetTransactionRequest +func (_e *AccessAPIServer_Expecter) GetTransaction(context1 interface{}, getTransactionRequest interface{}) *AccessAPIServer_GetTransaction_Call { + return &AccessAPIServer_GetTransaction_Call{Call: _e.mock.On("GetTransaction", context1, getTransactionRequest)} +} + +func (_c *AccessAPIServer_GetTransaction_Call) Run(run func(context1 context.Context, getTransactionRequest *access.GetTransactionRequest)) *AccessAPIServer_GetTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetTransaction_Call) Return(transactionResponse *access.TransactionResponse, err error) *AccessAPIServer_GetTransaction_Call { + _c.Call.Return(transactionResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetTransaction_Call) RunAndReturn(run func(context1 context.Context, getTransactionRequest *access.GetTransactionRequest) (*access.TransactionResponse, error)) *AccessAPIServer_GetTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResult provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetTransactionResult(context1 context.Context, getTransactionRequest *access.GetTransactionRequest) (*access.TransactionResultResponse, error) { + ret := _mock.Called(context1, getTransactionRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionResult") @@ -1045,29 +2496,67 @@ func (_m *AccessAPIServer) GetTransactionResult(_a0 context.Context, _a1 *access var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) (*access.TransactionResultResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) (*access.TransactionResultResponse, error)); ok { + return returnFunc(context1, getTransactionRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) *access.TransactionResultResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionRequest) *access.TransactionResultResponse); ok { + r0 = returnFunc(context1, getTransactionRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionRequest) error); ok { + r1 = returnFunc(context1, getTransactionRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultByIndex provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetTransactionResultByIndex(_a0 context.Context, _a1 *access.GetTransactionByIndexRequest) (*access.TransactionResultResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type AccessAPIServer_GetTransactionResult_Call struct { + *mock.Call +} + +// GetTransactionResult is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionRequest *access.GetTransactionRequest +func (_e *AccessAPIServer_Expecter) GetTransactionResult(context1 interface{}, getTransactionRequest interface{}) *AccessAPIServer_GetTransactionResult_Call { + return &AccessAPIServer_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", context1, getTransactionRequest)} +} + +func (_c *AccessAPIServer_GetTransactionResult_Call) Run(run func(context1 context.Context, getTransactionRequest *access.GetTransactionRequest)) *AccessAPIServer_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetTransactionResult_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIServer_GetTransactionResult_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetTransactionResult_Call) RunAndReturn(run func(context1 context.Context, getTransactionRequest *access.GetTransactionRequest) (*access.TransactionResultResponse, error)) *AccessAPIServer_GetTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultByIndex provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetTransactionResultByIndex(context1 context.Context, getTransactionByIndexRequest *access.GetTransactionByIndexRequest) (*access.TransactionResultResponse, error) { + ret := _mock.Called(context1, getTransactionByIndexRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionResultByIndex") @@ -1075,29 +2564,67 @@ func (_m *AccessAPIServer) GetTransactionResultByIndex(_a0 context.Context, _a1 var r0 *access.TransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest) (*access.TransactionResultResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest) (*access.TransactionResultResponse, error)); ok { + return returnFunc(context1, getTransactionByIndexRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest) *access.TransactionResultResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionByIndexRequest) *access.TransactionResultResponse); ok { + r0 = returnFunc(context1, getTransactionByIndexRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionByIndexRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionByIndexRequest) error); ok { + r1 = returnFunc(context1, getTransactionByIndexRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultsByBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetTransactionResultsByBlockID(_a0 context.Context, _a1 *access.GetTransactionsByBlockIDRequest) (*access.TransactionResultsResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetTransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultByIndex' +type AccessAPIServer_GetTransactionResultByIndex_Call struct { + *mock.Call +} + +// GetTransactionResultByIndex is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionByIndexRequest *access.GetTransactionByIndexRequest +func (_e *AccessAPIServer_Expecter) GetTransactionResultByIndex(context1 interface{}, getTransactionByIndexRequest interface{}) *AccessAPIServer_GetTransactionResultByIndex_Call { + return &AccessAPIServer_GetTransactionResultByIndex_Call{Call: _e.mock.On("GetTransactionResultByIndex", context1, getTransactionByIndexRequest)} +} + +func (_c *AccessAPIServer_GetTransactionResultByIndex_Call) Run(run func(context1 context.Context, getTransactionByIndexRequest *access.GetTransactionByIndexRequest)) *AccessAPIServer_GetTransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionByIndexRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionByIndexRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetTransactionResultByIndex_Call) Return(transactionResultResponse *access.TransactionResultResponse, err error) *AccessAPIServer_GetTransactionResultByIndex_Call { + _c.Call.Return(transactionResultResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetTransactionResultByIndex_Call) RunAndReturn(run func(context1 context.Context, getTransactionByIndexRequest *access.GetTransactionByIndexRequest) (*access.TransactionResultResponse, error)) *AccessAPIServer_GetTransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultsByBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetTransactionResultsByBlockID(context1 context.Context, getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest) (*access.TransactionResultsResponse, error) { + ret := _mock.Called(context1, getTransactionsByBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionResultsByBlockID") @@ -1105,29 +2632,67 @@ func (_m *AccessAPIServer) GetTransactionResultsByBlockID(_a0 context.Context, _ var r0 *access.TransactionResultsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) (*access.TransactionResultsResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) (*access.TransactionResultsResponse, error)); ok { + return returnFunc(context1, getTransactionsByBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) *access.TransactionResultsResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) *access.TransactionResultsResponse); ok { + r0 = returnFunc(context1, getTransactionsByBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResultsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest) error); ok { + r1 = returnFunc(context1, getTransactionsByBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionsByBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) GetTransactionsByBlockID(_a0 context.Context, _a1 *access.GetTransactionsByBlockIDRequest) (*access.TransactionsResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetTransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultsByBlockID' +type AccessAPIServer_GetTransactionResultsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionResultsByBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest +func (_e *AccessAPIServer_Expecter) GetTransactionResultsByBlockID(context1 interface{}, getTransactionsByBlockIDRequest interface{}) *AccessAPIServer_GetTransactionResultsByBlockID_Call { + return &AccessAPIServer_GetTransactionResultsByBlockID_Call{Call: _e.mock.On("GetTransactionResultsByBlockID", context1, getTransactionsByBlockIDRequest)} +} + +func (_c *AccessAPIServer_GetTransactionResultsByBlockID_Call) Run(run func(context1 context.Context, getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest)) *AccessAPIServer_GetTransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionsByBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetTransactionResultsByBlockID_Call) Return(transactionResultsResponse *access.TransactionResultsResponse, err error) *AccessAPIServer_GetTransactionResultsByBlockID_Call { + _c.Call.Return(transactionResultsResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetTransactionResultsByBlockID_Call) RunAndReturn(run func(context1 context.Context, getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest) (*access.TransactionResultsResponse, error)) *AccessAPIServer_GetTransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionsByBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) GetTransactionsByBlockID(context1 context.Context, getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest) (*access.TransactionsResponse, error) { + ret := _mock.Called(context1, getTransactionsByBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionsByBlockID") @@ -1135,29 +2700,67 @@ func (_m *AccessAPIServer) GetTransactionsByBlockID(_a0 context.Context, _a1 *ac var r0 *access.TransactionsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) (*access.TransactionsResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) (*access.TransactionsResponse, error)); ok { + return returnFunc(context1, getTransactionsByBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) *access.TransactionsResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.GetTransactionsByBlockIDRequest) *access.TransactionsResponse); ok { + r0 = returnFunc(context1, getTransactionsByBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.GetTransactionsByBlockIDRequest) error); ok { + r1 = returnFunc(context1, getTransactionsByBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// Ping provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) Ping(_a0 context.Context, _a1 *access.PingRequest) (*access.PingResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_GetTransactionsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionsByBlockID' +type AccessAPIServer_GetTransactionsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionsByBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest +func (_e *AccessAPIServer_Expecter) GetTransactionsByBlockID(context1 interface{}, getTransactionsByBlockIDRequest interface{}) *AccessAPIServer_GetTransactionsByBlockID_Call { + return &AccessAPIServer_GetTransactionsByBlockID_Call{Call: _e.mock.On("GetTransactionsByBlockID", context1, getTransactionsByBlockIDRequest)} +} + +func (_c *AccessAPIServer_GetTransactionsByBlockID_Call) Run(run func(context1 context.Context, getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest)) *AccessAPIServer_GetTransactionsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.GetTransactionsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*access.GetTransactionsByBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_GetTransactionsByBlockID_Call) Return(transactionsResponse *access.TransactionsResponse, err error) *AccessAPIServer_GetTransactionsByBlockID_Call { + _c.Call.Return(transactionsResponse, err) + return _c +} + +func (_c *AccessAPIServer_GetTransactionsByBlockID_Call) RunAndReturn(run func(context1 context.Context, getTransactionsByBlockIDRequest *access.GetTransactionsByBlockIDRequest) (*access.TransactionsResponse, error)) *AccessAPIServer_GetTransactionsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Ping provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) Ping(context1 context.Context, pingRequest *access.PingRequest) (*access.PingResponse, error) { + ret := _mock.Called(context1, pingRequest) if len(ret) == 0 { panic("no return value specified for Ping") @@ -1165,47 +2768,124 @@ func (_m *AccessAPIServer) Ping(_a0 context.Context, _a1 *access.PingRequest) (* var r0 *access.PingResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.PingRequest) (*access.PingResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.PingRequest) (*access.PingResponse, error)); ok { + return returnFunc(context1, pingRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.PingRequest) *access.PingResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.PingRequest) *access.PingResponse); ok { + r0 = returnFunc(context1, pingRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.PingResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.PingRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.PingRequest) error); ok { + r1 = returnFunc(context1, pingRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// SendAndSubscribeTransactionStatuses provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SendAndSubscribeTransactionStatuses(_a0 *access.SendAndSubscribeTransactionStatusesRequest, _a1 access.AccessAPI_SendAndSubscribeTransactionStatusesServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping' +type AccessAPIServer_Ping_Call struct { + *mock.Call +} + +// Ping is a helper method to define mock.On call +// - context1 context.Context +// - pingRequest *access.PingRequest +func (_e *AccessAPIServer_Expecter) Ping(context1 interface{}, pingRequest interface{}) *AccessAPIServer_Ping_Call { + return &AccessAPIServer_Ping_Call{Call: _e.mock.On("Ping", context1, pingRequest)} +} + +func (_c *AccessAPIServer_Ping_Call) Run(run func(context1 context.Context, pingRequest *access.PingRequest)) *AccessAPIServer_Ping_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.PingRequest + if args[1] != nil { + arg1 = args[1].(*access.PingRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_Ping_Call) Return(pingResponse *access.PingResponse, err error) *AccessAPIServer_Ping_Call { + _c.Call.Return(pingResponse, err) + return _c +} + +func (_c *AccessAPIServer_Ping_Call) RunAndReturn(run func(context1 context.Context, pingRequest *access.PingRequest) (*access.PingResponse, error)) *AccessAPIServer_Ping_Call { + _c.Call.Return(run) + return _c +} + +// SendAndSubscribeTransactionStatuses provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SendAndSubscribeTransactionStatuses(sendAndSubscribeTransactionStatusesRequest *access.SendAndSubscribeTransactionStatusesRequest, accessAPI_SendAndSubscribeTransactionStatusesServer access.AccessAPI_SendAndSubscribeTransactionStatusesServer) error { + ret := _mock.Called(sendAndSubscribeTransactionStatusesRequest, accessAPI_SendAndSubscribeTransactionStatusesServer) if len(ret) == 0 { panic("no return value specified for SendAndSubscribeTransactionStatuses") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SendAndSubscribeTransactionStatusesRequest, access.AccessAPI_SendAndSubscribeTransactionStatusesServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SendAndSubscribeTransactionStatusesRequest, access.AccessAPI_SendAndSubscribeTransactionStatusesServer) error); ok { + r0 = returnFunc(sendAndSubscribeTransactionStatusesRequest, accessAPI_SendAndSubscribeTransactionStatusesServer) } else { r0 = ret.Error(0) } - return r0 } -// SendTransaction provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SendTransaction(_a0 context.Context, _a1 *access.SendTransactionRequest) (*access.SendTransactionResponse, error) { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SendAndSubscribeTransactionStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendAndSubscribeTransactionStatuses' +type AccessAPIServer_SendAndSubscribeTransactionStatuses_Call struct { + *mock.Call +} + +// SendAndSubscribeTransactionStatuses is a helper method to define mock.On call +// - sendAndSubscribeTransactionStatusesRequest *access.SendAndSubscribeTransactionStatusesRequest +// - accessAPI_SendAndSubscribeTransactionStatusesServer access.AccessAPI_SendAndSubscribeTransactionStatusesServer +func (_e *AccessAPIServer_Expecter) SendAndSubscribeTransactionStatuses(sendAndSubscribeTransactionStatusesRequest interface{}, accessAPI_SendAndSubscribeTransactionStatusesServer interface{}) *AccessAPIServer_SendAndSubscribeTransactionStatuses_Call { + return &AccessAPIServer_SendAndSubscribeTransactionStatuses_Call{Call: _e.mock.On("SendAndSubscribeTransactionStatuses", sendAndSubscribeTransactionStatusesRequest, accessAPI_SendAndSubscribeTransactionStatusesServer)} +} + +func (_c *AccessAPIServer_SendAndSubscribeTransactionStatuses_Call) Run(run func(sendAndSubscribeTransactionStatusesRequest *access.SendAndSubscribeTransactionStatusesRequest, accessAPI_SendAndSubscribeTransactionStatusesServer access.AccessAPI_SendAndSubscribeTransactionStatusesServer)) *AccessAPIServer_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SendAndSubscribeTransactionStatusesRequest + if args[0] != nil { + arg0 = args[0].(*access.SendAndSubscribeTransactionStatusesRequest) + } + var arg1 access.AccessAPI_SendAndSubscribeTransactionStatusesServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SendAndSubscribeTransactionStatusesServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SendAndSubscribeTransactionStatuses_Call) Return(err error) *AccessAPIServer_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SendAndSubscribeTransactionStatuses_Call) RunAndReturn(run func(sendAndSubscribeTransactionStatusesRequest *access.SendAndSubscribeTransactionStatusesRequest, accessAPI_SendAndSubscribeTransactionStatusesServer access.AccessAPI_SendAndSubscribeTransactionStatusesServer) error) *AccessAPIServer_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(run) + return _c +} + +// SendTransaction provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SendTransaction(context1 context.Context, sendTransactionRequest *access.SendTransactionRequest) (*access.SendTransactionResponse, error) { + ret := _mock.Called(context1, sendTransactionRequest) if len(ret) == 0 { panic("no return value specified for SendTransaction") @@ -1213,198 +2893,573 @@ func (_m *AccessAPIServer) SendTransaction(_a0 context.Context, _a1 *access.Send var r0 *access.SendTransactionResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest) (*access.SendTransactionResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest) (*access.SendTransactionResponse, error)); ok { + return returnFunc(context1, sendTransactionRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest) *access.SendTransactionResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *access.SendTransactionRequest) *access.SendTransactionResponse); ok { + r0 = returnFunc(context1, sendTransactionRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.SendTransactionResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *access.SendTransactionRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *access.SendTransactionRequest) error); ok { + r1 = returnFunc(context1, sendTransactionRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeBlockDigestsFromLatest provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlockDigestsFromLatest(_a0 *access.SubscribeBlockDigestsFromLatestRequest, _a1 access.AccessAPI_SubscribeBlockDigestsFromLatestServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' +type AccessAPIServer_SendTransaction_Call struct { + *mock.Call +} + +// SendTransaction is a helper method to define mock.On call +// - context1 context.Context +// - sendTransactionRequest *access.SendTransactionRequest +func (_e *AccessAPIServer_Expecter) SendTransaction(context1 interface{}, sendTransactionRequest interface{}) *AccessAPIServer_SendTransaction_Call { + return &AccessAPIServer_SendTransaction_Call{Call: _e.mock.On("SendTransaction", context1, sendTransactionRequest)} +} + +func (_c *AccessAPIServer_SendTransaction_Call) Run(run func(context1 context.Context, sendTransactionRequest *access.SendTransactionRequest)) *AccessAPIServer_SendTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *access.SendTransactionRequest + if args[1] != nil { + arg1 = args[1].(*access.SendTransactionRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SendTransaction_Call) Return(sendTransactionResponse *access.SendTransactionResponse, err error) *AccessAPIServer_SendTransaction_Call { + _c.Call.Return(sendTransactionResponse, err) + return _c +} + +func (_c *AccessAPIServer_SendTransaction_Call) RunAndReturn(run func(context1 context.Context, sendTransactionRequest *access.SendTransactionRequest) (*access.SendTransactionResponse, error)) *AccessAPIServer_SendTransaction_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromLatest provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlockDigestsFromLatest(subscribeBlockDigestsFromLatestRequest *access.SubscribeBlockDigestsFromLatestRequest, accessAPI_SubscribeBlockDigestsFromLatestServer access.AccessAPI_SubscribeBlockDigestsFromLatestServer) error { + ret := _mock.Called(subscribeBlockDigestsFromLatestRequest, accessAPI_SubscribeBlockDigestsFromLatestServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromLatest") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlockDigestsFromLatestRequest, access.AccessAPI_SubscribeBlockDigestsFromLatestServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlockDigestsFromLatestRequest, access.AccessAPI_SubscribeBlockDigestsFromLatestServer) error); ok { + r0 = returnFunc(subscribeBlockDigestsFromLatestRequest, accessAPI_SubscribeBlockDigestsFromLatestServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlockDigestsFromStartBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlockDigestsFromStartBlockID(_a0 *access.SubscribeBlockDigestsFromStartBlockIDRequest, _a1 access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlockDigestsFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromLatest' +type AccessAPIServer_SubscribeBlockDigestsFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromLatest is a helper method to define mock.On call +// - subscribeBlockDigestsFromLatestRequest *access.SubscribeBlockDigestsFromLatestRequest +// - accessAPI_SubscribeBlockDigestsFromLatestServer access.AccessAPI_SubscribeBlockDigestsFromLatestServer +func (_e *AccessAPIServer_Expecter) SubscribeBlockDigestsFromLatest(subscribeBlockDigestsFromLatestRequest interface{}, accessAPI_SubscribeBlockDigestsFromLatestServer interface{}) *AccessAPIServer_SubscribeBlockDigestsFromLatest_Call { + return &AccessAPIServer_SubscribeBlockDigestsFromLatest_Call{Call: _e.mock.On("SubscribeBlockDigestsFromLatest", subscribeBlockDigestsFromLatestRequest, accessAPI_SubscribeBlockDigestsFromLatestServer)} +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromLatest_Call) Run(run func(subscribeBlockDigestsFromLatestRequest *access.SubscribeBlockDigestsFromLatestRequest, accessAPI_SubscribeBlockDigestsFromLatestServer access.AccessAPI_SubscribeBlockDigestsFromLatestServer)) *AccessAPIServer_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlockDigestsFromLatestRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlockDigestsFromLatestRequest) + } + var arg1 access.AccessAPI_SubscribeBlockDigestsFromLatestServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlockDigestsFromLatestServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromLatest_Call) Return(err error) *AccessAPIServer_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromLatest_Call) RunAndReturn(run func(subscribeBlockDigestsFromLatestRequest *access.SubscribeBlockDigestsFromLatestRequest, accessAPI_SubscribeBlockDigestsFromLatestServer access.AccessAPI_SubscribeBlockDigestsFromLatestServer) error) *AccessAPIServer_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlockDigestsFromStartBlockID(subscribeBlockDigestsFromStartBlockIDRequest *access.SubscribeBlockDigestsFromStartBlockIDRequest, accessAPI_SubscribeBlockDigestsFromStartBlockIDServer access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer) error { + ret := _mock.Called(subscribeBlockDigestsFromStartBlockIDRequest, accessAPI_SubscribeBlockDigestsFromStartBlockIDServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlockDigestsFromStartBlockIDRequest, access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlockDigestsFromStartBlockIDRequest, access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer) error); ok { + r0 = returnFunc(subscribeBlockDigestsFromStartBlockIDRequest, accessAPI_SubscribeBlockDigestsFromStartBlockIDServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlockDigestsFromStartHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlockDigestsFromStartHeight(_a0 *access.SubscribeBlockDigestsFromStartHeightRequest, _a1 access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartBlockID' +type AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartBlockID is a helper method to define mock.On call +// - subscribeBlockDigestsFromStartBlockIDRequest *access.SubscribeBlockDigestsFromStartBlockIDRequest +// - accessAPI_SubscribeBlockDigestsFromStartBlockIDServer access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer +func (_e *AccessAPIServer_Expecter) SubscribeBlockDigestsFromStartBlockID(subscribeBlockDigestsFromStartBlockIDRequest interface{}, accessAPI_SubscribeBlockDigestsFromStartBlockIDServer interface{}) *AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call { + return &AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartBlockID", subscribeBlockDigestsFromStartBlockIDRequest, accessAPI_SubscribeBlockDigestsFromStartBlockIDServer)} +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call) Run(run func(subscribeBlockDigestsFromStartBlockIDRequest *access.SubscribeBlockDigestsFromStartBlockIDRequest, accessAPI_SubscribeBlockDigestsFromStartBlockIDServer access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer)) *AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlockDigestsFromStartBlockIDRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlockDigestsFromStartBlockIDRequest) + } + var arg1 access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call) Return(err error) *AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call) RunAndReturn(run func(subscribeBlockDigestsFromStartBlockIDRequest *access.SubscribeBlockDigestsFromStartBlockIDRequest, accessAPI_SubscribeBlockDigestsFromStartBlockIDServer access.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer) error) *AccessAPIServer_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlockDigestsFromStartHeight(subscribeBlockDigestsFromStartHeightRequest *access.SubscribeBlockDigestsFromStartHeightRequest, accessAPI_SubscribeBlockDigestsFromStartHeightServer access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer) error { + ret := _mock.Called(subscribeBlockDigestsFromStartHeightRequest, accessAPI_SubscribeBlockDigestsFromStartHeightServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartHeight") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlockDigestsFromStartHeightRequest, access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlockDigestsFromStartHeightRequest, access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer) error); ok { + r0 = returnFunc(subscribeBlockDigestsFromStartHeightRequest, accessAPI_SubscribeBlockDigestsFromStartHeightServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlockHeadersFromLatest provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlockHeadersFromLatest(_a0 *access.SubscribeBlockHeadersFromLatestRequest, _a1 access.AccessAPI_SubscribeBlockHeadersFromLatestServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartHeight' +type AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartHeight is a helper method to define mock.On call +// - subscribeBlockDigestsFromStartHeightRequest *access.SubscribeBlockDigestsFromStartHeightRequest +// - accessAPI_SubscribeBlockDigestsFromStartHeightServer access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer +func (_e *AccessAPIServer_Expecter) SubscribeBlockDigestsFromStartHeight(subscribeBlockDigestsFromStartHeightRequest interface{}, accessAPI_SubscribeBlockDigestsFromStartHeightServer interface{}) *AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call { + return &AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartHeight", subscribeBlockDigestsFromStartHeightRequest, accessAPI_SubscribeBlockDigestsFromStartHeightServer)} +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call) Run(run func(subscribeBlockDigestsFromStartHeightRequest *access.SubscribeBlockDigestsFromStartHeightRequest, accessAPI_SubscribeBlockDigestsFromStartHeightServer access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer)) *AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlockDigestsFromStartHeightRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlockDigestsFromStartHeightRequest) + } + var arg1 access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call) Return(err error) *AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call) RunAndReturn(run func(subscribeBlockDigestsFromStartHeightRequest *access.SubscribeBlockDigestsFromStartHeightRequest, accessAPI_SubscribeBlockDigestsFromStartHeightServer access.AccessAPI_SubscribeBlockDigestsFromStartHeightServer) error) *AccessAPIServer_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromLatest provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlockHeadersFromLatest(subscribeBlockHeadersFromLatestRequest *access.SubscribeBlockHeadersFromLatestRequest, accessAPI_SubscribeBlockHeadersFromLatestServer access.AccessAPI_SubscribeBlockHeadersFromLatestServer) error { + ret := _mock.Called(subscribeBlockHeadersFromLatestRequest, accessAPI_SubscribeBlockHeadersFromLatestServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromLatest") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlockHeadersFromLatestRequest, access.AccessAPI_SubscribeBlockHeadersFromLatestServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlockHeadersFromLatestRequest, access.AccessAPI_SubscribeBlockHeadersFromLatestServer) error); ok { + r0 = returnFunc(subscribeBlockHeadersFromLatestRequest, accessAPI_SubscribeBlockHeadersFromLatestServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlockHeadersFromStartBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlockHeadersFromStartBlockID(_a0 *access.SubscribeBlockHeadersFromStartBlockIDRequest, _a1 access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlockHeadersFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromLatest' +type AccessAPIServer_SubscribeBlockHeadersFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromLatest is a helper method to define mock.On call +// - subscribeBlockHeadersFromLatestRequest *access.SubscribeBlockHeadersFromLatestRequest +// - accessAPI_SubscribeBlockHeadersFromLatestServer access.AccessAPI_SubscribeBlockHeadersFromLatestServer +func (_e *AccessAPIServer_Expecter) SubscribeBlockHeadersFromLatest(subscribeBlockHeadersFromLatestRequest interface{}, accessAPI_SubscribeBlockHeadersFromLatestServer interface{}) *AccessAPIServer_SubscribeBlockHeadersFromLatest_Call { + return &AccessAPIServer_SubscribeBlockHeadersFromLatest_Call{Call: _e.mock.On("SubscribeBlockHeadersFromLatest", subscribeBlockHeadersFromLatestRequest, accessAPI_SubscribeBlockHeadersFromLatestServer)} +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromLatest_Call) Run(run func(subscribeBlockHeadersFromLatestRequest *access.SubscribeBlockHeadersFromLatestRequest, accessAPI_SubscribeBlockHeadersFromLatestServer access.AccessAPI_SubscribeBlockHeadersFromLatestServer)) *AccessAPIServer_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlockHeadersFromLatestRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlockHeadersFromLatestRequest) + } + var arg1 access.AccessAPI_SubscribeBlockHeadersFromLatestServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlockHeadersFromLatestServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromLatest_Call) Return(err error) *AccessAPIServer_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromLatest_Call) RunAndReturn(run func(subscribeBlockHeadersFromLatestRequest *access.SubscribeBlockHeadersFromLatestRequest, accessAPI_SubscribeBlockHeadersFromLatestServer access.AccessAPI_SubscribeBlockHeadersFromLatestServer) error) *AccessAPIServer_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlockHeadersFromStartBlockID(subscribeBlockHeadersFromStartBlockIDRequest *access.SubscribeBlockHeadersFromStartBlockIDRequest, accessAPI_SubscribeBlockHeadersFromStartBlockIDServer access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer) error { + ret := _mock.Called(subscribeBlockHeadersFromStartBlockIDRequest, accessAPI_SubscribeBlockHeadersFromStartBlockIDServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlockHeadersFromStartBlockIDRequest, access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlockHeadersFromStartBlockIDRequest, access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer) error); ok { + r0 = returnFunc(subscribeBlockHeadersFromStartBlockIDRequest, accessAPI_SubscribeBlockHeadersFromStartBlockIDServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlockHeadersFromStartHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlockHeadersFromStartHeight(_a0 *access.SubscribeBlockHeadersFromStartHeightRequest, _a1 access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartBlockID' +type AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartBlockID is a helper method to define mock.On call +// - subscribeBlockHeadersFromStartBlockIDRequest *access.SubscribeBlockHeadersFromStartBlockIDRequest +// - accessAPI_SubscribeBlockHeadersFromStartBlockIDServer access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer +func (_e *AccessAPIServer_Expecter) SubscribeBlockHeadersFromStartBlockID(subscribeBlockHeadersFromStartBlockIDRequest interface{}, accessAPI_SubscribeBlockHeadersFromStartBlockIDServer interface{}) *AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call { + return &AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartBlockID", subscribeBlockHeadersFromStartBlockIDRequest, accessAPI_SubscribeBlockHeadersFromStartBlockIDServer)} +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call) Run(run func(subscribeBlockHeadersFromStartBlockIDRequest *access.SubscribeBlockHeadersFromStartBlockIDRequest, accessAPI_SubscribeBlockHeadersFromStartBlockIDServer access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer)) *AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlockHeadersFromStartBlockIDRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlockHeadersFromStartBlockIDRequest) + } + var arg1 access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call) Return(err error) *AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call) RunAndReturn(run func(subscribeBlockHeadersFromStartBlockIDRequest *access.SubscribeBlockHeadersFromStartBlockIDRequest, accessAPI_SubscribeBlockHeadersFromStartBlockIDServer access.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer) error) *AccessAPIServer_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlockHeadersFromStartHeight(subscribeBlockHeadersFromStartHeightRequest *access.SubscribeBlockHeadersFromStartHeightRequest, accessAPI_SubscribeBlockHeadersFromStartHeightServer access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer) error { + ret := _mock.Called(subscribeBlockHeadersFromStartHeightRequest, accessAPI_SubscribeBlockHeadersFromStartHeightServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartHeight") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlockHeadersFromStartHeightRequest, access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlockHeadersFromStartHeightRequest, access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer) error); ok { + r0 = returnFunc(subscribeBlockHeadersFromStartHeightRequest, accessAPI_SubscribeBlockHeadersFromStartHeightServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlocksFromLatest provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlocksFromLatest(_a0 *access.SubscribeBlocksFromLatestRequest, _a1 access.AccessAPI_SubscribeBlocksFromLatestServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartHeight' +type AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartHeight is a helper method to define mock.On call +// - subscribeBlockHeadersFromStartHeightRequest *access.SubscribeBlockHeadersFromStartHeightRequest +// - accessAPI_SubscribeBlockHeadersFromStartHeightServer access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer +func (_e *AccessAPIServer_Expecter) SubscribeBlockHeadersFromStartHeight(subscribeBlockHeadersFromStartHeightRequest interface{}, accessAPI_SubscribeBlockHeadersFromStartHeightServer interface{}) *AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call { + return &AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartHeight", subscribeBlockHeadersFromStartHeightRequest, accessAPI_SubscribeBlockHeadersFromStartHeightServer)} +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call) Run(run func(subscribeBlockHeadersFromStartHeightRequest *access.SubscribeBlockHeadersFromStartHeightRequest, accessAPI_SubscribeBlockHeadersFromStartHeightServer access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer)) *AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlockHeadersFromStartHeightRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlockHeadersFromStartHeightRequest) + } + var arg1 access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call) Return(err error) *AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call) RunAndReturn(run func(subscribeBlockHeadersFromStartHeightRequest *access.SubscribeBlockHeadersFromStartHeightRequest, accessAPI_SubscribeBlockHeadersFromStartHeightServer access.AccessAPI_SubscribeBlockHeadersFromStartHeightServer) error) *AccessAPIServer_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromLatest provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlocksFromLatest(subscribeBlocksFromLatestRequest *access.SubscribeBlocksFromLatestRequest, accessAPI_SubscribeBlocksFromLatestServer access.AccessAPI_SubscribeBlocksFromLatestServer) error { + ret := _mock.Called(subscribeBlocksFromLatestRequest, accessAPI_SubscribeBlocksFromLatestServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromLatest") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlocksFromLatestRequest, access.AccessAPI_SubscribeBlocksFromLatestServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlocksFromLatestRequest, access.AccessAPI_SubscribeBlocksFromLatestServer) error); ok { + r0 = returnFunc(subscribeBlocksFromLatestRequest, accessAPI_SubscribeBlocksFromLatestServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlocksFromStartBlockID provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlocksFromStartBlockID(_a0 *access.SubscribeBlocksFromStartBlockIDRequest, _a1 access.AccessAPI_SubscribeBlocksFromStartBlockIDServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlocksFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromLatest' +type AccessAPIServer_SubscribeBlocksFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlocksFromLatest is a helper method to define mock.On call +// - subscribeBlocksFromLatestRequest *access.SubscribeBlocksFromLatestRequest +// - accessAPI_SubscribeBlocksFromLatestServer access.AccessAPI_SubscribeBlocksFromLatestServer +func (_e *AccessAPIServer_Expecter) SubscribeBlocksFromLatest(subscribeBlocksFromLatestRequest interface{}, accessAPI_SubscribeBlocksFromLatestServer interface{}) *AccessAPIServer_SubscribeBlocksFromLatest_Call { + return &AccessAPIServer_SubscribeBlocksFromLatest_Call{Call: _e.mock.On("SubscribeBlocksFromLatest", subscribeBlocksFromLatestRequest, accessAPI_SubscribeBlocksFromLatestServer)} +} + +func (_c *AccessAPIServer_SubscribeBlocksFromLatest_Call) Run(run func(subscribeBlocksFromLatestRequest *access.SubscribeBlocksFromLatestRequest, accessAPI_SubscribeBlocksFromLatestServer access.AccessAPI_SubscribeBlocksFromLatestServer)) *AccessAPIServer_SubscribeBlocksFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlocksFromLatestRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlocksFromLatestRequest) + } + var arg1 access.AccessAPI_SubscribeBlocksFromLatestServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlocksFromLatestServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlocksFromLatest_Call) Return(err error) *AccessAPIServer_SubscribeBlocksFromLatest_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlocksFromLatest_Call) RunAndReturn(run func(subscribeBlocksFromLatestRequest *access.SubscribeBlocksFromLatestRequest, accessAPI_SubscribeBlocksFromLatestServer access.AccessAPI_SubscribeBlocksFromLatestServer) error) *AccessAPIServer_SubscribeBlocksFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartBlockID provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlocksFromStartBlockID(subscribeBlocksFromStartBlockIDRequest *access.SubscribeBlocksFromStartBlockIDRequest, accessAPI_SubscribeBlocksFromStartBlockIDServer access.AccessAPI_SubscribeBlocksFromStartBlockIDServer) error { + ret := _mock.Called(subscribeBlocksFromStartBlockIDRequest, accessAPI_SubscribeBlocksFromStartBlockIDServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlocksFromStartBlockIDRequest, access.AccessAPI_SubscribeBlocksFromStartBlockIDServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlocksFromStartBlockIDRequest, access.AccessAPI_SubscribeBlocksFromStartBlockIDServer) error); ok { + r0 = returnFunc(subscribeBlocksFromStartBlockIDRequest, accessAPI_SubscribeBlocksFromStartBlockIDServer) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeBlocksFromStartHeight provides a mock function with given fields: _a0, _a1 -func (_m *AccessAPIServer) SubscribeBlocksFromStartHeight(_a0 *access.SubscribeBlocksFromStartHeightRequest, _a1 access.AccessAPI_SubscribeBlocksFromStartHeightServer) error { - ret := _m.Called(_a0, _a1) +// AccessAPIServer_SubscribeBlocksFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartBlockID' +type AccessAPIServer_SubscribeBlocksFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlocksFromStartBlockID is a helper method to define mock.On call +// - subscribeBlocksFromStartBlockIDRequest *access.SubscribeBlocksFromStartBlockIDRequest +// - accessAPI_SubscribeBlocksFromStartBlockIDServer access.AccessAPI_SubscribeBlocksFromStartBlockIDServer +func (_e *AccessAPIServer_Expecter) SubscribeBlocksFromStartBlockID(subscribeBlocksFromStartBlockIDRequest interface{}, accessAPI_SubscribeBlocksFromStartBlockIDServer interface{}) *AccessAPIServer_SubscribeBlocksFromStartBlockID_Call { + return &AccessAPIServer_SubscribeBlocksFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlocksFromStartBlockID", subscribeBlocksFromStartBlockIDRequest, accessAPI_SubscribeBlocksFromStartBlockIDServer)} +} + +func (_c *AccessAPIServer_SubscribeBlocksFromStartBlockID_Call) Run(run func(subscribeBlocksFromStartBlockIDRequest *access.SubscribeBlocksFromStartBlockIDRequest, accessAPI_SubscribeBlocksFromStartBlockIDServer access.AccessAPI_SubscribeBlocksFromStartBlockIDServer)) *AccessAPIServer_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlocksFromStartBlockIDRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlocksFromStartBlockIDRequest) + } + var arg1 access.AccessAPI_SubscribeBlocksFromStartBlockIDServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlocksFromStartBlockIDServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlocksFromStartBlockID_Call) Return(err error) *AccessAPIServer_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlocksFromStartBlockID_Call) RunAndReturn(run func(subscribeBlocksFromStartBlockIDRequest *access.SubscribeBlocksFromStartBlockIDRequest, accessAPI_SubscribeBlocksFromStartBlockIDServer access.AccessAPI_SubscribeBlocksFromStartBlockIDServer) error) *AccessAPIServer_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartHeight provides a mock function for the type AccessAPIServer +func (_mock *AccessAPIServer) SubscribeBlocksFromStartHeight(subscribeBlocksFromStartHeightRequest *access.SubscribeBlocksFromStartHeightRequest, accessAPI_SubscribeBlocksFromStartHeightServer access.AccessAPI_SubscribeBlocksFromStartHeightServer) error { + ret := _mock.Called(subscribeBlocksFromStartHeightRequest, accessAPI_SubscribeBlocksFromStartHeightServer) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartHeight") } var r0 error - if rf, ok := ret.Get(0).(func(*access.SubscribeBlocksFromStartHeightRequest, access.AccessAPI_SubscribeBlocksFromStartHeightServer) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*access.SubscribeBlocksFromStartHeightRequest, access.AccessAPI_SubscribeBlocksFromStartHeightServer) error); ok { + r0 = returnFunc(subscribeBlocksFromStartHeightRequest, accessAPI_SubscribeBlocksFromStartHeightServer) } else { r0 = ret.Error(0) } - return r0 } -// NewAccessAPIServer creates a new instance of AccessAPIServer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccessAPIServer(t interface { - mock.TestingT - Cleanup(func()) -}) *AccessAPIServer { - mock := &AccessAPIServer{} - mock.Mock.Test(t) +// AccessAPIServer_SubscribeBlocksFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartHeight' +type AccessAPIServer_SubscribeBlocksFromStartHeight_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubscribeBlocksFromStartHeight is a helper method to define mock.On call +// - subscribeBlocksFromStartHeightRequest *access.SubscribeBlocksFromStartHeightRequest +// - accessAPI_SubscribeBlocksFromStartHeightServer access.AccessAPI_SubscribeBlocksFromStartHeightServer +func (_e *AccessAPIServer_Expecter) SubscribeBlocksFromStartHeight(subscribeBlocksFromStartHeightRequest interface{}, accessAPI_SubscribeBlocksFromStartHeightServer interface{}) *AccessAPIServer_SubscribeBlocksFromStartHeight_Call { + return &AccessAPIServer_SubscribeBlocksFromStartHeight_Call{Call: _e.mock.On("SubscribeBlocksFromStartHeight", subscribeBlocksFromStartHeightRequest, accessAPI_SubscribeBlocksFromStartHeightServer)} +} - return mock +func (_c *AccessAPIServer_SubscribeBlocksFromStartHeight_Call) Run(run func(subscribeBlocksFromStartHeightRequest *access.SubscribeBlocksFromStartHeightRequest, accessAPI_SubscribeBlocksFromStartHeightServer access.AccessAPI_SubscribeBlocksFromStartHeightServer)) *AccessAPIServer_SubscribeBlocksFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.SubscribeBlocksFromStartHeightRequest + if args[0] != nil { + arg0 = args[0].(*access.SubscribeBlocksFromStartHeightRequest) + } + var arg1 access.AccessAPI_SubscribeBlocksFromStartHeightServer + if args[1] != nil { + arg1 = args[1].(access.AccessAPI_SubscribeBlocksFromStartHeightServer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlocksFromStartHeight_Call) Return(err error) *AccessAPIServer_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccessAPIServer_SubscribeBlocksFromStartHeight_Call) RunAndReturn(run func(subscribeBlocksFromStartHeightRequest *access.SubscribeBlocksFromStartHeightRequest, accessAPI_SubscribeBlocksFromStartHeightServer access.AccessAPI_SubscribeBlocksFromStartHeightServer) error) *AccessAPIServer_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/mock/execution_api_client.go b/engine/access/mock/execution_api_client.go index 21dc0f71b8f..c884f022c02 100644 --- a/engine/access/mock/execution_api_client.go +++ b/engine/access/mock/execution_api_client.go @@ -1,23 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - execution "github.com/onflow/flow/protobuf/go/flow/execution" - grpc "google.golang.org/grpc" + "context" + "github.com/onflow/flow/protobuf/go/flow/execution" mock "github.com/stretchr/testify/mock" + "google.golang.org/grpc" ) +// NewExecutionAPIClient creates a new instance of ExecutionAPIClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionAPIClient(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionAPIClient { + mock := &ExecutionAPIClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionAPIClient is an autogenerated mock type for the ExecutionAPIClient type type ExecutionAPIClient struct { mock.Mock } -// ExecuteScriptAtBlockID provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *execution.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption) (*execution.ExecuteScriptAtBlockIDResponse, error) { +type ExecutionAPIClient_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionAPIClient) EXPECT() *ExecutionAPIClient_Expecter { + return &ExecutionAPIClient_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockID provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *execution.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption) (*execution.ExecuteScriptAtBlockIDResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -25,7 +49,7 @@ func (_m *ExecutionAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *ex var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -33,28 +57,78 @@ func (_m *ExecutionAPIClient) ExecuteScriptAtBlockID(ctx context.Context, in *ex var r0 *execution.ExecuteScriptAtBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) (*execution.ExecuteScriptAtBlockIDResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) (*execution.ExecuteScriptAtBlockIDResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) *execution.ExecuteScriptAtBlockIDResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) *execution.ExecuteScriptAtBlockIDResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.ExecuteScriptAtBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockID provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetAccountAtBlockID(ctx context.Context, in *execution.GetAccountAtBlockIDRequest, opts ...grpc.CallOption) (*execution.GetAccountAtBlockIDResponse, error) { +// ExecutionAPIClient_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type ExecutionAPIClient_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.ExecuteScriptAtBlockIDRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) ExecuteScriptAtBlockID(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_ExecuteScriptAtBlockID_Call { + return &ExecutionAPIClient_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_ExecuteScriptAtBlockID_Call) Run(run func(ctx context.Context, in *execution.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.ExecuteScriptAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.ExecuteScriptAtBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_ExecuteScriptAtBlockID_Call) Return(executeScriptAtBlockIDResponse *execution.ExecuteScriptAtBlockIDResponse, err error) *ExecutionAPIClient_ExecuteScriptAtBlockID_Call { + _c.Call.Return(executeScriptAtBlockIDResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(ctx context.Context, in *execution.ExecuteScriptAtBlockIDRequest, opts ...grpc.CallOption) (*execution.ExecuteScriptAtBlockIDResponse, error)) *ExecutionAPIClient_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockID provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetAccountAtBlockID(ctx context.Context, in *execution.GetAccountAtBlockIDRequest, opts ...grpc.CallOption) (*execution.GetAccountAtBlockIDResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -62,7 +136,7 @@ func (_m *ExecutionAPIClient) GetAccountAtBlockID(ctx context.Context, in *execu var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockID") @@ -70,28 +144,78 @@ func (_m *ExecutionAPIClient) GetAccountAtBlockID(ctx context.Context, in *execu var r0 *execution.GetAccountAtBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest, ...grpc.CallOption) (*execution.GetAccountAtBlockIDResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest, ...grpc.CallOption) (*execution.GetAccountAtBlockIDResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest, ...grpc.CallOption) *execution.GetAccountAtBlockIDResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest, ...grpc.CallOption) *execution.GetAccountAtBlockIDResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetAccountAtBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetAccountAtBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetAccountAtBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByID provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetBlockHeaderByID(ctx context.Context, in *execution.GetBlockHeaderByIDRequest, opts ...grpc.CallOption) (*execution.BlockHeaderResponse, error) { +// ExecutionAPIClient_GetAccountAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockID' +type ExecutionAPIClient_GetAccountAtBlockID_Call struct { + *mock.Call +} + +// GetAccountAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetAccountAtBlockIDRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetAccountAtBlockID(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetAccountAtBlockID_Call { + return &ExecutionAPIClient_GetAccountAtBlockID_Call{Call: _e.mock.On("GetAccountAtBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetAccountAtBlockID_Call) Run(run func(ctx context.Context, in *execution.GetAccountAtBlockIDRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetAccountAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetAccountAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetAccountAtBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetAccountAtBlockID_Call) Return(getAccountAtBlockIDResponse *execution.GetAccountAtBlockIDResponse, err error) *ExecutionAPIClient_GetAccountAtBlockID_Call { + _c.Call.Return(getAccountAtBlockIDResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetAccountAtBlockID_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetAccountAtBlockIDRequest, opts ...grpc.CallOption) (*execution.GetAccountAtBlockIDResponse, error)) *ExecutionAPIClient_GetAccountAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByID provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetBlockHeaderByID(ctx context.Context, in *execution.GetBlockHeaderByIDRequest, opts ...grpc.CallOption) (*execution.BlockHeaderResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -99,7 +223,7 @@ func (_m *ExecutionAPIClient) GetBlockHeaderByID(ctx context.Context, in *execut var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByID") @@ -107,28 +231,78 @@ func (_m *ExecutionAPIClient) GetBlockHeaderByID(ctx context.Context, in *execut var r0 *execution.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest, ...grpc.CallOption) (*execution.BlockHeaderResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest, ...grpc.CallOption) (*execution.BlockHeaderResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest, ...grpc.CallOption) *execution.BlockHeaderResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest, ...grpc.CallOption) *execution.BlockHeaderResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetBlockHeaderByIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetBlockHeaderByIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForBlockIDs provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetEventsForBlockIDs(ctx context.Context, in *execution.GetEventsForBlockIDsRequest, opts ...grpc.CallOption) (*execution.GetEventsForBlockIDsResponse, error) { +// ExecutionAPIClient_GetBlockHeaderByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByID' +type ExecutionAPIClient_GetBlockHeaderByID_Call struct { + *mock.Call +} + +// GetBlockHeaderByID is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetBlockHeaderByIDRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetBlockHeaderByID(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetBlockHeaderByID_Call { + return &ExecutionAPIClient_GetBlockHeaderByID_Call{Call: _e.mock.On("GetBlockHeaderByID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetBlockHeaderByID_Call) Run(run func(ctx context.Context, in *execution.GetBlockHeaderByIDRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetBlockHeaderByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetBlockHeaderByIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetBlockHeaderByIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetBlockHeaderByID_Call) Return(blockHeaderResponse *execution.BlockHeaderResponse, err error) *ExecutionAPIClient_GetBlockHeaderByID_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetBlockHeaderByID_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetBlockHeaderByIDRequest, opts ...grpc.CallOption) (*execution.BlockHeaderResponse, error)) *ExecutionAPIClient_GetBlockHeaderByID_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForBlockIDs provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetEventsForBlockIDs(ctx context.Context, in *execution.GetEventsForBlockIDsRequest, opts ...grpc.CallOption) (*execution.GetEventsForBlockIDsResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -136,7 +310,7 @@ func (_m *ExecutionAPIClient) GetEventsForBlockIDs(ctx context.Context, in *exec var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetEventsForBlockIDs") @@ -144,28 +318,78 @@ func (_m *ExecutionAPIClient) GetEventsForBlockIDs(ctx context.Context, in *exec var r0 *execution.GetEventsForBlockIDsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest, ...grpc.CallOption) (*execution.GetEventsForBlockIDsResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest, ...grpc.CallOption) (*execution.GetEventsForBlockIDsResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest, ...grpc.CallOption) *execution.GetEventsForBlockIDsResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest, ...grpc.CallOption) *execution.GetEventsForBlockIDsResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetEventsForBlockIDsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetEventsForBlockIDsRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetEventsForBlockIDsRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlockHeader provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetLatestBlockHeader(ctx context.Context, in *execution.GetLatestBlockHeaderRequest, opts ...grpc.CallOption) (*execution.BlockHeaderResponse, error) { +// ExecutionAPIClient_GetEventsForBlockIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForBlockIDs' +type ExecutionAPIClient_GetEventsForBlockIDs_Call struct { + *mock.Call +} + +// GetEventsForBlockIDs is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetEventsForBlockIDsRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetEventsForBlockIDs(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetEventsForBlockIDs_Call { + return &ExecutionAPIClient_GetEventsForBlockIDs_Call{Call: _e.mock.On("GetEventsForBlockIDs", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetEventsForBlockIDs_Call) Run(run func(ctx context.Context, in *execution.GetEventsForBlockIDsRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetEventsForBlockIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetEventsForBlockIDsRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetEventsForBlockIDsRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetEventsForBlockIDs_Call) Return(getEventsForBlockIDsResponse *execution.GetEventsForBlockIDsResponse, err error) *ExecutionAPIClient_GetEventsForBlockIDs_Call { + _c.Call.Return(getEventsForBlockIDsResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetEventsForBlockIDs_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetEventsForBlockIDsRequest, opts ...grpc.CallOption) (*execution.GetEventsForBlockIDsResponse, error)) *ExecutionAPIClient_GetEventsForBlockIDs_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlockHeader provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetLatestBlockHeader(ctx context.Context, in *execution.GetLatestBlockHeaderRequest, opts ...grpc.CallOption) (*execution.BlockHeaderResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -173,7 +397,7 @@ func (_m *ExecutionAPIClient) GetLatestBlockHeader(ctx context.Context, in *exec var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetLatestBlockHeader") @@ -181,28 +405,78 @@ func (_m *ExecutionAPIClient) GetLatestBlockHeader(ctx context.Context, in *exec var r0 *execution.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest, ...grpc.CallOption) (*execution.BlockHeaderResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest, ...grpc.CallOption) (*execution.BlockHeaderResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest, ...grpc.CallOption) *execution.BlockHeaderResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest, ...grpc.CallOption) *execution.BlockHeaderResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetLatestBlockHeaderRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetLatestBlockHeaderRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetRegisterAtBlockID provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetRegisterAtBlockID(ctx context.Context, in *execution.GetRegisterAtBlockIDRequest, opts ...grpc.CallOption) (*execution.GetRegisterAtBlockIDResponse, error) { +// ExecutionAPIClient_GetLatestBlockHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlockHeader' +type ExecutionAPIClient_GetLatestBlockHeader_Call struct { + *mock.Call +} + +// GetLatestBlockHeader is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetLatestBlockHeaderRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetLatestBlockHeader(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetLatestBlockHeader_Call { + return &ExecutionAPIClient_GetLatestBlockHeader_Call{Call: _e.mock.On("GetLatestBlockHeader", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetLatestBlockHeader_Call) Run(run func(ctx context.Context, in *execution.GetLatestBlockHeaderRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetLatestBlockHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetLatestBlockHeaderRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetLatestBlockHeaderRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetLatestBlockHeader_Call) Return(blockHeaderResponse *execution.BlockHeaderResponse, err error) *ExecutionAPIClient_GetLatestBlockHeader_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetLatestBlockHeader_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetLatestBlockHeaderRequest, opts ...grpc.CallOption) (*execution.BlockHeaderResponse, error)) *ExecutionAPIClient_GetLatestBlockHeader_Call { + _c.Call.Return(run) + return _c +} + +// GetRegisterAtBlockID provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetRegisterAtBlockID(ctx context.Context, in *execution.GetRegisterAtBlockIDRequest, opts ...grpc.CallOption) (*execution.GetRegisterAtBlockIDResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -210,7 +484,7 @@ func (_m *ExecutionAPIClient) GetRegisterAtBlockID(ctx context.Context, in *exec var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetRegisterAtBlockID") @@ -218,28 +492,78 @@ func (_m *ExecutionAPIClient) GetRegisterAtBlockID(ctx context.Context, in *exec var r0 *execution.GetRegisterAtBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest, ...grpc.CallOption) (*execution.GetRegisterAtBlockIDResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest, ...grpc.CallOption) (*execution.GetRegisterAtBlockIDResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest, ...grpc.CallOption) *execution.GetRegisterAtBlockIDResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest, ...grpc.CallOption) *execution.GetRegisterAtBlockIDResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetRegisterAtBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetRegisterAtBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetRegisterAtBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionErrorMessage provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetTransactionErrorMessage(ctx context.Context, in *execution.GetTransactionErrorMessageRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error) { +// ExecutionAPIClient_GetRegisterAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegisterAtBlockID' +type ExecutionAPIClient_GetRegisterAtBlockID_Call struct { + *mock.Call +} + +// GetRegisterAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetRegisterAtBlockIDRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetRegisterAtBlockID(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetRegisterAtBlockID_Call { + return &ExecutionAPIClient_GetRegisterAtBlockID_Call{Call: _e.mock.On("GetRegisterAtBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetRegisterAtBlockID_Call) Run(run func(ctx context.Context, in *execution.GetRegisterAtBlockIDRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetRegisterAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetRegisterAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetRegisterAtBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetRegisterAtBlockID_Call) Return(getRegisterAtBlockIDResponse *execution.GetRegisterAtBlockIDResponse, err error) *ExecutionAPIClient_GetRegisterAtBlockID_Call { + _c.Call.Return(getRegisterAtBlockIDResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetRegisterAtBlockID_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetRegisterAtBlockIDRequest, opts ...grpc.CallOption) (*execution.GetRegisterAtBlockIDResponse, error)) *ExecutionAPIClient_GetRegisterAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionErrorMessage provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetTransactionErrorMessage(ctx context.Context, in *execution.GetTransactionErrorMessageRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -247,7 +571,7 @@ func (_m *ExecutionAPIClient) GetTransactionErrorMessage(ctx context.Context, in var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionErrorMessage") @@ -255,28 +579,78 @@ func (_m *ExecutionAPIClient) GetTransactionErrorMessage(ctx context.Context, in var r0 *execution.GetTransactionErrorMessageResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest, ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest, ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest, ...grpc.CallOption) *execution.GetTransactionErrorMessageResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest, ...grpc.CallOption) *execution.GetTransactionErrorMessageResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionErrorMessageResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionErrorMessageByIndex provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetTransactionErrorMessageByIndex(ctx context.Context, in *execution.GetTransactionErrorMessageByIndexRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error) { +// ExecutionAPIClient_GetTransactionErrorMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionErrorMessage' +type ExecutionAPIClient_GetTransactionErrorMessage_Call struct { + *mock.Call +} + +// GetTransactionErrorMessage is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetTransactionErrorMessageRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetTransactionErrorMessage(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetTransactionErrorMessage_Call { + return &ExecutionAPIClient_GetTransactionErrorMessage_Call{Call: _e.mock.On("GetTransactionErrorMessage", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessage_Call) Run(run func(ctx context.Context, in *execution.GetTransactionErrorMessageRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetTransactionErrorMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionErrorMessageRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionErrorMessageRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessage_Call) Return(getTransactionErrorMessageResponse *execution.GetTransactionErrorMessageResponse, err error) *ExecutionAPIClient_GetTransactionErrorMessage_Call { + _c.Call.Return(getTransactionErrorMessageResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessage_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetTransactionErrorMessageRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error)) *ExecutionAPIClient_GetTransactionErrorMessage_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionErrorMessageByIndex provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetTransactionErrorMessageByIndex(ctx context.Context, in *execution.GetTransactionErrorMessageByIndexRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -284,7 +658,7 @@ func (_m *ExecutionAPIClient) GetTransactionErrorMessageByIndex(ctx context.Cont var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionErrorMessageByIndex") @@ -292,28 +666,78 @@ func (_m *ExecutionAPIClient) GetTransactionErrorMessageByIndex(ctx context.Cont var r0 *execution.GetTransactionErrorMessageResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest, ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest, ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest, ...grpc.CallOption) *execution.GetTransactionErrorMessageResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest, ...grpc.CallOption) *execution.GetTransactionErrorMessageResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionErrorMessageResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionErrorMessagesByBlockID provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetTransactionErrorMessagesByBlockID(ctx context.Context, in *execution.GetTransactionErrorMessagesByBlockIDRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessagesResponse, error) { +// ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionErrorMessageByIndex' +type ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call struct { + *mock.Call +} + +// GetTransactionErrorMessageByIndex is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetTransactionErrorMessageByIndexRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetTransactionErrorMessageByIndex(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call { + return &ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call{Call: _e.mock.On("GetTransactionErrorMessageByIndex", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call) Run(run func(ctx context.Context, in *execution.GetTransactionErrorMessageByIndexRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionErrorMessageByIndexRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionErrorMessageByIndexRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call) Return(getTransactionErrorMessageResponse *execution.GetTransactionErrorMessageResponse, err error) *ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call { + _c.Call.Return(getTransactionErrorMessageResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetTransactionErrorMessageByIndexRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessageResponse, error)) *ExecutionAPIClient_GetTransactionErrorMessageByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionErrorMessagesByBlockID provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetTransactionErrorMessagesByBlockID(ctx context.Context, in *execution.GetTransactionErrorMessagesByBlockIDRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessagesResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -321,7 +745,7 @@ func (_m *ExecutionAPIClient) GetTransactionErrorMessagesByBlockID(ctx context.C var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionErrorMessagesByBlockID") @@ -329,28 +753,78 @@ func (_m *ExecutionAPIClient) GetTransactionErrorMessagesByBlockID(ctx context.C var r0 *execution.GetTransactionErrorMessagesResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest, ...grpc.CallOption) (*execution.GetTransactionErrorMessagesResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest, ...grpc.CallOption) (*execution.GetTransactionErrorMessagesResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest, ...grpc.CallOption) *execution.GetTransactionErrorMessagesResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest, ...grpc.CallOption) *execution.GetTransactionErrorMessagesResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionErrorMessagesResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionExecutionMetricsAfter provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetTransactionExecutionMetricsAfter(ctx context.Context, in *execution.GetTransactionExecutionMetricsAfterRequest, opts ...grpc.CallOption) (*execution.GetTransactionExecutionMetricsAfterResponse, error) { +// ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionErrorMessagesByBlockID' +type ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call struct { + *mock.Call +} + +// GetTransactionErrorMessagesByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetTransactionErrorMessagesByBlockIDRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetTransactionErrorMessagesByBlockID(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call { + return &ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call{Call: _e.mock.On("GetTransactionErrorMessagesByBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call) Run(run func(ctx context.Context, in *execution.GetTransactionErrorMessagesByBlockIDRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionErrorMessagesByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionErrorMessagesByBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call) Return(getTransactionErrorMessagesResponse *execution.GetTransactionErrorMessagesResponse, err error) *ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call { + _c.Call.Return(getTransactionErrorMessagesResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetTransactionErrorMessagesByBlockIDRequest, opts ...grpc.CallOption) (*execution.GetTransactionErrorMessagesResponse, error)) *ExecutionAPIClient_GetTransactionErrorMessagesByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionExecutionMetricsAfter provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetTransactionExecutionMetricsAfter(ctx context.Context, in *execution.GetTransactionExecutionMetricsAfterRequest, opts ...grpc.CallOption) (*execution.GetTransactionExecutionMetricsAfterResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -358,7 +832,7 @@ func (_m *ExecutionAPIClient) GetTransactionExecutionMetricsAfter(ctx context.Co var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionExecutionMetricsAfter") @@ -366,28 +840,78 @@ func (_m *ExecutionAPIClient) GetTransactionExecutionMetricsAfter(ctx context.Co var r0 *execution.GetTransactionExecutionMetricsAfterResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest, ...grpc.CallOption) (*execution.GetTransactionExecutionMetricsAfterResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest, ...grpc.CallOption) (*execution.GetTransactionExecutionMetricsAfterResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest, ...grpc.CallOption) *execution.GetTransactionExecutionMetricsAfterResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest, ...grpc.CallOption) *execution.GetTransactionExecutionMetricsAfterResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionExecutionMetricsAfterResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResult provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetTransactionResult(ctx context.Context, in *execution.GetTransactionResultRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultResponse, error) { +// ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionExecutionMetricsAfter' +type ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call struct { + *mock.Call +} + +// GetTransactionExecutionMetricsAfter is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetTransactionExecutionMetricsAfterRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetTransactionExecutionMetricsAfter(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call { + return &ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call{Call: _e.mock.On("GetTransactionExecutionMetricsAfter", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call) Run(run func(ctx context.Context, in *execution.GetTransactionExecutionMetricsAfterRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionExecutionMetricsAfterRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionExecutionMetricsAfterRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call) Return(getTransactionExecutionMetricsAfterResponse *execution.GetTransactionExecutionMetricsAfterResponse, err error) *ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call { + _c.Call.Return(getTransactionExecutionMetricsAfterResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetTransactionExecutionMetricsAfterRequest, opts ...grpc.CallOption) (*execution.GetTransactionExecutionMetricsAfterResponse, error)) *ExecutionAPIClient_GetTransactionExecutionMetricsAfter_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResult provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetTransactionResult(ctx context.Context, in *execution.GetTransactionResultRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -395,7 +919,7 @@ func (_m *ExecutionAPIClient) GetTransactionResult(ctx context.Context, in *exec var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionResult") @@ -403,28 +927,78 @@ func (_m *ExecutionAPIClient) GetTransactionResult(ctx context.Context, in *exec var r0 *execution.GetTransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest, ...grpc.CallOption) (*execution.GetTransactionResultResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest, ...grpc.CallOption) (*execution.GetTransactionResultResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest, ...grpc.CallOption) *execution.GetTransactionResultResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest, ...grpc.CallOption) *execution.GetTransactionResultResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionResultRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionResultRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultByIndex provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetTransactionResultByIndex(ctx context.Context, in *execution.GetTransactionByIndexRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultResponse, error) { +// ExecutionAPIClient_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type ExecutionAPIClient_GetTransactionResult_Call struct { + *mock.Call +} + +// GetTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetTransactionResultRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetTransactionResult(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetTransactionResult_Call { + return &ExecutionAPIClient_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetTransactionResult_Call) Run(run func(ctx context.Context, in *execution.GetTransactionResultRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionResultRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionResultRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionResult_Call) Return(getTransactionResultResponse *execution.GetTransactionResultResponse, err error) *ExecutionAPIClient_GetTransactionResult_Call { + _c.Call.Return(getTransactionResultResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionResult_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetTransactionResultRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultResponse, error)) *ExecutionAPIClient_GetTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultByIndex provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetTransactionResultByIndex(ctx context.Context, in *execution.GetTransactionByIndexRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -432,7 +1006,7 @@ func (_m *ExecutionAPIClient) GetTransactionResultByIndex(ctx context.Context, i var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionResultByIndex") @@ -440,28 +1014,78 @@ func (_m *ExecutionAPIClient) GetTransactionResultByIndex(ctx context.Context, i var r0 *execution.GetTransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest, ...grpc.CallOption) (*execution.GetTransactionResultResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest, ...grpc.CallOption) (*execution.GetTransactionResultResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest, ...grpc.CallOption) *execution.GetTransactionResultResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest, ...grpc.CallOption) *execution.GetTransactionResultResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionByIndexRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionByIndexRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultsByBlockID provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) GetTransactionResultsByBlockID(ctx context.Context, in *execution.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultsResponse, error) { +// ExecutionAPIClient_GetTransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultByIndex' +type ExecutionAPIClient_GetTransactionResultByIndex_Call struct { + *mock.Call +} + +// GetTransactionResultByIndex is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetTransactionByIndexRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetTransactionResultByIndex(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetTransactionResultByIndex_Call { + return &ExecutionAPIClient_GetTransactionResultByIndex_Call{Call: _e.mock.On("GetTransactionResultByIndex", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetTransactionResultByIndex_Call) Run(run func(ctx context.Context, in *execution.GetTransactionByIndexRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetTransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionByIndexRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionByIndexRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionResultByIndex_Call) Return(getTransactionResultResponse *execution.GetTransactionResultResponse, err error) *ExecutionAPIClient_GetTransactionResultByIndex_Call { + _c.Call.Return(getTransactionResultResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionResultByIndex_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetTransactionByIndexRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultResponse, error)) *ExecutionAPIClient_GetTransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultsByBlockID provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) GetTransactionResultsByBlockID(ctx context.Context, in *execution.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultsResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -469,7 +1093,7 @@ func (_m *ExecutionAPIClient) GetTransactionResultsByBlockID(ctx context.Context var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for GetTransactionResultsByBlockID") @@ -477,28 +1101,78 @@ func (_m *ExecutionAPIClient) GetTransactionResultsByBlockID(ctx context.Context var r0 *execution.GetTransactionResultsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest, ...grpc.CallOption) (*execution.GetTransactionResultsResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest, ...grpc.CallOption) (*execution.GetTransactionResultsResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest, ...grpc.CallOption) *execution.GetTransactionResultsResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest, ...grpc.CallOption) *execution.GetTransactionResultsResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionResultsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionsByBlockIDRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionsByBlockIDRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// Ping provides a mock function with given fields: ctx, in, opts -func (_m *ExecutionAPIClient) Ping(ctx context.Context, in *execution.PingRequest, opts ...grpc.CallOption) (*execution.PingResponse, error) { +// ExecutionAPIClient_GetTransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultsByBlockID' +type ExecutionAPIClient_GetTransactionResultsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionResultsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.GetTransactionsByBlockIDRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) GetTransactionResultsByBlockID(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_GetTransactionResultsByBlockID_Call { + return &ExecutionAPIClient_GetTransactionResultsByBlockID_Call{Call: _e.mock.On("GetTransactionResultsByBlockID", + append([]interface{}{ctx, in}, opts...)...)} +} + +func (_c *ExecutionAPIClient_GetTransactionResultsByBlockID_Call) Run(run func(ctx context.Context, in *execution.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_GetTransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionsByBlockIDRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionResultsByBlockID_Call) Return(getTransactionResultsResponse *execution.GetTransactionResultsResponse, err error) *ExecutionAPIClient_GetTransactionResultsByBlockID_Call { + _c.Call.Return(getTransactionResultsResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_GetTransactionResultsByBlockID_Call) RunAndReturn(run func(ctx context.Context, in *execution.GetTransactionsByBlockIDRequest, opts ...grpc.CallOption) (*execution.GetTransactionResultsResponse, error)) *ExecutionAPIClient_GetTransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Ping provides a mock function for the type ExecutionAPIClient +func (_mock *ExecutionAPIClient) Ping(ctx context.Context, in *execution.PingRequest, opts ...grpc.CallOption) (*execution.PingResponse, error) { + // grpc.CallOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -506,7 +1180,7 @@ func (_m *ExecutionAPIClient) Ping(ctx context.Context, in *execution.PingReques var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for Ping") @@ -514,36 +1188,71 @@ func (_m *ExecutionAPIClient) Ping(ctx context.Context, in *execution.PingReques var r0 *execution.PingResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.PingRequest, ...grpc.CallOption) (*execution.PingResponse, error)); ok { - return rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.PingRequest, ...grpc.CallOption) (*execution.PingResponse, error)); ok { + return returnFunc(ctx, in, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.PingRequest, ...grpc.CallOption) *execution.PingResponse); ok { - r0 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.PingRequest, ...grpc.CallOption) *execution.PingResponse); ok { + r0 = returnFunc(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.PingResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.PingRequest, ...grpc.CallOption) error); ok { - r1 = rf(ctx, in, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.PingRequest, ...grpc.CallOption) error); ok { + r1 = returnFunc(ctx, in, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionAPIClient creates a new instance of ExecutionAPIClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionAPIClient(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionAPIClient { - mock := &ExecutionAPIClient{} - mock.Mock.Test(t) +// ExecutionAPIClient_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping' +type ExecutionAPIClient_Ping_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Ping is a helper method to define mock.On call +// - ctx context.Context +// - in *execution.PingRequest +// - opts ...grpc.CallOption +func (_e *ExecutionAPIClient_Expecter) Ping(ctx interface{}, in interface{}, opts ...interface{}) *ExecutionAPIClient_Ping_Call { + return &ExecutionAPIClient_Ping_Call{Call: _e.mock.On("Ping", + append([]interface{}{ctx, in}, opts...)...)} +} - return mock +func (_c *ExecutionAPIClient_Ping_Call) Run(run func(ctx context.Context, in *execution.PingRequest, opts ...grpc.CallOption)) *ExecutionAPIClient_Ping_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.PingRequest + if args[1] != nil { + arg1 = args[1].(*execution.PingRequest) + } + var arg2 []grpc.CallOption + variadicArgs := make([]grpc.CallOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(grpc.CallOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ExecutionAPIClient_Ping_Call) Return(pingResponse *execution.PingResponse, err error) *ExecutionAPIClient_Ping_Call { + _c.Call.Return(pingResponse, err) + return _c +} + +func (_c *ExecutionAPIClient_Ping_Call) RunAndReturn(run func(ctx context.Context, in *execution.PingRequest, opts ...grpc.CallOption) (*execution.PingResponse, error)) *ExecutionAPIClient_Ping_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/mock/execution_api_server.go b/engine/access/mock/execution_api_server.go index 0f66134f6b1..8f4b90e9994 100644 --- a/engine/access/mock/execution_api_server.go +++ b/engine/access/mock/execution_api_server.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - execution "github.com/onflow/flow/protobuf/go/flow/execution" + "github.com/onflow/flow/protobuf/go/flow/execution" mock "github.com/stretchr/testify/mock" ) +// NewExecutionAPIServer creates a new instance of ExecutionAPIServer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionAPIServer(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionAPIServer { + mock := &ExecutionAPIServer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionAPIServer is an autogenerated mock type for the ExecutionAPIServer type type ExecutionAPIServer struct { mock.Mock } -// ExecuteScriptAtBlockID provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) ExecuteScriptAtBlockID(_a0 context.Context, _a1 *execution.ExecuteScriptAtBlockIDRequest) (*execution.ExecuteScriptAtBlockIDResponse, error) { - ret := _m.Called(_a0, _a1) +type ExecutionAPIServer_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionAPIServer) EXPECT() *ExecutionAPIServer_Expecter { + return &ExecutionAPIServer_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockID provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) ExecuteScriptAtBlockID(context1 context.Context, executeScriptAtBlockIDRequest *execution.ExecuteScriptAtBlockIDRequest) (*execution.ExecuteScriptAtBlockIDResponse, error) { + ret := _mock.Called(context1, executeScriptAtBlockIDRequest) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -24,29 +48,67 @@ func (_m *ExecutionAPIServer) ExecuteScriptAtBlockID(_a0 context.Context, _a1 *e var r0 *execution.ExecuteScriptAtBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest) (*execution.ExecuteScriptAtBlockIDResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest) (*execution.ExecuteScriptAtBlockIDResponse, error)); ok { + return returnFunc(context1, executeScriptAtBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest) *execution.ExecuteScriptAtBlockIDResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest) *execution.ExecuteScriptAtBlockIDResponse); ok { + r0 = returnFunc(context1, executeScriptAtBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.ExecuteScriptAtBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.ExecuteScriptAtBlockIDRequest) error); ok { + r1 = returnFunc(context1, executeScriptAtBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockID provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetAccountAtBlockID(_a0 context.Context, _a1 *execution.GetAccountAtBlockIDRequest) (*execution.GetAccountAtBlockIDResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type ExecutionAPIServer_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - context1 context.Context +// - executeScriptAtBlockIDRequest *execution.ExecuteScriptAtBlockIDRequest +func (_e *ExecutionAPIServer_Expecter) ExecuteScriptAtBlockID(context1 interface{}, executeScriptAtBlockIDRequest interface{}) *ExecutionAPIServer_ExecuteScriptAtBlockID_Call { + return &ExecutionAPIServer_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", context1, executeScriptAtBlockIDRequest)} +} + +func (_c *ExecutionAPIServer_ExecuteScriptAtBlockID_Call) Run(run func(context1 context.Context, executeScriptAtBlockIDRequest *execution.ExecuteScriptAtBlockIDRequest)) *ExecutionAPIServer_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.ExecuteScriptAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.ExecuteScriptAtBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_ExecuteScriptAtBlockID_Call) Return(executeScriptAtBlockIDResponse *execution.ExecuteScriptAtBlockIDResponse, err error) *ExecutionAPIServer_ExecuteScriptAtBlockID_Call { + _c.Call.Return(executeScriptAtBlockIDResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(context1 context.Context, executeScriptAtBlockIDRequest *execution.ExecuteScriptAtBlockIDRequest) (*execution.ExecuteScriptAtBlockIDResponse, error)) *ExecutionAPIServer_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockID provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetAccountAtBlockID(context1 context.Context, getAccountAtBlockIDRequest *execution.GetAccountAtBlockIDRequest) (*execution.GetAccountAtBlockIDResponse, error) { + ret := _mock.Called(context1, getAccountAtBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockID") @@ -54,29 +116,67 @@ func (_m *ExecutionAPIServer) GetAccountAtBlockID(_a0 context.Context, _a1 *exec var r0 *execution.GetAccountAtBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest) (*execution.GetAccountAtBlockIDResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest) (*execution.GetAccountAtBlockIDResponse, error)); ok { + return returnFunc(context1, getAccountAtBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest) *execution.GetAccountAtBlockIDResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetAccountAtBlockIDRequest) *execution.GetAccountAtBlockIDResponse); ok { + r0 = returnFunc(context1, getAccountAtBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetAccountAtBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetAccountAtBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetAccountAtBlockIDRequest) error); ok { + r1 = returnFunc(context1, getAccountAtBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByID provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetBlockHeaderByID(_a0 context.Context, _a1 *execution.GetBlockHeaderByIDRequest) (*execution.BlockHeaderResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetAccountAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockID' +type ExecutionAPIServer_GetAccountAtBlockID_Call struct { + *mock.Call +} + +// GetAccountAtBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getAccountAtBlockIDRequest *execution.GetAccountAtBlockIDRequest +func (_e *ExecutionAPIServer_Expecter) GetAccountAtBlockID(context1 interface{}, getAccountAtBlockIDRequest interface{}) *ExecutionAPIServer_GetAccountAtBlockID_Call { + return &ExecutionAPIServer_GetAccountAtBlockID_Call{Call: _e.mock.On("GetAccountAtBlockID", context1, getAccountAtBlockIDRequest)} +} + +func (_c *ExecutionAPIServer_GetAccountAtBlockID_Call) Run(run func(context1 context.Context, getAccountAtBlockIDRequest *execution.GetAccountAtBlockIDRequest)) *ExecutionAPIServer_GetAccountAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetAccountAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetAccountAtBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetAccountAtBlockID_Call) Return(getAccountAtBlockIDResponse *execution.GetAccountAtBlockIDResponse, err error) *ExecutionAPIServer_GetAccountAtBlockID_Call { + _c.Call.Return(getAccountAtBlockIDResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetAccountAtBlockID_Call) RunAndReturn(run func(context1 context.Context, getAccountAtBlockIDRequest *execution.GetAccountAtBlockIDRequest) (*execution.GetAccountAtBlockIDResponse, error)) *ExecutionAPIServer_GetAccountAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByID provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetBlockHeaderByID(context1 context.Context, getBlockHeaderByIDRequest *execution.GetBlockHeaderByIDRequest) (*execution.BlockHeaderResponse, error) { + ret := _mock.Called(context1, getBlockHeaderByIDRequest) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByID") @@ -84,29 +184,67 @@ func (_m *ExecutionAPIServer) GetBlockHeaderByID(_a0 context.Context, _a1 *execu var r0 *execution.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest) (*execution.BlockHeaderResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest) (*execution.BlockHeaderResponse, error)); ok { + return returnFunc(context1, getBlockHeaderByIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest) *execution.BlockHeaderResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetBlockHeaderByIDRequest) *execution.BlockHeaderResponse); ok { + r0 = returnFunc(context1, getBlockHeaderByIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetBlockHeaderByIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetBlockHeaderByIDRequest) error); ok { + r1 = returnFunc(context1, getBlockHeaderByIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForBlockIDs provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetEventsForBlockIDs(_a0 context.Context, _a1 *execution.GetEventsForBlockIDsRequest) (*execution.GetEventsForBlockIDsResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetBlockHeaderByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByID' +type ExecutionAPIServer_GetBlockHeaderByID_Call struct { + *mock.Call +} + +// GetBlockHeaderByID is a helper method to define mock.On call +// - context1 context.Context +// - getBlockHeaderByIDRequest *execution.GetBlockHeaderByIDRequest +func (_e *ExecutionAPIServer_Expecter) GetBlockHeaderByID(context1 interface{}, getBlockHeaderByIDRequest interface{}) *ExecutionAPIServer_GetBlockHeaderByID_Call { + return &ExecutionAPIServer_GetBlockHeaderByID_Call{Call: _e.mock.On("GetBlockHeaderByID", context1, getBlockHeaderByIDRequest)} +} + +func (_c *ExecutionAPIServer_GetBlockHeaderByID_Call) Run(run func(context1 context.Context, getBlockHeaderByIDRequest *execution.GetBlockHeaderByIDRequest)) *ExecutionAPIServer_GetBlockHeaderByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetBlockHeaderByIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetBlockHeaderByIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetBlockHeaderByID_Call) Return(blockHeaderResponse *execution.BlockHeaderResponse, err error) *ExecutionAPIServer_GetBlockHeaderByID_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetBlockHeaderByID_Call) RunAndReturn(run func(context1 context.Context, getBlockHeaderByIDRequest *execution.GetBlockHeaderByIDRequest) (*execution.BlockHeaderResponse, error)) *ExecutionAPIServer_GetBlockHeaderByID_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForBlockIDs provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetEventsForBlockIDs(context1 context.Context, getEventsForBlockIDsRequest *execution.GetEventsForBlockIDsRequest) (*execution.GetEventsForBlockIDsResponse, error) { + ret := _mock.Called(context1, getEventsForBlockIDsRequest) if len(ret) == 0 { panic("no return value specified for GetEventsForBlockIDs") @@ -114,29 +252,67 @@ func (_m *ExecutionAPIServer) GetEventsForBlockIDs(_a0 context.Context, _a1 *exe var r0 *execution.GetEventsForBlockIDsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest) (*execution.GetEventsForBlockIDsResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest) (*execution.GetEventsForBlockIDsResponse, error)); ok { + return returnFunc(context1, getEventsForBlockIDsRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest) *execution.GetEventsForBlockIDsResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetEventsForBlockIDsRequest) *execution.GetEventsForBlockIDsResponse); ok { + r0 = returnFunc(context1, getEventsForBlockIDsRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetEventsForBlockIDsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetEventsForBlockIDsRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetEventsForBlockIDsRequest) error); ok { + r1 = returnFunc(context1, getEventsForBlockIDsRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlockHeader provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetLatestBlockHeader(_a0 context.Context, _a1 *execution.GetLatestBlockHeaderRequest) (*execution.BlockHeaderResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetEventsForBlockIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForBlockIDs' +type ExecutionAPIServer_GetEventsForBlockIDs_Call struct { + *mock.Call +} + +// GetEventsForBlockIDs is a helper method to define mock.On call +// - context1 context.Context +// - getEventsForBlockIDsRequest *execution.GetEventsForBlockIDsRequest +func (_e *ExecutionAPIServer_Expecter) GetEventsForBlockIDs(context1 interface{}, getEventsForBlockIDsRequest interface{}) *ExecutionAPIServer_GetEventsForBlockIDs_Call { + return &ExecutionAPIServer_GetEventsForBlockIDs_Call{Call: _e.mock.On("GetEventsForBlockIDs", context1, getEventsForBlockIDsRequest)} +} + +func (_c *ExecutionAPIServer_GetEventsForBlockIDs_Call) Run(run func(context1 context.Context, getEventsForBlockIDsRequest *execution.GetEventsForBlockIDsRequest)) *ExecutionAPIServer_GetEventsForBlockIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetEventsForBlockIDsRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetEventsForBlockIDsRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetEventsForBlockIDs_Call) Return(getEventsForBlockIDsResponse *execution.GetEventsForBlockIDsResponse, err error) *ExecutionAPIServer_GetEventsForBlockIDs_Call { + _c.Call.Return(getEventsForBlockIDsResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetEventsForBlockIDs_Call) RunAndReturn(run func(context1 context.Context, getEventsForBlockIDsRequest *execution.GetEventsForBlockIDsRequest) (*execution.GetEventsForBlockIDsResponse, error)) *ExecutionAPIServer_GetEventsForBlockIDs_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlockHeader provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetLatestBlockHeader(context1 context.Context, getLatestBlockHeaderRequest *execution.GetLatestBlockHeaderRequest) (*execution.BlockHeaderResponse, error) { + ret := _mock.Called(context1, getLatestBlockHeaderRequest) if len(ret) == 0 { panic("no return value specified for GetLatestBlockHeader") @@ -144,29 +320,67 @@ func (_m *ExecutionAPIServer) GetLatestBlockHeader(_a0 context.Context, _a1 *exe var r0 *execution.BlockHeaderResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest) (*execution.BlockHeaderResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest) (*execution.BlockHeaderResponse, error)); ok { + return returnFunc(context1, getLatestBlockHeaderRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest) *execution.BlockHeaderResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetLatestBlockHeaderRequest) *execution.BlockHeaderResponse); ok { + r0 = returnFunc(context1, getLatestBlockHeaderRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.BlockHeaderResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetLatestBlockHeaderRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetLatestBlockHeaderRequest) error); ok { + r1 = returnFunc(context1, getLatestBlockHeaderRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetRegisterAtBlockID provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetRegisterAtBlockID(_a0 context.Context, _a1 *execution.GetRegisterAtBlockIDRequest) (*execution.GetRegisterAtBlockIDResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetLatestBlockHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlockHeader' +type ExecutionAPIServer_GetLatestBlockHeader_Call struct { + *mock.Call +} + +// GetLatestBlockHeader is a helper method to define mock.On call +// - context1 context.Context +// - getLatestBlockHeaderRequest *execution.GetLatestBlockHeaderRequest +func (_e *ExecutionAPIServer_Expecter) GetLatestBlockHeader(context1 interface{}, getLatestBlockHeaderRequest interface{}) *ExecutionAPIServer_GetLatestBlockHeader_Call { + return &ExecutionAPIServer_GetLatestBlockHeader_Call{Call: _e.mock.On("GetLatestBlockHeader", context1, getLatestBlockHeaderRequest)} +} + +func (_c *ExecutionAPIServer_GetLatestBlockHeader_Call) Run(run func(context1 context.Context, getLatestBlockHeaderRequest *execution.GetLatestBlockHeaderRequest)) *ExecutionAPIServer_GetLatestBlockHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetLatestBlockHeaderRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetLatestBlockHeaderRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetLatestBlockHeader_Call) Return(blockHeaderResponse *execution.BlockHeaderResponse, err error) *ExecutionAPIServer_GetLatestBlockHeader_Call { + _c.Call.Return(blockHeaderResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetLatestBlockHeader_Call) RunAndReturn(run func(context1 context.Context, getLatestBlockHeaderRequest *execution.GetLatestBlockHeaderRequest) (*execution.BlockHeaderResponse, error)) *ExecutionAPIServer_GetLatestBlockHeader_Call { + _c.Call.Return(run) + return _c +} + +// GetRegisterAtBlockID provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetRegisterAtBlockID(context1 context.Context, getRegisterAtBlockIDRequest *execution.GetRegisterAtBlockIDRequest) (*execution.GetRegisterAtBlockIDResponse, error) { + ret := _mock.Called(context1, getRegisterAtBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetRegisterAtBlockID") @@ -174,29 +388,67 @@ func (_m *ExecutionAPIServer) GetRegisterAtBlockID(_a0 context.Context, _a1 *exe var r0 *execution.GetRegisterAtBlockIDResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest) (*execution.GetRegisterAtBlockIDResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest) (*execution.GetRegisterAtBlockIDResponse, error)); ok { + return returnFunc(context1, getRegisterAtBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest) *execution.GetRegisterAtBlockIDResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetRegisterAtBlockIDRequest) *execution.GetRegisterAtBlockIDResponse); ok { + r0 = returnFunc(context1, getRegisterAtBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetRegisterAtBlockIDResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetRegisterAtBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetRegisterAtBlockIDRequest) error); ok { + r1 = returnFunc(context1, getRegisterAtBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionErrorMessage provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetTransactionErrorMessage(_a0 context.Context, _a1 *execution.GetTransactionErrorMessageRequest) (*execution.GetTransactionErrorMessageResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetRegisterAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegisterAtBlockID' +type ExecutionAPIServer_GetRegisterAtBlockID_Call struct { + *mock.Call +} + +// GetRegisterAtBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getRegisterAtBlockIDRequest *execution.GetRegisterAtBlockIDRequest +func (_e *ExecutionAPIServer_Expecter) GetRegisterAtBlockID(context1 interface{}, getRegisterAtBlockIDRequest interface{}) *ExecutionAPIServer_GetRegisterAtBlockID_Call { + return &ExecutionAPIServer_GetRegisterAtBlockID_Call{Call: _e.mock.On("GetRegisterAtBlockID", context1, getRegisterAtBlockIDRequest)} +} + +func (_c *ExecutionAPIServer_GetRegisterAtBlockID_Call) Run(run func(context1 context.Context, getRegisterAtBlockIDRequest *execution.GetRegisterAtBlockIDRequest)) *ExecutionAPIServer_GetRegisterAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetRegisterAtBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetRegisterAtBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetRegisterAtBlockID_Call) Return(getRegisterAtBlockIDResponse *execution.GetRegisterAtBlockIDResponse, err error) *ExecutionAPIServer_GetRegisterAtBlockID_Call { + _c.Call.Return(getRegisterAtBlockIDResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetRegisterAtBlockID_Call) RunAndReturn(run func(context1 context.Context, getRegisterAtBlockIDRequest *execution.GetRegisterAtBlockIDRequest) (*execution.GetRegisterAtBlockIDResponse, error)) *ExecutionAPIServer_GetRegisterAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionErrorMessage provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetTransactionErrorMessage(context1 context.Context, getTransactionErrorMessageRequest *execution.GetTransactionErrorMessageRequest) (*execution.GetTransactionErrorMessageResponse, error) { + ret := _mock.Called(context1, getTransactionErrorMessageRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionErrorMessage") @@ -204,29 +456,67 @@ func (_m *ExecutionAPIServer) GetTransactionErrorMessage(_a0 context.Context, _a var r0 *execution.GetTransactionErrorMessageResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest) (*execution.GetTransactionErrorMessageResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest) (*execution.GetTransactionErrorMessageResponse, error)); ok { + return returnFunc(context1, getTransactionErrorMessageRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest) *execution.GetTransactionErrorMessageResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageRequest) *execution.GetTransactionErrorMessageResponse); ok { + r0 = returnFunc(context1, getTransactionErrorMessageRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionErrorMessageResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageRequest) error); ok { + r1 = returnFunc(context1, getTransactionErrorMessageRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionErrorMessageByIndex provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetTransactionErrorMessageByIndex(_a0 context.Context, _a1 *execution.GetTransactionErrorMessageByIndexRequest) (*execution.GetTransactionErrorMessageResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetTransactionErrorMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionErrorMessage' +type ExecutionAPIServer_GetTransactionErrorMessage_Call struct { + *mock.Call +} + +// GetTransactionErrorMessage is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionErrorMessageRequest *execution.GetTransactionErrorMessageRequest +func (_e *ExecutionAPIServer_Expecter) GetTransactionErrorMessage(context1 interface{}, getTransactionErrorMessageRequest interface{}) *ExecutionAPIServer_GetTransactionErrorMessage_Call { + return &ExecutionAPIServer_GetTransactionErrorMessage_Call{Call: _e.mock.On("GetTransactionErrorMessage", context1, getTransactionErrorMessageRequest)} +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessage_Call) Run(run func(context1 context.Context, getTransactionErrorMessageRequest *execution.GetTransactionErrorMessageRequest)) *ExecutionAPIServer_GetTransactionErrorMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionErrorMessageRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionErrorMessageRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessage_Call) Return(getTransactionErrorMessageResponse *execution.GetTransactionErrorMessageResponse, err error) *ExecutionAPIServer_GetTransactionErrorMessage_Call { + _c.Call.Return(getTransactionErrorMessageResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessage_Call) RunAndReturn(run func(context1 context.Context, getTransactionErrorMessageRequest *execution.GetTransactionErrorMessageRequest) (*execution.GetTransactionErrorMessageResponse, error)) *ExecutionAPIServer_GetTransactionErrorMessage_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionErrorMessageByIndex provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetTransactionErrorMessageByIndex(context1 context.Context, getTransactionErrorMessageByIndexRequest *execution.GetTransactionErrorMessageByIndexRequest) (*execution.GetTransactionErrorMessageResponse, error) { + ret := _mock.Called(context1, getTransactionErrorMessageByIndexRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionErrorMessageByIndex") @@ -234,29 +524,67 @@ func (_m *ExecutionAPIServer) GetTransactionErrorMessageByIndex(_a0 context.Cont var r0 *execution.GetTransactionErrorMessageResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest) (*execution.GetTransactionErrorMessageResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest) (*execution.GetTransactionErrorMessageResponse, error)); ok { + return returnFunc(context1, getTransactionErrorMessageByIndexRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest) *execution.GetTransactionErrorMessageResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest) *execution.GetTransactionErrorMessageResponse); ok { + r0 = returnFunc(context1, getTransactionErrorMessageByIndexRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionErrorMessageResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessageByIndexRequest) error); ok { + r1 = returnFunc(context1, getTransactionErrorMessageByIndexRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionErrorMessagesByBlockID provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetTransactionErrorMessagesByBlockID(_a0 context.Context, _a1 *execution.GetTransactionErrorMessagesByBlockIDRequest) (*execution.GetTransactionErrorMessagesResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionErrorMessageByIndex' +type ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call struct { + *mock.Call +} + +// GetTransactionErrorMessageByIndex is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionErrorMessageByIndexRequest *execution.GetTransactionErrorMessageByIndexRequest +func (_e *ExecutionAPIServer_Expecter) GetTransactionErrorMessageByIndex(context1 interface{}, getTransactionErrorMessageByIndexRequest interface{}) *ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call { + return &ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call{Call: _e.mock.On("GetTransactionErrorMessageByIndex", context1, getTransactionErrorMessageByIndexRequest)} +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call) Run(run func(context1 context.Context, getTransactionErrorMessageByIndexRequest *execution.GetTransactionErrorMessageByIndexRequest)) *ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionErrorMessageByIndexRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionErrorMessageByIndexRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call) Return(getTransactionErrorMessageResponse *execution.GetTransactionErrorMessageResponse, err error) *ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call { + _c.Call.Return(getTransactionErrorMessageResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call) RunAndReturn(run func(context1 context.Context, getTransactionErrorMessageByIndexRequest *execution.GetTransactionErrorMessageByIndexRequest) (*execution.GetTransactionErrorMessageResponse, error)) *ExecutionAPIServer_GetTransactionErrorMessageByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionErrorMessagesByBlockID provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetTransactionErrorMessagesByBlockID(context1 context.Context, getTransactionErrorMessagesByBlockIDRequest *execution.GetTransactionErrorMessagesByBlockIDRequest) (*execution.GetTransactionErrorMessagesResponse, error) { + ret := _mock.Called(context1, getTransactionErrorMessagesByBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionErrorMessagesByBlockID") @@ -264,29 +592,67 @@ func (_m *ExecutionAPIServer) GetTransactionErrorMessagesByBlockID(_a0 context.C var r0 *execution.GetTransactionErrorMessagesResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest) (*execution.GetTransactionErrorMessagesResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest) (*execution.GetTransactionErrorMessagesResponse, error)); ok { + return returnFunc(context1, getTransactionErrorMessagesByBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest) *execution.GetTransactionErrorMessagesResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest) *execution.GetTransactionErrorMessagesResponse); ok { + r0 = returnFunc(context1, getTransactionErrorMessagesByBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionErrorMessagesResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionErrorMessagesByBlockIDRequest) error); ok { + r1 = returnFunc(context1, getTransactionErrorMessagesByBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionExecutionMetricsAfter provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetTransactionExecutionMetricsAfter(_a0 context.Context, _a1 *execution.GetTransactionExecutionMetricsAfterRequest) (*execution.GetTransactionExecutionMetricsAfterResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionErrorMessagesByBlockID' +type ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call struct { + *mock.Call +} + +// GetTransactionErrorMessagesByBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionErrorMessagesByBlockIDRequest *execution.GetTransactionErrorMessagesByBlockIDRequest +func (_e *ExecutionAPIServer_Expecter) GetTransactionErrorMessagesByBlockID(context1 interface{}, getTransactionErrorMessagesByBlockIDRequest interface{}) *ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call { + return &ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call{Call: _e.mock.On("GetTransactionErrorMessagesByBlockID", context1, getTransactionErrorMessagesByBlockIDRequest)} +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call) Run(run func(context1 context.Context, getTransactionErrorMessagesByBlockIDRequest *execution.GetTransactionErrorMessagesByBlockIDRequest)) *ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionErrorMessagesByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionErrorMessagesByBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call) Return(getTransactionErrorMessagesResponse *execution.GetTransactionErrorMessagesResponse, err error) *ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call { + _c.Call.Return(getTransactionErrorMessagesResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call) RunAndReturn(run func(context1 context.Context, getTransactionErrorMessagesByBlockIDRequest *execution.GetTransactionErrorMessagesByBlockIDRequest) (*execution.GetTransactionErrorMessagesResponse, error)) *ExecutionAPIServer_GetTransactionErrorMessagesByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionExecutionMetricsAfter provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetTransactionExecutionMetricsAfter(context1 context.Context, getTransactionExecutionMetricsAfterRequest *execution.GetTransactionExecutionMetricsAfterRequest) (*execution.GetTransactionExecutionMetricsAfterResponse, error) { + ret := _mock.Called(context1, getTransactionExecutionMetricsAfterRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionExecutionMetricsAfter") @@ -294,29 +660,67 @@ func (_m *ExecutionAPIServer) GetTransactionExecutionMetricsAfter(_a0 context.Co var r0 *execution.GetTransactionExecutionMetricsAfterResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest) (*execution.GetTransactionExecutionMetricsAfterResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest) (*execution.GetTransactionExecutionMetricsAfterResponse, error)); ok { + return returnFunc(context1, getTransactionExecutionMetricsAfterRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest) *execution.GetTransactionExecutionMetricsAfterResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest) *execution.GetTransactionExecutionMetricsAfterResponse); ok { + r0 = returnFunc(context1, getTransactionExecutionMetricsAfterRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionExecutionMetricsAfterResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionExecutionMetricsAfterRequest) error); ok { + r1 = returnFunc(context1, getTransactionExecutionMetricsAfterRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResult provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetTransactionResult(_a0 context.Context, _a1 *execution.GetTransactionResultRequest) (*execution.GetTransactionResultResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionExecutionMetricsAfter' +type ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call struct { + *mock.Call +} + +// GetTransactionExecutionMetricsAfter is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionExecutionMetricsAfterRequest *execution.GetTransactionExecutionMetricsAfterRequest +func (_e *ExecutionAPIServer_Expecter) GetTransactionExecutionMetricsAfter(context1 interface{}, getTransactionExecutionMetricsAfterRequest interface{}) *ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call { + return &ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call{Call: _e.mock.On("GetTransactionExecutionMetricsAfter", context1, getTransactionExecutionMetricsAfterRequest)} +} + +func (_c *ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call) Run(run func(context1 context.Context, getTransactionExecutionMetricsAfterRequest *execution.GetTransactionExecutionMetricsAfterRequest)) *ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionExecutionMetricsAfterRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionExecutionMetricsAfterRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call) Return(getTransactionExecutionMetricsAfterResponse *execution.GetTransactionExecutionMetricsAfterResponse, err error) *ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call { + _c.Call.Return(getTransactionExecutionMetricsAfterResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call) RunAndReturn(run func(context1 context.Context, getTransactionExecutionMetricsAfterRequest *execution.GetTransactionExecutionMetricsAfterRequest) (*execution.GetTransactionExecutionMetricsAfterResponse, error)) *ExecutionAPIServer_GetTransactionExecutionMetricsAfter_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResult provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetTransactionResult(context1 context.Context, getTransactionResultRequest *execution.GetTransactionResultRequest) (*execution.GetTransactionResultResponse, error) { + ret := _mock.Called(context1, getTransactionResultRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionResult") @@ -324,29 +728,67 @@ func (_m *ExecutionAPIServer) GetTransactionResult(_a0 context.Context, _a1 *exe var r0 *execution.GetTransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest) (*execution.GetTransactionResultResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest) (*execution.GetTransactionResultResponse, error)); ok { + return returnFunc(context1, getTransactionResultRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest) *execution.GetTransactionResultResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionResultRequest) *execution.GetTransactionResultResponse); ok { + r0 = returnFunc(context1, getTransactionResultRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionResultRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionResultRequest) error); ok { + r1 = returnFunc(context1, getTransactionResultRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultByIndex provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetTransactionResultByIndex(_a0 context.Context, _a1 *execution.GetTransactionByIndexRequest) (*execution.GetTransactionResultResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type ExecutionAPIServer_GetTransactionResult_Call struct { + *mock.Call +} + +// GetTransactionResult is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionResultRequest *execution.GetTransactionResultRequest +func (_e *ExecutionAPIServer_Expecter) GetTransactionResult(context1 interface{}, getTransactionResultRequest interface{}) *ExecutionAPIServer_GetTransactionResult_Call { + return &ExecutionAPIServer_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", context1, getTransactionResultRequest)} +} + +func (_c *ExecutionAPIServer_GetTransactionResult_Call) Run(run func(context1 context.Context, getTransactionResultRequest *execution.GetTransactionResultRequest)) *ExecutionAPIServer_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionResultRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionResultRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionResult_Call) Return(getTransactionResultResponse *execution.GetTransactionResultResponse, err error) *ExecutionAPIServer_GetTransactionResult_Call { + _c.Call.Return(getTransactionResultResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionResult_Call) RunAndReturn(run func(context1 context.Context, getTransactionResultRequest *execution.GetTransactionResultRequest) (*execution.GetTransactionResultResponse, error)) *ExecutionAPIServer_GetTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultByIndex provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetTransactionResultByIndex(context1 context.Context, getTransactionByIndexRequest *execution.GetTransactionByIndexRequest) (*execution.GetTransactionResultResponse, error) { + ret := _mock.Called(context1, getTransactionByIndexRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionResultByIndex") @@ -354,29 +796,67 @@ func (_m *ExecutionAPIServer) GetTransactionResultByIndex(_a0 context.Context, _ var r0 *execution.GetTransactionResultResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest) (*execution.GetTransactionResultResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest) (*execution.GetTransactionResultResponse, error)); ok { + return returnFunc(context1, getTransactionByIndexRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest) *execution.GetTransactionResultResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionByIndexRequest) *execution.GetTransactionResultResponse); ok { + r0 = returnFunc(context1, getTransactionByIndexRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionResultResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionByIndexRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionByIndexRequest) error); ok { + r1 = returnFunc(context1, getTransactionByIndexRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultsByBlockID provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) GetTransactionResultsByBlockID(_a0 context.Context, _a1 *execution.GetTransactionsByBlockIDRequest) (*execution.GetTransactionResultsResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetTransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultByIndex' +type ExecutionAPIServer_GetTransactionResultByIndex_Call struct { + *mock.Call +} + +// GetTransactionResultByIndex is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionByIndexRequest *execution.GetTransactionByIndexRequest +func (_e *ExecutionAPIServer_Expecter) GetTransactionResultByIndex(context1 interface{}, getTransactionByIndexRequest interface{}) *ExecutionAPIServer_GetTransactionResultByIndex_Call { + return &ExecutionAPIServer_GetTransactionResultByIndex_Call{Call: _e.mock.On("GetTransactionResultByIndex", context1, getTransactionByIndexRequest)} +} + +func (_c *ExecutionAPIServer_GetTransactionResultByIndex_Call) Run(run func(context1 context.Context, getTransactionByIndexRequest *execution.GetTransactionByIndexRequest)) *ExecutionAPIServer_GetTransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionByIndexRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionByIndexRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionResultByIndex_Call) Return(getTransactionResultResponse *execution.GetTransactionResultResponse, err error) *ExecutionAPIServer_GetTransactionResultByIndex_Call { + _c.Call.Return(getTransactionResultResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionResultByIndex_Call) RunAndReturn(run func(context1 context.Context, getTransactionByIndexRequest *execution.GetTransactionByIndexRequest) (*execution.GetTransactionResultResponse, error)) *ExecutionAPIServer_GetTransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultsByBlockID provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) GetTransactionResultsByBlockID(context1 context.Context, getTransactionsByBlockIDRequest *execution.GetTransactionsByBlockIDRequest) (*execution.GetTransactionResultsResponse, error) { + ret := _mock.Called(context1, getTransactionsByBlockIDRequest) if len(ret) == 0 { panic("no return value specified for GetTransactionResultsByBlockID") @@ -384,29 +864,67 @@ func (_m *ExecutionAPIServer) GetTransactionResultsByBlockID(_a0 context.Context var r0 *execution.GetTransactionResultsResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest) (*execution.GetTransactionResultsResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest) (*execution.GetTransactionResultsResponse, error)); ok { + return returnFunc(context1, getTransactionsByBlockIDRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest) *execution.GetTransactionResultsResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.GetTransactionsByBlockIDRequest) *execution.GetTransactionResultsResponse); ok { + r0 = returnFunc(context1, getTransactionsByBlockIDRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.GetTransactionResultsResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionsByBlockIDRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.GetTransactionsByBlockIDRequest) error); ok { + r1 = returnFunc(context1, getTransactionsByBlockIDRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// Ping provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionAPIServer) Ping(_a0 context.Context, _a1 *execution.PingRequest) (*execution.PingResponse, error) { - ret := _m.Called(_a0, _a1) +// ExecutionAPIServer_GetTransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultsByBlockID' +type ExecutionAPIServer_GetTransactionResultsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionResultsByBlockID is a helper method to define mock.On call +// - context1 context.Context +// - getTransactionsByBlockIDRequest *execution.GetTransactionsByBlockIDRequest +func (_e *ExecutionAPIServer_Expecter) GetTransactionResultsByBlockID(context1 interface{}, getTransactionsByBlockIDRequest interface{}) *ExecutionAPIServer_GetTransactionResultsByBlockID_Call { + return &ExecutionAPIServer_GetTransactionResultsByBlockID_Call{Call: _e.mock.On("GetTransactionResultsByBlockID", context1, getTransactionsByBlockIDRequest)} +} + +func (_c *ExecutionAPIServer_GetTransactionResultsByBlockID_Call) Run(run func(context1 context.Context, getTransactionsByBlockIDRequest *execution.GetTransactionsByBlockIDRequest)) *ExecutionAPIServer_GetTransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.GetTransactionsByBlockIDRequest + if args[1] != nil { + arg1 = args[1].(*execution.GetTransactionsByBlockIDRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionResultsByBlockID_Call) Return(getTransactionResultsResponse *execution.GetTransactionResultsResponse, err error) *ExecutionAPIServer_GetTransactionResultsByBlockID_Call { + _c.Call.Return(getTransactionResultsResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_GetTransactionResultsByBlockID_Call) RunAndReturn(run func(context1 context.Context, getTransactionsByBlockIDRequest *execution.GetTransactionsByBlockIDRequest) (*execution.GetTransactionResultsResponse, error)) *ExecutionAPIServer_GetTransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Ping provides a mock function for the type ExecutionAPIServer +func (_mock *ExecutionAPIServer) Ping(context1 context.Context, pingRequest *execution.PingRequest) (*execution.PingResponse, error) { + ret := _mock.Called(context1, pingRequest) if len(ret) == 0 { panic("no return value specified for Ping") @@ -414,36 +932,60 @@ func (_m *ExecutionAPIServer) Ping(_a0 context.Context, _a1 *execution.PingReque var r0 *execution.PingResponse var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.PingRequest) (*execution.PingResponse, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.PingRequest) (*execution.PingResponse, error)); ok { + return returnFunc(context1, pingRequest) } - if rf, ok := ret.Get(0).(func(context.Context, *execution.PingRequest) *execution.PingResponse); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.PingRequest) *execution.PingResponse); ok { + r0 = returnFunc(context1, pingRequest) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.PingResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution.PingRequest) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution.PingRequest) error); ok { + r1 = returnFunc(context1, pingRequest) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionAPIServer creates a new instance of ExecutionAPIServer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionAPIServer(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionAPIServer { - mock := &ExecutionAPIServer{} - mock.Mock.Test(t) +// ExecutionAPIServer_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping' +type ExecutionAPIServer_Ping_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Ping is a helper method to define mock.On call +// - context1 context.Context +// - pingRequest *execution.PingRequest +func (_e *ExecutionAPIServer_Expecter) Ping(context1 interface{}, pingRequest interface{}) *ExecutionAPIServer_Ping_Call { + return &ExecutionAPIServer_Ping_Call{Call: _e.mock.On("Ping", context1, pingRequest)} +} - return mock +func (_c *ExecutionAPIServer_Ping_Call) Run(run func(context1 context.Context, pingRequest *execution.PingRequest)) *ExecutionAPIServer_Ping_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.PingRequest + if args[1] != nil { + arg1 = args[1].(*execution.PingRequest) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionAPIServer_Ping_Call) Return(pingResponse *execution.PingResponse, err error) *ExecutionAPIServer_Ping_Call { + _c.Call.Return(pingResponse, err) + return _c +} + +func (_c *ExecutionAPIServer_Ping_Call) RunAndReturn(run func(context1 context.Context, pingRequest *execution.PingRequest) (*execution.PingResponse, error)) *ExecutionAPIServer_Ping_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rest/apiproxy/rest_proxy_handler.go b/engine/access/rest/apiproxy/rest_proxy_handler.go index 3b29778e0d0..5d4476188fa 100644 --- a/engine/access/rest/apiproxy/rest_proxy_handler.go +++ b/engine/access/rest/apiproxy/rest_proxy_handler.go @@ -148,6 +148,32 @@ func (r *RestProxyHandler) GetTransaction(ctx context.Context, id flow.Identifie return &transactionBody, nil } +// GetTransactionsByBlockID returns transactions by the block ID. +func (r *RestProxyHandler) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionBody, error) { + upstream, closer, err := r.FaultTolerantClient() + if err != nil { + return nil, err + } + defer closer.Close() + + getTransactionsRequest := &accessproto.GetTransactionsByBlockIDRequest{ + BlockId: blockID[:], + } + transactionsResponse, err := upstream.GetTransactionsByBlockID(ctx, getTransactionsRequest) + r.log("upstream", "GetTransactionsByBlockID", err) + + if err != nil { + return nil, err + } + + transactionBody, err := convert.MessagesToTransactions(transactionsResponse.Transactions, r.Chain) + if err != nil { + return nil, err + } + + return transactionBody, nil +} + // GetTransactionResult returns transaction result by the transaction ID. func (r *RestProxyHandler) GetTransactionResult( ctx context.Context, @@ -180,6 +206,29 @@ func (r *RestProxyHandler) GetTransactionResult( return convert.MessageToTransactionResult(transactionResultResponse) } +// GetTransactionResultsByBlockID returns transaction results by the block ID. +func (r *RestProxyHandler) GetTransactionResultsByBlockID(ctx context.Context, blockID flow.Identifier, requiredEventEncodingVersion entities.EventEncodingVersion) ([]*accessmodel.TransactionResult, error) { + upstream, closer, err := r.FaultTolerantClient() + if err != nil { + return nil, err + } + defer closer.Close() + + getTransactionResultsRequest := &accessproto.GetTransactionsByBlockIDRequest{ + BlockId: blockID[:], + EventEncodingVersion: requiredEventEncodingVersion, + } + + transactionResultsResponse, err := upstream.GetTransactionResultsByBlockID(ctx, getTransactionResultsRequest) + r.log("upstream", "GetTransactionResultsByBlockID", err) + + if err != nil { + return nil, err + } + + return convert.MessageToTransactionResults(transactionResultsResponse) +} + // GetAccountAtBlockHeight returns account by account address and block height. func (r *RestProxyHandler) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { upstream, closer, err := r.FaultTolerantClient() diff --git a/engine/access/rest/common/http_request_handler.go b/engine/access/rest/common/http_request_handler.go index fe40f2a97c0..0c77f50afda 100644 --- a/engine/access/rest/common/http_request_handler.go +++ b/engine/access/rest/common/http_request_handler.go @@ -81,25 +81,32 @@ func (h *HttpHandler) ErrorHandler(w http.ResponseWriter, err error, errorLogger // handle grpc status error returned from the backend calls, we are forwarding the message to the client if se, ok := status.FromError(err); ok { - if se.Code() == codes.NotFound { + switch se.Code() { + case codes.NotFound: msg := fmt.Sprintf("Flow resource not found: %s", se.Message()) h.errorResponse(w, http.StatusNotFound, msg, errorLogger) return - } - if se.Code() == codes.InvalidArgument { + case codes.InvalidArgument: msg := fmt.Sprintf("Invalid Flow argument: %s", se.Message()) h.errorResponse(w, http.StatusBadRequest, msg, errorLogger) return - } - if se.Code() == codes.Internal { + case codes.Internal: msg := fmt.Sprintf("Invalid Flow request: %s", se.Message()) - h.errorResponse(w, http.StatusBadRequest, msg, errorLogger) + h.errorResponse(w, http.StatusInternalServerError, msg, errorLogger) return - } - if se.Code() == codes.Unavailable { + case codes.Unavailable: msg := fmt.Sprintf("Failed to process request: %s", se.Message()) h.errorResponse(w, http.StatusServiceUnavailable, msg, errorLogger) return + case codes.FailedPrecondition: + // indicates the system wasn't in a state to handle the request, treated as a bad request. + msg := fmt.Sprintf("Precondition failed: %s", se.Message()) + h.errorResponse(w, http.StatusBadRequest, msg, errorLogger) + return + case codes.OutOfRange: + msg := fmt.Sprintf("Out of range: %s", se.Message()) + h.errorResponse(w, http.StatusBadRequest, msg, errorLogger) + return } } @@ -110,7 +117,7 @@ func (h *HttpHandler) ErrorHandler(w http.ResponseWriter, err error, errorLogger } // JsonResponse builds a JSON response and send it to the client -func (h *HttpHandler) JsonResponse(w http.ResponseWriter, code int, response interface{}, errLogger zerolog.Logger) { +func (h *HttpHandler) JsonResponse(w http.ResponseWriter, code int, response any, errLogger zerolog.Logger) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") // serialize response to JSON and handler errors diff --git a/engine/access/rest/common/middleware/logging.go b/engine/access/rest/common/middleware/logging.go index 1f03d810cf1..20121876d5c 100644 --- a/engine/access/rest/common/middleware/logging.go +++ b/engine/access/rest/common/middleware/logging.go @@ -12,24 +12,36 @@ import ( ) // LoggingMiddleware creates a middleware which adds a logger interceptor to each request to log the request method, uri, -// duration and response code +// duration and response code. Both start and finish logs are at DEBUG level. +// +// Example log messages for searching: +// - Start: DBG "started REST request" method=GET uri=/v1/blocks client_ip=... user_agent=... +// - Finish: DBG "finished REST request" method=GET uri=/v1/blocks client_ip=... user_agent=... duration=... response_code=200 func LoggingMiddleware(logger zerolog.Logger) mux.MiddlewareFunc { return func(inner http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - // record star time + lg := logger.With(). + Str("method", req.Method). + Str("uri", req.RequestURI). + Str("client_ip", req.RemoteAddr). + Str("user_agent", req.UserAgent()). + Logger() + + // Log at start of request for debugging and tracing + lg.Debug().Msg("started REST request") + + // record start time start := time.Now() // modify the writer respWriter := newResponseWriter(w) // continue to the next handler inner.ServeHTTP(respWriter, req) - log := logger.Info() - log.Str("method", req.Method). - Str("uri", req.RequestURI). - Str("client_ip", req.RemoteAddr). - Str("user_agent", req.UserAgent()). + + // Log at end of request with response details + lg.Debug(). Dur("duration", time.Since(start)). Int("response_code", respWriter.statusCode). - Msg("api") + Msg("finished REST request") }) } } diff --git a/engine/access/rest/common/middleware/request_attribute.go b/engine/access/rest/common/middleware/request_attribute.go index b1bdbb6ba1b..f012ba6706b 100644 --- a/engine/access/rest/common/middleware/request_attribute.go +++ b/engine/access/rest/common/middleware/request_attribute.go @@ -8,13 +8,13 @@ import ( type ctxKeyType string // addRequestAttribute adds the given attribute name and value to the request context -func addRequestAttribute(req *http.Request, attributeName string, attributeValue interface{}) *http.Request { +func addRequestAttribute(req *http.Request, attributeName string, attributeValue any) *http.Request { contextKey := ctxKeyType(attributeName) return req.WithContext(context.WithValue(req.Context(), contextKey, attributeValue)) } // getRequestAttribute returns the value for the given attribute name from the request context if found -func getRequestAttribute(req *http.Request, attributeName string) (interface{}, bool) { +func getRequestAttribute(req *http.Request, attributeName string) (any, bool) { contextKey := ctxKeyType(attributeName) value := req.Context().Value(contextKey) return value, value != nil diff --git a/engine/access/rest/common/models/execution_receipt.go b/engine/access/rest/common/models/execution_receipt.go new file mode 100644 index 00000000000..e52f5a718f5 --- /dev/null +++ b/engine/access/rest/common/models/execution_receipt.go @@ -0,0 +1,49 @@ +package models + +import ( + "fmt" + + "github.com/onflow/flow-go/engine/access/rest/util" + "github.com/onflow/flow-go/model/flow" +) + +const ExpandableFieldExecutionResult = "execution_result" + +// Build populates an ExecutionReceipt response model from the given domain receipt. +// If expand[ExpandableFieldExecutionResult] is true, the full execution result is inlined; +// otherwise only the link to the execution result is set in the expandable field. +// +// No error returns are expected during normal operation. +func (e *ExecutionReceipt) Build( + receipt *flow.ExecutionReceipt, + link LinkGenerator, + expand map[string]bool, +) error { + e.ExecutorId = receipt.ExecutorID.String() + e.ResultId = receipt.ExecutionResult.ID().String() + + spocks := make([]string, len(receipt.Spocks)) + for i, spock := range receipt.Spocks { + spocks[i] = util.ToBase64(spock) + } + e.Spocks = spocks + e.ExecutorSignature = util.ToBase64(receipt.ExecutorSignature) + + e.Expandable = &ExecutionReceiptExpandable{} + if expand[ExpandableFieldExecutionResult] { + var exeResult ExecutionResult + err := exeResult.Build(&receipt.ExecutionResult, link) + if err != nil { + return fmt.Errorf("failed to build execution result: %w", err) + } + e.ExecutionResult = &exeResult + } else { + resultLink, err := link.ExecutionResultLink(receipt.ExecutionResult.ID()) + if err != nil { + return fmt.Errorf("failed to build execution result link: %w", err) + } + e.Expandable.ExecutionResult = resultLink + } + + return nil +} diff --git a/engine/access/rest/common/models/mock/link_generator.go b/engine/access/rest/common/models/mock/link_generator.go index 07740cff2e0..4df4a6d6114 100644 --- a/engine/access/rest/common/models/mock/link_generator.go +++ b/engine/access/rest/common/models/mock/link_generator.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewLinkGenerator creates a new instance of LinkGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLinkGenerator(t interface { + mock.TestingT + Cleanup(func()) +}) *LinkGenerator { + mock := &LinkGenerator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LinkGenerator is an autogenerated mock type for the LinkGenerator type type LinkGenerator struct { mock.Mock } -// AccountLink provides a mock function with given fields: address -func (_m *LinkGenerator) AccountLink(address string) (string, error) { - ret := _m.Called(address) +type LinkGenerator_Expecter struct { + mock *mock.Mock +} + +func (_m *LinkGenerator) EXPECT() *LinkGenerator_Expecter { + return &LinkGenerator_Expecter{mock: &_m.Mock} +} + +// AccountLink provides a mock function for the type LinkGenerator +func (_mock *LinkGenerator) AccountLink(address string) (string, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for AccountLink") @@ -22,27 +46,59 @@ func (_m *LinkGenerator) AccountLink(address string) (string, error) { var r0 string var r1 error - if rf, ok := ret.Get(0).(func(string) (string, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(string) (string, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(string) string); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(string) string); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(string) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// BlockLink provides a mock function with given fields: id -func (_m *LinkGenerator) BlockLink(id flow.Identifier) (string, error) { - ret := _m.Called(id) +// LinkGenerator_AccountLink_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AccountLink' +type LinkGenerator_AccountLink_Call struct { + *mock.Call +} + +// AccountLink is a helper method to define mock.On call +// - address string +func (_e *LinkGenerator_Expecter) AccountLink(address interface{}) *LinkGenerator_AccountLink_Call { + return &LinkGenerator_AccountLink_Call{Call: _e.mock.On("AccountLink", address)} +} + +func (_c *LinkGenerator_AccountLink_Call) Run(run func(address string)) *LinkGenerator_AccountLink_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LinkGenerator_AccountLink_Call) Return(s string, err error) *LinkGenerator_AccountLink_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *LinkGenerator_AccountLink_Call) RunAndReturn(run func(address string) (string, error)) *LinkGenerator_AccountLink_Call { + _c.Call.Return(run) + return _c +} + +// BlockLink provides a mock function for the type LinkGenerator +func (_mock *LinkGenerator) BlockLink(id flow.Identifier) (string, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for BlockLink") @@ -50,27 +106,59 @@ func (_m *LinkGenerator) BlockLink(id flow.Identifier) (string, error) { var r0 string var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) string); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) string); ok { + r0 = returnFunc(id) } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// CollectionLink provides a mock function with given fields: id -func (_m *LinkGenerator) CollectionLink(id flow.Identifier) (string, error) { - ret := _m.Called(id) +// LinkGenerator_BlockLink_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockLink' +type LinkGenerator_BlockLink_Call struct { + *mock.Call +} + +// BlockLink is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LinkGenerator_Expecter) BlockLink(id interface{}) *LinkGenerator_BlockLink_Call { + return &LinkGenerator_BlockLink_Call{Call: _e.mock.On("BlockLink", id)} +} + +func (_c *LinkGenerator_BlockLink_Call) Run(run func(id flow.Identifier)) *LinkGenerator_BlockLink_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LinkGenerator_BlockLink_Call) Return(s string, err error) *LinkGenerator_BlockLink_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *LinkGenerator_BlockLink_Call) RunAndReturn(run func(id flow.Identifier) (string, error)) *LinkGenerator_BlockLink_Call { + _c.Call.Return(run) + return _c +} + +// CollectionLink provides a mock function for the type LinkGenerator +func (_mock *LinkGenerator) CollectionLink(id flow.Identifier) (string, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for CollectionLink") @@ -78,27 +166,59 @@ func (_m *LinkGenerator) CollectionLink(id flow.Identifier) (string, error) { var r0 string var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) string); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) string); ok { + r0 = returnFunc(id) } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecutionResultLink provides a mock function with given fields: id -func (_m *LinkGenerator) ExecutionResultLink(id flow.Identifier) (string, error) { - ret := _m.Called(id) +// LinkGenerator_CollectionLink_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CollectionLink' +type LinkGenerator_CollectionLink_Call struct { + *mock.Call +} + +// CollectionLink is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LinkGenerator_Expecter) CollectionLink(id interface{}) *LinkGenerator_CollectionLink_Call { + return &LinkGenerator_CollectionLink_Call{Call: _e.mock.On("CollectionLink", id)} +} + +func (_c *LinkGenerator_CollectionLink_Call) Run(run func(id flow.Identifier)) *LinkGenerator_CollectionLink_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LinkGenerator_CollectionLink_Call) Return(s string, err error) *LinkGenerator_CollectionLink_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *LinkGenerator_CollectionLink_Call) RunAndReturn(run func(id flow.Identifier) (string, error)) *LinkGenerator_CollectionLink_Call { + _c.Call.Return(run) + return _c +} + +// ExecutionResultLink provides a mock function for the type LinkGenerator +func (_mock *LinkGenerator) ExecutionResultLink(id flow.Identifier) (string, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ExecutionResultLink") @@ -106,27 +226,59 @@ func (_m *LinkGenerator) ExecutionResultLink(id flow.Identifier) (string, error) var r0 string var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) string); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) string); ok { + r0 = returnFunc(id) } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// PayloadLink provides a mock function with given fields: id -func (_m *LinkGenerator) PayloadLink(id flow.Identifier) (string, error) { - ret := _m.Called(id) +// LinkGenerator_ExecutionResultLink_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionResultLink' +type LinkGenerator_ExecutionResultLink_Call struct { + *mock.Call +} + +// ExecutionResultLink is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LinkGenerator_Expecter) ExecutionResultLink(id interface{}) *LinkGenerator_ExecutionResultLink_Call { + return &LinkGenerator_ExecutionResultLink_Call{Call: _e.mock.On("ExecutionResultLink", id)} +} + +func (_c *LinkGenerator_ExecutionResultLink_Call) Run(run func(id flow.Identifier)) *LinkGenerator_ExecutionResultLink_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LinkGenerator_ExecutionResultLink_Call) Return(s string, err error) *LinkGenerator_ExecutionResultLink_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *LinkGenerator_ExecutionResultLink_Call) RunAndReturn(run func(id flow.Identifier) (string, error)) *LinkGenerator_ExecutionResultLink_Call { + _c.Call.Return(run) + return _c +} + +// PayloadLink provides a mock function for the type LinkGenerator +func (_mock *LinkGenerator) PayloadLink(id flow.Identifier) (string, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for PayloadLink") @@ -134,27 +286,59 @@ func (_m *LinkGenerator) PayloadLink(id flow.Identifier) (string, error) { var r0 string var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) string); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) string); ok { + r0 = returnFunc(id) } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionLink provides a mock function with given fields: id -func (_m *LinkGenerator) TransactionLink(id flow.Identifier) (string, error) { - ret := _m.Called(id) +// LinkGenerator_PayloadLink_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PayloadLink' +type LinkGenerator_PayloadLink_Call struct { + *mock.Call +} + +// PayloadLink is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LinkGenerator_Expecter) PayloadLink(id interface{}) *LinkGenerator_PayloadLink_Call { + return &LinkGenerator_PayloadLink_Call{Call: _e.mock.On("PayloadLink", id)} +} + +func (_c *LinkGenerator_PayloadLink_Call) Run(run func(id flow.Identifier)) *LinkGenerator_PayloadLink_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LinkGenerator_PayloadLink_Call) Return(s string, err error) *LinkGenerator_PayloadLink_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *LinkGenerator_PayloadLink_Call) RunAndReturn(run func(id flow.Identifier) (string, error)) *LinkGenerator_PayloadLink_Call { + _c.Call.Return(run) + return _c +} + +// TransactionLink provides a mock function for the type LinkGenerator +func (_mock *LinkGenerator) TransactionLink(id flow.Identifier) (string, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for TransactionLink") @@ -162,27 +346,59 @@ func (_m *LinkGenerator) TransactionLink(id flow.Identifier) (string, error) { var r0 string var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) string); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) string); ok { + r0 = returnFunc(id) } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionResultLink provides a mock function with given fields: id -func (_m *LinkGenerator) TransactionResultLink(id flow.Identifier) (string, error) { - ret := _m.Called(id) +// LinkGenerator_TransactionLink_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionLink' +type LinkGenerator_TransactionLink_Call struct { + *mock.Call +} + +// TransactionLink is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LinkGenerator_Expecter) TransactionLink(id interface{}) *LinkGenerator_TransactionLink_Call { + return &LinkGenerator_TransactionLink_Call{Call: _e.mock.On("TransactionLink", id)} +} + +func (_c *LinkGenerator_TransactionLink_Call) Run(run func(id flow.Identifier)) *LinkGenerator_TransactionLink_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LinkGenerator_TransactionLink_Call) Return(s string, err error) *LinkGenerator_TransactionLink_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *LinkGenerator_TransactionLink_Call) RunAndReturn(run func(id flow.Identifier) (string, error)) *LinkGenerator_TransactionLink_Call { + _c.Call.Return(run) + return _c +} + +// TransactionResultLink provides a mock function for the type LinkGenerator +func (_mock *LinkGenerator) TransactionResultLink(id flow.Identifier) (string, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for TransactionResultLink") @@ -190,34 +406,52 @@ func (_m *LinkGenerator) TransactionResultLink(id flow.Identifier) (string, erro var r0 string var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (string, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) string); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) string); ok { + r0 = returnFunc(id) } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewLinkGenerator creates a new instance of LinkGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLinkGenerator(t interface { - mock.TestingT - Cleanup(func()) -}) *LinkGenerator { - mock := &LinkGenerator{} - mock.Mock.Test(t) +// LinkGenerator_TransactionResultLink_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionResultLink' +type LinkGenerator_TransactionResultLink_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TransactionResultLink is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LinkGenerator_Expecter) TransactionResultLink(id interface{}) *LinkGenerator_TransactionResultLink_Call { + return &LinkGenerator_TransactionResultLink_Call{Call: _e.mock.On("TransactionResultLink", id)} +} - return mock +func (_c *LinkGenerator_TransactionResultLink_Call) Run(run func(id flow.Identifier)) *LinkGenerator_TransactionResultLink_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LinkGenerator_TransactionResultLink_Call) Return(s string, err error) *LinkGenerator_TransactionResultLink_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *LinkGenerator_TransactionResultLink_Call) RunAndReturn(run func(id flow.Identifier) (string, error)) *LinkGenerator_TransactionResultLink_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rest/common/models/model_execution_receipt.go b/engine/access/rest/common/models/model_execution_receipt.go new file mode 100644 index 00000000000..d35e31ad110 --- /dev/null +++ b/engine/access/rest/common/models/model_execution_receipt.go @@ -0,0 +1,18 @@ +/* + * Access API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type ExecutionReceipt struct { + ExecutorId string `json:"executor_id"` + ResultId string `json:"result_id"` + Spocks []string `json:"spocks,omitempty"` + ExecutorSignature string `json:"executor_signature"` + ExecutionResult *ExecutionResult `json:"execution_result,omitempty"` + Expandable *ExecutionReceiptExpandable `json:"_expandable"` +} diff --git a/engine/access/rest/common/models/model_execution_receipt__expandable.go b/engine/access/rest/common/models/model_execution_receipt__expandable.go new file mode 100644 index 00000000000..ea850d9e097 --- /dev/null +++ b/engine/access/rest/common/models/model_execution_receipt__expandable.go @@ -0,0 +1,13 @@ +/* + * Access API + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: 1.0.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type ExecutionReceiptExpandable struct { + ExecutionResult string `json:"execution_result,omitempty"` +} diff --git a/engine/access/rest/common/models/transaction.go b/engine/access/rest/common/models/transaction.go index 89f7e85ef42..6366dc97dd7 100644 --- a/engine/access/rest/common/models/transaction.go +++ b/engine/access/rest/common/models/transaction.go @@ -107,7 +107,7 @@ func (t *TransactionResult) Build(txr *accessmodel.TransactionResult, txID flow. t.Execution = &execution t.StatusCode = int32(txr.StatusCode) t.ErrorMessage = txr.ErrorMessage - t.ComputationUsed = util.FromUint(uint64(0)) // todo: define this + t.ComputationUsed = util.FromUint(txr.ComputationUsed) t.Events = events self, _ := SelfLink(txID, link.TransactionResultLink) diff --git a/engine/access/rest/common/parser/address.go b/engine/access/rest/common/parser/address.go index a2db50c4427..123e31627b2 100644 --- a/engine/access/rest/common/parser/address.go +++ b/engine/access/rest/common/parser/address.go @@ -10,7 +10,7 @@ import ( ) func ParseAddress(raw string, chain flow.Chain) (flow.Address, error) { - raw = strings.ReplaceAll(raw, "0x", "") // remove 0x prefix + raw = strings.TrimPrefix(raw, "0x") // remove 0x prefix valid, _ := regexp.MatchString(`^[0-9a-fA-F]{16}$`, raw) if !valid { diff --git a/engine/access/rest/common/parser/address_test.go b/engine/access/rest/common/parser/address_test.go index 95cc90dbdf0..14371aca283 100644 --- a/engine/access/rest/common/parser/address_test.go +++ b/engine/access/rest/common/parser/address_test.go @@ -19,6 +19,7 @@ func TestAddress_InvalidParse(t *testing.T) { "foo", "1", "@", + "0x0x0b807ae5da6210df", "ead892083b3e2c61222", // too long } diff --git a/engine/access/rest/common/utils.go b/engine/access/rest/common/utils.go index 6141c373433..6f813a677e6 100644 --- a/engine/access/rest/common/utils.go +++ b/engine/access/rest/common/utils.go @@ -20,7 +20,7 @@ func SliceToMap(values []string) map[string]bool { // ParseBody parses the input data into the destination interface and returns any decoding errors // updated to be more user-friendly. It also checks that there is exactly one json object in the input -func ParseBody(raw io.Reader, dst interface{}) error { +func ParseBody(raw io.Reader, dst any) error { dec := json.NewDecoder(raw) dec.DisallowUnknownFields() @@ -62,12 +62,12 @@ func ParseBody(raw io.Reader, dst interface{}) error { // ConvertInterfaceToArrayOfStrings converts a slice of interface{} to a slice of strings. // // No errors are expected during normal operations. -func ConvertInterfaceToArrayOfStrings(value interface{}) ([]string, error) { +func ConvertInterfaceToArrayOfStrings(value any) ([]string, error) { if strSlice, ok := value.([]string); ok { return strSlice, nil } - interfaceSlice, ok := value.([]interface{}) + interfaceSlice, ok := value.([]any) if !ok { return nil, fmt.Errorf("value must be an array. got %T", value) } diff --git a/engine/access/rest/common/utils_test.go b/engine/access/rest/common/utils_test.go index 326e24f4d37..abb77941620 100644 --- a/engine/access/rest/common/utils_test.go +++ b/engine/access/rest/common/utils_test.go @@ -26,7 +26,7 @@ func Test_ParseBody(t *testing.T) { for i, test := range invalid { readerIn := strings.NewReader(test.in) - var out interface{} + var out any err := ParseBody(readerIn, out) assert.EqualError(t, err, test.err, fmt.Sprintf("test #%d failed", i)) } @@ -50,7 +50,7 @@ func Test_ParseBody(t *testing.T) { func TestConvertInterfaceToArrayOfStrings(t *testing.T) { tests := []struct { name string - input interface{} + input any expect []string expectErr bool }{ @@ -62,25 +62,25 @@ func TestConvertInterfaceToArrayOfStrings(t *testing.T) { }, { name: "Valid slice of interfaces containing strings", - input: []interface{}{"a", "b", "c"}, + input: []any{"a", "b", "c"}, expect: []string{"a", "b", "c"}, expectErr: false, }, { name: "Empty slice", - input: []interface{}{}, + input: []any{}, expect: []string{}, expectErr: false, }, { name: "Array contains nil value", - input: []interface{}{"a", nil, "c"}, + input: []any{"a", nil, "c"}, expect: nil, expectErr: true, }, { name: "Mixed types in slice", - input: []interface{}{"a", 123, "c"}, + input: []any{"a", 123, "c"}, expect: nil, expectErr: true, }, @@ -98,13 +98,13 @@ func TestConvertInterfaceToArrayOfStrings(t *testing.T) { }, { name: "Slice with non-string interface values", - input: []interface{}{true, false}, + input: []any{true, false}, expect: nil, expectErr: true, }, { name: "Slice with nested slices", - input: []interface{}{[]string{"a"}}, + input: []any{[]string{"a"}}, expect: nil, expectErr: true, }, diff --git a/engine/access/rest/experimental/README.md b/engine/access/rest/experimental/README.md new file mode 100644 index 00000000000..bfd0122a1f2 --- /dev/null +++ b/engine/access/rest/experimental/README.md @@ -0,0 +1,3 @@ +# Experimental API + +The OpenAPI spec for this api can be found at https://github.com/onflow/flow/blob/cf44613233910eade91759399f94fadfccd37b72/openapi/experimental/openapi.yaml diff --git a/engine/access/rest/experimental/get_account_transactions.go b/engine/access/rest/experimental/get_account_transactions.go new file mode 100644 index 00000000000..48cc9e1f05d --- /dev/null +++ b/engine/access/rest/experimental/get_account_transactions.go @@ -0,0 +1,158 @@ +package experimental + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + "github.com/onflow/flow-go/engine/access/rest/common/parser" + accessmodel "github.com/onflow/flow-go/model/access" +) + +// AccountTransactionsResponse is the JSON response for the GetAccountTransactions endpoint. +type AccountTransactionsResponse struct { + Transactions []AccountTransactionResponse `json:"transactions"` + NextCursor string `json:"next_cursor,omitempty"` +} + +// AccountTransactionResponse is a single transaction entry in the response. +type AccountTransactionResponse struct { + BlockHeight string `json:"block_height"` + BlockTimestamp string `json:"timestamp"` + TransactionID string `json:"transaction_id"` + TransactionIndex string `json:"transaction_index"` + Roles []string `json:"roles,omitempty"` + Transaction *commonmodels.Transaction `json:"transaction,omitempty"` + Result *commonmodels.TransactionResult `json:"result,omitempty"` +} + +type AccountTransactionFilter struct { + Roles []string `json:"roles,omitempty"` +} + +// GetAccountTransactions returns a paginated list of transactions for the given account address. +func GetAccountTransactions(r *common.Request, backend extended.API, link commonmodels.LinkGenerator) (interface{}, error) { + address, err := parser.ParseAddress(r.GetVar("address"), r.Chain) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + var limit uint32 + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return nil, common.NewBadRequestError(fmt.Errorf("invalid limit: %w", err)) + } + limit = uint32(parsed) + } + + var cursor *accessmodel.AccountTransactionCursor + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := parseCursor(raw) + if err != nil { + return nil, common.NewBadRequestError(err) + } + if c.BlockHeight != 0 || c.TransactionIndex != 0 { + cursor = c + } + } + + var filter extended.AccountTransactionFilter + if raw := r.GetQueryParam("roles"); raw != "" { + roles := strings.Split(raw, ",") + for _, role := range roles { + parsed, err := accessmodel.ParseTransactionRole(strings.TrimSpace(role)) + if err != nil { + return nil, common.NewBadRequestError(fmt.Errorf("invalid role: %w", err)) + } + filter.Roles = append(filter.Roles, parsed) + } + } + + expandOptions := extended.AccountTransactionExpandOptions{ + Transaction: r.Expands("transaction"), + Result: r.Expands("result"), + } + + page, err := backend.GetAccountTransactions(r.Context(), address, limit, cursor, filter, expandOptions, entities.EventEncodingVersion_JSON_CDC_V0) + if err != nil { + return nil, err + } + + resp := AccountTransactionsResponse{ + Transactions: make([]AccountTransactionResponse, len(page.Transactions)), + } + for i, tx := range page.Transactions { + roles := make([]string, len(tx.Roles)) + for j, role := range tx.Roles { + roles[j] = role.String() + } + var transaction *commonmodels.Transaction + if r.Expands("transaction") && tx.Transaction != nil { + transaction = new(commonmodels.Transaction) + transaction.Build(tx.Transaction, nil, link) + } + var result *commonmodels.TransactionResult + if r.Expands("result") && tx.Result != nil { + result = new(commonmodels.TransactionResult) + result.Build(tx.Result, tx.TransactionID, link) + } + resp.Transactions[i] = AccountTransactionResponse{ + BlockHeight: strconv.FormatUint(tx.BlockHeight, 10), + BlockTimestamp: time.UnixMilli(int64(tx.BlockTimestamp)).UTC().Format(time.RFC3339Nano), + TransactionID: tx.TransactionID.String(), + TransactionIndex: strconv.FormatUint(uint64(tx.TransactionIndex), 10), + Roles: roles, + Transaction: transaction, + Result: result, + } + } + if page.NextCursor != nil { + resp.NextCursor = encodeCursor(page.NextCursor) + } + + return resp, nil +} + +// accountTransactionCursor is the JSON representation of a pagination cursor. +// Encoded as base64 in query params and responses to keep the format opaque to clients. +type accountTransactionCursor struct { + BlockHeight uint64 `json:"h"` + TransactionIndex uint32 `json:"i"` +} + +// parseCursor decodes a base64-encoded JSON cursor string. +func parseCursor(raw string) (*accessmodel.AccountTransactionCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, fmt.Errorf("invalid cursor encoding: %w", err) + } + + var c accountTransactionCursor + if err := json.Unmarshal(data, &c); err != nil { + return nil, fmt.Errorf("invalid cursor format: %w", err) + } + + return &accessmodel.AccountTransactionCursor{ + BlockHeight: c.BlockHeight, + TransactionIndex: c.TransactionIndex, + }, nil +} + +// encodeCursor encodes a cursor as base64-encoded JSON. +func encodeCursor(cursor *accessmodel.AccountTransactionCursor) string { + c := accountTransactionCursor{ + BlockHeight: cursor.BlockHeight, + TransactionIndex: cursor.TransactionIndex, + } + data, _ := json.Marshal(c) // accountTransactionCursor marshaling cannot fail + return base64.RawURLEncoding.EncodeToString(data) +} diff --git a/engine/access/rest/experimental/handler.go b/engine/access/rest/experimental/handler.go new file mode 100644 index 00000000000..d8781be8219 --- /dev/null +++ b/engine/access/rest/experimental/handler.go @@ -0,0 +1,61 @@ +package experimental + +import ( + "net/http" + + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/experimental/models" + "github.com/onflow/flow-go/model/flow" +) + +// ApiHandlerFunc is the handler function signature for experimental API endpoints. +// It uses extended.API as the backend instead of access.API. +type ApiHandlerFunc func(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) + +// Handler wraps an ApiHandlerFunc with common HTTP handling (error handling, JSON responses). +type Handler struct { + *common.HttpHandler + backend extended.API + linkGenerator models.LinkGenerator + apiHandlerFunc ApiHandlerFunc +} + +// NewHandler creates a new experimental Handler. +func NewHandler( + logger zerolog.Logger, + backend extended.API, + handlerFunc ApiHandlerFunc, + linkGenerator models.LinkGenerator, + chain flow.Chain, + maxRequestSize int64, + maxResponseSize int64, +) *Handler { + return &Handler{ + backend: backend, + linkGenerator: linkGenerator, + apiHandlerFunc: handlerFunc, + HttpHandler: common.NewHttpHandler(logger, chain, maxRequestSize, maxResponseSize), + } +} + +// ServeHTTP handles the request: verify, decorate, execute handler, write JSON response. +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + errLog := h.Logger.With().Str("request_url", r.URL.String()).Logger() + + err := h.VerifyRequest(w, r) + if err != nil { + return + } + decoratedRequest := common.Decorate(r, h.Chain) + + response, err := h.apiHandlerFunc(decoratedRequest, h.backend, h.linkGenerator) + if err != nil { + h.ErrorHandler(w, err, errLog) + return + } + + h.JsonResponse(w, http.StatusOK, response, errLog) +} diff --git a/engine/access/rest/experimental/models/account_transaction.go b/engine/access/rest/experimental/models/account_transaction.go new file mode 100644 index 00000000000..3f8df02a7f8 --- /dev/null +++ b/engine/access/rest/experimental/models/account_transaction.go @@ -0,0 +1,62 @@ +package models + +import ( + "fmt" + "strconv" + "time" + + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// addressHex returns the hex representation of addr, or an empty string if addr +// is the zero address (flow.EmptyAddress), which indicates a mint or burn. +func addressHex(addr flow.Address) string { + if addr == flow.EmptyAddress { + return "" + } + return addr.Hex() +} + +// Build populates the AccountTransaction from a domain model. +func (t *AccountTransaction) Build( + tx *accessmodel.AccountTransaction, + link LinkGenerator, +) error { + roles := make([]string, len(tx.Roles)) + for i, role := range tx.Roles { + roles[i] = role.String() + } + + t.BlockHeight = strconv.FormatUint(tx.BlockHeight, 10) + t.Timestamp = time.UnixMilli(int64(tx.BlockTimestamp)).UTC().Format(time.RFC3339Nano) + t.TransactionId = tx.TransactionID.String() + t.TransactionIndex = strconv.FormatUint(uint64(tx.TransactionIndex), 10) + t.Roles = roles + t.Expandable = new(AccountTransactionExpandable) + + if tx.Transaction != nil { + t.Transaction = new(commonmodels.Transaction) + t.Transaction.Build(tx.Transaction, nil, link) + } else { + transactionLink, err := link.TransactionLink(tx.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate transaction link: %w", err) + } + t.Expandable.Transaction = transactionLink + } + + if tx.Result != nil { + t.Result = new(commonmodels.TransactionResult) + t.Result.Build(tx.Result, tx.TransactionID, link) + } else { + resultLink, err := link.TransactionResultLink(tx.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate result link: %w", err) + } + t.Expandable.Result = resultLink + } + + return nil +} diff --git a/engine/access/rest/experimental/models/contract_deployment.go b/engine/access/rest/experimental/models/contract_deployment.go new file mode 100644 index 00000000000..f795dff35f4 --- /dev/null +++ b/engine/access/rest/experimental/models/contract_deployment.go @@ -0,0 +1,61 @@ +package models + +import ( + "encoding/base64" + "encoding/hex" + "fmt" + "strconv" + + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + accessmodel "github.com/onflow/flow-go/model/access" +) + +// Build populates the REST model from the domain model. +func (m *ContractDeployment) Build(d *accessmodel.ContractDeployment, link LinkGenerator, expand map[string]bool) error { + m.ContractId = accessmodel.ContractID(d.Address, d.ContractName) + m.Address = d.Address.Hex() + m.BlockHeight = strconv.FormatUint(d.BlockHeight, 10) + m.TransactionId = d.TransactionID.String() + m.TxIndex = strconv.FormatUint(uint64(d.TransactionIndex), 10) + m.EventIndex = strconv.FormatUint(uint64(d.EventIndex), 10) + m.CodeHash = hex.EncodeToString(d.CodeHash) + m.IsPlaceholder = d.IsPlaceholder + + m.Expandable = new(ContractDeploymentExpandable) + + if expand["code"] { + if len(d.Code) > 0 { + m.Code = base64.StdEncoding.EncodeToString(d.Code) + } + } else { + codeLink, err := link.ContractCodeLink(m.ContractId) + if err != nil { + return fmt.Errorf("failed to generate code link: %w", err) + } + m.Expandable.Code = codeLink + } + + if d.Transaction != nil { + m.Transaction = new(commonmodels.Transaction) + m.Transaction.Build(d.Transaction, nil, link) + } else if !d.IsPlaceholder { + transactionLink, err := link.TransactionLink(d.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate transaction link: %w", err) + } + m.Expandable.Transaction = transactionLink + } + + if d.Result != nil { + m.Result = new(commonmodels.TransactionResult) + m.Result.Build(d.Result, d.TransactionID, link) + } else if !d.IsPlaceholder { + resultLink, err := link.TransactionResultLink(d.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate result link: %w", err) + } + m.Expandable.Result = resultLink + } + + return nil +} diff --git a/engine/access/rest/experimental/models/fungible_token_transfer.go b/engine/access/rest/experimental/models/fungible_token_transfer.go new file mode 100644 index 00000000000..13f574f24f1 --- /dev/null +++ b/engine/access/rest/experimental/models/fungible_token_transfer.go @@ -0,0 +1,56 @@ +package models + +import ( + "fmt" + "strconv" + "time" + + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + accessmodel "github.com/onflow/flow-go/model/access" +) + +// Build populates the FungibleTokenTransfer from a domain model. +func (t *FungibleTokenTransfer) Build( + transfer *accessmodel.FungibleTokenTransfer, + link LinkGenerator, +) error { + eventIndices := make([]string, len(transfer.EventIndices)) + for i, idx := range transfer.EventIndices { + eventIndices[i] = strconv.FormatUint(uint64(idx), 10) + } + + t.BlockHeight = strconv.FormatUint(transfer.BlockHeight, 10) + t.BlockTimestamp = time.UnixMilli(int64(transfer.BlockTimestamp)).UTC().Format(time.RFC3339Nano) + t.TransactionId = transfer.TransactionID.String() + t.TransactionIndex = strconv.FormatUint(uint64(transfer.TransactionIndex), 10) + t.EventIndices = eventIndices + t.TokenType = transfer.TokenType + t.Amount = transfer.Amount.String() + t.SourceAddress = addressHex(transfer.SourceAddress) + t.RecipientAddress = addressHex(transfer.RecipientAddress) + t.Expandable = new(AccountTransactionExpandable) + + if transfer.Transaction != nil { + t.Transaction = new(commonmodels.Transaction) + t.Transaction.Build(transfer.Transaction, nil, link) + } else { + transactionLink, err := link.TransactionLink(transfer.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate transaction link: %w", err) + } + t.Expandable.Transaction = transactionLink + } + + if transfer.Result != nil { + t.Result = new(commonmodels.TransactionResult) + t.Result.Build(transfer.Result, transfer.TransactionID, link) + } else { + resultLink, err := link.TransactionResultLink(transfer.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate result link: %w", err) + } + t.Expandable.Result = resultLink + } + + return nil +} diff --git a/engine/access/rest/experimental/models/link.go b/engine/access/rest/experimental/models/link.go new file mode 100644 index 00000000000..f2f67ae0ebe --- /dev/null +++ b/engine/access/rest/experimental/models/link.go @@ -0,0 +1,51 @@ +package models + +import ( + "github.com/gorilla/mux" + + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" +) + +// LinkGenerator generates the expandable value for the known endpoints +// e.g. "/v1/blocks/c5e935bc75163db82e4a6cf9dc3b54656709d3e21c87385138300abd479c33b7" +type LinkGenerator interface { + commonmodels.LinkGenerator + + ContractLink(identifier string) (string, error) + ContractCodeLink(identifier string) (string, error) +} + +type LinkGeneratorImpl struct { + commonmodels.LinkGenerator + router *mux.Router +} + +func NewLinkGeneratorImpl(router *mux.Router, baseGenerator commonmodels.LinkGenerator) *LinkGeneratorImpl { + return &LinkGeneratorImpl{ + LinkGenerator: baseGenerator, + router: router, + } +} + +func (generator *LinkGeneratorImpl) ContractLink(identifier string) (string, error) { + return generator.link("getContract", "identifier", identifier) +} + +func (generator *LinkGeneratorImpl) ContractCodeLink(identifier string) (string, error) { + u, err := generator.router.Get("getContract").URLPath("identifier", identifier) + if err != nil { + return "", err + } + q := u.Query() + q.Set("expand", "code") + u.RawQuery = q.Encode() + return u.String(), nil +} + +func (generator *LinkGeneratorImpl) link(route string, key string, value string) (string, error) { + url, err := generator.router.Get(route).URLPath(key, value) + if err != nil { + return "", err + } + return url.String(), nil +} diff --git a/engine/access/rest/experimental/models/model_account_fungible_transfers_response.go b/engine/access/rest/experimental/models/model_account_fungible_transfers_response.go new file mode 100644 index 00000000000..835bbe67580 --- /dev/null +++ b/engine/access/rest/experimental/models/model_account_fungible_transfers_response.go @@ -0,0 +1,14 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type AccountFungibleTransfersResponse struct { + Transfers []FungibleTokenTransfer `json:"transfers"` + NextCursor string `json:"next_cursor,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_account_non_fungible_transfers_response.go b/engine/access/rest/experimental/models/model_account_non_fungible_transfers_response.go new file mode 100644 index 00000000000..16325b62bb7 --- /dev/null +++ b/engine/access/rest/experimental/models/model_account_non_fungible_transfers_response.go @@ -0,0 +1,14 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type AccountNonFungibleTransfersResponse struct { + Transfers []NonFungibleTokenTransfer `json:"transfers"` + NextCursor string `json:"next_cursor,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_account_transaction.go b/engine/access/rest/experimental/models/model_account_transaction.go new file mode 100644 index 00000000000..ade01001c97 --- /dev/null +++ b/engine/access/rest/experimental/models/model_account_transaction.go @@ -0,0 +1,26 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +import commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + +type AccountTransaction struct { + // Block height where the transaction was included. + BlockHeight string `json:"block_height"` + // Block timestamp where the transaction was included, in RFC3339Nano format. + Timestamp string `json:"timestamp"` + TransactionId string `json:"transaction_id"` + // Index of the transaction within the block. + TransactionIndex string `json:"transaction_index"` + Roles []string `json:"roles"` + Transaction *commonmodels.Transaction `json:"transaction,omitempty"` + Result *commonmodels.TransactionResult `json:"result,omitempty"` + Expandable *AccountTransactionExpandable `json:"_expandable"` + Links *commonmodels.Links `json:"_links,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_account_transaction__expandable.go b/engine/access/rest/experimental/models/model_account_transaction__expandable.go new file mode 100644 index 00000000000..1fd15067d9f --- /dev/null +++ b/engine/access/rest/experimental/models/model_account_transaction__expandable.go @@ -0,0 +1,17 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +// Contains URI links for fields not included in the response. When a field is expanded via the `expand` query parameter, it appears inline and is removed from `_expandable`. +type AccountTransactionExpandable struct { + // Link to fetch the full transaction body. + Transaction string `json:"transaction,omitempty"` + // Link to fetch the transaction result. + Result string `json:"result,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_account_transactions_response.go b/engine/access/rest/experimental/models/model_account_transactions_response.go new file mode 100644 index 00000000000..73d6aaaec66 --- /dev/null +++ b/engine/access/rest/experimental/models/model_account_transactions_response.go @@ -0,0 +1,14 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type AccountTransactionsResponse struct { + Transactions []AccountTransaction `json:"transactions"` + NextCursor string `json:"next_cursor,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_contract_deployment.go b/engine/access/rest/experimental/models/model_contract_deployment.go new file mode 100644 index 00000000000..68989d6e558 --- /dev/null +++ b/engine/access/rest/experimental/models/model_contract_deployment.go @@ -0,0 +1,33 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +import commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + +type ContractDeployment struct { + ContractId string `json:"contract_id"` + Address string `json:"address"` + // Block height at which this deployment was applied. + BlockHeight string `json:"block_height,omitempty"` + TransactionId string `json:"transaction_id,omitempty"` + // Position of the deploying transaction within its block. + TxIndex string `json:"tx_index,omitempty"` + // Position of the contract event within its transaction. + EventIndex string `json:"event_index,omitempty"` + // Base64-encoded Cadence source code of the contract deployed. + Code string `json:"code,omitempty"` + // Hex-encoded SHA3-256 hash of the contract code. + CodeHash string `json:"code_hash"` + // True if the deployment was created during bootstrapping based on the current chain state, not based on a protocol event. When true, block_height, transaction_id, tx_index, and event_index are absent. + IsPlaceholder bool `json:"is_placeholder,omitempty"` + Transaction *commonmodels.Transaction `json:"transaction,omitempty"` + Result *commonmodels.TransactionResult `json:"result,omitempty"` + Expandable *ContractDeploymentExpandable `json:"_expandable"` + Links *commonmodels.Links `json:"_links,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_contract_deployment__expandable.go b/engine/access/rest/experimental/models/model_contract_deployment__expandable.go new file mode 100644 index 00000000000..9b234a5fae4 --- /dev/null +++ b/engine/access/rest/experimental/models/model_contract_deployment__expandable.go @@ -0,0 +1,19 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +// Contains URI links for fields not included in the response. When a field is expanded via the `expand` query parameter, it appears inline and is removed from `_expandable`. +type ContractDeploymentExpandable struct { + // Link to fetch the Cadence source code of this deployment. + Code string `json:"code,omitempty"` + // Link to fetch the full transaction that applied this deployment. + Transaction string `json:"transaction,omitempty"` + // Link to fetch the transaction result. + Result string `json:"result,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_contract_deployments_response.go b/engine/access/rest/experimental/models/model_contract_deployments_response.go new file mode 100644 index 00000000000..3f9d6412293 --- /dev/null +++ b/engine/access/rest/experimental/models/model_contract_deployments_response.go @@ -0,0 +1,14 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type ContractDeploymentsResponse struct { + Deployments []ContractDeployment `json:"deployments"` + NextCursor string `json:"next_cursor,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_contracts_response.go b/engine/access/rest/experimental/models/model_contracts_response.go new file mode 100644 index 00000000000..b2a77de5af7 --- /dev/null +++ b/engine/access/rest/experimental/models/model_contracts_response.go @@ -0,0 +1,14 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type ContractsResponse struct { + Contracts []ContractDeployment `json:"contracts"` + NextCursor string `json:"next_cursor,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_fungible_token_transfer.go b/engine/access/rest/experimental/models/model_fungible_token_transfer.go new file mode 100644 index 00000000000..372a30cb837 --- /dev/null +++ b/engine/access/rest/experimental/models/model_fungible_token_transfer.go @@ -0,0 +1,34 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +import commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + +type FungibleTokenTransfer struct { + TransactionId string `json:"transaction_id"` + // Block height where the transfer was included. + BlockHeight string `json:"block_height"` + // Block timestamp where the transfer was included, in RFC3339Nano format. + BlockTimestamp string `json:"timestamp"` + // Index of the transaction within the block. + TransactionIndex string `json:"transaction_index"` + // Indices of the events within the transaction that represent this transfer. + EventIndices []string `json:"event_indices"` + // Fully qualified token type identifier (e.g. `A.1654653399040a61.FlowToken`). + TokenType string `json:"token_type"` + // Amount of tokens transferred, as a decimal string. + Amount string `json:"amount"` + SourceAddress string `json:"source_address"` + RecipientAddress string `json:"recipient_address"` + Transaction *commonmodels.Transaction `json:"transaction,omitempty"` + Result *commonmodels.TransactionResult `json:"result,omitempty"` + Events []commonmodels.Event `json:"events,omitempty"` + Expandable *AccountTransactionExpandable `json:"_expandable"` + Links *commonmodels.Links `json:"_links,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_non_fungible_token_transfer.go b/engine/access/rest/experimental/models/model_non_fungible_token_transfer.go new file mode 100644 index 00000000000..c777045904e --- /dev/null +++ b/engine/access/rest/experimental/models/model_non_fungible_token_transfer.go @@ -0,0 +1,34 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +import commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + +type NonFungibleTokenTransfer struct { + TransactionId string `json:"transaction_id"` + // Block height where the transfer was included. + BlockHeight string `json:"block_height"` + // Block timestamp where the transfer was included, in RFC3339Nano format. + BlockTimestamp string `json:"timestamp"` + // Index of the transaction within the block. + TransactionIndex string `json:"transaction_index"` + // Indices of the events within the transaction that represent this transfer. + EventIndices []string `json:"event_indices"` + // Fully qualified NFT collection type (e.g. `A.1654653399040a61.MyNFT`). + TokenType string `json:"token_type"` + // Unique identifier of the NFT within its collection. + NftId string `json:"nft_id"` + SourceAddress string `json:"source_address"` + RecipientAddress string `json:"recipient_address"` + Transaction *commonmodels.Transaction `json:"transaction,omitempty"` + Result *commonmodels.TransactionResult `json:"result,omitempty"` + Events []commonmodels.Event `json:"events,omitempty"` + Expandable *AccountTransactionExpandable `json:"_expandable"` + Links *commonmodels.Links `json:"_links,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_scheduled_transaction.go b/engine/access/rest/experimental/models/model_scheduled_transaction.go new file mode 100644 index 00000000000..bb60f88409c --- /dev/null +++ b/engine/access/rest/experimental/models/model_scheduled_transaction.go @@ -0,0 +1,49 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +import commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + +type ScheduledTransaction struct { + // Scheduler-assigned uint64 identifier. + Id string `json:"id"` + Status *ScheduledTransactionStatus `json:"status"` + Priority *ScheduledTransactionPriority `json:"priority"` + // Scheduled execution timestamp as a UFix64 decimal string. + Timestamp string `json:"timestamp"` + // Execution effort estimate as a UFix64 decimal string. + ExecutionEffort string `json:"execution_effort"` + // Scheduled fee as a UFix64 decimal string. + Fees string `json:"fees"` + TransactionHandlerOwner string `json:"transaction_handler_owner"` + // Fully qualified Cadence type identifier of the transaction handler (e.g. `A.1654653399040a61.MyScheduler.Handler`). + TransactionHandlerTypeIdentifier string `json:"transaction_handler_type_identifier"` + // Resource UUID of the transaction handler. + TransactionHandlerUuid string `json:"transaction_handler_uuid"` + // Public path of the transaction handler, if set. + TransactionHandlerPublicPath string `json:"transaction_handler_public_path,omitempty"` + // Fees returned on cancellation, as a UFix64 decimal string. + FeesReturned string `json:"fees_returned,omitempty"` + // Fees deducted on cancellation, as a UFix64 decimal string. + FeesDeducted string `json:"fees_deducted,omitempty"` + CreatedTransactionId string `json:"created_transaction_id"` + ExecutedTransactionId string `json:"executed_transaction_id,omitempty"` + CancelledTransactionId string `json:"cancelled_transaction_id,omitempty"` + // RFC3339Nano timestamp of the block in which the scheduled transaction was created. Absent for placeholder transactions. + CreatedAt string `json:"created_at,omitempty"` + // RFC3339Nano timestamp of the block in which the scheduled transaction was executed or cancelled. Absent when still scheduled. + CompletedAt string `json:"completed_at,omitempty"` + // True if the scheduled transaction was created during bootstrapping based on the current chain state, not based on a protocol event. When true, block_height, transaction_id, tx_index, and event_index are absent. + IsPlaceholder bool `json:"is_placeholder,omitempty"` + Transaction *commonmodels.Transaction `json:"transaction,omitempty"` + Result *commonmodels.TransactionResult `json:"result,omitempty"` + HandlerContract *ContractDeployment `json:"handler_contract,omitempty"` + Expandable *ScheduledTransactionExpandable `json:"_expandable"` + Links *commonmodels.Links `json:"_links,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_scheduled_transaction__expandable.go b/engine/access/rest/experimental/models/model_scheduled_transaction__expandable.go new file mode 100644 index 00000000000..d1a34be9e8a --- /dev/null +++ b/engine/access/rest/experimental/models/model_scheduled_transaction__expandable.go @@ -0,0 +1,19 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +// Contains URI links for fields not included in the response. When a field is expanded via the `expand` query parameter, it appears inline and is removed from `_expandable`. +type ScheduledTransactionExpandable struct { + // Link to fetch the full transaction body. + Transaction string `json:"transaction,omitempty"` + // Link to fetch the transaction result. + Result string `json:"result,omitempty"` + // Link to fetch the Cadence contract that implements the transaction handler. + HandlerContract string `json:"handler_contract,omitempty"` +} diff --git a/engine/access/rest/experimental/models/model_scheduled_transaction_priority.go b/engine/access/rest/experimental/models/model_scheduled_transaction_priority.go new file mode 100644 index 00000000000..59f083070a3 --- /dev/null +++ b/engine/access/rest/experimental/models/model_scheduled_transaction_priority.go @@ -0,0 +1,19 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +// ScheduledTransactionPriority : The execution priority of a scheduled transaction. +type ScheduledTransactionPriority string + +// List of ScheduledTransactionPriority +const ( + LOW_ScheduledTransactionPriority ScheduledTransactionPriority = "low" + MEDIUM_ScheduledTransactionPriority ScheduledTransactionPriority = "medium" + HIGH_ScheduledTransactionPriority ScheduledTransactionPriority = "high" +) diff --git a/engine/access/rest/experimental/models/model_scheduled_transaction_status.go b/engine/access/rest/experimental/models/model_scheduled_transaction_status.go new file mode 100644 index 00000000000..bc78c87bd5f --- /dev/null +++ b/engine/access/rest/experimental/models/model_scheduled_transaction_status.go @@ -0,0 +1,20 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +// ScheduledTransactionStatus : The current lifecycle status of a scheduled transaction. +type ScheduledTransactionStatus string + +// List of ScheduledTransactionStatus +const ( + SCHEDULED_ScheduledTransactionStatus ScheduledTransactionStatus = "scheduled" + EXECUTED_ScheduledTransactionStatus ScheduledTransactionStatus = "executed" + CANCELLED_ScheduledTransactionStatus ScheduledTransactionStatus = "cancelled" + FAILED_ScheduledTransactionStatus ScheduledTransactionStatus = "failed" +) diff --git a/engine/access/rest/experimental/models/model_scheduled_transactions_response.go b/engine/access/rest/experimental/models/model_scheduled_transactions_response.go new file mode 100644 index 00000000000..9077f2e4655 --- /dev/null +++ b/engine/access/rest/experimental/models/model_scheduled_transactions_response.go @@ -0,0 +1,14 @@ +/* + * Flow Experimental API + * + * Experimental API endpoints for the Flow Access Node. These endpoints are subject to change without notice. Endpoints may be moved to a permanent API once they are stable. + * + * API version: 0.1.0 + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ +package models + +type ScheduledTransactionsResponse struct { + ScheduledTransactions []ScheduledTransaction `json:"scheduled_transactions"` + NextCursor string `json:"next_cursor,omitempty"` +} diff --git a/engine/access/rest/experimental/models/non_fungible_token_transfer.go b/engine/access/rest/experimental/models/non_fungible_token_transfer.go new file mode 100644 index 00000000000..d21dda8c23f --- /dev/null +++ b/engine/access/rest/experimental/models/non_fungible_token_transfer.go @@ -0,0 +1,56 @@ +package models + +import ( + "fmt" + "strconv" + "time" + + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + accessmodel "github.com/onflow/flow-go/model/access" +) + +// Build populates the NonFungibleTokenTransfer from a domain model. +func (t *NonFungibleTokenTransfer) Build( + transfer *accessmodel.NonFungibleTokenTransfer, + link LinkGenerator, +) error { + eventIndices := make([]string, len(transfer.EventIndices)) + for i, idx := range transfer.EventIndices { + eventIndices[i] = strconv.FormatUint(uint64(idx), 10) + } + + t.BlockHeight = strconv.FormatUint(transfer.BlockHeight, 10) + t.BlockTimestamp = time.UnixMilli(int64(transfer.BlockTimestamp)).UTC().Format(time.RFC3339Nano) + t.TransactionId = transfer.TransactionID.String() + t.TransactionIndex = strconv.FormatUint(uint64(transfer.TransactionIndex), 10) + t.EventIndices = eventIndices + t.TokenType = transfer.TokenType + t.NftId = strconv.FormatUint(transfer.ID, 10) + t.SourceAddress = addressHex(transfer.SourceAddress) + t.RecipientAddress = addressHex(transfer.RecipientAddress) + t.Expandable = new(AccountTransactionExpandable) + + if transfer.Transaction != nil { + t.Transaction = new(commonmodels.Transaction) + t.Transaction.Build(transfer.Transaction, nil, link) + } else { + transactionLink, err := link.TransactionLink(transfer.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate transaction link: %w", err) + } + t.Expandable.Transaction = transactionLink + } + + if transfer.Result != nil { + t.Result = new(commonmodels.TransactionResult) + t.Result.Build(transfer.Result, transfer.TransactionID, link) + } else { + resultLink, err := link.TransactionResultLink(transfer.TransactionID) + if err != nil { + return fmt.Errorf("failed to generate result link: %w", err) + } + t.Expandable.Result = resultLink + } + + return nil +} diff --git a/engine/access/rest/experimental/models/scheduled_transaction.go b/engine/access/rest/experimental/models/scheduled_transaction.go new file mode 100644 index 00000000000..3747af7f3ba --- /dev/null +++ b/engine/access/rest/experimental/models/scheduled_transaction.go @@ -0,0 +1,143 @@ +package models + +import ( + "fmt" + "strconv" + "time" + + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// Build populates a [ScheduledTransaction] from a domain model. +func (t *ScheduledTransaction) Build( + tx *accessmodel.ScheduledTransaction, + link LinkGenerator, + expand map[string]bool, +) error { + t.Id = strconv.FormatUint(tx.ID, 10) + + var priority ScheduledTransactionPriority + if err := priority.Build(tx.Priority); err != nil { + return fmt.Errorf("failed to build scheduled transaction priority: %w", err) + } + t.Priority = &priority + + var status ScheduledTransactionStatus + if err := status.Build(tx.Status); err != nil { + return fmt.Errorf("failed to build scheduled transaction status: %w", err) + } + t.Status = &status + + t.Timestamp = strconv.FormatUint(tx.Timestamp, 10) + t.ExecutionEffort = strconv.FormatUint(tx.ExecutionEffort, 10) + t.Fees = strconv.FormatUint(tx.Fees, 10) + t.TransactionHandlerOwner = tx.TransactionHandlerOwner.String() + t.TransactionHandlerTypeIdentifier = tx.TransactionHandlerTypeIdentifier + t.TransactionHandlerUuid = strconv.FormatUint(tx.TransactionHandlerUUID, 10) + t.TransactionHandlerPublicPath = tx.TransactionHandlerPublicPath + + if tx.FeesReturned > 0 { + t.FeesReturned = strconv.FormatUint(tx.FeesReturned, 10) + } + if tx.FeesDeducted > 0 { + t.FeesDeducted = strconv.FormatUint(tx.FeesDeducted, 10) + } + if tx.CreatedTransactionID != flow.ZeroID { + t.CreatedTransactionId = tx.CreatedTransactionID.String() + } + if tx.ExecutedTransactionID != flow.ZeroID { + t.ExecutedTransactionId = tx.ExecutedTransactionID.String() + } + if tx.CancelledTransactionID != flow.ZeroID { + t.CancelledTransactionId = tx.CancelledTransactionID.String() + } + + t.IsPlaceholder = tx.IsPlaceholder + + if tx.CreatedAt != 0 { + t.CreatedAt = time.UnixMilli(int64(tx.CreatedAt)).UTC().Format(time.RFC3339Nano) + } + if tx.CompletedAt != 0 { + t.CompletedAt = time.UnixMilli(int64(tx.CompletedAt)).UTC().Format(time.RFC3339Nano) + } + + t.Expandable = new(ScheduledTransactionExpandable) + + if tx.Transaction != nil { + t.Transaction = new(commonmodels.Transaction) + t.Transaction.Build(tx.Transaction, nil, link) + } else if tx.ExecutedTransactionID != flow.ZeroID { + transactionLink, err := link.TransactionLink(tx.ExecutedTransactionID) + if err != nil { + return fmt.Errorf("failed to generate transaction link: %w", err) + } + t.Expandable.Transaction = transactionLink + } + + if tx.Result != nil { + t.Result = new(commonmodels.TransactionResult) + t.Result.Build(tx.Result, tx.ExecutedTransactionID, link) + } else if tx.ExecutedTransactionID != flow.ZeroID { + resultLink, err := link.TransactionResultLink(tx.ExecutedTransactionID) + if err != nil { + return fmt.Errorf("failed to generate result link: %w", err) + } + t.Expandable.Result = resultLink + } + + if tx.HandlerContract != nil { + t.HandlerContract = new(ContractDeployment) + expandWithCode := map[string]bool{"code": true} + if err := t.HandlerContract.Build(tx.HandlerContract, link, expandWithCode); err != nil { + return err + } + } else { + contractID, err := tx.HandlerContractID() + if err != nil { + return fmt.Errorf("failed to get handler contract ID: %w", err) + } + + handlerContractLink, err := link.ContractCodeLink(contractID) + if err != nil { + return fmt.Errorf("failed to generate handler contract link: %w", err) + } + t.Expandable.HandlerContract = handlerContractLink + } + + return nil +} + +// Build sets the [ScheduledTransactionStatus] from a domain status value. +func (s *ScheduledTransactionStatus) Build(status accessmodel.ScheduledTransactionStatus) error { + switch status { + case accessmodel.ScheduledTxStatusScheduled: + *s = SCHEDULED_ScheduledTransactionStatus + case accessmodel.ScheduledTxStatusExecuted: + *s = EXECUTED_ScheduledTransactionStatus + case accessmodel.ScheduledTxStatusCancelled: + *s = CANCELLED_ScheduledTransactionStatus + case accessmodel.ScheduledTxStatusFailed: + *s = FAILED_ScheduledTransactionStatus + default: + return fmt.Errorf("unknown scheduled transaction status: %d", status) + } + return nil +} + +// Build sets the [ScheduledTransactionPriority] from a domain priority value. +// The contract encodes priority as: 0 = high, 1 = medium, 2 = low. +func (p *ScheduledTransactionPriority) Build(priority accessmodel.ScheduledTransactionPriority) error { + switch priority { + case accessmodel.ScheduledTxPriorityHigh: + *p = HIGH_ScheduledTransactionPriority + case accessmodel.ScheduledTxPriorityMedium: + *p = MEDIUM_ScheduledTransactionPriority + case accessmodel.ScheduledTxPriorityLow: + *p = LOW_ScheduledTransactionPriority + default: + return fmt.Errorf("unknown scheduled transaction priority: %d", priority) + } + return nil +} diff --git a/engine/access/rest/experimental/request/cursor_contracts.go b/engine/access/rest/experimental/request/cursor_contracts.go new file mode 100644 index 00000000000..41463b25c31 --- /dev/null +++ b/engine/access/rest/experimental/request/cursor_contracts.go @@ -0,0 +1,69 @@ +package request + +import ( + "encoding/base64" + "encoding/json" + "fmt" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// contractDeploymentsCursor is the JSON shape for a [accessmodel.ContractDeploymentsCursor]. +// Address and Name are omitted when empty (DeploymentsByContract cursors; the contract is +// identified by the URL parameter). +type contractDeploymentsCursor struct { + Address string `json:"a,omitempty"` + Name string `json:"n,omitempty"` + Height uint64 `json:"h"` + TxIndex uint32 `json:"t"` + EventIndex uint32 `json:"e"` +} + +// EncodeContractDeploymentsCursor encodes a [accessmodel.ContractDeploymentsCursor] as a +// base64url JSON string. Address and Name are included when non-empty (All/ByAddress cursors). +// +// No error returns are expected during normal operation. +func EncodeContractDeploymentsCursor(cursor *accessmodel.ContractDeploymentsCursor) (string, error) { + data, err := json.Marshal(contractDeploymentsCursor{ + Address: cursor.Address.Hex(), + Name: cursor.ContractName, + Height: cursor.BlockHeight, + TxIndex: cursor.TransactionIndex, + EventIndex: cursor.EventIndex, + }) + if err != nil { + return "", fmt.Errorf("failed to marshal deployments cursor: %w", err) + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +// DecodeContractDeploymentsCursor decodes a base64url JSON string into a +// [accessmodel.ContractDeploymentsCursor]. +// +// Expected error returns during normal operation: +// - wrapped base64 or JSON decode error if the cursor is malformed. +func DecodeContractDeploymentsCursor(raw string) (*accessmodel.ContractDeploymentsCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, fmt.Errorf("invalid cursor encoding: %w", err) + } + var c contractDeploymentsCursor + if err := json.Unmarshal(data, &c); err != nil { + return nil, fmt.Errorf("invalid deployments cursor format: %w", err) + } + cursor := &accessmodel.ContractDeploymentsCursor{ + ContractName: c.Name, + BlockHeight: c.Height, + TransactionIndex: c.TxIndex, + EventIndex: c.EventIndex, + } + if c.Address != "" { + addr, err := flow.StringToAddress(c.Address) + if err != nil { + return nil, fmt.Errorf("invalid address in cursor: %w", err) + } + cursor.Address = addr + } + return cursor, nil +} diff --git a/engine/access/rest/experimental/request/cursor_scheduled_transactions.go b/engine/access/rest/experimental/request/cursor_scheduled_transactions.go new file mode 100644 index 00000000000..7d2afba67a7 --- /dev/null +++ b/engine/access/rest/experimental/request/cursor_scheduled_transactions.go @@ -0,0 +1,38 @@ +package request + +import ( + "encoding/base64" + "encoding/json" + "fmt" + + accessmodel "github.com/onflow/flow-go/model/access" +) + +// scheduledTxCursor is the JSON shape of a pagination cursor (opaque to clients). +type scheduledTxCursor struct { + ID uint64 `json:"i"` +} + +// parseScheduledTxCursor decodes a base64-encoded JSON cursor string. +func parseScheduledTxCursor(raw string) (*accessmodel.ScheduledTransactionCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, fmt.Errorf("invalid cursor encoding: %w", err) + } + var c scheduledTxCursor + if err := json.Unmarshal(data, &c); err != nil { + return nil, fmt.Errorf("invalid cursor format: %w", err) + } + return &accessmodel.ScheduledTransactionCursor{ID: c.ID}, nil +} + +// EncodeScheduledTxCursor encodes a cursor as base64 URL-encoded JSON. +// +// All errors indicate the cursor is invalid. +func EncodeScheduledTxCursor(cursor *accessmodel.ScheduledTransactionCursor) (string, error) { + data, err := json.Marshal(scheduledTxCursor{ID: cursor.ID}) + if err != nil { + return "", fmt.Errorf("failed to marshal cursor: %w", err) + } + return base64.RawURLEncoding.EncodeToString(data), nil +} diff --git a/engine/access/rest/experimental/request/cursor_transfer.go b/engine/access/rest/experimental/request/cursor_transfer.go new file mode 100644 index 00000000000..1925c9cae22 --- /dev/null +++ b/engine/access/rest/experimental/request/cursor_transfer.go @@ -0,0 +1,58 @@ +package request + +import ( + "encoding/base64" + "encoding/json" + "fmt" + + accessmodel "github.com/onflow/flow-go/model/access" +) + +// transferCursor is the JSON representation of a transfer pagination cursor. +// Encoded as base64 in query params and responses to keep the format opaque to clients. +type transferCursor struct { + BlockHeight uint64 `json:"h"` + TransactionIndex uint32 `json:"i"` + EventIndex uint32 `json:"e"` +} + +// ParseTransferCursor decodes a base64-encoded JSON transfer cursor string. +// +// All errors indicate the cursor is invalid. +func ParseTransferCursor(raw string) (*accessmodel.TransferCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, fmt.Errorf("invalid cursor encoding: %w", err) + } + + var c transferCursor + if err := json.Unmarshal(data, &c); err != nil { + return nil, fmt.Errorf("invalid cursor format: %w", err) + } + + if c.BlockHeight == 0 && c.TransactionIndex == 0 && c.EventIndex == 0 { + return nil, nil + } + + return &accessmodel.TransferCursor{ + BlockHeight: c.BlockHeight, + TransactionIndex: c.TransactionIndex, + EventIndex: c.EventIndex, + }, nil +} + +// EncodeTransferCursor encodes a transfer cursor as base64-encoded JSON. +// +// All errors indicate the cursor is invalid. +func EncodeTransferCursor(cursor *accessmodel.TransferCursor) (string, error) { + c := transferCursor{ + BlockHeight: cursor.BlockHeight, + TransactionIndex: cursor.TransactionIndex, + EventIndex: cursor.EventIndex, + } + data, err := json.Marshal(c) + if err != nil { + return "", fmt.Errorf("failed to marshal transfer cursor: %w", err) + } + return base64.RawURLEncoding.EncodeToString(data), nil +} diff --git a/engine/access/rest/experimental/request/get_account_ft_transfers.go b/engine/access/rest/experimental/request/get_account_ft_transfers.go new file mode 100644 index 00000000000..6207706c215 --- /dev/null +++ b/engine/access/rest/experimental/request/get_account_ft_transfers.go @@ -0,0 +1,72 @@ +package request + +import ( + "fmt" + "strconv" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/common/parser" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// GetAccountFTTransfers holds the parsed request parameters for the GetAccountFungibleTokenTransfers endpoint. +type GetAccountFTTransfers struct { + Address flow.Address + Limit uint32 + Cursor *accessmodel.TransferCursor + Filter extended.AccountTransferFilter +} + +// NewGetAccountFTTransfers parses and validates the HTTP request for the +// GetAccountFungibleTokenTransfers endpoint. +// +// All errors indicate the request is invalid. +func NewGetAccountFTTransfers(r *common.Request) (GetAccountFTTransfers, error) { + var req GetAccountFTTransfers + + address, err := parser.ParseAddress(r.GetVar("address"), r.Chain) + if err != nil { + return req, err + } + req.Address = address + + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return req, fmt.Errorf("invalid limit: %w", err) + } + req.Limit = uint32(parsed) + } + + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := ParseTransferCursor(raw) + if err != nil { + return req, err + } + req.Cursor = c + } + + if raw := r.GetQueryParam("token_type"); raw != "" { + req.Filter.TokenType = raw + } + + if raw := r.GetQueryParam("source_address"); raw != "" { + addr, err := parser.ParseAddress(raw, r.Chain) + if err != nil { + return req, fmt.Errorf("invalid source_address: %w", err) + } + req.Filter.SourceAddress = addr + } + + if raw := r.GetQueryParam("recipient_address"); raw != "" { + addr, err := parser.ParseAddress(raw, r.Chain) + if err != nil { + return req, fmt.Errorf("invalid recipient_address: %w", err) + } + req.Filter.RecipientAddress = addr + } + + return req, nil +} diff --git a/engine/access/rest/experimental/request/get_account_nft_transfers.go b/engine/access/rest/experimental/request/get_account_nft_transfers.go new file mode 100644 index 00000000000..b123bb979cf --- /dev/null +++ b/engine/access/rest/experimental/request/get_account_nft_transfers.go @@ -0,0 +1,72 @@ +package request + +import ( + "fmt" + "strconv" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/common/parser" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// GetAccountNFTTransfers holds the parsed request parameters for the GetAccountNonFungibleTokenTransfers endpoint. +type GetAccountNFTTransfers struct { + Address flow.Address + Limit uint32 + Cursor *accessmodel.TransferCursor + Filter extended.AccountTransferFilter +} + +// NewGetAccountNFTTransfers parses and validates the HTTP request for the +// GetAccountNonFungibleTokenTransfers endpoint. +// +// All errors indicate the request is invalid. +func NewGetAccountNFTTransfers(r *common.Request) (GetAccountNFTTransfers, error) { + var req GetAccountNFTTransfers + + address, err := parser.ParseAddress(r.GetVar("address"), r.Chain) + if err != nil { + return req, err + } + req.Address = address + + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return req, fmt.Errorf("invalid limit: %w", err) + } + req.Limit = uint32(parsed) + } + + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := ParseTransferCursor(raw) + if err != nil { + return req, err + } + req.Cursor = c + } + + if raw := r.GetQueryParam("token_type"); raw != "" { + req.Filter.TokenType = raw + } + + if raw := r.GetQueryParam("source_address"); raw != "" { + addr, err := parser.ParseAddress(raw, r.Chain) + if err != nil { + return req, fmt.Errorf("invalid source_address: %w", err) + } + req.Filter.SourceAddress = addr + } + + if raw := r.GetQueryParam("recipient_address"); raw != "" { + addr, err := parser.ParseAddress(raw, r.Chain) + if err != nil { + return req, fmt.Errorf("invalid recipient_address: %w", err) + } + req.Filter.RecipientAddress = addr + } + + return req, nil +} diff --git a/engine/access/rest/experimental/request/get_account_transactions.go b/engine/access/rest/experimental/request/get_account_transactions.go new file mode 100644 index 00000000000..40ccda0507d --- /dev/null +++ b/engine/access/rest/experimental/request/get_account_transactions.go @@ -0,0 +1,106 @@ +package request + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "strconv" + "strings" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/common/parser" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// GetAccountTransactions holds the parsed request parameters for the GetAccountTransactions endpoint. +type GetAccountTransactions struct { + Address flow.Address + Limit uint32 + Cursor *accessmodel.AccountTransactionCursor + Filter extended.AccountTransactionFilter +} + +// NewGetAccountTransactions parses and validates the HTTP request for the GetAccountTransactions endpoint. +// +// All errors indicate the request is invalid. +func NewGetAccountTransactions(r *common.Request) (GetAccountTransactions, error) { + var req GetAccountTransactions + + address, err := parser.ParseAddress(r.GetVar("address"), r.Chain) + if err != nil { + return req, err + } + req.Address = address + + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return req, fmt.Errorf("invalid limit: %w", err) + } + req.Limit = uint32(parsed) + } + + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := parseAccountTransactionCursor(raw) + if err != nil { + return req, err + } + req.Cursor = c + } + + if raw := r.GetQueryParam("roles"); raw != "" { + for role := range strings.SplitSeq(raw, ",") { + parsed, err := accessmodel.ParseTransactionRole(strings.TrimSpace(role)) + if err != nil { + return req, fmt.Errorf("invalid role: %w", err) + } + req.Filter.Roles = append(req.Filter.Roles, parsed) + } + } + + return req, nil +} + +// accountTransactionCursor is the JSON representation of an account transaction pagination cursor. +// Encoded as base64 in query params and responses to keep the format opaque to clients. +type accountTransactionCursor struct { + BlockHeight uint64 `json:"h"` + TransactionIndex uint32 `json:"i"` +} + +// parseAccountTransactionCursor decodes a base64-encoded JSON cursor string. +func parseAccountTransactionCursor(raw string) (*accessmodel.AccountTransactionCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, fmt.Errorf("invalid cursor encoding: %w", err) + } + + var c accountTransactionCursor + if err := json.Unmarshal(data, &c); err != nil { + return nil, fmt.Errorf("invalid cursor format: %w", err) + } + + if c.BlockHeight == 0 && c.TransactionIndex == 0 { + return nil, nil + } + + return &accessmodel.AccountTransactionCursor{ + BlockHeight: c.BlockHeight, + TransactionIndex: c.TransactionIndex, + }, nil +} + +// EncodeAccountTransactionCursor encodes a cursor as base64-encoded JSON. +func EncodeAccountTransactionCursor(cursor *accessmodel.AccountTransactionCursor) (string, error) { + c := accountTransactionCursor{ + BlockHeight: cursor.BlockHeight, + TransactionIndex: cursor.TransactionIndex, + } + data, err := json.Marshal(c) // accountTransactionCursor marshaling cannot fail + if err != nil { + return "", fmt.Errorf("failed to marshal account transaction cursor: %w", err) + } + return base64.RawURLEncoding.EncodeToString(data), nil +} diff --git a/engine/access/rest/experimental/request/get_contracts.go b/engine/access/rest/experimental/request/get_contracts.go new file mode 100644 index 00000000000..cb22693ac7d --- /dev/null +++ b/engine/access/rest/experimental/request/get_contracts.go @@ -0,0 +1,201 @@ +package request + +import ( + "fmt" + "strconv" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/common/parser" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// GetContracts holds parsed request params for GET /contracts. +type GetContracts struct { + Limit uint32 + Cursor *accessmodel.ContractDeploymentsCursor + Filter extended.ContractDeploymentFilter + ExpandOptions extended.ContractDeploymentExpandOptions +} + +// NewGetContracts parses and validates the HTTP request for GET /contracts. +// +// All errors indicate an invalid request. +func NewGetContracts(r *common.Request) (GetContracts, error) { + var req GetContracts + + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return req, fmt.Errorf("invalid limit: %w", err) + } + req.Limit = uint32(parsed) + } + + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := DecodeContractDeploymentsCursor(raw) + if err != nil { + return req, err + } + req.Cursor = c + } + + if err := parseContractFilter(r, &req.Filter); err != nil { + return req, err + } + + req.ExpandOptions = parseContractExpandOptions(r) + + return req, nil +} + +// GetContract holds parsed request params for GET /contracts/{identifier}. +type GetContract struct { + ID string + Filter extended.ContractDeploymentFilter + ExpandOptions extended.ContractDeploymentExpandOptions +} + +// NewGetContract parses and validates the HTTP request for GET /contracts/{identifier}. +// +// All errors indicate an invalid request. +func NewGetContract(r *common.Request) (GetContract, error) { + var req GetContract + + req.ID = r.GetVar("identifier") + + if err := parseContractFilter(r, &req.Filter); err != nil { + return req, err + } + + req.ExpandOptions = parseContractExpandOptions(r) + + return req, nil +} + +// GetContractDeployments holds parsed request params for GET /contracts/{identifier}/deployments. +type GetContractDeployments struct { + ID string + Limit uint32 + Cursor *accessmodel.ContractDeploymentsCursor + Filter extended.ContractDeploymentFilter + ExpandOptions extended.ContractDeploymentExpandOptions +} + +// NewGetContractDeployments parses and validates the HTTP request for +// GET /contracts/{identifier}/deployments. +// +// All errors indicate an invalid request. +func NewGetContractDeployments(r *common.Request) (GetContractDeployments, error) { + var req GetContractDeployments + + req.ID = r.GetVar("identifier") + + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return req, fmt.Errorf("invalid limit: %w", err) + } + req.Limit = uint32(parsed) + } + + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := DecodeContractDeploymentsCursor(raw) + if err != nil { + return req, err + } + req.Cursor = c + } + + if err := parseContractFilter(r, &req.Filter); err != nil { + return req, err + } + + req.ExpandOptions = parseContractExpandOptions(r) + + return req, nil +} + +// GetContractsByAddress holds parsed request params for GET /accounts/{address}/contracts. +type GetContractsByAddress struct { + Address flow.Address + Limit uint32 + Cursor *accessmodel.ContractDeploymentsCursor + Filter extended.ContractDeploymentFilter + ExpandOptions extended.ContractDeploymentExpandOptions +} + +// NewGetContractsByAddress parses and validates the HTTP request for +// GET /accounts/{address}/contracts. +// +// All errors indicate an invalid request. +func NewGetContractsByAddress(r *common.Request) (GetContractsByAddress, error) { + var req GetContractsByAddress + + address, err := parser.ParseAddress(r.GetVar("address"), r.Chain) + if err != nil { + return req, fmt.Errorf("invalid address: %w", err) + } + req.Address = address + + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return req, fmt.Errorf("invalid limit: %w", err) + } + req.Limit = uint32(parsed) + } + + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := DecodeContractDeploymentsCursor(raw) + if err != nil { + return req, err + } + req.Cursor = c + } + + if err := parseContractFilter(r, &req.Filter); err != nil { + return req, err + } + + req.ExpandOptions = parseContractExpandOptions(r) + + return req, nil +} + +// parseContractExpandOptions parses the expand query parameter for contract endpoints. +func parseContractExpandOptions(r *common.Request) extended.ContractDeploymentExpandOptions { + return extended.ContractDeploymentExpandOptions{ + Code: r.Expands("code"), + Transaction: r.Expands("transaction"), + Result: r.Expands("result"), + } +} + +// parseContractFilter parses all optional filter query params from r into filter. +// +// All errors indicate an invalid request. +func parseContractFilter(r *common.Request, filter *extended.ContractDeploymentFilter) error { + if raw := r.GetQueryParam("contract_name"); raw != "" { + filter.ContractName = raw + } + + if raw := r.GetQueryParam("start_block"); raw != "" { + v, err := strconv.ParseUint(raw, 10, 64) + if err != nil { + return fmt.Errorf("invalid start_block: %w", err) + } + filter.StartBlock = &v + } + + if raw := r.GetQueryParam("end_block"); raw != "" { + v, err := strconv.ParseUint(raw, 10, 64) + if err != nil { + return fmt.Errorf("invalid end_block: %w", err) + } + filter.EndBlock = &v + } + + return nil +} diff --git a/engine/access/rest/experimental/request/get_scheduled_transactions.go b/engine/access/rest/experimental/request/get_scheduled_transactions.go new file mode 100644 index 00000000000..60e09465fcb --- /dev/null +++ b/engine/access/rest/experimental/request/get_scheduled_transactions.go @@ -0,0 +1,178 @@ +package request + +import ( + "fmt" + "strconv" + "strings" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/common/parser" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// GetScheduledTransactions holds parsed request params for the list endpoints. +type GetScheduledTransactions struct { + Limit uint32 + Cursor *accessmodel.ScheduledTransactionCursor + Filter extended.ScheduledTransactionFilter + ExpandOptions extended.ScheduledTransactionExpandOptions +} + +// NewGetScheduledTransactions parses and validates the HTTP request for GET /scheduled. +// +// All errors indicate an invalid request. +func NewGetScheduledTransactions(r *common.Request) (GetScheduledTransactions, error) { + var req GetScheduledTransactions + + if raw := r.GetQueryParam("limit"); raw != "" { + parsed, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + return req, fmt.Errorf("invalid limit: %w", err) + } + req.Limit = uint32(parsed) + } + + if raw := r.GetQueryParam("cursor"); raw != "" { + c, err := parseScheduledTxCursor(raw) + if err != nil { + return req, err + } + req.Cursor = c + } + + if err := parseScheduledTxFilter(r, &req.Filter); err != nil { + return req, err + } + + req.ExpandOptions = parseExpandOptions(r) + + return req, nil +} + +// GetAccountScheduledTransactions holds parsed request params for the list endpoints. +type GetAccountScheduledTransactions struct { + GetScheduledTransactions + Address flow.Address +} + +// NewGetScheduledTransactionsByAddress parses GET /accounts/{address}/scheduled. +// +// All errors indicate an invalid request. +func NewGetScheduledTransactionsByAddress(r *common.Request) (GetAccountScheduledTransactions, error) { + req, err := NewGetScheduledTransactions(r) + if err != nil { + return GetAccountScheduledTransactions{}, err + } + + address, err := parser.ParseAddress(r.GetVar("address"), r.Chain) + if err != nil { + return GetAccountScheduledTransactions{}, err + } + + if req.Filter.TransactionHandlerOwner != nil && *req.Filter.TransactionHandlerOwner != address { + return GetAccountScheduledTransactions{}, fmt.Errorf("handler_owner must be the same as the address") + } + + return GetAccountScheduledTransactions{ + GetScheduledTransactions: req, + Address: address, + }, nil +} + +// GetScheduledTransaction holds parsed request params for the single-transaction endpoint. +type GetScheduledTransaction struct { + ID uint64 + ExpandOptions extended.ScheduledTransactionExpandOptions +} + +// NewGetScheduledTransaction parses GET /scheduled/transaction/{id}. +// +// All errors indicate an invalid request. +func NewGetScheduledTransaction(r *common.Request) (GetScheduledTransaction, error) { + var req GetScheduledTransaction + + id, err := strconv.ParseUint(r.GetVar("id"), 10, 64) + if err != nil { + return req, fmt.Errorf("invalid scheduled transaction ID: %w", err) + } + req.ID = id + req.ExpandOptions = parseExpandOptions(r) + + return req, nil +} + +// parseScheduledTxFilter parses all optional filter query params from r into filter. +// +// All errors indicate an invalid request. +func parseScheduledTxFilter(r *common.Request, filter *extended.ScheduledTransactionFilter) error { + if raw := r.GetQueryParam("status"); raw != "" { + for rawStatus := range strings.SplitSeq(raw, ",") { + s, err := accessmodel.ParseScheduledTransactionStatus(strings.TrimSpace(rawStatus)) + if err != nil { + return fmt.Errorf("invalid status: %w", err) + } + filter.Statuses = append(filter.Statuses, s) + } + } + + if raw := r.GetQueryParam("priority"); raw != "" { + p, err := accessmodel.ParseScheduledTransactionPriority(raw) + if err != nil { + return fmt.Errorf("invalid priority: %w", err) + } + filter.Priority = &p + } + + if raw := r.GetQueryParam("start_time"); raw != "" { + v, err := strconv.ParseUint(raw, 10, 64) + if err != nil { + return fmt.Errorf("invalid start_time: %w", err) + } + filter.StartTime = &v + } + + if raw := r.GetQueryParam("end_time"); raw != "" { + v, err := strconv.ParseUint(raw, 10, 64) + if err != nil { + return fmt.Errorf("invalid end_time: %w", err) + } + filter.EndTime = &v + } + + if filter.StartTime != nil && filter.EndTime != nil && *filter.StartTime > *filter.EndTime { + return fmt.Errorf("start_time must be before end_time") + } + + if raw := r.GetQueryParam("handler_owner"); raw != "" { + addr, err := parser.ParseAddress(raw, r.Chain) + if err != nil { + return fmt.Errorf("invalid handler_owner: %w", err) + } + filter.TransactionHandlerOwner = &addr + } + + if raw := r.GetQueryParam("handler_type_id"); raw != "" { + filter.TransactionHandlerTypeID = &raw + } + + if raw := r.GetQueryParam("handler_uuid"); raw != "" { + v, err := strconv.ParseUint(raw, 10, 64) + if err != nil { + return fmt.Errorf("invalid handler_uuid: %w", err) + } + filter.TransactionHandlerUUID = &v + } + + return nil +} + +// parseExpandOptions parses the expand options from the request. +func parseExpandOptions(r *common.Request) extended.ScheduledTransactionExpandOptions { + return extended.ScheduledTransactionExpandOptions{ + Transaction: r.Expands("transaction"), + Result: r.Expands("result"), + HandlerContract: r.Expands("handler_contract"), + } +} diff --git a/engine/access/rest/experimental/routes/account_ft_transfers.go b/engine/access/rest/experimental/routes/account_ft_transfers.go new file mode 100644 index 00000000000..454f44730fa --- /dev/null +++ b/engine/access/rest/experimental/routes/account_ft_transfers.go @@ -0,0 +1,48 @@ +package routes + +import ( + "net/http" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/experimental/models" + "github.com/onflow/flow-go/engine/access/rest/experimental/request" +) + +// GetAccountFungibleTokenTransfers returns a paginated list of fungible token transfers for the given account address. +func GetAccountFungibleTokenTransfers(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetAccountFTTransfers(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + expandOptions := extended.AccountTransferExpandOptions{ + Transaction: r.Expands("transaction"), + Result: r.Expands("result"), + } + + page, err := backend.GetAccountFungibleTokenTransfers(r.Context(), req.Address, req.Limit, req.Cursor, req.Filter, expandOptions, entities.EventEncodingVersion_JSON_CDC_V0) + if err != nil { + return nil, err + } + + resp := models.AccountFungibleTransfersResponse{ + Transfers: make([]models.FungibleTokenTransfer, len(page.Transfers)), + } + for i := range page.Transfers { + err := resp.Transfers[i].Build(&page.Transfers[i], link) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to build transfer", err) + } + } + if page.NextCursor != nil { + resp.NextCursor, err = request.EncodeTransferCursor(page.NextCursor) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to encode next cursor", err) + } + } + + return resp, nil +} diff --git a/engine/access/rest/experimental/routes/account_ft_transfers_test.go b/engine/access/rest/experimental/routes/account_ft_transfers_test.go new file mode 100644 index 00000000000..1bf1c1d02fc --- /dev/null +++ b/engine/access/rest/experimental/routes/account_ft_transfers_test.go @@ -0,0 +1,525 @@ +package routes_test + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "math/big" + "net/http" + "net/url" + "testing" + "time" + + "github.com/stretchr/testify/assert" + mocktestify "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + extendedmock "github.com/onflow/flow-go/access/backends/extended/mock" + "github.com/onflow/flow-go/engine/access/rest/router" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/utils/unittest" +) + +type ftTransfersURLParams struct { + limit string + cursor string + tokenType string + sourceAddr string + recipientAddr string + expand string +} + +func accountFTTransfersURL(t *testing.T, address string, params ftTransfersURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/accounts/%s/ft/transfers", address)) + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.tokenType != "" { + q.Add("token_type", params.tokenType) + } + if params.sourceAddr != "" { + q.Add("source_address", params.sourceAddr) + } + if params.recipientAddr != "" { + q.Add("recipient_address", params.recipientAddr) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +// testEncodeTransferCursor encodes a transfer cursor the same way the handler does, for use in +// test assertions and inputs. +func testEncodeTransferCursor(t *testing.T, height uint64, txIndex uint32, eventIndex uint32) string { + data, err := json.Marshal(struct { + BlockHeight uint64 `json:"h"` + TransactionIndex uint32 `json:"i"` + EventIndex uint32 `json:"e"` + }{height, txIndex, eventIndex}) + require.NoError(t, err) + return base64.RawURLEncoding.EncodeToString(data) +} + +func TestGetAccountFungibleTokenTransfers(t *testing.T) { + address := unittest.AddressFixture() + txID := unittest.IdentifierFixture() + sourceAddr := unittest.RandomAddressFixture() + recipientAddr := unittest.RandomAddressFixture() + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 1000, + BlockTimestamp: 1700000000000, + TransactionIndex: 3, + EventIndices: []uint32{5}, + TokenType: "A.1654653399040a61.FlowToken", + Amount: big.NewInt(1000000000), + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + NextCursor: &accessmodel.TransferCursor{ + BlockHeight: 999, + TransactionIndex: 0, + EventIndex: 2, + }, + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + ts := time.UnixMilli(1700000000000).UTC().Format(time.RFC3339Nano) + expectedCursorStr := testEncodeTransferCursor(t, 999, 0, 2) + expected := fmt.Sprintf(`{ + "transfers": [ + { + "transaction_id": "%s", + "block_height": "1000", + "timestamp": "%s", + "transaction_index": "3", + "event_indices": ["5"], + "token_type": "A.1654653399040a61.FlowToken", + "amount": "1000000000", + "source_address": "%s", + "recipient_address": "%s", + "_expandable": {"transaction": "/v1/transactions/%s", "result": "/v1/transaction_results/%s"} + } + ], + "next_cursor": "%s" + }`, txID.String(), ts, sourceAddr.Hex(), recipientAddr.Hex(), txID.String(), txID.String(), expectedCursorStr) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 500, + BlockTimestamp: 1698000000000, + TransactionIndex: 1, + EventIndices: []uint32{0}, + TokenType: "A.1654653399040a61.FlowToken", + Amount: big.NewInt(500), + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + NextCursor: nil, + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(10), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{limit: "10"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + ts := time.UnixMilli(1698000000000).UTC().Format(time.RFC3339Nano) + expected := fmt.Sprintf(`{ + "transfers": [ + { + "transaction_id": "%s", + "block_height": "500", + "timestamp": "%s", + "transaction_index": "1", + "event_indices": ["0"], + "token_type": "A.1654653399040a61.FlowToken", + "amount": "500", + "source_address": "%s", + "recipient_address": "%s", + "_expandable": {"transaction": "/v1/transactions/%s", "result": "/v1/transaction_results/%s"} + } + ] + }`, txID.String(), ts, sourceAddr.Hex(), recipientAddr.Hex(), txID.String(), txID.String()) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 900, + TransactionIndex: 2, + EventIndices: []uint32{1}, + TokenType: "A.1654653399040a61.FlowToken", + Amount: big.NewInt(100), + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + NextCursor: nil, + } + + expectedCursor := &accessmodel.TransferCursor{ + BlockHeight: 1000, + TransactionIndex: 3, + EventIndex: 5, + } + encodedCursor := testEncodeTransferCursor(t, expectedCursor.BlockHeight, expectedCursor.TransactionIndex, expectedCursor.EventIndex) + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + expectedCursor, + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{cursor: encodedCursor}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with token_type filter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{}, + } + + expectedFilter := extended.AccountTransferFilter{ + TokenType: "A.1654653399040a61.FlowToken", + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + expectedFilter, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{tokenType: "A.1654653399040a61.FlowToken"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with source_address filter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{}, + } + + expectedFilter := extended.AccountTransferFilter{ + SourceAddress: sourceAddr, + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + expectedFilter, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{sourceAddr: sourceAddr.String()}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with recipient_address filter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{}, + } + + expectedFilter := extended.AccountTransferFilter{ + RecipientAddress: recipientAddr, + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + expectedFilter, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{recipientAddr: recipientAddr.String()}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with expand=transaction", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{}, + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{Transaction: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{expand: "transaction"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with expand=result", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{}, + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{Result: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{expand: "result"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid address", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountFTTransfersURL(t, "invalid", ftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid address") + }) + + t.Run("invalid cursor format", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{cursor: "badcursor"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("invalid limit", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{limit: "abc"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid limit") + }) + + t.Run("invalid source_address", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{sourceAddr: "not-an-address"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid source_address") + }) + + t.Run("backend returns not found", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.NotFound, "no transfers found for account %s", address)) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusNotFound, rr.Code) + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + reqURL := accountFTTransfersURL(t, address.String(), ftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) + + t.Run("address with 0x prefix", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.FungibleTokenTransfersPage{ + Transfers: []accessmodel.FungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 100, + TransactionIndex: 0, + EventIndices: []uint32{0}, + TokenType: "A.1654653399040a61.FlowToken", + Amount: big.NewInt(1), + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + } + + backend.On("GetAccountFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountFTTransfersURL(t, "0x"+address.String(), ftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) +} diff --git a/engine/access/rest/experimental/routes/account_nft_transfers.go b/engine/access/rest/experimental/routes/account_nft_transfers.go new file mode 100644 index 00000000000..adfc0572351 --- /dev/null +++ b/engine/access/rest/experimental/routes/account_nft_transfers.go @@ -0,0 +1,48 @@ +package routes + +import ( + "net/http" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/experimental/models" + "github.com/onflow/flow-go/engine/access/rest/experimental/request" +) + +// GetAccountNonFungibleTokenTransfers returns a paginated list of non-fungible token transfers for the given account address. +func GetAccountNonFungibleTokenTransfers(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetAccountNFTTransfers(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + expandOptions := extended.AccountTransferExpandOptions{ + Transaction: r.Expands("transaction"), + Result: r.Expands("result"), + } + + page, err := backend.GetAccountNonFungibleTokenTransfers(r.Context(), req.Address, req.Limit, req.Cursor, req.Filter, expandOptions, entities.EventEncodingVersion_JSON_CDC_V0) + if err != nil { + return nil, err + } + + resp := models.AccountNonFungibleTransfersResponse{ + Transfers: make([]models.NonFungibleTokenTransfer, len(page.Transfers)), + } + for i := range page.Transfers { + err := resp.Transfers[i].Build(&page.Transfers[i], link) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to build transfer", err) + } + } + if page.NextCursor != nil { + resp.NextCursor, err = request.EncodeTransferCursor(page.NextCursor) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to encode next cursor", err) + } + } + + return resp, nil +} diff --git a/engine/access/rest/experimental/routes/account_nft_transfers_test.go b/engine/access/rest/experimental/routes/account_nft_transfers_test.go new file mode 100644 index 00000000000..fa2908688c5 --- /dev/null +++ b/engine/access/rest/experimental/routes/account_nft_transfers_test.go @@ -0,0 +1,450 @@ +package routes_test + +import ( + "fmt" + "net/http" + "net/url" + "testing" + "time" + + "github.com/stretchr/testify/assert" + mocktestify "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + extendedmock "github.com/onflow/flow-go/access/backends/extended/mock" + "github.com/onflow/flow-go/engine/access/rest/router" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/utils/unittest" +) + +type nftTransfersURLParams struct { + limit string + cursor string + tokenType string + sourceAddr string + recipientAddr string + expand string +} + +func accountNFTTransfersURL(t *testing.T, address string, params nftTransfersURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/accounts/%s/nft/transfers", address)) + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.tokenType != "" { + q.Add("token_type", params.tokenType) + } + if params.sourceAddr != "" { + q.Add("source_address", params.sourceAddr) + } + if params.recipientAddr != "" { + q.Add("recipient_address", params.recipientAddr) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +func TestGetAccountNonFungibleTokenTransfers(t *testing.T) { + address := unittest.AddressFixture() + txID := unittest.IdentifierFixture() + sourceAddr := unittest.RandomAddressFixture() + recipientAddr := unittest.RandomAddressFixture() + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 1000, + BlockTimestamp: 1700000000000, + TransactionIndex: 3, + EventIndices: []uint32{5, 6}, + TokenType: "A.1654653399040a61.MyNFT", + ID: 42, + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + NextCursor: &accessmodel.TransferCursor{ + BlockHeight: 999, + TransactionIndex: 0, + EventIndex: 1, + }, + } + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + ts := time.UnixMilli(1700000000000).UTC().Format(time.RFC3339Nano) + expectedCursorStr := testEncodeTransferCursor(t, 999, 0, 1) + expected := fmt.Sprintf(`{ + "transfers": [ + { + "transaction_id": "%s", + "block_height": "1000", + "timestamp": "%s", + "transaction_index": "3", + "event_indices": ["5", "6"], + "token_type": "A.1654653399040a61.MyNFT", + "nft_id": "42", + "source_address": "%s", + "recipient_address": "%s", + "_expandable": {"transaction": "/v1/transactions/%s", "result": "/v1/transaction_results/%s"} + } + ], + "next_cursor": "%s" + }`, txID.String(), ts, sourceAddr.Hex(), recipientAddr.Hex(), txID.String(), txID.String(), expectedCursorStr) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 500, + BlockTimestamp: 1698000000000, + TransactionIndex: 1, + EventIndices: []uint32{0}, + TokenType: "A.1654653399040a61.MyNFT", + ID: 7, + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + NextCursor: nil, + } + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(10), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{limit: "10"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + ts := time.UnixMilli(1698000000000).UTC().Format(time.RFC3339Nano) + expected := fmt.Sprintf(`{ + "transfers": [ + { + "transaction_id": "%s", + "block_height": "500", + "timestamp": "%s", + "transaction_index": "1", + "event_indices": ["0"], + "token_type": "A.1654653399040a61.MyNFT", + "nft_id": "7", + "source_address": "%s", + "recipient_address": "%s", + "_expandable": {"transaction": "/v1/transactions/%s", "result": "/v1/transaction_results/%s"} + } + ] + }`, txID.String(), ts, sourceAddr.Hex(), recipientAddr.Hex(), txID.String(), txID.String()) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 900, + TransactionIndex: 2, + EventIndices: []uint32{1}, + TokenType: "A.1654653399040a61.MyNFT", + ID: 3, + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + NextCursor: nil, + } + + expectedCursor := &accessmodel.TransferCursor{ + BlockHeight: 1000, + TransactionIndex: 3, + EventIndex: 5, + } + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + expectedCursor, + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + encodedCursor := testEncodeTransferCursor(t, 1000, 3, 5) + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{cursor: encodedCursor}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with token_type filter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{}, + } + + expectedFilter := extended.AccountTransferFilter{ + TokenType: "A.1654653399040a61.MyNFT", + } + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + expectedFilter, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{tokenType: "A.1654653399040a61.MyNFT"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with expand=transaction", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{}, + } + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{Transaction: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{expand: "transaction"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with expand=result", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{}, + } + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{Result: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{expand: "result"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid address", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountNFTTransfersURL(t, "invalid", nftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid address") + }) + + t.Run("invalid cursor format", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{cursor: "badcursor"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("invalid limit", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{limit: "abc"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid limit") + }) + + t.Run("invalid recipient_address", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{recipientAddr: "not-an-address"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid recipient_address") + }) + + t.Run("backend returns not found", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.NotFound, "no transfers found for account %s", address)) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusNotFound, rr.Code) + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + reqURL := accountNFTTransfersURL(t, address.String(), nftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) + + t.Run("address with 0x prefix", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.NonFungibleTokenTransfersPage{ + Transfers: []accessmodel.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 100, + TransactionIndex: 0, + EventIndices: []uint32{0}, + TokenType: "A.1654653399040a61.MyNFT", + ID: 1, + SourceAddress: sourceAddr, + RecipientAddress: recipientAddr, + }, + }, + } + + backend.On("GetAccountNonFungibleTokenTransfers", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.TransferCursor)(nil), + extended.AccountTransferFilter{}, + extended.AccountTransferExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountNFTTransfersURL(t, "0x"+address.String(), nftTransfersURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) +} diff --git a/engine/access/rest/experimental/routes/account_transactions.go b/engine/access/rest/experimental/routes/account_transactions.go new file mode 100644 index 00000000000..02a35f718f2 --- /dev/null +++ b/engine/access/rest/experimental/routes/account_transactions.go @@ -0,0 +1,48 @@ +package routes + +import ( + "net/http" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/experimental/models" + "github.com/onflow/flow-go/engine/access/rest/experimental/request" +) + +// GetAccountTransactions returns a paginated list of transactions for the given account address. +func GetAccountTransactions(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetAccountTransactions(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + expandOptions := extended.AccountTransactionExpandOptions{ + Transaction: r.Expands("transaction"), + Result: r.Expands("result"), + } + + page, err := backend.GetAccountTransactions(r.Context(), req.Address, req.Limit, req.Cursor, req.Filter, expandOptions, entities.EventEncodingVersion_JSON_CDC_V0) + if err != nil { + return nil, err + } + + resp := models.AccountTransactionsResponse{ + Transactions: make([]models.AccountTransaction, len(page.Transactions)), + } + for i := range page.Transactions { + err := resp.Transactions[i].Build(&page.Transactions[i], link) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to build transaction", err) + } + } + if page.NextCursor != nil { + resp.NextCursor, err = request.EncodeAccountTransactionCursor(page.NextCursor) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to encode next cursor", err) + } + } + + return resp, nil +} diff --git a/engine/access/rest/experimental/routes/account_transactions_test.go b/engine/access/rest/experimental/routes/account_transactions_test.go new file mode 100644 index 00000000000..bb6ef5574d9 --- /dev/null +++ b/engine/access/rest/experimental/routes/account_transactions_test.go @@ -0,0 +1,407 @@ +package routes_test + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/url" + "testing" + "time" + + "github.com/stretchr/testify/assert" + mocktestify "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + extendedmock "github.com/onflow/flow-go/access/backends/extended/mock" + "github.com/onflow/flow-go/engine/access/rest/router" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/utils/unittest" +) + +type accountTransactionsURLParams struct { + limit string + cursor string + roles string + expand string +} + +func accountTransactionsURL(t *testing.T, address string, params accountTransactionsURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/accounts/%s/transactions", address)) + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.roles != "" { + q.Add("roles", params.roles) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +// testEncodeCursor encodes a cursor the same way the handler does, for use in test assertions and inputs. +func testEncodeCursor(height uint64, txIndex uint32) string { + data, _ := json.Marshal(struct { + BlockHeight uint64 `json:"h"` + TransactionIndex uint32 `json:"i"` + }{height, txIndex}) + return base64.RawURLEncoding.EncodeToString(data) +} + +func TestGetAccountTransactions(t *testing.T) { + address := unittest.AddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.AccountTransactionsPage{ + Transactions: []accessmodel.AccountTransaction{ + { + Address: address, + BlockHeight: 1000, + BlockTimestamp: 1700000000000, + TransactionID: txID1, + TransactionIndex: 3, + Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleAuthorizer}, + }, + { + Address: address, + BlockHeight: 999, + BlockTimestamp: 1699999000000, + TransactionID: txID2, + TransactionIndex: 0, + Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleInteracted}, + }, + }, + NextCursor: &accessmodel.AccountTransactionCursor{ + BlockHeight: 999, + TransactionIndex: 0, + }, + } + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.AccountTransactionCursor)(nil), + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + ts1 := time.UnixMilli(1700000000000).UTC().Format(time.RFC3339Nano) + ts2 := time.UnixMilli(1699999000000).UTC().Format(time.RFC3339Nano) + expectedCursorStr := testEncodeCursor(999, 0) + expected := fmt.Sprintf(`{ + "transactions": [ + { + "block_height": "1000", + "timestamp": "%s", + "transaction_id": "%s", + "transaction_index": "3", + "roles": ["authorizer"], + "_expandable": {"transaction": "/v1/transactions/%s", "result": "/v1/transaction_results/%s"} + }, + { + "block_height": "999", + "timestamp": "%s", + "transaction_id": "%s", + "transaction_index": "0", + "roles": ["interacted"], + "_expandable": {"transaction": "/v1/transactions/%s", "result": "/v1/transaction_results/%s"} + } + ], + "next_cursor": "%s" + }`, ts1, txID1.String(), txID1.String(), txID1.String(), ts2, txID2.String(), txID2.String(), txID2.String(), expectedCursorStr) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.AccountTransactionsPage{ + Transactions: []accessmodel.AccountTransaction{ + { + Address: address, + BlockHeight: 500, + BlockTimestamp: 1698000000000, + TransactionID: txID1, + TransactionIndex: 1, + Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleAuthorizer}, + }, + }, + NextCursor: nil, + } + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(10), + (*accessmodel.AccountTransactionCursor)(nil), + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{limit: "10"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + ts := time.UnixMilli(1698000000000).UTC().Format(time.RFC3339Nano) + expected := fmt.Sprintf(`{ + "transactions": [ + { + "block_height": "500", + "timestamp": "%s", + "transaction_id": "%s", + "transaction_index": "1", + "roles": ["authorizer"], + "_expandable": {"transaction": "/v1/transactions/%s", "result": "/v1/transaction_results/%s"} + } + ] + }`, ts, txID1.String(), txID1.String(), txID1.String()) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.AccountTransactionsPage{ + Transactions: []accessmodel.AccountTransaction{ + { + Address: address, + BlockHeight: 900, + TransactionID: txID1, + TransactionIndex: 2, + Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleInteracted}, + }, + }, + NextCursor: nil, + } + + expectedCursor := &accessmodel.AccountTransactionCursor{ + BlockHeight: 1000, + TransactionIndex: 3, + } + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(0), + expectedCursor, + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{cursor: testEncodeCursor(1000, 3)}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with expand=transaction", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.AccountTransactionsPage{ + Transactions: []accessmodel.AccountTransaction{}, + } + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.AccountTransactionCursor)(nil), + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{Transaction: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{expand: "transaction"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with expand=result", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.AccountTransactionsPage{ + Transactions: []accessmodel.AccountTransaction{}, + } + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.AccountTransactionCursor)(nil), + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{Result: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{expand: "result"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid address", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountTransactionsURL(t, "invalid", accountTransactionsURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid address") + }) + + t.Run("invalid cursor format", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{cursor: "badcursor"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("backend returns not found", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.AccountTransactionCursor)(nil), + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.NotFound, "no transactions found for account %s", address)) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusNotFound, rr.Code) + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.AccountTransactionCursor)(nil), + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) + + t.Run("invalid limit", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + reqURL := accountTransactionsURL(t, address.String(), accountTransactionsURLParams{limit: "abc"}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid limit") + }) +} + +func TestParseCursorRoundtrip(t *testing.T) { + // Verify that addresses are properly validated + t.Run("address with 0x prefix works", func(t *testing.T) { + address := unittest.AddressFixture() + txID := unittest.IdentifierFixture() + backend := extendedmock.NewAPI(t) + + page := &accessmodel.AccountTransactionsPage{ + Transactions: []accessmodel.AccountTransaction{ + { + Address: address, + BlockHeight: 100, + TransactionID: txID, + TransactionIndex: 0, + Roles: []accessmodel.TransactionRole{accessmodel.TransactionRoleAuthorizer}, + }, + }, + } + + backend.On("GetAccountTransactions", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.AccountTransactionCursor)(nil), + extended.AccountTransactionFilter{}, + extended.AccountTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + reqURL := accountTransactionsURL(t, "0x"+address.String(), accountTransactionsURLParams{}) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + assert.Equal(t, http.StatusOK, rr.Code) + }) +} diff --git a/engine/access/rest/experimental/routes/contracts.go b/engine/access/rest/experimental/routes/contracts.go new file mode 100644 index 00000000000..28f41500683 --- /dev/null +++ b/engine/access/rest/experimental/routes/contracts.go @@ -0,0 +1,167 @@ +package routes + +import ( + "net/http" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/experimental/models" + "github.com/onflow/flow-go/engine/access/rest/experimental/request" + accessmodel "github.com/onflow/flow-go/model/access" +) + +// GetContracts handles GET /experimental/v1/contracts. +func GetContracts(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetContracts(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + page, err := backend.GetContracts( + r.Context(), + req.Limit, + req.Cursor, + req.Filter, + req.ExpandOptions, + entities.EventEncodingVersion_JSON_CDC_V0, + ) + if err != nil { + return nil, err + } + + return buildContractsResponse(page, link, r.ExpandFields) +} + +// GetContract handles GET /experimental/v1/contracts/{identifier}. +func GetContract(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetContract(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + deployment, err := backend.GetContract( + r.Context(), + req.ID, + req.Filter, + req.ExpandOptions, + entities.EventEncodingVersion_JSON_CDC_V0, + ) + if err != nil { + return nil, err + } + + var m models.ContractDeployment + err = m.Build(deployment, link, r.ExpandFields) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to build contract deployment", err) + } + return m, nil +} + +// GetContractDeployments handles GET /experimental/v1/contracts/{identifier}/deployments. +func GetContractDeployments(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetContractDeployments(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + page, err := backend.GetContractDeployments( + r.Context(), + req.ID, + req.Limit, + req.Cursor, + req.Filter, + req.ExpandOptions, + entities.EventEncodingVersion_JSON_CDC_V0, + ) + if err != nil { + return nil, err + } + + return buildContractDeploymentsResponse(page, link, r.ExpandFields) +} + +// GetContractsByAddress handles GET /experimental/v1/accounts/{address}/contracts. +func GetContractsByAddress(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetContractsByAddress(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + page, err := backend.GetContractsByAddress( + r.Context(), + req.Address, + req.Limit, + req.Cursor, + req.Filter, + req.ExpandOptions, + entities.EventEncodingVersion_JSON_CDC_V0, + ) + if err != nil { + return nil, err + } + + return buildContractsResponse(page, link, r.ExpandFields) +} + +// buildContractDeploymentsResponse converts a [accessmodel.ContractDeploymentPage] to a +// [models.ContractDeploymentsResponse] for the deployment history endpoint. +func buildContractDeploymentsResponse( + page *accessmodel.ContractDeploymentPage, + link models.LinkGenerator, + expand map[string]bool, +) (models.ContractDeploymentsResponse, error) { + deployments := make([]models.ContractDeployment, len(page.Deployments)) + for i := range page.Deployments { + err := deployments[i].Build(&page.Deployments[i], link, expand) + if err != nil { + return models.ContractDeploymentsResponse{}, common.NewRestError(http.StatusInternalServerError, "failed to build deployment", err) + } + } + + var nextCursor string + if page.NextCursor != nil { + var err error + nextCursor, err = request.EncodeContractDeploymentsCursor(page.NextCursor) + if err != nil { + return models.ContractDeploymentsResponse{}, common.NewRestError(http.StatusInternalServerError, "failed to encode next cursor", err) + } + } + + return models.ContractDeploymentsResponse{ + Deployments: deployments, + NextCursor: nextCursor, + }, nil +} + +// buildContractsResponse converts a [accessmodel.ContractDeploymentPage] to a [models.ContractsResponse] +// for the list and by-address endpoints. +func buildContractsResponse( + page *accessmodel.ContractDeploymentPage, + link models.LinkGenerator, + expand map[string]bool, +) (models.ContractsResponse, error) { + contracts := make([]models.ContractDeployment, len(page.Deployments)) + for i := range page.Deployments { + err := contracts[i].Build(&page.Deployments[i], link, expand) + if err != nil { + return models.ContractsResponse{}, common.NewRestError(http.StatusInternalServerError, "failed to build deployment", err) + } + } + + var nextCursor string + if page.NextCursor != nil { + var err error + nextCursor, err = request.EncodeContractDeploymentsCursor(page.NextCursor) + if err != nil { + return models.ContractsResponse{}, common.NewRestError(http.StatusInternalServerError, "failed to encode next cursor", err) + } + } + + return models.ContractsResponse{ + Contracts: contracts, + NextCursor: nextCursor, + }, nil +} diff --git a/engine/access/rest/experimental/routes/contracts_test.go b/engine/access/rest/experimental/routes/contracts_test.go new file mode 100644 index 00000000000..7e1f8610470 --- /dev/null +++ b/engine/access/rest/experimental/routes/contracts_test.go @@ -0,0 +1,1048 @@ +package routes_test + +import ( + "encoding/base64" + "encoding/hex" + "fmt" + "net/http" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + mocktestify "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + extendedmock "github.com/onflow/flow-go/access/backends/extended/mock" + "github.com/onflow/flow-go/engine/access/rest/experimental/request" + "github.com/onflow/flow-go/engine/access/rest/router" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" +) + +// testEncodeContractsCursor encodes a cursor using the same logic as the handler, for test inputs +// and assertions. +func testEncodeContractsCursor(t *testing.T, cursor *accessmodel.ContractDeploymentsCursor) string { + data, err := request.EncodeContractDeploymentsCursor(cursor) + require.NoError(t, err) + return data +} + +type contractsListURLParams struct { + limit string + cursor string + contractName string + startBlock string + endBlock string + expand string +} + +func contractsListURL(t *testing.T, params contractsListURLParams) string { + u, err := url.ParseRequestURI("/experimental/v1/contracts") + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.contractName != "" { + q.Add("contract_name", params.contractName) + } + if params.startBlock != "" { + q.Add("start_block", params.startBlock) + } + if params.endBlock != "" { + q.Add("end_block", params.endBlock) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +func contractURL(t *testing.T, identifier string, params contractsListURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/contracts/%s", identifier)) + require.NoError(t, err) + q := u.Query() + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +func contractDeploymentsURL(t *testing.T, identifier string, params contractsListURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/contracts/%s/deployments", identifier)) + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.contractName != "" { + q.Add("contract_name", params.contractName) + } + if params.startBlock != "" { + q.Add("start_block", params.startBlock) + } + if params.endBlock != "" { + q.Add("end_block", params.endBlock) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +func contractsByAddressURL(t *testing.T, address string, params contractsListURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/accounts/%s/contracts", address)) + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.contractName != "" { + q.Add("contract_name", params.contractName) + } + if params.startBlock != "" { + q.Add("start_block", params.startBlock) + } + if params.endBlock != "" { + q.Add("end_block", params.endBlock) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +// buildExpectedDeploymentJSON produces the expected JSON object for a ContractDeployment with +// no inline expansions: code, transaction, and result appear as expandable links. +func buildExpectedDeploymentJSON(d *accessmodel.ContractDeployment) string { + codeHashStr := hex.EncodeToString(d.CodeHash) + contractID := accessmodel.ContractID(d.Address, d.ContractName) + txID := d.TransactionID.String() + + return fmt.Sprintf(`{ + "contract_id": %q, + "address": %q, + "block_height": "%d", + "transaction_id": %q, + "tx_index": "%d", + "event_index": "%d", + "code_hash": %q, + "_expandable": { + "code": "/experimental/v1/contracts/%s?expand=code", + "transaction": "/v1/transactions/%s", + "result": "/v1/transaction_results/%s" + } + }`, + contractID, + d.Address.Hex(), + d.BlockHeight, + txID, + d.TransactionIndex, + d.EventIndex, + codeHashStr, + contractID, + txID, + txID, + ) +} + +// buildExpectedDeploymentJSONWithCode produces the expected JSON object for a ContractDeployment +// with code expanded inline (expand=code), and transaction/result as expandable links. +func buildExpectedDeploymentJSONWithCode(d *accessmodel.ContractDeployment) string { + var codeStr string + if len(d.Code) > 0 { + codeStr = base64.StdEncoding.EncodeToString(d.Code) + } + codeHashStr := hex.EncodeToString(d.CodeHash) + txID := d.TransactionID.String() + + return fmt.Sprintf(`{ + "contract_id": %q, + "address": %q, + "block_height": "%d", + "transaction_id": %q, + "tx_index": "%d", + "event_index": "%d", + "code": %q, + "code_hash": %q, + "_expandable": { + "transaction": "/v1/transactions/%s", + "result": "/v1/transaction_results/%s" + } + }`, + accessmodel.ContractID(d.Address, d.ContractName), + d.Address.Hex(), + d.BlockHeight, + txID, + d.TransactionIndex, + d.EventIndex, + codeStr, + codeHashStr, + txID, + txID, + ) +} + +func TestGetContracts(t *testing.T) { + addr1 := flow.HexToAddress("1234567890abcdef") + addr2 := flow.HexToAddress("fedcba0987654321") + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + code1 := []byte("pub contract First {}") + code2 := []byte("pub contract Second {}") + + d1 := accessmodel.ContractDeployment{ + Address: addr1, + ContractName: "First", + BlockHeight: 1000, + TransactionID: txID1, + TransactionIndex: 2, + EventIndex: 1, + Code: code1, + CodeHash: accessmodel.CadenceCodeHash(code1), + } + d2 := accessmodel.ContractDeployment{ + Address: addr2, + ContractName: "Second", + BlockHeight: 999, + TransactionID: txID2, + TransactionIndex: 0, + EventIndex: 0, + Code: code2, + CodeHash: accessmodel.CadenceCodeHash(code2), + } + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + nextCursorVal := &accessmodel.ContractDeploymentsCursor{ + Address: d2.Address, + ContractName: d2.ContractName, + BlockHeight: d2.BlockHeight, + TransactionIndex: d2.TransactionIndex, + EventIndex: d2.EventIndex, + } + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d1, d2}, + NextCursor: nextCursorVal, + } + + backend.On("GetContracts", + mocktestify.Anything, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + expectedCursor := testEncodeContractsCursor(t, nextCursorVal) + expected := fmt.Sprintf(`{ + "contracts": [%s, %s], + "next_cursor": %q + }`, + buildExpectedDeploymentJSON(&d1), + buildExpectedDeploymentJSON(&d2), + expectedCursor, + ) + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d1}, + NextCursor: nil, + } + + backend.On("GetContracts", + mocktestify.Anything, + uint32(10), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{limit: "10"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.NotContains(t, rr.Body.String(), "next_cursor") + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + inputCursor := &accessmodel.ContractDeploymentsCursor{ + Address: d1.Address, + ContractName: d1.ContractName, + BlockHeight: d1.BlockHeight, + TransactionIndex: d1.TransactionIndex, + EventIndex: d1.EventIndex, + } + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d2}, + } + + backend.On("GetContracts", + mocktestify.Anything, + uint32(0), + inputCursor, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{ + cursor: testEncodeContractsCursor(t, inputCursor), + }), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with contract_name filter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{}, + } + + backend.On("GetContracts", + mocktestify.Anything, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{ContractName: "First"}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{contractName: "First"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with start_block filter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{}, + } + + startBlock := uint64(500) + backend.On("GetContracts", + mocktestify.Anything, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{StartBlock: &startBlock}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{startBlock: "500"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid limit", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{limit: "abc"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid limit") + }) + + t.Run("invalid cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{cursor: "!notbase64!"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("invalid start_block", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{startBlock: "notanumber"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid start_block") + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetContracts", + mocktestify.Anything, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + req, err := http.NewRequest(http.MethodGet, contractsListURL(t, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) +} + +func TestGetContract(t *testing.T) { + addr := flow.HexToAddress("1234567890abcdef") + txID := unittest.IdentifierFixture() + code := []byte("pub contract MyContract {}") + codeHash := accessmodel.CadenceCodeHash(code) + + contractID := "A.1234567890abcdef.MyContract" + + t.Run("happy path - code in expandable by default", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + d := &accessmodel.ContractDeployment{ + Address: addr, + ContractName: "MyContract", + BlockHeight: 1234, + TransactionID: txID, + TransactionIndex: 5, + EventIndex: 3, + Code: code, + CodeHash: codeHash, + } + + backend.On("GetContract", + mocktestify.Anything, + contractID, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(d, nil) + + req, err := http.NewRequest(http.MethodGet, contractURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.JSONEq(t, buildExpectedDeploymentJSON(d), rr.Body.String()) + }) + + t.Run("expand=code includes code inline", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + d := &accessmodel.ContractDeployment{ + Address: addr, + ContractName: "MyContract", + BlockHeight: 1234, + TransactionID: txID, + TransactionIndex: 5, + EventIndex: 3, + Code: code, + CodeHash: codeHash, + } + + backend.On("GetContract", + mocktestify.Anything, + contractID, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{Code: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(d, nil) + + req, err := http.NewRequest(http.MethodGet, contractURL(t, contractID, contractsListURLParams{expand: "code"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.JSONEq(t, buildExpectedDeploymentJSONWithCode(d), rr.Body.String()) + }) + + t.Run("happy path - code not loaded by backend", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + d := &accessmodel.ContractDeployment{ + Address: addr, + ContractName: "MyContract", + BlockHeight: 1234, + TransactionID: txID, + TransactionIndex: 5, + EventIndex: 3, + Code: nil, + CodeHash: codeHash, + } + + backend.On("GetContract", + mocktestify.Anything, + contractID, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(d, nil) + + req, err := http.NewRequest(http.MethodGet, contractURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.JSONEq(t, buildExpectedDeploymentJSON(d), rr.Body.String()) + }) + + t.Run("placeholder deployment", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + d := &accessmodel.ContractDeployment{ + Address: addr, + ContractName: "MyContract", + Code: code, + CodeHash: codeHash, + IsPlaceholder: true, + // BlockHeight, TransactionID, TransactionIndex, EventIndex are zero values + } + + backend.On("GetContract", + mocktestify.Anything, + contractID, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(d, nil) + + req, err := http.NewRequest(http.MethodGet, contractURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + // Placeholder deployments have is_placeholder=true, no transaction/result links, and code is expandable. + codeHashStr := hex.EncodeToString(codeHash) + expected := fmt.Sprintf(`{ + "contract_id": %q, + "address": %q, + "block_height": "0", + "transaction_id": "0000000000000000000000000000000000000000000000000000000000000000", + "tx_index": "0", + "event_index": "0", + "code_hash": %q, + "is_placeholder": true, + "_expandable": { + "code": "/experimental/v1/contracts/%s?expand=code" + } + }`, contractID, addr.Hex(), codeHashStr, contractID) + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("backend returns not found", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetContract", + mocktestify.Anything, + contractID, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.NotFound, "contract %s not found", contractID)) + + req, err := http.NewRequest(http.MethodGet, contractURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusNotFound, rr.Code) + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetContract", + mocktestify.Anything, + contractID, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + req, err := http.NewRequest(http.MethodGet, contractURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) +} + +func TestGetContractDeployments(t *testing.T) { + addr := flow.HexToAddress("1234567890abcdef") + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + code := []byte("pub contract MyContract {}") + + contractID := "A.1234567890abcdef.MyContract" + + d1 := accessmodel.ContractDeployment{ + Address: addr, + ContractName: "MyContract", + BlockHeight: 2000, + TransactionID: txID1, + TransactionIndex: 1, + EventIndex: 0, + Code: code, + CodeHash: accessmodel.CadenceCodeHash(code), + } + d2 := accessmodel.ContractDeployment{ + Address: addr, + ContractName: "MyContract", + BlockHeight: 1000, + TransactionID: txID2, + TransactionIndex: 3, + EventIndex: 2, + Code: code, + CodeHash: accessmodel.CadenceCodeHash(code), + } + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + // For DeploymentsByContractID, the contract is identified by the URL; Address and + // ContractName are populated from the storage key but not used for resumption. + nextCursorVal := &accessmodel.ContractDeploymentsCursor{ + Address: d2.Address, + ContractName: d2.ContractName, + BlockHeight: d2.BlockHeight, + TransactionIndex: d2.TransactionIndex, + EventIndex: d2.EventIndex, + } + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d1, d2}, + NextCursor: nextCursorVal, + } + + backend.On("GetContractDeployments", + mocktestify.Anything, + contractID, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractDeploymentsURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + expectedCursor := testEncodeContractsCursor(t, nextCursorVal) + expected := fmt.Sprintf(`{ + "deployments": [%s, %s], + "next_cursor": %q + }`, + buildExpectedDeploymentJSON(&d1), + buildExpectedDeploymentJSON(&d2), + expectedCursor, + ) + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d1}, + NextCursor: nil, + } + + backend.On("GetContractDeployments", + mocktestify.Anything, + contractID, + uint32(5), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractDeploymentsURL(t, contractID, contractsListURLParams{limit: "5"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.NotContains(t, rr.Body.String(), "next_cursor") + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + // DeploymentsByContractID cursors include Address and ContractName from the storage key. + inputCursor := &accessmodel.ContractDeploymentsCursor{ + Address: d1.Address, + ContractName: d1.ContractName, + BlockHeight: d1.BlockHeight, + TransactionIndex: d1.TransactionIndex, + EventIndex: d1.EventIndex, + } + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d2}, + } + + backend.On("GetContractDeployments", + mocktestify.Anything, + contractID, + uint32(0), + inputCursor, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractDeploymentsURL(t, contractID, contractsListURLParams{ + cursor: testEncodeContractsCursor(t, inputCursor), + }), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid limit", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractDeploymentsURL(t, contractID, contractsListURLParams{limit: "abc"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid limit") + }) + + t.Run("invalid cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractDeploymentsURL(t, contractID, contractsListURLParams{cursor: "badcursor"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("backend returns not found", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetContractDeployments", + mocktestify.Anything, + contractID, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.NotFound, "contract %s not found", contractID)) + + req, err := http.NewRequest(http.MethodGet, contractDeploymentsURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusNotFound, rr.Code) + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetContractDeployments", + mocktestify.Anything, + contractID, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + req, err := http.NewRequest(http.MethodGet, contractDeploymentsURL(t, contractID, contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) +} + +func TestGetContractsByAddress(t *testing.T) { + address := unittest.AddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + code := []byte("pub contract MyContract {}") + + d1 := accessmodel.ContractDeployment{ + Address: address, + ContractName: "First", + BlockHeight: 1500, + TransactionID: txID1, + TransactionIndex: 0, + EventIndex: 0, + Code: code, + CodeHash: accessmodel.CadenceCodeHash(code), + } + d2 := accessmodel.ContractDeployment{ + Address: address, + ContractName: "Second", + BlockHeight: 1400, + TransactionID: txID2, + TransactionIndex: 1, + EventIndex: 0, + Code: code, + CodeHash: accessmodel.CadenceCodeHash(code), + } + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + nextCursorVal := &accessmodel.ContractDeploymentsCursor{ + Address: d2.Address, + ContractName: d2.ContractName, + BlockHeight: d2.BlockHeight, + TransactionIndex: d2.TransactionIndex, + EventIndex: d2.EventIndex, + } + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d1, d2}, + NextCursor: nextCursorVal, + } + + backend.On("GetContractsByAddress", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, address.String(), contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + expectedCursor := testEncodeContractsCursor(t, nextCursorVal) + expected := fmt.Sprintf(`{ + "contracts": [%s, %s], + "next_cursor": %q + }`, + buildExpectedDeploymentJSON(&d1), + buildExpectedDeploymentJSON(&d2), + expectedCursor, + ) + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d1}, + NextCursor: nil, + } + + backend.On("GetContractsByAddress", + mocktestify.Anything, + address, + uint32(3), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, address.String(), contractsListURLParams{limit: "3"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.NotContains(t, rr.Body.String(), "next_cursor") + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + // ByAddress cursors include Address and ContractName as the resume key. + inputCursor := &accessmodel.ContractDeploymentsCursor{ + Address: d1.Address, + ContractName: d1.ContractName, + BlockHeight: d1.BlockHeight, + TransactionIndex: d1.TransactionIndex, + EventIndex: d1.EventIndex, + } + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d2}, + } + + backend.On("GetContractsByAddress", + mocktestify.Anything, + address, + uint32(0), + inputCursor, + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, address.String(), contractsListURLParams{ + cursor: testEncodeContractsCursor(t, inputCursor), + }), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("address with 0x prefix", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ContractDeploymentPage{ + Deployments: []accessmodel.ContractDeployment{d1}, + } + + backend.On("GetContractsByAddress", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, "0x"+address.String(), contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid address", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, "invalid", contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid address") + }) + + t.Run("invalid cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, address.String(), contractsListURLParams{cursor: "!notbase64!"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("invalid limit", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, address.String(), contractsListURLParams{limit: "abc"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid limit") + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetContractsByAddress", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.ContractDeploymentsCursor)(nil), + extended.ContractDeploymentFilter{}, + extended.ContractDeploymentExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + req, err := http.NewRequest(http.MethodGet, contractsByAddressURL(t, address.String(), contractsListURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) +} diff --git a/engine/access/rest/experimental/routes/scheduled_transactions.go b/engine/access/rest/experimental/routes/scheduled_transactions.go new file mode 100644 index 00000000000..ca06e60779e --- /dev/null +++ b/engine/access/rest/experimental/routes/scheduled_transactions.go @@ -0,0 +1,113 @@ +package routes + +import ( + "net/http" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/experimental/models" + "github.com/onflow/flow-go/engine/access/rest/experimental/request" + accessmodel "github.com/onflow/flow-go/model/access" +) + +// GetScheduledTransactions handles GET /scheduled. +func GetScheduledTransactions(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetScheduledTransactions(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + page, err := backend.GetScheduledTransactions( + r.Context(), + req.Limit, + req.Cursor, + req.Filter, + req.ExpandOptions, + entities.EventEncodingVersion_JSON_CDC_V0, + ) + if err != nil { + return nil, err + } + + return buildScheduledTransactionsResponse(page, link, r.ExpandFields) +} + +// GetScheduledTransaction handles GET /scheduled/transaction/{id}. +func GetScheduledTransaction(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetScheduledTransaction(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + tx, err := backend.GetScheduledTransaction( + r.Context(), + req.ID, + req.ExpandOptions, + entities.EventEncodingVersion_JSON_CDC_V0, + ) + if err != nil { + return nil, err + } + + var m models.ScheduledTransaction + err = m.Build(tx, link, r.ExpandFields) + if err != nil { + return nil, common.NewRestError(http.StatusInternalServerError, "failed to build scheduled transaction", err) + } + return m, nil +} + +// GetScheduledTransactionsByAddress handles GET /accounts/{address}/scheduled. +func GetScheduledTransactionsByAddress(r *common.Request, backend extended.API, link models.LinkGenerator) (interface{}, error) { + req, err := request.NewGetScheduledTransactionsByAddress(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + page, err := backend.GetScheduledTransactionsByAddress( + r.Context(), + req.Address, + req.Limit, + req.Cursor, + req.Filter, + req.ExpandOptions, + entities.EventEncodingVersion_JSON_CDC_V0, + ) + if err != nil { + return nil, err + } + + return buildScheduledTransactionsResponse(page, link, r.ExpandFields) +} + +// buildScheduledTransactionsResponse converts a [accessmodel.ScheduledTransactionsPage] to a REST +// response, encoding the next cursor if present. +func buildScheduledTransactionsResponse( + page *accessmodel.ScheduledTransactionsPage, + link models.LinkGenerator, + expandMap map[string]bool, +) (models.ScheduledTransactionsResponse, error) { + scheduledTransactions := make([]models.ScheduledTransaction, len(page.Transactions)) + for i := range page.Transactions { + err := scheduledTransactions[i].Build(&page.Transactions[i], link, expandMap) + if err != nil { + return models.ScheduledTransactionsResponse{}, common.NewRestError(http.StatusInternalServerError, "failed to build scheduled transaction", err) + } + } + + var nextCursor string + if page.NextCursor != nil { + var err error + nextCursor, err = request.EncodeScheduledTxCursor(page.NextCursor) + if err != nil { + return models.ScheduledTransactionsResponse{}, common.NewRestError(http.StatusInternalServerError, "failed to encode next cursor", err) + } + } + + return models.ScheduledTransactionsResponse{ + ScheduledTransactions: scheduledTransactions, + NextCursor: nextCursor, + }, nil +} diff --git a/engine/access/rest/experimental/routes/scheduled_transactions_test.go b/engine/access/rest/experimental/routes/scheduled_transactions_test.go new file mode 100644 index 00000000000..5376c320031 --- /dev/null +++ b/engine/access/rest/experimental/routes/scheduled_transactions_test.go @@ -0,0 +1,692 @@ +package routes_test + +import ( + "fmt" + "net/http" + "net/url" + "testing" + "time" + + "github.com/stretchr/testify/assert" + mocktestify "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow/protobuf/go/flow/entities" + + "github.com/onflow/flow-go/access/backends/extended" + extendedmock "github.com/onflow/flow-go/access/backends/extended/mock" + "github.com/onflow/flow-go/engine/access/rest/experimental/request" + "github.com/onflow/flow-go/engine/access/rest/router" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" +) + +type scheduledTxURLParams struct { + limit string + cursor string + status string + expand string +} + +func scheduledTxsURL(t *testing.T, params scheduledTxURLParams) string { + u, err := url.ParseRequestURI("/experimental/v1/scheduled") + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.status != "" { + q.Add("status", params.status) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +func scheduledTxByIDURL(t *testing.T, id uint64, params scheduledTxURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/scheduled/transaction/%d", id)) + require.NoError(t, err) + if params.expand != "" { + q := u.Query() + q.Add("expand", params.expand) + u.RawQuery = q.Encode() + } + return u.String() +} + +func scheduledTxsByAddrURL(t *testing.T, address string, params scheduledTxURLParams) string { + u, err := url.ParseRequestURI(fmt.Sprintf("/experimental/v1/accounts/%s/scheduled", address)) + require.NoError(t, err) + q := u.Query() + if params.limit != "" { + q.Add("limit", params.limit) + } + if params.cursor != "" { + q.Add("cursor", params.cursor) + } + if params.status != "" { + q.Add("status", params.status) + } + if params.expand != "" { + q.Add("expand", params.expand) + } + u.RawQuery = q.Encode() + return u.String() +} + +// testEncodeScheduledTxCursor encodes a cursor the same way the handler does, for use in +// test assertions and inputs. +func testEncodeScheduledTxCursor(t *testing.T, id uint64) string { + data, err := request.EncodeScheduledTxCursor(&accessmodel.ScheduledTransactionCursor{ID: id}) + require.NoError(t, err) + return data +} + +func TestGetScheduledTransactions(t *testing.T) { + handlerOwner := unittest.AddressFixture() + + tx1CreatedAt := uint64(1700000000000) // Unix ms + tx1CreatedID := unittest.IdentifierFixture() + tx1 := accessmodel.ScheduledTransaction{ + ID: 100, + Priority: 0, // high + Timestamp: 1000000, + ExecutionEffort: 500, + Fees: 250, + TransactionHandlerOwner: handlerOwner, + TransactionHandlerTypeIdentifier: "A.0000.MyScheduler.Handler", + TransactionHandlerUUID: 7, + Status: accessmodel.ScheduledTxStatusScheduled, + CreatedTransactionID: tx1CreatedID, + CreatedAt: tx1CreatedAt, + } + tx2CreatedAt := uint64(1699999000000) // Unix ms + tx2CompletedAt := uint64(1700001000000) // Unix ms + tx2CreatedID := unittest.IdentifierFixture() + tx2ExecutedID := unittest.IdentifierFixture() + tx2 := accessmodel.ScheduledTransaction{ + ID: 99, + Priority: 1, // medium + Timestamp: 999000, + ExecutionEffort: 200, + Fees: 100, + TransactionHandlerOwner: handlerOwner, + TransactionHandlerTypeIdentifier: "A.0000.MyScheduler.Handler", + TransactionHandlerUUID: 8, + Status: accessmodel.ScheduledTxStatusExecuted, + CreatedTransactionID: tx2CreatedID, + ExecutedTransactionID: tx2ExecutedID, + CreatedAt: tx2CreatedAt, + CompletedAt: tx2CompletedAt, + } + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{tx1, tx2}, + NextCursor: &accessmodel.ScheduledTransactionCursor{ID: 99}, + } + + backend.On("GetScheduledTransactions", + mocktestify.Anything, + uint32(0), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + expectedNextCursor := testEncodeScheduledTxCursor(t, 99) + tx1CreatedAtStr := time.UnixMilli(int64(tx1CreatedAt)).UTC().Format(time.RFC3339Nano) + tx2CreatedAtStr := time.UnixMilli(int64(tx2CreatedAt)).UTC().Format(time.RFC3339Nano) + tx2CompletedAtStr := time.UnixMilli(int64(tx2CompletedAt)).UTC().Format(time.RFC3339Nano) + expected := fmt.Sprintf(`{ + "scheduled_transactions": [ + { + "id": "100", + "status": "scheduled", + "priority": "high", + "timestamp": "1000000", + "execution_effort": "500", + "fees": "250", + "transaction_handler_owner": "%s", + "transaction_handler_type_identifier": "A.0000.MyScheduler.Handler", + "transaction_handler_uuid": "7", + "created_transaction_id": "%s", + "created_at": "%s", + "_expandable": { + "handler_contract": "/experimental/v1/contracts/A.0000.MyScheduler?expand=code" + } + }, + { + "id": "99", + "status": "executed", + "priority": "medium", + "timestamp": "999000", + "execution_effort": "200", + "fees": "100", + "transaction_handler_owner": "%s", + "transaction_handler_type_identifier": "A.0000.MyScheduler.Handler", + "transaction_handler_uuid": "8", + "created_transaction_id": "%s", + "executed_transaction_id": "%s", + "created_at": "%s", + "completed_at": "%s", + "_expandable": { + "handler_contract": "/experimental/v1/contracts/A.0000.MyScheduler?expand=code", + "transaction": "/v1/transactions/%s", + "result": "/v1/transaction_results/%s" + } + } + ], + "next_cursor": "%s" + }`, handlerOwner.String(), tx1CreatedID.String(), tx1CreatedAtStr, + handlerOwner.String(), tx2CreatedID.String(), tx2ExecutedID.String(), tx2CreatedAtStr, tx2CompletedAtStr, + tx2ExecutedID.String(), tx2ExecutedID.String(), expectedNextCursor) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{tx1}, + } + + backend.On("GetScheduledTransactions", + mocktestify.Anything, + uint32(10), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{limit: "10"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.NotContains(t, rr.Body.String(), "next_cursor") + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{tx2}, + } + + backend.On("GetScheduledTransactions", + mocktestify.Anything, + uint32(0), + &accessmodel.ScheduledTransactionCursor{ID: 100}, + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{ + cursor: testEncodeScheduledTxCursor(t, 100), + }), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("with status filter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{}, + } + + backend.On("GetScheduledTransactions", + mocktestify.Anything, + uint32(0), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{ + Statuses: []accessmodel.ScheduledTransactionStatus{accessmodel.ScheduledTxStatusScheduled}, + }, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{status: "scheduled"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid limit", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{limit: "abc"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid limit") + }) + + t.Run("invalid cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{cursor: "!notbase64!"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("invalid status", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{status: "unknown"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid status") + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetScheduledTransactions", + mocktestify.Anything, + uint32(0), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsURL(t, scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) +} + +func TestGetScheduledTransaction(t *testing.T) { + handlerOwner := unittest.AddressFixture() + + txCreatedID := unittest.IdentifierFixture() + tx := &accessmodel.ScheduledTransaction{ + ID: 42, + Priority: 0, // high + Timestamp: 2000000, + ExecutionEffort: 750, + Fees: 300, + TransactionHandlerOwner: handlerOwner, + TransactionHandlerTypeIdentifier: "A.0000.MyScheduler.Handler", + TransactionHandlerUUID: 3, + Status: accessmodel.ScheduledTxStatusScheduled, + CreatedTransactionID: txCreatedID, + } + + t.Run("happy path", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetScheduledTransaction", + mocktestify.Anything, + uint64(42), + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(tx, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxByIDURL(t, 42, scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + expected := fmt.Sprintf(`{ + "id": "42", + "status": "scheduled", + "priority": "high", + "timestamp": "2000000", + "execution_effort": "750", + "fees": "300", + "transaction_handler_owner": "%s", + "transaction_handler_type_identifier": "A.0000.MyScheduler.Handler", + "transaction_handler_uuid": "3", + "created_transaction_id": "%s", + "_expandable": { + "handler_contract": "/experimental/v1/contracts/A.0000.MyScheduler?expand=code" + } + }`, handlerOwner.String(), txCreatedID.String()) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("invalid ID - non-numeric", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, "/experimental/v1/scheduled/transaction/notanumber", nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid scheduled transaction ID") + }) + + t.Run("with handler_contract expand", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + txWithContract := &accessmodel.ScheduledTransaction{ + ID: 42, + Priority: 0, + Timestamp: 2000000, + ExecutionEffort: 750, + Fees: 300, + TransactionHandlerOwner: handlerOwner, + TransactionHandlerTypeIdentifier: "A.0000.MyScheduler.Handler", + TransactionHandlerUUID: 3, + Status: accessmodel.ScheduledTxStatusScheduled, + CreatedTransactionID: txCreatedID, + HandlerContract: &accessmodel.ContractDeployment{ + Address: flow.HexToAddress("0000"), + ContractName: "MyScheduler", + Code: []byte("pub contract MyScheduler {}"), + CodeHash: accessmodel.CadenceCodeHash([]byte("pub contract MyScheduler {}")), + }, + } + + backend.On("GetScheduledTransaction", + mocktestify.Anything, + uint64(42), + extended.ScheduledTransactionExpandOptions{HandlerContract: true}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(txWithContract, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxByIDURL(t, 42, scheduledTxURLParams{expand: "handler_contract"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + + expected := fmt.Sprintf(`{ + "id": "42", + "status": "scheduled", + "priority": "high", + "timestamp": "2000000", + "execution_effort": "750", + "fees": "300", + "transaction_handler_owner": "%s", + "transaction_handler_type_identifier": "A.0000.MyScheduler.Handler", + "transaction_handler_uuid": "3", + "created_transaction_id": "%s", + "handler_contract": { + "contract_id": "A.0000000000000000.MyScheduler", + "address": "0000000000000000", + "block_height": "0", + "transaction_id": "0000000000000000000000000000000000000000000000000000000000000000", + "tx_index": "0", + "event_index": "0", + "code": "cHViIGNvbnRyYWN0IE15U2NoZWR1bGVyIHt9", + "code_hash": "383198cd7e974ca055c4137bdd1fa44934882f569e7f0c353254e0e7ce8a50fb", + "_expandable": { + "transaction": "/v1/transactions/0000000000000000000000000000000000000000000000000000000000000000", + "result": "/v1/transaction_results/0000000000000000000000000000000000000000000000000000000000000000" + } + }, + "_expandable": {} + }`, handlerOwner.String(), txCreatedID.String()) + + assert.JSONEq(t, expected, rr.Body.String()) + }) + + t.Run("backend returns not found", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetScheduledTransaction", + mocktestify.Anything, + uint64(999), + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.NotFound, "scheduled transaction 999 not found")) + + req, err := http.NewRequest(http.MethodGet, scheduledTxByIDURL(t, 999, scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusNotFound, rr.Code) + }) +} + +func TestGetScheduledTransactionsByAddress(t *testing.T) { + address := unittest.AddressFixture() + handlerOwner := unittest.AddressFixture() + + tx1CreatedID := unittest.IdentifierFixture() + tx1 := accessmodel.ScheduledTransaction{ + ID: 50, + Priority: 0, // high + Timestamp: 5000000, + ExecutionEffort: 300, + Fees: 150, + TransactionHandlerOwner: handlerOwner, + TransactionHandlerTypeIdentifier: "A.0000.MyScheduler.Handler", + TransactionHandlerUUID: 5, + Status: accessmodel.ScheduledTxStatusScheduled, + CreatedTransactionID: tx1CreatedID, + } + tx2CreatedID := unittest.IdentifierFixture() + tx2CancelledID := unittest.IdentifierFixture() + tx2 := accessmodel.ScheduledTransaction{ + ID: 49, + Priority: 2, // low + Timestamp: 4500000, + ExecutionEffort: 100, + Fees: 50, + TransactionHandlerOwner: handlerOwner, + TransactionHandlerTypeIdentifier: "A.0000.MyScheduler.Handler", + TransactionHandlerUUID: 6, + Status: accessmodel.ScheduledTxStatusCancelled, + CreatedTransactionID: tx2CreatedID, + CancelledTransactionID: tx2CancelledID, + } + + t.Run("happy path with next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{tx1, tx2}, + NextCursor: &accessmodel.ScheduledTransactionCursor{ID: 49}, + } + + backend.On("GetScheduledTransactionsByAddress", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, address.String(), scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.Contains(t, rr.Body.String(), testEncodeScheduledTxCursor(t, 49)) + }) + + t.Run("last page without next cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{tx1}, + } + + backend.On("GetScheduledTransactionsByAddress", + mocktestify.Anything, + address, + uint32(5), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, address.String(), scheduledTxURLParams{limit: "5"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusOK, rr.Code) + assert.NotContains(t, rr.Body.String(), "next_cursor") + }) + + t.Run("with cursor parameter", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{tx2}, + } + + backend.On("GetScheduledTransactionsByAddress", + mocktestify.Anything, + address, + uint32(0), + &accessmodel.ScheduledTransactionCursor{ID: 50}, + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, address.String(), scheduledTxURLParams{ + cursor: testEncodeScheduledTxCursor(t, 50), + }), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("address with 0x prefix", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + page := &accessmodel.ScheduledTransactionsPage{ + Transactions: []accessmodel.ScheduledTransaction{tx1}, + } + + backend.On("GetScheduledTransactionsByAddress", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(page, nil) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, "0x"+address.String(), scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + assert.Equal(t, http.StatusOK, rr.Code) + }) + + t.Run("invalid address", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, "invalid", scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid address") + }) + + t.Run("invalid cursor", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, address.String(), scheduledTxURLParams{cursor: "badcursor"}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "invalid cursor encoding") + }) + + t.Run("backend returns not found", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetScheduledTransactionsByAddress", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.NotFound, "no transactions for address %s", address)) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, address.String(), scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusNotFound, rr.Code) + }) + + t.Run("backend returns failed precondition", func(t *testing.T) { + backend := extendedmock.NewAPI(t) + + backend.On("GetScheduledTransactionsByAddress", + mocktestify.Anything, + address, + uint32(0), + (*accessmodel.ScheduledTransactionCursor)(nil), + extended.ScheduledTransactionFilter{}, + extended.ScheduledTransactionExpandOptions{}, + entities.EventEncodingVersion_JSON_CDC_V0, + ).Return(nil, status.Errorf(codes.FailedPrecondition, "index not initialized")) + + req, err := http.NewRequest(http.MethodGet, scheduledTxsByAddrURL(t, address.String(), scheduledTxURLParams{}), nil) + require.NoError(t, err) + + rr := router.ExecuteExperimentalRequest(req, backend) + + assert.Equal(t, http.StatusBadRequest, rr.Code) + assert.Contains(t, rr.Body.String(), "Precondition failed") + }) +} diff --git a/engine/access/rest/http/handler.go b/engine/access/rest/http/handler.go index eb634806f16..c1a0059edee 100644 --- a/engine/access/rest/http/handler.go +++ b/engine/access/rest/http/handler.go @@ -18,7 +18,7 @@ type ApiHandlerFunc func( r *common.Request, backend access.API, generator models.LinkGenerator, -) (interface{}, error) +) (any, error) // Handler is custom http handler implementing custom handler function. // Handler function allows easier handling of errors and responses as it diff --git a/engine/access/rest/http/request/get_execution_receipt.go b/engine/access/rest/http/request/get_execution_receipt.go new file mode 100644 index 00000000000..83c915e6e98 --- /dev/null +++ b/engine/access/rest/http/request/get_execution_receipt.go @@ -0,0 +1,54 @@ +package request + +import ( + "fmt" + + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/engine/access/rest/common/parser" + "github.com/onflow/flow-go/model/flow" +) + +// GetExecutionReceiptsByBlockID holds the parsed block_id query parameter for +// retrieving execution receipts by block ID. +type GetExecutionReceiptsByBlockID struct { + BlockID flow.Identifier +} + +// GetExecutionReceiptsByBlockIDRequest extracts necessary variables from the provided request, +// builds a GetExecutionReceiptsByBlockID instance, and validates it. +// +// No errors are expected during normal operation. +func GetExecutionReceiptsByBlockIDRequest(r *common.Request) (GetExecutionReceiptsByBlockID, error) { + var req GetExecutionReceiptsByBlockID + err := req.Build(r) + return req, err +} + +func (g *GetExecutionReceiptsByBlockID) Build(r *common.Request) error { + rawID := r.GetQueryParam(blockIDQuery) + if rawID == "" { + return fmt.Errorf("block_id query parameter is required") + } + var id parser.ID + if err := id.Parse(rawID); err != nil { + return err + } + g.BlockID = id.Flow() + return nil +} + +// GetExecutionReceiptsByResultID holds the parsed result ID path parameter for +// retrieving execution receipts by execution result ID. +type GetExecutionReceiptsByResultID struct { + GetByIDRequest +} + +// GetExecutionReceiptsByResultIDRequest extracts necessary variables from the provided request, +// builds a GetExecutionReceiptsByResultID instance, and validates it. +// +// No errors are expected during normal operation. +func GetExecutionReceiptsByResultIDRequest(r *common.Request) (GetExecutionReceiptsByResultID, error) { + var req GetExecutionReceiptsByResultID + err := req.Build(r) + return req, err +} diff --git a/engine/access/rest/http/request/get_transaction.go b/engine/access/rest/http/request/get_transaction.go index 060adf605c4..807aa6d9934 100644 --- a/engine/access/rest/http/request/get_transaction.go +++ b/engine/access/rest/http/request/get_transaction.go @@ -64,6 +64,57 @@ func (g *GetTransaction) Build(r *common.Request) error { return err } +// GetTransactionsByBlock represents a request to get transactions by +// a block ID, and contains the parsed and validated input parameters. +type GetTransactionsByBlock struct { + TransactionOptionals + BlockHeight uint64 + ExpandsResult bool +} + +// NewGetTransactionsByBlockRequest extracts necessary variables from the provided request, +// builds a GetTransactionsByBlock instance, and validates it. +// +// All errors indicate a malformed request. +func NewGetTransactionsByBlockRequest(r *common.Request) (*GetTransactionsByBlock, error) { + req, err := parseGetTransactionsByBlock(r) + if err != nil { + return nil, err + } + + return req, nil +} + +// parseGetTransactionsByBlock parses raw query and body parameters from an incoming request +// and constructs a validated GetTransactionsByBlock instance. +// +// All errors indicate the request is invalid. +func parseGetTransactionsByBlock(r *common.Request) (*GetTransactionsByBlock, error) { + var req GetTransactionsByBlock + err := req.TransactionOptionals.Parse(r) + if err != nil { + return nil, err + } + + var height Height + err = height.Parse(r.GetQueryParam(blockHeightQuery)) + if err != nil { + return nil, err + } + req.BlockHeight = height.Flow() + req.ExpandsResult = r.Expands(resultExpandable) + + if req.BlockHeight == EmptyHeight && req.BlockID == flow.ZeroID { + req.BlockHeight = SealedHeight + } + + if req.BlockHeight != EmptyHeight && req.BlockID != flow.ZeroID { + return nil, fmt.Errorf("can not provide both block ID and block height") + } + + return &req, err +} + type GetTransactionResult struct { GetByIDRequest TransactionOptionals @@ -90,6 +141,55 @@ func (g *GetTransactionResult) Build(r *common.Request) error { return err } +// GetTransactionResultsByBlock represents a request to get transaction results by +// block ID or height, and contains the parsed and validated input parameters. +type GetTransactionResultsByBlock struct { + TransactionOptionals + BlockHeight uint64 +} + +// NewGetTransactionResultsByBlockRequest extracts necessary variables from the provided request, +// builds a GetTransactionResultsByBlock instance, and validates it. +// +// All errors indicate a malformed request. +func NewGetTransactionResultsByBlockRequest(r *common.Request) (*GetTransactionResultsByBlock, error) { + req, err := parseGetTransactionResultsByBlock(r) + if err != nil { + return nil, err + } + + return req, nil +} + +// parseGetTransactionResultsByBlock parses raw query and body parameters from an incoming request +// and constructs a validated GetTransactionResultsByBlock instance. +// +// All errors indicate the request is invalid. +func parseGetTransactionResultsByBlock(r *common.Request) (*GetTransactionResultsByBlock, error) { + var req GetTransactionResultsByBlock + err := req.TransactionOptionals.Parse(r) + if err != nil { + return nil, err + } + + var height Height + err = height.Parse(r.GetQueryParam(blockHeightQuery)) + if err != nil { + return nil, err + } + req.BlockHeight = height.Flow() + + if req.BlockHeight == EmptyHeight && req.BlockID == flow.ZeroID { + req.BlockHeight = SealedHeight + } + + if req.BlockHeight != EmptyHeight && req.BlockID != flow.ZeroID { + return nil, fmt.Errorf("can not provide both block ID and block height") + } + + return &req, err +} + // GetScheduledTransaction represents a request to get a scheduled transaction by its scheduled // transaction ID, and contains the parsed and validated input parameters. type GetScheduledTransaction struct { diff --git a/engine/access/rest/http/routes/account_balance.go b/engine/access/rest/http/routes/account_balance.go index 44afc38f164..0dd9b6d83ee 100644 --- a/engine/access/rest/http/routes/account_balance.go +++ b/engine/access/rest/http/routes/account_balance.go @@ -11,7 +11,7 @@ import ( ) // GetAccountBalance handler retrieves an account balance by address and block height and returns the response -func GetAccountBalance(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (interface{}, error) { +func GetAccountBalance(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (any, error) { req, err := request.GetAccountBalanceRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/account_keys.go b/engine/access/rest/http/routes/account_keys.go index 4b3a5647f79..4ba102dfcc3 100644 --- a/engine/access/rest/http/routes/account_keys.go +++ b/engine/access/rest/http/routes/account_keys.go @@ -12,7 +12,7 @@ import ( ) // GetAccountKeyByIndex handler retrieves an account key by address and index and returns the response -func GetAccountKeyByIndex(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (interface{}, error) { +func GetAccountKeyByIndex(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (any, error) { req, err := request.GetAccountKeyRequest(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -42,7 +42,7 @@ func GetAccountKeyByIndex(r *common.Request, backend access.API, _ commonmodels. } // GetAccountKeys handler retrieves an account keys by address and returns the response -func GetAccountKeys(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (interface{}, error) { +func GetAccountKeys(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (any, error) { req, err := request.GetAccountKeysRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/accounts.go b/engine/access/rest/http/routes/accounts.go index ade6736d4ac..5464b6ddf4f 100644 --- a/engine/access/rest/http/routes/accounts.go +++ b/engine/access/rest/http/routes/accounts.go @@ -9,7 +9,7 @@ import ( ) // GetAccount handler retrieves account by address and returns the response -func GetAccount(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetAccount(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.GetAccountRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/blocks.go b/engine/access/rest/http/routes/blocks.go index f5baea84946..65d8536aba7 100644 --- a/engine/access/rest/http/routes/blocks.go +++ b/engine/access/rest/http/routes/blocks.go @@ -16,7 +16,7 @@ import ( ) // GetBlocksByIDs gets blocks by provided ID or list of IDs. -func GetBlocksByIDs(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetBlocksByIDs(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.GetBlockByIDsRequest(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -36,7 +36,7 @@ func GetBlocksByIDs(r *common.Request, backend access.API, link commonmodels.Lin } // GetBlocksByHeight gets blocks by height. -func GetBlocksByHeight(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetBlocksByHeight(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.GetBlockRequest(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -93,7 +93,7 @@ func GetBlocksByHeight(r *common.Request, backend access.API, link commonmodels. } // GetBlockPayloadByID gets block payload by ID -func GetBlockPayloadByID(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (interface{}, error) { +func GetBlockPayloadByID(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (any, error) { req, err := request.GetBlockPayloadRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/collections.go b/engine/access/rest/http/routes/collections.go index 574ab96318d..4378b54be25 100644 --- a/engine/access/rest/http/routes/collections.go +++ b/engine/access/rest/http/routes/collections.go @@ -9,7 +9,7 @@ import ( ) // GetCollectionByID retrieves a collection by ID and builds a response -func GetCollectionByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetCollectionByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.GetCollectionRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/collections_test.go b/engine/access/rest/http/routes/collections_test.go index 990cc5596ce..aa9decf12a1 100644 --- a/engine/access/rest/http/routes/collections_test.go +++ b/engine/access/rest/http/routes/collections_test.go @@ -129,9 +129,9 @@ func TestGetCollections(t *testing.T) { { unittest.IdentifierFixture().String(), nil, - status.Errorf(codes.Internal, "block not found"), - `{"code":400,"message":"Invalid Flow request: block not found"}`, - http.StatusBadRequest, + status.Errorf(codes.Internal, "some internal error"), + `{"code":500,"message":"Invalid Flow request: some internal error"}`, + http.StatusInternalServerError, }, } diff --git a/engine/access/rest/http/routes/events.go b/engine/access/rest/http/routes/events.go index 93ea1367b3b..6e1a016ea53 100644 --- a/engine/access/rest/http/routes/events.go +++ b/engine/access/rest/http/routes/events.go @@ -15,7 +15,7 @@ const BlockQueryParam = "block_ids" const EventTypeQuery = "type" // GetEvents for the provided block range or list of block IDs filtered by type. -func GetEvents(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (interface{}, error) { +func GetEvents(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (any, error) { req, err := request.GetEventsRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/execution_receipts.go b/engine/access/rest/http/routes/execution_receipts.go new file mode 100644 index 00000000000..7fd5fd535e0 --- /dev/null +++ b/engine/access/rest/http/routes/execution_receipts.go @@ -0,0 +1,60 @@ +package routes + +import ( + "github.com/onflow/flow-go/access" + "github.com/onflow/flow-go/engine/access/rest/common" + commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" + "github.com/onflow/flow-go/engine/access/rest/http/request" +) + +// GetExecutionReceiptsByBlockID returns all execution receipts for the given block ID. +// The execution_result field is included inline when the caller sets expand=execution_result. +func GetExecutionReceiptsByBlockID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { + req, err := request.GetExecutionReceiptsByBlockIDRequest(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + receipts, err := backend.GetExecutionReceiptsByBlockID(r.Context(), req.BlockID) + if err != nil { + return nil, err + } + + expand := r.ExpandFields + responses := make([]commonmodels.ExecutionReceipt, len(receipts)) + for i, receipt := range receipts { + var response commonmodels.ExecutionReceipt + if err := response.Build(receipt, link, expand); err != nil { + return nil, err + } + responses[i] = response + } + + return responses, nil +} + +// GetExecutionReceiptsByResultID returns all execution receipts for the given execution result ID. +// The execution_result field is included inline when the caller sets expand=execution_result. +func GetExecutionReceiptsByResultID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { + req, err := request.GetExecutionReceiptsByResultIDRequest(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + receipts, err := backend.GetExecutionReceiptsByResultID(r.Context(), req.ID) + if err != nil { + return nil, err + } + + expand := r.ExpandFields + responses := make([]commonmodels.ExecutionReceipt, len(receipts)) + for i, receipt := range receipts { + var response commonmodels.ExecutionReceipt + if err := response.Build(receipt, link, expand); err != nil { + return nil, err + } + responses[i] = response + } + + return responses, nil +} diff --git a/engine/access/rest/http/routes/execution_receipts_test.go b/engine/access/rest/http/routes/execution_receipts_test.go new file mode 100644 index 00000000000..7337748e07f --- /dev/null +++ b/engine/access/rest/http/routes/execution_receipts_test.go @@ -0,0 +1,125 @@ +package routes_test + +import ( + "fmt" + "net/http" + "strings" + "testing" + + mocks "github.com/stretchr/testify/mock" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow-go/access/mock" + "github.com/onflow/flow-go/engine/access/rest/router" + "github.com/onflow/flow-go/engine/access/rest/util" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" +) + +func getReceiptsByBlockIDReq(blockID string) *http.Request { + u := fmt.Sprintf("/v1/execution_receipts?block_id=%s", blockID) + req, _ := http.NewRequest("GET", u, nil) + return req +} + +func getReceiptsByResultIDReq(resultID string) *http.Request { + u := fmt.Sprintf("/v1/execution_receipts/results/%s", resultID) + req, _ := http.NewRequest("GET", u, nil) + return req +} + +func executionReceiptExpectedStr(receipt *flow.ExecutionReceipt) string { + spocks := make([]string, len(receipt.Spocks)) + for i, spock := range receipt.Spocks { + spocks[i] = fmt.Sprintf(`"%s"`, util.ToBase64(spock)) + } + spocksStr := fmt.Sprintf("[%s]", strings.Join(spocks, ",")) + + resultID := receipt.ExecutionResult.ID() + return fmt.Sprintf(`{ + "executor_id": "%s", + "result_id": "%s", + "spocks": %s, + "executor_signature": "%s", + "_expandable": { + "execution_result": "/v1/execution_results/%s" + } + }`, + receipt.ExecutorID, + resultID, + spocksStr, + util.ToBase64(receipt.ExecutorSignature), + resultID, + ) +} + +func TestGetExecutionReceiptsByBlockID(t *testing.T) { + t.Run("get by block_id", func(t *testing.T) { + backend := &mock.API{} + blockID := unittest.IdentifierFixture() + receipt := unittest.ExecutionReceiptFixture() + + backend.Mock. + On("GetExecutionReceiptsByBlockID", mocks.Anything, blockID). + Return([]*flow.ExecutionReceipt{receipt}, nil). + Once() + + req := getReceiptsByBlockIDReq(blockID.String()) + expected := fmt.Sprintf(`[%s]`, executionReceiptExpectedStr(receipt)) + router.AssertOKResponse(t, req, expected, backend) + mocks.AssertExpectationsForObjects(t, backend) + }) + + t.Run("missing block_id parameter", func(t *testing.T) { + backend := &mock.API{} + req, _ := http.NewRequest("GET", "/v1/execution_receipts", nil) + router.AssertResponse(t, req, http.StatusBadRequest, `{"code":400,"message":"block_id query parameter is required"}`, backend) + }) + + t.Run("block not found", func(t *testing.T) { + backend := &mock.API{} + blockID := unittest.IdentifierFixture() + + backend.Mock. + On("GetExecutionReceiptsByBlockID", mocks.Anything, blockID). + Return(nil, status.Error(codes.NotFound, "block not found")). + Once() + + req := getReceiptsByBlockIDReq(blockID.String()) + router.AssertResponse(t, req, http.StatusNotFound, `{"code":404,"message":"Flow resource not found: block not found"}`, backend) + mocks.AssertExpectationsForObjects(t, backend) + }) +} + +func TestGetExecutionReceiptsByResultID(t *testing.T) { + t.Run("get by result_id", func(t *testing.T) { + backend := &mock.API{} + resultID := unittest.IdentifierFixture() + receipt := unittest.ExecutionReceiptFixture() + + backend.Mock. + On("GetExecutionReceiptsByResultID", mocks.Anything, resultID). + Return([]*flow.ExecutionReceipt{receipt}, nil). + Once() + + req := getReceiptsByResultIDReq(resultID.String()) + expected := fmt.Sprintf(`[%s]`, executionReceiptExpectedStr(receipt)) + router.AssertOKResponse(t, req, expected, backend) + mocks.AssertExpectationsForObjects(t, backend) + }) + + t.Run("result not found", func(t *testing.T) { + backend := &mock.API{} + resultID := unittest.IdentifierFixture() + + backend.Mock. + On("GetExecutionReceiptsByResultID", mocks.Anything, resultID). + Return(nil, status.Error(codes.NotFound, "result not found")). + Once() + + req := getReceiptsByResultIDReq(resultID.String()) + router.AssertResponse(t, req, http.StatusNotFound, `{"code":404,"message":"Flow resource not found: result not found"}`, backend) + mocks.AssertExpectationsForObjects(t, backend) + }) +} diff --git a/engine/access/rest/http/routes/execution_result.go b/engine/access/rest/http/routes/execution_result.go index 74508753d77..271b0516228 100644 --- a/engine/access/rest/http/routes/execution_result.go +++ b/engine/access/rest/http/routes/execution_result.go @@ -10,7 +10,7 @@ import ( ) // GetExecutionResultsByBlockIDs gets Execution Result payload by block IDs. -func GetExecutionResultsByBlockIDs(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetExecutionResultsByBlockIDs(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.GetExecutionResultByBlockIDsRequest(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -36,7 +36,7 @@ func GetExecutionResultsByBlockIDs(r *common.Request, backend access.API, link c } // GetExecutionResultByID gets execution result by the ID. -func GetExecutionResultByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetExecutionResultByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.GetExecutionResultRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/network.go b/engine/access/rest/http/routes/network.go index 5f2954e4b8e..c977367f6d9 100644 --- a/engine/access/rest/http/routes/network.go +++ b/engine/access/rest/http/routes/network.go @@ -8,7 +8,7 @@ import ( ) // GetNetworkParameters returns network-wide parameters of the blockchain -func GetNetworkParameters(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (interface{}, error) { +func GetNetworkParameters(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (any, error) { params := backend.GetNetworkParameters(r.Context()) var response models.NetworkParameters diff --git a/engine/access/rest/http/routes/node_version_info.go b/engine/access/rest/http/routes/node_version_info.go index da2da3e59af..6c7dc38abd2 100644 --- a/engine/access/rest/http/routes/node_version_info.go +++ b/engine/access/rest/http/routes/node_version_info.go @@ -8,7 +8,7 @@ import ( ) // GetNodeVersionInfo returns node version information -func GetNodeVersionInfo(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (interface{}, error) { +func GetNodeVersionInfo(r *common.Request, backend access.API, _ commonmodels.LinkGenerator) (any, error) { params, err := backend.GetNodeVersionInfo(r.Context()) if err != nil { return nil, err diff --git a/engine/access/rest/http/routes/scripts.go b/engine/access/rest/http/routes/scripts.go index 92ec825de7e..351740d5298 100644 --- a/engine/access/rest/http/routes/scripts.go +++ b/engine/access/rest/http/routes/scripts.go @@ -9,7 +9,7 @@ import ( ) // ExecuteScript handler sends the script from the request to be executed. -func ExecuteScript(r *common.Request, backend access.API, _ models.LinkGenerator) (interface{}, error) { +func ExecuteScript(r *common.Request, backend access.API, _ models.LinkGenerator) (any, error) { req, err := request.GetScriptRequest(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/scripts_test.go b/engine/access/rest/http/routes/scripts_test.go index 8e08c5d21a6..9f1c7da813d 100644 --- a/engine/access/rest/http/routes/scripts_test.go +++ b/engine/access/rest/http/routes/scripts_test.go @@ -99,8 +99,8 @@ func TestScripts(t *testing.T) { router.AssertResponse( t, req, - http.StatusBadRequest, - `{"code":400, "message":"Invalid Flow request: internal server error"}`, + http.StatusInternalServerError, + `{"code":500, "message":"Invalid Flow request: internal server error"}`, backend, ) }) diff --git a/engine/access/rest/http/routes/transactions.go b/engine/access/rest/http/routes/transactions.go index 36e157de037..8f154fb3eba 100644 --- a/engine/access/rest/http/routes/transactions.go +++ b/engine/access/rest/http/routes/transactions.go @@ -17,7 +17,7 @@ const idQuery = "id" // The ID may be either: // 1. the hex-encoded 32-byte hash of a user-submitted transaction, or // 2. the integral system-assigned identifier of a scheduled transaction -func GetTransactionByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetTransactionByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { if !isTransactionID(r.GetVar(idQuery)) { return GetScheduledTransaction(r, backend, link) } @@ -52,11 +52,56 @@ func GetTransactionByID(r *common.Request, backend access.API, link commonmodels return response, nil } +// GetTransactionsByBlock gets transactions by requested blockID or height. +func GetTransactionsByBlock(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { + req, err := request.NewGetTransactionsByBlockRequest(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + blockID := req.BlockID + if blockID == flow.ZeroID { + block, _, err := backend.GetBlockByHeight(r.Context(), req.BlockHeight) + if err != nil { + return nil, err + } + + blockID = block.ID() + } + + transactions, err := backend.GetTransactionsByBlockID(r.Context(), blockID) + if err != nil { + return nil, err + } + + var transactionsResponse commonmodels.Transactions + // only lookup result if transaction result is to be expanded + if req.ExpandsResult { + transactionsResponse = make(commonmodels.Transactions, len(transactions)) + + txResults, err := backend.GetTransactionResultsByBlockID(r.Context(), blockID, entitiesproto.EventEncodingVersion_JSON_CDC_V0) + if err != nil { + return nil, err + } + + for i, transaction := range transactions { + var response commonmodels.Transaction + response.Build(transaction, txResults[i], link) + + transactionsResponse[i] = response + } + } else { + transactionsResponse.Build(transactions, link) + } + + return transactionsResponse, nil +} + // GetTransactionResultByID retrieves transaction result by the transaction ID. // The ID may be either: // 1. the hex-encoded 32-byte hash of a user-submitted transaction, or // 2. the integral system-assigned identifier of a scheduled transaction -func GetTransactionResultByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetTransactionResultByID(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { if !isTransactionID(r.GetVar(idQuery)) { return GetScheduledTransactionResult(r, backend, link) } @@ -82,8 +127,40 @@ func GetTransactionResultByID(r *common.Request, backend access.API, link common return response, nil } +// GetTransactionResultsByBlock gets transaction results by requested blockID or height. +func GetTransactionResultsByBlock(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { + req, err := request.NewGetTransactionResultsByBlockRequest(r) + if err != nil { + return nil, common.NewBadRequestError(err) + } + + blockID := req.BlockID + if blockID == flow.ZeroID { + block, _, err := backend.GetBlockByHeight(r.Context(), req.BlockHeight) + if err != nil { + return nil, err + } + + blockID = block.ID() + } + + transactionResults, err := backend.GetTransactionResultsByBlockID(r.Context(), blockID, entitiesproto.EventEncodingVersion_JSON_CDC_V0) + if err != nil { + return nil, err + } + + var response = make([]commonmodels.TransactionResult, len(transactionResults)) + for i, transactionResult := range transactionResults { + var txr commonmodels.TransactionResult + txr.Build(transactionResult, transactionResult.TransactionID, link) + response[i] = txr + } + + return response, nil +} + // CreateTransaction creates a new transaction from provided payload. -func CreateTransaction(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func CreateTransaction(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.CreateTransactionRequest(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -100,7 +177,7 @@ func CreateTransaction(r *common.Request, backend access.API, link commonmodels. } // GetScheduledTransaction gets a scheduled transaction by scheduled transaction ID. -func GetScheduledTransaction(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetScheduledTransaction(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.NewGetScheduledTransaction(r) if err != nil { return nil, common.NewBadRequestError(err) @@ -125,7 +202,7 @@ func GetScheduledTransaction(r *common.Request, backend access.API, link commonm } // GetScheduledTransactionResult gets a scheduled transaction result by scheduled transaction ID. -func GetScheduledTransactionResult(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (interface{}, error) { +func GetScheduledTransactionResult(r *common.Request, backend access.API, link commonmodels.LinkGenerator) (any, error) { req, err := request.NewGetScheduledTransactionResult(r) if err != nil { return nil, common.NewBadRequestError(err) diff --git a/engine/access/rest/http/routes/transactions_test.go b/engine/access/rest/http/routes/transactions_test.go index 333055d456a..ad2a7655c8b 100644 --- a/engine/access/rest/http/routes/transactions_test.go +++ b/engine/access/rest/http/routes/transactions_test.go @@ -17,12 +17,11 @@ import ( "google.golang.org/grpc/status" "github.com/onflow/flow/protobuf/go/flow/entities" - entitiesproto "github.com/onflow/flow/protobuf/go/flow/entities" "github.com/onflow/flow-go/access/mock" - "github.com/onflow/flow-go/engine/access/rest/common/models" commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" mockcommonmodels "github.com/onflow/flow-go/engine/access/rest/common/models/mock" + "github.com/onflow/flow-go/engine/access/rest/http/request" "github.com/onflow/flow-go/engine/access/rest/router" "github.com/onflow/flow-go/engine/access/rest/util" "github.com/onflow/flow-go/fvm/blueprints" @@ -32,7 +31,7 @@ import ( "github.com/onflow/flow-go/utils/unittest/fixtures" ) -func getTransactionReq(id string, expandResult bool, blockIdQuery string, collectionIdQuery string) *http.Request { +func newGetTransactionRequest(id string, expandResult bool, blockIdQuery string, collectionIdQuery string) *http.Request { u, _ := url.Parse(fmt.Sprintf("/v1/transactions/%s", id)) q := u.Query() @@ -55,7 +54,33 @@ func getTransactionReq(id string, expandResult bool, blockIdQuery string, collec return req } -func getTransactionResultReq(id string, blockIdQuery string, collectionIdQuery string) *http.Request { +func newGetTransactionsRequest(blockId string, height string, expandResult bool, collectionIdQuery string) *http.Request { + u, _ := url.Parse("/v1/transactions") + q := u.Query() + + if blockId != "" { + q.Add("block_id", blockId) + } + + if height != "" { + q.Add("block_height", height) + } + + if expandResult { + q.Add("expand", "result") + } + + if collectionIdQuery != "" { + q.Add("collection_id", collectionIdQuery) + } + + u.RawQuery = q.Encode() + + req, _ := http.NewRequest("GET", u.String(), nil) + return req +} + +func newGetTransactionResultRequest(id string, blockIdQuery string, collectionIdQuery string) *http.Request { u, _ := url.Parse(fmt.Sprintf("/v1/transaction_results/%s", id)) q := u.Query() if blockIdQuery != "" { @@ -72,7 +97,25 @@ func getTransactionResultReq(id string, blockIdQuery string, collectionIdQuery s return req } -func createTransactionReq(body interface{}) *http.Request { +func newGetTransactionResultsRequest(blockIdQuery string, height string) *http.Request { + u, _ := url.Parse("/v1/transaction_results") + q := u.Query() + + if blockIdQuery != "" { + q.Add("block_id", blockIdQuery) + } + + if height != "" { + q.Add("block_height", height) + } + + u.RawQuery = q.Encode() + + req, _ := http.NewRequest("GET", u.String(), nil) + return req +} + +func newCreateTransactionRequest(body interface{}) *http.Request { jsonBody, _ := json.Marshal(body) req, _ := http.NewRequest("POST", "/v1/transactions", bytes.NewBuffer(jsonBody)) return req @@ -82,7 +125,7 @@ func TestGetTransactions(t *testing.T) { t.Run("get by ID without results", func(t *testing.T) { backend := mock.NewAPI(t) tx := unittest.TransactionFixture() - req := getTransactionReq(tx.ID().String(), false, "", "") + req := newGetTransactionRequest(tx.ID().String(), false, "", "") backend.Mock. On("GetTransaction", mocks.Anything, tx.ID()). @@ -138,7 +181,7 @@ func TestGetTransactions(t *testing.T) { On("GetTransactionResult", mocks.Anything, tx.ID(), flow.ZeroID, flow.ZeroID, entities.EventEncodingVersion_JSON_CDC_V0). Return(txr, nil) - req := getTransactionReq(tx.ID().String(), true, "", "") + req := newGetTransactionRequest(tx.ID().String(), true, "", "") expected := fmt.Sprintf(` { @@ -197,7 +240,7 @@ func TestGetTransactions(t *testing.T) { t.Run("get by ID Invalid", func(t *testing.T) { backend := mock.NewAPI(t) - req := getTransactionReq("invalid", false, "", "") + req := newGetTransactionRequest("invalid", false, "", "") expected := `{"code":400, "message":"invalid ID format"}` router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) }) @@ -206,7 +249,7 @@ func TestGetTransactions(t *testing.T) { backend := mock.NewAPI(t) tx := unittest.TransactionFixture() - req := getTransactionReq(tx.ID().String(), false, "", "") + req := newGetTransactionRequest(tx.ID().String(), false, "", "") backend.Mock. On("GetTransaction", mocks.Anything, tx.ID()). @@ -217,6 +260,753 @@ func TestGetTransactions(t *testing.T) { }) } +func TestGetTransactionsByBlock(t *testing.T) { + t.Run("get by block ID without expanded results", func(t *testing.T) { + backend := mock.NewAPI(t) + blockID := unittest.IdentifierFixture() + + tx1 := unittest.TransactionFixture() + tx2 := unittest.TransactionFixture() + txs := []*flow.TransactionBody{&tx1, &tx2} + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(txs, nil). + Once() + req := newGetTransactionsRequest(blockID.String(), "", false, "") + + expected := fmt.Sprintf(`[ + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + }, + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + } + ]`, + txs[0].ID(), txs[0].ReferenceBlockID, util.ToBase64(txs[0].EnvelopeSignatures[0].Signature), txs[0].ID(), txs[0].ID(), + txs[1].ID(), txs[1].ReferenceBlockID, util.ToBase64(txs[1].EnvelopeSignatures[0].Signature), txs[1].ID(), txs[1].ID(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by height without expanded results", func(t *testing.T) { + backend := mock.NewAPI(t) + height := uint64(123) + block := unittest.BlockFixture() + blockID := block.ID() + + tx1 := unittest.TransactionFixture() + tx2 := unittest.TransactionFixture() + txs := []*flow.TransactionBody{&tx1, &tx2} + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, height). + Return(block, flow.BlockStatusSealed, nil).Once() + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(txs, nil). + Once() + + req := newGetTransactionsRequest("", fmt.Sprintf("%d", height), false, "") + + expected := fmt.Sprintf(`[ + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + }, + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + } + ]`, + txs[0].ID(), txs[0].ReferenceBlockID, util.ToBase64(txs[0].EnvelopeSignatures[0].Signature), txs[0].ID(), txs[0].ID(), + txs[1].ID(), txs[1].ReferenceBlockID, util.ToBase64(txs[1].EnvelopeSignatures[0].Signature), txs[1].ID(), txs[1].ID(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by height sealed", func(t *testing.T) { + backend := mock.NewAPI(t) + + block := unittest.BlockFixture() + blockID := block.ID() + + tx1 := unittest.TransactionFixture() + tx2 := unittest.TransactionFixture() + txs := []*flow.TransactionBody{&tx1, &tx2} + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, request.SealedHeight). + Return(block, flow.BlockStatusSealed, nil).Once() + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(txs, nil). + Once() + + req := newGetTransactionsRequest("", router.SealedHeightQueryParam, false, "") + + expected := fmt.Sprintf(`[ + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + }, + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + } + ]`, + txs[0].ID(), txs[0].ReferenceBlockID, util.ToBase64(txs[0].EnvelopeSignatures[0].Signature), txs[0].ID(), txs[0].ID(), + txs[1].ID(), txs[1].ReferenceBlockID, util.ToBase64(txs[1].EnvelopeSignatures[0].Signature), txs[1].ID(), txs[1].ID(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by height final", func(t *testing.T) { + backend := mock.NewAPI(t) + + block := unittest.BlockFixture() + blockID := block.ID() + + tx1 := unittest.TransactionFixture() + tx2 := unittest.TransactionFixture() + txs := []*flow.TransactionBody{&tx1, &tx2} + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, request.FinalHeight). + Return(block, flow.BlockStatusFinalized, nil).Once() + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(txs, nil). + Once() + + req := newGetTransactionsRequest("", router.FinalHeightQueryParam, false, "") + + expected := fmt.Sprintf(`[ + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + }, + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + } + ]`, + txs[0].ID(), txs[0].ReferenceBlockID, util.ToBase64(txs[0].EnvelopeSignatures[0].Signature), txs[0].ID(), txs[0].ID(), + txs[1].ID(), txs[1].ReferenceBlockID, util.ToBase64(txs[1].EnvelopeSignatures[0].Signature), txs[1].ID(), txs[1].ID(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get with no block_id or height defaults to sealed", func(t *testing.T) { + backend := mock.NewAPI(t) + + block := unittest.BlockFixture() + blockID := block.ID() + + tx1 := unittest.TransactionFixture() + txs := []*flow.TransactionBody{&tx1} + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, request.SealedHeight). + Return(block, flow.BlockStatusSealed, nil). + Once() + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(txs, nil). + Once() + + req := newGetTransactionsRequest("", "", false, "") + + expected := fmt.Sprintf(`[ + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "_links":{ + "_self":"/v1/transactions/%s" + }, + "_expandable": { + "result": "/v1/transaction_results/%s" + } + } + ]`, + txs[0].ID(), txs[0].ReferenceBlockID, util.ToBase64(txs[0].EnvelopeSignatures[0].Signature), txs[0].ID(), txs[0].ID(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by block ID with expanded results", func(t *testing.T) { + backend := mock.NewAPI(t) + blockID := unittest.IdentifierFixture() + + tx1 := unittest.TransactionFixture() + tx2 := unittest.TransactionFixture() + txs := []*flow.TransactionBody{&tx1, &tx2} + + txr1 := transactionResultFixture(tx1) + txr2 := transactionResultFixture(tx2) + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(txs, nil). + Once() + + txResults := []*accessmodel.TransactionResult{txr1, txr2} + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return(txResults, nil). + Once() + + req := newGetTransactionsRequest(blockID.String(), "", true, "") + + expected := fmt.Sprintf(`[ + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "result": { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 1, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "0", + "event_index": "0", + "payload": "" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + }, + "_expandable": {}, + "_links":{ + "_self":"/v1/transactions/%s" + } + }, + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "result": { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 1, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "0", + "event_index": "0", + "payload": "" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + }, + "_expandable": {}, + "_links":{ + "_self":"/v1/transactions/%s" + } + } + ]`, + tx1.ID(), tx1.ReferenceBlockID, util.ToBase64(tx1.EnvelopeSignatures[0].Signature), + tx1.ReferenceBlockID, txr1.CollectionID, tx1.ID(), tx1.ID(), tx1.ID(), + tx2.ID(), tx2.ReferenceBlockID, util.ToBase64(tx2.EnvelopeSignatures[0].Signature), + tx2.ReferenceBlockID, txr2.CollectionID, tx2.ID(), tx2.ID(), tx2.ID(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by height with expanded results", func(t *testing.T) { + backend := mock.NewAPI(t) + height := uint64(123) + block := unittest.BlockFixture() + blockID := block.ID() + + tx1 := unittest.TransactionFixture() + tx2 := unittest.TransactionFixture() + txs := []*flow.TransactionBody{&tx1, &tx2} + + txr1 := transactionResultFixture(tx1) + txr2 := transactionResultFixture(tx2) + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, height). + Return(block, flow.BlockStatusSealed, nil). + Once() + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(txs, nil). + Once() + + txResults := []*accessmodel.TransactionResult{txr1, txr2} + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return(txResults, nil). + Once() + + req := newGetTransactionsRequest("", fmt.Sprintf("%d", height), true, "") + + expected := fmt.Sprintf(`[ + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "result": { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 1, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "0", + "event_index": "0", + "payload": "" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + }, + "_expandable": {}, + "_links":{ + "_self":"/v1/transactions/%s" + } + }, + { + "id":"%s", + "script":"YWNjZXNzKGFsbCkgZnVuIG1haW4oKSB7fQ==", + "arguments": [], + "reference_block_id":"%s", + "gas_limit":"10", + "payer":"8c5303eaa26202d6", + "proposal_key":{ + "address":"8c5303eaa26202d6", + "key_index":"1", + "sequence_number":"0" + }, + "authorizers":[ + "8c5303eaa26202d6" + ], + "payload_signatures": [], + "envelope_signatures":[ + { + "address":"8c5303eaa26202d6", + "key_index":"1", + "signature":"%s" + } + ], + "result": { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 1, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "0", + "event_index": "0", + "payload": "" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + }, + "_expandable": {}, + "_links":{ + "_self":"/v1/transactions/%s" + } + } + ]`, + tx1.ID(), tx1.ReferenceBlockID, util.ToBase64(tx1.EnvelopeSignatures[0].Signature), + tx1.ReferenceBlockID, txr1.CollectionID, tx1.ID(), tx1.ID(), tx1.ID(), + tx2.ID(), tx2.ReferenceBlockID, util.ToBase64(tx2.EnvelopeSignatures[0].Signature), + tx2.ReferenceBlockID, txr2.CollectionID, tx2.ID(), tx2.ID(), tx2.ID(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by block ID invalid block_id", func(t *testing.T) { + backend := mock.NewAPI(t) + + req := newGetTransactionsRequest("invalid", "", false, "") + + expected := `{"code":400, "message":"invalid ID format"}` + router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) + }) + + t.Run("get by block ID non-existing block", func(t *testing.T) { + backend := mock.NewAPI(t) + blockID := unittest.IdentifierFixture() + + backend.Mock. + On("GetTransactionsByBlockID", mocks.Anything, blockID). + Return(nil, status.Error(codes.NotFound, "block not found")). + Once() + + req := newGetTransactionsRequest(blockID.String(), "", false, "") + + expected := `{"code":404, "message":"Flow resource not found: block not found"}` + router.AssertResponse(t, req, http.StatusNotFound, expected, backend) + }) + + t.Run("get by height invalid height", func(t *testing.T) { + backend := mock.NewAPI(t) + + req := newGetTransactionsRequest("", "not-a-height", false, "") + + expected := `{"code":400, "message":"invalid height format"}` + router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) + }) + + t.Run("get by height non-existing block", func(t *testing.T) { + backend := mock.NewAPI(t) + + height := uint64(123) + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, height). + Return((*flow.Block)(nil), flow.BlockStatusUnknown, status.Error(codes.NotFound, "block not found")). + Once() + + req := newGetTransactionsRequest("", fmt.Sprintf("%d", height), false, "") + + expected := `{"code":404, "message":"Flow resource not found: block not found"}` + router.AssertResponse(t, req, http.StatusNotFound, expected, backend) + }) + + t.Run("get with both block_id and height is invalid", func(t *testing.T) { + backend := mock.NewAPI(t) + + blockID := unittest.IdentifierFixture() + req := newGetTransactionsRequest(blockID.String(), "123", false, "") + + expected := `{"code":400, "message":"can not provide both block ID and block height"}` + router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) + }) + +} + func TestGetTransactionResult(t *testing.T) { id := unittest.IdentifierFixture() bid := unittest.IdentifierFixture() @@ -232,9 +1022,10 @@ func TestGetTransactionResult(t *testing.T) { unittest.Event.WithTransactionID(id), ), }, - ErrorMessage: "", - BlockID: bid, - CollectionID: cid, + ErrorMessage: "", + BlockID: bid, + CollectionID: cid, + ComputationUsed: 1234, } txr.Events[0].Payload = []byte(`test payload`) expected := fmt.Sprintf(`{ @@ -244,7 +1035,7 @@ func TestGetTransactionResult(t *testing.T) { "status": "Sealed", "status_code": 10, "error_message": "", - "computation_used": "0", + "computation_used": "1234", "events": [ { "type": "flow.AccountCreated", @@ -261,7 +1052,7 @@ func TestGetTransactionResult(t *testing.T) { t.Run("get by transaction ID", func(t *testing.T) { backend := mock.NewAPI(t) - req := getTransactionResultReq(id.String(), "", "") + req := newGetTransactionResultRequest(id.String(), "", "") backend.Mock. On("GetTransactionResult", mocks.Anything, id, flow.ZeroID, flow.ZeroID, entities.EventEncodingVersion_JSON_CDC_V0). @@ -273,7 +1064,7 @@ func TestGetTransactionResult(t *testing.T) { t.Run("get by block ID", func(t *testing.T) { backend := mock.NewAPI(t) - req := getTransactionResultReq(id.String(), bid.String(), "") + req := newGetTransactionResultRequest(id.String(), bid.String(), "") backend.Mock. On("GetTransactionResult", mocks.Anything, id, bid, flow.ZeroID, entities.EventEncodingVersion_JSON_CDC_V0). @@ -284,7 +1075,7 @@ func TestGetTransactionResult(t *testing.T) { t.Run("get by collection ID", func(t *testing.T) { backend := mock.NewAPI(t) - req := getTransactionResultReq(id.String(), "", cid.String()) + req := newGetTransactionResultRequest(id.String(), "", cid.String()) backend.Mock. On("GetTransactionResult", mocks.Anything, id, flow.ZeroID, cid, entities.EventEncodingVersion_JSON_CDC_V0). @@ -299,27 +1090,27 @@ func TestGetTransactionResult(t *testing.T) { testVectors := map[*accessmodel.TransactionResult]string{{ Status: flow.TransactionStatusExpired, ErrorMessage: "", - }: string(models.FAILURE_RESULT), { + }: string(commonmodels.FAILURE_RESULT), { Status: flow.TransactionStatusSealed, ErrorMessage: "cadence runtime exception", - }: string(models.FAILURE_RESULT), { + }: string(commonmodels.FAILURE_RESULT), { Status: flow.TransactionStatusFinalized, ErrorMessage: "", - }: string(models.PENDING_RESULT), { + }: string(commonmodels.PENDING_RESULT), { Status: flow.TransactionStatusPending, ErrorMessage: "", - }: string(models.PENDING_RESULT), { + }: string(commonmodels.PENDING_RESULT), { Status: flow.TransactionStatusExecuted, ErrorMessage: "", - }: string(models.PENDING_RESULT), { + }: string(commonmodels.PENDING_RESULT), { Status: flow.TransactionStatusSealed, ErrorMessage: "", - }: string(models.SUCCESS_RESULT)} + }: string(commonmodels.SUCCESS_RESULT)} for txResult, err := range testVectors { txResult.BlockID = bid txResult.CollectionID = cid - req := getTransactionResultReq(id.String(), "", "") + req := newGetTransactionResultRequest(id.String(), "", "") backend.Mock. On("GetTransactionResult", mocks.Anything, id, flow.ZeroID, flow.ZeroID, entities.EventEncodingVersion_JSON_CDC_V0). Return(txResult, nil). @@ -345,11 +1136,482 @@ func TestGetTransactionResult(t *testing.T) { t.Run("get by ID Invalid", func(t *testing.T) { backend := mock.NewAPI(t) - req := getTransactionResultReq("invalid", "", "") + req := newGetTransactionResultRequest("invalid", "", "") + + expected := `{"code":400, "message":"invalid ID format"}` + router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) + }) +} + +func TestGetTransactionResultsByBlock(t *testing.T) { + t.Run("get by block ID", func(t *testing.T) { + backend := mock.NewAPI(t) + blockID := unittest.IdentifierFixture() + + id1 := unittest.IdentifierFixture() + bid1 := blockID + cid1 := unittest.IdentifierFixture() + txr1 := &accessmodel.TransactionResult{ + Status: flow.TransactionStatusSealed, + StatusCode: 10, + Events: []flow.Event{ + unittest.EventFixture( + unittest.Event.WithEventType(flow.EventAccountCreated), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + unittest.Event.WithTransactionID(id1), + ), + }, + ErrorMessage: "", + BlockID: bid1, + CollectionID: cid1, + TransactionID: id1, + } + txr1.Events[0].Payload = []byte(`test payload 1`) + + id2 := unittest.IdentifierFixture() + bid2 := blockID + cid2 := unittest.IdentifierFixture() + txr2 := &accessmodel.TransactionResult{ + Status: flow.TransactionStatusSealed, + StatusCode: 10, + Events: []flow.Event{ + unittest.EventFixture( + unittest.Event.WithEventType(flow.EventAccountCreated), + unittest.Event.WithTransactionIndex(0), + unittest.Event.WithEventIndex(0), + unittest.Event.WithTransactionID(id2), + ), + }, + ErrorMessage: "", + BlockID: bid2, + CollectionID: cid2, + TransactionID: id2, + } + txr2.Events[0].Payload = []byte(`test payload 2`) + + txResults := []*accessmodel.TransactionResult{txr1, txr2} + + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return(txResults, nil).Once() + + req := newGetTransactionResultsRequest(blockID.String(), "") + + expected := fmt.Sprintf(`[ + { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 10, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "1", + "event_index": "0", + "payload": "%s" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + }, + { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 10, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "0", + "event_index": "0", + "payload": "%s" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + } + ]`, + bid1.String(), cid1.String(), id1.String(), util.ToBase64(txr1.Events[0].Payload), id1.String(), + bid2.String(), cid2.String(), id2.String(), util.ToBase64(txr2.Events[0].Payload), id2.String(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by height", func(t *testing.T) { + backend := mock.NewAPI(t) + height := uint64(123) + block := unittest.BlockFixture() + blockID := block.ID() + + id1 := unittest.IdentifierFixture() + cid1 := unittest.IdentifierFixture() + txr1 := &accessmodel.TransactionResult{ + Status: flow.TransactionStatusSealed, + StatusCode: 10, + Events: []flow.Event{ + unittest.EventFixture( + unittest.Event.WithEventType(flow.EventAccountCreated), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + unittest.Event.WithTransactionID(id1), + ), + }, + ErrorMessage: "", + BlockID: blockID, + CollectionID: cid1, + TransactionID: id1, + } + txr1.Events[0].Payload = []byte(`test payload 1`) + + id2 := unittest.IdentifierFixture() + cid2 := unittest.IdentifierFixture() + txr2 := &accessmodel.TransactionResult{ + Status: flow.TransactionStatusSealed, + StatusCode: 10, + Events: []flow.Event{ + unittest.EventFixture( + unittest.Event.WithEventType(flow.EventAccountCreated), + unittest.Event.WithTransactionIndex(0), + unittest.Event.WithEventIndex(0), + unittest.Event.WithTransactionID(id2), + ), + }, + ErrorMessage: "", + BlockID: blockID, + CollectionID: cid2, + TransactionID: id2, + } + txr2.Events[0].Payload = []byte(`test payload 2`) + + txResults := []*accessmodel.TransactionResult{txr1, txr2} + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, height). + Return(block, flow.BlockStatusSealed, nil).Once() + + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return(txResults, nil).Once() + + req := newGetTransactionResultsRequest("", fmt.Sprintf("%d", height)) + + expected := fmt.Sprintf(`[ + { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 10, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "1", + "event_index": "0", + "payload": "%s" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + }, + { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 10, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "0", + "event_index": "0", + "payload": "%s" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + } + ]`, + blockID.String(), cid1.String(), id1.String(), util.ToBase64(txr1.Events[0].Payload), id1.String(), + blockID.String(), cid2.String(), id2.String(), util.ToBase64(txr2.Events[0].Payload), id2.String(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get results by height sealed", func(t *testing.T) { + backend := mock.NewAPI(t) + + block := unittest.BlockFixture() + blockID := block.ID() + + id1 := unittest.IdentifierFixture() + cid1 := unittest.IdentifierFixture() + txr1 := &accessmodel.TransactionResult{ + Status: flow.TransactionStatusSealed, + StatusCode: 10, + ErrorMessage: "", + BlockID: blockID, + CollectionID: cid1, + TransactionID: id1, + Events: []flow.Event{ + unittest.EventFixture( + unittest.Event.WithEventType(flow.EventAccountCreated), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + unittest.Event.WithTransactionID(id1), + ), + }, + } + txr1.Events[0].Payload = []byte(`test payload 1`) + + txResults := []*accessmodel.TransactionResult{txr1} + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, request.SealedHeight). + Return(block, flow.BlockStatusSealed, nil).Once() + + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return(txResults, nil).Once() + + req := newGetTransactionResultsRequest("", router.SealedHeightQueryParam) + + expected := fmt.Sprintf(`[ + { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 10, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "1", + "event_index": "0", + "payload": "%s" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + } + ]`, + blockID.String(), cid1.String(), id1.String(), util.ToBase64(txr1.Events[0].Payload), id1.String(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get results by height finalized", func(t *testing.T) { + backend := mock.NewAPI(t) + + block := unittest.BlockFixture() + blockID := block.ID() + + id1 := unittest.IdentifierFixture() + cid1 := unittest.IdentifierFixture() + txr1 := &accessmodel.TransactionResult{ + Status: flow.TransactionStatusFinalized, + StatusCode: 10, + ErrorMessage: "", + BlockID: blockID, + CollectionID: cid1, + TransactionID: id1, + Events: []flow.Event{ + unittest.EventFixture( + unittest.Event.WithEventType(flow.EventAccountCreated), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + unittest.Event.WithTransactionID(id1), + ), + }, + } + txr1.Events[0].Payload = []byte(`test payload 1`) + + txResults := []*accessmodel.TransactionResult{txr1} + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, request.FinalHeight). + Return(block, flow.BlockStatusFinalized, nil).Once() + + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return(txResults, nil).Once() + + req := newGetTransactionResultsRequest("", router.FinalHeightQueryParam) + + expected := fmt.Sprintf(`[ + { + "block_id": "%s", + "collection_id": "%s", + "execution": "Pending", + "status": "Finalized", + "status_code": 10, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "1", + "event_index": "0", + "payload": "%s" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + } + ]`, + blockID.String(), cid1.String(), id1.String(), util.ToBase64(txr1.Events[0].Payload), id1.String(), + ) + + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get results with no block_id or height defaults to sealed", func(t *testing.T) { + backend := mock.NewAPI(t) + + block := unittest.BlockFixture() + blockID := block.ID() + + id1 := unittest.IdentifierFixture() + cid1 := unittest.IdentifierFixture() + txr1 := &accessmodel.TransactionResult{ + Status: flow.TransactionStatusSealed, + StatusCode: 10, + ErrorMessage: "", + BlockID: blockID, + CollectionID: cid1, + TransactionID: id1, + Events: []flow.Event{ + unittest.EventFixture( + unittest.Event.WithEventType(flow.EventAccountCreated), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + unittest.Event.WithTransactionID(id1), + ), + }, + } + txr1.Events[0].Payload = []byte(`test payload 1`) + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, request.SealedHeight). + Return(block, flow.BlockStatusSealed, nil).Once() + + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return([]*accessmodel.TransactionResult{txr1}, nil).Once() + + req := newGetTransactionResultsRequest("", "") + + expected := fmt.Sprintf(`[ + { + "block_id": "%s", + "collection_id": "%s", + "execution": "Success", + "status": "Sealed", + "status_code": 10, + "error_message": "", + "computation_used": "0", + "events": [ + { + "type": "flow.AccountCreated", + "transaction_id": "%s", + "transaction_index": "1", + "event_index": "0", + "payload": "%s" + } + ], + "_links": { + "_self": "/v1/transaction_results/%s" + } + } + ]`, blockID.String(), cid1.String(), id1.String(), util.ToBase64(txr1.Events[0].Payload), id1.String()) + router.AssertOKResponse(t, req, expected, backend) + }) + + t.Run("get by block ID invalid block_id", func(t *testing.T) { + backend := mock.NewAPI(t) + + req := newGetTransactionResultsRequest("invalid", "") expected := `{"code":400, "message":"invalid ID format"}` router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) }) + + t.Run("get by height invalid height", func(t *testing.T) { + backend := mock.NewAPI(t) + + req := newGetTransactionResultsRequest("", "not-a-height") + + expected := `{"code":400, "message":"invalid height format"}` + router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) + }) + + t.Run("get by block ID non-existing block", func(t *testing.T) { + backend := mock.NewAPI(t) + + blockID := unittest.IdentifierFixture() + + backend.Mock. + On("GetTransactionResultsByBlockID", mocks.Anything, blockID, entities.EventEncodingVersion_JSON_CDC_V0). + Return(nil, status.Error(codes.NotFound, "block not found")).Once() + + req := newGetTransactionResultsRequest(blockID.String(), "") + + expected := `{"code":404, "message":"Flow resource not found: block not found"}` + router.AssertResponse(t, req, http.StatusNotFound, expected, backend) + }) + + t.Run("get by height non-existing block", func(t *testing.T) { + backend := mock.NewAPI(t) + + height := uint64(123) + + backend.Mock. + On("GetBlockByHeight", mocks.Anything, height). + Return((*flow.Block)(nil), flow.BlockStatusUnknown, status.Error(codes.NotFound, "block not found")). + Once() + + req := newGetTransactionResultsRequest("", fmt.Sprintf("%d", height)) + + expected := `{"code":404, "message":"Flow resource not found: block not found"}` + router.AssertResponse(t, req, http.StatusNotFound, expected, backend) + }) + + t.Run("get with both block_id and height is invalid", func(t *testing.T) { + backend := mock.NewAPI(t) + + blockID := unittest.IdentifierFixture() + req := newGetTransactionResultsRequest(blockID.String(), "123") + + expected := `{"code":400, "message":"can not provide both block ID and block height"}` + router.AssertResponse(t, req, http.StatusBadRequest, expected, backend) + }) } func TestGetScheduledTransactions(t *testing.T) { @@ -375,7 +1637,7 @@ func TestGetScheduledTransactions(t *testing.T) { Return(tx, nil). Once() - req := getTransactionReq(fmt.Sprint(scheduledTxID), false, "", "") + req := newGetTransactionRequest(fmt.Sprint(scheduledTxID), false, "", "") router.AssertOKResponse(t, req, string(expectedWithoutResult), backend) }) @@ -387,28 +1649,28 @@ func TestGetScheduledTransactions(t *testing.T) { Return(tx, nil). Once() backend. - On("GetScheduledTransactionResult", mocks.Anything, scheduledTxID, entitiesproto.EventEncodingVersion_JSON_CDC_V0). + On("GetScheduledTransactionResult", mocks.Anything, scheduledTxID, entities.EventEncodingVersion_JSON_CDC_V0). Return(txr, nil). Once() - req := getTransactionReq(fmt.Sprint(scheduledTxID), true, "", "") + req := newGetTransactionRequest(fmt.Sprint(scheduledTxID), true, "", "") router.AssertOKResponse(t, req, string(expectedWithResult), backend) }) t.Run("get result by scheduled transaction ID", func(t *testing.T) { - var expectedTxResult models.TransactionResult + var expectedTxResult commonmodels.TransactionResult expectedTxResult.Build(txr, txID, link) expectedResult, err := json.Marshal(expectedTxResult) require.NoError(t, err) backend := mock.NewAPI(t) backend. - On("GetScheduledTransactionResult", mocks.Anything, scheduledTxID, entitiesproto.EventEncodingVersion_JSON_CDC_V0). + On("GetScheduledTransactionResult", mocks.Anything, scheduledTxID, entities.EventEncodingVersion_JSON_CDC_V0). Return(txr, nil). Once() - req := getTransactionResultReq(fmt.Sprint(scheduledTxID), "", "") + req := newGetTransactionResultRequest(fmt.Sprint(scheduledTxID), "", "") router.AssertOKResponse(t, req, string(expectedResult), backend) }) @@ -423,7 +1685,7 @@ func TestGetScheduledTransactions(t *testing.T) { Return(tx, nil). Once() - req := getTransactionReq(txID.String(), false, "", "") + req := newGetTransactionRequest(txID.String(), false, "", "") router.AssertOKResponse(t, req, string(expectedWithoutResult), backend) }) @@ -435,11 +1697,11 @@ func TestGetScheduledTransactions(t *testing.T) { Return(tx, nil). Once() backend. - On("GetTransactionResult", mocks.Anything, txID, flow.ZeroID, flow.ZeroID, entitiesproto.EventEncodingVersion_JSON_CDC_V0). + On("GetTransactionResult", mocks.Anything, txID, flow.ZeroID, flow.ZeroID, entities.EventEncodingVersion_JSON_CDC_V0). Return(txr, nil). Once() - req := getTransactionReq(txID.String(), true, "", "") + req := newGetTransactionRequest(txID.String(), true, "", "") router.AssertOKResponse(t, req, string(expectedWithResult), backend) }) @@ -450,7 +1712,7 @@ func TestGetScheduledTransactions(t *testing.T) { On("GetScheduledTransaction", mocks.Anything, scheduledTxID). Return(nil, status.Error(codes.NotFound, "transaction not found")) - req := getTransactionReq(fmt.Sprint(scheduledTxID), false, "", "") + req := newGetTransactionRequest(fmt.Sprint(scheduledTxID), false, "", "") expected := `{"code":404, "message":"Flow resource not found: transaction not found"}` router.AssertResponse(t, req, http.StatusNotFound, expected, backend) @@ -464,7 +1726,7 @@ func TestCreateTransaction(t *testing.T) { tx := unittest.TransactionBodyFixture() tx.PayloadSignatures = []flow.TransactionSignature{unittest.TransactionSignatureFixture()} tx.Arguments = [][]uint8{} - req := createTransactionReq(unittest.CreateSendTxHttpPayload(tx)) + req := newCreateTransactionRequest(unittest.CreateSendTxHttpPayload(tx)) backend.Mock. On("SendTransaction", mocks.Anything, &tx). @@ -534,7 +1796,7 @@ func TestCreateTransaction(t *testing.T) { tx.PayloadSignatures = []flow.TransactionSignature{unittest.TransactionSignatureFixture()} testTx := unittest.CreateSendTxHttpPayload(tx) testTx[test.inputField] = test.inputValue - req := createTransactionReq(testTx) + req := newCreateTransactionRequest(testTx) router.AssertResponse(t, req, http.StatusBadRequest, test.output, backend) } @@ -582,7 +1844,7 @@ func scheduledTransactionFixture(t *testing.T, g *fixtures.GeneratorSuite, sched // expectedTransactionResponse constructs the expected json transaction response for the given // transaction body and transaction result. func expectedTransactionResponse(t *testing.T, tx *flow.TransactionBody, txr *accessmodel.TransactionResult, link commonmodels.LinkGenerator) string { - var expectedTxWithoutResult models.Transaction + var expectedTxWithoutResult commonmodels.Transaction expectedTxWithoutResult.Build(tx, txr, link) expected, err := json.Marshal(expectedTxWithoutResult) diff --git a/engine/access/rest/router/metrics.go b/engine/access/rest/router/metrics.go index eb84f1d6904..72d0c2c9122 100644 --- a/engine/access/rest/router/metrics.go +++ b/engine/access/rest/router/metrics.go @@ -6,29 +6,35 @@ import ( "strings" ) -// the following logic is used to match the URL with the correct route for metrics collection. +// routeMatcher ties together an HTTP method with a compiled regex for the path and the route name. +type routeMatcher struct { + method string + re *regexp.Regexp + name string +} -var routePatterns []*regexp.Regexp -var routeNameMap map[*regexp.Regexp]string +var matchers []routeMatcher func init() { - routePatterns = make([]*regexp.Regexp, 0, len(Routes)+len(WSLegacyRoutes)) - routeNameMap = make(map[*regexp.Regexp]string) + matchers = make([]routeMatcher, 0, len(Routes)+len(WSLegacyRoutes)+len(ExperimentalRoutes)) - // Convert REST route patterns to regex patterns for matching - for _, r := range Routes { - regexPattern := patternToRegex(r.Pattern) - re := regexp.MustCompile("^" + regexPattern + "$") - routePatterns = append(routePatterns, re) - routeNameMap[re] = r.Name + add := func(method, pattern, name string) { + regexPattern := "^" + patternToRegex(pattern) + "$" + matchers = append(matchers, routeMatcher{ + method: method, + re: regexp.MustCompile(regexPattern), + name: name, + }) } - // Convert WebSocket route patterns to regex patterns for matching + for _, r := range Routes { + add(r.Method, r.Pattern, r.Name) + } for _, r := range WSLegacyRoutes { - regexPattern := patternToRegex(r.Pattern) - re := regexp.MustCompile("^" + regexPattern + "$") - routePatterns = append(routePatterns, re) - routeNameMap[re] = r.Name + add(r.Method, r.Pattern, r.Name) + } + for _, r := range ExperimentalRoutes { + add(r.Method, r.Pattern, r.Name) } } @@ -46,13 +52,31 @@ func patternToRegex(pattern string) string { return escaped } -// URLToRoute matches the URL against route patterns and returns the matching route name -func URLToRoute(url string) (string, error) { - path := strings.TrimPrefix(url, "/v1") - for _, pattern := range routePatterns { - if pattern.MatchString(path) { - return routeNameMap[pattern], nil +// MethodURLToRoute matches (method, url) against compiled route regexes and returns the route name. +func MethodURLToRoute(method, url string) (string, error) { + + path, found := strings.CutPrefix(url, "/v1") + if !found { + path = strings.TrimPrefix(url, "/experimental/v1") + } + + if method == "" { + for _, m := range matchers { + if m.re.MatchString(path) { + return m.name, nil + } + } + return "", fmt.Errorf("no matching route found for URL: %s", url) + } + + for _, m := range matchers { + if m.method != method { + continue + } + if m.re.MatchString(path) { + return m.name, nil } } - return "", fmt.Errorf("no matching route found for URL: %s", url) + + return "", fmt.Errorf("no matching route found for method %s and URL: %s", method, url) } diff --git a/engine/access/rest/router/metrics_test.go b/engine/access/rest/router/metrics_test.go index 5f0d97afe15..fb883ec3de0 100644 --- a/engine/access/rest/router/metrics_test.go +++ b/engine/access/rest/router/metrics_test.go @@ -1,6 +1,7 @@ package router import ( + "net/http" "testing" "time" @@ -9,6 +10,7 @@ import ( ) type testCase struct { + method string name string url string expected string @@ -17,112 +19,174 @@ type testCase struct { func testCases() []testCase { return []testCase{ { + method: http.MethodPost, name: "/v1/transactions", url: "/v1/transactions", expected: "createTransaction", }, { + method: http.MethodGet, + name: "/v1/transactions", + url: "/v1/transactions", + expected: "getTransactionsByBlock", + }, + { + method: http.MethodGet, name: "/v1/transactions/{id}", url: "/v1/transactions/53730d3f3d2d2f46cb910b16db817d3a62adaaa72fdb3a92ee373c37c5b55a76", expected: "getTransactionByID", }, { + method: http.MethodGet, name: "/v1/transactions/{index}", url: "/v1/transactions/12345678", expected: "getTransactionByID", }, { + method: http.MethodGet, + name: "/v1/transaction_results", + url: "/v1/transaction_results", + expected: "getTransactionResultsByBlock", + }, + { + method: http.MethodGet, name: "/v1/transaction_results/{id}", url: "/v1/transaction_results/53730d3f3d2d2f46cb910b16db817d3a62adaaa72fdb3a92ee373c37c5b55a76", expected: "getTransactionResultByID", }, { + method: http.MethodGet, name: "/v1/transaction_results/{index}", url: "/v1/transaction_results/12345678", expected: "getTransactionResultByID", }, { + method: http.MethodGet, name: "/v1/blocks", url: "/v1/blocks", expected: "getBlocksByHeight", }, { + method: http.MethodGet, name: "/v1/blocks/{id}", url: "/v1/blocks/53730d3f3d2d2f46cb910b16db817d3a62adaaa72fdb3a92ee373c37c5b55a76", expected: "getBlocksByIDs", }, { + method: http.MethodGet, name: "/v1/blocks/{id}/payload", url: "/v1/blocks/53730d3f3d2d2f46cb910b16db817d3a62adaaa72fdb3a92ee373c37c5b55a76/payload", expected: "getBlockPayloadByID", }, { + method: http.MethodGet, name: "/v1/execution_results/{id}", url: "/v1/execution_results/53730d3f3d2d2f46cb910b16db817d3a62adaaa72fdb3a92ee373c37c5b55a76", expected: "getExecutionResultByID", }, { + method: http.MethodGet, name: "/v1/execution_results", url: "/v1/execution_results", expected: "getExecutionResultByBlockID", }, { + method: http.MethodGet, + name: "/v1/execution_receipts", + url: "/v1/execution_receipts", + expected: "getExecutionReceiptsByBlockID", + }, + { + method: http.MethodGet, + name: "/v1/execution_receipts/results/{id}", + url: "/v1/execution_receipts/results/53730d3f3d2d2f46cb910b16db817d3a62adaaa72fdb3a92ee373c37c5b55a76", + expected: "getExecutionReceiptsByResultID", + }, + { + method: http.MethodGet, name: "/v1/collections/{id}", url: "/v1/collections/53730d3f3d2d2f46cb910b16db817d3a62adaaa72fdb3a92ee373c37c5b55a76", expected: "getCollectionByID", }, { + method: http.MethodPost, name: "/v1/scripts", url: "/v1/scripts", expected: "executeScript", }, { + method: http.MethodGet, name: "/v1/accounts/{address}", url: "/v1/accounts/6a587be304c1224c", expected: "getAccount", }, { + method: http.MethodGet, name: "/v1/accounts/{address}/balance", url: "/v1/accounts/6a587be304c1224c/balance", expected: "getAccountBalance", }, { + method: http.MethodGet, name: "/v1/accounts/{address}/keys/{index}", url: "/v1/accounts/6a587be304c1224c/keys/0", expected: "getAccountKeyByIndex", }, { + method: http.MethodGet, name: "/v1/accounts/{address}/keys", url: "/v1/accounts/6a587be304c1224c/keys", expected: "getAccountKeys", }, { + method: http.MethodGet, name: "/v1/events", url: "/v1/events", expected: "getEvents", }, { + method: http.MethodGet, name: "/v1/network/parameters", url: "/v1/network/parameters", expected: "getNetworkParameters", }, { + method: http.MethodGet, name: "/v1/node_version_info", url: "/v1/node_version_info", expected: "getNodeVersionInfo", }, { + method: http.MethodGet, name: "/v1/subscribe_events", url: "/v1/subscribe_events", expected: "subscribeEvents", }, + { + method: http.MethodGet, + name: "/experimental/v1/accounts/{address}/transactions", + url: "/experimental/v1/accounts/6a587be304c1224c/transactions", + expected: "getAccountTransactions", + }, + { + method: http.MethodGet, + name: "/experimental/v1/accounts/{address}/ft/transfers", + url: "/experimental/v1/accounts/6a587be304c1224c/ft/transfers", + expected: "getAccountFungibleTokenTransfers", + }, + { + method: http.MethodGet, + name: "/experimental/v1/accounts/{address}/nft/transfers", + url: "/experimental/v1/accounts/6a587be304c1224c/nft/transfers", + expected: "getAccountNonFungibleTokenTransfers", + }, } } func TestURLToRoute(t *testing.T) { for _, tt := range testCases() { - t.Run(tt.name, func(t *testing.T) { - got, err := URLToRoute(tt.url) + t.Run(tt.method+" "+tt.name, func(t *testing.T) { + got, err := MethodURLToRoute(tt.method, tt.url) require.NoError(t, err) assert.Equal(t, tt.expected, got) }) @@ -131,12 +195,12 @@ func TestURLToRoute(t *testing.T) { func TestBenchmarkURLToRoute(t *testing.T) { for _, tt := range testCases() { - t.Run(tt.name, func(t *testing.T) { + t.Run(tt.method+" "+tt.name, func(t *testing.T) { start := time.Now() - for i := 0; i < 100_000; i++ { - _, _ = URLToRoute(tt.url) + for range 100_000 { + _, _ = MethodURLToRoute(tt.method, tt.url) } - t.Logf("%s: %v", tt.name, time.Since(start)/100_000) + t.Logf("%s %s: %v", tt.method, tt.name, time.Since(start)/100_000) }) } } diff --git a/engine/access/rest/router/router.go b/engine/access/rest/router/router.go index f9818b9fbcb..53b9dc01832 100644 --- a/engine/access/rest/router/router.go +++ b/engine/access/rest/router/router.go @@ -7,8 +7,11 @@ import ( "github.com/rs/zerolog" "github.com/onflow/flow-go/access" + "github.com/onflow/flow-go/access/backends/extended" "github.com/onflow/flow-go/engine/access/rest/common/middleware" "github.com/onflow/flow-go/engine/access/rest/common/models" + "github.com/onflow/flow-go/engine/access/rest/experimental" + experimentalmodels "github.com/onflow/flow-go/engine/access/rest/experimental/models" flowhttp "github.com/onflow/flow-go/engine/access/rest/http" "github.com/onflow/flow-go/engine/access/rest/websockets" dp "github.com/onflow/flow-go/engine/access/rest/websockets/data_providers" @@ -18,13 +21,15 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" ) // RouterBuilder is a utility for building HTTP routers with common middleware and routes. type RouterBuilder struct { - logger zerolog.Logger - router *mux.Router - v1SubRouter *mux.Router + logger zerolog.Logger + router *mux.Router + v1SubRouter *mux.Router + restCollector module.RestMetrics LinkGenerator models.LinkGenerator } @@ -32,7 +37,8 @@ type RouterBuilder struct { // NewRouterBuilder creates a new RouterBuilder instance with common middleware and a v1 sub-router. func NewRouterBuilder( logger zerolog.Logger, - restCollector module.RestMetrics) *RouterBuilder { + restCollector module.RestMetrics, +) *RouterBuilder { router := mux.NewRouter().StrictSlash(true) v1SubRouter := router.PathPrefix("/v1").Subrouter() @@ -46,6 +52,7 @@ func NewRouterBuilder( logger: logger, router: router, v1SubRouter: v1SubRouter, + restCollector: restCollector, LinkGenerator: models.NewLinkGeneratorImpl(v1SubRouter), } } @@ -78,15 +85,17 @@ func (b *RouterBuilder) AddLegacyWebsocketsRoutes( stateStreamConfig backend.Config, maxRequestSize int64, maxResponseSize int64, + limiter *limiters.ConcurrencyLimiter, ) *RouterBuilder { - for _, r := range WSLegacyRoutes { h := legacyws.NewWSHandler(b.logger, stateStreamApi, r.Handler, chain, stateStreamConfig, maxRequestSize, maxResponseSize) + handler := websockets.NewConnectionLimitedHandler(b.logger, h.HttpHandler, h, limiter) + b.v1SubRouter. Methods(r.Method). Path(r.Pattern). Name(r.Name). - Handler(h) + Handler(handler) } return b @@ -99,14 +108,41 @@ func (b *RouterBuilder) AddWebsocketsRoute( maxRequestSize int64, maxResponseSize int64, dataProviderFactory dp.DataProviderFactory, + streamLimiter *limiters.ConcurrencyLimiter, ) *RouterBuilder { - handler := websockets.NewWebSocketHandler(ctx, b.logger, config, chain, maxRequestSize, maxResponseSize, dataProviderFactory) + h := websockets.NewWebSocketHandler(ctx, b.logger, config, chain, maxRequestSize, maxResponseSize, dataProviderFactory, streamLimiter) b.v1SubRouter. Methods(http.MethodGet). Path("/ws"). Name("ws"). - Handler(handler) + Handler(h) + + return b +} + +// AddExperimentalRoutes adds experimental API routes under the /experimental prefix. +func (b *RouterBuilder) AddExperimentalRoutes( + backend extended.API, + chain flow.Chain, + maxRequestSize int64, + maxResponseSize int64, +) *RouterBuilder { + router := b.router.PathPrefix("/experimental/v1").Subrouter() + router.Use(middleware.LoggingMiddleware(b.logger)) + router.Use(middleware.QueryExpandable()) + router.Use(middleware.QuerySelect()) + router.Use(middleware.MetricsMiddleware(b.restCollector)) + experimentalLinkGenerator := experimentalmodels.NewLinkGeneratorImpl(router, b.LinkGenerator) + + for _, r := range ExperimentalRoutes { + h := experimental.NewHandler(b.logger, backend, r.Handler, experimentalLinkGenerator, chain, maxRequestSize, maxResponseSize) + router. + Methods(r.Method). + Path(r.Pattern). + Name(r.Name). + Handler(h) + } return b } diff --git a/engine/access/rest/router/router_test_helpers.go b/engine/access/rest/router/router_test_helpers.go index 7abd297f39b..17cfc5cbe80 100644 --- a/engine/access/rest/router/router_test_helpers.go +++ b/engine/access/rest/router/router_test_helpers.go @@ -15,12 +15,14 @@ import ( "github.com/stretchr/testify/require" "github.com/onflow/flow-go/access" + "github.com/onflow/flow-go/access/backends/extended" "github.com/onflow/flow-go/access/mock" "github.com/onflow/flow-go/engine/access/state_stream" "github.com/onflow/flow-go/engine/access/state_stream/backend" "github.com/onflow/flow-go/engine/access/subscription" commonrpc "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/metrics" "github.com/onflow/flow-go/utils/unittest" ) @@ -136,7 +138,7 @@ func ExecuteRequest(req *http.Request, backend access.API) *httptest.ResponseRec return rr } -func ExecuteLegacyWsRequest(req *http.Request, stateStreamApi state_stream.API, responseRecorder *TestHijackResponseRecorder, chain flow.Chain) { +func ExecuteLegacyWsRequest(t *testing.T, req *http.Request, stateStreamApi state_stream.API, responseRecorder *TestHijackResponseRecorder, chain flow.Chain) { restCollector := metrics.NewNoopCollector() config := backend.Config{ @@ -145,12 +147,14 @@ func ExecuteLegacyWsRequest(req *http.Request, stateStreamApi state_stream.API, HeartbeatInterval: subscription.DefaultHeartbeatInterval, } + limiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + require.NoError(t, err) router := NewRouterBuilder( unittest.Logger(), restCollector, ).AddLegacyWebsocketsRoutes( stateStreamApi, - chain, config, commonrpc.DefaultAccessMaxRequestSize, commonrpc.DefaultAccessMaxResponseSize, + chain, config, commonrpc.DefaultAccessMaxRequestSize, commonrpc.DefaultAccessMaxResponseSize, limiter, ).Build() router.ServeHTTP(responseRecorder, req) } @@ -159,6 +163,30 @@ func AssertOKResponse(t *testing.T, req *http.Request, expectedRespBody string, AssertResponse(t, req, http.StatusOK, expectedRespBody, backend) } +// ExecuteExperimentalRequest builds a router with experimental routes and executes the given request. +// Named routes from the main v1 API (e.g. getTransactionByID) are registered as no-ops so that +// the link generator can produce proper expandable links without requiring a full access backend. +func ExecuteExperimentalRequest(req *http.Request, backend extended.API) *httptest.ResponseRecorder { + builder := NewRouterBuilder( + unittest.Logger(), + metrics.NewNoopCollector(), + ) + noop := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) + for _, r := range Routes { + builder.v1SubRouter.Methods(r.Method).Path(r.Pattern).Name(r.Name).Handler(noop) + } + router := builder.AddExperimentalRoutes( + backend, + flow.Testnet.Chain(), + commonrpc.DefaultAccessMaxRequestSize, + commonrpc.DefaultAccessMaxResponseSize, + ).Build() + + rr := httptest.NewRecorder() + router.ServeHTTP(rr, req) + return rr +} + func AssertResponse(t *testing.T, req *http.Request, status int, expectedRespBody string, backend *mock.API) { rr := ExecuteRequest(req, backend) actualResponseBody := rr.Body.String() diff --git a/engine/access/rest/router/routes_experimental.go b/engine/access/rest/router/routes_experimental.go new file mode 100644 index 00000000000..d454244707a --- /dev/null +++ b/engine/access/rest/router/routes_experimental.go @@ -0,0 +1,69 @@ +package router + +import ( + "net/http" + + "github.com/onflow/flow-go/engine/access/rest/experimental" + "github.com/onflow/flow-go/engine/access/rest/experimental/routes" +) + +// Route defines an experimental API route. +type experimentalRoute struct { + Name string + Method string + Pattern string + Handler experimental.ApiHandlerFunc +} + +// Routes lists all experimental API routes. +var ExperimentalRoutes = []experimentalRoute{{ + Method: http.MethodGet, + Pattern: "/accounts/{address}/transactions", + Name: "getAccountTransactions", + Handler: routes.GetAccountTransactions, +}, { + Method: http.MethodGet, + Pattern: "/accounts/{address}/ft/transfers", + Name: "getAccountFungibleTokenTransfers", + Handler: routes.GetAccountFungibleTokenTransfers, +}, { + Method: http.MethodGet, + Pattern: "/accounts/{address}/nft/transfers", + Name: "getAccountNonFungibleTokenTransfers", + Handler: routes.GetAccountNonFungibleTokenTransfers, +}, { + Method: http.MethodGet, + Pattern: "/scheduled", + Name: "getScheduledTransactions", + Handler: routes.GetScheduledTransactions, +}, { + Method: http.MethodGet, + Pattern: "/scheduled/transaction/{id}", + Name: "getScheduledTransaction", + Handler: routes.GetScheduledTransaction, +}, { + Method: http.MethodGet, + Pattern: "/accounts/{address}/scheduled", + Name: "getScheduledTransactionsByAddress", + Handler: routes.GetScheduledTransactionsByAddress, +}, { + Method: http.MethodGet, + Pattern: "/contracts", + Name: "getContracts", + Handler: routes.GetContracts, +}, { + Method: http.MethodGet, + Pattern: "/accounts/{address}/contracts", + Name: "getContractsByAddress", + Handler: routes.GetContractsByAddress, +}, { + Method: http.MethodGet, + Pattern: "/contracts/{identifier}", + Name: "getContract", + Handler: routes.GetContract, +}, { + Method: http.MethodGet, + Pattern: "/contracts/{identifier}/deployments", + Name: "getContractDeployments", + Handler: routes.GetContractDeployments, +}} diff --git a/engine/access/rest/router/http_routes.go b/engine/access/rest/router/routes_main.go similarity index 80% rename from engine/access/rest/router/http_routes.go rename to engine/access/rest/router/routes_main.go index 5032f591142..46d3cc1f3af 100644 --- a/engine/access/rest/router/http_routes.go +++ b/engine/access/rest/router/routes_main.go @@ -19,6 +19,11 @@ var Routes = []route{{ Pattern: "/transactions/{id}", Name: "getTransactionByID", Handler: routes.GetTransactionByID, +}, { + Method: http.MethodGet, + Pattern: "/transactions", + Name: "getTransactionsByBlock", + Handler: routes.GetTransactionsByBlock, }, { Method: http.MethodPost, Pattern: "/transactions", @@ -29,6 +34,11 @@ var Routes = []route{{ Pattern: "/transaction_results/{id}", Name: "getTransactionResultByID", Handler: routes.GetTransactionResultByID, +}, { + Method: http.MethodGet, + Pattern: "/transaction_results", + Name: "getTransactionResultsByBlock", + Handler: routes.GetTransactionResultsByBlock, }, { Method: http.MethodGet, Pattern: "/blocks/{id}", @@ -54,6 +64,16 @@ var Routes = []route{{ Pattern: "/execution_results", Name: "getExecutionResultByBlockID", Handler: routes.GetExecutionResultsByBlockIDs, +}, { + Method: http.MethodGet, + Pattern: "/execution_receipts", + Name: "getExecutionReceiptsByBlockID", + Handler: routes.GetExecutionReceiptsByBlockID, +}, { + Method: http.MethodGet, + Pattern: "/execution_receipts/results/{id}", + Name: "getExecutionReceiptsByResultID", + Handler: routes.GetExecutionReceiptsByResultID, }, { Method: http.MethodGet, Pattern: "/collections/{id}", diff --git a/engine/access/rest/router/ws_routes.go b/engine/access/rest/router/routes_ws_legacy.go similarity index 100% rename from engine/access/rest/router/ws_routes.go rename to engine/access/rest/router/routes_ws_legacy.go diff --git a/engine/access/rest/server.go b/engine/access/rest/server.go index ce31c99ebf1..2dd3bf3520b 100644 --- a/engine/access/rest/server.go +++ b/engine/access/rest/server.go @@ -1,6 +1,7 @@ package rest import ( + "errors" "net/http" "time" @@ -8,6 +9,7 @@ import ( "github.com/rs/zerolog" "github.com/onflow/flow-go/access" + "github.com/onflow/flow-go/access/backends/extended" "github.com/onflow/flow-go/engine/access/rest/router" "github.com/onflow/flow-go/engine/access/rest/websockets" dp "github.com/onflow/flow-go/engine/access/rest/websockets/data_providers" @@ -16,6 +18,7 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" ) const ( @@ -50,10 +53,16 @@ func NewServer( stateStreamConfig backend.Config, enableNewWebsocketsStreamAPI bool, wsConfig websockets.Config, + extendedBackend extended.API, + limiter *limiters.ConcurrencyLimiter, ) (*http.Server, error) { + if limiter == nil && (stateStreamApi != nil || enableNewWebsocketsStreamAPI) { + return nil, errors.New("stream limiter is required when websocket routes are enabled") + } + builder := router.NewRouterBuilder(logger, restCollector).AddRestRoutes(serverAPI, chain, config.MaxRequestSize, config.MaxResponseSize) if stateStreamApi != nil { - builder.AddLegacyWebsocketsRoutes(stateStreamApi, chain, stateStreamConfig, config.MaxRequestSize, config.MaxResponseSize) + builder.AddLegacyWebsocketsRoutes(stateStreamApi, chain, stateStreamConfig, config.MaxRequestSize, config.MaxResponseSize, limiter) } dataProviderFactory := dp.NewDataProviderFactory( @@ -67,7 +76,11 @@ func NewServer( ) if enableNewWebsocketsStreamAPI { - builder.AddWebsocketsRoute(ctx, chain, wsConfig, config.MaxRequestSize, config.MaxResponseSize, dataProviderFactory) + builder.AddWebsocketsRoute(ctx, chain, wsConfig, config.MaxRequestSize, config.MaxResponseSize, dataProviderFactory, limiter) + } + + if extendedBackend != nil { + builder.AddExperimentalRoutes(extendedBackend, chain, config.MaxRequestSize, config.MaxResponseSize) } c := cors.New(cors.Options{ diff --git a/engine/access/rest/util/select_filter.go b/engine/access/rest/util/select_filter.go index 4f7172a7ff5..8d6ad493c71 100644 --- a/engine/access/rest/util/select_filter.go +++ b/engine/access/rest/util/select_filter.go @@ -7,7 +7,7 @@ import ( // SelectFilter selects the specified keys from the given object. The keys are in the json dot notation and must refer // to leaf elements e.g. payload.collection_guarantees.signer_ids -func SelectFilter(object interface{}, selectKeys []string) (interface{}, error) { +func SelectFilter(object any, selectKeys []string) (any, error) { // avoid doing any work if no select keys provided if len(selectKeys) == 0 { return object, nil @@ -18,7 +18,7 @@ func SelectFilter(object interface{}, selectKeys []string) (interface{}, error) return nil, err } - var outputMap = new(interface{}) + var outputMap = new(any) err = json.Unmarshal(marshalled, outputMap) if err != nil { return nil, err @@ -26,10 +26,10 @@ func SelectFilter(object interface{}, selectKeys []string) (interface{}, error) filter := sliceToMap(selectKeys) switch itemAsType := (*outputMap).(type) { - case []interface{}: + case []any: filteredSlice, _ := filterSlice(itemAsType, "", filter) *outputMap = filteredSlice - case map[string]interface{}: + case map[string]any: filterObject(itemAsType, "", filter) } return *outputMap, nil @@ -37,7 +37,7 @@ func SelectFilter(object interface{}, selectKeys []string) (interface{}, error) // filterObject filters a json struct. Prefix is the key prefix to use to find keys from the filterMap // Leaf elements whose keys are not found in the filter map will be removed -func filterObject(jsonStruct map[string]interface{}, prefix string, filterMap map[string]bool) { +func filterObject(jsonStruct map[string]any, prefix string, filterMap map[string]bool) { for key, item := range jsonStruct { newPrefix := jsonPath(prefix, key) // if the leaf object is the key, go to others @@ -45,7 +45,7 @@ func filterObject(jsonStruct map[string]interface{}, prefix string, filterMap ma continue } switch itemAsType := item.(type) { - case []interface{}: + case []any: // if the value of a key is a list, call filterSlice // e.g. { a : [ {b:1}, {b:2}...] itemAsType, simpleSlice := filterSlice(itemAsType, newPrefix, filterMap) @@ -60,7 +60,7 @@ func filterObject(jsonStruct map[string]interface{}, prefix string, filterMap ma if len(itemAsType) == 0 { delete(jsonStruct, key) } - case map[string]interface{}: + case map[string]any: // if the value of a key is an object, then recurse // e.g. { a : { b: 1 } } filterObject(itemAsType, newPrefix, filterMap) @@ -80,10 +80,10 @@ func filterObject(jsonStruct map[string]interface{}, prefix string, filterMap ma // filterSlice filters a json slice. Prefix is the key prefix to use to find keys from the filterMap // Leaf elements whose keys are not found in the filter map will be removed // The function returns the modified slice and true if the slice only contains simple non-struct, non-list elements -func filterSlice(jsonSlice []interface{}, prefix string, filterMap map[string]bool) ([]interface{}, bool) { +func filterSlice(jsonSlice []any, prefix string, filterMap map[string]bool) ([]any, bool) { for _, item := range jsonSlice { switch itemAsType := item.(type) { - case []interface{}: + case []any: // if the slice has other slice as elements, recurse // e.g [[{b:1}, {b:2}...]] var sliceType bool @@ -91,16 +91,16 @@ func filterSlice(jsonSlice []interface{}, prefix string, filterMap map[string]bo if len(itemAsType) == 0 { // since all elements of the slice are the same, if one sub-slice has been filtered out, we can safely // remove all sub-slices and return (instead of iterating all slice elements) - return make([]interface{}, 0), sliceType + return make([]any, 0), sliceType } - case map[string]interface{}: + case map[string]any: // if the slice has structs as elements, call filterObject // e.g. [{a:1, b:2}, {a:3, b:4}] filterObject(itemAsType, prefix, filterMap) if len(itemAsType) == 0 { // since all elements of the slice are the same, if one struct element has been filtered out, we can safely // remove all struct elements and return (instead of iterating all slice elements) - return make([]interface{}, 0), false + return make([]any, 0), false } default: // if the elements are neither a slice nor a struct, then return the slice and true to indicate the slice has diff --git a/engine/access/rest/util/select_filter_test.go b/engine/access/rest/util/select_filter_test.go index 61c194b039a..6a927d961d7 100644 --- a/engine/access/rest/util/select_filter_test.go +++ b/engine/access/rest/util/select_filter_test.go @@ -73,11 +73,11 @@ func TestSelectFilter(t *testing.T) { } func testFilter(t *testing.T, inputJson, exepectedJson string, description string, selectKeys ...string) { - var outputInterface interface{} + var outputInterface any if strings.HasPrefix(inputJson, "{") { - outputInterface = make(map[string]interface{}) + outputInterface = make(map[string]any) } else { - outputInterface = make([]interface{}, 0) + outputInterface = make([]any, 0) } err := json.Unmarshal([]byte(inputJson), &outputInterface) require.NoErrorf(t, err, description) diff --git a/engine/access/rest/websockets/connection_limited_handler.go b/engine/access/rest/websockets/connection_limited_handler.go new file mode 100644 index 00000000000..faff85ab296 --- /dev/null +++ b/engine/access/rest/websockets/connection_limited_handler.go @@ -0,0 +1,43 @@ +package websockets + +import ( + "net/http" + + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/module/limiters" +) + +type ConnectionLimitedHandler struct { + *common.HttpHandler + + log zerolog.Logger + handler http.Handler + + connections *limiters.ConcurrencyLimiter +} + +func NewConnectionLimitedHandler( + log zerolog.Logger, + httpHandler *common.HttpHandler, + handler http.Handler, + limiter *limiters.ConcurrencyLimiter, +) *ConnectionLimitedHandler { + return &ConnectionLimitedHandler{ + HttpHandler: httpHandler, + log: log, + handler: handler, + connections: limiter, + } +} + +func (h *ConnectionLimitedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + allowed := h.connections.Allow(func() { + h.handler.ServeHTTP(w, r) + }) + if !allowed { + h.HttpHandler.ErrorHandler(w, common.NewRestError(http.StatusTooManyRequests, "maximum number of connections reached", nil), h.log) + return + } +} diff --git a/engine/access/rest/websockets/connection_limited_handler_test.go b/engine/access/rest/websockets/connection_limited_handler_test.go new file mode 100644 index 00000000000..303262143ee --- /dev/null +++ b/engine/access/rest/websockets/connection_limited_handler_test.go @@ -0,0 +1,46 @@ +package websockets + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/engine/access/rest/common" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/limiters" +) + +func TestConnectionLimitedHandler_RejectsWhenLimitReached(t *testing.T) { + limiter, err := limiters.NewConcurrencyLimiter(1) + require.NoError(t, err) + + inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + httpHandler := common.NewHttpHandler(zerolog.Nop(), flow.Localnet.Chain(), 1024, 1024) + handler := NewConnectionLimitedHandler(zerolog.Nop(), httpHandler, inner, limiter) + + // Saturate the limiter by blocking inside Allow. + started := make(chan struct{}) + unblock := make(chan struct{}) + go func() { + limiter.Allow(func() { + close(started) + <-unblock + }) + }() + <-started + + // A request while the limiter is full must return 429. + req := httptest.NewRequest(http.MethodGet, "/ws", nil) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + assert.Equal(t, http.StatusTooManyRequests, rec.Code) + + close(unblock) +} diff --git a/engine/access/rest/websockets/controller.go b/engine/access/rest/websockets/controller.go index bf201afe95f..02401f77056 100644 --- a/engine/access/rest/websockets/controller.go +++ b/engine/access/rest/websockets/controller.go @@ -89,6 +89,7 @@ import ( dp "github.com/onflow/flow-go/engine/access/rest/websockets/data_providers" "github.com/onflow/flow-go/engine/access/rest/websockets/models" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/utils/concurrentmap" ) @@ -135,7 +136,8 @@ type Controller struct { dataProviders *concurrentmap.Map[SubscriptionID, dp.DataProvider] dataProviderFactory dp.DataProviderFactory dataProvidersGroup *sync.WaitGroup - limiter *rate.Limiter + rateLimiter *rate.Limiter + streamLimiter *limiters.ConcurrencyLimiter keepaliveConfig KeepaliveConfig } @@ -145,10 +147,15 @@ func NewWebSocketController( config Config, conn WebsocketConnection, dataProviderFactory dp.DataProviderFactory, -) *Controller { - var limiter *rate.Limiter + streamLimiter *limiters.ConcurrencyLimiter, +) (*Controller, error) { + if streamLimiter == nil { + return nil, errors.New("stream limiter is required") + } + + var rateLimiter *rate.Limiter if config.MaxResponsesPerSecond > 0 { - limiter = rate.NewLimiter(rate.Limit(config.MaxResponsesPerSecond), 1) + rateLimiter = rate.NewLimiter(rate.Limit(config.MaxResponsesPerSecond), 1) } return &Controller{ @@ -159,9 +166,10 @@ func NewWebSocketController( dataProviders: concurrentmap.New[SubscriptionID, dp.DataProvider](), dataProviderFactory: dataProviderFactory, dataProvidersGroup: &sync.WaitGroup{}, - limiter: limiter, + rateLimiter: rateLimiter, + streamLimiter: streamLimiter, keepaliveConfig: DefaultKeepaliveConfig(), - } + }, nil } // HandleConnection manages the lifecycle of a WebSocket connection, @@ -442,8 +450,20 @@ func (c *Controller) handleSubscribe(ctx context.Context, msg models.SubscribeMe return } + // Check if the global stream limit has been reached. + if !c.streamLimiter.Acquire() { + err := fmt.Errorf("error creating new subscription: maximum number of streams reached") + c.writeErrorResponse( + ctx, + err, + wrapErrorMessage(http.StatusTooManyRequests, err.Error(), models.SubscribeAction, msg.SubscriptionID), + ) + return + } + subscriptionID, err := c.parseOrCreateSubscriptionID(msg.SubscriptionID) if err != nil { + c.streamLimiter.Release() err = fmt.Errorf("error parsing subscription id: %w", err) c.writeErrorResponse( ctx, @@ -456,6 +476,7 @@ func (c *Controller) handleSubscribe(ctx context.Context, msg models.SubscribeMe // register new provider provider, err := c.dataProviderFactory.NewDataProvider(ctx, subscriptionID.String(), msg.Topic, msg.Arguments, c.multiplexedStream) if err != nil { + c.streamLimiter.Release() err = fmt.Errorf("error creating data provider: %w", err) c.writeErrorResponse( ctx, @@ -478,6 +499,8 @@ func (c *Controller) handleSubscribe(ctx context.Context, msg models.SubscribeMe // run provider c.dataProvidersGroup.Add(1) go func() { + defer c.streamLimiter.Release() + err = provider.Run() if err != nil { err = fmt.Errorf("internal error: %w", err) @@ -604,9 +627,9 @@ func (c *Controller) parseOrCreateSubscriptionID(id string) (SubscriptionID, err // An error is returned if the context is canceled or the expected wait time exceeds the context's // deadline. func (c *Controller) checkRateLimit(ctx context.Context) error { - if c.limiter == nil { + if c.rateLimiter == nil { return nil } - return c.limiter.WaitN(ctx, 1) + return c.rateLimiter.WaitN(ctx, 1) } diff --git a/engine/access/rest/websockets/controller_test.go b/engine/access/rest/websockets/controller_test.go index 44df8a0746b..14e90613613 100644 --- a/engine/access/rest/websockets/controller_test.go +++ b/engine/access/rest/websockets/controller_test.go @@ -23,6 +23,7 @@ import ( connmock "github.com/onflow/flow-go/engine/access/rest/websockets/mock" "github.com/onflow/flow-go/engine/access/rest/websockets/models" "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/utils/unittest" ) @@ -30,8 +31,9 @@ import ( type WsControllerSuite struct { suite.Suite - logger zerolog.Logger - wsConfig Config + logger zerolog.Logger + wsConfig Config + streamLimiter *limiters.ConcurrencyLimiter } func TestControllerSuite(t *testing.T) { @@ -42,6 +44,10 @@ func TestControllerSuite(t *testing.T) { func (s *WsControllerSuite) SetupTest() { s.logger = unittest.Logger() s.wsConfig = NewDefaultWebsocketConfig() + + var err error + s.streamLimiter, err = limiters.NewConcurrencyLimiter(1000) + s.Require().NoError(err) } // TestSubscribeRequest tests the subscribe to topic flow. @@ -51,7 +57,8 @@ func (s *WsControllerSuite) TestSubscribeRequest() { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -115,7 +122,8 @@ func (s *WsControllerSuite) TestSubscribeRequest() { t.Parallel() conn, dataProviderFactory, _ := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) type Request struct { Action string `json:"action"` @@ -164,7 +172,8 @@ func (s *WsControllerSuite) TestSubscribeRequest() { t.Parallel() conn, dataProviderFactory, _ := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -201,7 +210,8 @@ func (s *WsControllerSuite) TestSubscribeRequest() { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) // data provider might finish on its own or controller will close it via Close() dataProvider.On("Close").Return(nil).Maybe() @@ -245,12 +255,156 @@ func (s *WsControllerSuite) TestSubscribeRequest() { }) } +// TestGlobalStreamLimiter verifies that the global stream limiter correctly +// controls subscription creation and releases slots on completion or error. +func (s *WsControllerSuite) TestGlobalStreamLimiter() { + s.T().Run("Rejects subscription when global limit reached", func(t *testing.T) { + t.Parallel() + + // Create a limiter with capacity 1 and exhaust it. + streamLimiter, err := limiters.NewConcurrencyLimiter(1) + require.NoError(t, err) + require.True(t, streamLimiter.Acquire()) // exhaust the single slot + + conn, dataProviderFactory, _ := newControllerMocks(t) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, streamLimiter) + require.NoError(t, err) + + done := make(chan struct{}) + subscriptionID := "dummy-id" + s.expectSubscribeRequest(t, conn, subscriptionID) + + conn. + On("WriteJSON", mock.Anything). + Return(func(msg interface{}) error { + defer close(done) + + response, ok := msg.(models.BaseMessageResponse) + require.True(t, ok) + require.NotEmpty(t, response.Error) + require.Equal(t, http.StatusTooManyRequests, response.Error.Code) + require.Contains(t, response.Error.Message, "maximum number of streams reached") + + return &websocket.CloseError{Code: websocket.CloseNormalClosure} + }) + + s.expectCloseConnection(conn, done) + + controller.HandleConnection(context.Background()) + + conn.AssertExpectations(t) + // Factory should never be called — rejected before provider creation. + dataProviderFactory.AssertExpectations(t) + + // The externally acquired slot must still be held. + require.False(t, streamLimiter.Acquire(), "externally acquired slot should still be held") + streamLimiter.Release() + }) + + s.T().Run("Releases slot when provider creation fails", func(t *testing.T) { + t.Parallel() + + streamLimiter, err := limiters.NewConcurrencyLimiter(1) + require.NoError(t, err) + + conn, dataProviderFactory, _ := newControllerMocks(t) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, streamLimiter) + require.NoError(t, err) + + dataProviderFactory. + On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(nil, fmt.Errorf("invalid topic")). + Once() + + done := make(chan struct{}) + subscriptionID := "dummy-id" + s.expectSubscribeRequest(t, conn, subscriptionID) + + conn. + On("WriteJSON", mock.Anything). + Return(func(msg interface{}) error { + defer close(done) + + response, ok := msg.(models.BaseMessageResponse) + require.True(t, ok) + require.NotEmpty(t, response.Error) + require.Equal(t, http.StatusBadRequest, response.Error.Code) + + return &websocket.CloseError{Code: websocket.CloseNormalClosure} + }) + + s.expectCloseConnection(conn, done) + + controller.HandleConnection(context.Background()) + + // Slot must have been released despite the error. + require.True(t, streamLimiter.Acquire(), "slot should be released after provider creation failure") + streamLimiter.Release() + + conn.AssertExpectations(t) + dataProviderFactory.AssertExpectations(t) + }) + + s.T().Run("Releases slot when provider completes", func(t *testing.T) { + t.Parallel() + + streamLimiter, err := limiters.NewConcurrencyLimiter(1) + require.NoError(t, err) + + conn, dataProviderFactory, dataProvider := newControllerMocks(t) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, streamLimiter) + require.NoError(t, err) + + dataProvider.On("Close").Return(nil).Maybe() + dataProvider. + On("Run", mock.Anything). + Return(nil). + Once() + + dataProviderFactory. + On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(dataProvider, nil). + Once() + + done := make(chan struct{}) + subscriptionID := "dummy-id" + s.expectSubscribeRequest(t, conn, subscriptionID) + + // When the subscribe OK response is written, close done to trigger + // connection shutdown. The provider runs and completes immediately + // (Run returns nil), so no further writes are expected. + conn. + On("WriteJSON", mock.Anything). + Run(func(args mock.Arguments) { + response, ok := args.Get(0).(models.SubscribeMessageResponse) + require.True(t, ok) + require.Equal(t, subscriptionID, response.SubscriptionID) + close(done) + }). + Return(nil). + Once() + + s.expectCloseConnection(conn, done) + + controller.HandleConnection(context.Background()) + + // Slot must have been released after provider completed. + require.True(t, streamLimiter.Acquire(), "slot should be released after provider completes") + streamLimiter.Release() + + conn.AssertExpectations(t) + dataProviderFactory.AssertExpectations(t) + dataProvider.AssertExpectations(t) + }) +} + func (s *WsControllerSuite) TestUnsubscribeRequest() { s.T().Run("Happy path", func(t *testing.T) { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -318,7 +472,8 @@ func (s *WsControllerSuite) TestUnsubscribeRequest() { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -388,7 +543,8 @@ func (s *WsControllerSuite) TestUnsubscribeRequest() { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -461,7 +617,8 @@ func (s *WsControllerSuite) TestListSubscriptions() { s.T().Run("Happy path", func(t *testing.T) { conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -543,7 +700,8 @@ func (s *WsControllerSuite) TestSubscribeBlocks() { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -597,7 +755,8 @@ func (s *WsControllerSuite) TestSubscribeBlocks() { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -682,7 +841,8 @@ func (s *WsControllerSuite) TestRateLimiter() { config := NewDefaultWebsocketConfig() config.MaxResponsesPerSecond = 2 - controller := NewWebSocketController(s.logger, config, conn, nil) + controller, err := NewWebSocketController(s.logger, config, conn, nil, s.streamLimiter) + require.NoError(s.T(), err) // Step 3: Simulate sending messages to the controller's `multiplexedStream`. go func() { @@ -733,9 +893,10 @@ func (s *WsControllerSuite) TestConfigureKeepaliveConnection() { conn.On("SetReadDeadline", mock.Anything).Return(nil) factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) - err := controller.configureKeepalive() + err = controller.configureKeepalive() s.Require().NoError(err, "configureKeepalive should not return an error") conn.AssertExpectations(t) @@ -752,7 +913,8 @@ func (s *WsControllerSuite) TestControllerShutdown() { conn.On("SetPongHandler", mock.AnythingOfType("func(string) error")).Return(nil).Once() factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) // Mock keepalive to return an error done := make(chan struct{}, 1) @@ -786,7 +948,8 @@ func (s *WsControllerSuite) TestControllerShutdown() { conn.On("SetPongHandler", mock.AnythingOfType("func(string) error")).Return(nil).Once() factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) conn. On("ReadJSON", mock.Anything). @@ -803,7 +966,8 @@ func (s *WsControllerSuite) TestControllerShutdown() { t.Parallel() conn, dataProviderFactory, dataProvider := newControllerMocks(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, dataProviderFactory, s.streamLimiter) + require.NoError(t, err) dataProviderFactory. On("NewDataProvider", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -852,7 +1016,8 @@ func (s *WsControllerSuite) TestControllerShutdown() { conn.On("SetPongHandler", mock.AnythingOfType("func(string) error")).Return(nil).Once() factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) ctx, cancel := context.WithCancel(context.Background()) @@ -875,7 +1040,8 @@ func (s *WsControllerSuite) TestControllerShutdown() { wsConfig := s.wsConfig wsConfig.InactivityTimeout = 50 * time.Millisecond - controller := NewWebSocketController(s.logger, wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) conn. On("ReadJSON", mock.Anything). @@ -927,7 +1093,8 @@ func (s *WsControllerSuite) TestKeepaliveRoutine() { }) factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) controller.keepaliveConfig = keepaliveConfig controller.HandleConnection(context.Background()) @@ -942,13 +1109,14 @@ func (s *WsControllerSuite) TestKeepaliveRoutine() { Once() factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) controller.keepaliveConfig = keepaliveConfig ctx, cancel := context.WithCancel(context.Background()) defer cancel() - err := controller.keepalive(ctx) + err = controller.keepalive(ctx) s.Require().Error(err) s.Require().ErrorIs(expectedError, err) }) @@ -961,13 +1129,14 @@ func (s *WsControllerSuite) TestKeepaliveRoutine() { Once() factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) controller.keepaliveConfig = keepaliveConfig ctx, cancel := context.WithCancel(context.Background()) defer cancel() - err := controller.keepalive(ctx) + err = controller.keepalive(ctx) s.Require().Error(err) s.Require().ErrorContains(err, "error sending ping") }) @@ -975,14 +1144,15 @@ func (s *WsControllerSuite) TestKeepaliveRoutine() { s.T().Run("Context cancelled", func(t *testing.T) { conn := connmock.NewWebsocketConnection(t) factory := dpmock.NewDataProviderFactory(t) - controller := NewWebSocketController(s.logger, s.wsConfig, conn, factory) + controller, err := NewWebSocketController(s.logger, s.wsConfig, conn, factory, s.streamLimiter) + require.NoError(t, err) controller.keepaliveConfig = keepaliveConfig ctx, cancel := context.WithCancel(context.Background()) cancel() // Immediately cancel the context // Start the keepalive process with the context canceled - err := controller.keepalive(ctx) + err = controller.keepalive(ctx) s.Require().NoError(err) }) } diff --git a/engine/access/rest/websockets/data_providers/mock/data_provider.go b/engine/access/rest/websockets/data_providers/mock/data_provider.go index 5e6ef7846ae..60b187efe58 100644 --- a/engine/access/rest/websockets/data_providers/mock/data_provider.go +++ b/engine/access/rest/websockets/data_providers/mock/data_provider.go @@ -1,106 +1,248 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - models "github.com/onflow/flow-go/engine/access/rest/websockets/models" + "github.com/onflow/flow-go/engine/access/rest/websockets/models" mock "github.com/stretchr/testify/mock" ) +// NewDataProvider creates a new instance of DataProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDataProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *DataProvider { + mock := &DataProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DataProvider is an autogenerated mock type for the DataProvider type type DataProvider struct { mock.Mock } -// Arguments provides a mock function with no fields -func (_m *DataProvider) Arguments() models.Arguments { - ret := _m.Called() +type DataProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *DataProvider) EXPECT() *DataProvider_Expecter { + return &DataProvider_Expecter{mock: &_m.Mock} +} + +// Arguments provides a mock function for the type DataProvider +func (_mock *DataProvider) Arguments() models.Arguments { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Arguments") } var r0 models.Arguments - if rf, ok := ret.Get(0).(func() models.Arguments); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() models.Arguments); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(models.Arguments) } } - return r0 } -// Close provides a mock function with no fields -func (_m *DataProvider) Close() { - _m.Called() +// DataProvider_Arguments_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Arguments' +type DataProvider_Arguments_Call struct { + *mock.Call +} + +// Arguments is a helper method to define mock.On call +func (_e *DataProvider_Expecter) Arguments() *DataProvider_Arguments_Call { + return &DataProvider_Arguments_Call{Call: _e.mock.On("Arguments")} +} + +func (_c *DataProvider_Arguments_Call) Run(run func()) *DataProvider_Arguments_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DataProvider_Arguments_Call) Return(arguments models.Arguments) *DataProvider_Arguments_Call { + _c.Call.Return(arguments) + return _c +} + +func (_c *DataProvider_Arguments_Call) RunAndReturn(run func() models.Arguments) *DataProvider_Arguments_Call { + _c.Call.Return(run) + return _c +} + +// Close provides a mock function for the type DataProvider +func (_mock *DataProvider) Close() { + _mock.Called() + return +} + +// DataProvider_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type DataProvider_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *DataProvider_Expecter) Close() *DataProvider_Close_Call { + return &DataProvider_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *DataProvider_Close_Call) Run(run func()) *DataProvider_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DataProvider_Close_Call) Return() *DataProvider_Close_Call { + _c.Call.Return() + return _c +} + +func (_c *DataProvider_Close_Call) RunAndReturn(run func()) *DataProvider_Close_Call { + _c.Run(run) + return _c } -// ID provides a mock function with no fields -func (_m *DataProvider) ID() string { - ret := _m.Called() +// ID provides a mock function for the type DataProvider +func (_mock *DataProvider) ID() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// Run provides a mock function with no fields -func (_m *DataProvider) Run() error { - ret := _m.Called() +// DataProvider_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type DataProvider_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *DataProvider_Expecter) ID() *DataProvider_ID_Call { + return &DataProvider_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *DataProvider_ID_Call) Run(run func()) *DataProvider_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DataProvider_ID_Call) Return(s string) *DataProvider_ID_Call { + _c.Call.Return(s) + return _c +} + +func (_c *DataProvider_ID_Call) RunAndReturn(run func() string) *DataProvider_ID_Call { + _c.Call.Return(run) + return _c +} + +// Run provides a mock function for the type DataProvider +func (_mock *DataProvider) Run() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Run") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Topic provides a mock function with no fields -func (_m *DataProvider) Topic() string { - ret := _m.Called() +// DataProvider_Run_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Run' +type DataProvider_Run_Call struct { + *mock.Call +} + +// Run is a helper method to define mock.On call +func (_e *DataProvider_Expecter) Run() *DataProvider_Run_Call { + return &DataProvider_Run_Call{Call: _e.mock.On("Run")} +} + +func (_c *DataProvider_Run_Call) Run(run func()) *DataProvider_Run_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DataProvider_Run_Call) Return(err error) *DataProvider_Run_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DataProvider_Run_Call) RunAndReturn(run func() error) *DataProvider_Run_Call { + _c.Call.Return(run) + return _c +} + +// Topic provides a mock function for the type DataProvider +func (_mock *DataProvider) Topic() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Topic") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// NewDataProvider creates a new instance of DataProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDataProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *DataProvider { - mock := &DataProvider{} - mock.Mock.Test(t) +// DataProvider_Topic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Topic' +type DataProvider_Topic_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Topic is a helper method to define mock.On call +func (_e *DataProvider_Expecter) Topic() *DataProvider_Topic_Call { + return &DataProvider_Topic_Call{Call: _e.mock.On("Topic")} +} - return mock +func (_c *DataProvider_Topic_Call) Run(run func()) *DataProvider_Topic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DataProvider_Topic_Call) Return(s string) *DataProvider_Topic_Call { + _c.Call.Return(s) + return _c +} + +func (_c *DataProvider_Topic_Call) RunAndReturn(run func() string) *DataProvider_Topic_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go b/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go index 61be02fc1b0..8ad7275f4eb 100644 --- a/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go +++ b/engine/access/rest/websockets/data_providers/mock/data_provider_factory.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - data_providers "github.com/onflow/flow-go/engine/access/rest/websockets/data_providers" + "github.com/onflow/flow-go/engine/access/rest/websockets/data_providers" + "github.com/onflow/flow-go/engine/access/rest/websockets/models" mock "github.com/stretchr/testify/mock" - - models "github.com/onflow/flow-go/engine/access/rest/websockets/models" ) +// NewDataProviderFactory creates a new instance of DataProviderFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDataProviderFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *DataProviderFactory { + mock := &DataProviderFactory{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DataProviderFactory is an autogenerated mock type for the DataProviderFactory type type DataProviderFactory struct { mock.Mock } -// NewDataProvider provides a mock function with given fields: ctx, subID, topic, args, stream -func (_m *DataProviderFactory) NewDataProvider(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- interface{}) (data_providers.DataProvider, error) { - ret := _m.Called(ctx, subID, topic, args, stream) +type DataProviderFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *DataProviderFactory) EXPECT() *DataProviderFactory_Expecter { + return &DataProviderFactory_Expecter{mock: &_m.Mock} +} + +// NewDataProvider provides a mock function for the type DataProviderFactory +func (_mock *DataProviderFactory) NewDataProvider(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- interface{}) (data_providers.DataProvider, error) { + ret := _mock.Called(ctx, subID, topic, args, stream) if len(ret) == 0 { panic("no return value specified for NewDataProvider") @@ -26,36 +49,78 @@ func (_m *DataProviderFactory) NewDataProvider(ctx context.Context, subID string var r0 data_providers.DataProvider var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- interface{}) (data_providers.DataProvider, error)); ok { - return rf(ctx, subID, topic, args, stream) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- interface{}) (data_providers.DataProvider, error)); ok { + return returnFunc(ctx, subID, topic, args, stream) } - if rf, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- interface{}) data_providers.DataProvider); ok { - r0 = rf(ctx, subID, topic, args, stream) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, models.Arguments, chan<- interface{}) data_providers.DataProvider); ok { + r0 = returnFunc(ctx, subID, topic, args, stream) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(data_providers.DataProvider) } } - - if rf, ok := ret.Get(1).(func(context.Context, string, string, models.Arguments, chan<- interface{}) error); ok { - r1 = rf(ctx, subID, topic, args, stream) + if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, models.Arguments, chan<- interface{}) error); ok { + r1 = returnFunc(ctx, subID, topic, args, stream) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewDataProviderFactory creates a new instance of DataProviderFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDataProviderFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *DataProviderFactory { - mock := &DataProviderFactory{} - mock.Mock.Test(t) +// DataProviderFactory_NewDataProvider_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewDataProvider' +type DataProviderFactory_NewDataProvider_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NewDataProvider is a helper method to define mock.On call +// - ctx context.Context +// - subID string +// - topic string +// - args models.Arguments +// - stream chan<- interface{} +func (_e *DataProviderFactory_Expecter) NewDataProvider(ctx interface{}, subID interface{}, topic interface{}, args interface{}, stream interface{}) *DataProviderFactory_NewDataProvider_Call { + return &DataProviderFactory_NewDataProvider_Call{Call: _e.mock.On("NewDataProvider", ctx, subID, topic, args, stream)} +} - return mock +func (_c *DataProviderFactory_NewDataProvider_Call) Run(run func(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- interface{})) *DataProviderFactory_NewDataProvider_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 models.Arguments + if args[3] != nil { + arg3 = args[3].(models.Arguments) + } + var arg4 chan<- interface{} + if args[4] != nil { + arg4 = args[4].(chan<- interface{}) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *DataProviderFactory_NewDataProvider_Call) Return(dataProvider data_providers.DataProvider, err error) *DataProviderFactory_NewDataProvider_Call { + _c.Call.Return(dataProvider, err) + return _c +} + +func (_c *DataProviderFactory_NewDataProvider_Call) RunAndReturn(run func(ctx context.Context, subID string, topic string, args models.Arguments, stream chan<- interface{}) (data_providers.DataProvider, error)) *DataProviderFactory_NewDataProvider_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rest/websockets/data_providers/models/event.go b/engine/access/rest/websockets/data_providers/models/event.go index c3db39bb559..b8e289e7674 100644 --- a/engine/access/rest/websockets/data_providers/models/event.go +++ b/engine/access/rest/websockets/data_providers/models/event.go @@ -3,15 +3,14 @@ package models import ( "strconv" - "github.com/onflow/flow-go/engine/access/rest/common/models" commonmodels "github.com/onflow/flow-go/engine/access/rest/common/models" "github.com/onflow/flow-go/engine/access/state_stream/backend" ) // EventResponse is the response message for 'events' topic. type EventResponse struct { - models.BlockEvents // Embed BlockEvents struct to reuse its fields - MessageIndex uint64 `json:"message_index"` + commonmodels.BlockEvents // Embed BlockEvents struct to reuse its fields + MessageIndex uint64 `json:"message_index"` } // NewEventResponse creates EventResponse instance. diff --git a/engine/access/rest/websockets/handler.go b/engine/access/rest/websockets/handler.go index 951e56e7896..8ee100aa07d 100644 --- a/engine/access/rest/websockets/handler.go +++ b/engine/access/rest/websockets/handler.go @@ -10,6 +10,7 @@ import ( dp "github.com/onflow/flow-go/engine/access/rest/websockets/data_providers" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" ) type Handler struct { @@ -24,6 +25,7 @@ type Handler struct { logger zerolog.Logger websocketConfig Config dataProviderFactory dp.DataProviderFactory + streamLimiter *limiters.ConcurrencyLimiter } var _ http.Handler = (*Handler)(nil) @@ -36,6 +38,7 @@ func NewWebSocketHandler( maxRequestSize int64, maxResponseSize int64, dataProviderFactory dp.DataProviderFactory, + streamLimiter *limiters.ConcurrencyLimiter, ) *Handler { return &Handler{ ctx: ctx, @@ -43,6 +46,7 @@ func NewWebSocketHandler( websocketConfig: config, logger: logger, dataProviderFactory: dataProviderFactory, + streamLimiter: streamLimiter, } } @@ -69,6 +73,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - controller := NewWebSocketController(logger, h.websocketConfig, NewWebsocketConnection(conn), h.dataProviderFactory) + controller, err := NewWebSocketController(logger, h.websocketConfig, NewWebsocketConnection(conn), h.dataProviderFactory, h.streamLimiter) + if err != nil { + h.HttpHandler.ErrorHandler(w, common.NewRestError(http.StatusInternalServerError, "could not create websocket controller: ", err), logger) + return + } controller.HandleConnection(h.ctx) } diff --git a/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go b/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go index aa59ffc8d99..9f0809ec0f1 100644 --- a/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go +++ b/engine/access/rest/websockets/legacy/routes/subscribe_events_test.go @@ -248,7 +248,7 @@ func (s *SubscribeEventsSuite) TestSubscribeEvents() { time.Sleep(1 * time.Second) respRecorder.Close() }() - router.ExecuteLegacyWsRequest(req, stateStreamBackend, respRecorder, chainID.Chain()) + router.ExecuteLegacyWsRequest(s.T(), req, stateStreamBackend, respRecorder, chainID.Chain()) requireResponse(s.T(), respRecorder, expectedEventsResponses) }) } @@ -260,7 +260,7 @@ func (s *SubscribeEventsSuite) TestSubscribeEventsHandlesErrors() { req, err := getSubscribeEventsRequest(s.T(), s.blocks[0].ID(), s.blocks[0].Height, nil, nil, nil, 1, nil) require.NoError(s.T(), err) respRecorder := router.NewTestHijackResponseRecorder() - router.ExecuteLegacyWsRequest(req, stateStreamBackend, respRecorder, chainID.Chain()) + router.ExecuteLegacyWsRequest(s.T(), req, stateStreamBackend, respRecorder, chainID.Chain()) requireError(s.T(), respRecorder, "can only provide either block ID or start height") }) @@ -285,7 +285,7 @@ func (s *SubscribeEventsSuite) TestSubscribeEventsHandlesErrors() { req, err := getSubscribeEventsRequest(s.T(), invalidBlock.ID(), request.EmptyHeight, nil, nil, nil, 1, nil) require.NoError(s.T(), err) respRecorder := router.NewTestHijackResponseRecorder() - router.ExecuteLegacyWsRequest(req, stateStreamBackend, respRecorder, chainID.Chain()) + router.ExecuteLegacyWsRequest(s.T(), req, stateStreamBackend, respRecorder, chainID.Chain()) requireError(s.T(), respRecorder, "stream encountered an error: subscription error") }) @@ -294,7 +294,7 @@ func (s *SubscribeEventsSuite) TestSubscribeEventsHandlesErrors() { req, err := getSubscribeEventsRequest(s.T(), s.blocks[0].ID(), request.EmptyHeight, []string{"foo"}, nil, nil, 1, nil) require.NoError(s.T(), err) respRecorder := router.NewTestHijackResponseRecorder() - router.ExecuteLegacyWsRequest(req, stateStreamBackend, respRecorder, chainID.Chain()) + router.ExecuteLegacyWsRequest(s.T(), req, stateStreamBackend, respRecorder, chainID.Chain()) requireError(s.T(), respRecorder, "invalid event type format") }) @@ -319,7 +319,7 @@ func (s *SubscribeEventsSuite) TestSubscribeEventsHandlesErrors() { req, err := getSubscribeEventsRequest(s.T(), s.blocks[0].ID(), request.EmptyHeight, nil, nil, nil, 1, nil) require.NoError(s.T(), err) respRecorder := router.NewTestHijackResponseRecorder() - router.ExecuteLegacyWsRequest(req, stateStreamBackend, respRecorder, chainID.Chain()) + router.ExecuteLegacyWsRequest(s.T(), req, stateStreamBackend, respRecorder, chainID.Chain()) requireError(s.T(), respRecorder, "subscription channel closed") }) } diff --git a/engine/access/rest/websockets/legacy/websocket_handler.go b/engine/access/rest/websockets/legacy/websocket_handler.go index 37e30d53d49..072f2d542c2 100644 --- a/engine/access/rest/websockets/legacy/websocket_handler.go +++ b/engine/access/rest/websockets/legacy/websocket_handler.go @@ -9,7 +9,6 @@ import ( "github.com/gorilla/websocket" "github.com/rs/zerolog" - "go.uber.org/atomic" "github.com/onflow/flow-go/engine/access/rest/common" "github.com/onflow/flow-go/engine/access/rest/websockets" @@ -29,8 +28,6 @@ type WebsocketController struct { conn *websocket.Conn // the WebSocket connection for communication with the client Api state_stream.API // the state_stream.API instance for managing event subscriptions EventFilterConfig state_stream.EventFilterConfig // the configuration for filtering events - maxStreams int32 // the maximum number of streams allowed - activeStreamCount *atomic.Int32 // the current number of active streams readChannel chan error // channel which notify closing connection by the client and provide errors to the client HeartbeatInterval uint64 // the interval to deliver heartbeat messages to client[IN BLOCKS] } @@ -244,9 +241,7 @@ type WSHandler struct { api state_stream.API eventFilterConfig state_stream.EventFilterConfig - maxStreams int32 defaultHeartbeatInterval uint64 - activeStreamCount *atomic.Int32 } var _ http.Handler = (*WSHandler)(nil) @@ -264,9 +259,7 @@ func NewWSHandler( subscribeFunc: subscribeFunc, api: api, eventFilterConfig: stateStreamConfig.EventFilterConfig, - maxStreams: int32(stateStreamConfig.MaxGlobalStreams), defaultHeartbeatInterval: stateStreamConfig.HeartbeatInterval, - activeStreamCount: atomic.NewInt32(0), HttpHandler: common.NewHttpHandler(logger, chain, maxRequestSize, maxResponseSize), } @@ -304,8 +297,6 @@ func (h *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { conn: conn, Api: h.api, EventFilterConfig: h.eventFilterConfig, - maxStreams: h.maxStreams, - activeStreamCount: h.activeStreamCount, readChannel: make(chan error), HeartbeatInterval: h.defaultHeartbeatInterval, // set default heartbeat interval from state stream config } @@ -316,14 +307,6 @@ func (h *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - if wsController.activeStreamCount.Load() >= wsController.maxStreams { - err := fmt.Errorf("maximum number of streams reached") - wsController.wsErrorHandler(common.NewRestError(http.StatusServiceUnavailable, err.Error(), err)) - return - } - wsController.activeStreamCount.Add(1) - defer wsController.activeStreamCount.Add(-1) - // cancelling the context passed into the `subscribeFunc` to ensure that when the client disconnects, // gorountines setup by the backend are cleaned up. ctx, cancel := context.WithCancel(context.Background()) diff --git a/engine/access/rest/websockets/mock/websocket_connection.go b/engine/access/rest/websockets/mock/websocket_connection.go index c235d8246ba..eacc351edd9 100644 --- a/engine/access/rest/websockets/mock/websocket_connection.go +++ b/engine/access/rest/websockets/mock/websocket_connection.go @@ -1,141 +1,383 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - time "time" + "time" mock "github.com/stretchr/testify/mock" ) +// NewWebsocketConnection creates a new instance of WebsocketConnection. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewWebsocketConnection(t interface { + mock.TestingT + Cleanup(func()) +}) *WebsocketConnection { + mock := &WebsocketConnection{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // WebsocketConnection is an autogenerated mock type for the WebsocketConnection type type WebsocketConnection struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *WebsocketConnection) Close() error { - ret := _m.Called() +type WebsocketConnection_Expecter struct { + mock *mock.Mock +} + +func (_m *WebsocketConnection) EXPECT() *WebsocketConnection_Expecter { + return &WebsocketConnection_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type WebsocketConnection +func (_mock *WebsocketConnection) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// ReadJSON provides a mock function with given fields: v -func (_m *WebsocketConnection) ReadJSON(v interface{}) error { - ret := _m.Called(v) +// WebsocketConnection_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type WebsocketConnection_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *WebsocketConnection_Expecter) Close() *WebsocketConnection_Close_Call { + return &WebsocketConnection_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *WebsocketConnection_Close_Call) Run(run func()) *WebsocketConnection_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *WebsocketConnection_Close_Call) Return(err error) *WebsocketConnection_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WebsocketConnection_Close_Call) RunAndReturn(run func() error) *WebsocketConnection_Close_Call { + _c.Call.Return(run) + return _c +} + +// ReadJSON provides a mock function for the type WebsocketConnection +func (_mock *WebsocketConnection) ReadJSON(v interface{}) error { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for ReadJSON") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}) error); ok { - r0 = rf(v) + if returnFunc, ok := ret.Get(0).(func(interface{}) error); ok { + r0 = returnFunc(v) } else { r0 = ret.Error(0) } - return r0 } -// SetPongHandler provides a mock function with given fields: h -func (_m *WebsocketConnection) SetPongHandler(h func(string) error) { - _m.Called(h) +// WebsocketConnection_ReadJSON_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadJSON' +type WebsocketConnection_ReadJSON_Call struct { + *mock.Call +} + +// ReadJSON is a helper method to define mock.On call +// - v interface{} +func (_e *WebsocketConnection_Expecter) ReadJSON(v interface{}) *WebsocketConnection_ReadJSON_Call { + return &WebsocketConnection_ReadJSON_Call{Call: _e.mock.On("ReadJSON", v)} +} + +func (_c *WebsocketConnection_ReadJSON_Call) Run(run func(v interface{})) *WebsocketConnection_ReadJSON_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 interface{} + if args[0] != nil { + arg0 = args[0].(interface{}) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *WebsocketConnection_ReadJSON_Call) Return(err error) *WebsocketConnection_ReadJSON_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WebsocketConnection_ReadJSON_Call) RunAndReturn(run func(v interface{}) error) *WebsocketConnection_ReadJSON_Call { + _c.Call.Return(run) + return _c +} + +// SetPongHandler provides a mock function for the type WebsocketConnection +func (_mock *WebsocketConnection) SetPongHandler(h func(string) error) { + _mock.Called(h) + return +} + +// WebsocketConnection_SetPongHandler_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetPongHandler' +type WebsocketConnection_SetPongHandler_Call struct { + *mock.Call +} + +// SetPongHandler is a helper method to define mock.On call +// - h func(string) error +func (_e *WebsocketConnection_Expecter) SetPongHandler(h interface{}) *WebsocketConnection_SetPongHandler_Call { + return &WebsocketConnection_SetPongHandler_Call{Call: _e.mock.On("SetPongHandler", h)} +} + +func (_c *WebsocketConnection_SetPongHandler_Call) Run(run func(h func(string) error)) *WebsocketConnection_SetPongHandler_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(string) error + if args[0] != nil { + arg0 = args[0].(func(string) error) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *WebsocketConnection_SetPongHandler_Call) Return() *WebsocketConnection_SetPongHandler_Call { + _c.Call.Return() + return _c +} + +func (_c *WebsocketConnection_SetPongHandler_Call) RunAndReturn(run func(h func(string) error)) *WebsocketConnection_SetPongHandler_Call { + _c.Run(run) + return _c } -// SetReadDeadline provides a mock function with given fields: deadline -func (_m *WebsocketConnection) SetReadDeadline(deadline time.Time) error { - ret := _m.Called(deadline) +// SetReadDeadline provides a mock function for the type WebsocketConnection +func (_mock *WebsocketConnection) SetReadDeadline(deadline time.Time) error { + ret := _mock.Called(deadline) if len(ret) == 0 { panic("no return value specified for SetReadDeadline") } var r0 error - if rf, ok := ret.Get(0).(func(time.Time) error); ok { - r0 = rf(deadline) + if returnFunc, ok := ret.Get(0).(func(time.Time) error); ok { + r0 = returnFunc(deadline) } else { r0 = ret.Error(0) } - return r0 } -// SetWriteDeadline provides a mock function with given fields: deadline -func (_m *WebsocketConnection) SetWriteDeadline(deadline time.Time) error { - ret := _m.Called(deadline) +// WebsocketConnection_SetReadDeadline_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetReadDeadline' +type WebsocketConnection_SetReadDeadline_Call struct { + *mock.Call +} + +// SetReadDeadline is a helper method to define mock.On call +// - deadline time.Time +func (_e *WebsocketConnection_Expecter) SetReadDeadline(deadline interface{}) *WebsocketConnection_SetReadDeadline_Call { + return &WebsocketConnection_SetReadDeadline_Call{Call: _e.mock.On("SetReadDeadline", deadline)} +} + +func (_c *WebsocketConnection_SetReadDeadline_Call) Run(run func(deadline time.Time)) *WebsocketConnection_SetReadDeadline_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Time + if args[0] != nil { + arg0 = args[0].(time.Time) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *WebsocketConnection_SetReadDeadline_Call) Return(err error) *WebsocketConnection_SetReadDeadline_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WebsocketConnection_SetReadDeadline_Call) RunAndReturn(run func(deadline time.Time) error) *WebsocketConnection_SetReadDeadline_Call { + _c.Call.Return(run) + return _c +} + +// SetWriteDeadline provides a mock function for the type WebsocketConnection +func (_mock *WebsocketConnection) SetWriteDeadline(deadline time.Time) error { + ret := _mock.Called(deadline) if len(ret) == 0 { panic("no return value specified for SetWriteDeadline") } var r0 error - if rf, ok := ret.Get(0).(func(time.Time) error); ok { - r0 = rf(deadline) + if returnFunc, ok := ret.Get(0).(func(time.Time) error); ok { + r0 = returnFunc(deadline) } else { r0 = ret.Error(0) } - return r0 } -// WriteControl provides a mock function with given fields: messageType, deadline -func (_m *WebsocketConnection) WriteControl(messageType int, deadline time.Time) error { - ret := _m.Called(messageType, deadline) +// WebsocketConnection_SetWriteDeadline_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetWriteDeadline' +type WebsocketConnection_SetWriteDeadline_Call struct { + *mock.Call +} + +// SetWriteDeadline is a helper method to define mock.On call +// - deadline time.Time +func (_e *WebsocketConnection_Expecter) SetWriteDeadline(deadline interface{}) *WebsocketConnection_SetWriteDeadline_Call { + return &WebsocketConnection_SetWriteDeadline_Call{Call: _e.mock.On("SetWriteDeadline", deadline)} +} + +func (_c *WebsocketConnection_SetWriteDeadline_Call) Run(run func(deadline time.Time)) *WebsocketConnection_SetWriteDeadline_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Time + if args[0] != nil { + arg0 = args[0].(time.Time) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *WebsocketConnection_SetWriteDeadline_Call) Return(err error) *WebsocketConnection_SetWriteDeadline_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WebsocketConnection_SetWriteDeadline_Call) RunAndReturn(run func(deadline time.Time) error) *WebsocketConnection_SetWriteDeadline_Call { + _c.Call.Return(run) + return _c +} + +// WriteControl provides a mock function for the type WebsocketConnection +func (_mock *WebsocketConnection) WriteControl(messageType int, deadline time.Time) error { + ret := _mock.Called(messageType, deadline) if len(ret) == 0 { panic("no return value specified for WriteControl") } var r0 error - if rf, ok := ret.Get(0).(func(int, time.Time) error); ok { - r0 = rf(messageType, deadline) + if returnFunc, ok := ret.Get(0).(func(int, time.Time) error); ok { + r0 = returnFunc(messageType, deadline) } else { r0 = ret.Error(0) } - return r0 } -// WriteJSON provides a mock function with given fields: v -func (_m *WebsocketConnection) WriteJSON(v interface{}) error { - ret := _m.Called(v) +// WebsocketConnection_WriteControl_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteControl' +type WebsocketConnection_WriteControl_Call struct { + *mock.Call +} + +// WriteControl is a helper method to define mock.On call +// - messageType int +// - deadline time.Time +func (_e *WebsocketConnection_Expecter) WriteControl(messageType interface{}, deadline interface{}) *WebsocketConnection_WriteControl_Call { + return &WebsocketConnection_WriteControl_Call{Call: _e.mock.On("WriteControl", messageType, deadline)} +} + +func (_c *WebsocketConnection_WriteControl_Call) Run(run func(messageType int, deadline time.Time)) *WebsocketConnection_WriteControl_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *WebsocketConnection_WriteControl_Call) Return(err error) *WebsocketConnection_WriteControl_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WebsocketConnection_WriteControl_Call) RunAndReturn(run func(messageType int, deadline time.Time) error) *WebsocketConnection_WriteControl_Call { + _c.Call.Return(run) + return _c +} + +// WriteJSON provides a mock function for the type WebsocketConnection +func (_mock *WebsocketConnection) WriteJSON(v interface{}) error { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for WriteJSON") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}) error); ok { - r0 = rf(v) + if returnFunc, ok := ret.Get(0).(func(interface{}) error); ok { + r0 = returnFunc(v) } else { r0 = ret.Error(0) } - return r0 } -// NewWebsocketConnection creates a new instance of WebsocketConnection. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewWebsocketConnection(t interface { - mock.TestingT - Cleanup(func()) -}) *WebsocketConnection { - mock := &WebsocketConnection{} - mock.Mock.Test(t) +// WebsocketConnection_WriteJSON_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteJSON' +type WebsocketConnection_WriteJSON_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WriteJSON is a helper method to define mock.On call +// - v interface{} +func (_e *WebsocketConnection_Expecter) WriteJSON(v interface{}) *WebsocketConnection_WriteJSON_Call { + return &WebsocketConnection_WriteJSON_Call{Call: _e.mock.On("WriteJSON", v)} +} - return mock +func (_c *WebsocketConnection_WriteJSON_Call) Run(run func(v interface{})) *WebsocketConnection_WriteJSON_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 interface{} + if args[0] != nil { + arg0 = args[0].(interface{}) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *WebsocketConnection_WriteJSON_Call) Return(err error) *WebsocketConnection_WriteJSON_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WebsocketConnection_WriteJSON_Call) RunAndReturn(run func(v interface{}) error) *WebsocketConnection_WriteJSON_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rest/websockets/models/subscribe_message.go b/engine/access/rest/websockets/models/subscribe_message.go index 532e4c6a987..3908f855fa6 100644 --- a/engine/access/rest/websockets/models/subscribe_message.go +++ b/engine/access/rest/websockets/models/subscribe_message.go @@ -1,6 +1,6 @@ package models -type Arguments map[string]interface{} +type Arguments map[string]any // SubscribeMessageRequest represents a request to subscribe to a topic. type SubscribeMessageRequest struct { diff --git a/engine/access/rest_api_test.go b/engine/access/rest_api_test.go index 50c4b235f70..bb7e75176ac 100644 --- a/engine/access/rest_api_test.go +++ b/engine/access/rest_api_test.go @@ -29,10 +29,12 @@ import ( "github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator" "github.com/onflow/flow-go/engine/access/rpc/backend/query_mode" statestreambackend "github.com/onflow/flow-go/engine/access/state_stream/backend" + "github.com/onflow/flow-go/engine/access/subscription" commonrpc "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/metrics" module "github.com/onflow/flow-go/module/mock" "github.com/onflow/flow-go/network" @@ -194,6 +196,8 @@ func (suite *RestAPITestSuite) SetupTest() { stateStreamConfig := statestreambackend.Config{} followerDistributor := pubsub.NewFollowerDistributor() + streamLimiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + suite.Require().NoError(err) rpcEngBuilder, err := rpc.NewBuilder( suite.log, suite.state, @@ -210,6 +214,8 @@ func (suite *RestAPITestSuite) SetupTest() { stateStreamConfig, nil, followerDistributor, + nil, + streamLimiter, ) assert.NoError(suite.T(), err) suite.rpcEng, err = rpcEngBuilder.WithLegacy().Build() diff --git a/engine/access/rpc/backend/accounts/accounts_test.go b/engine/access/rpc/backend/accounts/accounts_test.go index bfb597607e2..fe2fde42a4c 100644 --- a/engine/access/rpc/backend/accounts/accounts_test.go +++ b/engine/access/rpc/backend/accounts/accounts_test.go @@ -632,7 +632,7 @@ func (s *AccountsSuite) setupExecutionNodes(block *flow.Block) { // this line causes a S1021 lint error because receipts is explicitly declared. this is required // to ensure the mock library handles the response type correctly - var receipts flow.ExecutionReceiptList //nolint:gosimple + var receipts flow.ExecutionReceiptList //nolint:staticcheck receipts = unittest.ReceiptsForBlockFixture(block, s.executionNodes.NodeIDs()) s.receipts.On("ByBlockID", block.ID()).Return(receipts, nil) diff --git a/engine/access/rpc/backend/accounts/provider/mock/account_provider.go b/engine/access/rpc/backend/accounts/provider/mock/account_provider.go deleted file mode 100644 index 7d5034c1187..00000000000 --- a/engine/access/rpc/backend/accounts/provider/mock/account_provider.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - mock "github.com/stretchr/testify/mock" -) - -// AccountProvider is an autogenerated mock type for the AccountProvider type -type AccountProvider struct { - mock.Mock -} - -// GetAccountAtBlock provides a mock function with given fields: ctx, address, blockID, height -func (_m *AccountProvider) GetAccountAtBlock(ctx context.Context, address flow.Address, blockID flow.Identifier, height uint64) (*flow.Account, error) { - ret := _m.Called(ctx, address, blockID, height) - - if len(ret) == 0 { - panic("no return value specified for GetAccountAtBlock") - } - - var r0 *flow.Account - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier, uint64) (*flow.Account, error)); ok { - return rf(ctx, address, blockID, height) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier, uint64) *flow.Account); ok { - r0 = rf(ctx, address, blockID, height) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Account) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, flow.Identifier, uint64) error); ok { - r1 = rf(ctx, address, blockID, height) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAccountBalanceAtBlock provides a mock function with given fields: ctx, address, blockID, height -func (_m *AccountProvider) GetAccountBalanceAtBlock(ctx context.Context, address flow.Address, blockID flow.Identifier, height uint64) (uint64, error) { - ret := _m.Called(ctx, address, blockID, height) - - if len(ret) == 0 { - panic("no return value specified for GetAccountBalanceAtBlock") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier, uint64) (uint64, error)); ok { - return rf(ctx, address, blockID, height) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier, uint64) uint64); ok { - r0 = rf(ctx, address, blockID, height) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, flow.Identifier, uint64) error); ok { - r1 = rf(ctx, address, blockID, height) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAccountKeyAtBlock provides a mock function with given fields: ctx, address, keyIndex, blockID, height -func (_m *AccountProvider) GetAccountKeyAtBlock(ctx context.Context, address flow.Address, keyIndex uint32, blockID flow.Identifier, height uint64) (*flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, keyIndex, blockID, height) - - if len(ret) == 0 { - panic("no return value specified for GetAccountKeyAtBlock") - } - - var r0 *flow.AccountPublicKey - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, flow.Identifier, uint64) (*flow.AccountPublicKey, error)); ok { - return rf(ctx, address, keyIndex, blockID, height) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, flow.Identifier, uint64) *flow.AccountPublicKey); ok { - r0 = rf(ctx, address, keyIndex, blockID, height) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.AccountPublicKey) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, flow.Identifier, uint64) error); ok { - r1 = rf(ctx, address, keyIndex, blockID, height) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAccountKeysAtBlock provides a mock function with given fields: ctx, address, blockID, height -func (_m *AccountProvider) GetAccountKeysAtBlock(ctx context.Context, address flow.Address, blockID flow.Identifier, height uint64) ([]flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, blockID, height) - - if len(ret) == 0 { - panic("no return value specified for GetAccountKeysAtBlock") - } - - var r0 []flow.AccountPublicKey - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier, uint64) ([]flow.AccountPublicKey, error)); ok { - return rf(ctx, address, blockID, height) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier, uint64) []flow.AccountPublicKey); ok { - r0 = rf(ctx, address, blockID, height) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]flow.AccountPublicKey) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, flow.Identifier, uint64) error); ok { - r1 = rf(ctx, address, blockID, height) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewAccountProvider creates a new instance of AccountProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccountProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *AccountProvider { - mock := &AccountProvider{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/access/rpc/backend/backend.go b/engine/access/rpc/backend/backend.go index a5c6d3ab649..f6e019be575 100644 --- a/engine/access/rpc/backend/backend.go +++ b/engine/access/rpc/backend/backend.go @@ -312,6 +312,7 @@ func New(params Params) (*Backend, error) { backendExecutionResults: backendExecutionResults{ executionResults: params.ExecutionResults, seals: params.Seals, + receipts: params.ExecutionReceipts, }, backendNetwork: backendNetwork{ state: params.State, diff --git a/engine/access/rpc/backend/backend_execution_results.go b/engine/access/rpc/backend/backend_execution_results.go index b9e8c65898a..37d58afbbab 100644 --- a/engine/access/rpc/backend/backend_execution_results.go +++ b/engine/access/rpc/backend/backend_execution_results.go @@ -2,15 +2,22 @@ package backend import ( "context" + "errors" + "fmt" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" "github.com/onflow/flow-go/storage" ) type backendExecutionResults struct { executionResults storage.ExecutionResults seals storage.Seals + receipts storage.ExecutionReceipts } func (b *backendExecutionResults) GetExecutionResultForBlockID(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionResult, error) { @@ -38,3 +45,65 @@ func (b *backendExecutionResults) GetExecutionResultByID(ctx context.Context, id return result, nil } + +// GetExecutionReceiptsByBlockID retrieves all known execution receipts for the given block. +// +// Expected error returns during normal operation: +// - [codes.NotFound]: if no receipts are indexed for the given block ID. +func (b *backendExecutionResults) GetExecutionReceiptsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + // the block/receipt index is populated by the Access ingestion engine when receiving receipts + // directly from execution nodes, and by the follower engine when persisting blocks. + receipts, err := b.receipts.ByBlockID(blockID) + if err != nil { + // ByBlockID does not return an error if no receipts are found + err = fmt.Errorf("failed to get execution receipts by block ID: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + if len(receipts) == 0 { + return nil, status.Errorf(codes.NotFound, "no receipts found for block") + } + + return receipts, nil +} + +// GetExecutionReceiptsByResultID retrieves all known execution receipts that commit to the given +// execution result ID. It resolves the associated block ID from the result, then retrieves all +// receipts for that block, filtering to those matching the requested result. +// +// Expected error returns during normal operation: +// - [codes.NotFound]: if the execution result or its block's receipts are not found. +func (b *backendExecutionResults) GetExecutionReceiptsByResultID(ctx context.Context, resultID flow.Identifier) ([]*flow.ExecutionReceipt, error) { + result, err := b.executionResults.ByID(resultID) + if err != nil { + if !errors.Is(err, storage.ErrNotFound) { + err = fmt.Errorf("failed to get execution result: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + return nil, status.Errorf(codes.NotFound, "could not find execution result: %v", err) + } + + // there is no receipt/result index, so we have to lookup the block and filter by result ID + allReceipts, err := b.receipts.ByBlockID(result.BlockID) + if err != nil { + // ByBlockID does not return an error if no receipts are found for the given block. + err = fmt.Errorf("failed to get execution receipts by result ID: %w", err) + irrecoverable.Throw(ctx, err) + return nil, err + } + + var receipts []*flow.ExecutionReceipt + for _, receipt := range allReceipts { + if receipt.ExecutionResult.ID() == resultID { + receipts = append(receipts, receipt) + } + } + + if len(receipts) == 0 { + return nil, status.Errorf(codes.NotFound, "no receipts found for result") + } + + return receipts, nil +} diff --git a/engine/access/rpc/backend/backend_execution_results_test.go b/engine/access/rpc/backend/backend_execution_results_test.go new file mode 100644 index 00000000000..32e6adbd10d --- /dev/null +++ b/engine/access/rpc/backend/backend_execution_results_test.go @@ -0,0 +1,287 @@ +package backend + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/storage" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/utils/unittest/fixtures" +) + +// ExecutionResultsSuite tests backendExecutionResults directly, verifying correct delegation +// to storage and correct gRPC error code translation. +type ExecutionResultsSuite struct { + suite.Suite + + g *fixtures.GeneratorSuite + + results *storagemock.ExecutionResults + seals *storagemock.Seals + receipts *storagemock.ExecutionReceipts + + backend backendExecutionResults +} + +func TestExecutionResults(t *testing.T) { + suite.Run(t, new(ExecutionResultsSuite)) +} + +func (s *ExecutionResultsSuite) SetupTest() { + s.g = fixtures.NewGeneratorSuite() + + s.results = storagemock.NewExecutionResults(s.T()) + s.seals = storagemock.NewSeals(s.T()) + s.receipts = storagemock.NewExecutionReceipts(s.T()) + + s.backend = backendExecutionResults{ + executionResults: s.results, + seals: s.seals, + receipts: s.receipts, + } +} + +// TestGetExecutionResultForBlockID tests the GetExecutionResultForBlockID method, which looks +// up the finalized seal for the block, then fetches the execution result referenced by the seal. +func (s *ExecutionResultsSuite) TestGetExecutionResultForBlockID() { + ctx := context.Background() + + blockID := s.g.Identifiers().Fixture() + result := s.g.ExecutionResults().Fixture(fixtures.ExecutionResult.WithBlockID(blockID)) + seal := s.g.Seals().Fixture( + fixtures.Seal.WithBlockID(blockID), + fixtures.Seal.WithResultID(result.ID()), + ) + + s.Run("not found - no seal for block", func() { + unknownBlockID := s.g.Identifiers().Fixture() + s.seals.On("FinalizedSealForBlock", unknownBlockID). + Return(nil, storage.ErrNotFound).Once() + + _, err := s.backend.GetExecutionResultForBlockID(ctx, unknownBlockID) + s.Require().Error(err) + s.Assert().Equal(codes.NotFound, status.Code(err)) + }) + + s.Run("not found - seal exists but result missing", func() { + missingResultSeal := s.g.Seals().Fixture(fixtures.Seal.WithBlockID(blockID)) + s.seals.On("FinalizedSealForBlock", blockID). + Return(missingResultSeal, nil).Once() + s.results.On("ByID", missingResultSeal.ResultID). + Return(nil, storage.ErrNotFound).Once() + + _, err := s.backend.GetExecutionResultForBlockID(ctx, blockID) + s.Require().Error(err) + s.Assert().Equal(codes.NotFound, status.Code(err)) + }) + + // GetExecutionResultForBlockID uses rpc.ConvertStorageError, so unexpected storage + // errors translate to codes.Internal without triggering irrecoverable.Throw. + s.Run("exception - seals storage failure", func() { + unknownBlockID := s.g.Identifiers().Fixture() + s.seals.On("FinalizedSealForBlock", unknownBlockID). + Return(nil, errors.New("seal db failure")).Once() + + _, err := s.backend.GetExecutionResultForBlockID(ctx, unknownBlockID) + s.Require().Error(err) + s.Assert().Equal(codes.Internal, status.Code(err)) + }) + + s.Run("exception - results storage failure", func() { + s.seals.On("FinalizedSealForBlock", blockID). + Return(seal, nil).Once() + s.results.On("ByID", seal.ResultID). + Return(nil, errors.New("result db failure")).Once() + + _, err := s.backend.GetExecutionResultForBlockID(ctx, blockID) + s.Require().Error(err) + s.Assert().Equal(codes.Internal, status.Code(err)) + }) + + s.Run("happy path", func() { + s.seals.On("FinalizedSealForBlock", blockID). + Return(seal, nil).Once() + s.results.On("ByID", seal.ResultID). + Return(result, nil).Once() + + actual, err := s.backend.GetExecutionResultForBlockID(ctx, blockID) + s.Require().NoError(err) + s.Assert().Equal(result, actual) + }) +} + +// TestGetExecutionResultByID tests the GetExecutionResultByID method, which fetches +// an execution result directly by its ID. +func (s *ExecutionResultsSuite) TestGetExecutionResultByID() { + ctx := context.Background() + + result := s.g.ExecutionResults().Fixture() + + s.Run("not found", func() { + unknownID := s.g.Identifiers().Fixture() + s.results.On("ByID", unknownID). + Return(nil, storage.ErrNotFound).Once() + + _, err := s.backend.GetExecutionResultByID(ctx, unknownID) + s.Require().Error(err) + s.Assert().Equal(codes.NotFound, status.Code(err)) + }) + + // GetExecutionResultByID uses rpc.ConvertStorageError, so unexpected storage + // errors translate to codes.Internal without triggering irrecoverable.Throw. + s.Run("exception - results storage failure", func() { + unknownID := s.g.Identifiers().Fixture() + s.results.On("ByID", unknownID). + Return(nil, errors.New("result db failure")).Once() + + _, err := s.backend.GetExecutionResultByID(ctx, unknownID) + s.Require().Error(err) + s.Assert().Equal(codes.Internal, status.Code(err)) + }) + + s.Run("happy path", func() { + s.results.On("ByID", result.ID()). + Return(result, nil).Once() + + actual, err := s.backend.GetExecutionResultByID(ctx, result.ID()) + s.Require().NoError(err) + s.Assert().Equal(result, actual) + }) +} + +// TestGetExecutionReceiptsByBlockID tests the GetExecutionReceiptsByBlockID method, which +// retrieves all execution receipts for a given block ID. +func (s *ExecutionResultsSuite) TestGetExecutionReceiptsByBlockID() { + ctx := context.Background() + + blockID := s.g.Identifiers().Fixture() + result1 := s.g.ExecutionResults().Fixture(fixtures.ExecutionResult.WithBlockID(blockID)) + result2 := s.g.ExecutionResults().Fixture(fixtures.ExecutionResult.WithBlockID(blockID)) + receipt1 := s.g.ExecutionReceipts().Fixture(fixtures.ExecutionReceipt.WithExecutionResult(*result1)) + receipt2 := s.g.ExecutionReceipts().Fixture(fixtures.ExecutionReceipt.WithExecutionResult(*result2)) + + // GetExecutionReceiptsByBlockID calls irrecoverable.Throw for unexpected storage errors. + s.Run("exception - receipts storage failure", func() { + unknownBlockID := s.g.Identifiers().Fixture() + storageErr := errors.New("receipts db failure") + expectedThrow := fmt.Errorf("failed to get execution receipts by block ID: %w", storageErr) + + signalerCtx := irrecoverable.NewMockSignalerContextExpectError(s.T(), context.Background(), expectedThrow) + ictx := irrecoverable.WithSignalerContext(context.Background(), signalerCtx) + + s.receipts.On("ByBlockID", unknownBlockID).Return(nil, storageErr).Once() + + _, err := s.backend.GetExecutionReceiptsByBlockID(ictx, unknownBlockID) + s.Require().Error(err) + s.Assert().True(errors.Is(err, storageErr)) + }) + + s.Run("not found - empty list", func() { + emptyBlockID := s.g.Identifiers().Fixture() + s.receipts.On("ByBlockID", emptyBlockID). + Return(flow.ExecutionReceiptList{}, nil).Once() + + _, err := s.backend.GetExecutionReceiptsByBlockID(ctx, emptyBlockID) + s.Require().Error(err) + s.Assert().Equal(codes.NotFound, status.Code(err)) + }) + + s.Run("happy path - multiple receipts", func() { + expected := flow.ExecutionReceiptList{receipt1, receipt2} + s.receipts.On("ByBlockID", blockID). + Return(expected, nil).Once() + + actual, err := s.backend.GetExecutionReceiptsByBlockID(ctx, blockID) + s.Require().NoError(err) + require.Equal(s.T(), []*flow.ExecutionReceipt(expected), actual) + }) +} + +// TestGetExecutionReceiptsByResultID tests the GetExecutionReceiptsByResultID method, which +// resolves the block from the result, retrieves all receipts for that block, and filters +// to only those committing to the requested result ID. +func (s *ExecutionResultsSuite) TestGetExecutionReceiptsByResultID() { + ctx := context.Background() + + blockID := s.g.Identifiers().Fixture() + targetResult := s.g.ExecutionResults().Fixture(fixtures.ExecutionResult.WithBlockID(blockID)) + matchingReceipt1 := s.g.ExecutionReceipts().Fixture(fixtures.ExecutionReceipt.WithExecutionResult(*targetResult)) + matchingReceipt2 := s.g.ExecutionReceipts().Fixture(fixtures.ExecutionReceipt.WithExecutionResult(*targetResult)) + + otherResult := s.g.ExecutionResults().Fixture(fixtures.ExecutionResult.WithBlockID(blockID)) + nonMatchingReceipt := s.g.ExecutionReceipts().Fixture(fixtures.ExecutionReceipt.WithExecutionResult(*otherResult)) + + s.Run("not found - unknown result ID", func() { + unknownID := s.g.Identifiers().Fixture() + s.results.On("ByID", unknownID). + Return(nil, storage.ErrNotFound).Once() + + _, err := s.backend.GetExecutionReceiptsByResultID(ctx, unknownID) + s.Require().Error(err) + s.Assert().Equal(codes.NotFound, status.Code(err)) + }) + + // GetExecutionReceiptsByResultID calls irrecoverable.Throw for unexpected storage errors. + s.Run("exception - results storage failure", func() { + unknownID := s.g.Identifiers().Fixture() + storageErr := errors.New("result db failure") + expectedThrow := fmt.Errorf("failed to get execution result: %w", storageErr) + + signalerCtx := irrecoverable.NewMockSignalerContextExpectError(s.T(), context.Background(), expectedThrow) + ictx := irrecoverable.WithSignalerContext(context.Background(), signalerCtx) + + s.results.On("ByID", unknownID).Return(nil, storageErr).Once() + + _, err := s.backend.GetExecutionReceiptsByResultID(ictx, unknownID) + s.Require().Error(err) + s.Assert().True(errors.Is(err, storageErr)) + }) + + s.Run("exception - receipts storage failure", func() { + storageErr := errors.New("receipts db failure") + expectedThrow := fmt.Errorf("failed to get execution receipts by result ID: %w", storageErr) + + signalerCtx := irrecoverable.NewMockSignalerContextExpectError(s.T(), context.Background(), expectedThrow) + ictx := irrecoverable.WithSignalerContext(context.Background(), signalerCtx) + + s.results.On("ByID", targetResult.ID()).Return(targetResult, nil).Once() + s.receipts.On("ByBlockID", blockID).Return(nil, storageErr).Once() + + _, err := s.backend.GetExecutionReceiptsByResultID(ictx, targetResult.ID()) + s.Require().Error(err) + s.Assert().True(errors.Is(err, storageErr)) + }) + + s.Run("happy path - returns only matching receipts", func() { + allReceipts := flow.ExecutionReceiptList{matchingReceipt1, nonMatchingReceipt, matchingReceipt2} + s.results.On("ByID", targetResult.ID()). + Return(targetResult, nil).Once() + s.receipts.On("ByBlockID", blockID). + Return(allReceipts, nil).Once() + + actual, err := s.backend.GetExecutionReceiptsByResultID(ctx, targetResult.ID()) + s.Require().NoError(err) + s.Require().Len(actual, 2) + s.Assert().ElementsMatch([]*flow.ExecutionReceipt{matchingReceipt1, matchingReceipt2}, actual) + }) + + s.Run("not found - no matching receipts for result", func() { + s.results.On("ByID", targetResult.ID()). + Return(targetResult, nil).Once() + s.receipts.On("ByBlockID", blockID). + Return(flow.ExecutionReceiptList{nonMatchingReceipt}, nil).Once() + + _, err := s.backend.GetExecutionReceiptsByResultID(ctx, targetResult.ID()) + s.Require().Error(err) + s.Assert().Equal(codes.NotFound, status.Code(err)) + }) +} diff --git a/engine/access/rpc/backend/backend_test.go b/engine/access/rpc/backend/backend_test.go index 170f20ce7db..1d314664b12 100644 --- a/engine/access/rpc/backend/backend_test.go +++ b/engine/access/rpc/backend/backend_test.go @@ -2031,6 +2031,115 @@ func (suite *Suite) TestNodeCommunicator() { suite.Assert().Equal(codes.Unavailable, status.Code(err)) } +func (suite *Suite) TestGetExecutionReceiptsByBlockID() { + nonexistingBlockID := unittest.IdentifierFixture() + blockID := unittest.IdentifierFixture() + + ctx := context.Background() + + receipts := new(storagemock.ExecutionReceipts) + receipts. + On("ByBlockID", nonexistingBlockID). + Return(flow.ExecutionReceiptList{}, nil) + + result1 := unittest.ExecutionResultFixture(unittest.WithExecutionResultBlockID(blockID)) + receipt1 := unittest.ExecutionReceiptFixture(unittest.WithResult(result1)) + result2 := unittest.ExecutionResultFixture(unittest.WithExecutionResultBlockID(blockID)) + receipt2 := unittest.ExecutionReceiptFixture(unittest.WithResult(result2)) + existingReceipts := flow.ExecutionReceiptList{receipt1, receipt2} + + receipts. + On("ByBlockID", blockID). + Return(existingReceipts, nil) + + suite.Run("nonexisting block", func() { + params := suite.defaultBackendParams() + params.ExecutionReceipts = receipts + + backend, err := New(params) + suite.Require().NoError(err) + + _, err = backend.GetExecutionReceiptsByBlockID(ctx, nonexistingBlockID) + suite.Assert().Error(err) + }) + + suite.Run("existing block with two receipts", func() { + params := suite.defaultBackendParams() + params.ExecutionReceipts = receipts + + backend, err := New(params) + suite.Require().NoError(err) + + actual, err := backend.GetExecutionReceiptsByBlockID(ctx, blockID) + suite.Require().NoError(err) + suite.Require().Len(actual, 2) + suite.Assert().Equal([]*flow.ExecutionReceipt(existingReceipts), actual) + }) + + receipts.AssertExpectations(suite.T()) + suite.assertAllExpectations() +} + +func (suite *Suite) TestGetExecutionReceiptsByResultID() { + nonexistingID := unittest.IdentifierFixture() + blockID := unittest.IdentifierFixture() + + ctx := context.Background() + + results := new(storagemock.ExecutionResults) + results. + On("ByID", nonexistingID). + Return(nil, storage.ErrNotFound) + + targetResult := unittest.ExecutionResultFixture(unittest.WithExecutionResultBlockID(blockID)) + matchingReceipt1 := unittest.ExecutionReceiptFixture(unittest.WithResult(targetResult)) + matchingReceipt2 := unittest.ExecutionReceiptFixture(unittest.WithResult(targetResult)) + + otherResult := unittest.ExecutionResultFixture(unittest.WithExecutionResultBlockID(blockID)) + nonMatchingReceipt := unittest.ExecutionReceiptFixture(unittest.WithResult(otherResult)) + + allReceipts := flow.ExecutionReceiptList{matchingReceipt1, matchingReceipt2, nonMatchingReceipt} + + results. + On("ByID", targetResult.ID()). + Return(targetResult, nil) + + receipts := new(storagemock.ExecutionReceipts) + receipts. + On("ByBlockID", blockID). + Return(allReceipts, nil) + + suite.Run("nonexisting result ID", func() { + params := suite.defaultBackendParams() + params.ExecutionResults = results + params.ExecutionReceipts = receipts + + backend, err := New(params) + suite.Require().NoError(err) + + _, err = backend.GetExecutionReceiptsByResultID(ctx, nonexistingID) + suite.Assert().Error(err) + }) + + suite.Run("existing result with two matching receipts", func() { + params := suite.defaultBackendParams() + params.ExecutionResults = results + params.ExecutionReceipts = receipts + + backend, err := New(params) + suite.Require().NoError(err) + + actual, err := backend.GetExecutionReceiptsByResultID(ctx, targetResult.ID()) + suite.Require().NoError(err) + suite.Require().Len(actual, 2) + suite.Assert().ElementsMatch([]*flow.ExecutionReceipt{matchingReceipt1, matchingReceipt2}, actual) + }) + + results.AssertExpectations(suite.T()) + receipts.AssertExpectations(suite.T()) + suite.assertAllExpectations() +} + func (suite *Suite) assertAllExpectations() { suite.snapshot.AssertExpectations(suite.T()) suite.state.AssertExpectations(suite.T()) diff --git a/engine/access/rpc/backend/events/events.go b/engine/access/rpc/backend/events/events.go index 2afbced5f8b..7c00b8d645f 100644 --- a/engine/access/rpc/backend/events/events.go +++ b/engine/access/rpc/backend/events/events.go @@ -94,10 +94,15 @@ func (e *Events) GetEventsForHeightRange( return nil, status.Error(codes.InvalidArgument, "start height must not be larger than end height") } - rangeSize := endHeight - startHeight + 1 // range is inclusive on both ends - if rangeSize > uint64(e.maxHeightRange) { + // Overflow-safe range validation: compute (endHeight - startHeight) first, then check if + // adding 1 (for inclusive range) would exceed maxHeightRange. This avoids the overflow that + // occurs when endHeight = math.MaxUint64 and startHeight = 0, where (endHeight - startHeight + 1) + // wraps to 0. + rangeSpan := endHeight - startHeight // safe: we already checked endHeight >= startHeight + if rangeSpan >= uint64(e.maxHeightRange) { + // rangeSpan + 1 > maxHeightRange, but we compute it this way to avoid overflow return nil, status.Errorf(codes.InvalidArgument, - "requested block range (%d) exceeded maximum (%d)", rangeSize, e.maxHeightRange) + "requested block range (%d) exceeded maximum (%d)", rangeSpan+1, e.maxHeightRange) } // get the latest sealed block header diff --git a/engine/access/rpc/backend/events/events_test.go b/engine/access/rpc/backend/events/events_test.go index 4884527a506..046b05c12c6 100644 --- a/engine/access/rpc/backend/events/events_test.go +++ b/engine/access/rpc/backend/events/events_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "math" "sort" "testing" @@ -319,6 +320,38 @@ func (s *EventsSuite) TestGetEventsForHeightRange_HandlesErrors() { s.Assert().Nil(response) }) + // Regression tests for unsigned integer overflow vulnerability (KRITT-1) + // When endHeight = math.MaxUint64 and startHeight = 0, the computation + // (endHeight - startHeight + 1) would overflow to 0, bypassing the range check. + s.Run("returns error for max uint64 end height - overflow prevention", func() { + backend := s.defaultBackend(query_mode.IndexQueryModeExecutionNodesOnly, s.eventsIndex) + + response, err := backend.GetEventsForHeightRange(ctx, targetEvent, 0, math.MaxUint64, encoding) + s.Assert().Equal(codes.InvalidArgument, status.Code(err)) + s.Assert().Contains(err.Error(), "exceeded maximum") + s.Assert().Nil(response) + }) + + s.Run("returns error for max uint64 end height with non-zero start - overflow prevention", func() { + backend := s.defaultBackend(query_mode.IndexQueryModeExecutionNodesOnly, s.eventsIndex) + + response, err := backend.GetEventsForHeightRange(ctx, targetEvent, 100, math.MaxUint64, encoding) + s.Assert().Equal(codes.InvalidArgument, status.Code(err)) + s.Assert().Contains(err.Error(), "exceeded maximum") + s.Assert().Nil(response) + }) + + s.Run("returns error for range exactly at max boundary", func() { + backend := s.defaultBackend(query_mode.IndexQueryModeExecutionNodesOnly, s.eventsIndex) + // Range of exactly maxHeightRange should be allowed (inclusive range = maxHeightRange blocks) + // But range of maxHeightRange + 1 blocks (endHeight = startHeight + maxHeightRange) should fail + + // endHeight = startHeight + maxHeightRange gives maxHeightRange + 1 blocks, should fail + response, err := backend.GetEventsForHeightRange(ctx, targetEvent, startHeight, startHeight+DefaultMaxHeightRange, encoding) + s.Assert().Equal(codes.InvalidArgument, status.Code(err)) + s.Assert().Nil(response) + }) + s.Run("throws irrecoverable if sealed header not available", func() { s.state.On("Sealed").Return(s.snapshot) s.snapshot.On("Head").Return(nil, storage.ErrNotFound).Once() @@ -472,7 +505,7 @@ func (s *EventsSuite) setupExecutionNodes(block *flow.Block) { // this line causes a S1021 lint error because receipts is explicitly declared. this is required // to ensure the mock library handles the response type correctly - var receipts flow.ExecutionReceiptList //nolint:gosimple + var receipts flow.ExecutionReceiptList //nolint:staticcheck receipts = unittest.ReceiptsForBlockFixture(block, s.executionNodes.NodeIDs()) s.receipts.On("ByBlockID", block.ID()).Return(receipts, nil) diff --git a/engine/access/rpc/backend/events/provider/mock/event_provider.go b/engine/access/rpc/backend/events/provider/mock/event_provider.go deleted file mode 100644 index 1b1f8523d74..00000000000 --- a/engine/access/rpc/backend/events/provider/mock/event_provider.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - entities "github.com/onflow/flow/protobuf/go/flow/entities" - - mock "github.com/stretchr/testify/mock" - - provider "github.com/onflow/flow-go/engine/access/rpc/backend/events/provider" -) - -// EventProvider is an autogenerated mock type for the EventProvider type -type EventProvider struct { - mock.Mock -} - -// Events provides a mock function with given fields: ctx, blocks, eventType, requiredEventEncodingVersion -func (_m *EventProvider) Events(ctx context.Context, blocks []provider.BlockMetadata, eventType flow.EventType, requiredEventEncodingVersion entities.EventEncodingVersion) (provider.Response, error) { - ret := _m.Called(ctx, blocks, eventType, requiredEventEncodingVersion) - - if len(ret) == 0 { - panic("no return value specified for Events") - } - - var r0 provider.Response - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, []provider.BlockMetadata, flow.EventType, entities.EventEncodingVersion) (provider.Response, error)); ok { - return rf(ctx, blocks, eventType, requiredEventEncodingVersion) - } - if rf, ok := ret.Get(0).(func(context.Context, []provider.BlockMetadata, flow.EventType, entities.EventEncodingVersion) provider.Response); ok { - r0 = rf(ctx, blocks, eventType, requiredEventEncodingVersion) - } else { - r0 = ret.Get(0).(provider.Response) - } - - if rf, ok := ret.Get(1).(func(context.Context, []provider.BlockMetadata, flow.EventType, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, blocks, eventType, requiredEventEncodingVersion) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewEventProvider creates a new instance of EventProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEventProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *EventProvider { - mock := &EventProvider{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/access/rpc/backend/node_communicator/mock/communicator.go b/engine/access/rpc/backend/node_communicator/mock/communicator.go index 21be9e88f90..396a372f699 100644 --- a/engine/access/rpc/backend/node_communicator/mock/communicator.go +++ b/engine/access/rpc/backend/node_communicator/mock/communicator.go @@ -1,45 +1,100 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewCommunicator creates a new instance of Communicator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCommunicator(t interface { + mock.TestingT + Cleanup(func()) +}) *Communicator { + mock := &Communicator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Communicator is an autogenerated mock type for the Communicator type type Communicator struct { mock.Mock } -// CallAvailableNode provides a mock function with given fields: nodes, call, shouldTerminateOnError -func (_m *Communicator) CallAvailableNode(nodes flow.IdentitySkeletonList, call func(*flow.IdentitySkeleton) error, shouldTerminateOnError func(*flow.IdentitySkeleton, error) bool) error { - ret := _m.Called(nodes, call, shouldTerminateOnError) +type Communicator_Expecter struct { + mock *mock.Mock +} + +func (_m *Communicator) EXPECT() *Communicator_Expecter { + return &Communicator_Expecter{mock: &_m.Mock} +} + +// CallAvailableNode provides a mock function for the type Communicator +func (_mock *Communicator) CallAvailableNode(nodes flow.IdentitySkeletonList, call func(node *flow.IdentitySkeleton) error, shouldTerminateOnError func(node *flow.IdentitySkeleton, err error) bool) error { + ret := _mock.Called(nodes, call, shouldTerminateOnError) if len(ret) == 0 { panic("no return value specified for CallAvailableNode") } var r0 error - if rf, ok := ret.Get(0).(func(flow.IdentitySkeletonList, func(*flow.IdentitySkeleton) error, func(*flow.IdentitySkeleton, error) bool) error); ok { - r0 = rf(nodes, call, shouldTerminateOnError) + if returnFunc, ok := ret.Get(0).(func(flow.IdentitySkeletonList, func(node *flow.IdentitySkeleton) error, func(node *flow.IdentitySkeleton, err error) bool) error); ok { + r0 = returnFunc(nodes, call, shouldTerminateOnError) } else { r0 = ret.Error(0) } - return r0 } -// NewCommunicator creates a new instance of Communicator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCommunicator(t interface { - mock.TestingT - Cleanup(func()) -}) *Communicator { - mock := &Communicator{} - mock.Mock.Test(t) +// Communicator_CallAvailableNode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CallAvailableNode' +type Communicator_CallAvailableNode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// CallAvailableNode is a helper method to define mock.On call +// - nodes flow.IdentitySkeletonList +// - call func(node *flow.IdentitySkeleton) error +// - shouldTerminateOnError func(node *flow.IdentitySkeleton, err error) bool +func (_e *Communicator_Expecter) CallAvailableNode(nodes interface{}, call interface{}, shouldTerminateOnError interface{}) *Communicator_CallAvailableNode_Call { + return &Communicator_CallAvailableNode_Call{Call: _e.mock.On("CallAvailableNode", nodes, call, shouldTerminateOnError)} +} - return mock +func (_c *Communicator_CallAvailableNode_Call) Run(run func(nodes flow.IdentitySkeletonList, call func(node *flow.IdentitySkeleton) error, shouldTerminateOnError func(node *flow.IdentitySkeleton, err error) bool)) *Communicator_CallAvailableNode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.IdentitySkeletonList + if args[0] != nil { + arg0 = args[0].(flow.IdentitySkeletonList) + } + var arg1 func(node *flow.IdentitySkeleton) error + if args[1] != nil { + arg1 = args[1].(func(node *flow.IdentitySkeleton) error) + } + var arg2 func(node *flow.IdentitySkeleton, err error) bool + if args[2] != nil { + arg2 = args[2].(func(node *flow.IdentitySkeleton, err error) bool) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Communicator_CallAvailableNode_Call) Return(err error) *Communicator_CallAvailableNode_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Communicator_CallAvailableNode_Call) RunAndReturn(run func(nodes flow.IdentitySkeletonList, call func(node *flow.IdentitySkeleton) error, shouldTerminateOnError func(node *flow.IdentitySkeleton, err error) bool) error) *Communicator_CallAvailableNode_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rpc/backend/node_communicator/mock/node_selector.go b/engine/access/rpc/backend/node_communicator/mock/node_selector.go index 40d3fb78a36..19a4972c222 100644 --- a/engine/access/rpc/backend/node_communicator/mock/node_selector.go +++ b/engine/access/rpc/backend/node_communicator/mock/node_selector.go @@ -1,65 +1,127 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewNodeSelector creates a new instance of NodeSelector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNodeSelector(t interface { + mock.TestingT + Cleanup(func()) +}) *NodeSelector { + mock := &NodeSelector{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // NodeSelector is an autogenerated mock type for the NodeSelector type type NodeSelector struct { mock.Mock } -// HasNext provides a mock function with no fields -func (_m *NodeSelector) HasNext() bool { - ret := _m.Called() +type NodeSelector_Expecter struct { + mock *mock.Mock +} + +func (_m *NodeSelector) EXPECT() *NodeSelector_Expecter { + return &NodeSelector_Expecter{mock: &_m.Mock} +} + +// HasNext provides a mock function for the type NodeSelector +func (_mock *NodeSelector) HasNext() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HasNext") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// Next provides a mock function with no fields -func (_m *NodeSelector) Next() *flow.IdentitySkeleton { - ret := _m.Called() +// NodeSelector_HasNext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasNext' +type NodeSelector_HasNext_Call struct { + *mock.Call +} + +// HasNext is a helper method to define mock.On call +func (_e *NodeSelector_Expecter) HasNext() *NodeSelector_HasNext_Call { + return &NodeSelector_HasNext_Call{Call: _e.mock.On("HasNext")} +} + +func (_c *NodeSelector_HasNext_Call) Run(run func()) *NodeSelector_HasNext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NodeSelector_HasNext_Call) Return(b bool) *NodeSelector_HasNext_Call { + _c.Call.Return(b) + return _c +} + +func (_c *NodeSelector_HasNext_Call) RunAndReturn(run func() bool) *NodeSelector_HasNext_Call { + _c.Call.Return(run) + return _c +} + +// Next provides a mock function for the type NodeSelector +func (_mock *NodeSelector) Next() *flow.IdentitySkeleton { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Next") } var r0 *flow.IdentitySkeleton - if rf, ok := ret.Get(0).(func() *flow.IdentitySkeleton); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.IdentitySkeleton); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.IdentitySkeleton) } } - return r0 } -// NewNodeSelector creates a new instance of NodeSelector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNodeSelector(t interface { - mock.TestingT - Cleanup(func()) -}) *NodeSelector { - mock := &NodeSelector{} - mock.Mock.Test(t) +// NodeSelector_Next_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Next' +type NodeSelector_Next_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Next is a helper method to define mock.On call +func (_e *NodeSelector_Expecter) Next() *NodeSelector_Next_Call { + return &NodeSelector_Next_Call{Call: _e.mock.On("Next")} +} - return mock +func (_c *NodeSelector_Next_Call) Run(run func()) *NodeSelector_Next_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NodeSelector_Next_Call) Return(identitySkeleton *flow.IdentitySkeleton) *NodeSelector_Next_Call { + _c.Call.Return(identitySkeleton) + return _c +} + +func (_c *NodeSelector_Next_Call) RunAndReturn(run func() *flow.IdentitySkeleton) *NodeSelector_Next_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rpc/backend/script_executor.go b/engine/access/rpc/backend/script_executor.go index fc4ea418e51..2a818f711fb 100644 --- a/engine/access/rpc/backend/script_executor.go +++ b/engine/access/rpc/backend/script_executor.go @@ -9,12 +9,18 @@ import ( "go.uber.org/atomic" "github.com/onflow/flow-go/engine/common/version" + "github.com/onflow/flow-go/fvm/storage/snapshot" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/execution" - "github.com/onflow/flow-go/module/state_synchronization" "github.com/onflow/flow-go/storage" ) +// indexReporter provides information about the data available in the registers database +type indexReporter interface { + LatestHeight() uint64 + FirstHeight() uint64 +} + // ErrIncompatibleNodeVersion indicates that node version is incompatible with the block version var ErrIncompatibleNodeVersion = errors.New("node version is incompatible with data for block") @@ -25,7 +31,7 @@ type ScriptExecutor struct { scriptExecutor *execution.Scripts // indexReporter provides information about the current state of the execution state indexer. - indexReporter state_synchronization.IndexReporter + indexReporter indexReporter // versionControl provides information about the current version beacon for each block versionControl *version.VersionControl @@ -40,6 +46,8 @@ type ScriptExecutor struct { maxCompatibleHeight *atomic.Uint64 } +var _ execution.ScriptExecutor = (*ScriptExecutor)(nil) + func NewScriptExecutor(log zerolog.Logger, minHeight, maxHeight uint64) *ScriptExecutor { logger := log.With().Str("component", "script-executor").Logger() logger.Info(). @@ -73,7 +81,7 @@ func (s *ScriptExecutor) SetMaxCompatibleHeight(height uint64) { // This method can be called at any time after the ScriptExecutor object is created. Any requests // made to the other methods will return storage.ErrHeightNotIndexed until this method is called. func (s *ScriptExecutor) Initialize( - indexReporter state_synchronization.IndexReporter, + indexReporter indexReporter, scriptExecutor *execution.Scripts, versionControl *version.VersionControl, ) error { @@ -90,10 +98,10 @@ func (s *ScriptExecutor) Initialize( // ExecuteAtBlockHeight executes provided script at the provided block height against a local execution state. // // Expected errors: -// - storage.ErrNotFound if the register or block height is not found -// - storage.ErrHeightNotIndexed if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// - [storage.ErrNotFound] if the register or block height is not found +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, // or if the height is before the lowest indexed height. -// - ErrIncompatibleNodeVersion if the block height is not compatible with the node version. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. func (s *ScriptExecutor) ExecuteAtBlockHeight(ctx context.Context, script []byte, arguments [][]byte, height uint64) ([]byte, error) { if err := s.checkHeight(height); err != nil { return nil, err @@ -105,10 +113,10 @@ func (s *ScriptExecutor) ExecuteAtBlockHeight(ctx context.Context, script []byte // GetAccountAtBlockHeight returns the account at the provided block height from a local execution state. // // Expected errors: -// - storage.ErrNotFound if the account or block height is not found -// - storage.ErrHeightNotIndexed if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// - [storage.ErrNotFound] if the account or block height is not found +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, // or if the height is before the lowest indexed height. -// - ErrIncompatibleNodeVersion if the block height is not compatible with the node version. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. func (s *ScriptExecutor) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { if err := s.checkHeight(height); err != nil { return nil, err @@ -120,9 +128,9 @@ func (s *ScriptExecutor) GetAccountAtBlockHeight(ctx context.Context, address fl // GetAccountBalance returns a balance of Flow account by the provided address and block height. // Expected errors: // - Script execution related errors -// - storage.ErrHeightNotIndexed if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, // or if the height is before the lowest indexed height. -// - ErrIncompatibleNodeVersion if the block height is not compatible with the node version. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. func (s *ScriptExecutor) GetAccountBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { if err := s.checkHeight(height); err != nil { return 0, err @@ -134,9 +142,9 @@ func (s *ScriptExecutor) GetAccountBalance(ctx context.Context, address flow.Add // GetAccountAvailableBalance returns an available balance of Flow account by the provided address and block height. // Expected errors: // - Script execution related errors -// - storage.ErrHeightNotIndexed if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, // or if the height is before the lowest indexed height. -// - ErrIncompatibleNodeVersion if the block height is not compatible with the node version. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. func (s *ScriptExecutor) GetAccountAvailableBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { if err := s.checkHeight(height); err != nil { return 0, err @@ -148,9 +156,9 @@ func (s *ScriptExecutor) GetAccountAvailableBalance(ctx context.Context, address // GetAccountKeys returns a public key of Flow account by the provided address, block height and index. // Expected errors: // - Script execution related errors -// - storage.ErrHeightNotIndexed if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, // or if the height is before the lowest indexed height. -// - ErrIncompatibleNodeVersion if the block height is not compatible with the node version. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. func (s *ScriptExecutor) GetAccountKeys(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { if err := s.checkHeight(height); err != nil { return nil, err @@ -162,9 +170,9 @@ func (s *ScriptExecutor) GetAccountKeys(ctx context.Context, address flow.Addres // GetAccountKey returns // Expected errors: // - Script execution related errors -// - storage.ErrHeightNotIndexed if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, // or if the height is before the lowest indexed height. -// - ErrIncompatibleNodeVersion if the block height is not compatible with the node version. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. func (s *ScriptExecutor) GetAccountKey(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { if err := s.checkHeight(height); err != nil { return nil, err @@ -173,6 +181,48 @@ func (s *ScriptExecutor) GetAccountKey(ctx context.Context, address flow.Address return s.scriptExecutor.GetAccountKey(ctx, address, keyIndex, height) } +// GetAccountCode returns a Flow account code by the provided address, contract name and block height. +// Expected errors: +// - Script execution related errors +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// or if the height is before the lowest indexed height. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. +func (s *ScriptExecutor) GetAccountCode(ctx context.Context, address flow.Address, contractName string, height uint64) ([]byte, error) { + if err := s.checkHeight(height); err != nil { + return nil, err + } + + return s.scriptExecutor.GetAccountCode(ctx, address, contractName, height) +} + +// RegisterValue returns the register value for the given register ID at the provided block height. +// +// Expected errors: +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// or if the height is before the lowest indexed height. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. +func (s *ScriptExecutor) RegisterValue(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { + if err := s.checkHeight(height); err != nil { + return nil, err + } + + return s.scriptExecutor.RegisterValue(ID, height) +} + +// GetStorageSnapshot returns a storage snapshot at the provided block height. +// +// Expected errors: +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// or if the height is before the lowest indexed height. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. +func (s *ScriptExecutor) GetStorageSnapshot(height uint64) (snapshot.StorageSnapshot, error) { + if err := s.checkHeight(height); err != nil { + return nil, err + } + + return s.scriptExecutor.GetStorageSnapshot(height) +} + // checkHeight checks if the provided block height is within the range of indexed heights // and compatible with the node's version. // @@ -181,35 +231,20 @@ func (s *ScriptExecutor) GetAccountKey(ctx context.Context, address flow.Address // 2. Compares the provided height with the highest and lowest indexed heights. // 3. Ensures the height is within the compatible version range if version control is enabled. // -// Parameters: -// - height: the block height to check. -// -// Returns: -// - error: if the block height is not within the indexed range or not compatible with the node's version. -// // Expected errors: -// - storage.ErrHeightNotIndexed if the ScriptExecutor is not initialized, or if the height is not indexed yet, +// - [storage.ErrHeightNotIndexed] if the ScriptExecutor is not initialized, or if the height is not indexed yet, // or if the height is before the lowest indexed height. -// - ErrIncompatibleNodeVersion if the block height is not compatible with the node version. +// - [ErrIncompatibleNodeVersion] if the block height is not compatible with the node version. func (s *ScriptExecutor) checkHeight(height uint64) error { if !s.initialized.Load() { return fmt.Errorf("%w: script executor not initialized", storage.ErrHeightNotIndexed) } - highestHeight, err := s.indexReporter.HighestIndexedHeight() - if err != nil { - return fmt.Errorf("could not get highest indexed height: %w", err) - } - if height > highestHeight { + if height > s.indexReporter.LatestHeight() { return fmt.Errorf("%w: block not indexed yet", storage.ErrHeightNotIndexed) } - lowestHeight, err := s.indexReporter.LowestIndexedHeight() - if err != nil { - return fmt.Errorf("could not get lowest indexed height: %w", err) - } - - if height < lowestHeight { + if height < s.indexReporter.FirstHeight() { return fmt.Errorf("%w: block is before lowest indexed height", storage.ErrHeightNotIndexed) } diff --git a/engine/access/rpc/backend/script_executor_test.go b/engine/access/rpc/backend/script_executor_test.go index 9d127da6810..321283765cb 100644 --- a/engine/access/rpc/backend/script_executor_test.go +++ b/engine/access/rpc/backend/script_executor_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "github.com/onflow/flow-go/engine/access/index" "github.com/onflow/flow-go/engine/common/version" "github.com/onflow/flow-go/engine/execution/computation/query" "github.com/onflow/flow-go/engine/execution/testutil" @@ -20,12 +19,9 @@ import ( "github.com/onflow/flow-go/fvm/storage/derived" "github.com/onflow/flow-go/fvm/storage/snapshot" "github.com/onflow/flow-go/model/flow" - "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/execution" "github.com/onflow/flow-go/module/irrecoverable" "github.com/onflow/flow-go/module/metrics" - "github.com/onflow/flow-go/module/state_synchronization/indexer" - syncmock "github.com/onflow/flow-go/module/state_synchronization/mock" synctest "github.com/onflow/flow-go/module/state_synchronization/requester/unittest" "github.com/onflow/flow-go/storage" storageMock "github.com/onflow/flow-go/storage/mock" @@ -42,8 +38,6 @@ type ScriptExecutorSuite struct { log zerolog.Logger registerIndex storage.RegisterIndex versionControl *version.VersionControl - reporter *syncmock.IndexReporter - indexReporter *index.Reporter scripts *execution.Scripts chain flow.Chain dbDir string @@ -97,15 +91,9 @@ func (s *ScriptExecutorSuite) bootstrap() { // SetupTest sets up the test environment for each test in the suite. // This includes initializing various components and mock objects needed for the tests. func (s *ScriptExecutorSuite) SetupTest() { - lockManager := storage.NewTestingLockManager() s.log = unittest.Logger() s.chain = flow.Emulator.Chain() - s.reporter = syncmock.NewIndexReporter(s.T()) - s.indexReporter = index.NewReporter() - err := s.indexReporter.Initialize(s.reporter) - require.NoError(s.T(), err) - blockchain := unittest.BlockchainFixture(10) s.headers = newBlockHeadersStorage(blockchain) s.height = blockchain[0].Height @@ -115,7 +103,7 @@ func (s *ScriptExecutorSuite) SetupTest() { s.snapshot = snapshot.NewSnapshotTree(nil) s.vm = fvm.NewVirtualMachine() s.vmCtx = fvm.NewContext( - fvm.WithChain(s.chain), + s.chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), ) @@ -129,31 +117,13 @@ func (s *ScriptExecutorSuite) SetupTest() { derivedChainData, err := derived.NewDerivedChainData(derived.DefaultDerivedDataCacheSize) s.Require().NoError(err) - indexerCore := indexer.New( - s.log, - module.ExecutionStateIndexerMetrics(metrics.NewNoopCollector()), - nil, - s.registerIndex, - s.headers, - nil, - nil, - nil, - nil, - nil, - s.chain.ChainID(), - derivedChainData, - nil, - metrics.NewNoopCollector(), - lockManager, - ) - s.scripts = execution.NewScripts( s.log, metrics.NewNoopCollector(), s.chain.ChainID(), protocolState, s.headers, - indexerCore.RegisterValue, + s.registerIndex.Get, query.NewDefaultConfig(), derivedChainData, true, @@ -176,16 +146,13 @@ func (s *ScriptExecutorSuite) TestExecuteAtBlockHeight() { var scriptArgs [][]byte var expectedResult = []byte("{\"type\":\"Void\"}\n") - s.reporter.On("LowestIndexedHeight").Return(s.height, nil) - // This test simulates the behavior when the version beacon is not set in the script executor, // but it should still work by omitting the version control checks. s.Run("test script execution without version control", func() { scriptExec := NewScriptExecutor(s.log, uint64(0), math.MaxUint64) - s.reporter.On("HighestIndexedHeight").Return(s.height+1, nil).Once() // Initialize the script executor without version control - err := scriptExec.Initialize(s.indexReporter, s.scripts, nil) + err := scriptExec.Initialize(s.registerIndex, s.scripts, nil) s.Require().NoError(err) // Execute the script at the specified block height @@ -235,9 +202,8 @@ func (s *ScriptExecutorSuite) TestExecuteAtBlockHeight() { // Initialize the script executor with version control scriptExec := NewScriptExecutor(s.log, uint64(0), math.MaxUint64) - s.reporter.On("HighestIndexedHeight").Return(s.height+1, nil) - err = scriptExec.Initialize(s.indexReporter, s.scripts, s.versionControl) + err = scriptExec.Initialize(s.registerIndex, s.scripts, s.versionControl) s.Require().NoError(err) // Execute the script at the specified block height @@ -287,9 +253,8 @@ func (s *ScriptExecutorSuite) TestExecuteAtBlockHeight() { // Initialize the script executor with version control scriptExec := NewScriptExecutor(s.log, uint64(0), math.MaxUint64) - s.reporter.On("HighestIndexedHeight").Return(s.height+1, nil) - err = scriptExec.Initialize(s.indexReporter, s.scripts, s.versionControl) + err = scriptExec.Initialize(s.registerIndex, s.scripts, s.versionControl) s.Require().NoError(err) // Execute the script at the specified block height diff --git a/engine/access/rpc/backend/scripts/executor/execution_node.go b/engine/access/rpc/backend/scripts/executor/execution_node.go index d6c58e35b43..ba727f18361 100644 --- a/engine/access/rpc/backend/scripts/executor/execution_node.go +++ b/engine/access/rpc/backend/scripts/executor/execution_node.go @@ -12,7 +12,6 @@ import ( "github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator" "github.com/onflow/flow-go/engine/access/rpc/connection" - "github.com/onflow/flow-go/engine/common/rpc" commonrpc "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" @@ -96,7 +95,7 @@ func (e *ENScriptExecutor) Execute(ctx context.Context, request *Request) ([]byt e.metrics.ScriptExecutionErrorOnExecutionNode() e.log.Error().Err(errToReturn).Msg("script execution failed for execution node internal reasons") } - return nil, execDuration, rpc.ConvertError(errToReturn, "failed to execute script on execution nodes", codes.Internal) + return nil, execDuration, commonrpc.ConvertError(errToReturn, "failed to execute script on execution nodes", codes.Internal) } return result, execDuration, nil diff --git a/engine/access/rpc/backend/scripts/scripts_test.go b/engine/access/rpc/backend/scripts/scripts_test.go index bc997576060..77b34a6f121 100644 --- a/engine/access/rpc/backend/scripts/scripts_test.go +++ b/engine/access/rpc/backend/scripts/scripts_test.go @@ -133,7 +133,7 @@ func (s *BackendScriptsSuite) setupExecutionNodes(block *flow.Block) { // this line causes a S1021 lint error because receipts is explicitly declared. this is required // to ensure the mock library handles the response type correctly - var receipts flow.ExecutionReceiptList //nolint:gosimple + var receipts flow.ExecutionReceiptList //nolint:staticcheck receipts = unittest.ReceiptsForBlockFixture(block, s.executionNodes.NodeIDs()) s.receipts.On("ByBlockID", block.ID()).Return(receipts, nil) diff --git a/engine/access/rpc/backend/transactions/error_messages/mock/provider.go b/engine/access/rpc/backend/transactions/error_messages/mock/provider.go deleted file mode 100644 index f829c16512b..00000000000 --- a/engine/access/rpc/backend/transactions/error_messages/mock/provider.go +++ /dev/null @@ -1,217 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - execution "github.com/onflow/flow/protobuf/go/flow/execution" - - flow "github.com/onflow/flow-go/model/flow" - - mock "github.com/stretchr/testify/mock" -) - -// Provider is an autogenerated mock type for the Provider type -type Provider struct { - mock.Mock -} - -// ErrorMessageByBlockIDFromAnyEN provides a mock function with given fields: ctx, execNodes, req -func (_m *Provider) ErrorMessageByBlockIDFromAnyEN(ctx context.Context, execNodes flow.IdentitySkeletonList, req *execution.GetTransactionErrorMessagesByBlockIDRequest) ([]*execution.GetTransactionErrorMessagesResponse_Result, *flow.IdentitySkeleton, error) { - ret := _m.Called(ctx, execNodes, req) - - if len(ret) == 0 { - panic("no return value specified for ErrorMessageByBlockIDFromAnyEN") - } - - var r0 []*execution.GetTransactionErrorMessagesResponse_Result - var r1 *flow.IdentitySkeleton - var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessagesByBlockIDRequest) ([]*execution.GetTransactionErrorMessagesResponse_Result, *flow.IdentitySkeleton, error)); ok { - return rf(ctx, execNodes, req) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessagesByBlockIDRequest) []*execution.GetTransactionErrorMessagesResponse_Result); ok { - r0 = rf(ctx, execNodes, req) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]*execution.GetTransactionErrorMessagesResponse_Result) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessagesByBlockIDRequest) *flow.IdentitySkeleton); ok { - r1 = rf(ctx, execNodes, req) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(*flow.IdentitySkeleton) - } - } - - if rf, ok := ret.Get(2).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessagesByBlockIDRequest) error); ok { - r2 = rf(ctx, execNodes, req) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// ErrorMessageByIndex provides a mock function with given fields: ctx, blockID, height, index -func (_m *Provider) ErrorMessageByIndex(ctx context.Context, blockID flow.Identifier, height uint64, index uint32) (string, error) { - ret := _m.Called(ctx, blockID, height, index) - - if len(ret) == 0 { - panic("no return value specified for ErrorMessageByIndex") - } - - var r0 string - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64, uint32) (string, error)); ok { - return rf(ctx, blockID, height, index) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64, uint32) string); ok { - r0 = rf(ctx, blockID, height, index) - } else { - r0 = ret.Get(0).(string) - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint64, uint32) error); ok { - r1 = rf(ctx, blockID, height, index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ErrorMessageByIndexFromAnyEN provides a mock function with given fields: ctx, execNodes, req -func (_m *Provider) ErrorMessageByIndexFromAnyEN(ctx context.Context, execNodes flow.IdentitySkeletonList, req *execution.GetTransactionErrorMessageByIndexRequest) (*execution.GetTransactionErrorMessageResponse, error) { - ret := _m.Called(ctx, execNodes, req) - - if len(ret) == 0 { - panic("no return value specified for ErrorMessageByIndexFromAnyEN") - } - - var r0 *execution.GetTransactionErrorMessageResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessageByIndexRequest) (*execution.GetTransactionErrorMessageResponse, error)); ok { - return rf(ctx, execNodes, req) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessageByIndexRequest) *execution.GetTransactionErrorMessageResponse); ok { - r0 = rf(ctx, execNodes, req) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*execution.GetTransactionErrorMessageResponse) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessageByIndexRequest) error); ok { - r1 = rf(ctx, execNodes, req) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ErrorMessageByTransactionID provides a mock function with given fields: ctx, blockID, height, transactionID -func (_m *Provider) ErrorMessageByTransactionID(ctx context.Context, blockID flow.Identifier, height uint64, transactionID flow.Identifier) (string, error) { - ret := _m.Called(ctx, blockID, height, transactionID) - - if len(ret) == 0 { - panic("no return value specified for ErrorMessageByTransactionID") - } - - var r0 string - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64, flow.Identifier) (string, error)); ok { - return rf(ctx, blockID, height, transactionID) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64, flow.Identifier) string); ok { - r0 = rf(ctx, blockID, height, transactionID) - } else { - r0 = ret.Get(0).(string) - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint64, flow.Identifier) error); ok { - r1 = rf(ctx, blockID, height, transactionID) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ErrorMessageFromAnyEN provides a mock function with given fields: ctx, execNodes, req -func (_m *Provider) ErrorMessageFromAnyEN(ctx context.Context, execNodes flow.IdentitySkeletonList, req *execution.GetTransactionErrorMessageRequest) (*execution.GetTransactionErrorMessageResponse, error) { - ret := _m.Called(ctx, execNodes, req) - - if len(ret) == 0 { - panic("no return value specified for ErrorMessageFromAnyEN") - } - - var r0 *execution.GetTransactionErrorMessageResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessageRequest) (*execution.GetTransactionErrorMessageResponse, error)); ok { - return rf(ctx, execNodes, req) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessageRequest) *execution.GetTransactionErrorMessageResponse); ok { - r0 = rf(ctx, execNodes, req) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*execution.GetTransactionErrorMessageResponse) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.IdentitySkeletonList, *execution.GetTransactionErrorMessageRequest) error); ok { - r1 = rf(ctx, execNodes, req) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ErrorMessagesByBlockID provides a mock function with given fields: ctx, blockID, height -func (_m *Provider) ErrorMessagesByBlockID(ctx context.Context, blockID flow.Identifier, height uint64) (map[flow.Identifier]string, error) { - ret := _m.Called(ctx, blockID, height) - - if len(ret) == 0 { - panic("no return value specified for ErrorMessagesByBlockID") - } - - var r0 map[flow.Identifier]string - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) (map[flow.Identifier]string, error)); ok { - return rf(ctx, blockID, height) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) map[flow.Identifier]string); ok { - r0 = rf(ctx, blockID, height) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(map[flow.Identifier]string) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint64) error); ok { - r1 = rf(ctx, blockID, height) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewProvider creates a new instance of Provider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *Provider { - mock := &Provider{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/access/rpc/backend/transactions/provider/execution_node.go b/engine/access/rpc/backend/transactions/provider/execution_node.go index ebb1d19e43e..79f2e4a8b3a 100644 --- a/engine/access/rpc/backend/transactions/provider/execution_node.go +++ b/engine/access/rpc/backend/transactions/provider/execution_node.go @@ -117,17 +117,24 @@ func (e *ENTransactionProvider) TransactionResult( } return &accessmodel.TransactionResult{ - TransactionID: transactionID, - Status: txStatus, - StatusCode: uint(resp.GetStatusCode()), - Events: events, - ErrorMessage: resp.GetErrorMessage(), - BlockID: blockID, - BlockHeight: block.Height, - CollectionID: collectionID, + TransactionID: transactionID, + Status: txStatus, + StatusCode: uint(resp.GetStatusCode()), + Events: events, + ErrorMessage: resp.GetErrorMessage(), + BlockID: blockID, + BlockHeight: block.Height, + CollectionID: collectionID, + ComputationUsed: resp.GetComputationUsage(), }, nil } +// TransactionsByBlockID returns the transaction for the given block ID. +// +// Expected error returns during normal operation: +// - [codes.NotFound]: If the requested data is not found. +// - [codes.Unavailable]: If no nodes are available or a connection to an execution node cannot be established. +// - [codes.Internal]: If the system collection cannot be constructed. func (e *ENTransactionProvider) TransactionsByBlockID( ctx context.Context, block *flow.Block, @@ -153,7 +160,7 @@ func (e *ENTransactionProvider) TransactionsByBlockID( ByHeight(block.Height). SystemCollection(e.chainID.Chain(), eventProvider) if err != nil { - return nil, status.Errorf(codes.Internal, "could not construct system collection: %v", err) + return nil, rpc.ConvertError(err, "could not construct system collection", codes.Internal) } return append(transactions, systemCollection.Transactions...), nil @@ -210,17 +217,24 @@ func (e *ENTransactionProvider) TransactionResultByIndex( // convert to response, cache and return return &accessmodel.TransactionResult{ - Status: txStatus, - StatusCode: uint(resp.GetStatusCode()), - Events: events, - ErrorMessage: resp.GetErrorMessage(), - BlockID: blockID, - BlockHeight: block.Height, - TransactionID: txID, - CollectionID: collectionID, + Status: txStatus, + StatusCode: uint(resp.GetStatusCode()), + Events: events, + ErrorMessage: resp.GetErrorMessage(), + BlockID: blockID, + BlockHeight: block.Height, + TransactionID: txID, + CollectionID: collectionID, + ComputationUsed: resp.GetComputationUsage(), }, nil } +// TransactionResultsByBlockID get the transaction results by block ID. +// +// Expected error returns during normal operation: +// - [codes.NotFound]: If the requested data is not found. +// - [codes.Unavailable]: If no nodes are available or a connection to an execution node cannot be established. +// - [codes.Internal]: For internal execution node failures. func (e *ENTransactionProvider) TransactionResultsByBlockID( ctx context.Context, block *flow.Block, @@ -295,8 +309,9 @@ func (e *ENTransactionProvider) TransactionResultsByBlockID( // execution node response. // // Expected error returns during normal operation: -// - [codes.Internal]: if the scheduled transactions cannot be constructed -// - [status.Error]: for any error returned by the execution node +// - [codes.Internal]: If the scheduled transactions cannot be constructed. +// - [codes.Unavailable]: If no nodes are available or a connection to an execution node cannot be established. +// - [status.Error]: For any error returned by the execution node. func (e *ENTransactionProvider) ScheduledTransactionsByBlockID( ctx context.Context, header *flow.Header, @@ -355,14 +370,15 @@ func (e *ENTransactionProvider) userTransactionResults( } results = append(results, &accessmodel.TransactionResult{ - Status: txStatus, - StatusCode: uint(txResult.GetStatusCode()), - Events: events, - ErrorMessage: txResult.GetErrorMessage(), - BlockID: blockID, - TransactionID: txID, - CollectionID: guarantee.CollectionID, - BlockHeight: block.Height, + Status: txStatus, + StatusCode: uint(txResult.GetStatusCode()), + Events: events, + ErrorMessage: txResult.GetErrorMessage(), + BlockID: blockID, + TransactionID: txID, + CollectionID: guarantee.CollectionID, + BlockHeight: block.Height, + ComputationUsed: txResult.GetComputationUsage(), }) i++ @@ -406,14 +422,15 @@ func (e *ENTransactionProvider) systemTransactionResults( } results = append(results, &accessmodel.TransactionResult{ - Status: txStatus, - StatusCode: uint(systemTxResult.GetStatusCode()), - Events: events, - ErrorMessage: systemTxResult.GetErrorMessage(), - BlockID: blockID, - TransactionID: systemTxIDs[i], - CollectionID: flow.ZeroID, - BlockHeight: block.Height, + Status: txStatus, + StatusCode: uint(systemTxResult.GetStatusCode()), + Events: events, + ErrorMessage: systemTxResult.GetErrorMessage(), + BlockID: blockID, + TransactionID: systemTxIDs[i], + CollectionID: flow.ZeroID, + BlockHeight: block.Height, + ComputationUsed: systemTxResult.GetComputationUsage(), }) } @@ -443,7 +460,7 @@ func (e *ENTransactionProvider) systemTransactionIDs( ByHeight(blockHeight). SystemCollection(e.chainID.Chain(), eventProvider) if err != nil { - return nil, rpc.ConvertError(err, "failed to construct system collection", codes.Internal) + return nil, rpc.ConvertError(err, "could not construct system collection", codes.Internal) } var systemTxIDs []flow.Identifier @@ -454,6 +471,12 @@ func (e *ENTransactionProvider) systemTransactionIDs( return systemTxIDs, nil } +// getBlockEvents returns all events by the given block ID. +// +// Expected error returns during normal operation: +// - [codes.NotFound]: If the requested data is not found. +// - [codes.Unavailable]: If no nodes are available or a connection to an execution node cannot be established. +// - [codes.Internal]: For internal execution node failures. func (e *ENTransactionProvider) getBlockEvents( ctx context.Context, blockID flow.Identifier, @@ -609,6 +632,11 @@ func (e *ENTransactionProvider) getTransactionResultByIndexFromAnyExeNode( return resp, errToReturn } +// getBlockEventsByBlockIDsFromAnyExeNode get events by block ID from the execution node. +// +// Expected error returns during normal operation: +// - [codes.Unavailable]: If no nodes are available or a connection to an execution node cannot be established. +// - [status.Error]: If the execution node returns a gRPC error. func (e *ENTransactionProvider) getBlockEventsByBlockIDsFromAnyExeNode( ctx context.Context, execNodes flow.IdentitySkeletonList, @@ -696,6 +724,11 @@ func (e *ENTransactionProvider) tryGetTransactionResultByIndex( return resp, nil } +// tryGetBlockEventsByBlockIDs attempts to get events by block ID from the given execution node. +// +// Expected error returns during normal operation: +// - [codes.Unavailable]: If a connection to an execution node cannot be established. +// - [status.Error]: If the execution node returns a gRPC error. func (e *ENTransactionProvider) tryGetBlockEventsByBlockIDs( ctx context.Context, execNode *flow.IdentitySkeleton, @@ -720,6 +753,7 @@ func (e *ENTransactionProvider) tryGetBlockEventsByBlockIDs( // // Expected error returns during normal operation: // - [codes.NotFound]: if the transaction is not found in the block. +// - [codes.Unavailable]: If no nodes are available or a connection to an execution node cannot be established. // - [codes.Internal]: if the system collection cannot be constructed. func (e *ENTransactionProvider) getTransactionIDByIndex(ctx context.Context, block *flow.Block, index uint32) (flow.Identifier, error) { i := uint32(0) @@ -747,7 +781,7 @@ func (e *ENTransactionProvider) getTransactionIDByIndex(ctx context.Context, blo ByHeight(block.Height). SystemCollection(e.chainID.Chain(), eventProvider) if err != nil { - return flow.ZeroID, status.Errorf(codes.Internal, "could not construct system collection: %v", err) + return flow.ZeroID, rpc.ConvertError(err, "could not construct system collection", codes.Internal) } for _, tx := range systemCollection.Transactions { diff --git a/engine/access/rpc/backend/transactions/provider/local.go b/engine/access/rpc/backend/transactions/provider/local.go index 888a1768a5f..23ae780a683 100644 --- a/engine/access/rpc/backend/transactions/provider/local.go +++ b/engine/access/rpc/backend/transactions/provider/local.go @@ -30,7 +30,7 @@ var ErrTransactionNotInBlock = errors.New("transaction not in block") // LocalTransactionProvider provides functionality for retrieving transaction results and error messages from local storages type LocalTransactionProvider struct { state protocol.State - collections storage.Collections + collections storage.CollectionsReader blocks storage.Blocks eventsIndex *index.EventsIndex txResultsIndex *index.TransactionResultsIndex @@ -44,7 +44,7 @@ var _ TransactionProvider = (*LocalTransactionProvider)(nil) func NewLocalTransactionProvider( state protocol.State, - collections storage.Collections, + collections storage.CollectionsReader, blocks storage.Blocks, eventsIndex *index.EventsIndex, txResultsIndex *index.TransactionResultsIndex, @@ -91,9 +91,13 @@ func (t *LocalTransactionProvider) TransactionResult( var txErrorMessage string var txStatusCode uint = 0 if txResult.Failed { - txErrorMessage, err = t.txErrorMessages.ErrorMessageByTransactionID(ctx, blockID, header.Height, transactionID) - if err != nil { - return nil, err + if t.txErrorMessages != nil { + txErrorMessage, err = t.txErrorMessages.ErrorMessageByTransactionID(ctx, blockID, header.Height, transactionID) + if err != nil { + return nil, err + } + } else { + txErrorMessage = error_messages.DefaultFailedErrorMessage } if len(txErrorMessage) == 0 { @@ -130,14 +134,15 @@ func (t *LocalTransactionProvider) TransactionResult( } return &accessmodel.TransactionResult{ - TransactionID: txResult.TransactionID, - Status: txStatus, - StatusCode: txStatusCode, - Events: events, - ErrorMessage: txErrorMessage, - BlockID: blockID, - BlockHeight: header.Height, - CollectionID: collectionID, + TransactionID: txResult.TransactionID, + Status: txStatus, + StatusCode: txStatusCode, + Events: events, + ErrorMessage: txErrorMessage, + BlockID: blockID, + BlockHeight: header.Height, + CollectionID: collectionID, + ComputationUsed: txResult.ComputationUsed, }, nil } @@ -166,9 +171,13 @@ func (t *LocalTransactionProvider) TransactionResultByIndex( var txErrorMessage string var txStatusCode uint = 0 if txResult.Failed { - txErrorMessage, err = t.txErrorMessages.ErrorMessageByIndex(ctx, blockID, block.Height, index) - if err != nil { - return nil, err + if t.txErrorMessages != nil { + txErrorMessage, err = t.txErrorMessages.ErrorMessageByIndex(ctx, blockID, block.Height, index) + if err != nil { + return nil, err + } + } else { + txErrorMessage = error_messages.DefaultFailedErrorMessage } if len(txErrorMessage) == 0 { @@ -200,14 +209,15 @@ func (t *LocalTransactionProvider) TransactionResultByIndex( } return &accessmodel.TransactionResult{ - TransactionID: txResult.TransactionID, - Status: txStatus, - StatusCode: txStatusCode, - Events: events, - ErrorMessage: txErrorMessage, - BlockID: blockID, - BlockHeight: block.Height, - CollectionID: collectionID, + TransactionID: txResult.TransactionID, + Status: txStatus, + StatusCode: txStatusCode, + Events: events, + ErrorMessage: txErrorMessage, + BlockID: blockID, + BlockHeight: block.Height, + CollectionID: collectionID, + ComputationUsed: txResult.ComputationUsed, }, nil } @@ -268,9 +278,12 @@ func (t *LocalTransactionProvider) TransactionResultsByBlockID( return nil, rpc.ConvertIndexError(err, block.Height, "failed to get transaction result") } - txErrors, err := t.txErrorMessages.ErrorMessagesByBlockID(ctx, blockID, block.Height) - if err != nil { - return nil, err + txErrors := make(map[flow.Identifier]string) + if t.txErrorMessages != nil { + txErrors, err = t.txErrorMessages.ErrorMessagesByBlockID(ctx, blockID, block.Height) + if err != nil { + return nil, err + } } numberOfTxResults := len(txResults) @@ -301,9 +314,13 @@ func (t *LocalTransactionProvider) TransactionResultsByBlockID( var txErrorMessage string var txStatusCode uint = 0 if txResult.Failed { - txErrorMessage = txErrors[txResult.TransactionID] - if len(txErrorMessage) == 0 { - return nil, status.Errorf(codes.Internal, "transaction failed but error message is empty for tx ID: %s block ID: %s", txID, blockID) + if t.txErrorMessages != nil { + txErrorMessage = txErrors[txResult.TransactionID] + if len(txErrorMessage) == 0 { + return nil, status.Errorf(codes.Internal, "transaction failed but error message is empty for tx ID: %s block ID: %s", txID, blockID) + } + } else { + txErrorMessage = error_messages.DefaultFailedErrorMessage } txStatusCode = 1 } @@ -329,14 +346,15 @@ func (t *LocalTransactionProvider) TransactionResultsByBlockID( } results = append(results, &accessmodel.TransactionResult{ - Status: txStatus, - StatusCode: txStatusCode, - Events: events, - ErrorMessage: txErrorMessage, - BlockID: blockID, - TransactionID: txID, - CollectionID: collectionID, - BlockHeight: block.Height, + Status: txStatus, + StatusCode: txStatusCode, + Events: events, + ErrorMessage: txErrorMessage, + BlockID: blockID, + TransactionID: txID, + CollectionID: collectionID, + BlockHeight: block.Height, + ComputationUsed: txResult.ComputationUsed, }) } diff --git a/engine/access/rpc/backend/transactions/provider/mock/transaction_provider.go b/engine/access/rpc/backend/transactions/provider/mock/transaction_provider.go index 1a762a038de..109fea3a1bd 100644 --- a/engine/access/rpc/backend/transactions/provider/mock/transaction_provider.go +++ b/engine/access/rpc/backend/transactions/provider/mock/transaction_provider.go @@ -1,27 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - access "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow/protobuf/go/flow/entities" + mock "github.com/stretchr/testify/mock" +) - entities "github.com/onflow/flow/protobuf/go/flow/entities" +// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionProvider { + mock := &TransactionProvider{} + mock.Mock.Test(t) - flow "github.com/onflow/flow-go/model/flow" + t.Cleanup(func() { mock.AssertExpectations(t) }) - mock "github.com/stretchr/testify/mock" -) + return mock +} // TransactionProvider is an autogenerated mock type for the TransactionProvider type type TransactionProvider struct { mock.Mock } -// ScheduledTransactionsByBlockID provides a mock function with given fields: ctx, header -func (_m *TransactionProvider) ScheduledTransactionsByBlockID(ctx context.Context, header *flow.Header) ([]*flow.TransactionBody, error) { - ret := _m.Called(ctx, header) +type TransactionProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionProvider) EXPECT() *TransactionProvider_Expecter { + return &TransactionProvider_Expecter{mock: &_m.Mock} +} + +// ScheduledTransactionsByBlockID provides a mock function for the type TransactionProvider +func (_mock *TransactionProvider) ScheduledTransactionsByBlockID(ctx context.Context, header *flow.Header) ([]*flow.TransactionBody, error) { + ret := _mock.Called(ctx, header) if len(ret) == 0 { panic("no return value specified for ScheduledTransactionsByBlockID") @@ -29,29 +50,67 @@ func (_m *TransactionProvider) ScheduledTransactionsByBlockID(ctx context.Contex var r0 []*flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.Header) ([]*flow.TransactionBody, error)); ok { - return rf(ctx, header) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Header) ([]*flow.TransactionBody, error)); ok { + return returnFunc(ctx, header) } - if rf, ok := ret.Get(0).(func(context.Context, *flow.Header) []*flow.TransactionBody); ok { - r0 = rf(ctx, header) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Header) []*flow.TransactionBody); ok { + r0 = returnFunc(ctx, header) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, *flow.Header) error); ok { - r1 = rf(ctx, header) + if returnFunc, ok := ret.Get(1).(func(context.Context, *flow.Header) error); ok { + r1 = returnFunc(ctx, header) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionResult provides a mock function with given fields: ctx, header, txID, collectionID, encodingVersion -func (_m *TransactionProvider) TransactionResult(ctx context.Context, header *flow.Header, txID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { - ret := _m.Called(ctx, header, txID, collectionID, encodingVersion) +// TransactionProvider_ScheduledTransactionsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScheduledTransactionsByBlockID' +type TransactionProvider_ScheduledTransactionsByBlockID_Call struct { + *mock.Call +} + +// ScheduledTransactionsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - header *flow.Header +func (_e *TransactionProvider_Expecter) ScheduledTransactionsByBlockID(ctx interface{}, header interface{}) *TransactionProvider_ScheduledTransactionsByBlockID_Call { + return &TransactionProvider_ScheduledTransactionsByBlockID_Call{Call: _e.mock.On("ScheduledTransactionsByBlockID", ctx, header)} +} + +func (_c *TransactionProvider_ScheduledTransactionsByBlockID_Call) Run(run func(ctx context.Context, header *flow.Header)) *TransactionProvider_ScheduledTransactionsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionProvider_ScheduledTransactionsByBlockID_Call) Return(transactionBodys []*flow.TransactionBody, err error) *TransactionProvider_ScheduledTransactionsByBlockID_Call { + _c.Call.Return(transactionBodys, err) + return _c +} + +func (_c *TransactionProvider_ScheduledTransactionsByBlockID_Call) RunAndReturn(run func(ctx context.Context, header *flow.Header) ([]*flow.TransactionBody, error)) *TransactionProvider_ScheduledTransactionsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// TransactionResult provides a mock function for the type TransactionProvider +func (_mock *TransactionProvider) TransactionResult(ctx context.Context, header *flow.Header, txID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, header, txID, collectionID, encodingVersion) if len(ret) == 0 { panic("no return value specified for TransactionResult") @@ -59,29 +118,85 @@ func (_m *TransactionProvider) TransactionResult(ctx context.Context, header *fl var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.Header, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { - return rf(ctx, header, txID, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Header, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, header, txID, collectionID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, *flow.Header, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { - r0 = rf(ctx, header, txID, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Header, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, header, txID, collectionID, encodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, *flow.Header, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, header, txID, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, *flow.Header, flow.Identifier, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, header, txID, collectionID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionResultByIndex provides a mock function with given fields: ctx, block, index, collectionID, encodingVersion -func (_m *TransactionProvider) TransactionResultByIndex(ctx context.Context, block *flow.Block, index uint32, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { - ret := _m.Called(ctx, block, index, collectionID, encodingVersion) +// TransactionProvider_TransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionResult' +type TransactionProvider_TransactionResult_Call struct { + *mock.Call +} + +// TransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - header *flow.Header +// - txID flow.Identifier +// - collectionID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionProvider_Expecter) TransactionResult(ctx interface{}, header interface{}, txID interface{}, collectionID interface{}, encodingVersion interface{}) *TransactionProvider_TransactionResult_Call { + return &TransactionProvider_TransactionResult_Call{Call: _e.mock.On("TransactionResult", ctx, header, txID, collectionID, encodingVersion)} +} + +func (_c *TransactionProvider_TransactionResult_Call) Run(run func(ctx context.Context, header *flow.Header, txID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *TransactionProvider_TransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + var arg4 entities.EventEncodingVersion + if args[4] != nil { + arg4 = args[4].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *TransactionProvider_TransactionResult_Call) Return(transactionResult *access.TransactionResult, err error) *TransactionProvider_TransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionProvider_TransactionResult_Call) RunAndReturn(run func(ctx context.Context, header *flow.Header, txID flow.Identifier, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *TransactionProvider_TransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// TransactionResultByIndex provides a mock function for the type TransactionProvider +func (_mock *TransactionProvider) TransactionResultByIndex(ctx context.Context, block *flow.Block, index uint32, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error) { + ret := _mock.Called(ctx, block, index, collectionID, encodingVersion) if len(ret) == 0 { panic("no return value specified for TransactionResultByIndex") @@ -89,29 +204,85 @@ func (_m *TransactionProvider) TransactionResultByIndex(ctx context.Context, blo var r0 *access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.Block, uint32, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { - return rf(ctx, block, index, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Block, uint32, flow.Identifier, entities.EventEncodingVersion) (*access.TransactionResult, error)); ok { + return returnFunc(ctx, block, index, collectionID, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, *flow.Block, uint32, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { - r0 = rf(ctx, block, index, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Block, uint32, flow.Identifier, entities.EventEncodingVersion) *access.TransactionResult); ok { + r0 = returnFunc(ctx, block, index, collectionID, encodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, *flow.Block, uint32, flow.Identifier, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, block, index, collectionID, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, *flow.Block, uint32, flow.Identifier, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, block, index, collectionID, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionResultsByBlockID provides a mock function with given fields: ctx, block, encodingVersion -func (_m *TransactionProvider) TransactionResultsByBlockID(ctx context.Context, block *flow.Block, encodingVersion entities.EventEncodingVersion) ([]*access.TransactionResult, error) { - ret := _m.Called(ctx, block, encodingVersion) +// TransactionProvider_TransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionResultByIndex' +type TransactionProvider_TransactionResultByIndex_Call struct { + *mock.Call +} + +// TransactionResultByIndex is a helper method to define mock.On call +// - ctx context.Context +// - block *flow.Block +// - index uint32 +// - collectionID flow.Identifier +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionProvider_Expecter) TransactionResultByIndex(ctx interface{}, block interface{}, index interface{}, collectionID interface{}, encodingVersion interface{}) *TransactionProvider_TransactionResultByIndex_Call { + return &TransactionProvider_TransactionResultByIndex_Call{Call: _e.mock.On("TransactionResultByIndex", ctx, block, index, collectionID, encodingVersion)} +} + +func (_c *TransactionProvider_TransactionResultByIndex_Call) Run(run func(ctx context.Context, block *flow.Block, index uint32, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion)) *TransactionProvider_TransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.Block + if args[1] != nil { + arg1 = args[1].(*flow.Block) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + var arg4 entities.EventEncodingVersion + if args[4] != nil { + arg4 = args[4].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *TransactionProvider_TransactionResultByIndex_Call) Return(transactionResult *access.TransactionResult, err error) *TransactionProvider_TransactionResultByIndex_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionProvider_TransactionResultByIndex_Call) RunAndReturn(run func(ctx context.Context, block *flow.Block, index uint32, collectionID flow.Identifier, encodingVersion entities.EventEncodingVersion) (*access.TransactionResult, error)) *TransactionProvider_TransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// TransactionResultsByBlockID provides a mock function for the type TransactionProvider +func (_mock *TransactionProvider) TransactionResultsByBlockID(ctx context.Context, block *flow.Block, encodingVersion entities.EventEncodingVersion) ([]*access.TransactionResult, error) { + ret := _mock.Called(ctx, block, encodingVersion) if len(ret) == 0 { panic("no return value specified for TransactionResultsByBlockID") @@ -119,29 +290,73 @@ func (_m *TransactionProvider) TransactionResultsByBlockID(ctx context.Context, var r0 []*access.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.Block, entities.EventEncodingVersion) ([]*access.TransactionResult, error)); ok { - return rf(ctx, block, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Block, entities.EventEncodingVersion) ([]*access.TransactionResult, error)); ok { + return returnFunc(ctx, block, encodingVersion) } - if rf, ok := ret.Get(0).(func(context.Context, *flow.Block, entities.EventEncodingVersion) []*access.TransactionResult); ok { - r0 = rf(ctx, block, encodingVersion) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Block, entities.EventEncodingVersion) []*access.TransactionResult); ok { + r0 = returnFunc(ctx, block, encodingVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*access.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, *flow.Block, entities.EventEncodingVersion) error); ok { - r1 = rf(ctx, block, encodingVersion) + if returnFunc, ok := ret.Get(1).(func(context.Context, *flow.Block, entities.EventEncodingVersion) error); ok { + r1 = returnFunc(ctx, block, encodingVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionsByBlockID provides a mock function with given fields: ctx, block -func (_m *TransactionProvider) TransactionsByBlockID(ctx context.Context, block *flow.Block) ([]*flow.TransactionBody, error) { - ret := _m.Called(ctx, block) +// TransactionProvider_TransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionResultsByBlockID' +type TransactionProvider_TransactionResultsByBlockID_Call struct { + *mock.Call +} + +// TransactionResultsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - block *flow.Block +// - encodingVersion entities.EventEncodingVersion +func (_e *TransactionProvider_Expecter) TransactionResultsByBlockID(ctx interface{}, block interface{}, encodingVersion interface{}) *TransactionProvider_TransactionResultsByBlockID_Call { + return &TransactionProvider_TransactionResultsByBlockID_Call{Call: _e.mock.On("TransactionResultsByBlockID", ctx, block, encodingVersion)} +} + +func (_c *TransactionProvider_TransactionResultsByBlockID_Call) Run(run func(ctx context.Context, block *flow.Block, encodingVersion entities.EventEncodingVersion)) *TransactionProvider_TransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.Block + if args[1] != nil { + arg1 = args[1].(*flow.Block) + } + var arg2 entities.EventEncodingVersion + if args[2] != nil { + arg2 = args[2].(entities.EventEncodingVersion) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TransactionProvider_TransactionResultsByBlockID_Call) Return(transactionResults []*access.TransactionResult, err error) *TransactionProvider_TransactionResultsByBlockID_Call { + _c.Call.Return(transactionResults, err) + return _c +} + +func (_c *TransactionProvider_TransactionResultsByBlockID_Call) RunAndReturn(run func(ctx context.Context, block *flow.Block, encodingVersion entities.EventEncodingVersion) ([]*access.TransactionResult, error)) *TransactionProvider_TransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// TransactionsByBlockID provides a mock function for the type TransactionProvider +func (_mock *TransactionProvider) TransactionsByBlockID(ctx context.Context, block *flow.Block) ([]*flow.TransactionBody, error) { + ret := _mock.Called(ctx, block) if len(ret) == 0 { panic("no return value specified for TransactionsByBlockID") @@ -149,36 +364,60 @@ func (_m *TransactionProvider) TransactionsByBlockID(ctx context.Context, block var r0 []*flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.Block) ([]*flow.TransactionBody, error)); ok { - return rf(ctx, block) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Block) ([]*flow.TransactionBody, error)); ok { + return returnFunc(ctx, block) } - if rf, ok := ret.Get(0).(func(context.Context, *flow.Block) []*flow.TransactionBody); ok { - r0 = rf(ctx, block) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Block) []*flow.TransactionBody); ok { + r0 = returnFunc(ctx, block) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(context.Context, *flow.Block) error); ok { - r1 = rf(ctx, block) + if returnFunc, ok := ret.Get(1).(func(context.Context, *flow.Block) error); ok { + r1 = returnFunc(ctx, block) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionProvider { - mock := &TransactionProvider{} - mock.Mock.Test(t) +// TransactionProvider_TransactionsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionsByBlockID' +type TransactionProvider_TransactionsByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TransactionsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - block *flow.Block +func (_e *TransactionProvider_Expecter) TransactionsByBlockID(ctx interface{}, block interface{}) *TransactionProvider_TransactionsByBlockID_Call { + return &TransactionProvider_TransactionsByBlockID_Call{Call: _e.mock.On("TransactionsByBlockID", ctx, block)} +} - return mock +func (_c *TransactionProvider_TransactionsByBlockID_Call) Run(run func(ctx context.Context, block *flow.Block)) *TransactionProvider_TransactionsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.Block + if args[1] != nil { + arg1 = args[1].(*flow.Block) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionProvider_TransactionsByBlockID_Call) Return(transactionBodys []*flow.TransactionBody, err error) *TransactionProvider_TransactionsByBlockID_Call { + _c.Call.Return(transactionBodys, err) + return _c +} + +func (_c *TransactionProvider_TransactionsByBlockID_Call) RunAndReturn(run func(ctx context.Context, block *flow.Block) ([]*flow.TransactionBody, error)) *TransactionProvider_TransactionsByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rpc/backend/transactions/stream/stream_backend_test.go b/engine/access/rpc/backend/transactions/stream/stream_backend_test.go index 0dc3a05b1ff..8cd8687b193 100644 --- a/engine/access/rpc/backend/transactions/stream/stream_backend_test.go +++ b/engine/access/rpc/backend/transactions/stream/stream_backend_test.go @@ -193,7 +193,7 @@ func (s *TransactionStreamSuite) initializeBackend() { // this line causes a S1021 lint error because receipts is explicitly declared. this is required // to ensure the mock library handles the response type correctly - var receipts flow.ExecutionReceiptList //nolint:gosimple + var receipts flow.ExecutionReceiptList //nolint:staticcheck executionNodes := unittest.IdentityListFixture(2, unittest.WithRole(flow.RoleExecution)) receipts = unittest.ReceiptsForBlockFixture(s.rootBlock, executionNodes.NodeIDs()) s.receipts.On("ByBlockID", mock.AnythingOfType("flow.Identifier")).Return(receipts, nil).Maybe() diff --git a/engine/access/rpc/backend/transactions/transactions.go b/engine/access/rpc/backend/transactions/transactions.go index a15147410e2..45aed86b3c6 100644 --- a/engine/access/rpc/backend/transactions/transactions.go +++ b/engine/access/rpc/backend/transactions/transactions.go @@ -413,8 +413,17 @@ func (t *Transactions) lookupSubmittedTransactionResult( // 2. lookup the block containing the collection. block, err := t.blocks.ByCollectionID(collectionID) if err != nil { - // this is an exception. the block/collection index must exist if the collection/tx is indexed, - // otherwise the stored state is inconsistent. + // The txID → collectionID index (checked in step 1) and the guaranteeID → blockID index + // (checked here) are built by separate async components: the collection Indexer and + // the FinalizedBlockProcessor respectively. During catch-up or under load, the + // FinalizedBlockProcessor may lag behind, causing ErrNotFound here even though the + // collection is indexed. This is a transient state that resolves once finalization + // processing catches up. + if errors.Is(err, storage.ErrNotFound) { + return nil, nil, status.Errorf(codes.NotFound, "block not found for collection %v", collectionID) + } + + // any other error is an exception. err = fmt.Errorf("failed to find block for collection %v: %w", collectionID, err) irrecoverable.Throw(ctx, err) return nil, nil, err diff --git a/engine/access/rpc/backend/transactions/transactions_functional_test.go b/engine/access/rpc/backend/transactions/transactions_functional_test.go index 263f8022029..0c7b927b9f9 100644 --- a/engine/access/rpc/backend/transactions/transactions_functional_test.go +++ b/engine/access/rpc/backend/transactions/transactions_functional_test.go @@ -11,9 +11,10 @@ import ( "github.com/rs/zerolog" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/onflow/flow/protobuf/go/flow/entities" - "github.com/onflow/flow/protobuf/go/flow/execution" execproto "github.com/onflow/flow/protobuf/go/flow/execution" "github.com/onflow/flow-go/access/validator" @@ -28,14 +29,13 @@ import ( "github.com/onflow/flow-go/engine/common/rpc/convert" "github.com/onflow/flow-go/fvm/blueprints" "github.com/onflow/flow-go/fvm/systemcontracts" - "github.com/onflow/flow-go/model/access" accessmodel "github.com/onflow/flow-go/model/access" "github.com/onflow/flow-go/model/access/systemcollection" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/counters" execmock "github.com/onflow/flow-go/module/execution/mock" - testutil "github.com/onflow/flow-go/module/executiondatasync/testutil" + "github.com/onflow/flow-go/module/executiondatasync/testutil" "github.com/onflow/flow-go/module/metrics" syncmock "github.com/onflow/flow-go/module/state_synchronization/mock" protocol "github.com/onflow/flow-go/state/protocol/badger" @@ -345,7 +345,7 @@ func scheduledTransactionFromEvents( ) (*flow.TransactionBody, error) { systemCollection, err := systemcollection.Default(chainID). ByHeight(blockHeight). - SystemCollection(chainID.Chain(), access.StaticEventProvider(events)) + SystemCollection(chainID.Chain(), accessmodel.StaticEventProvider(events)) if err != nil { return nil, err } @@ -402,14 +402,15 @@ func (s *TransactionsFunctionalSuite) expectedResultForIndex(index int, encoding } return &accessmodel.TransactionResult{ - TransactionID: txID, - Status: flow.TransactionStatusExecuted, - StatusCode: statusCode, - Events: events, - ErrorMessage: errorMessage, - BlockID: blockID, - BlockHeight: block.Height, - CollectionID: collectionID, + TransactionID: txID, + Status: flow.TransactionStatusExecuted, + StatusCode: statusCode, + Events: events, + ErrorMessage: errorMessage, + BlockID: blockID, + BlockHeight: block.Height, + CollectionID: collectionID, + ComputationUsed: txResult.ComputationUsed, } } @@ -521,7 +522,7 @@ func (s *TransactionsFunctionalSuite) TestTransactionsByBlockID_Local() { versionedSystemCollection := systemcollection.Default(s.g.ChainID()) systemCollection, err := versionedSystemCollection. ByHeight(block.Height). - SystemCollection(s.g.ChainID().Chain(), access.StaticEventProvider(s.tf.ExpectedEvents)) + SystemCollection(s.g.ChainID().Chain(), accessmodel.StaticEventProvider(s.tf.ExpectedEvents)) s.Require().NoError(err) expectedTransactions = append(expectedTransactions, systemCollection.Transactions...) @@ -592,11 +593,12 @@ func (s *TransactionsFunctionalSuite) TestTransactionResult_ExecutionNode() { txID := s.tf.ExpectedResults[1].TransactionID accessResponse := convert.TransactionResultToMessage(s.expectedResultForIndex(1, entities.EventEncodingVersion_CCF_V0)) - nodeResponse := &execution.GetTransactionResultResponse{ + nodeResponse := &execproto.GetTransactionResultResponse{ StatusCode: accessResponse.StatusCode, ErrorMessage: accessResponse.ErrorMessage, Events: accessResponse.Events, EventEncodingVersion: entities.EventEncodingVersion_CCF_V0, + ComputationUsage: accessResponse.ComputationUsage, } expectedResult := s.expectedResultForIndex(1, entities.EventEncodingVersion_JSON_CDC_V0) @@ -622,11 +624,12 @@ func (s *TransactionsFunctionalSuite) TestTransactionResultByIndex_ExecutionNode blockID := s.tf.Block.ID() accessResponse := convert.TransactionResultToMessage(s.expectedResultForIndex(1, entities.EventEncodingVersion_CCF_V0)) - nodeResponse := &execution.GetTransactionResultResponse{ + nodeResponse := &execproto.GetTransactionResultResponse{ StatusCode: accessResponse.StatusCode, ErrorMessage: accessResponse.ErrorMessage, Events: accessResponse.Events, EventEncodingVersion: entities.EventEncodingVersion_CCF_V0, + ComputationUsage: accessResponse.ComputationUsage, } expectedResult := s.expectedResultForIndex(1, entities.EventEncodingVersion_JSON_CDC_V0) @@ -648,22 +651,50 @@ func (s *TransactionsFunctionalSuite) TestTransactionResultByIndex_ExecutionNode s.Require().Equal(expectedResult, result) } +func (s *TransactionsFunctionalSuite) TestTransactionResultByIndex_ExecutionNode_Errors() { + s.T().Run("failed to get events from EN", func(t *testing.T) { + blockID := s.tf.Block.ID() + env := systemcontracts.SystemContractsForChain(s.g.ChainID()).AsTemplateEnv() + pendingExecuteEventType := blueprints.PendingExecutionEventType(env) + + eventsExpectedErr := status.Error( + codes.Unavailable, + "there are no available nodes", + ) + s.setupExecutionGetEventsRequestFailed(blockID, pendingExecuteEventType, eventsExpectedErr) + + params := s.defaultExecutionNodeParams() + txBackend, err := NewTransactionsBackend(params) + s.Require().NoError(err) + + expectedErr := fmt.Errorf("failed to get process transactions events: rpc error: code = Unavailable desc = failed to retrieve result from any execution node: 1 error occurred:\n\t* %w\n\n", eventsExpectedErr) + index := uint32(20) // case when user transactions is not within the guarantees + result, err := txBackend.GetTransactionResultByIndex(context.Background(), blockID, index, entities.EventEncodingVersion_JSON_CDC_V0) + s.Require().Error(err) + s.Require().Nil(result) + + s.Require().Equal(codes.Unavailable, status.Code(err)) + s.Require().Equal(expectedErr.Error(), err.Error()) + }) +} + func (s *TransactionsFunctionalSuite) TestTransactionResultsByBlockID_ExecutionNode() { blockID := s.tf.Block.ID() expectedResults := make([]*accessmodel.TransactionResult, len(s.tf.ExpectedResults)) - nodeResults := make([]*execution.GetTransactionResultResponse, len(s.tf.ExpectedResults)) + nodeResults := make([]*execproto.GetTransactionResultResponse, len(s.tf.ExpectedResults)) for i := range s.tf.ExpectedResults { accessResponse := convert.TransactionResultToMessage(s.expectedResultForIndex(i, entities.EventEncodingVersion_CCF_V0)) - nodeResults[i] = &execution.GetTransactionResultResponse{ - StatusCode: accessResponse.StatusCode, - ErrorMessage: accessResponse.ErrorMessage, - Events: accessResponse.Events, + nodeResults[i] = &execproto.GetTransactionResultResponse{ + StatusCode: accessResponse.StatusCode, + ErrorMessage: accessResponse.ErrorMessage, + Events: accessResponse.Events, + ComputationUsage: accessResponse.ComputationUsage, } expectedResults[i] = s.expectedResultForIndex(i, entities.EventEncodingVersion_JSON_CDC_V0) } - nodeResponse := &execution.GetTransactionResultsResponse{ + nodeResponse := &execproto.GetTransactionResultsResponse{ TransactionResults: nodeResults, EventEncodingVersion: entities.EventEncodingVersion_CCF_V0, } @@ -697,7 +728,7 @@ func (s *TransactionsFunctionalSuite) TestTransactionsByBlockID_ExecutionNode() versionedSystemCollection := systemcollection.Default(s.g.ChainID()) systemCollection, err := versionedSystemCollection. ByHeight(block.Height). - SystemCollection(s.g.ChainID().Chain(), access.StaticEventProvider(s.tf.ExpectedEvents)) + SystemCollection(s.g.ChainID().Chain(), accessmodel.StaticEventProvider(s.tf.ExpectedEvents)) s.Require().NoError(err) expectedTransactions = append(expectedTransactions, systemCollection.Transactions...) @@ -716,18 +747,20 @@ func (s *TransactionsFunctionalSuite) TestTransactionsByBlockID_ExecutionNode() } } - nodeResponse := &execution.GetEventsForBlockIDsResponse{ - Results: []*execution.GetEventsForBlockIDsResponse_Result{{ - BlockId: blockID[:], - BlockHeight: block.Height, - Events: events, - }}, + nodeResponse := &execproto.GetEventsForBlockIDsResponse{ + Results: []*execproto.GetEventsForBlockIDsResponse_Result{ + { + BlockId: blockID[:], + BlockHeight: block.Height, + Events: events, + }, + }, EventEncodingVersion: entities.EventEncodingVersion_CCF_V0, } s.execClient. On("GetEventsForBlockIDs", mock.Anything, expectedRequest). - Return(nodeResponse, nil) + Return(nodeResponse, nil).Once() params := s.defaultExecutionNodeParams() txBackend, err := NewTransactionsBackend(params) @@ -738,6 +771,32 @@ func (s *TransactionsFunctionalSuite) TestTransactionsByBlockID_ExecutionNode() s.Require().Equal(expectedTransactions, results) } +func (s *TransactionsFunctionalSuite) TestTransactionsByBlockID_ExecutionNode_Errors() { + s.T().Run("failed to get events from EN", func(t *testing.T) { + blockID := s.tf.Block.ID() + env := systemcontracts.SystemContractsForChain(s.g.ChainID()).AsTemplateEnv() + pendingExecuteEventType := blueprints.PendingExecutionEventType(env) + + eventsExpectedErr := status.Error( + codes.Unavailable, + "there are no available nodes", + ) + s.setupExecutionGetEventsRequestFailed(blockID, pendingExecuteEventType, eventsExpectedErr) + + params := s.defaultExecutionNodeParams() + txBackend, err := NewTransactionsBackend(params) + s.Require().NoError(err) + + expectedErr := fmt.Errorf("failed to get process transactions events: rpc error: code = Unavailable desc = failed to retrieve result from any execution node: 1 error occurred:\n\t* %w\n\n", eventsExpectedErr) + results, err := txBackend.GetTransactionsByBlockID(context.Background(), blockID) + s.Require().Error(err) + s.Require().Nil(results) + + s.Require().Equal(codes.Unavailable, status.Code(err)) + s.Require().Equal(expectedErr.Error(), err.Error()) + }) +} + func (s *TransactionsFunctionalSuite) TestScheduledTransactionsByBlockID_ExecutionNode() { block := s.tf.Block blockID := block.ID() @@ -745,30 +804,13 @@ func (s *TransactionsFunctionalSuite) TestScheduledTransactionsByBlockID_Executi env := systemcontracts.SystemContractsForChain(s.g.ChainID()).AsTemplateEnv() pendingExecuteEventType := blueprints.PendingExecutionEventType(env) - expectedRequest := &execproto.GetEventsForBlockIDsRequest{ - Type: string(pendingExecuteEventType), - BlockIds: [][]byte{blockID[:]}, - } - - events := make([]*entities.Event, 0) + events := make([]flow.Event, 0) for _, event := range s.tf.ExpectedEvents { if blueprints.IsPendingExecutionEvent(env, event) { - events = append(events, convert.EventToMessage(event)) + events = append(events, event) } } - - nodeResponse := &execution.GetEventsForBlockIDsResponse{ - Results: []*execution.GetEventsForBlockIDsResponse_Result{{ - BlockId: blockID[:], - BlockHeight: block.Height, - Events: events, - }}, - EventEncodingVersion: entities.EventEncodingVersion_CCF_V0, - } - - s.execClient. - On("GetEventsForBlockIDs", mock.Anything, expectedRequest). - Return(nodeResponse, nil) + s.setupExecutionGetEventsRequest(blockID, pendingExecuteEventType, block.Height, events) params := s.defaultExecutionNodeParams() txBackend, err := NewTransactionsBackend(params) @@ -785,3 +827,72 @@ func (s *TransactionsFunctionalSuite) TestScheduledTransactionsByBlockID_Executi break // call for the first scheduled transaction iterated } } + +func (s *TransactionsFunctionalSuite) TestScheduledTransactionsByBlockID_ExecutionNode_Errors() { + s.T().Run("failed to get events from EN", func(t *testing.T) { + block := s.tf.Block + blockID := block.ID() + env := systemcontracts.SystemContractsForChain(s.g.ChainID()).AsTemplateEnv() + pendingExecuteEventType := blueprints.PendingExecutionEventType(env) + + eventsExpectedErr := status.Error( + codes.Unavailable, + "there are no available nodes", + ) + s.setupExecutionGetEventsRequestFailed(blockID, pendingExecuteEventType, eventsExpectedErr) + + params := s.defaultExecutionNodeParams() + txBackend, err := NewTransactionsBackend(params) + s.Require().NoError(err) + + expectedErr := fmt.Errorf("rpc error: code = Unavailable desc = failed to retrieve result from any execution node: 1 error occurred:\n\t* %w\n\n", eventsExpectedErr) + for _, scheduledTxID := range s.tf.ExpectedScheduledTransactions { + results, err := txBackend.GetScheduledTransaction(context.Background(), scheduledTxID) + s.Require().Error(err) + s.Require().Nil(results) + + s.Require().Equal(codes.Unavailable, status.Code(err)) + s.Require().Equal(expectedErr.Error(), err.Error()) + + break // call for the first scheduled transaction iterated + } + }) +} + +func (s *TransactionsFunctionalSuite) setupExecutionGetEventsRequest(blockID flow.Identifier, eventType flow.EventType, blockHeight uint64, events []flow.Event) { + eventMessages := make([]*entities.Event, len(events)) + for i, event := range events { + eventMessages[i] = convert.EventToMessage(event) + } + + request := &execproto.GetEventsForBlockIDsRequest{ + Type: string(eventType), + BlockIds: [][]byte{blockID[:]}, + } + expectedResponse := &execproto.GetEventsForBlockIDsResponse{ + Results: []*execproto.GetEventsForBlockIDsResponse_Result{ + { + BlockId: blockID[:], + BlockHeight: blockHeight, + Events: eventMessages, + }, + }, + EventEncodingVersion: entities.EventEncodingVersion_CCF_V0, + } + + s.execClient. + On("GetEventsForBlockIDs", mock.Anything, request). + Return(expectedResponse, nil). + Once() +} + +func (s *TransactionsFunctionalSuite) setupExecutionGetEventsRequestFailed(blockID flow.Identifier, eventType flow.EventType, expectedErr error) { + expectedRequest := &execproto.GetEventsForBlockIDsRequest{ + Type: string(eventType), + BlockIds: [][]byte{blockID[:]}, + } + + s.execClient. + On("GetEventsForBlockIDs", mock.Anything, expectedRequest). + Return(nil, expectedErr).Once() +} diff --git a/engine/access/rpc/backend/transactions/transactions_test.go b/engine/access/rpc/backend/transactions/transactions_test.go index 0d3edc7d3ed..60bae6de05d 100644 --- a/engine/access/rpc/backend/transactions/transactions_test.go +++ b/engine/access/rpc/backend/transactions/transactions_test.go @@ -990,7 +990,7 @@ func (suite *Suite) TestGetTransactionResult_SubmittedTx() { suite.Require().Nil(res) }) - suite.Run("block lookup failure throws exception", func() { + suite.Run("block lookup notfound returns not found error", func() { suite.collections. On("LightByTransactionID", txID). Return(lightCollection, nil). @@ -1007,7 +1007,34 @@ func (suite *Suite) TestGetTransactionResult_SubmittedTx() { txBackend, err := NewTransactionsBackend(params) suite.Require().NoError(err) - expectedErr := fmt.Errorf("failed to find block for collection %v: %w", collectionID, storage.ErrNotFound) + ctx := irrecoverable.NewMockSignalerContext(suite.T(), context.Background()) + signalerCtx := irrecoverable.WithSignalerContext(context.Background(), ctx) + + res, err := txBackend.GetTransactionResult(signalerCtx, txID, blockID, collectionID, encodingVersion) + suite.Require().Error(err) + suite.Require().Equal(codes.NotFound, status.Code(err)) + suite.Require().Nil(res) + }) + + suite.Run("block lookup failure throws exception", func() { + suite.collections. + On("LightByTransactionID", txID). + Return(lightCollection, nil). + Once() + + blockLookupException := fmt.Errorf("collection lookup exception") + suite.blocks. + On("ByCollectionID", collectionID). + Return(nil, blockLookupException). + Once() + + params := suite.defaultTransactionsParams() + params.TxProvider = providermock.NewTransactionProvider(suite.T()) + + txBackend, err := NewTransactionsBackend(params) + suite.Require().NoError(err) + + expectedErr := fmt.Errorf("failed to find block for collection %v: %w", collectionID, blockLookupException) ctx := irrecoverable.NewMockSignalerContextExpectError(suite.T(), context.Background(), expectedErr) signalerCtx := irrecoverable.WithSignalerContext(context.Background(), ctx) diff --git a/engine/access/rpc/connection/cache_test.go b/engine/access/rpc/connection/cache_test.go index a54187307b8..37470f14180 100644 --- a/engine/access/rpc/connection/cache_test.go +++ b/engine/access/rpc/connection/cache_test.go @@ -159,35 +159,49 @@ func TestConcurrentConnectionsAndDisconnects(t *testing.T) { assert.Equal(t, int32(1), callCount.Load()) }) + // Test that connections and invalidations work correctly under concurrent load. + // Invalidation is done between batches (not concurrently with AddRequest) to avoid + // a known WaitGroup race between AddRequest and Close in CachedClient. + // The production code fix is tracked in https://github.com/onflow/flow-go/pull/7859 t.Run("test rapid connections and invalidations", func(t *testing.T) { - wg := sync.WaitGroup{} - wg.Add(connectionCount) callCount := atomic.NewInt32(0) - for i := 0; i < connectionCount; i++ { - go func() { - defer wg.Done() - cachedConn, err := cache.GetConnected("foo", cfg, nil, func(string, Config, crypto.PublicKey, *CachedClient) (*grpc.ClientConn, error) { - callCount.Inc() - return conn, nil - }) - require.NoError(t, err) + connectFn := func(string, Config, crypto.PublicKey, *CachedClient) (*grpc.ClientConn, error) { + callCount.Inc() + return conn, nil + } - done := cachedConn.AddRequest() - time.Sleep(1 * time.Millisecond) - cachedConn.Invalidate() - done() - }() + batchSize := 1000 + numBatches := 100 + + for batch := 0; batch < numBatches; batch++ { + wg := sync.WaitGroup{} + wg.Add(batchSize) + for i := 0; i < batchSize; i++ { + go func() { + defer wg.Done() + cachedConn, err := cache.GetConnected("foo", cfg, nil, connectFn) + require.NoError(t, err) + + done := cachedConn.AddRequest() + time.Sleep(1 * time.Millisecond) + done() + }() + } + wg.Wait() + + // Invalidate after all requests in this batch complete. + // Safe: no concurrent AddRequest on this client at this point. + cache.invalidate("foo") } - wg.Wait() // since all connections are invalidated, the cache should be empty at the end require.Eventually(t, func() bool { return cache.Len() == 0 }, time.Second, 20*time.Millisecond, "cache should be empty") - // Many connections should be created, but some will be shared + // Multiple connections should be created due to invalidation between batches assert.Greater(t, callCount.Load(), int32(1)) - assert.LessOrEqual(t, callCount.Load(), int32(connectionCount)) + assert.LessOrEqual(t, callCount.Load(), int32(numBatches*batchSize)) }) } diff --git a/engine/access/rpc/connection/connection_test.go b/engine/access/rpc/connection/connection_test.go index 1e4488c109d..4533e469c54 100644 --- a/engine/access/rpc/connection/connection_test.go +++ b/engine/access/rpc/connection/connection_test.go @@ -6,6 +6,8 @@ import ( "fmt" "math/big" "net" + "strconv" + "strings" "sync" "testing" "time" @@ -24,6 +26,7 @@ import ( "google.golang.org/grpc/status" "pgregory.net/rapid" + "github.com/onflow/flow-go/engine/access/mock" "github.com/onflow/flow-go/module/metrics" "github.com/onflow/flow-go/utils/grpcutils" "github.com/onflow/flow-go/utils/unittest" @@ -711,7 +714,7 @@ func TestEvictingCacheClients(t *testing.T) { // Invalidate marks the connection for closure asynchronously, so give it some time to run require.Eventually(t, func() bool { - return cachedClient.closeRequested.Load() + return cachedClient.CloseRequested() }, 100*time.Millisecond, 10*time.Millisecond, "client timed out closing connection") // Call a gRPC method on the client, requests should be blocked since the connection is invalidated @@ -1081,3 +1084,95 @@ func TestCircuitBreakerCollectionNode(t *testing.T) { }) } } + +// node mocks a flow node that runs a GRPC server +type node struct { + server *grpc.Server + listener net.Listener + port uint +} + +func (n *node) setupNode(tb testing.TB) { + n.server = grpc.NewServer() + listener, err := net.Listen("tcp4", unittest.DefaultAddress) + assert.NoError(tb, err) + n.listener = listener + assert.Eventually(tb, func() bool { + return !strings.HasSuffix(listener.Addr().String(), ":0") + }, time.Second*4, 10*time.Millisecond) + + _, port, err := net.SplitHostPort(listener.Addr().String()) + assert.NoError(tb, err) + portAsUint, err := strconv.ParseUint(port, 10, 32) + assert.NoError(tb, err) + n.port = uint(portAsUint) +} + +func (n *node) start(tb testing.TB) { + // using a wait group here to ensure the goroutine has started before returning. Otherwise, + // there's a race condition where the server is sometimes stopped before it has started + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + wg.Done() + err := n.server.Serve(n.listener) + assert.NoError(tb, err) + }() + unittest.RequireReturnsBefore(tb, wg.Wait, 10*time.Millisecond, "could not start goroutine on time") +} + +func (n *node) stop(tb testing.TB) { + if n.server != nil { + n.server.Stop() + } +} + +type executionNode struct { + node + handler *mock.ExecutionAPIServer +} + +func newExecutionNode(tb testing.TB) *executionNode { + return &executionNode{ + handler: mock.NewExecutionAPIServer(tb), + } +} + +func (en *executionNode) start(tb testing.TB) { + if en.handler == nil { + tb.Fatalf("executionNode must be initialized using newExecutionNode") + } + + en.setupNode(tb) + execution.RegisterExecutionAPIServer(en.server, en.handler) + en.node.start(tb) +} + +func (en *executionNode) stop(tb testing.TB) { + en.node.stop(tb) +} + +type collectionNode struct { + node + handler *mock.AccessAPIServer +} + +func newCollectionNode(tb testing.TB) *collectionNode { + return &collectionNode{ + handler: mock.NewAccessAPIServer(tb), + } +} + +func (cn *collectionNode) start(tb testing.TB) { + if cn.handler == nil { + tb.Fatalf("collectionNode must be initialized using newCollectionNode") + } + + cn.setupNode(tb) + access.RegisterAccessAPIServer(cn.server, cn.handler) + cn.node.start(tb) +} + +func (cn *collectionNode) stop(tb testing.TB) { + cn.node.stop(tb) +} diff --git a/engine/access/rpc/connection/mock/connection_factory.go b/engine/access/rpc/connection/mock/connection_factory.go index c7120b1f5de..56b9b18602d 100644 --- a/engine/access/rpc/connection/mock/connection_factory.go +++ b/engine/access/rpc/connection/mock/connection_factory.go @@ -1,27 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - access "github.com/onflow/flow/protobuf/go/flow/access" + "io" - crypto "github.com/onflow/crypto" + "github.com/onflow/crypto" + "github.com/onflow/flow/protobuf/go/flow/access" + "github.com/onflow/flow/protobuf/go/flow/execution" + mock "github.com/stretchr/testify/mock" +) - execution "github.com/onflow/flow/protobuf/go/flow/execution" +// NewConnectionFactory creates a new instance of ConnectionFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConnectionFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *ConnectionFactory { + mock := &ConnectionFactory{} + mock.Mock.Test(t) - io "io" + t.Cleanup(func() { mock.AssertExpectations(t) }) - mock "github.com/stretchr/testify/mock" -) + return mock +} // ConnectionFactory is an autogenerated mock type for the ConnectionFactory type type ConnectionFactory struct { mock.Mock } -// GetAccessAPIClientWithPort provides a mock function with given fields: address, networkPubKey -func (_m *ConnectionFactory) GetAccessAPIClientWithPort(address string, networkPubKey crypto.PublicKey) (access.AccessAPIClient, io.Closer, error) { - ret := _m.Called(address, networkPubKey) +type ConnectionFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *ConnectionFactory) EXPECT() *ConnectionFactory_Expecter { + return &ConnectionFactory_Expecter{mock: &_m.Mock} +} + +// GetAccessAPIClientWithPort provides a mock function for the type ConnectionFactory +func (_mock *ConnectionFactory) GetAccessAPIClientWithPort(address string, networkPubKey crypto.PublicKey) (access.AccessAPIClient, io.Closer, error) { + ret := _mock.Called(address, networkPubKey) if len(ret) == 0 { panic("no return value specified for GetAccessAPIClientWithPort") @@ -30,37 +51,74 @@ func (_m *ConnectionFactory) GetAccessAPIClientWithPort(address string, networkP var r0 access.AccessAPIClient var r1 io.Closer var r2 error - if rf, ok := ret.Get(0).(func(string, crypto.PublicKey) (access.AccessAPIClient, io.Closer, error)); ok { - return rf(address, networkPubKey) + if returnFunc, ok := ret.Get(0).(func(string, crypto.PublicKey) (access.AccessAPIClient, io.Closer, error)); ok { + return returnFunc(address, networkPubKey) } - if rf, ok := ret.Get(0).(func(string, crypto.PublicKey) access.AccessAPIClient); ok { - r0 = rf(address, networkPubKey) + if returnFunc, ok := ret.Get(0).(func(string, crypto.PublicKey) access.AccessAPIClient); ok { + r0 = returnFunc(address, networkPubKey) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPIClient) } } - - if rf, ok := ret.Get(1).(func(string, crypto.PublicKey) io.Closer); ok { - r1 = rf(address, networkPubKey) + if returnFunc, ok := ret.Get(1).(func(string, crypto.PublicKey) io.Closer); ok { + r1 = returnFunc(address, networkPubKey) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(io.Closer) } } - - if rf, ok := ret.Get(2).(func(string, crypto.PublicKey) error); ok { - r2 = rf(address, networkPubKey) + if returnFunc, ok := ret.Get(2).(func(string, crypto.PublicKey) error); ok { + r2 = returnFunc(address, networkPubKey) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetCollectionAPIClient provides a mock function with given fields: address, networkPubKey -func (_m *ConnectionFactory) GetCollectionAPIClient(address string, networkPubKey crypto.PublicKey) (access.AccessAPIClient, io.Closer, error) { - ret := _m.Called(address, networkPubKey) +// ConnectionFactory_GetAccessAPIClientWithPort_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccessAPIClientWithPort' +type ConnectionFactory_GetAccessAPIClientWithPort_Call struct { + *mock.Call +} + +// GetAccessAPIClientWithPort is a helper method to define mock.On call +// - address string +// - networkPubKey crypto.PublicKey +func (_e *ConnectionFactory_Expecter) GetAccessAPIClientWithPort(address interface{}, networkPubKey interface{}) *ConnectionFactory_GetAccessAPIClientWithPort_Call { + return &ConnectionFactory_GetAccessAPIClientWithPort_Call{Call: _e.mock.On("GetAccessAPIClientWithPort", address, networkPubKey)} +} + +func (_c *ConnectionFactory_GetAccessAPIClientWithPort_Call) Run(run func(address string, networkPubKey crypto.PublicKey)) *ConnectionFactory_GetAccessAPIClientWithPort_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 crypto.PublicKey + if args[1] != nil { + arg1 = args[1].(crypto.PublicKey) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ConnectionFactory_GetAccessAPIClientWithPort_Call) Return(accessAPIClient access.AccessAPIClient, closer io.Closer, err error) *ConnectionFactory_GetAccessAPIClientWithPort_Call { + _c.Call.Return(accessAPIClient, closer, err) + return _c +} + +func (_c *ConnectionFactory_GetAccessAPIClientWithPort_Call) RunAndReturn(run func(address string, networkPubKey crypto.PublicKey) (access.AccessAPIClient, io.Closer, error)) *ConnectionFactory_GetAccessAPIClientWithPort_Call { + _c.Call.Return(run) + return _c +} + +// GetCollectionAPIClient provides a mock function for the type ConnectionFactory +func (_mock *ConnectionFactory) GetCollectionAPIClient(address string, networkPubKey crypto.PublicKey) (access.AccessAPIClient, io.Closer, error) { + ret := _mock.Called(address, networkPubKey) if len(ret) == 0 { panic("no return value specified for GetCollectionAPIClient") @@ -69,37 +127,74 @@ func (_m *ConnectionFactory) GetCollectionAPIClient(address string, networkPubKe var r0 access.AccessAPIClient var r1 io.Closer var r2 error - if rf, ok := ret.Get(0).(func(string, crypto.PublicKey) (access.AccessAPIClient, io.Closer, error)); ok { - return rf(address, networkPubKey) + if returnFunc, ok := ret.Get(0).(func(string, crypto.PublicKey) (access.AccessAPIClient, io.Closer, error)); ok { + return returnFunc(address, networkPubKey) } - if rf, ok := ret.Get(0).(func(string, crypto.PublicKey) access.AccessAPIClient); ok { - r0 = rf(address, networkPubKey) + if returnFunc, ok := ret.Get(0).(func(string, crypto.PublicKey) access.AccessAPIClient); ok { + r0 = returnFunc(address, networkPubKey) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(access.AccessAPIClient) } } - - if rf, ok := ret.Get(1).(func(string, crypto.PublicKey) io.Closer); ok { - r1 = rf(address, networkPubKey) + if returnFunc, ok := ret.Get(1).(func(string, crypto.PublicKey) io.Closer); ok { + r1 = returnFunc(address, networkPubKey) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(io.Closer) } } - - if rf, ok := ret.Get(2).(func(string, crypto.PublicKey) error); ok { - r2 = rf(address, networkPubKey) + if returnFunc, ok := ret.Get(2).(func(string, crypto.PublicKey) error); ok { + r2 = returnFunc(address, networkPubKey) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetExecutionAPIClient provides a mock function with given fields: address -func (_m *ConnectionFactory) GetExecutionAPIClient(address string) (execution.ExecutionAPIClient, io.Closer, error) { - ret := _m.Called(address) +// ConnectionFactory_GetCollectionAPIClient_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCollectionAPIClient' +type ConnectionFactory_GetCollectionAPIClient_Call struct { + *mock.Call +} + +// GetCollectionAPIClient is a helper method to define mock.On call +// - address string +// - networkPubKey crypto.PublicKey +func (_e *ConnectionFactory_Expecter) GetCollectionAPIClient(address interface{}, networkPubKey interface{}) *ConnectionFactory_GetCollectionAPIClient_Call { + return &ConnectionFactory_GetCollectionAPIClient_Call{Call: _e.mock.On("GetCollectionAPIClient", address, networkPubKey)} +} + +func (_c *ConnectionFactory_GetCollectionAPIClient_Call) Run(run func(address string, networkPubKey crypto.PublicKey)) *ConnectionFactory_GetCollectionAPIClient_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 crypto.PublicKey + if args[1] != nil { + arg1 = args[1].(crypto.PublicKey) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ConnectionFactory_GetCollectionAPIClient_Call) Return(accessAPIClient access.AccessAPIClient, closer io.Closer, err error) *ConnectionFactory_GetCollectionAPIClient_Call { + _c.Call.Return(accessAPIClient, closer, err) + return _c +} + +func (_c *ConnectionFactory_GetCollectionAPIClient_Call) RunAndReturn(run func(address string, networkPubKey crypto.PublicKey) (access.AccessAPIClient, io.Closer, error)) *ConnectionFactory_GetCollectionAPIClient_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionAPIClient provides a mock function for the type ConnectionFactory +func (_mock *ConnectionFactory) GetExecutionAPIClient(address string) (execution.ExecutionAPIClient, io.Closer, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GetExecutionAPIClient") @@ -108,44 +203,61 @@ func (_m *ConnectionFactory) GetExecutionAPIClient(address string) (execution.Ex var r0 execution.ExecutionAPIClient var r1 io.Closer var r2 error - if rf, ok := ret.Get(0).(func(string) (execution.ExecutionAPIClient, io.Closer, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(string) (execution.ExecutionAPIClient, io.Closer, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(string) execution.ExecutionAPIClient); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(string) execution.ExecutionAPIClient); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(execution.ExecutionAPIClient) } } - - if rf, ok := ret.Get(1).(func(string) io.Closer); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(string) io.Closer); ok { + r1 = returnFunc(address) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(io.Closer) } } - - if rf, ok := ret.Get(2).(func(string) error); ok { - r2 = rf(address) + if returnFunc, ok := ret.Get(2).(func(string) error); ok { + r2 = returnFunc(address) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewConnectionFactory creates a new instance of ConnectionFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConnectionFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *ConnectionFactory { - mock := &ConnectionFactory{} - mock.Mock.Test(t) +// ConnectionFactory_GetExecutionAPIClient_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionAPIClient' +type ConnectionFactory_GetExecutionAPIClient_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetExecutionAPIClient is a helper method to define mock.On call +// - address string +func (_e *ConnectionFactory_Expecter) GetExecutionAPIClient(address interface{}) *ConnectionFactory_GetExecutionAPIClient_Call { + return &ConnectionFactory_GetExecutionAPIClient_Call{Call: _e.mock.On("GetExecutionAPIClient", address)} +} - return mock +func (_c *ConnectionFactory_GetExecutionAPIClient_Call) Run(run func(address string)) *ConnectionFactory_GetExecutionAPIClient_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectionFactory_GetExecutionAPIClient_Call) Return(executionAPIClient execution.ExecutionAPIClient, closer io.Closer, err error) *ConnectionFactory_GetExecutionAPIClient_Call { + _c.Call.Return(executionAPIClient, closer, err) + return _c +} + +func (_c *ConnectionFactory_GetExecutionAPIClient_Call) RunAndReturn(run func(address string) (execution.ExecutionAPIClient, io.Closer, error)) *ConnectionFactory_GetExecutionAPIClient_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/rpc/connection/node_mock.go b/engine/access/rpc/connection/node_mock.go deleted file mode 100644 index af613f4ffc8..00000000000 --- a/engine/access/rpc/connection/node_mock.go +++ /dev/null @@ -1,110 +0,0 @@ -package connection - -import ( - "net" - "strconv" - "strings" - "sync" - "testing" - "time" - - "github.com/onflow/flow/protobuf/go/flow/access" - "github.com/onflow/flow/protobuf/go/flow/execution" - "github.com/stretchr/testify/assert" - "google.golang.org/grpc" - - "github.com/onflow/flow-go/engine/access/mock" - "github.com/onflow/flow-go/utils/unittest" -) - -// node mocks a flow node that runs a GRPC server -type node struct { - server *grpc.Server - listener net.Listener - port uint -} - -func (n *node) setupNode(tb testing.TB) { - n.server = grpc.NewServer() - listener, err := net.Listen("tcp4", unittest.DefaultAddress) - assert.NoError(tb, err) - n.listener = listener - assert.Eventually(tb, func() bool { - return !strings.HasSuffix(listener.Addr().String(), ":0") - }, time.Second*4, 10*time.Millisecond) - - _, port, err := net.SplitHostPort(listener.Addr().String()) - assert.NoError(tb, err) - portAsUint, err := strconv.ParseUint(port, 10, 32) - assert.NoError(tb, err) - n.port = uint(portAsUint) -} - -func (n *node) start(tb testing.TB) { - // using a wait group here to ensure the goroutine has started before returning. Otherwise, - // there's a race condition where the server is sometimes stopped before it has started - wg := sync.WaitGroup{} - wg.Add(1) - go func() { - wg.Done() - err := n.server.Serve(n.listener) - assert.NoError(tb, err) - }() - unittest.RequireReturnsBefore(tb, wg.Wait, 10*time.Millisecond, "could not start goroutine on time") -} - -func (n *node) stop(tb testing.TB) { - if n.server != nil { - n.server.Stop() - } -} - -type executionNode struct { - node - handler *mock.ExecutionAPIServer -} - -func newExecutionNode(tb testing.TB) *executionNode { - return &executionNode{ - handler: mock.NewExecutionAPIServer(tb), - } -} - -func (en *executionNode) start(tb testing.TB) { - if en.handler == nil { - tb.Fatalf("executionNode must be initialized using newExecutionNode") - } - - en.setupNode(tb) - execution.RegisterExecutionAPIServer(en.server, en.handler) - en.node.start(tb) -} - -func (en *executionNode) stop(tb testing.TB) { - en.node.stop(tb) -} - -type collectionNode struct { - node - handler *mock.AccessAPIServer -} - -func newCollectionNode(tb testing.TB) *collectionNode { - return &collectionNode{ - handler: mock.NewAccessAPIServer(tb), - } -} - -func (cn *collectionNode) start(tb testing.TB) { - if cn.handler == nil { - tb.Fatalf("collectionNode must be initialized using newCollectionNode") - } - - cn.setupNode(tb) - access.RegisterAccessAPIServer(cn.server, cn.handler) - cn.node.start(tb) -} - -func (cn *collectionNode) stop(tb testing.TB) { - cn.node.stop(tb) -} diff --git a/engine/access/rpc/engine.go b/engine/access/rpc/engine.go index fad6183a457..934ea54d093 100644 --- a/engine/access/rpc/engine.go +++ b/engine/access/rpc/engine.go @@ -12,6 +12,7 @@ import ( "google.golang.org/grpc/credentials" "github.com/onflow/flow-go/access" + "github.com/onflow/flow-go/access/backends/extended" "github.com/onflow/flow-go/consensus/hotstuff" "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/engine/access/rest" @@ -25,6 +26,7 @@ import ( "github.com/onflow/flow-go/module/events" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/state_synchronization" "github.com/onflow/flow-go/state/protocol" ) @@ -71,13 +73,15 @@ type Engine struct { config Config chain flow.Chain - restHandler access.API + restHandler access.API + extendedBackend extended.API addrLock sync.RWMutex restAPIAddress net.Addr stateStreamBackend state_stream.API stateStreamConfig statestreambackend.Config + limiter *limiters.ConcurrencyLimiter } type Option func(*RPCEngineBuilder) @@ -98,6 +102,8 @@ func NewBuilder( stateStreamConfig statestreambackend.Config, indexReporter state_synchronization.IndexReporter, finalizationRegistrar hotstuff.FinalizationRegistrar, + extendedBackend extended.API, + limiter *limiters.ConcurrencyLimiter, ) (*RPCEngineBuilder, error) { log = log.With().Str("engine", "rpc").Logger() @@ -121,8 +127,10 @@ func NewBuilder( chain: chainID.Chain(), restCollector: accessMetrics, restHandler: restHandler, + extendedBackend: extendedBackend, stateStreamBackend: stateStreamBackend, stateStreamConfig: stateStreamConfig, + limiter: limiter, } backendNotifierActor, backendNotifierWorker := events.NewFinalizationActor(eng.processOnFinalizedBlock) eng.backendNotifierActor = backendNotifierActor @@ -253,6 +261,8 @@ func (e *Engine) serveREST(ctx irrecoverable.SignalerContext, ready component.Re e.stateStreamConfig, e.config.EnableWebSocketsStreamAPI, e.config.WebSocketConfig, + e.extendedBackend, + e.limiter, ) if err != nil { e.log.Err(err).Msg("failed to initialize the REST server") diff --git a/engine/access/rpc/engine_builder.go b/engine/access/rpc/engine_builder.go index 88dec3aac96..8d3fe5a3cfa 100644 --- a/engine/access/rpc/engine_builder.go +++ b/engine/access/rpc/engine_builder.go @@ -81,9 +81,9 @@ func (builder *RPCEngineBuilder) WithLegacy() *RPCEngineBuilder { func (builder *RPCEngineBuilder) DefaultHandler(signerIndicesDecoder hotstuff.BlockSignerDecoder) *Handler { if signerIndicesDecoder == nil { - return NewHandler(builder.Engine.backend, builder.Engine.chain, builder.finalizedHeaderCache, builder.me, builder.stateStreamConfig.MaxGlobalStreams, WithIndexReporter(builder.indexReporter)) + return NewHandler(builder.Engine.backend, builder.Engine.chain, builder.finalizedHeaderCache, builder.me, builder.Engine.limiter, WithIndexReporter(builder.indexReporter)) } else { - return NewHandler(builder.Engine.backend, builder.Engine.chain, builder.finalizedHeaderCache, builder.me, builder.stateStreamConfig.MaxGlobalStreams, WithBlockSignerDecoder(signerIndicesDecoder), WithIndexReporter(builder.indexReporter)) + return NewHandler(builder.Engine.backend, builder.Engine.chain, builder.finalizedHeaderCache, builder.me, builder.Engine.limiter, WithBlockSignerDecoder(signerIndicesDecoder), WithIndexReporter(builder.indexReporter)) } } diff --git a/engine/access/rpc/handler.go b/engine/access/rpc/handler.go index 485813cbb33..bcb347344db 100644 --- a/engine/access/rpc/handler.go +++ b/engine/access/rpc/handler.go @@ -21,12 +21,13 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/counters" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/state_synchronization" "github.com/onflow/flow-go/module/state_synchronization/indexer" ) type Handler struct { - subscription.StreamingData + limiter *limiters.ConcurrencyLimiter api access.API chain flow.Chain signerIndicesDecoder hotstuff.BlockSignerDecoder @@ -57,11 +58,11 @@ func NewHandler( chain flow.Chain, finalizedHeader module.FinalizedHeaderCache, me module.Local, - maxStreams uint32, + limiter *limiters.ConcurrencyLimiter, options ...HandlerOption, ) *Handler { h := &Handler{ - StreamingData: subscription.NewStreamingData(maxStreams), + limiter: limiter, api: api, chain: chain, finalizedHeaderCache: finalizedHeader, @@ -74,6 +75,19 @@ func NewHandler( return h } +// withStreamLimit executes fn within the global stream concurrency limit. +// Returns codes.ResourceExhausted if the limit is reached. +func (h *Handler) withStreamLimit(fn func() error) error { + var err error + allowed := h.limiter.Allow(func() { + err = fn() + }) + if !allowed { + return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") + } + return err +} + // Ping the Access API server for a response. func (h *Handler) Ping(ctx context.Context, _ *accessproto.PingRequest) (*accessproto.PingResponse, error) { err := h.api.Ping(ctx) @@ -1106,6 +1120,64 @@ func (h *Handler) GetExecutionResultByID(ctx context.Context, req *accessproto.G }, nil } +// GetExecutionReceiptsByBlockID returns all execution receipts for the given block ID. +// If req.IncludeResult is true, each receipt in the response includes the full ExecutionResult. +// +// Expected error returns during normal operation: +// - codes.NotFound: if no receipts are indexed for the given block ID. +func (h *Handler) GetExecutionReceiptsByBlockID(ctx context.Context, req *accessproto.GetExecutionReceiptsByBlockIDRequest) (*accessproto.ExecutionReceiptsResponse, error) { + metadata, err := h.buildMetadataResponse() + if err != nil { + return nil, err + } + + blockID := convert.MessageToIdentifier(req.GetBlockId()) + + receipts, err := h.api.GetExecutionReceiptsByBlockID(ctx, blockID) + if err != nil { + return nil, err + } + + msgs, err := convert.ExecutionReceiptsToMessages(receipts, req.GetIncludeResult()) + if err != nil { + return nil, err + } + + return &accessproto.ExecutionReceiptsResponse{ + Receipts: msgs, + Metadata: metadata, + }, nil +} + +// GetExecutionReceiptsByResultID returns all execution receipts committing to the given execution +// result ID. If req.IncludeResult is true, each receipt in the response includes the full ExecutionResult. +// +// Expected error returns during normal operation: +// - codes.NotFound: if the execution result or its block's receipts are not found. +func (h *Handler) GetExecutionReceiptsByResultID(ctx context.Context, req *accessproto.GetExecutionReceiptsByResultIDRequest) (*accessproto.ExecutionReceiptsResponse, error) { + metadata, err := h.buildMetadataResponse() + if err != nil { + return nil, err + } + + resultID := convert.MessageToIdentifier(req.GetResultId()) + + receipts, err := h.api.GetExecutionReceiptsByResultID(ctx, resultID) + if err != nil { + return nil, err + } + + msgs, err := convert.ExecutionReceiptsToMessages(receipts, req.GetIncludeResult()) + if err != nil { + return nil, err + } + + return &accessproto.ExecutionReceiptsResponse{ + Receipts: msgs, + Metadata: metadata, + }, nil +} + // SubscribeBlocksFromStartBlockID handles subscription requests for blocks started from block id. // It takes a SubscribeBlocksFromStartBlockIDRequest and an AccessAPI_SubscribeBlocksFromStartBlockIDServer stream as input. // The handler manages the subscription to block updates and sends the subscribed block information @@ -1116,20 +1188,15 @@ func (h *Handler) GetExecutionResultByID(ctx context.Context, req *accessproto.G // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block to message or could not send response. func (h *Handler) SubscribeBlocksFromStartBlockID(request *accessproto.SubscribeBlocksFromStartBlockIDRequest, stream accessproto.AccessAPI_SubscribeBlocksFromStartBlockIDServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - startBlockID, blockStatus, err := h.getSubscriptionDataFromStartBlockID(request.GetStartBlockId(), request.GetBlockStatus()) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + startBlockID, blockStatus, err := h.getSubscriptionDataFromStartBlockID(request.GetStartBlockId(), request.GetBlockStatus()) + if err != nil { + return err + } - sub := h.api.SubscribeBlocksFromStartBlockID(stream.Context(), startBlockID, blockStatus) - return HandleRPCSubscription(sub, h.handleBlocksResponse(stream.Send, request.GetFullBlockResponse(), blockStatus)) + sub := h.api.SubscribeBlocksFromStartBlockID(stream.Context(), startBlockID, blockStatus) + return HandleRPCSubscription(sub, h.handleBlocksResponse(stream.Send, request.GetFullBlockResponse(), blockStatus)) + }) } // SubscribeBlocksFromStartHeight handles subscription requests for blocks started from block height. @@ -1142,21 +1209,16 @@ func (h *Handler) SubscribeBlocksFromStartBlockID(request *accessproto.Subscribe // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block to message or could not send response. func (h *Handler) SubscribeBlocksFromStartHeight(request *accessproto.SubscribeBlocksFromStartHeightRequest, stream accessproto.AccessAPI_SubscribeBlocksFromStartHeightServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) - err := checkBlockStatus(blockStatus) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) + err := checkBlockStatus(blockStatus) + if err != nil { + return err + } - sub := h.api.SubscribeBlocksFromStartHeight(stream.Context(), request.GetStartBlockHeight(), blockStatus) - return HandleRPCSubscription(sub, h.handleBlocksResponse(stream.Send, request.GetFullBlockResponse(), blockStatus)) + sub := h.api.SubscribeBlocksFromStartHeight(stream.Context(), request.GetStartBlockHeight(), blockStatus) + return HandleRPCSubscription(sub, h.handleBlocksResponse(stream.Send, request.GetFullBlockResponse(), blockStatus)) + }) } // SubscribeBlocksFromLatest handles subscription requests for blocks started from latest sealed block. @@ -1169,21 +1231,16 @@ func (h *Handler) SubscribeBlocksFromStartHeight(request *accessproto.SubscribeB // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block to message or could not send response. func (h *Handler) SubscribeBlocksFromLatest(request *accessproto.SubscribeBlocksFromLatestRequest, stream accessproto.AccessAPI_SubscribeBlocksFromLatestServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) - err := checkBlockStatus(blockStatus) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) + err := checkBlockStatus(blockStatus) + if err != nil { + return err + } - sub := h.api.SubscribeBlocksFromLatest(stream.Context(), blockStatus) - return HandleRPCSubscription(sub, h.handleBlocksResponse(stream.Send, request.GetFullBlockResponse(), blockStatus)) + sub := h.api.SubscribeBlocksFromLatest(stream.Context(), blockStatus) + return HandleRPCSubscription(sub, h.handleBlocksResponse(stream.Send, request.GetFullBlockResponse(), blockStatus)) + }) } // handleBlocksResponse handles the subscription to block updates and sends @@ -1229,20 +1286,15 @@ func (h *Handler) handleBlocksResponse(send sendSubscribeBlocksResponseFunc, ful // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block header to message or could not send response. func (h *Handler) SubscribeBlockHeadersFromStartBlockID(request *accessproto.SubscribeBlockHeadersFromStartBlockIDRequest, stream accessproto.AccessAPI_SubscribeBlockHeadersFromStartBlockIDServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - startBlockID, blockStatus, err := h.getSubscriptionDataFromStartBlockID(request.GetStartBlockId(), request.GetBlockStatus()) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + startBlockID, blockStatus, err := h.getSubscriptionDataFromStartBlockID(request.GetStartBlockId(), request.GetBlockStatus()) + if err != nil { + return err + } - sub := h.api.SubscribeBlockHeadersFromStartBlockID(stream.Context(), startBlockID, blockStatus) - return HandleRPCSubscription(sub, h.handleBlockHeadersResponse(stream.Send)) + sub := h.api.SubscribeBlockHeadersFromStartBlockID(stream.Context(), startBlockID, blockStatus) + return HandleRPCSubscription(sub, h.handleBlockHeadersResponse(stream.Send)) + }) } // SubscribeBlockHeadersFromStartHeight handles subscription requests for block headers started from block height. @@ -1255,21 +1307,16 @@ func (h *Handler) SubscribeBlockHeadersFromStartBlockID(request *accessproto.Sub // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block header to message or could not send response. func (h *Handler) SubscribeBlockHeadersFromStartHeight(request *accessproto.SubscribeBlockHeadersFromStartHeightRequest, stream accessproto.AccessAPI_SubscribeBlockHeadersFromStartHeightServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) - err := checkBlockStatus(blockStatus) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) + err := checkBlockStatus(blockStatus) + if err != nil { + return err + } - sub := h.api.SubscribeBlockHeadersFromStartHeight(stream.Context(), request.GetStartBlockHeight(), blockStatus) - return HandleRPCSubscription(sub, h.handleBlockHeadersResponse(stream.Send)) + sub := h.api.SubscribeBlockHeadersFromStartHeight(stream.Context(), request.GetStartBlockHeight(), blockStatus) + return HandleRPCSubscription(sub, h.handleBlockHeadersResponse(stream.Send)) + }) } // SubscribeBlockHeadersFromLatest handles subscription requests for block headers started from latest sealed block. @@ -1282,21 +1329,16 @@ func (h *Handler) SubscribeBlockHeadersFromStartHeight(request *accessproto.Subs // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block header to message or could not send response. func (h *Handler) SubscribeBlockHeadersFromLatest(request *accessproto.SubscribeBlockHeadersFromLatestRequest, stream accessproto.AccessAPI_SubscribeBlockHeadersFromLatestServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) - err := checkBlockStatus(blockStatus) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) + err := checkBlockStatus(blockStatus) + if err != nil { + return err + } - sub := h.api.SubscribeBlockHeadersFromLatest(stream.Context(), blockStatus) - return HandleRPCSubscription(sub, h.handleBlockHeadersResponse(stream.Send)) + sub := h.api.SubscribeBlockHeadersFromLatest(stream.Context(), blockStatus) + return HandleRPCSubscription(sub, h.handleBlockHeadersResponse(stream.Send)) + }) } // handleBlockHeadersResponse handles the subscription to block updates and sends @@ -1343,20 +1385,15 @@ func (h *Handler) handleBlockHeadersResponse(send sendSubscribeBlockHeadersRespo // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block to message or could not send response. func (h *Handler) SubscribeBlockDigestsFromStartBlockID(request *accessproto.SubscribeBlockDigestsFromStartBlockIDRequest, stream accessproto.AccessAPI_SubscribeBlockDigestsFromStartBlockIDServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - startBlockID, blockStatus, err := h.getSubscriptionDataFromStartBlockID(request.GetStartBlockId(), request.GetBlockStatus()) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + startBlockID, blockStatus, err := h.getSubscriptionDataFromStartBlockID(request.GetStartBlockId(), request.GetBlockStatus()) + if err != nil { + return err + } - sub := h.api.SubscribeBlockDigestsFromStartBlockID(stream.Context(), startBlockID, blockStatus) - return HandleRPCSubscription(sub, h.handleBlockDigestsResponse(stream.Send)) + sub := h.api.SubscribeBlockDigestsFromStartBlockID(stream.Context(), startBlockID, blockStatus) + return HandleRPCSubscription(sub, h.handleBlockDigestsResponse(stream.Send)) + }) } // SubscribeBlockDigestsFromStartHeight handles subscription requests for lightweight blocks started from block height. @@ -1369,21 +1406,16 @@ func (h *Handler) SubscribeBlockDigestsFromStartBlockID(request *accessproto.Sub // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block to message or could not send response. func (h *Handler) SubscribeBlockDigestsFromStartHeight(request *accessproto.SubscribeBlockDigestsFromStartHeightRequest, stream accessproto.AccessAPI_SubscribeBlockDigestsFromStartHeightServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) - err := checkBlockStatus(blockStatus) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) + err := checkBlockStatus(blockStatus) + if err != nil { + return err + } - sub := h.api.SubscribeBlockDigestsFromStartHeight(stream.Context(), request.GetStartBlockHeight(), blockStatus) - return HandleRPCSubscription(sub, h.handleBlockDigestsResponse(stream.Send)) + sub := h.api.SubscribeBlockDigestsFromStartHeight(stream.Context(), request.GetStartBlockHeight(), blockStatus) + return HandleRPCSubscription(sub, h.handleBlockDigestsResponse(stream.Send)) + }) } // SubscribeBlockDigestsFromLatest handles subscription requests for lightweight block started from latest sealed block. @@ -1396,21 +1428,16 @@ func (h *Handler) SubscribeBlockDigestsFromStartHeight(request *accessproto.Subs // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream encountered an error, if stream got unexpected response or could not convert block to message or could not send response. func (h *Handler) SubscribeBlockDigestsFromLatest(request *accessproto.SubscribeBlockDigestsFromLatestRequest, stream accessproto.AccessAPI_SubscribeBlockDigestsFromLatestServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) - err := checkBlockStatus(blockStatus) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + blockStatus := convert.MessageToBlockStatus(request.GetBlockStatus()) + err := checkBlockStatus(blockStatus) + if err != nil { + return err + } - sub := h.api.SubscribeBlockDigestsFromLatest(stream.Context(), blockStatus) - return HandleRPCSubscription(sub, h.handleBlockDigestsResponse(stream.Send)) + sub := h.api.SubscribeBlockDigestsFromLatest(stream.Context(), blockStatus) + return HandleRPCSubscription(sub, h.handleBlockDigestsResponse(stream.Send)) + }) } // handleBlockDigestsResponse handles the subscription to block updates and sends @@ -1474,41 +1501,36 @@ func (h *Handler) SendAndSubscribeTransactionStatuses( request *accessproto.SendAndSubscribeTransactionStatusesRequest, stream accessproto.AccessAPI_SendAndSubscribeTransactionStatusesServer, ) error { - ctx := stream.Context() + return h.withStreamLimit(func() error { + ctx := stream.Context() - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) + tx, err := convert.MessageToTransaction(request.GetTransaction(), h.chain) + if err != nil { + return status.Error(codes.InvalidArgument, err.Error()) + } - tx, err := convert.MessageToTransaction(request.GetTransaction(), h.chain) - if err != nil { - return status.Error(codes.InvalidArgument, err.Error()) - } + sub := h.api.SendAndSubscribeTransactionStatuses(ctx, &tx, request.GetEventEncodingVersion()) - sub := h.api.SendAndSubscribeTransactionStatuses(ctx, &tx, request.GetEventEncodingVersion()) + messageIndex := counters.NewMonotonicCounter(0) + return HandleRPCSubscription(sub, func(txResults []*accessmodel.TransactionResult) error { + for i := range txResults { + index := messageIndex.Value() + if ok := messageIndex.Set(index + 1); !ok { + return status.Errorf(codes.Internal, "message index already incremented to %d", messageIndex.Value()) + } - messageIndex := counters.NewMonotonicCounter(0) - return HandleRPCSubscription(sub, func(txResults []*accessmodel.TransactionResult) error { - for i := range txResults { - index := messageIndex.Value() - if ok := messageIndex.Set(index + 1); !ok { - return status.Errorf(codes.Internal, "message index already incremented to %d", messageIndex.Value()) - } + err = stream.Send(&accessproto.SendAndSubscribeTransactionStatusesResponse{ + TransactionResults: convert.TransactionResultToMessage(txResults[i]), + MessageIndex: index, + }) + if err != nil { + return rpc.ConvertError(err, "could not send response", codes.Internal) + } - err = stream.Send(&accessproto.SendAndSubscribeTransactionStatusesResponse{ - TransactionResults: convert.TransactionResultToMessage(txResults[i]), - MessageIndex: index, - }) - if err != nil { - return rpc.ConvertError(err, "could not send response", codes.Internal) } - } - - return nil + return nil + }) }) } diff --git a/engine/access/rpc/handler_test.go b/engine/access/rpc/handler_test.go new file mode 100644 index 00000000000..bf034f0ccc0 --- /dev/null +++ b/engine/access/rpc/handler_test.go @@ -0,0 +1,40 @@ +package rpc + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onflow/flow-go/module/limiters" +) + +func TestWithStreamLimit_RejectsWhenLimitReached(t *testing.T) { + limiter, err := limiters.NewConcurrencyLimiter(1) + require.NoError(t, err) + + h := &Handler{limiter: limiter} + + // Saturate the limiter by blocking inside Allow. + started := make(chan struct{}) + unblock := make(chan struct{}) + go func() { + limiter.Allow(func() { + close(started) + <-unblock + }) + }() + <-started + + // A streaming call while the limiter is full must return ResourceExhausted. + err = h.withStreamLimit(func() error { + t.Fatal("fn should not be called when limiter is full") + return nil + }) + require.Error(t, err) + assert.Equal(t, codes.ResourceExhausted, status.Code(err)) + + close(unblock) +} diff --git a/engine/access/rpc/rate_limit_test.go b/engine/access/rpc/rate_limit_test.go index d04ab8d3c65..4b0e18a8a8a 100644 --- a/engine/access/rpc/rate_limit_test.go +++ b/engine/access/rpc/rate_limit_test.go @@ -26,10 +26,12 @@ import ( "github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator" "github.com/onflow/flow-go/engine/access/rpc/backend/query_mode" statestreambackend "github.com/onflow/flow-go/engine/access/state_stream/backend" + "github.com/onflow/flow-go/engine/access/subscription" commonrpc "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/metrics" module "github.com/onflow/flow-go/module/mock" "github.com/onflow/flow-go/network" @@ -186,6 +188,9 @@ func (suite *RateLimitTestSuite) SetupTest() { stateStreamConfig := statestreambackend.Config{} followerDistributor := pubsub.NewFollowerDistributor() + streamLimiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + require.NoError(suite.T(), err) + rpcEngBuilder, err := NewBuilder( suite.log, suite.state, @@ -202,6 +207,8 @@ func (suite *RateLimitTestSuite) SetupTest() { stateStreamConfig, nil, followerDistributor, + nil, + streamLimiter, ) require.NoError(suite.T(), err) suite.rpcEng, err = rpcEngBuilder.WithLegacy().Build() diff --git a/engine/access/secure_grpcr_test.go b/engine/access/secure_grpcr_test.go index d6007e18aed..1277eeaaa8b 100644 --- a/engine/access/secure_grpcr_test.go +++ b/engine/access/secure_grpcr_test.go @@ -25,10 +25,12 @@ import ( "github.com/onflow/flow-go/engine/access/rpc/backend/node_communicator" "github.com/onflow/flow-go/engine/access/rpc/backend/query_mode" statestreambackend "github.com/onflow/flow-go/engine/access/state_stream/backend" + "github.com/onflow/flow-go/engine/access/subscription" commonrpc "github.com/onflow/flow-go/engine/common/rpc" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/module/metrics" module "github.com/onflow/flow-go/module/mock" "github.com/onflow/flow-go/network" @@ -170,6 +172,8 @@ func (suite *SecureGRPCTestSuite) SetupTest() { stateStreamConfig := statestreambackend.Config{} followerDistributor := pubsub.NewFollowerDistributor() + streamLimiter, err := limiters.NewConcurrencyLimiter(subscription.DefaultMaxGlobalStreams) + suite.Require().NoError(err) rpcEngBuilder, err := rpc.NewBuilder( suite.log, suite.state, @@ -186,6 +190,8 @@ func (suite *SecureGRPCTestSuite) SetupTest() { stateStreamConfig, nil, followerDistributor, + nil, + streamLimiter, ) assert.NoError(suite.T(), err) suite.rpcEng, err = rpcEngBuilder.WithLegacy().Build() diff --git a/engine/access/state_stream/backend/backend_events_test.go b/engine/access/state_stream/backend/backend_events_test.go index 36e62e96807..6f4181512f8 100644 --- a/engine/access/state_stream/backend/backend_events_test.go +++ b/engine/access/state_stream/backend/backend_events_test.go @@ -1,7 +1,6 @@ package backend import ( - "bytes" "context" "fmt" "sort" @@ -103,7 +102,7 @@ func (s *BackendEventsSuite) setupFilterForTestCases(baseTests []eventsTestType) func (s *BackendEventsSuite) setupLocalStorage() { s.SetupBackend(true) - // events returned from the db are sorted by txID, txIndex, then eventIndex. + // events returned from storage are sorted by txIndex, then eventIndex (execution order). // reproduce that here to ensure output order works as expected blockEvents := make(map[flow.Identifier][]flow.Event) for _, b := range s.blocks { @@ -112,14 +111,10 @@ func (s *BackendEventsSuite) setupLocalStorage() { events[i] = event } sort.Slice(events, func(i, j int) bool { - cmp := bytes.Compare(events[i].TransactionID[:], events[j].TransactionID[:]) - if cmp == 0 { - if events[i].TransactionIndex == events[j].TransactionIndex { - return events[i].EventIndex < events[j].EventIndex - } - return events[i].TransactionIndex < events[j].TransactionIndex + if events[i].TransactionIndex == events[j].TransactionIndex { + return events[i].EventIndex < events[j].EventIndex } - return cmp < 0 + return events[i].TransactionIndex < events[j].TransactionIndex }) blockEvents[b.ID()] = events } diff --git a/engine/access/state_stream/backend/engine.go b/engine/access/state_stream/backend/engine.go index 97ce090dd04..3926b5683a2 100644 --- a/engine/access/state_stream/backend/engine.go +++ b/engine/access/state_stream/backend/engine.go @@ -11,6 +11,7 @@ import ( "github.com/onflow/flow-go/module/executiondatasync/execution_data/cache" "github.com/onflow/flow-go/module/grpcserver" "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/storage" ) @@ -38,6 +39,7 @@ func NewEng( chainID flow.ChainID, server *grpcserver.GrpcServer, backend *StateStreamBackend, + limiter *limiters.ConcurrencyLimiter, ) (*Engine, error) { logger := log.With().Str("engine", "state_stream_rpc").Logger() @@ -47,7 +49,7 @@ func NewEng( headers: headers, chain: chainID.Chain(), config: config, - handler: NewHandler(backend, chainID.Chain(), config), + handler: NewHandler(backend, chainID.Chain(), config, limiter), execDataCache: execDataCache, } diff --git a/engine/access/state_stream/backend/handler.go b/engine/access/state_stream/backend/handler.go index ea9cded1bed..4f06b19ec5f 100644 --- a/engine/access/state_stream/backend/handler.go +++ b/engine/access/state_stream/backend/handler.go @@ -16,10 +16,11 @@ import ( "github.com/onflow/flow-go/engine/common/rpc/convert" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/counters" + "github.com/onflow/flow-go/module/limiters" ) type Handler struct { - subscription.StreamingData + limiter *limiters.ConcurrencyLimiter api state_stream.API chain flow.Chain @@ -38,9 +39,9 @@ type sendSubscribeExecutionDataResponseFunc func(*executiondata.SubscribeExecuti var _ executiondata.ExecutionDataAPIServer = (*Handler)(nil) -func NewHandler(api state_stream.API, chain flow.Chain, config Config) *Handler { +func NewHandler(api state_stream.API, chain flow.Chain, config Config, limiter *limiters.ConcurrencyLimiter) *Handler { h := &Handler{ - StreamingData: subscription.NewStreamingData(config.MaxGlobalStreams), + limiter: limiter, api: api, chain: chain, eventFilterConfig: config.EventFilterConfig, @@ -49,6 +50,19 @@ func NewHandler(api state_stream.API, chain flow.Chain, config Config) *Handler return h } +// withStreamLimit executes fn within the global stream concurrency limit. +// Returns codes.ResourceExhausted if the limit is reached. +func (h *Handler) withStreamLimit(fn func() error) error { + var err error + allowed := h.limiter.Allow(func() { + err = fn() + }) + if !allowed { + return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") + } + return err +} + func (h *Handler) GetExecutionDataByBlockID(ctx context.Context, request *executiondata.GetExecutionDataByBlockIDRequest) (*executiondata.GetExecutionDataByBlockIDResponse, error) { blockID, err := convert.BlockID(request.GetBlockId()) if err != nil { @@ -84,25 +98,20 @@ func (h *Handler) GetExecutionDataByBlockID(ctx context.Context, request *execut // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream got unexpected response or could not send response. func (h *Handler) SubscribeExecutionData(request *executiondata.SubscribeExecutionDataRequest, stream executiondata.ExecutionDataAPI_SubscribeExecutionDataServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - startBlockID := flow.ZeroID - if request.GetStartBlockId() != nil { - blockID, err := convert.BlockID(request.GetStartBlockId()) - if err != nil { - return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) + return h.withStreamLimit(func() error { + startBlockID := flow.ZeroID + if request.GetStartBlockId() != nil { + blockID, err := convert.BlockID(request.GetStartBlockId()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) + } + startBlockID = blockID } - startBlockID = blockID - } - sub := h.api.SubscribeExecutionData(stream.Context(), startBlockID, request.GetStartBlockHeight()) + sub := h.api.SubscribeExecutionData(stream.Context(), startBlockID, request.GetStartBlockHeight()) - return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + }) } // SubscribeExecutionDataFromStartBlockID handles subscription requests for @@ -115,21 +124,16 @@ func (h *Handler) SubscribeExecutionData(request *executiondata.SubscribeExecuti // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream got unexpected response or could not send response. func (h *Handler) SubscribeExecutionDataFromStartBlockID(request *executiondata.SubscribeExecutionDataFromStartBlockIDRequest, stream executiondata.ExecutionDataAPI_SubscribeExecutionDataFromStartBlockIDServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - startBlockID, err := convert.BlockID(request.GetStartBlockId()) - if err != nil { - return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) - } + return h.withStreamLimit(func() error { + startBlockID, err := convert.BlockID(request.GetStartBlockId()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) + } - sub := h.api.SubscribeExecutionDataFromStartBlockID(stream.Context(), startBlockID) + sub := h.api.SubscribeExecutionDataFromStartBlockID(stream.Context(), startBlockID) - return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + }) } // SubscribeExecutionDataFromStartBlockHeight handles subscription requests for @@ -141,16 +145,11 @@ func (h *Handler) SubscribeExecutionDataFromStartBlockID(request *executiondata. // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream got unexpected response or could not send response. func (h *Handler) SubscribeExecutionDataFromStartBlockHeight(request *executiondata.SubscribeExecutionDataFromStartBlockHeightRequest, stream executiondata.ExecutionDataAPI_SubscribeExecutionDataFromStartBlockHeightServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - sub := h.api.SubscribeExecutionDataFromStartBlockHeight(stream.Context(), request.GetStartBlockHeight()) + return h.withStreamLimit(func() error { + sub := h.api.SubscribeExecutionDataFromStartBlockHeight(stream.Context(), request.GetStartBlockHeight()) - return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + }) } // SubscribeExecutionDataFromLatest handles subscription requests for @@ -162,16 +161,11 @@ func (h *Handler) SubscribeExecutionDataFromStartBlockHeight(request *executiond // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - if stream got unexpected response or could not send response. func (h *Handler) SubscribeExecutionDataFromLatest(request *executiondata.SubscribeExecutionDataFromLatestRequest, stream executiondata.ExecutionDataAPI_SubscribeExecutionDataFromLatestServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - sub := h.api.SubscribeExecutionDataFromLatest(stream.Context()) + return h.withStreamLimit(func() error { + sub := h.api.SubscribeExecutionDataFromLatest(stream.Context()) - return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, handleSubscribeExecutionData(stream.Send, request.GetEventEncodingVersion())) + }) } // SubscribeEvents is deprecated and will be removed in a future version. @@ -190,30 +184,25 @@ func (h *Handler) SubscribeExecutionDataFromLatest(request *executiondata.Subscr // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - could not convert events to entity, if stream encountered an error, if stream got unexpected response or could not send response. func (h *Handler) SubscribeEvents(request *executiondata.SubscribeEventsRequest, stream executiondata.ExecutionDataAPI_SubscribeEventsServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) + return h.withStreamLimit(func() error { + startBlockID := flow.ZeroID + if request.GetStartBlockId() != nil { + blockID, err := convert.BlockID(request.GetStartBlockId()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) + } + startBlockID = blockID + } - startBlockID := flow.ZeroID - if request.GetStartBlockId() != nil { - blockID, err := convert.BlockID(request.GetStartBlockId()) + filter, err := h.getEventFilter(request.GetFilter()) if err != nil { - return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) + return err } - startBlockID = blockID - } - - filter, err := h.getEventFilter(request.GetFilter()) - if err != nil { - return err - } - sub := h.api.SubscribeEvents(stream.Context(), startBlockID, request.GetStartBlockHeight(), filter) + sub := h.api.SubscribeEvents(stream.Context(), startBlockID, request.GetStartBlockHeight(), filter) - return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + }) } // SubscribeEventsFromStartBlockID handles subscription requests for events starting at the specified block ID. @@ -229,26 +218,21 @@ func (h *Handler) SubscribeEvents(request *executiondata.SubscribeEventsRequest, // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - could not convert events to entity, if stream encountered an error, if stream got unexpected response or could not send response. func (h *Handler) SubscribeEventsFromStartBlockID(request *executiondata.SubscribeEventsFromStartBlockIDRequest, stream executiondata.ExecutionDataAPI_SubscribeEventsFromStartBlockIDServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - startBlockID, err := convert.BlockID(request.GetStartBlockId()) - if err != nil { - return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) - } + return h.withStreamLimit(func() error { + startBlockID, err := convert.BlockID(request.GetStartBlockId()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) + } - filter, err := h.getEventFilter(request.GetFilter()) - if err != nil { - return err - } + filter, err := h.getEventFilter(request.GetFilter()) + if err != nil { + return err + } - sub := h.api.SubscribeEventsFromStartBlockID(stream.Context(), startBlockID, filter) + sub := h.api.SubscribeEventsFromStartBlockID(stream.Context(), startBlockID, filter) - return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + }) } // SubscribeEventsFromStartHeight handles subscription requests for events starting at the specified block height. @@ -264,21 +248,16 @@ func (h *Handler) SubscribeEventsFromStartBlockID(request *executiondata.Subscri // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - could not convert events to entity, if stream encountered an error, if stream got unexpected response or could not send response. func (h *Handler) SubscribeEventsFromStartHeight(request *executiondata.SubscribeEventsFromStartHeightRequest, stream executiondata.ExecutionDataAPI_SubscribeEventsFromStartHeightServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - filter, err := h.getEventFilter(request.GetFilter()) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + filter, err := h.getEventFilter(request.GetFilter()) + if err != nil { + return err + } - sub := h.api.SubscribeEventsFromStartHeight(stream.Context(), request.GetStartBlockHeight(), filter) + sub := h.api.SubscribeEventsFromStartHeight(stream.Context(), request.GetStartBlockHeight(), filter) - return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + }) } // SubscribeEventsFromLatest handles subscription requests for events started from latest sealed block.. @@ -294,21 +273,16 @@ func (h *Handler) SubscribeEventsFromStartHeight(request *executiondata.Subscrib // - codes.ResourceExhausted - if the maximum number of streams is reached. // - codes.Internal - could not convert events to entity, if stream encountered an error, if stream got unexpected response or could not send response. func (h *Handler) SubscribeEventsFromLatest(request *executiondata.SubscribeEventsFromLatestRequest, stream executiondata.ExecutionDataAPI_SubscribeEventsFromLatestServer) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - filter, err := h.getEventFilter(request.GetFilter()) - if err != nil { - return err - } + return h.withStreamLimit(func() error { + filter, err := h.getEventFilter(request.GetFilter()) + if err != nil { + return err + } - sub := h.api.SubscribeEventsFromLatest(stream.Context(), filter) + sub := h.api.SubscribeEventsFromLatest(stream.Context(), filter) - return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + return HandleRPCSubscription(sub, h.handleEventsResponse(stream.Send, request.HeartbeatInterval, request.GetEventEncodingVersion())) + }) } // handleSubscribeExecutionData handles the subscription to execution data and sends it to the client via the provided stream. @@ -525,28 +499,22 @@ func (h *Handler) SubscribeAccountStatusesFromStartBlockID( request *executiondata.SubscribeAccountStatusesFromStartBlockIDRequest, stream executiondata.ExecutionDataAPI_SubscribeAccountStatusesFromStartBlockIDServer, ) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - startBlockID, err := convert.BlockID(request.GetStartBlockId()) - if err != nil { - return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) - } + return h.withStreamLimit(func() error { + startBlockID, err := convert.BlockID(request.GetStartBlockId()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not convert start block ID: %v", err) + } - statusFilter := request.GetFilter() - filter, err := state_stream.NewAccountStatusFilter(h.eventFilterConfig, h.chain, statusFilter.GetEventType(), statusFilter.GetAddress()) - if err != nil { - return status.Errorf(codes.InvalidArgument, "could not create account status filter: %v", err) - } + statusFilter := request.GetFilter() + filter, err := state_stream.NewAccountStatusFilter(h.eventFilterConfig, h.chain, statusFilter.GetEventType(), statusFilter.GetAddress()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not create account status filter: %v", err) + } - sub := h.api.SubscribeAccountStatusesFromStartBlockID(stream.Context(), startBlockID, filter) + sub := h.api.SubscribeAccountStatusesFromStartBlockID(stream.Context(), startBlockID, filter) - return HandleRPCSubscription(sub, h.handleAccountStatusesResponse(request.HeartbeatInterval, request.GetEventEncodingVersion(), stream.Send)) + return HandleRPCSubscription(sub, h.handleAccountStatusesResponse(request.HeartbeatInterval, request.GetEventEncodingVersion(), stream.Send)) + }) } // SubscribeAccountStatusesFromStartHeight streams account statuses for all blocks starting at the requested @@ -557,23 +525,17 @@ func (h *Handler) SubscribeAccountStatusesFromStartHeight( request *executiondata.SubscribeAccountStatusesFromStartHeightRequest, stream executiondata.ExecutionDataAPI_SubscribeAccountStatusesFromStartHeightServer, ) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - statusFilter := request.GetFilter() - filter, err := state_stream.NewAccountStatusFilter(h.eventFilterConfig, h.chain, statusFilter.GetEventType(), statusFilter.GetAddress()) - if err != nil { - return status.Errorf(codes.InvalidArgument, "could not create account status filter: %v", err) - } + return h.withStreamLimit(func() error { + statusFilter := request.GetFilter() + filter, err := state_stream.NewAccountStatusFilter(h.eventFilterConfig, h.chain, statusFilter.GetEventType(), statusFilter.GetAddress()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not create account status filter: %v", err) + } - sub := h.api.SubscribeAccountStatusesFromStartHeight(stream.Context(), request.GetStartBlockHeight(), filter) + sub := h.api.SubscribeAccountStatusesFromStartHeight(stream.Context(), request.GetStartBlockHeight(), filter) - return HandleRPCSubscription(sub, h.handleAccountStatusesResponse(request.HeartbeatInterval, request.GetEventEncodingVersion(), stream.Send)) + return HandleRPCSubscription(sub, h.handleAccountStatusesResponse(request.HeartbeatInterval, request.GetEventEncodingVersion(), stream.Send)) + }) } // SubscribeAccountStatusesFromLatestBlock streams account statuses for all blocks starting @@ -584,23 +546,17 @@ func (h *Handler) SubscribeAccountStatusesFromLatestBlock( request *executiondata.SubscribeAccountStatusesFromLatestBlockRequest, stream executiondata.ExecutionDataAPI_SubscribeAccountStatusesFromLatestBlockServer, ) error { - // check if the maximum number of streams is reached - if h.StreamCount.Load() >= h.MaxStreams { - return status.Errorf(codes.ResourceExhausted, "maximum number of streams reached") - } - - h.StreamCount.Add(1) - defer h.StreamCount.Add(-1) - - statusFilter := request.GetFilter() - filter, err := state_stream.NewAccountStatusFilter(h.eventFilterConfig, h.chain, statusFilter.GetEventType(), statusFilter.GetAddress()) - if err != nil { - return status.Errorf(codes.InvalidArgument, "could not create account status filter: %v", err) - } + return h.withStreamLimit(func() error { + statusFilter := request.GetFilter() + filter, err := state_stream.NewAccountStatusFilter(h.eventFilterConfig, h.chain, statusFilter.GetEventType(), statusFilter.GetAddress()) + if err != nil { + return status.Errorf(codes.InvalidArgument, "could not create account status filter: %v", err) + } - sub := h.api.SubscribeAccountStatusesFromLatestBlock(stream.Context(), filter) + sub := h.api.SubscribeAccountStatusesFromLatestBlock(stream.Context(), filter) - return HandleRPCSubscription(sub, h.handleAccountStatusesResponse(request.HeartbeatInterval, request.GetEventEncodingVersion(), stream.Send)) + return HandleRPCSubscription(sub, h.handleAccountStatusesResponse(request.HeartbeatInterval, request.GetEventEncodingVersion(), stream.Send)) + }) } // HandleRPCSubscription is a generic handler for subscriptions to a specific type for rpc calls. diff --git a/engine/access/state_stream/backend/handler_test.go b/engine/access/state_stream/backend/handler_test.go index affe2167dfe..bdf28cda29b 100644 --- a/engine/access/state_stream/backend/handler_test.go +++ b/engine/access/state_stream/backend/handler_test.go @@ -27,6 +27,7 @@ import ( "github.com/onflow/flow-go/engine/access/subscription" "github.com/onflow/flow-go/engine/common/rpc/convert" "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/limiters" "github.com/onflow/flow-go/storage" "github.com/onflow/flow-go/utils/unittest" ) @@ -62,7 +63,7 @@ func (fake *fakeReadServerImpl) Send(response *executiondata.SubscribeEventsResp func (s *HandlerTestSuite) SetupTest() { s.BackendExecutionDataSuite.SetupTest() chain := flow.MonotonicEmulator.Chain() - s.handler = NewHandler(s.backend, chain, makeConfig(5)) + s.handler = NewHandler(s.backend, chain, makeConfig(5), makeLimiter(s.T(), 5)) } // TestHeartbeatResponse tests the periodic heartbeat response. @@ -227,7 +228,7 @@ func TestGetExecutionDataByBlockID(t *testing.T) { api := ssmock.NewAPI(t) api.On("GetExecutionDataByBlockID", mock.Anything, blockID).Return(result, nil) - h := NewHandler(api, flow.Localnet.Chain(), makeConfig(1)) + h := NewHandler(api, flow.Localnet.Chain(), makeConfig(1), makeLimiter(t, 1)) response, err := h.GetExecutionDataByBlockID(ctx, &executiondata.GetExecutionDataByBlockIDRequest{ BlockId: blockID[:], @@ -281,7 +282,7 @@ func TestExecutionDataStream(t *testing.T) { api.On("SubscribeExecutionData", mock.Anything, flow.ZeroID, uint64(0), mock.Anything).Return(sub) - h := NewHandler(api, flow.Localnet.Chain(), makeConfig(1)) + h := NewHandler(api, flow.Localnet.Chain(), makeConfig(1), makeLimiter(t, 1)) wg := sync.WaitGroup{} wg.Add(1) @@ -407,7 +408,7 @@ func TestEventStream(t *testing.T) { api.On("SubscribeEvents", mock.Anything, flow.ZeroID, uint64(0), mock.Anything).Return(sub) - h := NewHandler(api, flow.Localnet.Chain(), makeConfig(1)) + h := NewHandler(api, flow.Localnet.Chain(), makeConfig(1), makeLimiter(t, 1)) wg := sync.WaitGroup{} wg.Add(1) @@ -532,7 +533,7 @@ func TestGetRegisterValues(t *testing.T) { t.Run("invalid message", func(t *testing.T) { api := ssmock.NewAPI(t) - h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1)) + h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1), makeLimiter(t, 1)) invalidMessage := &executiondata.GetRegisterValuesRequest{ RegisterIds: nil, @@ -544,7 +545,7 @@ func TestGetRegisterValues(t *testing.T) { t.Run("valid registers", func(t *testing.T) { api := ssmock.NewAPI(t) api.On("GetRegisterValues", testIds, testHeight).Return(testValues, nil) - h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1)) + h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1), makeLimiter(t, 1)) validRegisters := make([]*entities.RegisterID, len(testIds)) for i, id := range testIds { @@ -565,7 +566,7 @@ func TestGetRegisterValues(t *testing.T) { api := ssmock.NewAPI(t) expectedErr := status.Errorf(codes.NotFound, "could not get register values: %v", storage.ErrNotFound) api.On("GetRegisterValues", invalidIDs, testHeight).Return(nil, expectedErr) - h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1)) + h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1), makeLimiter(t, 1)) unavailableRegisters := make([]*entities.RegisterID, len(invalidIDs)) for i, id := range invalidIDs { @@ -585,7 +586,7 @@ func TestGetRegisterValues(t *testing.T) { api := ssmock.NewAPI(t) expectedErr := status.Errorf(codes.OutOfRange, "could not get register values: %v", storage.ErrHeightNotIndexed) api.On("GetRegisterValues", testIds, testHeight+1).Return(nil, expectedErr) - h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1)) + h := NewHandler(api, flow.Testnet.Chain(), makeConfig(1), makeLimiter(t, 1)) validRegisters := make([]*entities.RegisterID, len(testIds)) for i, id := range testIds { @@ -613,6 +614,38 @@ func generateEvents(t *testing.T, n int) ([]flow.Event, []flow.Event) { return ccfEvents, jsonEvents } +func TestWithStreamLimit_RejectsWhenLimitReached(t *testing.T) { + limiter := makeLimiter(t, 1) + h := NewHandler(nil, flow.Localnet.Chain(), makeConfig(1), limiter) + + // Saturate the limiter by blocking inside Allow. + started := make(chan struct{}) + unblock := make(chan struct{}) + go func() { + limiter.Allow(func() { + close(started) + <-unblock + }) + }() + <-started + + // A streaming call while the limiter is full must return ResourceExhausted. + err := h.withStreamLimit(func() error { + t.Fatal("fn should not be called when limiter is full") + return nil + }) + require.Error(t, err) + assert.Equal(t, codes.ResourceExhausted, status.Code(err)) + + close(unblock) +} + +func makeLimiter(t *testing.T, maxGlobalStreams uint32) *limiters.ConcurrencyLimiter { + l, err := limiters.NewConcurrencyLimiter(maxGlobalStreams) + require.NoError(t, err) + return l +} + func makeConfig(maxGlobalStreams uint32) Config { return Config{ EventFilterConfig: state_stream.DefaultEventFilterConfig, diff --git a/engine/access/state_stream/mock/api.go b/engine/access/state_stream/mock/api.go index ba8bd9e7544..f3b8b09a1e8 100644 --- a/engine/access/state_stream/mock/api.go +++ b/engine/access/state_stream/mock/api.go @@ -1,28 +1,49 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "context" + "github.com/onflow/flow-go/engine/access/state_stream" + "github.com/onflow/flow-go/engine/access/subscription" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" +) - state_stream "github.com/onflow/flow-go/engine/access/state_stream" +// NewAPI creates a new instance of API. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *API { + mock := &API{} + mock.Mock.Test(t) - subscription "github.com/onflow/flow-go/engine/access/subscription" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // API is an autogenerated mock type for the API type type API struct { mock.Mock } -// GetExecutionDataByBlockID provides a mock function with given fields: ctx, blockID -func (_m *API) GetExecutionDataByBlockID(ctx context.Context, blockID flow.Identifier) (*execution_data.BlockExecutionData, error) { - ret := _m.Called(ctx, blockID) +type API_Expecter struct { + mock *mock.Mock +} + +func (_m *API) EXPECT() *API_Expecter { + return &API_Expecter{mock: &_m.Mock} +} + +// GetExecutionDataByBlockID provides a mock function for the type API +func (_mock *API) GetExecutionDataByBlockID(ctx context.Context, blockID flow.Identifier) (*execution_data.BlockExecutionData, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetExecutionDataByBlockID") @@ -30,29 +51,67 @@ func (_m *API) GetExecutionDataByBlockID(ctx context.Context, blockID flow.Ident var r0 *execution_data.BlockExecutionData var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionData) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetRegisterValues provides a mock function with given fields: registerIDs, height -func (_m *API) GetRegisterValues(registerIDs flow.RegisterIDs, height uint64) ([]flow.RegisterValue, error) { - ret := _m.Called(registerIDs, height) +// API_GetExecutionDataByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionDataByBlockID' +type API_GetExecutionDataByBlockID_Call struct { + *mock.Call +} + +// GetExecutionDataByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *API_Expecter) GetExecutionDataByBlockID(ctx interface{}, blockID interface{}) *API_GetExecutionDataByBlockID_Call { + return &API_GetExecutionDataByBlockID_Call{Call: _e.mock.On("GetExecutionDataByBlockID", ctx, blockID)} +} + +func (_c *API_GetExecutionDataByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *API_GetExecutionDataByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetExecutionDataByBlockID_Call) Return(blockExecutionData *execution_data.BlockExecutionData, err error) *API_GetExecutionDataByBlockID_Call { + _c.Call.Return(blockExecutionData, err) + return _c +} + +func (_c *API_GetExecutionDataByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*execution_data.BlockExecutionData, error)) *API_GetExecutionDataByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetRegisterValues provides a mock function for the type API +func (_mock *API) GetRegisterValues(registerIDs flow.RegisterIDs, height uint64) ([]flow.RegisterValue, error) { + ret := _mock.Called(registerIDs, height) if len(ret) == 0 { panic("no return value specified for GetRegisterValues") @@ -60,256 +119,745 @@ func (_m *API) GetRegisterValues(registerIDs flow.RegisterIDs, height uint64) ([ var r0 []flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterIDs, uint64) ([]flow.RegisterValue, error)); ok { - return rf(registerIDs, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterIDs, uint64) ([]flow.RegisterValue, error)); ok { + return returnFunc(registerIDs, height) } - if rf, ok := ret.Get(0).(func(flow.RegisterIDs, uint64) []flow.RegisterValue); ok { - r0 = rf(registerIDs, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterIDs, uint64) []flow.RegisterValue); ok { + r0 = returnFunc(registerIDs, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterIDs, uint64) error); ok { - r1 = rf(registerIDs, height) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterIDs, uint64) error); ok { + r1 = returnFunc(registerIDs, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubscribeAccountStatusesFromLatestBlock provides a mock function with given fields: ctx, filter -func (_m *API) SubscribeAccountStatusesFromLatestBlock(ctx context.Context, filter state_stream.AccountStatusFilter) subscription.Subscription { - ret := _m.Called(ctx, filter) +// API_GetRegisterValues_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegisterValues' +type API_GetRegisterValues_Call struct { + *mock.Call +} + +// GetRegisterValues is a helper method to define mock.On call +// - registerIDs flow.RegisterIDs +// - height uint64 +func (_e *API_Expecter) GetRegisterValues(registerIDs interface{}, height interface{}) *API_GetRegisterValues_Call { + return &API_GetRegisterValues_Call{Call: _e.mock.On("GetRegisterValues", registerIDs, height)} +} + +func (_c *API_GetRegisterValues_Call) Run(run func(registerIDs flow.RegisterIDs, height uint64)) *API_GetRegisterValues_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterIDs + if args[0] != nil { + arg0 = args[0].(flow.RegisterIDs) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_GetRegisterValues_Call) Return(vs []flow.RegisterValue, err error) *API_GetRegisterValues_Call { + _c.Call.Return(vs, err) + return _c +} + +func (_c *API_GetRegisterValues_Call) RunAndReturn(run func(registerIDs flow.RegisterIDs, height uint64) ([]flow.RegisterValue, error)) *API_GetRegisterValues_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeAccountStatusesFromLatestBlock provides a mock function for the type API +func (_mock *API) SubscribeAccountStatusesFromLatestBlock(ctx context.Context, filter state_stream.AccountStatusFilter) subscription.Subscription { + ret := _mock.Called(ctx, filter) if len(ret) == 0 { panic("no return value specified for SubscribeAccountStatusesFromLatestBlock") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, state_stream.AccountStatusFilter) subscription.Subscription); ok { - r0 = rf(ctx, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, state_stream.AccountStatusFilter) subscription.Subscription); ok { + r0 = returnFunc(ctx, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeAccountStatusesFromStartBlockID provides a mock function with given fields: ctx, startBlockID, filter -func (_m *API) SubscribeAccountStatusesFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, filter state_stream.AccountStatusFilter) subscription.Subscription { - ret := _m.Called(ctx, startBlockID, filter) +// API_SubscribeAccountStatusesFromLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeAccountStatusesFromLatestBlock' +type API_SubscribeAccountStatusesFromLatestBlock_Call struct { + *mock.Call +} + +// SubscribeAccountStatusesFromLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - filter state_stream.AccountStatusFilter +func (_e *API_Expecter) SubscribeAccountStatusesFromLatestBlock(ctx interface{}, filter interface{}) *API_SubscribeAccountStatusesFromLatestBlock_Call { + return &API_SubscribeAccountStatusesFromLatestBlock_Call{Call: _e.mock.On("SubscribeAccountStatusesFromLatestBlock", ctx, filter)} +} + +func (_c *API_SubscribeAccountStatusesFromLatestBlock_Call) Run(run func(ctx context.Context, filter state_stream.AccountStatusFilter)) *API_SubscribeAccountStatusesFromLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 state_stream.AccountStatusFilter + if args[1] != nil { + arg1 = args[1].(state_stream.AccountStatusFilter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SubscribeAccountStatusesFromLatestBlock_Call) Return(subscription1 subscription.Subscription) *API_SubscribeAccountStatusesFromLatestBlock_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeAccountStatusesFromLatestBlock_Call) RunAndReturn(run func(ctx context.Context, filter state_stream.AccountStatusFilter) subscription.Subscription) *API_SubscribeAccountStatusesFromLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeAccountStatusesFromStartBlockID provides a mock function for the type API +func (_mock *API) SubscribeAccountStatusesFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, filter state_stream.AccountStatusFilter) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID, filter) if len(ret) == 0 { panic("no return value specified for SubscribeAccountStatusesFromStartBlockID") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, state_stream.AccountStatusFilter) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, state_stream.AccountStatusFilter) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeAccountStatusesFromStartHeight provides a mock function with given fields: ctx, startHeight, filter -func (_m *API) SubscribeAccountStatusesFromStartHeight(ctx context.Context, startHeight uint64, filter state_stream.AccountStatusFilter) subscription.Subscription { - ret := _m.Called(ctx, startHeight, filter) +// API_SubscribeAccountStatusesFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeAccountStatusesFromStartBlockID' +type API_SubscribeAccountStatusesFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeAccountStatusesFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - filter state_stream.AccountStatusFilter +func (_e *API_Expecter) SubscribeAccountStatusesFromStartBlockID(ctx interface{}, startBlockID interface{}, filter interface{}) *API_SubscribeAccountStatusesFromStartBlockID_Call { + return &API_SubscribeAccountStatusesFromStartBlockID_Call{Call: _e.mock.On("SubscribeAccountStatusesFromStartBlockID", ctx, startBlockID, filter)} +} + +func (_c *API_SubscribeAccountStatusesFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, filter state_stream.AccountStatusFilter)) *API_SubscribeAccountStatusesFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 state_stream.AccountStatusFilter + if args[2] != nil { + arg2 = args[2].(state_stream.AccountStatusFilter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeAccountStatusesFromStartBlockID_Call) Return(subscription1 subscription.Subscription) *API_SubscribeAccountStatusesFromStartBlockID_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeAccountStatusesFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, filter state_stream.AccountStatusFilter) subscription.Subscription) *API_SubscribeAccountStatusesFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeAccountStatusesFromStartHeight provides a mock function for the type API +func (_mock *API) SubscribeAccountStatusesFromStartHeight(ctx context.Context, startHeight uint64, filter state_stream.AccountStatusFilter) subscription.Subscription { + ret := _mock.Called(ctx, startHeight, filter) if len(ret) == 0 { panic("no return value specified for SubscribeAccountStatusesFromStartHeight") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, uint64, state_stream.AccountStatusFilter) subscription.Subscription); ok { - r0 = rf(ctx, startHeight, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, state_stream.AccountStatusFilter) subscription.Subscription); ok { + r0 = returnFunc(ctx, startHeight, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeEvents provides a mock function with given fields: ctx, startBlockID, startHeight, filter -func (_m *API) SubscribeEvents(ctx context.Context, startBlockID flow.Identifier, startHeight uint64, filter state_stream.EventFilter) subscription.Subscription { - ret := _m.Called(ctx, startBlockID, startHeight, filter) +// API_SubscribeAccountStatusesFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeAccountStatusesFromStartHeight' +type API_SubscribeAccountStatusesFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeAccountStatusesFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - filter state_stream.AccountStatusFilter +func (_e *API_Expecter) SubscribeAccountStatusesFromStartHeight(ctx interface{}, startHeight interface{}, filter interface{}) *API_SubscribeAccountStatusesFromStartHeight_Call { + return &API_SubscribeAccountStatusesFromStartHeight_Call{Call: _e.mock.On("SubscribeAccountStatusesFromStartHeight", ctx, startHeight, filter)} +} + +func (_c *API_SubscribeAccountStatusesFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, filter state_stream.AccountStatusFilter)) *API_SubscribeAccountStatusesFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 state_stream.AccountStatusFilter + if args[2] != nil { + arg2 = args[2].(state_stream.AccountStatusFilter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeAccountStatusesFromStartHeight_Call) Return(subscription1 subscription.Subscription) *API_SubscribeAccountStatusesFromStartHeight_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeAccountStatusesFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, filter state_stream.AccountStatusFilter) subscription.Subscription) *API_SubscribeAccountStatusesFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeEvents provides a mock function for the type API +func (_mock *API) SubscribeEvents(ctx context.Context, startBlockID flow.Identifier, startHeight uint64, filter state_stream.EventFilter) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID, startHeight, filter) if len(ret) == 0 { panic("no return value specified for SubscribeEvents") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64, state_stream.EventFilter) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID, startHeight, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64, state_stream.EventFilter) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID, startHeight, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeEventsFromLatest provides a mock function with given fields: ctx, filter -func (_m *API) SubscribeEventsFromLatest(ctx context.Context, filter state_stream.EventFilter) subscription.Subscription { - ret := _m.Called(ctx, filter) +// API_SubscribeEvents_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeEvents' +type API_SubscribeEvents_Call struct { + *mock.Call +} + +// SubscribeEvents is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - startHeight uint64 +// - filter state_stream.EventFilter +func (_e *API_Expecter) SubscribeEvents(ctx interface{}, startBlockID interface{}, startHeight interface{}, filter interface{}) *API_SubscribeEvents_Call { + return &API_SubscribeEvents_Call{Call: _e.mock.On("SubscribeEvents", ctx, startBlockID, startHeight, filter)} +} + +func (_c *API_SubscribeEvents_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, startHeight uint64, filter state_stream.EventFilter)) *API_SubscribeEvents_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 state_stream.EventFilter + if args[3] != nil { + arg3 = args[3].(state_stream.EventFilter) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *API_SubscribeEvents_Call) Return(subscription1 subscription.Subscription) *API_SubscribeEvents_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeEvents_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, startHeight uint64, filter state_stream.EventFilter) subscription.Subscription) *API_SubscribeEvents_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeEventsFromLatest provides a mock function for the type API +func (_mock *API) SubscribeEventsFromLatest(ctx context.Context, filter state_stream.EventFilter) subscription.Subscription { + ret := _mock.Called(ctx, filter) if len(ret) == 0 { panic("no return value specified for SubscribeEventsFromLatest") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, state_stream.EventFilter) subscription.Subscription); ok { - r0 = rf(ctx, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, state_stream.EventFilter) subscription.Subscription); ok { + r0 = returnFunc(ctx, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeEventsFromStartBlockID provides a mock function with given fields: ctx, startBlockID, filter -func (_m *API) SubscribeEventsFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, filter state_stream.EventFilter) subscription.Subscription { - ret := _m.Called(ctx, startBlockID, filter) +// API_SubscribeEventsFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeEventsFromLatest' +type API_SubscribeEventsFromLatest_Call struct { + *mock.Call +} + +// SubscribeEventsFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - filter state_stream.EventFilter +func (_e *API_Expecter) SubscribeEventsFromLatest(ctx interface{}, filter interface{}) *API_SubscribeEventsFromLatest_Call { + return &API_SubscribeEventsFromLatest_Call{Call: _e.mock.On("SubscribeEventsFromLatest", ctx, filter)} +} + +func (_c *API_SubscribeEventsFromLatest_Call) Run(run func(ctx context.Context, filter state_stream.EventFilter)) *API_SubscribeEventsFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 state_stream.EventFilter + if args[1] != nil { + arg1 = args[1].(state_stream.EventFilter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SubscribeEventsFromLatest_Call) Return(subscription1 subscription.Subscription) *API_SubscribeEventsFromLatest_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeEventsFromLatest_Call) RunAndReturn(run func(ctx context.Context, filter state_stream.EventFilter) subscription.Subscription) *API_SubscribeEventsFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeEventsFromStartBlockID provides a mock function for the type API +func (_mock *API) SubscribeEventsFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, filter state_stream.EventFilter) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID, filter) if len(ret) == 0 { panic("no return value specified for SubscribeEventsFromStartBlockID") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, state_stream.EventFilter) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, state_stream.EventFilter) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeEventsFromStartHeight provides a mock function with given fields: ctx, startHeight, filter -func (_m *API) SubscribeEventsFromStartHeight(ctx context.Context, startHeight uint64, filter state_stream.EventFilter) subscription.Subscription { - ret := _m.Called(ctx, startHeight, filter) +// API_SubscribeEventsFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeEventsFromStartBlockID' +type API_SubscribeEventsFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeEventsFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - filter state_stream.EventFilter +func (_e *API_Expecter) SubscribeEventsFromStartBlockID(ctx interface{}, startBlockID interface{}, filter interface{}) *API_SubscribeEventsFromStartBlockID_Call { + return &API_SubscribeEventsFromStartBlockID_Call{Call: _e.mock.On("SubscribeEventsFromStartBlockID", ctx, startBlockID, filter)} +} + +func (_c *API_SubscribeEventsFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, filter state_stream.EventFilter)) *API_SubscribeEventsFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 state_stream.EventFilter + if args[2] != nil { + arg2 = args[2].(state_stream.EventFilter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeEventsFromStartBlockID_Call) Return(subscription1 subscription.Subscription) *API_SubscribeEventsFromStartBlockID_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeEventsFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, filter state_stream.EventFilter) subscription.Subscription) *API_SubscribeEventsFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeEventsFromStartHeight provides a mock function for the type API +func (_mock *API) SubscribeEventsFromStartHeight(ctx context.Context, startHeight uint64, filter state_stream.EventFilter) subscription.Subscription { + ret := _mock.Called(ctx, startHeight, filter) if len(ret) == 0 { panic("no return value specified for SubscribeEventsFromStartHeight") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, uint64, state_stream.EventFilter) subscription.Subscription); ok { - r0 = rf(ctx, startHeight, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, state_stream.EventFilter) subscription.Subscription); ok { + r0 = returnFunc(ctx, startHeight, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeExecutionData provides a mock function with given fields: ctx, startBlockID, startBlockHeight -func (_m *API) SubscribeExecutionData(ctx context.Context, startBlockID flow.Identifier, startBlockHeight uint64) subscription.Subscription { - ret := _m.Called(ctx, startBlockID, startBlockHeight) +// API_SubscribeEventsFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeEventsFromStartHeight' +type API_SubscribeEventsFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeEventsFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - filter state_stream.EventFilter +func (_e *API_Expecter) SubscribeEventsFromStartHeight(ctx interface{}, startHeight interface{}, filter interface{}) *API_SubscribeEventsFromStartHeight_Call { + return &API_SubscribeEventsFromStartHeight_Call{Call: _e.mock.On("SubscribeEventsFromStartHeight", ctx, startHeight, filter)} +} + +func (_c *API_SubscribeEventsFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, filter state_stream.EventFilter)) *API_SubscribeEventsFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 state_stream.EventFilter + if args[2] != nil { + arg2 = args[2].(state_stream.EventFilter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeEventsFromStartHeight_Call) Return(subscription1 subscription.Subscription) *API_SubscribeEventsFromStartHeight_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeEventsFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, filter state_stream.EventFilter) subscription.Subscription) *API_SubscribeEventsFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeExecutionData provides a mock function for the type API +func (_mock *API) SubscribeExecutionData(ctx context.Context, startBlockID flow.Identifier, startBlockHeight uint64) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID, startBlockHeight) if len(ret) == 0 { panic("no return value specified for SubscribeExecutionData") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID, startBlockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID, startBlockHeight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeExecutionDataFromLatest provides a mock function with given fields: ctx -func (_m *API) SubscribeExecutionDataFromLatest(ctx context.Context) subscription.Subscription { - ret := _m.Called(ctx) +// API_SubscribeExecutionData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeExecutionData' +type API_SubscribeExecutionData_Call struct { + *mock.Call +} + +// SubscribeExecutionData is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - startBlockHeight uint64 +func (_e *API_Expecter) SubscribeExecutionData(ctx interface{}, startBlockID interface{}, startBlockHeight interface{}) *API_SubscribeExecutionData_Call { + return &API_SubscribeExecutionData_Call{Call: _e.mock.On("SubscribeExecutionData", ctx, startBlockID, startBlockHeight)} +} + +func (_c *API_SubscribeExecutionData_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, startBlockHeight uint64)) *API_SubscribeExecutionData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *API_SubscribeExecutionData_Call) Return(subscription1 subscription.Subscription) *API_SubscribeExecutionData_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeExecutionData_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, startBlockHeight uint64) subscription.Subscription) *API_SubscribeExecutionData_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeExecutionDataFromLatest provides a mock function for the type API +func (_mock *API) SubscribeExecutionDataFromLatest(ctx context.Context) subscription.Subscription { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for SubscribeExecutionDataFromLatest") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context) subscription.Subscription); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) subscription.Subscription); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeExecutionDataFromStartBlockHeight provides a mock function with given fields: ctx, startBlockHeight -func (_m *API) SubscribeExecutionDataFromStartBlockHeight(ctx context.Context, startBlockHeight uint64) subscription.Subscription { - ret := _m.Called(ctx, startBlockHeight) +// API_SubscribeExecutionDataFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeExecutionDataFromLatest' +type API_SubscribeExecutionDataFromLatest_Call struct { + *mock.Call +} + +// SubscribeExecutionDataFromLatest is a helper method to define mock.On call +// - ctx context.Context +func (_e *API_Expecter) SubscribeExecutionDataFromLatest(ctx interface{}) *API_SubscribeExecutionDataFromLatest_Call { + return &API_SubscribeExecutionDataFromLatest_Call{Call: _e.mock.On("SubscribeExecutionDataFromLatest", ctx)} +} + +func (_c *API_SubscribeExecutionDataFromLatest_Call) Run(run func(ctx context.Context)) *API_SubscribeExecutionDataFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *API_SubscribeExecutionDataFromLatest_Call) Return(subscription1 subscription.Subscription) *API_SubscribeExecutionDataFromLatest_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeExecutionDataFromLatest_Call) RunAndReturn(run func(ctx context.Context) subscription.Subscription) *API_SubscribeExecutionDataFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeExecutionDataFromStartBlockHeight provides a mock function for the type API +func (_mock *API) SubscribeExecutionDataFromStartBlockHeight(ctx context.Context, startBlockHeight uint64) subscription.Subscription { + ret := _mock.Called(ctx, startBlockHeight) if len(ret) == 0 { panic("no return value specified for SubscribeExecutionDataFromStartBlockHeight") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, uint64) subscription.Subscription); ok { - r0 = rf(ctx, startBlockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockHeight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// SubscribeExecutionDataFromStartBlockID provides a mock function with given fields: ctx, startBlockID -func (_m *API) SubscribeExecutionDataFromStartBlockID(ctx context.Context, startBlockID flow.Identifier) subscription.Subscription { - ret := _m.Called(ctx, startBlockID) +// API_SubscribeExecutionDataFromStartBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeExecutionDataFromStartBlockHeight' +type API_SubscribeExecutionDataFromStartBlockHeight_Call struct { + *mock.Call +} + +// SubscribeExecutionDataFromStartBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - startBlockHeight uint64 +func (_e *API_Expecter) SubscribeExecutionDataFromStartBlockHeight(ctx interface{}, startBlockHeight interface{}) *API_SubscribeExecutionDataFromStartBlockHeight_Call { + return &API_SubscribeExecutionDataFromStartBlockHeight_Call{Call: _e.mock.On("SubscribeExecutionDataFromStartBlockHeight", ctx, startBlockHeight)} +} + +func (_c *API_SubscribeExecutionDataFromStartBlockHeight_Call) Run(run func(ctx context.Context, startBlockHeight uint64)) *API_SubscribeExecutionDataFromStartBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SubscribeExecutionDataFromStartBlockHeight_Call) Return(subscription1 subscription.Subscription) *API_SubscribeExecutionDataFromStartBlockHeight_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeExecutionDataFromStartBlockHeight_Call) RunAndReturn(run func(ctx context.Context, startBlockHeight uint64) subscription.Subscription) *API_SubscribeExecutionDataFromStartBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeExecutionDataFromStartBlockID provides a mock function for the type API +func (_mock *API) SubscribeExecutionDataFromStartBlockID(ctx context.Context, startBlockID flow.Identifier) subscription.Subscription { + ret := _mock.Called(ctx, startBlockID) if len(ret) == 0 { panic("no return value specified for SubscribeExecutionDataFromStartBlockID") } var r0 subscription.Subscription - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) subscription.Subscription); ok { - r0 = rf(ctx, startBlockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) subscription.Subscription); ok { + r0 = returnFunc(ctx, startBlockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(subscription.Subscription) } } - return r0 } -// NewAPI creates a new instance of API. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *API { - mock := &API{} - mock.Mock.Test(t) +// API_SubscribeExecutionDataFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeExecutionDataFromStartBlockID' +type API_SubscribeExecutionDataFromStartBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubscribeExecutionDataFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +func (_e *API_Expecter) SubscribeExecutionDataFromStartBlockID(ctx interface{}, startBlockID interface{}) *API_SubscribeExecutionDataFromStartBlockID_Call { + return &API_SubscribeExecutionDataFromStartBlockID_Call{Call: _e.mock.On("SubscribeExecutionDataFromStartBlockID", ctx, startBlockID)} +} - return mock +func (_c *API_SubscribeExecutionDataFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier)) *API_SubscribeExecutionDataFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *API_SubscribeExecutionDataFromStartBlockID_Call) Return(subscription1 subscription.Subscription) *API_SubscribeExecutionDataFromStartBlockID_Call { + _c.Call.Return(subscription1) + return _c +} + +func (_c *API_SubscribeExecutionDataFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier) subscription.Subscription) *API_SubscribeExecutionDataFromStartBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/subscription/mock/streamable.go b/engine/access/subscription/mock/streamable.go index c4cd36a00e2..d3d194e2296 100644 --- a/engine/access/subscription/mock/streamable.go +++ b/engine/access/subscription/mock/streamable.go @@ -1,106 +1,281 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" + "time" mock "github.com/stretchr/testify/mock" - - time "time" ) +// NewStreamable creates a new instance of Streamable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStreamable(t interface { + mock.TestingT + Cleanup(func()) +}) *Streamable { + mock := &Streamable{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Streamable is an autogenerated mock type for the Streamable type type Streamable struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *Streamable) Close() { - _m.Called() +type Streamable_Expecter struct { + mock *mock.Mock +} + +func (_m *Streamable) EXPECT() *Streamable_Expecter { + return &Streamable_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type Streamable +func (_mock *Streamable) Close() { + _mock.Called() + return +} + +// Streamable_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type Streamable_Close_Call struct { + *mock.Call } -// Fail provides a mock function with given fields: _a0 -func (_m *Streamable) Fail(_a0 error) { - _m.Called(_a0) +// Close is a helper method to define mock.On call +func (_e *Streamable_Expecter) Close() *Streamable_Close_Call { + return &Streamable_Close_Call{Call: _e.mock.On("Close")} } -// ID provides a mock function with no fields -func (_m *Streamable) ID() string { - ret := _m.Called() +func (_c *Streamable_Close_Call) Run(run func()) *Streamable_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Streamable_Close_Call) Return() *Streamable_Close_Call { + _c.Call.Return() + return _c +} + +func (_c *Streamable_Close_Call) RunAndReturn(run func()) *Streamable_Close_Call { + _c.Run(run) + return _c +} + +// Fail provides a mock function for the type Streamable +func (_mock *Streamable) Fail(err error) { + _mock.Called(err) + return +} + +// Streamable_Fail_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Fail' +type Streamable_Fail_Call struct { + *mock.Call +} + +// Fail is a helper method to define mock.On call +// - err error +func (_e *Streamable_Expecter) Fail(err interface{}) *Streamable_Fail_Call { + return &Streamable_Fail_Call{Call: _e.mock.On("Fail", err)} +} + +func (_c *Streamable_Fail_Call) Run(run func(err error)) *Streamable_Fail_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 error + if args[0] != nil { + arg0 = args[0].(error) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Streamable_Fail_Call) Return() *Streamable_Fail_Call { + _c.Call.Return() + return _c +} + +func (_c *Streamable_Fail_Call) RunAndReturn(run func(err error)) *Streamable_Fail_Call { + _c.Run(run) + return _c +} + +// ID provides a mock function for the type Streamable +func (_mock *Streamable) ID() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// Next provides a mock function with given fields: _a0 -func (_m *Streamable) Next(_a0 context.Context) (interface{}, error) { - ret := _m.Called(_a0) +// Streamable_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type Streamable_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *Streamable_Expecter) ID() *Streamable_ID_Call { + return &Streamable_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *Streamable_ID_Call) Run(run func()) *Streamable_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Streamable_ID_Call) Return(s string) *Streamable_ID_Call { + _c.Call.Return(s) + return _c +} + +func (_c *Streamable_ID_Call) RunAndReturn(run func() string) *Streamable_ID_Call { + _c.Call.Return(run) + return _c +} + +// Next provides a mock function for the type Streamable +func (_mock *Streamable) Next(context1 context.Context) (any, error) { + ret := _mock.Called(context1) if len(ret) == 0 { panic("no return value specified for Next") } - var r0 interface{} + var r0 any var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (interface{}, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) (any, error)); ok { + return returnFunc(context1) } - if rf, ok := ret.Get(0).(func(context.Context) interface{}); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) any); ok { + r0 = returnFunc(context1) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(interface{}) + r0 = ret.Get(0).(any) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(context1) } else { r1 = ret.Error(1) } - return r0, r1 } -// Send provides a mock function with given fields: _a0, _a1, _a2 -func (_m *Streamable) Send(_a0 context.Context, _a1 interface{}, _a2 time.Duration) error { - ret := _m.Called(_a0, _a1, _a2) +// Streamable_Next_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Next' +type Streamable_Next_Call struct { + *mock.Call +} + +// Next is a helper method to define mock.On call +// - context1 context.Context +func (_e *Streamable_Expecter) Next(context1 interface{}) *Streamable_Next_Call { + return &Streamable_Next_Call{Call: _e.mock.On("Next", context1)} +} + +func (_c *Streamable_Next_Call) Run(run func(context1 context.Context)) *Streamable_Next_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Streamable_Next_Call) Return(v any, err error) *Streamable_Next_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Streamable_Next_Call) RunAndReturn(run func(context1 context.Context) (any, error)) *Streamable_Next_Call { + _c.Call.Return(run) + return _c +} + +// Send provides a mock function for the type Streamable +func (_mock *Streamable) Send(context1 context.Context, v any, duration time.Duration) error { + ret := _mock.Called(context1, v, duration) if len(ret) == 0 { panic("no return value specified for Send") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, interface{}, time.Duration) error); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(context.Context, any, time.Duration) error); ok { + r0 = returnFunc(context1, v, duration) } else { r0 = ret.Error(0) } - return r0 } -// NewStreamable creates a new instance of Streamable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStreamable(t interface { - mock.TestingT - Cleanup(func()) -}) *Streamable { - mock := &Streamable{} - mock.Mock.Test(t) +// Streamable_Send_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Send' +type Streamable_Send_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Send is a helper method to define mock.On call +// - context1 context.Context +// - v any +// - duration time.Duration +func (_e *Streamable_Expecter) Send(context1 interface{}, v interface{}, duration interface{}) *Streamable_Send_Call { + return &Streamable_Send_Call{Call: _e.mock.On("Send", context1, v, duration)} +} - return mock +func (_c *Streamable_Send_Call) Run(run func(context1 context.Context, v any, duration time.Duration)) *Streamable_Send_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 any + if args[1] != nil { + arg1 = args[1].(any) + } + var arg2 time.Duration + if args[2] != nil { + arg2 = args[2].(time.Duration) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Streamable_Send_Call) Return(err error) *Streamable_Send_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Streamable_Send_Call) RunAndReturn(run func(context1 context.Context, v any, duration time.Duration) error) *Streamable_Send_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/subscription/mock/subscription.go b/engine/access/subscription/mock/subscription.go index 467cd80f7cc..f3ad1b1cf83 100644 --- a/engine/access/subscription/mock/subscription.go +++ b/engine/access/subscription/mock/subscription.go @@ -1,80 +1,170 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewSubscription creates a new instance of Subscription. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscription(t interface { + mock.TestingT + Cleanup(func()) +}) *Subscription { + mock := &Subscription{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Subscription is an autogenerated mock type for the Subscription type type Subscription struct { mock.Mock } -// Channel provides a mock function with no fields -func (_m *Subscription) Channel() <-chan interface{} { - ret := _m.Called() +type Subscription_Expecter struct { + mock *mock.Mock +} + +func (_m *Subscription) EXPECT() *Subscription_Expecter { + return &Subscription_Expecter{mock: &_m.Mock} +} + +// Channel provides a mock function for the type Subscription +func (_mock *Subscription) Channel() <-chan any { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Channel") } - var r0 <-chan interface{} - if rf, ok := ret.Get(0).(func() <-chan interface{}); ok { - r0 = rf() + var r0 <-chan any + if returnFunc, ok := ret.Get(0).(func() <-chan any); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(<-chan interface{}) + r0 = ret.Get(0).(<-chan any) } } - return r0 } -// Err provides a mock function with no fields -func (_m *Subscription) Err() error { - ret := _m.Called() +// Subscription_Channel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Channel' +type Subscription_Channel_Call struct { + *mock.Call +} + +// Channel is a helper method to define mock.On call +func (_e *Subscription_Expecter) Channel() *Subscription_Channel_Call { + return &Subscription_Channel_Call{Call: _e.mock.On("Channel")} +} + +func (_c *Subscription_Channel_Call) Run(run func()) *Subscription_Channel_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Subscription_Channel_Call) Return(vCh <-chan any) *Subscription_Channel_Call { + _c.Call.Return(vCh) + return _c +} + +func (_c *Subscription_Channel_Call) RunAndReturn(run func() <-chan any) *Subscription_Channel_Call { + _c.Call.Return(run) + return _c +} + +// Err provides a mock function for the type Subscription +func (_mock *Subscription) Err() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Err") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// ID provides a mock function with no fields -func (_m *Subscription) ID() string { - ret := _m.Called() +// Subscription_Err_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Err' +type Subscription_Err_Call struct { + *mock.Call +} + +// Err is a helper method to define mock.On call +func (_e *Subscription_Expecter) Err() *Subscription_Err_Call { + return &Subscription_Err_Call{Call: _e.mock.On("Err")} +} + +func (_c *Subscription_Err_Call) Run(run func()) *Subscription_Err_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Subscription_Err_Call) Return(err error) *Subscription_Err_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Subscription_Err_Call) RunAndReturn(run func() error) *Subscription_Err_Call { + _c.Call.Return(run) + return _c +} + +// ID provides a mock function for the type Subscription +func (_mock *Subscription) ID() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// NewSubscription creates a new instance of Subscription. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSubscription(t interface { - mock.TestingT - Cleanup(func()) -}) *Subscription { - mock := &Subscription{} - mock.Mock.Test(t) +// Subscription_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type Subscription_ID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ID is a helper method to define mock.On call +func (_e *Subscription_Expecter) ID() *Subscription_ID_Call { + return &Subscription_ID_Call{Call: _e.mock.On("ID")} +} - return mock +func (_c *Subscription_ID_Call) Run(run func()) *Subscription_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Subscription_ID_Call) Return(s string) *Subscription_ID_Call { + _c.Call.Return(s) + return _c +} + +func (_c *Subscription_ID_Call) RunAndReturn(run func() string) *Subscription_ID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/subscription/streamer.go b/engine/access/subscription/streamer.go index 437028edc6c..5ae9eab8779 100644 --- a/engine/access/subscription/streamer.go +++ b/engine/access/subscription/streamer.go @@ -59,8 +59,17 @@ func (s *Streamer) Stream(ctx context.Context) { s.log.Debug().Msg("starting streaming") defer s.log.Debug().Msg("finished streaming") + // Check if context is already cancelled before subscribing to avoid leaking subscribers + select { + case <-ctx.Done(): + s.sub.Fail(fmt.Errorf("client disconnected before subscribe: %w", ctx.Err())) + return + default: + } + notifier := engine.NewNotifier() s.broadcaster.Subscribe(notifier) + defer s.broadcaster.Unsubscribe(notifier) // always check the first time. This ensures that streaming continues to work even if the // execution sync is not functioning (e.g. on a past spork network, or during an temporary outage) diff --git a/engine/access/subscription/streamer_test.go b/engine/access/subscription/streamer_test.go index bc6bc7df72f..671c04aae3c 100644 --- a/engine/access/subscription/streamer_test.go +++ b/engine/access/subscription/streamer_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "testing" + "testing/synctest" "time" "github.com/google/uuid" @@ -107,6 +108,157 @@ func TestStreamRatelimited(t *testing.T) { } } +// TestStreamUnsubscribesOnContextCancel tests that the streamer properly unsubscribes from the +// broadcaster when the context is cancelled, preventing subscriber leaks. +func TestStreamUnsubscribesOnContextCancel(t *testing.T) { + t.Parallel() + + timeout := subscription.DefaultSendTimeout + + t.Run("unsubscribes on context cancel", func(t *testing.T) { + t.Parallel() + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + + sub := submock.NewStreamable(t) + sub.On("ID").Return(uuid.NewString()) + // Mock Next to return ErrBlockNotReady so the stream waits for more notifications + sub.On("Next", mock.Anything).Return(nil, subscription.ErrBlockNotReady).Maybe() + sub.On("Fail", mock.Anything).Return().Once() + + broadcaster := engine.NewBroadcaster() + streamer := subscription.NewStreamer(unittest.Logger(), broadcaster, timeout, subscription.DefaultResponseLimit, sub) + + assert.Equal(t, 0, broadcaster.SubscriberCount()) + + // Start streaming in a goroutine + go streamer.Stream(ctx) + + // Wait for the stream to start and subscribe (blocks until goroutine is waiting) + synctest.Wait() + assert.Equal(t, 1, broadcaster.SubscriberCount()) + + // Cancel the context + cancel() + + // Wait for the stream to finish + synctest.Wait() + + // Verify subscriber was removed + assert.Equal(t, 0, broadcaster.SubscriberCount()) + }) + }) + + t.Run("unsubscribes on error", func(t *testing.T) { + t.Parallel() + ctx := context.Background() + + sub := submock.NewStreamable(t) + sub.On("ID").Return(uuid.NewString()) + sub.On("Next", mock.Anything).Return(nil, testErr).Once() + sub.On("Fail", mock.Anything).Return().Once() + + broadcaster := engine.NewBroadcaster() + streamer := subscription.NewStreamer(unittest.Logger(), broadcaster, timeout, subscription.DefaultResponseLimit, sub) + + assert.Equal(t, 0, broadcaster.SubscriberCount()) + + unittest.RequireReturnsBefore(t, func() { + streamer.Stream(ctx) + }, 100*time.Millisecond, "stream should finish") + + // Verify subscriber was removed after error + assert.Equal(t, 0, broadcaster.SubscriberCount()) + }) + + t.Run("unsubscribes on end of data", func(t *testing.T) { + t.Parallel() + ctx := context.Background() + + sub := submock.NewStreamable(t) + sub.On("ID").Return(uuid.NewString()) + sub.On("Next", mock.Anything).Return(nil, subscription.ErrEndOfData).Once() + sub.On("Close").Return().Once() + + broadcaster := engine.NewBroadcaster() + streamer := subscription.NewStreamer(unittest.Logger(), broadcaster, timeout, subscription.DefaultResponseLimit, sub) + + assert.Equal(t, 0, broadcaster.SubscriberCount()) + + unittest.RequireReturnsBefore(t, func() { + streamer.Stream(ctx) + }, 100*time.Millisecond, "stream should finish") + + // Verify subscriber was removed after end of data + assert.Equal(t, 0, broadcaster.SubscriberCount()) + }) + + t.Run("does not subscribe if context already cancelled", func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithCancel(context.Background()) + cancel() // Cancel before streaming starts + + sub := submock.NewStreamable(t) + sub.On("ID").Return(uuid.NewString()) + sub.On("Fail", mock.Anything).Return().Once() + + broadcaster := engine.NewBroadcaster() + streamer := subscription.NewStreamer(unittest.Logger(), broadcaster, timeout, subscription.DefaultResponseLimit, sub) + + assert.Equal(t, 0, broadcaster.SubscriberCount()) + + unittest.RequireReturnsBefore(t, func() { + streamer.Stream(ctx) + }, 100*time.Millisecond, "stream should finish immediately") + + // Verify no subscriber was ever added + assert.Equal(t, 0, broadcaster.SubscriberCount()) + }) + + t.Run("multiple streams subscribe and unsubscribe correctly", func(t *testing.T) { + t.Parallel() + synctest.Test(t, func(t *testing.T) { + broadcaster := engine.NewBroadcaster() + const numStreams = 10 + + cancels := make([]context.CancelFunc, numStreams) + + for i := 0; i < numStreams; i++ { + var ctx context.Context + ctx, cancels[i] = context.WithCancel(context.Background()) + + sub := submock.NewStreamable(t) + sub.On("ID").Return(uuid.NewString()) + // Mock Next to return ErrBlockNotReady so the stream waits for more notifications + sub.On("Next", mock.Anything).Return(nil, subscription.ErrBlockNotReady).Maybe() + sub.On("Fail", mock.Anything).Return().Once() + + streamer := subscription.NewStreamer(unittest.Logger(), broadcaster, timeout, subscription.DefaultResponseLimit, sub) + + go streamer.Stream(ctx) + } + + // Wait for all streams to start (blocks until all goroutines are waiting) + synctest.Wait() + assert.Equal(t, numStreams, broadcaster.SubscriberCount()) + + // Verify broadcast reaches all subscribers + broadcaster.Publish() + synctest.Wait() + + // Cancel streams one by one and verify count decreases + for i := 0; i < numStreams; i++ { + cancels[i]() + synctest.Wait() + assert.Equal(t, numStreams-i-1, broadcaster.SubscriberCount()) + } + + // Verify broadcasting to empty subscriber list works + broadcaster.Publish() + }) + }) +} + // TestLongStreamRatelimited tests that the streamer is uses the correct rate limit over a longer // period of time func TestLongStreamRatelimited(t *testing.T) { diff --git a/engine/access/subscription/streaming_data.go b/engine/access/subscription/streaming_data.go deleted file mode 100644 index 90fc9d0f788..00000000000 --- a/engine/access/subscription/streaming_data.go +++ /dev/null @@ -1,18 +0,0 @@ -package subscription - -import ( - "sync/atomic" -) - -// StreamingData represents common streaming data configuration for access and state_stream handlers. -type StreamingData struct { - MaxStreams int32 - StreamCount atomic.Int32 -} - -func NewStreamingData(maxStreams uint32) StreamingData { - return StreamingData{ - MaxStreams: int32(maxStreams), - StreamCount: atomic.Int32{}, - } -} diff --git a/engine/access/subscription/subscription.go b/engine/access/subscription/subscription.go index 3c5a12cee31..674e2bc1867 100644 --- a/engine/access/subscription/subscription.go +++ b/engine/access/subscription/subscription.go @@ -39,7 +39,7 @@ const ( // - storage.ErrNotFound // - execution_data.BlobNotFoundError // All other errors are considered exceptions -type GetDataByHeightFunc func(ctx context.Context, height uint64) (interface{}, error) +type GetDataByHeightFunc func(ctx context.Context, height uint64) (any, error) // Subscription represents a streaming request, and handles the communication between the grpc handler // and the backend implementation. @@ -48,7 +48,7 @@ type Subscription interface { ID() string // Channel returns the channel from which subscription data can be read - Channel() <-chan interface{} + Channel() <-chan any // Err returns the error that caused the subscription to fail Err() error @@ -67,9 +67,9 @@ type Streamable interface { // Expected errors: // - context.DeadlineExceeded if send timed out // - context.Canceled if the client disconnected - Send(context.Context, interface{}, time.Duration) error + Send(context.Context, any, time.Duration) error // Next returns the value for the next height from the subscription - Next(context.Context) (interface{}, error) + Next(context.Context) (any, error) } var _ Subscription = (*SubscriptionImpl)(nil) @@ -78,7 +78,7 @@ type SubscriptionImpl struct { id string // ch is the channel used to pass data to the receiver - ch chan interface{} + ch chan any // err is the error that caused the subscription to fail err error @@ -93,7 +93,7 @@ type SubscriptionImpl struct { func NewSubscription(bufferSize int) *SubscriptionImpl { return &SubscriptionImpl{ id: uuid.New().String(), - ch: make(chan interface{}, bufferSize), + ch: make(chan any, bufferSize), } } @@ -104,7 +104,7 @@ func (sub *SubscriptionImpl) ID() string { } // Channel returns the channel from which subscription data can be read -func (sub *SubscriptionImpl) Channel() <-chan interface{} { +func (sub *SubscriptionImpl) Channel() <-chan any { return sub.ch } @@ -131,7 +131,7 @@ func (sub *SubscriptionImpl) Close() { // Expected errors: // - context.DeadlineExceeded if send timed out // - context.Canceled if the client disconnected -func (sub *SubscriptionImpl) Send(ctx context.Context, v interface{}, timeout time.Duration) error { +func (sub *SubscriptionImpl) Send(ctx context.Context, v any, timeout time.Duration) error { if sub.closed { return fmt.Errorf("subscription closed") } @@ -182,7 +182,7 @@ func NewHeightBasedSubscription(bufferSize int, firstHeight uint64, getData GetD } // Next returns the value for the next height from the subscription -func (s *HeightBasedSubscription) Next(ctx context.Context) (interface{}, error) { +func (s *HeightBasedSubscription) Next(ctx context.Context) (any, error) { v, err := s.getData(ctx, s.nextHeight) if err != nil { return nil, fmt.Errorf("could not get data for height %d: %w", s.nextHeight, err) diff --git a/engine/access/subscription/tracker/mock/base_tracker.go b/engine/access/subscription/tracker/mock/base_tracker.go index 1b3c125b5fb..5ca22a9f630 100644 --- a/engine/access/subscription/tracker/mock/base_tracker.go +++ b/engine/access/subscription/tracker/mock/base_tracker.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBaseTracker creates a new instance of BaseTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBaseTracker(t interface { + mock.TestingT + Cleanup(func()) +}) *BaseTracker { + mock := &BaseTracker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BaseTracker is an autogenerated mock type for the BaseTracker type type BaseTracker struct { mock.Mock } -// GetStartHeightFromBlockID provides a mock function with given fields: _a0 -func (_m *BaseTracker) GetStartHeightFromBlockID(_a0 flow.Identifier) (uint64, error) { - ret := _m.Called(_a0) +type BaseTracker_Expecter struct { + mock *mock.Mock +} + +func (_m *BaseTracker) EXPECT() *BaseTracker_Expecter { + return &BaseTracker_Expecter{mock: &_m.Mock} +} + +// GetStartHeightFromBlockID provides a mock function for the type BaseTracker +func (_mock *BaseTracker) GetStartHeightFromBlockID(identifier flow.Identifier) (uint64, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromBlockID") @@ -24,27 +48,59 @@ func (_m *BaseTracker) GetStartHeightFromBlockID(_a0 flow.Identifier) (uint64, e var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (uint64, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromHeight provides a mock function with given fields: _a0 -func (_m *BaseTracker) GetStartHeightFromHeight(_a0 uint64) (uint64, error) { - ret := _m.Called(_a0) +// BaseTracker_GetStartHeightFromBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromBlockID' +type BaseTracker_GetStartHeightFromBlockID_Call struct { + *mock.Call +} + +// GetStartHeightFromBlockID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *BaseTracker_Expecter) GetStartHeightFromBlockID(identifier interface{}) *BaseTracker_GetStartHeightFromBlockID_Call { + return &BaseTracker_GetStartHeightFromBlockID_Call{Call: _e.mock.On("GetStartHeightFromBlockID", identifier)} +} + +func (_c *BaseTracker_GetStartHeightFromBlockID_Call) Run(run func(identifier flow.Identifier)) *BaseTracker_GetStartHeightFromBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BaseTracker_GetStartHeightFromBlockID_Call) Return(v uint64, err error) *BaseTracker_GetStartHeightFromBlockID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BaseTracker_GetStartHeightFromBlockID_Call) RunAndReturn(run func(identifier flow.Identifier) (uint64, error)) *BaseTracker_GetStartHeightFromBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromHeight provides a mock function for the type BaseTracker +func (_mock *BaseTracker) GetStartHeightFromHeight(v uint64) (uint64, error) { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromHeight") @@ -52,27 +108,59 @@ func (_m *BaseTracker) GetStartHeightFromHeight(_a0 uint64) (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(v) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(v) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(v) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromLatest provides a mock function with given fields: _a0 -func (_m *BaseTracker) GetStartHeightFromLatest(_a0 context.Context) (uint64, error) { - ret := _m.Called(_a0) +// BaseTracker_GetStartHeightFromHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromHeight' +type BaseTracker_GetStartHeightFromHeight_Call struct { + *mock.Call +} + +// GetStartHeightFromHeight is a helper method to define mock.On call +// - v uint64 +func (_e *BaseTracker_Expecter) GetStartHeightFromHeight(v interface{}) *BaseTracker_GetStartHeightFromHeight_Call { + return &BaseTracker_GetStartHeightFromHeight_Call{Call: _e.mock.On("GetStartHeightFromHeight", v)} +} + +func (_c *BaseTracker_GetStartHeightFromHeight_Call) Run(run func(v uint64)) *BaseTracker_GetStartHeightFromHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BaseTracker_GetStartHeightFromHeight_Call) Return(v1 uint64, err error) *BaseTracker_GetStartHeightFromHeight_Call { + _c.Call.Return(v1, err) + return _c +} + +func (_c *BaseTracker_GetStartHeightFromHeight_Call) RunAndReturn(run func(v uint64) (uint64, error)) *BaseTracker_GetStartHeightFromHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromLatest provides a mock function for the type BaseTracker +func (_mock *BaseTracker) GetStartHeightFromLatest(context1 context.Context) (uint64, error) { + ret := _mock.Called(context1) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromLatest") @@ -80,34 +168,52 @@ func (_m *BaseTracker) GetStartHeightFromLatest(_a0 context.Context) (uint64, er var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { + return returnFunc(context1) } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) uint64); ok { + r0 = returnFunc(context1) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(context1) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBaseTracker creates a new instance of BaseTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBaseTracker(t interface { - mock.TestingT - Cleanup(func()) -}) *BaseTracker { - mock := &BaseTracker{} - mock.Mock.Test(t) +// BaseTracker_GetStartHeightFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromLatest' +type BaseTracker_GetStartHeightFromLatest_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetStartHeightFromLatest is a helper method to define mock.On call +// - context1 context.Context +func (_e *BaseTracker_Expecter) GetStartHeightFromLatest(context1 interface{}) *BaseTracker_GetStartHeightFromLatest_Call { + return &BaseTracker_GetStartHeightFromLatest_Call{Call: _e.mock.On("GetStartHeightFromLatest", context1)} +} - return mock +func (_c *BaseTracker_GetStartHeightFromLatest_Call) Run(run func(context1 context.Context)) *BaseTracker_GetStartHeightFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BaseTracker_GetStartHeightFromLatest_Call) Return(v uint64, err error) *BaseTracker_GetStartHeightFromLatest_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BaseTracker_GetStartHeightFromLatest_Call) RunAndReturn(run func(context1 context.Context) (uint64, error)) *BaseTracker_GetStartHeightFromLatest_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/subscription/tracker/mock/block_tracker.go b/engine/access/subscription/tracker/mock/block_tracker.go index b1481656bd9..27aaecd2d64 100644 --- a/engine/access/subscription/tracker/mock/block_tracker.go +++ b/engine/access/subscription/tracker/mock/block_tracker.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBlockTracker creates a new instance of BlockTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockTracker(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockTracker { + mock := &BlockTracker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BlockTracker is an autogenerated mock type for the BlockTracker type type BlockTracker struct { mock.Mock } -// GetHighestHeight provides a mock function with given fields: _a0 -func (_m *BlockTracker) GetHighestHeight(_a0 flow.BlockStatus) (uint64, error) { - ret := _m.Called(_a0) +type BlockTracker_Expecter struct { + mock *mock.Mock +} + +func (_m *BlockTracker) EXPECT() *BlockTracker_Expecter { + return &BlockTracker_Expecter{mock: &_m.Mock} +} + +// GetHighestHeight provides a mock function for the type BlockTracker +func (_mock *BlockTracker) GetHighestHeight(blockStatus flow.BlockStatus) (uint64, error) { + ret := _mock.Called(blockStatus) if len(ret) == 0 { panic("no return value specified for GetHighestHeight") @@ -24,27 +48,59 @@ func (_m *BlockTracker) GetHighestHeight(_a0 flow.BlockStatus) (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.BlockStatus) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.BlockStatus) (uint64, error)); ok { + return returnFunc(blockStatus) } - if rf, ok := ret.Get(0).(func(flow.BlockStatus) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.BlockStatus) uint64); ok { + r0 = returnFunc(blockStatus) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.BlockStatus) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.BlockStatus) error); ok { + r1 = returnFunc(blockStatus) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromBlockID provides a mock function with given fields: _a0 -func (_m *BlockTracker) GetStartHeightFromBlockID(_a0 flow.Identifier) (uint64, error) { - ret := _m.Called(_a0) +// BlockTracker_GetHighestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetHighestHeight' +type BlockTracker_GetHighestHeight_Call struct { + *mock.Call +} + +// GetHighestHeight is a helper method to define mock.On call +// - blockStatus flow.BlockStatus +func (_e *BlockTracker_Expecter) GetHighestHeight(blockStatus interface{}) *BlockTracker_GetHighestHeight_Call { + return &BlockTracker_GetHighestHeight_Call{Call: _e.mock.On("GetHighestHeight", blockStatus)} +} + +func (_c *BlockTracker_GetHighestHeight_Call) Run(run func(blockStatus flow.BlockStatus)) *BlockTracker_GetHighestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.BlockStatus + if args[0] != nil { + arg0 = args[0].(flow.BlockStatus) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockTracker_GetHighestHeight_Call) Return(v uint64, err error) *BlockTracker_GetHighestHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BlockTracker_GetHighestHeight_Call) RunAndReturn(run func(blockStatus flow.BlockStatus) (uint64, error)) *BlockTracker_GetHighestHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromBlockID provides a mock function for the type BlockTracker +func (_mock *BlockTracker) GetStartHeightFromBlockID(identifier flow.Identifier) (uint64, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromBlockID") @@ -52,27 +108,59 @@ func (_m *BlockTracker) GetStartHeightFromBlockID(_a0 flow.Identifier) (uint64, var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (uint64, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromHeight provides a mock function with given fields: _a0 -func (_m *BlockTracker) GetStartHeightFromHeight(_a0 uint64) (uint64, error) { - ret := _m.Called(_a0) +// BlockTracker_GetStartHeightFromBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromBlockID' +type BlockTracker_GetStartHeightFromBlockID_Call struct { + *mock.Call +} + +// GetStartHeightFromBlockID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *BlockTracker_Expecter) GetStartHeightFromBlockID(identifier interface{}) *BlockTracker_GetStartHeightFromBlockID_Call { + return &BlockTracker_GetStartHeightFromBlockID_Call{Call: _e.mock.On("GetStartHeightFromBlockID", identifier)} +} + +func (_c *BlockTracker_GetStartHeightFromBlockID_Call) Run(run func(identifier flow.Identifier)) *BlockTracker_GetStartHeightFromBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockTracker_GetStartHeightFromBlockID_Call) Return(v uint64, err error) *BlockTracker_GetStartHeightFromBlockID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BlockTracker_GetStartHeightFromBlockID_Call) RunAndReturn(run func(identifier flow.Identifier) (uint64, error)) *BlockTracker_GetStartHeightFromBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromHeight provides a mock function for the type BlockTracker +func (_mock *BlockTracker) GetStartHeightFromHeight(v uint64) (uint64, error) { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromHeight") @@ -80,27 +168,59 @@ func (_m *BlockTracker) GetStartHeightFromHeight(_a0 uint64) (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(v) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(v) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(v) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromLatest provides a mock function with given fields: _a0 -func (_m *BlockTracker) GetStartHeightFromLatest(_a0 context.Context) (uint64, error) { - ret := _m.Called(_a0) +// BlockTracker_GetStartHeightFromHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromHeight' +type BlockTracker_GetStartHeightFromHeight_Call struct { + *mock.Call +} + +// GetStartHeightFromHeight is a helper method to define mock.On call +// - v uint64 +func (_e *BlockTracker_Expecter) GetStartHeightFromHeight(v interface{}) *BlockTracker_GetStartHeightFromHeight_Call { + return &BlockTracker_GetStartHeightFromHeight_Call{Call: _e.mock.On("GetStartHeightFromHeight", v)} +} + +func (_c *BlockTracker_GetStartHeightFromHeight_Call) Run(run func(v uint64)) *BlockTracker_GetStartHeightFromHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockTracker_GetStartHeightFromHeight_Call) Return(v1 uint64, err error) *BlockTracker_GetStartHeightFromHeight_Call { + _c.Call.Return(v1, err) + return _c +} + +func (_c *BlockTracker_GetStartHeightFromHeight_Call) RunAndReturn(run func(v uint64) (uint64, error)) *BlockTracker_GetStartHeightFromHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromLatest provides a mock function for the type BlockTracker +func (_mock *BlockTracker) GetStartHeightFromLatest(context1 context.Context) (uint64, error) { + ret := _mock.Called(context1) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromLatest") @@ -108,52 +228,96 @@ func (_m *BlockTracker) GetStartHeightFromLatest(_a0 context.Context) (uint64, e var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { + return returnFunc(context1) } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) uint64); ok { + r0 = returnFunc(context1) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(context1) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProcessOnFinalizedBlock provides a mock function with no fields -func (_m *BlockTracker) ProcessOnFinalizedBlock() error { - ret := _m.Called() +// BlockTracker_GetStartHeightFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromLatest' +type BlockTracker_GetStartHeightFromLatest_Call struct { + *mock.Call +} + +// GetStartHeightFromLatest is a helper method to define mock.On call +// - context1 context.Context +func (_e *BlockTracker_Expecter) GetStartHeightFromLatest(context1 interface{}) *BlockTracker_GetStartHeightFromLatest_Call { + return &BlockTracker_GetStartHeightFromLatest_Call{Call: _e.mock.On("GetStartHeightFromLatest", context1)} +} + +func (_c *BlockTracker_GetStartHeightFromLatest_Call) Run(run func(context1 context.Context)) *BlockTracker_GetStartHeightFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockTracker_GetStartHeightFromLatest_Call) Return(v uint64, err error) *BlockTracker_GetStartHeightFromLatest_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BlockTracker_GetStartHeightFromLatest_Call) RunAndReturn(run func(context1 context.Context) (uint64, error)) *BlockTracker_GetStartHeightFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// ProcessOnFinalizedBlock provides a mock function for the type BlockTracker +func (_mock *BlockTracker) ProcessOnFinalizedBlock() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ProcessOnFinalizedBlock") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// NewBlockTracker creates a new instance of BlockTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockTracker(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockTracker { - mock := &BlockTracker{} - mock.Mock.Test(t) +// BlockTracker_ProcessOnFinalizedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessOnFinalizedBlock' +type BlockTracker_ProcessOnFinalizedBlock_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ProcessOnFinalizedBlock is a helper method to define mock.On call +func (_e *BlockTracker_Expecter) ProcessOnFinalizedBlock() *BlockTracker_ProcessOnFinalizedBlock_Call { + return &BlockTracker_ProcessOnFinalizedBlock_Call{Call: _e.mock.On("ProcessOnFinalizedBlock")} +} - return mock +func (_c *BlockTracker_ProcessOnFinalizedBlock_Call) Run(run func()) *BlockTracker_ProcessOnFinalizedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BlockTracker_ProcessOnFinalizedBlock_Call) Return(err error) *BlockTracker_ProcessOnFinalizedBlock_Call { + _c.Call.Return(err) + return _c +} + +func (_c *BlockTracker_ProcessOnFinalizedBlock_Call) RunAndReturn(run func() error) *BlockTracker_ProcessOnFinalizedBlock_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/access/subscription/tracker/mock/execution_data_tracker.go b/engine/access/subscription/tracker/mock/execution_data_tracker.go index ccfad6bc8b4..6f879326f2f 100644 --- a/engine/access/subscription/tracker/mock/execution_data_tracker.go +++ b/engine/access/subscription/tracker/mock/execution_data_tracker.go @@ -1,42 +1,91 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "context" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataTracker creates a new instance of ExecutionDataTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataTracker(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataTracker { + mock := &ExecutionDataTracker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataTracker is an autogenerated mock type for the ExecutionDataTracker type type ExecutionDataTracker struct { mock.Mock } -// GetHighestHeight provides a mock function with no fields -func (_m *ExecutionDataTracker) GetHighestHeight() uint64 { - ret := _m.Called() +type ExecutionDataTracker_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionDataTracker) EXPECT() *ExecutionDataTracker_Expecter { + return &ExecutionDataTracker_Expecter{mock: &_m.Mock} +} + +// GetHighestHeight provides a mock function for the type ExecutionDataTracker +func (_mock *ExecutionDataTracker) GetHighestHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetHighestHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetStartHeight provides a mock function with given fields: _a0, _a1, _a2 -func (_m *ExecutionDataTracker) GetStartHeight(_a0 context.Context, _a1 flow.Identifier, _a2 uint64) (uint64, error) { - ret := _m.Called(_a0, _a1, _a2) +// ExecutionDataTracker_GetHighestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetHighestHeight' +type ExecutionDataTracker_GetHighestHeight_Call struct { + *mock.Call +} + +// GetHighestHeight is a helper method to define mock.On call +func (_e *ExecutionDataTracker_Expecter) GetHighestHeight() *ExecutionDataTracker_GetHighestHeight_Call { + return &ExecutionDataTracker_GetHighestHeight_Call{Call: _e.mock.On("GetHighestHeight")} +} + +func (_c *ExecutionDataTracker_GetHighestHeight_Call) Run(run func()) *ExecutionDataTracker_GetHighestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataTracker_GetHighestHeight_Call) Return(v uint64) *ExecutionDataTracker_GetHighestHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ExecutionDataTracker_GetHighestHeight_Call) RunAndReturn(run func() uint64) *ExecutionDataTracker_GetHighestHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeight provides a mock function for the type ExecutionDataTracker +func (_mock *ExecutionDataTracker) GetStartHeight(context1 context.Context, identifier flow.Identifier, v uint64) (uint64, error) { + ret := _mock.Called(context1, identifier, v) if len(ret) == 0 { panic("no return value specified for GetStartHeight") @@ -44,27 +93,71 @@ func (_m *ExecutionDataTracker) GetStartHeight(_a0 context.Context, _a1 flow.Ide var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) (uint64, error)); ok { - return rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) (uint64, error)); ok { + return returnFunc(context1, identifier, v) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) uint64); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint64) uint64); ok { + r0 = returnFunc(context1, identifier, v) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint64) error); ok { - r1 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint64) error); ok { + r1 = returnFunc(context1, identifier, v) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromBlockID provides a mock function with given fields: _a0 -func (_m *ExecutionDataTracker) GetStartHeightFromBlockID(_a0 flow.Identifier) (uint64, error) { - ret := _m.Called(_a0) +// ExecutionDataTracker_GetStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeight' +type ExecutionDataTracker_GetStartHeight_Call struct { + *mock.Call +} + +// GetStartHeight is a helper method to define mock.On call +// - context1 context.Context +// - identifier flow.Identifier +// - v uint64 +func (_e *ExecutionDataTracker_Expecter) GetStartHeight(context1 interface{}, identifier interface{}, v interface{}) *ExecutionDataTracker_GetStartHeight_Call { + return &ExecutionDataTracker_GetStartHeight_Call{Call: _e.mock.On("GetStartHeight", context1, identifier, v)} +} + +func (_c *ExecutionDataTracker_GetStartHeight_Call) Run(run func(context1 context.Context, identifier flow.Identifier, v uint64)) *ExecutionDataTracker_GetStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ExecutionDataTracker_GetStartHeight_Call) Return(v1 uint64, err error) *ExecutionDataTracker_GetStartHeight_Call { + _c.Call.Return(v1, err) + return _c +} + +func (_c *ExecutionDataTracker_GetStartHeight_Call) RunAndReturn(run func(context1 context.Context, identifier flow.Identifier, v uint64) (uint64, error)) *ExecutionDataTracker_GetStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromBlockID provides a mock function for the type ExecutionDataTracker +func (_mock *ExecutionDataTracker) GetStartHeightFromBlockID(identifier flow.Identifier) (uint64, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromBlockID") @@ -72,27 +165,59 @@ func (_m *ExecutionDataTracker) GetStartHeightFromBlockID(_a0 flow.Identifier) ( var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (uint64, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromHeight provides a mock function with given fields: _a0 -func (_m *ExecutionDataTracker) GetStartHeightFromHeight(_a0 uint64) (uint64, error) { - ret := _m.Called(_a0) +// ExecutionDataTracker_GetStartHeightFromBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromBlockID' +type ExecutionDataTracker_GetStartHeightFromBlockID_Call struct { + *mock.Call +} + +// GetStartHeightFromBlockID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ExecutionDataTracker_Expecter) GetStartHeightFromBlockID(identifier interface{}) *ExecutionDataTracker_GetStartHeightFromBlockID_Call { + return &ExecutionDataTracker_GetStartHeightFromBlockID_Call{Call: _e.mock.On("GetStartHeightFromBlockID", identifier)} +} + +func (_c *ExecutionDataTracker_GetStartHeightFromBlockID_Call) Run(run func(identifier flow.Identifier)) *ExecutionDataTracker_GetStartHeightFromBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionDataTracker_GetStartHeightFromBlockID_Call) Return(v uint64, err error) *ExecutionDataTracker_GetStartHeightFromBlockID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ExecutionDataTracker_GetStartHeightFromBlockID_Call) RunAndReturn(run func(identifier flow.Identifier) (uint64, error)) *ExecutionDataTracker_GetStartHeightFromBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromHeight provides a mock function for the type ExecutionDataTracker +func (_mock *ExecutionDataTracker) GetStartHeightFromHeight(v uint64) (uint64, error) { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromHeight") @@ -100,27 +225,59 @@ func (_m *ExecutionDataTracker) GetStartHeightFromHeight(_a0 uint64) (uint64, er var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(v) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(v) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(v) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStartHeightFromLatest provides a mock function with given fields: _a0 -func (_m *ExecutionDataTracker) GetStartHeightFromLatest(_a0 context.Context) (uint64, error) { - ret := _m.Called(_a0) +// ExecutionDataTracker_GetStartHeightFromHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromHeight' +type ExecutionDataTracker_GetStartHeightFromHeight_Call struct { + *mock.Call +} + +// GetStartHeightFromHeight is a helper method to define mock.On call +// - v uint64 +func (_e *ExecutionDataTracker_Expecter) GetStartHeightFromHeight(v interface{}) *ExecutionDataTracker_GetStartHeightFromHeight_Call { + return &ExecutionDataTracker_GetStartHeightFromHeight_Call{Call: _e.mock.On("GetStartHeightFromHeight", v)} +} + +func (_c *ExecutionDataTracker_GetStartHeightFromHeight_Call) Run(run func(v uint64)) *ExecutionDataTracker_GetStartHeightFromHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionDataTracker_GetStartHeightFromHeight_Call) Return(v1 uint64, err error) *ExecutionDataTracker_GetStartHeightFromHeight_Call { + _c.Call.Return(v1, err) + return _c +} + +func (_c *ExecutionDataTracker_GetStartHeightFromHeight_Call) RunAndReturn(run func(v uint64) (uint64, error)) *ExecutionDataTracker_GetStartHeightFromHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetStartHeightFromLatest provides a mock function for the type ExecutionDataTracker +func (_mock *ExecutionDataTracker) GetStartHeightFromLatest(context1 context.Context) (uint64, error) { + ret := _mock.Called(context1) if len(ret) == 0 { panic("no return value specified for GetStartHeightFromLatest") @@ -128,39 +285,92 @@ func (_m *ExecutionDataTracker) GetStartHeightFromLatest(_a0 context.Context) (u var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { + return returnFunc(context1) } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) uint64); ok { + r0 = returnFunc(context1) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(context1) } else { r1 = ret.Error(1) } - return r0, r1 } -// OnExecutionData provides a mock function with given fields: _a0 -func (_m *ExecutionDataTracker) OnExecutionData(_a0 *execution_data.BlockExecutionDataEntity) { - _m.Called(_a0) +// ExecutionDataTracker_GetStartHeightFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStartHeightFromLatest' +type ExecutionDataTracker_GetStartHeightFromLatest_Call struct { + *mock.Call } -// NewExecutionDataTracker creates a new instance of ExecutionDataTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataTracker(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataTracker { - mock := &ExecutionDataTracker{} - mock.Mock.Test(t) +// GetStartHeightFromLatest is a helper method to define mock.On call +// - context1 context.Context +func (_e *ExecutionDataTracker_Expecter) GetStartHeightFromLatest(context1 interface{}) *ExecutionDataTracker_GetStartHeightFromLatest_Call { + return &ExecutionDataTracker_GetStartHeightFromLatest_Call{Call: _e.mock.On("GetStartHeightFromLatest", context1)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ExecutionDataTracker_GetStartHeightFromLatest_Call) Run(run func(context1 context.Context)) *ExecutionDataTracker_GetStartHeightFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *ExecutionDataTracker_GetStartHeightFromLatest_Call) Return(v uint64, err error) *ExecutionDataTracker_GetStartHeightFromLatest_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ExecutionDataTracker_GetStartHeightFromLatest_Call) RunAndReturn(run func(context1 context.Context) (uint64, error)) *ExecutionDataTracker_GetStartHeightFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// OnExecutionData provides a mock function for the type ExecutionDataTracker +func (_mock *ExecutionDataTracker) OnExecutionData(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity) { + _mock.Called(blockExecutionDataEntity) + return +} + +// ExecutionDataTracker_OnExecutionData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnExecutionData' +type ExecutionDataTracker_OnExecutionData_Call struct { + *mock.Call +} + +// OnExecutionData is a helper method to define mock.On call +// - blockExecutionDataEntity *execution_data.BlockExecutionDataEntity +func (_e *ExecutionDataTracker_Expecter) OnExecutionData(blockExecutionDataEntity interface{}) *ExecutionDataTracker_OnExecutionData_Call { + return &ExecutionDataTracker_OnExecutionData_Call{Call: _e.mock.On("OnExecutionData", blockExecutionDataEntity)} +} + +func (_c *ExecutionDataTracker_OnExecutionData_Call) Run(run func(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity)) *ExecutionDataTracker_OnExecutionData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *execution_data.BlockExecutionDataEntity + if args[0] != nil { + arg0 = args[0].(*execution_data.BlockExecutionDataEntity) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionDataTracker_OnExecutionData_Call) Return() *ExecutionDataTracker_OnExecutionData_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataTracker_OnExecutionData_Call) RunAndReturn(run func(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity)) *ExecutionDataTracker_OnExecutionData_Call { + _c.Run(run) + return _c } diff --git a/engine/access/subscription/util.go b/engine/access/subscription/util.go index 6ecfeeb8b16..2b7ebf75fe1 100644 --- a/engine/access/subscription/util.go +++ b/engine/access/subscription/util.go @@ -41,7 +41,7 @@ func HandleSubscription[T any](sub Subscription, handleResponse func(resp T) err // - transform: A function to transform the response into the expected interface{} type. // // No errors are expected during normal operations. -func HandleResponse[T any](send chan<- interface{}, transform func(resp T) (interface{}, error)) func(resp T) error { +func HandleResponse[T any](send chan<- any, transform func(resp T) (any, error)) func(resp T) error { return func(response T) error { // Transform the response resp, err := transform(response) diff --git a/engine/broadcaster.go b/engine/broadcaster.go index dfca6e03933..79b5be5bd3c 100644 --- a/engine/broadcaster.go +++ b/engine/broadcaster.go @@ -30,6 +30,31 @@ func (b *Broadcaster) Subscribe(n Notifiable) { b.subscribers = append(b.subscribers, n) } +// Unsubscribe removes a Notifier from the list of subscribers. If the subscriber is not found, +// this is a no-op. +func (b *Broadcaster) Unsubscribe(n Notifiable) { + b.mu.Lock() + defer b.mu.Unlock() + + for i, sub := range b.subscribers { + if sub == n { + // Remove by swapping with the last element and truncating + b.subscribers[i] = b.subscribers[len(b.subscribers)-1] + b.subscribers[len(b.subscribers)-1] = nil // Allow GC + b.subscribers = b.subscribers[:len(b.subscribers)-1] + return + } + } +} + +// SubscriberCount returns the current number of subscribers. +func (b *Broadcaster) SubscriberCount() int { + b.mu.RLock() + defer b.mu.RUnlock() + + return len(b.subscribers) +} + // Publish sends notifications to all subscribers func (b *Broadcaster) Publish() { b.mu.RLock() diff --git a/engine/broadcaster_test.go b/engine/broadcaster_test.go index 5e5d8089d1f..e6f999a4693 100644 --- a/engine/broadcaster_test.go +++ b/engine/broadcaster_test.go @@ -13,6 +13,114 @@ import ( "github.com/onflow/flow-go/utils/unittest" ) +func TestUnsubscribe(t *testing.T) { + t.Parallel() + + t.Run("unsubscribe removes subscriber", func(t *testing.T) { + t.Parallel() + b := engine.NewBroadcaster() + + notifier1 := engine.NewNotifier() + notifier2 := engine.NewNotifier() + notifier3 := engine.NewNotifier() + + b.Subscribe(notifier1) + b.Subscribe(notifier2) + b.Subscribe(notifier3) + + assert.Equal(t, 3, b.SubscriberCount()) + + b.Unsubscribe(notifier2) + assert.Equal(t, 2, b.SubscriberCount()) + + // Verify remaining subscribers still receive notifications + received1 := make(chan struct{}, 1) + received3 := make(chan struct{}, 1) + + go func() { + <-notifier1.Channel() + received1 <- struct{}{} + }() + go func() { + <-notifier3.Channel() + received3 <- struct{}{} + }() + + b.Publish() + + unittest.RequireReturnsBefore(t, func() { <-received1 }, 100*time.Millisecond, "notifier1 should receive") + unittest.RequireReturnsBefore(t, func() { <-received3 }, 100*time.Millisecond, "notifier3 should receive") + }) + + t.Run("unsubscribe non-existent subscriber is no-op", func(t *testing.T) { + t.Parallel() + b := engine.NewBroadcaster() + + notifier1 := engine.NewNotifier() + notifier2 := engine.NewNotifier() + + b.Subscribe(notifier1) + assert.Equal(t, 1, b.SubscriberCount()) + + // Unsubscribe a notifier that was never subscribed + b.Unsubscribe(notifier2) + assert.Equal(t, 1, b.SubscriberCount()) + }) + + t.Run("unsubscribe same subscriber twice is no-op", func(t *testing.T) { + t.Parallel() + b := engine.NewBroadcaster() + + notifier := engine.NewNotifier() + + b.Subscribe(notifier) + assert.Equal(t, 1, b.SubscriberCount()) + + b.Unsubscribe(notifier) + assert.Equal(t, 0, b.SubscriberCount()) + + // Unsubscribe again should be a no-op + b.Unsubscribe(notifier) + assert.Equal(t, 0, b.SubscriberCount()) + }) + + t.Run("concurrent subscribe and unsubscribe", func(t *testing.T) { + t.Parallel() + b := engine.NewBroadcaster() + + const numOperations = 100 + notifiers := make([]engine.Notifier, numOperations) + for i := 0; i < numOperations; i++ { + notifiers[i] = engine.NewNotifier() + } + + // Subscribe all notifiers concurrently + var wg sync.WaitGroup + wg.Add(numOperations) + for i := 0; i < numOperations; i++ { + go func(n engine.Notifier) { + defer wg.Done() + b.Subscribe(n) + }(notifiers[i]) + } + wg.Wait() + + assert.Equal(t, numOperations, b.SubscriberCount()) + + // Unsubscribe all notifiers concurrently + wg.Add(numOperations) + for i := 0; i < numOperations; i++ { + go func(n engine.Notifier) { + defer wg.Done() + b.Unsubscribe(n) + }(notifiers[i]) + } + wg.Wait() + + assert.Equal(t, 0, b.SubscriberCount()) + }) +} + func TestPublish(t *testing.T) { t.Parallel() diff --git a/engine/collection/epochmgr/mock/epoch_components_factory.go b/engine/collection/epochmgr/mock/epoch_components_factory.go index 4e58c01c41a..75d21a28f45 100644 --- a/engine/collection/epochmgr/mock/epoch_components_factory.go +++ b/engine/collection/epochmgr/mock/epoch_components_factory.go @@ -1,28 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - component "github.com/onflow/flow-go/module/component" - cluster "github.com/onflow/flow-go/state/cluster" - - hotstuff "github.com/onflow/flow-go/consensus/hotstuff" - + "github.com/onflow/flow-go/consensus/hotstuff" + "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/state/cluster" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" +) - module "github.com/onflow/flow-go/module" +// NewEpochComponentsFactory creates a new instance of EpochComponentsFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochComponentsFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochComponentsFactory { + mock := &EpochComponentsFactory{} + mock.Mock.Test(t) - protocol "github.com/onflow/flow-go/state/protocol" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EpochComponentsFactory is an autogenerated mock type for the EpochComponentsFactory type type EpochComponentsFactory struct { mock.Mock } -// Create provides a mock function with given fields: epoch -func (_m *EpochComponentsFactory) Create(epoch protocol.CommittedEpoch) (cluster.State, component.Component, module.ReadyDoneAware, module.HotStuff, hotstuff.VoteAggregator, hotstuff.TimeoutAggregator, component.Component, error) { - ret := _m.Called(epoch) +type EpochComponentsFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochComponentsFactory) EXPECT() *EpochComponentsFactory_Expecter { + return &EpochComponentsFactory_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type EpochComponentsFactory +func (_mock *EpochComponentsFactory) Create(epoch protocol.CommittedEpoch) (cluster.State, component.Component, module.ReadyDoneAware, module.HotStuff, hotstuff.VoteAggregator, hotstuff.TimeoutAggregator, component.Component, error) { + ret := _mock.Called(epoch) if len(ret) == 0 { panic("no return value specified for Create") @@ -36,84 +56,96 @@ func (_m *EpochComponentsFactory) Create(epoch protocol.CommittedEpoch) (cluster var r5 hotstuff.TimeoutAggregator var r6 component.Component var r7 error - if rf, ok := ret.Get(0).(func(protocol.CommittedEpoch) (cluster.State, component.Component, module.ReadyDoneAware, module.HotStuff, hotstuff.VoteAggregator, hotstuff.TimeoutAggregator, component.Component, error)); ok { - return rf(epoch) + if returnFunc, ok := ret.Get(0).(func(protocol.CommittedEpoch) (cluster.State, component.Component, module.ReadyDoneAware, module.HotStuff, hotstuff.VoteAggregator, hotstuff.TimeoutAggregator, component.Component, error)); ok { + return returnFunc(epoch) } - if rf, ok := ret.Get(0).(func(protocol.CommittedEpoch) cluster.State); ok { - r0 = rf(epoch) + if returnFunc, ok := ret.Get(0).(func(protocol.CommittedEpoch) cluster.State); ok { + r0 = returnFunc(epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cluster.State) } } - - if rf, ok := ret.Get(1).(func(protocol.CommittedEpoch) component.Component); ok { - r1 = rf(epoch) + if returnFunc, ok := ret.Get(1).(func(protocol.CommittedEpoch) component.Component); ok { + r1 = returnFunc(epoch) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(component.Component) } } - - if rf, ok := ret.Get(2).(func(protocol.CommittedEpoch) module.ReadyDoneAware); ok { - r2 = rf(epoch) + if returnFunc, ok := ret.Get(2).(func(protocol.CommittedEpoch) module.ReadyDoneAware); ok { + r2 = returnFunc(epoch) } else { if ret.Get(2) != nil { r2 = ret.Get(2).(module.ReadyDoneAware) } } - - if rf, ok := ret.Get(3).(func(protocol.CommittedEpoch) module.HotStuff); ok { - r3 = rf(epoch) + if returnFunc, ok := ret.Get(3).(func(protocol.CommittedEpoch) module.HotStuff); ok { + r3 = returnFunc(epoch) } else { if ret.Get(3) != nil { r3 = ret.Get(3).(module.HotStuff) } } - - if rf, ok := ret.Get(4).(func(protocol.CommittedEpoch) hotstuff.VoteAggregator); ok { - r4 = rf(epoch) + if returnFunc, ok := ret.Get(4).(func(protocol.CommittedEpoch) hotstuff.VoteAggregator); ok { + r4 = returnFunc(epoch) } else { if ret.Get(4) != nil { r4 = ret.Get(4).(hotstuff.VoteAggregator) } } - - if rf, ok := ret.Get(5).(func(protocol.CommittedEpoch) hotstuff.TimeoutAggregator); ok { - r5 = rf(epoch) + if returnFunc, ok := ret.Get(5).(func(protocol.CommittedEpoch) hotstuff.TimeoutAggregator); ok { + r5 = returnFunc(epoch) } else { if ret.Get(5) != nil { r5 = ret.Get(5).(hotstuff.TimeoutAggregator) } } - - if rf, ok := ret.Get(6).(func(protocol.CommittedEpoch) component.Component); ok { - r6 = rf(epoch) + if returnFunc, ok := ret.Get(6).(func(protocol.CommittedEpoch) component.Component); ok { + r6 = returnFunc(epoch) } else { if ret.Get(6) != nil { r6 = ret.Get(6).(component.Component) } } - - if rf, ok := ret.Get(7).(func(protocol.CommittedEpoch) error); ok { - r7 = rf(epoch) + if returnFunc, ok := ret.Get(7).(func(protocol.CommittedEpoch) error); ok { + r7 = returnFunc(epoch) } else { r7 = ret.Error(7) } - return r0, r1, r2, r3, r4, r5, r6, r7 } -// NewEpochComponentsFactory creates a new instance of EpochComponentsFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochComponentsFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochComponentsFactory { - mock := &EpochComponentsFactory{} - mock.Mock.Test(t) +// EpochComponentsFactory_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type EpochComponentsFactory_Create_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Create is a helper method to define mock.On call +// - epoch protocol.CommittedEpoch +func (_e *EpochComponentsFactory_Expecter) Create(epoch interface{}) *EpochComponentsFactory_Create_Call { + return &EpochComponentsFactory_Create_Call{Call: _e.mock.On("Create", epoch)} +} - return mock +func (_c *EpochComponentsFactory_Create_Call) Run(run func(epoch protocol.CommittedEpoch)) *EpochComponentsFactory_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.CommittedEpoch + if args[0] != nil { + arg0 = args[0].(protocol.CommittedEpoch) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochComponentsFactory_Create_Call) Return(state cluster.State, proposal component.Component, sync module.ReadyDoneAware, hotstuff1 module.HotStuff, voteAggregator hotstuff.VoteAggregator, timeoutAggregator hotstuff.TimeoutAggregator, messageHub component.Component, err error) *EpochComponentsFactory_Create_Call { + _c.Call.Return(state, proposal, sync, hotstuff1, voteAggregator, timeoutAggregator, messageHub, err) + return _c +} + +func (_c *EpochComponentsFactory_Create_Call) RunAndReturn(run func(epoch protocol.CommittedEpoch) (cluster.State, component.Component, module.ReadyDoneAware, module.HotStuff, hotstuff.VoteAggregator, hotstuff.TimeoutAggregator, component.Component, error)) *EpochComponentsFactory_Create_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/collection/ingest/engine_test.go b/engine/collection/ingest/engine_test.go index 9f9a96902f2..e066b2ad669 100644 --- a/engine/collection/ingest/engine_test.go +++ b/engine/collection/ingest/engine_test.go @@ -257,6 +257,83 @@ func (suite *Suite) TestInvalidTransaction() { suite.Assert().Error(err) suite.Assert().True(errors.As(err, &validator.DuplicatedSignatureError{})) }) + + suite.Run("missing payer signature", func() { + tx := unittest.TransactionBodyFixture() + tx.ReferenceBlockID = suite.root.ID() + tx.Payer = unittest.RandomAddressFixture() + tx.ProposalKey.Address = signer + tx.Authorizers = []flow.Address{signer} + + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + err := suite.engine.ProcessTransaction(&tx) + + suite.Assert().True(errors.As(err, &validator.MissingSignatureError{})) + suite.Assert().Contains(err.Error(), "payer envelope signature is missing") + }) + + suite.Run("missing proposal signature", func() { + tx := unittest.TransactionBodyFixture() + tx.ReferenceBlockID = suite.root.ID() + tx.Payer = signer + tx.ProposalKey.Address = unittest.RandomAddressFixture() + tx.Authorizers = []flow.Address{signer} + + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + err := suite.engine.ProcessTransaction(&tx) + + suite.Assert().True(errors.As(err, &validator.MissingSignatureError{})) + suite.Assert().Contains(err.Error(), "proposer signature on either payload or envelope is missing") + }) + + suite.Run("missing authorizer signature", func() { + tx := unittest.TransactionBodyFixture() + tx.ReferenceBlockID = suite.root.ID() + tx.Payer = signer + tx.ProposalKey.Address = signer + tx.Authorizers = []flow.Address{signer, unittest.RandomAddressFixture()} + + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + err := suite.engine.ProcessTransaction(&tx) + + suite.Assert().True(errors.As(err, &validator.MissingSignatureError{})) + suite.Assert().Contains(err.Error(), "authorizer signature on either payload or envelope is missing") + }) + + suite.Run("unrelated signature (envelope only)", func() { + tx := unittest.TransactionBodyFixture() + tx.ReferenceBlockID = suite.root.ID() + tx.Payer = signer + tx.ProposalKey.Address = signer + tx.Authorizers = []flow.Address{signer} + + unrelatedSig := unittest.TransactionSignatureFixture() + unrelatedSig.Address = unittest.RandomAddressFixture() // unrelated address + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1, unrelatedSig} + + err := suite.engine.ProcessTransaction(&tx) + suite.Assert().Error(err) + suite.Assert().True(errors.As(err, &validator.UnrelatedAccountSignatureError{})) + }) + + suite.Run("unrelated signature (payload only)", func() { + tx := unittest.TransactionBodyFixture() + tx.ReferenceBlockID = suite.root.ID() + tx.Payer = signer + tx.ProposalKey.Address = signer + tx.Authorizers = []flow.Address{signer} + + unrelatedSig := unittest.TransactionSignatureFixture() + unrelatedSig.Address = unittest.RandomAddressFixture() // unrelated address + tx.PayloadSignatures = []flow.TransactionSignature{sig1, unrelatedSig} + + err := suite.engine.ProcessTransaction(&tx) + suite.Assert().Error(err) + suite.Assert().True(errors.As(err, &validator.UnrelatedAccountSignatureError{})) + }) }) suite.Run("invalid signature", func() { diff --git a/engine/collection/message_hub/message_hub.go b/engine/collection/message_hub/message_hub.go index ca620719763..a0b790a537c 100644 --- a/engine/collection/message_hub/message_hub.go +++ b/engine/collection/message_hub/message_hub.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync" "time" "github.com/rs/zerolog" @@ -166,16 +167,29 @@ func NewMessageHub(log zerolog.Logger, } hub.con = conduit + var workers sync.WaitGroup componentBuilder := component.NewComponentManagerBuilder() // This implementation tolerates if the networking layer sometimes blocks on send requests. // We use by default 5 go-routines here. This is fine, because outbound messages are temporally sparse // under normal operations. Hence, the go-routines should mostly be asleep waiting for work. for i := 0; i < defaultMessageHubRequestsWorkers; i++ { + workers.Add(1) componentBuilder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { + defer workers.Done() ready() hub.queuedMessagesProcessingLoop(ctx) }) } + componentBuilder.AddWorker(func(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { + ready() + // ensure we clean up the network Conduit when shutting down + workers.Wait() + // close the network conduit + err := hub.con.Close() + if err != nil { + ctx.Throw(fmt.Errorf("could not close network conduit: %w", err)) + } + }) hub.ComponentManager = componentBuilder.Build() return hub, nil } diff --git a/engine/collection/message_hub/message_hub_test.go b/engine/collection/message_hub/message_hub_test.go index cb67a12d918..9844fbf442d 100644 --- a/engine/collection/message_hub/message_hub_test.go +++ b/engine/collection/message_hub/message_hub_test.go @@ -135,6 +135,8 @@ func (s *MessageHubSuite) SetupTest() { }, nil, ) + // set up conduit mock + s.con.On("Close").Return(nil).Once() // set up protocol snapshot mock s.snapshot = &clusterstate.Snapshot{} diff --git a/engine/collection/mock/cluster_events.go b/engine/collection/mock/cluster_events.go index 07c02b298ca..dc55b450b0f 100644 --- a/engine/collection/mock/cluster_events.go +++ b/engine/collection/mock/cluster_events.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) -// ClusterEvents is an autogenerated mock type for the ClusterEvents type -type ClusterEvents struct { - mock.Mock -} - -// ActiveClustersChanged provides a mock function with given fields: _a0 -func (_m *ClusterEvents) ActiveClustersChanged(_a0 flow.ChainIDList) { - _m.Called(_a0) -} - // NewClusterEvents creates a new instance of ClusterEvents. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewClusterEvents(t interface { @@ -30,3 +22,56 @@ func NewClusterEvents(t interface { return mock } + +// ClusterEvents is an autogenerated mock type for the ClusterEvents type +type ClusterEvents struct { + mock.Mock +} + +type ClusterEvents_Expecter struct { + mock *mock.Mock +} + +func (_m *ClusterEvents) EXPECT() *ClusterEvents_Expecter { + return &ClusterEvents_Expecter{mock: &_m.Mock} +} + +// ActiveClustersChanged provides a mock function for the type ClusterEvents +func (_mock *ClusterEvents) ActiveClustersChanged(chainIDList flow.ChainIDList) { + _mock.Called(chainIDList) + return +} + +// ClusterEvents_ActiveClustersChanged_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ActiveClustersChanged' +type ClusterEvents_ActiveClustersChanged_Call struct { + *mock.Call +} + +// ActiveClustersChanged is a helper method to define mock.On call +// - chainIDList flow.ChainIDList +func (_e *ClusterEvents_Expecter) ActiveClustersChanged(chainIDList interface{}) *ClusterEvents_ActiveClustersChanged_Call { + return &ClusterEvents_ActiveClustersChanged_Call{Call: _e.mock.On("ActiveClustersChanged", chainIDList)} +} + +func (_c *ClusterEvents_ActiveClustersChanged_Call) Run(run func(chainIDList flow.ChainIDList)) *ClusterEvents_ActiveClustersChanged_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ChainIDList + if args[0] != nil { + arg0 = args[0].(flow.ChainIDList) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ClusterEvents_ActiveClustersChanged_Call) Return() *ClusterEvents_ActiveClustersChanged_Call { + _c.Call.Return() + return _c +} + +func (_c *ClusterEvents_ActiveClustersChanged_Call) RunAndReturn(run func(chainIDList flow.ChainIDList)) *ClusterEvents_ActiveClustersChanged_Call { + _c.Run(run) + return _c +} diff --git a/engine/collection/mock/compliance.go b/engine/collection/mock/compliance.go index 95bf491c08a..4c4b6f866da 100644 --- a/engine/collection/mock/compliance.go +++ b/engine/collection/mock/compliance.go @@ -1,87 +1,251 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cluster "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + mock "github.com/stretchr/testify/mock" +) - flow "github.com/onflow/flow-go/model/flow" +// NewCompliance creates a new instance of Compliance. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCompliance(t interface { + mock.TestingT + Cleanup(func()) +}) *Compliance { + mock := &Compliance{} + mock.Mock.Test(t) - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + t.Cleanup(func() { mock.AssertExpectations(t) }) - mock "github.com/stretchr/testify/mock" -) + return mock +} // Compliance is an autogenerated mock type for the Compliance type type Compliance struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *Compliance) Done() <-chan struct{} { - ret := _m.Called() +type Compliance_Expecter struct { + mock *mock.Mock +} + +func (_m *Compliance) EXPECT() *Compliance_Expecter { + return &Compliance_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type Compliance +func (_mock *Compliance) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// OnClusterBlockProposal provides a mock function with given fields: proposal -func (_m *Compliance) OnClusterBlockProposal(proposal flow.Slashable[*cluster.Proposal]) { - _m.Called(proposal) +// Compliance_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Compliance_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Compliance_Expecter) Done() *Compliance_Done_Call { + return &Compliance_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Compliance_Done_Call) Run(run func()) *Compliance_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Compliance_Done_Call) Return(valCh <-chan struct{}) *Compliance_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Compliance_Done_Call) RunAndReturn(run func() <-chan struct{}) *Compliance_Done_Call { + _c.Call.Return(run) + return _c +} + +// OnClusterBlockProposal provides a mock function for the type Compliance +func (_mock *Compliance) OnClusterBlockProposal(proposal flow.Slashable[*cluster.Proposal]) { + _mock.Called(proposal) + return +} + +// Compliance_OnClusterBlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnClusterBlockProposal' +type Compliance_OnClusterBlockProposal_Call struct { + *mock.Call +} + +// OnClusterBlockProposal is a helper method to define mock.On call +// - proposal flow.Slashable[*cluster.Proposal] +func (_e *Compliance_Expecter) OnClusterBlockProposal(proposal interface{}) *Compliance_OnClusterBlockProposal_Call { + return &Compliance_OnClusterBlockProposal_Call{Call: _e.mock.On("OnClusterBlockProposal", proposal)} +} + +func (_c *Compliance_OnClusterBlockProposal_Call) Run(run func(proposal flow.Slashable[*cluster.Proposal])) *Compliance_OnClusterBlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[*cluster.Proposal] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[*cluster.Proposal]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compliance_OnClusterBlockProposal_Call) Return() *Compliance_OnClusterBlockProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *Compliance_OnClusterBlockProposal_Call) RunAndReturn(run func(proposal flow.Slashable[*cluster.Proposal])) *Compliance_OnClusterBlockProposal_Call { + _c.Run(run) + return _c +} + +// OnSyncedClusterBlock provides a mock function for the type Compliance +func (_mock *Compliance) OnSyncedClusterBlock(block flow.Slashable[*cluster.Proposal]) { + _mock.Called(block) + return +} + +// Compliance_OnSyncedClusterBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnSyncedClusterBlock' +type Compliance_OnSyncedClusterBlock_Call struct { + *mock.Call +} + +// OnSyncedClusterBlock is a helper method to define mock.On call +// - block flow.Slashable[*cluster.Proposal] +func (_e *Compliance_Expecter) OnSyncedClusterBlock(block interface{}) *Compliance_OnSyncedClusterBlock_Call { + return &Compliance_OnSyncedClusterBlock_Call{Call: _e.mock.On("OnSyncedClusterBlock", block)} +} + +func (_c *Compliance_OnSyncedClusterBlock_Call) Run(run func(block flow.Slashable[*cluster.Proposal])) *Compliance_OnSyncedClusterBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[*cluster.Proposal] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[*cluster.Proposal]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compliance_OnSyncedClusterBlock_Call) Return() *Compliance_OnSyncedClusterBlock_Call { + _c.Call.Return() + return _c } -// OnSyncedClusterBlock provides a mock function with given fields: block -func (_m *Compliance) OnSyncedClusterBlock(block flow.Slashable[*cluster.Proposal]) { - _m.Called(block) +func (_c *Compliance_OnSyncedClusterBlock_Call) RunAndReturn(run func(block flow.Slashable[*cluster.Proposal])) *Compliance_OnSyncedClusterBlock_Call { + _c.Run(run) + return _c } -// Ready provides a mock function with no fields -func (_m *Compliance) Ready() <-chan struct{} { - ret := _m.Called() +// Ready provides a mock function for the type Compliance +func (_mock *Compliance) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *Compliance) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// Compliance_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Compliance_Ready_Call struct { + *mock.Call } -// NewCompliance creates a new instance of Compliance. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCompliance(t interface { - mock.TestingT - Cleanup(func()) -}) *Compliance { - mock := &Compliance{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *Compliance_Expecter) Ready() *Compliance_Ready_Call { + return &Compliance_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *Compliance_Ready_Call) Run(run func()) *Compliance_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *Compliance_Ready_Call) Return(valCh <-chan struct{}) *Compliance_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Compliance_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Compliance_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type Compliance +func (_mock *Compliance) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// Compliance_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type Compliance_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *Compliance_Expecter) Start(signalerContext interface{}) *Compliance_Start_Call { + return &Compliance_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *Compliance_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *Compliance_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compliance_Start_Call) Return() *Compliance_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *Compliance_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *Compliance_Start_Call { + _c.Run(run) + return _c } diff --git a/engine/collection/mock/engine_events.go b/engine/collection/mock/engine_events.go index f34b9d5f085..ba914d24747 100644 --- a/engine/collection/mock/engine_events.go +++ b/engine/collection/mock/engine_events.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) -// EngineEvents is an autogenerated mock type for the EngineEvents type -type EngineEvents struct { - mock.Mock -} - -// ActiveClustersChanged provides a mock function with given fields: _a0 -func (_m *EngineEvents) ActiveClustersChanged(_a0 flow.ChainIDList) { - _m.Called(_a0) -} - // NewEngineEvents creates a new instance of EngineEvents. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewEngineEvents(t interface { @@ -30,3 +22,56 @@ func NewEngineEvents(t interface { return mock } + +// EngineEvents is an autogenerated mock type for the EngineEvents type +type EngineEvents struct { + mock.Mock +} + +type EngineEvents_Expecter struct { + mock *mock.Mock +} + +func (_m *EngineEvents) EXPECT() *EngineEvents_Expecter { + return &EngineEvents_Expecter{mock: &_m.Mock} +} + +// ActiveClustersChanged provides a mock function for the type EngineEvents +func (_mock *EngineEvents) ActiveClustersChanged(chainIDList flow.ChainIDList) { + _mock.Called(chainIDList) + return +} + +// EngineEvents_ActiveClustersChanged_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ActiveClustersChanged' +type EngineEvents_ActiveClustersChanged_Call struct { + *mock.Call +} + +// ActiveClustersChanged is a helper method to define mock.On call +// - chainIDList flow.ChainIDList +func (_e *EngineEvents_Expecter) ActiveClustersChanged(chainIDList interface{}) *EngineEvents_ActiveClustersChanged_Call { + return &EngineEvents_ActiveClustersChanged_Call{Call: _e.mock.On("ActiveClustersChanged", chainIDList)} +} + +func (_c *EngineEvents_ActiveClustersChanged_Call) Run(run func(chainIDList flow.ChainIDList)) *EngineEvents_ActiveClustersChanged_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ChainIDList + if args[0] != nil { + arg0 = args[0].(flow.ChainIDList) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EngineEvents_ActiveClustersChanged_Call) Return() *EngineEvents_ActiveClustersChanged_Call { + _c.Call.Return() + return _c +} + +func (_c *EngineEvents_ActiveClustersChanged_Call) RunAndReturn(run func(chainIDList flow.ChainIDList)) *EngineEvents_ActiveClustersChanged_Call { + _c.Run(run) + return _c +} diff --git a/engine/collection/mock/guaranteed_collection_publisher.go b/engine/collection/mock/guaranteed_collection_publisher.go index b2754e5f4ef..f70ef4bf080 100644 --- a/engine/collection/mock/guaranteed_collection_publisher.go +++ b/engine/collection/mock/guaranteed_collection_publisher.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - messages "github.com/onflow/flow-go/model/messages" + "github.com/onflow/flow-go/model/messages" mock "github.com/stretchr/testify/mock" ) -// GuaranteedCollectionPublisher is an autogenerated mock type for the GuaranteedCollectionPublisher type -type GuaranteedCollectionPublisher struct { - mock.Mock -} - -// SubmitCollectionGuarantee provides a mock function with given fields: guarantee -func (_m *GuaranteedCollectionPublisher) SubmitCollectionGuarantee(guarantee *messages.CollectionGuarantee) { - _m.Called(guarantee) -} - // NewGuaranteedCollectionPublisher creates a new instance of GuaranteedCollectionPublisher. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewGuaranteedCollectionPublisher(t interface { @@ -30,3 +22,56 @@ func NewGuaranteedCollectionPublisher(t interface { return mock } + +// GuaranteedCollectionPublisher is an autogenerated mock type for the GuaranteedCollectionPublisher type +type GuaranteedCollectionPublisher struct { + mock.Mock +} + +type GuaranteedCollectionPublisher_Expecter struct { + mock *mock.Mock +} + +func (_m *GuaranteedCollectionPublisher) EXPECT() *GuaranteedCollectionPublisher_Expecter { + return &GuaranteedCollectionPublisher_Expecter{mock: &_m.Mock} +} + +// SubmitCollectionGuarantee provides a mock function for the type GuaranteedCollectionPublisher +func (_mock *GuaranteedCollectionPublisher) SubmitCollectionGuarantee(guarantee *messages.CollectionGuarantee) { + _mock.Called(guarantee) + return +} + +// GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitCollectionGuarantee' +type GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call struct { + *mock.Call +} + +// SubmitCollectionGuarantee is a helper method to define mock.On call +// - guarantee *messages.CollectionGuarantee +func (_e *GuaranteedCollectionPublisher_Expecter) SubmitCollectionGuarantee(guarantee interface{}) *GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call { + return &GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call{Call: _e.mock.On("SubmitCollectionGuarantee", guarantee)} +} + +func (_c *GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call) Run(run func(guarantee *messages.CollectionGuarantee)) *GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *messages.CollectionGuarantee + if args[0] != nil { + arg0 = args[0].(*messages.CollectionGuarantee) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call) Return() *GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call { + _c.Call.Return() + return _c +} + +func (_c *GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call) RunAndReturn(run func(guarantee *messages.CollectionGuarantee)) *GuaranteedCollectionPublisher_SubmitCollectionGuarantee_Call { + _c.Run(run) + return _c +} diff --git a/engine/collection/rpc/engine.go b/engine/collection/rpc/engine.go index c1b1f76e9d5..789db4e3e1d 100644 --- a/engine/collection/rpc/engine.go +++ b/engine/collection/rpc/engine.go @@ -81,6 +81,13 @@ func New( interceptors = append(interceptors, rateLimitInterceptor) } + // Note: logging interceptor should be last (innermost) to capture all messages. + // Both start and finish logs are at debug level. + // Example log messages for searching: + // - Start: DBG "started call" grpc.method=SendTransaction grpc.service=flow.access.AccessAPI peer.address=... + // - Finish: DBG "finished call" grpc.method=SendTransaction grpc.service=flow.access.AccessAPI peer.address=... grpc.code=OK grpc.time_ms=... + interceptors = append(interceptors, grpcserver.LoggingInterceptor(log)) + // create a chained unary interceptor chainedInterceptors := grpc.ChainUnaryInterceptor(interceptors...) grpcOpts = append(grpcOpts, chainedInterceptors) diff --git a/engine/collection/rpc/mock/backend.go b/engine/collection/rpc/mock/backend.go index ca92f33b0d1..33f93f5c7c3 100644 --- a/engine/collection/rpc/mock/backend.go +++ b/engine/collection/rpc/mock/backend.go @@ -1,45 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBackend creates a new instance of Backend. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBackend(t interface { + mock.TestingT + Cleanup(func()) +}) *Backend { + mock := &Backend{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Backend is an autogenerated mock type for the Backend type type Backend struct { mock.Mock } -// ProcessTransaction provides a mock function with given fields: _a0 -func (_m *Backend) ProcessTransaction(_a0 *flow.TransactionBody) error { - ret := _m.Called(_a0) +type Backend_Expecter struct { + mock *mock.Mock +} + +func (_m *Backend) EXPECT() *Backend_Expecter { + return &Backend_Expecter{mock: &_m.Mock} +} + +// ProcessTransaction provides a mock function for the type Backend +func (_mock *Backend) ProcessTransaction(transactionBody *flow.TransactionBody) error { + ret := _mock.Called(transactionBody) if len(ret) == 0 { panic("no return value specified for ProcessTransaction") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.TransactionBody) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*flow.TransactionBody) error); ok { + r0 = returnFunc(transactionBody) } else { r0 = ret.Error(0) } - return r0 } -// NewBackend creates a new instance of Backend. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBackend(t interface { - mock.TestingT - Cleanup(func()) -}) *Backend { - mock := &Backend{} - mock.Mock.Test(t) +// Backend_ProcessTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessTransaction' +type Backend_ProcessTransaction_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ProcessTransaction is a helper method to define mock.On call +// - transactionBody *flow.TransactionBody +func (_e *Backend_Expecter) ProcessTransaction(transactionBody interface{}) *Backend_ProcessTransaction_Call { + return &Backend_ProcessTransaction_Call{Call: _e.mock.On("ProcessTransaction", transactionBody)} +} - return mock +func (_c *Backend_ProcessTransaction_Call) Run(run func(transactionBody *flow.TransactionBody)) *Backend_ProcessTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TransactionBody + if args[0] != nil { + arg0 = args[0].(*flow.TransactionBody) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Backend_ProcessTransaction_Call) Return(err error) *Backend_ProcessTransaction_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Backend_ProcessTransaction_Call) RunAndReturn(run func(transactionBody *flow.TransactionBody) error) *Backend_ProcessTransaction_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/collection/synchronization/engine.go b/engine/collection/synchronization/engine.go index d87910e2fa7..7de58ba6942 100644 --- a/engine/collection/synchronization/engine.go +++ b/engine/collection/synchronization/engine.go @@ -182,6 +182,11 @@ func (e *Engine) Done() <-chan struct{} { <-e.unit.Done() // wait for request handler shutdown to complete <-requestHandlerDone + // close the network conduit + err := e.con.Close() + if err != nil { + e.log.Error().Err(err).Msg("could not close network conduit") + } }) return e.lm.Stopped() } diff --git a/engine/collection/synchronization/engine_test.go b/engine/collection/synchronization/engine_test.go index 9b9fbf50015..7ae5df6d38c 100644 --- a/engine/collection/synchronization/engine_test.go +++ b/engine/collection/synchronization/engine_test.go @@ -20,7 +20,6 @@ import ( "github.com/onflow/flow-go/model/flow/filter" "github.com/onflow/flow-go/model/messages" "github.com/onflow/flow-go/module/chainsync" - synccore "github.com/onflow/flow-go/module/chainsync" "github.com/onflow/flow-go/module/metrics" module "github.com/onflow/flow-go/module/mock" netint "github.com/onflow/flow-go/network" @@ -81,7 +80,7 @@ func (ss *SyncSuite) SetupTest() { ) // set up the network conduit mock - ss.con = &mocknetwork.Conduit{} + ss.con = mocknetwork.NewConduit(ss.T()) // set up the local module mock ss.me = &module.Local{} @@ -502,7 +501,7 @@ func (ss *SyncSuite) TestPollHeight() { // check that we send to three nodes from our total list others := ss.participants.Filter(filter.HasNodeID[flow.Identity](ss.participants[1:].NodeIDs()...)) - ss.con.On("Multicast", mock.Anything, synccore.DefaultPollNodes, others[0].NodeID, others[1].NodeID).Return(nil).Run( + ss.con.On("Multicast", mock.Anything, chainsync.DefaultPollNodes, others[0].NodeID, others[1].NodeID).Return(nil).Run( func(args mock.Arguments) { req := args.Get(0).(*messages.SyncRequest) require.Equal(ss.T(), ss.head.Height, req.Height, "request should contain finalized height") @@ -520,7 +519,7 @@ func (ss *SyncSuite) TestSendRequests() { batches := unittest.BatchListFixture(1) // should submit and mark requested all ranges - ss.con.On("Multicast", mock.AnythingOfType("*messages.RangeRequest"), synccore.DefaultBlockRequestNodes, mock.Anything, mock.Anything).Return(nil).Run( + ss.con.On("Multicast", mock.AnythingOfType("*messages.RangeRequest"), chainsync.DefaultBlockRequestNodes, mock.Anything, mock.Anything).Return(nil).Run( func(args mock.Arguments) { req := args.Get(0).(*messages.RangeRequest) ss.Assert().Equal(ranges[0].From, req.FromHeight) @@ -530,7 +529,7 @@ func (ss *SyncSuite) TestSendRequests() { ss.core.On("RangeRequested", ranges[0]) // should submit and mark requested all batches - ss.con.On("Multicast", mock.AnythingOfType("*messages.BatchRequest"), synccore.DefaultBlockRequestNodes, mock.Anything, mock.Anything, mock.Anything).Return(nil).Run( + ss.con.On("Multicast", mock.AnythingOfType("*messages.BatchRequest"), chainsync.DefaultBlockRequestNodes, mock.Anything, mock.Anything, mock.Anything).Return(nil).Run( func(args mock.Arguments) { req := args.Get(0).(*messages.BatchRequest) ss.Assert().Equal(batches[0].BlockIDs, req.BlockIDs) @@ -550,6 +549,8 @@ func (ss *SyncSuite) TestSendRequests() { func (ss *SyncSuite) TestStartStop() { unittest.AssertReturnsBefore(ss.T(), func() { <-ss.e.Ready() + // require the conduit is closed on stop + ss.con.On("Close").Return(nil).Once() <-ss.e.Done() }, time.Second) } diff --git a/engine/collection/test/cluster_switchover_test.go b/engine/collection/test/cluster_switchover_test.go index 8eb42d61314..ea970be07bb 100644 --- a/engine/collection/test/cluster_switchover_test.go +++ b/engine/collection/test/cluster_switchover_test.go @@ -275,14 +275,24 @@ func (tc *ClusterSwitchoverTestCase) ServiceAddress() flow.Address { // Transaction returns a transaction which is valid for ingestion by a // collection node in this test suite. func (tc *ClusterSwitchoverTestCase) Transaction(opts ...func(*flow.TransactionBody)) *flow.TransactionBody { + tx, err := flow.NewTransactionBodyBuilder(). AddAuthorizer(tc.ServiceAddress()). SetPayer(tc.ServiceAddress()). + SetProposalKey(tc.ServiceAddress(), 0, 0). SetScript(unittest.NoopTxScript()). SetReferenceBlockID(tc.RootBlock().ID()). Build() require.NoError(tc.T(), err) + // add an envelope signature to pass access transaction sanity validation for payer proposer and authorizers + tx.EnvelopeSignatures = []flow.TransactionSignature{ + flow.TransactionSignature{ + Address: tc.ServiceAddress(), + Signature: unittest.SignatureFixtureForTransactions(), + }, + } + for _, apply := range opts { apply(tx) } diff --git a/engine/common/fifoqueue/fifoqueue.go b/engine/common/fifoqueue/fifoqueue.go index cc921251c38..281010359c3 100644 --- a/engine/common/fifoqueue/fifoqueue.go +++ b/engine/common/fifoqueue/fifoqueue.go @@ -86,8 +86,9 @@ func NewFifoQueue(maxCapacity int, options ...ConstructorOption) (*FifoQueue, er } // Push appends the given value to the tail of the queue. -// If queue capacity is reached, the message is silently dropped. -func (q *FifoQueue) Push(element interface{}) bool { +// Returns true if and only if the element was added, or false if +// the element was dropped due the queue being full. +func (q *FifoQueue) Push(element any) bool { length, pushed := q.push(element) if pushed { @@ -96,7 +97,7 @@ func (q *FifoQueue) Push(element interface{}) bool { return pushed } -func (q *FifoQueue) push(element interface{}) (int, bool) { +func (q *FifoQueue) push(element any) (int, bool) { q.mu.Lock() defer q.mu.Unlock() @@ -109,7 +110,7 @@ func (q *FifoQueue) push(element interface{}) (int, bool) { } // Front peeks message at the head of the queue (without removing the head). -func (q *FifoQueue) Head() (interface{}, bool) { +func (q *FifoQueue) Head() (any, bool) { q.mu.RLock() defer q.mu.RUnlock() @@ -118,7 +119,7 @@ func (q *FifoQueue) Head() (interface{}, bool) { // Pop removes and returns the queue's head element. // If the queue is empty, (nil, false) is returned. -func (q *FifoQueue) Pop() (interface{}, bool) { +func (q *FifoQueue) Pop() (any, bool) { event, length, ok := q.pop() if !ok { return nil, false @@ -128,7 +129,7 @@ func (q *FifoQueue) Pop() (interface{}, bool) { return event, true } -func (q *FifoQueue) pop() (interface{}, int, bool) { +func (q *FifoQueue) pop() (any, int, bool) { q.mu.Lock() defer q.mu.Unlock() diff --git a/engine/common/fifoqueue/fifoqueue_test.go b/engine/common/fifoqueue/fifoqueue_test.go index 66c2e0a318a..1f8ad228131 100644 --- a/engine/common/fifoqueue/fifoqueue_test.go +++ b/engine/common/fifoqueue/fifoqueue_test.go @@ -10,13 +10,13 @@ import ( func TestPushAndPull(t *testing.T) { queue, err := NewFifoQueue(CapacityUnlimited) require.NoError(t, err) - for i := 0; i < 10; i++ { + for i := range 10 { queue.Push(i) } require.Equal(t, 10, queue.Len()) - for i := 0; i < 10; i++ { + for i := range 10 { n, ok := queue.Pop() require.True(t, ok) require.Equal(t, i, n) @@ -34,7 +34,7 @@ func TestConcurrentPushPull(t *testing.T) { count := 100 // verify that concurrent push will end up having 100 items in the queue var sent sync.WaitGroup - for i := 0; i < count; i++ { + for i := range count { sent.Add(1) go func(i int) { queue.Push(i) @@ -47,7 +47,7 @@ func TestConcurrentPushPull(t *testing.T) { // verify that concurrent Pop will always get one, and in the end, the queue // is empty - for i := 0; i < count; i++ { + for i := range count { sent.Add(1) go func(i int) { _, ok := queue.Pop() diff --git a/engine/common/follower/integration_test.go b/engine/common/follower/integration_test.go index 486f1b236a0..b94522ef76f 100644 --- a/engine/common/follower/integration_test.go +++ b/engine/common/follower/integration_test.go @@ -4,7 +4,7 @@ import ( "context" "sync" "testing" - "time" + "testing/synctest" "github.com/cockroachdb/pebble/v2" "github.com/stretchr/testify/mock" @@ -14,6 +14,7 @@ import ( "github.com/onflow/flow-go/consensus" "github.com/onflow/flow-go/consensus/hotstuff" "github.com/onflow/flow-go/consensus/hotstuff/mocks" + "github.com/onflow/flow-go/consensus/hotstuff/model" "github.com/onflow/flow-go/consensus/hotstuff/notifications/pubsub" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/compliance" @@ -43,6 +44,13 @@ import ( // Each worker submits batchesPerWorker*blocksPerBatch blocks // In total we will submit workers*batchesPerWorker*blocksPerBatch func TestFollowerHappyPath(t *testing.T) { + // All construction happens inside the synctest bubble so that channels + // created by the engine components are associated with the bubble. + // This allows synctest.Wait() to detect when all goroutines have settled. + synctest.Test(t, runTestFollowerHappyPath) +} + +func runTestFollowerHappyPath(t *testing.T) { allIdentities := unittest.CompleteIdentitySet() rootSnapshot := unittest.RootSnapshotFixture(allIdentities) lockManager := storage.NewTestingLockManager() @@ -148,7 +156,26 @@ func TestFollowerHappyPath(t *testing.T) { // start hotstuff logic and follower engine followerLoop.Start(mockCtx) engine.Start(mockCtx) - unittest.RequireCloseBefore(t, moduleutil.AllReady(engine, followerLoop), time.Second, "engine failed to start") + allReady := moduleutil.AllReady(engine, followerLoop) + defer func() { + cancel() + + allDone := moduleutil.AllDone(engine, followerLoop) + synctest.Wait() + select { + case <-allDone: + default: + t.Fatal("engine failed to stop") + } + }() + + // Wait until all startup goroutines have settled, then verify readiness. + synctest.Wait() + select { + case <-allReady: + default: + t.Fatal("engine failed to start") + } // prepare chain of blocks, we will use a continuous chain assuming it was generated on happy path. workers := 5 @@ -188,6 +215,22 @@ func TestFollowerHappyPath(t *testing.T) { // where ◄(B) denotes a QC for block B targetBlockHeight := pendingBlocks[len(pendingBlocks)-3].Block.Height + // Register a finalization callback so the test can block on a channel instead of polling + // with require.Eventually. require.Eventually uses time.Sleep internally; in a synctest + // bubble fake time only advances when all goroutines are durably blocked, which never + // happens while the worker goroutines are running their continuous submission loop. + // A channel receive IS durably blocking, so the main goroutine can wait here while workers + // keep running and the engine keeps processing blocks. + finalized := make(chan struct{}, 1) + consensusConsumer.AddOnBlockFinalizedConsumer(func(b *model.Block) { + if b.View >= targetBlockHeight { + select { + case finalized <- struct{}{}: + default: + } + } + }) + // emulate syncing logic, where we push same blocks over and over. originID := unittest.IdentifierFixture() submittingBlocks := atomic.NewBool(true) @@ -207,33 +250,15 @@ func TestFollowerHappyPath(t *testing.T) { }(pendingBlocks[i*blocksPerWorker : (i+1)*blocksPerWorker]) } - // Ensure graceful shutdown even if the test fails early (e.g., Eventually times out). - // Otherwise, the test may panic with "pebble: closed" when threads are attempting to still write to the database, while - // the test is unwinding and closing the database. If such panics happen, we don't know what assertation failed and - // just see the panic. Hence, we call `cancel()` and attempt to wait for the engine to stop in all cases. - defer func() { - // stop producers and wait for them to exit - submittingBlocks.Store(false) - unittest.RequireReturnsBefore(t, wg.Wait, time.Second, "expect workers to stop producing") + // Block until the target block is finalized. The callback above fires from within the + // HotStuff finalization goroutine (inside the bubble) and sends on this channel, which + // unblocks the main goroutine. + <-finalized - // stop engines and wait for graceful shutdown - cancel() - unittest.RequireCloseBefore(t, moduleutil.AllDone(engine, followerLoop), time.Second, "engine failed to stop") - // Note: in case any error occur, the `mockCtx` will fail the test, due to the unexpected call of `Throw` on the mock. - }() - - // wait for target block to become finalized, this might take a while. - require.Eventually(t, func() bool { - final, err := followerState.Final().Head() - require.NoError(t, err) - success := final.Height == targetBlockHeight - if !success { - t.Logf("finalized height %d, waiting for %d", final.Height, targetBlockHeight) - } else { - t.Logf("successfully finalized target height %d\n", targetBlockHeight) - } - return success - }, 90*time.Second, time.Second, "expect to process all blocks before timeout") + // stop producers and wait for them to exit, then wait for engine shutdown. + submittingBlocks.Store(false) + // Note: in case any error occur, the `mockCtx` will fail the test, due to the unexpected call of `Throw` on the mock. + // shutdown is in defer }) } diff --git a/engine/common/follower/mock/compliance_core.go b/engine/common/follower/mock/compliance_core.go index b0ecb00adae..1a41f0b30ce 100644 --- a/engine/common/follower/mock/compliance_core.go +++ b/engine/common/follower/mock/compliance_core.go @@ -1,98 +1,267 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewComplianceCore creates a new instance of ComplianceCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewComplianceCore(t interface { + mock.TestingT + Cleanup(func()) +}) *ComplianceCore { + mock := &ComplianceCore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ComplianceCore is an autogenerated mock type for the complianceCore type type ComplianceCore struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *ComplianceCore) Done() <-chan struct{} { - ret := _m.Called() +type ComplianceCore_Expecter struct { + mock *mock.Mock +} + +func (_m *ComplianceCore) EXPECT() *ComplianceCore_Expecter { + return &ComplianceCore_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type ComplianceCore +func (_mock *ComplianceCore) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// OnBlockRange provides a mock function with given fields: originID, connectedRange -func (_m *ComplianceCore) OnBlockRange(originID flow.Identifier, connectedRange []*flow.Proposal) error { - ret := _m.Called(originID, connectedRange) +// ComplianceCore_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type ComplianceCore_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *ComplianceCore_Expecter) Done() *ComplianceCore_Done_Call { + return &ComplianceCore_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *ComplianceCore_Done_Call) Run(run func()) *ComplianceCore_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ComplianceCore_Done_Call) Return(valCh <-chan struct{}) *ComplianceCore_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ComplianceCore_Done_Call) RunAndReturn(run func() <-chan struct{}) *ComplianceCore_Done_Call { + _c.Call.Return(run) + return _c +} + +// OnBlockRange provides a mock function for the type ComplianceCore +func (_mock *ComplianceCore) OnBlockRange(originID flow.Identifier, connectedRange []*flow.Proposal) error { + ret := _mock.Called(originID, connectedRange) if len(ret) == 0 { panic("no return value specified for OnBlockRange") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, []*flow.Proposal) error); ok { - r0 = rf(originID, connectedRange) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, []*flow.Proposal) error); ok { + r0 = returnFunc(originID, connectedRange) } else { r0 = ret.Error(0) } - return r0 } -// OnFinalizedBlock provides a mock function with given fields: finalized -func (_m *ComplianceCore) OnFinalizedBlock(finalized *flow.Header) { - _m.Called(finalized) +// ComplianceCore_OnBlockRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockRange' +type ComplianceCore_OnBlockRange_Call struct { + *mock.Call } -// Ready provides a mock function with no fields -func (_m *ComplianceCore) Ready() <-chan struct{} { - ret := _m.Called() +// OnBlockRange is a helper method to define mock.On call +// - originID flow.Identifier +// - connectedRange []*flow.Proposal +func (_e *ComplianceCore_Expecter) OnBlockRange(originID interface{}, connectedRange interface{}) *ComplianceCore_OnBlockRange_Call { + return &ComplianceCore_OnBlockRange_Call{Call: _e.mock.On("OnBlockRange", originID, connectedRange)} +} + +func (_c *ComplianceCore_OnBlockRange_Call) Run(run func(originID flow.Identifier, connectedRange []*flow.Proposal)) *ComplianceCore_OnBlockRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 []*flow.Proposal + if args[1] != nil { + arg1 = args[1].([]*flow.Proposal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ComplianceCore_OnBlockRange_Call) Return(err error) *ComplianceCore_OnBlockRange_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ComplianceCore_OnBlockRange_Call) RunAndReturn(run func(originID flow.Identifier, connectedRange []*flow.Proposal) error) *ComplianceCore_OnBlockRange_Call { + _c.Call.Return(run) + return _c +} + +// OnFinalizedBlock provides a mock function for the type ComplianceCore +func (_mock *ComplianceCore) OnFinalizedBlock(finalized *flow.Header) { + _mock.Called(finalized) + return +} + +// ComplianceCore_OnFinalizedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFinalizedBlock' +type ComplianceCore_OnFinalizedBlock_Call struct { + *mock.Call +} + +// OnFinalizedBlock is a helper method to define mock.On call +// - finalized *flow.Header +func (_e *ComplianceCore_Expecter) OnFinalizedBlock(finalized interface{}) *ComplianceCore_OnFinalizedBlock_Call { + return &ComplianceCore_OnFinalizedBlock_Call{Call: _e.mock.On("OnFinalizedBlock", finalized)} +} + +func (_c *ComplianceCore_OnFinalizedBlock_Call) Run(run func(finalized *flow.Header)) *ComplianceCore_OnFinalizedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceCore_OnFinalizedBlock_Call) Return() *ComplianceCore_OnFinalizedBlock_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceCore_OnFinalizedBlock_Call) RunAndReturn(run func(finalized *flow.Header)) *ComplianceCore_OnFinalizedBlock_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type ComplianceCore +func (_mock *ComplianceCore) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *ComplianceCore) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// ComplianceCore_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type ComplianceCore_Ready_Call struct { + *mock.Call } -// NewComplianceCore creates a new instance of ComplianceCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewComplianceCore(t interface { - mock.TestingT - Cleanup(func()) -}) *ComplianceCore { - mock := &ComplianceCore{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *ComplianceCore_Expecter) Ready() *ComplianceCore_Ready_Call { + return &ComplianceCore_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ComplianceCore_Ready_Call) Run(run func()) *ComplianceCore_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *ComplianceCore_Ready_Call) Return(valCh <-chan struct{}) *ComplianceCore_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ComplianceCore_Ready_Call) RunAndReturn(run func() <-chan struct{}) *ComplianceCore_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type ComplianceCore +func (_mock *ComplianceCore) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// ComplianceCore_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type ComplianceCore_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *ComplianceCore_Expecter) Start(signalerContext interface{}) *ComplianceCore_Start_Call { + return &ComplianceCore_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *ComplianceCore_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *ComplianceCore_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceCore_Start_Call) Return() *ComplianceCore_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceCore_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *ComplianceCore_Start_Call { + _c.Run(run) + return _c } diff --git a/engine/common/grpc/compressor/deflate/deflate.go b/engine/common/grpc/compressor/deflate/deflate.go index 7bbba76f506..2d904440b06 100644 --- a/engine/common/grpc/compressor/deflate/deflate.go +++ b/engine/common/grpc/compressor/deflate/deflate.go @@ -16,7 +16,7 @@ const Name = "deflate" func init() { c := &compressor{} w, _ := flate.NewWriter(nil, flate.DefaultCompression) - c.poolCompressor.New = func() interface{} { + c.poolCompressor.New = func() any { return &writer{Writer: w, pool: &c.poolCompressor} } encoding.RegisterCompressor(c) diff --git a/engine/common/grpc/compressor/snappy/snappy.go b/engine/common/grpc/compressor/snappy/snappy.go index cb7dec75853..1a0a9fe9f33 100644 --- a/engine/common/grpc/compressor/snappy/snappy.go +++ b/engine/common/grpc/compressor/snappy/snappy.go @@ -13,7 +13,7 @@ const Name = "snappy" func init() { c := &compressor{} - c.poolCompressor.New = func() interface{} { + c.poolCompressor.New = func() any { return &writer{Writer: snappy.NewBufferedWriter(nil), pool: &c.poolCompressor} } encoding.RegisterCompressor(c) diff --git a/engine/common/provider/engine.go b/engine/common/provider/engine.go index 5cb77c6a3e2..2104e8452c3 100644 --- a/engine/common/provider/engine.go +++ b/engine/common/provider/engine.go @@ -30,6 +30,19 @@ const ( // DefaultEntityRequestCacheSize is the default max message queue size for the provider engine. // This equates to ~5GB of memory usage with a full queue (10M*500) DefaultEntityRequestCacheSize = 500 + + // DefaultMaxEntityIDs is the default maximum number of entity IDs that can be requested in a single + // EntityRequest. This limit prevents amplification attacks where a small request triggers excessive + // retrieval and serialization work. Note: the default requester engine (engine/common/requester) only + // requests up to 32 entity IDs per batch (see BatchThreshold), so this limit provides ample headroom + // for legitimate requests. + DefaultMaxEntityIDs = 100 + + // DefaultMaxResponseByteSize is the default maximum cumulative byte size of encoded entities in a response. + // This is set conservatively below the network's DefaultMaxUnicastMsgSize (10MB) to account for + // message overhead (headers, encoding wrappers, etc.). The provider will stop adding entities to the + // response once this budget is exceeded, preventing unbounded serialization work. + DefaultMaxResponseByteSize = 8 * 1024 * 1024 // 8MB ) // RetrieveFunc is a function provided to the provider engine upon construction. @@ -56,10 +69,35 @@ type Engine struct { retrieve RetrieveFunc // buffered channel for EntityRequest workers to pick and process. requestChannel chan *internal.EntityRequest + // maxEntityIDs is the maximum number of entity IDs allowed per request. + // Requests with more IDs will be truncated to this limit. + maxEntityIDs int + // maxResponseByteSize is the maximum cumulative byte size of encoded entities in a response. + // The provider will stop adding entities once this budget is exceeded. + maxResponseByteSize int } var _ network.MessageProcessor = (*Engine)(nil) +// Option is a functional option for configuring the provider Engine. +type Option func(*Engine) + +// WithMaxEntityIDs sets the maximum number of entity IDs that can be requested in a single request. +// Requests with more IDs will be truncated to this limit. +func WithMaxEntityIDs(max int) Option { + return func(e *Engine) { + e.maxEntityIDs = max + } +} + +// WithMaxResponseByteSize sets the maximum cumulative byte size of encoded entities in a response. +// The provider will stop adding entities once this budget is exceeded. +func WithMaxResponseByteSize(max int) Option { + return func(e *Engine) { + e.maxResponseByteSize = max + } +} + // New creates a new provider engine, operating on the provided network channel, and accepting requests for entities // from a node within the set obtained by applying the provided selector filter. It uses the injected retrieve function // to manage the fullfilment of these requests. @@ -73,7 +111,8 @@ func New( requestWorkers uint, channel channels.Channel, selector flow.IdentityFilter[flow.Identity], - retrieve RetrieveFunc) (*Engine, error) { + retrieve RetrieveFunc, + opts ...Option) (*Engine, error) { // make sure we don't respond to request sent by self or unauthorized nodes selector = filter.And( @@ -114,15 +153,22 @@ func New( // initialize the propagation engine with its dependencies e := &Engine{ - log: log.With().Str("engine", "provider").Logger(), - metrics: metrics, - state: state, - channel: channel, - selector: selector, - retrieve: retrieve, - requestHandler: handler, - requestQueue: requestQueue, - requestChannel: make(chan *internal.EntityRequest, requestWorkers), + log: log.With().Str("engine", "provider").Logger(), + metrics: metrics, + state: state, + channel: channel, + selector: selector, + retrieve: retrieve, + requestHandler: handler, + requestQueue: requestQueue, + requestChannel: make(chan *internal.EntityRequest, requestWorkers), + maxEntityIDs: DefaultMaxEntityIDs, + maxResponseByteSize: DefaultMaxResponseByteSize, + } + + // apply functional options + for _, opt := range opts { + opt(e) } // register the engine with the network layer and store the conduit @@ -134,7 +180,7 @@ func New( cm := component.NewComponentManagerBuilder() cm.AddWorker(e.processQueuedRequestsShovellerWorker) - for i := uint(0); i < requestWorkers; i++ { + for range requestWorkers { cm.AddWorker(e.processEntityRequestWorker) } @@ -146,7 +192,7 @@ func New( // Process processes the given message from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { select { case <-e.cm.ShutdownSignal(): e.log.Warn(). @@ -176,21 +222,45 @@ func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, eve } // onEntityRequest processes an entity request message from a remote node. +// +// To prevent amplification attacks, this method enforces two limits: +// - Maximum number of entity IDs per request (truncates to maxEntityIDs) +// - Maximum cumulative response size (stops adding entities once maxResponseByteSize is exceeded) +// // Error returns: -// * NetworkTransmissionError if there is a network error happens on transmitting the requested entities. -// * InvalidInputError if the list of requested entities is invalid (empty). -// * generic error in case of unexpected failure or implementation bug. +// - NetworkTransmissionError if there is a network error happens on transmitting the requested entities. +// - InvalidInputError if the list of requested entities is invalid (empty). +// - generic error in case of unexpected failure or implementation bug. func (e *Engine) onEntityRequest(request *internal.EntityRequest) error { defer e.metrics.MessageHandled(e.channel.String(), metrics.MessageEntityRequest) + requestedIDs := request.EntityIds + truncated := false + + // Enforce maximum number of entity IDs per request to limit retrieval work + if len(requestedIDs) > e.maxEntityIDs { + requestedIDs = requestedIDs[:e.maxEntityIDs] + truncated = true + } + lg := e.log.With(). Str("origin_id", request.OriginId.String()). - Strs("entity_ids", flow.IdentifierList(request.EntityIds).Strings()). + Strs("entity_ids", flow.IdentifierList(requestedIDs).Strings()). Logger() - lg.Info(). - Uint64("nonce", request.Nonce). - Msg("entity request received") + if truncated { + lg.Warn(). + Uint64("nonce", request.Nonce). + Int("original_count", len(request.EntityIds)). + Int("truncated_to", len(requestedIDs)). + Bool(logging.KeySuspicious, true). + Msg("entity request truncated: exceeded maximum entity IDs limit") + } else { + lg.Info(). + Uint64("nonce", request.Nonce). + Int("requested_count", len(request.EntityIds)). + Msg("entity request received") + } // TODO: add reputation system to punish nodes for malicious behaviour (spam / repeated requests) @@ -207,11 +277,15 @@ func (e *Engine) onEntityRequest(request *internal.EntityRequest) error { return engine.NewInvalidInputErrorf("invalid requester origin (%x)", request.OriginId) } - // try to retrieve each entity and skip missing ones - entities := make([]flow.Entity, 0, len(request.EntityIds)) - entityIDs := make([]flow.Identifier, 0, len(request.EntityIds)) + // Retrieve and encode entities one at a time, tracking cumulative response size. + // We encode during retrieval (rather than in a separate loop) to allow early termination + // once the response byte budget is exceeded. This prevents unbounded serialization work. + blobs := make([][]byte, 0, len(requestedIDs)) + entityIDs := make([]flow.Identifier, 0, len(requestedIDs)) seen := make(map[flow.Identifier]struct{}) - for _, entityID := range request.EntityIds { + var cumulativeSize int + + for _, entityID := range requestedIDs { // skip requesting duplicate entity IDs if _, ok := seen[entityID]; ok { lg.Warn(). @@ -220,6 +294,7 @@ func (e *Engine) onEntityRequest(request *internal.EntityRequest) error { Msg("duplicate entity ID in entity request") continue } + seen[entityID] = struct{}{} entity, err := e.retrieve(entityID) if errors.Is(err, storage.ErrNotFound) { @@ -231,19 +306,27 @@ func (e *Engine) onEntityRequest(request *internal.EntityRequest) error { if err != nil { return fmt.Errorf("could not retrieve entity (%x): %w", entityID, err) } - entities = append(entities, entity) - entityIDs = append(entityIDs, entityID) - seen[entityID] = struct{}{} - } - // encode all of the entities - blobs := make([][]byte, 0, len(entities)) - for _, entity := range entities { + // Encode the entity immediately to check size budget blob, err := msgpack.Marshal(entity) if err != nil { return fmt.Errorf("could not encode entity (%x): %w", entity.ID(), err) } + + // Check if adding this entity would exceed the response byte budget + if cumulativeSize+len(blob) > e.maxResponseByteSize { + lg.Info(). + Int("cumulative_size", cumulativeSize). + Int("blob_size", len(blob)). + Int("max_response_size", e.maxResponseByteSize). + Int("entities_included", len(blobs)). + Msg("response byte budget exceeded, returning partial response") + break + } + blobs = append(blobs, blob) + entityIDs = append(entityIDs, entityID) + cumulativeSize += len(blob) } // NOTE: we do _NOT_ avoid sending empty responses, as this will allow diff --git a/engine/common/provider/engine_test.go b/engine/common/provider/engine_test.go index ad86e5a6d65..31983f64110 100644 --- a/engine/common/provider/engine_test.go +++ b/engine/common/provider/engine_test.go @@ -90,6 +90,10 @@ func TestOnEntityRequestFull(t *testing.T) { me := mockmodule.NewLocal(t) me.On("NodeID").Return(unittest.IdentifierFixture()) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) e, err := provider.New( @@ -184,6 +188,10 @@ func TestOnEntityRequestPartial(t *testing.T) { me := mockmodule.NewLocal(t) me.On("NodeID").Return(unittest.IdentifierFixture()) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) e, err := provider.New( @@ -272,6 +280,10 @@ func TestOnEntityRequestDuplicates(t *testing.T) { me := mockmodule.NewLocal(t) me.On("NodeID").Return(unittest.IdentifierFixture()) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) e, err := provider.New( @@ -351,6 +363,10 @@ func TestOnEntityRequestEmpty(t *testing.T) { me := mockmodule.NewLocal(t) me.On("NodeID").Return(unittest.IdentifierFixture()) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) e, err := provider.New( @@ -425,6 +441,10 @@ func TestOnEntityRequestInvalidOrigin(t *testing.T) { net.On("Register", mock.Anything, mock.Anything).Return(con, nil) me := mockmodule.NewLocal(t) me.On("NodeID").Return(unittest.IdentifierFixture()) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) e, err := provider.New( @@ -451,3 +471,212 @@ func TestOnEntityRequestInvalidOrigin(t *testing.T) { require.NoError(t, err) unittest.RequireCloseBefore(t, e.Done(), 100*time.Millisecond, "could not stop engine") } + +// TestOnEntityRequestTruncatesExcessiveIDs verifies that requests with more entity IDs than +// the maximum limit are truncated. This prevents amplification attacks where a small request +// triggers excessive retrieval work. +func TestOnEntityRequestTruncatesExcessiveIDs(t *testing.T) { + cancelCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx := irrecoverable.NewMockSignalerContext(t, cancelCtx) + + // Set a low limit for testing + const maxEntityIDs = 3 + + entities := make(map[flow.Identifier]flow.Entity) + identities := unittest.IdentityListFixture(8) + selector := filter.HasNodeID[flow.Identity](identities.NodeIDs()...) + originID := identities[0].NodeID + + // Create 5 collections, but only the first 3 should be returned due to the limit + coll1 := unittest.CollectionFixture(1) + coll2 := unittest.CollectionFixture(2) + coll3 := unittest.CollectionFixture(3) + coll4 := unittest.CollectionFixture(4) + coll5 := unittest.CollectionFixture(5) + + entities[coll1.ID()] = coll1 + entities[coll2.ID()] = coll2 + entities[coll3.ID()] = coll3 + entities[coll4.ID()] = coll4 + entities[coll5.ID()] = coll5 + + retrieve := func(entityID flow.Identifier) (flow.Entity, error) { + entity, ok := entities[entityID] + if !ok { + return nil, storage.ErrNotFound + } + return entity, nil + } + + final := protocol.NewSnapshot(t) + final.On("Identities", mock.Anything).Return( + func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { + return identities.Filter(selector) + }, + nil, + ) + + state := protocol.NewState(t) + state.On("Final").Return(final, nil) + + net := mocknetwork.NewEngineRegistry(t) + con := mocknetwork.NewConduit(t) + net.On("Register", mock.Anything, mock.Anything).Return(con, nil) + con.On("Unicast", mock.Anything, mock.Anything).Run( + func(args mock.Arguments) { + defer cancel() + + response := args.Get(0).(*messages.EntityResponse) + nodeID := args.Get(1).(flow.Identifier) + assert.Equal(t, nodeID, originID) + + // Only the first 3 collections should be returned due to the maxEntityIDs limit + assert.Len(t, response.Blobs, maxEntityIDs, "response should contain exactly maxEntityIDs entities") + + var returnedEntities []flow.Entity + for _, blob := range response.Blobs { + coll := &flow.Collection{} + _ = msgpack.Unmarshal(blob, &coll) + returnedEntities = append(returnedEntities, coll) + } + // The request was [coll1, coll2, coll3, coll4, coll5], truncated to first 3 + assert.ElementsMatch(t, returnedEntities, []flow.Entity{&coll1, &coll2, &coll3}) + }, + ).Return(nil) + + me := mockmodule.NewLocal(t) + me.On("NodeID").Return(unittest.IdentifierFixture()) + requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) + + e, err := provider.New( + unittest.Logger(), + metrics.NewNoopCollector(), + net, + me, + state, + requestQueue, + provider.DefaultRequestProviderWorkers, + channels.TestNetworkChannel, + selector, + retrieve, + provider.WithMaxEntityIDs(maxEntityIDs)) + require.NoError(t, err) + + // Request 5 entities, but only 3 should be returned + request := &flow.EntityRequest{ + Nonce: rand.Uint64(), + EntityIDs: []flow.Identifier{coll1.ID(), coll2.ID(), coll3.ID(), coll4.ID(), coll5.ID()}, + } + + e.Start(ctx) + unittest.RequireCloseBefore(t, e.Ready(), 100*time.Millisecond, "could not start engine") + err = e.Process(channels.TestNetworkChannel, originID, request) + require.NoError(t, err, "should not error when truncating excessive IDs") + unittest.RequireCloseBefore(t, e.Done(), 100*time.Millisecond, "could not stop engine") +} + +// TestOnEntityRequestResponseByteBudget verifies that the response byte budget is enforced. +// The provider should stop adding entities once the cumulative encoded size exceeds the budget, +// preventing unbounded serialization work. +func TestOnEntityRequestResponseByteBudget(t *testing.T) { + cancelCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx := irrecoverable.NewMockSignalerContext(t, cancelCtx) + + entities := make(map[flow.Identifier]flow.Entity) + identities := unittest.IdentityListFixture(8) + selector := filter.HasNodeID[flow.Identity](identities.NodeIDs()...) + originID := identities[0].NodeID + + // Create collections with varying sizes + coll1 := unittest.CollectionFixture(1) + coll2 := unittest.CollectionFixture(2) + coll3 := unittest.CollectionFixture(3) + + entities[coll1.ID()] = coll1 + entities[coll2.ID()] = coll2 + entities[coll3.ID()] = coll3 + + // Calculate the encoded size of the first collection to set a budget that allows + // only 1-2 collections + blob1, err := msgpack.Marshal(coll1) + require.NoError(t, err) + blob2, err := msgpack.Marshal(coll2) + require.NoError(t, err) + + // Set budget to allow first two collections but not the third + maxResponseByteSize := len(blob1) + len(blob2) + 10 // small buffer, but not enough for coll3 + + retrieve := func(entityID flow.Identifier) (flow.Entity, error) { + entity, ok := entities[entityID] + if !ok { + return nil, storage.ErrNotFound + } + return entity, nil + } + + final := protocol.NewSnapshot(t) + final.On("Identities", mock.Anything).Return( + func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { + return identities.Filter(selector) + }, + nil, + ) + + state := protocol.NewState(t) + state.On("Final").Return(final, nil) + + net := mocknetwork.NewEngineRegistry(t) + con := mocknetwork.NewConduit(t) + net.On("Register", mock.Anything, mock.Anything).Return(con, nil) + con.On("Unicast", mock.Anything, mock.Anything).Run( + func(args mock.Arguments) { + defer cancel() + + response := args.Get(0).(*messages.EntityResponse) + nodeID := args.Get(1).(flow.Identifier) + assert.Equal(t, nodeID, originID) + + // Should have at most 2 entities due to byte budget + assert.LessOrEqual(t, len(response.Blobs), 2, "response should not exceed byte budget") + + // Calculate total response size + totalSize := 0 + for _, blob := range response.Blobs { + totalSize += len(blob) + } + assert.LessOrEqual(t, totalSize, maxResponseByteSize, "total response size should not exceed budget") + }, + ).Return(nil) + + me := mockmodule.NewLocal(t) + me.On("NodeID").Return(unittest.IdentifierFixture()) + requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) + + e, err := provider.New( + unittest.Logger(), + metrics.NewNoopCollector(), + net, + me, + state, + requestQueue, + provider.DefaultRequestProviderWorkers, + channels.TestNetworkChannel, + selector, + retrieve, + provider.WithMaxResponseByteSize(maxResponseByteSize)) + require.NoError(t, err) + + // Request all 3 entities, but byte budget should limit response + request := &flow.EntityRequest{ + Nonce: rand.Uint64(), + EntityIDs: []flow.Identifier{coll1.ID(), coll2.ID(), coll3.ID()}, + } + + e.Start(ctx) + unittest.RequireCloseBefore(t, e.Ready(), 100*time.Millisecond, "could not start engine") + err = e.Process(channels.TestNetworkChannel, originID, request) + require.NoError(t, err, "should not error when byte budget is exceeded") + unittest.RequireCloseBefore(t, e.Done(), 100*time.Millisecond, "could not stop engine") +} diff --git a/engine/common/requester/config.go b/engine/common/requester/config.go index eb52a8eef9a..5007683fbf9 100644 --- a/engine/common/requester/config.go +++ b/engine/common/requester/config.go @@ -6,13 +6,12 @@ import ( ) type Config struct { - BatchInterval time.Duration // minimum interval between requests - BatchThreshold uint // maximum batch size for one request - RetryInitial time.Duration // interval after which we retry request for an entity - RetryFunction RetryFunc // function determining growth of retry interval - RetryMaximum time.Duration // maximum interval for retrying request for an entity - RetryAttempts uint // maximum amount of request attempts per entity - ValidateStaking bool // should staking of target/origin be checked + BatchInterval time.Duration // minimum interval between requests + BatchThreshold uint // maximum batch size for one request + RetryInitial time.Duration // interval after which we retry request for an entity + RetryFunction RetryFunc // function determining growth of retry interval + RetryMaximum time.Duration // maximum interval for retrying request for an entity + RetryAttempts uint // maximum amount of request attempts per entity } type RetryFunc func(time.Duration) time.Duration @@ -88,10 +87,3 @@ func WithRetryAttempts(attempts uint) OptionFunc { cfg.RetryAttempts = attempts } } - -// WithValidateStaking sets the flag which determines if the target and origin must be checked for staking -func WithValidateStaking(validateStaking bool) OptionFunc { - return func(cfg *Config) { - cfg.ValidateStaking = validateStaking - } -} diff --git a/engine/common/requester/engine.go b/engine/common/requester/engine.go index 1354425b1ed..a5b2cb5fa0c 100644 --- a/engine/common/requester/engine.go +++ b/engine/common/requester/engine.go @@ -3,6 +3,7 @@ package requester import ( "fmt" "math" + "sync" "time" "github.com/rs/zerolog" @@ -14,6 +15,8 @@ import ( "github.com/onflow/flow-go/model/flow/filter" "github.com/onflow/flow-go/model/messages" "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/module/irrecoverable" "github.com/onflow/flow-go/module/metrics" "github.com/onflow/flow-go/network" "github.com/onflow/flow-go/network/channels" @@ -22,7 +25,14 @@ import ( "github.com/onflow/flow-go/utils/rand" ) -// HandleFunc is a function provided to the requester engine to handle an entity +// DefaultEntityRequestCacheSize is the default max message queue size for the requester engine. +// Assuming a maximum size 10MB per message, a full queue would consume ~5GB of memory (10M*500). +// While most messages (such as execution receipts) are significantly smaller than 10MB, some +// messages like chunk data packs can be significantly larger. The user should properly tune +// this parameter based on their use case and ensure enough memory is available. +const DefaultEntityRequestCacheSize = 500 + +// HandleFunc is a function provided to the requester engine to entityConsumer an entity // once it has been retrieved from a provider. The function should be non-blocking // and errors should be handled internally within the function. type HandleFunc func(originID flow.Identifier, entity flow.Entity) @@ -34,40 +44,66 @@ type CreateFunc func() flow.Entity // Engine is a generic requester engine, handling the requesting of entities // on the flow network. It is the `request` part of the request-reply // pattern provided by the pair of generic exchange engines. +// All exported methods are concurrency safe. type Engine struct { - unit *engine.Unit - log zerolog.Logger - cfg Config - metrics module.EngineMetrics - me module.Local - state protocol.State - con network.Conduit - channel channels.Channel - selector flow.IdentityFilter[flow.Identity] - create CreateFunc - handle HandleFunc - - // changing the following state variables must be guarded by unit.Lock() - items map[flow.Identifier]*Item + *component.ComponentManager + mu sync.Mutex + log zerolog.Logger + cfg Config + metrics module.EngineMetrics + me module.Local + state protocol.State + con network.Conduit + channel channels.Channel + requestHandler *engine.MessageHandler + requestQueue engine.MessageStore + selector flow.IdentityFilter[flow.Identity] + create CreateFunc + entityConsumer HandleFunc + + // changing the following state variables must be guarded by mu.Lock() + items map[flow.Identifier]*Request requests map[uint64]*messages.EntityRequest forcedDispatchOngoing *atomic.Bool // to ensure only trigger dispatching logic once at any time } +var _ component.Component = (*Engine)(nil) +var _ network.MessageProcessor = (*Engine)(nil) + // New creates a new requester engine, operating on the provided network channel, and requesting entities from a node // within the set obtained by applying the provided selector filter. The options allow customization of the parameters // related to the batch and retry logic. -func New(log zerolog.Logger, metrics module.EngineMetrics, net network.EngineRegistry, me module.Local, state protocol.State, - channel channels.Channel, selector flow.IdentityFilter[flow.Identity], create CreateFunc, options ...OptionFunc) (*Engine, error) { +// +// IMPORTANT: +// - The injected [engine.MessageStore] is used to queue incoming responses from potentially byzantine peers. +// The backing implementation must be fully BFT, including resilience against resource exhaustion attacks and targeted +// cache eviction attacks. Hero data structures are generally not suitable, as most of them are not BFT at the time +// of writing (see www.notion.so/flowfoundation/Intro-to-heap-friendly-hero-structures-d1e420752ce6470f857e848ad1e60213 ). +// - Challenging, borderline overload scenarios should be anticipated. The injected [engine.MessageStore] must have bounded +// size and drop messages when full (instead of blocking). The requester engine will log warnings when messages are dropped. +// +// No error returns are expected during normal operations. +func New( + log zerolog.Logger, + metrics module.EngineMetrics, + net network.EngineRegistry, + me module.Local, + state protocol.State, + requestQueue engine.MessageStore, + channel channels.Channel, + selector flow.IdentityFilter[flow.Identity], + create CreateFunc, + options ...OptionFunc, +) (*Engine, error) { // initialize the default config cfg := Config{ - BatchThreshold: 32, - BatchInterval: time.Second, - RetryInitial: 4 * time.Second, - RetryFunction: RetryGeometric(2), - RetryMaximum: 2 * time.Minute, - RetryAttempts: math.MaxUint32, - ValidateStaking: true, + BatchThreshold: 32, + BatchInterval: time.Second, + RetryInitial: 4 * time.Second, + RetryFunction: RetryGeometric(2), + RetryMaximum: 2 * time.Minute, + RetryAttempts: math.MaxUint32, } // apply the custom option parameters @@ -86,166 +122,231 @@ func New(log zerolog.Logger, metrics module.EngineMetrics, net network.EngineReg return nil, fmt.Errorf("invalid retry maximum (must not be smaller than initial interval)") } - // make sure we don't send requests from self + // This node may request data from and node that + // 1. has positive weight in the current epoch (ignoring observer variants of roles) + // 2. and is not ejected + // 3. and is not the requester itself + // Note: we allow requesting data from joining or leaving nodes. This is important during grace periods + // before and after the cluster switchover, where the joining and leaving nodes (e.g. collectors part of + // a cluster) must still be able to communicate with each other including requesting data. selector = filter.And( selector, - filter.Not(filter.HasNodeID[flow.Identity](me.NodeID())), + filter.HasInitialWeight[flow.Identity](true), filter.Not(filter.HasParticipationStatus(flow.EpochParticipationStatusEjected)), + filter.Not(filter.HasNodeID[flow.Identity](me.NodeID())), ) - // make sure we only send requests to nodes that are active in the current epoch and have positive weight - if cfg.ValidateStaking { - selector = filter.And( - selector, - filter.HasInitialWeight[flow.Identity](true), - filter.HasParticipationStatus(flow.EpochParticipationStatusActive), - ) - } + requestHandler := engine.NewMessageHandler( + log, + engine.NewNotifier(), + engine.Pattern{ + // Match is called on every new message coming to this engine. + // Requester engine only expects *flow.EntityResponse. + // Other message types are discarded by Match. + Match: func(message *engine.Message) bool { + _, ok := message.Payload.(*flow.EntityResponse) + return ok + }, + Store: requestQueue, + }) // initialize the propagation engine with its dependencies e := &Engine{ - unit: engine.NewUnit(), log: log.With().Str("engine", "requester").Logger(), cfg: cfg, metrics: metrics, me: me, state: state, + requestHandler: requestHandler, + requestQueue: requestQueue, channel: channel, selector: selector, create: create, - handle: nil, - items: make(map[flow.Identifier]*Item), // holds all pending items + entityConsumer: nil, + items: make(map[flow.Identifier]*Request), // holds all pending items requests: make(map[uint64]*messages.EntityRequest), // holds all sent requests forcedDispatchOngoing: atomic.NewBool(false), } // register the engine with the network layer and store the conduit - con, err := net.Register(channels.Channel(channel), e) + con, err := net.Register(channel, e) if err != nil { return nil, fmt.Errorf("could not register engine: %w", err) } e.con = con + e.ComponentManager = component.NewComponentManagerBuilder(). + AddWorker(e.poll). + AddWorker(e.processInboundEntityResponses). + Build() + return e, nil } -// WithHandle sets the handle function of the requester, which is how it processes -// returned entities. The engine can not be started without setting the handle +// WithHandle sets the entityConsumer function of the requester, which is how it processes +// returned entities. The engine can not be started without setting the entityConsumer // function. It is done in a separate call so that the requester can be injected -// into engines upon construction, and then provide a handle function to the +// into engines upon construction, and then provide a entityConsumer function to the // requester from that engine itself. func (e *Engine) WithHandle(handle HandleFunc) { - e.handle = handle + e.entityConsumer = handle } -// Ready returns a ready channel that is closed once the engine has fully -// started. For consensus engine, this is true once the underlying consensus -// algorithm has started. -func (e *Engine) Ready() <-chan struct{} { - if e.handle == nil { - panic("must initialize requester engine with handler") +// Process queues the given message from the node with the given origin ID for asynchronous processing. +// If the injected `requestQueue` is full, the message is dropped and a warning is logged. +// For inputs of unexpected type, a warning is logged and the message is dropped. +// +// No error returns are expected during normal operations. +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { + select { + case <-e.ShutdownSignal(): + e.log.Warn(). + Hex("origin_id", logging.ID(originID)). + Msgf("received message after shutdown") + return nil + default: } - e.unit.Launch(e.poll) - return e.unit.Ready() -} -// Done returns a done channel that is closed once the engine has fully stopped. -// For the consensus engine, we wait for hotstuff to finish. -func (e *Engine) Done() <-chan struct{} { - return e.unit.Done() + e.metrics.MessageReceived(e.channel.String(), metrics.MessageEntityResponse) + err := e.requestHandler.Process(originID, event) + if err != nil { + if engine.IsIncompatibleInputTypeError(err) { + e.log.Warn(). + Hex("origin_id", logging.ID(originID)). + Str("channel", channel.String()). + Str("event", fmt.Sprintf("%+v", event)). + Bool(logging.KeySuspicious, true). + Msg("received unsupported message type") + return nil + } + return fmt.Errorf("unexpected error while processing engine event: %w", err) + } + return nil } -// SubmitLocal submits an message originating on the local node. -func (e *Engine) SubmitLocal(message interface{}) { - e.unit.Launch(func() { - err := e.process(e.me.NodeID(), message) - if err != nil { - engine.LogError(e.log, err) +// processInboundEntityResponses requires a dedicated worker from the [component.ComponentManager]. +// It tracks when there is available work and performs dispatch of incoming messages. +func (e *Engine) processInboundEntityResponses(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { + ready() + e.log.Debug().Msg("process entity request shoveller worker started") + + receivedResponseNotifier := e.requestHandler.GetNotifier() + for { + select { + case <-receivedResponseNotifier: + // there is at least a single request in the queue, so we try to process it. + e.onQueuedEntityResponses(ctx) + case <-ctx.Done(): + return } - }) + } } -// Submit submits the given message from the node with the given origin ID -// for processing in a non-blocking manner. It returns instantly and logs -// a potential processing error internally when done. -func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, message interface{}) { - e.unit.Launch(func() { - err := e.Process(channel, originID, message) - if err != nil { - engine.LogError(e.log, err) +// onQueuedEntityResponses consumes all messages from the `requestQueue` waiting to be processed (or aborts in case +// of shutdown). All unexpected errors are reported to the SignalerContext. +func (e *Engine) onQueuedEntityResponses(ctx irrecoverable.SignalerContext) { + for { + select { + case <-ctx.Done(): + return + default: } - }) -} -// ProcessLocal processes an message originating on the local node. -func (e *Engine) ProcessLocal(message interface{}) error { - return e.unit.Do(func() error { - return e.process(e.me.NodeID(), message) - }) -} + msg, ok := e.requestQueue.Get() + if !ok { + // no more requests, return + return + } + + res, ok := msg.Payload.(*flow.EntityResponse) + if !ok { + // should never happen, as we only put *flow.EntityResponse in the queue, + // if it does happen, it means there is a bug in the queue implementation. + ctx.Throw(fmt.Errorf("invalid message type in entity request queue: %T", msg.Payload)) + } -// Process processes the given message from the node with the given origin ID in -// a blocking manner. It returns the potential processing error when done. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, message interface{}) error { - return e.unit.Do(func() error { - return e.process(originID, message) - }) + err := e.onEntityResponse(msg.OriginID, res) + if err != nil { + if engine.IsInvalidInputError(err) { + e.log.Err(err). + Str("origin_id", msg.OriginID.String()). + Uint64("nonce", res.Nonce). + Bool(logging.KeySuspicious, true). + Msg("invalid response detected") + continue + } + ctx.Throw(err) + } + } } -// EntityByID adds an entity to the list of entities to be requested from the -// provider. It is idempotent, meaning that adding the same entity to the -// requester engine multiple times has no effect, unless the item has -// expired due to too many requests and has thus been deleted from the -// list. The provided selector will be applied to the set of valid providers on top -// of the global selector injected upon construction. It allows for finer-grained -// control over which subset of providers to request a given entity from, such as -// selection of a collection cluster. Use `filter.Any` if no additional selection -// is required. Checks integrity of response to make sure that we got entity that we were requesting. +// EntityByID will enqueue the given entity for request by its ID (content hash). +// We permit request data only from non-ejected, staked nodes (excluding observer variants of roles +// and the requesting node itself). The selector will be applied to the resulting set of peers. +// This allows finer-grained control over which providers to request from on a per-entity basis. +// Use `filter.Any` if no additional restrictions are required. +// Received entities will be verified for integrity using their ID function. +// Idempotent w.r.t. `queryKey` (if prior request is still ongoing, we just continue trying). +// Concurrency safe. func (e *Engine) EntityByID(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { e.addEntityRequest(entityID, selector, true) } -// Query will request data through the request engine backing the interface. -// The additional selector will be applied to the subset -// of valid providers for the data and allows finer-grained control -// over which providers to request data from. Doesn't perform integrity check -// can be used to get entities without knowing their ID. -func (e *Engine) Query(key flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { +// EntityBySecondaryKey will enqueue the given entity for request by some secondary identifier (NOT its content hash). +// We permit request data only from non-ejected, staked nodes (excluding observer variants of roles +// and the requesting node itself). The selector will be applied to the resulting set of peers. +// This allows finer-grained control over which providers to request from on a per-entity basis. +// Use `filter.Any` if no additional restrictions are required. +// It is the CALLER's RESPONSIBILITY to verify integrity (and authenticity if applicable) of the received data +// which might be provided by a byzantine peer. +// Idempotent w.r.t. `queryKey` (if prior request is still ongoing, we just continue trying). +// Concurrency safe. +func (e *Engine) EntityBySecondaryKey(key flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { e.addEntityRequest(key, selector, false) } -func (e *Engine) addEntityRequest(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity], checkIntegrity bool) { - e.unit.Lock() - defer e.unit.Unlock() +// addEntityRequest adds the entity identified by `queryKey` to the pool of data to be requested. +// Items to be requested are held in memory and forgotten during a restart. +// Idempotent w.r.t. `queryKey` (if prior request is still ongoing, we just continue trying). Aside +// from acquiring a lock, this function returns almost immediately. The actual requests are done +// asynchronously. +// ATTENTION: If `queryKeyIsContentHash` is `false`, it is the CALLER's RESPONSIBILITY to verify +// integrity (and authenticity if applicable) of the received data! +// Concurrency safe. +func (e *Engine) addEntityRequest(queryKey flow.Identifier, selector flow.IdentityFilter[flow.Identity], queryKeyIsContentHash bool) { + e.mu.Lock() + defer e.mu.Unlock() // check if we already have an item for this entity - _, duplicate := e.items[entityID] + _, duplicate := e.items[queryKey] if duplicate { return } // otherwise, add a new item to the list - item := &Item{ - EntityID: entityID, - NumAttempts: 0, - LastRequested: time.Time{}, - RetryAfter: e.cfg.RetryInitial, - ExtraSelector: selector, - checkIntegrity: checkIntegrity, + item := &Request{ + QueryKey: queryKey, + NumAttempts: 0, + LastRequested: time.Time{}, + RetryAfter: e.cfg.RetryInitial, + ExtraSelector: selector, + queryByContentHash: queryKeyIsContentHash, } - e.items[entityID] = item + e.items[queryKey] = item } -// Force will force the requester engine to dispatch all currently -// valid batch requests. +// Force will force the requester engine to dispatch all currently valid batch requests. +// This method does not block; requests are checked asynchronously. Repeated calls are +// no-ops as long as once forced request is ongoing. func (e *Engine) Force() { // exit early in case a forced dispatch is currently ongoing if e.forcedDispatchOngoing.Load() { return } - // using Launch to ensure the caller won't be blocked - e.unit.Launch(func() { + // Go routine ensures that the caller won't be blocked. At most one goroutine will be consumed, + // because if another goroutine is already active, a newly spawned routine will immediately be done. + go func() { // using atomic bool to ensure there is at most one caller would trigger dispatching requests if e.forcedDispatchOngoing.CompareAndSwap(false, true) { count := uint(0) @@ -263,46 +364,48 @@ func (e *Engine) Force() { } e.forcedDispatchOngoing.Store(false) } - }) + }() } -func (e *Engine) poll() { - ticker := time.NewTicker(e.cfg.BatchInterval) +// poll runs inside a dedicated worker owned by the [component.ComponentManager]. It performs dispatch of pending requests using a timer. +func (e *Engine) poll(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { + if e.entityConsumer == nil { + ctx.Throw(fmt.Errorf("must initialize requester engine with handler")) + } + ready() -PollLoop: + ticker := time.NewTicker(e.cfg.BatchInterval) + defer ticker.Stop() for { select { - case <-e.unit.Quit(): - break PollLoop + case <-ctx.Done(): + return case <-ticker.C: if e.forcedDispatchOngoing.Load() { - return + continue } dispatched, err := e.dispatchRequest() if err != nil { - e.log.Error().Err(err).Msg("could not dispatch requests") - continue PollLoop + ctx.Throw(err) } if dispatched { e.log.Debug().Uint("requests", 1).Msg("regular request dispatch") } } } - - ticker.Stop() } // dispatchRequest dispatches a subset of requests (selection based on internal heuristic). -// While `dispatchRequest` sends a request (covering some but not necessarily all items), +// We send request(s) covering some but not necessarily all items, // if and only if there is something to request. In other words it cannot happen that // `dispatchRequest` sends no request, but there is something to be requested. // The boolean return value indicates whether a request was dispatched at all. +// No error returns are expected during normal operations. func (e *Engine) dispatchRequest() (bool, error) { - - e.unit.Lock() - defer e.unit.Unlock() + e.mu.Lock() + defer e.mu.Unlock() e.log.Debug().Int("num_entities", len(e.items)).Msg("selecting entities") @@ -314,7 +417,7 @@ func (e *Engine) dispatchRequest() (bool, error) { // go through each item and decide if it should be requested again now := time.Now().UTC() - var providerID flow.Identifier + var provider *flow.Identity var entityIDs []flow.Identifier for entityID, item := range e.items { @@ -331,40 +434,36 @@ func (e *Engine) dispatchRequest() (bool, error) { continue } - // if the provider has already been chosen, check if this item - // can be requested from the same provider; otherwise skip it - // for now, so it will be part of the next batch request - if providerID != flow.ZeroID { - overlap := providers.Filter(filter.And( - filter.HasNodeID[flow.Identity](providerID), - item.ExtraSelector, - )) - if len(overlap) == 0 { - continue - } - } - - // if no provider has been chosen yet, choose from restricted set - // NOTE: a single item can not permanently block requests going - // out when no providers are available for it, because the iteration - // order is random and will skip the item most of the times - // when other items are available - if providerID == flow.ZeroID { + // If no provider has been chosen yet, select one that: + // - is part of the previously determined `providers` set (staked, non-ejected nodes) + // - and matches the item's specific requirements (as per ExtraSelector) + // NOTE: a single item can not permanently block requests going out when no providers are available for it, + // because the iteration order is random. The `ExtraSelector` of the item that is iterated over first (at + // random) will determine the selected provider. + if provider == nil { filteredProviders := providers.Filter(item.ExtraSelector) + // if we failed to select a provider for given item instead of aborting we will try the same for the next item in the queue. if len(filteredProviders) == 0 { - return false, fmt.Errorf("no valid providers available for item %s, total providers: %v", entityID.String(), len(providers)) + continue } - // ramdonly select a provider from the filtered set - // to send as many item requests as possible. + // Randomly select a provider from the eligible set. We will ask this data provider for all entities, whose `ExtraSelector` + // matches this provider. Thereby, we maximize the batch size, requesting as many entities as possible via a single message. id, err := filteredProviders.Sample(1) if err != nil { return false, fmt.Errorf("sampling failed: %w", err) } - providerID = id[0].NodeID + provider = id[0] providers = filteredProviders } - // add item to list and set retry parameters + // if the provider has already been chosen, check if this item + // can be requested from the same provider; otherwise skip it + // for now, so it will be part of the next batch request + if !item.ExtraSelector(provider) { + continue + } + + // Add item to list and update the retry parameters. // NOTE: we add the retry interval to the last requested timestamp, // rather than using the current timestamp, in order to conserve a // more even distribution of timestamps over time, which should lead @@ -408,35 +507,41 @@ func (e *Engine) dispatchRequest() (bool, error) { if e.log.Debug().Enabled() { e.log.Debug(). - Hex("provider", logging.ID(providerID)). + Hex("provider", logging.ID(provider.NodeID)). Uint64("nonce", req.Nonce). Int("num_selected", len(entityIDs)). Strs("entities", logging.IDs(entityIDs)). Msg("sending entity request") } - err = e.con.Unicast(req, providerID) + err = e.con.Unicast(req, provider.NodeID) if err != nil { - return true, fmt.Errorf("could not send request for entities %v: %w", logging.IDs(entityIDs), err) + e.log.Error().Err(err).Msgf("could not dispatch requests: could not send request for entities %v", logging.IDs(entityIDs)) + return false, nil } e.requests[req.Nonce] = req - // NOTE: we forget about requests after the expiry of the shortest retry time - // from the entities in the list; this means that we purge requests aggressively. - // However, most requests should be responded to on the first attempt and clearing - // these up only removes the ability to instantly retry upon partial responses, so - // it won't affect much. + // NOTE: we forget about open requests after the default expiry duration; i.e. we purge the set of requests for which + // we accept answer for aggressively. However, most requests should be responded to on the first attempt and clearing + // these up only removes the ability to instantly retry upon partial responses, so it won't affect much. go func() { + done := e.Done() + // check if the goroutine didn't outlive the context + select { + case <-done: + return + default: + } <-time.After(e.cfg.RetryInitial) - e.unit.Lock() - defer e.unit.Unlock() + e.mu.Lock() delete(e.requests, req.Nonce) + e.mu.Unlock() }() if e.log.Debug().Enabled() { e.log.Debug(). - Hex("provider", logging.ID(providerID)). + Hex("provider", logging.ID(provider.NodeID)). Uint64("nonce", req.Nonce). Strs("entities", logging.IDs(entityIDs)). TimeDiff("duration", time.Now(), requestStart). @@ -447,38 +552,30 @@ func (e *Engine) dispatchRequest() (bool, error) { return true, nil } -// process processes events for the propagation engine on the consensus node. -func (e *Engine) process(originID flow.Identifier, message interface{}) error { - - e.metrics.MessageReceived(e.channel.String(), metrics.MessageEntityResponse) - defer e.metrics.MessageHandled(e.channel.String(), metrics.MessageEntityResponse) - - switch msg := message.(type) { - case *flow.EntityResponse: - return e.onEntityResponse(originID, msg) - default: - return engine.NewInvalidInputErrorf("invalid message type (%T)", message) - } -} - +// onEntityResponse handles response for requests that were originally made by the engine (and have not yet expired). +// For each successful response, this function spawns a dedicated go routine to perform handling of the parsed response. +// +// IMPORTANT BFT consideration: We process only responses that we have previously requested. Hence, it's impossible to +// force this function to spawn arbitrary number of goroutines (resource exhaustion attack). +// +// Expected errors during normal operations: +// - [engine.InvalidInputError] if the provided response is malformed func (e *Engine) onEntityResponse(originID flow.Identifier, res *flow.EntityResponse) error { + defer e.metrics.MessageHandled(e.channel.String(), metrics.MessageEntityResponse) lg := e.log.With().Str("origin_id", originID.String()).Uint64("nonce", res.Nonce).Logger() lg.Debug().Strs("entity_ids", flow.IdentifierList(res.EntityIDs).Strings()).Msg("entity response received") - if e.cfg.ValidateStaking { - - // check that the response comes from a valid provider - providers, err := e.state.Final().Identities(filter.And( - e.selector, - filter.HasNodeID[flow.Identity](originID), - )) - if err != nil { - return fmt.Errorf("could not get providers: %w", err) - } - if len(providers) == 0 { - return engine.NewInvalidInputErrorf("invalid provider origin (%x)", originID) - } + // check that the response comes from a valid provider + providers, err := e.state.Final().Identities(filter.And( + e.selector, + filter.HasNodeID[flow.Identity](originID), + )) + if err != nil { + return fmt.Errorf("could not get providers: %w", err) + } + if len(providers) == 0 { + return engine.NewInvalidInputErrorf("invalid provider origin (%x)", originID) } if e.log.Debug().Enabled() { @@ -489,11 +586,11 @@ func (e *Engine) onEntityResponse(originID flow.Identifier, res *flow.EntityResp Msg("onEntityResponse entries received") } - e.unit.Lock() - defer e.unit.Unlock() + e.mu.Lock() + defer e.mu.Unlock() - // build a list of needed entities; if not available, process anyway, - // but in that case we can't re-queue missing items + // Build a list of needed entities; if not available, proceed anyway, but in that case we + // can't re-queue missing items. Note: we still only process requested items (see code below) needed := make(map[flow.Identifier]struct{}) req, exists := e.requests[res.Nonce] if exists { @@ -526,10 +623,10 @@ func (e *Engine) onEntityResponse(originID flow.Identifier, res *flow.EntityResp entity := e.create() err := msgpack.Unmarshal(blob, &entity) if err != nil { - return fmt.Errorf("could not decode entity: %w", err) + return engine.NewInvalidInputErrorf("could not decode entity: %s", err.Error()) } - if item.checkIntegrity { + if item.queryByContentHash { actualEntityID := entity.ID() // validate that we got correct entity, exactly what we were expecting if entityID != actualEntityID { @@ -547,7 +644,9 @@ func (e *Engine) onEntityResponse(originID flow.Identifier, res *flow.EntityResp delete(e.items, entityID) // process the entity - go e.handle(originID, entity) + // TODO: We should update users of requester engine to uniformly pass in a non-blocking `entityConsumer` function + // (Currently all users except the execution ingestion engine have non-blocking handlers: https://github.com/onflow/flow-go/blob/be489481bff28f42bc887fe26fe19476585ab6aa/engine/execution/ingestion/machine.go#L99) + go e.entityConsumer(originID, entity) } // requeue requested entities that have not been delivered in the response diff --git a/engine/common/requester/engine_test.go b/engine/common/requester/engine_test.go index e10555e19ba..871a5aaec52 100644 --- a/engine/common/requester/engine_test.go +++ b/engine/common/requester/engine_test.go @@ -3,12 +3,14 @@ package requester import ( "math/rand" "testing" + "testing/synctest" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "github.com/vmihailenco/msgpack/v4" "go.uber.org/atomic" @@ -18,161 +20,188 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/flow/filter" "github.com/onflow/flow-go/model/messages" + "github.com/onflow/flow-go/module/mempool/queue" "github.com/onflow/flow-go/module/metrics" mocknetwork "github.com/onflow/flow-go/network/mock" protocol "github.com/onflow/flow-go/state/protocol/mock" "github.com/onflow/flow-go/utils/unittest" ) -func TestEntityByID(t *testing.T) { - - request := Engine{ - unit: engine.NewUnit(), - items: make(map[flow.Identifier]*Item), - } - - now := time.Now().UTC() - - entityID := unittest.IdentifierFixture() - selector := filter.Any - request.EntityByID(entityID, selector) - - assert.Len(t, request.items, 1) - item, contains := request.items[entityID] - if assert.True(t, contains) { - assert.Equal(t, item.EntityID, entityID) - assert.Equal(t, item.NumAttempts, uint(0)) - cutoff := item.LastRequested.Add(item.RetryAfter) - assert.True(t, cutoff.Before(now)) // make sure we push out immediately - } +func TestRequesterEngine(t *testing.T) { + suite.Run(t, new(RequesterEngineSuite)) } -func TestDispatchRequestVarious(t *testing.T) { +// RequesterEngineSuite is a test suite for the requester engine that holds minimal state for testing. +type RequesterEngineSuite struct { + suite.Suite + con *mocknetwork.Conduit + final *protocol.Snapshot - identities := unittest.IdentityListFixture(16) - targetID := identities[0].NodeID + engine *Engine +} - final := &protocol.Snapshot{} - final.On("Identities", mock.Anything).Return( - func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { - return identities.Filter(selector) - }, - nil, - ) +func (s *RequesterEngineSuite) SetupTest() { + s.final = protocol.NewSnapshot(s.T()) - state := &protocol.State{} - state.On("Final").Return(final) + state := protocol.NewState(s.T()) + state.On("Final").Return(s.final).Maybe() - cfg := Config{ - BatchInterval: 200 * time.Millisecond, - BatchThreshold: 999, - RetryInitial: 100 * time.Millisecond, - RetryFunction: RetryLinear(10 * time.Millisecond), - RetryAttempts: 2, - RetryMaximum: 300 * time.Millisecond, - } + me := module.NewLocal(s.T()) + localID := unittest.IdentifierFixture() + me.On("NodeID").Return(localID).Maybe() - // item that has just been added, should be included - justAdded := &Item{ - EntityID: unittest.IdentifierFixture(), - NumAttempts: 0, - LastRequested: time.Time{}, - RetryAfter: cfg.RetryInitial, - ExtraSelector: filter.Any, - } + s.con = mocknetwork.NewConduit(s.T()) - // item was tried long time ago, should be included - triedAnciently := &Item{ - EntityID: unittest.IdentifierFixture(), - NumAttempts: 1, - LastRequested: time.Now().UTC().Add(-cfg.RetryMaximum), - RetryAfter: cfg.RetryFunction(cfg.RetryInitial), - ExtraSelector: filter.Any, - } + network := mocknetwork.NewEngineRegistry(s.T()) + network.On("Register", mock.Anything, mock.Anything).Return(s.con, nil) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). + requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) + var err error + s.engine, err = New( + zerolog.Nop(), + metrics.NewNoopCollector(), + network, + me, + state, + requestQueue, + "", + filter.Any, + func() flow.Entity { return &flow.Collection{} }, + ) + require.NoError(s.T(), err) +} - // item that was just tried, should be excluded - triedRecently := &Item{ - EntityID: unittest.IdentifierFixture(), - NumAttempts: 1, - LastRequested: time.Now().UTC(), - RetryAfter: cfg.RetryFunction(cfg.RetryInitial), - } +// TestEntityByID verifies that calling EntityByID adds the correct entry +// to the requester's internal map of entities to be requested. +func (s *RequesterEngineSuite) TestEntityByID() { + now := time.Now().UTC() + entityID := unittest.IdentifierFixture() + selector := filter.Any + s.engine.EntityByID(entityID, selector) - // item was tried twice, should be excluded - triedTwice := &Item{ - EntityID: unittest.IdentifierFixture(), - NumAttempts: 2, - LastRequested: time.Time{}, - RetryAfter: cfg.RetryInitial, - ExtraSelector: filter.Any, + assert.Len(s.T(), s.engine.items, 1) + item, contains := s.engine.items[entityID] + if assert.True(s.T(), contains) { + assert.Equal(s.T(), item.QueryKey, entityID) + assert.Equal(s.T(), item.NumAttempts, uint(0)) + cutoff := item.LastRequested.Add(item.RetryAfter) + assert.True(s.T(), cutoff.Before(now)) // make sure we push out immediately } +} - items := make(map[flow.Identifier]*Item) - items[justAdded.EntityID] = justAdded - items[triedAnciently.EntityID] = triedAnciently - items[triedRecently.EntityID] = triedRecently - items[triedTwice.EntityID] = triedTwice - - var nonce uint64 +// TestDispatchRequestVarious verifies that we only dispatch requests for items +// that are eligible based on their retry policy. +func (s *RequesterEngineSuite) TestDispatchRequestVarious() { + synctest.Test(s.T(), func(t *testing.T) { + identities := unittest.IdentityListFixture(16) + targetID := identities[0].NodeID + + s.final.On("Identities", mock.Anything).Return( + func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { + return identities.Filter(selector) + }, + nil, + ) + + cfg := Config{ + BatchInterval: 200 * time.Millisecond, + BatchThreshold: 999, + RetryInitial: 100 * time.Millisecond, + RetryFunction: RetryLinear(10 * time.Millisecond), + RetryAttempts: 2, + RetryMaximum: 300 * time.Millisecond, + } - con := &mocknetwork.Conduit{} - con.On("Unicast", mock.Anything, mock.Anything).Run( - func(args mock.Arguments) { - request := args.Get(0).(*messages.EntityRequest) - originID := args.Get(1).(flow.Identifier) - nonce = request.Nonce - assert.Equal(t, originID, targetID) - assert.ElementsMatch(t, request.EntityIDs, []flow.Identifier{justAdded.EntityID, triedAnciently.EntityID}) - }, - ).Return(nil) - - request := Engine{ - unit: engine.NewUnit(), - metrics: metrics.NewNoopCollector(), - cfg: cfg, - state: state, - con: con, - items: items, - requests: make(map[uint64]*messages.EntityRequest), - selector: filter.HasNodeID[flow.Identity](targetID), - } - dispatched, err := request.dispatchRequest() - require.NoError(t, err) - require.True(t, dispatched) + // item that has just been added, should be included + justAdded := &Request{ + QueryKey: unittest.IdentifierFixture(), + NumAttempts: 0, + LastRequested: time.Time{}, + RetryAfter: cfg.RetryInitial, + ExtraSelector: filter.Any, + } - con.AssertExpectations(t) + // item was tried long time ago, should be included + triedAnciently := &Request{ + QueryKey: unittest.IdentifierFixture(), + NumAttempts: 1, + LastRequested: time.Now().UTC().Add(-cfg.RetryMaximum), + RetryAfter: cfg.RetryFunction(cfg.RetryInitial), + ExtraSelector: filter.Any, + } - request.unit.Lock() - assert.Contains(t, request.requests, nonce) - request.unit.Unlock() + // item that was just tried, should be excluded + triedRecently := &Request{ + QueryKey: unittest.IdentifierFixture(), + NumAttempts: 1, + LastRequested: time.Now().UTC(), + RetryAfter: cfg.RetryFunction(cfg.RetryInitial), + } - // TODO: racy/slow test - time.Sleep(2 * cfg.RetryInitial) + // item was tried twice, should be excluded + triedTwice := &Request{ + QueryKey: unittest.IdentifierFixture(), + NumAttempts: 2, + LastRequested: time.Time{}, + RetryAfter: cfg.RetryInitial, + ExtraSelector: filter.Any, + } - request.unit.Lock() - assert.NotContains(t, request.requests, nonce) - request.unit.Unlock() + items := make(map[flow.Identifier]*Request) + items[justAdded.QueryKey] = justAdded + items[triedAnciently.QueryKey] = triedAnciently + items[triedRecently.QueryKey] = triedRecently + items[triedTwice.QueryKey] = triedTwice + s.engine.cfg = cfg + s.engine.items = items + s.engine.selector = filter.HasNodeID[flow.Identity](targetID) + + var nonce uint64 + + s.con.On("Unicast", mock.Anything, mock.Anything).Run( + func(args mock.Arguments) { + request := args.Get(0).(*messages.EntityRequest) + originID := args.Get(1).(flow.Identifier) + nonce = request.Nonce + assert.Equal(s.T(), originID, targetID) + assert.ElementsMatch(s.T(), request.EntityIDs, []flow.Identifier{justAdded.QueryKey, triedAnciently.QueryKey}) + }, + ).Return(nil).Once() + + dispatched, err := s.engine.dispatchRequest() + require.NoError(s.T(), err) + require.True(s.T(), dispatched) + + s.engine.mu.Lock() + assert.Contains(s.T(), s.engine.requests, nonce) + s.engine.mu.Unlock() + + time.Sleep(cfg.BatchInterval) + unittest.RequireReturnsBefore(s.T(), synctest.Wait, 5*time.Second, "should return before timeout") + + s.engine.mu.Lock() + assert.NotContains(s.T(), s.engine.requests, nonce) + s.engine.mu.Unlock() + }) } -func TestDispatchRequestBatchSize(t *testing.T) { - +// TestDispatchRequestBatchSize verifies that we respect the batch size limit when dispatching requests. +func (s *RequesterEngineSuite) TestDispatchRequestBatchSize() { batchLimit := uint(16) totalItems := uint(99) identities := unittest.IdentityListFixture(16) - - final := &protocol.Snapshot{} - final.On("Identities", mock.Anything).Return( + s.final.On("Identities", mock.Anything).Return( func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { return identities.Filter(selector) }, nil, ) - state := &protocol.State{} - state.On("Final").Return(final) - - cfg := Config{ + s.engine.cfg = Config{ BatchInterval: 24 * time.Hour, BatchThreshold: batchLimit, RetryInitial: 24 * time.Hour, @@ -182,59 +211,46 @@ func TestDispatchRequestBatchSize(t *testing.T) { } // item that has just been added, should be included - items := make(map[flow.Identifier]*Item) for i := uint(0); i < totalItems; i++ { - item := &Item{ - EntityID: unittest.IdentifierFixture(), + item := &Request{ + QueryKey: unittest.IdentifierFixture(), NumAttempts: 0, LastRequested: time.Time{}, - RetryAfter: cfg.RetryInitial, + RetryAfter: s.engine.cfg.RetryInitial, ExtraSelector: filter.Any, } - items[item.EntityID] = item + s.engine.items[item.QueryKey] = item } - con := &mocknetwork.Conduit{} - con.On("Unicast", mock.Anything, mock.Anything).Run( + s.con.On("Unicast", mock.Anything, mock.Anything).Run( func(args mock.Arguments) { request := args.Get(0).(*messages.EntityRequest) - assert.Len(t, request.EntityIDs, int(batchLimit)) + assert.Len(s.T(), request.EntityIDs, int(batchLimit)) }, - ).Return(nil) - - request := Engine{ - unit: engine.NewUnit(), - metrics: metrics.NewNoopCollector(), - cfg: cfg, - state: state, - con: con, - items: items, - requests: make(map[uint64]*messages.EntityRequest), - selector: filter.Any, - } - dispatched, err := request.dispatchRequest() - require.NoError(t, err) - require.True(t, dispatched) + ).Return(nil).Once() - con.AssertExpectations(t) + dispatched, err := s.engine.dispatchRequest() + require.NoError(s.T(), err) + require.True(s.T(), dispatched) } -func TestOnEntityResponseValid(t *testing.T) { - +// TestOnEntityResponseValid verifies that we correctly process a valid entity response, even if +// (i) they only contain a subset of the requested entities. +// (ii) contain extra entities that were not requested. +// Specifically, we expect that only requested entities are processed and removed from the pending items. +// Furthermore, we expect that missing entities are not removed from the pending items, and their +// last requested timestamp is reset to allow for immediate re-requesting. +func (s *RequesterEngineSuite) TestOnEntityResponseValid() { identities := unittest.IdentityListFixture(16) targetID := identities[0].NodeID - final := &protocol.Snapshot{} - final.On("Identities", mock.Anything).Return( + s.final.On("Identities", mock.Anything).Return( func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { return identities.Filter(selector) }, nil, ) - state := &protocol.State{} - state.On("Final").Return(final) - nonce := rand.Uint64() wanted1 := unittest.CollectionFixture(1) @@ -244,18 +260,18 @@ func TestOnEntityResponseValid(t *testing.T) { now := time.Now() - iwanted1 := &Item{ - EntityID: wanted1.ID(), + iwanted1 := &Request{ + QueryKey: wanted1.ID(), LastRequested: now, ExtraSelector: filter.Any, } - iwanted2 := &Item{ - EntityID: wanted2.ID(), + iwanted2 := &Request{ + QueryKey: wanted2.ID(), LastRequested: now, ExtraSelector: filter.Any, } - iunavailable := &Item{ - EntityID: unavailable.ID(), + iunavailable := &Request{ + QueryKey: unavailable.ID(), LastRequested: now, ExtraSelector: filter.Any, } @@ -264,225 +280,172 @@ func TestOnEntityResponseValid(t *testing.T) { bwanted2, _ := msgpack.Marshal(wanted2) bunwanted, _ := msgpack.Marshal(unwanted) - res := &flow.EntityResponse{ + req := &messages.EntityRequest{ Nonce: nonce, - EntityIDs: []flow.Identifier{wanted1.ID(), wanted2.ID(), unwanted.ID()}, - Blobs: [][]byte{bwanted1, bwanted2, bunwanted}, + EntityIDs: []flow.Identifier{wanted1.ID(), wanted2.ID(), unavailable.ID()}, } - req := &messages.EntityRequest{ + res := &flow.EntityResponse{ Nonce: nonce, - EntityIDs: []flow.Identifier{wanted1.ID(), wanted2.ID(), unavailable.ID()}, + EntityIDs: []flow.Identifier{wanted1.ID(), wanted2.ID(), unwanted.ID()}, + Blobs: [][]byte{bwanted1, bwanted2, bunwanted}, } done := make(chan struct{}) called := *atomic.NewUint64(0) - request := Engine{ - unit: engine.NewUnit(), - metrics: metrics.NewNoopCollector(), - state: state, - items: make(map[flow.Identifier]*Item), - requests: make(map[uint64]*messages.EntityRequest), - selector: filter.HasNodeID[flow.Identity](targetID), - create: func() flow.Entity { return &flow.Collection{} }, - handle: func(flow.Identifier, flow.Entity) { - if called.Inc() >= 2 { - close(done) - } - }, - } + s.engine.WithHandle(func(flow.Identifier, flow.Entity) { + if called.Inc() >= 2 { + close(done) + } + }) - request.items[iwanted1.EntityID] = iwanted1 - request.items[iwanted2.EntityID] = iwanted2 - request.items[iunavailable.EntityID] = iunavailable + s.engine.items[iwanted1.QueryKey] = iwanted1 + s.engine.items[iwanted2.QueryKey] = iwanted2 + s.engine.items[iunavailable.QueryKey] = iunavailable - request.requests[req.Nonce] = req + s.engine.requests[req.Nonce] = req - err := request.onEntityResponse(targetID, res) - assert.NoError(t, err) + err := s.engine.onEntityResponse(targetID, res) + assert.NoError(s.T(), err) // check that the request was removed - assert.NotContains(t, request.requests, nonce) + assert.NotContains(s.T(), s.engine.requests, nonce) // check that the provided items were removed - assert.NotContains(t, request.items, wanted1.ID()) - assert.NotContains(t, request.items, wanted2.ID()) + assert.NotContains(s.T(), s.engine.items, wanted1.ID()) + assert.NotContains(s.T(), s.engine.items, wanted2.ID()) // check that the missing item is still there - assert.Contains(t, request.items, unavailable.ID()) + assert.Contains(s.T(), s.engine.items, unavailable.ID()) - // make sure we processed two items - unittest.AssertClosesBefore(t, done, time.Second) + // make sure we processed only two items: this indicates that the unwanted item was ignored + unittest.AssertClosesBefore(s.T(), done, time.Second) // check that the missing items timestamp was reset - assert.Equal(t, iunavailable.LastRequested, time.Time{}) + assert.Equal(s.T(), iunavailable.LastRequested, time.Time{}) } -func TestOnEntityIntegrityCheck(t *testing.T) { +// TestOnEntityIntegrityCheck verifies that +// (i) the structural integrity of received [flow.EntityResponse] messages is properly checked against the hash by which the +// item was requested. This check should be performed if and only if `queryByContentHash` is set to `true` for a requested item. +// (ii) If and only if `queryByContentHash` is `false`, the received entity should not be compared against the requested key. +func (s *RequesterEngineSuite) TestOnEntityIntegrityCheck() { identities := unittest.IdentityListFixture(16) targetID := identities[0].NodeID - final := &protocol.Snapshot{} - final.On("Identities", mock.Anything).Return( + s.final.On("Identities", mock.Anything).Return( func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { return identities.Filter(selector) }, nil, ) - state := &protocol.State{} - state.On("Final").Return(final) - nonce := rand.Uint64() - wanted := unittest.CollectionFixture(1) wanted2 := unittest.CollectionFixture(2) - now := time.Now() - iwanted := &Item{ - EntityID: wanted.ID(), - LastRequested: now, - ExtraSelector: filter.Any, - checkIntegrity: true, + iwanted := &Request{ + QueryKey: wanted.ID(), + LastRequested: now, + ExtraSelector: filter.Any, + queryByContentHash: true, } - assert.NotEqual(t, wanted, wanted2) + assert.NotEqual(s.T(), wanted, wanted2) // sanity check - // prepare payload from different entity - bwanted, _ := msgpack.Marshal(wanted2) - - res := &flow.EntityResponse{ + req := &messages.EntityRequest{ Nonce: nonce, EntityIDs: []flow.Identifier{wanted.ID()}, - Blobs: [][]byte{bwanted}, } - req := &messages.EntityRequest{ + // prepare payload from different entity + bwanted, _ := msgpack.Marshal(wanted2) + res := &flow.EntityResponse{ Nonce: nonce, EntityIDs: []flow.Identifier{wanted.ID()}, + Blobs: [][]byte{bwanted}, } called := make(chan struct{}) - request := Engine{ - unit: engine.NewUnit(), - metrics: metrics.NewNoopCollector(), - state: state, - items: make(map[flow.Identifier]*Item), - requests: make(map[uint64]*messages.EntityRequest), - selector: filter.HasNodeID[flow.Identity](targetID), - create: func() flow.Entity { return &flow.Collection{} }, - handle: func(flow.Identifier, flow.Entity) { close(called) }, - } - - request.items[iwanted.EntityID] = iwanted + s.engine.WithHandle(func(flow.Identifier, flow.Entity) { close(called) }) - request.requests[req.Nonce] = req + // PART (i) + s.engine.items[iwanted.QueryKey] = iwanted + s.engine.requests[req.Nonce] = req - err := request.onEntityResponse(targetID, res) - assert.NoError(t, err) + err := s.engine.onEntityResponse(targetID, res) + assert.NoError(s.T(), err) - // check that the request was removed - assert.NotContains(t, request.requests, nonce) + // check that the request was removed, because it was answered by the selected provider + assert.NotContains(s.T(), s.engine.requests, nonce) - // check that the provided item wasn't removed - assert.Contains(t, request.items, wanted.ID()) + // However, since the provider sent an entity that does not match the requested content hash, the + // request should not be considered fulfilled. Instead, the item should remain in the pending `items` map. + assert.Contains(s.T(), s.engine.items, wanted.ID()) - iwanted.checkIntegrity = false - request.items[iwanted.EntityID] = iwanted - request.requests[req.Nonce] = req + // PART (ii) + iwanted.queryByContentHash = false + s.engine.items[iwanted.QueryKey] = iwanted + s.engine.requests[req.Nonce] = req - err = request.onEntityResponse(targetID, res) - assert.NoError(t, err) + err = s.engine.onEntityResponse(targetID, res) + assert.NoError(s.T(), err) - // make sure we process item without checking integrity - unittest.AssertClosesBefore(t, called, time.Second) + // Since `queryByContentHash` is `false`, the entity should be propagated to the handler, + // despite its hash not matching the requested key. + unittest.AssertClosesBefore(s.T(), called, time.Second) } -// Verify that the origin should not be checked when ValidateStaking config is set to false -func TestOriginValidation(t *testing.T) { +// TestOriginValidation verifies that responses from unexpected origins are rejected. +func (s *RequesterEngineSuite) TestOriginValidation() { identities := unittest.IdentityListFixture(16) targetID := identities[0].NodeID - wrongID := identities[1].NodeID - meID := identities[3].NodeID + wrongID := unittest.IdentifierFixture() - final := &protocol.Snapshot{} - final.On("Identities", mock.Anything).Return( + s.final.On("Identities", mock.Anything).Return( func(selector flow.IdentityFilter[flow.Identity]) flow.IdentityList { return identities.Filter(selector) }, nil, ) - state := &protocol.State{} - state.On("Final").Return(final) - - me := &module.Local{} - - me.On("NodeID").Return(meID) - nonce := rand.Uint64() - wanted := unittest.CollectionFixture(1) - now := time.Now() - - iwanted := &Item{ - EntityID: wanted.ID(), - LastRequested: now, - ExtraSelector: filter.HasNodeID[flow.Identity](targetID), - checkIntegrity: true, + iwanted := &Request{ + QueryKey: wanted.ID(), + LastRequested: now, + ExtraSelector: filter.HasNodeID[flow.Identity](targetID), + queryByContentHash: true, } - // prepare payload - bwanted, _ := msgpack.Marshal(wanted) - - res := &flow.EntityResponse{ + req := &messages.EntityRequest{ Nonce: nonce, EntityIDs: []flow.Identifier{wanted.ID()}, - Blobs: [][]byte{bwanted}, } - req := &messages.EntityRequest{ + // prepare byzantine response: it contains the correct entity, but is from an invalid data source (e.g. ejected peer) + bwanted, _ := msgpack.Marshal(wanted) + res := &flow.EntityResponse{ Nonce: nonce, EntityIDs: []flow.Identifier{wanted.ID()}, + Blobs: [][]byte{bwanted}, } network := &mocknetwork.EngineRegistry{} network.On("Register", mock.Anything, mock.Anything).Return(nil, nil) - e, err := New( - zerolog.Nop(), - metrics.NewNoopCollector(), - network, - me, - state, - "", - filter.HasNodeID[flow.Identity](targetID), - func() flow.Entity { return &flow.Collection{} }, - ) - assert.NoError(t, err) - called := make(chan struct{}) - - e.WithHandle(func(origin flow.Identifier, _ flow.Entity) { + s.engine.WithHandle(func(origin flow.Identifier, _ flow.Entity) { // we expect wrong origin to propagate here with validation disabled - assert.Equal(t, wrongID, origin) + assert.Equal(s.T(), wrongID, origin) close(called) }) - e.items[iwanted.EntityID] = iwanted - e.requests[req.Nonce] = req - - err = e.onEntityResponse(wrongID, res) - assert.Error(t, err) - assert.IsType(t, engine.InvalidInputError{}, err) - - e.cfg.ValidateStaking = false - - err = e.onEntityResponse(wrongID, res) - assert.NoError(t, err) + s.engine.items[iwanted.QueryKey] = iwanted + s.engine.requests[req.Nonce] = req - // handler are called async, but this should be extremely quick - unittest.AssertClosesBefore(t, called, time.Second) + err := s.engine.onEntityResponse(wrongID, res) + assert.True(s.T(), engine.IsInvalidInputError(err)) } diff --git a/engine/common/requester/item.go b/engine/common/requester/item.go index 06cdf2acb01..ce832da4900 100644 --- a/engine/common/requester/item.go +++ b/engine/common/requester/item.go @@ -6,11 +6,11 @@ import ( "github.com/onflow/flow-go/model/flow" ) -type Item struct { - EntityID flow.Identifier // ID for the entity to be requested - NumAttempts uint // number of times the entity was requested - LastRequested time.Time // approximate timestamp of last request - RetryAfter time.Duration // interval until request should be retried - ExtraSelector flow.IdentityFilter[flow.Identity] // additional filters for providers of this entity - checkIntegrity bool // check response integrity using `EntityID` +type Request struct { + QueryKey flow.Identifier // the key used to identify the requested entity (content hash or secondary key) + NumAttempts uint // number of times the entity was requested + LastRequested time.Time // approximate timestamp of last request + RetryAfter time.Duration // interval until request should be retried + ExtraSelector flow.IdentityFilter[flow.Identity] // additional filters for providers of this entity + queryByContentHash bool // whether QueryKey is the content hash of the requested entity } diff --git a/engine/common/rpc/convert/execution_results.go b/engine/common/rpc/convert/execution_results.go index 9dc896ea7ca..a5c67147df0 100644 --- a/engine/common/rpc/convert/execution_results.go +++ b/engine/common/rpc/convert/execution_results.go @@ -143,6 +143,48 @@ func MessagesToExecutionResultMetaList(m []*entities.ExecutionReceiptMeta) (flow return execMetaList[:], nil } +// ExecutionReceiptToMessage converts an execution receipt to a protobuf message. +// If includeResult is true, the full ExecutionResult is included in the message; +// otherwise only the ExecutionReceiptMeta is set. +// +// No error returns are expected during normal operation. +func ExecutionReceiptToMessage(receipt *flow.ExecutionReceipt, includeResult bool) (*entities.ExecutionReceipt, error) { + msg := &entities.ExecutionReceipt{ + Meta: &entities.ExecutionReceiptMeta{ + ExecutorId: IdentifierToMessage(receipt.ExecutorID), + ResultId: IdentifierToMessage(receipt.ExecutionResult.ID()), + Spocks: SignaturesToMessages(receipt.Spocks), + ExecutorSignature: MessageToSignature(receipt.ExecutorSignature), + }, + } + + if includeResult { + result, err := ExecutionResultToMessage(&receipt.ExecutionResult) + if err != nil { + return nil, fmt.Errorf("could not convert execution result: %w", err) + } + msg.ExecutionResult = result + } + + return msg, nil +} + +// ExecutionReceiptsToMessages converts a slice of execution receipts to a slice of protobuf messages. +// If includeResult is true, each message will include the full ExecutionResult. +// +// No error returns are expected during normal operation. +func ExecutionReceiptsToMessages(receipts []*flow.ExecutionReceipt, includeResult bool) ([]*entities.ExecutionReceipt, error) { + msgs := make([]*entities.ExecutionReceipt, len(receipts)) + for i, receipt := range receipts { + msg, err := ExecutionReceiptToMessage(receipt, includeResult) + if err != nil { + return nil, fmt.Errorf("could not convert execution receipt at index %d: %w", i, err) + } + msgs[i] = msg + } + return msgs, nil +} + // ChunkToMessage converts a chunk to a protobuf message func ChunkToMessage(chunk *flow.Chunk) *entities.Chunk { return &entities.Chunk{ diff --git a/engine/common/rpc/convert/execution_results_test.go b/engine/common/rpc/convert/execution_results_test.go index 6a98f61d222..3dc9dea1783 100644 --- a/engine/common/rpc/convert/execution_results_test.go +++ b/engine/common/rpc/convert/execution_results_test.go @@ -9,6 +9,7 @@ import ( "github.com/onflow/flow-go/engine/common/rpc/convert" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/utils/unittest" + "github.com/onflow/flow-go/utils/unittest/fixtures" ) func TestConvertExecutionResult(t *testing.T) { @@ -55,3 +56,91 @@ func TestConvertExecutionResultMetaList(t *testing.T) { assert.Equal(t, metaList, converted) } + +// TestConvertExecutionReceiptExcludeResult tests converting an execution receipt to a proto message +// with includeResult=false. Meta fields must match the original receipt and ExecutionResult must be nil. +func TestConvertExecutionReceiptExcludeResult(t *testing.T) { + t.Parallel() + + g := fixtures.NewGeneratorSuite() + receipt := g.ExecutionReceipts().Fixture() + + msg, err := convert.ExecutionReceiptToMessage(receipt, false) + require.NoError(t, err) + require.NotNil(t, msg.Meta) + assert.Nil(t, msg.ExecutionResult) + + assert.Equal(t, receipt.ExecutorID, convert.MessageToIdentifier(msg.Meta.ExecutorId)) + assert.Equal(t, receipt.ExecutionResult.ID(), convert.MessageToIdentifier(msg.Meta.ResultId)) + assert.Equal(t, receipt.ExecutorSignature, convert.MessageToSignature(msg.Meta.ExecutorSignature)) + assert.Equal(t, receipt.Spocks, convert.MessagesToSignatures(msg.Meta.Spocks)) +} + +// TestConvertExecutionReceiptIncludeResult tests converting an execution receipt to a proto message +// with includeResult=true. Meta fields must match and ExecutionResult must round-trip correctly. +func TestConvertExecutionReceiptIncludeResult(t *testing.T) { + t.Parallel() + + g := fixtures.NewGeneratorSuite() + receipt := g.ExecutionReceipts().Fixture() + + msg, err := convert.ExecutionReceiptToMessage(receipt, true) + require.NoError(t, err) + require.NotNil(t, msg.Meta) + require.NotNil(t, msg.ExecutionResult) + + assert.Equal(t, receipt.ExecutorID, convert.MessageToIdentifier(msg.Meta.ExecutorId)) + assert.Equal(t, receipt.ExecutionResult.ID(), convert.MessageToIdentifier(msg.Meta.ResultId)) + assert.Equal(t, receipt.ExecutorSignature, convert.MessageToSignature(msg.Meta.ExecutorSignature)) + assert.Equal(t, receipt.Spocks, convert.MessagesToSignatures(msg.Meta.Spocks)) + + convertedResult, err := convert.MessageToExecutionResult(msg.ExecutionResult) + require.NoError(t, err) + assert.Equal(t, &receipt.ExecutionResult, convertedResult) +} + +// TestConvertExecutionReceiptsExcludeResult tests the batch conversion with includeResult=false. +func TestConvertExecutionReceiptsExcludeResult(t *testing.T) { + t.Parallel() + + g := fixtures.NewGeneratorSuite() + receipts := g.ExecutionReceipts().List(3) + + msgs, err := convert.ExecutionReceiptsToMessages(receipts, false) + require.NoError(t, err) + require.Len(t, msgs, len(receipts)) + + for i, msg := range msgs { + require.NotNil(t, msg.Meta) + assert.Nil(t, msg.ExecutionResult) + assert.Equal(t, receipts[i].ExecutorID, convert.MessageToIdentifier(msg.Meta.ExecutorId)) + assert.Equal(t, receipts[i].ExecutionResult.ID(), convert.MessageToIdentifier(msg.Meta.ResultId)) + assert.Equal(t, receipts[i].ExecutorSignature, convert.MessageToSignature(msg.Meta.ExecutorSignature)) + assert.Equal(t, receipts[i].Spocks, convert.MessagesToSignatures(msg.Meta.Spocks)) + } +} + +// TestConvertExecutionReceiptsIncludeResult tests the batch conversion with includeResult=true. +func TestConvertExecutionReceiptsIncludeResult(t *testing.T) { + t.Parallel() + + g := fixtures.NewGeneratorSuite() + receipts := g.ExecutionReceipts().List(3) + + msgs, err := convert.ExecutionReceiptsToMessages(receipts, true) + require.NoError(t, err) + require.Len(t, msgs, len(receipts)) + + for i, msg := range msgs { + require.NotNil(t, msg.Meta) + require.NotNil(t, msg.ExecutionResult) + assert.Equal(t, receipts[i].ExecutorID, convert.MessageToIdentifier(msg.Meta.ExecutorId)) + assert.Equal(t, receipts[i].ExecutionResult.ID(), convert.MessageToIdentifier(msg.Meta.ResultId)) + assert.Equal(t, receipts[i].ExecutorSignature, convert.MessageToSignature(msg.Meta.ExecutorSignature)) + assert.Equal(t, receipts[i].Spocks, convert.MessagesToSignatures(msg.Meta.Spocks)) + + convertedResult, err := convert.MessageToExecutionResult(msg.ExecutionResult) + require.NoError(t, err) + assert.Equal(t, &receipts[i].ExecutionResult, convertedResult) + } +} diff --git a/engine/common/rpc/convert/transaction_result.go b/engine/common/rpc/convert/transaction_result.go index f5e21ce1c2d..6ee8ff88f1b 100644 --- a/engine/common/rpc/convert/transaction_result.go +++ b/engine/common/rpc/convert/transaction_result.go @@ -13,14 +13,15 @@ import ( // TransactionResultToMessage converts a TransactionResult to a protobuf message func TransactionResultToMessage(result *accessmodel.TransactionResult) *access.TransactionResultResponse { return &access.TransactionResultResponse{ - Status: entities.TransactionStatus(result.Status), - StatusCode: uint32(result.StatusCode), - ErrorMessage: result.ErrorMessage, - Events: EventsToMessages(result.Events), - BlockId: result.BlockID[:], - TransactionId: result.TransactionID[:], - CollectionId: result.CollectionID[:], - BlockHeight: result.BlockHeight, + Status: entities.TransactionStatus(result.Status), + StatusCode: uint32(result.StatusCode), + ErrorMessage: result.ErrorMessage, + Events: EventsToMessages(result.Events), + BlockId: result.BlockID[:], + TransactionId: result.TransactionID[:], + CollectionId: result.CollectionID[:], + BlockHeight: result.BlockHeight, + ComputationUsage: result.ComputationUsed, } } @@ -33,14 +34,15 @@ func MessageToTransactionResult(message *access.TransactionResultResponse) (*acc } return &accessmodel.TransactionResult{ - Status: flow.TransactionStatus(message.Status), - StatusCode: uint(message.StatusCode), - ErrorMessage: message.ErrorMessage, - Events: events, - BlockID: flow.HashToID(message.BlockId), - TransactionID: flow.HashToID(message.TransactionId), - CollectionID: flow.HashToID(message.CollectionId), - BlockHeight: message.BlockHeight, + Status: flow.TransactionStatus(message.Status), + StatusCode: uint(message.StatusCode), + ErrorMessage: message.ErrorMessage, + Events: events, + BlockID: flow.HashToID(message.BlockId), + TransactionID: flow.HashToID(message.TransactionId), + CollectionID: flow.HashToID(message.CollectionId), + BlockHeight: message.BlockHeight, + ComputationUsed: message.ComputationUsage, }, nil } diff --git a/engine/common/rpc/convert/transaction_result_test.go b/engine/common/rpc/convert/transaction_result_test.go index 2d4a62b4436..255e320a06f 100644 --- a/engine/common/rpc/convert/transaction_result_test.go +++ b/engine/common/rpc/convert/transaction_result_test.go @@ -40,13 +40,14 @@ func TestConvertTransactionResults(t *testing.T) { func txResultFixture() *accessmodel.TransactionResult { return &accessmodel.TransactionResult{ - Status: flow.TransactionStatusExecuted, - StatusCode: 0, - Events: unittest.EventsFixture(3), - ErrorMessage: "", - BlockID: unittest.IdentifierFixture(), - TransactionID: unittest.IdentifierFixture(), - CollectionID: unittest.IdentifierFixture(), - BlockHeight: 100, + Status: flow.TransactionStatusExecuted, + StatusCode: 0, + Events: unittest.EventsFixture(3), + ErrorMessage: "", + BlockID: unittest.IdentifierFixture(), + TransactionID: unittest.IdentifierFixture(), + CollectionID: unittest.IdentifierFixture(), + BlockHeight: 100, + ComputationUsed: 9999, } } diff --git a/engine/common/rpc/convert/transactions.go b/engine/common/rpc/convert/transactions.go index 63b337d8116..6e5ff9058b6 100644 --- a/engine/common/rpc/convert/transactions.go +++ b/engine/common/rpc/convert/transactions.go @@ -138,3 +138,17 @@ func TransactionsToMessages(transactions []*flow.TransactionBody) []*entities.Tr } return transactionMessages } + +// MessagesToTransactions converts a slice of protobuf messages to a slice of flow.TransactionBody +func MessagesToTransactions(messages []*entities.Transaction, chain flow.Chain) ([]*flow.TransactionBody, error) { + messagesToTransactions := make([]*flow.TransactionBody, len(messages)) + for i, m := range messages { + tx, err := MessageToTransaction(m, chain) + if err != nil { + return messagesToTransactions, fmt.Errorf("could not convert messages: %w", err) + } + + messagesToTransactions[i] = &tx + } + return messagesToTransactions, nil +} diff --git a/engine/common/rpc/execution_node_identities_provider.go b/engine/common/rpc/execution_node_identities_provider.go index 8bd9ec26d3e..aa6d514447f 100644 --- a/engine/common/rpc/execution_node_identities_provider.go +++ b/engine/common/rpc/execution_node_identities_provider.go @@ -70,8 +70,8 @@ func NewExecutionNodeIdentitiesProvider( // which have executed the given block ID. // // Expected errors during normal operations: -// - InsufficientExecutionReceipts - If no such execution node is found. -// - ErrNoENsFoundForExecutionResult - if no execution nodes were found that produced +// - [context.Canceled] - if the context is canceled +// - [ErrNoENsFoundForExecutionResult] - if no execution nodes were found that produced // the provided execution result and matched the operators criteria func (e *ExecutionNodeIdentitiesProvider) ExecutionNodesForBlockID( ctx context.Context, diff --git a/engine/common/version/version_control.go b/engine/common/version/version_control.go index aac2f96ae40..3944208e06f 100644 --- a/engine/common/version/version_control.go +++ b/engine/common/version/version_control.go @@ -38,6 +38,7 @@ var NoHeight = uint64(0) // IMPORTANT: only add versions to this list if you are certain that the cadence and fvm changes // deployed during the HCU are backwards compatible for scripts. var defaultCompatibilityOverrides = map[string]struct{}{ + "0.37.11": {}, // mainnet, testnet "0.37.17": {}, // mainnet, testnet "0.37.18": {}, // testnet only "0.37.20": {}, // mainnet, testnet @@ -51,8 +52,26 @@ var defaultCompatibilityOverrides = map[string]struct{}{ "0.41.4": {}, // mainnet, testnet "0.42.0": {}, // mainnet, testnet "0.42.1": {}, // mainnet, testnet + "0.42.3": {}, // mainnet, testnet "0.43.1": {}, // testnet only "0.44.0": {}, // mainnet, testnet + "0.44.1": {}, // mainnet, testnet + "0.44.7": {}, // mainnet, testnet + "0.44.10": {}, // mainnet, testnet + "0.44.14": {}, // mainnet, testnet + "0.44.15": {}, // mainnet, testnet + "0.44.16": {}, // mainnet, testnet + "0.44.17": {}, // mainnet, testnet + "0.44.18": {}, // mainnet, testnet + "0.45.0": {}, // mainnet, testnet + "0.46.0": {}, // mainnet, testnet + "0.46.1": {}, // mainnet, testnet + "0.47.0": {}, // mainnet, testnet + "0.48.0": {}, // mainnet, testnet + "0.49.0": {}, // mainnet, testnet + "0.49.1": {}, // mainnet, testnet + "0.49.2": {}, // mainnet, testnet + "0.50.0": {}, // mainnet, testnet } // VersionControl manages the version control system for the node. @@ -389,13 +408,14 @@ func (v *VersionControl) blockFinalized( // Start height is the sealed root block if there is no start boundary in the current spork. func (v *VersionControl) StartHeight() uint64 { startHeight := v.startHeight.Load() + sealedRootHeight := v.sealedRootBlockHeight.Load() // in case no start boundary in the current spork if startHeight == NoHeight { - startHeight = v.sealedRootBlockHeight.Load() + startHeight = sealedRootHeight } - return startHeight + return max(startHeight, sealedRootHeight) } // EndHeight return the last block that the version supports. diff --git a/engine/common/version/version_control_test.go b/engine/common/version/version_control_test.go index 4dce52bd8f3..5e1db72b919 100644 --- a/engine/common/version/version_control_test.go +++ b/engine/common/version/version_control_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + "go.uber.org/atomic" + "github.com/onflow/flow-go/utils/unittest/mocks" "github.com/coreos/go-semver/semver" @@ -188,8 +190,14 @@ func TestVersionControlInitialization(t *testing.T) { name: "start and end version set, start ignored due to override", nodeVersion: "0.0.2", versionEvents: []*flow.SealedVersionBeacon{ - VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{BlockHeight: sealedRootBlockHeight + 12, Version: "0.0.1"}), - VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{BlockHeight: latestBlockHeight - 8, Version: "0.0.3"}), + VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{ + BlockHeight: sealedRootBlockHeight + 12, + Version: "0.0.1", + }), + VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{ + BlockHeight: latestBlockHeight - 8, + Version: "0.0.3", + }), }, overrides: map[string]struct{}{"0.0.1": {}}, expectedStart: sealedRootBlockHeight, @@ -199,8 +207,14 @@ func TestVersionControlInitialization(t *testing.T) { name: "start and end version set, end ignored due to override", nodeVersion: "0.0.2", versionEvents: []*flow.SealedVersionBeacon{ - VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{BlockHeight: sealedRootBlockHeight + 12, Version: "0.0.1"}), - VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{BlockHeight: latestBlockHeight - 8, Version: "0.0.3"}), + VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{ + BlockHeight: sealedRootBlockHeight + 12, + Version: "0.0.1", + }), + VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{ + BlockHeight: latestBlockHeight - 8, + Version: "0.0.3", + }), }, overrides: map[string]struct{}{"0.0.3": {}}, expectedStart: sealedRootBlockHeight + 12, @@ -210,9 +224,18 @@ func TestVersionControlInitialization(t *testing.T) { name: "start and end version set, middle envent ignored due to override", nodeVersion: "0.0.2", versionEvents: []*flow.SealedVersionBeacon{ - VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{BlockHeight: sealedRootBlockHeight + 12, Version: "0.0.1"}), - VersionBeaconEvent(latestBlockHeight-3, flow.VersionBoundary{BlockHeight: latestBlockHeight - 1, Version: "0.0.3"}), - VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{BlockHeight: latestBlockHeight - 8, Version: "0.0.4"}), + VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{ + BlockHeight: sealedRootBlockHeight + 12, + Version: "0.0.1", + }), + VersionBeaconEvent(latestBlockHeight-3, flow.VersionBoundary{ + BlockHeight: latestBlockHeight - 1, + Version: "0.0.3", + }), + VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{ + BlockHeight: latestBlockHeight - 8, + Version: "0.0.4", + }), }, overrides: map[string]struct{}{"0.0.3": {}}, expectedStart: sealedRootBlockHeight + 12, @@ -222,13 +245,32 @@ func TestVersionControlInitialization(t *testing.T) { name: "pre-release version matches overrides", nodeVersion: "0.0.2", versionEvents: []*flow.SealedVersionBeacon{ - VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{BlockHeight: sealedRootBlockHeight + 12, Version: "0.0.1-pre-release.0"}), - VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{BlockHeight: latestBlockHeight - 8, Version: "0.0.3"}), + VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{ + BlockHeight: sealedRootBlockHeight + 12, + Version: "0.0.1-pre-release.0", + }), + VersionBeaconEvent(latestBlockHeight-10, flow.VersionBoundary{ + BlockHeight: latestBlockHeight - 8, + Version: "0.0.3", + }), }, overrides: map[string]struct{}{"0.0.1": {}}, expectedStart: sealedRootBlockHeight, expectedEnd: latestBlockHeight - 9, }, + { + name: "version boundary height is lower than spork root height", + nodeVersion: "0.0.1", + versionEvents: []*flow.SealedVersionBeacon{ + VersionBeaconEvent(sealedRootBlockHeight+10, flow.VersionBoundary{ + BlockHeight: sealedRootBlockHeight - 10, + Version: "0.0.1", + }), + }, + overrides: map[string]struct{}{}, + expectedStart: sealedRootBlockHeight, + expectedEnd: latestBlockHeight, + }, } for _, testCase := range testCases { @@ -278,6 +320,39 @@ func TestVersionControlInitialization(t *testing.T) { } } +// TestVersionControlStartHeight verifies that StartHeight correctly resolves the +// effective starting block height based on an optional start boundary and the +// sealed root block height. +// +// Test cases: +// 1. When no start boundary is set, the sealed root block height is returned. +// 2. When the start boundary is higher than the sealed root, the start boundary is used. +// 3. When the start boundary is lower than the sealed root, the result is clamped to the sealed root. +func TestVersionControlStartHeight(t *testing.T) { + vc := &VersionControl{} + + t.Run("no start boundary → sealed root returned", func(t *testing.T) { + vc.startHeight = atomic.NewUint64(NoHeight) + vc.sealedRootBlockHeight = atomic.NewUint64(1000) + + require.Equal(t, uint64(1000), vc.StartHeight()) + }) + + t.Run("start boundary above sealed root", func(t *testing.T) { + vc.startHeight = atomic.NewUint64(1200) + vc.sealedRootBlockHeight = atomic.NewUint64(1000) + + require.Equal(t, uint64(1200), vc.StartHeight()) + }) + + t.Run("start boundary below sealed root → clamp to sealed root", func(t *testing.T) { + vc.startHeight = atomic.NewUint64(900) + vc.sealedRootBlockHeight = atomic.NewUint64(1000) + + require.Equal(t, uint64(1000), vc.StartHeight()) + }) +} + // TestVersionControlInitializationWithErrors tests the initialization process of the VersionControl component with error cases func TestVersionControlInitializationWithErrors(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) diff --git a/engine/consensus/approvals/approval_collector_test.go b/engine/consensus/approvals/approval_collector_test.go index 4b283559eb8..0a652aa8821 100644 --- a/engine/consensus/approvals/approval_collector_test.go +++ b/engine/consensus/approvals/approval_collector_test.go @@ -1,4 +1,4 @@ -package approvals +package approvals_test import ( "testing" @@ -8,6 +8,8 @@ import ( "github.com/stretchr/testify/suite" "github.com/onflow/flow-go/engine" + "github.com/onflow/flow-go/engine/consensus/approvals" + "github.com/onflow/flow-go/engine/consensus/approvals/testutil" "github.com/onflow/flow-go/model/flow" mempool "github.com/onflow/flow-go/module/mempool/mock" "github.com/onflow/flow-go/utils/unittest" @@ -23,10 +25,10 @@ func TestApprovalCollector(t *testing.T) { } type ApprovalCollectorTestSuite struct { - BaseApprovalsTestSuite + testutil.BaseApprovalsTestSuite sealsPL *mempool.IncorporatedResultSeals - collector *ApprovalCollector + collector *approvals.ApprovalCollector } func (s *ApprovalCollectorTestSuite) SetupTest() { @@ -34,7 +36,7 @@ func (s *ApprovalCollectorTestSuite) SetupTest() { s.sealsPL = &mempool.IncorporatedResultSeals{} var err error - s.collector, err = NewApprovalCollector(unittest.Logger(), s.IncorporatedResult, s.IncorporatedBlock, s.Block, s.ChunksAssignment, s.sealsPL, uint(len(s.AuthorizedVerifiers))) + s.collector, err = approvals.NewApprovalCollector(unittest.Logger(), s.IncorporatedResult, s.IncorporatedBlock, s.Block, s.ChunksAssignment, s.sealsPL, uint(len(s.AuthorizedVerifiers))) require.NoError(s.T(), err) } @@ -62,7 +64,7 @@ func (s *ApprovalCollectorTestSuite) TestProcessApproval_SealResult() { for i, chunk := range s.Chunks { var err error - sigCollector := NewSignatureCollector() + sigCollector := approvals.NewSignatureCollector() for verID := range s.AuthorizedVerifiers { approval := unittest.ResultApprovalFixture(unittest.WithChunk(chunk.Index), unittest.WithApproverID(verID)) err = s.collector.ProcessApproval(approval) diff --git a/engine/consensus/approvals/assignment_collector_statemachine_test.go b/engine/consensus/approvals/assignment_collector_statemachine_test.go index aeb3bd6a3b4..e19449b69fe 100644 --- a/engine/consensus/approvals/assignment_collector_statemachine_test.go +++ b/engine/consensus/approvals/assignment_collector_statemachine_test.go @@ -1,4 +1,4 @@ -package approvals +package approvals_test import ( "sync" @@ -6,10 +6,13 @@ import ( "time" "github.com/gammazero/workerpool" + "github.com/rs/zerolog" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/onflow/flow-go/engine/consensus/approvals" + "github.com/onflow/flow-go/engine/consensus/approvals/testutil" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/utils/unittest" ) @@ -17,8 +20,8 @@ import ( // AssignmentCollectorStateMachineTestSuite is a test suite for testing AssignmentCollectorStateMachine. Contains a minimal set of // helper mocks to test the behavior. type AssignmentCollectorStateMachineTestSuite struct { - BaseAssignmentCollectorTestSuite - collector *AssignmentCollectorStateMachine + testutil.BaseAssignmentCollectorTestSuite + collector *approvals.AssignmentCollectorStateMachine } func TestAssignmentCollectorStateMachine(t *testing.T) { @@ -28,26 +31,28 @@ func TestAssignmentCollectorStateMachine(t *testing.T) { func (s *AssignmentCollectorStateMachineTestSuite) SetupTest() { s.BaseAssignmentCollectorTestSuite.SetupTest() - s.collector = NewAssignmentCollectorStateMachine(AssignmentCollectorBase{ - workerPool: workerpool.New(4), - assigner: s.Assigner, - state: s.State, - headers: s.Headers, - sigHasher: s.SigHasher, - seals: s.SealsPL, - approvalConduit: s.Conduit, - requestTracker: s.RequestTracker, - requiredApprovalsForSealConstruction: 5, - executedBlock: s.Block, - result: s.IncorporatedResult.Result, - resultID: s.IncorporatedResult.Result.ID(), - }) + ac, err := approvals.NewAssignmentCollectorBase( + zerolog.Nop(), + workerpool.New(4), + s.IncorporatedResult.Result, + s.State, + s.Headers, + s.Assigner, + s.SealsPL, + s.SigHasher, + s.Conduit, + s.RequestTracker, + 5, + ) + require.NoError(s.T(), err) + + s.collector = approvals.NewAssignmentCollectorStateMachine(ac) } // TestChangeProcessingStatus_CachingToVerifying tests that state machine correctly performs transition from CachingApprovals to // VerifyingApprovals state. After transition all caches approvals and results need to be applied to new state. func (s *AssignmentCollectorStateMachineTestSuite) TestChangeProcessingStatus_CachingToVerifying() { - require.Equal(s.T(), CachingApprovals, s.collector.ProcessingStatus()) + require.Equal(s.T(), approvals.CachingApprovals, s.collector.ProcessingStatus()) results := make([]*flow.IncorporatedResult, 3) s.PublicKey.On("Verify", mock.Anything, mock.Anything, mock.Anything).Return(true, nil) @@ -62,58 +67,47 @@ func (s *AssignmentCollectorStateMachineTestSuite) TestChangeProcessingStatus_Ca results[i] = result } - approvals := make([]*flow.ResultApproval, s.Chunks.Len()) + approvs := make([]*flow.ResultApproval, s.Chunks.Len()) - for i := range approvals { + for i := range approvs { approval := unittest.ResultApprovalFixture( unittest.WithExecutionResultID(s.IncorporatedResult.Result.ID()), unittest.WithChunk(uint64(i)), unittest.WithApproverID(s.VerID), unittest.WithBlockID(s.Block.ID()), ) - approvals[i] = approval + approvs[i] = approval } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for _, result := range results { require.NoError(s.T(), s.collector.ProcessIncorporatedResult(result)) } - }() - - wg.Add(1) - go func() { - defer wg.Done() - for _, approval := range approvals { + }) + wg.Go(func() { + for _, approval := range approvs { require.NoError(s.T(), s.collector.ProcessApproval(approval)) } - }() + }) - err := s.collector.ChangeProcessingStatus(CachingApprovals, VerifyingApprovals) + err := s.collector.ChangeProcessingStatus(approvals.CachingApprovals, approvals.VerifyingApprovals) require.NoError(s.T(), err) - require.Equal(s.T(), VerifyingApprovals, s.collector.ProcessingStatus()) + require.Equal(s.T(), approvals.VerifyingApprovals, s.collector.ProcessingStatus()) wg.Wait() // give some time to process on worker pool time.Sleep(1 * time.Second) // need to check if collector has processed cached items - verifyingCollector, ok := s.collector.atomicLoadCollector().(*VerifyingAssignmentCollector) + verifyingCollector, ok := s.collector.GetCollectorState().(*approvals.VerifyingAssignmentCollector) require.True(s.T(), ok) for _, ir := range results { - verifyingCollector.lock.Lock() - collector, ok := verifyingCollector.collectors[ir.IncorporatedBlockID] - verifyingCollector.lock.Unlock() - require.True(s.T(), ok) - - for _, approval := range approvals { - chunkCollector := collector.chunkCollectors[approval.Body.ChunkIndex] - chunkCollector.lock.Lock() - signed := chunkCollector.chunkApprovals.HasSigned(approval.Body.ApproverID) - chunkCollector.lock.Unlock() + require.True(s.T(), verifyingCollector.HasIncorporatedResult(ir.IncorporatedBlockID)) + + for _, approval := range approvs { + signed := verifyingCollector.HasApprovalBeenProcessed(ir.IncorporatedBlockID, approval.Body.ChunkIndex, approval.Body.ApproverID) require.True(s.T(), signed) } } @@ -123,10 +117,10 @@ func (s *AssignmentCollectorStateMachineTestSuite) TestChangeProcessingStatus_Ca // but with underlying orphan status. This should result in sentinel error ErrInvalidCollectorStateTransition. func (s *AssignmentCollectorStateMachineTestSuite) TestChangeProcessingStatus_InvalidTransition() { // first change status to orphan - err := s.collector.ChangeProcessingStatus(CachingApprovals, Orphaned) + err := s.collector.ChangeProcessingStatus(approvals.CachingApprovals, approvals.Orphaned) require.NoError(s.T(), err) - require.Equal(s.T(), Orphaned, s.collector.ProcessingStatus()) + require.Equal(s.T(), approvals.Orphaned, s.collector.ProcessingStatus()) // then try to perform transition from caching to verifying - err = s.collector.ChangeProcessingStatus(CachingApprovals, VerifyingApprovals) - require.ErrorIs(s.T(), err, ErrDifferentCollectorState) + err = s.collector.ChangeProcessingStatus(approvals.CachingApprovals, approvals.VerifyingApprovals) + require.ErrorIs(s.T(), err, approvals.ErrDifferentCollectorState) } diff --git a/engine/consensus/approvals/assignment_collector_tree_test.go b/engine/consensus/approvals/assignment_collector_tree_test.go index b05a2212682..0c84a7abbe4 100644 --- a/engine/consensus/approvals/assignment_collector_tree_test.go +++ b/engine/consensus/approvals/assignment_collector_tree_test.go @@ -13,6 +13,7 @@ import ( "github.com/onflow/flow-go/engine" "github.com/onflow/flow-go/engine/consensus/approvals" mockAC "github.com/onflow/flow-go/engine/consensus/approvals/mock" + "github.com/onflow/flow-go/engine/consensus/approvals/testutil" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/utils/unittest" ) @@ -34,7 +35,7 @@ type mockedCollectorWrapper struct { } type AssignmentCollectorTreeSuite struct { - approvals.BaseAssignmentCollectorTestSuite + testutil.BaseAssignmentCollectorTestSuite collectorTree *approvals.AssignmentCollectorTree factoryMethod approvals.NewCollectorFactoryMethod diff --git a/engine/consensus/approvals/chunk_collector_test.go b/engine/consensus/approvals/chunk_collector_test.go index bb14345b01a..5b7b51778e9 100644 --- a/engine/consensus/approvals/chunk_collector_test.go +++ b/engine/consensus/approvals/chunk_collector_test.go @@ -1,4 +1,4 @@ -package approvals +package approvals_test import ( "testing" @@ -6,6 +6,8 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/onflow/flow-go/engine/consensus/approvals" + "github.com/onflow/flow-go/engine/consensus/approvals/testutil" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/utils/unittest" ) @@ -19,11 +21,11 @@ func TestChunkApprovalCollector(t *testing.T) { } type ChunkApprovalCollectorTestSuite struct { - BaseApprovalsTestSuite + testutil.BaseApprovalsTestSuite chunk *flow.Chunk chunkAssignment map[flow.Identifier]struct{} - collector *ChunkApprovalCollector + collector *approvals.ChunkApprovalCollector } func (s *ChunkApprovalCollectorTestSuite) SetupTest() { @@ -32,16 +34,17 @@ func (s *ChunkApprovalCollectorTestSuite) SetupTest() { verifiers, err := s.ChunksAssignment.Verifiers(s.chunk.Index) require.NoError(s.T(), err) s.chunkAssignment = verifiers - s.collector = NewChunkApprovalCollector(s.chunkAssignment, uint(len(s.chunkAssignment))) + s.collector = approvals.NewChunkApprovalCollector(s.chunkAssignment, uint(len(s.chunkAssignment))) } // TestProcessApproval_ValidApproval tests processing a valid approval. Expected to process it without error // and report status to caller. func (s *ChunkApprovalCollectorTestSuite) TestProcessApproval_ValidApproval() { approval := unittest.ResultApprovalFixture(unittest.WithChunk(s.chunk.Index), unittest.WithApproverID(s.VerID)) + require.Len(s.T(), s.collector.GetMissingSigners(), len(s.chunkAssignment)) _, collected := s.collector.ProcessApproval(approval) require.False(s.T(), collected) - require.Equal(s.T(), uint(1), s.collector.chunkApprovals.NumberSignatures()) + require.Len(s.T(), s.collector.GetMissingSigners(), len(s.chunkAssignment)-1) } // TestProcessApproval_InvalidChunkAssignment tests processing approval with invalid chunk assignment. Expected to @@ -49,9 +52,10 @@ func (s *ChunkApprovalCollectorTestSuite) TestProcessApproval_ValidApproval() { func (s *ChunkApprovalCollectorTestSuite) TestProcessApproval_InvalidChunkAssignment() { approval := unittest.ResultApprovalFixture(unittest.WithChunk(s.chunk.Index), unittest.WithApproverID(s.VerID)) delete(s.chunkAssignment, s.VerID) + require.Len(s.T(), s.collector.GetMissingSigners(), len(s.chunkAssignment)) _, collected := s.collector.ProcessApproval(approval) require.False(s.T(), collected) - require.Equal(s.T(), uint(0), s.collector.chunkApprovals.NumberSignatures()) + require.Len(s.T(), s.collector.GetMissingSigners(), len(s.chunkAssignment)) } // TestGetAggregatedSignature_MultipleApprovals tests processing approvals from different verifiers. Expected to provide a valid @@ -59,7 +63,8 @@ func (s *ChunkApprovalCollectorTestSuite) TestProcessApproval_InvalidChunkAssign func (s *ChunkApprovalCollectorTestSuite) TestGetAggregatedSignature_MultipleApprovals() { var aggregatedSig flow.AggregatedSignature var collected bool - sigCollector := NewSignatureCollector() + sigCollector := approvals.NewSignatureCollector() + require.Len(s.T(), s.collector.GetMissingSigners(), len(s.chunkAssignment)) for verID := range s.AuthorizedVerifiers { approval := unittest.ResultApprovalFixture(unittest.WithChunk(s.chunk.Index), unittest.WithApproverID(verID)) aggregatedSig, collected = s.collector.ProcessApproval(approval) @@ -68,7 +73,7 @@ func (s *ChunkApprovalCollectorTestSuite) TestGetAggregatedSignature_MultipleApp require.True(s.T(), collected) require.NotNil(s.T(), aggregatedSig) - require.Equal(s.T(), uint(len(s.AuthorizedVerifiers)), s.collector.chunkApprovals.NumberSignatures()) + require.Empty(s.T(), s.collector.GetMissingSigners()) require.Equal(s.T(), sigCollector.ToAggregatedSignature(), aggregatedSig) } diff --git a/engine/consensus/approvals/export_test.go b/engine/consensus/approvals/export_test.go new file mode 100644 index 00000000000..76a6aec982a --- /dev/null +++ b/engine/consensus/approvals/export_test.go @@ -0,0 +1,40 @@ +package approvals + +import "github.com/onflow/flow-go/model/flow" + +// The functions in this file expose internal state for testing purposes only. +// They are only available to tests in the approvals_test package. + +// GetCollectorState returns the underlying AssignmentCollectorState for testing. +func (asm *AssignmentCollectorStateMachine) GetCollectorState() AssignmentCollectorState { + return asm.atomicLoadCollector() +} + +// HasApprovalBeenProcessed checks if an approval from a given approver for a specific chunk +// has been processed for a given incorporated block. This is used for testing to verify +// that approvals were correctly transferred from CachingAssignmentCollector to VerifyingAssignmentCollector. +func (ac *VerifyingAssignmentCollector) HasApprovalBeenProcessed(incorporatedBlockID flow.Identifier, chunkIndex uint64, approverID flow.Identifier) bool { + ac.lock.RLock() + collector, ok := ac.collectors[incorporatedBlockID] + ac.lock.RUnlock() + if !ok { + return false + } + + if chunkIndex >= uint64(len(collector.chunkCollectors)) { + return false + } + + chunkCollector := collector.chunkCollectors[chunkIndex] + chunkCollector.lock.Lock() + defer chunkCollector.lock.Unlock() + return chunkCollector.chunkApprovals.HasSigned(approverID) +} + +// HasIncorporatedResult checks if an incorporated result has been processed for a given incorporated block. +func (ac *VerifyingAssignmentCollector) HasIncorporatedResult(incorporatedBlockID flow.Identifier) bool { + ac.lock.RLock() + defer ac.lock.RUnlock() + _, ok := ac.collectors[incorporatedBlockID] + return ok +} diff --git a/engine/consensus/approvals/mock/assignment_collector.go b/engine/consensus/approvals/mock/assignment_collector.go index d34c93bd206..b2b7e57778d 100644 --- a/engine/consensus/approvals/mock/assignment_collector.go +++ b/engine/consensus/approvals/mock/assignment_collector.go @@ -1,154 +1,398 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - consensus "github.com/onflow/flow-go/engine/consensus" - approvals "github.com/onflow/flow-go/engine/consensus/approvals" - - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/engine/consensus" + "github.com/onflow/flow-go/engine/consensus/approvals" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewAssignmentCollector creates a new instance of AssignmentCollector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAssignmentCollector(t interface { + mock.TestingT + Cleanup(func()) +}) *AssignmentCollector { + mock := &AssignmentCollector{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AssignmentCollector is an autogenerated mock type for the AssignmentCollector type type AssignmentCollector struct { mock.Mock } -// Block provides a mock function with no fields -func (_m *AssignmentCollector) Block() *flow.Header { - ret := _m.Called() +type AssignmentCollector_Expecter struct { + mock *mock.Mock +} + +func (_m *AssignmentCollector) EXPECT() *AssignmentCollector_Expecter { + return &AssignmentCollector_Expecter{mock: &_m.Mock} +} + +// Block provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) Block() *flow.Header { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Block") } var r0 *flow.Header - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - return r0 } -// BlockID provides a mock function with no fields -func (_m *AssignmentCollector) BlockID() flow.Identifier { - ret := _m.Called() +// AssignmentCollector_Block_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Block' +type AssignmentCollector_Block_Call struct { + *mock.Call +} + +// Block is a helper method to define mock.On call +func (_e *AssignmentCollector_Expecter) Block() *AssignmentCollector_Block_Call { + return &AssignmentCollector_Block_Call{Call: _e.mock.On("Block")} +} + +func (_c *AssignmentCollector_Block_Call) Run(run func()) *AssignmentCollector_Block_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollector_Block_Call) Return(header *flow.Header) *AssignmentCollector_Block_Call { + _c.Call.Return(header) + return _c +} + +func (_c *AssignmentCollector_Block_Call) RunAndReturn(run func() *flow.Header) *AssignmentCollector_Block_Call { + _c.Call.Return(run) + return _c +} + +// BlockID provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) BlockID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for BlockID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// ChangeProcessingStatus provides a mock function with given fields: expectedValue, newValue -func (_m *AssignmentCollector) ChangeProcessingStatus(expectedValue approvals.ProcessingStatus, newValue approvals.ProcessingStatus) error { - ret := _m.Called(expectedValue, newValue) +// AssignmentCollector_BlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockID' +type AssignmentCollector_BlockID_Call struct { + *mock.Call +} + +// BlockID is a helper method to define mock.On call +func (_e *AssignmentCollector_Expecter) BlockID() *AssignmentCollector_BlockID_Call { + return &AssignmentCollector_BlockID_Call{Call: _e.mock.On("BlockID")} +} + +func (_c *AssignmentCollector_BlockID_Call) Run(run func()) *AssignmentCollector_BlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollector_BlockID_Call) Return(identifier flow.Identifier) *AssignmentCollector_BlockID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *AssignmentCollector_BlockID_Call) RunAndReturn(run func() flow.Identifier) *AssignmentCollector_BlockID_Call { + _c.Call.Return(run) + return _c +} + +// ChangeProcessingStatus provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) ChangeProcessingStatus(expectedValue approvals.ProcessingStatus, newValue approvals.ProcessingStatus) error { + ret := _mock.Called(expectedValue, newValue) if len(ret) == 0 { panic("no return value specified for ChangeProcessingStatus") } var r0 error - if rf, ok := ret.Get(0).(func(approvals.ProcessingStatus, approvals.ProcessingStatus) error); ok { - r0 = rf(expectedValue, newValue) + if returnFunc, ok := ret.Get(0).(func(approvals.ProcessingStatus, approvals.ProcessingStatus) error); ok { + r0 = returnFunc(expectedValue, newValue) } else { r0 = ret.Error(0) } - return r0 } -// CheckEmergencySealing provides a mock function with given fields: observer, finalizedBlockHeight -func (_m *AssignmentCollector) CheckEmergencySealing(observer consensus.SealingObservation, finalizedBlockHeight uint64) error { - ret := _m.Called(observer, finalizedBlockHeight) +// AssignmentCollector_ChangeProcessingStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChangeProcessingStatus' +type AssignmentCollector_ChangeProcessingStatus_Call struct { + *mock.Call +} + +// ChangeProcessingStatus is a helper method to define mock.On call +// - expectedValue approvals.ProcessingStatus +// - newValue approvals.ProcessingStatus +func (_e *AssignmentCollector_Expecter) ChangeProcessingStatus(expectedValue interface{}, newValue interface{}) *AssignmentCollector_ChangeProcessingStatus_Call { + return &AssignmentCollector_ChangeProcessingStatus_Call{Call: _e.mock.On("ChangeProcessingStatus", expectedValue, newValue)} +} + +func (_c *AssignmentCollector_ChangeProcessingStatus_Call) Run(run func(expectedValue approvals.ProcessingStatus, newValue approvals.ProcessingStatus)) *AssignmentCollector_ChangeProcessingStatus_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 approvals.ProcessingStatus + if args[0] != nil { + arg0 = args[0].(approvals.ProcessingStatus) + } + var arg1 approvals.ProcessingStatus + if args[1] != nil { + arg1 = args[1].(approvals.ProcessingStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AssignmentCollector_ChangeProcessingStatus_Call) Return(err error) *AssignmentCollector_ChangeProcessingStatus_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AssignmentCollector_ChangeProcessingStatus_Call) RunAndReturn(run func(expectedValue approvals.ProcessingStatus, newValue approvals.ProcessingStatus) error) *AssignmentCollector_ChangeProcessingStatus_Call { + _c.Call.Return(run) + return _c +} + +// CheckEmergencySealing provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) CheckEmergencySealing(observer consensus.SealingObservation, finalizedBlockHeight uint64) error { + ret := _mock.Called(observer, finalizedBlockHeight) if len(ret) == 0 { panic("no return value specified for CheckEmergencySealing") } var r0 error - if rf, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) error); ok { - r0 = rf(observer, finalizedBlockHeight) + if returnFunc, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) error); ok { + r0 = returnFunc(observer, finalizedBlockHeight) } else { r0 = ret.Error(0) } - return r0 } -// ProcessApproval provides a mock function with given fields: approval -func (_m *AssignmentCollector) ProcessApproval(approval *flow.ResultApproval) error { - ret := _m.Called(approval) +// AssignmentCollector_CheckEmergencySealing_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckEmergencySealing' +type AssignmentCollector_CheckEmergencySealing_Call struct { + *mock.Call +} + +// CheckEmergencySealing is a helper method to define mock.On call +// - observer consensus.SealingObservation +// - finalizedBlockHeight uint64 +func (_e *AssignmentCollector_Expecter) CheckEmergencySealing(observer interface{}, finalizedBlockHeight interface{}) *AssignmentCollector_CheckEmergencySealing_Call { + return &AssignmentCollector_CheckEmergencySealing_Call{Call: _e.mock.On("CheckEmergencySealing", observer, finalizedBlockHeight)} +} + +func (_c *AssignmentCollector_CheckEmergencySealing_Call) Run(run func(observer consensus.SealingObservation, finalizedBlockHeight uint64)) *AssignmentCollector_CheckEmergencySealing_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 consensus.SealingObservation + if args[0] != nil { + arg0 = args[0].(consensus.SealingObservation) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AssignmentCollector_CheckEmergencySealing_Call) Return(err error) *AssignmentCollector_CheckEmergencySealing_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AssignmentCollector_CheckEmergencySealing_Call) RunAndReturn(run func(observer consensus.SealingObservation, finalizedBlockHeight uint64) error) *AssignmentCollector_CheckEmergencySealing_Call { + _c.Call.Return(run) + return _c +} + +// ProcessApproval provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) ProcessApproval(approval *flow.ResultApproval) error { + ret := _mock.Called(approval) if len(ret) == 0 { panic("no return value specified for ProcessApproval") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ResultApproval) error); ok { - r0 = rf(approval) + if returnFunc, ok := ret.Get(0).(func(*flow.ResultApproval) error); ok { + r0 = returnFunc(approval) } else { r0 = ret.Error(0) } - return r0 } -// ProcessIncorporatedResult provides a mock function with given fields: incorporatedResult -func (_m *AssignmentCollector) ProcessIncorporatedResult(incorporatedResult *flow.IncorporatedResult) error { - ret := _m.Called(incorporatedResult) +// AssignmentCollector_ProcessApproval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessApproval' +type AssignmentCollector_ProcessApproval_Call struct { + *mock.Call +} + +// ProcessApproval is a helper method to define mock.On call +// - approval *flow.ResultApproval +func (_e *AssignmentCollector_Expecter) ProcessApproval(approval interface{}) *AssignmentCollector_ProcessApproval_Call { + return &AssignmentCollector_ProcessApproval_Call{Call: _e.mock.On("ProcessApproval", approval)} +} + +func (_c *AssignmentCollector_ProcessApproval_Call) Run(run func(approval *flow.ResultApproval)) *AssignmentCollector_ProcessApproval_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ResultApproval + if args[0] != nil { + arg0 = args[0].(*flow.ResultApproval) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AssignmentCollector_ProcessApproval_Call) Return(err error) *AssignmentCollector_ProcessApproval_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AssignmentCollector_ProcessApproval_Call) RunAndReturn(run func(approval *flow.ResultApproval) error) *AssignmentCollector_ProcessApproval_Call { + _c.Call.Return(run) + return _c +} + +// ProcessIncorporatedResult provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) ProcessIncorporatedResult(incorporatedResult *flow.IncorporatedResult) error { + ret := _mock.Called(incorporatedResult) if len(ret) == 0 { panic("no return value specified for ProcessIncorporatedResult") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.IncorporatedResult) error); ok { - r0 = rf(incorporatedResult) + if returnFunc, ok := ret.Get(0).(func(*flow.IncorporatedResult) error); ok { + r0 = returnFunc(incorporatedResult) } else { r0 = ret.Error(0) } - return r0 } -// ProcessingStatus provides a mock function with no fields -func (_m *AssignmentCollector) ProcessingStatus() approvals.ProcessingStatus { - ret := _m.Called() +// AssignmentCollector_ProcessIncorporatedResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessIncorporatedResult' +type AssignmentCollector_ProcessIncorporatedResult_Call struct { + *mock.Call +} + +// ProcessIncorporatedResult is a helper method to define mock.On call +// - incorporatedResult *flow.IncorporatedResult +func (_e *AssignmentCollector_Expecter) ProcessIncorporatedResult(incorporatedResult interface{}) *AssignmentCollector_ProcessIncorporatedResult_Call { + return &AssignmentCollector_ProcessIncorporatedResult_Call{Call: _e.mock.On("ProcessIncorporatedResult", incorporatedResult)} +} + +func (_c *AssignmentCollector_ProcessIncorporatedResult_Call) Run(run func(incorporatedResult *flow.IncorporatedResult)) *AssignmentCollector_ProcessIncorporatedResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IncorporatedResult + if args[0] != nil { + arg0 = args[0].(*flow.IncorporatedResult) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AssignmentCollector_ProcessIncorporatedResult_Call) Return(err error) *AssignmentCollector_ProcessIncorporatedResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AssignmentCollector_ProcessIncorporatedResult_Call) RunAndReturn(run func(incorporatedResult *flow.IncorporatedResult) error) *AssignmentCollector_ProcessIncorporatedResult_Call { + _c.Call.Return(run) + return _c +} + +// ProcessingStatus provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) ProcessingStatus() approvals.ProcessingStatus { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ProcessingStatus") } var r0 approvals.ProcessingStatus - if rf, ok := ret.Get(0).(func() approvals.ProcessingStatus); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() approvals.ProcessingStatus); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(approvals.ProcessingStatus) } - return r0 } -// RequestMissingApprovals provides a mock function with given fields: observer, maxHeightForRequesting -func (_m *AssignmentCollector) RequestMissingApprovals(observer consensus.SealingObservation, maxHeightForRequesting uint64) (uint, error) { - ret := _m.Called(observer, maxHeightForRequesting) +// AssignmentCollector_ProcessingStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessingStatus' +type AssignmentCollector_ProcessingStatus_Call struct { + *mock.Call +} + +// ProcessingStatus is a helper method to define mock.On call +func (_e *AssignmentCollector_Expecter) ProcessingStatus() *AssignmentCollector_ProcessingStatus_Call { + return &AssignmentCollector_ProcessingStatus_Call{Call: _e.mock.On("ProcessingStatus")} +} + +func (_c *AssignmentCollector_ProcessingStatus_Call) Run(run func()) *AssignmentCollector_ProcessingStatus_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollector_ProcessingStatus_Call) Return(processingStatus approvals.ProcessingStatus) *AssignmentCollector_ProcessingStatus_Call { + _c.Call.Return(processingStatus) + return _c +} + +func (_c *AssignmentCollector_ProcessingStatus_Call) RunAndReturn(run func() approvals.ProcessingStatus) *AssignmentCollector_ProcessingStatus_Call { + _c.Call.Return(run) + return _c +} + +// RequestMissingApprovals provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) RequestMissingApprovals(observer consensus.SealingObservation, maxHeightForRequesting uint64) (uint, error) { + ret := _mock.Called(observer, maxHeightForRequesting) if len(ret) == 0 { panic("no return value specified for RequestMissingApprovals") @@ -156,74 +400,150 @@ func (_m *AssignmentCollector) RequestMissingApprovals(observer consensus.Sealin var r0 uint var r1 error - if rf, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) (uint, error)); ok { - return rf(observer, maxHeightForRequesting) + if returnFunc, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) (uint, error)); ok { + return returnFunc(observer, maxHeightForRequesting) } - if rf, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) uint); ok { - r0 = rf(observer, maxHeightForRequesting) + if returnFunc, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) uint); ok { + r0 = returnFunc(observer, maxHeightForRequesting) } else { r0 = ret.Get(0).(uint) } - - if rf, ok := ret.Get(1).(func(consensus.SealingObservation, uint64) error); ok { - r1 = rf(observer, maxHeightForRequesting) + if returnFunc, ok := ret.Get(1).(func(consensus.SealingObservation, uint64) error); ok { + r1 = returnFunc(observer, maxHeightForRequesting) } else { r1 = ret.Error(1) } - return r0, r1 } -// Result provides a mock function with no fields -func (_m *AssignmentCollector) Result() *flow.ExecutionResult { - ret := _m.Called() +// AssignmentCollector_RequestMissingApprovals_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestMissingApprovals' +type AssignmentCollector_RequestMissingApprovals_Call struct { + *mock.Call +} + +// RequestMissingApprovals is a helper method to define mock.On call +// - observer consensus.SealingObservation +// - maxHeightForRequesting uint64 +func (_e *AssignmentCollector_Expecter) RequestMissingApprovals(observer interface{}, maxHeightForRequesting interface{}) *AssignmentCollector_RequestMissingApprovals_Call { + return &AssignmentCollector_RequestMissingApprovals_Call{Call: _e.mock.On("RequestMissingApprovals", observer, maxHeightForRequesting)} +} + +func (_c *AssignmentCollector_RequestMissingApprovals_Call) Run(run func(observer consensus.SealingObservation, maxHeightForRequesting uint64)) *AssignmentCollector_RequestMissingApprovals_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 consensus.SealingObservation + if args[0] != nil { + arg0 = args[0].(consensus.SealingObservation) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AssignmentCollector_RequestMissingApprovals_Call) Return(v uint, err error) *AssignmentCollector_RequestMissingApprovals_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AssignmentCollector_RequestMissingApprovals_Call) RunAndReturn(run func(observer consensus.SealingObservation, maxHeightForRequesting uint64) (uint, error)) *AssignmentCollector_RequestMissingApprovals_Call { + _c.Call.Return(run) + return _c +} + +// Result provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) Result() *flow.ExecutionResult { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Result") } var r0 *flow.ExecutionResult - if rf, ok := ret.Get(0).(func() *flow.ExecutionResult); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.ExecutionResult); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - return r0 } -// ResultID provides a mock function with no fields -func (_m *AssignmentCollector) ResultID() flow.Identifier { - ret := _m.Called() +// AssignmentCollector_Result_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Result' +type AssignmentCollector_Result_Call struct { + *mock.Call +} + +// Result is a helper method to define mock.On call +func (_e *AssignmentCollector_Expecter) Result() *AssignmentCollector_Result_Call { + return &AssignmentCollector_Result_Call{Call: _e.mock.On("Result")} +} + +func (_c *AssignmentCollector_Result_Call) Run(run func()) *AssignmentCollector_Result_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollector_Result_Call) Return(executionResult *flow.ExecutionResult) *AssignmentCollector_Result_Call { + _c.Call.Return(executionResult) + return _c +} + +func (_c *AssignmentCollector_Result_Call) RunAndReturn(run func() *flow.ExecutionResult) *AssignmentCollector_Result_Call { + _c.Call.Return(run) + return _c +} + +// ResultID provides a mock function for the type AssignmentCollector +func (_mock *AssignmentCollector) ResultID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ResultID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// NewAssignmentCollector creates a new instance of AssignmentCollector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAssignmentCollector(t interface { - mock.TestingT - Cleanup(func()) -}) *AssignmentCollector { - mock := &AssignmentCollector{} - mock.Mock.Test(t) +// AssignmentCollector_ResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResultID' +type AssignmentCollector_ResultID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ResultID is a helper method to define mock.On call +func (_e *AssignmentCollector_Expecter) ResultID() *AssignmentCollector_ResultID_Call { + return &AssignmentCollector_ResultID_Call{Call: _e.mock.On("ResultID")} +} - return mock +func (_c *AssignmentCollector_ResultID_Call) Run(run func()) *AssignmentCollector_ResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollector_ResultID_Call) Return(identifier flow.Identifier) *AssignmentCollector_ResultID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *AssignmentCollector_ResultID_Call) RunAndReturn(run func() flow.Identifier) *AssignmentCollector_ResultID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/consensus/approvals/mock/assignment_collector_state.go b/engine/consensus/approvals/mock/assignment_collector_state.go index 5df81f76726..f1d89e2bd83 100644 --- a/engine/consensus/approvals/mock/assignment_collector_state.go +++ b/engine/consensus/approvals/mock/assignment_collector_state.go @@ -1,136 +1,341 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - consensus "github.com/onflow/flow-go/engine/consensus" - approvals "github.com/onflow/flow-go/engine/consensus/approvals" - - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/engine/consensus" + "github.com/onflow/flow-go/engine/consensus/approvals" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewAssignmentCollectorState creates a new instance of AssignmentCollectorState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAssignmentCollectorState(t interface { + mock.TestingT + Cleanup(func()) +}) *AssignmentCollectorState { + mock := &AssignmentCollectorState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AssignmentCollectorState is an autogenerated mock type for the AssignmentCollectorState type type AssignmentCollectorState struct { mock.Mock } -// Block provides a mock function with no fields -func (_m *AssignmentCollectorState) Block() *flow.Header { - ret := _m.Called() +type AssignmentCollectorState_Expecter struct { + mock *mock.Mock +} + +func (_m *AssignmentCollectorState) EXPECT() *AssignmentCollectorState_Expecter { + return &AssignmentCollectorState_Expecter{mock: &_m.Mock} +} + +// Block provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) Block() *flow.Header { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Block") } var r0 *flow.Header - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - return r0 } -// BlockID provides a mock function with no fields -func (_m *AssignmentCollectorState) BlockID() flow.Identifier { - ret := _m.Called() +// AssignmentCollectorState_Block_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Block' +type AssignmentCollectorState_Block_Call struct { + *mock.Call +} + +// Block is a helper method to define mock.On call +func (_e *AssignmentCollectorState_Expecter) Block() *AssignmentCollectorState_Block_Call { + return &AssignmentCollectorState_Block_Call{Call: _e.mock.On("Block")} +} + +func (_c *AssignmentCollectorState_Block_Call) Run(run func()) *AssignmentCollectorState_Block_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollectorState_Block_Call) Return(header *flow.Header) *AssignmentCollectorState_Block_Call { + _c.Call.Return(header) + return _c +} + +func (_c *AssignmentCollectorState_Block_Call) RunAndReturn(run func() *flow.Header) *AssignmentCollectorState_Block_Call { + _c.Call.Return(run) + return _c +} + +// BlockID provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) BlockID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for BlockID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// CheckEmergencySealing provides a mock function with given fields: observer, finalizedBlockHeight -func (_m *AssignmentCollectorState) CheckEmergencySealing(observer consensus.SealingObservation, finalizedBlockHeight uint64) error { - ret := _m.Called(observer, finalizedBlockHeight) +// AssignmentCollectorState_BlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockID' +type AssignmentCollectorState_BlockID_Call struct { + *mock.Call +} + +// BlockID is a helper method to define mock.On call +func (_e *AssignmentCollectorState_Expecter) BlockID() *AssignmentCollectorState_BlockID_Call { + return &AssignmentCollectorState_BlockID_Call{Call: _e.mock.On("BlockID")} +} + +func (_c *AssignmentCollectorState_BlockID_Call) Run(run func()) *AssignmentCollectorState_BlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollectorState_BlockID_Call) Return(identifier flow.Identifier) *AssignmentCollectorState_BlockID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *AssignmentCollectorState_BlockID_Call) RunAndReturn(run func() flow.Identifier) *AssignmentCollectorState_BlockID_Call { + _c.Call.Return(run) + return _c +} + +// CheckEmergencySealing provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) CheckEmergencySealing(observer consensus.SealingObservation, finalizedBlockHeight uint64) error { + ret := _mock.Called(observer, finalizedBlockHeight) if len(ret) == 0 { panic("no return value specified for CheckEmergencySealing") } var r0 error - if rf, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) error); ok { - r0 = rf(observer, finalizedBlockHeight) + if returnFunc, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) error); ok { + r0 = returnFunc(observer, finalizedBlockHeight) } else { r0 = ret.Error(0) } - return r0 } -// ProcessApproval provides a mock function with given fields: approval -func (_m *AssignmentCollectorState) ProcessApproval(approval *flow.ResultApproval) error { - ret := _m.Called(approval) +// AssignmentCollectorState_CheckEmergencySealing_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckEmergencySealing' +type AssignmentCollectorState_CheckEmergencySealing_Call struct { + *mock.Call +} + +// CheckEmergencySealing is a helper method to define mock.On call +// - observer consensus.SealingObservation +// - finalizedBlockHeight uint64 +func (_e *AssignmentCollectorState_Expecter) CheckEmergencySealing(observer interface{}, finalizedBlockHeight interface{}) *AssignmentCollectorState_CheckEmergencySealing_Call { + return &AssignmentCollectorState_CheckEmergencySealing_Call{Call: _e.mock.On("CheckEmergencySealing", observer, finalizedBlockHeight)} +} + +func (_c *AssignmentCollectorState_CheckEmergencySealing_Call) Run(run func(observer consensus.SealingObservation, finalizedBlockHeight uint64)) *AssignmentCollectorState_CheckEmergencySealing_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 consensus.SealingObservation + if args[0] != nil { + arg0 = args[0].(consensus.SealingObservation) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AssignmentCollectorState_CheckEmergencySealing_Call) Return(err error) *AssignmentCollectorState_CheckEmergencySealing_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AssignmentCollectorState_CheckEmergencySealing_Call) RunAndReturn(run func(observer consensus.SealingObservation, finalizedBlockHeight uint64) error) *AssignmentCollectorState_CheckEmergencySealing_Call { + _c.Call.Return(run) + return _c +} + +// ProcessApproval provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) ProcessApproval(approval *flow.ResultApproval) error { + ret := _mock.Called(approval) if len(ret) == 0 { panic("no return value specified for ProcessApproval") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ResultApproval) error); ok { - r0 = rf(approval) + if returnFunc, ok := ret.Get(0).(func(*flow.ResultApproval) error); ok { + r0 = returnFunc(approval) } else { r0 = ret.Error(0) } - return r0 } -// ProcessIncorporatedResult provides a mock function with given fields: incorporatedResult -func (_m *AssignmentCollectorState) ProcessIncorporatedResult(incorporatedResult *flow.IncorporatedResult) error { - ret := _m.Called(incorporatedResult) +// AssignmentCollectorState_ProcessApproval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessApproval' +type AssignmentCollectorState_ProcessApproval_Call struct { + *mock.Call +} + +// ProcessApproval is a helper method to define mock.On call +// - approval *flow.ResultApproval +func (_e *AssignmentCollectorState_Expecter) ProcessApproval(approval interface{}) *AssignmentCollectorState_ProcessApproval_Call { + return &AssignmentCollectorState_ProcessApproval_Call{Call: _e.mock.On("ProcessApproval", approval)} +} + +func (_c *AssignmentCollectorState_ProcessApproval_Call) Run(run func(approval *flow.ResultApproval)) *AssignmentCollectorState_ProcessApproval_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ResultApproval + if args[0] != nil { + arg0 = args[0].(*flow.ResultApproval) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AssignmentCollectorState_ProcessApproval_Call) Return(err error) *AssignmentCollectorState_ProcessApproval_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AssignmentCollectorState_ProcessApproval_Call) RunAndReturn(run func(approval *flow.ResultApproval) error) *AssignmentCollectorState_ProcessApproval_Call { + _c.Call.Return(run) + return _c +} + +// ProcessIncorporatedResult provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) ProcessIncorporatedResult(incorporatedResult *flow.IncorporatedResult) error { + ret := _mock.Called(incorporatedResult) if len(ret) == 0 { panic("no return value specified for ProcessIncorporatedResult") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.IncorporatedResult) error); ok { - r0 = rf(incorporatedResult) + if returnFunc, ok := ret.Get(0).(func(*flow.IncorporatedResult) error); ok { + r0 = returnFunc(incorporatedResult) } else { r0 = ret.Error(0) } - return r0 } -// ProcessingStatus provides a mock function with no fields -func (_m *AssignmentCollectorState) ProcessingStatus() approvals.ProcessingStatus { - ret := _m.Called() +// AssignmentCollectorState_ProcessIncorporatedResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessIncorporatedResult' +type AssignmentCollectorState_ProcessIncorporatedResult_Call struct { + *mock.Call +} + +// ProcessIncorporatedResult is a helper method to define mock.On call +// - incorporatedResult *flow.IncorporatedResult +func (_e *AssignmentCollectorState_Expecter) ProcessIncorporatedResult(incorporatedResult interface{}) *AssignmentCollectorState_ProcessIncorporatedResult_Call { + return &AssignmentCollectorState_ProcessIncorporatedResult_Call{Call: _e.mock.On("ProcessIncorporatedResult", incorporatedResult)} +} + +func (_c *AssignmentCollectorState_ProcessIncorporatedResult_Call) Run(run func(incorporatedResult *flow.IncorporatedResult)) *AssignmentCollectorState_ProcessIncorporatedResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IncorporatedResult + if args[0] != nil { + arg0 = args[0].(*flow.IncorporatedResult) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AssignmentCollectorState_ProcessIncorporatedResult_Call) Return(err error) *AssignmentCollectorState_ProcessIncorporatedResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AssignmentCollectorState_ProcessIncorporatedResult_Call) RunAndReturn(run func(incorporatedResult *flow.IncorporatedResult) error) *AssignmentCollectorState_ProcessIncorporatedResult_Call { + _c.Call.Return(run) + return _c +} + +// ProcessingStatus provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) ProcessingStatus() approvals.ProcessingStatus { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ProcessingStatus") } var r0 approvals.ProcessingStatus - if rf, ok := ret.Get(0).(func() approvals.ProcessingStatus); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() approvals.ProcessingStatus); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(approvals.ProcessingStatus) } - return r0 } -// RequestMissingApprovals provides a mock function with given fields: observer, maxHeightForRequesting -func (_m *AssignmentCollectorState) RequestMissingApprovals(observer consensus.SealingObservation, maxHeightForRequesting uint64) (uint, error) { - ret := _m.Called(observer, maxHeightForRequesting) +// AssignmentCollectorState_ProcessingStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessingStatus' +type AssignmentCollectorState_ProcessingStatus_Call struct { + *mock.Call +} + +// ProcessingStatus is a helper method to define mock.On call +func (_e *AssignmentCollectorState_Expecter) ProcessingStatus() *AssignmentCollectorState_ProcessingStatus_Call { + return &AssignmentCollectorState_ProcessingStatus_Call{Call: _e.mock.On("ProcessingStatus")} +} + +func (_c *AssignmentCollectorState_ProcessingStatus_Call) Run(run func()) *AssignmentCollectorState_ProcessingStatus_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollectorState_ProcessingStatus_Call) Return(processingStatus approvals.ProcessingStatus) *AssignmentCollectorState_ProcessingStatus_Call { + _c.Call.Return(processingStatus) + return _c +} + +func (_c *AssignmentCollectorState_ProcessingStatus_Call) RunAndReturn(run func() approvals.ProcessingStatus) *AssignmentCollectorState_ProcessingStatus_Call { + _c.Call.Return(run) + return _c +} + +// RequestMissingApprovals provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) RequestMissingApprovals(observer consensus.SealingObservation, maxHeightForRequesting uint64) (uint, error) { + ret := _mock.Called(observer, maxHeightForRequesting) if len(ret) == 0 { panic("no return value specified for RequestMissingApprovals") @@ -138,74 +343,150 @@ func (_m *AssignmentCollectorState) RequestMissingApprovals(observer consensus.S var r0 uint var r1 error - if rf, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) (uint, error)); ok { - return rf(observer, maxHeightForRequesting) + if returnFunc, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) (uint, error)); ok { + return returnFunc(observer, maxHeightForRequesting) } - if rf, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) uint); ok { - r0 = rf(observer, maxHeightForRequesting) + if returnFunc, ok := ret.Get(0).(func(consensus.SealingObservation, uint64) uint); ok { + r0 = returnFunc(observer, maxHeightForRequesting) } else { r0 = ret.Get(0).(uint) } - - if rf, ok := ret.Get(1).(func(consensus.SealingObservation, uint64) error); ok { - r1 = rf(observer, maxHeightForRequesting) + if returnFunc, ok := ret.Get(1).(func(consensus.SealingObservation, uint64) error); ok { + r1 = returnFunc(observer, maxHeightForRequesting) } else { r1 = ret.Error(1) } - return r0, r1 } -// Result provides a mock function with no fields -func (_m *AssignmentCollectorState) Result() *flow.ExecutionResult { - ret := _m.Called() +// AssignmentCollectorState_RequestMissingApprovals_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestMissingApprovals' +type AssignmentCollectorState_RequestMissingApprovals_Call struct { + *mock.Call +} + +// RequestMissingApprovals is a helper method to define mock.On call +// - observer consensus.SealingObservation +// - maxHeightForRequesting uint64 +func (_e *AssignmentCollectorState_Expecter) RequestMissingApprovals(observer interface{}, maxHeightForRequesting interface{}) *AssignmentCollectorState_RequestMissingApprovals_Call { + return &AssignmentCollectorState_RequestMissingApprovals_Call{Call: _e.mock.On("RequestMissingApprovals", observer, maxHeightForRequesting)} +} + +func (_c *AssignmentCollectorState_RequestMissingApprovals_Call) Run(run func(observer consensus.SealingObservation, maxHeightForRequesting uint64)) *AssignmentCollectorState_RequestMissingApprovals_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 consensus.SealingObservation + if args[0] != nil { + arg0 = args[0].(consensus.SealingObservation) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AssignmentCollectorState_RequestMissingApprovals_Call) Return(v uint, err error) *AssignmentCollectorState_RequestMissingApprovals_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AssignmentCollectorState_RequestMissingApprovals_Call) RunAndReturn(run func(observer consensus.SealingObservation, maxHeightForRequesting uint64) (uint, error)) *AssignmentCollectorState_RequestMissingApprovals_Call { + _c.Call.Return(run) + return _c +} + +// Result provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) Result() *flow.ExecutionResult { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Result") } var r0 *flow.ExecutionResult - if rf, ok := ret.Get(0).(func() *flow.ExecutionResult); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.ExecutionResult); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - return r0 } -// ResultID provides a mock function with no fields -func (_m *AssignmentCollectorState) ResultID() flow.Identifier { - ret := _m.Called() +// AssignmentCollectorState_Result_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Result' +type AssignmentCollectorState_Result_Call struct { + *mock.Call +} + +// Result is a helper method to define mock.On call +func (_e *AssignmentCollectorState_Expecter) Result() *AssignmentCollectorState_Result_Call { + return &AssignmentCollectorState_Result_Call{Call: _e.mock.On("Result")} +} + +func (_c *AssignmentCollectorState_Result_Call) Run(run func()) *AssignmentCollectorState_Result_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollectorState_Result_Call) Return(executionResult *flow.ExecutionResult) *AssignmentCollectorState_Result_Call { + _c.Call.Return(executionResult) + return _c +} + +func (_c *AssignmentCollectorState_Result_Call) RunAndReturn(run func() *flow.ExecutionResult) *AssignmentCollectorState_Result_Call { + _c.Call.Return(run) + return _c +} + +// ResultID provides a mock function for the type AssignmentCollectorState +func (_mock *AssignmentCollectorState) ResultID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ResultID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// NewAssignmentCollectorState creates a new instance of AssignmentCollectorState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAssignmentCollectorState(t interface { - mock.TestingT - Cleanup(func()) -}) *AssignmentCollectorState { - mock := &AssignmentCollectorState{} - mock.Mock.Test(t) +// AssignmentCollectorState_ResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResultID' +type AssignmentCollectorState_ResultID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ResultID is a helper method to define mock.On call +func (_e *AssignmentCollectorState_Expecter) ResultID() *AssignmentCollectorState_ResultID_Call { + return &AssignmentCollectorState_ResultID_Call{Call: _e.mock.On("ResultID")} +} - return mock +func (_c *AssignmentCollectorState_ResultID_Call) Run(run func()) *AssignmentCollectorState_ResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignmentCollectorState_ResultID_Call) Return(identifier flow.Identifier) *AssignmentCollectorState_ResultID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *AssignmentCollectorState_ResultID_Call) RunAndReturn(run func() flow.Identifier) *AssignmentCollectorState_ResultID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/consensus/approvals/testutil.go b/engine/consensus/approvals/testutil/testutil.go similarity index 97% rename from engine/consensus/approvals/testutil.go rename to engine/consensus/approvals/testutil/testutil.go index d958553a377..97420f1072a 100644 --- a/engine/consensus/approvals/testutil.go +++ b/engine/consensus/approvals/testutil/testutil.go @@ -1,4 +1,4 @@ -package approvals +package testutil import ( "github.com/gammazero/workerpool" @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/onflow/flow-go/engine/consensus/approvals" "github.com/onflow/flow-go/model/chunks" "github.com/onflow/flow-go/model/flow" mempool "github.com/onflow/flow-go/module/mempool/mock" @@ -95,7 +96,7 @@ type BaseAssignmentCollectorTestSuite struct { Conduit *mocknetwork.Conduit FinalizedAtHeight map[uint64]*flow.Header IdentitiesCache map[flow.Identifier]map[flow.Identifier]*flow.Identity // helper map to store identities for given block - RequestTracker *RequestTracker + RequestTracker *approvals.RequestTracker } func (s *BaseAssignmentCollectorTestSuite) SetupTest() { @@ -108,7 +109,7 @@ func (s *BaseAssignmentCollectorTestSuite) SetupTest() { s.Conduit = &mocknetwork.Conduit{} s.Headers = &storage.Headers{} - s.RequestTracker = NewRequestTracker(s.Headers, 1, 3) + s.RequestTracker = approvals.NewRequestTracker(s.Headers, 1, 3) s.FinalizedAtHeight = make(map[uint64]*flow.Header) s.FinalizedAtHeight[s.ParentBlock.Height] = s.ParentBlock diff --git a/engine/consensus/approvals/tracker/record.go b/engine/consensus/approvals/tracker/record.go index 0b249947f3b..9c240ca6bf1 100644 --- a/engine/consensus/approvals/tracker/record.go +++ b/engine/consensus/approvals/tracker/record.go @@ -9,7 +9,7 @@ import ( "github.com/onflow/flow-go/storage" ) -type Rec map[string]interface{} +type Rec map[string]any // SealingRecord is a record of the sealing status for a specific // incorporated result. It holds information whether the result is sealable, @@ -33,9 +33,9 @@ func (r *SealingRecord) ApprovalsMissing(chunksWithMissingApprovals map[uint64]f sufficientApprovals := len(chunksWithMissingApprovals) == 0 r.entries["sufficient_approvals_for_sealing"] = sufficientApprovals if !sufficientApprovals { - chunksInfo := make([]map[string]interface{}, 0, len(chunksWithMissingApprovals)) + chunksInfo := make([]map[string]any, 0, len(chunksWithMissingApprovals)) for i, list := range chunksWithMissingApprovals { - chunk := make(map[string]interface{}) + chunk := make(map[string]any) chunk["chunk_index"] = i chunk["missing_approvals_from_verifiers"] = list chunksInfo = append(chunksInfo, chunk) diff --git a/engine/consensus/approvals/tracker/tracker.go b/engine/consensus/approvals/tracker/tracker.go index f553ce207aa..5f3a419ee89 100644 --- a/engine/consensus/approvals/tracker/tracker.go +++ b/engine/consensus/approvals/tracker/tracker.go @@ -176,7 +176,7 @@ func (st *SealingObservation) Complete() { // latestFinalizedSealInfo returns a json string representation with the most // relevant data about the latest finalized seal func (st *SealingObservation) latestFinalizedSealInfo() (string, error) { - r := make(map[string]interface{}) + r := make(map[string]any) r["executed_block_id"] = st.latestFinalizedSeal.BlockID.String() r["executed_block_height"] = st.latestSealedBlock.Height r["result_id"] = st.latestFinalizedSeal.ResultID.String() diff --git a/engine/consensus/approvals/verifying_assignment_collector.go b/engine/consensus/approvals/verifying_assignment_collector.go index d32324c8bb8..151d0d9d53e 100644 --- a/engine/consensus/approvals/verifying_assignment_collector.go +++ b/engine/consensus/approvals/verifying_assignment_collector.go @@ -387,6 +387,14 @@ func (ac *VerifyingAssignmentCollector) RequestMissingApprovals(observation cons return overallRequestCount, nil } +// ColectorsLen returns the number of collectors. +// This is currently only used in tests +func (ac *VerifyingAssignmentCollector) ColectorsLen() int { + ac.lock.RLock() + defer ac.lock.RUnlock() + return len(ac.collectors) +} + // authorizedVerifiersAtBlock pre-select all authorized Verifiers at the block that incorporates the result. // The method returns the set of all node IDs that: // - are authorized members of the network at the given block and diff --git a/engine/consensus/approvals/verifying_assignment_collector_test.go b/engine/consensus/approvals/verifying_assignment_collector_test.go index fe87c612ff1..3d1208c22f7 100644 --- a/engine/consensus/approvals/verifying_assignment_collector_test.go +++ b/engine/consensus/approvals/verifying_assignment_collector_test.go @@ -1,4 +1,4 @@ -package approvals +package approvals_test import ( "fmt" @@ -15,6 +15,8 @@ import ( "github.com/onflow/crypto/hash" "github.com/onflow/flow-go/engine" + "github.com/onflow/flow-go/engine/consensus/approvals" + "github.com/onflow/flow-go/engine/consensus/approvals/testutil" "github.com/onflow/flow-go/engine/consensus/approvals/tracker" "github.com/onflow/flow-go/model/chunks" "github.com/onflow/flow-go/model/flow" @@ -49,20 +51,20 @@ func newVerifyingAssignmentCollector(logger zerolog.Logger, seals realmempool.IncorporatedResultSeals, sigHasher hash.Hasher, approvalConduit network.Conduit, - requestTracker *RequestTracker, + requestTracker *approvals.RequestTracker, requiredApprovalsForSealConstruction uint, -) (*VerifyingAssignmentCollector, error) { - b, err := NewAssignmentCollectorBase(logger, workerPool, result, state, headers, assigner, seals, sigHasher, +) (*approvals.VerifyingAssignmentCollector, error) { + b, err := approvals.NewAssignmentCollectorBase(logger, workerPool, result, state, headers, assigner, seals, sigHasher, approvalConduit, requestTracker, requiredApprovalsForSealConstruction) if err != nil { return nil, err } - return NewVerifyingAssignmentCollector(b) + return approvals.NewVerifyingAssignmentCollector(b) } type AssignmentCollectorTestSuite struct { - BaseAssignmentCollectorTestSuite - collector *VerifyingAssignmentCollector + testutil.BaseAssignmentCollectorTestSuite + collector *approvals.VerifyingAssignmentCollector } func (s *AssignmentCollectorTestSuite) SetupTest() { @@ -369,8 +371,9 @@ func (s *AssignmentCollectorTestSuite) TestRequestMissingApprovals() { requestCount, err = s.collector.RequestMissingApprovals(&tracker.NoopSealingTracker{}, lastHeight) s.Require().NoError(err) - require.Equal(s.T(), int(requestCount), s.Chunks.Len()*len(s.collector.collectors)) - require.Len(s.T(), requests, s.Chunks.Len()*len(s.collector.collectors)) + require.NotNil(s.T(), requestCount) + require.Equal(s.T(), int(requestCount), s.Chunks.Len()*s.collector.ColectorsLen()) + require.Len(s.T(), requests, s.Chunks.Len()*s.collector.ColectorsLen()) result := s.IncorporatedResult.Result for _, chunk := range s.Chunks { @@ -401,7 +404,7 @@ func (s *AssignmentCollectorTestSuite) TestCheckEmergencySealing() { }, ).Return(true, nil).Once() - err = s.collector.CheckEmergencySealing(&tracker.NoopSealingTracker{}, DefaultEmergencySealingThresholdForFinalization+s.IncorporatedBlock.Height) + err = s.collector.CheckEmergencySealing(&tracker.NoopSealingTracker{}, approvals.DefaultEmergencySealingThresholdForFinalization+s.IncorporatedBlock.Height) require.NoError(s.T(), err) s.SealsPL.AssertExpectations(s.T()) @@ -412,7 +415,7 @@ func (s *AssignmentCollectorTestSuite) TestCheckEmergencySealingNotEnoughFinaliz err := s.collector.ProcessIncorporatedResult(s.IncorporatedResult) require.NoError(s.T(), err) - err = s.collector.CheckEmergencySealing(&tracker.NoopSealingTracker{}, DefaultEmergencySealingThresholdForVerification+s.IncorporatedBlock.Height) + err = s.collector.CheckEmergencySealing(&tracker.NoopSealingTracker{}, approvals.DefaultEmergencySealingThresholdForVerification+s.IncorporatedBlock.Height) require.NoError(s.T(), err) // SealsPL.Add is not being called, because there isn't enough finalized blocks to trigger diff --git a/engine/consensus/matching/core.go b/engine/consensus/matching/core.go index f83512861ce..9fd0c6029e0 100644 --- a/engine/consensus/matching/core.go +++ b/engine/consensus/matching/core.go @@ -350,7 +350,7 @@ HEIGHT_LOOP: // request missing execution results, if sealed height is low enough for _, blockID := range missingBlocksOrderedByHeight { - c.receiptRequester.Query(blockID, filter.Any) + c.receiptRequester.EntityBySecondaryKey(blockID, filter.Any) } return len(missingBlocksOrderedByHeight), firstMissingHeight, nil diff --git a/engine/consensus/matching/core_test.go b/engine/consensus/matching/core_test.go index 2cd76d588d8..6ef122693e8 100644 --- a/engine/consensus/matching/core_test.go +++ b/engine/consensus/matching/core_test.go @@ -249,7 +249,7 @@ func (ms *MatchingSuite) TestRequestPendingReceipts() { // Expecting all blocks to be requested: from sealed height + 1 up to (incl.) latest finalized for i := 1; i < n; i++ { id := orderedBlocks[i].ID() - ms.requester.On("Query", id, mock.Anything).Return().Once() + ms.requester.On("EntityBySecondaryKey", id, mock.Anything).Return().Once() } ms.SealsPL.On("All").Return([]*flow.IncorporatedResultSeal{}).Maybe() @@ -258,7 +258,7 @@ func (ms *MatchingSuite) TestRequestPendingReceipts() { _, _, err := ms.core.requestPendingReceipts() ms.Require().NoError(err, "should request results for pending blocks") - ms.requester.AssertExpectations(ms.T()) // asserts that requester.Query(, filter.Any) was called + ms.requester.AssertExpectations(ms.T()) // asserts that requester.EntityBySecondaryKey(, filter.Any) was called } // TestRequestSecondPendingReceipt verifies that a second receipt is re-requested @@ -286,14 +286,14 @@ func (ms *MatchingSuite) TestRequestSecondPendingReceipt() { // Situation A: we have _once_ receipt for an unsealed finalized block in storage ms.ReceiptsDB.On("ByBlockID", ms.LatestFinalizedBlock.ID()).Return(flow.ExecutionReceiptList{receipt1}, nil).Once() - ms.requester.On("Query", ms.LatestFinalizedBlock.ID(), mock.Anything).Return().Once() // Core should trigger requester to re-request a second receipt + ms.requester.On("EntityBySecondaryKey", ms.LatestFinalizedBlock.ID(), mock.Anything).Return().Once() // Core should trigger requester to re-request a second receipt _, _, err := ms.core.requestPendingReceipts() ms.Require().NoError(err, "should request results for pending blocks") - ms.requester.AssertExpectations(ms.T()) // asserts that requester.Query(, filter.Any) was called + ms.requester.AssertExpectations(ms.T()) // asserts that requester.EntityBySecondaryKey(, filter.Any) was called // Situation B: we have _two_ receipts for an unsealed finalized block storage ms.ReceiptsDB.On("ByBlockID", ms.LatestFinalizedBlock.ID()).Return(flow.ExecutionReceiptList{receipt1, receipt2}, nil).Once() _, _, err = ms.core.requestPendingReceipts() ms.Require().NoError(err, "should request results for pending blocks") - ms.requester.AssertExpectations(ms.T()) // asserts that requester.Query(, filter.Any) was called + ms.requester.AssertExpectations(ms.T()) // asserts that requester.EntityBySecondaryKey(, filter.Any) was called } diff --git a/engine/consensus/mock/compliance.go b/engine/consensus/mock/compliance.go index 3a5229dfb4d..75c57673f74 100644 --- a/engine/consensus/mock/compliance.go +++ b/engine/consensus/mock/compliance.go @@ -1,84 +1,250 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewCompliance creates a new instance of Compliance. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCompliance(t interface { + mock.TestingT + Cleanup(func()) +}) *Compliance { + mock := &Compliance{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Compliance is an autogenerated mock type for the Compliance type type Compliance struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *Compliance) Done() <-chan struct{} { - ret := _m.Called() +type Compliance_Expecter struct { + mock *mock.Mock +} + +func (_m *Compliance) EXPECT() *Compliance_Expecter { + return &Compliance_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type Compliance +func (_mock *Compliance) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// OnBlockProposal provides a mock function with given fields: proposal -func (_m *Compliance) OnBlockProposal(proposal flow.Slashable[*flow.Proposal]) { - _m.Called(proposal) +// Compliance_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Compliance_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Compliance_Expecter) Done() *Compliance_Done_Call { + return &Compliance_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Compliance_Done_Call) Run(run func()) *Compliance_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Compliance_Done_Call) Return(valCh <-chan struct{}) *Compliance_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Compliance_Done_Call) RunAndReturn(run func() <-chan struct{}) *Compliance_Done_Call { + _c.Call.Return(run) + return _c +} + +// OnBlockProposal provides a mock function for the type Compliance +func (_mock *Compliance) OnBlockProposal(proposal flow.Slashable[*flow.Proposal]) { + _mock.Called(proposal) + return +} + +// Compliance_OnBlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockProposal' +type Compliance_OnBlockProposal_Call struct { + *mock.Call +} + +// OnBlockProposal is a helper method to define mock.On call +// - proposal flow.Slashable[*flow.Proposal] +func (_e *Compliance_Expecter) OnBlockProposal(proposal interface{}) *Compliance_OnBlockProposal_Call { + return &Compliance_OnBlockProposal_Call{Call: _e.mock.On("OnBlockProposal", proposal)} +} + +func (_c *Compliance_OnBlockProposal_Call) Run(run func(proposal flow.Slashable[*flow.Proposal])) *Compliance_OnBlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[*flow.Proposal] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[*flow.Proposal]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compliance_OnBlockProposal_Call) Return() *Compliance_OnBlockProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *Compliance_OnBlockProposal_Call) RunAndReturn(run func(proposal flow.Slashable[*flow.Proposal])) *Compliance_OnBlockProposal_Call { + _c.Run(run) + return _c +} + +// OnSyncedBlocks provides a mock function for the type Compliance +func (_mock *Compliance) OnSyncedBlocks(blocks flow.Slashable[[]*flow.Proposal]) { + _mock.Called(blocks) + return +} + +// Compliance_OnSyncedBlocks_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnSyncedBlocks' +type Compliance_OnSyncedBlocks_Call struct { + *mock.Call +} + +// OnSyncedBlocks is a helper method to define mock.On call +// - blocks flow.Slashable[[]*flow.Proposal] +func (_e *Compliance_Expecter) OnSyncedBlocks(blocks interface{}) *Compliance_OnSyncedBlocks_Call { + return &Compliance_OnSyncedBlocks_Call{Call: _e.mock.On("OnSyncedBlocks", blocks)} +} + +func (_c *Compliance_OnSyncedBlocks_Call) Run(run func(blocks flow.Slashable[[]*flow.Proposal])) *Compliance_OnSyncedBlocks_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[[]*flow.Proposal] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[[]*flow.Proposal]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compliance_OnSyncedBlocks_Call) Return() *Compliance_OnSyncedBlocks_Call { + _c.Call.Return() + return _c } -// OnSyncedBlocks provides a mock function with given fields: blocks -func (_m *Compliance) OnSyncedBlocks(blocks flow.Slashable[[]*flow.Proposal]) { - _m.Called(blocks) +func (_c *Compliance_OnSyncedBlocks_Call) RunAndReturn(run func(blocks flow.Slashable[[]*flow.Proposal])) *Compliance_OnSyncedBlocks_Call { + _c.Run(run) + return _c } -// Ready provides a mock function with no fields -func (_m *Compliance) Ready() <-chan struct{} { - ret := _m.Called() +// Ready provides a mock function for the type Compliance +func (_mock *Compliance) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *Compliance) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// Compliance_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Compliance_Ready_Call struct { + *mock.Call } -// NewCompliance creates a new instance of Compliance. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCompliance(t interface { - mock.TestingT - Cleanup(func()) -}) *Compliance { - mock := &Compliance{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *Compliance_Expecter) Ready() *Compliance_Ready_Call { + return &Compliance_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *Compliance_Ready_Call) Run(run func()) *Compliance_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *Compliance_Ready_Call) Return(valCh <-chan struct{}) *Compliance_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Compliance_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Compliance_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type Compliance +func (_mock *Compliance) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// Compliance_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type Compliance_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *Compliance_Expecter) Start(signalerContext interface{}) *Compliance_Start_Call { + return &Compliance_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *Compliance_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *Compliance_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compliance_Start_Call) Return() *Compliance_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *Compliance_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *Compliance_Start_Call { + _c.Run(run) + return _c } diff --git a/engine/consensus/mock/matching_core.go b/engine/consensus/mock/matching_core.go index 0b6e647387b..75dc3ad1b0b 100644 --- a/engine/consensus/mock/matching_core.go +++ b/engine/consensus/mock/matching_core.go @@ -1,63 +1,132 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewMatchingCore creates a new instance of MatchingCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMatchingCore(t interface { + mock.TestingT + Cleanup(func()) +}) *MatchingCore { + mock := &MatchingCore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MatchingCore is an autogenerated mock type for the MatchingCore type type MatchingCore struct { mock.Mock } -// OnBlockFinalization provides a mock function with no fields -func (_m *MatchingCore) OnBlockFinalization() error { - ret := _m.Called() +type MatchingCore_Expecter struct { + mock *mock.Mock +} + +func (_m *MatchingCore) EXPECT() *MatchingCore_Expecter { + return &MatchingCore_Expecter{mock: &_m.Mock} +} + +// OnBlockFinalization provides a mock function for the type MatchingCore +func (_mock *MatchingCore) OnBlockFinalization() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for OnBlockFinalization") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// ProcessReceipt provides a mock function with given fields: receipt -func (_m *MatchingCore) ProcessReceipt(receipt *flow.ExecutionReceipt) error { - ret := _m.Called(receipt) +// MatchingCore_OnBlockFinalization_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockFinalization' +type MatchingCore_OnBlockFinalization_Call struct { + *mock.Call +} + +// OnBlockFinalization is a helper method to define mock.On call +func (_e *MatchingCore_Expecter) OnBlockFinalization() *MatchingCore_OnBlockFinalization_Call { + return &MatchingCore_OnBlockFinalization_Call{Call: _e.mock.On("OnBlockFinalization")} +} + +func (_c *MatchingCore_OnBlockFinalization_Call) Run(run func()) *MatchingCore_OnBlockFinalization_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MatchingCore_OnBlockFinalization_Call) Return(err error) *MatchingCore_OnBlockFinalization_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MatchingCore_OnBlockFinalization_Call) RunAndReturn(run func() error) *MatchingCore_OnBlockFinalization_Call { + _c.Call.Return(run) + return _c +} + +// ProcessReceipt provides a mock function for the type MatchingCore +func (_mock *MatchingCore) ProcessReceipt(receipt *flow.ExecutionReceipt) error { + ret := _mock.Called(receipt) if len(ret) == 0 { panic("no return value specified for ProcessReceipt") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt) error); ok { - r0 = rf(receipt) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt) error); ok { + r0 = returnFunc(receipt) } else { r0 = ret.Error(0) } - return r0 } -// NewMatchingCore creates a new instance of MatchingCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMatchingCore(t interface { - mock.TestingT - Cleanup(func()) -}) *MatchingCore { - mock := &MatchingCore{} - mock.Mock.Test(t) +// MatchingCore_ProcessReceipt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessReceipt' +type MatchingCore_ProcessReceipt_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ProcessReceipt is a helper method to define mock.On call +// - receipt *flow.ExecutionReceipt +func (_e *MatchingCore_Expecter) ProcessReceipt(receipt interface{}) *MatchingCore_ProcessReceipt_Call { + return &MatchingCore_ProcessReceipt_Call{Call: _e.mock.On("ProcessReceipt", receipt)} +} - return mock +func (_c *MatchingCore_ProcessReceipt_Call) Run(run func(receipt *flow.ExecutionReceipt)) *MatchingCore_ProcessReceipt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MatchingCore_ProcessReceipt_Call) Return(err error) *MatchingCore_ProcessReceipt_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MatchingCore_ProcessReceipt_Call) RunAndReturn(run func(receipt *flow.ExecutionReceipt) error) *MatchingCore_ProcessReceipt_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/consensus/mock/sealing_core.go b/engine/consensus/mock/sealing_core.go index 243a6b0d7ff..323b5e384f2 100644 --- a/engine/consensus/mock/sealing_core.go +++ b/engine/consensus/mock/sealing_core.go @@ -1,81 +1,190 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSealingCore creates a new instance of SealingCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSealingCore(t interface { + mock.TestingT + Cleanup(func()) +}) *SealingCore { + mock := &SealingCore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SealingCore is an autogenerated mock type for the SealingCore type type SealingCore struct { mock.Mock } -// ProcessApproval provides a mock function with given fields: approval -func (_m *SealingCore) ProcessApproval(approval *flow.ResultApproval) error { - ret := _m.Called(approval) +type SealingCore_Expecter struct { + mock *mock.Mock +} + +func (_m *SealingCore) EXPECT() *SealingCore_Expecter { + return &SealingCore_Expecter{mock: &_m.Mock} +} + +// ProcessApproval provides a mock function for the type SealingCore +func (_mock *SealingCore) ProcessApproval(approval *flow.ResultApproval) error { + ret := _mock.Called(approval) if len(ret) == 0 { panic("no return value specified for ProcessApproval") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ResultApproval) error); ok { - r0 = rf(approval) + if returnFunc, ok := ret.Get(0).(func(*flow.ResultApproval) error); ok { + r0 = returnFunc(approval) } else { r0 = ret.Error(0) } - return r0 } -// ProcessFinalizedBlock provides a mock function with given fields: finalizedBlockID -func (_m *SealingCore) ProcessFinalizedBlock(finalizedBlockID flow.Identifier) error { - ret := _m.Called(finalizedBlockID) +// SealingCore_ProcessApproval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessApproval' +type SealingCore_ProcessApproval_Call struct { + *mock.Call +} + +// ProcessApproval is a helper method to define mock.On call +// - approval *flow.ResultApproval +func (_e *SealingCore_Expecter) ProcessApproval(approval interface{}) *SealingCore_ProcessApproval_Call { + return &SealingCore_ProcessApproval_Call{Call: _e.mock.On("ProcessApproval", approval)} +} + +func (_c *SealingCore_ProcessApproval_Call) Run(run func(approval *flow.ResultApproval)) *SealingCore_ProcessApproval_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ResultApproval + if args[0] != nil { + arg0 = args[0].(*flow.ResultApproval) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingCore_ProcessApproval_Call) Return(err error) *SealingCore_ProcessApproval_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingCore_ProcessApproval_Call) RunAndReturn(run func(approval *flow.ResultApproval) error) *SealingCore_ProcessApproval_Call { + _c.Call.Return(run) + return _c +} + +// ProcessFinalizedBlock provides a mock function for the type SealingCore +func (_mock *SealingCore) ProcessFinalizedBlock(finalizedBlockID flow.Identifier) error { + ret := _mock.Called(finalizedBlockID) if len(ret) == 0 { panic("no return value specified for ProcessFinalizedBlock") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier) error); ok { - r0 = rf(finalizedBlockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) error); ok { + r0 = returnFunc(finalizedBlockID) } else { r0 = ret.Error(0) } - return r0 } -// ProcessIncorporatedResult provides a mock function with given fields: result -func (_m *SealingCore) ProcessIncorporatedResult(result *flow.IncorporatedResult) error { - ret := _m.Called(result) +// SealingCore_ProcessFinalizedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessFinalizedBlock' +type SealingCore_ProcessFinalizedBlock_Call struct { + *mock.Call +} + +// ProcessFinalizedBlock is a helper method to define mock.On call +// - finalizedBlockID flow.Identifier +func (_e *SealingCore_Expecter) ProcessFinalizedBlock(finalizedBlockID interface{}) *SealingCore_ProcessFinalizedBlock_Call { + return &SealingCore_ProcessFinalizedBlock_Call{Call: _e.mock.On("ProcessFinalizedBlock", finalizedBlockID)} +} + +func (_c *SealingCore_ProcessFinalizedBlock_Call) Run(run func(finalizedBlockID flow.Identifier)) *SealingCore_ProcessFinalizedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingCore_ProcessFinalizedBlock_Call) Return(err error) *SealingCore_ProcessFinalizedBlock_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingCore_ProcessFinalizedBlock_Call) RunAndReturn(run func(finalizedBlockID flow.Identifier) error) *SealingCore_ProcessFinalizedBlock_Call { + _c.Call.Return(run) + return _c +} + +// ProcessIncorporatedResult provides a mock function for the type SealingCore +func (_mock *SealingCore) ProcessIncorporatedResult(result *flow.IncorporatedResult) error { + ret := _mock.Called(result) if len(ret) == 0 { panic("no return value specified for ProcessIncorporatedResult") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.IncorporatedResult) error); ok { - r0 = rf(result) + if returnFunc, ok := ret.Get(0).(func(*flow.IncorporatedResult) error); ok { + r0 = returnFunc(result) } else { r0 = ret.Error(0) } - return r0 } -// NewSealingCore creates a new instance of SealingCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSealingCore(t interface { - mock.TestingT - Cleanup(func()) -}) *SealingCore { - mock := &SealingCore{} - mock.Mock.Test(t) +// SealingCore_ProcessIncorporatedResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessIncorporatedResult' +type SealingCore_ProcessIncorporatedResult_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ProcessIncorporatedResult is a helper method to define mock.On call +// - result *flow.IncorporatedResult +func (_e *SealingCore_Expecter) ProcessIncorporatedResult(result interface{}) *SealingCore_ProcessIncorporatedResult_Call { + return &SealingCore_ProcessIncorporatedResult_Call{Call: _e.mock.On("ProcessIncorporatedResult", result)} +} - return mock +func (_c *SealingCore_ProcessIncorporatedResult_Call) Run(run func(result *flow.IncorporatedResult)) *SealingCore_ProcessIncorporatedResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IncorporatedResult + if args[0] != nil { + arg0 = args[0].(*flow.IncorporatedResult) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingCore_ProcessIncorporatedResult_Call) Return(err error) *SealingCore_ProcessIncorporatedResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingCore_ProcessIncorporatedResult_Call) RunAndReturn(run func(result *flow.IncorporatedResult) error) *SealingCore_ProcessIncorporatedResult_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/consensus/mock/sealing_observation.go b/engine/consensus/mock/sealing_observation.go index 12222208e81..4ac0cb5c1d9 100644 --- a/engine/consensus/mock/sealing_observation.go +++ b/engine/consensus/mock/sealing_observation.go @@ -1,47 +1,208 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSealingObservation creates a new instance of SealingObservation. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSealingObservation(t interface { + mock.TestingT + Cleanup(func()) +}) *SealingObservation { + mock := &SealingObservation{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SealingObservation is an autogenerated mock type for the SealingObservation type type SealingObservation struct { mock.Mock } -// ApprovalsMissing provides a mock function with given fields: ir, chunksWithMissingApprovals -func (_m *SealingObservation) ApprovalsMissing(ir *flow.IncorporatedResult, chunksWithMissingApprovals map[uint64]flow.IdentifierList) { - _m.Called(ir, chunksWithMissingApprovals) +type SealingObservation_Expecter struct { + mock *mock.Mock } -// ApprovalsRequested provides a mock function with given fields: ir, requestCount -func (_m *SealingObservation) ApprovalsRequested(ir *flow.IncorporatedResult, requestCount uint) { - _m.Called(ir, requestCount) +func (_m *SealingObservation) EXPECT() *SealingObservation_Expecter { + return &SealingObservation_Expecter{mock: &_m.Mock} } -// Complete provides a mock function with no fields -func (_m *SealingObservation) Complete() { - _m.Called() +// ApprovalsMissing provides a mock function for the type SealingObservation +func (_mock *SealingObservation) ApprovalsMissing(ir *flow.IncorporatedResult, chunksWithMissingApprovals map[uint64]flow.IdentifierList) { + _mock.Called(ir, chunksWithMissingApprovals) + return } -// QualifiesForEmergencySealing provides a mock function with given fields: ir, emergencySealable -func (_m *SealingObservation) QualifiesForEmergencySealing(ir *flow.IncorporatedResult, emergencySealable bool) { - _m.Called(ir, emergencySealable) +// SealingObservation_ApprovalsMissing_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ApprovalsMissing' +type SealingObservation_ApprovalsMissing_Call struct { + *mock.Call } -// NewSealingObservation creates a new instance of SealingObservation. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSealingObservation(t interface { - mock.TestingT - Cleanup(func()) -}) *SealingObservation { - mock := &SealingObservation{} - mock.Mock.Test(t) +// ApprovalsMissing is a helper method to define mock.On call +// - ir *flow.IncorporatedResult +// - chunksWithMissingApprovals map[uint64]flow.IdentifierList +func (_e *SealingObservation_Expecter) ApprovalsMissing(ir interface{}, chunksWithMissingApprovals interface{}) *SealingObservation_ApprovalsMissing_Call { + return &SealingObservation_ApprovalsMissing_Call{Call: _e.mock.On("ApprovalsMissing", ir, chunksWithMissingApprovals)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *SealingObservation_ApprovalsMissing_Call) Run(run func(ir *flow.IncorporatedResult, chunksWithMissingApprovals map[uint64]flow.IdentifierList)) *SealingObservation_ApprovalsMissing_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IncorporatedResult + if args[0] != nil { + arg0 = args[0].(*flow.IncorporatedResult) + } + var arg1 map[uint64]flow.IdentifierList + if args[1] != nil { + arg1 = args[1].(map[uint64]flow.IdentifierList) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return mock +func (_c *SealingObservation_ApprovalsMissing_Call) Return() *SealingObservation_ApprovalsMissing_Call { + _c.Call.Return() + return _c +} + +func (_c *SealingObservation_ApprovalsMissing_Call) RunAndReturn(run func(ir *flow.IncorporatedResult, chunksWithMissingApprovals map[uint64]flow.IdentifierList)) *SealingObservation_ApprovalsMissing_Call { + _c.Run(run) + return _c +} + +// ApprovalsRequested provides a mock function for the type SealingObservation +func (_mock *SealingObservation) ApprovalsRequested(ir *flow.IncorporatedResult, requestCount uint) { + _mock.Called(ir, requestCount) + return +} + +// SealingObservation_ApprovalsRequested_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ApprovalsRequested' +type SealingObservation_ApprovalsRequested_Call struct { + *mock.Call +} + +// ApprovalsRequested is a helper method to define mock.On call +// - ir *flow.IncorporatedResult +// - requestCount uint +func (_e *SealingObservation_Expecter) ApprovalsRequested(ir interface{}, requestCount interface{}) *SealingObservation_ApprovalsRequested_Call { + return &SealingObservation_ApprovalsRequested_Call{Call: _e.mock.On("ApprovalsRequested", ir, requestCount)} +} + +func (_c *SealingObservation_ApprovalsRequested_Call) Run(run func(ir *flow.IncorporatedResult, requestCount uint)) *SealingObservation_ApprovalsRequested_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IncorporatedResult + if args[0] != nil { + arg0 = args[0].(*flow.IncorporatedResult) + } + var arg1 uint + if args[1] != nil { + arg1 = args[1].(uint) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SealingObservation_ApprovalsRequested_Call) Return() *SealingObservation_ApprovalsRequested_Call { + _c.Call.Return() + return _c +} + +func (_c *SealingObservation_ApprovalsRequested_Call) RunAndReturn(run func(ir *flow.IncorporatedResult, requestCount uint)) *SealingObservation_ApprovalsRequested_Call { + _c.Run(run) + return _c +} + +// Complete provides a mock function for the type SealingObservation +func (_mock *SealingObservation) Complete() { + _mock.Called() + return +} + +// SealingObservation_Complete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Complete' +type SealingObservation_Complete_Call struct { + *mock.Call +} + +// Complete is a helper method to define mock.On call +func (_e *SealingObservation_Expecter) Complete() *SealingObservation_Complete_Call { + return &SealingObservation_Complete_Call{Call: _e.mock.On("Complete")} +} + +func (_c *SealingObservation_Complete_Call) Run(run func()) *SealingObservation_Complete_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingObservation_Complete_Call) Return() *SealingObservation_Complete_Call { + _c.Call.Return() + return _c +} + +func (_c *SealingObservation_Complete_Call) RunAndReturn(run func()) *SealingObservation_Complete_Call { + _c.Run(run) + return _c +} + +// QualifiesForEmergencySealing provides a mock function for the type SealingObservation +func (_mock *SealingObservation) QualifiesForEmergencySealing(ir *flow.IncorporatedResult, emergencySealable bool) { + _mock.Called(ir, emergencySealable) + return +} + +// SealingObservation_QualifiesForEmergencySealing_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QualifiesForEmergencySealing' +type SealingObservation_QualifiesForEmergencySealing_Call struct { + *mock.Call +} + +// QualifiesForEmergencySealing is a helper method to define mock.On call +// - ir *flow.IncorporatedResult +// - emergencySealable bool +func (_e *SealingObservation_Expecter) QualifiesForEmergencySealing(ir interface{}, emergencySealable interface{}) *SealingObservation_QualifiesForEmergencySealing_Call { + return &SealingObservation_QualifiesForEmergencySealing_Call{Call: _e.mock.On("QualifiesForEmergencySealing", ir, emergencySealable)} +} + +func (_c *SealingObservation_QualifiesForEmergencySealing_Call) Run(run func(ir *flow.IncorporatedResult, emergencySealable bool)) *SealingObservation_QualifiesForEmergencySealing_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IncorporatedResult + if args[0] != nil { + arg0 = args[0].(*flow.IncorporatedResult) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SealingObservation_QualifiesForEmergencySealing_Call) Return() *SealingObservation_QualifiesForEmergencySealing_Call { + _c.Call.Return() + return _c +} + +func (_c *SealingObservation_QualifiesForEmergencySealing_Call) RunAndReturn(run func(ir *flow.IncorporatedResult, emergencySealable bool)) *SealingObservation_QualifiesForEmergencySealing_Call { + _c.Run(run) + return _c } diff --git a/engine/consensus/mock/sealing_tracker.go b/engine/consensus/mock/sealing_tracker.go index 294b7bf5e48..717b291f74a 100644 --- a/engine/consensus/mock/sealing_tracker.go +++ b/engine/consensus/mock/sealing_tracker.go @@ -1,49 +1,103 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - consensus "github.com/onflow/flow-go/engine/consensus" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/engine/consensus" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSealingTracker creates a new instance of SealingTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSealingTracker(t interface { + mock.TestingT + Cleanup(func()) +}) *SealingTracker { + mock := &SealingTracker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SealingTracker is an autogenerated mock type for the SealingTracker type type SealingTracker struct { mock.Mock } -// NewSealingObservation provides a mock function with given fields: finalizedBlock, seal, sealedBlock -func (_m *SealingTracker) NewSealingObservation(finalizedBlock *flow.Header, seal *flow.Seal, sealedBlock *flow.Header) consensus.SealingObservation { - ret := _m.Called(finalizedBlock, seal, sealedBlock) +type SealingTracker_Expecter struct { + mock *mock.Mock +} + +func (_m *SealingTracker) EXPECT() *SealingTracker_Expecter { + return &SealingTracker_Expecter{mock: &_m.Mock} +} + +// NewSealingObservation provides a mock function for the type SealingTracker +func (_mock *SealingTracker) NewSealingObservation(finalizedBlock *flow.Header, seal *flow.Seal, sealedBlock *flow.Header) consensus.SealingObservation { + ret := _mock.Called(finalizedBlock, seal, sealedBlock) if len(ret) == 0 { panic("no return value specified for NewSealingObservation") } var r0 consensus.SealingObservation - if rf, ok := ret.Get(0).(func(*flow.Header, *flow.Seal, *flow.Header) consensus.SealingObservation); ok { - r0 = rf(finalizedBlock, seal, sealedBlock) + if returnFunc, ok := ret.Get(0).(func(*flow.Header, *flow.Seal, *flow.Header) consensus.SealingObservation); ok { + r0 = returnFunc(finalizedBlock, seal, sealedBlock) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(consensus.SealingObservation) } } - return r0 } -// NewSealingTracker creates a new instance of SealingTracker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSealingTracker(t interface { - mock.TestingT - Cleanup(func()) -}) *SealingTracker { - mock := &SealingTracker{} - mock.Mock.Test(t) +// SealingTracker_NewSealingObservation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewSealingObservation' +type SealingTracker_NewSealingObservation_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NewSealingObservation is a helper method to define mock.On call +// - finalizedBlock *flow.Header +// - seal *flow.Seal +// - sealedBlock *flow.Header +func (_e *SealingTracker_Expecter) NewSealingObservation(finalizedBlock interface{}, seal interface{}, sealedBlock interface{}) *SealingTracker_NewSealingObservation_Call { + return &SealingTracker_NewSealingObservation_Call{Call: _e.mock.On("NewSealingObservation", finalizedBlock, seal, sealedBlock)} +} - return mock +func (_c *SealingTracker_NewSealingObservation_Call) Run(run func(finalizedBlock *flow.Header, seal *flow.Seal, sealedBlock *flow.Header)) *SealingTracker_NewSealingObservation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + var arg1 *flow.Seal + if args[1] != nil { + arg1 = args[1].(*flow.Seal) + } + var arg2 *flow.Header + if args[2] != nil { + arg2 = args[2].(*flow.Header) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *SealingTracker_NewSealingObservation_Call) Return(sealingObservation consensus.SealingObservation) *SealingTracker_NewSealingObservation_Call { + _c.Call.Return(sealingObservation) + return _c +} + +func (_c *SealingTracker_NewSealingObservation_Call) RunAndReturn(run func(finalizedBlock *flow.Header, seal *flow.Seal, sealedBlock *flow.Header) consensus.SealingObservation) *SealingTracker_NewSealingObservation_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/consensus/sealing/core_test.go b/engine/consensus/sealing/core_test.go index 9b58b90e557..cee3e95cfc6 100644 --- a/engine/consensus/sealing/core_test.go +++ b/engine/consensus/sealing/core_test.go @@ -12,6 +12,7 @@ import ( "github.com/onflow/flow-go/engine" "github.com/onflow/flow-go/engine/consensus/approvals" + "github.com/onflow/flow-go/engine/consensus/approvals/testutil" "github.com/onflow/flow-go/engine/consensus/approvals/tracker" "github.com/onflow/flow-go/model/chunks" "github.com/onflow/flow-go/model/flow" @@ -40,7 +41,7 @@ func TestApprovalProcessingCore(t *testing.T) { const RequiredApprovalsForSealConstructionTestingValue = 1 type ApprovalProcessingCoreTestSuite struct { - approvals.BaseAssignmentCollectorTestSuite + testutil.BaseAssignmentCollectorTestSuite sealsDB *storage.Seals finalizedRootHeader *flow.Header diff --git a/engine/enqueue.go b/engine/enqueue.go index c3221da3044..b5599dba234 100644 --- a/engine/enqueue.go +++ b/engine/enqueue.go @@ -11,7 +11,7 @@ import ( type Message struct { OriginID flow.Identifier - Payload interface{} + Payload any } // MessageStore is the interface to abstract how messages are buffered in memory @@ -73,7 +73,7 @@ func NewMessageHandler(log zerolog.Logger, notifier Notifier, patterns ...Patter // Returns // - IncompatibleInputTypeError if no matching processor was found // - All other errors are potential symptoms of internal state corruption or bugs (fatal). -func (e *MessageHandler) Process(originID flow.Identifier, payload interface{}) error { +func (e *MessageHandler) Process(originID flow.Identifier, payload any) error { msg := &Message{ OriginID: originID, Payload: payload, diff --git a/engine/errors.go b/engine/errors.go index df31acd58a8..4b3202098b6 100644 --- a/engine/errors.go +++ b/engine/errors.go @@ -22,7 +22,7 @@ type InvalidInputError struct { err error } -func NewInvalidInputErrorf(msg string, args ...interface{}) error { +func NewInvalidInputErrorf(msg string, args ...any) error { return InvalidInputError{ err: fmt.Errorf(msg, args...), } @@ -54,7 +54,7 @@ type NetworkTransmissionError struct { err error } -func NewNetworkTransmissionErrorf(msg string, args ...interface{}) error { +func NewNetworkTransmissionErrorf(msg string, args ...any) error { return NetworkTransmissionError{ err: fmt.Errorf(msg, args...), } @@ -76,7 +76,7 @@ type OutdatedInputError struct { err error } -func NewOutdatedInputErrorf(msg string, args ...interface{}) error { +func NewOutdatedInputErrorf(msg string, args ...any) error { return OutdatedInputError{ err: fmt.Errorf(msg, args...), } @@ -102,7 +102,7 @@ type UnverifiableInputError struct { err error } -func NewUnverifiableInputError(msg string, args ...interface{}) error { +func NewUnverifiableInputError(msg string, args ...any) error { return UnverifiableInputError{ err: fmt.Errorf(msg, args...), } @@ -125,7 +125,7 @@ type DuplicatedEntryError struct { err error } -func NewDuplicatedEntryErrorf(msg string, args ...interface{}) error { +func NewDuplicatedEntryErrorf(msg string, args ...any) error { return DuplicatedEntryError{ err: fmt.Errorf(msg, args...), } diff --git a/engine/execution/computation/computer/computer.go b/engine/execution/computation/computer/computer.go index a9c524830b0..2fb265af80a 100644 --- a/engine/execution/computation/computer/computer.go +++ b/engine/execution/computation/computer/computer.go @@ -11,7 +11,6 @@ import ( otelTrace "go.opentelemetry.io/otel/trace" "github.com/onflow/flow-go/engine/execution" - "github.com/onflow/flow-go/engine/execution/computation/result" "github.com/onflow/flow-go/engine/execution/utils" "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/blueprints" @@ -125,7 +124,6 @@ type blockComputer struct { signer module.Local spockHasher hash.Hasher receiptHasher hash.Hasher - colResCons []result.ExecutedCollectionConsumer protocolState protocol.SnapshotExecutionSubsetProvider maxConcurrency int } @@ -169,7 +167,6 @@ func NewBlockComputer( committer ViewCommitter, signer module.Local, executionDataProvider provider.Provider, - colResCons []result.ExecutedCollectionConsumer, state protocol.SnapshotExecutionSubsetProvider, maxConcurrency int, ) (BlockComputer, error) { @@ -213,7 +210,6 @@ func NewBlockComputer( signer: signer, spockHasher: utils.NewSPOCKHasher(), receiptHasher: utils.NewExecutionReceiptHasher(), - colResCons: colResCons, protocolState: state, maxConcurrency: maxConcurrency, }, nil @@ -403,7 +399,6 @@ func (e *blockComputer) executeBlock( block, // Add buffer just in case result collection becomes slower than the execution e.maxConcurrency*2, - e.colResCons, baseSnapshot, ) defer collector.Stop() @@ -638,7 +633,7 @@ func (e *blockComputer) executeProcessCallback( txnIndex++ - txn, err := e.executeTransactionInternal(blockSpan, database, request, 0) + txn, err := e.executeTransactionInternal(blockSpan, database, request, 1) if err != nil { snapshotTime := logical.Time(0) if txn != nil { diff --git a/engine/execution/computation/computer/computer_test.go b/engine/execution/computation/computer/computer_test.go index f65209e0000..87e2441c496 100644 --- a/engine/execution/computation/computer/computer_test.go +++ b/engine/execution/computation/computer/computer_test.go @@ -36,6 +36,7 @@ import ( "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/environment" fvmErrors "github.com/onflow/flow-go/fvm/errors" + "github.com/onflow/flow-go/fvm/inspection" fvmmock "github.com/onflow/flow-go/fvm/mock" reusableRuntime "github.com/onflow/flow-go/fvm/runtime" "github.com/onflow/flow-go/fvm/storage" @@ -134,7 +135,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { t.Run("single collection", func(t *testing.T) { - execCtx := fvm.NewContext() + execCtx := fvm.NewContext(flow.Mainnet.Chain()) vm := &testVM{ t: t, @@ -201,7 +202,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { committer, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -315,7 +315,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { t.Run("empty block still computes system chunk", func(t *testing.T) { - execCtx := fvm.NewContext() + execCtx := fvm.NewContext(flow.Mainnet.Chain()) vm := new(fvmmock.VM) committer := new(computermock.ViewCommitter) @@ -340,7 +340,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { committer, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -381,7 +380,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { t.Run("system chunk transaction should not fail", func(t *testing.T) { // include all fees. System chunk should ignore them contextOptions := []fvm.Option{ - fvm.WithEVMEnabled(true), fvm.WithTransactionFeesEnabled(true), fvm.WithAccountStorageLimit(true), fvm.WithBlocks(&environment.NoopBlockFinder{}), @@ -401,12 +399,11 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { vm := fvm.NewVirtualMachine() derivedBlockData := derived.NewEmptyDerivedBlockData(0) baseOpts := []fvm.Option{ - fvm.WithChain(chain), fvm.WithDerivedBlockData(derivedBlockData), } opts := append(baseOpts, contextOptions...) - ctx := fvm.NewContext(opts...) + ctx := fvm.NewContext(chain, opts...) snapshotTree := snapshot.NewSnapshotTree(nil) baseBootstrapOpts := []fvm.BootstrapProcedureOption{ @@ -443,7 +440,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { comm, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -475,7 +471,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { }) t.Run("multiple collections", func(t *testing.T) { - execCtx := fvm.NewContext() + execCtx := fvm.NewContext(flow.Mainnet.Chain()) committer := new(computermock.ViewCommitter) @@ -508,7 +504,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { committer, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -592,6 +587,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { t.Run( "service events are emitted", func(t *testing.T) { execCtx := fvm.NewContext( + flow.Mainnet.Chain(), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), ) @@ -704,6 +700,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewCustomReusableCadenceRuntimePool( 0, + execCtx.Chain, runtime.Config{}, func(_ runtime.Config) runtime.Runtime { return emittingRuntime @@ -734,7 +731,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -781,7 +777,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { t.Run("succeeding transactions store programs", func(t *testing.T) { - execCtx := fvm.NewContext() + execCtx := fvm.NewContext(flow.Mainnet.Chain()) address := common.Address{0x1} contractLocation := common.AddressLocation{ @@ -818,6 +814,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewCustomReusableCadenceRuntimePool( 0, + execCtx.Chain, runtime.Config{}, func(_ runtime.Config) runtime.Runtime { return rt @@ -846,7 +843,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -871,6 +867,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { t.Run("failing transactions do not store programs", func(t *testing.T) { execCtx := fvm.NewContext( + flow.Mainnet.Chain(), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), ) @@ -932,6 +929,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewCustomReusableCadenceRuntimePool( 0, + execCtx.Chain, runtime.Config{}, func(_ runtime.Config) runtime.Runtime { return rt @@ -960,7 +958,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -980,7 +977,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { }) t.Run("internal error", func(t *testing.T) { - execCtx := fvm.NewContext() + execCtx := fvm.NewContext(flow.Mainnet.Chain()) committer := new(computermock.ViewCommitter) @@ -1005,7 +1002,6 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { committer, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -1231,8 +1227,7 @@ func (f *FixedAddressGenerator) AddressCount() uint64 { func Test_ExecutingSystemCollection(t *testing.T) { execCtx := fvm.NewContext( - fvm.WithEVMEnabled(true), - fvm.WithChain(flow.Localnet.Chain()), + flow.Localnet.Chain(), fvm.WithBlocks(&environment.NoopBlockFinder{}), ) @@ -1345,7 +1340,6 @@ func Test_ExecutingSystemCollection(t *testing.T) { committer, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(constRandomSource), testMaxConcurrency) require.NoError(t, err) @@ -1451,8 +1445,8 @@ func testScheduledTransactionsWithError( testLogger := NewTestLogger() execCtx := fvm.NewContext( - fvm.WithScheduledTransactionsEnabled(true), // Enable scheduled transactions - fvm.WithChain(chain), + chain, + fvm.WithScheduledTransactionsEnabled(true), fvm.WithLogger(testLogger.Logger), ) @@ -1592,7 +1586,6 @@ func testScheduledTransactionsWithError( committer, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -2011,6 +2004,16 @@ func (testVM) GetAccount( panic("not implemented") } +func (testVM) Inspect( + _ fvm.Context, + _ fvm.Procedure, + _ snapshot.StorageSnapshot, + _ *snapshot.ExecutionSnapshot, + _ fvm.ProcedureOutput, +) []inspection.Result { + return nil +} + func generateEvents(eventCount int, txIndex uint32) []flow.Event { events := make([]flow.Event, eventCount) for i := 0; i < eventCount; i++ { @@ -2087,6 +2090,16 @@ func (errorVM) GetAccount( panic("not implemented") } +func (errorVM) Inspect( + _ fvm.Context, + _ fvm.Procedure, + _ snapshot.StorageSnapshot, + _ *snapshot.ExecutionSnapshot, + _ fvm.ProcedureOutput, +) []inspection.Result { + return nil +} + func getSetAProgram( t *testing.T, txnState storage.TransactionPreparer, diff --git a/engine/execution/computation/computer/mock/block_computer.go b/engine/execution/computation/computer/mock/block_computer.go index 2e309602195..42036146b76 100644 --- a/engine/execution/computation/computer/mock/block_computer.go +++ b/engine/execution/computation/computer/mock/block_computer.go @@ -1,30 +1,50 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - derived "github.com/onflow/flow-go/fvm/storage/derived" - entity "github.com/onflow/flow-go/module/mempool/entity" - - execution "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/fvm/storage/derived" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/mempool/entity" + mock "github.com/stretchr/testify/mock" +) - flow "github.com/onflow/flow-go/model/flow" +// NewBlockComputer creates a new instance of BlockComputer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockComputer(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockComputer { + mock := &BlockComputer{} + mock.Mock.Test(t) - mock "github.com/stretchr/testify/mock" + t.Cleanup(func() { mock.AssertExpectations(t) }) - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" -) + return mock +} // BlockComputer is an autogenerated mock type for the BlockComputer type type BlockComputer struct { mock.Mock } -// ExecuteBlock provides a mock function with given fields: ctx, parentBlockExecutionResultID, block, _a3, derivedBlockData -func (_m *BlockComputer) ExecuteBlock(ctx context.Context, parentBlockExecutionResultID flow.Identifier, block *entity.ExecutableBlock, _a3 snapshot.StorageSnapshot, derivedBlockData *derived.DerivedBlockData) (*execution.ComputationResult, error) { - ret := _m.Called(ctx, parentBlockExecutionResultID, block, _a3, derivedBlockData) +type BlockComputer_Expecter struct { + mock *mock.Mock +} + +func (_m *BlockComputer) EXPECT() *BlockComputer_Expecter { + return &BlockComputer_Expecter{mock: &_m.Mock} +} + +// ExecuteBlock provides a mock function for the type BlockComputer +func (_mock *BlockComputer) ExecuteBlock(ctx context.Context, parentBlockExecutionResultID flow.Identifier, block *entity.ExecutableBlock, snapshot1 snapshot.StorageSnapshot, derivedBlockData *derived.DerivedBlockData) (*execution.ComputationResult, error) { + ret := _mock.Called(ctx, parentBlockExecutionResultID, block, snapshot1, derivedBlockData) if len(ret) == 0 { panic("no return value specified for ExecuteBlock") @@ -32,36 +52,78 @@ func (_m *BlockComputer) ExecuteBlock(ctx context.Context, parentBlockExecutionR var r0 *execution.ComputationResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot, *derived.DerivedBlockData) (*execution.ComputationResult, error)); ok { - return rf(ctx, parentBlockExecutionResultID, block, _a3, derivedBlockData) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot, *derived.DerivedBlockData) (*execution.ComputationResult, error)); ok { + return returnFunc(ctx, parentBlockExecutionResultID, block, snapshot1, derivedBlockData) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot, *derived.DerivedBlockData) *execution.ComputationResult); ok { - r0 = rf(ctx, parentBlockExecutionResultID, block, _a3, derivedBlockData) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot, *derived.DerivedBlockData) *execution.ComputationResult); ok { + r0 = returnFunc(ctx, parentBlockExecutionResultID, block, snapshot1, derivedBlockData) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution.ComputationResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot, *derived.DerivedBlockData) error); ok { - r1 = rf(ctx, parentBlockExecutionResultID, block, _a3, derivedBlockData) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot, *derived.DerivedBlockData) error); ok { + r1 = returnFunc(ctx, parentBlockExecutionResultID, block, snapshot1, derivedBlockData) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBlockComputer creates a new instance of BlockComputer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockComputer(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockComputer { - mock := &BlockComputer{} - mock.Mock.Test(t) +// BlockComputer_ExecuteBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteBlock' +type BlockComputer_ExecuteBlock_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ExecuteBlock is a helper method to define mock.On call +// - ctx context.Context +// - parentBlockExecutionResultID flow.Identifier +// - block *entity.ExecutableBlock +// - snapshot1 snapshot.StorageSnapshot +// - derivedBlockData *derived.DerivedBlockData +func (_e *BlockComputer_Expecter) ExecuteBlock(ctx interface{}, parentBlockExecutionResultID interface{}, block interface{}, snapshot1 interface{}, derivedBlockData interface{}) *BlockComputer_ExecuteBlock_Call { + return &BlockComputer_ExecuteBlock_Call{Call: _e.mock.On("ExecuteBlock", ctx, parentBlockExecutionResultID, block, snapshot1, derivedBlockData)} +} - return mock +func (_c *BlockComputer_ExecuteBlock_Call) Run(run func(ctx context.Context, parentBlockExecutionResultID flow.Identifier, block *entity.ExecutableBlock, snapshot1 snapshot.StorageSnapshot, derivedBlockData *derived.DerivedBlockData)) *BlockComputer_ExecuteBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 *entity.ExecutableBlock + if args[2] != nil { + arg2 = args[2].(*entity.ExecutableBlock) + } + var arg3 snapshot.StorageSnapshot + if args[3] != nil { + arg3 = args[3].(snapshot.StorageSnapshot) + } + var arg4 *derived.DerivedBlockData + if args[4] != nil { + arg4 = args[4].(*derived.DerivedBlockData) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *BlockComputer_ExecuteBlock_Call) Return(computationResult *execution.ComputationResult, err error) *BlockComputer_ExecuteBlock_Call { + _c.Call.Return(computationResult, err) + return _c +} + +func (_c *BlockComputer_ExecuteBlock_Call) RunAndReturn(run func(ctx context.Context, parentBlockExecutionResultID flow.Identifier, block *entity.ExecutableBlock, snapshot1 snapshot.StorageSnapshot, derivedBlockData *derived.DerivedBlockData) (*execution.ComputationResult, error)) *BlockComputer_ExecuteBlock_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/computation/computer/mock/transaction_write_behind_logger.go b/engine/execution/computation/computer/mock/transaction_write_behind_logger.go index 7122b9ecee4..1081d02fb65 100644 --- a/engine/execution/computation/computer/mock/transaction_write_behind_logger.go +++ b/engine/execution/computation/computer/mock/transaction_write_behind_logger.go @@ -1,28 +1,18 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - computer "github.com/onflow/flow-go/engine/execution/computation/computer" - fvm "github.com/onflow/flow-go/fvm" + "time" + "github.com/onflow/flow-go/engine/execution/computation/computer" + "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm/storage/snapshot" mock "github.com/stretchr/testify/mock" - - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" - - time "time" ) -// TransactionWriteBehindLogger is an autogenerated mock type for the TransactionWriteBehindLogger type -type TransactionWriteBehindLogger struct { - mock.Mock -} - -// AddTransactionResult provides a mock function with given fields: txn, _a1, output, timeSpent, numTxnConflictRetries -func (_m *TransactionWriteBehindLogger) AddTransactionResult(txn computer.TransactionRequest, _a1 *snapshot.ExecutionSnapshot, output fvm.ProcedureOutput, timeSpent time.Duration, numTxnConflictRetries int) { - _m.Called(txn, _a1, output, timeSpent, numTxnConflictRetries) -} - // NewTransactionWriteBehindLogger creates a new instance of TransactionWriteBehindLogger. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewTransactionWriteBehindLogger(t interface { @@ -36,3 +26,80 @@ func NewTransactionWriteBehindLogger(t interface { return mock } + +// TransactionWriteBehindLogger is an autogenerated mock type for the TransactionWriteBehindLogger type +type TransactionWriteBehindLogger struct { + mock.Mock +} + +type TransactionWriteBehindLogger_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionWriteBehindLogger) EXPECT() *TransactionWriteBehindLogger_Expecter { + return &TransactionWriteBehindLogger_Expecter{mock: &_m.Mock} +} + +// AddTransactionResult provides a mock function for the type TransactionWriteBehindLogger +func (_mock *TransactionWriteBehindLogger) AddTransactionResult(txn computer.TransactionRequest, snapshot1 *snapshot.ExecutionSnapshot, output fvm.ProcedureOutput, timeSpent time.Duration, numTxnConflictRetries int) { + _mock.Called(txn, snapshot1, output, timeSpent, numTxnConflictRetries) + return +} + +// TransactionWriteBehindLogger_AddTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddTransactionResult' +type TransactionWriteBehindLogger_AddTransactionResult_Call struct { + *mock.Call +} + +// AddTransactionResult is a helper method to define mock.On call +// - txn computer.TransactionRequest +// - snapshot1 *snapshot.ExecutionSnapshot +// - output fvm.ProcedureOutput +// - timeSpent time.Duration +// - numTxnConflictRetries int +func (_e *TransactionWriteBehindLogger_Expecter) AddTransactionResult(txn interface{}, snapshot1 interface{}, output interface{}, timeSpent interface{}, numTxnConflictRetries interface{}) *TransactionWriteBehindLogger_AddTransactionResult_Call { + return &TransactionWriteBehindLogger_AddTransactionResult_Call{Call: _e.mock.On("AddTransactionResult", txn, snapshot1, output, timeSpent, numTxnConflictRetries)} +} + +func (_c *TransactionWriteBehindLogger_AddTransactionResult_Call) Run(run func(txn computer.TransactionRequest, snapshot1 *snapshot.ExecutionSnapshot, output fvm.ProcedureOutput, timeSpent time.Duration, numTxnConflictRetries int)) *TransactionWriteBehindLogger_AddTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 computer.TransactionRequest + if args[0] != nil { + arg0 = args[0].(computer.TransactionRequest) + } + var arg1 *snapshot.ExecutionSnapshot + if args[1] != nil { + arg1 = args[1].(*snapshot.ExecutionSnapshot) + } + var arg2 fvm.ProcedureOutput + if args[2] != nil { + arg2 = args[2].(fvm.ProcedureOutput) + } + var arg3 time.Duration + if args[3] != nil { + arg3 = args[3].(time.Duration) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *TransactionWriteBehindLogger_AddTransactionResult_Call) Return() *TransactionWriteBehindLogger_AddTransactionResult_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionWriteBehindLogger_AddTransactionResult_Call) RunAndReturn(run func(txn computer.TransactionRequest, snapshot1 *snapshot.ExecutionSnapshot, output fvm.ProcedureOutput, timeSpent time.Duration, numTxnConflictRetries int)) *TransactionWriteBehindLogger_AddTransactionResult_Call { + _c.Run(run) + return _c +} diff --git a/engine/execution/computation/computer/mock/view_committer.go b/engine/execution/computation/computer/mock/view_committer.go index 8ce508c4fc9..8f8afa411f5 100644 --- a/engine/execution/computation/computer/mock/view_committer.go +++ b/engine/execution/computation/computer/mock/view_committer.go @@ -1,26 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - execution "github.com/onflow/flow-go/engine/execution" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/model/flow" + mock "github.com/stretchr/testify/mock" +) - ledger "github.com/onflow/flow-go/ledger" +// NewViewCommitter creates a new instance of ViewCommitter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewViewCommitter(t interface { + mock.TestingT + Cleanup(func()) +}) *ViewCommitter { + mock := &ViewCommitter{} + mock.Mock.Test(t) - mock "github.com/stretchr/testify/mock" + t.Cleanup(func() { mock.AssertExpectations(t) }) - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" -) + return mock +} // ViewCommitter is an autogenerated mock type for the ViewCommitter type type ViewCommitter struct { mock.Mock } -// CommitView provides a mock function with given fields: _a0, _a1 -func (_m *ViewCommitter) CommitView(_a0 *snapshot.ExecutionSnapshot, _a1 execution.ExtendableStorageSnapshot) (flow.StateCommitment, []byte, *ledger.TrieUpdate, execution.ExtendableStorageSnapshot, error) { - ret := _m.Called(_a0, _a1) +type ViewCommitter_Expecter struct { + mock *mock.Mock +} + +func (_m *ViewCommitter) EXPECT() *ViewCommitter_Expecter { + return &ViewCommitter_Expecter{mock: &_m.Mock} +} + +// CommitView provides a mock function for the type ViewCommitter +func (_mock *ViewCommitter) CommitView(executionSnapshot *snapshot.ExecutionSnapshot, extendableStorageSnapshot execution.ExtendableStorageSnapshot) (flow.StateCommitment, []byte, *ledger.TrieUpdate, execution.ExtendableStorageSnapshot, error) { + ret := _mock.Called(executionSnapshot, extendableStorageSnapshot) if len(ret) == 0 { panic("no return value specified for CommitView") @@ -31,60 +52,81 @@ func (_m *ViewCommitter) CommitView(_a0 *snapshot.ExecutionSnapshot, _a1 executi var r2 *ledger.TrieUpdate var r3 execution.ExtendableStorageSnapshot var r4 error - if rf, ok := ret.Get(0).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) (flow.StateCommitment, []byte, *ledger.TrieUpdate, execution.ExtendableStorageSnapshot, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) (flow.StateCommitment, []byte, *ledger.TrieUpdate, execution.ExtendableStorageSnapshot, error)); ok { + return returnFunc(executionSnapshot, extendableStorageSnapshot) } - if rf, ok := ret.Get(0).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) flow.StateCommitment); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) flow.StateCommitment); ok { + r0 = returnFunc(executionSnapshot, extendableStorageSnapshot) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) []byte); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) []byte); ok { + r1 = returnFunc(executionSnapshot, extendableStorageSnapshot) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]byte) } } - - if rf, ok := ret.Get(2).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) *ledger.TrieUpdate); ok { - r2 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(2).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) *ledger.TrieUpdate); ok { + r2 = returnFunc(executionSnapshot, extendableStorageSnapshot) } else { if ret.Get(2) != nil { r2 = ret.Get(2).(*ledger.TrieUpdate) } } - - if rf, ok := ret.Get(3).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) execution.ExtendableStorageSnapshot); ok { - r3 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(3).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) execution.ExtendableStorageSnapshot); ok { + r3 = returnFunc(executionSnapshot, extendableStorageSnapshot) } else { if ret.Get(3) != nil { r3 = ret.Get(3).(execution.ExtendableStorageSnapshot) } } - - if rf, ok := ret.Get(4).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) error); ok { - r4 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(4).(func(*snapshot.ExecutionSnapshot, execution.ExtendableStorageSnapshot) error); ok { + r4 = returnFunc(executionSnapshot, extendableStorageSnapshot) } else { r4 = ret.Error(4) } - return r0, r1, r2, r3, r4 } -// NewViewCommitter creates a new instance of ViewCommitter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewViewCommitter(t interface { - mock.TestingT - Cleanup(func()) -}) *ViewCommitter { - mock := &ViewCommitter{} - mock.Mock.Test(t) +// ViewCommitter_CommitView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CommitView' +type ViewCommitter_CommitView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// CommitView is a helper method to define mock.On call +// - executionSnapshot *snapshot.ExecutionSnapshot +// - extendableStorageSnapshot execution.ExtendableStorageSnapshot +func (_e *ViewCommitter_Expecter) CommitView(executionSnapshot interface{}, extendableStorageSnapshot interface{}) *ViewCommitter_CommitView_Call { + return &ViewCommitter_CommitView_Call{Call: _e.mock.On("CommitView", executionSnapshot, extendableStorageSnapshot)} +} - return mock +func (_c *ViewCommitter_CommitView_Call) Run(run func(executionSnapshot *snapshot.ExecutionSnapshot, extendableStorageSnapshot execution.ExtendableStorageSnapshot)) *ViewCommitter_CommitView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *snapshot.ExecutionSnapshot + if args[0] != nil { + arg0 = args[0].(*snapshot.ExecutionSnapshot) + } + var arg1 execution.ExtendableStorageSnapshot + if args[1] != nil { + arg1 = args[1].(execution.ExtendableStorageSnapshot) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ViewCommitter_CommitView_Call) Return(stateCommitment flow.StateCommitment, bytes []byte, trieUpdate *ledger.TrieUpdate, extendableStorageSnapshot1 execution.ExtendableStorageSnapshot, err error) *ViewCommitter_CommitView_Call { + _c.Call.Return(stateCommitment, bytes, trieUpdate, extendableStorageSnapshot1, err) + return _c +} + +func (_c *ViewCommitter_CommitView_Call) RunAndReturn(run func(executionSnapshot *snapshot.ExecutionSnapshot, extendableStorageSnapshot execution.ExtendableStorageSnapshot) (flow.StateCommitment, []byte, *ledger.TrieUpdate, execution.ExtendableStorageSnapshot, error)) *ViewCommitter_CommitView_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/computation/computer/result_collector.go b/engine/execution/computation/computer/result_collector.go index 3e249147394..ab0580445c4 100644 --- a/engine/execution/computation/computer/result_collector.go +++ b/engine/execution/computation/computer/result_collector.go @@ -8,12 +8,13 @@ import ( "github.com/onflow/crypto" "github.com/onflow/crypto/hash" + "github.com/rs/zerolog" otelTrace "go.opentelemetry.io/otel/trace" "github.com/onflow/flow-go/engine/execution" - "github.com/onflow/flow-go/engine/execution/computation/result" "github.com/onflow/flow-go/engine/execution/storehouse" "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm/inspection" "github.com/onflow/flow-go/fvm/meter" "github.com/onflow/flow-go/fvm/storage/snapshot" "github.com/onflow/flow-go/fvm/storage/state" @@ -72,8 +73,7 @@ type resultCollector struct { parentBlockExecutionResultID flow.Identifier - result *execution.ComputationResult - consumers []result.ExecutedCollectionConsumer + result *execution.ComputationResult spockSignatures []crypto.Signature @@ -99,7 +99,6 @@ func newResultCollector( parentBlockExecutionResultID flow.Identifier, block *entity.ExecutableBlock, inputChannelSize int, - consumers []result.ExecutedCollectionConsumer, previousBlockSnapshot snapshot.StorageSnapshot, ) *resultCollector { numCollections := len(block.Collections()) + 1 @@ -117,7 +116,6 @@ func newResultCollector( executionDataProvider: executionDataProvider, parentBlockExecutionResultID: parentBlockExecutionResultID, result: execution.NewEmptyComputationResult(block), - consumers: consumers, spockSignatures: make([]crypto.Signature, 0, numCollections), blockStartTime: now, blockMeter: meter.NewMeter(meter.DefaultParameters()), @@ -209,13 +207,6 @@ func (collector *resultCollector) commitCollection( collector.currentCollectionState = state.NewExecutionState(nil, state.DefaultParameters()) collector.currentCollectionStats = module.CollectionExecutionResultStats{} - for _, consumer := range collector.consumers { - err = consumer.OnExecutedCollection(collector.result.CollectionExecutionResultAt(collection.collectionIndex)) - if err != nil { - return fmt.Errorf("consumer failed: %w", err) - } - } - return nil } @@ -227,6 +218,7 @@ func (collector *resultCollector) processTransactionResult( numConflictRetries int, ) error { logger := txn.ctx.Logger.With(). + Hex("tx_id", txn.ID[:]). Uint64("computation_used", output.ComputationUsed). Uint64("memory_used", output.MemoryEstimate). Int64("time_spent_in_ms", timeSpent.Milliseconds()). @@ -252,6 +244,14 @@ func (collector *resultCollector) processTransactionResult( logger.Info().Msg("transaction executed successfully") } + // We log inspection results here, because if we logged them in the FVM + // they would get logged on every transaction retry. + // Same for the metrics. + collector.logInspectionResults( + logger.With().Str("module", "transaction-inspection").Logger(), + output.InspectionResults, + ) + collector.handleTransactionExecutionMetrics( timeSpent, output, @@ -293,6 +293,52 @@ func (collector *resultCollector) processTransactionResult( collector.currentCollectionState.Finalize()) } +func (collector *resultCollector) logInspectionResults( + log zerolog.Logger, + results []inspection.Result, +) { + if len(results) == 0 { + log.Info(). + Msg("no inspection results for transaction") + return + } + + logEvents := make([]func(e *zerolog.Event), 0, len(results)) + + // The log level will be decided by the inspectionResults + // logLevel := zerolog.TraceLevel + // leo: debugging with info level log + logLevel := zerolog.InfoLevel + for i, inspectionResult := range results { + if inspectionResult == nil { + // This code path is unlikely since it should be handled earlier + log.Error(). + Int("index", i). + Msg("inspection result is nil, likely due to a panic or error during inspection") + continue + } + lvl, evt := inspectionResult.AsLogEvent() + if lvl > logLevel { + logLevel = lvl + } + if evt != nil { + logEvents = append(logEvents, evt) + } + } + + // if there are no loggable inspection results, don't log at all + if len(logEvents) == 0 { + + return + } + + evt := log.WithLevel(logLevel) + for _, logEvent := range logEvents { + logEvent(evt) + } + evt.Msg("Transaction inspection results") +} + func (collector *resultCollector) handleTransactionExecutionMetrics( timeSpent time.Duration, output fvm.ProcedureOutput, diff --git a/engine/execution/computation/computer/transaction_coordinator.go b/engine/execution/computation/computer/transaction_coordinator.go index 6ce2cb3757c..353c8ace85f 100644 --- a/engine/execution/computation/computer/transaction_coordinator.go +++ b/engine/execution/computation/computer/transaction_coordinator.go @@ -124,7 +124,7 @@ func (coordinator *transactionCoordinator) NewTransaction( return &transaction{ request: request, coordinator: coordinator, - numConflictRetries: attempt, + numConflictRetries: attempt - 1, startedAt: time.Now(), Transaction: txn, ProcedureExecutor: coordinator.vm.NewExecutor( diff --git a/engine/execution/computation/computer/transaction_coordinator_test.go b/engine/execution/computation/computer/transaction_coordinator_test.go index 0cee4598883..1cca10017d3 100644 --- a/engine/execution/computation/computer/transaction_coordinator_test.go +++ b/engine/execution/computation/computer/transaction_coordinator_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm/inspection" "github.com/onflow/flow-go/fvm/storage" "github.com/onflow/flow-go/fvm/storage/logical" "github.com/onflow/flow-go/fvm/storage/snapshot" @@ -50,6 +51,16 @@ func (testCoordinatorVM) GetAccount( panic("not implemented") } +func (testCoordinatorVM) Inspect( + _ fvm.Context, + _ fvm.Procedure, + _ snapshot.StorageSnapshot, + _ *snapshot.ExecutionSnapshot, + _ fvm.ProcedureOutput, +) []inspection.Result { + return nil +} + type testCoordinatorExecutor struct { executionTime logical.Time } @@ -118,7 +129,7 @@ func (db *testCoordinator) newTransaction(txnIndex uint32) ( return db.NewTransaction( newTransactionRequest( collectionInfo{}, - fvm.NewContext(), + fvm.NewContext(flow.Mainnet.Chain()), zerolog.Nop(), txnIndex, &flow.TransactionBody{}, diff --git a/engine/execution/computation/execution_verification_test.go b/engine/execution/computation/execution_verification_test.go index 465adc2e500..a95f4e2afe3 100644 --- a/engine/execution/computation/execution_verification_test.go +++ b/engine/execution/computation/execution_verification_test.go @@ -220,7 +220,7 @@ func Test_ExecutionMatchesVerification(t *testing.T) { err = testutil.SignTransaction(addKeyTxBuilder, accountAddress, accountPrivKey, 0) require.NoError(t, err) - minimumStorage, err := cadence.NewUFix64("0.00011661") + minimumStorage, err := cadence.NewUFix64("0.00015594") require.NoError(t, err) createAccountTx, err := createAccountTxBuilder.Build() @@ -746,14 +746,11 @@ func executeBlockAndVerifyWithParameters(t *testing.T, logger := zerolog.Nop() - opts = append(opts, fvm.WithChain(chain)) opts = append(opts, fvm.WithLogger(logger)) opts = append(opts, fvm.WithBlocks(&environment.NoopBlockFinder{})) fvmContext := - fvm.NewContext( - opts..., - ) + fvm.NewContext(chain, opts...) collector := metrics.NewNoopCollector() tracer := trace.NewNoopTracer() @@ -817,7 +814,6 @@ func executeBlockAndVerifyWithParameters(t *testing.T, ledgerCommiter, me, prov, - nil, stateForRandomSource, testVerifyMaxConcurrency) require.NoError(t, err) diff --git a/engine/execution/computation/manager.go b/engine/execution/computation/manager.go index baa4e6639e2..9078ab0020e 100644 --- a/engine/execution/computation/manager.go +++ b/engine/execution/computation/manager.go @@ -7,6 +7,8 @@ import ( "github.com/onflow/cadence/runtime" "github.com/rs/zerolog" + "github.com/onflow/flow-go/fvm/inspection" + "github.com/onflow/flow-go/engine/execution" "github.com/onflow/flow-go/engine/execution/computation/computer" "github.com/onflow/flow-go/engine/execution/computation/query" @@ -66,6 +68,9 @@ type ComputationConfig struct { DerivedDataCacheSize uint MaxConcurrency int + // TokenTrackingEnabled enables tracking and logging of token movements on transactions. + TokenTrackingEnabled bool + // When NewCustomVirtualMachine is nil, the manager will create a standard // fvm virtual machine via fvm.NewVirtualMachine. Otherwise, the manager // will create a virtual machine using this function. @@ -106,7 +111,7 @@ func New( } chainID := vmCtx.Chain.ChainID() - options := DefaultFVMOptions(chainID, params.ExtensiveTracing, vmCtx.ScheduledTransactionsEnabled) + options := DefaultFVMOptions(chainID, params.ExtensiveTracing, vmCtx.ScheduledTransactionsEnabled, params.TokenTrackingEnabled) vmCtx = fvm.NewContextFromParent(vmCtx, options...) blockComputer, err := computer.NewBlockComputer( @@ -118,7 +123,6 @@ func New( committer, me, executionDataProvider, - nil, // TODO(ramtin): update me with proper consumers protoState, params.MaxConcurrency, ) @@ -223,16 +227,15 @@ func (e *Manager) QueryExecutor() query.Executor { return e.queryExecutor } -func DefaultFVMOptions(chainID flow.ChainID, extensiveTracing bool, scheduleCallbacksEnabled bool) []fvm.Option { +func DefaultFVMOptions(chainID flow.ChainID, extensiveTracing, scheduleCallbacksEnabled, tokenTracking bool) []fvm.Option { options := []fvm.Option{ - fvm.WithChain(chainID.Chain()), fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewReusableCadenceRuntimePool( ReusableCadenceRuntimePoolSize, + chainID.Chain(), runtime.Config{}, ), ), - fvm.WithEVMEnabled(true), fvm.WithScheduledTransactionsEnabled(scheduleCallbacksEnabled), } @@ -240,5 +243,11 @@ func DefaultFVMOptions(chainID flow.ChainID, extensiveTracing bool, scheduleCall options = append(options, fvm.WithExtensiveTracing()) } + if tokenTracking { + options = append(options, fvm.WithInspectors([]inspection.Inspector{ + inspection.NewTokenChangesInspector(inspection.DefaultTokenDiffSearchTokens(chainID.Chain()), chainID), + })) + } + return options } diff --git a/engine/execution/computation/manager_benchmark_test.go b/engine/execution/computation/manager_benchmark_test.go index fa3d91e0fed..39dab40c887 100644 --- a/engine/execution/computation/manager_benchmark_test.go +++ b/engine/execution/computation/manager_benchmark_test.go @@ -155,13 +155,14 @@ func benchmarkComputeBlock( const chainID = flow.Emulator execCtx := fvm.NewContext( - fvm.WithChain(chainID.Chain()), + chainID.Chain(), fvm.WithAccountStorageLimit(true), fvm.WithTransactionFeesEnabled(true), fvm.WithTracer(tracer), fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewReusableCadenceRuntimePool( ReusableCadenceRuntimePoolSize, + chainID.Chain(), runtime.Config{}, )), ) @@ -203,7 +204,6 @@ func benchmarkComputeBlock( committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), maxConcurrency) require.NoError(b, err) diff --git a/engine/execution/computation/manager_test.go b/engine/execution/computation/manager_test.go index c5a5f885b8d..afed9fa844a 100644 --- a/engine/execution/computation/manager_test.go +++ b/engine/execution/computation/manager_test.go @@ -30,6 +30,7 @@ import ( "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/environment" fvmErrors "github.com/onflow/flow-go/fvm/errors" + "github.com/onflow/flow-go/fvm/inspection" "github.com/onflow/flow-go/fvm/storage" "github.com/onflow/flow-go/fvm/storage/derived" "github.com/onflow/flow-go/fvm/storage/snapshot" @@ -56,7 +57,7 @@ func TestComputeBlockWithStorage(t *testing.T) { chain := flow.Mainnet.Chain() vm := fvm.NewVirtualMachine() - execCtx := fvm.NewContext(fvm.WithChain(chain)) + execCtx := fvm.NewContext(chain) privateKeys, err := testutil.GenerateAccountPrivateKeys(2) require.NoError(t, err) @@ -149,7 +150,6 @@ func TestComputeBlockWithStorage(t *testing.T) { committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -237,7 +237,7 @@ func TestExecuteScript(t *testing.T) { logger := zerolog.Nop() - execCtx := fvm.NewContext(fvm.WithLogger(logger)) + execCtx := fvm.NewContext(flow.Mainnet.Chain(), fvm.WithLogger(logger)) me := new(module.Local) me.On("NodeID").Return(unittest.IdentifierFixture()) @@ -304,7 +304,7 @@ func TestExecuteScript_BalanceScriptFailsIfViewIsEmpty(t *testing.T) { logger := zerolog.Nop() - execCtx := fvm.NewContext(fvm.WithLogger(logger)) + execCtx := fvm.NewContext(flow.Mainnet.Chain(), fvm.WithLogger(logger)) me := new(module.Local) me.On("NodeID").Return(unittest.IdentifierFixture()) @@ -368,7 +368,7 @@ func TestExecuteScript_BalanceScriptFailsIfViewIsEmpty(t *testing.T) { func TestExecuteScripPanicsAreHandled(t *testing.T) { t.Parallel() - ctx := fvm.NewContext() + ctx := fvm.NewContext(flow.Mainnet.Chain()) buffer := &bytes.Buffer{} log := zerolog.New(buffer) @@ -419,7 +419,7 @@ func TestExecuteScripPanicsAreHandled(t *testing.T) { func TestExecuteScript_LongScriptsAreLogged(t *testing.T) { t.Parallel() - ctx := fvm.NewContext() + ctx := fvm.NewContext(flow.Mainnet.Chain()) buffer := &bytes.Buffer{} log := zerolog.New(buffer) @@ -473,7 +473,7 @@ func TestExecuteScript_LongScriptsAreLogged(t *testing.T) { func TestExecuteScript_ShortScriptsAreNotLogged(t *testing.T) { t.Parallel() - ctx := fvm.NewContext() + ctx := fvm.NewContext(flow.Mainnet.Chain()) buffer := &bytes.Buffer{} log := zerolog.New(buffer) @@ -573,6 +573,16 @@ func (p *PanickingVM) GetAccount( panic("not expected") } +func (p *PanickingVM) Inspect( + ctx fvm.Context, + proc fvm.Procedure, + storageSnapshot snapshot.StorageSnapshot, + executionSnapshot *snapshot.ExecutionSnapshot, + output fvm.ProcedureOutput, +) []inspection.Result { + return nil +} + type LongRunningExecutor struct { duration time.Duration } @@ -637,6 +647,16 @@ func (l *LongRunningVM) GetAccount( panic("not expected") } +func (l *LongRunningVM) Inspect( + ctx fvm.Context, + proc fvm.Procedure, + storageSnapshot snapshot.StorageSnapshot, + executionSnapshot *snapshot.ExecutionSnapshot, + output fvm.ProcedureOutput, +) []inspection.Result { + return nil +} + type FakeBlockComputer struct { computationResult *execution.ComputationResult } @@ -664,7 +684,7 @@ func TestExecuteScriptTimeout(t *testing.T) { trace.NewNoopTracer(), nil, testutil.ProtocolStateWithSourceFixture(nil), - fvm.NewContext(), + fvm.NewContext(flow.Mainnet.Chain()), committer.NewNoopViewCommitter(), nil, ComputationConfig{ @@ -712,7 +732,7 @@ func TestExecuteScriptCancelled(t *testing.T) { trace.NewNoopTracer(), nil, testutil.ProtocolStateWithSourceFixture(nil), - fvm.NewContext(), + fvm.NewContext(flow.Mainnet.Chain()), committer.NewNoopViewCommitter(), nil, ComputationConfig{ @@ -770,7 +790,7 @@ func Test_EventEncodingFailsOnlyTxAndCarriesOn(t *testing.T) { } execCtx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithEventEncoder(eventEncoder), ) @@ -858,7 +878,6 @@ func Test_EventEncodingFailsOnlyTxAndCarriesOn(t *testing.T) { committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -923,7 +942,7 @@ func TestScriptStorageMutationsDiscarded(t *testing.T) { timeout := 10 * time.Second chain := flow.Mainnet.Chain() - ctx := fvm.NewContext(fvm.WithChain(chain)) + ctx := fvm.NewContext(chain) manager, _ := New( zerolog.Nop(), metrics.NewExecutionCollector(ctx.Tracer), diff --git a/engine/execution/computation/mock/computation_manager.go b/engine/execution/computation/mock/computation_manager.go deleted file mode 100644 index 060e1671b4d..00000000000 --- a/engine/execution/computation/mock/computation_manager.go +++ /dev/null @@ -1,132 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - execution "github.com/onflow/flow-go/engine/execution" - entity "github.com/onflow/flow-go/module/mempool/entity" - - flow "github.com/onflow/flow-go/model/flow" - - mock "github.com/stretchr/testify/mock" - - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" -) - -// ComputationManager is an autogenerated mock type for the ComputationManager type -type ComputationManager struct { - mock.Mock -} - -// ComputeBlock provides a mock function with given fields: ctx, parentBlockExecutionResultID, block, _a3 -func (_m *ComputationManager) ComputeBlock(ctx context.Context, parentBlockExecutionResultID flow.Identifier, block *entity.ExecutableBlock, _a3 snapshot.StorageSnapshot) (*execution.ComputationResult, error) { - ret := _m.Called(ctx, parentBlockExecutionResultID, block, _a3) - - if len(ret) == 0 { - panic("no return value specified for ComputeBlock") - } - - var r0 *execution.ComputationResult - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot) (*execution.ComputationResult, error)); ok { - return rf(ctx, parentBlockExecutionResultID, block, _a3) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot) *execution.ComputationResult); ok { - r0 = rf(ctx, parentBlockExecutionResultID, block, _a3) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*execution.ComputationResult) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, *entity.ExecutableBlock, snapshot.StorageSnapshot) error); ok { - r1 = rf(ctx, parentBlockExecutionResultID, block, _a3) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ExecuteScript provides a mock function with given fields: ctx, script, arguments, blockHeader, _a4 -func (_m *ComputationManager) ExecuteScript(ctx context.Context, script []byte, arguments [][]byte, blockHeader *flow.Header, _a4 snapshot.StorageSnapshot) ([]byte, uint64, error) { - ret := _m.Called(ctx, script, arguments, blockHeader, _a4) - - if len(ret) == 0 { - panic("no return value specified for ExecuteScript") - } - - var r0 []byte - var r1 uint64 - var r2 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) ([]byte, uint64, error)); ok { - return rf(ctx, script, arguments, blockHeader, _a4) - } - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) []byte); ok { - r0 = rf(ctx, script, arguments, blockHeader, _a4) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) uint64); ok { - r1 = rf(ctx, script, arguments, blockHeader, _a4) - } else { - r1 = ret.Get(1).(uint64) - } - - if rf, ok := ret.Get(2).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) error); ok { - r2 = rf(ctx, script, arguments, blockHeader, _a4) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// GetAccount provides a mock function with given fields: ctx, addr, header, _a3 -func (_m *ComputationManager) GetAccount(ctx context.Context, addr flow.Address, header *flow.Header, _a3 snapshot.StorageSnapshot) (*flow.Account, error) { - ret := _m.Called(ctx, addr, header, _a3) - - if len(ret) == 0 { - panic("no return value specified for GetAccount") - } - - var r0 *flow.Account - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) (*flow.Account, error)); ok { - return rf(ctx, addr, header, _a3) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) *flow.Account); ok { - r0 = rf(ctx, addr, header, _a3) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Account) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) error); ok { - r1 = rf(ctx, addr, header, _a3) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewComputationManager creates a new instance of ComputationManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewComputationManager(t interface { - mock.TestingT - Cleanup(func()) -}) *ComputationManager { - mock := &ComputationManager{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/execution/computation/programs_test.go b/engine/execution/computation/programs_test.go index 883775b6241..8b3798dc4e3 100644 --- a/engine/execution/computation/programs_test.go +++ b/engine/execution/computation/programs_test.go @@ -44,7 +44,7 @@ func TestPrograms_TestContractUpdates(t *testing.T) { chain := flow.Mainnet.Chain() vm := fvm.NewVirtualMachine() - execCtx := fvm.NewContext(fvm.WithChain(chain)) + execCtx := fvm.NewContext(chain) privateKeys, err := testutil.GenerateAccountPrivateKeys(1) require.NoError(t, err) @@ -151,7 +151,6 @@ func TestPrograms_TestContractUpdates(t *testing.T) { committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) @@ -223,10 +222,10 @@ func TestPrograms_TestBlockForks(t *testing.T) { chain := flow.Emulator.Chain() vm := fvm.NewVirtualMachine() execCtx := fvm.NewContext( - fvm.WithEVMEnabled(true), + chain, fvm.WithBlockHeader(block.ToHeader()), fvm.WithBlocks(blockProvider{map[uint64]*flow.Block{0: block}}), - fvm.WithChain(chain)) + ) privateKeys, err := testutil.GenerateAccountPrivateKeys(1) require.NoError(t, err) snapshotTree, accounts, err := testutil.CreateAccounts( @@ -265,7 +264,6 @@ func TestPrograms_TestBlockForks(t *testing.T) { committer.NewNoopViewCommitter(), me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), testMaxConcurrency) require.NoError(t, err) diff --git a/engine/execution/computation/query/executor.go b/engine/execution/computation/query/executor.go index 1027cebcbfa..5bb5364fc8f 100644 --- a/engine/execution/computation/query/executor.go +++ b/engine/execution/computation/query/executor.go @@ -10,6 +10,7 @@ import ( "github.com/onflow/flow-go/fvm/errors" + "github.com/onflow/cadence/common" jsoncdc "github.com/onflow/cadence/encoding/json" "github.com/rs/zerolog" @@ -406,3 +407,34 @@ func (e *QueryExecutor) GetAccountKey( return accountKey, nil } + +// GetAccountCode returns the code for the given account and contract name at the provided block height. +func (e *QueryExecutor) GetAccountCode( + _ context.Context, + address flow.Address, + contractName string, + blockHeader *flow.Header, + snapshot snapshot.StorageSnapshot, +) ([]byte, error) { + blockCtx := fvm.NewContextFromParent( + e.vmCtx, + fvm.WithBlockHeader(blockHeader), + fvm.WithDerivedBlockData( + e.derivedChainData.NewDerivedBlockDataForScript(blockHeader.ID()))) + + location := common.AddressLocation{ + Address: common.Address(address), + Name: contractName, + } + + code, err := fvm.GetAccountCode(blockCtx, location, snapshot) + if err != nil { + return nil, fmt.Errorf( + "failed to get account code (%s) at block (%s): %w", + location.String(), + blockHeader.ID(), + err) + } + + return code, nil +} diff --git a/engine/execution/computation/query/mock/executor.go b/engine/execution/computation/query/mock/executor.go deleted file mode 100644 index ec40569c661..00000000000 --- a/engine/execution/computation/query/mock/executor.go +++ /dev/null @@ -1,214 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - mock "github.com/stretchr/testify/mock" - - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" -) - -// Executor is an autogenerated mock type for the Executor type -type Executor struct { - mock.Mock -} - -// ExecuteScript provides a mock function with given fields: ctx, script, arguments, blockHeader, _a4 -func (_m *Executor) ExecuteScript(ctx context.Context, script []byte, arguments [][]byte, blockHeader *flow.Header, _a4 snapshot.StorageSnapshot) ([]byte, uint64, error) { - ret := _m.Called(ctx, script, arguments, blockHeader, _a4) - - if len(ret) == 0 { - panic("no return value specified for ExecuteScript") - } - - var r0 []byte - var r1 uint64 - var r2 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) ([]byte, uint64, error)); ok { - return rf(ctx, script, arguments, blockHeader, _a4) - } - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) []byte); ok { - r0 = rf(ctx, script, arguments, blockHeader, _a4) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) uint64); ok { - r1 = rf(ctx, script, arguments, blockHeader, _a4) - } else { - r1 = ret.Get(1).(uint64) - } - - if rf, ok := ret.Get(2).(func(context.Context, []byte, [][]byte, *flow.Header, snapshot.StorageSnapshot) error); ok { - r2 = rf(ctx, script, arguments, blockHeader, _a4) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// GetAccount provides a mock function with given fields: ctx, addr, header, _a3 -func (_m *Executor) GetAccount(ctx context.Context, addr flow.Address, header *flow.Header, _a3 snapshot.StorageSnapshot) (*flow.Account, error) { - ret := _m.Called(ctx, addr, header, _a3) - - if len(ret) == 0 { - panic("no return value specified for GetAccount") - } - - var r0 *flow.Account - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) (*flow.Account, error)); ok { - return rf(ctx, addr, header, _a3) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) *flow.Account); ok { - r0 = rf(ctx, addr, header, _a3) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Account) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) error); ok { - r1 = rf(ctx, addr, header, _a3) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAccountAvailableBalance provides a mock function with given fields: ctx, addr, header, _a3 -func (_m *Executor) GetAccountAvailableBalance(ctx context.Context, addr flow.Address, header *flow.Header, _a3 snapshot.StorageSnapshot) (uint64, error) { - ret := _m.Called(ctx, addr, header, _a3) - - if len(ret) == 0 { - panic("no return value specified for GetAccountAvailableBalance") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) (uint64, error)); ok { - return rf(ctx, addr, header, _a3) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) uint64); ok { - r0 = rf(ctx, addr, header, _a3) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) error); ok { - r1 = rf(ctx, addr, header, _a3) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAccountBalance provides a mock function with given fields: ctx, addr, header, _a3 -func (_m *Executor) GetAccountBalance(ctx context.Context, addr flow.Address, header *flow.Header, _a3 snapshot.StorageSnapshot) (uint64, error) { - ret := _m.Called(ctx, addr, header, _a3) - - if len(ret) == 0 { - panic("no return value specified for GetAccountBalance") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) (uint64, error)); ok { - return rf(ctx, addr, header, _a3) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) uint64); ok { - r0 = rf(ctx, addr, header, _a3) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) error); ok { - r1 = rf(ctx, addr, header, _a3) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAccountKey provides a mock function with given fields: ctx, addr, keyIndex, header, _a4 -func (_m *Executor) GetAccountKey(ctx context.Context, addr flow.Address, keyIndex uint32, header *flow.Header, _a4 snapshot.StorageSnapshot) (*flow.AccountPublicKey, error) { - ret := _m.Called(ctx, addr, keyIndex, header, _a4) - - if len(ret) == 0 { - panic("no return value specified for GetAccountKey") - } - - var r0 *flow.AccountPublicKey - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *flow.Header, snapshot.StorageSnapshot) (*flow.AccountPublicKey, error)); ok { - return rf(ctx, addr, keyIndex, header, _a4) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, *flow.Header, snapshot.StorageSnapshot) *flow.AccountPublicKey); ok { - r0 = rf(ctx, addr, keyIndex, header, _a4) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.AccountPublicKey) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, *flow.Header, snapshot.StorageSnapshot) error); ok { - r1 = rf(ctx, addr, keyIndex, header, _a4) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAccountKeys provides a mock function with given fields: ctx, addr, header, _a3 -func (_m *Executor) GetAccountKeys(ctx context.Context, addr flow.Address, header *flow.Header, _a3 snapshot.StorageSnapshot) ([]flow.AccountPublicKey, error) { - ret := _m.Called(ctx, addr, header, _a3) - - if len(ret) == 0 { - panic("no return value specified for GetAccountKeys") - } - - var r0 []flow.AccountPublicKey - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) ([]flow.AccountPublicKey, error)); ok { - return rf(ctx, addr, header, _a3) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) []flow.AccountPublicKey); ok { - r0 = rf(ctx, addr, header, _a3) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]flow.AccountPublicKey) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, *flow.Header, snapshot.StorageSnapshot) error); ok { - r1 = rf(ctx, addr, header, _a3) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewExecutor creates a new instance of Executor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutor(t interface { - mock.TestingT - Cleanup(func()) -}) *Executor { - mock := &Executor{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/execution/computation/result/consumer.go b/engine/execution/computation/result/consumer.go index b7218577f10..a9ea9960e2e 100644 --- a/engine/execution/computation/result/consumer.go +++ b/engine/execution/computation/result/consumer.go @@ -39,12 +39,6 @@ type ExecutedCollection interface { ExecutionSnapshot() *snapshot.ExecutionSnapshot } -// ExecutedCollectionConsumer consumes ExecutedCollections -type ExecutedCollectionConsumer interface { - module.ReadyDoneAware - OnExecutedCollection(res ExecutedCollection) error -} - // AttestedCollection holds results of a collection attestation type AttestedCollection interface { ExecutedCollection diff --git a/engine/execution/ingestion/block_executed_notifier.go b/engine/execution/ingestion/block_executed_notifier.go new file mode 100644 index 00000000000..b134e8603a7 --- /dev/null +++ b/engine/execution/ingestion/block_executed_notifier.go @@ -0,0 +1,40 @@ +package ingestion + +import ( + "sync" + + "github.com/onflow/flow-go/engine/execution/storehouse" +) + +// BlockExecutedNotifier is a thread-safe event distributor that notifies subscribers +// when blocks have been executed. It allows multiple callbacks to subscribe to block execution events. +type BlockExecutedNotifier struct { + callbacks []func() + mu sync.RWMutex +} + +// Ensure BlockExecutedNotifier implements storehouse.BlockExecutedNotifier +var _ storehouse.BlockExecutedNotifier = (*BlockExecutedNotifier)(nil) + +// NewBlockExecutedNotifier creates a new BlockExecutedNotifier. +func NewBlockExecutedNotifier() *BlockExecutedNotifier { + return &BlockExecutedNotifier{} +} + +// AddConsumer adds a callback to be notified when blocks are executed. +// This method is thread-safe. +func (n *BlockExecutedNotifier) AddConsumer(callback func()) { + n.mu.Lock() + defer n.mu.Unlock() + n.callbacks = append(n.callbacks, callback) +} + +// OnExecuted notifies all registered callbacks that a block has been executed. +// This method is thread-safe and should be called from the ingestion machine. +func (n *BlockExecutedNotifier) OnExecuted() { + n.mu.RLock() + defer n.mu.RUnlock() + for _, callback := range n.callbacks { + callback() + } +} diff --git a/engine/execution/ingestion/machine.go b/engine/execution/ingestion/machine.go index 194c12b8fea..bc7cfe38f11 100644 --- a/engine/execution/ingestion/machine.go +++ b/engine/execution/ingestion/machine.go @@ -23,26 +23,30 @@ import ( // Machine forwards blocks and collections to the core for processing. type Machine struct { - events.Noop // satisfy protocol events consumer interface - log zerolog.Logger - core *Core - throttle Throttle - broadcaster provider.ProviderEngine - uploader *uploader.Manager - execState state.ExecutionState - computationManager computation.ComputationManager + events.Noop // satisfy protocol events consumer interface + log zerolog.Logger + core *Core + throttle Throttle + broadcaster provider.ProviderEngine + uploader *uploader.Manager + execState state.ExecutionState + computationManager computation.ComputationManager + blockExecutedCallback BlockExecutedCallback // optional: callback invoked when blocks are executed } type CollectionRequester interface { module.ReadyDoneAware + module.Startable WithHandle(requester.HandleFunc) } +// BlockExecutedCallback is an optional callback function that is invoked when a block has been executed. +type BlockExecutedCallback func() + func NewMachine( logger zerolog.Logger, protocolEvents *events.Distributor, collectionRequester CollectionRequester, - collectionFetcher CollectionFetcher, headers storage.Headers, blocks storage.Blocks, @@ -54,14 +58,16 @@ func NewMachine( broadcaster provider.ProviderEngine, uploader *uploader.Manager, stopControl *stop.StopControl, + blockExecutedCallback BlockExecutedCallback, // optional: callback invoked when blocks are executed ) (*Machine, *Core, error) { e := &Machine{ - log: logger.With().Str("engine", "ingestion_machine").Logger(), - broadcaster: broadcaster, - uploader: uploader, - execState: execState, - computationManager: computationManager, + log: logger.With().Str("engine", "ingestion_machine").Logger(), + broadcaster: broadcaster, + uploader: uploader, + execState: execState, + computationManager: computationManager, + blockExecutedCallback: blockExecutedCallback, } throttle, err := NewBlockThrottle( @@ -102,6 +108,8 @@ func NewMachine( e.log.Error().Msgf("invalid entity type (%T)", entity) return } + // TODO: this should be a non-blocking handler function. Currently this is the only non-blocking + // handler, which requires the requester engine to spawn a goroutine for each entity response. e.core.OnCollection(collection) }) @@ -145,6 +153,12 @@ func (e *Machine) OnComputationResultSaved( if err != nil { e.log.Err(err).Msg("critical: failed to broadcast the receipt") } + + // invoke block executed callback if configured + if e.blockExecutedCallback != nil { + e.blockExecutedCallback() + } + return fmt.Sprintf("broadcasted: %v", broadcasted) } diff --git a/engine/execution/ingestion/uploader/mock/retryable_uploader_wrapper.go b/engine/execution/ingestion/uploader/mock/retryable_uploader_wrapper.go index 441f9c46eba..cc2527ba147 100644 --- a/engine/execution/ingestion/uploader/mock/retryable_uploader_wrapper.go +++ b/engine/execution/ingestion/uploader/mock/retryable_uploader_wrapper.go @@ -1,63 +1,132 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - execution "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/engine/execution" mock "github.com/stretchr/testify/mock" ) +// NewRetryableUploaderWrapper creates a new instance of RetryableUploaderWrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRetryableUploaderWrapper(t interface { + mock.TestingT + Cleanup(func()) +}) *RetryableUploaderWrapper { + mock := &RetryableUploaderWrapper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RetryableUploaderWrapper is an autogenerated mock type for the RetryableUploaderWrapper type type RetryableUploaderWrapper struct { mock.Mock } -// RetryUpload provides a mock function with no fields -func (_m *RetryableUploaderWrapper) RetryUpload() error { - ret := _m.Called() +type RetryableUploaderWrapper_Expecter struct { + mock *mock.Mock +} + +func (_m *RetryableUploaderWrapper) EXPECT() *RetryableUploaderWrapper_Expecter { + return &RetryableUploaderWrapper_Expecter{mock: &_m.Mock} +} + +// RetryUpload provides a mock function for the type RetryableUploaderWrapper +func (_mock *RetryableUploaderWrapper) RetryUpload() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RetryUpload") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Upload provides a mock function with given fields: computationResult -func (_m *RetryableUploaderWrapper) Upload(computationResult *execution.ComputationResult) error { - ret := _m.Called(computationResult) +// RetryableUploaderWrapper_RetryUpload_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RetryUpload' +type RetryableUploaderWrapper_RetryUpload_Call struct { + *mock.Call +} + +// RetryUpload is a helper method to define mock.On call +func (_e *RetryableUploaderWrapper_Expecter) RetryUpload() *RetryableUploaderWrapper_RetryUpload_Call { + return &RetryableUploaderWrapper_RetryUpload_Call{Call: _e.mock.On("RetryUpload")} +} + +func (_c *RetryableUploaderWrapper_RetryUpload_Call) Run(run func()) *RetryableUploaderWrapper_RetryUpload_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RetryableUploaderWrapper_RetryUpload_Call) Return(err error) *RetryableUploaderWrapper_RetryUpload_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RetryableUploaderWrapper_RetryUpload_Call) RunAndReturn(run func() error) *RetryableUploaderWrapper_RetryUpload_Call { + _c.Call.Return(run) + return _c +} + +// Upload provides a mock function for the type RetryableUploaderWrapper +func (_mock *RetryableUploaderWrapper) Upload(computationResult *execution.ComputationResult) error { + ret := _mock.Called(computationResult) if len(ret) == 0 { panic("no return value specified for Upload") } var r0 error - if rf, ok := ret.Get(0).(func(*execution.ComputationResult) error); ok { - r0 = rf(computationResult) + if returnFunc, ok := ret.Get(0).(func(*execution.ComputationResult) error); ok { + r0 = returnFunc(computationResult) } else { r0 = ret.Error(0) } - return r0 } -// NewRetryableUploaderWrapper creates a new instance of RetryableUploaderWrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRetryableUploaderWrapper(t interface { - mock.TestingT - Cleanup(func()) -}) *RetryableUploaderWrapper { - mock := &RetryableUploaderWrapper{} - mock.Mock.Test(t) +// RetryableUploaderWrapper_Upload_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Upload' +type RetryableUploaderWrapper_Upload_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Upload is a helper method to define mock.On call +// - computationResult *execution.ComputationResult +func (_e *RetryableUploaderWrapper_Expecter) Upload(computationResult interface{}) *RetryableUploaderWrapper_Upload_Call { + return &RetryableUploaderWrapper_Upload_Call{Call: _e.mock.On("Upload", computationResult)} +} - return mock +func (_c *RetryableUploaderWrapper_Upload_Call) Run(run func(computationResult *execution.ComputationResult)) *RetryableUploaderWrapper_Upload_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *execution.ComputationResult + if args[0] != nil { + arg0 = args[0].(*execution.ComputationResult) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RetryableUploaderWrapper_Upload_Call) Return(err error) *RetryableUploaderWrapper_Upload_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RetryableUploaderWrapper_Upload_Call) RunAndReturn(run func(computationResult *execution.ComputationResult) error) *RetryableUploaderWrapper_Upload_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/ingestion/uploader/mock/uploader.go b/engine/execution/ingestion/uploader/mock/uploader.go index 6ac5d1da993..f9d62850005 100644 --- a/engine/execution/ingestion/uploader/mock/uploader.go +++ b/engine/execution/ingestion/uploader/mock/uploader.go @@ -1,45 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - execution "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/engine/execution" mock "github.com/stretchr/testify/mock" ) +// NewUploader creates a new instance of Uploader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewUploader(t interface { + mock.TestingT + Cleanup(func()) +}) *Uploader { + mock := &Uploader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Uploader is an autogenerated mock type for the Uploader type type Uploader struct { mock.Mock } -// Upload provides a mock function with given fields: computationResult -func (_m *Uploader) Upload(computationResult *execution.ComputationResult) error { - ret := _m.Called(computationResult) +type Uploader_Expecter struct { + mock *mock.Mock +} + +func (_m *Uploader) EXPECT() *Uploader_Expecter { + return &Uploader_Expecter{mock: &_m.Mock} +} + +// Upload provides a mock function for the type Uploader +func (_mock *Uploader) Upload(computationResult *execution.ComputationResult) error { + ret := _mock.Called(computationResult) if len(ret) == 0 { panic("no return value specified for Upload") } var r0 error - if rf, ok := ret.Get(0).(func(*execution.ComputationResult) error); ok { - r0 = rf(computationResult) + if returnFunc, ok := ret.Get(0).(func(*execution.ComputationResult) error); ok { + r0 = returnFunc(computationResult) } else { r0 = ret.Error(0) } - return r0 } -// NewUploader creates a new instance of Uploader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewUploader(t interface { - mock.TestingT - Cleanup(func()) -}) *Uploader { - mock := &Uploader{} - mock.Mock.Test(t) +// Uploader_Upload_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Upload' +type Uploader_Upload_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Upload is a helper method to define mock.On call +// - computationResult *execution.ComputationResult +func (_e *Uploader_Expecter) Upload(computationResult interface{}) *Uploader_Upload_Call { + return &Uploader_Upload_Call{Call: _e.mock.On("Upload", computationResult)} +} - return mock +func (_c *Uploader_Upload_Call) Run(run func(computationResult *execution.ComputationResult)) *Uploader_Upload_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *execution.ComputationResult + if args[0] != nil { + arg0 = args[0].(*execution.ComputationResult) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Uploader_Upload_Call) Return(err error) *Uploader_Upload_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Uploader_Upload_Call) RunAndReturn(run func(computationResult *execution.ComputationResult) error) *Uploader_Upload_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/executed_finalized_wal.go b/engine/execution/mock/executed_finalized_wal.go index e1805e7b7f1..d8dfe6a884d 100644 --- a/engine/execution/mock/executed_finalized_wal.go +++ b/engine/execution/mock/executed_finalized_wal.go @@ -1,60 +1,155 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - execution "github.com/onflow/flow-go/engine/execution" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewExecutedFinalizedWAL creates a new instance of ExecutedFinalizedWAL. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutedFinalizedWAL(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutedFinalizedWAL { + mock := &ExecutedFinalizedWAL{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutedFinalizedWAL is an autogenerated mock type for the ExecutedFinalizedWAL type type ExecutedFinalizedWAL struct { mock.Mock } -// Append provides a mock function with given fields: height, registers -func (_m *ExecutedFinalizedWAL) Append(height uint64, registers flow.RegisterEntries) error { - ret := _m.Called(height, registers) +type ExecutedFinalizedWAL_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutedFinalizedWAL) EXPECT() *ExecutedFinalizedWAL_Expecter { + return &ExecutedFinalizedWAL_Expecter{mock: &_m.Mock} +} + +// Append provides a mock function for the type ExecutedFinalizedWAL +func (_mock *ExecutedFinalizedWAL) Append(height uint64, registers flow.RegisterEntries) error { + ret := _mock.Called(height, registers) if len(ret) == 0 { panic("no return value specified for Append") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, flow.RegisterEntries) error); ok { - r0 = rf(height, registers) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.RegisterEntries) error); ok { + r0 = returnFunc(height, registers) } else { r0 = ret.Error(0) } - return r0 } -// GetReader provides a mock function with given fields: height -func (_m *ExecutedFinalizedWAL) GetReader(height uint64) execution.WALReader { - ret := _m.Called(height) +// ExecutedFinalizedWAL_Append_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Append' +type ExecutedFinalizedWAL_Append_Call struct { + *mock.Call +} + +// Append is a helper method to define mock.On call +// - height uint64 +// - registers flow.RegisterEntries +func (_e *ExecutedFinalizedWAL_Expecter) Append(height interface{}, registers interface{}) *ExecutedFinalizedWAL_Append_Call { + return &ExecutedFinalizedWAL_Append_Call{Call: _e.mock.On("Append", height, registers)} +} + +func (_c *ExecutedFinalizedWAL_Append_Call) Run(run func(height uint64, registers flow.RegisterEntries)) *ExecutedFinalizedWAL_Append_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.RegisterEntries + if args[1] != nil { + arg1 = args[1].(flow.RegisterEntries) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutedFinalizedWAL_Append_Call) Return(err error) *ExecutedFinalizedWAL_Append_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutedFinalizedWAL_Append_Call) RunAndReturn(run func(height uint64, registers flow.RegisterEntries) error) *ExecutedFinalizedWAL_Append_Call { + _c.Call.Return(run) + return _c +} + +// GetReader provides a mock function for the type ExecutedFinalizedWAL +func (_mock *ExecutedFinalizedWAL) GetReader(height uint64) execution.WALReader { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for GetReader") } var r0 execution.WALReader - if rf, ok := ret.Get(0).(func(uint64) execution.WALReader); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) execution.WALReader); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(execution.WALReader) } } - return r0 } -// Latest provides a mock function with no fields -func (_m *ExecutedFinalizedWAL) Latest() (uint64, error) { - ret := _m.Called() +// ExecutedFinalizedWAL_GetReader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetReader' +type ExecutedFinalizedWAL_GetReader_Call struct { + *mock.Call +} + +// GetReader is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutedFinalizedWAL_Expecter) GetReader(height interface{}) *ExecutedFinalizedWAL_GetReader_Call { + return &ExecutedFinalizedWAL_GetReader_Call{Call: _e.mock.On("GetReader", height)} +} + +func (_c *ExecutedFinalizedWAL_GetReader_Call) Run(run func(height uint64)) *ExecutedFinalizedWAL_GetReader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutedFinalizedWAL_GetReader_Call) Return(wALReader execution.WALReader) *ExecutedFinalizedWAL_GetReader_Call { + _c.Call.Return(wALReader) + return _c +} + +func (_c *ExecutedFinalizedWAL_GetReader_Call) RunAndReturn(run func(height uint64) execution.WALReader) *ExecutedFinalizedWAL_GetReader_Call { + _c.Call.Return(run) + return _c +} + +// Latest provides a mock function for the type ExecutedFinalizedWAL +func (_mock *ExecutedFinalizedWAL) Latest() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Latest") @@ -62,34 +157,45 @@ func (_m *ExecutedFinalizedWAL) Latest() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutedFinalizedWAL creates a new instance of ExecutedFinalizedWAL. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutedFinalizedWAL(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutedFinalizedWAL { - mock := &ExecutedFinalizedWAL{} - mock.Mock.Test(t) +// ExecutedFinalizedWAL_Latest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Latest' +type ExecutedFinalizedWAL_Latest_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Latest is a helper method to define mock.On call +func (_e *ExecutedFinalizedWAL_Expecter) Latest() *ExecutedFinalizedWAL_Latest_Call { + return &ExecutedFinalizedWAL_Latest_Call{Call: _e.mock.On("Latest")} +} - return mock +func (_c *ExecutedFinalizedWAL_Latest_Call) Run(run func()) *ExecutedFinalizedWAL_Latest_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutedFinalizedWAL_Latest_Call) Return(v uint64, err error) *ExecutedFinalizedWAL_Latest_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ExecutedFinalizedWAL_Latest_Call) RunAndReturn(run func() (uint64, error)) *ExecutedFinalizedWAL_Latest_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/extendable_storage_snapshot.go b/engine/execution/mock/extendable_storage_snapshot.go index 0a3a558bb4f..0621c0f268d 100644 --- a/engine/execution/mock/extendable_storage_snapshot.go +++ b/engine/execution/mock/extendable_storage_snapshot.go @@ -1,62 +1,150 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - execution "github.com/onflow/flow-go/engine/execution" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewExtendableStorageSnapshot creates a new instance of ExtendableStorageSnapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExtendableStorageSnapshot(t interface { + mock.TestingT + Cleanup(func()) +}) *ExtendableStorageSnapshot { + mock := &ExtendableStorageSnapshot{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExtendableStorageSnapshot is an autogenerated mock type for the ExtendableStorageSnapshot type type ExtendableStorageSnapshot struct { mock.Mock } -// Commitment provides a mock function with no fields -func (_m *ExtendableStorageSnapshot) Commitment() flow.StateCommitment { - ret := _m.Called() +type ExtendableStorageSnapshot_Expecter struct { + mock *mock.Mock +} + +func (_m *ExtendableStorageSnapshot) EXPECT() *ExtendableStorageSnapshot_Expecter { + return &ExtendableStorageSnapshot_Expecter{mock: &_m.Mock} +} + +// Commitment provides a mock function for the type ExtendableStorageSnapshot +func (_mock *ExtendableStorageSnapshot) Commitment() flow.StateCommitment { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Commitment") } var r0 flow.StateCommitment - if rf, ok := ret.Get(0).(func() flow.StateCommitment); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.StateCommitment); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - return r0 } -// Extend provides a mock function with given fields: newCommit, updatedRegisters -func (_m *ExtendableStorageSnapshot) Extend(newCommit flow.StateCommitment, updatedRegisters map[flow.RegisterID]flow.RegisterValue) execution.ExtendableStorageSnapshot { - ret := _m.Called(newCommit, updatedRegisters) +// ExtendableStorageSnapshot_Commitment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Commitment' +type ExtendableStorageSnapshot_Commitment_Call struct { + *mock.Call +} + +// Commitment is a helper method to define mock.On call +func (_e *ExtendableStorageSnapshot_Expecter) Commitment() *ExtendableStorageSnapshot_Commitment_Call { + return &ExtendableStorageSnapshot_Commitment_Call{Call: _e.mock.On("Commitment")} +} + +func (_c *ExtendableStorageSnapshot_Commitment_Call) Run(run func()) *ExtendableStorageSnapshot_Commitment_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExtendableStorageSnapshot_Commitment_Call) Return(stateCommitment flow.StateCommitment) *ExtendableStorageSnapshot_Commitment_Call { + _c.Call.Return(stateCommitment) + return _c +} + +func (_c *ExtendableStorageSnapshot_Commitment_Call) RunAndReturn(run func() flow.StateCommitment) *ExtendableStorageSnapshot_Commitment_Call { + _c.Call.Return(run) + return _c +} + +// Extend provides a mock function for the type ExtendableStorageSnapshot +func (_mock *ExtendableStorageSnapshot) Extend(newCommit flow.StateCommitment, updatedRegisters map[flow.RegisterID]flow.RegisterValue) execution.ExtendableStorageSnapshot { + ret := _mock.Called(newCommit, updatedRegisters) if len(ret) == 0 { panic("no return value specified for Extend") } var r0 execution.ExtendableStorageSnapshot - if rf, ok := ret.Get(0).(func(flow.StateCommitment, map[flow.RegisterID]flow.RegisterValue) execution.ExtendableStorageSnapshot); ok { - r0 = rf(newCommit, updatedRegisters) + if returnFunc, ok := ret.Get(0).(func(flow.StateCommitment, map[flow.RegisterID]flow.RegisterValue) execution.ExtendableStorageSnapshot); ok { + r0 = returnFunc(newCommit, updatedRegisters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(execution.ExtendableStorageSnapshot) } } - return r0 } -// Get provides a mock function with given fields: id -func (_m *ExtendableStorageSnapshot) Get(id flow.RegisterID) (flow.RegisterValue, error) { - ret := _m.Called(id) +// ExtendableStorageSnapshot_Extend_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Extend' +type ExtendableStorageSnapshot_Extend_Call struct { + *mock.Call +} + +// Extend is a helper method to define mock.On call +// - newCommit flow.StateCommitment +// - updatedRegisters map[flow.RegisterID]flow.RegisterValue +func (_e *ExtendableStorageSnapshot_Expecter) Extend(newCommit interface{}, updatedRegisters interface{}) *ExtendableStorageSnapshot_Extend_Call { + return &ExtendableStorageSnapshot_Extend_Call{Call: _e.mock.On("Extend", newCommit, updatedRegisters)} +} + +func (_c *ExtendableStorageSnapshot_Extend_Call) Run(run func(newCommit flow.StateCommitment, updatedRegisters map[flow.RegisterID]flow.RegisterValue)) *ExtendableStorageSnapshot_Extend_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.StateCommitment + if args[0] != nil { + arg0 = args[0].(flow.StateCommitment) + } + var arg1 map[flow.RegisterID]flow.RegisterValue + if args[1] != nil { + arg1 = args[1].(map[flow.RegisterID]flow.RegisterValue) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExtendableStorageSnapshot_Extend_Call) Return(extendableStorageSnapshot execution.ExtendableStorageSnapshot) *ExtendableStorageSnapshot_Extend_Call { + _c.Call.Return(extendableStorageSnapshot) + return _c +} + +func (_c *ExtendableStorageSnapshot_Extend_Call) RunAndReturn(run func(newCommit flow.StateCommitment, updatedRegisters map[flow.RegisterID]flow.RegisterValue) execution.ExtendableStorageSnapshot) *ExtendableStorageSnapshot_Extend_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type ExtendableStorageSnapshot +func (_mock *ExtendableStorageSnapshot) Get(id flow.RegisterID) (flow.RegisterValue, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for Get") @@ -64,36 +152,54 @@ func (_m *ExtendableStorageSnapshot) Get(id flow.RegisterID) (flow.RegisterValue var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterID) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExtendableStorageSnapshot creates a new instance of ExtendableStorageSnapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExtendableStorageSnapshot(t interface { - mock.TestingT - Cleanup(func()) -}) *ExtendableStorageSnapshot { - mock := &ExtendableStorageSnapshot{} - mock.Mock.Test(t) +// ExtendableStorageSnapshot_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type ExtendableStorageSnapshot_Get_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Get is a helper method to define mock.On call +// - id flow.RegisterID +func (_e *ExtendableStorageSnapshot_Expecter) Get(id interface{}) *ExtendableStorageSnapshot_Get_Call { + return &ExtendableStorageSnapshot_Get_Call{Call: _e.mock.On("Get", id)} +} - return mock +func (_c *ExtendableStorageSnapshot_Get_Call) Run(run func(id flow.RegisterID)) *ExtendableStorageSnapshot_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExtendableStorageSnapshot_Get_Call) Return(v flow.RegisterValue, err error) *ExtendableStorageSnapshot_Get_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ExtendableStorageSnapshot_Get_Call) RunAndReturn(run func(id flow.RegisterID) (flow.RegisterValue, error)) *ExtendableStorageSnapshot_Get_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/finalized_reader.go b/engine/execution/mock/finalized_reader.go index d1117d4dfc1..63cdfa4cc8d 100644 --- a/engine/execution/mock/finalized_reader.go +++ b/engine/execution/mock/finalized_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewFinalizedReader creates a new instance of FinalizedReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFinalizedReader(t interface { + mock.TestingT + Cleanup(func()) +}) *FinalizedReader { + mock := &FinalizedReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // FinalizedReader is an autogenerated mock type for the FinalizedReader type type FinalizedReader struct { mock.Mock } -// FinalizedBlockIDAtHeight provides a mock function with given fields: height -func (_m *FinalizedReader) FinalizedBlockIDAtHeight(height uint64) (flow.Identifier, error) { - ret := _m.Called(height) +type FinalizedReader_Expecter struct { + mock *mock.Mock +} + +func (_m *FinalizedReader) EXPECT() *FinalizedReader_Expecter { + return &FinalizedReader_Expecter{mock: &_m.Mock} +} + +// FinalizedBlockIDAtHeight provides a mock function for the type FinalizedReader +func (_mock *FinalizedReader) FinalizedBlockIDAtHeight(height uint64) (flow.Identifier, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for FinalizedBlockIDAtHeight") @@ -22,36 +46,54 @@ func (_m *FinalizedReader) FinalizedBlockIDAtHeight(height uint64) (flow.Identif var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewFinalizedReader creates a new instance of FinalizedReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewFinalizedReader(t interface { - mock.TestingT - Cleanup(func()) -}) *FinalizedReader { - mock := &FinalizedReader{} - mock.Mock.Test(t) +// FinalizedReader_FinalizedBlockIDAtHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedBlockIDAtHeight' +type FinalizedReader_FinalizedBlockIDAtHeight_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// FinalizedBlockIDAtHeight is a helper method to define mock.On call +// - height uint64 +func (_e *FinalizedReader_Expecter) FinalizedBlockIDAtHeight(height interface{}) *FinalizedReader_FinalizedBlockIDAtHeight_Call { + return &FinalizedReader_FinalizedBlockIDAtHeight_Call{Call: _e.mock.On("FinalizedBlockIDAtHeight", height)} +} - return mock +func (_c *FinalizedReader_FinalizedBlockIDAtHeight_Call) Run(run func(height uint64)) *FinalizedReader_FinalizedBlockIDAtHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FinalizedReader_FinalizedBlockIDAtHeight_Call) Return(identifier flow.Identifier, err error) *FinalizedReader_FinalizedBlockIDAtHeight_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *FinalizedReader_FinalizedBlockIDAtHeight_Call) RunAndReturn(run func(height uint64) (flow.Identifier, error)) *FinalizedReader_FinalizedBlockIDAtHeight_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/in_memory_register_store.go b/engine/execution/mock/in_memory_register_store.go index 40975612100..8bc1b839201 100644 --- a/engine/execution/mock/in_memory_register_store.go +++ b/engine/execution/mock/in_memory_register_store.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewInMemoryRegisterStore creates a new instance of InMemoryRegisterStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewInMemoryRegisterStore(t interface { + mock.TestingT + Cleanup(func()) +}) *InMemoryRegisterStore { + mock := &InMemoryRegisterStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // InMemoryRegisterStore is an autogenerated mock type for the InMemoryRegisterStore type type InMemoryRegisterStore struct { mock.Mock } -// GetRegister provides a mock function with given fields: height, blockID, register -func (_m *InMemoryRegisterStore) GetRegister(height uint64, blockID flow.Identifier, register flow.RegisterID) (flow.RegisterValue, error) { - ret := _m.Called(height, blockID, register) +type InMemoryRegisterStore_Expecter struct { + mock *mock.Mock +} + +func (_m *InMemoryRegisterStore) EXPECT() *InMemoryRegisterStore_Expecter { + return &InMemoryRegisterStore_Expecter{mock: &_m.Mock} +} + +// GetRegister provides a mock function for the type InMemoryRegisterStore +func (_mock *InMemoryRegisterStore) GetRegister(height uint64, blockID flow.Identifier, register flow.RegisterID) (flow.RegisterValue, error) { + ret := _mock.Called(height, blockID, register) if len(ret) == 0 { panic("no return value specified for GetRegister") @@ -22,29 +46,73 @@ func (_m *InMemoryRegisterStore) GetRegister(height uint64, blockID flow.Identif var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) (flow.RegisterValue, error)); ok { - return rf(height, blockID, register) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) (flow.RegisterValue, error)); ok { + return returnFunc(height, blockID, register) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) flow.RegisterValue); ok { - r0 = rf(height, blockID, register) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) flow.RegisterValue); ok { + r0 = returnFunc(height, blockID, register) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier, flow.RegisterID) error); ok { - r1 = rf(height, blockID, register) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier, flow.RegisterID) error); ok { + r1 = returnFunc(height, blockID, register) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetUpdatedRegisters provides a mock function with given fields: height, blockID -func (_m *InMemoryRegisterStore) GetUpdatedRegisters(height uint64, blockID flow.Identifier) (flow.RegisterEntries, error) { - ret := _m.Called(height, blockID) +// InMemoryRegisterStore_GetRegister_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegister' +type InMemoryRegisterStore_GetRegister_Call struct { + *mock.Call +} + +// GetRegister is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +// - register flow.RegisterID +func (_e *InMemoryRegisterStore_Expecter) GetRegister(height interface{}, blockID interface{}, register interface{}) *InMemoryRegisterStore_GetRegister_Call { + return &InMemoryRegisterStore_GetRegister_Call{Call: _e.mock.On("GetRegister", height, blockID, register)} +} + +func (_c *InMemoryRegisterStore_GetRegister_Call) Run(run func(height uint64, blockID flow.Identifier, register flow.RegisterID)) *InMemoryRegisterStore_GetRegister_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.RegisterID + if args[2] != nil { + arg2 = args[2].(flow.RegisterID) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *InMemoryRegisterStore_GetRegister_Call) Return(v flow.RegisterValue, err error) *InMemoryRegisterStore_GetRegister_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *InMemoryRegisterStore_GetRegister_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier, register flow.RegisterID) (flow.RegisterValue, error)) *InMemoryRegisterStore_GetRegister_Call { + _c.Call.Return(run) + return _c +} + +// GetUpdatedRegisters provides a mock function for the type InMemoryRegisterStore +func (_mock *InMemoryRegisterStore) GetUpdatedRegisters(height uint64, blockID flow.Identifier) (flow.RegisterEntries, error) { + ret := _mock.Called(height, blockID) if len(ret) == 0 { panic("no return value specified for GetUpdatedRegisters") @@ -52,29 +120,67 @@ func (_m *InMemoryRegisterStore) GetUpdatedRegisters(height uint64, blockID flow var r0 flow.RegisterEntries var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (flow.RegisterEntries, error)); ok { - return rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (flow.RegisterEntries, error)); ok { + return returnFunc(height, blockID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) flow.RegisterEntries); ok { - r0 = rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) flow.RegisterEntries); ok { + r0 = returnFunc(height, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterEntries) } } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(height, blockID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(height, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// IsBlockExecuted provides a mock function with given fields: height, blockID -func (_m *InMemoryRegisterStore) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { - ret := _m.Called(height, blockID) +// InMemoryRegisterStore_GetUpdatedRegisters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetUpdatedRegisters' +type InMemoryRegisterStore_GetUpdatedRegisters_Call struct { + *mock.Call +} + +// GetUpdatedRegisters is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +func (_e *InMemoryRegisterStore_Expecter) GetUpdatedRegisters(height interface{}, blockID interface{}) *InMemoryRegisterStore_GetUpdatedRegisters_Call { + return &InMemoryRegisterStore_GetUpdatedRegisters_Call{Call: _e.mock.On("GetUpdatedRegisters", height, blockID)} +} + +func (_c *InMemoryRegisterStore_GetUpdatedRegisters_Call) Run(run func(height uint64, blockID flow.Identifier)) *InMemoryRegisterStore_GetUpdatedRegisters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *InMemoryRegisterStore_GetUpdatedRegisters_Call) Return(registerEntries flow.RegisterEntries, err error) *InMemoryRegisterStore_GetUpdatedRegisters_Call { + _c.Call.Return(registerEntries, err) + return _c +} + +func (_c *InMemoryRegisterStore_GetUpdatedRegisters_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier) (flow.RegisterEntries, error)) *InMemoryRegisterStore_GetUpdatedRegisters_Call { + _c.Call.Return(run) + return _c +} + +// IsBlockExecuted provides a mock function for the type InMemoryRegisterStore +func (_mock *InMemoryRegisterStore) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { + ret := _mock.Called(height, blockID) if len(ret) == 0 { panic("no return value specified for IsBlockExecuted") @@ -82,88 +188,228 @@ func (_m *InMemoryRegisterStore) IsBlockExecuted(height uint64, blockID flow.Ide var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { - return rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { + return returnFunc(height, blockID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { - r0 = rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { + r0 = returnFunc(height, blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(height, blockID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(height, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Prune provides a mock function with given fields: finalizedHeight, finalizedBlockID -func (_m *InMemoryRegisterStore) Prune(finalizedHeight uint64, finalizedBlockID flow.Identifier) error { - ret := _m.Called(finalizedHeight, finalizedBlockID) +// InMemoryRegisterStore_IsBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsBlockExecuted' +type InMemoryRegisterStore_IsBlockExecuted_Call struct { + *mock.Call +} + +// IsBlockExecuted is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +func (_e *InMemoryRegisterStore_Expecter) IsBlockExecuted(height interface{}, blockID interface{}) *InMemoryRegisterStore_IsBlockExecuted_Call { + return &InMemoryRegisterStore_IsBlockExecuted_Call{Call: _e.mock.On("IsBlockExecuted", height, blockID)} +} + +func (_c *InMemoryRegisterStore_IsBlockExecuted_Call) Run(run func(height uint64, blockID flow.Identifier)) *InMemoryRegisterStore_IsBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *InMemoryRegisterStore_IsBlockExecuted_Call) Return(b bool, err error) *InMemoryRegisterStore_IsBlockExecuted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *InMemoryRegisterStore_IsBlockExecuted_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier) (bool, error)) *InMemoryRegisterStore_IsBlockExecuted_Call { + _c.Call.Return(run) + return _c +} + +// Prune provides a mock function for the type InMemoryRegisterStore +func (_mock *InMemoryRegisterStore) Prune(finalizedHeight uint64, finalizedBlockID flow.Identifier) error { + ret := _mock.Called(finalizedHeight, finalizedBlockID) if len(ret) == 0 { panic("no return value specified for Prune") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) error); ok { - r0 = rf(finalizedHeight, finalizedBlockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) error); ok { + r0 = returnFunc(finalizedHeight, finalizedBlockID) } else { r0 = ret.Error(0) } - return r0 } -// PrunedHeight provides a mock function with no fields -func (_m *InMemoryRegisterStore) PrunedHeight() uint64 { - ret := _m.Called() +// InMemoryRegisterStore_Prune_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Prune' +type InMemoryRegisterStore_Prune_Call struct { + *mock.Call +} + +// Prune is a helper method to define mock.On call +// - finalizedHeight uint64 +// - finalizedBlockID flow.Identifier +func (_e *InMemoryRegisterStore_Expecter) Prune(finalizedHeight interface{}, finalizedBlockID interface{}) *InMemoryRegisterStore_Prune_Call { + return &InMemoryRegisterStore_Prune_Call{Call: _e.mock.On("Prune", finalizedHeight, finalizedBlockID)} +} + +func (_c *InMemoryRegisterStore_Prune_Call) Run(run func(finalizedHeight uint64, finalizedBlockID flow.Identifier)) *InMemoryRegisterStore_Prune_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *InMemoryRegisterStore_Prune_Call) Return(err error) *InMemoryRegisterStore_Prune_Call { + _c.Call.Return(err) + return _c +} + +func (_c *InMemoryRegisterStore_Prune_Call) RunAndReturn(run func(finalizedHeight uint64, finalizedBlockID flow.Identifier) error) *InMemoryRegisterStore_Prune_Call { + _c.Call.Return(run) + return _c +} + +// PrunedHeight provides a mock function for the type InMemoryRegisterStore +func (_mock *InMemoryRegisterStore) PrunedHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PrunedHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// SaveRegisters provides a mock function with given fields: height, blockID, parentID, registers -func (_m *InMemoryRegisterStore) SaveRegisters(height uint64, blockID flow.Identifier, parentID flow.Identifier, registers flow.RegisterEntries) error { - ret := _m.Called(height, blockID, parentID, registers) +// InMemoryRegisterStore_PrunedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PrunedHeight' +type InMemoryRegisterStore_PrunedHeight_Call struct { + *mock.Call +} + +// PrunedHeight is a helper method to define mock.On call +func (_e *InMemoryRegisterStore_Expecter) PrunedHeight() *InMemoryRegisterStore_PrunedHeight_Call { + return &InMemoryRegisterStore_PrunedHeight_Call{Call: _e.mock.On("PrunedHeight")} +} + +func (_c *InMemoryRegisterStore_PrunedHeight_Call) Run(run func()) *InMemoryRegisterStore_PrunedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *InMemoryRegisterStore_PrunedHeight_Call) Return(v uint64) *InMemoryRegisterStore_PrunedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *InMemoryRegisterStore_PrunedHeight_Call) RunAndReturn(run func() uint64) *InMemoryRegisterStore_PrunedHeight_Call { + _c.Call.Return(run) + return _c +} + +// SaveRegisters provides a mock function for the type InMemoryRegisterStore +func (_mock *InMemoryRegisterStore) SaveRegisters(height uint64, blockID flow.Identifier, parentID flow.Identifier, registers flow.RegisterEntries) error { + ret := _mock.Called(height, blockID, parentID, registers) if len(ret) == 0 { panic("no return value specified for SaveRegisters") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.Identifier, flow.RegisterEntries) error); ok { - r0 = rf(height, blockID, parentID, registers) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.Identifier, flow.RegisterEntries) error); ok { + r0 = returnFunc(height, blockID, parentID, registers) } else { r0 = ret.Error(0) } - return r0 } -// NewInMemoryRegisterStore creates a new instance of InMemoryRegisterStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewInMemoryRegisterStore(t interface { - mock.TestingT - Cleanup(func()) -}) *InMemoryRegisterStore { - mock := &InMemoryRegisterStore{} - mock.Mock.Test(t) +// InMemoryRegisterStore_SaveRegisters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SaveRegisters' +type InMemoryRegisterStore_SaveRegisters_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SaveRegisters is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +// - parentID flow.Identifier +// - registers flow.RegisterEntries +func (_e *InMemoryRegisterStore_Expecter) SaveRegisters(height interface{}, blockID interface{}, parentID interface{}, registers interface{}) *InMemoryRegisterStore_SaveRegisters_Call { + return &InMemoryRegisterStore_SaveRegisters_Call{Call: _e.mock.On("SaveRegisters", height, blockID, parentID, registers)} +} - return mock +func (_c *InMemoryRegisterStore_SaveRegisters_Call) Run(run func(height uint64, blockID flow.Identifier, parentID flow.Identifier, registers flow.RegisterEntries)) *InMemoryRegisterStore_SaveRegisters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.RegisterEntries + if args[3] != nil { + arg3 = args[3].(flow.RegisterEntries) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *InMemoryRegisterStore_SaveRegisters_Call) Return(err error) *InMemoryRegisterStore_SaveRegisters_Call { + _c.Call.Return(err) + return _c +} + +func (_c *InMemoryRegisterStore_SaveRegisters_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier, parentID flow.Identifier, registers flow.RegisterEntries) error) *InMemoryRegisterStore_SaveRegisters_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/on_disk_register_store.go b/engine/execution/mock/on_disk_register_store.go index 01e7bab3b53..f510ea1c03b 100644 --- a/engine/execution/mock/on_disk_register_store.go +++ b/engine/execution/mock/on_disk_register_store.go @@ -1,38 +1,154 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewOnDiskRegisterStore creates a new instance of OnDiskRegisterStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewOnDiskRegisterStore(t interface { + mock.TestingT + Cleanup(func()) +}) *OnDiskRegisterStore { + mock := &OnDiskRegisterStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // OnDiskRegisterStore is an autogenerated mock type for the OnDiskRegisterStore type type OnDiskRegisterStore struct { mock.Mock } -// FirstHeight provides a mock function with no fields -func (_m *OnDiskRegisterStore) FirstHeight() uint64 { - ret := _m.Called() +type OnDiskRegisterStore_Expecter struct { + mock *mock.Mock +} + +func (_m *OnDiskRegisterStore) EXPECT() *OnDiskRegisterStore_Expecter { + return &OnDiskRegisterStore_Expecter{mock: &_m.Mock} +} + +// ByKeyPrefix provides a mock function for the type OnDiskRegisterStore +func (_mock *OnDiskRegisterStore) ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] { + ret := _mock.Called(keyPrefix, height, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByKeyPrefix") + } + + var r0 storage.IndexIterator[flow.RegisterValue, flow.RegisterID] + if returnFunc, ok := ret.Get(0).(func(string, uint64, *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]); ok { + r0 = returnFunc(keyPrefix, height, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) + } + } + return r0 +} + +// OnDiskRegisterStore_ByKeyPrefix_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByKeyPrefix' +type OnDiskRegisterStore_ByKeyPrefix_Call struct { + *mock.Call +} + +// ByKeyPrefix is a helper method to define mock.On call +// - keyPrefix string +// - height uint64 +// - cursor *flow.RegisterID +func (_e *OnDiskRegisterStore_Expecter) ByKeyPrefix(keyPrefix interface{}, height interface{}, cursor interface{}) *OnDiskRegisterStore_ByKeyPrefix_Call { + return &OnDiskRegisterStore_ByKeyPrefix_Call{Call: _e.mock.On("ByKeyPrefix", keyPrefix, height, cursor)} +} + +func (_c *OnDiskRegisterStore_ByKeyPrefix_Call) Run(run func(keyPrefix string, height uint64, cursor *flow.RegisterID)) *OnDiskRegisterStore_ByKeyPrefix_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.RegisterID + if args[2] != nil { + arg2 = args[2].(*flow.RegisterID) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *OnDiskRegisterStore_ByKeyPrefix_Call) Return(indexIterator storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *OnDiskRegisterStore_ByKeyPrefix_Call { + _c.Call.Return(indexIterator) + return _c +} + +func (_c *OnDiskRegisterStore_ByKeyPrefix_Call) RunAndReturn(run func(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *OnDiskRegisterStore_ByKeyPrefix_Call { + _c.Call.Return(run) + return _c +} + +// FirstHeight provides a mock function for the type OnDiskRegisterStore +func (_mock *OnDiskRegisterStore) FirstHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FirstHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Get provides a mock function with given fields: ID, height -func (_m *OnDiskRegisterStore) Get(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { - ret := _m.Called(ID, height) +// OnDiskRegisterStore_FirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstHeight' +type OnDiskRegisterStore_FirstHeight_Call struct { + *mock.Call +} + +// FirstHeight is a helper method to define mock.On call +func (_e *OnDiskRegisterStore_Expecter) FirstHeight() *OnDiskRegisterStore_FirstHeight_Call { + return &OnDiskRegisterStore_FirstHeight_Call{Call: _e.mock.On("FirstHeight")} +} + +func (_c *OnDiskRegisterStore_FirstHeight_Call) Run(run func()) *OnDiskRegisterStore_FirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OnDiskRegisterStore_FirstHeight_Call) Return(v uint64) *OnDiskRegisterStore_FirstHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *OnDiskRegisterStore_FirstHeight_Call) RunAndReturn(run func() uint64) *OnDiskRegisterStore_FirstHeight_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type OnDiskRegisterStore +func (_mock *OnDiskRegisterStore) Get(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { + ret := _mock.Called(ID, height) if len(ret) == 0 { panic("no return value specified for Get") @@ -40,72 +156,161 @@ func (_m *OnDiskRegisterStore) Get(ID flow.RegisterID, height uint64) (flow.Regi var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { - return rf(ID, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { + return returnFunc(ID, height) } - if rf, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { - r0 = rf(ID, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { + r0 = returnFunc(ID, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { - r1 = rf(ID, height) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { + r1 = returnFunc(ID, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// LatestHeight provides a mock function with no fields -func (_m *OnDiskRegisterStore) LatestHeight() uint64 { - ret := _m.Called() +// OnDiskRegisterStore_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type OnDiskRegisterStore_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - ID flow.RegisterID +// - height uint64 +func (_e *OnDiskRegisterStore_Expecter) Get(ID interface{}, height interface{}) *OnDiskRegisterStore_Get_Call { + return &OnDiskRegisterStore_Get_Call{Call: _e.mock.On("Get", ID, height)} +} + +func (_c *OnDiskRegisterStore_Get_Call) Run(run func(ID flow.RegisterID, height uint64)) *OnDiskRegisterStore_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *OnDiskRegisterStore_Get_Call) Return(v flow.RegisterValue, err error) *OnDiskRegisterStore_Get_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *OnDiskRegisterStore_Get_Call) RunAndReturn(run func(ID flow.RegisterID, height uint64) (flow.RegisterValue, error)) *OnDiskRegisterStore_Get_Call { + _c.Call.Return(run) + return _c +} + +// LatestHeight provides a mock function for the type OnDiskRegisterStore +func (_mock *OnDiskRegisterStore) LatestHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LatestHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Store provides a mock function with given fields: entries, height -func (_m *OnDiskRegisterStore) Store(entries flow.RegisterEntries, height uint64) error { - ret := _m.Called(entries, height) +// OnDiskRegisterStore_LatestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestHeight' +type OnDiskRegisterStore_LatestHeight_Call struct { + *mock.Call +} + +// LatestHeight is a helper method to define mock.On call +func (_e *OnDiskRegisterStore_Expecter) LatestHeight() *OnDiskRegisterStore_LatestHeight_Call { + return &OnDiskRegisterStore_LatestHeight_Call{Call: _e.mock.On("LatestHeight")} +} + +func (_c *OnDiskRegisterStore_LatestHeight_Call) Run(run func()) *OnDiskRegisterStore_LatestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OnDiskRegisterStore_LatestHeight_Call) Return(v uint64) *OnDiskRegisterStore_LatestHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *OnDiskRegisterStore_LatestHeight_Call) RunAndReturn(run func() uint64) *OnDiskRegisterStore_LatestHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type OnDiskRegisterStore +func (_mock *OnDiskRegisterStore) Store(entries flow.RegisterEntries, height uint64) error { + ret := _mock.Called(entries, height) if len(ret) == 0 { panic("no return value specified for Store") } var r0 error - if rf, ok := ret.Get(0).(func(flow.RegisterEntries, uint64) error); ok { - r0 = rf(entries, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterEntries, uint64) error); ok { + r0 = returnFunc(entries, height) } else { r0 = ret.Error(0) } - return r0 } -// NewOnDiskRegisterStore creates a new instance of OnDiskRegisterStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewOnDiskRegisterStore(t interface { - mock.TestingT - Cleanup(func()) -}) *OnDiskRegisterStore { - mock := &OnDiskRegisterStore{} - mock.Mock.Test(t) +// OnDiskRegisterStore_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type OnDiskRegisterStore_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - entries flow.RegisterEntries +// - height uint64 +func (_e *OnDiskRegisterStore_Expecter) Store(entries interface{}, height interface{}) *OnDiskRegisterStore_Store_Call { + return &OnDiskRegisterStore_Store_Call{Call: _e.mock.On("Store", entries, height)} +} - return mock +func (_c *OnDiskRegisterStore_Store_Call) Run(run func(entries flow.RegisterEntries, height uint64)) *OnDiskRegisterStore_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterEntries + if args[0] != nil { + arg0 = args[0].(flow.RegisterEntries) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *OnDiskRegisterStore_Store_Call) Return(err error) *OnDiskRegisterStore_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *OnDiskRegisterStore_Store_Call) RunAndReturn(run func(entries flow.RegisterEntries, height uint64) error) *OnDiskRegisterStore_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/register_store.go b/engine/execution/mock/register_store.go index 3df9af78fd2..fcec40a71c8 100644 --- a/engine/execution/mock/register_store.go +++ b/engine/execution/mock/register_store.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewRegisterStore creates a new instance of RegisterStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRegisterStore(t interface { + mock.TestingT + Cleanup(func()) +}) *RegisterStore { + mock := &RegisterStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RegisterStore is an autogenerated mock type for the RegisterStore type type RegisterStore struct { mock.Mock } -// GetRegister provides a mock function with given fields: height, blockID, register -func (_m *RegisterStore) GetRegister(height uint64, blockID flow.Identifier, register flow.RegisterID) (flow.RegisterValue, error) { - ret := _m.Called(height, blockID, register) +type RegisterStore_Expecter struct { + mock *mock.Mock +} + +func (_m *RegisterStore) EXPECT() *RegisterStore_Expecter { + return &RegisterStore_Expecter{mock: &_m.Mock} +} + +// GetRegister provides a mock function for the type RegisterStore +func (_mock *RegisterStore) GetRegister(height uint64, blockID flow.Identifier, register flow.RegisterID) (flow.RegisterValue, error) { + ret := _mock.Called(height, blockID, register) if len(ret) == 0 { panic("no return value specified for GetRegister") @@ -22,29 +46,73 @@ func (_m *RegisterStore) GetRegister(height uint64, blockID flow.Identifier, reg var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) (flow.RegisterValue, error)); ok { - return rf(height, blockID, register) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) (flow.RegisterValue, error)); ok { + return returnFunc(height, blockID, register) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) flow.RegisterValue); ok { - r0 = rf(height, blockID, register) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier, flow.RegisterID) flow.RegisterValue); ok { + r0 = returnFunc(height, blockID, register) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier, flow.RegisterID) error); ok { - r1 = rf(height, blockID, register) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier, flow.RegisterID) error); ok { + r1 = returnFunc(height, blockID, register) } else { r1 = ret.Error(1) } - return r0, r1 } -// IsBlockExecuted provides a mock function with given fields: height, blockID -func (_m *RegisterStore) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { - ret := _m.Called(height, blockID) +// RegisterStore_GetRegister_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegister' +type RegisterStore_GetRegister_Call struct { + *mock.Call +} + +// GetRegister is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +// - register flow.RegisterID +func (_e *RegisterStore_Expecter) GetRegister(height interface{}, blockID interface{}, register interface{}) *RegisterStore_GetRegister_Call { + return &RegisterStore_GetRegister_Call{Call: _e.mock.On("GetRegister", height, blockID, register)} +} + +func (_c *RegisterStore_GetRegister_Call) Run(run func(height uint64, blockID flow.Identifier, register flow.RegisterID)) *RegisterStore_GetRegister_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.RegisterID + if args[2] != nil { + arg2 = args[2].(flow.RegisterID) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *RegisterStore_GetRegister_Call) Return(v flow.RegisterValue, err error) *RegisterStore_GetRegister_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *RegisterStore_GetRegister_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier, register flow.RegisterID) (flow.RegisterValue, error)) *RegisterStore_GetRegister_Call { + _c.Call.Return(run) + return _c +} + +// IsBlockExecuted provides a mock function for the type RegisterStore +func (_mock *RegisterStore) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { + ret := _mock.Called(height, blockID) if len(ret) == 0 { panic("no return value specified for IsBlockExecuted") @@ -52,88 +120,203 @@ func (_m *RegisterStore) IsBlockExecuted(height uint64, blockID flow.Identifier) var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { - return rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { + return returnFunc(height, blockID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { - r0 = rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { + r0 = returnFunc(height, blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(height, blockID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(height, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LastFinalizedAndExecutedHeight provides a mock function with no fields -func (_m *RegisterStore) LastFinalizedAndExecutedHeight() uint64 { - ret := _m.Called() +// RegisterStore_IsBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsBlockExecuted' +type RegisterStore_IsBlockExecuted_Call struct { + *mock.Call +} + +// IsBlockExecuted is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +func (_e *RegisterStore_Expecter) IsBlockExecuted(height interface{}, blockID interface{}) *RegisterStore_IsBlockExecuted_Call { + return &RegisterStore_IsBlockExecuted_Call{Call: _e.mock.On("IsBlockExecuted", height, blockID)} +} + +func (_c *RegisterStore_IsBlockExecuted_Call) Run(run func(height uint64, blockID flow.Identifier)) *RegisterStore_IsBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RegisterStore_IsBlockExecuted_Call) Return(b bool, err error) *RegisterStore_IsBlockExecuted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *RegisterStore_IsBlockExecuted_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier) (bool, error)) *RegisterStore_IsBlockExecuted_Call { + _c.Call.Return(run) + return _c +} + +// LastFinalizedAndExecutedHeight provides a mock function for the type RegisterStore +func (_mock *RegisterStore) LastFinalizedAndExecutedHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LastFinalizedAndExecutedHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// OnBlockFinalized provides a mock function with no fields -func (_m *RegisterStore) OnBlockFinalized() error { - ret := _m.Called() +// RegisterStore_LastFinalizedAndExecutedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LastFinalizedAndExecutedHeight' +type RegisterStore_LastFinalizedAndExecutedHeight_Call struct { + *mock.Call +} + +// LastFinalizedAndExecutedHeight is a helper method to define mock.On call +func (_e *RegisterStore_Expecter) LastFinalizedAndExecutedHeight() *RegisterStore_LastFinalizedAndExecutedHeight_Call { + return &RegisterStore_LastFinalizedAndExecutedHeight_Call{Call: _e.mock.On("LastFinalizedAndExecutedHeight")} +} + +func (_c *RegisterStore_LastFinalizedAndExecutedHeight_Call) Run(run func()) *RegisterStore_LastFinalizedAndExecutedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterStore_LastFinalizedAndExecutedHeight_Call) Return(v uint64) *RegisterStore_LastFinalizedAndExecutedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *RegisterStore_LastFinalizedAndExecutedHeight_Call) RunAndReturn(run func() uint64) *RegisterStore_LastFinalizedAndExecutedHeight_Call { + _c.Call.Return(run) + return _c +} + +// OnBlockFinalized provides a mock function for the type RegisterStore +func (_mock *RegisterStore) OnBlockFinalized() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for OnBlockFinalized") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// SaveRegisters provides a mock function with given fields: header, registers -func (_m *RegisterStore) SaveRegisters(header *flow.Header, registers flow.RegisterEntries) error { - ret := _m.Called(header, registers) +// RegisterStore_OnBlockFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockFinalized' +type RegisterStore_OnBlockFinalized_Call struct { + *mock.Call +} + +// OnBlockFinalized is a helper method to define mock.On call +func (_e *RegisterStore_Expecter) OnBlockFinalized() *RegisterStore_OnBlockFinalized_Call { + return &RegisterStore_OnBlockFinalized_Call{Call: _e.mock.On("OnBlockFinalized")} +} + +func (_c *RegisterStore_OnBlockFinalized_Call) Run(run func()) *RegisterStore_OnBlockFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterStore_OnBlockFinalized_Call) Return(err error) *RegisterStore_OnBlockFinalized_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RegisterStore_OnBlockFinalized_Call) RunAndReturn(run func() error) *RegisterStore_OnBlockFinalized_Call { + _c.Call.Return(run) + return _c +} + +// SaveRegisters provides a mock function for the type RegisterStore +func (_mock *RegisterStore) SaveRegisters(header *flow.Header, registers flow.RegisterEntries) error { + ret := _mock.Called(header, registers) if len(ret) == 0 { panic("no return value specified for SaveRegisters") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.Header, flow.RegisterEntries) error); ok { - r0 = rf(header, registers) + if returnFunc, ok := ret.Get(0).(func(*flow.Header, flow.RegisterEntries) error); ok { + r0 = returnFunc(header, registers) } else { r0 = ret.Error(0) } - return r0 } -// NewRegisterStore creates a new instance of RegisterStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRegisterStore(t interface { - mock.TestingT - Cleanup(func()) -}) *RegisterStore { - mock := &RegisterStore{} - mock.Mock.Test(t) +// RegisterStore_SaveRegisters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SaveRegisters' +type RegisterStore_SaveRegisters_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SaveRegisters is a helper method to define mock.On call +// - header *flow.Header +// - registers flow.RegisterEntries +func (_e *RegisterStore_Expecter) SaveRegisters(header interface{}, registers interface{}) *RegisterStore_SaveRegisters_Call { + return &RegisterStore_SaveRegisters_Call{Call: _e.mock.On("SaveRegisters", header, registers)} +} - return mock +func (_c *RegisterStore_SaveRegisters_Call) Run(run func(header *flow.Header, registers flow.RegisterEntries)) *RegisterStore_SaveRegisters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + var arg1 flow.RegisterEntries + if args[1] != nil { + arg1 = args[1].(flow.RegisterEntries) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RegisterStore_SaveRegisters_Call) Return(err error) *RegisterStore_SaveRegisters_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RegisterStore_SaveRegisters_Call) RunAndReturn(run func(header *flow.Header, registers flow.RegisterEntries) error) *RegisterStore_SaveRegisters_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/register_store_notifier.go b/engine/execution/mock/register_store_notifier.go index 1d50c4c01d0..957cbfc49eb 100644 --- a/engine/execution/mock/register_store_notifier.go +++ b/engine/execution/mock/register_store_notifier.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// RegisterStoreNotifier is an autogenerated mock type for the RegisterStoreNotifier type -type RegisterStoreNotifier struct { - mock.Mock -} - -// OnFinalizedAndExecutedHeightUpdated provides a mock function with given fields: height -func (_m *RegisterStoreNotifier) OnFinalizedAndExecutedHeightUpdated(height uint64) { - _m.Called(height) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewRegisterStoreNotifier creates a new instance of RegisterStoreNotifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,56 @@ func NewRegisterStoreNotifier(t interface { return mock } + +// RegisterStoreNotifier is an autogenerated mock type for the RegisterStoreNotifier type +type RegisterStoreNotifier struct { + mock.Mock +} + +type RegisterStoreNotifier_Expecter struct { + mock *mock.Mock +} + +func (_m *RegisterStoreNotifier) EXPECT() *RegisterStoreNotifier_Expecter { + return &RegisterStoreNotifier_Expecter{mock: &_m.Mock} +} + +// OnFinalizedAndExecutedHeightUpdated provides a mock function for the type RegisterStoreNotifier +func (_mock *RegisterStoreNotifier) OnFinalizedAndExecutedHeightUpdated(height uint64) { + _mock.Called(height) + return +} + +// RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFinalizedAndExecutedHeightUpdated' +type RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call struct { + *mock.Call +} + +// OnFinalizedAndExecutedHeightUpdated is a helper method to define mock.On call +// - height uint64 +func (_e *RegisterStoreNotifier_Expecter) OnFinalizedAndExecutedHeightUpdated(height interface{}) *RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call { + return &RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call{Call: _e.mock.On("OnFinalizedAndExecutedHeightUpdated", height)} +} + +func (_c *RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call) Run(run func(height uint64)) *RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call) Return() *RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call) RunAndReturn(run func(height uint64)) *RegisterStoreNotifier_OnFinalizedAndExecutedHeightUpdated_Call { + _c.Run(run) + return _c +} diff --git a/engine/execution/mock/script_executor.go b/engine/execution/mock/script_executor.go index ce31e1adb2d..fa9895c9979 100644 --- a/engine/execution/mock/script_executor.go +++ b/engine/execution/mock/script_executor.go @@ -1,23 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" + "context" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewScriptExecutor creates a new instance of ScriptExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScriptExecutor(t interface { + mock.TestingT + Cleanup(func()) +}) *ScriptExecutor { + mock := &ScriptExecutor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ScriptExecutor is an autogenerated mock type for the ScriptExecutor type type ScriptExecutor struct { mock.Mock } -// ExecuteScriptAtBlockID provides a mock function with given fields: ctx, script, arguments, blockID -func (_m *ScriptExecutor) ExecuteScriptAtBlockID(ctx context.Context, script []byte, arguments [][]byte, blockID flow.Identifier) ([]byte, uint64, error) { - ret := _m.Called(ctx, script, arguments, blockID) +type ScriptExecutor_Expecter struct { + mock *mock.Mock +} + +func (_m *ScriptExecutor) EXPECT() *ScriptExecutor_Expecter { + return &ScriptExecutor_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockID provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) ExecuteScriptAtBlockID(ctx context.Context, script []byte, arguments [][]byte, blockID flow.Identifier) ([]byte, uint64, error) { + ret := _mock.Called(ctx, script, arguments, blockID) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -26,35 +49,84 @@ func (_m *ScriptExecutor) ExecuteScriptAtBlockID(ctx context.Context, script []b var r0 []byte var r1 uint64 var r2 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, flow.Identifier) ([]byte, uint64, error)); ok { - return rf(ctx, script, arguments, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, flow.Identifier) ([]byte, uint64, error)); ok { + return returnFunc(ctx, script, arguments, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, flow.Identifier) []byte); ok { - r0 = rf(ctx, script, arguments, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, flow.Identifier) []byte); ok { + r0 = returnFunc(ctx, script, arguments, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, [][]byte, flow.Identifier) uint64); ok { - r1 = rf(ctx, script, arguments, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, [][]byte, flow.Identifier) uint64); ok { + r1 = returnFunc(ctx, script, arguments, blockID) } else { r1 = ret.Get(1).(uint64) } - - if rf, ok := ret.Get(2).(func(context.Context, []byte, [][]byte, flow.Identifier) error); ok { - r2 = rf(ctx, script, arguments, blockID) + if returnFunc, ok := ret.Get(2).(func(context.Context, []byte, [][]byte, flow.Identifier) error); ok { + r2 = returnFunc(ctx, script, arguments, blockID) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetAccount provides a mock function with given fields: ctx, address, blockID -func (_m *ScriptExecutor) GetAccount(ctx context.Context, address flow.Address, blockID flow.Identifier) (*flow.Account, error) { - ret := _m.Called(ctx, address, blockID) +// ScriptExecutor_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type ScriptExecutor_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - script []byte +// - arguments [][]byte +// - blockID flow.Identifier +func (_e *ScriptExecutor_Expecter) ExecuteScriptAtBlockID(ctx interface{}, script interface{}, arguments interface{}, blockID interface{}) *ScriptExecutor_ExecuteScriptAtBlockID_Call { + return &ScriptExecutor_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", ctx, script, arguments, blockID)} +} + +func (_c *ScriptExecutor_ExecuteScriptAtBlockID_Call) Run(run func(ctx context.Context, script []byte, arguments [][]byte, blockID flow.Identifier)) *ScriptExecutor_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 [][]byte + if args[2] != nil { + arg2 = args[2].([][]byte) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScriptExecutor_ExecuteScriptAtBlockID_Call) Return(bytes []byte, v uint64, err error) *ScriptExecutor_ExecuteScriptAtBlockID_Call { + _c.Call.Return(bytes, v, err) + return _c +} + +func (_c *ScriptExecutor_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(ctx context.Context, script []byte, arguments [][]byte, blockID flow.Identifier) ([]byte, uint64, error)) *ScriptExecutor_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetAccount provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetAccount(ctx context.Context, address flow.Address, blockID flow.Identifier) (*flow.Account, error) { + ret := _mock.Called(ctx, address, blockID) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -62,29 +134,73 @@ func (_m *ScriptExecutor) GetAccount(ctx context.Context, address flow.Address, var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier) (*flow.Account, error)); ok { - return rf(ctx, address, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier) (*flow.Account, error)); ok { + return returnFunc(ctx, address, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier) *flow.Account); ok { - r0 = rf(ctx, address, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, flow.Identifier) *flow.Account); ok { + r0 = returnFunc(ctx, address, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, flow.Identifier) error); ok { - r1 = rf(ctx, address, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, flow.Identifier) error); ok { + r1 = returnFunc(ctx, address, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetRegisterAtBlockID provides a mock function with given fields: ctx, owner, key, blockID -func (_m *ScriptExecutor) GetRegisterAtBlockID(ctx context.Context, owner []byte, key []byte, blockID flow.Identifier) ([]byte, error) { - ret := _m.Called(ctx, owner, key, blockID) +// ScriptExecutor_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type ScriptExecutor_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - blockID flow.Identifier +func (_e *ScriptExecutor_Expecter) GetAccount(ctx interface{}, address interface{}, blockID interface{}) *ScriptExecutor_GetAccount_Call { + return &ScriptExecutor_GetAccount_Call{Call: _e.mock.On("GetAccount", ctx, address, blockID)} +} + +func (_c *ScriptExecutor_GetAccount_Call) Run(run func(ctx context.Context, address flow.Address, blockID flow.Identifier)) *ScriptExecutor_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetAccount_Call) Return(account *flow.Account, err error) *ScriptExecutor_GetAccount_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *ScriptExecutor_GetAccount_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, blockID flow.Identifier) (*flow.Account, error)) *ScriptExecutor_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetRegisterAtBlockID provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetRegisterAtBlockID(ctx context.Context, owner []byte, key []byte, blockID flow.Identifier) ([]byte, error) { + ret := _mock.Called(ctx, owner, key, blockID) if len(ret) == 0 { panic("no return value specified for GetRegisterAtBlockID") @@ -92,36 +208,72 @@ func (_m *ScriptExecutor) GetRegisterAtBlockID(ctx context.Context, owner []byte var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, []byte, flow.Identifier) ([]byte, error)); ok { - return rf(ctx, owner, key, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, []byte, flow.Identifier) ([]byte, error)); ok { + return returnFunc(ctx, owner, key, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, []byte, []byte, flow.Identifier) []byte); ok { - r0 = rf(ctx, owner, key, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, []byte, flow.Identifier) []byte); ok { + r0 = returnFunc(ctx, owner, key, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, []byte, flow.Identifier) error); ok { - r1 = rf(ctx, owner, key, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, []byte, flow.Identifier) error); ok { + r1 = returnFunc(ctx, owner, key, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewScriptExecutor creates a new instance of ScriptExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewScriptExecutor(t interface { - mock.TestingT - Cleanup(func()) -}) *ScriptExecutor { - mock := &ScriptExecutor{} - mock.Mock.Test(t) +// ScriptExecutor_GetRegisterAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegisterAtBlockID' +type ScriptExecutor_GetRegisterAtBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetRegisterAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - owner []byte +// - key []byte +// - blockID flow.Identifier +func (_e *ScriptExecutor_Expecter) GetRegisterAtBlockID(ctx interface{}, owner interface{}, key interface{}, blockID interface{}) *ScriptExecutor_GetRegisterAtBlockID_Call { + return &ScriptExecutor_GetRegisterAtBlockID_Call{Call: _e.mock.On("GetRegisterAtBlockID", ctx, owner, key, blockID)} +} - return mock +func (_c *ScriptExecutor_GetRegisterAtBlockID_Call) Run(run func(ctx context.Context, owner []byte, key []byte, blockID flow.Identifier)) *ScriptExecutor_GetRegisterAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetRegisterAtBlockID_Call) Return(bytes []byte, err error) *ScriptExecutor_GetRegisterAtBlockID_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ScriptExecutor_GetRegisterAtBlockID_Call) RunAndReturn(run func(ctx context.Context, owner []byte, key []byte, blockID flow.Identifier) ([]byte, error)) *ScriptExecutor_GetRegisterAtBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/mock/wal_reader.go b/engine/execution/mock/wal_reader.go index 9cc87a5401a..0cb8ca6e8c2 100644 --- a/engine/execution/mock/wal_reader.go +++ b/engine/execution/mock/wal_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewWALReader creates a new instance of WALReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewWALReader(t interface { + mock.TestingT + Cleanup(func()) +}) *WALReader { + mock := &WALReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // WALReader is an autogenerated mock type for the WALReader type type WALReader struct { mock.Mock } -// Next provides a mock function with no fields -func (_m *WALReader) Next() (uint64, flow.RegisterEntries, error) { - ret := _m.Called() +type WALReader_Expecter struct { + mock *mock.Mock +} + +func (_m *WALReader) EXPECT() *WALReader_Expecter { + return &WALReader_Expecter{mock: &_m.Mock} +} + +// Next provides a mock function for the type WALReader +func (_mock *WALReader) Next() (uint64, flow.RegisterEntries, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Next") @@ -23,42 +47,52 @@ func (_m *WALReader) Next() (uint64, flow.RegisterEntries, error) { var r0 uint64 var r1 flow.RegisterEntries var r2 error - if rf, ok := ret.Get(0).(func() (uint64, flow.RegisterEntries, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, flow.RegisterEntries, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() flow.RegisterEntries); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() flow.RegisterEntries); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).(flow.RegisterEntries) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewWALReader creates a new instance of WALReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewWALReader(t interface { - mock.TestingT - Cleanup(func()) -}) *WALReader { - mock := &WALReader{} - mock.Mock.Test(t) +// WALReader_Next_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Next' +type WALReader_Next_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Next is a helper method to define mock.On call +func (_e *WALReader_Expecter) Next() *WALReader_Next_Call { + return &WALReader_Next_Call{Call: _e.mock.On("Next")} +} - return mock +func (_c *WALReader_Next_Call) Run(run func()) *WALReader_Next_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *WALReader_Next_Call) Return(height uint64, registers flow.RegisterEntries, err error) *WALReader_Next_Call { + _c.Call.Return(height, registers, err) + return _c +} + +func (_c *WALReader_Next_Call) RunAndReturn(run func() (uint64, flow.RegisterEntries, error)) *WALReader_Next_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/provider/engine_test.go b/engine/execution/provider/engine_test.go index d1c441521cf..4c141676339 100644 --- a/engine/execution/provider/engine_test.go +++ b/engine/execution/provider/engine_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/stretchr/testify/assert" - _ "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -185,6 +184,10 @@ func newTestEngine(t *testing.T, net *mocknetwork.EngineRegistry, authorized boo ) { ps := mockprotocol.NewState(t) execState := state.NewExecutionState(t) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) e, err := New( diff --git a/engine/execution/provider/mock/provider_engine.go b/engine/execution/provider/mock/provider_engine.go deleted file mode 100644 index 559292675b6..00000000000 --- a/engine/execution/provider/mock/provider_engine.go +++ /dev/null @@ -1,118 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - channels "github.com/onflow/flow-go/network/channels" - - flow "github.com/onflow/flow-go/model/flow" - - mock "github.com/stretchr/testify/mock" -) - -// ProviderEngine is an autogenerated mock type for the ProviderEngine type -type ProviderEngine struct { - mock.Mock -} - -// BroadcastExecutionReceipt provides a mock function with given fields: _a0, _a1, _a2 -func (_m *ProviderEngine) BroadcastExecutionReceipt(_a0 context.Context, _a1 uint64, _a2 *flow.ExecutionReceipt) (bool, error) { - ret := _m.Called(_a0, _a1, _a2) - - if len(ret) == 0 { - panic("no return value specified for BroadcastExecutionReceipt") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, *flow.ExecutionReceipt) (bool, error)); ok { - return rf(_a0, _a1, _a2) - } - if rf, ok := ret.Get(0).(func(context.Context, uint64, *flow.ExecutionReceipt) bool); ok { - r0 = rf(_a0, _a1, _a2) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, *flow.ExecutionReceipt) error); ok { - r1 = rf(_a0, _a1, _a2) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Done provides a mock function with no fields -func (_m *ProviderEngine) Done() <-chan struct{} { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Done") - } - - var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(<-chan struct{}) - } - } - - return r0 -} - -// Process provides a mock function with given fields: channel, originID, message -func (_m *ProviderEngine) Process(channel channels.Channel, originID flow.Identifier, message interface{}) error { - ret := _m.Called(channel, originID, message) - - if len(ret) == 0 { - panic("no return value specified for Process") - } - - var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel, flow.Identifier, interface{}) error); ok { - r0 = rf(channel, originID, message) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Ready provides a mock function with no fields -func (_m *ProviderEngine) Ready() <-chan struct{} { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Ready") - } - - var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(<-chan struct{}) - } - } - - return r0 -} - -// NewProviderEngine creates a new instance of ProviderEngine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProviderEngine(t interface { - mock.TestingT - Cleanup(func()) -}) *ProviderEngine { - mock := &ProviderEngine{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/execution/rpc/engine.go b/engine/execution/rpc/engine.go index d32d093c72d..0235c9f6252 100644 --- a/engine/execution/rpc/engine.go +++ b/engine/execution/rpc/engine.go @@ -96,6 +96,13 @@ func New( interceptors = append(interceptors, rateLimitInterceptor) } + // Note: logging interceptor should be last (innermost) to capture all messages. + // Both start and finish logs are at debug level. + // Example log messages for searching: + // - Start: DBG "started call" grpc.method=ExecuteScriptAtBlockID grpc.service=flow.execution.ExecutionAPI peer.address=... + // - Finish: DBG "finished call" grpc.method=ExecuteScriptAtBlockID grpc.service=flow.execution.ExecutionAPI peer.address=... grpc.code=OK grpc.time_ms=... + interceptors = append(interceptors, grpcserver.LoggingInterceptor(log)) + // create a chained unary interceptor chainedInterceptors := grpc.ChainUnaryInterceptor(interceptors...) serverOptions = append(serverOptions, chainedInterceptors) diff --git a/engine/execution/state/bootstrap/bootstrap.go b/engine/execution/state/bootstrap/bootstrap.go index 4a5e11c9f10..0ad7c2c1721 100644 --- a/engine/execution/state/bootstrap/bootstrap.go +++ b/engine/execution/state/bootstrap/bootstrap.go @@ -48,9 +48,9 @@ func (b *Bootstrapper) BootstrapLedger( vm := fvm.NewVirtualMachine() ctx := fvm.NewContext( + chain, fvm.WithLogger(b.logger), fvm.WithMaxStateInteractionSize(ledgerIntractionLimitNeededForBootstrapping), - fvm.WithChain(chain), ) bootstrap := fvm.Bootstrap( diff --git a/engine/execution/state/bootstrap/bootstrap_test.go b/engine/execution/state/bootstrap/bootstrap_test.go index aee578b7729..58401ad633d 100644 --- a/engine/execution/state/bootstrap/bootstrap_test.go +++ b/engine/execution/state/bootstrap/bootstrap_test.go @@ -58,7 +58,7 @@ func TestBootstrapLedger(t *testing.T) { func TestBootstrapLedger_ZeroTokenSupply(t *testing.T) { expectedStateCommitmentBytes, _ := hex.DecodeString( - "072ff5128df34db4483879f1b617338cd51def0e55cae25927eb5f3b404f3ef9", + "250dab8c1ebccd4a6e047b52f4d2bd33b35e2fdaa6b12e701803149aad4046d0", ) expectedStateCommitment, err := flow.ToStateCommitment(expectedStateCommitmentBytes) require.NoError(t, err) @@ -107,7 +107,7 @@ func TestBootstrapLedger_ZeroTokenSupply(t *testing.T) { // This tests that the state commitment has not changed for the bookkeeping parts of the transaction. func TestBootstrapLedger_EmptyTransaction(t *testing.T) { expectedStateCommitmentBytes, _ := hex.DecodeString( - "61acd22132b90efd23bb1c4413ae5071dc9c0e123c288371a755e4f041791a20", + "a35f40f037369b37b9762e983601e4fe9557fbd8f3431e8132f21f4ff856ac9c", ) expectedStateCommitment, err := flow.ToStateCommitment(expectedStateCommitmentBytes) require.NoError(t, err) @@ -143,7 +143,7 @@ func TestBootstrapLedger_EmptyTransaction(t *testing.T) { vm := fvm.NewVirtualMachine() ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithTransactionFeesEnabled(true), fvm.WithAccountStorageLimit(true), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), diff --git a/engine/execution/state/mock/execution_state.go b/engine/execution/state/mock/execution_state.go index 5199ca35e26..5ca4557cbf9 100644 --- a/engine/execution/state/mock/execution_state.go +++ b/engine/execution/state/mock/execution_state.go @@ -1,26 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - execution "github.com/onflow/flow-go/engine/execution" - flow "github.com/onflow/flow-go/model/flow" + "context" + "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" ) +// NewExecutionState creates a new instance of ExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionState(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionState { + mock := &ExecutionState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionState is an autogenerated mock type for the ExecutionState type type ExecutionState struct { mock.Mock } -// ChunkDataPackByChunkID provides a mock function with given fields: _a0 -func (_m *ExecutionState) ChunkDataPackByChunkID(_a0 flow.Identifier) (*flow.ChunkDataPack, error) { - ret := _m.Called(_a0) +type ExecutionState_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionState) EXPECT() *ExecutionState_Expecter { + return &ExecutionState_Expecter{mock: &_m.Mock} +} + +// ChunkDataPackByChunkID provides a mock function for the type ExecutionState +func (_mock *ExecutionState) ChunkDataPackByChunkID(identifier flow.Identifier) (*flow.ChunkDataPack, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for ChunkDataPackByChunkID") @@ -28,29 +50,61 @@ func (_m *ExecutionState) ChunkDataPackByChunkID(_a0 flow.Identifier) (*flow.Chu var r0 *flow.ChunkDataPack var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ChunkDataPack, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ChunkDataPack, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ChunkDataPack); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ChunkDataPack); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ChunkDataPack) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// CreateStorageSnapshot provides a mock function with given fields: blockID -func (_m *ExecutionState) CreateStorageSnapshot(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error) { - ret := _m.Called(blockID) +// ExecutionState_ChunkDataPackByChunkID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChunkDataPackByChunkID' +type ExecutionState_ChunkDataPackByChunkID_Call struct { + *mock.Call +} + +// ChunkDataPackByChunkID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ExecutionState_Expecter) ChunkDataPackByChunkID(identifier interface{}) *ExecutionState_ChunkDataPackByChunkID_Call { + return &ExecutionState_ChunkDataPackByChunkID_Call{Call: _e.mock.On("ChunkDataPackByChunkID", identifier)} +} + +func (_c *ExecutionState_ChunkDataPackByChunkID_Call) Run(run func(identifier flow.Identifier)) *ExecutionState_ChunkDataPackByChunkID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionState_ChunkDataPackByChunkID_Call) Return(chunkDataPack *flow.ChunkDataPack, err error) *ExecutionState_ChunkDataPackByChunkID_Call { + _c.Call.Return(chunkDataPack, err) + return _c +} + +func (_c *ExecutionState_ChunkDataPackByChunkID_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.ChunkDataPack, error)) *ExecutionState_ChunkDataPackByChunkID_Call { + _c.Call.Return(run) + return _c +} + +// CreateStorageSnapshot provides a mock function for the type ExecutionState +func (_mock *ExecutionState) CreateStorageSnapshot(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for CreateStorageSnapshot") @@ -59,37 +113,68 @@ func (_m *ExecutionState) CreateStorageSnapshot(blockID flow.Identifier) (snapsh var r0 snapshot.StorageSnapshot var r1 *flow.Header var r2 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) snapshot.StorageSnapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) snapshot.StorageSnapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(snapshot.StorageSnapshot) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) *flow.Header); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) *flow.Header); ok { + r1 = returnFunc(blockID) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*flow.Header) } } - - if rf, ok := ret.Get(2).(func(flow.Identifier) error); ok { - r2 = rf(blockID) + if returnFunc, ok := ret.Get(2).(func(flow.Identifier) error); ok { + r2 = returnFunc(blockID) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetExecutionResultID provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionState) GetExecutionResultID(_a0 context.Context, _a1 flow.Identifier) (flow.Identifier, error) { - ret := _m.Called(_a0, _a1) +// ExecutionState_CreateStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateStorageSnapshot' +type ExecutionState_CreateStorageSnapshot_Call struct { + *mock.Call +} + +// CreateStorageSnapshot is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionState_Expecter) CreateStorageSnapshot(blockID interface{}) *ExecutionState_CreateStorageSnapshot_Call { + return &ExecutionState_CreateStorageSnapshot_Call{Call: _e.mock.On("CreateStorageSnapshot", blockID)} +} + +func (_c *ExecutionState_CreateStorageSnapshot_Call) Run(run func(blockID flow.Identifier)) *ExecutionState_CreateStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionState_CreateStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot, header *flow.Header, err error) *ExecutionState_CreateStorageSnapshot_Call { + _c.Call.Return(storageSnapshot, header, err) + return _c +} + +func (_c *ExecutionState_CreateStorageSnapshot_Call) RunAndReturn(run func(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)) *ExecutionState_CreateStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultID provides a mock function for the type ExecutionState +func (_mock *ExecutionState) GetExecutionResultID(context1 context.Context, identifier flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(context1, identifier) if len(ret) == 0 { panic("no return value specified for GetExecutionResultID") @@ -97,29 +182,67 @@ func (_m *ExecutionState) GetExecutionResultID(_a0 context.Context, _a1 flow.Ide var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (flow.Identifier, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(context1, identifier) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) flow.Identifier); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(context1, identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(context1, identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetHighestFinalizedExecuted provides a mock function with no fields -func (_m *ExecutionState) GetHighestFinalizedExecuted() (uint64, error) { - ret := _m.Called() +// ExecutionState_GetExecutionResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultID' +type ExecutionState_GetExecutionResultID_Call struct { + *mock.Call +} + +// GetExecutionResultID is a helper method to define mock.On call +// - context1 context.Context +// - identifier flow.Identifier +func (_e *ExecutionState_Expecter) GetExecutionResultID(context1 interface{}, identifier interface{}) *ExecutionState_GetExecutionResultID_Call { + return &ExecutionState_GetExecutionResultID_Call{Call: _e.mock.On("GetExecutionResultID", context1, identifier)} +} + +func (_c *ExecutionState_GetExecutionResultID_Call) Run(run func(context1 context.Context, identifier flow.Identifier)) *ExecutionState_GetExecutionResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionState_GetExecutionResultID_Call) Return(identifier1 flow.Identifier, err error) *ExecutionState_GetExecutionResultID_Call { + _c.Call.Return(identifier1, err) + return _c +} + +func (_c *ExecutionState_GetExecutionResultID_Call) RunAndReturn(run func(context1 context.Context, identifier flow.Identifier) (flow.Identifier, error)) *ExecutionState_GetExecutionResultID_Call { + _c.Call.Return(run) + return _c +} + +// GetHighestFinalizedExecuted provides a mock function for the type ExecutionState +func (_mock *ExecutionState) GetHighestFinalizedExecuted() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetHighestFinalizedExecuted") @@ -127,27 +250,52 @@ func (_m *ExecutionState) GetHighestFinalizedExecuted() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLastExecutedBlockID provides a mock function with given fields: _a0 -func (_m *ExecutionState) GetLastExecutedBlockID(_a0 context.Context) (uint64, flow.Identifier, error) { - ret := _m.Called(_a0) +// ExecutionState_GetHighestFinalizedExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetHighestFinalizedExecuted' +type ExecutionState_GetHighestFinalizedExecuted_Call struct { + *mock.Call +} + +// GetHighestFinalizedExecuted is a helper method to define mock.On call +func (_e *ExecutionState_Expecter) GetHighestFinalizedExecuted() *ExecutionState_GetHighestFinalizedExecuted_Call { + return &ExecutionState_GetHighestFinalizedExecuted_Call{Call: _e.mock.On("GetHighestFinalizedExecuted")} +} + +func (_c *ExecutionState_GetHighestFinalizedExecuted_Call) Run(run func()) *ExecutionState_GetHighestFinalizedExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionState_GetHighestFinalizedExecuted_Call) Return(v uint64, err error) *ExecutionState_GetHighestFinalizedExecuted_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ExecutionState_GetHighestFinalizedExecuted_Call) RunAndReturn(run func() (uint64, error)) *ExecutionState_GetHighestFinalizedExecuted_Call { + _c.Call.Return(run) + return _c +} + +// GetLastExecutedBlockID provides a mock function for the type ExecutionState +func (_mock *ExecutionState) GetLastExecutedBlockID(context1 context.Context) (uint64, flow.Identifier, error) { + ret := _mock.Called(context1) if len(ret) == 0 { panic("no return value specified for GetLastExecutedBlockID") @@ -156,35 +304,66 @@ func (_m *ExecutionState) GetLastExecutedBlockID(_a0 context.Context) (uint64, f var r0 uint64 var r1 flow.Identifier var r2 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, flow.Identifier, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) (uint64, flow.Identifier, error)); ok { + return returnFunc(context1) } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) uint64); ok { + r0 = returnFunc(context1) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context) flow.Identifier); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(context.Context) flow.Identifier); ok { + r1 = returnFunc(context1) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(flow.Identifier) } } - - if rf, ok := ret.Get(2).(func(context.Context) error); ok { - r2 = rf(_a0) + if returnFunc, ok := ret.Get(2).(func(context.Context) error); ok { + r2 = returnFunc(context1) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// IsBlockExecuted provides a mock function with given fields: height, blockID -func (_m *ExecutionState) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { - ret := _m.Called(height, blockID) +// ExecutionState_GetLastExecutedBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLastExecutedBlockID' +type ExecutionState_GetLastExecutedBlockID_Call struct { + *mock.Call +} + +// GetLastExecutedBlockID is a helper method to define mock.On call +// - context1 context.Context +func (_e *ExecutionState_Expecter) GetLastExecutedBlockID(context1 interface{}) *ExecutionState_GetLastExecutedBlockID_Call { + return &ExecutionState_GetLastExecutedBlockID_Call{Call: _e.mock.On("GetLastExecutedBlockID", context1)} +} + +func (_c *ExecutionState_GetLastExecutedBlockID_Call) Run(run func(context1 context.Context)) *ExecutionState_GetLastExecutedBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionState_GetLastExecutedBlockID_Call) Return(v uint64, identifier flow.Identifier, err error) *ExecutionState_GetLastExecutedBlockID_Call { + _c.Call.Return(v, identifier, err) + return _c +} + +func (_c *ExecutionState_GetLastExecutedBlockID_Call) RunAndReturn(run func(context1 context.Context) (uint64, flow.Identifier, error)) *ExecutionState_GetLastExecutedBlockID_Call { + _c.Call.Return(run) + return _c +} + +// IsBlockExecuted provides a mock function for the type ExecutionState +func (_mock *ExecutionState) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { + ret := _mock.Called(height, blockID) if len(ret) == 0 { panic("no return value specified for IsBlockExecuted") @@ -192,65 +371,187 @@ func (_m *ExecutionState) IsBlockExecuted(height uint64, blockID flow.Identifier var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { - return rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { + return returnFunc(height, blockID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { - r0 = rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { + r0 = returnFunc(height, blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(height, blockID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(height, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewStorageSnapshot provides a mock function with given fields: commit, blockID, height -func (_m *ExecutionState) NewStorageSnapshot(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot { - ret := _m.Called(commit, blockID, height) +// ExecutionState_IsBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsBlockExecuted' +type ExecutionState_IsBlockExecuted_Call struct { + *mock.Call +} + +// IsBlockExecuted is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +func (_e *ExecutionState_Expecter) IsBlockExecuted(height interface{}, blockID interface{}) *ExecutionState_IsBlockExecuted_Call { + return &ExecutionState_IsBlockExecuted_Call{Call: _e.mock.On("IsBlockExecuted", height, blockID)} +} + +func (_c *ExecutionState_IsBlockExecuted_Call) Run(run func(height uint64, blockID flow.Identifier)) *ExecutionState_IsBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionState_IsBlockExecuted_Call) Return(b bool, err error) *ExecutionState_IsBlockExecuted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ExecutionState_IsBlockExecuted_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier) (bool, error)) *ExecutionState_IsBlockExecuted_Call { + _c.Call.Return(run) + return _c +} + +// NewStorageSnapshot provides a mock function for the type ExecutionState +func (_mock *ExecutionState) NewStorageSnapshot(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot { + ret := _mock.Called(commit, blockID, height) if len(ret) == 0 { panic("no return value specified for NewStorageSnapshot") } var r0 snapshot.StorageSnapshot - if rf, ok := ret.Get(0).(func(flow.StateCommitment, flow.Identifier, uint64) snapshot.StorageSnapshot); ok { - r0 = rf(commit, blockID, height) + if returnFunc, ok := ret.Get(0).(func(flow.StateCommitment, flow.Identifier, uint64) snapshot.StorageSnapshot); ok { + r0 = returnFunc(commit, blockID, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(snapshot.StorageSnapshot) } } - return r0 } -// SaveExecutionResults provides a mock function with given fields: ctx, result -func (_m *ExecutionState) SaveExecutionResults(ctx context.Context, result *execution.ComputationResult) error { - ret := _m.Called(ctx, result) +// ExecutionState_NewStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewStorageSnapshot' +type ExecutionState_NewStorageSnapshot_Call struct { + *mock.Call +} + +// NewStorageSnapshot is a helper method to define mock.On call +// - commit flow.StateCommitment +// - blockID flow.Identifier +// - height uint64 +func (_e *ExecutionState_Expecter) NewStorageSnapshot(commit interface{}, blockID interface{}, height interface{}) *ExecutionState_NewStorageSnapshot_Call { + return &ExecutionState_NewStorageSnapshot_Call{Call: _e.mock.On("NewStorageSnapshot", commit, blockID, height)} +} + +func (_c *ExecutionState_NewStorageSnapshot_Call) Run(run func(commit flow.StateCommitment, blockID flow.Identifier, height uint64)) *ExecutionState_NewStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.StateCommitment + if args[0] != nil { + arg0 = args[0].(flow.StateCommitment) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ExecutionState_NewStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot) *ExecutionState_NewStorageSnapshot_Call { + _c.Call.Return(storageSnapshot) + return _c +} + +func (_c *ExecutionState_NewStorageSnapshot_Call) RunAndReturn(run func(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot) *ExecutionState_NewStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// SaveExecutionResults provides a mock function for the type ExecutionState +func (_mock *ExecutionState) SaveExecutionResults(ctx context.Context, result *execution.ComputationResult) error { + ret := _mock.Called(ctx, result) if len(ret) == 0 { panic("no return value specified for SaveExecutionResults") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *execution.ComputationResult) error); ok { - r0 = rf(ctx, result) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution.ComputationResult) error); ok { + r0 = returnFunc(ctx, result) } else { r0 = ret.Error(0) } - return r0 } -// StateCommitmentByBlockID provides a mock function with given fields: _a0 -func (_m *ExecutionState) StateCommitmentByBlockID(_a0 flow.Identifier) (flow.StateCommitment, error) { - ret := _m.Called(_a0) +// ExecutionState_SaveExecutionResults_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SaveExecutionResults' +type ExecutionState_SaveExecutionResults_Call struct { + *mock.Call +} + +// SaveExecutionResults is a helper method to define mock.On call +// - ctx context.Context +// - result *execution.ComputationResult +func (_e *ExecutionState_Expecter) SaveExecutionResults(ctx interface{}, result interface{}) *ExecutionState_SaveExecutionResults_Call { + return &ExecutionState_SaveExecutionResults_Call{Call: _e.mock.On("SaveExecutionResults", ctx, result)} +} + +func (_c *ExecutionState_SaveExecutionResults_Call) Run(run func(ctx context.Context, result *execution.ComputationResult)) *ExecutionState_SaveExecutionResults_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution.ComputationResult + if args[1] != nil { + arg1 = args[1].(*execution.ComputationResult) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionState_SaveExecutionResults_Call) Return(err error) *ExecutionState_SaveExecutionResults_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionState_SaveExecutionResults_Call) RunAndReturn(run func(ctx context.Context, result *execution.ComputationResult) error) *ExecutionState_SaveExecutionResults_Call { + _c.Call.Return(run) + return _c +} + +// StateCommitmentByBlockID provides a mock function for the type ExecutionState +func (_mock *ExecutionState) StateCommitmentByBlockID(identifier flow.Identifier) (flow.StateCommitment, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for StateCommitmentByBlockID") @@ -258,54 +559,111 @@ func (_m *ExecutionState) StateCommitmentByBlockID(_a0 flow.Identifier) (flow.St var r0 flow.StateCommitment var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// UpdateLastExecutedBlock provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionState) UpdateLastExecutedBlock(_a0 context.Context, _a1 flow.Identifier) error { - ret := _m.Called(_a0, _a1) +// ExecutionState_StateCommitmentByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StateCommitmentByBlockID' +type ExecutionState_StateCommitmentByBlockID_Call struct { + *mock.Call +} + +// StateCommitmentByBlockID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ExecutionState_Expecter) StateCommitmentByBlockID(identifier interface{}) *ExecutionState_StateCommitmentByBlockID_Call { + return &ExecutionState_StateCommitmentByBlockID_Call{Call: _e.mock.On("StateCommitmentByBlockID", identifier)} +} + +func (_c *ExecutionState_StateCommitmentByBlockID_Call) Run(run func(identifier flow.Identifier)) *ExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionState_StateCommitmentByBlockID_Call) Return(stateCommitment flow.StateCommitment, err error) *ExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Return(stateCommitment, err) + return _c +} + +func (_c *ExecutionState_StateCommitmentByBlockID_Call) RunAndReturn(run func(identifier flow.Identifier) (flow.StateCommitment, error)) *ExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// UpdateLastExecutedBlock provides a mock function for the type ExecutionState +func (_mock *ExecutionState) UpdateLastExecutedBlock(context1 context.Context, identifier flow.Identifier) error { + ret := _mock.Called(context1, identifier) if len(ret) == 0 { panic("no return value specified for UpdateLastExecutedBlock") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) error); ok { + r0 = returnFunc(context1, identifier) } else { r0 = ret.Error(0) } - return r0 } -// NewExecutionState creates a new instance of ExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionState(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionState { - mock := &ExecutionState{} - mock.Mock.Test(t) +// ExecutionState_UpdateLastExecutedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateLastExecutedBlock' +type ExecutionState_UpdateLastExecutedBlock_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UpdateLastExecutedBlock is a helper method to define mock.On call +// - context1 context.Context +// - identifier flow.Identifier +func (_e *ExecutionState_Expecter) UpdateLastExecutedBlock(context1 interface{}, identifier interface{}) *ExecutionState_UpdateLastExecutedBlock_Call { + return &ExecutionState_UpdateLastExecutedBlock_Call{Call: _e.mock.On("UpdateLastExecutedBlock", context1, identifier)} +} - return mock +func (_c *ExecutionState_UpdateLastExecutedBlock_Call) Run(run func(context1 context.Context, identifier flow.Identifier)) *ExecutionState_UpdateLastExecutedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionState_UpdateLastExecutedBlock_Call) Return(err error) *ExecutionState_UpdateLastExecutedBlock_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionState_UpdateLastExecutedBlock_Call) RunAndReturn(run func(context1 context.Context, identifier flow.Identifier) error) *ExecutionState_UpdateLastExecutedBlock_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/state/mock/finalized_execution_state.go b/engine/execution/state/mock/finalized_execution_state.go index 99826ff92af..e4d1356b768 100644 --- a/engine/execution/state/mock/finalized_execution_state.go +++ b/engine/execution/state/mock/finalized_execution_state.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewFinalizedExecutionState creates a new instance of FinalizedExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFinalizedExecutionState(t interface { + mock.TestingT + Cleanup(func()) +}) *FinalizedExecutionState { + mock := &FinalizedExecutionState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // FinalizedExecutionState is an autogenerated mock type for the FinalizedExecutionState type type FinalizedExecutionState struct { mock.Mock } -// GetHighestFinalizedExecuted provides a mock function with no fields -func (_m *FinalizedExecutionState) GetHighestFinalizedExecuted() (uint64, error) { - ret := _m.Called() +type FinalizedExecutionState_Expecter struct { + mock *mock.Mock +} + +func (_m *FinalizedExecutionState) EXPECT() *FinalizedExecutionState_Expecter { + return &FinalizedExecutionState_Expecter{mock: &_m.Mock} +} + +// GetHighestFinalizedExecuted provides a mock function for the type FinalizedExecutionState +func (_mock *FinalizedExecutionState) GetHighestFinalizedExecuted() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetHighestFinalizedExecuted") @@ -19,34 +45,45 @@ func (_m *FinalizedExecutionState) GetHighestFinalizedExecuted() (uint64, error) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewFinalizedExecutionState creates a new instance of FinalizedExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewFinalizedExecutionState(t interface { - mock.TestingT - Cleanup(func()) -}) *FinalizedExecutionState { - mock := &FinalizedExecutionState{} - mock.Mock.Test(t) +// FinalizedExecutionState_GetHighestFinalizedExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetHighestFinalizedExecuted' +type FinalizedExecutionState_GetHighestFinalizedExecuted_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetHighestFinalizedExecuted is a helper method to define mock.On call +func (_e *FinalizedExecutionState_Expecter) GetHighestFinalizedExecuted() *FinalizedExecutionState_GetHighestFinalizedExecuted_Call { + return &FinalizedExecutionState_GetHighestFinalizedExecuted_Call{Call: _e.mock.On("GetHighestFinalizedExecuted")} +} - return mock +func (_c *FinalizedExecutionState_GetHighestFinalizedExecuted_Call) Run(run func()) *FinalizedExecutionState_GetHighestFinalizedExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FinalizedExecutionState_GetHighestFinalizedExecuted_Call) Return(v uint64, err error) *FinalizedExecutionState_GetHighestFinalizedExecuted_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *FinalizedExecutionState_GetHighestFinalizedExecuted_Call) RunAndReturn(run func() (uint64, error)) *FinalizedExecutionState_GetHighestFinalizedExecuted_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/state/mock/read_only_execution_state.go b/engine/execution/state/mock/read_only_execution_state.go index 8ebe4f18c33..5a31f5b0329 100644 --- a/engine/execution/state/mock/read_only_execution_state.go +++ b/engine/execution/state/mock/read_only_execution_state.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" ) +// NewReadOnlyExecutionState creates a new instance of ReadOnlyExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReadOnlyExecutionState(t interface { + mock.TestingT + Cleanup(func()) +}) *ReadOnlyExecutionState { + mock := &ReadOnlyExecutionState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ReadOnlyExecutionState is an autogenerated mock type for the ReadOnlyExecutionState type type ReadOnlyExecutionState struct { mock.Mock } -// ChunkDataPackByChunkID provides a mock function with given fields: _a0 -func (_m *ReadOnlyExecutionState) ChunkDataPackByChunkID(_a0 flow.Identifier) (*flow.ChunkDataPack, error) { - ret := _m.Called(_a0) +type ReadOnlyExecutionState_Expecter struct { + mock *mock.Mock +} + +func (_m *ReadOnlyExecutionState) EXPECT() *ReadOnlyExecutionState_Expecter { + return &ReadOnlyExecutionState_Expecter{mock: &_m.Mock} +} + +// ChunkDataPackByChunkID provides a mock function for the type ReadOnlyExecutionState +func (_mock *ReadOnlyExecutionState) ChunkDataPackByChunkID(identifier flow.Identifier) (*flow.ChunkDataPack, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for ChunkDataPackByChunkID") @@ -26,29 +49,61 @@ func (_m *ReadOnlyExecutionState) ChunkDataPackByChunkID(_a0 flow.Identifier) (* var r0 *flow.ChunkDataPack var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ChunkDataPack, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ChunkDataPack, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ChunkDataPack); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ChunkDataPack); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ChunkDataPack) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// CreateStorageSnapshot provides a mock function with given fields: blockID -func (_m *ReadOnlyExecutionState) CreateStorageSnapshot(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error) { - ret := _m.Called(blockID) +// ReadOnlyExecutionState_ChunkDataPackByChunkID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChunkDataPackByChunkID' +type ReadOnlyExecutionState_ChunkDataPackByChunkID_Call struct { + *mock.Call +} + +// ChunkDataPackByChunkID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ReadOnlyExecutionState_Expecter) ChunkDataPackByChunkID(identifier interface{}) *ReadOnlyExecutionState_ChunkDataPackByChunkID_Call { + return &ReadOnlyExecutionState_ChunkDataPackByChunkID_Call{Call: _e.mock.On("ChunkDataPackByChunkID", identifier)} +} + +func (_c *ReadOnlyExecutionState_ChunkDataPackByChunkID_Call) Run(run func(identifier flow.Identifier)) *ReadOnlyExecutionState_ChunkDataPackByChunkID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReadOnlyExecutionState_ChunkDataPackByChunkID_Call) Return(chunkDataPack *flow.ChunkDataPack, err error) *ReadOnlyExecutionState_ChunkDataPackByChunkID_Call { + _c.Call.Return(chunkDataPack, err) + return _c +} + +func (_c *ReadOnlyExecutionState_ChunkDataPackByChunkID_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.ChunkDataPack, error)) *ReadOnlyExecutionState_ChunkDataPackByChunkID_Call { + _c.Call.Return(run) + return _c +} + +// CreateStorageSnapshot provides a mock function for the type ReadOnlyExecutionState +func (_mock *ReadOnlyExecutionState) CreateStorageSnapshot(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for CreateStorageSnapshot") @@ -57,37 +112,68 @@ func (_m *ReadOnlyExecutionState) CreateStorageSnapshot(blockID flow.Identifier) var r0 snapshot.StorageSnapshot var r1 *flow.Header var r2 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) snapshot.StorageSnapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) snapshot.StorageSnapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(snapshot.StorageSnapshot) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) *flow.Header); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) *flow.Header); ok { + r1 = returnFunc(blockID) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*flow.Header) } } - - if rf, ok := ret.Get(2).(func(flow.Identifier) error); ok { - r2 = rf(blockID) + if returnFunc, ok := ret.Get(2).(func(flow.Identifier) error); ok { + r2 = returnFunc(blockID) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetExecutionResultID provides a mock function with given fields: _a0, _a1 -func (_m *ReadOnlyExecutionState) GetExecutionResultID(_a0 context.Context, _a1 flow.Identifier) (flow.Identifier, error) { - ret := _m.Called(_a0, _a1) +// ReadOnlyExecutionState_CreateStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateStorageSnapshot' +type ReadOnlyExecutionState_CreateStorageSnapshot_Call struct { + *mock.Call +} + +// CreateStorageSnapshot is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ReadOnlyExecutionState_Expecter) CreateStorageSnapshot(blockID interface{}) *ReadOnlyExecutionState_CreateStorageSnapshot_Call { + return &ReadOnlyExecutionState_CreateStorageSnapshot_Call{Call: _e.mock.On("CreateStorageSnapshot", blockID)} +} + +func (_c *ReadOnlyExecutionState_CreateStorageSnapshot_Call) Run(run func(blockID flow.Identifier)) *ReadOnlyExecutionState_CreateStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReadOnlyExecutionState_CreateStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot, header *flow.Header, err error) *ReadOnlyExecutionState_CreateStorageSnapshot_Call { + _c.Call.Return(storageSnapshot, header, err) + return _c +} + +func (_c *ReadOnlyExecutionState_CreateStorageSnapshot_Call) RunAndReturn(run func(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)) *ReadOnlyExecutionState_CreateStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultID provides a mock function for the type ReadOnlyExecutionState +func (_mock *ReadOnlyExecutionState) GetExecutionResultID(context1 context.Context, identifier flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(context1, identifier) if len(ret) == 0 { panic("no return value specified for GetExecutionResultID") @@ -95,29 +181,67 @@ func (_m *ReadOnlyExecutionState) GetExecutionResultID(_a0 context.Context, _a1 var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (flow.Identifier, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(context1, identifier) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) flow.Identifier); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(context1, identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(context1, identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLastExecutedBlockID provides a mock function with given fields: _a0 -func (_m *ReadOnlyExecutionState) GetLastExecutedBlockID(_a0 context.Context) (uint64, flow.Identifier, error) { - ret := _m.Called(_a0) +// ReadOnlyExecutionState_GetExecutionResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultID' +type ReadOnlyExecutionState_GetExecutionResultID_Call struct { + *mock.Call +} + +// GetExecutionResultID is a helper method to define mock.On call +// - context1 context.Context +// - identifier flow.Identifier +func (_e *ReadOnlyExecutionState_Expecter) GetExecutionResultID(context1 interface{}, identifier interface{}) *ReadOnlyExecutionState_GetExecutionResultID_Call { + return &ReadOnlyExecutionState_GetExecutionResultID_Call{Call: _e.mock.On("GetExecutionResultID", context1, identifier)} +} + +func (_c *ReadOnlyExecutionState_GetExecutionResultID_Call) Run(run func(context1 context.Context, identifier flow.Identifier)) *ReadOnlyExecutionState_GetExecutionResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReadOnlyExecutionState_GetExecutionResultID_Call) Return(identifier1 flow.Identifier, err error) *ReadOnlyExecutionState_GetExecutionResultID_Call { + _c.Call.Return(identifier1, err) + return _c +} + +func (_c *ReadOnlyExecutionState_GetExecutionResultID_Call) RunAndReturn(run func(context1 context.Context, identifier flow.Identifier) (flow.Identifier, error)) *ReadOnlyExecutionState_GetExecutionResultID_Call { + _c.Call.Return(run) + return _c +} + +// GetLastExecutedBlockID provides a mock function for the type ReadOnlyExecutionState +func (_mock *ReadOnlyExecutionState) GetLastExecutedBlockID(context1 context.Context) (uint64, flow.Identifier, error) { + ret := _mock.Called(context1) if len(ret) == 0 { panic("no return value specified for GetLastExecutedBlockID") @@ -126,35 +250,66 @@ func (_m *ReadOnlyExecutionState) GetLastExecutedBlockID(_a0 context.Context) (u var r0 uint64 var r1 flow.Identifier var r2 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, flow.Identifier, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) (uint64, flow.Identifier, error)); ok { + return returnFunc(context1) } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) uint64); ok { + r0 = returnFunc(context1) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context) flow.Identifier); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(context.Context) flow.Identifier); ok { + r1 = returnFunc(context1) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(flow.Identifier) } } - - if rf, ok := ret.Get(2).(func(context.Context) error); ok { - r2 = rf(_a0) + if returnFunc, ok := ret.Get(2).(func(context.Context) error); ok { + r2 = returnFunc(context1) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// IsBlockExecuted provides a mock function with given fields: height, blockID -func (_m *ReadOnlyExecutionState) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { - ret := _m.Called(height, blockID) +// ReadOnlyExecutionState_GetLastExecutedBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLastExecutedBlockID' +type ReadOnlyExecutionState_GetLastExecutedBlockID_Call struct { + *mock.Call +} + +// GetLastExecutedBlockID is a helper method to define mock.On call +// - context1 context.Context +func (_e *ReadOnlyExecutionState_Expecter) GetLastExecutedBlockID(context1 interface{}) *ReadOnlyExecutionState_GetLastExecutedBlockID_Call { + return &ReadOnlyExecutionState_GetLastExecutedBlockID_Call{Call: _e.mock.On("GetLastExecutedBlockID", context1)} +} + +func (_c *ReadOnlyExecutionState_GetLastExecutedBlockID_Call) Run(run func(context1 context.Context)) *ReadOnlyExecutionState_GetLastExecutedBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReadOnlyExecutionState_GetLastExecutedBlockID_Call) Return(v uint64, identifier flow.Identifier, err error) *ReadOnlyExecutionState_GetLastExecutedBlockID_Call { + _c.Call.Return(v, identifier, err) + return _c +} + +func (_c *ReadOnlyExecutionState_GetLastExecutedBlockID_Call) RunAndReturn(run func(context1 context.Context) (uint64, flow.Identifier, error)) *ReadOnlyExecutionState_GetLastExecutedBlockID_Call { + _c.Call.Return(run) + return _c +} + +// IsBlockExecuted provides a mock function for the type ReadOnlyExecutionState +func (_mock *ReadOnlyExecutionState) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { + ret := _mock.Called(height, blockID) if len(ret) == 0 { panic("no return value specified for IsBlockExecuted") @@ -162,47 +317,130 @@ func (_m *ReadOnlyExecutionState) IsBlockExecuted(height uint64, blockID flow.Id var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { - return rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { + return returnFunc(height, blockID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { - r0 = rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { + r0 = returnFunc(height, blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(height, blockID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(height, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewStorageSnapshot provides a mock function with given fields: commit, blockID, height -func (_m *ReadOnlyExecutionState) NewStorageSnapshot(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot { - ret := _m.Called(commit, blockID, height) +// ReadOnlyExecutionState_IsBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsBlockExecuted' +type ReadOnlyExecutionState_IsBlockExecuted_Call struct { + *mock.Call +} + +// IsBlockExecuted is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +func (_e *ReadOnlyExecutionState_Expecter) IsBlockExecuted(height interface{}, blockID interface{}) *ReadOnlyExecutionState_IsBlockExecuted_Call { + return &ReadOnlyExecutionState_IsBlockExecuted_Call{Call: _e.mock.On("IsBlockExecuted", height, blockID)} +} + +func (_c *ReadOnlyExecutionState_IsBlockExecuted_Call) Run(run func(height uint64, blockID flow.Identifier)) *ReadOnlyExecutionState_IsBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReadOnlyExecutionState_IsBlockExecuted_Call) Return(b bool, err error) *ReadOnlyExecutionState_IsBlockExecuted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ReadOnlyExecutionState_IsBlockExecuted_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier) (bool, error)) *ReadOnlyExecutionState_IsBlockExecuted_Call { + _c.Call.Return(run) + return _c +} + +// NewStorageSnapshot provides a mock function for the type ReadOnlyExecutionState +func (_mock *ReadOnlyExecutionState) NewStorageSnapshot(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot { + ret := _mock.Called(commit, blockID, height) if len(ret) == 0 { panic("no return value specified for NewStorageSnapshot") } var r0 snapshot.StorageSnapshot - if rf, ok := ret.Get(0).(func(flow.StateCommitment, flow.Identifier, uint64) snapshot.StorageSnapshot); ok { - r0 = rf(commit, blockID, height) + if returnFunc, ok := ret.Get(0).(func(flow.StateCommitment, flow.Identifier, uint64) snapshot.StorageSnapshot); ok { + r0 = returnFunc(commit, blockID, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(snapshot.StorageSnapshot) } } - return r0 } -// StateCommitmentByBlockID provides a mock function with given fields: _a0 -func (_m *ReadOnlyExecutionState) StateCommitmentByBlockID(_a0 flow.Identifier) (flow.StateCommitment, error) { - ret := _m.Called(_a0) +// ReadOnlyExecutionState_NewStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewStorageSnapshot' +type ReadOnlyExecutionState_NewStorageSnapshot_Call struct { + *mock.Call +} + +// NewStorageSnapshot is a helper method to define mock.On call +// - commit flow.StateCommitment +// - blockID flow.Identifier +// - height uint64 +func (_e *ReadOnlyExecutionState_Expecter) NewStorageSnapshot(commit interface{}, blockID interface{}, height interface{}) *ReadOnlyExecutionState_NewStorageSnapshot_Call { + return &ReadOnlyExecutionState_NewStorageSnapshot_Call{Call: _e.mock.On("NewStorageSnapshot", commit, blockID, height)} +} + +func (_c *ReadOnlyExecutionState_NewStorageSnapshot_Call) Run(run func(commit flow.StateCommitment, blockID flow.Identifier, height uint64)) *ReadOnlyExecutionState_NewStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.StateCommitment + if args[0] != nil { + arg0 = args[0].(flow.StateCommitment) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ReadOnlyExecutionState_NewStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot) *ReadOnlyExecutionState_NewStorageSnapshot_Call { + _c.Call.Return(storageSnapshot) + return _c +} + +func (_c *ReadOnlyExecutionState_NewStorageSnapshot_Call) RunAndReturn(run func(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot) *ReadOnlyExecutionState_NewStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// StateCommitmentByBlockID provides a mock function for the type ReadOnlyExecutionState +func (_mock *ReadOnlyExecutionState) StateCommitmentByBlockID(identifier flow.Identifier) (flow.StateCommitment, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for StateCommitmentByBlockID") @@ -210,36 +448,54 @@ func (_m *ReadOnlyExecutionState) StateCommitmentByBlockID(_a0 flow.Identifier) var r0 flow.StateCommitment var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewReadOnlyExecutionState creates a new instance of ReadOnlyExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReadOnlyExecutionState(t interface { - mock.TestingT - Cleanup(func()) -}) *ReadOnlyExecutionState { - mock := &ReadOnlyExecutionState{} - mock.Mock.Test(t) +// ReadOnlyExecutionState_StateCommitmentByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StateCommitmentByBlockID' +type ReadOnlyExecutionState_StateCommitmentByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StateCommitmentByBlockID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ReadOnlyExecutionState_Expecter) StateCommitmentByBlockID(identifier interface{}) *ReadOnlyExecutionState_StateCommitmentByBlockID_Call { + return &ReadOnlyExecutionState_StateCommitmentByBlockID_Call{Call: _e.mock.On("StateCommitmentByBlockID", identifier)} +} - return mock +func (_c *ReadOnlyExecutionState_StateCommitmentByBlockID_Call) Run(run func(identifier flow.Identifier)) *ReadOnlyExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReadOnlyExecutionState_StateCommitmentByBlockID_Call) Return(stateCommitment flow.StateCommitment, err error) *ReadOnlyExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Return(stateCommitment, err) + return _c +} + +func (_c *ReadOnlyExecutionState_StateCommitmentByBlockID_Call) RunAndReturn(run func(identifier flow.Identifier) (flow.StateCommitment, error)) *ReadOnlyExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/state/mock/register_updates_holder.go b/engine/execution/state/mock/register_updates_holder.go index 42bb218545b..e89a1e3ddac 100644 --- a/engine/execution/state/mock/register_updates_holder.go +++ b/engine/execution/state/mock/register_updates_holder.go @@ -1,67 +1,129 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewRegisterUpdatesHolder creates a new instance of RegisterUpdatesHolder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRegisterUpdatesHolder(t interface { + mock.TestingT + Cleanup(func()) +}) *RegisterUpdatesHolder { + mock := &RegisterUpdatesHolder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RegisterUpdatesHolder is an autogenerated mock type for the RegisterUpdatesHolder type type RegisterUpdatesHolder struct { mock.Mock } -// UpdatedRegisterSet provides a mock function with no fields -func (_m *RegisterUpdatesHolder) UpdatedRegisterSet() map[flow.RegisterID]flow.RegisterValue { - ret := _m.Called() +type RegisterUpdatesHolder_Expecter struct { + mock *mock.Mock +} + +func (_m *RegisterUpdatesHolder) EXPECT() *RegisterUpdatesHolder_Expecter { + return &RegisterUpdatesHolder_Expecter{mock: &_m.Mock} +} + +// UpdatedRegisterSet provides a mock function for the type RegisterUpdatesHolder +func (_mock *RegisterUpdatesHolder) UpdatedRegisterSet() map[flow.RegisterID]flow.RegisterValue { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for UpdatedRegisterSet") } var r0 map[flow.RegisterID]flow.RegisterValue - if rf, ok := ret.Get(0).(func() map[flow.RegisterID]flow.RegisterValue); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[flow.RegisterID]flow.RegisterValue); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[flow.RegisterID]flow.RegisterValue) } } - return r0 } -// UpdatedRegisters provides a mock function with no fields -func (_m *RegisterUpdatesHolder) UpdatedRegisters() flow.RegisterEntries { - ret := _m.Called() +// RegisterUpdatesHolder_UpdatedRegisterSet_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatedRegisterSet' +type RegisterUpdatesHolder_UpdatedRegisterSet_Call struct { + *mock.Call +} + +// UpdatedRegisterSet is a helper method to define mock.On call +func (_e *RegisterUpdatesHolder_Expecter) UpdatedRegisterSet() *RegisterUpdatesHolder_UpdatedRegisterSet_Call { + return &RegisterUpdatesHolder_UpdatedRegisterSet_Call{Call: _e.mock.On("UpdatedRegisterSet")} +} + +func (_c *RegisterUpdatesHolder_UpdatedRegisterSet_Call) Run(run func()) *RegisterUpdatesHolder_UpdatedRegisterSet_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterUpdatesHolder_UpdatedRegisterSet_Call) Return(registerIDToV map[flow.RegisterID]flow.RegisterValue) *RegisterUpdatesHolder_UpdatedRegisterSet_Call { + _c.Call.Return(registerIDToV) + return _c +} + +func (_c *RegisterUpdatesHolder_UpdatedRegisterSet_Call) RunAndReturn(run func() map[flow.RegisterID]flow.RegisterValue) *RegisterUpdatesHolder_UpdatedRegisterSet_Call { + _c.Call.Return(run) + return _c +} + +// UpdatedRegisters provides a mock function for the type RegisterUpdatesHolder +func (_mock *RegisterUpdatesHolder) UpdatedRegisters() flow.RegisterEntries { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for UpdatedRegisters") } var r0 flow.RegisterEntries - if rf, ok := ret.Get(0).(func() flow.RegisterEntries); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.RegisterEntries); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterEntries) } } - return r0 } -// NewRegisterUpdatesHolder creates a new instance of RegisterUpdatesHolder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRegisterUpdatesHolder(t interface { - mock.TestingT - Cleanup(func()) -}) *RegisterUpdatesHolder { - mock := &RegisterUpdatesHolder{} - mock.Mock.Test(t) +// RegisterUpdatesHolder_UpdatedRegisters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatedRegisters' +type RegisterUpdatesHolder_UpdatedRegisters_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UpdatedRegisters is a helper method to define mock.On call +func (_e *RegisterUpdatesHolder_Expecter) UpdatedRegisters() *RegisterUpdatesHolder_UpdatedRegisters_Call { + return &RegisterUpdatesHolder_UpdatedRegisters_Call{Call: _e.mock.On("UpdatedRegisters")} +} - return mock +func (_c *RegisterUpdatesHolder_UpdatedRegisters_Call) Run(run func()) *RegisterUpdatesHolder_UpdatedRegisters_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterUpdatesHolder_UpdatedRegisters_Call) Return(registerEntries flow.RegisterEntries) *RegisterUpdatesHolder_UpdatedRegisters_Call { + _c.Call.Return(registerEntries) + return _c +} + +func (_c *RegisterUpdatesHolder_UpdatedRegisters_Call) RunAndReturn(run func() flow.RegisterEntries) *RegisterUpdatesHolder_UpdatedRegisters_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/state/mock/script_execution_state.go b/engine/execution/state/mock/script_execution_state.go index 7632abe8f0a..ccef0a789f9 100644 --- a/engine/execution/state/mock/script_execution_state.go +++ b/engine/execution/state/mock/script_execution_state.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" ) +// NewScriptExecutionState creates a new instance of ScriptExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScriptExecutionState(t interface { + mock.TestingT + Cleanup(func()) +}) *ScriptExecutionState { + mock := &ScriptExecutionState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ScriptExecutionState is an autogenerated mock type for the ScriptExecutionState type type ScriptExecutionState struct { mock.Mock } -// CreateStorageSnapshot provides a mock function with given fields: blockID -func (_m *ScriptExecutionState) CreateStorageSnapshot(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error) { - ret := _m.Called(blockID) +type ScriptExecutionState_Expecter struct { + mock *mock.Mock +} + +func (_m *ScriptExecutionState) EXPECT() *ScriptExecutionState_Expecter { + return &ScriptExecutionState_Expecter{mock: &_m.Mock} +} + +// CreateStorageSnapshot provides a mock function for the type ScriptExecutionState +func (_mock *ScriptExecutionState) CreateStorageSnapshot(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for CreateStorageSnapshot") @@ -25,37 +48,68 @@ func (_m *ScriptExecutionState) CreateStorageSnapshot(blockID flow.Identifier) ( var r0 snapshot.StorageSnapshot var r1 *flow.Header var r2 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) snapshot.StorageSnapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) snapshot.StorageSnapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(snapshot.StorageSnapshot) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) *flow.Header); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) *flow.Header); ok { + r1 = returnFunc(blockID) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*flow.Header) } } - - if rf, ok := ret.Get(2).(func(flow.Identifier) error); ok { - r2 = rf(blockID) + if returnFunc, ok := ret.Get(2).(func(flow.Identifier) error); ok { + r2 = returnFunc(blockID) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// IsBlockExecuted provides a mock function with given fields: height, blockID -func (_m *ScriptExecutionState) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { - ret := _m.Called(height, blockID) +// ScriptExecutionState_CreateStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateStorageSnapshot' +type ScriptExecutionState_CreateStorageSnapshot_Call struct { + *mock.Call +} + +// CreateStorageSnapshot is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ScriptExecutionState_Expecter) CreateStorageSnapshot(blockID interface{}) *ScriptExecutionState_CreateStorageSnapshot_Call { + return &ScriptExecutionState_CreateStorageSnapshot_Call{Call: _e.mock.On("CreateStorageSnapshot", blockID)} +} + +func (_c *ScriptExecutionState_CreateStorageSnapshot_Call) Run(run func(blockID flow.Identifier)) *ScriptExecutionState_CreateStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScriptExecutionState_CreateStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot, header *flow.Header, err error) *ScriptExecutionState_CreateStorageSnapshot_Call { + _c.Call.Return(storageSnapshot, header, err) + return _c +} + +func (_c *ScriptExecutionState_CreateStorageSnapshot_Call) RunAndReturn(run func(blockID flow.Identifier) (snapshot.StorageSnapshot, *flow.Header, error)) *ScriptExecutionState_CreateStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// IsBlockExecuted provides a mock function for the type ScriptExecutionState +func (_mock *ScriptExecutionState) IsBlockExecuted(height uint64, blockID flow.Identifier) (bool, error) { + ret := _mock.Called(height, blockID) if len(ret) == 0 { panic("no return value specified for IsBlockExecuted") @@ -63,47 +117,130 @@ func (_m *ScriptExecutionState) IsBlockExecuted(height uint64, blockID flow.Iden var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { - return rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) (bool, error)); ok { + return returnFunc(height, blockID) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { - r0 = rf(height, blockID) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier) bool); ok { + r0 = returnFunc(height, blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { - r1 = rf(height, blockID) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier) error); ok { + r1 = returnFunc(height, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewStorageSnapshot provides a mock function with given fields: commit, blockID, height -func (_m *ScriptExecutionState) NewStorageSnapshot(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot { - ret := _m.Called(commit, blockID, height) +// ScriptExecutionState_IsBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsBlockExecuted' +type ScriptExecutionState_IsBlockExecuted_Call struct { + *mock.Call +} + +// IsBlockExecuted is a helper method to define mock.On call +// - height uint64 +// - blockID flow.Identifier +func (_e *ScriptExecutionState_Expecter) IsBlockExecuted(height interface{}, blockID interface{}) *ScriptExecutionState_IsBlockExecuted_Call { + return &ScriptExecutionState_IsBlockExecuted_Call{Call: _e.mock.On("IsBlockExecuted", height, blockID)} +} + +func (_c *ScriptExecutionState_IsBlockExecuted_Call) Run(run func(height uint64, blockID flow.Identifier)) *ScriptExecutionState_IsBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ScriptExecutionState_IsBlockExecuted_Call) Return(b bool, err error) *ScriptExecutionState_IsBlockExecuted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ScriptExecutionState_IsBlockExecuted_Call) RunAndReturn(run func(height uint64, blockID flow.Identifier) (bool, error)) *ScriptExecutionState_IsBlockExecuted_Call { + _c.Call.Return(run) + return _c +} + +// NewStorageSnapshot provides a mock function for the type ScriptExecutionState +func (_mock *ScriptExecutionState) NewStorageSnapshot(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot { + ret := _mock.Called(commit, blockID, height) if len(ret) == 0 { panic("no return value specified for NewStorageSnapshot") } var r0 snapshot.StorageSnapshot - if rf, ok := ret.Get(0).(func(flow.StateCommitment, flow.Identifier, uint64) snapshot.StorageSnapshot); ok { - r0 = rf(commit, blockID, height) + if returnFunc, ok := ret.Get(0).(func(flow.StateCommitment, flow.Identifier, uint64) snapshot.StorageSnapshot); ok { + r0 = returnFunc(commit, blockID, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(snapshot.StorageSnapshot) } } - return r0 } -// StateCommitmentByBlockID provides a mock function with given fields: _a0 -func (_m *ScriptExecutionState) StateCommitmentByBlockID(_a0 flow.Identifier) (flow.StateCommitment, error) { - ret := _m.Called(_a0) +// ScriptExecutionState_NewStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewStorageSnapshot' +type ScriptExecutionState_NewStorageSnapshot_Call struct { + *mock.Call +} + +// NewStorageSnapshot is a helper method to define mock.On call +// - commit flow.StateCommitment +// - blockID flow.Identifier +// - height uint64 +func (_e *ScriptExecutionState_Expecter) NewStorageSnapshot(commit interface{}, blockID interface{}, height interface{}) *ScriptExecutionState_NewStorageSnapshot_Call { + return &ScriptExecutionState_NewStorageSnapshot_Call{Call: _e.mock.On("NewStorageSnapshot", commit, blockID, height)} +} + +func (_c *ScriptExecutionState_NewStorageSnapshot_Call) Run(run func(commit flow.StateCommitment, blockID flow.Identifier, height uint64)) *ScriptExecutionState_NewStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.StateCommitment + if args[0] != nil { + arg0 = args[0].(flow.StateCommitment) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ScriptExecutionState_NewStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot) *ScriptExecutionState_NewStorageSnapshot_Call { + _c.Call.Return(storageSnapshot) + return _c +} + +func (_c *ScriptExecutionState_NewStorageSnapshot_Call) RunAndReturn(run func(commit flow.StateCommitment, blockID flow.Identifier, height uint64) snapshot.StorageSnapshot) *ScriptExecutionState_NewStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// StateCommitmentByBlockID provides a mock function for the type ScriptExecutionState +func (_mock *ScriptExecutionState) StateCommitmentByBlockID(identifier flow.Identifier) (flow.StateCommitment, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for StateCommitmentByBlockID") @@ -111,36 +248,54 @@ func (_m *ScriptExecutionState) StateCommitmentByBlockID(_a0 flow.Identifier) (f var r0 flow.StateCommitment var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewScriptExecutionState creates a new instance of ScriptExecutionState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewScriptExecutionState(t interface { - mock.TestingT - Cleanup(func()) -}) *ScriptExecutionState { - mock := &ScriptExecutionState{} - mock.Mock.Test(t) +// ScriptExecutionState_StateCommitmentByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StateCommitmentByBlockID' +type ScriptExecutionState_StateCommitmentByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StateCommitmentByBlockID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ScriptExecutionState_Expecter) StateCommitmentByBlockID(identifier interface{}) *ScriptExecutionState_StateCommitmentByBlockID_Call { + return &ScriptExecutionState_StateCommitmentByBlockID_Call{Call: _e.mock.On("StateCommitmentByBlockID", identifier)} +} - return mock +func (_c *ScriptExecutionState_StateCommitmentByBlockID_Call) Run(run func(identifier flow.Identifier)) *ScriptExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScriptExecutionState_StateCommitmentByBlockID_Call) Return(stateCommitment flow.StateCommitment, err error) *ScriptExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Return(stateCommitment, err) + return _c +} + +func (_c *ScriptExecutionState_StateCommitmentByBlockID_Call) RunAndReturn(run func(identifier flow.Identifier) (flow.StateCommitment, error)) *ScriptExecutionState_StateCommitmentByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/engine/execution/storehouse/background_indexer.go b/engine/execution/storehouse/background_indexer.go new file mode 100644 index 00000000000..02e2d6f639e --- /dev/null +++ b/engine/execution/storehouse/background_indexer.go @@ -0,0 +1,126 @@ +package storehouse + +import ( + "context" + "fmt" + "time" + + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" +) + +// RegisterUpdatesProvider defines an interface to fetch register updates for a given block ID. +type RegisterUpdatesProvider interface { + RegisterUpdatesByBlockID(ctx context.Context, blockID flow.Identifier) (flow.RegisterEntries, bool, error) +} + +const DefaultHeightsPerSecond = 0 // 0 means no rate limiting by default +const MaxHeightsPerSecond = 1_000_000 // hard cap to prevent ineffective rate limiting + +// BackgroundIndexer indexes register updates for finalized and executed blocks. +// It is passive and runs only when triggered by the BackgroundIndexerEngine. +type BackgroundIndexer struct { + log zerolog.Logger + registerStore execution.RegisterStore // write register updates to database + provider RegisterUpdatesProvider // read register updates for each block + state protocol.State // read last finalized height for iteration + headers storage.Headers // read block headers by height, header is needed to store registers + heightsPerSecond uint64 // rate limit for indexing heights per second +} + +func NewBackgroundIndexer( + log zerolog.Logger, + provider RegisterUpdatesProvider, + registerStore execution.RegisterStore, + state protocol.State, + headers storage.Headers, + heightsPerSecond uint64, +) *BackgroundIndexer { + // Cap heightsPerSecond to prevent ineffective rate limiting + if heightsPerSecond > MaxHeightsPerSecond { + heightsPerSecond = MaxHeightsPerSecond + } + + return &BackgroundIndexer{ + log: log.With().Str("component", "background_indexer").Logger(), + provider: provider, + registerStore: registerStore, + state: state, + headers: headers, + heightsPerSecond: heightsPerSecond, + } +} + +// IndexUpToLatestFinalizedAndExecutedHeight indexes register updates for each finalized +// and executed block, starting from the last indexed height up to the latest finalized and +// executed height. +func (b *BackgroundIndexer) IndexUpToLatestFinalizedAndExecutedHeight(ctx context.Context) error { + lastIndexedHeight := b.registerStore.LastFinalizedAndExecutedHeight() + latestFinalized, err := b.state.Final().Head() + if err != nil { + return fmt.Errorf("failed to get latest finalized height: %w", err) + } + + b.log.Debug(). + Uint64("last_indexed_height", lastIndexedHeight). + Uint64("latest_finalized_height", latestFinalized.Height). + Uint64("heights_per_second", b.heightsPerSecond). + Msg("indexing registers up to latest finalized and executed height") + + // Calculate sleep duration per height if rate limiting is enabled + var sleepDuration time.Duration + if b.heightsPerSecond > 0 { + sleepDuration = time.Second / time.Duration(b.heightsPerSecond) + } + + // Loop through each unindexed finalized height, fetch register updates and store them + for h := lastIndexedHeight + 1; h <= latestFinalized.Height; h++ { + // Check context cancellation before processing each height + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + header, err := b.headers.ByHeight(h) + if err != nil { + return fmt.Errorf("failed to get header for height %d: %w", h, err) + } + + // Get register entries for this height + registerEntries, executed, err := b.provider.RegisterUpdatesByBlockID(ctx, header.ID()) + if err != nil { + return fmt.Errorf("failed to get register entries for height %d: %w", h, err) + } + + if !executed { + // if the finalized block has not been executed, then we finish indexing, + // as we have finished indexing all executed blocks up to this point. + // in happy case, all finalized blocks should have been executed. + // this might happen when the execution node is catching up or during HCU. + return nil + } + + // Store registers directly to disk store + err = b.registerStore.SaveRegisters(header, registerEntries) + if err != nil { + return fmt.Errorf("failed to store registers for height %d: %w", h, err) + } + + // Throttle indexing rate if configured + if b.heightsPerSecond > 0 && h < latestFinalized.Height { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(sleepDuration): + // Continue to next iteration + } + } + } + + return nil +} diff --git a/engine/execution/storehouse/background_indexer_engine.go b/engine/execution/storehouse/background_indexer_engine.go new file mode 100644 index 00000000000..4b421185739 --- /dev/null +++ b/engine/execution/storehouse/background_indexer_engine.go @@ -0,0 +1,126 @@ +package storehouse + +import ( + "context" + "errors" + "fmt" + "io" + + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/notifications/pubsub" + "github.com/onflow/flow-go/engine" + "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/module/irrecoverable" +) + +// BackgroundIndexerEngine indexes register updates to storehouse for each executed and finalized blocks. +// "background" means that it runs in a separate worker loop and does not block the startup or the block +// execution. +type BackgroundIndexerEngine struct { + component.Component + log zerolog.Logger + // since the indexer indexes for executed and finalized blocks, + // we use a combined notifier to listen for the events and trigger the indexing. + newBlockExecutedOrFinalized engine.Notifier + // initializes the register store database by importing the root checkpoint, + // which is then used to create the background indexer. + bootstrapper func(ctx context.Context) (*BackgroundIndexer, io.Closer, error) +} + +// newFinalizedAndExecutedNotifier creates a notifier that notifies when either a block is executed or finalized. +func newFinalizedAndExecutedNotifier( + blockExecutedNotifier BlockExecutedNotifier, + followerDistributor *pubsub.FollowerDistributor, +) engine.Notifier { + notifier := engine.NewNotifier() + + blockExecutedNotifier.AddConsumer(func() { + notifier.Notify() + }) + + // Subscribe to block finalized events from the follower distributor + followerDistributor.AddOnBlockFinalizedConsumer(func(_ *model.Block) { + notifier.Notify() + }) + + return notifier +} + +// NewBackgroundIndexerEngine creates a new BackgroundIndexerEngine. +func NewBackgroundIndexerEngine( + log zerolog.Logger, + bootstrapper func(ctx context.Context) (*BackgroundIndexer, io.Closer, error), + blockExecutedNotifier BlockExecutedNotifier, + followerDistributor *pubsub.FollowerDistributor, +) *BackgroundIndexerEngine { + // blockExecutedNotifier notifies when a block is executed + // followerDistributor notifies when a block is finalized + // we combine both notifiers to trigger indexing on either event + finalizedOrExecutedNotifier := newFinalizedAndExecutedNotifier(blockExecutedNotifier, followerDistributor) + + b := &BackgroundIndexerEngine{ + log: log, + bootstrapper: bootstrapper, + newBlockExecutedOrFinalized: finalizedOrExecutedNotifier, + } + + // Initialize the notifier so that even if no new data comes in, + // the worker loop can still be triggered to process any existing data. + finalizedOrExecutedNotifier.Notify() + + // Build component manager with worker loop + cm := component.NewComponentManagerBuilder(). + AddWorker(b.workerLoop). + Build() + + b.Component = cm + return b +} + +// The background indexer engine runs worker loop to kick off the bootstrapping process, +// then listens for new executed or finalized blocks to trigger indexing. +func (b *BackgroundIndexerEngine) workerLoop(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { + ready() + + b.log.Info().Msg("bootstrapping register store in background") + + backgroundIndexer, closer, err := b.bootstrapper(ctx) + if err != nil { + ctx.Throw(fmt.Errorf("failed to bootstrap background indexer: %w", err)) + return + } + // ensure the register store database is closed when the worker loop exits + defer func() { + if err := closer.Close(); err != nil { + b.log.Error().Err(err).Msg("failed to close register store database") + } + }() + + b.log.Info().Msg("bootstrapping completed, starting background indexer worker loop") + + for { + select { + case <-ctx.Done(): + return + case <-b.newBlockExecutedOrFinalized.Channel(): + // the background indexer is + err := backgroundIndexer.IndexUpToLatestFinalizedAndExecutedHeight(ctx) + if err != nil { + // If the error is context.Canceled and the parent context is also done, + // it's likely due to termination/shutdown, so handle gracefully. + // Otherwise, throw the error as it indicates a real problem. + // TODO (leo): extract into a reusable function + if errors.Is(err, context.Canceled) && ctx.Err() != nil { + // Cancellation due to termination - handle gracefully + b.log.Warn().Msg("background indexer worker loop terminating due to context cancellation") + return + } + // All other errors (including unexpected cancellations) should be thrown + ctx.Throw(fmt.Errorf("background indexer failed to index up to latest finalized and executed height: %w", err)) + return + } + } + } +} diff --git a/engine/execution/storehouse/background_indexer_factory.go b/engine/execution/storehouse/background_indexer_factory.go new file mode 100644 index 00000000000..69fe85ed81e --- /dev/null +++ b/engine/execution/storehouse/background_indexer_factory.go @@ -0,0 +1,229 @@ +// The factory provides functions for the execution_builder to load and initialize +// the register store and background indexer engine, simplifying the builder by +// encapsulating database setup, bootstrapping, and checkpoint import logic. +package storehouse + +import ( + "context" + "fmt" + "io" + "path" + + "github.com/cockroachdb/pebble/v2" + "github.com/hashicorp/go-multierror" + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/consensus/hotstuff/notifications/pubsub" + "github.com/onflow/flow-go/ledger" + modelbootstrap "github.com/onflow/flow-go/model/bootstrap" + "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/finalizedreader" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/state/protocol/events" + storageerr "github.com/onflow/flow-go/storage" + storagepebble "github.com/onflow/flow-go/storage/pebble" +) + +// BlockExecutedNotifier is an interface for components that can register callbacks +// to be notified when blocks are executed. +type BlockExecutedNotifier interface { + AddConsumer(callback func()) +} + +// ImportRegistersFromCheckpoint imports registers from a checkpoint file. +// It is defined as a function type to avoid a circular dependency; the +// implementation (bootstrap.ImportRegistersFromCheckpoint) is provided by the caller. +type ImportRegistersFromCheckpoint func(logger zerolog.Logger, checkpointFile string, checkpointHeight uint64, checkpointRootHash ledger.RootHash, pdb *pebble.DB, workerCount int) error + +// LoadRegisterStore creates and initializes a RegisterStore. +// It handles opening the pebble database, bootstrapping if needed, and creating the RegisterStore. +func LoadRegisterStore( + log zerolog.Logger, + state protocol.State, + headers storageerr.Headers, + protocolEvents *events.Distributor, + lastFinalizedHeight uint64, + collector module.ExecutionMetrics, + registerDir string, + triedir string, + importCheckpointWorkerCount int, + importFunc ImportRegistersFromCheckpoint, +) ( + *RegisterStore, + io.Closer, + error, +) { + log.Info(). + Str("pebble_db_path", registerDir). + Msg("register store enabled") + + pebbledb, err := storagepebble.OpenRegisterPebbleDB( + log.With().Str("pebbledb", "registers").Logger(), + registerDir) + + if err != nil { + return nil, nil, fmt.Errorf("could not create disk register store: %w", err) + } + + // wrap the pebble db with a struct to include detailed error message + closer := &pebbleDBCloser{db: pebbledb} + + bootstrapped, err := storagepebble.IsBootstrapped(pebbledb) + if err != nil { + originalErr := fmt.Errorf("could not check if registers db is bootstrapped: %w", err) + return nil, nil, multierror.Append(originalErr, closer.Close()).ErrorOrNil() + } + + log.Info().Msgf("register store bootstrapped: %v", bootstrapped) + + if !bootstrapped { + checkpointFile := path.Join(triedir, modelbootstrap.FilenameWALRootCheckpoint) + sealedRoot := state.Params().SealedRoot() + + rootSeal := state.Params().Seal() + + if sealedRoot.ID() != rootSeal.BlockID { + originalErr := fmt.Errorf("mismatching root seal and sealed root: %v != %v", sealedRoot.ID(), rootSeal.BlockID) + return nil, nil, multierror.Append(originalErr, closer.Close()).ErrorOrNil() + } + + checkpointHeight := sealedRoot.Height + rootHash := ledger.RootHash(rootSeal.FinalState) + + err = importFunc(log.With().Str("component", "background-indexing").Logger(), + checkpointFile, checkpointHeight, rootHash, pebbledb, importCheckpointWorkerCount) + if err != nil { + originalErr := fmt.Errorf("could not import registers from checkpoint: %w", err) + return nil, nil, multierror.Append(originalErr, closer.Close()).ErrorOrNil() + } + } + + diskStore, err := storagepebble.NewRegisters(pebbledb, storagepebble.PruningDisabled) + if err != nil { + originalErr := fmt.Errorf("could not create registers storage: %w", err) + return nil, nil, multierror.Append(originalErr, closer.Close()).ErrorOrNil() + } + + reader := finalizedreader.NewFinalizedReader(headers, lastFinalizedHeight) + protocolEvents.AddConsumer(reader) + notifier := NewRegisterStoreMetrics(collector) + + // report latest finalized and executed height as metrics + notifier.OnFinalizedAndExecutedHeightUpdated(diskStore.LatestHeight()) + + registerStore, err := NewRegisterStore( + diskStore, + nil, // TODO(leo): replace with real WAL in storehouse phase 4 + reader, + log, + notifier, + ) + if err != nil { + return nil, nil, multierror.Append(err, closer.Close()).ErrorOrNil() + } + + return registerStore, closer, nil +} + +// LoadBackgroundIndexerEngine creates and initializes a BackgroundIndexerEngine. +func LoadBackgroundIndexerEngine( + log zerolog.Logger, + enableBackgroundStorehouseIndexing bool, + state protocol.State, + headers storageerr.Headers, + protocolEvents *events.Distributor, + lastFinalizedHeight uint64, + collector module.ExecutionMetrics, + registerDir string, + triedir string, + importCheckpointWorkerCount int, + importFunc ImportRegistersFromCheckpoint, + executionDataStore execution_data.ExecutionDataGetter, + resultsReader storageerr.ExecutionResultsReader, + blockExecutedNotifier BlockExecutedNotifier, // optional: notifier for block executed events + followerDistributor *pubsub.FollowerDistributor, + heightsPerSecond uint64, // rate limit for indexing heights per second +) (*BackgroundIndexerEngine, bool, error) { + + lg := log.With().Str("component", "background_indexer_loader").Logger() + + if !enableBackgroundStorehouseIndexing { + lg.Info().Msg("background indexer engine disabled, since --enable-background-storehouse-indexing==false") + return nil, false, nil + } + + lg.Info().Msg("background indexer engine enabled") + + // Check that required dependencies are available + if executionDataStore == nil { + return nil, false, fmt.Errorf("execution data store is not initialized") + } + if resultsReader == nil { + return nil, false, fmt.Errorf("execution results reader is not initialized") + } + + // bootstrapper function allows deferred initialization of register store + // and the initial indexing work, so that it happens within the engine's worker loop + // and not block the component initialization + bootstrapper := func(ctx context.Context) (*BackgroundIndexer, io.Closer, error) { + // Load register store for background indexing + registerStore, closer, err := LoadRegisterStore( + log, + state, + headers, + protocolEvents, + lastFinalizedHeight, + collector, + registerDir, + triedir, + importCheckpointWorkerCount, + importFunc, + ) + if err != nil { + return nil, nil, fmt.Errorf("failed to load register store: %w", err) + } + + // Create the register updates provider + provider := NewExecutionDataRegisterUpdatesProvider( + executionDataStore, + resultsReader, + ) + + // Create the background indexer + backgroundIndexer := NewBackgroundIndexer( + log, + provider, + registerStore, + state, + headers, + heightsPerSecond, + ) + + return backgroundIndexer, closer, nil + } + + // Create the background indexer engine + backgroundIndexerEngine := NewBackgroundIndexerEngine( + log, + bootstrapper, + blockExecutedNotifier, + followerDistributor, + ) + + return backgroundIndexerEngine, true, nil +} + +type pebbleDBCloser struct { + db *pebble.DB +} + +var _ io.Closer = (*pebbleDBCloser)(nil) + +func (c *pebbleDBCloser) Close() error { + err := c.db.Close() + if err != nil { + return fmt.Errorf("could not close register store: %w", err) + } + return nil +} diff --git a/engine/execution/storehouse/background_indexer_factory_test.go b/engine/execution/storehouse/background_indexer_factory_test.go new file mode 100644 index 00000000000..506ae6513af --- /dev/null +++ b/engine/execution/storehouse/background_indexer_factory_test.go @@ -0,0 +1,595 @@ +package storehouse_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/ipfs/go-datastore" + dssync "github.com/ipfs/go-datastore/sync" + "github.com/stretchr/testify/require" + + "github.com/cockroachdb/pebble/v2" + "github.com/rs/zerolog" + "github.com/stretchr/testify/mock" + + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/notifications/pubsub" + "github.com/onflow/flow-go/engine/execution/ingestion" + "github.com/onflow/flow-go/engine/execution/storehouse" + "github.com/onflow/flow-go/ledger" + ledgerconvert "github.com/onflow/flow-go/ledger/common/convert" + "github.com/onflow/flow-go/ledger/common/pathfinder" + ledgercomplete "github.com/onflow/flow-go/ledger/complete" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/blobs" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/metrics" + modulemock "github.com/onflow/flow-go/module/mock" + "github.com/onflow/flow-go/state/protocol/events" + protocolmock "github.com/onflow/flow-go/state/protocol/mock" + storagemock "github.com/onflow/flow-go/storage/mock" + storagepebble "github.com/onflow/flow-go/storage/pebble" + "github.com/onflow/flow-go/utils/unittest" +) + +// TestLoadBackgroundIndexerEngine_StorehouseEnabled tests that LoadBackgroundIndexerEngine returns nil when enableStorehouse is true +func TestLoadBackgroundIndexerEngine_StorehouseEnabled(t *testing.T) { + t.Parallel() + + log := unittest.Logger() + enableBackgroundStorehouseIndexing := true + state := protocolmock.NewState(t) + headers := storagemock.NewHeaders(t) + protocolEvents := events.NewDistributor() + lastFinalizedHeight := uint64(100) + collector := &metrics.NoopCollector{} + registerDir := t.TempDir() + triedir := t.TempDir() + importCheckpointWorkerCount := 1 + var importFunc storehouse.ImportRegistersFromCheckpoint = nil + // Set up execution data store (required when indexing is enabled) + bs := blobs.NewBlobstore(dssync.MutexWrap(datastore.NewMapDatastore())) + executionDataStore := execution_data.NewExecutionDataStore(bs, execution_data.DefaultSerializer) + resultsReader := storagemock.NewExecutionResults(t) + blockExecutedNotifier := ingestion.NewBlockExecutedNotifier() + followerDistributor := pubsub.NewFollowerDistributor() + heightsPerSecond := uint64(10) + engine, created, err := storehouse.LoadBackgroundIndexerEngine( + log, + enableBackgroundStorehouseIndexing, + state, + headers, + protocolEvents, + lastFinalizedHeight, + collector, + registerDir, + triedir, + importCheckpointWorkerCount, + importFunc, + executionDataStore, + resultsReader, + blockExecutedNotifier, + followerDistributor, + heightsPerSecond, + ) + + require.NoError(t, err) + require.NotNil(t, engine) + require.True(t, created) +} + +// TestLoadBackgroundIndexerEngine_BackgroundIndexingDisabled tests that LoadBackgroundIndexerEngine returns nil when enableBackgroundStorehouseIndexing is false +func TestLoadBackgroundIndexerEngine_BackgroundIndexingDisabled(t *testing.T) { + t.Parallel() + + log := unittest.Logger() + enableBackgroundStorehouseIndexing := false + state := protocolmock.NewState(t) + headers := storagemock.NewHeaders(t) + protocolEvents := events.NewDistributor() + lastFinalizedHeight := uint64(100) + collector := &metrics.NoopCollector{} + registerDir := t.TempDir() + triedir := t.TempDir() + importCheckpointWorkerCount := 1 + var importFunc storehouse.ImportRegistersFromCheckpoint = nil + var executionDataStore execution_data.ExecutionDataGetter = nil + resultsReader := storagemock.NewExecutionResults(t) + blockExecutedNotifier := ingestion.NewBlockExecutedNotifier() + followerDistributor := pubsub.NewFollowerDistributor() + heightsPerSecond := uint64(10) + engine, created, err := storehouse.LoadBackgroundIndexerEngine( + log, + enableBackgroundStorehouseIndexing, + state, + headers, + protocolEvents, + lastFinalizedHeight, + collector, + registerDir, + triedir, + importCheckpointWorkerCount, + importFunc, + executionDataStore, + resultsReader, + blockExecutedNotifier, + followerDistributor, + heightsPerSecond, + ) + + require.NoError(t, err) + require.Nil(t, engine) + require.False(t, created) +} + +// TestLoadBackgroundIndexerEngine_Bootstrap tests the happy case where the background indexer engine +// bootstraps by importing the checkpoint and then stops, notifying metrics about the last saved height +func TestLoadBackgroundIndexerEngine_Bootstrap(t *testing.T) { + t.Parallel() + + const ( + startHeight = 100 + registerStoreStart = 100 + ) + + log := unittest.Logger() + enableBackgroundStorehouseIndexing := true + + // Set up protocol state with finalized blocks + state := protocolmock.NewState(t) + finalSnapshot := protocolmock.NewSnapshot(t) + params := protocolmock.NewParams(t) + sealedRoot := unittest.BlockHeaderFixture() + sealedRoot.Height = startHeight + seal := unittest.Seal.Fixture() + seal.BlockID = sealedRoot.ID() + params.On("SealedRoot").Return(sealedRoot).Maybe() + params.On("Seal").Return(seal).Maybe() + state.On("Final").Return(finalSnapshot).Maybe() + state.On("Params").Return(params).Maybe() + + // Create headers storage + headers := storagemock.NewHeaders(t) + // Mock BlockIDByHeight for the finalized reader initialization + // The finalized reader calls this during initialization to check the last finalized height + parentBlockID := sealedRoot.ID() + headers.On("BlockIDByHeight", uint64(startHeight)).Return(parentBlockID, nil).Maybe() + + // Mock Head() for the indexer - it may be called when trying to index additional blocks + // We'll stop the engine before it actually indexes, but the call might happen + initialFinalHeader := unittest.BlockHeaderFixture() + initialFinalHeader.Height = startHeight + finalSnapshot.On("Head").Return(initialFinalHeader, nil).Maybe() + + protocolEvents := events.NewDistributor() + lastFinalizedHeight := uint64(startHeight) + + // Use a mock metrics collector to detect when the checkpoint height is reported + mockMetrics := modulemock.NewExecutionMetrics(t) + checkpointHeight := uint64(registerStoreStart) + heightReached := make(chan uint64, 1) + + // Set up expectation to signal when checkpoint height is reported + // This will be called during bootstrapping when the checkpoint is imported + mockMetrics.On("ExecutionLastFinalizedExecutedBlockHeight", mock.MatchedBy(func(height uint64) bool { + log.Info().Msgf("Metrics reported finalized and executed height: %d", height) + if height == checkpointHeight { + select { + case heightReached <- height: + default: + } + return true + } + return true + })).Return().Maybe() + + collector := mockMetrics + registerDir := t.TempDir() + triedir := t.TempDir() + importCheckpointWorkerCount := 1 + // Bootstrap the register database before creating the engine + // This ensures the database is ready when the engine tries to use it + bootstrappedDB := storagepebble.NewBootstrappedRegistersWithPathForTest(t, registerDir, startHeight, startHeight) + require.NoError(t, bootstrappedDB.Close()) + + // Provide a no-op import function since database is already bootstrapped + importFunc := storehouse.ImportRegistersFromCheckpoint(func(logger zerolog.Logger, checkpointFile string, checkpointHeight uint64, checkpointRootHash ledger.RootHash, pdb *pebble.DB, workerCount int) error { + // Database is already bootstrapped, so this is a no-op + return nil + }) + + // Set up execution data store + bs := blobs.NewBlobstore(dssync.MutexWrap(datastore.NewMapDatastore())) + executionDataStore := execution_data.NewExecutionDataStore(bs, execution_data.DefaultSerializer) + + // Set up execution results reader + resultsReader := storagemock.NewExecutionResults(t) + + // Set up block executed notifier and follower distributor (required by the engine) + // These are needed even though we stop after bootstrapping + blockExecutedNotifier := ingestion.NewBlockExecutedNotifier() + followerDistributor := pubsub.NewFollowerDistributor() + heightsPerSecond := uint64(10) + + // Create background indexer engine + engine, created, err := storehouse.LoadBackgroundIndexerEngine( + log, + enableBackgroundStorehouseIndexing, + state, + headers, + protocolEvents, + lastFinalizedHeight, + collector, + registerDir, + triedir, + importCheckpointWorkerCount, + importFunc, + executionDataStore, + resultsReader, + blockExecutedNotifier, + followerDistributor, + heightsPerSecond, + ) + + require.NoError(t, err) + require.NotNil(t, engine) + require.True(t, created) + + // Start the engine + ctx, cancel := irrecoverable.NewMockSignalerContextWithCancel(t, context.Background()) + defer cancel() + + engine.Start(ctx) + unittest.RequireReturnsBefore(t, func() { + <-engine.Ready() + }, 5*time.Second, "engine should be ready") + + // Wait for bootstrapping to complete and metrics to be notified + // The bootstrapper imports the checkpoint and notifies metrics about the last saved height + // We use the metric notification as the signal to stop everything and assert + unittest.RequireReturnsBefore(t, func() { + // Wait for metrics to be notified about the last saved height from checkpoint import + // The checkpoint import happens during bootstrapping and notifies metrics + select { + case reachedHeight := <-heightReached: + // The checkpoint was imported at registerStoreStart, so metrics should report that height + require.Equal(t, uint64(registerStoreStart), reachedHeight, "expected checkpoint height %d to be reported", registerStoreStart) + // Stop the engine immediately after metrics notification (before it tries to index additional blocks) + cancel() + case <-time.After(30 * time.Second): + t.Fatal("timeout waiting for bootstrapping to complete and metrics to be notified") + } + }, 35*time.Second, "bootstrapping should complete and notify metrics") + + // Wait for the engine to fully shut down (including closing the database) + unittest.RequireReturnsBefore(t, func() { + <-engine.Done() + }, 5*time.Second, "engine should stop") + + // Wait a bit for the database to be fully closed + time.Sleep(100 * time.Millisecond) + + // Verify register store has data from checkpoint + // After the engine stops, we can load the register store and check its latest height + // The register store should have the checkpoint height from bootstrapping + registerStore, closer, err := storehouse.LoadRegisterStore( + log, + state, + headers, + protocolEvents, + registerStoreStart, + collector, + registerDir, + triedir, + importCheckpointWorkerCount, + importFunc, + ) + require.NoError(t, err) + require.NotNil(t, registerStore) + defer func() { + if closer != nil { + require.NoError(t, closer.Close()) + } + }() + + // The register store should have the checkpoint height from bootstrapping + // Since we only bootstrap (import checkpoint) and don't index additional blocks, + // the latest height should be the checkpoint height + latestHeight := registerStore.LastFinalizedAndExecutedHeight() + require.Equal(t, uint64(registerStoreStart), latestHeight, + "register store should have checkpoint height %d, but got %d", + registerStoreStart, latestHeight) +} + +// TestLoadBackgroundIndexerEngine_Indexing tests that the background indexer engine +// indexes additional finalized and executed blocks after bootstrapping +func TestLoadBackgroundIndexerEngine_Indexing(t *testing.T) { + t.Parallel() + + const ( + startHeight = 100 + registerStoreStart = 100 + numBlocks = 5 + ) + + log := unittest.Logger() + enableBackgroundStorehouseIndexing := true + + // Set up protocol state + state := protocolmock.NewState(t) + finalSnapshot := protocolmock.NewSnapshot(t) + params := protocolmock.NewParams(t) + sealedRoot := unittest.BlockHeaderFixture() + sealedRoot.Height = startHeight + seal := unittest.Seal.Fixture() + seal.BlockID = sealedRoot.ID() + params.On("SealedRoot").Return(sealedRoot).Maybe() + params.On("Seal").Return(seal).Maybe() + state.On("Final").Return(finalSnapshot).Maybe() + state.On("Params").Return(params).Maybe() + + // Create headers storage and blocks + headers := storagemock.NewHeaders(t) + parentBlockID := sealedRoot.ID() + headers.On("BlockIDByHeight", uint64(startHeight)).Return(parentBlockID, nil) + + blocks := make([]*flow.Block, numBlocks) + parentHeader := sealedRoot + for i := 0; i < numBlocks; i++ { + height := startHeight + uint64(i) + 1 + block := unittest.BlockWithParentFixture(parentHeader) + blocks[i] = block + headers.On("ByHeight", height).Return(block.ToHeader(), nil) + // Mock BlockIDByHeight for all heights - the finalized reader needs this + headers.On("BlockIDByHeight", height).Return(block.ID(), nil) + parentHeader = block.ToHeader() + } + + // Initially set finalized snapshot to return startHeight (no blocks finalized yet) + // This prevents the initial notification from trying to process blocks + initialFinalHeader := unittest.BlockHeaderFixture() + initialFinalHeader.Height = startHeight + finalSnapshot.On("Head").Return(initialFinalHeader, nil) + + protocolEvents := events.NewDistributor() + lastFinalizedHeight := uint64(startHeight) + + // Use a mock metrics collector to detect when the target height is reached + mockMetrics := modulemock.NewExecutionMetrics(t) + targetHeight := uint64(registerStoreStart + numBlocks) + heightReached := make(chan uint64, 1) + + // Set up expectation to signal when target height is reached + // Also log all metric calls to help debug + mockMetrics.On("ExecutionLastFinalizedExecutedBlockHeight", mock.AnythingOfType("uint64")).Run(func(args mock.Arguments) { + height := args.Get(0).(uint64) + log.Info().Msgf("Metrics reported finalized and executed height: %d (target: %d)", height, targetHeight) + if height >= targetHeight { + select { + case heightReached <- height: + default: + } + } + }).Return() + + collector := mockMetrics + registerDir := t.TempDir() + triedir := t.TempDir() + importCheckpointWorkerCount := 1 + + // Bootstrap the register database + bootstrappedDB := storagepebble.NewBootstrappedRegistersWithPathForTest(t, registerDir, startHeight, startHeight) + require.NoError(t, bootstrappedDB.Close()) + + // Provide a no-op import function since database is already bootstrapped + importFunc := storehouse.ImportRegistersFromCheckpoint(func(logger zerolog.Logger, checkpointFile string, checkpointHeight uint64, checkpointRootHash ledger.RootHash, pdb *pebble.DB, workerCount int) error { + return nil + }) + + // Set up execution data store + bs := blobs.NewBlobstore(dssync.MutexWrap(datastore.NewMapDatastore())) + executionDataStore := execution_data.NewExecutionDataStore(bs, execution_data.DefaultSerializer) + + // Set up execution results reader + resultsReader := storagemock.NewExecutionResults(t) + + // Create execution data and results for all blocks + for i := 0; i < numBlocks; i++ { + block := blocks[i] + + // Create valid register entries and convert to trie update + registerEntries := flow.RegisterEntries{ + { + Key: flow.RegisterID{ + Owner: "owner", + Key: fmt.Sprintf("key%d", i), + }, + Value: []byte(fmt.Sprintf("value%d", i)), + }, + } + + // Convert register entries to ledger keys and values + keys := make([]ledger.Key, 0, len(registerEntries)) + values := make([]ledger.Value, 0, len(registerEntries)) + for _, entry := range registerEntries { + key := ledgerconvert.RegisterIDToLedgerKey(entry.Key) + keys = append(keys, key) + values = append(values, entry.Value) + } + + // Create trie update from keys and values + update, err := ledger.NewUpdate(ledger.DummyState, keys, values) + require.NoError(t, err) + trieUpdate, err := pathfinder.UpdateToTrieUpdate(update, ledgercomplete.DefaultPathFinderVersion) + require.NoError(t, err) + + chunkData := unittest.ChunkExecutionDataFixture(t, 100, unittest.WithTrieUpdate(trieUpdate)) + execData := unittest.BlockExecutionDataFixture( + unittest.WithBlockExecutionDataBlockID(block.ID()), + unittest.WithChunkExecutionDatas(chunkData), + ) + + // Add execution data to store + executionDataID, err := executionDataStore.Add(context.Background(), execData) + require.NoError(t, err) + + // Verify the execution data can be retrieved + retrievedData, err := executionDataStore.Get(context.Background(), executionDataID) + require.NoError(t, err) + require.NotNil(t, retrievedData) + + // Create execution result + result := unittest.ExecutionResultFixture( + unittest.WithBlock(block), + ) + result.ExecutionDataID = executionDataID + + // Set up mock to return execution result + // Use mock.MatchedBy to match any block ID for this block's height + resultsReader.On("ByBlockID", mock.MatchedBy(func(blockID flow.Identifier) bool { + return blockID == block.ID() + })).Return(result, nil).Maybe() + } + + // Set up block executed notifier and follower distributor + blockExecutedNotifier := ingestion.NewBlockExecutedNotifier() + followerDistributor := pubsub.NewFollowerDistributor() + heightsPerSecond := uint64(10) + + // Create background indexer engine + engine, created, err := storehouse.LoadBackgroundIndexerEngine( + log, + enableBackgroundStorehouseIndexing, + state, + headers, + protocolEvents, + lastFinalizedHeight, + collector, + registerDir, + triedir, + importCheckpointWorkerCount, + importFunc, + executionDataStore, + resultsReader, + blockExecutedNotifier, + followerDistributor, + heightsPerSecond, + ) + + require.NoError(t, err) + require.NotNil(t, engine) + require.True(t, created) + + // Start the engine + ctx, cancel := irrecoverable.NewMockSignalerContextWithCancel(t, context.Background()) + defer cancel() + + engine.Start(ctx) + unittest.RequireReturnsBefore(t, func() { + <-engine.Ready() + }, 5*time.Second, "engine should be ready") + + // Finalize blocks one by one and wait for each to propagate + // The finalized reader subscribes to protocolEvents during bootstrapping, so it will receive these events + // We need to finalize them sequentially so the finalized reader's lastHeight is updated correctly + // The FinalizedReader's BlockFinalized method is called synchronously, so we don't need long waits + for i := 0; i < numBlocks; i++ { + block := blocks[i] + protocolEvents.BlockFinalized(block.ToHeader()) + // Small wait to ensure the event is processed + time.Sleep(50 * time.Millisecond) + } + + // Wait a bit for any async processing + time.Sleep(500 * time.Millisecond) + + // Update finalized snapshot to return the last finalized block AFTER finalizing + // This allows the background indexer to know which blocks are finalized + // Remove the previous mock and set a new one that returns height 105 + finalizedBlock := blocks[numBlocks-1] + finalSnapshot.ExpectedCalls = nil // Clear previous expectations + finalSnapshot.On("Head").Return(finalizedBlock.ToHeader(), nil) + + // Notify the follower distributor to trigger the background indexer + for i := 0; i < numBlocks; i++ { + block := blocks[i] + hotstuffBlock := &model.Block{ + BlockID: block.ID(), + View: block.ToHeader().View, + ProposerID: unittest.IdentifierFixture(), + } + followerDistributor.OnFinalizedBlock(hotstuffBlock) + } + + // Wait for finalization events to propagate + time.Sleep(500 * time.Millisecond) + + // Notify that blocks were executed (this triggers indexing) + // The background indexer will process all finalized and executed blocks sequentially + // We may need to trigger multiple times as blocks get processed + for attempt := 0; attempt < 10; attempt++ { + blockExecutedNotifier.OnExecuted() + time.Sleep(200 * time.Millisecond) + + // Check if we've reached the target height + select { + case reachedHeight := <-heightReached: + require.Equal(t, targetHeight, reachedHeight, "expected target height %d to be reached", targetHeight) + goto indexingComplete + default: + // Continue trying + } + } + + // Final attempt - wait for the target height to be reached + unittest.RequireReturnsBefore(t, func() { + select { + case reachedHeight := <-heightReached: + require.Equal(t, targetHeight, reachedHeight, "expected target height %d to be reached", targetHeight) + case <-time.After(30 * time.Second): + t.Fatal("timeout waiting for target height to be reached") + } + }, 35*time.Second, "all blocks should be indexed and metrics notified") + +indexingComplete: + + // Stop the engine + cancel() + unittest.RequireReturnsBefore(t, func() { + <-engine.Done() + }, 5*time.Second, "engine should stop") + + // Wait a bit for the database to be fully closed + time.Sleep(100 * time.Millisecond) + + // Verify register store has indexed all blocks + // Initialize with the target height so the FinalizedReader knows about all finalized blocks + registerStore, closer, err := storehouse.LoadRegisterStore( + log, + state, + headers, + protocolEvents, + targetHeight, // Use targetHeight instead of registerStoreStart so FinalizedReader knows about all blocks + collector, + registerDir, + triedir, + importCheckpointWorkerCount, + importFunc, + ) + require.NoError(t, err) + require.NotNil(t, registerStore) + defer func() { + if closer != nil { + require.NoError(t, closer.Close()) + } + }() + + // The register store should have indexed up to the target height + latestHeight := registerStore.LastFinalizedAndExecutedHeight() + require.GreaterOrEqual(t, latestHeight, targetHeight, + "register store should have indexed at least %d heights (from %d to %d), but got %d", + numBlocks, registerStoreStart+1, targetHeight, latestHeight) +} diff --git a/engine/execution/storehouse/background_indexer_provider.go b/engine/execution/storehouse/background_indexer_provider.go new file mode 100644 index 00000000000..360dcc1e718 --- /dev/null +++ b/engine/execution/storehouse/background_indexer_provider.go @@ -0,0 +1,86 @@ +package storehouse + +import ( + "context" + "errors" + "fmt" + + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger/common/convert" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/storage" +) + +type ExecutionDataRegisterUpdatesProvider struct { + dataStore execution_data.ExecutionDataGetter + results storage.ExecutionResultsReader +} + +var _ RegisterUpdatesProvider = (*ExecutionDataRegisterUpdatesProvider)(nil) + +func NewExecutionDataRegisterUpdatesProvider( + dataStore execution_data.ExecutionDataGetter, + results storage.ExecutionResultsReader, +) *ExecutionDataRegisterUpdatesProvider { + return &ExecutionDataRegisterUpdatesProvider{ + dataStore: dataStore, + results: results, + } +} + +func (p *ExecutionDataRegisterUpdatesProvider) RegisterUpdatesByBlockID(ctx context.Context, blockID flow.Identifier) (flow.RegisterEntries, bool, error) { + result, err := p.results.ByBlockID(blockID) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + // No execution result for this block + return nil, false, nil + } + + return nil, false, fmt.Errorf("failed to get execution result for block %v: %w", blockID, err) + } + + data, err := p.dataStore.Get(ctx, result.ExecutionDataID) + if err != nil { + return nil, false, fmt.Errorf("failed to get execution data %v: %w", result.ExecutionDataID, err) + } + + // Collect register updates from all chunks + // Use a map to track the last update for each path (since there can be multiple + // updates to the same path within a block, we only persist the last one) + registerUpdates := make(map[ledger.Path]*ledger.Payload) + + for _, chunk := range data.ChunkExecutionDatas { + // Collect register updates from this chunk + if chunk.TrieUpdate == nil { + continue + } + + // Sanity check: there must be a one-to-one mapping between paths and payloads + if len(chunk.TrieUpdate.Paths) != len(chunk.TrieUpdate.Payloads) { + return nil, false, fmt.Errorf("number of ledger paths (%d) does not match number of ledger payloads (%d)", + len(chunk.TrieUpdate.Paths), len(chunk.TrieUpdate.Payloads)) + } + + // Collect registers (last update for a path within the block is persisted) + for i, path := range chunk.TrieUpdate.Paths { + registerUpdates[path] = chunk.TrieUpdate.Payloads[i] + } + } + + // Convert final payloads to register entries + registerEntries := make(flow.RegisterEntries, 0, len(registerUpdates)) + for path, payload := range registerUpdates { + key, value, err := convert.PayloadToRegister(payload) + if err != nil { + return nil, false, fmt.Errorf("failed to convert payload to register entry (path: %s): %w", path.String(), err) + } + + registerEntries = append(registerEntries, flow.RegisterEntry{ + Key: key, + Value: value, + }) + } + + return registerEntries, true, nil +} diff --git a/engine/execution/storehouse/checkpoint_validator.go b/engine/execution/storehouse/checkpoint_validator.go new file mode 100644 index 00000000000..99534fadacc --- /dev/null +++ b/engine/execution/storehouse/checkpoint_validator.go @@ -0,0 +1,202 @@ +package storehouse + +import ( + "bytes" + "context" + "errors" + "fmt" + "sync/atomic" + "time" + + "github.com/rs/zerolog" + "golang.org/x/sync/errgroup" + + "github.com/onflow/flow-go/engine/execution" + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger/common/convert" + "github.com/onflow/flow-go/ledger/complete/wal" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// ErrMismatch represents a register value mismatch error with details about the mismatch. +type ErrMismatch struct { + RegisterID flow.RegisterID + Height uint64 + StoredLength int + ExpectedLength int + StoredData []byte + ExpectedData []byte + Message string +} + +func (e *ErrMismatch) Error() string { + msg := "register value mismatch" + if e.Message != "" { + msg = e.Message + } + return fmt.Sprintf("%s: owner=%x, key=%x, height=%d, stored_length=%d, expected_length=%d", + msg, e.RegisterID.Owner, e.RegisterID.Key, e.Height, e.StoredLength, e.ExpectedLength) +} + +// IsErrMismatch returns true if the given error is an ErrMismatch or wraps an ErrMismatch. +func IsErrMismatch(err error) (*ErrMismatch, bool) { + var mismatchErr *ErrMismatch + isErr := errors.As(err, &mismatchErr) + return mismatchErr, isErr +} + +// ValidateWithCheckpoint validates the registers in the given store against the leaf nodes read from the checkpoint file. +// Limitation: the validation can not cover if there are extra non-empty registers in the store that are not in the checkpoint file. +func ValidateWithCheckpoint( + log zerolog.Logger, + ctx context.Context, + store execution.OnDiskRegisterStore, + results storage.ExecutionResults, + headers storage.Headers, + checkpointDir string, // checkpointDir must have a root.checkpoint file that contains only a single trie + blockHeight uint64, + workerCount int, +) error { + // used by the wal reader to send leaf nodes read from checkpoint file + // used by N workers to validate registers in store + leafNodeChan := make(chan *wal.LeafNode, 1000) + + // get rootHash before creating goroutines since we need a valid rootHash to validate registers + rootHash, err := rootHashByHeight(results, headers, blockHeight) + if err != nil { + return err + } + + // create N workers to validate registers in store + cct, cancel := context.WithCancel(ctx) + defer cancel() + + g, gCtx := errgroup.WithContext(cct) + + // track total number of mismatch errors across all workers + var mismatchErrorCount atomic.Int64 + + start := time.Now() + log.Info().Msgf("validation registers from checkpoint with %v worker", workerCount) + for i := 0; i < workerCount; i++ { + g.Go(func() error { + return validatingRegisterInStore(gCtx, log, store, leafNodeChan, blockHeight, &mismatchErrorCount) + }) + } + + // read leaf nodes from checkpoint file and send to leafNodeChan + err = wal.OpenAndReadLeafNodesFromCheckpointV6(leafNodeChan, checkpointDir, "root.checkpoint", rootHash, log) + if err != nil { + return fmt.Errorf("error reading leaf node from checkpoint: %w", err) + } + + if err = g.Wait(); err != nil { + return fmt.Errorf("failed to validate registers from checkpoint file: %w", err) + } + + totalMismatches := mismatchErrorCount.Load() + if totalMismatches > 0 { + return fmt.Errorf("validation failed: found %d register value mismatches", totalMismatches) + } + + log.Info().Msgf("finished validating registers from checkpoint in %s, no mismatch found", time.Since(start)) + return nil +} + +func rootHashByHeight(results storage.ExecutionResults, headers storage.Headers, height uint64) (ledger.RootHash, error) { + blockID, err := headers.BlockIDByHeight(height) + if err != nil { + return ledger.RootHash{}, fmt.Errorf("could not get block ID at height %d: %w", height, err) + } + + result, err := results.ByBlockID(blockID) + if err != nil { + return ledger.RootHash{}, fmt.Errorf("could not get execution result for block ID %s: %w", blockID, err) + } + + commit, err := result.FinalStateCommitment() + if err != nil { + return ledger.RootHash{}, fmt.Errorf("could not get final state commitment for block ID %s: %w", blockID, err) + } + + return ledger.RootHash(commit), nil +} + +func validatingRegisterInStore(ctx context.Context, log zerolog.Logger, store execution.OnDiskRegisterStore, leafNodeChan chan *wal.LeafNode, height uint64, mismatchErrorCount *atomic.Int64) error { + for { + select { + case <-ctx.Done(): + return ctx.Err() + case leafNode, ok := <-leafNodeChan: + if !ok { + return nil + } + err := validateRegister(store, leafNode, height) + if err != nil { + mismatchErr, ok := IsErrMismatch(err) + if ok { + // mismatch error: log and continue, increment counter + log.Error().Msg(mismatchErr.Error()) + mismatchErrorCount.Add(1) + } else { + // non-mismatch error: this is an exception, crash the process + return fmt.Errorf("exception when validating register: %w", err) + } + } + } + } +} + +// validateRegister checks if the register store has the same register as the leaf node. +// It follows the same pattern as batchIndexRegisters but validates instead of indexing. +// Returns ErrMismatch for value mismatches, or other errors for exceptions. +func validateRegister(store execution.OnDiskRegisterStore, leafNode *wal.LeafNode, height uint64) error { + payload := leafNode.Payload + key, err := payload.Key() + if err != nil { + return fmt.Errorf("could not get key from register payload: %w", err) + } + + registerID, err := convert.LedgerKeyToRegisterID(key) + if err != nil { + return fmt.Errorf("could not get register ID from key: %w", err) + } + + // Get the expected value from the leaf node payload + expectedValue := payload.Value() + + // Get the register value from the store at the given height + storedValue, err := store.Get(registerID, height) + if err != nil { + if err == storage.ErrNotFound { + // register not found is a mismatch error (expected register missing) + return &ErrMismatch{ + RegisterID: registerID, + Height: height, + StoredLength: 0, + ExpectedLength: len(expectedValue), + StoredData: nil, + ExpectedData: expectedValue, + Message: "register not found in store", + } + } + // other store errors are exceptions + return fmt.Errorf("failed to get register from store: owner=%s, key=%s, height=%d: %w", registerID.Owner, registerID.Key, height, err) + } + + // Compare the stored value with the expected value + if !bytes.Equal(storedValue, expectedValue) { + // value mismatch is a mismatch error + return &ErrMismatch{ + RegisterID: registerID, + Height: height, + StoredLength: len(storedValue), + ExpectedLength: len(expectedValue), + StoredData: storedValue, + ExpectedData: expectedValue, + } + } + + return nil +} diff --git a/engine/execution/storehouse/checkpoint_validator_test.go b/engine/execution/storehouse/checkpoint_validator_test.go new file mode 100644 index 00000000000..4d9de5d453f --- /dev/null +++ b/engine/execution/storehouse/checkpoint_validator_test.go @@ -0,0 +1,227 @@ +package storehouse + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "testing" + + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger/common/convert" + "github.com/onflow/flow-go/ledger/common/pathfinder" + "github.com/onflow/flow-go/ledger/complete" + "github.com/onflow/flow-go/ledger/complete/mtrie/trie" + "github.com/onflow/flow-go/ledger/complete/wal" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/storage/pebble" + "github.com/onflow/flow-go/utils/unittest" + "github.com/onflow/flow-go/utils/unittest/fixtures" +) + +func TestIsErrMismatch(t *testing.T) { + t.Parallel() + + t.Run("returns true for direct ErrMismatch", func(t *testing.T) { + err := &ErrMismatch{ + RegisterID: flow.RegisterID{Owner: "owner", Key: "key"}, + Height: 100, + StoredLength: 10, + ExpectedLength: 20, + } + mismatchErr, ok := IsErrMismatch(err) + require.True(t, ok) + require.Equal(t, err, mismatchErr) + }) + + t.Run("returns true for wrapped ErrMismatch", func(t *testing.T) { + original := &ErrMismatch{ + RegisterID: flow.RegisterID{Owner: "owner", Key: "key"}, + Height: 100, + StoredLength: 10, + ExpectedLength: 20, + } + wrapped := fmt.Errorf("wrapper: %w", original) + mismatchErr, ok := IsErrMismatch(wrapped) + require.True(t, ok) + require.Equal(t, original, mismatchErr) + }) + + t.Run("returns false for non-ErrMismatch", func(t *testing.T) { + err := errors.New("some other error") + mismatchErr, ok := IsErrMismatch(err) + require.False(t, ok) + require.Nil(t, mismatchErr) + }) + + t.Run("returns false for nil error", func(t *testing.T) { + mismatchErr, ok := IsErrMismatch(nil) + require.False(t, ok) + require.Nil(t, mismatchErr) + }) +} + +func TestValidateWithCheckpoint_AllMatching(t *testing.T) { + t.Parallel() + log := zerolog.New(io.Discard) + rootHeight := uint64(10000) + workerCount := 2 + registerCount := 10 + + unittest.RunWithTempDir(t, func(dir string) { + // create generator suite for random register entries + suite := fixtures.NewGeneratorSuite() + + // generate random register entries using unittest fixtures + registerEntries := suite.RegisterEntries().List(registerCount) + + // create checkpoint from register entries + tries, rootHash := createTrieFromRegisterEntries(t, registerEntries) + fileName := "root.checkpoint" + require.NoError(t, wal.StoreCheckpointV6Concurrently(tries, dir, fileName, log)) + + // create pebble store and populate with matching registers + dbDir := unittest.TempPebblePath(t) + defer func() { + require.NoError(t, os.RemoveAll(dbDir)) + }() + + // bootstrap DB at rootHeight + db := pebble.NewBootstrappedRegistersWithPathForTest(t, dbDir, rootHeight, rootHeight) + defer func() { + require.NoError(t, db.Close()) + }() + + // create Registers instance + pb, err := pebble.NewRegisters(db, pebble.PruningDisabled) + require.NoError(t, err) + + // store registers at rootHeight + 1 + storeHeight := rootHeight + 1 + require.NoError(t, pb.Store(registerEntries, storeHeight)) + + // verify registers are stored at rootHeight + 1 + require.Equal(t, storeHeight, pb.LatestHeight()) + for _, entry := range registerEntries { + value, err := pb.Get(entry.Key, storeHeight) + require.NoError(t, err) + require.Equal(t, entry.Value, value) + } + + // create mocks for validation at storeHeight + headers, results := createMocks(t, storeHeight, rootHash) + + // validate at storeHeight - should return no error + err = ValidateWithCheckpoint(log, context.Background(), pb, results, headers, dir, storeHeight, workerCount) + require.NoError(t, err) + }) +} + +func TestValidateWithCheckpoint_WithMismatches(t *testing.T) { + t.Parallel() + log := zerolog.New(io.Discard) + rootHeight := uint64(10000) + workerCount := 2 + registerCount := 50 // Increased from 5 to ensure some registers are in subtries, not all in top trie + + unittest.RunWithTempDir(t, func(dir string) { + // create generator suite for random register entries + suite := fixtures.NewGeneratorSuite() + + // generate random register entries using unittest fixtures + registerEntries := suite.RegisterEntries().List(registerCount) + + // create checkpoint from register entries + tries, rootHash := createTrieFromRegisterEntries(t, registerEntries) + fileName := "root.checkpoint" + require.NoError(t, wal.StoreCheckpointV6Concurrently(tries, dir, fileName, log)) + + // create pebble store and populate with mismatched registers + dbDir := unittest.TempPebblePath(t) + defer func() { + require.NoError(t, os.RemoveAll(dbDir)) + }() + + // bootstrap DB at rootHeight + db := pebble.NewBootstrappedRegistersWithPathForTest(t, dbDir, rootHeight, rootHeight) + defer func() { + require.NoError(t, db.Close()) + }() + + // create Registers instance + pb, err := pebble.NewRegisters(db, pebble.PruningDisabled) + require.NoError(t, err) + + // store registers at rootHeight + 1 with wrong values + storeHeight := rootHeight + 1 + mismatchedEntries := make(flow.RegisterEntries, 0, len(registerEntries)) + for _, entry := range registerEntries { + mismatchedEntries = append(mismatchedEntries, flow.RegisterEntry{ + Key: entry.Key, + Value: []byte{'x'}, // different value from checkpoint + }) + } + require.NoError(t, pb.Store(mismatchedEntries, storeHeight)) + + // create mocks for validation at storeHeight + headers, results := createMocks(t, storeHeight, rootHash) + + // validate at storeHeight - should return error with mismatch count + err = ValidateWithCheckpoint(log, context.Background(), pb, results, headers, dir, storeHeight, workerCount) + require.Error(t, err) + require.Contains(t, err.Error(), "validation failed: found") + require.Contains(t, err.Error(), "register value mismatches") + }) +} + +// createTrieFromRegisterEntries creates a trie from register entries for checkpoint creation +func createTrieFromRegisterEntries(t *testing.T, entries flow.RegisterEntries) ([]*trie.MTrie, ledger.RootHash) { + // convert register entries to payloads + payloads := make([]*ledger.Payload, 0, len(entries)) + for _, entry := range entries { + key := convert.RegisterIDToLedgerKey(entry.Key) + payload := ledger.NewPayload(key, ledger.Value(entry.Value)) + payloads = append(payloads, payload) + } + + // get paths from payloads + paths, err := pathfinder.PathsFromPayloads(payloads, complete.DefaultPathFinderVersion) + require.NoError(t, err) + + // create trie + emptyTrie := trie.NewEmptyMTrie() + derefPayloads := make([]ledger.Payload, len(payloads)) + for i, p := range payloads { + derefPayloads[i] = *p + } + + populatedTrie, _, err := trie.NewTrieWithUpdatedRegisters(emptyTrie, paths, derefPayloads, true) + require.NoError(t, err) + return []*trie.MTrie{populatedTrie}, populatedTrie.RootHash() +} + +func createMocks(t *testing.T, height uint64, rootHash ledger.RootHash) (storage.Headers, storage.ExecutionResults) { + header := unittest.BlockHeaderFixture(unittest.WithHeaderHeight(height)) + result := unittest.ExecutionResultFixture(func(result *flow.ExecutionResult) { + result.BlockID = header.ID() + result.Chunks = flow.ChunkList{ + { + EndState: flow.StateCommitment(rootHash), + }, + } + }) + + mockHeaders := storagemock.NewHeaders(t) + mockHeaders.On("BlockIDByHeight", height).Return(header.ID(), nil) + + mockResults := storagemock.NewExecutionResults(t) + mockResults.On("ByBlockID", header.ID()).Return(result, nil) + + return mockHeaders, mockResults +} diff --git a/engine/execution/storehouse/executing_block_snapshot.go b/engine/execution/storehouse/executing_block_snapshot.go index e9e9b97c32b..5ba3ce2526e 100644 --- a/engine/execution/storehouse/executing_block_snapshot.go +++ b/engine/execution/storehouse/executing_block_snapshot.go @@ -53,7 +53,7 @@ func (s *ExecutingBlockSnapshot) getFromUpdates(id flow.RegisterID) (flow.Regist return value, ok } -// Extend returns a new storage snapshot at the same block but but for a different state commitment, +// Extend returns a new storage snapshot at the same block but for a different state commitment, // which contains the given registerUpdates // Usually it's used to create a new storage snapshot at the next executed collection. // The registerUpdates contains the register updates at the executed collection. diff --git a/engine/execution/testutil/fixtures.go b/engine/execution/testutil/fixtures.go index fb9ee6e398a..9fd5a1e0e1c 100644 --- a/engine/execution/testutil/fixtures.go +++ b/engine/execution/testutil/fixtures.go @@ -223,11 +223,7 @@ func CreateAccountsWithSimpleAddresses( []flow.Address, error, ) { - ctx := fvm.NewContext( - fvm.WithChain(chain), - fvm.WithAuthorizationChecksEnabled(false), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - ) + ctx := fvm.NewContext(chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false)) var accounts []flow.Address @@ -309,7 +305,7 @@ func CreateAccountsWithSimpleAddresses( stdlib.AccountEventAddressParameter.Identifier, ).(cadence.Address) - addr = flow.ConvertAddress(address) + addr = flow.Address(address) break } } diff --git a/engine/execution/testutil/fixtures_counter.go b/engine/execution/testutil/fixtures_counter.go index 702c8797392..eb2646d37ef 100644 --- a/engine/execution/testutil/fixtures_counter.go +++ b/engine/execution/testutil/fixtures_counter.go @@ -69,7 +69,7 @@ func RemoveCounterContractTransaction(authorizer flow.Address, chain flow.Chain) func CreateCounterTransaction(counter, signer flow.Address) *flow.TransactionBodyBuilder { return flow.NewTransactionBodyBuilder(). SetScript([]byte(fmt.Sprintf(` - import 0x%s + import Container from 0x%s transaction { prepare(acc: auth(Storage) &Account) { @@ -91,7 +91,7 @@ func CreateCounterTransaction(counter, signer flow.Address) *flow.TransactionBod func CreateCounterPanicTransaction(counter, signer flow.Address) *flow.TransactionBodyBuilder { return flow.NewTransactionBodyBuilder(). SetScript([]byte(fmt.Sprintf(` - import 0x%s + import Container from 0x%s transaction { prepare(acc: auth(Storage) &Account) { @@ -108,7 +108,7 @@ func CreateCounterPanicTransaction(counter, signer flow.Address) *flow.Transacti func AddToCounterTransaction(counter, signer flow.Address) *flow.TransactionBodyBuilder { return flow.NewTransactionBodyBuilder(). SetScript([]byte(fmt.Sprintf(` - import 0x%s + import Container from 0x%s transaction { prepare(acc: auth(Storage) &Account) { diff --git a/engine/fifoqueue.go b/engine/fifoqueue.go index 459e5951a78..50dce1ec9c9 100644 --- a/engine/fifoqueue.go +++ b/engine/fifoqueue.go @@ -9,10 +9,31 @@ type FifoMessageStore struct { *fifoqueue.FifoQueue } +var _ MessageStore = (*FifoMessageStore)(nil) + +// NewFifoMessageStore creates a FifoMessageStore backed by a [fifoqueue.FifoQueue]. +// No errors are expected during normal operations. +func NewFifoMessageStore(maxCapacity int) (*FifoMessageStore, error) { + queue, err := fifoqueue.NewFifoQueue(maxCapacity) + if err != nil { + return nil, err + } + return &FifoMessageStore{FifoQueue: queue}, nil +} + +// Put appends the given value to the tail of the queue. +// Returns true if and only if the element was added, or false if the +// element was dropped due the queue being full. +// Elements successfully added to the queue stay in the queue until they +// are popped by a Get() call. In other words, a return value of `true` +// implies that the message will eventually be processed. This provides +// stronger guarantees than minimally required by the [MessageStore] interface. func (s *FifoMessageStore) Put(msg *Message) bool { return s.Push(msg) } +// Get retrieves the next message from the head of the queue. It returns +// true if a message is retrieved, and false if the message store is empty. func (s *FifoMessageStore) Get() (*Message, bool) { msgint, ok := s.Pop() if !ok { diff --git a/engine/ghost/engine/rpc.go b/engine/ghost/engine/rpc.go index f73c2b3ec18..188468bc091 100644 --- a/engine/ghost/engine/rpc.go +++ b/engine/ghost/engine/rpc.go @@ -149,7 +149,7 @@ func (e *RPC) Done() <-chan struct{} { } // SubmitLocal submits an event originating on the local node. -func (e *RPC) SubmitLocal(event interface{}) { +func (e *RPC) SubmitLocal(event any) { e.unit.Launch(func() { err := e.process(e.me.NodeID(), event) if err != nil { @@ -161,7 +161,7 @@ func (e *RPC) SubmitLocal(event interface{}) { // Submit submits the given event from the node with the given origin ID // for processing in a non-blocking manner. It returns instantly and logs // a potential processing error internally when done. -func (e *RPC) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { +func (e *RPC) Submit(channel channels.Channel, originID flow.Identifier, event any) { e.unit.Launch(func() { err := e.process(originID, event) if err != nil { @@ -171,7 +171,7 @@ func (e *RPC) Submit(channel channels.Channel, originID flow.Identifier, event i } // ProcessLocal processes an event originating on the local node. -func (e *RPC) ProcessLocal(event interface{}) error { +func (e *RPC) ProcessLocal(event any) error { return e.unit.Do(func() error { return e.process(e.me.NodeID(), event) }) @@ -179,13 +179,13 @@ func (e *RPC) ProcessLocal(event interface{}) error { // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (e *RPC) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { +func (e *RPC) Process(channel channels.Channel, originID flow.Identifier, event any) error { return e.unit.Do(func() error { return e.process(originID, event) }) } -func (e *RPC) process(originID flow.Identifier, event interface{}) error { +func (e *RPC) process(originID flow.Identifier, event any) error { msg, err := messages.InternalToMessage(event) if err != nil { return fmt.Errorf("failed to convert event to message: %v", err) diff --git a/engine/protocol/mock/api.go b/engine/protocol/mock/api.go deleted file mode 100644 index 0597385edef..00000000000 --- a/engine/protocol/mock/api.go +++ /dev/null @@ -1,350 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - access "github.com/onflow/flow-go/model/access" - - flow "github.com/onflow/flow-go/model/flow" - - mock "github.com/stretchr/testify/mock" -) - -// API is an autogenerated mock type for the API type -type API struct { - mock.Mock -} - -// GetBlockByHeight provides a mock function with given fields: ctx, height -func (_m *API) GetBlockByHeight(ctx context.Context, height uint64) (*flow.Block, error) { - ret := _m.Called(ctx, height) - - if len(ret) == 0 { - panic("no return value specified for GetBlockByHeight") - } - - var r0 *flow.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Block, error)); ok { - return rf(ctx, height) - } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.Block); ok { - r0 = rf(ctx, height) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, height) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetBlockByID provides a mock function with given fields: ctx, id -func (_m *API) GetBlockByID(ctx context.Context, id flow.Identifier) (*flow.Block, error) { - ret := _m.Called(ctx, id) - - if len(ret) == 0 { - panic("no return value specified for GetBlockByID") - } - - var r0 *flow.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Block, error)); ok { - return rf(ctx, id) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Block); ok { - r0 = rf(ctx, id) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetBlockHeaderByHeight provides a mock function with given fields: ctx, height -func (_m *API) GetBlockHeaderByHeight(ctx context.Context, height uint64) (*flow.Header, error) { - ret := _m.Called(ctx, height) - - if len(ret) == 0 { - panic("no return value specified for GetBlockHeaderByHeight") - } - - var r0 *flow.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Header, error)); ok { - return rf(ctx, height) - } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.Header); ok { - r0 = rf(ctx, height) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, height) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetBlockHeaderByID provides a mock function with given fields: ctx, id -func (_m *API) GetBlockHeaderByID(ctx context.Context, id flow.Identifier) (*flow.Header, error) { - ret := _m.Called(ctx, id) - - if len(ret) == 0 { - panic("no return value specified for GetBlockHeaderByID") - } - - var r0 *flow.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Header, error)); ok { - return rf(ctx, id) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Header); ok { - r0 = rf(ctx, id) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetLatestBlock provides a mock function with given fields: ctx, isSealed -func (_m *API) GetLatestBlock(ctx context.Context, isSealed bool) (*flow.Block, error) { - ret := _m.Called(ctx, isSealed) - - if len(ret) == 0 { - panic("no return value specified for GetLatestBlock") - } - - var r0 *flow.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, bool) (*flow.Block, error)); ok { - return rf(ctx, isSealed) - } - if rf, ok := ret.Get(0).(func(context.Context, bool) *flow.Block); ok { - r0 = rf(ctx, isSealed) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, bool) error); ok { - r1 = rf(ctx, isSealed) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetLatestBlockHeader provides a mock function with given fields: ctx, isSealed -func (_m *API) GetLatestBlockHeader(ctx context.Context, isSealed bool) (*flow.Header, error) { - ret := _m.Called(ctx, isSealed) - - if len(ret) == 0 { - panic("no return value specified for GetLatestBlockHeader") - } - - var r0 *flow.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, bool) (*flow.Header, error)); ok { - return rf(ctx, isSealed) - } - if rf, ok := ret.Get(0).(func(context.Context, bool) *flow.Header); ok { - r0 = rf(ctx, isSealed) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, bool) error); ok { - r1 = rf(ctx, isSealed) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetLatestProtocolStateSnapshot provides a mock function with given fields: ctx -func (_m *API) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetLatestProtocolStateSnapshot") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) ([]byte, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) []byte); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetNetworkParameters provides a mock function with given fields: ctx -func (_m *API) GetNetworkParameters(ctx context.Context) access.NetworkParameters { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetNetworkParameters") - } - - var r0 access.NetworkParameters - if rf, ok := ret.Get(0).(func(context.Context) access.NetworkParameters); ok { - r0 = rf(ctx) - } else { - r0 = ret.Get(0).(access.NetworkParameters) - } - - return r0 -} - -// GetNodeVersionInfo provides a mock function with given fields: ctx -func (_m *API) GetNodeVersionInfo(ctx context.Context) (*access.NodeVersionInfo, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetNodeVersionInfo") - } - - var r0 *access.NodeVersionInfo - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*access.NodeVersionInfo, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *access.NodeVersionInfo); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*access.NodeVersionInfo) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetProtocolStateSnapshotByBlockID provides a mock function with given fields: ctx, blockID -func (_m *API) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID flow.Identifier) ([]byte, error) { - ret := _m.Called(ctx, blockID) - - if len(ret) == 0 { - panic("no return value specified for GetProtocolStateSnapshotByBlockID") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]byte, error)); ok { - return rf(ctx, blockID) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []byte); ok { - r0 = rf(ctx, blockID) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetProtocolStateSnapshotByHeight provides a mock function with given fields: ctx, blockHeight -func (_m *API) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHeight uint64) ([]byte, error) { - ret := _m.Called(ctx, blockHeight) - - if len(ret) == 0 { - panic("no return value specified for GetProtocolStateSnapshotByHeight") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) ([]byte, error)); ok { - return rf(ctx, blockHeight) - } - if rf, ok := ret.Get(0).(func(context.Context, uint64) []byte); ok { - r0 = rf(ctx, blockHeight) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, blockHeight) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewAPI creates a new instance of API. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *API { - mock := &API{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/protocol/mock/network_api.go b/engine/protocol/mock/network_api.go deleted file mode 100644 index c2b907377fa..00000000000 --- a/engine/protocol/mock/network_api.go +++ /dev/null @@ -1,170 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - context "context" - - access "github.com/onflow/flow-go/model/access" - - flow "github.com/onflow/flow-go/model/flow" - - mock "github.com/stretchr/testify/mock" -) - -// NetworkAPI is an autogenerated mock type for the NetworkAPI type -type NetworkAPI struct { - mock.Mock -} - -// GetLatestProtocolStateSnapshot provides a mock function with given fields: ctx -func (_m *NetworkAPI) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetLatestProtocolStateSnapshot") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) ([]byte, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) []byte); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetNetworkParameters provides a mock function with given fields: ctx -func (_m *NetworkAPI) GetNetworkParameters(ctx context.Context) access.NetworkParameters { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetNetworkParameters") - } - - var r0 access.NetworkParameters - if rf, ok := ret.Get(0).(func(context.Context) access.NetworkParameters); ok { - r0 = rf(ctx) - } else { - r0 = ret.Get(0).(access.NetworkParameters) - } - - return r0 -} - -// GetNodeVersionInfo provides a mock function with given fields: ctx -func (_m *NetworkAPI) GetNodeVersionInfo(ctx context.Context) (*access.NodeVersionInfo, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetNodeVersionInfo") - } - - var r0 *access.NodeVersionInfo - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*access.NodeVersionInfo, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *access.NodeVersionInfo); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*access.NodeVersionInfo) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetProtocolStateSnapshotByBlockID provides a mock function with given fields: ctx, blockID -func (_m *NetworkAPI) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID flow.Identifier) ([]byte, error) { - ret := _m.Called(ctx, blockID) - - if len(ret) == 0 { - panic("no return value specified for GetProtocolStateSnapshotByBlockID") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]byte, error)); ok { - return rf(ctx, blockID) - } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []byte); ok { - r0 = rf(ctx, blockID) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetProtocolStateSnapshotByHeight provides a mock function with given fields: ctx, blockHeight -func (_m *NetworkAPI) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHeight uint64) ([]byte, error) { - ret := _m.Called(ctx, blockHeight) - - if len(ret) == 0 { - panic("no return value specified for GetProtocolStateSnapshotByHeight") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) ([]byte, error)); ok { - return rf(ctx, blockHeight) - } - if rf, ok := ret.Get(0).(func(context.Context, uint64) []byte); ok { - r0 = rf(ctx, blockHeight) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, blockHeight) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewNetworkAPI creates a new instance of NetworkAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNetworkAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *NetworkAPI { - mock := &NetworkAPI{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/engine/testutil/mock/nodes.go b/engine/testutil/mock/nodes.go index e41a4242be9..d509cc12c2f 100644 --- a/engine/testutil/mock/nodes.go +++ b/engine/testutil/mock/nodes.go @@ -243,6 +243,7 @@ func (en ExecutionNode) Ready(t *testing.T, ctx context.Context) { en.FollowerCore.Start(irctx) en.FollowerEngine.Start(irctx) en.SyncEngine.Start(irctx) + en.RequestEngine.Start(irctx) <-util.AllReady( en.Ledger, @@ -303,12 +304,12 @@ type VerificationNode struct { Receipts storage.ExecutionReceipts // chunk consumer and processor for fetcher engine - ProcessedChunkIndex storage.ConsumerProgressInitializer + ProcessedChunkIndex storage.ConsumerProgress ChunksQueue storage.ChunksQueue ChunkConsumer *chunkconsumer.ChunkConsumer // block consumer for chunk consumer - ProcessedBlockHeight storage.ConsumerProgressInitializer + ProcessedBlockHeight storage.ConsumerProgress BlockConsumer *blockconsumer.BlockConsumer FollowerDistributor *pubsub.FollowerDistributor diff --git a/engine/testutil/mocklocal/local.go b/engine/testutil/mocklocal/local.go index 377cd0767eb..c062d221f99 100644 --- a/engine/testutil/mocklocal/local.go +++ b/engine/testutil/mocklocal/local.go @@ -14,16 +14,18 @@ import ( // We needed to develop a separate mock for Local as we could not mock // a method with return values with gomock type MockLocal struct { - sk crypto.PrivateKey - t mock.TestingT - id flow.Identifier + sk crypto.PrivateKey + t mock.TestingT + id flow.Identifier + role flow.Role } func NewMockLocal(sk crypto.PrivateKey, id flow.Identifier, t mock.TestingT) *MockLocal { return &MockLocal{ - sk: sk, - t: t, - id: id, + sk: sk, + t: t, + id: id, + role: flow.RoleConsensus, } } @@ -31,6 +33,10 @@ func (m *MockLocal) NodeID() flow.Identifier { return m.id } +func (m *MockLocal) Role() flow.Role { + return m.role +} + func (m *MockLocal) Address() string { require.Fail(m.t, "should not call MockLocal Address") return "" diff --git a/engine/testutil/nodes.go b/engine/testutil/nodes.go index 6dbb9f33f3c..24d6e072fe1 100644 --- a/engine/testutil/nodes.go +++ b/engine/testutil/nodes.go @@ -30,7 +30,6 @@ import ( "github.com/onflow/flow-go/engine" "github.com/onflow/flow-go/engine/collection/epochmgr" "github.com/onflow/flow-go/engine/collection/epochmgr/factories" - "github.com/onflow/flow-go/engine/collection/ingest" collectioningest "github.com/onflow/flow-go/engine/collection/ingest" mockcollection "github.com/onflow/flow-go/engine/collection/mock" "github.com/onflow/flow-go/engine/collection/pusher" @@ -51,7 +50,6 @@ import ( "github.com/onflow/flow-go/engine/execution/ingestion/uploader" executionprovider "github.com/onflow/flow-go/engine/execution/provider" executionState "github.com/onflow/flow-go/engine/execution/state" - bootstrapexec "github.com/onflow/flow-go/engine/execution/state/bootstrap" esbootstrap "github.com/onflow/flow-go/engine/execution/state/bootstrap" "github.com/onflow/flow-go/engine/execution/storehouse" testmock "github.com/onflow/flow-go/engine/testutil/mock" @@ -303,7 +301,7 @@ func CollectionNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ro clusterPayloads := store.NewClusterPayloads(node.Metrics, db) ingestionEngine, err := collectioningest.New(node.Log, node.Net, node.State, node.Metrics, node.Metrics, node.Metrics, node.Me, node.ChainID.Chain(), pools, collectioningest.DefaultConfig(), - ingest.NewAddressRateLimiter(rate.Limit(1), 10)) // 10 tps + collectioningest.NewAddressRateLimiter(rate.Limit(1), 10)) // 10 tps require.NoError(t, err) selector := filter.HasRole[flow.Identity](flow.RoleAccess, flow.RoleVerification) @@ -317,6 +315,10 @@ func CollectionNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ro node.Net, node.Me, node.State, + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). queue.NewHeroStore(uint32(1000), unittest.Logger(), metrics.NewNoopCollector()), uint(1000), channels.ProvideCollections, @@ -459,8 +461,23 @@ func ConsensusNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ide ingestionEngine, err := consensusingest.New(node.Log, node.Metrics, node.Net, node.Me, ingestionCore) require.NoError(t, err) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). + requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) // request receipts from execution nodes - receiptRequester, err := requester.New(node.Log.With().Str("entity", "receipt").Logger(), node.Metrics, node.Net, node.Me, node.State, channels.RequestReceiptsByBlockID, filter.Any, func() flow.Entity { return new(flow.ExecutionReceipt) }) + receiptRequester, err := requester.New( + node.Log.With().Str("entity", "receipt").Logger(), + node.Metrics, + node.Net, + node.Me, + node.State, + requestQueue, + channels.RequestReceiptsByBlockID, + filter.Any, + func() flow.Entity { return new(flow.ExecutionReceipt) }, + ) require.NoError(t, err) assigner, err := chunks.NewChunkAssigner(flow.DefaultChunkAssignmentAlpha, node.State) @@ -603,7 +620,7 @@ func ExecutionNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ide genesisHead, err := node.State.Final().Head() require.NoError(t, err) - bootstrapper := bootstrapexec.NewBootstrapper(node.Log) + bootstrapper := esbootstrap.NewBootstrapper(node.Log) commit, err := bootstrapper.BootstrapLedger( ls, unittest.ServiceAccountPublicKey, @@ -666,8 +683,14 @@ func ExecutionNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ide node.LockManager, ) + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). + requestQueue := queue.NewHeroStore(10, unittest.Logger(), metrics.NewNoopCollector()) requestEngine, err := requester.New( node.Log.With().Str("entity", "collection").Logger(), node.Metrics, node.Net, node.Me, node.State, + requestQueue, channels.RequestCollections, filter.HasRole[flow.Identity](flow.RoleCollection), func() flow.Entity { return new(flow.Collection) }, @@ -682,6 +705,10 @@ func ExecutionNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ide execState, metricsCollector, checkAuthorizedAtBlock, + // CAUTION: the HeroStore fifo queue is NOT BFT. It should be used for messages from trusted sources only! + // In the requester engine, the injected fifo queue is used to hold [flow.EntityResponse] messages from other + // potentially byzantine peers. In PRODUCTION, you can NOT use a HeroStore here. However, for testing we + // use the HeroStore for its better performance (reduced GC load on the maxed-out testing server). queue.NewHeroStore(uint32(1000), unittest.Logger(), metrics.NewNoopCollector()), executionprovider.DefaultChunkDataPackRequestWorker, executionprovider.DefaultChunkDataPackQueryTimeout, @@ -692,8 +719,8 @@ func ExecutionNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ide blockFinder := environment.NewBlockFinder(node.Headers) vmCtx := fvm.NewContext( + node.ChainID.Chain(), fvm.WithLogger(node.Log), - fvm.WithChain(node.ChainID.Chain()), fvm.WithBlocks(blockFinder), ) committer := committer.NewLedgerViewCommitter(ls, node.Tracer) @@ -773,6 +800,7 @@ func ExecutionNode(t *testing.T, hub *stub.Hub, identity bootstrap.NodeInfo, ide pusherEngine, uploader, stopControl, + nil, // block executed callback not used in test ) require.NoError(t, err) node.ProtocolEvents.AddConsumer(stopControl) @@ -1020,7 +1048,8 @@ func VerificationNode(t testing.TB, } if node.ProcessedChunkIndex == nil { - node.ProcessedChunkIndex = store.NewConsumerProgress(node.PublicDB, module.ConsumeProgressVerificationChunkIndex) + node.ProcessedChunkIndex, err = store.NewConsumerProgress(node.PublicDB, module.ConsumeProgressVerificationChunkIndex).Initialize(chunkconsumer.DefaultJobIndex) + require.NoError(t, err) } if node.ChunksQueue == nil { @@ -1032,7 +1061,11 @@ func VerificationNode(t testing.TB, } if node.ProcessedBlockHeight == nil { - node.ProcessedBlockHeight = store.NewConsumerProgress(node.PublicDB, module.ConsumeProgressVerificationBlockHeight) + sealedHead, err := node.State.Sealed().Head() + require.NoError(t, err) + + node.ProcessedBlockHeight, err = store.NewConsumerProgress(node.PublicDB, module.ConsumeProgressVerificationBlockHeight).Initialize(sealedHead.Height) + require.NoError(t, err) } if node.VerifierEngine == nil { vm := fvm.NewVirtualMachine() @@ -1040,8 +1073,8 @@ func VerificationNode(t testing.TB, blockFinder := environment.NewBlockFinder(node.Headers) vmCtx := fvm.NewContext( + node.ChainID.Chain(), fvm.WithLogger(node.Log), - fvm.WithChain(node.ChainID.Chain()), fvm.WithBlocks(blockFinder), ) @@ -1125,7 +1158,7 @@ func VerificationNode(t testing.TB, if node.BlockConsumer == nil { followerDistributor := pubsub.NewFollowerDistributor() - node.BlockConsumer, _, err = blockconsumer.NewBlockConsumer(node.Log, + node.BlockConsumer, err = blockconsumer.NewBlockConsumer(node.Log, collector, node.ProcessedBlockHeight, node.Blocks, diff --git a/engine/verification/assigner/blockconsumer/consumer.go b/engine/verification/assigner/blockconsumer/consumer.go index 1b4470b0e28..92746a59c3a 100644 --- a/engine/verification/assigner/blockconsumer/consumer.go +++ b/engine/verification/assigner/blockconsumer/consumer.go @@ -27,28 +27,16 @@ type BlockConsumer struct { metrics module.VerificationMetrics } -// defaultProcessedIndex returns the last sealed block height from the protocol state. -// -// The BlockConsumer utilizes this return height to fetch and consume block jobs from -// jobs queue the first time it initializes. -func defaultProcessedIndex(state protocol.State) (uint64, error) { - final, err := state.Sealed().Head() - if err != nil { - return 0, fmt.Errorf("could not get finalized height: %w", err) - } - return final.Height, nil -} - -// NewBlockConsumer creates a new consumer and returns the default processed -// index for initializing the processed index in storage. +// NewBlockConsumer creates a new consumer func NewBlockConsumer(log zerolog.Logger, metrics module.VerificationMetrics, - processedHeight storage.ConsumerProgressInitializer, + processedHeight storage.ConsumerProgress, blocks storage.Blocks, state protocol.State, blockProcessor assigner.FinalizedBlockProcessor, maxProcessing uint64, - finalizationRegistrar hotstuff.FinalizationRegistrar) (*BlockConsumer, uint64, error) { + finalizationRegistrar hotstuff.FinalizationRegistrar, +) (*BlockConsumer, error) { lg := log.With().Str("module", "block_consumer").Logger() @@ -60,14 +48,9 @@ func NewBlockConsumer(log zerolog.Logger, // the block reader is where the consumer reads new finalized blocks from (i.e., jobs). jobs := jobqueue.NewFinalizedBlockReader(state, blocks) - defaultIndex, err := defaultProcessedIndex(state) - if err != nil { - return nil, 0, fmt.Errorf("could not read default processed index: %w", err) - } - - consumer, err := jobqueue.NewConsumer(lg, jobs, processedHeight, worker, maxProcessing, 0, defaultIndex) + consumer, err := jobqueue.NewConsumer(lg, jobs, processedHeight, worker, maxProcessing, 0) if err != nil { - return nil, 0, fmt.Errorf("could not create block consumer: %w", err) + return nil, fmt.Errorf("could not create block consumer: %w", err) } blockConsumer := &BlockConsumer{ @@ -80,7 +63,7 @@ func NewBlockConsumer(log zerolog.Logger, // register callback with finalization registrar finalizationRegistrar.AddOnBlockFinalizedConsumer(blockConsumer.onFinalizedBlock) - return blockConsumer, defaultIndex, nil + return blockConsumer, nil } // NotifyJobIsDone is invoked by the worker to let the consumer know that it is done diff --git a/engine/verification/assigner/blockconsumer/consumer_test.go b/engine/verification/assigner/blockconsumer/consumer_test.go index b34e3a9d9df..11c1aaef99d 100644 --- a/engine/verification/assigner/blockconsumer/consumer_test.go +++ b/engine/verification/assigner/blockconsumer/consumer_test.go @@ -77,18 +77,20 @@ func TestProduceConsume(t *testing.T) { var processAll sync.WaitGroup alwaysFinish := func(notifier module.ProcessingNotifier, block *flow.Block) { lock.Lock() - defer lock.Unlock() - received = append(received, block) + lock.Unlock() - go func() { - notifier.Notify(block.ID()) - processAll.Done() - }() + notifier.Notify(block.ID()) + processAll.Done() } withConsumer(t, 100, 3, alwaysFinish, func(consumer *blockconsumer.BlockConsumer, blocks []*flow.Block, followerDistributor *pubsub.FollowerDistributor) { unittest.RequireCloseBefore(t, consumer.Ready(), time.Second, "could not start consumer") + // defer shutdown to ensure it runs even if a `unittest.Require*` fails. + // this helps avoid a "pebble: closed" panic when the test times out. + defer func() { + unittest.RequireCloseBefore(t, consumer.Done(), time.Second, "could not terminate consumer") + }() processAll.Add(len(blocks)) for i := 0; i < len(blocks); i++ { @@ -100,7 +102,6 @@ func TestProduceConsume(t *testing.T) { // waits until all blocks finish processing unittest.RequireReturnsBefore(t, processAll.Wait, time.Second, "could not process all blocks on time") - unittest.RequireCloseBefore(t, consumer.Done(), time.Second, "could not terminate consumer") // expects the mock engine receive all 100 blocks. require.ElementsMatch(t, flow.GetIDs(blocks), flow.GetIDs(received)) @@ -123,7 +124,6 @@ func withConsumer( unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { maxProcessing := uint64(workerCount) - processedHeight := store.NewConsumerProgress(pebbleimpl.ToDB(pdb), module.ConsumeProgressVerificationBlockHeight) collector := &metrics.NoopCollector{} tracer := trace.NewNoopTracer() log := unittest.Logger() @@ -135,8 +135,14 @@ func withConsumer( process: process, } + sealedHead, err := s.State.Sealed().Head() + require.NoError(t, err) + + processedHeight, err := store.NewConsumerProgress(pebbleimpl.ToDB(pdb), module.ConsumeProgressVerificationBlockHeight).Initialize(sealedHead.Height) + require.NoError(t, err) + followerDistributor := pubsub.NewFollowerDistributor() - consumer, _, err := blockconsumer.NewBlockConsumer( + consumer, err := blockconsumer.NewBlockConsumer( unittest.Logger(), collector, processedHeight, diff --git a/engine/verification/fetcher/chunkconsumer/consumer.go b/engine/verification/fetcher/chunkconsumer/consumer.go index 45bad2e686a..f53fc4a9a02 100644 --- a/engine/verification/fetcher/chunkconsumer/consumer.go +++ b/engine/verification/fetcher/chunkconsumer/consumer.go @@ -29,7 +29,7 @@ type ChunkConsumer struct { func NewChunkConsumer( log zerolog.Logger, metrics module.VerificationMetrics, - processedIndexInitializer storage.ConsumerProgressInitializer, // to persist the processed index + processedIndex storage.ConsumerProgress, // to persist the processed index chunksQueue storage.ChunksQueue, // to read jobs (chunks) from chunkProcessor fetcher.AssignedChunkProcessor, // to process jobs (chunks) maxProcessing uint64, // max number of jobs to be processed in parallel @@ -40,7 +40,7 @@ func NewChunkConsumer( jobs := &ChunkJobs{locators: chunksQueue} lg := log.With().Str("module", "chunk_consumer").Logger() - consumer, err := jobqueue.NewConsumer(lg, jobs, processedIndexInitializer, worker, maxProcessing, 0, DefaultJobIndex) + consumer, err := jobqueue.NewConsumer(lg, jobs, processedIndex, worker, maxProcessing, 0) if err != nil { return nil, err } diff --git a/engine/verification/fetcher/chunkconsumer/consumer_test.go b/engine/verification/fetcher/chunkconsumer/consumer_test.go index e314a4627ae..3a23f3c2554 100644 --- a/engine/verification/fetcher/chunkconsumer/consumer_test.go +++ b/engine/verification/fetcher/chunkconsumer/consumer_test.go @@ -8,7 +8,6 @@ import ( "github.com/cockroachdb/pebble/v2" "github.com/stretchr/testify/require" - "go.uber.org/atomic" "github.com/onflow/flow-go/engine/verification/fetcher/chunkconsumer" "github.com/onflow/flow-go/model/chunks" @@ -68,11 +67,11 @@ func TestProduceConsume(t *testing.T) { var called chunks.LocatorList lock := &sync.Mutex{} var finishAll sync.WaitGroup + finishAll.Add(10) alwaysFinish := func(notifier module.ProcessingNotifier, locator *chunks.Locator) { lock.Lock() defer lock.Unlock() called = append(called, locator) - finishAll.Add(1) go func() { notifier.Notify(locator.ID()) finishAll.Done() @@ -90,8 +89,8 @@ func TestProduceConsume(t *testing.T) { consumer.Check() // notify the consumer } + finishAll.Wait() // wait until all 10 jobs are processed and notified <-consumer.Done() - finishAll.Wait() // wait until all finished // expect the mock engine receives all 10 calls require.Equal(t, locators, called) }) @@ -115,7 +114,6 @@ func TestProduceConsume(t *testing.T) { } WithConsumer(t, alwaysFinish, func(consumer *chunkconsumer.ChunkConsumer, chunksQueue storage.ChunksQueue) { <-consumer.Ready() - total := atomic.NewUint32(0) locators := unittest.ChunkLocatorListFixture(100) @@ -124,16 +122,19 @@ func TestProduceConsume(t *testing.T) { ok, err := chunksQueue.StoreChunkLocator(locators[i]) require.NoError(t, err, fmt.Sprintf("chunk locator %v can't be stored", i)) require.True(t, ok) - total.Inc() consumer.Check() // notify the consumer }(i) } - finishAll.Wait() + finishAll.Wait() // wait until all 100 jobs are processed and notified <-consumer.Done() - // expect the mock engine receives all 100 calls - require.Equal(t, uint32(100), total.Load()) + // expect the mock engine receives all 100 calls. `called` is appended to synchronously + // within the process callback (before the notify goroutine is spawned), so once + // finishAll.Wait returns all 100 appends are guaranteed visible. + lock.Lock() + defer lock.Unlock() + require.Len(t, called, 100) }) }) } @@ -148,7 +149,8 @@ func WithConsumer( db := pebbleimpl.ToDB(pebbleDB) collector := &metrics.NoopCollector{} - processedIndex := store.NewConsumerProgress(db, module.ConsumeProgressVerificationChunkIndex) + processedIndex, err := store.NewConsumerProgress(db, module.ConsumeProgressVerificationChunkIndex).Initialize(chunkconsumer.DefaultJobIndex) + require.NoError(t, err) chunksQueue := store.NewChunkQueue(collector, db) ok, err := chunksQueue.Init(chunkconsumer.DefaultJobIndex) require.NoError(t, err) diff --git a/engine/verification/fetcher/mock/assigned_chunk_processor.go b/engine/verification/fetcher/mock/assigned_chunk_processor.go index 7b7f3018d61..38d1cb27cca 100644 --- a/engine/verification/fetcher/mock/assigned_chunk_processor.go +++ b/engine/verification/fetcher/mock/assigned_chunk_processor.go @@ -1,80 +1,210 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - chunks "github.com/onflow/flow-go/model/chunks" - + "github.com/onflow/flow-go/model/chunks" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" - - module "github.com/onflow/flow-go/module" ) +// NewAssignedChunkProcessor creates a new instance of AssignedChunkProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAssignedChunkProcessor(t interface { + mock.TestingT + Cleanup(func()) +}) *AssignedChunkProcessor { + mock := &AssignedChunkProcessor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AssignedChunkProcessor is an autogenerated mock type for the AssignedChunkProcessor type type AssignedChunkProcessor struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *AssignedChunkProcessor) Done() <-chan struct{} { - ret := _m.Called() +type AssignedChunkProcessor_Expecter struct { + mock *mock.Mock +} + +func (_m *AssignedChunkProcessor) EXPECT() *AssignedChunkProcessor_Expecter { + return &AssignedChunkProcessor_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type AssignedChunkProcessor +func (_mock *AssignedChunkProcessor) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// ProcessAssignedChunk provides a mock function with given fields: locator -func (_m *AssignedChunkProcessor) ProcessAssignedChunk(locator *chunks.Locator) { - _m.Called(locator) +// AssignedChunkProcessor_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type AssignedChunkProcessor_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *AssignedChunkProcessor_Expecter) Done() *AssignedChunkProcessor_Done_Call { + return &AssignedChunkProcessor_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *AssignedChunkProcessor_Done_Call) Run(run func()) *AssignedChunkProcessor_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AssignedChunkProcessor_Done_Call) Return(valCh <-chan struct{}) *AssignedChunkProcessor_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *AssignedChunkProcessor_Done_Call) RunAndReturn(run func() <-chan struct{}) *AssignedChunkProcessor_Done_Call { + _c.Call.Return(run) + return _c +} + +// ProcessAssignedChunk provides a mock function for the type AssignedChunkProcessor +func (_mock *AssignedChunkProcessor) ProcessAssignedChunk(locator *chunks.Locator) { + _mock.Called(locator) + return +} + +// AssignedChunkProcessor_ProcessAssignedChunk_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessAssignedChunk' +type AssignedChunkProcessor_ProcessAssignedChunk_Call struct { + *mock.Call +} + +// ProcessAssignedChunk is a helper method to define mock.On call +// - locator *chunks.Locator +func (_e *AssignedChunkProcessor_Expecter) ProcessAssignedChunk(locator interface{}) *AssignedChunkProcessor_ProcessAssignedChunk_Call { + return &AssignedChunkProcessor_ProcessAssignedChunk_Call{Call: _e.mock.On("ProcessAssignedChunk", locator)} } -// Ready provides a mock function with no fields -func (_m *AssignedChunkProcessor) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *AssignedChunkProcessor_ProcessAssignedChunk_Call) Run(run func(locator *chunks.Locator)) *AssignedChunkProcessor_ProcessAssignedChunk_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *chunks.Locator + if args[0] != nil { + arg0 = args[0].(*chunks.Locator) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AssignedChunkProcessor_ProcessAssignedChunk_Call) Return() *AssignedChunkProcessor_ProcessAssignedChunk_Call { + _c.Call.Return() + return _c +} + +func (_c *AssignedChunkProcessor_ProcessAssignedChunk_Call) RunAndReturn(run func(locator *chunks.Locator)) *AssignedChunkProcessor_ProcessAssignedChunk_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type AssignedChunkProcessor +func (_mock *AssignedChunkProcessor) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// WithChunkConsumerNotifier provides a mock function with given fields: notifier -func (_m *AssignedChunkProcessor) WithChunkConsumerNotifier(notifier module.ProcessingNotifier) { - _m.Called(notifier) +// AssignedChunkProcessor_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type AssignedChunkProcessor_Ready_Call struct { + *mock.Call } -// NewAssignedChunkProcessor creates a new instance of AssignedChunkProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAssignedChunkProcessor(t interface { - mock.TestingT - Cleanup(func()) -}) *AssignedChunkProcessor { - mock := &AssignedChunkProcessor{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *AssignedChunkProcessor_Expecter) Ready() *AssignedChunkProcessor_Ready_Call { + return &AssignedChunkProcessor_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *AssignedChunkProcessor_Ready_Call) Run(run func()) *AssignedChunkProcessor_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *AssignedChunkProcessor_Ready_Call) Return(valCh <-chan struct{}) *AssignedChunkProcessor_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *AssignedChunkProcessor_Ready_Call) RunAndReturn(run func() <-chan struct{}) *AssignedChunkProcessor_Ready_Call { + _c.Call.Return(run) + return _c +} + +// WithChunkConsumerNotifier provides a mock function for the type AssignedChunkProcessor +func (_mock *AssignedChunkProcessor) WithChunkConsumerNotifier(notifier module.ProcessingNotifier) { + _mock.Called(notifier) + return +} + +// AssignedChunkProcessor_WithChunkConsumerNotifier_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithChunkConsumerNotifier' +type AssignedChunkProcessor_WithChunkConsumerNotifier_Call struct { + *mock.Call +} + +// WithChunkConsumerNotifier is a helper method to define mock.On call +// - notifier module.ProcessingNotifier +func (_e *AssignedChunkProcessor_Expecter) WithChunkConsumerNotifier(notifier interface{}) *AssignedChunkProcessor_WithChunkConsumerNotifier_Call { + return &AssignedChunkProcessor_WithChunkConsumerNotifier_Call{Call: _e.mock.On("WithChunkConsumerNotifier", notifier)} +} + +func (_c *AssignedChunkProcessor_WithChunkConsumerNotifier_Call) Run(run func(notifier module.ProcessingNotifier)) *AssignedChunkProcessor_WithChunkConsumerNotifier_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 module.ProcessingNotifier + if args[0] != nil { + arg0 = args[0].(module.ProcessingNotifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AssignedChunkProcessor_WithChunkConsumerNotifier_Call) Return() *AssignedChunkProcessor_WithChunkConsumerNotifier_Call { + _c.Call.Return() + return _c +} + +func (_c *AssignedChunkProcessor_WithChunkConsumerNotifier_Call) RunAndReturn(run func(notifier module.ProcessingNotifier)) *AssignedChunkProcessor_WithChunkConsumerNotifier_Call { + _c.Run(run) + return _c } diff --git a/engine/verification/fetcher/mock/chunk_data_pack_handler.go b/engine/verification/fetcher/mock/chunk_data_pack_handler.go index dd6f5f3335b..7b30310140a 100644 --- a/engine/verification/fetcher/mock/chunk_data_pack_handler.go +++ b/engine/verification/fetcher/mock/chunk_data_pack_handler.go @@ -1,29 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/verification" mock "github.com/stretchr/testify/mock" - - verification "github.com/onflow/flow-go/model/verification" ) -// ChunkDataPackHandler is an autogenerated mock type for the ChunkDataPackHandler type -type ChunkDataPackHandler struct { - mock.Mock -} - -// HandleChunkDataPack provides a mock function with given fields: originID, response -func (_m *ChunkDataPackHandler) HandleChunkDataPack(originID flow.Identifier, response *verification.ChunkDataPackResponse) { - _m.Called(originID, response) -} - -// NotifyChunkDataPackSealed provides a mock function with given fields: chunkIndex, resultID -func (_m *ChunkDataPackHandler) NotifyChunkDataPackSealed(chunkIndex uint64, resultID flow.Identifier) { - _m.Called(chunkIndex, resultID) -} - // NewChunkDataPackHandler creates a new instance of ChunkDataPackHandler. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewChunkDataPackHandler(t interface { @@ -37,3 +23,108 @@ func NewChunkDataPackHandler(t interface { return mock } + +// ChunkDataPackHandler is an autogenerated mock type for the ChunkDataPackHandler type +type ChunkDataPackHandler struct { + mock.Mock +} + +type ChunkDataPackHandler_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunkDataPackHandler) EXPECT() *ChunkDataPackHandler_Expecter { + return &ChunkDataPackHandler_Expecter{mock: &_m.Mock} +} + +// HandleChunkDataPack provides a mock function for the type ChunkDataPackHandler +func (_mock *ChunkDataPackHandler) HandleChunkDataPack(originID flow.Identifier, response *verification.ChunkDataPackResponse) { + _mock.Called(originID, response) + return +} + +// ChunkDataPackHandler_HandleChunkDataPack_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleChunkDataPack' +type ChunkDataPackHandler_HandleChunkDataPack_Call struct { + *mock.Call +} + +// HandleChunkDataPack is a helper method to define mock.On call +// - originID flow.Identifier +// - response *verification.ChunkDataPackResponse +func (_e *ChunkDataPackHandler_Expecter) HandleChunkDataPack(originID interface{}, response interface{}) *ChunkDataPackHandler_HandleChunkDataPack_Call { + return &ChunkDataPackHandler_HandleChunkDataPack_Call{Call: _e.mock.On("HandleChunkDataPack", originID, response)} +} + +func (_c *ChunkDataPackHandler_HandleChunkDataPack_Call) Run(run func(originID flow.Identifier, response *verification.ChunkDataPackResponse)) *ChunkDataPackHandler_HandleChunkDataPack_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 *verification.ChunkDataPackResponse + if args[1] != nil { + arg1 = args[1].(*verification.ChunkDataPackResponse) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkDataPackHandler_HandleChunkDataPack_Call) Return() *ChunkDataPackHandler_HandleChunkDataPack_Call { + _c.Call.Return() + return _c +} + +func (_c *ChunkDataPackHandler_HandleChunkDataPack_Call) RunAndReturn(run func(originID flow.Identifier, response *verification.ChunkDataPackResponse)) *ChunkDataPackHandler_HandleChunkDataPack_Call { + _c.Run(run) + return _c +} + +// NotifyChunkDataPackSealed provides a mock function for the type ChunkDataPackHandler +func (_mock *ChunkDataPackHandler) NotifyChunkDataPackSealed(chunkIndex uint64, resultID flow.Identifier) { + _mock.Called(chunkIndex, resultID) + return +} + +// ChunkDataPackHandler_NotifyChunkDataPackSealed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NotifyChunkDataPackSealed' +type ChunkDataPackHandler_NotifyChunkDataPackSealed_Call struct { + *mock.Call +} + +// NotifyChunkDataPackSealed is a helper method to define mock.On call +// - chunkIndex uint64 +// - resultID flow.Identifier +func (_e *ChunkDataPackHandler_Expecter) NotifyChunkDataPackSealed(chunkIndex interface{}, resultID interface{}) *ChunkDataPackHandler_NotifyChunkDataPackSealed_Call { + return &ChunkDataPackHandler_NotifyChunkDataPackSealed_Call{Call: _e.mock.On("NotifyChunkDataPackSealed", chunkIndex, resultID)} +} + +func (_c *ChunkDataPackHandler_NotifyChunkDataPackSealed_Call) Run(run func(chunkIndex uint64, resultID flow.Identifier)) *ChunkDataPackHandler_NotifyChunkDataPackSealed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkDataPackHandler_NotifyChunkDataPackSealed_Call) Return() *ChunkDataPackHandler_NotifyChunkDataPackSealed_Call { + _c.Call.Return() + return _c +} + +func (_c *ChunkDataPackHandler_NotifyChunkDataPackSealed_Call) RunAndReturn(run func(chunkIndex uint64, resultID flow.Identifier)) *ChunkDataPackHandler_NotifyChunkDataPackSealed_Call { + _c.Run(run) + return _c +} diff --git a/engine/verification/fetcher/mock/chunk_data_pack_requester.go b/engine/verification/fetcher/mock/chunk_data_pack_requester.go index fdf0973efe7..352d17daee3 100644 --- a/engine/verification/fetcher/mock/chunk_data_pack_requester.go +++ b/engine/verification/fetcher/mock/chunk_data_pack_requester.go @@ -1,79 +1,210 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - fetcher "github.com/onflow/flow-go/engine/verification/fetcher" + "github.com/onflow/flow-go/engine/verification/fetcher" + "github.com/onflow/flow-go/model/verification" mock "github.com/stretchr/testify/mock" - - verification "github.com/onflow/flow-go/model/verification" ) +// NewChunkDataPackRequester creates a new instance of ChunkDataPackRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChunkDataPackRequester(t interface { + mock.TestingT + Cleanup(func()) +}) *ChunkDataPackRequester { + mock := &ChunkDataPackRequester{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ChunkDataPackRequester is an autogenerated mock type for the ChunkDataPackRequester type type ChunkDataPackRequester struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *ChunkDataPackRequester) Done() <-chan struct{} { - ret := _m.Called() +type ChunkDataPackRequester_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunkDataPackRequester) EXPECT() *ChunkDataPackRequester_Expecter { + return &ChunkDataPackRequester_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type ChunkDataPackRequester +func (_mock *ChunkDataPackRequester) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *ChunkDataPackRequester) Ready() <-chan struct{} { - ret := _m.Called() +// ChunkDataPackRequester_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type ChunkDataPackRequester_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *ChunkDataPackRequester_Expecter) Done() *ChunkDataPackRequester_Done_Call { + return &ChunkDataPackRequester_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *ChunkDataPackRequester_Done_Call) Run(run func()) *ChunkDataPackRequester_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunkDataPackRequester_Done_Call) Return(valCh <-chan struct{}) *ChunkDataPackRequester_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ChunkDataPackRequester_Done_Call) RunAndReturn(run func() <-chan struct{}) *ChunkDataPackRequester_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type ChunkDataPackRequester +func (_mock *ChunkDataPackRequester) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Request provides a mock function with given fields: request -func (_m *ChunkDataPackRequester) Request(request *verification.ChunkDataPackRequest) { - _m.Called(request) +// ChunkDataPackRequester_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type ChunkDataPackRequester_Ready_Call struct { + *mock.Call } -// WithChunkDataPackHandler provides a mock function with given fields: handler -func (_m *ChunkDataPackRequester) WithChunkDataPackHandler(handler fetcher.ChunkDataPackHandler) { - _m.Called(handler) +// Ready is a helper method to define mock.On call +func (_e *ChunkDataPackRequester_Expecter) Ready() *ChunkDataPackRequester_Ready_Call { + return &ChunkDataPackRequester_Ready_Call{Call: _e.mock.On("Ready")} } -// NewChunkDataPackRequester creates a new instance of ChunkDataPackRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChunkDataPackRequester(t interface { - mock.TestingT - Cleanup(func()) -}) *ChunkDataPackRequester { - mock := &ChunkDataPackRequester{} - mock.Mock.Test(t) +func (_c *ChunkDataPackRequester_Ready_Call) Run(run func()) *ChunkDataPackRequester_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ChunkDataPackRequester_Ready_Call) Return(valCh <-chan struct{}) *ChunkDataPackRequester_Ready_Call { + _c.Call.Return(valCh) + return _c +} - return mock +func (_c *ChunkDataPackRequester_Ready_Call) RunAndReturn(run func() <-chan struct{}) *ChunkDataPackRequester_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Request provides a mock function for the type ChunkDataPackRequester +func (_mock *ChunkDataPackRequester) Request(request *verification.ChunkDataPackRequest) { + _mock.Called(request) + return +} + +// ChunkDataPackRequester_Request_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Request' +type ChunkDataPackRequester_Request_Call struct { + *mock.Call +} + +// Request is a helper method to define mock.On call +// - request *verification.ChunkDataPackRequest +func (_e *ChunkDataPackRequester_Expecter) Request(request interface{}) *ChunkDataPackRequester_Request_Call { + return &ChunkDataPackRequester_Request_Call{Call: _e.mock.On("Request", request)} +} + +func (_c *ChunkDataPackRequester_Request_Call) Run(run func(request *verification.ChunkDataPackRequest)) *ChunkDataPackRequester_Request_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *verification.ChunkDataPackRequest + if args[0] != nil { + arg0 = args[0].(*verification.ChunkDataPackRequest) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkDataPackRequester_Request_Call) Return() *ChunkDataPackRequester_Request_Call { + _c.Call.Return() + return _c +} + +func (_c *ChunkDataPackRequester_Request_Call) RunAndReturn(run func(request *verification.ChunkDataPackRequest)) *ChunkDataPackRequester_Request_Call { + _c.Run(run) + return _c +} + +// WithChunkDataPackHandler provides a mock function for the type ChunkDataPackRequester +func (_mock *ChunkDataPackRequester) WithChunkDataPackHandler(handler fetcher.ChunkDataPackHandler) { + _mock.Called(handler) + return +} + +// ChunkDataPackRequester_WithChunkDataPackHandler_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithChunkDataPackHandler' +type ChunkDataPackRequester_WithChunkDataPackHandler_Call struct { + *mock.Call +} + +// WithChunkDataPackHandler is a helper method to define mock.On call +// - handler fetcher.ChunkDataPackHandler +func (_e *ChunkDataPackRequester_Expecter) WithChunkDataPackHandler(handler interface{}) *ChunkDataPackRequester_WithChunkDataPackHandler_Call { + return &ChunkDataPackRequester_WithChunkDataPackHandler_Call{Call: _e.mock.On("WithChunkDataPackHandler", handler)} +} + +func (_c *ChunkDataPackRequester_WithChunkDataPackHandler_Call) Run(run func(handler fetcher.ChunkDataPackHandler)) *ChunkDataPackRequester_WithChunkDataPackHandler_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 fetcher.ChunkDataPackHandler + if args[0] != nil { + arg0 = args[0].(fetcher.ChunkDataPackHandler) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkDataPackRequester_WithChunkDataPackHandler_Call) Return() *ChunkDataPackRequester_WithChunkDataPackHandler_Call { + _c.Call.Return() + return _c +} + +func (_c *ChunkDataPackRequester_WithChunkDataPackHandler_Call) RunAndReturn(run func(handler fetcher.ChunkDataPackHandler)) *ChunkDataPackRequester_WithChunkDataPackHandler_Call { + _c.Run(run) + return _c } diff --git a/engine/verification/requester/requester.go b/engine/verification/requester/requester.go index 938e1752dad..53ba9dcad55 100644 --- a/engine/verification/requester/requester.go +++ b/engine/verification/requester/requester.go @@ -103,14 +103,14 @@ func (e *Engine) WithChunkDataPackHandler(handler fetcher.ChunkDataPackHandler) } // SubmitLocal submits an event originating on the local node. -func (e *Engine) SubmitLocal(event interface{}) { +func (e *Engine) SubmitLocal(event any) { e.log.Fatal().Msg("engine is not supposed to be invoked on SubmitLocal") } // Submit submits the given event from the node with the given origin ID // for processing in a non-blocking manner. It returns instantly and logs // a potential processing error internally when done. -func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { +func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, event any) { e.unit.Launch(func() { err := e.Process(channel, originID, event) if err != nil { @@ -120,13 +120,13 @@ func (e *Engine) Submit(channel channels.Channel, originID flow.Identifier, even } // ProcessLocal processes an event originating on the local node. -func (e *Engine) ProcessLocal(event interface{}) error { +func (e *Engine) ProcessLocal(event any) error { return fmt.Errorf("should not invoke ProcessLocal of Match engine, use Process instead") } // Process processes the given event from the node with the given origin ID in // a blocking manner. It returns the potential processing error when done. -func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { +func (e *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { return e.unit.Do(func() error { return e.process(originID, event) }) @@ -153,7 +153,7 @@ func (e *Engine) Done() <-chan struct{} { // it is successfully processed by the engine. // The origin ID indicates the node which originally submitted the event to // the peer-to-peer network. -func (e *Engine) process(originID flow.Identifier, event interface{}) error { +func (e *Engine) process(originID flow.Identifier, event any) error { switch resource := event.(type) { case *flow.ChunkDataResponse: e.handleChunkDataPackWithTracing(originID, &resource.ChunkDataPack) diff --git a/engine/verification/utils/unittest/fixture.go b/engine/verification/utils/unittest/fixture.go index c587fbfe2a6..018b769b4f6 100644 --- a/engine/verification/utils/unittest/fixture.go +++ b/engine/verification/utils/unittest/fixture.go @@ -267,11 +267,7 @@ func ExecutionResultFixture(t *testing.T, blocks := new(envMock.Blocks) - execCtx := fvm.NewContext( - fvm.WithLogger(log), - fvm.WithChain(chain), - fvm.WithBlocks(blocks), - ) + execCtx := fvm.NewContext(chain, fvm.WithLogger(log), fvm.WithBlocks(blocks)) // create state.View snapshot := exstate.NewLedgerStorageSnapshot( @@ -308,7 +304,6 @@ func ExecutionResultFixture(t *testing.T, committer, me, prov, - nil, protocolState, testMaxConcurrency) require.NoError(t, err) diff --git a/engine/verification/verifier/engine_test.go b/engine/verification/verifier/engine_test.go index 627ca29cdbb..3bf01b3cbf7 100644 --- a/engine/verification/verifier/engine_test.go +++ b/engine/verification/verifier/engine_test.go @@ -9,7 +9,6 @@ import ( "github.com/ipfs/go-cid" "github.com/jordanschalm/lockctx" "github.com/stretchr/testify/mock" - testifymock "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -69,11 +68,11 @@ func (suite *VerifierEngineTestSuite) SetupTest() { suite.approvals = mockstorage.NewResultApprovals(suite.T()) suite.chunkVerifier = mockmodule.NewChunkVerifier(suite.T()) - suite.net.On("Register", channels.PushApprovals, testifymock.Anything). + suite.net.On("Register", channels.PushApprovals, mock.Anything). Return(suite.pushCon, nil). Once() - suite.net.On("Register", channels.ProvideApprovalsByChunk, testifymock.Anything). + suite.net.On("Register", channels.ProvideApprovalsByChunk, mock.Anything). Return(suite.pullCon, nil). Once() @@ -128,7 +127,7 @@ func (suite *VerifierEngineTestSuite) TestVerifyHappyPath() { eng := suite.getTestNewEngine() consensusNodes := unittest.IdentityListFixture(1, unittest.WithRole(flow.RoleConsensus)) - suite.ss.On("Identities", testifymock.Anything).Return(consensusNodes, nil) + suite.ss.On("Identities", mock.Anything).Return(consensusNodes, nil) vChunk, _ := unittest.VerifiableChunkDataFixture(uint64(0)) @@ -183,9 +182,9 @@ func (suite *VerifierEngineTestSuite) TestVerifyHappyPath() { Once() suite.pushCon. - On("Publish", testifymock.Anything, testifymock.Anything). + On("Publish", mock.Anything, mock.Anything). Return(nil). - Run(func(args testifymock.Arguments) { + Run(func(args mock.Arguments) { // check that the approval matches the input execution result ra, ok := args[0].(*messages.ResultApproval) suite.Require().True(ok) diff --git a/engine/verification/verifier/verifiers.go b/engine/verification/verifier/verifiers.go index 45101a4fc6b..90ad44bc96e 100644 --- a/engine/verification/verifier/verifiers.go +++ b/engine/verification/verifier/verifiers.go @@ -41,17 +41,13 @@ func VerifyLastKHeight( stopOnMismatch bool, transactionFeesDisabled bool, scheduledTransactionsEnabled bool, -) (err error) { - closer, storages, chunkDataPacks, state, verifier, err := initStorages( - lockManager, - chainID, - protocolDataDir, - chunkDataPackDir, - transactionFeesDisabled, - scheduledTransactionsEnabled, - ) +) ( + totalStats BlockVerificationStats, + err error, +) { + closer, storages, chunkDataPacks, state, verifier, err := initStorages(lockManager, chainID, protocolDataDir, chunkDataPackDir, transactionFeesDisabled, scheduledTransactionsEnabled) if err != nil { - return fmt.Errorf("could not init storages: %w", err) + return BlockVerificationStats{}, fmt.Errorf("could not init storages: %w", err) } defer func() { closerErr := closer() @@ -62,14 +58,18 @@ func VerifyLastKHeight( lastSealed, err := state.Sealed().Head() if err != nil { - return fmt.Errorf("could not get last sealed height: %w", err) + return BlockVerificationStats{}, fmt.Errorf("could not get last sealed height: %w", err) } root := state.Params().SealedRoot().Height // preventing overflow if k > lastSealed.Height+1 { - return fmt.Errorf("k is greater than the number of sealed blocks, k: %d, last sealed height: %d", k, lastSealed.Height) + return BlockVerificationStats{}, fmt.Errorf( + "k is greater than the number of sealed blocks, k: %d, last sealed height: %d", + k, + lastSealed.Height, + ) } from := lastSealed.Height - k + 1 @@ -85,12 +85,23 @@ func VerifyLastKHeight( log.Info().Msgf("verifying blocks from %d to %d", from, to) - err = verifyConcurrently(from, to, nWorker, stopOnMismatch, storages.Headers, chunkDataPacks, storages.Results, state, verifier, verifyHeight) + totalStats, err = verifyConcurrently( + from, + to, + nWorker, + stopOnMismatch, + storages.Headers, + chunkDataPacks, + storages.Results, + state, + verifier, + verifyHeight, + ) if err != nil { - return err + return totalStats, err } - return nil + return totalStats, nil } // VerifyRange verifies all chunks in the results of the blocks in the given range. @@ -105,17 +116,13 @@ func VerifyRange( stopOnMismatch bool, transactionFeesDisabled bool, scheduledTransactionsEnabled bool, -) (err error) { - closer, storages, chunkDataPacks, state, verifier, err := initStorages( - lockManager, - chainID, - protocolDataDir, - chunkDataPackDir, - transactionFeesDisabled, - scheduledTransactionsEnabled, - ) +) ( + totalStats BlockVerificationStats, + err error, +) { + closer, storages, chunkDataPacks, state, verifier, err := initStorages(lockManager, chainID, protocolDataDir, chunkDataPackDir, transactionFeesDisabled, scheduledTransactionsEnabled) if err != nil { - return fmt.Errorf("could not init storages: %w", err) + return BlockVerificationStats{}, fmt.Errorf("could not init storages: %w", err) } defer func() { closerErr := closer() @@ -129,15 +136,30 @@ func VerifyRange( root := state.Params().SealedRoot().Height if from <= root { - return fmt.Errorf("cannot verify blocks before the root block, from: %d, root: %d", from, root) + return BlockVerificationStats{}, fmt.Errorf( + "cannot verify blocks before the root block, from: %d, root: %d", + from, + root, + ) } - err = verifyConcurrently(from, to, nWorker, stopOnMismatch, storages.Headers, chunkDataPacks, storages.Results, state, verifier, verifyHeight) + totalStats, err = verifyConcurrently( + from, + to, + nWorker, + stopOnMismatch, + storages.Headers, + chunkDataPacks, + storages.Results, + state, + verifier, + verifyHeight, + ) if err != nil { - return err + return totalStats, err } - return nil + return totalStats, nil } func verifyConcurrently( @@ -149,17 +171,29 @@ func verifyConcurrently( results storage.ExecutionResults, state protocol.State, verifier module.ChunkVerifier, - verifyHeight func(uint64, storage.Headers, storage.ChunkDataPacks, storage.ExecutionResults, protocol.State, module.ChunkVerifier, bool) error, -) error { + verifyHeight func( + height uint64, + headers storage.Headers, + chunkDataPacks storage.ChunkDataPacks, + results storage.ExecutionResults, + state protocol.State, + verifier module.ChunkVerifier, + stopOnMismatch bool, + ) (BlockVerificationStats, error), +) (BlockVerificationStats, error) { + tasks := make(chan uint64, int(nWorker)) ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Ensure cancel is called to release resources - var lowestErr error - var lowestErrHeight = ^uint64(0) // Initialize to max value of uint64 - var mu sync.Mutex // To protect access to lowestErr and lowestErrHeight + var ( + lowestErr error + lowestErrHeight = ^uint64(0) // Initialize to max value of uint64 + totalStats BlockVerificationStats + mu sync.Mutex // To protect access to variables above and blocksStats + ) - lg := util.LogProgress( + logProgress := util.LogProgress( log.Logger, util.DefaultLogProgressConfig( fmt.Sprintf("verifying heights progress for [%v:%v]", from, to), @@ -177,8 +211,26 @@ func verifyConcurrently( if !ok { return // Exit if the tasks channel is closed } + log.Info().Uint64("height", height).Msg("verifying height") - err := verifyHeight(height, headers, chunkDataPacks, results, state, verifier, stopOnMismatch) + + blockStats, err := verifyHeight( + height, + headers, + chunkDataPacks, + results, + state, + verifier, + stopOnMismatch, + ) + + mu.Lock() + + totalStats.MatchedChunkCount += blockStats.MatchedChunkCount + totalStats.MismatchedChunkCount += blockStats.MismatchedChunkCount + totalStats.MatchedTransactionCount += blockStats.MatchedTransactionCount + totalStats.MismatchedTransactionCount += blockStats.MismatchedTransactionCount + if err != nil { log.Error().Uint64("height", height).Err(err).Msg("error encountered while verifying height") @@ -186,18 +238,18 @@ func verifyConcurrently( // error, so we need to first cancel the context to stop worker from processing further tasks // and wait until all workers are done, which will ensure all the heights before this height // that had error are processed. Then we can safely update the lowestErr and lowestErrHeight - mu.Lock() if height < lowestErrHeight { lowestErr = err lowestErrHeight = height cancel() // Cancel context to stop further task dispatch } - mu.Unlock() } else { log.Info().Uint64("height", height).Msg("verified height successfully") } - lg(1) // log progress + mu.Unlock() + + logProgress(1) } } } @@ -230,10 +282,10 @@ func verifyConcurrently( // Check if there was an error if lowestErr != nil { log.Error().Uint64("height", lowestErrHeight).Err(lowestErr).Msg("error encountered while verifying height") - return fmt.Errorf("could not verify height %d: %w", lowestErrHeight, lowestErr) + return totalStats, fmt.Errorf("could not verify height %d: %w", lowestErrHeight, lowestErr) } - return nil + return totalStats, nil } func initStorages( @@ -295,6 +347,13 @@ func initStorages( return closer, storages, chunkDataPacks, state, verifier, nil } +type BlockVerificationStats struct { + MatchedChunkCount uint64 + MismatchedChunkCount uint64 + MatchedTransactionCount uint64 + MismatchedTransactionCount uint64 +} + // verifyHeight verifies all chunks in the results of the block at the given height. // Note: it returns nil if the block is not executed. func verifyHeight( @@ -305,10 +364,13 @@ func verifyHeight( state protocol.State, verifier module.ChunkVerifier, stopOnMismatch bool, -) error { +) ( + stats BlockVerificationStats, + err error, +) { header, err := headers.ByHeight(height) if err != nil { - return fmt.Errorf("could not get block header by height %d: %w", height, err) + return BlockVerificationStats{}, fmt.Errorf("could not get block header by height %d: %w", height, err) } blockID := header.ID() @@ -317,24 +379,26 @@ func verifyHeight( if err != nil { if errors.Is(err, storage.ErrNotFound) { log.Warn().Uint64("height", height).Hex("block_id", blockID[:]).Msg("execution result not found") - return nil + return BlockVerificationStats{}, nil } - return fmt.Errorf("could not get execution result by block ID %s: %w", blockID, err) + return BlockVerificationStats{}, fmt.Errorf("could not get execution result by block ID %s: %w", blockID, err) } snapshot := state.AtBlockID(blockID) for i, chunk := range result.Chunks { chunkDataPack, err := chunkDataPacks.ByChunkID(chunk.ID()) if err != nil { - return fmt.Errorf("could not get chunk data pack by chunk ID %s: %w", chunk.ID(), err) + return BlockVerificationStats{}, fmt.Errorf("could not get chunk data pack by chunk ID %s: %w", chunk.ID(), err) } vcd, err := convert.FromChunkDataPack(chunk, chunkDataPack, header, snapshot, result) if err != nil { - return err + return BlockVerificationStats{}, err } + chunkTransactionCount := vcd.Chunk.NumberOfTransactions + _, err = verifier.Verify(vcd) if err != nil { var collectionID flow.Identifier @@ -343,13 +407,43 @@ func verifyHeight( } if stopOnMismatch { - return fmt.Errorf("could not verify chunk (index: %v, ID: %v) at block %v (%v): %w", i, collectionID, height, blockID, err) + return BlockVerificationStats{ + MismatchedChunkCount: 1, + MismatchedTransactionCount: chunkTransactionCount, + }, fmt.Errorf( + "could not verify chunk (index: %v, ID: %v) at block %v (%v): %w", + i, + collectionID, + height, + blockID, + err, + ) + } + + if vcd.IsSystemChunk { + log.Warn().Err(err).Msgf( + "could not verify system chunk (index: %v, ID: %v) at block %v (%v)", + i, collectionID, height, blockID, + ) + } else { + + log.Error().Err(err).Msgf( + "could not verify chunk (index: %v, ID: %v) at block %v (%v)", + i, collectionID, height, blockID, + ) } - log.Error().Err(err).Msgf("could not verify chunk (index: %v, ID: %v) at block %v (%v)", i, collectionID, height, blockID) + stats.MismatchedChunkCount++ + stats.MismatchedTransactionCount += chunkTransactionCount + } else { + log.Info().Msgf("verified chunk (index: %v) at block %v (%v) successfully", i, height, blockID) + + stats.MatchedChunkCount++ + stats.MatchedTransactionCount += chunkTransactionCount } } - return nil + + return stats, nil } func makeVerifier( @@ -378,9 +472,10 @@ func makeVerifier( chainID, false, scheduledTransactionsEnabled, + false, )..., ) - vmCtx := fvm.NewContext(fvmOptions...) + vmCtx := fvm.NewContext(chainID.Chain(), fvmOptions...) chunkVerifier := chunks.NewChunkVerifier(vm, vmCtx, logger) return chunkVerifier diff --git a/engine/verification/verifier/verifiers_test.go b/engine/verification/verifier/verifiers_test.go index 907d9b6915c..addc07b844f 100644 --- a/engine/verification/verifier/verifiers_test.go +++ b/engine/verification/verifier/verifiers_test.go @@ -2,19 +2,29 @@ package verifier import ( "errors" - "fmt" "testing" + "github.com/stretchr/testify/assert" + testifymock "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" mockmodule "github.com/onflow/flow-go/module/mock" "github.com/onflow/flow-go/state/protocol" + protocolmock "github.com/onflow/flow-go/state/protocol/mock" "github.com/onflow/flow-go/storage" - "github.com/onflow/flow-go/storage/mock" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/utils/unittest" unittestMocks "github.com/onflow/flow-go/utils/unittest/mocks" ) func TestVerifyConcurrently(t *testing.T) { + errMock := errors.New("mock error") + errTwo := errors.New("error 2") + errFour := errors.New("error 4") + tests := []struct { name string from uint64 @@ -32,20 +42,25 @@ func TestVerifyConcurrently(t *testing.T) { expectedErr: nil, }, { - name: "Single error at a height", - from: 1, - to: 5, - nWorker: 3, - errors: map[uint64]error{3: errors.New("mock error")}, - expectedErr: fmt.Errorf("mock error"), + name: "Single error at a height", + from: 1, + to: 5, + nWorker: 3, + errors: map[uint64]error{ + 3: errMock, + }, + expectedErr: errMock, }, { - name: "Multiple errors, lowest height returned", - from: 1, - to: 5, - nWorker: 3, - errors: map[uint64]error{2: errors.New("error 2"), 4: errors.New("error 4")}, - expectedErr: fmt.Errorf("error 2"), + name: "Multiple errors, lowest height returned", + from: 1, + to: 5, + nWorker: 3, + errors: map[uint64]error{ + 2: errTwo, + 4: errFour, + }, + expectedErr: errTwo, }, } @@ -60,22 +75,33 @@ func TestVerifyConcurrently(t *testing.T) { state protocol.State, verifier module.ChunkVerifier, stopOnMismatch bool, - ) error { + ) (BlockVerificationStats, error) { if err, ok := tt.errors[height]; ok { - return err + return BlockVerificationStats{}, err } - return nil + return BlockVerificationStats{}, nil } - mockHeaders := mock.NewHeaders(t) - mockChunkDataPacks := mock.NewChunkDataPacks(t) - mockResults := mock.NewExecutionResults(t) + mockHeaders := storagemock.NewHeaders(t) + mockChunkDataPacks := storagemock.NewChunkDataPacks(t) + mockResults := storagemock.NewExecutionResults(t) mockState := unittestMocks.NewProtocolState() mockVerifier := mockmodule.NewChunkVerifier(t) - err := verifyConcurrently(tt.from, tt.to, tt.nWorker, true, mockHeaders, mockChunkDataPacks, mockResults, mockState, mockVerifier, mockVerifyHeight) + _, err := verifyConcurrently( + tt.from, + tt.to, + tt.nWorker, + true, + mockHeaders, + mockChunkDataPacks, + mockResults, + mockState, + mockVerifier, + mockVerifyHeight, + ) if tt.expectedErr != nil { - if err == nil || errors.Is(err, tt.expectedErr) { + if err == nil || !errors.Is(err, tt.expectedErr) { t.Fatalf("expected error: %v, got: %v", tt.expectedErr, err) } } else if err != nil { @@ -84,3 +110,258 @@ func TestVerifyConcurrently(t *testing.T) { }) } } + +func TestVerifyConcurrentlyAggregatesStats(t *testing.T) { + // each height returns different stats, verify they are summed correctly + statsPerHeight := map[uint64]BlockVerificationStats{ + 1: {MatchedChunkCount: 2, MismatchedChunkCount: 0, MatchedTransactionCount: 10, MismatchedTransactionCount: 0}, + 2: {MatchedChunkCount: 1, MismatchedChunkCount: 1, MatchedTransactionCount: 5, MismatchedTransactionCount: 3}, + 3: {MatchedChunkCount: 0, MismatchedChunkCount: 2, MatchedTransactionCount: 0, MismatchedTransactionCount: 8}, + } + + mockVerifyHeight := func( + height uint64, + headers storage.Headers, + chunkDataPacks storage.ChunkDataPacks, + results storage.ExecutionResults, + state protocol.State, + verifier module.ChunkVerifier, + stopOnMismatch bool, + ) (BlockVerificationStats, error) { + return statsPerHeight[height], nil + } + + totalStats, err := verifyConcurrently( + 1, 3, 2, false, + storagemock.NewHeaders(t), + storagemock.NewChunkDataPacks(t), + storagemock.NewExecutionResults(t), + unittestMocks.NewProtocolState(), + mockmodule.NewChunkVerifier(t), + mockVerifyHeight, + ) + require.NoError(t, err) + + assert.Equal(t, uint64(3), totalStats.MatchedChunkCount) + assert.Equal(t, uint64(3), totalStats.MismatchedChunkCount) + assert.Equal(t, uint64(15), totalStats.MatchedTransactionCount) + assert.Equal(t, uint64(11), totalStats.MismatchedTransactionCount) +} + +// setupVerifyHeightMocks creates mocks for verifyHeight with the given number of chunks. +// Each chunk gets NumberOfTransactions set to txPerChunk. +// The verifier mock is returned unconfigured so the caller can set up per-chunk behavior. +func setupVerifyHeightMocks( + t *testing.T, + height uint64, + numChunks int, + txPerChunk uint64, +) ( + *storagemock.Headers, + *storagemock.ChunkDataPacks, + *storagemock.ExecutionResults, + *protocolmock.State, + *mockmodule.ChunkVerifier, + *flow.ExecutionResult, +) { + header := unittest.BlockHeaderFixture(unittest.WithHeaderHeight(height)) + blockID := header.ID() + + startState := unittest.StateCommitmentFixture() + chunks := unittest.ChunkListFixture(uint(numChunks), blockID, startState) + for _, chunk := range chunks { + chunk.NumberOfTransactions = txPerChunk + } + + result := unittest.ExecutionResultFixture() + result.BlockID = blockID + result.Chunks = chunks + + headers := storagemock.NewHeaders(t) + headers.On("ByHeight", height).Return(header, nil) + + results := storagemock.NewExecutionResults(t) + results.On("ByBlockID", blockID).Return(result, nil) + + chunkDataPacks := storagemock.NewChunkDataPacks(t) + for _, chunk := range chunks { + coll := unittest.CollectionFixture(1) + cdp := unittest.ChunkDataPackFixture(chunk.ID(), unittest.WithChunkDataPackCollection(&coll)) + chunkDataPacks.On("ByChunkID", chunk.ID()).Return(cdp, nil).Maybe() + } + + mockState := protocolmock.NewState(t) + snapshot := protocolmock.NewSnapshot(t) + mockState.On("AtBlockID", blockID).Return(snapshot) + + chunkVerifier := mockmodule.NewChunkVerifier(t) + + return headers, chunkDataPacks, results, mockState, chunkVerifier, result +} + +func TestVerifyHeight_AllChunksMatch(t *testing.T) { + height := uint64(100) + txPerChunk := uint64(10) + numChunks := 3 + + headers, chunkDataPacks, results, state, chunkVerifier, _ := setupVerifyHeightMocks(t, height, numChunks, txPerChunk) + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, nil) + + stats, err := verifyHeight(height, headers, chunkDataPacks, results, state, chunkVerifier, false) + require.NoError(t, err) + + assert.Equal(t, uint64(numChunks), stats.MatchedChunkCount) + assert.Equal(t, uint64(0), stats.MismatchedChunkCount) + assert.Equal(t, uint64(numChunks)*txPerChunk, stats.MatchedTransactionCount) + assert.Equal(t, uint64(0), stats.MismatchedTransactionCount) +} + +func TestVerifyHeight_MismatchWithoutStop(t *testing.T) { + height := uint64(100) + txPerChunk := uint64(5) + numChunks := 3 + + headers, chunkDataPacks, results, state, chunkVerifier, _ := setupVerifyHeightMocks(t, height, numChunks, txPerChunk) + + verifyErr := errors.New("chunk mismatch") + // first call fails, subsequent calls succeed + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, verifyErr).Once() + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, nil) + + stats, err := verifyHeight(height, headers, chunkDataPacks, results, state, chunkVerifier, false) + require.NoError(t, err) + + assert.Equal(t, uint64(2), stats.MatchedChunkCount) + assert.Equal(t, uint64(1), stats.MismatchedChunkCount) + assert.Equal(t, uint64(2)*txPerChunk, stats.MatchedTransactionCount) + assert.Equal(t, txPerChunk, stats.MismatchedTransactionCount) +} + +func TestVerifyHeight_MismatchWithStop(t *testing.T) { + height := uint64(100) + txPerChunk := uint64(5) + numChunks := 3 + + headers, chunkDataPacks, results, state, chunkVerifier, _ := setupVerifyHeightMocks(t, height, numChunks, txPerChunk) + + verifyErr := errors.New("chunk mismatch") + // first chunk fails - with stopOnMismatch=true, should return error immediately + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, verifyErr).Once() + + stats, err := verifyHeight(height, headers, chunkDataPacks, results, state, chunkVerifier, true) + require.Error(t, err) + assert.ErrorIs(t, err, verifyErr) + assert.Equal(t, uint64(0), stats.MatchedChunkCount) + assert.Equal(t, uint64(1), stats.MismatchedChunkCount) + assert.Equal(t, uint64(0), stats.MatchedTransactionCount) + assert.Equal(t, txPerChunk, stats.MismatchedTransactionCount) +} + +func TestVerifyHeight_BlockNotExecuted(t *testing.T) { + height := uint64(100) + header := unittest.BlockHeaderFixture(unittest.WithHeaderHeight(height)) + blockID := header.ID() + + headers := storagemock.NewHeaders(t) + headers.On("ByHeight", height).Return(header, nil) + + results := storagemock.NewExecutionResults(t) + results.On("ByBlockID", blockID).Return(nil, storage.ErrNotFound) + + state := protocolmock.NewState(t) + chunkVerifier := mockmodule.NewChunkVerifier(t) + chunkDataPacks := storagemock.NewChunkDataPacks(t) + + stats, err := verifyHeight(height, headers, chunkDataPacks, results, state, chunkVerifier, false) + require.NoError(t, err) + assert.Equal(t, BlockVerificationStats{}, stats) +} + +func TestVerifyHeight_AllChunksMismatchWithoutStop(t *testing.T) { + height := uint64(100) + txPerChunk := uint64(7) + numChunks := 3 + + headers, chunkDataPacks, results, state, chunkVerifier, _ := setupVerifyHeightMocks(t, height, numChunks, txPerChunk) + + verifyErr := errors.New("chunk mismatch") + // all chunks fail, but stopOnMismatch=false so we continue and count all mismatches + // this also exercises the system chunk path (last chunk) + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, verifyErr) + + stats, err := verifyHeight(height, headers, chunkDataPacks, results, state, chunkVerifier, false) + require.NoError(t, err) + + assert.Equal(t, uint64(0), stats.MatchedChunkCount) + assert.Equal(t, uint64(numChunks), stats.MismatchedChunkCount) + assert.Equal(t, uint64(0), stats.MatchedTransactionCount) + assert.Equal(t, uint64(numChunks)*txPerChunk, stats.MismatchedTransactionCount) +} + +func TestVerifyHeight_VaryingTransactionCounts(t *testing.T) { + height := uint64(100) + header := unittest.BlockHeaderFixture(unittest.WithHeaderHeight(height)) + blockID := header.ID() + + startState := unittest.StateCommitmentFixture() + chunks := unittest.ChunkListFixture(3, blockID, startState) + // set different tx counts per chunk + chunks[0].NumberOfTransactions = 10 + chunks[1].NumberOfTransactions = 20 + chunks[2].NumberOfTransactions = 30 + + result := unittest.ExecutionResultFixture() + result.BlockID = blockID + result.Chunks = chunks + + headers := storagemock.NewHeaders(t) + headers.On("ByHeight", height).Return(header, nil) + + results := storagemock.NewExecutionResults(t) + results.On("ByBlockID", blockID).Return(result, nil) + + chunkDataPacks := storagemock.NewChunkDataPacks(t) + for _, chunk := range chunks { + coll := unittest.CollectionFixture(1) + cdp := unittest.ChunkDataPackFixture(chunk.ID(), unittest.WithChunkDataPackCollection(&coll)) + chunkDataPacks.On("ByChunkID", chunk.ID()).Return(cdp, nil).Maybe() + } + + state := protocolmock.NewState(t) + snapshot := protocolmock.NewSnapshot(t) + state.On("AtBlockID", blockID).Return(snapshot) + + verifyErr := errors.New("chunk mismatch") + chunkVerifier := mockmodule.NewChunkVerifier(t) + // chunk 0 (10 tx) matches, chunk 1 (20 tx) mismatches, chunk 2 (30 tx) matches + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, nil).Once() + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, verifyErr).Once() + chunkVerifier.On("Verify", testifymock.Anything).Return(nil, nil).Once() + + stats, err := verifyHeight(height, headers, chunkDataPacks, results, state, chunkVerifier, false) + require.NoError(t, err) + + assert.Equal(t, uint64(2), stats.MatchedChunkCount) + assert.Equal(t, uint64(1), stats.MismatchedChunkCount) + assert.Equal(t, uint64(40), stats.MatchedTransactionCount) // 10 + 30 + assert.Equal(t, uint64(20), stats.MismatchedTransactionCount) // 20 +} + +func TestVerifyHeight_HeaderNotFound(t *testing.T) { + height := uint64(100) + + headers := storagemock.NewHeaders(t) + headers.On("ByHeight", height).Return(nil, storage.ErrNotFound) + + stats, err := verifyHeight( + height, + headers, + storagemock.NewChunkDataPacks(t), + storagemock.NewExecutionResults(t), + protocolmock.NewState(t), + mockmodule.NewChunkVerifier(t), + false, + ) + require.Error(t, err) + assert.Equal(t, BlockVerificationStats{}, stats) +} diff --git a/flips/component-interface.md b/flips/component-interface.md deleted file mode 100644 index fed4129eb82..00000000000 --- a/flips/component-interface.md +++ /dev/null @@ -1,446 +0,0 @@ -# Component Interface (Core Protocol) - -| Status | Proposed | -:-------------- |:--------------------------------------------------------- | -| **FLIP #** | [1167](https://github.com/onflow/flow-go/pull/1167) | -| **Author(s)** | Simon Zhu (simon.zhu@dapperlabs.com) | -| **Sponsor** | Simon Zhu (simon.zhu@dapperlabs.com) | -| **Updated** | 9/16/2021 | - -## Objective - -FLIP to separate the API through which components are started from the API through which they expose their status. - -## Current Implementation - -The [`ReadyDoneAware`](https://github.com/onflow/flow-go/blob/7763000ba5724bb03f522380e513b784b4597d46/module/common.go#L6) interface provides an interface through which components / modules can be started and stopped. Calling the `Ready` method should start the component and return a channel that will close when startup has completed, and `Done` should be the corresponding method to shut down the component. - -### Potential problems - -The current `ReadyDoneAware` interface is misleading, as by the name one might expect that it is only used to check the state of a component. However, in almost all current implementations the `Ready` method is used to both start the component *and* check when it has started up, and similarly for the `Done` method. - -This introduces issues of concurrency safety / idempotency, as most implementations do not properly handle the case where the `Ready` or `Done` methods are called more than once. See [this example](https://github.com/onflow/flow-go/pull/1026). - -[Clearer documentation](https://github.com/onflow/flow-go/pull/1032) and a new [`LifecycleManager`](https://github.com/onflow/flow-go/pull/1031) component were introduced as a step towards fixing this by providing concurrency-safety for components implementing `ReadyDoneAware`, but this still does not provide a clear separation between the ability to start / stop a component and the ability to check its state. A component usually only needs to be started once, whereas multiple other components may wish to check its state. - -## Proposal - -Moving forward, we will add a new `Startable` interface in addition to the existing `ReadyDoneAware`: -```golang -// Startable provides an interface to start a component. Once started, the component -// can be stopped by cancelling the given context. -type Startable interface { - // Start starts the component. Any errors encountered during startup should be returned - // directly, whereas irrecoverable errors encountered while the component is running - // should be thrown with the given SignalerContext. - // This method should only be called once, and subsequent calls should return ErrMultipleStartup. - Start(irrecoverable.SignalerContext) error -} -``` -Components which implement this interface are passed in a `SignalerContext` upon startup, which they can use to propagate any irrecoverable errors they encounter up to their parent via `SignalerContext.Throw`. The parent can then choose to handle these errors however they like, including restarting the component, logging the error, propagating the error to their own parent, etc. - -```golang -// We define a constrained interface to provide a drop-in replacement for context.Context -// including in interfaces that compose it. -type SignalerContext interface { - context.Context - Throw(err error) // delegates to the signaler - sealed() // private, to constrain builder to using WithSignaler -} - -// private, to force context derivation / WithSignaler -type signalerCtx struct { - context.Context - *Signaler -} - -func (sc signalerCtx) sealed() {} - -// the One True Way of getting a SignalerContext -func WithSignaler(parent context.Context) (SignalerContext, <-chan error) { - sig, errChan := NewSignaler() - return &signalerCtx{parent, sig}, errChan -} - -// Signaler sends the error out. -type Signaler struct { - errChan chan error - errThrown *atomic.Bool -} - -func NewSignaler() (*Signaler, <-chan error) { - errChan := make(chan error, 1) - return &Signaler{ - errChan: errChan, - errThrown: atomic.NewBool(false), - }, errChan -} - -// Throw is a narrow drop-in replacement for panic, log.Fatal, log.Panic, etc -// anywhere there's something connected to the error channel. It only sends -// the first error it is called with to the error channel, there are various -// options as to how subsequent errors can be handled. -func (s *Signaler) Throw(err error) { - defer runtime.Goexit() - if s.errThrown.CAS(false, true) { - s.errChan <- err - close(s.errChan) - } else { - // Another thread, possibly from the same component, has already thrown - // an irrecoverable error to this Signaler. Any subsequent irrecoverable - // errors can either be logged or ignored, as the parent will already - // be taking steps to remediate the first error. - } -} -``` - -> For more details about `SignalerContext` and `ErrMultipleStartup`, see [#1275](https://github.com/onflow/flow-go/pull/1275) and [#1355](https://github.com/onflow/flow-go/pull/1355/). - -To start a component, a `SignalerContext` must be created to start it with: - -```golang -var parentCtx context.Context // this is the context for the routine which manages the component -var childComponent component.Component - -ctx, cancel := context.WithCancel(parentCtx) - -// create a SignalerContext and return an error channel which can be used to receive -// any irrecoverable errors thrown with the Signaler -signalerCtx, errChan := irrecoverable.WithSignaler(ctx) - -// start the child component -childComponent.Start(signalerCtx) - -// launch goroutine to handle errors thrown from the child component -go func() { - select { - case err := <-errChan: // error thrown by child component - cancel() - // handle the error... - case <-parentCtx.Done(): // canceled by parent - // perform any necessary cleanup... - } -} -``` - -With all of this in place, the semantics of `ReadyDoneAware` can be redefined to only be used to check a component's state (i.e wait for startup / shutdown to complete) -```golang -type ReadyDoneAware interface { - // Ready returns a channel that will close when component startup has completed. - Ready() <-chan struct{} - // Done returns a channel that will close when component shutdown has completed. - Done() <-chan struct{} -} -``` - -Finally, we can define a `Component` interface which combines both of these interfaces: -```golang -type Component interface { - Startable - ReadyDoneAware -} -``` - -A component will now be started by passing a `SignalerContext` to its `Start` method, and can be stopped by cancelling the `Context`. If a component needs to startup subcomponents, it can create child `Context`s from this `Context` and pass those to the subcomponents. -### Motivations -- `Context`s are the standard way of doing go-routine lifecycle management in Go, and adhering to standards helps eliminate confusion and ambiguity for anyone interacting with the `flow-go` codebase. This is especially true now that we are beginning to provide API's and interfaces for third parties to interact with the codebase (e.g DPS). - - Even to someone unfamiliar with our codebase (but familiar with Go idioms), it is clear how a method signature like `Start(context.Context) error` will behave. A method signature like `Ready()` is not so clear. -- This promotes a hierarchical supervision paradigm, where each `Component` is equipped with a fresh signaler to its parent at launch, and is thus supervised by his parent for any irrecoverable errors it may encounter (the call to `WithSignaler` replaces the signaler in a parent context). As a consequence, sub-components themselves started by a component have it as a supervisor, which handles their irrecoverable failures, and so on. - - If context propagation is done properly, there is no need to worry about any cleanup code in the `Done` method. Cancelling the context for a component will automatically cancel all subcomponents / child routines in the component tree, and we do not have to explicitly call `Done` on each and every subcomponent to trigger their shutdown. - - This allows us to separate the capability to check a component's state from the capability to start / stop it. We may want to give multiple other components the capability to check its state, without giving them the capability to start or stop it. Here is an [example](https://github.com/onflow/flow-go/blob/b50f0ffe054103a82e4aa9e0c9e4610c2cbf2cc9/engine/common/splitter/network/network.go#L112) of where this would be useful. - - This provides a clearer way of defining ownership of components, and hence may potentially eliminate the need to deal with concurrency-safety altogether. Whoever creates a component should be responsible for starting it, and therefore they should be the only one with access to its `Startable` interface. If each component only has a single parent that is capable of starting it, then we should never run into concurrency issues. - -## Implementation (WIP) -* Lifecycle management logic for components can be further abstracted into a `RunComponent` helper function: - - ```golang - type ComponentFactory func() (Component, error) - - // OnError reacts to an irrecoverable error - // It is meant to inspect the error, determining its type and seeing if e.g. a restart or some other measure is suitable, - // and then return an ErrorHandlingResult indicating how RunComponent should proceed. - // Before returning, it could also: - // - panic (in sandboxnet / benchmark) - // - log in various Error channels and / or send telemetry ... - type OnError = func(err error) ErrorHandlingResult - - type ErrorHandlingResult int - - const ( - ErrorHandlingRestart ErrorHandlingResult = iota - ErrorHandlingStop - ) - - // RunComponent repeatedly starts components returned from the given ComponentFactory, shutting them - // down when they encounter irrecoverable errors and passing those errors to the given error handler. - // If the given context is cancelled, it will wait for the current component instance to shutdown - // before returning. - // The returned error is either: - // - The context error if the context was canceled - // - The last error handled if the error handler returns ErrorHandlingStop - // - An error returned from componentFactory while generating an instance of component - func RunComponent(ctx context.Context, componentFactory ComponentFactory, handler OnError) error { - // reference to per-run signals for the component - var component Component - var cancel context.CancelFunc - var done <-chan struct{} - var irrecoverableErr <-chan error - - start := func() error { - var err error - - component, err = componentFactory() - if err != nil { - return err // failure to generate the component, should be handled out-of-band because a restart won't help - } - - // context used to run the component - var runCtx context.Context - runCtx, cancel = context.WithCancel(ctx) - - // signaler context used for irrecoverables - var signalCtx irrecoverable.SignalerContext - signalCtx, irrecoverableErr = irrecoverable.WithSignaler(runCtx) - - component.Start(signalCtx) - - done = component.Done() - - return nil - } - - stop := func() { - // shutdown the component and wait until it's done - cancel() - <-done - } - - for { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - if err := start(); err != nil { - return err // failure to start - } - - select { - case <-ctx.Done(): - stop() - return ctx.Err() - case err := <-irrecoverableErr: - stop() - - // send error to the handler - switch result := handler(err); result { - case ErrorHandlingRestart: - continue - case ErrorHandlingStop: - return err - default: - panic(fmt.Sprintf("invalid error handling result: %v", result)) - } - case <-done: - // Without this additional select, there is a race condition here where the done channel - // could have been closed as a result of an irrecoverable error being thrown, so that when - // the scheduler yields control back to this goroutine, both channels are available to read - // from. If this last case happens to be chosen at random to proceed instead of the one - // above, then we would return as if the component shutdown gracefully, when in fact it - // encountered an irrecoverable error. - select { - case err := <-irrecoverableErr: - switch result := handler(err); result { - case ErrorHandlingRestart: - continue - case ErrorHandlingStop: - return err - default: - panic(fmt.Sprintf("invalid error handling result: %v", result)) - } - default: - } - - // Similarly, the done channel could have closed as a result of the context being canceled. - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - // clean completion - return nil - } - } - } - ``` - - > Note: this is now implemented in [#1275](https://github.com/onflow/flow-go/pull/1275) and [#1355](https://github.com/onflow/flow-go/pull/1355), and an example can be found [here](https://github.com/onflow/flow-go/blob/24406ed3fde7661cb1df84a25755cedf041a1c50/module/irrecoverable/irrecoverable_example_test.go). -* We may be able to encapsulate a lot of the boilerplate code involved in handling startup / shutdown of worker routines into a single `ComponentManager` struct: - - ```golang - type ReadyFunc func() - - // ComponentWorker represents a worker routine of a component - type ComponentWorker func(ctx irrecoverable.SignalerContext, ready ReadyFunc) - - // ComponentManagerBuilder provides a mechanism for building a ComponentManager - type ComponentManagerBuilder interface { - // AddWorker adds a worker routine for the ComponentManager - AddWorker(ComponentWorker) ComponentManagerBuilder - - // Build builds and returns a new ComponentManager instance - Build() *ComponentManager - } - - // ComponentManager is used to manage the worker routines of a Component - type ComponentManager struct { - started *atomic.Bool - ready chan struct{} - done chan struct{} - shutdownSignal <-chan struct{} - - workers []ComponentWorker - } - - // Start initiates the ComponentManager by launching all worker routines. - func (c *ComponentManager) Start(parent irrecoverable.SignalerContext) { - // only start once - if c.started.CAS(false, true) { - ctx, cancel := context.WithCancel(parent) - signalerCtx, errChan := irrecoverable.WithSignaler(ctx) - c.shutdownSignal = ctx.Done() - - // launch goroutine to propagate irrecoverable error - go func() { - select { - case err := <-errChan: - cancel() // shutdown all workers - - // we propagate the error directly to the parent because a failure in a - // worker routine is considered irrecoverable - parent.Throw(err) - case <-c.done: - // Without this additional select, there is a race condition here where the done channel - // could be closed right after an irrecoverable error is thrown, so that when the scheduler - // yields control back to this goroutine, both channels are available to read from. If this - // second case happens to be chosen at random to proceed, then we would return and silently - // ignore the error. - select { - case err := <-errChan: - cancel() - parent.Throw(err) - default: - } - } - }() - - var workersReady sync.WaitGroup - var workersDone sync.WaitGroup - workersReady.Add(len(c.workers)) - workersDone.Add(len(c.workers)) - - // launch workers - for _, worker := range c.workers { - worker := worker - go func() { - defer workersDone.Done() - var readyOnce sync.Once - worker(signalerCtx, func() { - readyOnce.Do(func() { - workersReady.Done() - }) - }) - }() - } - - // launch goroutine to close ready channel - go c.waitForReady(&workersReady) - - // launch goroutine to close done channel - go c.waitForDone(&workersDone) - } else { - panic(module.ErrMultipleStartup) - } - } - - func (c *ComponentManager) waitForReady(workersReady *sync.WaitGroup) { - workersReady.Wait() - close(c.ready) - } - - func (c *ComponentManager) waitForDone(workersDone *sync.WaitGroup) { - workersDone.Wait() - close(c.done) - } - - // Ready returns a channel which is closed once all the worker routines have been launched and are ready. - // If any worker routines exit before they indicate that they are ready, the channel returned from Ready will never close. - func (c *ComponentManager) Ready() <-chan struct{} { - return c.ready - } - - // Done returns a channel which is closed once the ComponentManager has shut down. - // This happens when all worker routines have shut down (either gracefully or by throwing an error). - func (c *ComponentManager) Done() <-chan struct{} { - return c.done - } - - // ShutdownSignal returns a channel that is closed when shutdown has commenced. - // This can happen either if the ComponentManager's context is canceled, or a worker routine encounters - // an irrecoverable error. - // If this is called before Start, a nil channel will be returned. - func (c *ComponentManager) ShutdownSignal() <-chan struct{} { - return c.shutdownSignal - } - ``` - - Components that want to implement `Component` can use this `ComponentManager` to simplify implementation: - - ```golang - type FooComponent struct { - *component.ComponentManager - } - - func NewFooComponent(foo fooType) *FooComponent { - f := &FooComponent{} - - cmb := component.NewComponentManagerBuilder(). - AddWorker(f.childRoutine). - AddWorker(f.childRoutineWithFooParameter(foo)) - - f.ComponentManager = cmb.Build() - - return f - } - - func (f *FooComponent) childRoutine(ctx irrecoverable.SignalerContext) { - for { - select { - case <-ctx.Done(): - return - default: - // do work... - } - } - } - - func (f *FooComponent) childRoutineWithFooParameter(foo fooType) component.ComponentWorker { - return func(ctx irrecoverable.SignalerContext) { - for { - select { - case <-ctx.Done(): - return - default: - // do work with foo... - - // encounter irrecoverable error - ctx.Throw(errors.New("fatal error!")) - } - } - } - } - ``` - - > Note: this is now implemented in [#1355](https://github.com/onflow/flow-go/pull/1355) diff --git a/flips/network-api.md b/flips/network-api.md deleted file mode 100644 index a2caa57f54d..00000000000 --- a/flips/network-api.md +++ /dev/null @@ -1,93 +0,0 @@ -# Network Layer API (Core Protocol) - -| Status | Proposed | -:-------------- |:--------------------------------------------------------- | -| **FLIP #** | [1306](https://github.com/onflow/flow-go/pull/1306) | -| **Author(s)** | Simon Zhu (simon.zhu@dapperlabs.com) | -| **Sponsor** | Simon Zhu (simon.zhu@dapperlabs.com) | -| **Updated** | 9/16/2021 | - -## Objective - -Refactor the networking layer to split it into separate APIs for the public and private network, allow us to implement a strict separation in the code between these two networks. - -Enable registering a custom message ID function for the gossip layer. - -## Current Implementation - -When the network layer receives a message, it will pass the message to the [`Engine`](https://github.com/onflow/flow-go/blob/7763000ba5724bb03f522380e513b784b4597d46/network/engine.go) registered on -the corresponding channel by [calling the engine's `Process` method](https://github.com/onflow/flow-go/blob/d31fd63eb651ed9faf0f677e9934baef6c4d9792/network/p2p/network.go#L406), passing it the Flow ID of the message sender. - -[`Multicast`](https://github.com/onflow/flow-go/blob/4ddc17d1bee25c2ab12ceabcf814b702980fdebe/network/conduit.go#L82) is implemented by including a [`TargetIDs`](https://github.com/onflow/flow-go/blob/4ddc17d1bee25c2ab12ceabcf814b702980fdebe/network/message/message.proto#L12) field inside the message, which is published to a specific topic on the underlying gossip network. Upon receiving a new message on the gossip network, nodes must first [validate](https://github.com/onflow/flow-go/blob/4ddc17d1bee25c2ab12ceabcf814b702980fdebe/network/validator/targetValiator.go) that they are one of the intended recipients of the message before processing it. - -### Potential problems - -The current network layer API was designed with the assumption that all messages sent and received either target or originate from staked Flow nodes. This is why an engine's [`Process`](https://github.com/onflow/flow-go/blob/master/network/engine.go#L28) method accepts a Flow ID identifying the message sender, and outgoing messages [must specify Flow ID(s)](https://github.com/onflow/flow-go/blob/master/network/conduit.go#L62) as targets. - -This assumption is no longer true today. The access node, for example, may communicate with multiple (unstaked) consensus followers. It's perceivable that in the future there will be even more cases where communication with unstaked parties may happen (for example, execution nodes talking to DPS). - -Currently, a [`Message`](https://github.com/onflow/flow-go/blob/698c77460bc33d1a8ee8a154f7fe4877bc518a02/network/message/message.proto) which is sent over the network contains many unnecessary fields which can be deduced by the receiver of the message. The only exceptions to this are the `Payload` field (which contains the actual message data) and the `TargetIDs` field (which is used by `Multicast`). - -However, all of the existing calls to `Multicast` only target a very small number of recipients (3 to be exact), which means that there is a lot of noise on the network causing nodes to waste CPU cycles processing messages only to ignore them once they realize they are not one of the intended recipients. - -## Proposal - -We should split the existing network layer API into two distinct APIs / packages for the public and private network, and the `Engine` API should be modified so that the [`Process`](https://github.com/onflow/flow-go/blob/master/network/engine.go#L28) and [`Submit`](https://github.com/onflow/flow-go/blob/master/network/engine.go#L20) methods receive a `Context` as the first argument: - -* Private network - ```golang - type Engine interface { - Submit(ctx context.Context, channel Channel, originID flow.Identifier, event interface{}) - Process(ctx context.Context, channel Channel, originID flow.Identifier, event interface{}) error - } - - type Conduit interface { - Publish(event interface{}, targetIDs ...flow.Identifier) error - Unicast(event interface{}, targetID flow.Identifier) error - Multicast(event interface{}, num uint, targetIDs ...flow.Identifier) error - } - ``` -* Public network - ```golang - type Engine interface { - Submit(ctx context.Context, channel Channel, senderPeerID peer.ID, event interface{}) - Process(ctx context.Context, channel Channel, senderPeerID peer.ID, event interface{}) error - } - - type Conduit interface { - Publish(event interface{}, targetIDs ...peer.ID) error - Unicast(event interface{}, targetID peer.ID) error - Multicast(event interface{}, num uint, targetIDs ...peer.ID) error - } - ``` - -Various types of request-scoped data may be included in the `Context` as [values](https://pkg.go.dev/context#WithValue). For example, if a message sent on the public network originates from a staked node, that node's Flow ID may be included as a value. Once engine-side message queues are standardized as described in [FLIP 343](https://github.com/onflow/flow/pull/343), the given `Context` can be placed in the message queue along with the message itself in a wrapper struct: - -```golang -type Message struct { - ctx context.Context - event interface{} -} -``` - -> While this may seem to break the general rule of not storing `Context`s in structs, storing `Context`s in structs which are being passed like parameters is one of the exceptions to this rule. See [this](https://github.com/golang/go/issues/22602#:~:text=While%20we%27ve%20told,documentation%20and%20examples.) and [this](https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39#:~:text=The%20one%20exception%20to%20not%20storing%20a%20context%20is%20when%20you%20need%20to%20put%20it%20in%20a%20struct%20that%20is%20used%20purely%20as%20a%20message%20that%20is%20passed%20across%20a%20channel.%20This%20is%20shown%20in%20the%20example%20below.). The idea is that `Context`s should not be **stored** but should **flow** through the program, which is what they do in this usecase. - -When the message is dequeued, the engine should check the `Context` to see whether the message might already be obsolete before processing it. At this point, we will have two distinct `Context`s in scope: -* The message `Context` -* The `Context` of the goroutine which is dequeing / processing the message - -These can be combined into a [single context](https://github.com/teivah/onecontext) which can be used by the message processing business logic, so that the processing can be cancelled either by the network or by the engine. This will allow us to deprecate [`engine.Unit`](https://github.com/onflow/flow-go/blob/master/engine/unit.go), which uses a single `Context` for the entire engine. - -There are certain types of messages (e.g block proposals) which may transit between the private and public networks via relay nodes (e.g Access Nodes). Libp2p's [default message ID function](https://github.com/libp2p/go-libp2p-pubsub/blob/0c7092d1f50091ae88407ba93103ac5868da3d0a/pubsub.go#L1040-L1043) will treat a message originating from one network, relayed to the other network by `n` distinct relay nodes, as `n` distinct messages, causing unacceptable message duplification / traffic amplification. In order to prevent this, we will need to define a [custom message ID function](https://pkg.go.dev/github.com/libp2p/go-libp2p-pubsub#WithMessageIdFn) which returns the hash of the message [`Payload`](https://github.com/onflow/flow-go/blob/698c77460bc33d1a8ee8a154f7fe4877bc518a02/network/message/message.proto#L13). - -In order to avoid making the message ID function deserialize the `Message` to access the `Payload`, we need to remove all other fields from the `Message` protobuf so that the message ID function can simply take the hash of the pubsub [`Data`](https://github.com/libp2p/go-libp2p-pubsub/blob/0c7092d1f50091ae88407ba93103ac5868da3d0a/pb/rpc.pb.go#L145) field without needing to do any deserialization. - -The `Multicast` implementation will need to be changed to make direct connections to the target peers instead of sending messages with a `TargetIDs` field via gossip. - -### Motivations -- Having a strict separation between the public and private networks provides better safety by preventing unintended passage of messages between the two networks, and makes it easier to implement mechanisms for message prioritization / rate-limiting on staked nodes which participate in both. -- Passing `Context`s gives the network layer the ability to cancel the processing of a network message. This can be leveraged to implement [timeouts](https://pkg.go.dev/context#WithTimeout), but may also be useful for other situations. For example, if the network layer becomes aware that a certain peer has become unreachable, it can cancel the processing of any sync requests from that peer. -- Since existing calls to `Multicast` only target 3 peers, changing the implementation to use direct connections instead of gossip will reduce traffic on the network and make it more efficient. -- While `engine.Unit` provides some useful functionalities, it also uses the anti-pattern of [storing a `Context` inside a struct](https://github.com/onflow/flow-go/blob/b50f0ffe054103a82e4aa9e0c9e4610c2cbf2cc9/engine/unit.go#L117), something which is [specifically advised against](https://pkg.go.dev/context#:~:text=Do%20not%20store%20Contexts%20inside%20a%20struct%20type%3B%20instead%2C%20pass%20a%20Context%20explicitly%20to%20each%20function%20that%20needs%20it.%20The%20Context%20should%20be%20the%20first%20parameter%2C%20typically%20named%20ctx%3A) by [the developers of Go](https://go.dev/blog/context-and-structs#TOC_2.). Here is an [example](https://go.dev/blog/context-and-structs#:~:text=Storing%20context%20in%20structs%20leads%20to%20confusion) illustrating some of the problems with this approach. - -## Implementation (TODO) diff --git a/flips/sync-protocol.md b/flips/sync-protocol.md deleted file mode 100644 index c4ca019eb21..00000000000 --- a/flips/sync-protocol.md +++ /dev/null @@ -1,109 +0,0 @@ -# Sync Engine (Core Protocol) - -| Status | Proposed | -:-------------- |:--------------------------------------------------------- | -| **FLIP #** | 1697 | -| **Author(s)** | Simon Zhu (simon.zhu@dapperlabs.com) | -| **Sponsor** | Simon Zhu (simon.zhu@dapperlabs.com) | -| **Updated** | 11/29/2021 | - -## Objective - -Redesign the synchronization protocol to improve efficiency, robustness, and Byzantine fault tolerance. - -## Current Implementation - -The current synchronization protocol implementation consists of two main pieces: -* The [Sync Engine](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/engine/common/synchronization/engine.go) interfaces with the network layer and handles sending synchronization requests to other nodes and processing responses. -* The [Sync Core](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go) implements the core logic, configuration, and state management of the synchronization protocol. - -There are three types of synchronization requests: -* A [Sync Height Request](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/model/messages/synchronization.go#L8-L14) is sent to share the local finalized height while requesting the same information from the recipient. It is replied to with a [Sync Height Response](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/model/messages/synchronization.go#L16-L22). -* A [Batch Request](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/model/messages/synchronization.go#L34-L40) requests a list of blocks by ID. It is replied to with a [Block Response](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/model/messages/synchronization.go#L42-L48). -* A [Range Request](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/model/messages/synchronization.go#L24-L32) requests a range of finalized blocks by height. It is replied to with a [Block Response](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/model/messages/synchronization.go#L42-L48). - -The Sync Core uses two data structures to track the statuses of requestable items: -* [`Heights`](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L53) tracks the set of requestable finalized block heights. It is used to generate Ranges for the Sync Engine to request. -* [`BlockIDs`](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L54) tracks the set of requestable block IDs. It is used to generate Batches for the Sync Engine to request. - -The Sync Engine periodically picks a small number of random nodes to send Sync Height Requests to. It also periodically calls [`ScanPending`](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L148-L166) to get a list of requestable Ranges and Batches from the Sync Core, and picks some random nodes to send those requests to. - -Each time the Compliance Engine processes a new block proposal, it finds the first ancestor which has not yet been received (if one exists) and calls [`RequestBlock`](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L114-L126) to request the missing block ID. `RequestBlock` updates `BlockIDs` by queueing the block ID. - -Each time the Sync Engine receives a Sync Height Response, it calls [`HandleHeight`](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L95-L112) to pass the received height to the Sync Core, which updates `Heights` by queueing all heights between the local finalized height and the received height. - -Each time the Sync Engine receives a Block Response, it calls [`HandleBlock`](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L67-L93) to pass each of the received blocks to the Sync Core, which updates the tracked statuses in `Heights` and `BlockIDs`. - -### Potential Problems - -* Items in `BlockIDs` do not contain the block height, which means that they cannot be pruned until the corresponding block has actually been received. If a malicious block proposal causes a non-existent parent ID to be queued by the Compliance Engine, the item will not be pruned until the maximum number of attempts is reached. -* After a block corresponding to an item in `BlockIDs` is received, the item is not pruned until the local finalized height surpasses the height of the block. If a node is very far behind, `BlockIDs` could grow very large before the local finalization catches up. -* When the Sync Engine calls `ScanPending`, it passes in the local finalized height, which the Sync Core uses to prune requestable items. Since `Heights` and `BlockIDs` are both implemented using Go maps, pruning them involves iterating through all items to find the ones for which the associated block height is lower than the local finalized height, which is inefficient. Furthermore, pruning is triggered on every call to `ScanPending`, even if the local finalized height has not changed. -* The implementation of `ScanPending` is split into three steps: - * Iterate through `Heights` and `BlockIDs` and [find all requestable heights and block IDs](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L264-L326). - * Group these requestable items into [Ranges](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L360-L415) and [Batches](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L417-L439). - * [Select a subset of these Ranges and Batches to return](https://github.com/onflow/flow-go/blob/39c455da40c8f0aa6f9962c48f4cd34a5cbacfc0/module/synchronization/core.go#L441-L454) based on a configurable limit on the maximum number of in-flight requests. - - While conceptually easy to understand, this implementation is inefficient and performs many more loop iterations than necessary. -* `HandleHeight` iterates over the entire range from the local finalized height to the received height, queueing all new heights and requeueing heights which have already been received. This can be expensive if the node is very far behind. -* The Sync Core optimistically sets the status of an item in `Heights` as Received as soon as *any* block with the corresponding height is received, even though it has no way of knowing whether the received block has actually been finalized by consensus. This could cause the height to stop being requested before the finalized block has actually been received. It's also possible that this could cause `Heights` to become fragmented (smaller requestable ranges). -* Processing a Range Request response may or may not advance the local finalized height. There are two reasons why it may not progress: - * The response contains blocks that are not actually finalized (e.g. received from a malicious node). - * More blocks are needed to form a Three-Chain and advance the local finalized height. Although this case becomes increasingly unlikely with larger ranges, it is theoretically still possible under the event-driven version of the [HotStuff](https://arxiv.org/abs/1803.05069) algorithm. - - The Sync Core does not account for the second case, and so it is possible that the Sync Engine gets stuck requesting the same range over and over. -* There is no way to determine whether a Sync Height Response is honest or not. If `HandleHeight` is called for every received Sync Height Response, an attacker could cause `Heights` to grow unboundedly large by sending a Sync Height Response with an absurdly high height. - -## Proposal - -The `RequestBlock` API should be updated to accept a block height, which should be stored with the queued item in `BlockIDs`. This will allow items in `BlockIDs` to be pruned as soon as the local finalized height surpasses their associated block heights. This also allows the Sync Core to ignore calls to `RequestBlock` for block heights which exceed the local finalized height by more than a configurable threshold. This helps to reduce the amount of resources spent tracking and requesting blocks which cannot immediately be finalized anyways. - -Instead of pruning on every call to `ScanPending`, the Sync Core should keep track of the local finalized height from the latest call to `ScanPending`, and only trigger pruning if the height has actually changed. If necessary, it's possible to optimize the performance of pruning and avoid iterating through every item in `BlockIDs` by maintaining an additional mapping from block heights to the set of requestable block IDs at each height. - -Instead of sending synchronization requests via gossip, we should directly create a new stream to another node for each request and validate the response we receive: -* A Range Request response should contain a single chain of blocks which begins at the start height of the requested range and is no longer than the size of the requested range. -* A Batch Request response should contain a subset of the requested block IDs. - -This eliminates any ambiguity about whether a response corresponds to a Batch or Range Request, so we can avoid optimistically setting the statuses of heights as Received for responses to Batch Requests. - -At any time, there is a single range of heights that the Sync Engine actively requests, which is tracked by the Sync Core. We call this the Active Range. The Active Range is parameterized by two variables `RangeStart` and `RangeEnd`, which effectively replace the `Heights` map from the existing implementation, but it can be broken up and requested by the Sync Engine in multiple segments. `RangeStart` should be greater than the local finalized block height, and `RangeEnd` should be less than or equal to the target finalized block height (more details below). The logic for updating the Active Range can be abstracted with an interface: - -```golang -type ActiveRange interface { - // Update processes a range of blocks received from a Range Request - // response and updates the requestable height range. - Update(headers []flow.Header, originID flow.Identifier) - - // LocalFinalizedHeight is called to notify a change in the local finalized height. - LocalFinalizedHeight(height uint64) - - // TargetFinalizedHeight is called to notify a change in the target finalized height. - TargetFinalizedHeight(height uint64) - - // Get returns the range of requestable block heights. - Get() chainsync.Range -} -``` - -There are many ways to implement this interface, but one possible approach is as follows: -* Select values for parameters `DefaultRangeSize` and `MinResponses` -* Let `PendingStart` be the first height greater than `LocalFinalizedHeight` that has been received less than `MinResponses` times -* Let `RangeStart` be equal to `LocalFinalizedHeight + 1` -* Let `RangeEnd` be the smaller of `TargetFinalizedHeight` and `PendingStart + DefaultRangeSize` - -The reason we keep track of `PendingStart` is to ensure that `RangeEnd` eventually increases even if the local finalized height doesn't. This is needed to address the second last item in [Potential Problems](#potential-problems). - -The target finalized height represents the speculated finalized block height of the overall chain, and should reflect the Sync Height Responses that have been received while accounting for the possibility that some of these responses are malicious. Therefore, the Sync Height Response processing logic should incorporate some sort of expiration / filtering mechanism. The details of this logic can be abstracted with an interface: - -```golang -type TargetFinalizedHeight interface { - // Update processes a height received from a Sync Height Response - // and updates the finalized height estimate. - Update(height uint64, originID flow.Identifier) - - // Get returns the estimated finalized height of the overall chain. - Get() uint64 -} -``` - -One possible approach is to maintain a sliding window of the most recent Sync Height Responses, and take the median of these values. This implies that the target finalized height will always lag slightly behind the true finalized height, which may or may not be a problem depending on the block finalization rate. diff --git a/follower/follower_builder.go b/follower/follower_builder.go index 7bc46b95950..a1947ff3818 100644 --- a/follower/follower_builder.go +++ b/follower/follower_builder.go @@ -40,6 +40,7 @@ import ( "github.com/onflow/flow-go/network/channels" cborcodec "github.com/onflow/flow-go/network/codec/cbor" "github.com/onflow/flow-go/network/converter" + "github.com/onflow/flow-go/network/message" "github.com/onflow/flow-go/network/p2p" "github.com/onflow/flow-go/network/p2p/cache" "github.com/onflow/flow-go/network/p2p/conduit" @@ -626,6 +627,7 @@ func (builder *FollowerServiceBuilder) enqueuePublicNetworkInit() { SlashingViolationConsumerFactory: func(adapter network.ConduitAdapter) network.ViolationsConsumer { return slashing.NewSlashingViolationsConsumer(builder.Logger, builder.Metrics.Network, adapter) }, + UnicastStreamAuthorizer: message.AlwaysAuthorizedUnicastSenderRole, }, underlay.WithMessageValidators(publicNetworkMsgValidators(node.Logger, node.IdentityProvider, node.NodeID)...)) if err != nil { return nil, fmt.Errorf("could not initialize network: %w", err) diff --git a/fvm/accounts_test.go b/fvm/accounts_test.go index 9a5f1380c48..35ada309c6f 100644 --- a/fvm/accounts_test.go +++ b/fvm/accounts_test.go @@ -80,7 +80,7 @@ func createAccount( event := data.(cadence.Event) - address := flow.ConvertAddress( + address := flow.Address( cadence.SearchFieldByName( event, stdlib.AccountEventAddressParameter.Identifier, @@ -401,7 +401,7 @@ func TestCreateAccount(t *testing.T) { event := data.(cadence.Event) - address := flow.ConvertAddress( + address := flow.Address( cadence.SearchFieldByName( event, stdlib.AccountEventAddressParameter.Identifier, @@ -454,7 +454,7 @@ func TestCreateAccount(t *testing.T) { event := data.(cadence.Event) - address := flow.ConvertAddress( + address := flow.Address( cadence.SearchFieldByName( event, stdlib.AccountEventAddressParameter.Identifier, diff --git a/fvm/blueprints/bridge.go b/fvm/blueprints/bridge.go index 17a7cadcb91..d4813b52ebb 100644 --- a/fvm/blueprints/bridge.go +++ b/fvm/blueprints/bridge.go @@ -34,6 +34,8 @@ var BridgeContracts = []string{ "cadence/contracts/bridge/interfaces/CrossVMToken.cdc", "cadence/contracts/bridge/interfaces/IEVMBridgeNFTMinter.cdc", "cadence/contracts/bridge/interfaces/IEVMBridgeTokenMinter.cdc", + "cadence/contracts/bridge/FlowEVMBridgeCustomAssociationTypes.cdc", + "cadence/contracts/bridge/FlowEVMBridgeCustomAssociations.cdc", "cadence/contracts/bridge/FlowEVMBridgeConfig.cdc", "cadence/contracts/bridge/interfaces/IFlowEVMNFTBridge.cdc", "cadence/contracts/bridge/interfaces/IFlowEVMTokenBridge.cdc", diff --git a/fvm/blueprints/scheduled_callback.go b/fvm/blueprints/scheduled_callback.go index 0afcc44c493..38463da568b 100644 --- a/fvm/blueprints/scheduled_callback.go +++ b/fvm/blueprints/scheduled_callback.go @@ -56,14 +56,9 @@ func ExecuteCallbacksTransactions(chain flow.Chain, processEvents flow.EventsLis return nil, fmt.Errorf("failed to get callback args from event: %w", err) } - tx, err := flow.NewTransactionBodyBuilder(). - AddAuthorizer(sc.ScheduledTransactionExecutor.Address). - SetScript(script). - AddArgument(id). - SetComputeLimit(effort). - Build() + tx, err := generateExecuteCallbacksTransaction(sc, script, id, effort) if err != nil { - return nil, fmt.Errorf("failed to construct execute callback transactions: %w", err) + return nil, fmt.Errorf("failed to generate execute callback transaction: %w", err) } txs = append(txs, tx) } @@ -71,15 +66,53 @@ func ExecuteCallbacksTransactions(chain flow.Chain, processEvents flow.EventsLis return txs, nil } +// ExecuteCallbacksTransaction constructs a list of transaction to execute callbacks, for the given chain. +// +// No error returns are expected during normal operation. +func ExecuteCallbacksTransaction(chain flow.Chain, id uint64, effort uint64) (*flow.TransactionBody, error) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + env := sc.AsTemplateEnv() + script := templates.GenerateSchedulerExecutorTransactionScript(env) + + return generateExecuteCallbacksTransaction(sc, script, id, effort) +} + +// generateExecuteCallbacksTransaction generates a transaction to execute a callback, for the given chain. +// +// No error returns are expected during normal operation. +func generateExecuteCallbacksTransaction( + sc *systemcontracts.SystemContracts, + script []byte, + id uint64, + effort uint64, +) (*flow.TransactionBody, error) { + encID, err := jsoncdc.Encode(cadence.UInt64(id)) + if err != nil { + return nil, fmt.Errorf("failed to encode id: %w", err) + } + + tx, err := flow.NewTransactionBodyBuilder(). + AddAuthorizer(sc.ScheduledTransactionExecutor.Address). + SetScript(script). + AddArgument(encID). + SetComputeLimit(effort). + Build() + if err != nil { + return nil, fmt.Errorf("failed to construct execute callback transactions: %w", err) + } + + return tx, nil +} + // callbackArgsFromEvent decodes the event payload and returns the callback ID and effort. // // The event for processed callback event is emitted by the process callback transaction from // callback scheduler contract and has the following signature: // event PendingExecution(id: UInt64, priority: UInt8, executionEffort: UInt64, fees: UFix64, callbackOwner: Address) -func callbackArgsFromEvent(event flow.Event) ([]byte, uint64, error) { +func callbackArgsFromEvent(event flow.Event) (uint64, uint64, error) { cadenceId, cadenceEffort, err := ParsePendingExecutionEvent(event) if err != nil { - return nil, 0, err + return 0, 0, err } effort := uint64(cadenceEffort) @@ -89,12 +122,7 @@ func callbackArgsFromEvent(event flow.Event) ([]byte, uint64, error) { effort = flow.DefaultMaxTransactionGasLimit } - encID, err := jsoncdc.Encode(cadenceId) - if err != nil { - return nil, 0, fmt.Errorf("failed to encode id: %w", err) - } - - return encID, uint64(effort), nil + return uint64(cadenceId), uint64(effort), nil } // ParsePendingExecutionEvent decodes the PendingExecution event payload and returns the scheduled diff --git a/fvm/blueprints/scheduled_callback_test.go b/fvm/blueprints/scheduled_callback_test.go index 9aa7e2d1d67..d019db9f79c 100644 --- a/fvm/blueprints/scheduled_callback_test.go +++ b/fvm/blueprints/scheduled_callback_test.go @@ -18,6 +18,7 @@ import ( "github.com/onflow/flow-go/fvm/systemcontracts" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/utils/unittest" + "github.com/onflow/flow-go/utils/unittest/fixtures" ) func TestProcessCallbacksTransaction(t *testing.T) { @@ -351,3 +352,104 @@ func createEventWithModifiedField(t *testing.T, fieldName string, newValue caden Payload: payload, } } + +// TestProcessCallbacksTransactionHash tests that the hash of the ProcessCallbacksTransaction does not change. +func TestProcessCallbacksTransactionHash(t *testing.T) { + t.Parallel() + + expectedHashes := []chainHash{ + {chainId: "flow-mainnet", expectedHash: "a9caece21b073a85cdfa8e27c6781426025ab67d7018b9afe388a18cc293e14f"}, + {chainId: "flow-testnet", expectedHash: "af35ecd8b485e41ed9fa68580557ced336cf46789e4c93af0378ea9812cc1a4b"}, + {chainId: "flow-previewnet", expectedHash: "7a8b24b172d27d3174cfc8ad40f4412f2483b669b05ea4b25f7cbba6a1decbfb"}, + {chainId: "flow-emulator", expectedHash: "4b58ffb851c3ce5d98922c9b3e9ab0a858de84912d1697aa38bef95e23cee5d4"}, + } + + var actualHashes []chainHash + for _, expected := range expectedHashes { + chain := flow.ChainID(expected.chainId) + tx, err := blueprints.ProcessCallbacksTransaction(chain.Chain()) + require.NoError(t, err) + actualHashes = append(actualHashes, chainHash{chainId: expected.chainId, expectedHash: tx.ID().String()}) + } + + require.Equal(t, expectedHashes, actualHashes, + "Hashes of the ProcessCallbacksTransaction have changed.\n"+ + "Update the expected hashes with the following values:\n%s", formatHashes(actualHashes)) +} + +// TestExecuteCallbacksTransactionHash tests that the hash of the ExecuteCallbacksTransaction does not change +// for a given set of deterministic inputs. +func TestExecuteCallbacksTransactionHash(t *testing.T) { + t.Parallel() + + const id = 42 + const effort = 1000 + + expectedHashes := []chainHash{ + {chainId: "flow-mainnet", expectedHash: "cae4adc3eb92ee67a47754e3e7095e4402249aa482be19b800de601ce4cd0d32"}, + {chainId: "flow-testnet", expectedHash: "5ede5d3a9698685a98027a855cd2711968b21e1ed3b3e479eab8893ead883817"}, + {chainId: "flow-previewnet", expectedHash: "8fc04e2eb6672e75588ea1210be5d74b9453167dec82a0f5f78afd27a0e28f8b"}, + {chainId: "flow-emulator", expectedHash: "0ee4841eee4519049af0440ac7ab553adf4fa62d5835eed63029f73482a1ff54"}, + } + + var actualHashes []chainHash + for _, expected := range expectedHashes { + chain := flow.ChainID(expected.chainId) + tx, err := blueprints.ExecuteCallbacksTransaction(chain.Chain(), id, effort) + require.NoError(t, err) + actualHashes = append(actualHashes, chainHash{chainId: expected.chainId, expectedHash: tx.ID().String()}) + } + + require.Equal(t, expectedHashes, actualHashes, + "Hashes of the ExecuteCallbacksTransaction have changed.\n"+ + "Update the expected hashes with the following values:\n%s", formatHashes(actualHashes)) +} + +// TestExecuteCallbacksTransactionsHash tests that the hashes of transactions produced by +// ExecuteCallbacksTransactions do not change for a deterministic set of events. +func TestExecuteCallbacksTransactionsHash(t *testing.T) { + t.Parallel() + + type chainTxHashes struct { + chainId string + expectedHashes []string + } + + expected := []chainTxHashes{ + {chainId: "flow-mainnet", expectedHashes: []string{ + "9f7294a3490c0e1967022e03b485c28d9ac846ba81cd1689339f4b30996fa8e4", + "9a2e265f5df74caa80ef02121965b5e9f5626cee1585e3c8ac8cc84d7eceb901", + "e5d1f9d103d6e03751d0387bddfc586d07b8b9dc5cb9fa9d145742cdcd3e8bbd", + }}, + {chainId: "flow-testnet", expectedHashes: []string{ + "e2fc0bc9264e0a70250f69bfb0d60d8b9fb9b85292177f2ceaad75e00d03a51e", + "852f2f4c7a62e71770845d23abec273356595aa81dd1997b22d5b626e0baf821", + "3f8caada9afc30ca4ea85bb5181cfdad0d2f86db9767e1c3a7603c2f6bc30ee6", + }}, + {chainId: "flow-previewnet", expectedHashes: []string{ + "e34efc26d3cfb235fb505924eaaa94e409d1aef1b0ed465d11c0a561b346a5ac", + "07c93c8fddb9fdd4354518ae4ad4eb8131d2e8edab5bf84867cd9c4189f965fe", + "6d25de124ba1046c11d5b4e68a01e34dbd14d1ea152e69d543f0836cfc0ce501", + }}, + {chainId: "flow-emulator", expectedHashes: []string{ + "109794396aa22e43b9f18d955e9f8bd814727286dedd8eb0d27c9505255ee2ef", + "71d3019b3356d2358f670ef6b6167d19ab8534d641b7b0163798300fdea59ae9", + "286a2b217c23683d32510067ea213ca3bc693b9fb96db71f2ac07ab5cac2fb56", + }}, + } + + for _, exp := range expected { + chainID := flow.ChainID(exp.chainId) + gen := fixtures.NewGeneratorSuite(fixtures.WithSeed(42), fixtures.WithChainID(chainID)) + events := gen.PendingExecutionEvents().List(3) + + txs, err := blueprints.ExecuteCallbacksTransactions(chainID.Chain(), events) + require.NoError(t, err) + require.Len(t, txs, len(exp.expectedHashes), "chain %s: unexpected number of transactions", exp.chainId) + + for i, tx := range txs { + require.Equal(t, exp.expectedHashes[i], tx.ID().String(), + "chain %s tx[%d] hash changed", exp.chainId, i) + } + } +} diff --git a/fvm/blueprints/token.go b/fvm/blueprints/token.go index 3044e2c9822..e2dc8175e3b 100644 --- a/fvm/blueprints/token.go +++ b/fvm/blueprints/token.go @@ -154,12 +154,12 @@ func TransferFlowTokenTransaction( ) *flow.TransactionBodyBuilder { cadenceAmount, _ := cadence.NewUFix64(amount) txScript := templates.GenerateTransferGenericVaultWithAddressScript(env) + ftTypeIdentifier := fmt.Sprintf("A.%s.FlowToken.Vault", env.FlowTokenAddress) return flow.NewTransactionBodyBuilder(). SetScript(txScript). SetPayer(from). AddArgument(jsoncdc.MustEncode(cadenceAmount)). AddArgument(jsoncdc.MustEncode(cadence.NewAddress(to))). - AddArgument(jsoncdc.MustEncode(cadence.NewAddress(flow.HexToAddress(env.FlowTokenAddress)))). - AddArgument(jsoncdc.MustEncode(cadence.String("FlowToken"))). + AddArgument(jsoncdc.MustEncode(cadence.String(ftTypeIdentifier))). AddAuthorizer(from) } diff --git a/fvm/bootstrap.go b/fvm/bootstrap.go index 4364fb6a4b8..76b12a02797 100644 --- a/fvm/bootstrap.go +++ b/fvm/bootstrap.go @@ -85,8 +85,8 @@ type BootstrapParams struct { minimumStorageReservation cadence.UFix64 storagePerFlow cadence.UFix64 restrictedAccountCreationEnabled cadence.Bool - setupEVMEnabled cadence.Bool setupVMBridgeEnabled cadence.Bool + evmTestHelpersEnabled cadence.Bool // versionFreezePeriod is the number of blocks in the future where the version // changes are frozen. The Node version beacon manages the freeze period, @@ -222,18 +222,20 @@ func WithRestrictedAccountCreationEnabled(enabled cadence.Bool) BootstrapProcedu } } -func WithSetupEVMEnabled(enabled cadence.Bool) BootstrapProcedureOption { +// WithSetupVMBridgeEnabled returns a bootstrap option that enables deployment and setup +// of the Flow VM bridge, so that assets can be bridged between Flow-Cadence and Flow-EVM +func WithSetupVMBridgeEnabled(enabled cadence.Bool) BootstrapProcedureOption { return func(bp *BootstrapProcedure) *BootstrapProcedure { - bp.setupEVMEnabled = enabled + bp.setupVMBridgeEnabled = enabled return bp } } -// Option to deploy and setup the Flow VM bridge during bootstrapping -// so that assets can be bridged between Flow-Cadence and Flow-EVM -func WithSetupVMBridgeEnabled(enabled cadence.Bool) BootstrapProcedureOption { +// WithEVMTestHelpersEnabled returns a bootstrap option that enables testing helper functions +// in the EVM system contract. Useful for Emulator and forked networks. +func WithEVMTestHelpersEnabled(enabled cadence.Bool) BootstrapProcedureOption { return func(bp *BootstrapProcedure) *BootstrapProcedure { - bp.setupVMBridgeEnabled = enabled + bp.evmTestHelpersEnabled = enabled return bp } } @@ -257,12 +259,12 @@ func Bootstrap( ServiceAccountPublicKeys: []flow.AccountPublicKey{serviceAccountPublicKey}, FungibleTokenAccountPublicKeys: []flow.AccountPublicKey{serviceAccountPublicKey}, FlowTokenAccountPublicKeys: []flow.AccountPublicKey{serviceAccountPublicKey}, + FlowFeesAccountPublicKeys: []flow.AccountPublicKey{serviceAccountPublicKey}, NodeAccountPublicKeys: []flow.AccountPublicKey{serviceAccountPublicKey}, }, transactionFees: BootstrapProcedureFeeParameters{0, 0, 0}, epochConfig: epochs.DefaultEpochConfig(), versionFreezePeriod: DefaultVersionFreezePeriod, - setupEVMEnabled: true, }, } @@ -455,9 +457,8 @@ func (b *bootstrapExecutor) Execute() error { // sets up the EVM environment b.setupEVM(service, nonFungibleToken, fungibleToken, flowToken, &env) - b.setupVMBridge(service, &env) - b.deployCrossVMMetadataViews(nonFungibleToken, &env) + b.setupVMBridge(service, &env) err = expectAccounts(systemcontracts.EVMStorageAccountIndex) if err != nil { @@ -629,8 +630,7 @@ func (b *bootstrapExecutor) deployMetadataViews(fungibleToken, nonFungibleToken } func (b *bootstrapExecutor) deployCrossVMMetadataViews(nonFungibleToken flow.Address, env *templates.Environment) { - if !bool(b.setupEVMEnabled) || - !bool(b.setupVMBridgeEnabled) || + if !bool(b.setupVMBridgeEnabled) || !b.ctx.Chain.ChainID().Transient() { return } @@ -796,7 +796,8 @@ func (b *bootstrapExecutor) deployServiceAccount(deployTo flow.Address, env *tem func (b *bootstrapExecutor) deployNFTStorefrontV2(deployTo flow.Address, env *templates.Environment) { contract := storefront.NFTStorefrontV2( env.FungibleTokenAddress, - env.NonFungibleTokenAddress) + env.NonFungibleTokenAddress, + env.BurnerAddress) txBody, err := blueprints.DeployContractTransaction(deployTo, contract, "NFTStorefrontV2").Build() if err != nil { panic(fmt.Sprintf("failed to build deploy NFTStorefrontV2 transaction: %s", err)) @@ -1017,31 +1018,34 @@ func (b *bootstrapExecutor) setStakingAllowlist( } func (b *bootstrapExecutor) setupEVM(serviceAddress, nonFungibleTokenAddress, fungibleTokenAddress, flowTokenAddress flow.Address, env *templates.Environment) { - if b.setupEVMEnabled { - // account for storage - // we dont need to deploy anything to this account, but it needs to exist - // so that we can store the EVM state on it - evmAcc := b.createAccount(nil) - b.setupStorageForAccount(evmAcc, serviceAddress, fungibleTokenAddress, flowTokenAddress) - - // deploy the EVM contract to the service account - txBody, err := blueprints.DeployContractTransaction( - serviceAddress, - stdlib.ContractCode(nonFungibleTokenAddress, fungibleTokenAddress, flowTokenAddress), - stdlib.ContractName, - ).Build() - if err != nil { - panic(fmt.Sprintf("failed to build EVM transaction %s", err.Error())) - } - // WithEVMEnabled should only be used after we create an account for storage - txError, err := b.invokeMetaTransaction( - NewContextFromParent(b.ctx, WithEVMEnabled(true)), - Transaction(txBody, 0), - ) - panicOnMetaInvokeErrf("failed to deploy EVM contract: %s", txError, err) + // account for storage + // we dont need to deploy anything to this account, but it needs to exist + // so that we can store the EVM state on it + evmAcc := b.createAccount(nil) + b.setupStorageForAccount(evmAcc, serviceAddress, fungibleTokenAddress, flowTokenAddress) - env.EVMAddress = env.ServiceAccountAddress + // deploy the EVM contract to the service account + txBody, err := blueprints.DeployContractTransaction( + serviceAddress, + stdlib.ContractCode( + nonFungibleTokenAddress, + fungibleTokenAddress, + flowTokenAddress, + bool(b.evmTestHelpersEnabled), + ), + stdlib.ContractName, + ).Build() + if err != nil { + panic(fmt.Sprintf("failed to build EVM transaction %s", err.Error())) } + + txError, err := b.invokeMetaTransaction( + b.ctx, + Transaction(txBody, 0), + ) + panicOnMetaInvokeErrf("failed to deploy EVM contract: %s", txError, err) + + env.EVMAddress = env.ServiceAccountAddress } type stubEntropyProvider struct{} @@ -1053,43 +1057,43 @@ func (stubEntropyProvider) RandomSource() ([]byte, error) { func (b *bootstrapExecutor) setupVMBridge(serviceAddress flow.Address, env *templates.Environment) { // only setup VM bridge for transient networks // this is because the evm storage account for testnet and mainnet do not exist yet after boostrapping - if !bool(b.setupEVMEnabled) || - !bool(b.setupVMBridgeEnabled) || + if !bool(b.setupVMBridgeEnabled) || !b.ctx.Chain.ChainID().Transient() { return } bridgeEnv := bridge.Environment{ - CrossVMNFTAddress: env.ServiceAccountAddress, - CrossVMTokenAddress: env.ServiceAccountAddress, - FlowEVMBridgeHandlerInterfacesAddress: env.ServiceAccountAddress, - IBridgePermissionsAddress: env.ServiceAccountAddress, - ICrossVMAddress: env.ServiceAccountAddress, - ICrossVMAssetAddress: env.ServiceAccountAddress, - IEVMBridgeNFTMinterAddress: env.ServiceAccountAddress, - IEVMBridgeTokenMinterAddress: env.ServiceAccountAddress, - IFlowEVMNFTBridgeAddress: env.ServiceAccountAddress, - IFlowEVMTokenBridgeAddress: env.ServiceAccountAddress, - FlowEVMBridgeAddress: env.ServiceAccountAddress, - FlowEVMBridgeAccessorAddress: env.ServiceAccountAddress, - FlowEVMBridgeConfigAddress: env.ServiceAccountAddress, - FlowEVMBridgeHandlersAddress: env.ServiceAccountAddress, - FlowEVMBridgeNFTEscrowAddress: env.ServiceAccountAddress, - FlowEVMBridgeResolverAddress: env.ServiceAccountAddress, - FlowEVMBridgeTemplatesAddress: env.ServiceAccountAddress, - FlowEVMBridgeTokenEscrowAddress: env.ServiceAccountAddress, - FlowEVMBridgeUtilsAddress: env.ServiceAccountAddress, - ArrayUtilsAddress: env.ServiceAccountAddress, - ScopedFTProvidersAddress: env.ServiceAccountAddress, - SerializeAddress: env.ServiceAccountAddress, - SerializeMetadataAddress: env.ServiceAccountAddress, - StringUtilsAddress: env.ServiceAccountAddress, + CrossVMNFTAddress: env.ServiceAccountAddress, + CrossVMTokenAddress: env.ServiceAccountAddress, + FlowEVMBridgeHandlerInterfacesAddress: env.ServiceAccountAddress, + IBridgePermissionsAddress: env.ServiceAccountAddress, + ICrossVMAddress: env.ServiceAccountAddress, + ICrossVMAssetAddress: env.ServiceAccountAddress, + IEVMBridgeNFTMinterAddress: env.ServiceAccountAddress, + IEVMBridgeTokenMinterAddress: env.ServiceAccountAddress, + IFlowEVMNFTBridgeAddress: env.ServiceAccountAddress, + IFlowEVMTokenBridgeAddress: env.ServiceAccountAddress, + FlowEVMBridgeAddress: env.ServiceAccountAddress, + FlowEVMBridgeAccessorAddress: env.ServiceAccountAddress, + FlowEVMBridgeCustomAssociationTypesAddress: env.ServiceAccountAddress, + FlowEVMBridgeCustomAssociationsAddress: env.ServiceAccountAddress, + FlowEVMBridgeConfigAddress: env.ServiceAccountAddress, + FlowEVMBridgeHandlersAddress: env.ServiceAccountAddress, + FlowEVMBridgeNFTEscrowAddress: env.ServiceAccountAddress, + FlowEVMBridgeResolverAddress: env.ServiceAccountAddress, + FlowEVMBridgeTemplatesAddress: env.ServiceAccountAddress, + FlowEVMBridgeTokenEscrowAddress: env.ServiceAccountAddress, + FlowEVMBridgeUtilsAddress: env.ServiceAccountAddress, + ArrayUtilsAddress: env.ServiceAccountAddress, + ScopedFTProvidersAddress: env.ServiceAccountAddress, + SerializeAddress: env.ServiceAccountAddress, + SerializeMetadataAddress: env.ServiceAccountAddress, + StringUtilsAddress: env.ServiceAccountAddress, } ctx := NewContextFromParent(b.ctx, WithBlockHeader(b.rootHeader), WithEntropyProvider(stubEntropyProvider{}), - WithEVMEnabled(true), ) txIndex := uint32(0) diff --git a/fvm/context.go b/fvm/context.go index 3c5c9efaa30..12c621f663e 100644 --- a/fvm/context.go +++ b/fvm/context.go @@ -6,6 +6,9 @@ import ( "github.com/rs/zerolog" otelTrace "go.opentelemetry.io/otel/trace" + "github.com/onflow/flow-go/fvm/inspection" + + "github.com/onflow/flow-go/fvm/cadence_vm" "github.com/onflow/flow-go/fvm/environment" reusableRuntime "github.com/onflow/flow-go/fvm/runtime" "github.com/onflow/flow-go/fvm/storage/derived" @@ -33,7 +36,6 @@ type Context struct { // DisableMemoryAndInteractionLimits will override memory and interaction // limits and set them to MaxUint64, effectively disabling these limits. DisableMemoryAndInteractionLimits bool - EVMEnabled bool ScheduledTransactionsEnabled bool ComputationLimit uint64 MemoryLimit uint64 @@ -52,11 +54,13 @@ type Context struct { // AllowProgramCacheWritesInScripts determines if the program cache can be written to in scripts // By default, the program cache is only updated by transactions. AllowProgramCacheWritesInScripts bool + + Inspectors []inspection.Inspector } // NewContext initializes a new execution context with the provided options. -func NewContext(opts ...Option) Context { - return newContext(defaultContext(), opts...) +func NewContext(chain flow.Chain, opts ...Option) Context { + return newContext(defaultContext(chain), opts...) } // NewContextFromParent spawns a child execution context with the provided options. @@ -72,8 +76,8 @@ func newContext(ctx Context, opts ...Option) Context { return ctx } -func defaultContext() Context { - return Context{ +func defaultContext(chain flow.Chain) Context { + ctx := Context{ DisableMemoryAndInteractionLimits: false, ComputationLimit: DefaultComputationLimit, MemoryLimit: DefaultMemoryLimit, @@ -81,29 +85,30 @@ func defaultContext() Context { MaxStateValueSize: state.DefaultMaxValueSize, MaxStateInteractionSize: DefaultMaxInteractionSize, TransactionExecutorParams: DefaultTransactionExecutorParams(), - EnvironmentParams: environment.DefaultEnvironmentParams(), + EnvironmentParams: DefaultEnvironmentParams(chain), } + return ctx } -// An Option sets a configuration parameter for a virtual machine context. -type Option func(ctx Context) Context - -// WithChain sets the chain parameters for a virtual machine context. -func WithChain(chain flow.Chain) Option { - return func(ctx Context) Context { - ctx.Chain = chain - return ctx +// DefaultEnvironmentParams creates environment.EnvironmentParams that serve as base settings +// for EnvironmentParams and can be used as is for tests. +func DefaultEnvironmentParams(chain flow.Chain) environment.EnvironmentParams { + return environment.EnvironmentParams{ + Chain: chain, + ServiceAccountEnabled: true, + CadenceVMEnabled: cadence_vm.DefaultEnabled, + RuntimeParams: reusableRuntime.DefaultRuntimeParams(chain), + ProgramLoggerParams: environment.DefaultProgramLoggerParams(), + EventEmitterParams: environment.DefaultEventEmitterParams(), + BlockInfoParams: environment.DefaultBlockInfoParams(), + TransactionInfoParams: environment.DefaultTransactionInfoParams(), + ContractUpdaterParams: environment.DefaultContractUpdaterParams(), + ExecutionVersionProvider: environment.ZeroExecutionVersionProvider{}, } } -// Deprecated: WithGasLimit sets the computation limit for a virtual machine context. -// Use WithComputationLimit instead. -func WithGasLimit(limit uint64) Option { - return func(ctx Context) Context { - ctx.ComputationLimit = limit - return ctx - } -} +// An Option sets a configuration parameter for a virtual machine context. +type Option func(ctx Context) Context // WithMemoryAndInteractionLimitsDisabled will override memory and interaction // limits and set them to MaxUint64, effectively disabling these limits. @@ -368,18 +373,18 @@ func WithEventEncoder(encoder environment.EventEncoder) Option { } } -// WithEVMEnabled enables access to the evm environment -func WithEVMEnabled(enabled bool) Option { +// WithAllowProgramCacheWritesInScriptsEnabled enables caching of programs accessed by scripts +func WithAllowProgramCacheWritesInScriptsEnabled(enabled bool) Option { return func(ctx Context) Context { - ctx.EVMEnabled = enabled + ctx.AllowProgramCacheWritesInScripts = enabled return ctx } } -// WithAllowProgramCacheWritesInScriptsEnabled enables caching of programs accessed by scripts -func WithAllowProgramCacheWritesInScriptsEnabled(enabled bool) Option { +// WithEVMTestOperationsAllowed enables EVM test operations in the context +func WithEVMTestOperationsAllowed(enabled bool) Option { return func(ctx Context) Context { - ctx.AllowProgramCacheWritesInScripts = enabled + ctx.EVMTestOperationsAllowed = enabled return ctx } } @@ -428,3 +433,10 @@ func WithScheduledTransactionsEnabled(enabled bool) Option { func WithScheduleCallbacksEnabled(enabled bool) Option { return WithScheduledTransactionsEnabled(enabled) } + +func WithInspectors(inspectors []inspection.Inspector) Option { + return func(ctx Context) Context { + ctx.Inspectors = inspectors + return ctx + } +} diff --git a/fvm/crypto/hash_test.go b/fvm/crypto/hash_test.go index 6c8ba0354c8..11701587981 100644 --- a/fvm/crypto/hash_test.go +++ b/fvm/crypto/hash_test.go @@ -62,7 +62,7 @@ func TestPrefixedHash(t *testing.T) { }) t.Run(hashAlgo.String()+" without a prefix", func(t *testing.T) { - for i := 0; i < 5000; i++ { + for i := range 5000 { data := make([]byte, i) _, err := rand.Read(data) require.NoError(t, err) diff --git a/fvm/environment/account-key-metadata/digest.go b/fvm/environment/account-key-metadata/digest.go index 6d863e64969..07c04040e0b 100644 --- a/fvm/environment/account-key-metadata/digest.go +++ b/fvm/environment/account-key-metadata/digest.go @@ -6,6 +6,7 @@ import ( "github.com/fxamacker/circlehash" + "github.com/onflow/flow-go/fvm/errors" "github.com/onflow/flow-go/model/flow" ) @@ -78,3 +79,26 @@ func GetPublicKeyDigest(owner flow.Address, encodedPublicKey []byte) uint64 { // SentinelFastDigest64 is the sentinel digest used for 64-bit fast hash collision handling. SentinelFastDigest64 // is stored in key metadata's digest list as a placeholder. const SentinelFastDigest64 uint64 = 0 // don't change this value (instead, declare new constant with new value if needed) + +// Utility functions for tests and validation + +// DecodeDigests decodes raw bytes of digest list in account key metadata. +func DecodeDigests(b []byte) ([]uint64, error) { + if len(b)%digestSize != 0 { + return nil, errors.NewKeyMetadataUnexpectedLengthError( + "failed to decode digest list", + digestSize, + len(b), + ) + } + + storedDigestCount := len(b) / digestSize + + digests := make([]uint64, 0, storedDigestCount) + + for i := 0; i < len(b); i += digestSize { + digests = append(digests, binary.BigEndian.Uint64(b[i:])) + } + + return digests, nil +} diff --git a/fvm/environment/account-key-metadata/digest_test.go b/fvm/environment/account-key-metadata/digest_test.go index dfac8f062c1..de1f81cd6ac 100644 --- a/fvm/environment/account-key-metadata/digest_test.go +++ b/fvm/environment/account-key-metadata/digest_test.go @@ -111,3 +111,53 @@ func TestFindDuplicateKey(t *testing.T) { }) } } + +func TestDecodeDigests(t *testing.T) { + testcases := []struct { + name string + encodedDigests []byte + digests []uint64 + hasError bool + }{ + { + name: "nil encoded digests", + encodedDigests: nil, + digests: []uint64{}, + }, + { + name: "empty encoded digests", + encodedDigests: []byte{}, + digests: []uint64{}, + }, + { + name: "truncated encoded digests", + encodedDigests: []byte{0}, + hasError: true, + }, + { + name: "1 digest", + encodedDigests: []byte{0, 0, 0, 0, 0, 0, 0, 1}, + digests: []uint64{1}, + }, + { + name: "2 digests", + encodedDigests: []byte{ + 0, 0, 0, 0, 0, 0, 0, 1, + 0, 0, 0, 0, 0, 0, 0, 2, + }, + digests: []uint64{1, 2}, + }, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + decoded, err := DecodeDigests(tc.encodedDigests) + if tc.hasError { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.Equal(t, tc.digests, decoded) + }) + } +} diff --git a/fvm/environment/account-key-metadata/key_index_mapping_group.go b/fvm/environment/account-key-metadata/key_index_mapping_group.go index 6648e8a0203..32b814ef3bf 100644 --- a/fvm/environment/account-key-metadata/key_index_mapping_group.go +++ b/fvm/environment/account-key-metadata/key_index_mapping_group.go @@ -215,3 +215,36 @@ func parseMappingStoredKeyIndex(b []byte, off int) uint32 { _ = b[off+3] // bounds check return binary.BigEndian.Uint32(b[off : off+storedKeyIndexSize]) } + +// Utility functions for tests and validation + +// DecodeMappings decodes raw bytes of account public key mappings in account key metadata. +func DecodeMappings(b []byte) ([]uint32, error) { + if len(b)%mappingGroupSize != 0 { + return nil, errors.NewKeyMetadataUnexpectedLengthError( + "failed to decode key mappings", + mappingGroupSize, + len(b), + ) + } + + mapping := make([]uint32, 0, len(b)/mappingGroupSize) + + for i := 0; i < len(b); i += mappingGroupSize { + + isConsecutiveGroup, runLength := parseMappingRunLength(b, i) + storedKeyIndex := binary.BigEndian.Uint32(b[i+runLengthSize:]) + + if isConsecutiveGroup { + for index := range runLength { + mapping = append(mapping, storedKeyIndex+uint32(index)) + } + } else { + for range runLength { + mapping = append(mapping, storedKeyIndex) + } + } + } + + return mapping, nil +} diff --git a/fvm/environment/account-key-metadata/key_index_mapping_group_test.go b/fvm/environment/account-key-metadata/key_index_mapping_group_test.go index ceff93a8577..ea65ffd3acb 100644 --- a/fvm/environment/account-key-metadata/key_index_mapping_group_test.go +++ b/fvm/environment/account-key-metadata/key_index_mapping_group_test.go @@ -115,6 +115,11 @@ func TestAppendAndGetStoredKeyIndexFromMapping(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedStoredKeyIndex, storedKeyIndex) } + + // Decode entire mapping. + decoded, err := DecodeMappings(b) + require.NoError(t, err) + require.Equal(t, tc.mappings, decoded) }) } @@ -122,37 +127,44 @@ func TestAppendAndGetStoredKeyIndexFromMapping(t *testing.T) { testcases := []struct { name string encodedExistingMappings []byte - mapping uint32 - expected []byte - expectedCount uint32 - expectedMapping uint32 - expectedStartMapping uint32 - isConsecutiveGroup bool + newMapping uint32 + expectedEncodedMappings []byte + expectedMappings []uint32 }{ { name: "regular group, run length maxRunLengthInMappingGroup - 1", encodedExistingMappings: []byte{ 0x7f, 0xfe, 0x00, 0x00, 0x00, 0x01, }, - mapping: 1, - expected: []byte{ + newMapping: 1, + expectedEncodedMappings: []byte{ 0x7f, 0xff, 0x00, 0x00, 0x00, 0x01, }, - expectedCount: maxRunLengthInMappingGroup, - expectedMapping: 1, + expectedMappings: func() []uint32 { + m := make([]uint32, maxRunLengthInMappingGroup) + for i := range len(m) { + m[i] = 1 + } + return m + }(), }, { name: "regular group, run length maxRunLengthInMappingGroup", encodedExistingMappings: []byte{ 0x7f, 0xff, 0x00, 0x00, 0x00, 0x01, }, - mapping: 1, - expected: []byte{ + newMapping: 1, + expectedEncodedMappings: []byte{ 0x7f, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, }, - expectedCount: maxRunLengthInMappingGroup + 1, - expectedMapping: 1, + expectedMappings: func() []uint32 { + m := make([]uint32, maxRunLengthInMappingGroup+1) + for i := range len(m) { + m[i] = 1 + } + return m + }(), }, { name: "regular group, run length maxRunLengthInMappingGroup + 1", @@ -160,40 +172,53 @@ func TestAppendAndGetStoredKeyIndexFromMapping(t *testing.T) { 0x7f, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, }, - mapping: 1, - expected: []byte{ + newMapping: 1, + expectedEncodedMappings: []byte{ 0x7f, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, }, - expectedCount: maxRunLengthInMappingGroup + 2, - expectedMapping: 1, + expectedMappings: func() []uint32 { + m := make([]uint32, maxRunLengthInMappingGroup+2) + for i := range len(m) { + m[i] = 1 + } + return m + }(), }, { name: "consecutive group, run length maxRunLengthInMappingGroup - 1", encodedExistingMappings: []byte{ 0xff, 0xfe, 0x00, 0x00, 0x00, 0x01, }, - mapping: maxRunLengthInMappingGroup, - expected: []byte{ + newMapping: maxRunLengthInMappingGroup, + expectedEncodedMappings: []byte{ 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, }, - expectedCount: maxRunLengthInMappingGroup, - expectedStartMapping: 1, - isConsecutiveGroup: true, + expectedMappings: func() []uint32 { + m := make([]uint32, maxRunLengthInMappingGroup) + for i := range len(m) { + m[i] = uint32(1 + i) + } + return m + }(), }, { name: "consecutive group, run length maxRunLengthInMappingGroup", encodedExistingMappings: []byte{ 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, }, - mapping: maxRunLengthInMappingGroup + 1, - expected: []byte{ + newMapping: maxRunLengthInMappingGroup + 1, + expectedEncodedMappings: []byte{ 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, }, - expectedCount: maxRunLengthInMappingGroup + 1, - expectedStartMapping: 1, - isConsecutiveGroup: true, + expectedMappings: func() []uint32 { + m := make([]uint32, maxRunLengthInMappingGroup+1) + for i := range len(m) { + m[i] = uint32(1 + i) + } + return m + }(), }, { name: "consecutive group, run length maxRunLengthInMappingGroup + 1", @@ -201,14 +226,18 @@ func TestAppendAndGetStoredKeyIndexFromMapping(t *testing.T) { 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, }, - mapping: maxRunLengthInMappingGroup + 2, - expected: []byte{ + newMapping: maxRunLengthInMappingGroup + 2, + expectedEncodedMappings: []byte{ 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x80, 0x02, 0x00, 0x00, 0x80, 0x00, }, - expectedCount: maxRunLengthInMappingGroup + 2, - expectedStartMapping: 1, - isConsecutiveGroup: true, + expectedMappings: func() []uint32 { + m := make([]uint32, maxRunLengthInMappingGroup+2) + for i := range len(m) { + m[i] = uint32(1 + i) + } + return m + }(), }, } @@ -216,24 +245,21 @@ func TestAppendAndGetStoredKeyIndexFromMapping(t *testing.T) { t.Run(tc.name, func(t *testing.T) { // Encode and append stored key index - b, err := appendStoredKeyIndexToMappings(tc.encodedExistingMappings, tc.mapping) + b, err := appendStoredKeyIndexToMappings(tc.encodedExistingMappings, tc.newMapping) require.NoError(t, err) - require.Equal(t, tc.expected, b) - - // Get stored key index from mappings - if tc.isConsecutiveGroup { - for i := range tc.expectedCount { - retrievedStoredKeyIndex, err := getStoredKeyIndexFromMappings(b, i) - require.NoError(t, err) - require.Equal(t, tc.expectedStartMapping+i, retrievedStoredKeyIndex) - } - } else { - for i := range tc.expectedCount { - retrievedStoredKeyIndex, err := getStoredKeyIndexFromMappings(b, i) - require.NoError(t, err) - require.Equal(t, tc.expectedMapping, retrievedStoredKeyIndex) - } + require.Equal(t, tc.expectedEncodedMappings, b) + + // Get stored key index from mappings. + for index, expected := range tc.expectedMappings { + retrievedStoredKeyIndex, err := getStoredKeyIndexFromMappings(b, uint32(index)) + require.NoError(t, err) + require.Equal(t, expected, retrievedStoredKeyIndex) } + + // Decode entire mapping. + decoded, err := DecodeMappings(b) + require.NoError(t, err) + require.Equal(t, tc.expectedMappings, decoded) }) } }) diff --git a/fvm/environment/account-key-metadata/metadata.go b/fvm/environment/account-key-metadata/metadata.go index f657abdf400..98da956e339 100644 --- a/fvm/environment/account-key-metadata/metadata.go +++ b/fvm/environment/account-key-metadata/metadata.go @@ -135,49 +135,67 @@ func NewKeyMetadataAppenderFromBytes(b []byte, deduplicated bool, maxStoredDiges return nil, fmt.Errorf("failed to create KeyMetadataAppender with empty data: use NewKeyMetadataAppend() instead") } + weightAndRevokedStatusBytes, mappingBytes, digestBytes, startIndexForMappings, startIndexForDigests, err := parseKeyMetadata(b, deduplicated) + if err != nil { + return nil, err + } + keyMetadata := KeyMetadataAppender{ - original: b, - deduplicated: deduplicated, - maxStoredDigests: maxStoredDigests, + original: b, + weightAndRevokedStatusBytes: slices.Clone(weightAndRevokedStatusBytes), + mappingBytes: slices.Clone(mappingBytes), + digestBytes: slices.Clone(digestBytes), + startIndexForMapping: startIndexForMappings, + startIndexForDigests: startIndexForDigests, + maxStoredDigests: maxStoredDigests, + deduplicated: deduplicated, } - var err error + return &keyMetadata, nil +} + +func parseKeyMetadata(b []byte, deduplicated bool) ( + weightAndRevokedStatusBytes []byte, + mappingBytes []byte, + digestBytes []byte, + startIndexForMappings uint32, + startIndexForDigests uint32, + err error, +) { + if len(b) == 0 { + err = errors.NewKeyMetadataEmptyError("failed to decode key metadata") + return + } // Get revoked and weight raw bytes. - var weightAndRevokedStatusBytes []byte weightAndRevokedStatusBytes, b, err = parseWeightAndRevokedStatusFromKeyMetadataBytes(b) if err != nil { - return nil, err + return } - keyMetadata.weightAndRevokedStatusBytes = slices.Clone(weightAndRevokedStatusBytes) // Get mapping raw bytes. if deduplicated { - var mappingBytes []byte - keyMetadata.startIndexForMapping, mappingBytes, b, err = parseStoredKeyMappingFromKeyMetadataBytes(b) + startIndexForMappings, mappingBytes, b, err = parseStoredKeyMappingFromKeyMetadataBytes(b) if err != nil { - return nil, err + return } - keyMetadata.mappingBytes = slices.Clone(mappingBytes) } // Get digests list - var digestBytes []byte - keyMetadata.startIndexForDigests, digestBytes, b, err = parseDigestsFromKeyMetadataBytes(b) + startIndexForDigests, digestBytes, b, err = parseDigestsFromKeyMetadataBytes(b) if err != nil { - return nil, err + return } - keyMetadata.digestBytes = slices.Clone(digestBytes) if len(b) != 0 { - return nil, - errors.NewKeyMetadataTrailingDataError( - "failed to parse key metadata", - len(b), - ) + err = errors.NewKeyMetadataTrailingDataError( + "failed to parse key metadata", + len(b), + ) + return } - return &keyMetadata, nil + return } // With deduplicated flag, account key metadata is encoded as: @@ -346,3 +364,44 @@ func (m *KeyMetadataAppender) findDuplicateDigest(digest uint64) (found bool, du return false, 0 } + +// Utility functions for tests and validation + +// DecodeKeyMetadata decodes account key metadata. +func DecodeKeyMetadata(b []byte, deduplicated bool) ( + weightAndRevokedStatuses []WeightAndRevokedStatus, + startKeyIndexForMappings uint32, + mappings []uint32, + startKeyIndexForDigests uint32, + digests []uint64, + err error, +) { + // Parse key metadata + var weightAndRevokedStatusBytes, mappingBytes, digestBytes []byte + weightAndRevokedStatusBytes, mappingBytes, digestBytes, startKeyIndexForMappings, startKeyIndexForDigests, err = parseKeyMetadata(b, deduplicated) + if err != nil { + return + } + + // Decode weight and revoked list + weightAndRevokedStatuses, err = DecodeWeightAndRevokedStatuses(weightAndRevokedStatusBytes) + if err != nil { + return + } + + // Decode key mapping if deduplication is on + if deduplicated { + mappings, err = DecodeMappings(mappingBytes) + if err != nil { + return + } + } + + // Decode digests list + digests, err = DecodeDigests(digestBytes) + if err != nil { + return + } + + return +} diff --git a/fvm/environment/account-key-metadata/metadata_test.go b/fvm/environment/account-key-metadata/metadata_test.go index dd57802a200..fb2e2a872c5 100644 --- a/fvm/environment/account-key-metadata/metadata_test.go +++ b/fvm/environment/account-key-metadata/metadata_test.go @@ -641,3 +641,138 @@ func TestAppendDuplicateKeyMetadata(t *testing.T) { }) } } + +func TestDecodeKeyMetadata(t *testing.T) { + testcases := []struct { + name string + deduplicated bool + data []byte + expectedWeightAndRevokedStatuses []WeightAndRevokedStatus + expectedStartKeyIndexForMappings uint32 + expectedMappings []uint32 + expectedStartKeyIndexForDigests uint32 + expectedDigests []uint64 + }{ + { + name: "not deduplicated, 2 account public keys", + deduplicated: false, + data: []byte{ + 0, 0, 0, 4, // length prefix for weight and revoked list + 0, 1, 3, 0xe8, // weight and revoked group + 0, 0, 0, 0, // start index for digests + 0, 0, 0, 0x10, // length prefix for digests + 0, 0, 0, 0, 0, 0, 0, 1, // digest 1 + 0, 0, 0, 0, 0, 0, 0, 2, // digest 2 + }, + expectedWeightAndRevokedStatuses: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + }, + expectedStartKeyIndexForMappings: 0, + expectedMappings: nil, + expectedStartKeyIndexForDigests: 0, + expectedDigests: []uint64{1, 2}, + }, + { + name: "not deduplicated, 3 account public keys", + deduplicated: false, + data: []byte{ + 0, 0, 0, 8, // length prefix for weight and revoked list + 0, 1, 3, 0xe8, // weight and revoked group + 0, 1, 0x80, 0x01, // weight and revoked group + 0, 0, 0, 1, // start index for digests + 0, 0, 0, 0x10, // length prefix for digests + 0, 0, 0, 0, 0, 0, 0, 2, // digest 2 + 0, 0, 0, 0, 0, 0, 0, 3, // digest 3 + }, + expectedWeightAndRevokedStatuses: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1, Revoked: true}, + }, + expectedStartKeyIndexForMappings: 0, + expectedMappings: nil, + expectedStartKeyIndexForDigests: 1, + expectedDigests: []uint64{2, 3}, + }, + { + name: "deduplicated, 2 account public keys, 1 stored key, deduplication from key at index 1", + deduplicated: true, + data: []byte{ + 0, 0, 0, 4, // length prefix for weight and revoked list + 0, 1, 3, 0xe8, // weight and revoked group + 0, 0, 0, 1, // start index for mapping + 0, 0, 0, 6, // length prefix for mapping + 0, 1, 0, 0, 0, 0, // mapping group 1 + 0, 0, 0, 0, // start index for digests + 0, 0, 0, 8, // length prefix for digests + 0, 0, 0, 0, 0, 0, 0, 1, // digest 1 + }, + expectedWeightAndRevokedStatuses: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + }, + expectedStartKeyIndexForMappings: 1, + expectedMappings: []uint32{0}, + expectedStartKeyIndexForDigests: 0, + expectedDigests: []uint64{1}, + }, + { + name: "deduplicated, 3 account public keys, 2 stored keys, deduplication from key at index 1", + deduplicated: true, + data: []byte{ + 0, 0, 0, 4, // length prefix for weight and revoked list + 0, 2, 3, 0xe8, // weight and revoked group + 0, 0, 0, 1, // start index for mapping + 0, 0, 0, 6, // length prefix for mapping + 0x80, 2, 0, 0, 0, 0, // mapping group 1 + 0, 0, 0, 0, // start index for digests + 0, 0, 0, 0x10, // length prefix for digests + 0, 0, 0, 0, 0, 0, 0, 1, // digest 1 + 0, 0, 0, 0, 0, 0, 0, 2, // digest 2 + }, + expectedWeightAndRevokedStatuses: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + }, + expectedStartKeyIndexForMappings: 1, + expectedMappings: []uint32{0, 1}, + expectedStartKeyIndexForDigests: 0, + expectedDigests: []uint64{1, 2}, + }, + { + name: "deduplicated, 4 account public keys, 2 stored keys, deduplication from key at index 2", + deduplicated: true, + data: []byte{ + 0, 0, 0, 8, // length prefix for weight and revoked list + 0, 2, 3, 0xe8, // weight and revoked group + 0, 1, 0x80, 0x01, // weight and revoked group + 0, 0, 0, 2, // start index for mapping + 0, 0, 0, 0x06, // length prefix for mapping + 0, 2, 0, 0, 0, 0, // mapping group 1 + 0, 0, 0, 2, // start index for digests + 0, 0, 0, 0x10, // length prefix for digests + 0, 0, 0, 0, 0, 0, 0, 3, // digest 3 + 0, 0, 0, 0, 0, 0, 0, 4, // digest 4 + }, + expectedWeightAndRevokedStatuses: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1, Revoked: true}, + }, + expectedStartKeyIndexForMappings: 2, + expectedMappings: []uint32{0, 0}, + expectedStartKeyIndexForDigests: 2, + expectedDigests: []uint64{3, 4}, + }, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + weightAndRevokedStatuses, startKeyIndexForMappings, mappings, startKeyIndexForDigests, digests, err := DecodeKeyMetadata(tc.data, tc.deduplicated) + require.NoError(t, err) + require.Equal(t, tc.expectedWeightAndRevokedStatuses, weightAndRevokedStatuses) + require.Equal(t, tc.expectedStartKeyIndexForMappings, startKeyIndexForMappings) + require.Equal(t, tc.expectedMappings, mappings) + require.Equal(t, tc.expectedStartKeyIndexForDigests, startKeyIndexForDigests) + require.Equal(t, tc.expectedDigests, digests) + }) + } +} diff --git a/fvm/environment/account-key-metadata/weight_and_revoked_group.go b/fvm/environment/account-key-metadata/weight_and_revoked_group.go index 707746c1f55..ebf042611f2 100644 --- a/fvm/environment/account-key-metadata/weight_and_revoked_group.go +++ b/fvm/environment/account-key-metadata/weight_and_revoked_group.go @@ -319,3 +319,40 @@ func parseWeightAndRevokedStatus(b []byte, off int) (revoked bool, weight uint16 revoked = (weightAndRevoked & revokedMask) > 0 return revoked, weight } + +// Utility functions for tests and validation + +// WeightAndRevokedStatus represents weight and revoked status of an account public key. +type WeightAndRevokedStatus struct { + Weight uint16 + Revoked bool +} + +// DecodeWeightAndRevokedStatuses decodes raw bytes of weight and revoked statuses in account key metadata. +func DecodeWeightAndRevokedStatuses(b []byte) ([]WeightAndRevokedStatus, error) { + if len(b)%weightAndRevokedStatusGroupSize != 0 { + return nil, errors.NewKeyMetadataUnexpectedLengthError( + "failed to decode weight and revoked status", + weightAndRevokedStatusGroupSize, + len(b), + ) + } + + statuses := make([]WeightAndRevokedStatus, 0, len(b)/weightAndRevokedStatusGroupSize) + + for i := 0; i < len(b); i += weightAndRevokedStatusGroupSize { + runLength := parseRunLength(b, i) + revoked, weight := parseWeightAndRevokedStatus(b, i+runLengthSize) + + status := WeightAndRevokedStatus{ + Weight: weight, + Revoked: revoked, + } + + for range runLength { + statuses = append(statuses, status) + } + } + + return statuses, nil +} diff --git a/fvm/environment/account-key-metadata/weight_and_revoked_group_test.go b/fvm/environment/account-key-metadata/weight_and_revoked_group_test.go index 74d07c0ac27..136eaa7f434 100644 --- a/fvm/environment/account-key-metadata/weight_and_revoked_group_test.go +++ b/fvm/environment/account-key-metadata/weight_and_revoked_group_test.go @@ -8,11 +8,6 @@ import ( "github.com/onflow/flow-go/fvm/errors" ) -type weightAndRevokedStatus struct { - weight uint16 - revoked bool -} - func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { t.Run("get from empty data", func(t *testing.T) { _, _, err := getWeightAndRevokedStatus(nil, 0) @@ -37,38 +32,38 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { // in cmd/util/ledger/migrations/account_key_deduplication_encoder_test.go testcases := []struct { name string - status []weightAndRevokedStatus + status []WeightAndRevokedStatus expected []byte }{ { name: "one group, run length 1", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 1, 0x03, 0xe8}, }, { name: "one group, run length 1", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 1, 0x83, 0xe8}, }, { name: "one group, run length 3", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 3, 0x83, 0xe8}, }, { name: "three groups, run length 1", - status: []weightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 2, revoked: false}, - {weight: 2, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1, Revoked: false}, + {Weight: 2, Revoked: false}, + {Weight: 2, Revoked: true}, }, expected: []byte{ 0, 1, 0, 1, @@ -78,12 +73,12 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { }, { name: "three groups, different run length", - status: []weightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 2, revoked: true}, - {weight: 3, revoked: true}, - {weight: 3, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 2, Revoked: true}, + {Weight: 3, Revoked: true}, + {Weight: 3, Revoked: true}, }, expected: []byte{ 0, 2, 0, 1, @@ -100,7 +95,7 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range tc.status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } require.Equal(t, tc.expected, b) @@ -109,25 +104,30 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { for i, s := range tc.status { revoked, weight, err := getWeightAndRevokedStatus(b, uint32(i)) require.NoError(t, err) - require.Equal(t, s.revoked, revoked) - require.Equal(t, s.weight, weight) + require.Equal(t, s.Revoked, revoked) + require.Equal(t, s.Weight, weight) } _, _, err = getWeightAndRevokedStatus(b, uint32(len(tc.status))) require.True(t, errors.IsKeyMetadataNotFoundError(err)) + + // Decode entire revoked and weight statuses. + decoded, err := DecodeWeightAndRevokedStatuses(b) + require.NoError(t, err) + require.Equal(t, tc.status, decoded) }) } t.Run("run length around max group count", func(t *testing.T) { testcases := []struct { name string - status weightAndRevokedStatus + status WeightAndRevokedStatus count uint32 expected []byte }{ { name: "run length maxRunLengthInEncodedStatusGroup - 1", - status: weightAndRevokedStatus{weight: 1000, revoked: true}, + status: WeightAndRevokedStatus{Weight: 1000, Revoked: true}, count: maxRunLengthInWeightAndRevokedStatusGroup - 1, expected: []byte{ 0xff, 0xfe, 0x83, 0xe8, @@ -135,7 +135,7 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { }, { name: "run length maxRunLengthInEncodedStatusGroup ", - status: weightAndRevokedStatus{weight: 1000, revoked: true}, + status: WeightAndRevokedStatus{Weight: 1000, Revoked: true}, count: maxRunLengthInWeightAndRevokedStatusGroup, expected: []byte{ 0xff, 0xff, 0x83, 0xe8, @@ -143,7 +143,7 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { }, { name: "run length maxRunLengthInEncodedStatusGroup + 1", - status: weightAndRevokedStatus{weight: 1000, revoked: true}, + status: WeightAndRevokedStatus{Weight: 1000, Revoked: true}, count: maxRunLengthInWeightAndRevokedStatusGroup + 1, expected: []byte{ 0xff, 0xff, 0x83, 0xe8, @@ -154,7 +154,7 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { - status := make([]weightAndRevokedStatus, tc.count) + status := make([]WeightAndRevokedStatus, tc.count) for i := range len(status) { status[i] = tc.status } @@ -164,7 +164,7 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } require.Equal(t, tc.expected, b) @@ -173,9 +173,14 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { for i, s := range status { revoked, weight, err := getWeightAndRevokedStatus(b, uint32(i)) require.NoError(t, err) - require.Equal(t, s.revoked, revoked) - require.Equal(t, s.weight, weight) + require.Equal(t, s.Revoked, revoked) + require.Equal(t, s.Weight, weight) } + + // Decode entire revoked and weight status + decoded, err := DecodeWeightAndRevokedStatuses(b) + require.NoError(t, err) + require.Equal(t, status, decoded) }) } }) @@ -184,205 +189,205 @@ func TestAppendAndGetWeightAndRevokedStatus(t *testing.T) { func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { testcases := []struct { name string - status []weightAndRevokedStatus + status []WeightAndRevokedStatus expected []byte index uint32 }{ { name: "revoke in run-length 1 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 1, 0x83, 0xe8}, index: 0, }, { name: "no-op revoke in run-length 1 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 1, 0x83, 0xe8}, index: 0, }, { name: "revoke first of run-length 2 group (no prev group)", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 1, 0x83, 0xe8, 0, 1, 0x03, 0xe8}, index: 0, }, { name: "revoke second of run-length 2 group (no next group)", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 1, 0x03, 0xe8, 0, 1, 0x83, 0xe8}, index: 1, }, { name: "no-op revoke first of run-length 2 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 2, 0x83, 0xe8}, index: 0, }, { name: "no-op revoke second of run-length 2 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 2, 0x83, 0xe8}, index: 1, }, { name: "revoke first of run-length 3 group (no prev group)", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 1, 0x83, 0xe8, 0, 2, 0x03, 0xe8}, index: 0, }, { name: "revoke second of run-length 3 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 1, 0x03, 0xe8, 0, 1, 0x83, 0xe8, 0, 1, 0x03, 0xe8}, index: 1, }, { name: "revoke third of run-length 3 group (no next group)", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 2, 0x03, 0xe8, 0, 1, 0x83, 0xe8}, index: 2, }, { name: "no-op revoke first of run-length 3 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 3, 0x83, 0xe8}, index: 0, }, { name: "no-op revoke second of run-length 3 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 3, 0x83, 0xe8}, index: 1, }, { name: "no-op revoke last of run-length 3 group", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 3, 0x83, 0xe8}, index: 2, }, { name: "revoke first of run-length 2 group (cannot merge with previous group)", - status: []weightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 1, 0, 1, 0, 1, 0x83, 0xe8, 0, 1, 0x03, 0xe8}, index: 1, }, { name: "revoke first of run-length 2 group (merge with previous group)", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: true}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, }, expected: []byte{0, 2, 0x83, 0xe8, 0, 1, 0x03, 0xe8}, index: 1, }, { name: "revoke second of run-length 2 group (cann't merge with next group)", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1, Revoked: false}, }, expected: []byte{0, 1, 0x03, 0xe8, 0, 1, 0x83, 0xe8, 0, 1, 0, 1}, index: 1, }, { name: "revoke second of run-length 2 group (merge with next group)", - status: []weightAndRevokedStatus{ - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: true}, + status: []WeightAndRevokedStatus{ + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: true}, }, expected: []byte{0, 1, 0x03, 0xe8, 0, 2, 0x83, 0xe8}, index: 1, }, { name: "revoke middle of a large group", - status: []weightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, }, expected: []byte{0, 3, 0, 1, 0, 2, 0x03, 0xe8, 0, 1, 0x83, 0xe8, 0, 1, 0x03, 0xe8, 0, 3, 0, 1}, index: 5, }, { name: "revoke in run-length 1 group (cannot merge with previous and next groups)", - status: []weightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1000, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, - {weight: 1, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1000, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, + {Weight: 1, Revoked: false}, }, expected: []byte{0, 3, 0, 1, 0, 1, 0x83, 0xe8, 0, 3, 0, 1}, index: 3, }, { name: "revoke in run-length 1 group (merge with both previous and next groups)", - status: []weightAndRevokedStatus{ - {weight: 1, revoked: false}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: false}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1000, revoked: true}, - {weight: 1, revoked: false}, + status: []WeightAndRevokedStatus{ + {Weight: 1, Revoked: false}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: false}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1000, Revoked: true}, + {Weight: 1, Revoked: false}, }, expected: []byte{0, 1, 0, 1, 0, 7, 0x83, 0xe8, 0, 1, 0, 1}, index: 4, @@ -396,7 +401,7 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range tc.status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } @@ -412,20 +417,20 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { if uint32(i) == tc.index { require.Equal(t, true, revoked) } else { - require.Equal(t, s.revoked, revoked) + require.Equal(t, s.Revoked, revoked) } - require.Equal(t, s.weight, weight) + require.Equal(t, s.Weight, weight) } }) } t.Run("can't merge with previous group due to run length limit", func(t *testing.T) { - status := make([]weightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup) + status := make([]WeightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup) for i := range len(status) { - status[i] = weightAndRevokedStatus{weight: 1000, revoked: true} + status[i] = WeightAndRevokedStatus{Weight: 1000, Revoked: true} } - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: false}) - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: false}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: false}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: false}) revokeIndex := uint32(maxRunLengthInWeightAndRevokedStatusGroup) @@ -445,7 +450,7 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } require.Equal(t, expected, b) @@ -462,19 +467,19 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { if uint32(i) == revokeIndex { require.Equal(t, true, revoked) } else { - require.Equal(t, s.revoked, revoked) + require.Equal(t, s.Revoked, revoked) } - require.Equal(t, s.weight, weight) + require.Equal(t, s.Weight, weight) } }) t.Run("merge with previous group at run length limit", func(t *testing.T) { - status := make([]weightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup-1) + status := make([]WeightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup-1) for i := range len(status) { - status[i] = weightAndRevokedStatus{weight: 1000, revoked: true} + status[i] = WeightAndRevokedStatus{Weight: 1000, Revoked: true} } - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: false}) - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: false}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: false}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: false}) revokeIndex := uint32(maxRunLengthInWeightAndRevokedStatusGroup - 1) @@ -493,7 +498,7 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } require.Equal(t, expected, b) @@ -510,18 +515,18 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { if uint32(i) == revokeIndex { require.Equal(t, true, revoked) } else { - require.Equal(t, s.revoked, revoked) + require.Equal(t, s.Revoked, revoked) } - require.Equal(t, s.weight, weight) + require.Equal(t, s.Weight, weight) } }) t.Run("partially merge with next group", func(t *testing.T) { - status := make([]weightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup+2) - status[0] = weightAndRevokedStatus{weight: 1000, revoked: false} - status[1] = weightAndRevokedStatus{weight: 1000, revoked: false} + status := make([]WeightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup+2) + status[0] = WeightAndRevokedStatus{Weight: 1000, Revoked: false} + status[1] = WeightAndRevokedStatus{Weight: 1000, Revoked: false} for i := 2; i < len(status); i++ { - status[i] = weightAndRevokedStatus{weight: 1000, revoked: true} + status[i] = WeightAndRevokedStatus{Weight: 1000, Revoked: true} } revokeIndex := uint32(1) @@ -542,7 +547,7 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } require.Equal(t, expected, b) @@ -559,20 +564,20 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { if uint32(i) == revokeIndex { require.Equal(t, true, revoked) } else { - require.Equal(t, s.revoked, revoked) + require.Equal(t, s.Revoked, revoked) } - require.Equal(t, s.weight, weight) + require.Equal(t, s.Weight, weight) } }) t.Run("cannot merge with previous group due to run length limit, partially merge with next group", func(t *testing.T) { - status := make([]weightAndRevokedStatus, 0, 2*maxRunLengthInWeightAndRevokedStatusGroup+1) + status := make([]WeightAndRevokedStatus, 0, 2*maxRunLengthInWeightAndRevokedStatusGroup+1) for range maxRunLengthInWeightAndRevokedStatusGroup { - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: true}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: true}) } - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: false}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: false}) for range maxRunLengthInWeightAndRevokedStatusGroup { - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: true}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: true}) } revokeIndex := uint32(maxRunLengthInWeightAndRevokedStatusGroup) @@ -594,7 +599,7 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } require.Equal(t, expected, b) @@ -611,20 +616,20 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { if uint32(i) == revokeIndex { require.Equal(t, true, revoked) } else { - require.Equal(t, s.revoked, revoked) + require.Equal(t, s.Revoked, revoked) } - require.Equal(t, s.weight, weight) + require.Equal(t, s.Weight, weight) } }) t.Run("merge with previous group and next group", func(t *testing.T) { - status := make([]weightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup-15) + status := make([]WeightAndRevokedStatus, maxRunLengthInWeightAndRevokedStatusGroup-15) for i := range len(status) { - status[i] = weightAndRevokedStatus{weight: 1000, revoked: true} + status[i] = WeightAndRevokedStatus{Weight: 1000, Revoked: true} } - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: false}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: false}) for range 14 { - status = append(status, weightAndRevokedStatus{weight: 1000, revoked: true}) + status = append(status, WeightAndRevokedStatus{Weight: 1000, Revoked: true}) } revokeIndex := uint32(maxRunLengthInWeightAndRevokedStatusGroup - 15) @@ -644,7 +649,7 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { // Encode and append status for _, s := range status { - b, err = appendWeightAndRevokedStatus(b, s.revoked, s.weight) + b, err = appendWeightAndRevokedStatus(b, s.Revoked, s.Weight) require.NoError(t, err) } require.Equal(t, expected, b) @@ -661,9 +666,9 @@ func TestSetRevokeInWeightAndRevokedStatus(t *testing.T) { if uint32(i) == revokeIndex { require.Equal(t, true, revoked) } else { - require.Equal(t, s.revoked, revoked) + require.Equal(t, s.Revoked, revoked) } - require.Equal(t, s.weight, weight) + require.Equal(t, s.Weight, weight) } }) } diff --git a/fvm/environment/account_creator.go b/fvm/environment/account_creator.go index f0212bdbd5b..beda87b20a0 100644 --- a/fvm/environment/account_creator.go +++ b/fvm/environment/account_creator.go @@ -3,10 +3,15 @@ package environment import ( "fmt" + "github.com/onflow/cadence" "github.com/onflow/cadence/common" + "github.com/onflow/cadence/interpreter" + "github.com/onflow/cadence/runtime" + "github.com/onflow/cadence/sema" "github.com/onflow/flow-go/fvm/errors" "github.com/onflow/flow-go/fvm/storage/state" + "github.com/onflow/flow-go/fvm/systemcontracts" "github.com/onflow/flow-go/fvm/tracing" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/trace" @@ -47,26 +52,37 @@ func NewParseRestrictedAccountCreator( func (creator ParseRestrictedAccountCreator) CreateAccount( runtimePayer common.Address, + invocationContext interpreter.InvocationContext, ) ( common.Address, error, ) { - return parseRestrict1Arg1Ret( + return parseRestrict2Arg1Ret( creator.txnState, trace.FVMEnvCreateAccount, creator.impl.CreateAccount, - runtimePayer) + runtimePayer, + invocationContext, + ) } type AccountCreator interface { - CreateAccount(runtimePayer common.Address) (common.Address, error) + // CreateAccount creates a new account, deducting the minimum storage reservation from `payer`. + // + // `context` is the invocation context of the currently-executing Cadence program + // (the one that invoked the `Account` constructor). + CreateAccount( + runtimePayer common.Address, + invocationContext interpreter.InvocationContext, + ) (common.Address, error) } type NoAccountCreator struct { } func (NoAccountCreator) CreateAccount( - runtimePayer common.Address, + _ common.Address, + _ interpreter.InvocationContext, ) ( common.Address, error, @@ -246,7 +262,8 @@ func (creator *accountCreator) CreateBootstrapAccount( } func (creator *accountCreator) CreateAccount( - runtimePayer common.Address, + payer common.Address, + invocationContext interpreter.InvocationContext, ) ( common.Address, error, @@ -266,14 +283,18 @@ func (creator *accountCreator) CreateAccount( // don't enforce limit during account creation var address flow.Address creator.txnState.RunWithMeteringDisabled(func() { - address, err = creator.createAccount(flow.ConvertAddress(runtimePayer)) + address, err = creator.createAccount( + flow.Address(payer), + invocationContext, + ) }) - return common.MustBytesToAddress(address.Bytes()), err + return common.Address(address), err } func (creator *accountCreator) createAccount( payer flow.Address, + invocationContext interpreter.InvocationContext, ) ( flow.Address, error, @@ -284,9 +305,30 @@ func (creator *accountCreator) createAccount( } if creator.isServiceAccountEnabled { - _, invokeErr := creator.systemContracts.SetupNewAccount( - address, - payer) + // Run `FlowServiceAccount.setupNewAccount` against the SAME Cadence invocation context + // (and thus the same storage) as the program that triggered account creation. + // Rather than borrowing a fresh runtime with its own storage, + // using the shared context ensures the minimum storage reservation deducted from the payer here is visible to, + // and committed by, that outer program. + // Otherwise the deduction would be made in a separate, independently-committed storage instance + // and could be overwritten, creating FLOW without a corresponding `TokensMinted` event. + contractLocation := common.AddressLocation{ + Address: common.Address(creator.chain.ServiceAddress()), + Name: systemcontracts.ContractNameServiceAccount, + } + + args := []cadence.Value{ + cadence.Address(address), + cadence.Address(payer), + } + + _, invokeErr := runtime.InvokeContractFunctionOnContext( + invocationContext, + contractLocation, + systemcontracts.ContractServiceAccountFunction_setupNewAccount, + args, + setupNewAccountArgumentTypes, + ) if invokeErr != nil { return flow.EmptyAddress, invokeErr } @@ -295,3 +337,30 @@ func (creator *accountCreator) createAccount( creator.metrics.RuntimeSetNumberOfAccounts(creator.AddressCount()) return address, nil } + +// `FlowServiceAccount.setupNewAccount` +// from https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowServiceAccount.cdc +var setupNewAccountArgumentTypes = []sema.Type{ + sema.NewReferenceType( + nil, + sema.NewEntitlementSetAccess( + []*sema.EntitlementType{ + sema.SaveValueType, + sema.BorrowValueType, + sema.CapabilitiesType, + }, + sema.Conjunction, + ), + sema.AccountType, + ), + sema.NewReferenceType( + nil, + sema.NewEntitlementSetAccess( + []*sema.EntitlementType{ + sema.BorrowValueType, + }, + sema.Conjunction, + ), + sema.AccountType, + ), +} diff --git a/fvm/environment/account_info.go b/fvm/environment/account_info.go index 81a90106da9..f47babe81da 100644 --- a/fvm/environment/account_info.go +++ b/fvm/environment/account_info.go @@ -179,7 +179,7 @@ func (info *accountInfo) GetStorageUsed( } value, err := info.accounts.GetStorageUsed( - flow.ConvertAddress(runtimeAddress)) + flow.Address(runtimeAddress)) if err != nil { return 0, fmt.Errorf("get storage used failed: %w", err) } @@ -214,7 +214,7 @@ func (info *accountInfo) GetStorageCapacity( } result, invokeErr := info.systemContracts.AccountStorageCapacity( - flow.ConvertAddress(runtimeAddress)) + flow.Address(runtimeAddress)) if invokeErr != nil { return 0, invokeErr } @@ -243,7 +243,7 @@ func (info *accountInfo) GetAccountBalance( return 0, fmt.Errorf("get account balance failed: %w", err) } - result, invokeErr := info.systemContracts.AccountBalance(flow.ConvertAddress(runtimeAddress)) + result, invokeErr := info.systemContracts.AccountBalance(flow.Address(runtimeAddress)) if invokeErr != nil { return 0, invokeErr } @@ -270,7 +270,7 @@ func (info *accountInfo) GetAccountAvailableBalance( return 0, fmt.Errorf("get account available balance failed: %w", err) } - result, invokeErr := info.systemContracts.AccountAvailableBalance(flow.ConvertAddress(runtimeAddress)) + result, invokeErr := info.systemContracts.AccountAvailableBalance(flow.Address(runtimeAddress)) if invokeErr != nil { return 0, invokeErr } @@ -293,7 +293,7 @@ func (info *accountInfo) GetAccount( if info.serviceAccountEnabled { balance, err := info.GetAccountBalance( - common.MustBytesToAddress(address.Bytes())) + common.Address(address)) if err != nil { return nil, err } diff --git a/fvm/environment/account_key_reader.go b/fvm/environment/account_key_reader.go index 7144ea1f171..6eed39d5dd9 100644 --- a/fvm/environment/account_key_reader.go +++ b/fvm/environment/account_key_reader.go @@ -117,7 +117,7 @@ func (reader *accountKeyReader) GetAccountKey( return formatErr(err) } - address := flow.ConvertAddress(runtimeAddress) + address := flow.Address(runtimeAddress) // address verification is also done in this step accountPublicKey, err := reader.accounts.GetRuntimeAccountPublicKey( @@ -168,7 +168,8 @@ func (reader *accountKeyReader) AccountKeysCount( // address verification is also done in this step keyCount, err := reader.accounts.GetAccountPublicKeyCount( - flow.ConvertAddress(runtimeAddress)) + flow.Address(runtimeAddress), + ) return keyCount, err } diff --git a/fvm/environment/account_key_updater.go b/fvm/environment/account_key_updater.go index 70679e98b44..62b6cbf200e 100644 --- a/fvm/environment/account_key_updater.go +++ b/fvm/environment/account_key_updater.go @@ -362,10 +362,11 @@ func (updater *accountKeyUpdater) AddAccountKey( } accKey, err := updater.addAccountKey( - flow.ConvertAddress(runtimeAddress), + flow.Address(runtimeAddress), publicKey, hashAlgo, - weight) + weight, + ) if err != nil { return nil, fmt.Errorf("add account key failed: %w", err) } @@ -393,6 +394,7 @@ func (updater *accountKeyUpdater) RevokeAccountKey( } return updater.revokeAccountKey( - flow.ConvertAddress(runtimeAddress), - keyIndex) + flow.Address(runtimeAddress), + keyIndex, + ) } diff --git a/fvm/environment/account_local_id_generator.go b/fvm/environment/account_local_id_generator.go index 079f292ac3e..3a890912d02 100644 --- a/fvm/environment/account_local_id_generator.go +++ b/fvm/environment/account_local_id_generator.go @@ -77,6 +77,6 @@ func (generator *accountLocalIDGenerator) GenerateAccountID( } return generator.accounts.GenerateAccountLocalID( - flow.ConvertAddress(runtimeAddress), + flow.Address(runtimeAddress), ) } diff --git a/fvm/environment/account_local_id_generator_test.go b/fvm/environment/account_local_id_generator_test.go index b0f91b0e699..4fcd8d8cab4 100644 --- a/fvm/environment/account_local_id_generator_test.go +++ b/fvm/environment/account_local_id_generator_test.go @@ -29,7 +29,7 @@ func Test_accountLocalIDGenerator_GenerateAccountID(t *testing.T) { ).Return(nil) accounts := envMock.NewAccounts(t) - accounts.On("GenerateAccountLocalID", flow.ConvertAddress(address)). + accounts.On("GenerateAccountLocalID", flow.Address(address)). Return(uint64(1), nil) generator := environment.NewAccountLocalIDGenerator( @@ -78,7 +78,7 @@ func Test_accountLocalIDGenerator_GenerateAccountID(t *testing.T) { ).Return(nil) accounts := envMock.NewAccounts(t) - accounts.On("GenerateAccountLocalID", flow.ConvertAddress(address)). + accounts.On("GenerateAccountLocalID", flow.Address(address)). Return(uint64(0), expectedErr) generator := environment.NewAccountLocalIDGenerator( diff --git a/fvm/environment/account_public_key_util.go b/fvm/environment/account_public_key_util.go index 753413fe6a4..7bb6d6611e3 100644 --- a/fvm/environment/account_public_key_util.go +++ b/fvm/environment/account_public_key_util.go @@ -353,3 +353,46 @@ func encodeBatchedPublicKey(encodedPublicKey []byte) ([]byte, error) { return buf, nil } + +// Utility functions for tests and validation + +// DecodeBatchPublicKeys decodes raw bytes of batch public keys in the batch public key payload. +func DecodeBatchPublicKeys(b []byte) ([][]byte, error) { + if len(b) == 0 { + return nil, nil + } + + encodedPublicKeys := make([][]byte, 0, MaxPublicKeyCountInBatch) + + off := 0 + for off < len(b) { + size := int(b[off]) + off++ + + if off+size > len(b) { + return nil, errors.NewCodedFailuref( + errors.FailureCodeBatchPublicKeyDecodingFailure, + "failed to decode batch public key", + "batch public key data is too short: %x", + b, + ) + } + + encodedPublicKey := b[off : off+size] + off += size + + encodedPublicKeys = append(encodedPublicKeys, encodedPublicKey) + } + + if off != len(b) { + return nil, errors.NewCodedFailuref( + errors.FailureCodeBatchPublicKeyDecodingFailure, + "failed to decode batch public key", + "batch public key data has trailing data (%d bytes): %x", + len(b)-off, + b, + ) + } + + return encodedPublicKeys, nil +} diff --git a/fvm/environment/account_public_key_util_test.go b/fvm/environment/account_public_key_util_test.go index 973f31316ec..c70c5867389 100644 --- a/fvm/environment/account_public_key_util_test.go +++ b/fvm/environment/account_public_key_util_test.go @@ -238,11 +238,17 @@ func TestGetStoredPublicKey(t *testing.T) { expectedStoredPublicKey1 := accountPublicKeyToStoredKey(accountPublicKey1) expectedStoredPublicKey2 := accountPublicKeyToStoredKey(newAccountPublicKey(t, 1)) + encodedStoredPublicKey2, err := flow.EncodeStoredPublicKey(expectedStoredPublicKey2) + require.NoError(t, err) + + encodedBatchPublicKey := newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &expectedStoredPublicKey2}) + expectedBatchPublicKeys := [][]byte{[]byte{}, encodedStoredPublicKey2} + accounts := envMock.NewAccounts(t) accounts.On("GetValue", flow.AccountPublicKey0RegisterID(address)). Return(encodedAccountPublicKey1, nil) accounts.On("GetValue", flow.AccountBatchPublicKeyRegisterID(address, 0)). - Return(newBatchPublicKey(t, []*flow.StoredPublicKey{nil, &expectedStoredPublicKey2}), nil) + Return(encodedBatchPublicKey, nil) spk, err := environment.GetStoredPublicKey(accounts, address, 0) require.NoError(t, err) @@ -251,6 +257,10 @@ func TestGetStoredPublicKey(t *testing.T) { spk, err = environment.GetStoredPublicKey(accounts, address, 1) require.NoError(t, err) require.Equal(t, expectedStoredPublicKey2, spk) + + encodedKeys, err := environment.DecodeBatchPublicKeys(encodedBatchPublicKey) + require.NoError(t, err) + require.Equal(t, expectedBatchPublicKeys, encodedKeys) }) t.Run("one full batch", func(t *testing.T) { @@ -260,17 +270,26 @@ func TestGetStoredPublicKey(t *testing.T) { storedKeyCount := environment.MaxPublicKeyCountInBatch expectedStoredKeys := make([]*flow.StoredPublicKey, storedKeyCount) + expectedBatchPublicKeys := make([][]byte, storedKeyCount) + expectedBatchPublicKeys[0] = []byte{} for i := 1; i < environment.MaxPublicKeyCountInBatch; i++ { key := accountPublicKeyToStoredKey(newAccountPublicKey(t, 1)) expectedStoredKeys[i] = &key + + encodedStoredPublicKey, err := flow.EncodeStoredPublicKey(key) + require.NoError(t, err) + + expectedBatchPublicKeys[i] = encodedStoredPublicKey } + encodedBatchPublicKey := newBatchPublicKey(t, expectedStoredKeys) + accounts := envMock.NewAccounts(t) accounts.On("GetValue", flow.AccountPublicKey0RegisterID(address)). Return(encodedAccountPublicKey1, nil) accounts.On("GetValue", flow.AccountBatchPublicKeyRegisterID(address, 0)). - Return(newBatchPublicKey(t, expectedStoredKeys), nil) + Return(encodedBatchPublicKey, nil) spk, err := environment.GetStoredPublicKey(accounts, address, 0) require.NoError(t, err) @@ -281,6 +300,10 @@ func TestGetStoredPublicKey(t *testing.T) { require.NoError(t, err) require.Equal(t, *expectedStoredKeys[i], spk) } + + encodedKeys, err := environment.DecodeBatchPublicKeys(encodedBatchPublicKey) + require.NoError(t, err) + require.Equal(t, expectedBatchPublicKeys, encodedKeys) }) t.Run("more than one batch", func(t *testing.T) { @@ -291,19 +314,32 @@ func TestGetStoredPublicKey(t *testing.T) { storedKeyCount := environment.MaxPublicKeyCountInBatch + 1 expectedStoredKeys := make([]*flow.StoredPublicKey, storedKeyCount) + expectedBatchPublicKeys := make([][]byte, storedKeyCount) + expectedBatchPublicKeys[0] = []byte{} for i := 1; i < storedKeyCount; i++ { key := accountPublicKeyToStoredKey(newAccountPublicKey(t, 1)) expectedStoredKeys[i] = &key + + encodedStoredPublicKey, err := flow.EncodeStoredPublicKey(key) + require.NoError(t, err) + + expectedBatchPublicKeys[i] = encodedStoredPublicKey } + encodedBatchPublicKey1 := newBatchPublicKey(t, expectedStoredKeys[:environment.MaxPublicKeyCountInBatch]) + encodedBatchPublicKey2 := newBatchPublicKey(t, expectedStoredKeys[environment.MaxPublicKeyCountInBatch:]) + + expectedBatchPublicKeys1 := expectedBatchPublicKeys[:environment.MaxPublicKeyCountInBatch] + expectedBatchPublicKeys2 := expectedBatchPublicKeys[environment.MaxPublicKeyCountInBatch:] + accounts := envMock.NewAccounts(t) accounts.On("GetValue", flow.AccountPublicKey0RegisterID(address)). Return(encodedAccountPublicKey1, nil) accounts.On("GetValue", flow.AccountBatchPublicKeyRegisterID(address, 0)). - Return(newBatchPublicKey(t, expectedStoredKeys[:environment.MaxPublicKeyCountInBatch]), nil) + Return(encodedBatchPublicKey1, nil) accounts.On("GetValue", flow.AccountBatchPublicKeyRegisterID(address, 1)). - Return(newBatchPublicKey(t, expectedStoredKeys[environment.MaxPublicKeyCountInBatch:]), nil) + Return(encodedBatchPublicKey2, nil) spk, err := environment.GetStoredPublicKey(accounts, address, 0) require.NoError(t, err) @@ -314,6 +350,14 @@ func TestGetStoredPublicKey(t *testing.T) { require.NoError(t, err) require.Equal(t, *expectedStoredKeys[i], spk) } + + encodedKeys1, err := environment.DecodeBatchPublicKeys(encodedBatchPublicKey1) + require.NoError(t, err) + require.Equal(t, expectedBatchPublicKeys1, encodedKeys1) + + encodedKeys2, err := environment.DecodeBatchPublicKeys(encodedBatchPublicKey2) + require.NoError(t, err) + require.Equal(t, expectedBatchPublicKeys2, encodedKeys2) }) } diff --git a/fvm/environment/accounts_status.go b/fvm/environment/accounts_status.go index 48bf0561bc9..3f66b016c6b 100644 --- a/fvm/environment/accounts_status.go +++ b/fvm/environment/accounts_status.go @@ -12,32 +12,13 @@ import ( ) const ( - flagSize = 1 - storageUsedSize = 8 - storageIndexSize = 8 - oldAccountPublicKeyCountsSize = 8 - accountPublicKeyCountsSize = 4 - addressIdCounterSize = 8 - - // accountStatusSizeV1 is the size of the account status before the address - // id counter was added. After Crescendo check if it can be removed as all accounts - // should then have the new status sile len. - accountStatusSizeV1 = flagSize + - storageUsedSize + - storageIndexSize + - oldAccountPublicKeyCountsSize - - // accountStatusSizeV2 is the size of the account status before - // the public key count was changed from 8 to 4 bytes long. - // After Crescendo check if it can be removed as all accounts - // should then have the new status sile len. - accountStatusSizeV2 = flagSize + - storageUsedSize + - storageIndexSize + - oldAccountPublicKeyCountsSize + - addressIdCounterSize + flagSize = 1 + storageUsedSize = 8 + storageIndexSize = 8 + accountPublicKeyCountsSize = 4 + addressIdCounterSize = 8 - accountStatusSizeV3 = flagSize + + AccountStatusMinSize = flagSize + storageUsedSize + storageIndexSize + accountPublicKeyCountsSize + @@ -53,12 +34,10 @@ const ( deduplicationFlagMask = 0x01 accountStatusV4DefaultVersionAndFlag = 0x40 - - AccountStatusMinSizeV4 = accountStatusSizeV3 ) const ( - maxStoredDigests = 2 // Account status register stores up to 2 digests from last 2 stored keys. + MaxStoredDigests = 2 // Account status register stores up to 2 digests from last 2 stored keys. ) // AccountStatus holds meta information about an account @@ -69,17 +48,17 @@ const ( // the next 8 bytes (big-endian) captures the storage index of an account // the next 4 bytes (big-endian) captures the number of public keys stored on this account // the next 8 bytes (big-endian) captures the current address id counter -type accountStatusV3 [accountStatusSizeV3]byte +type accountStatusPacked [AccountStatusMinSize]byte type AccountStatus struct { - accountStatusV3 + accountStatusPacked keyMetadataBytes []byte } // NewAccountStatus returns a new AccountStatus // sets the storage index to the init value func NewAccountStatus() *AccountStatus { - as := accountStatusV3{ + as := accountStatusPacked{ accountStatusV4DefaultVersionAndFlag, // initial empty flags 0, 0, 0, 0, 0, 0, 0, 0, // init value for storage used 0, 0, 0, 0, 0, 0, 0, 1, // init value for storage index @@ -87,7 +66,7 @@ func NewAccountStatus() *AccountStatus { 0, 0, 0, 0, 0, 0, 0, 0, // init value for address id counter } return &AccountStatus{ - accountStatusV3: as, + accountStatusPacked: as, } } @@ -98,169 +77,88 @@ func NewAccountStatus() *AccountStatus { // account status. func (a *AccountStatus) ToBytes() []byte { if len(a.keyMetadataBytes) == 0 { - return a.accountStatusV3[:] + return a.accountStatusPacked[:] } - return append(a.accountStatusV3[:], a.keyMetadataBytes...) + return append(a.accountStatusPacked[:], a.keyMetadataBytes...) } // AccountStatusFromBytes constructs an AccountStatus from the given byte slice func AccountStatusFromBytes(inp []byte) (*AccountStatus, error) { - asv3, rest, err := accountStatusV3FromBytes(inp) + as, rest, err := accountStatusFromBytes(inp) if err != nil { return nil, err } - // NOTE: both accountStatusV3 and keyMetadataBytes are copies. + // NOTE: both accountStatusPacked and keyMetadataBytes are copies. return &AccountStatus{ - accountStatusV3: asv3, - keyMetadataBytes: append([]byte(nil), rest...), + accountStatusPacked: as, + keyMetadataBytes: append([]byte(nil), rest...), }, nil } -func accountStatusV3FromBytes(inp []byte) (accountStatusV3, []byte, error) { - sizeChange := int64(0) - - // this is to migrate old account status to new account status on the fly - // TODO: remove this whole block after Crescendo, when a full migration will be made. - if len(inp) == accountStatusSizeV1 { - // migrate v1 to v2 - inp2 := make([]byte, accountStatusSizeV2) - - // pad the input with zeros - sizeIncrease := int64(accountStatusSizeV2 - accountStatusSizeV1) - - // But we also need to fix the storage used by the appropriate size because - // the storage used is part of the account status itself. - copy(inp2, inp) - sizeChange = sizeIncrease - - inp = inp2 +func accountStatusFromBytes(inp []byte) (accountStatusPacked, []byte, error) { + if len(inp) < AccountStatusMinSize { + return accountStatusPacked{}, nil, errors.NewValueErrorf(hex.EncodeToString(inp), "invalid account status size") } - // this is to migrate old account status to new account status on the fly - // TODO: remove this whole block after Crescendo, when a full migration will be made. - if len(inp) == accountStatusSizeV2 { - // migrate v2 to v3 - - inp2 := make([]byte, accountStatusSizeV2) - // copy the old account status first, so that we don't slice the input - copy(inp2, inp) - - // cut leading 4 bytes of old public key count. - cutStart := flagSize + - storageUsedSize + - storageIndexSize - - cutEnd := flagSize + - storageUsedSize + - storageIndexSize + - (oldAccountPublicKeyCountsSize - accountPublicKeyCountsSize) - - // check if the public key count is larger than 4 bytes - for i := cutStart; i < cutEnd; i++ { - if inp2[i] != 0 { - return accountStatusV3{}, nil, fmt.Errorf("cannot migrate account status from v2 to v3: public key count is larger than 4 bytes %v, %v", hex.EncodeToString(inp2[flagSize+ - storageUsedSize+ - storageIndexSize:flagSize+ - storageUsedSize+ - storageIndexSize+ - oldAccountPublicKeyCountsSize]), inp2[i]) - } - } - - inp2 = append(inp2[:cutStart], inp2[cutEnd:]...) - - sizeDecrease := int64(accountStatusSizeV2 - accountStatusSizeV3) - - // But we also need to fix the storage used by the appropriate size because - // the storage used is part of the account status itself. - sizeChange -= sizeDecrease - - inp = inp2 - } - - if len(inp) < accountStatusSizeV3 { - return accountStatusV3{}, nil, errors.NewValueErrorf(hex.EncodeToString(inp), "invalid account status size") - } - - inp, rest := inp[:accountStatusSizeV3], inp[accountStatusSizeV3:] - - var as accountStatusV3 + inp, rest := inp[:AccountStatusMinSize], inp[AccountStatusMinSize:] + var as accountStatusPacked copy(as[:], inp) - if sizeChange != 0 { - used := as.StorageUsed() - - if sizeChange < 0 { - // check if the storage used is smaller than the size change - if used < uint64(-sizeChange) { - return accountStatusV3{}, nil, errors.NewValueErrorf(hex.EncodeToString(inp), "account would have negative storage used after migration") - } - - used = used - uint64(-sizeChange) - } - - if sizeChange > 0 { - used = used + uint64(sizeChange) - } - - as.SetStorageUsed(used) - } - return as, rest, nil } -func (a *accountStatusV3) Version() uint8 { +func (a *accountStatusPacked) Version() uint8 { return (a[0] & versionMask) >> 4 } -func (a *accountStatusV3) IsAccountKeyDeduplicated() bool { +func (a *accountStatusPacked) IsAccountKeyDeduplicated() bool { return (a[0] & deduplicationFlagMask) != 0 } -func (a *accountStatusV3) setAccountKeyDeduplicationFlag() { +func (a *accountStatusPacked) setAccountKeyDeduplicationFlag() { a[0] |= deduplicationFlagMask } // SetStorageUsed updates the storage used by the account -func (a *accountStatusV3) SetStorageUsed(used uint64) { +func (a *accountStatusPacked) SetStorageUsed(used uint64) { binary.BigEndian.PutUint64(a[storageUsedStartIndex:storageUsedStartIndex+storageUsedSize], used) } // StorageUsed returns the storage used by the account -func (a *accountStatusV3) StorageUsed() uint64 { +func (a *accountStatusPacked) StorageUsed() uint64 { return binary.BigEndian.Uint64(a[storageUsedStartIndex : storageUsedStartIndex+storageUsedSize]) } // SetStorageIndex updates the storage index of the account -func (a *accountStatusV3) SetStorageIndex(index atree.SlabIndex) { +func (a *accountStatusPacked) SetStorageIndex(index atree.SlabIndex) { copy(a[storageIndexStartIndex:storageIndexStartIndex+storageIndexSize], index[:storageIndexSize]) } // SlabIndex returns the storage index of the account -func (a *accountStatusV3) SlabIndex() atree.SlabIndex { +func (a *accountStatusPacked) SlabIndex() atree.SlabIndex { var index atree.SlabIndex copy(index[:], a[storageIndexStartIndex:storageIndexStartIndex+storageIndexSize]) return index } // SetAccountPublicKeyCount updates the account public key count of the account -func (a *accountStatusV3) SetAccountPublicKeyCount(count uint32) { +func (a *accountStatusPacked) SetAccountPublicKeyCount(count uint32) { binary.BigEndian.PutUint32(a[accountPublicKeyCountsStartIndex:accountPublicKeyCountsStartIndex+accountPublicKeyCountsSize], count) } // AccountPublicKeyCount returns the account public key count of the account -func (a *accountStatusV3) AccountPublicKeyCount() uint32 { +func (a *accountStatusPacked) AccountPublicKeyCount() uint32 { return binary.BigEndian.Uint32(a[accountPublicKeyCountsStartIndex : accountPublicKeyCountsStartIndex+accountPublicKeyCountsSize]) } // SetAccountIdCounter updates id counter of the account -func (a *accountStatusV3) SetAccountIdCounter(id uint64) { +func (a *accountStatusPacked) SetAccountIdCounter(id uint64) { binary.BigEndian.PutUint64(a[addressIdCounterStartIndex:addressIdCounterStartIndex+addressIdCounterSize], id) } // AccountIdCounter returns id counter of the account -func (a *accountStatusV3) AccountIdCounter() uint64 { +func (a *accountStatusPacked) AccountIdCounter() uint64 { return binary.BigEndian.Uint64(a[addressIdCounterStartIndex : addressIdCounterStartIndex+addressIdCounterSize]) } @@ -377,10 +275,10 @@ func (a *AccountStatus) appendAccountPublicKeyMetadata( key0Digest := getKeyDigest(key0) // Create empty KeyMetadataAppender with key 0 digest. - keyMetadata = accountkeymetadata.NewKeyMetadataAppender(key0Digest, maxStoredDigests) + keyMetadata = accountkeymetadata.NewKeyMetadataAppender(key0Digest, MaxStoredDigests) } else { // Create KeyMetadataAppender with stored key metadata bytes. - keyMetadata, err = accountkeymetadata.NewKeyMetadataAppenderFromBytes(a.keyMetadataBytes, a.IsAccountKeyDeduplicated(), maxStoredDigests) + keyMetadata, err = accountkeymetadata.NewKeyMetadataAppenderFromBytes(a.keyMetadataBytes, a.IsAccountKeyDeduplicated(), MaxStoredDigests) if err != nil { return nil, 0, false, err } diff --git a/fvm/environment/accounts_status_test.go b/fvm/environment/accounts_status_test.go index 83251064e7e..a53c9cc15ba 100644 --- a/fvm/environment/accounts_status_test.go +++ b/fvm/environment/accounts_status_test.go @@ -42,50 +42,6 @@ func TestAccountStatus(t *testing.T) { _, err = environment.AccountStatusFromBytes([]byte{1, 2}) require.Error(t, err) }) - - t.Run("test serialization - v1 format", func(t *testing.T) { - // TODO: remove this test when we remove support for the old format - oldBytes := []byte{ - 0, // flags - 0, 0, 0, 0, 0, 0, 0, 7, // storage used - 0, 0, 0, 0, 0, 0, 0, 6, // storage index - 0, 0, 0, 0, 0, 0, 0, 5, // public key counts - } - - // The new format has an extra 8 bytes for the account id counter - // so we need to increase the storage used by 8 bytes while migrating it - // for v2->v3 migration, we need to decrease the storage used by 4 bytes - increaseInSize := uint64(4) - - migrated, err := environment.AccountStatusFromBytes(oldBytes) - require.NoError(t, err) - require.Equal(t, atree.SlabIndex{0, 0, 0, 0, 0, 0, 0, 6}, migrated.SlabIndex()) - require.Equal(t, uint32(5), migrated.AccountPublicKeyCount()) - require.Equal(t, uint64(7)+increaseInSize, migrated.StorageUsed()) - require.Equal(t, uint64(0), migrated.AccountIdCounter()) - }) - - t.Run("test serialization - v2 format", func(t *testing.T) { - // TODO: remove this test when we remove support for the old format - oldBytes := []byte{ - 0, // flags - 0, 0, 0, 0, 0, 0, 0, 7, // storage used - 0, 0, 0, 0, 0, 0, 0, 6, // storage index - 0, 0, 0, 0, 0, 0, 0, 5, // public key counts - 0, 0, 0, 0, 0, 0, 0, 3, // account id counter - } - - // for v2->v3 migration, we are shrinking the public key counts from uint64 to uint32 - // so we need to decrease the storage used by 4 bytes - decreaseInSize := uint64(4) - - migrated, err := environment.AccountStatusFromBytes(oldBytes) - require.NoError(t, err) - require.Equal(t, atree.SlabIndex{0, 0, 0, 0, 0, 0, 0, 6}, migrated.SlabIndex()) - require.Equal(t, uint32(5), migrated.AccountPublicKeyCount()) - require.Equal(t, uint64(7)-decreaseInSize, migrated.StorageUsed()) - require.Equal(t, uint64(3), migrated.AccountIdCounter()) - }) } func TestAccountStatusV4AppendAndGetKeyMetadata(t *testing.T) { diff --git a/fvm/environment/contract_reader.go b/fvm/environment/contract_reader.go index d387cdae46c..9ae979781f8 100644 --- a/fvm/environment/contract_reader.go +++ b/fvm/environment/contract_reader.go @@ -55,7 +55,7 @@ func (reader *ContractReader) GetAccountContractNames( return nil, fmt.Errorf("get account contract names failed: %w", err) } - address := flow.ConvertAddress(runtimeAddress) + address := flow.Address(runtimeAddress) return reader.accounts.GetContractNames(address) } @@ -127,7 +127,7 @@ func ResolveLocation( return nil, fmt.Errorf("no identifiers provided") } - address := flow.ConvertAddress(addressLocation.Address) + address := flow.Address(addressLocation.Address) contractNames, err := getContractNames(address) if err != nil { @@ -184,7 +184,7 @@ func (reader *ContractReader) getCode( return nil, fmt.Errorf("get code failed: %w", err) } - add, err := reader.accounts.GetContract(location.Name, flow.ConvertAddress(location.Address)) + add, err := reader.accounts.GetContract(location.Name, flow.Address(location.Address)) if err != nil { return nil, fmt.Errorf("get code failed: %w", err) } diff --git a/fvm/environment/contract_updater.go b/fvm/environment/contract_updater.go index 534aea89afa..958b5802f1d 100644 --- a/fvm/environment/contract_updater.go +++ b/fvm/environment/contract_updater.go @@ -164,7 +164,7 @@ type contractUpdaterStubsImpl struct { logger *ProgramLogger systemContracts *SystemContracts - runtime *Runtime + runtime CadenceRuntimeProvider } func (impl *contractUpdaterStubsImpl) RestrictedDeploymentEnabled() bool { @@ -296,7 +296,7 @@ func NewContractUpdater( params ContractUpdaterParams, logger *ProgramLogger, systemContracts *SystemContracts, - runtime *Runtime, + runtime CadenceRuntimeProvider, ) *ContractUpdaterImpl { updater := &ContractUpdaterImpl{ tracer: tracer, @@ -378,7 +378,7 @@ func (updater *ContractUpdaterImpl) SetContract( // Initial contract deployments must be authorized by signing accounts. // // Contract updates are always allowed. - exists, err := updater.accounts.ContractExists(location.Name, flow.ConvertAddress(location.Address)) + exists, err := updater.accounts.ContractExists(location.Name, flow.Address(location.Address)) if err != nil { return err } @@ -433,7 +433,7 @@ func (updater *ContractUpdaterImpl) Commit() (ContractUpdates, error) { var err error for _, v := range updateList { var currentlyExists bool - currentlyExists, err = updater.accounts.ContractExists(v.Location.Name, flow.ConvertAddress(v.Location.Address)) + currentlyExists, err = updater.accounts.ContractExists(v.Location.Name, flow.Address(v.Location.Address)) if err != nil { return ContractUpdates{}, err } @@ -442,7 +442,7 @@ func (updater *ContractUpdaterImpl) Commit() (ContractUpdates, error) { if shouldDelete { // this is a removal contractUpdates.Deletions = append(contractUpdates.Deletions, v.Location) - err = updater.accounts.DeleteContract(v.Location.Name, flow.ConvertAddress(v.Location.Address)) + err = updater.accounts.DeleteContract(v.Location.Name, flow.Address(v.Location.Address)) if err != nil { return ContractUpdates{}, err } @@ -455,7 +455,11 @@ func (updater *ContractUpdaterImpl) Commit() (ContractUpdates, error) { contractUpdates.Updates = append(contractUpdates.Updates, v.Location) } - err = updater.accounts.SetContract(v.Location.Name, flow.ConvertAddress(v.Location.Address), v.Code) + err = updater.accounts.SetContract( + v.Location.Name, + flow.Address(v.Location.Address), + v.Code, + ) if err != nil { return ContractUpdates{}, err } @@ -541,7 +545,7 @@ func cadenceValueToAddressSlice(value cadence.Value) ( if !ok { return nil, false } - addresses = append(addresses, flow.ConvertAddress(a)) + addresses = append(addresses, flow.Address(a)) } return addresses, true } diff --git a/fvm/environment/contract_updater_test.go b/fvm/environment/contract_updater_test.go index 861b0bdb860..4e190b54a2b 100644 --- a/fvm/environment/contract_updater_test.go +++ b/fvm/environment/contract_updater_test.go @@ -60,7 +60,7 @@ func TestContract_ChildMergeFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract", - Address: common.MustBytesToAddress(address.Bytes())}, + Address: common.Address(address)}, []byte("ABC"), nil) require.NoError(t, err) @@ -82,7 +82,7 @@ func TestContract_ChildMergeFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract2", - Address: common.MustBytesToAddress(address.Bytes())}, + Address: common.Address(address)}, []byte("ABC"), nil) require.NoError(t, err) @@ -104,7 +104,7 @@ func TestContract_ChildMergeFunctionality(t *testing.T) { // remove err = contractUpdater.RemoveContract(common.AddressLocation{ Name: "testContract", - Address: common.MustBytesToAddress(address.Bytes())}, nil) + Address: common.Address(address)}, nil) require.NoError(t, err) // contract still there because no commit yet @@ -160,7 +160,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract1", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{unAuth}) require.Error(t, err) @@ -173,7 +173,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract1", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{authRemove}) require.Error(t, err) @@ -186,7 +186,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract2", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{authAdd}) require.NoError(t, err) @@ -199,7 +199,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract2", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{authBoth}) require.NoError(t, err) @@ -212,7 +212,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract1", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{authAdd}) require.NoError(t, err) @@ -222,7 +222,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.RemoveContract( common.AddressLocation{ Name: "testContract2", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []flow.Address{unAuth}) require.Error(t, err) require.False(t, contractUpdater.HasUpdates()) @@ -234,7 +234,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract1", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{authAdd}) require.NoError(t, err) @@ -244,7 +244,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.RemoveContract( common.AddressLocation{ Name: "testContract2", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []flow.Address{authRemove}) require.NoError(t, err) require.True(t, contractUpdater.HasUpdates()) @@ -256,7 +256,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract1", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{authAdd}) require.NoError(t, err) @@ -266,7 +266,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.RemoveContract( common.AddressLocation{ Name: "testContract2", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []flow.Address{authAdd}) require.Error(t, err) require.False(t, contractUpdater.HasUpdates()) @@ -278,7 +278,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.SetContract( common.AddressLocation{ Name: "testContract1", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []byte("ABC"), []flow.Address{authAdd}) require.NoError(t, err) @@ -288,7 +288,7 @@ func TestContract_AuthorizationFunctionality(t *testing.T) { err = contractUpdater.RemoveContract( common.AddressLocation{ Name: "testContract2", - Address: common.MustBytesToAddress(authAdd.Bytes())}, + Address: common.Address(authAdd)}, []flow.Address{authBoth}) require.NoError(t, err) require.True(t, contractUpdater.HasUpdates()) @@ -316,21 +316,21 @@ func TestContract_DeterministicErrorOnCommit(t *testing.T) { err := contractUpdater.SetContract( common.AddressLocation{ Name: "A", - Address: common.MustBytesToAddress(address2.Bytes())}, + Address: common.Address(address2)}, []byte("ABC"), nil) require.NoError(t, err) err = contractUpdater.SetContract( common.AddressLocation{ Name: "B", - Address: common.MustBytesToAddress(address1.Bytes())}, + Address: common.Address(address1)}, []byte("ABC"), nil) require.NoError(t, err) err = contractUpdater.SetContract( common.AddressLocation{ Name: "A", - Address: common.MustBytesToAddress(address1.Bytes())}, + Address: common.Address(address1)}, []byte("ABC"), nil) require.NoError(t, err) @@ -355,7 +355,7 @@ func TestContract_ContractRemoval(t *testing.T) { location := common.AddressLocation{ Name: "TestContract", - Address: common.MustBytesToAddress(flowAddress.Bytes())} + Address: common.Address(flowAddress)} // deploy contract with voucher err = contractUpdater.SetContract( @@ -411,7 +411,7 @@ func TestContract_ContractRemoval(t *testing.T) { location := common.AddressLocation{ Name: "TestContract", - Address: common.MustBytesToAddress(flowAddress.Bytes())} + Address: common.Address(flowAddress)} // deploy contract with voucher err = contractUpdater.SetContract( diff --git a/fvm/environment/derived_data_invalidator_test.go b/fvm/environment/derived_data_invalidator_test.go index 9598d93f4b1..598a509773a 100644 --- a/fvm/environment/derived_data_invalidator_test.go +++ b/fvm/environment/derived_data_invalidator_test.go @@ -28,7 +28,7 @@ func TestDerivedDataProgramInvalidator(t *testing.T) { // ``` addressA := flow.HexToAddress("0xa") - cAddressA := common.MustBytesToAddress(addressA.Bytes()) + cAddressA := common.Address(addressA) programALoc := common.AddressLocation{Address: cAddressA, Name: "A"} programA2Loc := common.AddressLocation{Address: cAddressA, Name: "A2"} programA := &derived.Program{ @@ -38,7 +38,7 @@ func TestDerivedDataProgramInvalidator(t *testing.T) { } addressB := flow.HexToAddress("0xb") - cAddressB := common.MustBytesToAddress(addressB.Bytes()) + cAddressB := common.Address(addressB) programBLoc := common.AddressLocation{Address: cAddressB, Name: "B"} programBDep := derived.NewProgramDependencies() programBDep.Add(programALoc) @@ -51,7 +51,7 @@ func TestDerivedDataProgramInvalidator(t *testing.T) { } addressD := flow.HexToAddress("0xd") - cAddressD := common.MustBytesToAddress(addressD.Bytes()) + cAddressD := common.Address(addressD) programDLoc := common.AddressLocation{Address: cAddressD, Name: "D"} programD := &derived.Program{ Program: nil, @@ -60,7 +60,7 @@ func TestDerivedDataProgramInvalidator(t *testing.T) { } addressC := flow.HexToAddress("0xc") - cAddressC := common.MustBytesToAddress(addressC.Bytes()) + cAddressC := common.Address(addressC) programCLoc := common.AddressLocation{Address: cAddressC, Name: "C"} programC := &derived.Program{ Program: nil, @@ -244,7 +244,7 @@ func TestMeterParamOverridesUpdated(t *testing.T) { snapshotTree := snapshot.NewSnapshotTree(nil) - ctx := fvm.NewContext(fvm.WithChain(flow.Emulator.Chain())) + ctx := fvm.NewContext(flow.Emulator.Chain()) vm := fvm.NewVirtualMachine() executionSnapshot, _, err := vm.Run( diff --git a/fvm/environment/env.go b/fvm/environment/env.go index 5f7606ea7f5..60066684c7e 100644 --- a/fvm/environment/env.go +++ b/fvm/environment/env.go @@ -2,10 +2,10 @@ package environment import ( "github.com/onflow/cadence" + "github.com/onflow/cadence/common" "github.com/onflow/cadence/runtime" + "github.com/onflow/cadence/sema" - "github.com/onflow/flow-go/fvm/cadence_vm" - reusableRuntime "github.com/onflow/flow-go/fvm/runtime" "github.com/onflow/flow-go/model/flow" ) @@ -21,8 +21,8 @@ type Environment interface { MetricsReporter // Runtime - BorrowCadenceRuntime() *reusableRuntime.ReusableCadenceRuntime - ReturnCadenceRuntime(*reusableRuntime.ReusableCadenceRuntime) + BorrowCadenceRuntime() ReusableCadenceRuntime + ReturnCadenceRuntime(ReusableCadenceRuntime) TransactionInfo @@ -72,6 +72,8 @@ type Environment interface { // history for commit-reveal schemes. RandomSourceHistory() ([]byte, error) + EVMTestOperationsAllowed() bool + // FlushPendingUpdates flushes pending updates from the stateful environment // modules (i.e., ContractUpdater) to the state transaction, and return // the updated contract keys. @@ -83,6 +85,56 @@ type Environment interface { // Reset resets all stateful environment modules (e.g., ContractUpdater, // EventEmitter) to initial state. Reset() + + EVMBlockStore +} + +// ReusableCadenceRuntime is a wrapper around the cadence runtime and environment that +// is reused between procedures +type ReusableCadenceRuntime interface { + // ReadStored calls the internal runtime.Runtime.ReadStored + ReadStored( + address common.Address, + path cadence.Path, + ) ( + cadence.Value, + error, + ) + + // NewTransactionExecutor calls the internal runtime.Runtime.NewTransactionExecutor + NewTransactionExecutor( + script runtime.Script, + location common.Location, + ) runtime.Executor + + // ExecuteScript calls the internal runtime.Runtime.ExecuteScript + ExecuteScript( + script runtime.Script, + location common.Location, + ) ( + cadence.Value, + error, + ) + + // InvokeContractFunction calls the internal runtime.Runtime.InvokeContractFunction + InvokeContractFunction( + contractLocation common.AddressLocation, + functionName string, + arguments []cadence.Value, + argumentTypes []sema.Type, + ) ( + cadence.Value, + error, + ) + + // CadenceTXEnv returns a cadence runtime.Environment set up for use in transactions + CadenceTXEnv() runtime.Environment + + // CadenceScriptEnv returns a cadence runtime.Environment set up for use in scripts + CadenceScriptEnv() runtime.Environment + + // SetFvmEnvironment sets the underlying Environment for the cadence runtime to use + SetFvmEnvironment(fvmEnv Environment) } type EnvironmentParams struct { @@ -110,22 +162,6 @@ type EnvironmentParams struct { ContractUpdaterParams } -func DefaultEnvironmentParams() EnvironmentParams { - const chainID = flow.Mainnet - return EnvironmentParams{ - Chain: chainID.Chain(), - ServiceAccountEnabled: true, - CadenceVMEnabled: cadence_vm.DefaultEnabled, - RuntimeParams: DefaultRuntimeParams(), - ProgramLoggerParams: DefaultProgramLoggerParams(), - EventEmitterParams: DefaultEventEmitterParams(), - BlockInfoParams: DefaultBlockInfoParams(), - TransactionInfoParams: DefaultTransactionInfoParams(), - ContractUpdaterParams: DefaultContractUpdaterParams(), - ExecutionVersionProvider: ZeroExecutionVersionProvider{}, - } -} - func (env *EnvironmentParams) SetScriptInfoParams(info *ScriptInfoParams) { env.ScriptInfoParams = *info } diff --git a/fvm/environment/event_emitter_test.go b/fvm/environment/event_emitter_test.go index ecd6e5ae17c..25e1addf4ab 100644 --- a/fvm/environment/event_emitter_test.go +++ b/fvm/environment/event_emitter_test.go @@ -30,8 +30,7 @@ func Test_IsServiceEvent(t *testing.T) { event := cadence.Event{ EventType: &cadence.EventType{ Location: common.AddressLocation{ - Address: common.MustBytesToAddress( - event.Address.Bytes()), + Address: common.Address(event.Address), }, QualifiedIdentifier: event.QualifiedIdentifier(), }, @@ -47,8 +46,7 @@ func Test_IsServiceEvent(t *testing.T) { event := cadence.Event{ EventType: &cadence.EventType{ Location: common.AddressLocation{ - Address: common.MustBytesToAddress( - flow.Testnet.Chain().ServiceAddress().Bytes()), + Address: common.Address(flow.Testnet.Chain().ServiceAddress()), }, QualifiedIdentifier: events.EpochCommit.QualifiedIdentifier(), }, @@ -63,8 +61,7 @@ func Test_IsServiceEvent(t *testing.T) { event := cadence.Event{ EventType: &cadence.EventType{ Location: common.AddressLocation{ - Address: common.MustBytesToAddress( - chain.Chain().ServiceAddress().Bytes()), + Address: common.Address(chain.Chain().ServiceAddress()), }, QualifiedIdentifier: "SomeContract.SomeEvent", }, diff --git a/fvm/evm/handler/blockHashList.go b/fvm/environment/evm_block_hash_list.go similarity index 98% rename from fvm/evm/handler/blockHashList.go rename to fvm/environment/evm_block_hash_list.go index 635e1b3fc82..cd85d2f4093 100644 --- a/fvm/evm/handler/blockHashList.go +++ b/fvm/environment/evm_block_hash_list.go @@ -1,4 +1,4 @@ -package handler +package environment import ( "encoding/binary" @@ -7,7 +7,6 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" - "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/model/flow" ) @@ -41,7 +40,7 @@ func IsBlockHashListMetaKey(id flow.RegisterID) bool { // smaller fixed size buckets to minimize the // number of bytes read and written during set/get operations. type BlockHashList struct { - backend types.BackendStorage + backend ValueStore rootAddress flow.Address // cached meta data @@ -55,7 +54,7 @@ type BlockHashList struct { // It tries to load the metadata from the backend // and if not exist it creates one func NewBlockHashList( - backend types.BackendStorage, + backend ValueStore, rootAddress flow.Address, capacity int, ) (*BlockHashList, error) { diff --git a/fvm/evm/handler/blockHashList_test.go b/fvm/environment/evm_block_hash_list_test.go similarity index 90% rename from fvm/evm/handler/blockHashList_test.go rename to fvm/environment/evm_block_hash_list_test.go index ebf1b21e1c8..8e731ada078 100644 --- a/fvm/evm/handler/blockHashList_test.go +++ b/fvm/environment/evm_block_hash_list_test.go @@ -1,4 +1,4 @@ -package handler_test +package environment_test import ( "testing" @@ -6,16 +6,16 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" - "github.com/onflow/flow-go/fvm/evm/handler" + "github.com/onflow/flow-go/fvm/environment" "github.com/onflow/flow-go/fvm/evm/testutils" "github.com/onflow/flow-go/model/flow" ) func TestBlockHashList(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(root flow.Address) { capacity := 256 - bhl, err := handler.NewBlockHashList(backend, root, capacity) + bhl, err := environment.NewBlockHashList(backend, root, capacity) require.NoError(t, err) require.True(t, bhl.IsEmpty()) @@ -75,7 +75,7 @@ func TestBlockHashList(t *testing.T) { require.Equal(t, gethCommon.Hash{byte(capacity + 2)}, h) // construct a new one and check - bhl, err = handler.NewBlockHashList(backend, root, capacity) + bhl, err = environment.NewBlockHashList(backend, root, capacity) require.NoError(t, err) require.False(t, bhl.IsEmpty()) diff --git a/fvm/environment/evm_block_store.go b/fvm/environment/evm_block_store.go new file mode 100644 index 00000000000..1aab448a129 --- /dev/null +++ b/fvm/environment/evm_block_store.go @@ -0,0 +1,297 @@ +package environment + +import ( + "fmt" + "time" + + gethCommon "github.com/ethereum/go-ethereum/common" + + "github.com/onflow/flow-go/fvm/evm/types" + "github.com/onflow/flow-go/model/flow" +) + +// BlockStore stores the chain of blocks +type EVMBlockStore interface { + // LatestBlock returns the latest appended block + LatestBlock() (*types.Block, error) + + // BlockHash returns the hash of the block at the given height + BlockHash(height uint64) (gethCommon.Hash, error) + + // BlockProposal returns the active block proposal + BlockProposal() (*types.BlockProposal, error) + + // StageBlockProposal updates the in-memory block proposal without writing to + // storage. Persistence happens at transaction end via FlushBlockProposal. + StageBlockProposal(*types.BlockProposal) + + // CommitBlockProposal commits the block proposal and update the chain of blocks + CommitBlockProposal(*types.BlockProposal) error +} + +const ( + BlockHashListCapacity = 256 + BlockStoreLatestBlockKey = "LatestBlock" + BlockStoreLatestBlockProposalKey = "LatestBlockProposal" +) + +// BlockStore manages EVM block storage and block proposal lifecycle during Flow block execution. +// +// Storage Keys: +// - LatestBlock: The last finalized EVM block. Updated only at CommitBlockProposal(). +// - LatestBlockProposal: The in-progress EVM block accumulating transactions. +// Its parent hash must equal hash(LatestBlock) and height must equal LatestBlock.Height + 1. +// +// Each Cadence transaction creates a new BlockStore instance with an empty cache. +// The cache avoids repeated storage reads within a single Cadence transaction. +// +// Flow Block K Execution: +// +// ├── Cadence tx 1 (succeed) +// │ ├── EVM Tx A +// │ │ ├── BlockProposal() +// │ │ │ ├── cache miss +// │ │ │ ├── read LatestBlockProposal from storage +// │ │ │ │ └── (if empty) read LatestBlock from storage (for parent hash, height) +// │ │ │ └── cache it +// │ │ └── StageBlockProposal() → update cache +// │ ├── EVM Tx B +// │ │ ├── BlockProposal() → cache hit +// │ │ └── StageBlockProposal() → update cache +// │ └── [tx end] +// │ └── FlushBlockProposal() → write LatestBlockProposal, cache = nil +// │ +// ├── Cadence tx 2 (failed) +// │ ├── EVM Tx C +// │ │ ├── BlockProposal() +// │ │ │ ├── cache miss +// │ │ │ └── read LatestBlockProposal from storage → cache it +// │ │ └── StageBlockProposal() → update cache +// │ ├── EVM Tx D +// │ │ ├── BlockProposal() → cache hit +// │ │ └── StageBlockProposal() → update cache +// │ └── [tx fail/revert] +// │ └── Reset() → cache = nil, storage unchanged +// │ +// └── System chunk tx (last) +// └── heartbeat() +// └── CommitBlockProposal() +// ├── write LatestBlock +// ├── write new LatestBlockProposal (for next flow block) +// └── cache = nil +type BlockStore struct { + chainID flow.ChainID + storage ValueStore + blockInfo BlockInfo + randGen RandomGenerator + rootAddress flow.Address + cached *types.BlockProposal +} + +var _ EVMBlockStore = &BlockStore{} + +// NewBlockStore constructs a new block store +func NewBlockStore( + chainID flow.ChainID, + storage ValueStore, + blockInfo BlockInfo, + randGen RandomGenerator, + rootAddress flow.Address, +) *BlockStore { + return &BlockStore{ + chainID: chainID, + storage: storage, + blockInfo: blockInfo, + randGen: randGen, + rootAddress: rootAddress, + } +} + +// BlockProposal returns the block proposal to be updated by the handler +func (bs *BlockStore) BlockProposal() (*types.BlockProposal, error) { + if bs.cached != nil { + return bs.cached, nil + } + // first fetch it from the storage + data, err := bs.storage.GetValue(bs.rootAddress[:], []byte(BlockStoreLatestBlockProposalKey)) + if err != nil { + return nil, err + } + if len(data) != 0 { + bp, err := types.NewBlockProposalFromBytes(data) + if err != nil { + return nil, err + } + bs.cached = bp + return bp, nil + } + bp, err := bs.constructBlockProposal() + if err != nil { + return nil, err + } + bs.cached = bp + return bp, nil +} + +func (bs *BlockStore) constructBlockProposal() (*types.BlockProposal, error) { + // if available construct a new one + cadenceHeight, err := bs.blockInfo.GetCurrentBlockHeight() + if err != nil { + return nil, err + } + + cadenceBlock, found, err := bs.blockInfo.GetBlockAtHeight(cadenceHeight) + if err != nil { + return nil, err + } + if !found { + return nil, fmt.Errorf("cadence block not found") + } + + lastExecutedBlock, err := bs.LatestBlock() + if err != nil { + return nil, err + } + + parentHash, err := lastExecutedBlock.Hash() + if err != nil { + return nil, err + } + + // cadence block timestamp is unix nanoseconds but evm blocks + // expect timestamps in unix seconds so we convert here + timestamp := uint64(cadenceBlock.Timestamp / int64(time.Second)) + + // read a random value for block proposal + prevrandao := gethCommon.Hash{} + err = bs.randGen.ReadRandom(prevrandao[:]) + if err != nil { + return nil, err + } + + blockProposal := types.NewBlockProposal( + parentHash, + lastExecutedBlock.Height+1, + timestamp, + lastExecutedBlock.TotalSupply, + prevrandao, + ) + + return blockProposal, nil +} + +// UpdateBlockProposal updates the block proposal +func (bs *BlockStore) updateBlockProposal(bp *types.BlockProposal) error { + blockProposalBytes, err := bp.ToBytes() + if err != nil { + return types.NewFatalError(err) + } + + return bs.storage.SetValue( + bs.rootAddress[:], + []byte(BlockStoreLatestBlockProposalKey), + blockProposalBytes, + ) +} + +// CommitBlockProposal commits the block proposal to the chain +func (bs *BlockStore) CommitBlockProposal(bp *types.BlockProposal) error { + bp.PopulateRoots() + + blockBytes, err := bp.Block.ToBytes() + if err != nil { + return types.NewFatalError(err) + } + + err = bs.storage.SetValue(bs.rootAddress[:], []byte(BlockStoreLatestBlockKey), blockBytes) + if err != nil { + return err + } + + hash, err := bp.Block.Hash() + if err != nil { + return err + } + + bhl, err := bs.getBlockHashList() + if err != nil { + return err + } + err = bhl.Push(bp.Block.Height, hash) + if err != nil { + return err + } + + // Construct and store the new block proposal eagerly to maintain + // state compatibility with the previous implementation. + newBP, err := bs.constructBlockProposal() + if err != nil { + return err + } + err = bs.updateBlockProposal(newBP) + if err != nil { + return err + } + bs.cached = nil + return nil +} + +// LatestBlock returns the latest executed block +func (bs *BlockStore) LatestBlock() (*types.Block, error) { + data, err := bs.storage.GetValue(bs.rootAddress[:], []byte(BlockStoreLatestBlockKey)) + if err != nil { + return nil, err + } + if len(data) == 0 { + return types.GenesisBlock(bs.chainID), nil + } + return types.NewBlockFromBytes(data) +} + +// BlockHash returns the block hash for the last x blocks +func (bs *BlockStore) BlockHash(height uint64) (gethCommon.Hash, error) { + bhl, err := bs.getBlockHashList() + if err != nil { + return gethCommon.Hash{}, err + } + _, hash, err := bhl.BlockHashByHeight(height) + return hash, err +} + +func (bs *BlockStore) getBlockHashList() (*BlockHashList, error) { + bhl, err := NewBlockHashList(bs.storage, bs.rootAddress, BlockHashListCapacity) + if err != nil { + return nil, err + } + + if bhl.IsEmpty() { + err = bhl.Push( + types.GenesisBlock(bs.chainID).Height, + types.GenesisBlockHash(bs.chainID), + ) + if err != nil { + return nil, err + } + } + + return bhl, nil +} + +func (bs *BlockStore) ResetBlockProposal() { + bs.cached = nil +} + +func (bs *BlockStore) StageBlockProposal(bp *types.BlockProposal) { + bs.cached = bp +} + +func (bs *BlockStore) FlushBlockProposal() error { + if bs.cached == nil { + return nil + } + err := bs.updateBlockProposal(bs.cached) + if err != nil { + return err + } + return nil +} diff --git a/fvm/evm/handler/blockstore_benchmark_test.go b/fvm/environment/evm_block_store_benchmark_test.go similarity index 84% rename from fvm/evm/handler/blockstore_benchmark_test.go rename to fvm/environment/evm_block_store_benchmark_test.go index 013b6326b0a..7f7e5170a21 100644 --- a/fvm/evm/handler/blockstore_benchmark_test.go +++ b/fvm/environment/evm_block_store_benchmark_test.go @@ -1,4 +1,4 @@ -package handler_test +package environment_test import ( "testing" @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/onflow/flow-go/fvm/evm/handler" + "github.com/onflow/flow-go/fvm/environment" "github.com/onflow/flow-go/fvm/evm/testutils" "github.com/onflow/flow-go/model/flow" ) @@ -14,17 +14,16 @@ import ( func BenchmarkProposalGrowth(b *testing.B) { benchmarkBlockProposalGrowth(b, 1000) } func benchmarkBlockProposalGrowth(b *testing.B, txCounts int) { - testutils.RunWithTestBackend(b, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(b, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(b, backend, func(rootAddr flow.Address) { - bs := handler.NewBlockStore(flow.Testnet, backend, rootAddr) + bs := environment.NewBlockStore(flow.Testnet, backend, backend, backend, rootAddr) for i := 0; i < txCounts; i++ { bp, err := bs.BlockProposal() require.NoError(b, err) res := testutils.RandomResultFixture(b) bp.AppendTransaction(res) - err = bs.UpdateBlockProposal(bp) - require.NoError(b, err) + bs.StageBlockProposal(bp) } // check the impact of updating block proposal after x number of transactions @@ -34,8 +33,7 @@ func benchmarkBlockProposalGrowth(b *testing.B, txCounts int) { require.NoError(b, err) res := testutils.RandomResultFixture(b) bp.AppendTransaction(res) - err = bs.UpdateBlockProposal(bp) - require.NoError(b, err) + bs.StageBlockProposal(bp) b.ReportMetric(float64(time.Since(startTime).Nanoseconds()), "proposal_update_time_ns") b.ReportMetric(float64(backend.TotalBytesRead()), "proposal_update_bytes_read") diff --git a/fvm/environment/evm_block_store_test.go b/fvm/environment/evm_block_store_test.go new file mode 100644 index 00000000000..b7a962db065 --- /dev/null +++ b/fvm/environment/evm_block_store_test.go @@ -0,0 +1,338 @@ +package environment_test + +import ( + "math/big" + "testing" + + gethCommon "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm/testutils" + "github.com/onflow/flow-go/fvm/evm/types" + "github.com/onflow/flow-go/model/flow" +) + +// TestBlockStoreLifecycle tests the block store lifecycle across two Flow blocks, +// following the execution flow documented in BlockStore comments. +// +// This test verifies: +// - Each Cadence tx creates a new BlockStore instance with empty cache +// - Cache hits/misses work correctly within a Cadence tx +// - FlushBlockProposal persists the proposal for the next Cadence tx +// - Reset discards changes on failed Cadence tx +// - CommitBlockProposal finalizes the block and clears LatestBlockProposal +// - Lazy construction of new proposal in the next Flow block +func TestBlockStoreLifecycle(t *testing.T) { + chainID := flow.Testnet + testutils.RunWithTestBackend(t, chainID, func(backend *testutils.TestBackend) { + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(root flow.Address) { + + // Gas constants for each EVM tx - using distinct digit positions for easy verification + // Each tx uses a different decimal place, so accumulated values are easy to read + const ( + evmTxAGas = uint64(1) // ones place + evmTxBGas = uint64(20) // tens place + evmTxCGas = uint64(300) // hundreds place + evmTxDGas = uint64(4000) // thousands place + evmTxEGas = uint64(50000) // ten-thousands place + evmTxFGas = uint64(600000) // hundred-thousands place + ) + + // TotalSupply changes for each EVM tx - also using distinct digit positions + // TotalSupply represents native token deposited in EVM (can increase via deposits) + var ( + evmTxASupply = big.NewInt(100) // ones place (x100) + evmTxBSupply = big.NewInt(2000) // tens place (x100) + evmTxESupply = big.NewInt(5000000) // ten-thousands place (x100) + evmTxFSupply = big.NewInt(60000000) // hundred-thousands place (x100) + ) + + // ============================================ + // Flow Block K + // ============================================ + + // --- Cadence tx 1 (succeed) --- + // Each Cadence tx creates a new BlockStore instance + bs1 := environment.NewBlockStore(chainID, backend, backend, backend, root) + + // EVM Tx A: BlockProposal() - cache miss, loads from storage + // Since this is the first ever call, LatestBlockProposal is empty, + // so it reads LatestBlock (genesis) to construct proposal + bpA, err := bs1.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(1), bpA.Height) + expectedParentHash, err := types.GenesisBlock(chainID).Hash() + require.NoError(t, err) + require.Equal(t, expectedParentHash, bpA.ParentBlockHash) + require.Equal(t, uint64(0), bpA.TotalGasUsed) // starts at 0 + + // Verify TotalSupply is inherited from genesis block (0) + require.Equal(t, big.NewInt(0), bpA.TotalSupply) + + // Verify PrevRandao is set (non-zero) - read from RandomGenerator during construction + require.NotEqual(t, gethCommon.Hash{}, bpA.PrevRandao) + prevRandaoBlockK := bpA.PrevRandao // save for later comparison + + // EVM Tx A: StageBlockProposal() - update cache (accumulate gas and supply) + bpA.TotalGasUsed += evmTxAGas + bpA.TotalSupply = new(big.Int).Add(bpA.TotalSupply, evmTxASupply) + bs1.StageBlockProposal(bpA) + + // EVM Tx B: BlockProposal() - cache hit (same BlockStore instance) + bpB, err := bs1.BlockProposal() + require.NoError(t, err) + require.Equal(t, bpA, bpB) // same pointer, cache hit + require.Equal(t, uint64(1), bpB.TotalGasUsed) // sees Tx A's gas + require.Equal(t, big.NewInt(100), bpB.TotalSupply) // sees Tx A's supply + require.Equal(t, prevRandaoBlockK, bpB.PrevRandao) // PrevRandao unchanged within block + + // EVM Tx B: StageBlockProposal() - update cache (accumulate gas and supply) + bpB.TotalGasUsed += evmTxBGas + bpB.TotalSupply = new(big.Int).Add(bpB.TotalSupply, evmTxBSupply) + bs1.StageBlockProposal(bpB) + + // [tx end]: FlushBlockProposal() - write LatestBlockProposal to storage + // At this point, TotalGasUsed = 1 + 20 = 21, TotalSupply = 100 + 2000 = 2100 + require.Equal(t, uint64(21), bpB.TotalGasUsed) + require.Equal(t, big.NewInt(2100), bpB.TotalSupply) + err = bs1.FlushBlockProposal() + require.NoError(t, err) + + // --- Cadence tx 2 (failed) --- + // New BlockStore instance (simulating new Cadence tx) + bs2 := environment.NewBlockStore(chainID, backend, backend, backend, root) + + // EVM Tx C: BlockProposal() - cache miss, loads from storage + // Should load the flushed proposal from tx 1 with accumulated gas = 21, supply = 2100 + bpC, err := bs2.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(21), bpC.TotalGasUsed) // persisted from tx 1 + require.Equal(t, big.NewInt(2100), bpC.TotalSupply) // persisted from tx 1 + require.Equal(t, prevRandaoBlockK, bpC.PrevRandao) // PrevRandao unchanged within block + + // EVM Tx C: StageBlockProposal() - update cache (accumulate gas) + bpC.TotalGasUsed += evmTxCGas + bs2.StageBlockProposal(bpC) + + // EVM Tx D: BlockProposal() - cache hit + bpD, err := bs2.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(321), bpD.TotalGasUsed) // sees A+B+C = 1+20+300 + + // EVM Tx D: StageBlockProposal() - update cache (accumulate gas) + bpD.TotalGasUsed += evmTxDGas + bs2.StageBlockProposal(bpD) + + // Verify all 4 txs' gas is accumulated before revert = 1+20+300+4000 = 4321 + require.Equal(t, uint64(4321), bpD.TotalGasUsed) + + // [tx fail/revert]: Reset() - cache = nil, storage unchanged + bs2.ResetBlockProposal() + + // Verify storage is unchanged by creating a new BlockStore and reading + // Should only see gas from Cadence tx 1 (A+B = 21), not from failed tx 2 (C+D) + bs2Check := environment.NewBlockStore(chainID, backend, backend, backend, root) + bpCheck, err := bs2Check.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(21), bpCheck.TotalGasUsed) // unchanged from tx 1 + require.Equal(t, big.NewInt(2100), bpCheck.TotalSupply) // unchanged from tx 1 + + // --- System chunk tx (last) --- + // New BlockStore instance for system tx + bsSystem := environment.NewBlockStore(chainID, backend, backend, backend, root) + + // heartbeat() -> CommitBlockProposal() + bpCommit, err := bsSystem.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(21), bpCommit.TotalGasUsed) // A+B = 21 + require.Equal(t, big.NewInt(2100), bpCommit.TotalSupply) // A+B supply = 2100 + + // CommitBlockProposal: write LatestBlock, remove LatestBlockProposal + err = bsSystem.CommitBlockProposal(bpCommit) + require.NoError(t, err) + + // Verify LatestBlock is now the committed block with accumulated values + latestBlock, err := bsSystem.LatestBlock() + require.NoError(t, err) + require.Equal(t, uint64(1), latestBlock.Height) + require.Equal(t, uint64(21), latestBlock.TotalGasUsed) + require.Equal(t, big.NewInt(2100), latestBlock.TotalSupply) + require.Equal(t, prevRandaoBlockK, latestBlock.PrevRandao) // PrevRandao preserved in block + + // ============================================ + // Flow Block K+1 + // ============================================ + + // --- Cadence tx 1 --- + // New BlockStore instance (new Flow block, new Cadence tx) + bsK1 := environment.NewBlockStore(chainID, backend, backend, backend, root) + + // EVM Tx E: BlockProposal() - cache miss + // After CommitBlockProposal, LatestBlockProposal was cleared (or new one written) + // This tests lazy construction: reads LatestBlock to construct new proposal + bpE, err := bsK1.BlockProposal() + require.NoError(t, err) + + // Verify the new proposal is a child of the committed block + require.Equal(t, uint64(2), bpE.Height) // height incremented + committedBlockHash, err := latestBlock.Hash() + require.NoError(t, err) + require.Equal(t, committedBlockHash, bpE.ParentBlockHash) // parent is committed block + + // Verify the proposal starts fresh (no accumulated gas from previous block) + require.Equal(t, uint64(0), bpE.TotalGasUsed) + + // Verify TotalSupply is inherited from the committed block (2100) + require.Equal(t, big.NewInt(2100), bpE.TotalSupply) + + // Verify PrevRandao is set and DIFFERENT from block K (new random value for new block) + require.NotEqual(t, gethCommon.Hash{}, bpE.PrevRandao) + require.NotEqual(t, prevRandaoBlockK, bpE.PrevRandao) // different random for new block + prevRandaoBlockK1 := bpE.PrevRandao + + // EVM Tx E: StageBlockProposal() - update cache (accumulate gas and supply) + bpE.TotalGasUsed += evmTxEGas + bpE.TotalSupply = new(big.Int).Add(bpE.TotalSupply, evmTxESupply) + bsK1.StageBlockProposal(bpE) + + // EVM Tx F: BlockProposal() - cache hit + bpF, err := bsK1.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(50000), bpF.TotalGasUsed) // sees Tx E's gas + require.Equal(t, big.NewInt(5002100), bpF.TotalSupply) // 2100 + 5000000 + require.Equal(t, prevRandaoBlockK1, bpF.PrevRandao) // PrevRandao unchanged within block + + // EVM Tx F: StageBlockProposal() - update cache (accumulate gas and supply) + bpF.TotalGasUsed += evmTxFGas + bpF.TotalSupply = new(big.Int).Add(bpF.TotalSupply, evmTxFSupply) + bsK1.StageBlockProposal(bpF) + + // [tx end]: FlushBlockProposal() + // Gas: E+F = 50000+600000 = 650000 + // Supply: 2100 + 5000000 + 60000000 = 65002100 + require.Equal(t, uint64(650000), bpF.TotalGasUsed) + require.Equal(t, big.NewInt(65002100), bpF.TotalSupply) + err = bsK1.FlushBlockProposal() + require.NoError(t, err) + + // --- System chunk tx for block K+1 --- + bsSystemK1 := environment.NewBlockStore(chainID, backend, backend, backend, root) + bpCommitK1, err := bsSystemK1.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(650000), bpCommitK1.TotalGasUsed) // E+F = 650000 + require.Equal(t, big.NewInt(65002100), bpCommitK1.TotalSupply) // accumulated supply + + err = bsSystemK1.CommitBlockProposal(bpCommitK1) + require.NoError(t, err) + + // Verify LatestBlock is now block 2 with accumulated values + latestBlockK1, err := bsSystemK1.LatestBlock() + require.NoError(t, err) + require.Equal(t, uint64(2), latestBlockK1.Height) + require.Equal(t, uint64(650000), latestBlockK1.TotalGasUsed) + require.Equal(t, big.NewInt(65002100), latestBlockK1.TotalSupply) + require.Equal(t, prevRandaoBlockK1, latestBlockK1.PrevRandao) // PrevRandao preserved + + // Verify block hashes are correct + hash0, err := bsSystemK1.BlockHash(0) + require.NoError(t, err) + require.Equal(t, types.GenesisBlockHash(chainID), hash0) + + hash1, err := bsSystemK1.BlockHash(1) + require.NoError(t, err) + require.Equal(t, committedBlockHash, hash1) + + hash2, err := bsSystemK1.BlockHash(2) + require.NoError(t, err) + expectedHash2, err := latestBlockK1.Hash() + require.NoError(t, err) + require.Equal(t, expectedHash2, hash2) + }) + }) +} + +func TestBlockStore(t *testing.T) { + + var chainID = flow.Testnet + testutils.RunWithTestBackend(t, chainID, func(backend *testutils.TestBackend) { + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(root flow.Address) { + bs := environment.NewBlockStore(chainID, backend, backend, backend, root) + + // check the Genesis block + b, err := bs.LatestBlock() + require.NoError(t, err) + require.Equal(t, types.GenesisBlock(chainID), b) + h, err := bs.BlockHash(0) + require.NoError(t, err) + require.Equal(t, types.GenesisBlockHash(chainID), h) + + // test block proposal construction from the Genesis block + bp, err := bs.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(1), bp.Height) + expectedParentHash, err := types.GenesisBlock(chainID).Hash() + require.NoError(t, err) + require.Equal(t, expectedParentHash, bp.ParentBlockHash) + + // if no commit and again block proposal call should return the same + retbp, err := bs.BlockProposal() + require.NoError(t, err) + require.Equal(t, bp, retbp) + + // update the block proposal + bp.TotalGasUsed += 100 + bs.StageBlockProposal(bp) + err = bs.FlushBlockProposal() + require.NoError(t, err) + + bs = environment.NewBlockStore(chainID, backend, backend, backend, root) + retbp, err = bs.BlockProposal() + require.NoError(t, err) + require.Equal(t, bp, retbp) + + // update the block proposal again + supply := big.NewInt(100) + bp.TotalSupply = supply + bs.StageBlockProposal(bp) + err = bs.FlushBlockProposal() + require.NoError(t, err) + // this should still return the genesis block + retb, err := bs.LatestBlock() + require.NoError(t, err) + require.Equal(t, types.GenesisBlock(chainID), retb) + + // commit the changes + err = bs.CommitBlockProposal(bp) + require.NoError(t, err) + retb, err = bs.LatestBlock() + require.NoError(t, err) + require.Equal(t, supply, retb.TotalSupply) + require.Equal(t, uint64(1), retb.Height) + + retbp, err = bs.BlockProposal() + require.NoError(t, err) + require.Equal(t, uint64(2), retbp.Height) + + // check block hashes + // genesis + h, err = bs.BlockHash(0) + require.NoError(t, err) + require.Equal(t, types.GenesisBlockHash(chainID), h) + + // block 1 + h, err = bs.BlockHash(1) + require.NoError(t, err) + expected, err := bp.Hash() + require.NoError(t, err) + require.Equal(t, expected, h) + + // block 2 + h, err = bs.BlockHash(2) + require.NoError(t, err) + require.Equal(t, gethCommon.Hash{}, h) + }) + + }) + +} diff --git a/fvm/environment/facade_env.go b/fvm/environment/facade_env.go index 8103ddb1f04..e8913dfce58 100644 --- a/fvm/environment/facade_env.go +++ b/fvm/environment/facade_env.go @@ -8,6 +8,8 @@ import ( "github.com/onflow/cadence/interpreter" "github.com/onflow/cadence/sema" + "github.com/onflow/flow-go/fvm/evm" + "github.com/onflow/flow-go/fvm/storage" "github.com/onflow/flow-go/fvm/storage/snapshot" "github.com/onflow/flow-go/fvm/storage/state" @@ -19,7 +21,7 @@ var _ Environment = &facadeEnvironment{} // facadeEnvironment exposes various fvm business logic as a single interface. type facadeEnvironment struct { - *Runtime + CadenceRuntimeProvider tracing.TracerSpan Meter @@ -51,9 +53,16 @@ type facadeEnvironment struct { *ContractReader ContractUpdater *Programs + *BlockStore accounts Accounts txnState storage.TransactionPreparer + + evmTestOperationsAllowed bool +} + +func (env *facadeEnvironment) EVMTestOperationsAllowed() bool { + return env.evmTestOperationsAllowed } func newFacadeEnvironment( @@ -61,14 +70,13 @@ func newFacadeEnvironment( params EnvironmentParams, txnState storage.TransactionPreparer, meter Meter, + runtime CadenceRuntimeProvider, ) *facadeEnvironment { accounts := NewAccounts(txnState) logger := NewProgramLogger(tracer, params.ProgramLoggerParams) - runtime := NewRuntime(params.RuntimeParams) chain := params.Chain systemContracts := NewSystemContracts( chain, - params.CadenceVMEnabled, tracer, logger, runtime) @@ -76,7 +84,7 @@ func newFacadeEnvironment( sc := systemcontracts.SystemContractsForChain(chain.ChainID()) env := &facadeEnvironment{ - Runtime: runtime, + CadenceRuntimeProvider: runtime, TracerSpan: tracer, Meter: meter, @@ -142,6 +150,7 @@ func newFacadeEnvironment( common.Address(sc.Crypto.Address), ), ContractUpdater: NoContractUpdater{}, + Programs: NewPrograms( tracer, meter, @@ -151,9 +160,11 @@ func newFacadeEnvironment( accounts: accounts, txnState: txnState, + + evmTestOperationsAllowed: params.TransactionInfoParams.EVMTestOperationsAllowed, } - env.Runtime.SetEnvironment(env) + env.CadenceRuntimeProvider.SetEnvironment(env) return env } @@ -179,17 +190,31 @@ func NewScriptEnv( params EnvironmentParams, txnState storage.TransactionPreparer, ) *facadeEnvironment { + runtimeType := CadenceScriptRuntime + if params.CadenceVMEnabled { + runtimeType = CadenceScriptVMRuntime + } + cadenceRuntime := NewRuntime(params.RuntimeParams, runtimeType) + env := newFacadeEnvironment( tracer, params, txnState, - NewCancellableMeter(ctx, txnState)) + NewCancellableMeter(ctx, txnState), + cadenceRuntime) env.RandomGenerator = NewRandomGenerator( tracer, params.EntropyProvider, params.ScriptInfoParams.ID[:], ) env.addParseRestrictedChecks() + env.BlockStore = NewBlockStore( + params.Chain.ChainID(), + env.ValueStore, + env.BlockInfo, + env.RandomGenerator, + evm.StorageAccountAddress(params.Chain.ChainID()), + ) return env } @@ -198,11 +223,17 @@ func NewTransactionEnvironment( params EnvironmentParams, txnState storage.TransactionPreparer, ) *facadeEnvironment { + runtimeType := CadenceTransactionRuntime + if params.CadenceVMEnabled { + runtimeType = CadenceTransactionVMRuntime + } + cadenceRuntime := NewRuntime(params.RuntimeParams, runtimeType) env := newFacadeEnvironment( tracer, params, txnState, NewMeter(txnState), + cadenceRuntime, ) env.TransactionInfo = NewTransactionInfo( @@ -236,7 +267,7 @@ func NewTransactionEnvironment( params.ContractUpdaterParams, env.ProgramLogger, env.SystemContracts, - env.Runtime) + cadenceRuntime) env.AccountKeyUpdater = NewAccountKeyUpdater( tracer, @@ -258,6 +289,14 @@ func NewTransactionEnvironment( params.TransactionInfoParams.RandomSourceHistoryCallAllowed, ) + env.BlockStore = NewBlockStore( + params.Chain.ChainID(), + env.ValueStore, + env.BlockInfo, + env.RandomGenerator, + evm.StorageAccountAddress(params.Chain.ChainID()), + ) + env.addParseRestrictedChecks() return env @@ -319,13 +358,22 @@ func (env *facadeEnvironment) FlushPendingUpdates() ( ContractUpdates, error, ) { - return env.ContractUpdater.Commit() + updates, err := env.ContractUpdater.Commit() + if err != nil { + return ContractUpdates{}, err + } + err = env.BlockStore.FlushBlockProposal() + if err != nil { + return ContractUpdates{}, err + } + return updates, nil } func (env *facadeEnvironment) Reset() { env.ContractUpdater.Reset() env.EventEmitter.Reset() env.Programs.Reset() + env.BlockStore.ResetBlockProposal() } // Miscellaneous Cadence runtime.Interface API diff --git a/fvm/environment/generate-wrappers/file_content.go b/fvm/environment/generate-wrappers/file_content.go index 58770a499e3..a795410f4e5 100644 --- a/fvm/environment/generate-wrappers/file_content.go +++ b/fvm/environment/generate-wrappers/file_content.go @@ -13,7 +13,7 @@ var ( type Chunk struct { indentLevel int format string - args []interface{} + args []any } func (chunk *Chunk) WriteTo(writer io.Writer) (int64, error) { @@ -68,13 +68,13 @@ func (content *FileContent) PopIndent() { } } -func (content *FileContent) Line(format string, args ...interface{}) { +func (content *FileContent) Line(format string, args ...any) { content.chunks = append( content.chunks, &Chunk{content.indentLevel, format, args}) } -func (content *FileContent) Section(format string, args ...interface{}) { +func (content *FileContent) Section(format string, args ...any) { content.chunks = append(content.chunks, &Chunk{0, format, args}) } diff --git a/fvm/environment/generate-wrappers/main.go b/fvm/environment/generate-wrappers/main.go index 53d8cd1ea8b..9ac2e51c779 100644 --- a/fvm/environment/generate-wrappers/main.go +++ b/fvm/environment/generate-wrappers/main.go @@ -51,7 +51,7 @@ func generateWrapper(numArgs int, numRets int, content *FileContent) { argTypes := []string{} argNames := []string{} - for i := 0; i < numArgs; i++ { + for i := range numArgs { argTypes = append(argTypes, fmt.Sprintf("Arg%dT", i)) argNames = append(argNames, fmt.Sprintf("arg%d", i)) } @@ -63,7 +63,7 @@ func generateWrapper(numArgs int, numRets int, content *FileContent) { retTypes := []string{} retNames := []string{} - for i := 0; i < numRets; i++ { + for i := range numRets { retTypes = append(retTypes, fmt.Sprintf("Ret%dT", i)) retNames = append(retNames, fmt.Sprintf("value%d", i)) } diff --git a/fvm/environment/meter_computation_kinds_test.go b/fvm/environment/meter_computation_kinds_test.go new file mode 100644 index 00000000000..e9a16c0c4e9 --- /dev/null +++ b/fvm/environment/meter_computation_kinds_test.go @@ -0,0 +1,165 @@ +package environment + +import ( + "encoding/json" + "fmt" + "sort" + "testing" + + "github.com/onflow/cadence/common" + "github.com/stretchr/testify/assert" +) + +// TestComputationKindValues hardcodes every ComputationKind constant and its expected numeric value. +// If an existing constant's value changes, the value assertion fails. +// If a constant is removed, the test fails to compile. +// If a new constant is added to MainnetExecutionEffortWeights without updating this test, the +// bidirectional check against that map fails. +func TestComputationKindValues(t *testing.T) { + + // Single hardcoded map of all known ComputationKind constants (both FVM and Cadence) to their + // expected numeric values. Every constant is referenced by its Go symbol so that removing a + // constant causes a compilation error. + knownKinds := map[common.ComputationKind]common.ComputationKind{ + // Cadence ComputationKind constants (range [1000, 2000)) + common.ComputationKindUnknown: 0, + common.ComputationKindStatement: 1001, + common.ComputationKindLoop: 1002, + common.ComputationKindFunctionInvocation: 1003, + common.ComputationKindCreateCompositeValue: 1010, + common.ComputationKindTransferCompositeValue: 1011, + common.ComputationKindDestroyCompositeValue: 1012, + common.ComputationKindCreateArrayValue: 1025, + common.ComputationKindTransferArrayValue: 1026, + common.ComputationKindDestroyArrayValue: 1027, + common.ComputationKindCreateDictionaryValue: 1040, + common.ComputationKindTransferDictionaryValue: 1041, + common.ComputationKindDestroyDictionaryValue: 1042, + common.ComputationKindStringToLower: 1055, + common.ComputationKindStringDecodeHex: 1056, + common.ComputationKindGraphemesIteration: 1057, + common.ComputationKindStringComparison: 1058, + common.ComputationKindEncodeValue: 1080, + common.ComputationKindWordSliceOperation: 1081, + common.ComputationKindUintParse: 1082, + common.ComputationKindIntParse: 1083, + common.ComputationKindBigIntParse: 1084, + common.ComputationKindUfixParse: 1085, + common.ComputationKindFixParse: 1086, + common.ComputationKindSTDLIBPanic: 1100, + common.ComputationKindSTDLIBAssert: 1101, + common.ComputationKindSTDLIBRevertibleRandom: 1102, + common.ComputationKindSTDLIBRLPDecodeString: 1108, + common.ComputationKindSTDLIBRLPDecodeList: 1109, + common.ComputationKindAtreeArraySingleSlabConstruction: 1200, + common.ComputationKindAtreeArrayBatchConstruction: 1201, + common.ComputationKindAtreeArrayGet: 1202, + common.ComputationKindAtreeArraySet: 1203, + common.ComputationKindAtreeArrayAppend: 1204, + common.ComputationKindAtreeArrayInsert: 1205, + common.ComputationKindAtreeArrayRemove: 1206, + common.ComputationKindAtreeArrayReadIteration: 1207, + common.ComputationKindAtreeArrayPopIteration: 1208, + common.ComputationKindAtreeMapConstruction: 1220, + common.ComputationKindAtreeMapSingleSlabConstruction: 1221, + common.ComputationKindAtreeMapBatchConstruction: 1222, + common.ComputationKindAtreeMapHas: 1223, + common.ComputationKindAtreeMapGet: 1224, + common.ComputationKindAtreeMapSet: 1225, + common.ComputationKindAtreeMapRemove: 1226, + common.ComputationKindAtreeMapReadIteration: 1227, + common.ComputationKindAtreeMapPopIteration: 1228, + + // FVM ComputationKind constants (range [2000, 3000)) + ComputationKindHash: 2001, + ComputationKindVerifySignature: 2002, + ComputationKindAddAccountKey: 2003, + ComputationKindAddEncodedAccountKey: 2004, + ComputationKindAllocateSlabIndex: 2005, + ComputationKindCreateAccount: 2006, + ComputationKindEmitEvent: 2007, + ComputationKindGenerateUUID: 2008, + ComputationKindGetAccountAvailableBalance: 2009, + ComputationKindGetAccountBalance: 2010, + ComputationKindGetAccountContractCode: 2011, + ComputationKindGetAccountContractNames: 2012, + ComputationKindGetAccountKey: 2013, + ComputationKindGetBlockAtHeight: 2014, + ComputationKindGetCode: 2015, + ComputationKindGetCurrentBlockHeight: 2016, + ComputationKindGetStorageCapacity: 2018, + ComputationKindGetStorageUsed: 2019, + ComputationKindGetValue: 2020, + ComputationKindRemoveAccountContractCode: 2021, + ComputationKindResolveLocation: 2022, + ComputationKindRevokeAccountKey: 2023, + ComputationKindSetValue: 2026, + ComputationKindUpdateAccountContractCode: 2027, + ComputationKindValidatePublicKey: 2028, + ComputationKindValueExists: 2029, + ComputationKindAccountKeysCount: 2030, + ComputationKindBLSVerifyPOP: 2031, + ComputationKindBLSAggregateSignatures: 2032, + ComputationKindBLSAggregatePublicKeys: 2033, + ComputationKindGetOrLoadProgram: 2034, + ComputationKindGenerateAccountLocalID: 2035, + ComputationKindGetRandomSourceHistory: 2036, + ComputationKindEVMGasUsage: 2037, + ComputationKindRLPEncoding: 2038, + ComputationKindRLPDecoding: 2039, + ComputationKindEncodeEvent: 2040, + ComputationKindEVMEncodeABI: 2042, + ComputationKindEVMDecodeABI: 2043, + } + + // Verify each constant's numeric value matches the hardcoded expectation. + for actual, expected := range knownKinds { + assert.Equal(t, expected, actual, "ComputationKind %d has unexpected value", actual) + } + + // Verify that every key in MainnetExecutionEffortWeights is present in knownKinds. + // This catches new constants added to the weights map without updating this test. + for kind := range MainnetExecutionEffortWeights { + _, ok := knownKinds[kind] + assert.True(t, ok, "MainnetExecutionEffortWeights contains ComputationKind %d which is not in knownKinds — add it to this test", kind) + } +} + +// TestPrintMainnetWeightsCadenceJSON is a test that prints MainnetExecutionEffortWeights +// as a Cadence JSON dictionary. +func TestPrintMainnetWeightsCadenceJSON(t *testing.T) { + t.Skip("This test is only useful for preparing the cadence JSON for the transactions for updating the weights") + + type cadenceValue struct { + Type string `json:"type"` + Value string `json:"value"` + } + type cadenceKV struct { + Key cadenceValue `json:"key"` + Value cadenceValue `json:"value"` + } + type cadenceDict struct { + Type string `json:"type"` + Value []cadenceKV `json:"value"` + } + + // Sort by computation kind ID for stable output. + keys := make([]int, 0, len(MainnetExecutionEffortWeights)) + for kind := range MainnetExecutionEffortWeights { + keys = append(keys, int(kind)) + } + sort.Ints(keys) + + entries := make([]cadenceKV, 0, len(MainnetExecutionEffortWeights)) + for _, k := range keys { + weight := MainnetExecutionEffortWeights[common.ComputationKind(k)] + entries = append(entries, cadenceKV{ + Key: cadenceValue{Type: "UInt64", Value: fmt.Sprintf("%d", k)}, + Value: cadenceValue{Type: "UInt64", Value: fmt.Sprintf("%d", weight)}, + }) + } + + out, err := json.MarshalIndent([]cadenceDict{{Type: "Dictionary", Value: entries}}, "", " ") + assert.NoError(t, err) + fmt.Println(string(out)) +} diff --git a/fvm/environment/mock/account_creator.go b/fvm/environment/mock/account_creator.go index 7c23cf079df..c06169170bb 100644 --- a/fvm/environment/mock/account_creator.go +++ b/fvm/environment/mock/account_creator.go @@ -1,21 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/interpreter" mock "github.com/stretchr/testify/mock" ) +// NewAccountCreator creates a new instance of AccountCreator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountCreator(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountCreator { + mock := &AccountCreator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccountCreator is an autogenerated mock type for the AccountCreator type type AccountCreator struct { mock.Mock } -// CreateAccount provides a mock function with given fields: runtimePayer -func (_m *AccountCreator) CreateAccount(runtimePayer common.Address) (common.Address, error) { - ret := _m.Called(runtimePayer) +type AccountCreator_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountCreator) EXPECT() *AccountCreator_Expecter { + return &AccountCreator_Expecter{mock: &_m.Mock} +} + +// CreateAccount provides a mock function for the type AccountCreator +func (_mock *AccountCreator) CreateAccount(runtimePayer common.Address, invocationContext interpreter.InvocationContext) (common.Address, error) { + ret := _mock.Called(runtimePayer, invocationContext) if len(ret) == 0 { panic("no return value specified for CreateAccount") @@ -23,36 +47,60 @@ func (_m *AccountCreator) CreateAccount(runtimePayer common.Address) (common.Add var r0 common.Address var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (common.Address, error)); ok { - return rf(runtimePayer) + if returnFunc, ok := ret.Get(0).(func(common.Address, interpreter.InvocationContext) (common.Address, error)); ok { + return returnFunc(runtimePayer, invocationContext) } - if rf, ok := ret.Get(0).(func(common.Address) common.Address); ok { - r0 = rf(runtimePayer) + if returnFunc, ok := ret.Get(0).(func(common.Address, interpreter.InvocationContext) common.Address); ok { + r0 = returnFunc(runtimePayer, invocationContext) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Address) } } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(runtimePayer) + if returnFunc, ok := ret.Get(1).(func(common.Address, interpreter.InvocationContext) error); ok { + r1 = returnFunc(runtimePayer, invocationContext) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAccountCreator creates a new instance of AccountCreator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccountCreator(t interface { - mock.TestingT - Cleanup(func()) -}) *AccountCreator { - mock := &AccountCreator{} - mock.Mock.Test(t) +// AccountCreator_CreateAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateAccount' +type AccountCreator_CreateAccount_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// CreateAccount is a helper method to define mock.On call +// - runtimePayer common.Address +// - invocationContext interpreter.InvocationContext +func (_e *AccountCreator_Expecter) CreateAccount(runtimePayer interface{}, invocationContext interface{}) *AccountCreator_CreateAccount_Call { + return &AccountCreator_CreateAccount_Call{Call: _e.mock.On("CreateAccount", runtimePayer, invocationContext)} +} - return mock +func (_c *AccountCreator_CreateAccount_Call) Run(run func(runtimePayer common.Address, invocationContext interpreter.InvocationContext)) *AccountCreator_CreateAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + var arg1 interpreter.InvocationContext + if args[1] != nil { + arg1 = args[1].(interpreter.InvocationContext) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountCreator_CreateAccount_Call) Return(address common.Address, err error) *AccountCreator_CreateAccount_Call { + _c.Call.Return(address, err) + return _c +} + +func (_c *AccountCreator_CreateAccount_Call) RunAndReturn(run func(runtimePayer common.Address, invocationContext interpreter.InvocationContext) (common.Address, error)) *AccountCreator_CreateAccount_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/account_info.go b/fvm/environment/mock/account_info.go index adeb91e4b60..f9383522df8 100644 --- a/fvm/environment/mock/account_info.go +++ b/fvm/environment/mock/account_info.go @@ -1,23 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/cadence/common" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewAccountInfo creates a new instance of AccountInfo. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountInfo(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountInfo { + mock := &AccountInfo{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccountInfo is an autogenerated mock type for the AccountInfo type type AccountInfo struct { mock.Mock } -// GetAccount provides a mock function with given fields: address -func (_m *AccountInfo) GetAccount(address flow.Address) (*flow.Account, error) { - ret := _m.Called(address) +type AccountInfo_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountInfo) EXPECT() *AccountInfo_Expecter { + return &AccountInfo_Expecter{mock: &_m.Mock} +} + +// GetAccount provides a mock function for the type AccountInfo +func (_mock *AccountInfo) GetAccount(address flow.Address) (*flow.Account, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -25,29 +47,61 @@ func (_m *AccountInfo) GetAccount(address flow.Address) (*flow.Account, error) { var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (*flow.Account, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) (*flow.Account, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) *flow.Account); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) *flow.Account); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAvailableBalance provides a mock function with given fields: runtimeAddress -func (_m *AccountInfo) GetAccountAvailableBalance(runtimeAddress common.Address) (uint64, error) { - ret := _m.Called(runtimeAddress) +// AccountInfo_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type AccountInfo_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - address flow.Address +func (_e *AccountInfo_Expecter) GetAccount(address interface{}) *AccountInfo_GetAccount_Call { + return &AccountInfo_GetAccount_Call{Call: _e.mock.On("GetAccount", address)} +} + +func (_c *AccountInfo_GetAccount_Call) Run(run func(address flow.Address)) *AccountInfo_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountInfo_GetAccount_Call) Return(account *flow.Account, err error) *AccountInfo_GetAccount_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *AccountInfo_GetAccount_Call) RunAndReturn(run func(address flow.Address) (*flow.Account, error)) *AccountInfo_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAvailableBalance provides a mock function for the type AccountInfo +func (_mock *AccountInfo) GetAccountAvailableBalance(runtimeAddress common.Address) (uint64, error) { + ret := _mock.Called(runtimeAddress) if len(ret) == 0 { panic("no return value specified for GetAccountAvailableBalance") @@ -55,27 +109,59 @@ func (_m *AccountInfo) GetAccountAvailableBalance(runtimeAddress common.Address) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { + return returnFunc(runtimeAddress) } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) uint64); ok { + r0 = returnFunc(runtimeAddress) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(1).(func(common.Address) error); ok { + r1 = returnFunc(runtimeAddress) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalance provides a mock function with given fields: runtimeAddress -func (_m *AccountInfo) GetAccountBalance(runtimeAddress common.Address) (uint64, error) { - ret := _m.Called(runtimeAddress) +// AccountInfo_GetAccountAvailableBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAvailableBalance' +type AccountInfo_GetAccountAvailableBalance_Call struct { + *mock.Call +} + +// GetAccountAvailableBalance is a helper method to define mock.On call +// - runtimeAddress common.Address +func (_e *AccountInfo_Expecter) GetAccountAvailableBalance(runtimeAddress interface{}) *AccountInfo_GetAccountAvailableBalance_Call { + return &AccountInfo_GetAccountAvailableBalance_Call{Call: _e.mock.On("GetAccountAvailableBalance", runtimeAddress)} +} + +func (_c *AccountInfo_GetAccountAvailableBalance_Call) Run(run func(runtimeAddress common.Address)) *AccountInfo_GetAccountAvailableBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountInfo_GetAccountAvailableBalance_Call) Return(v uint64, err error) *AccountInfo_GetAccountAvailableBalance_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountInfo_GetAccountAvailableBalance_Call) RunAndReturn(run func(runtimeAddress common.Address) (uint64, error)) *AccountInfo_GetAccountAvailableBalance_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalance provides a mock function for the type AccountInfo +func (_mock *AccountInfo) GetAccountBalance(runtimeAddress common.Address) (uint64, error) { + ret := _mock.Called(runtimeAddress) if len(ret) == 0 { panic("no return value specified for GetAccountBalance") @@ -83,27 +169,59 @@ func (_m *AccountInfo) GetAccountBalance(runtimeAddress common.Address) (uint64, var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { + return returnFunc(runtimeAddress) } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) uint64); ok { + r0 = returnFunc(runtimeAddress) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(1).(func(common.Address) error); ok { + r1 = returnFunc(runtimeAddress) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyByIndex provides a mock function with given fields: address, index -func (_m *AccountInfo) GetAccountKeyByIndex(address flow.Address, index uint32) (*flow.AccountPublicKey, error) { - ret := _m.Called(address, index) +// AccountInfo_GetAccountBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalance' +type AccountInfo_GetAccountBalance_Call struct { + *mock.Call +} + +// GetAccountBalance is a helper method to define mock.On call +// - runtimeAddress common.Address +func (_e *AccountInfo_Expecter) GetAccountBalance(runtimeAddress interface{}) *AccountInfo_GetAccountBalance_Call { + return &AccountInfo_GetAccountBalance_Call{Call: _e.mock.On("GetAccountBalance", runtimeAddress)} +} + +func (_c *AccountInfo_GetAccountBalance_Call) Run(run func(runtimeAddress common.Address)) *AccountInfo_GetAccountBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountInfo_GetAccountBalance_Call) Return(v uint64, err error) *AccountInfo_GetAccountBalance_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountInfo_GetAccountBalance_Call) RunAndReturn(run func(runtimeAddress common.Address) (uint64, error)) *AccountInfo_GetAccountBalance_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyByIndex provides a mock function for the type AccountInfo +func (_mock *AccountInfo) GetAccountKeyByIndex(address flow.Address, index uint32) (*flow.AccountPublicKey, error) { + ret := _mock.Called(address, index) if len(ret) == 0 { panic("no return value specified for GetAccountKeyByIndex") @@ -111,29 +229,67 @@ func (_m *AccountInfo) GetAccountKeyByIndex(address flow.Address, index uint32) var r0 *flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(flow.Address, uint32) (*flow.AccountPublicKey, error)); ok { - return rf(address, index) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) (*flow.AccountPublicKey, error)); ok { + return returnFunc(address, index) } - if rf, ok := ret.Get(0).(func(flow.Address, uint32) *flow.AccountPublicKey); ok { - r0 = rf(address, index) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) *flow.AccountPublicKey); ok { + r0 = returnFunc(address, index) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { - r1 = rf(address, index) + if returnFunc, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { + r1 = returnFunc(address, index) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeys provides a mock function with given fields: address -func (_m *AccountInfo) GetAccountKeys(address flow.Address) ([]flow.AccountPublicKey, error) { - ret := _m.Called(address) +// AccountInfo_GetAccountKeyByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyByIndex' +type AccountInfo_GetAccountKeyByIndex_Call struct { + *mock.Call +} + +// GetAccountKeyByIndex is a helper method to define mock.On call +// - address flow.Address +// - index uint32 +func (_e *AccountInfo_Expecter) GetAccountKeyByIndex(address interface{}, index interface{}) *AccountInfo_GetAccountKeyByIndex_Call { + return &AccountInfo_GetAccountKeyByIndex_Call{Call: _e.mock.On("GetAccountKeyByIndex", address, index)} +} + +func (_c *AccountInfo_GetAccountKeyByIndex_Call) Run(run func(address flow.Address, index uint32)) *AccountInfo_GetAccountKeyByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountInfo_GetAccountKeyByIndex_Call) Return(accountPublicKey *flow.AccountPublicKey, err error) *AccountInfo_GetAccountKeyByIndex_Call { + _c.Call.Return(accountPublicKey, err) + return _c +} + +func (_c *AccountInfo_GetAccountKeyByIndex_Call) RunAndReturn(run func(address flow.Address, index uint32) (*flow.AccountPublicKey, error)) *AccountInfo_GetAccountKeyByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeys provides a mock function for the type AccountInfo +func (_mock *AccountInfo) GetAccountKeys(address flow.Address) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GetAccountKeys") @@ -141,29 +297,61 @@ func (_m *AccountInfo) GetAccountKeys(address flow.Address) ([]flow.AccountPubli var r0 []flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) ([]flow.AccountPublicKey, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) []flow.AccountPublicKey); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) []flow.AccountPublicKey); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStorageCapacity provides a mock function with given fields: runtimeAddress -func (_m *AccountInfo) GetStorageCapacity(runtimeAddress common.Address) (uint64, error) { - ret := _m.Called(runtimeAddress) +// AccountInfo_GetAccountKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeys' +type AccountInfo_GetAccountKeys_Call struct { + *mock.Call +} + +// GetAccountKeys is a helper method to define mock.On call +// - address flow.Address +func (_e *AccountInfo_Expecter) GetAccountKeys(address interface{}) *AccountInfo_GetAccountKeys_Call { + return &AccountInfo_GetAccountKeys_Call{Call: _e.mock.On("GetAccountKeys", address)} +} + +func (_c *AccountInfo_GetAccountKeys_Call) Run(run func(address flow.Address)) *AccountInfo_GetAccountKeys_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountInfo_GetAccountKeys_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *AccountInfo_GetAccountKeys_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *AccountInfo_GetAccountKeys_Call) RunAndReturn(run func(address flow.Address) ([]flow.AccountPublicKey, error)) *AccountInfo_GetAccountKeys_Call { + _c.Call.Return(run) + return _c +} + +// GetStorageCapacity provides a mock function for the type AccountInfo +func (_mock *AccountInfo) GetStorageCapacity(runtimeAddress common.Address) (uint64, error) { + ret := _mock.Called(runtimeAddress) if len(ret) == 0 { panic("no return value specified for GetStorageCapacity") @@ -171,27 +359,59 @@ func (_m *AccountInfo) GetStorageCapacity(runtimeAddress common.Address) (uint64 var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { + return returnFunc(runtimeAddress) } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) uint64); ok { + r0 = returnFunc(runtimeAddress) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(1).(func(common.Address) error); ok { + r1 = returnFunc(runtimeAddress) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStorageUsed provides a mock function with given fields: runtimeAddress -func (_m *AccountInfo) GetStorageUsed(runtimeAddress common.Address) (uint64, error) { - ret := _m.Called(runtimeAddress) +// AccountInfo_GetStorageCapacity_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStorageCapacity' +type AccountInfo_GetStorageCapacity_Call struct { + *mock.Call +} + +// GetStorageCapacity is a helper method to define mock.On call +// - runtimeAddress common.Address +func (_e *AccountInfo_Expecter) GetStorageCapacity(runtimeAddress interface{}) *AccountInfo_GetStorageCapacity_Call { + return &AccountInfo_GetStorageCapacity_Call{Call: _e.mock.On("GetStorageCapacity", runtimeAddress)} +} + +func (_c *AccountInfo_GetStorageCapacity_Call) Run(run func(runtimeAddress common.Address)) *AccountInfo_GetStorageCapacity_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountInfo_GetStorageCapacity_Call) Return(v uint64, err error) *AccountInfo_GetStorageCapacity_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountInfo_GetStorageCapacity_Call) RunAndReturn(run func(runtimeAddress common.Address) (uint64, error)) *AccountInfo_GetStorageCapacity_Call { + _c.Call.Return(run) + return _c +} + +// GetStorageUsed provides a mock function for the type AccountInfo +func (_mock *AccountInfo) GetStorageUsed(runtimeAddress common.Address) (uint64, error) { + ret := _mock.Called(runtimeAddress) if len(ret) == 0 { panic("no return value specified for GetStorageUsed") @@ -199,34 +419,52 @@ func (_m *AccountInfo) GetStorageUsed(runtimeAddress common.Address) (uint64, er var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { + return returnFunc(runtimeAddress) } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) uint64); ok { + r0 = returnFunc(runtimeAddress) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(1).(func(common.Address) error); ok { + r1 = returnFunc(runtimeAddress) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAccountInfo creates a new instance of AccountInfo. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccountInfo(t interface { - mock.TestingT - Cleanup(func()) -}) *AccountInfo { - mock := &AccountInfo{} - mock.Mock.Test(t) +// AccountInfo_GetStorageUsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStorageUsed' +type AccountInfo_GetStorageUsed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetStorageUsed is a helper method to define mock.On call +// - runtimeAddress common.Address +func (_e *AccountInfo_Expecter) GetStorageUsed(runtimeAddress interface{}) *AccountInfo_GetStorageUsed_Call { + return &AccountInfo_GetStorageUsed_Call{Call: _e.mock.On("GetStorageUsed", runtimeAddress)} +} - return mock +func (_c *AccountInfo_GetStorageUsed_Call) Run(run func(runtimeAddress common.Address)) *AccountInfo_GetStorageUsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountInfo_GetStorageUsed_Call) Return(v uint64, err error) *AccountInfo_GetStorageUsed_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountInfo_GetStorageUsed_Call) RunAndReturn(run func(runtimeAddress common.Address) (uint64, error)) *AccountInfo_GetStorageUsed_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/account_key_reader.go b/fvm/environment/mock/account_key_reader.go index c577304bb55..e9c97af5d43 100644 --- a/fvm/environment/mock/account_key_reader.go +++ b/fvm/environment/mock/account_key_reader.go @@ -1,23 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/runtime" mock "github.com/stretchr/testify/mock" - - runtime "github.com/onflow/cadence/runtime" ) +// NewAccountKeyReader creates a new instance of AccountKeyReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountKeyReader(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountKeyReader { + mock := &AccountKeyReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccountKeyReader is an autogenerated mock type for the AccountKeyReader type type AccountKeyReader struct { mock.Mock } -// AccountKeysCount provides a mock function with given fields: runtimeAddress -func (_m *AccountKeyReader) AccountKeysCount(runtimeAddress common.Address) (uint32, error) { - ret := _m.Called(runtimeAddress) +type AccountKeyReader_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountKeyReader) EXPECT() *AccountKeyReader_Expecter { + return &AccountKeyReader_Expecter{mock: &_m.Mock} +} + +// AccountKeysCount provides a mock function for the type AccountKeyReader +func (_mock *AccountKeyReader) AccountKeysCount(runtimeAddress common.Address) (uint32, error) { + ret := _mock.Called(runtimeAddress) if len(ret) == 0 { panic("no return value specified for AccountKeysCount") @@ -25,27 +47,59 @@ func (_m *AccountKeyReader) AccountKeysCount(runtimeAddress common.Address) (uin var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint32, error)); ok { - return rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) (uint32, error)); ok { + return returnFunc(runtimeAddress) } - if rf, ok := ret.Get(0).(func(common.Address) uint32); ok { - r0 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(0).(func(common.Address) uint32); ok { + r0 = returnFunc(runtimeAddress) } else { r0 = ret.Get(0).(uint32) } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(runtimeAddress) + if returnFunc, ok := ret.Get(1).(func(common.Address) error); ok { + r1 = returnFunc(runtimeAddress) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKey provides a mock function with given fields: runtimeAddress, keyIndex -func (_m *AccountKeyReader) GetAccountKey(runtimeAddress common.Address, keyIndex uint32) (*runtime.AccountKey, error) { - ret := _m.Called(runtimeAddress, keyIndex) +// AccountKeyReader_AccountKeysCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AccountKeysCount' +type AccountKeyReader_AccountKeysCount_Call struct { + *mock.Call +} + +// AccountKeysCount is a helper method to define mock.On call +// - runtimeAddress common.Address +func (_e *AccountKeyReader_Expecter) AccountKeysCount(runtimeAddress interface{}) *AccountKeyReader_AccountKeysCount_Call { + return &AccountKeyReader_AccountKeysCount_Call{Call: _e.mock.On("AccountKeysCount", runtimeAddress)} +} + +func (_c *AccountKeyReader_AccountKeysCount_Call) Run(run func(runtimeAddress common.Address)) *AccountKeyReader_AccountKeysCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountKeyReader_AccountKeysCount_Call) Return(v uint32, err error) *AccountKeyReader_AccountKeysCount_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountKeyReader_AccountKeysCount_Call) RunAndReturn(run func(runtimeAddress common.Address) (uint32, error)) *AccountKeyReader_AccountKeysCount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKey provides a mock function for the type AccountKeyReader +func (_mock *AccountKeyReader) GetAccountKey(runtimeAddress common.Address, keyIndex uint32) (*runtime.AccountKey, error) { + ret := _mock.Called(runtimeAddress, keyIndex) if len(ret) == 0 { panic("no return value specified for GetAccountKey") @@ -53,36 +107,60 @@ func (_m *AccountKeyReader) GetAccountKey(runtimeAddress common.Address, keyInde var r0 *runtime.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(common.Address, uint32) (*runtime.AccountKey, error)); ok { - return rf(runtimeAddress, keyIndex) + if returnFunc, ok := ret.Get(0).(func(common.Address, uint32) (*runtime.AccountKey, error)); ok { + return returnFunc(runtimeAddress, keyIndex) } - if rf, ok := ret.Get(0).(func(common.Address, uint32) *runtime.AccountKey); ok { - r0 = rf(runtimeAddress, keyIndex) + if returnFunc, ok := ret.Get(0).(func(common.Address, uint32) *runtime.AccountKey); ok { + r0 = returnFunc(runtimeAddress, keyIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*runtime.AccountKey) } } - - if rf, ok := ret.Get(1).(func(common.Address, uint32) error); ok { - r1 = rf(runtimeAddress, keyIndex) + if returnFunc, ok := ret.Get(1).(func(common.Address, uint32) error); ok { + r1 = returnFunc(runtimeAddress, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAccountKeyReader creates a new instance of AccountKeyReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccountKeyReader(t interface { - mock.TestingT - Cleanup(func()) -}) *AccountKeyReader { - mock := &AccountKeyReader{} - mock.Mock.Test(t) +// AccountKeyReader_GetAccountKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKey' +type AccountKeyReader_GetAccountKey_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetAccountKey is a helper method to define mock.On call +// - runtimeAddress common.Address +// - keyIndex uint32 +func (_e *AccountKeyReader_Expecter) GetAccountKey(runtimeAddress interface{}, keyIndex interface{}) *AccountKeyReader_GetAccountKey_Call { + return &AccountKeyReader_GetAccountKey_Call{Call: _e.mock.On("GetAccountKey", runtimeAddress, keyIndex)} +} - return mock +func (_c *AccountKeyReader_GetAccountKey_Call) Run(run func(runtimeAddress common.Address, keyIndex uint32)) *AccountKeyReader_GetAccountKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountKeyReader_GetAccountKey_Call) Return(v *runtime.AccountKey, err error) *AccountKeyReader_GetAccountKey_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountKeyReader_GetAccountKey_Call) RunAndReturn(run func(runtimeAddress common.Address, keyIndex uint32) (*runtime.AccountKey, error)) *AccountKeyReader_GetAccountKey_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/account_key_updater.go b/fvm/environment/mock/account_key_updater.go index 45e77f77dde..44383c6b36a 100644 --- a/fvm/environment/mock/account_key_updater.go +++ b/fvm/environment/mock/account_key_updater.go @@ -1,23 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/runtime" mock "github.com/stretchr/testify/mock" - - runtime "github.com/onflow/cadence/runtime" ) +// NewAccountKeyUpdater creates a new instance of AccountKeyUpdater. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountKeyUpdater(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountKeyUpdater { + mock := &AccountKeyUpdater{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccountKeyUpdater is an autogenerated mock type for the AccountKeyUpdater type type AccountKeyUpdater struct { mock.Mock } -// AddAccountKey provides a mock function with given fields: runtimeAddress, publicKey, hashAlgo, weight -func (_m *AccountKeyUpdater) AddAccountKey(runtimeAddress common.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int) (*runtime.AccountKey, error) { - ret := _m.Called(runtimeAddress, publicKey, hashAlgo, weight) +type AccountKeyUpdater_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountKeyUpdater) EXPECT() *AccountKeyUpdater_Expecter { + return &AccountKeyUpdater_Expecter{mock: &_m.Mock} +} + +// AddAccountKey provides a mock function for the type AccountKeyUpdater +func (_mock *AccountKeyUpdater) AddAccountKey(runtimeAddress common.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int) (*runtime.AccountKey, error) { + ret := _mock.Called(runtimeAddress, publicKey, hashAlgo, weight) if len(ret) == 0 { panic("no return value specified for AddAccountKey") @@ -25,29 +47,79 @@ func (_m *AccountKeyUpdater) AddAccountKey(runtimeAddress common.Address, public var r0 *runtime.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(common.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) (*runtime.AccountKey, error)); ok { - return rf(runtimeAddress, publicKey, hashAlgo, weight) + if returnFunc, ok := ret.Get(0).(func(common.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) (*runtime.AccountKey, error)); ok { + return returnFunc(runtimeAddress, publicKey, hashAlgo, weight) } - if rf, ok := ret.Get(0).(func(common.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) *runtime.AccountKey); ok { - r0 = rf(runtimeAddress, publicKey, hashAlgo, weight) + if returnFunc, ok := ret.Get(0).(func(common.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) *runtime.AccountKey); ok { + r0 = returnFunc(runtimeAddress, publicKey, hashAlgo, weight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*runtime.AccountKey) } } - - if rf, ok := ret.Get(1).(func(common.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) error); ok { - r1 = rf(runtimeAddress, publicKey, hashAlgo, weight) + if returnFunc, ok := ret.Get(1).(func(common.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) error); ok { + r1 = returnFunc(runtimeAddress, publicKey, hashAlgo, weight) } else { r1 = ret.Error(1) } - return r0, r1 } -// RevokeAccountKey provides a mock function with given fields: runtimeAddress, keyIndex -func (_m *AccountKeyUpdater) RevokeAccountKey(runtimeAddress common.Address, keyIndex uint32) (*runtime.AccountKey, error) { - ret := _m.Called(runtimeAddress, keyIndex) +// AccountKeyUpdater_AddAccountKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddAccountKey' +type AccountKeyUpdater_AddAccountKey_Call struct { + *mock.Call +} + +// AddAccountKey is a helper method to define mock.On call +// - runtimeAddress common.Address +// - publicKey *runtime.PublicKey +// - hashAlgo runtime.HashAlgorithm +// - weight int +func (_e *AccountKeyUpdater_Expecter) AddAccountKey(runtimeAddress interface{}, publicKey interface{}, hashAlgo interface{}, weight interface{}) *AccountKeyUpdater_AddAccountKey_Call { + return &AccountKeyUpdater_AddAccountKey_Call{Call: _e.mock.On("AddAccountKey", runtimeAddress, publicKey, hashAlgo, weight)} +} + +func (_c *AccountKeyUpdater_AddAccountKey_Call) Run(run func(runtimeAddress common.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int)) *AccountKeyUpdater_AddAccountKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + var arg1 *runtime.PublicKey + if args[1] != nil { + arg1 = args[1].(*runtime.PublicKey) + } + var arg2 runtime.HashAlgorithm + if args[2] != nil { + arg2 = args[2].(runtime.HashAlgorithm) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *AccountKeyUpdater_AddAccountKey_Call) Return(v *runtime.AccountKey, err error) *AccountKeyUpdater_AddAccountKey_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountKeyUpdater_AddAccountKey_Call) RunAndReturn(run func(runtimeAddress common.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int) (*runtime.AccountKey, error)) *AccountKeyUpdater_AddAccountKey_Call { + _c.Call.Return(run) + return _c +} + +// RevokeAccountKey provides a mock function for the type AccountKeyUpdater +func (_mock *AccountKeyUpdater) RevokeAccountKey(runtimeAddress common.Address, keyIndex uint32) (*runtime.AccountKey, error) { + ret := _mock.Called(runtimeAddress, keyIndex) if len(ret) == 0 { panic("no return value specified for RevokeAccountKey") @@ -55,36 +127,60 @@ func (_m *AccountKeyUpdater) RevokeAccountKey(runtimeAddress common.Address, key var r0 *runtime.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(common.Address, uint32) (*runtime.AccountKey, error)); ok { - return rf(runtimeAddress, keyIndex) + if returnFunc, ok := ret.Get(0).(func(common.Address, uint32) (*runtime.AccountKey, error)); ok { + return returnFunc(runtimeAddress, keyIndex) } - if rf, ok := ret.Get(0).(func(common.Address, uint32) *runtime.AccountKey); ok { - r0 = rf(runtimeAddress, keyIndex) + if returnFunc, ok := ret.Get(0).(func(common.Address, uint32) *runtime.AccountKey); ok { + r0 = returnFunc(runtimeAddress, keyIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*runtime.AccountKey) } } - - if rf, ok := ret.Get(1).(func(common.Address, uint32) error); ok { - r1 = rf(runtimeAddress, keyIndex) + if returnFunc, ok := ret.Get(1).(func(common.Address, uint32) error); ok { + r1 = returnFunc(runtimeAddress, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAccountKeyUpdater creates a new instance of AccountKeyUpdater. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccountKeyUpdater(t interface { - mock.TestingT - Cleanup(func()) -}) *AccountKeyUpdater { - mock := &AccountKeyUpdater{} - mock.Mock.Test(t) +// AccountKeyUpdater_RevokeAccountKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RevokeAccountKey' +type AccountKeyUpdater_RevokeAccountKey_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RevokeAccountKey is a helper method to define mock.On call +// - runtimeAddress common.Address +// - keyIndex uint32 +func (_e *AccountKeyUpdater_Expecter) RevokeAccountKey(runtimeAddress interface{}, keyIndex interface{}) *AccountKeyUpdater_RevokeAccountKey_Call { + return &AccountKeyUpdater_RevokeAccountKey_Call{Call: _e.mock.On("RevokeAccountKey", runtimeAddress, keyIndex)} +} - return mock +func (_c *AccountKeyUpdater_RevokeAccountKey_Call) Run(run func(runtimeAddress common.Address, keyIndex uint32)) *AccountKeyUpdater_RevokeAccountKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountKeyUpdater_RevokeAccountKey_Call) Return(v *runtime.AccountKey, err error) *AccountKeyUpdater_RevokeAccountKey_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountKeyUpdater_RevokeAccountKey_Call) RunAndReturn(run func(runtimeAddress common.Address, keyIndex uint32) (*runtime.AccountKey, error)) *AccountKeyUpdater_RevokeAccountKey_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/account_local_id_generator.go b/fvm/environment/mock/account_local_id_generator.go index 269d411a316..a8741df7844 100644 --- a/fvm/environment/mock/account_local_id_generator.go +++ b/fvm/environment/mock/account_local_id_generator.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - + "github.com/onflow/cadence/common" mock "github.com/stretchr/testify/mock" ) +// NewAccountLocalIDGenerator creates a new instance of AccountLocalIDGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountLocalIDGenerator(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountLocalIDGenerator { + mock := &AccountLocalIDGenerator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccountLocalIDGenerator is an autogenerated mock type for the AccountLocalIDGenerator type type AccountLocalIDGenerator struct { mock.Mock } -// GenerateAccountID provides a mock function with given fields: address -func (_m *AccountLocalIDGenerator) GenerateAccountID(address common.Address) (uint64, error) { - ret := _m.Called(address) +type AccountLocalIDGenerator_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountLocalIDGenerator) EXPECT() *AccountLocalIDGenerator_Expecter { + return &AccountLocalIDGenerator_Expecter{mock: &_m.Mock} +} + +// GenerateAccountID provides a mock function for the type AccountLocalIDGenerator +func (_mock *AccountLocalIDGenerator) GenerateAccountID(address common.Address) (uint64, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GenerateAccountID") @@ -23,34 +46,52 @@ func (_m *AccountLocalIDGenerator) GenerateAccountID(address common.Address) (ui var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(common.Address) uint64); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(common.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAccountLocalIDGenerator creates a new instance of AccountLocalIDGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccountLocalIDGenerator(t interface { - mock.TestingT - Cleanup(func()) -}) *AccountLocalIDGenerator { - mock := &AccountLocalIDGenerator{} - mock.Mock.Test(t) +// AccountLocalIDGenerator_GenerateAccountID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateAccountID' +type AccountLocalIDGenerator_GenerateAccountID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GenerateAccountID is a helper method to define mock.On call +// - address common.Address +func (_e *AccountLocalIDGenerator_Expecter) GenerateAccountID(address interface{}) *AccountLocalIDGenerator_GenerateAccountID_Call { + return &AccountLocalIDGenerator_GenerateAccountID_Call{Call: _e.mock.On("GenerateAccountID", address)} +} - return mock +func (_c *AccountLocalIDGenerator_GenerateAccountID_Call) Run(run func(address common.Address)) *AccountLocalIDGenerator_GenerateAccountID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccountLocalIDGenerator_GenerateAccountID_Call) Return(v uint64, err error) *AccountLocalIDGenerator_GenerateAccountID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountLocalIDGenerator_GenerateAccountID_Call) RunAndReturn(run func(address common.Address) (uint64, error)) *AccountLocalIDGenerator_GenerateAccountID_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/accounts.go b/fvm/environment/mock/accounts.go index 7113bb6b275..260f8bc9b34 100644 --- a/fvm/environment/mock/accounts.go +++ b/fvm/environment/mock/accounts.go @@ -1,23 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - atree "github.com/onflow/atree" - - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/atree" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewAccounts creates a new instance of Accounts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccounts(t interface { + mock.TestingT + Cleanup(func()) +}) *Accounts { + mock := &Accounts{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Accounts is an autogenerated mock type for the Accounts type type Accounts struct { mock.Mock } -// AllocateSlabIndex provides a mock function with given fields: address -func (_m *Accounts) AllocateSlabIndex(address flow.Address) (atree.SlabIndex, error) { - ret := _m.Called(address) +type Accounts_Expecter struct { + mock *mock.Mock +} + +func (_m *Accounts) EXPECT() *Accounts_Expecter { + return &Accounts_Expecter{mock: &_m.Mock} +} + +// AllocateSlabIndex provides a mock function for the type Accounts +func (_mock *Accounts) AllocateSlabIndex(address flow.Address) (atree.SlabIndex, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for AllocateSlabIndex") @@ -25,47 +47,118 @@ func (_m *Accounts) AllocateSlabIndex(address flow.Address) (atree.SlabIndex, er var r0 atree.SlabIndex var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (atree.SlabIndex, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) (atree.SlabIndex, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) atree.SlabIndex); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) atree.SlabIndex); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(atree.SlabIndex) } } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// AppendAccountPublicKey provides a mock function with given fields: address, key -func (_m *Accounts) AppendAccountPublicKey(address flow.Address, key flow.AccountPublicKey) error { - ret := _m.Called(address, key) +// Accounts_AllocateSlabIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllocateSlabIndex' +type Accounts_AllocateSlabIndex_Call struct { + *mock.Call +} + +// AllocateSlabIndex is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) AllocateSlabIndex(address interface{}) *Accounts_AllocateSlabIndex_Call { + return &Accounts_AllocateSlabIndex_Call{Call: _e.mock.On("AllocateSlabIndex", address)} +} + +func (_c *Accounts_AllocateSlabIndex_Call) Run(run func(address flow.Address)) *Accounts_AllocateSlabIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_AllocateSlabIndex_Call) Return(slabIndex atree.SlabIndex, err error) *Accounts_AllocateSlabIndex_Call { + _c.Call.Return(slabIndex, err) + return _c +} + +func (_c *Accounts_AllocateSlabIndex_Call) RunAndReturn(run func(address flow.Address) (atree.SlabIndex, error)) *Accounts_AllocateSlabIndex_Call { + _c.Call.Return(run) + return _c +} + +// AppendAccountPublicKey provides a mock function for the type Accounts +func (_mock *Accounts) AppendAccountPublicKey(address flow.Address, key flow.AccountPublicKey) error { + ret := _mock.Called(address, key) if len(ret) == 0 { panic("no return value specified for AppendAccountPublicKey") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Address, flow.AccountPublicKey) error); ok { - r0 = rf(address, key) + if returnFunc, ok := ret.Get(0).(func(flow.Address, flow.AccountPublicKey) error); ok { + r0 = returnFunc(address, key) } else { r0 = ret.Error(0) } - return r0 } -// ContractExists provides a mock function with given fields: contractName, address -func (_m *Accounts) ContractExists(contractName string, address flow.Address) (bool, error) { - ret := _m.Called(contractName, address) +// Accounts_AppendAccountPublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AppendAccountPublicKey' +type Accounts_AppendAccountPublicKey_Call struct { + *mock.Call +} + +// AppendAccountPublicKey is a helper method to define mock.On call +// - address flow.Address +// - key flow.AccountPublicKey +func (_e *Accounts_Expecter) AppendAccountPublicKey(address interface{}, key interface{}) *Accounts_AppendAccountPublicKey_Call { + return &Accounts_AppendAccountPublicKey_Call{Call: _e.mock.On("AppendAccountPublicKey", address, key)} +} + +func (_c *Accounts_AppendAccountPublicKey_Call) Run(run func(address flow.Address, key flow.AccountPublicKey)) *Accounts_AppendAccountPublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 flow.AccountPublicKey + if args[1] != nil { + arg1 = args[1].(flow.AccountPublicKey) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_AppendAccountPublicKey_Call) Return(err error) *Accounts_AppendAccountPublicKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Accounts_AppendAccountPublicKey_Call) RunAndReturn(run func(address flow.Address, key flow.AccountPublicKey) error) *Accounts_AppendAccountPublicKey_Call { + _c.Call.Return(run) + return _c +} + +// ContractExists provides a mock function for the type Accounts +func (_mock *Accounts) ContractExists(contractName string, address flow.Address) (bool, error) { + ret := _mock.Called(contractName, address) if len(ret) == 0 { panic("no return value specified for ContractExists") @@ -73,63 +166,179 @@ func (_m *Accounts) ContractExists(contractName string, address flow.Address) (b var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(string, flow.Address) (bool, error)); ok { - return rf(contractName, address) + if returnFunc, ok := ret.Get(0).(func(string, flow.Address) (bool, error)); ok { + return returnFunc(contractName, address) } - if rf, ok := ret.Get(0).(func(string, flow.Address) bool); ok { - r0 = rf(contractName, address) + if returnFunc, ok := ret.Get(0).(func(string, flow.Address) bool); ok { + r0 = returnFunc(contractName, address) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(string, flow.Address) error); ok { - r1 = rf(contractName, address) + if returnFunc, ok := ret.Get(1).(func(string, flow.Address) error); ok { + r1 = returnFunc(contractName, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// Create provides a mock function with given fields: publicKeys, newAddress -func (_m *Accounts) Create(publicKeys []flow.AccountPublicKey, newAddress flow.Address) error { - ret := _m.Called(publicKeys, newAddress) +// Accounts_ContractExists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ContractExists' +type Accounts_ContractExists_Call struct { + *mock.Call +} + +// ContractExists is a helper method to define mock.On call +// - contractName string +// - address flow.Address +func (_e *Accounts_Expecter) ContractExists(contractName interface{}, address interface{}) *Accounts_ContractExists_Call { + return &Accounts_ContractExists_Call{Call: _e.mock.On("ContractExists", contractName, address)} +} + +func (_c *Accounts_ContractExists_Call) Run(run func(contractName string, address flow.Address)) *Accounts_ContractExists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_ContractExists_Call) Return(b bool, err error) *Accounts_ContractExists_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Accounts_ContractExists_Call) RunAndReturn(run func(contractName string, address flow.Address) (bool, error)) *Accounts_ContractExists_Call { + _c.Call.Return(run) + return _c +} + +// Create provides a mock function for the type Accounts +func (_mock *Accounts) Create(publicKeys []flow.AccountPublicKey, newAddress flow.Address) error { + ret := _mock.Called(publicKeys, newAddress) if len(ret) == 0 { panic("no return value specified for Create") } var r0 error - if rf, ok := ret.Get(0).(func([]flow.AccountPublicKey, flow.Address) error); ok { - r0 = rf(publicKeys, newAddress) + if returnFunc, ok := ret.Get(0).(func([]flow.AccountPublicKey, flow.Address) error); ok { + r0 = returnFunc(publicKeys, newAddress) } else { r0 = ret.Error(0) } - return r0 } -// DeleteContract provides a mock function with given fields: contractName, address -func (_m *Accounts) DeleteContract(contractName string, address flow.Address) error { - ret := _m.Called(contractName, address) +// Accounts_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type Accounts_Create_Call struct { + *mock.Call +} + +// Create is a helper method to define mock.On call +// - publicKeys []flow.AccountPublicKey +// - newAddress flow.Address +func (_e *Accounts_Expecter) Create(publicKeys interface{}, newAddress interface{}) *Accounts_Create_Call { + return &Accounts_Create_Call{Call: _e.mock.On("Create", publicKeys, newAddress)} +} + +func (_c *Accounts_Create_Call) Run(run func(publicKeys []flow.AccountPublicKey, newAddress flow.Address)) *Accounts_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.AccountPublicKey + if args[0] != nil { + arg0 = args[0].([]flow.AccountPublicKey) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_Create_Call) Return(err error) *Accounts_Create_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Accounts_Create_Call) RunAndReturn(run func(publicKeys []flow.AccountPublicKey, newAddress flow.Address) error) *Accounts_Create_Call { + _c.Call.Return(run) + return _c +} + +// DeleteContract provides a mock function for the type Accounts +func (_mock *Accounts) DeleteContract(contractName string, address flow.Address) error { + ret := _mock.Called(contractName, address) if len(ret) == 0 { panic("no return value specified for DeleteContract") } var r0 error - if rf, ok := ret.Get(0).(func(string, flow.Address) error); ok { - r0 = rf(contractName, address) + if returnFunc, ok := ret.Get(0).(func(string, flow.Address) error); ok { + r0 = returnFunc(contractName, address) } else { r0 = ret.Error(0) } - return r0 } -// Exists provides a mock function with given fields: address -func (_m *Accounts) Exists(address flow.Address) (bool, error) { - ret := _m.Called(address) +// Accounts_DeleteContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteContract' +type Accounts_DeleteContract_Call struct { + *mock.Call +} + +// DeleteContract is a helper method to define mock.On call +// - contractName string +// - address flow.Address +func (_e *Accounts_Expecter) DeleteContract(contractName interface{}, address interface{}) *Accounts_DeleteContract_Call { + return &Accounts_DeleteContract_Call{Call: _e.mock.On("DeleteContract", contractName, address)} +} + +func (_c *Accounts_DeleteContract_Call) Run(run func(contractName string, address flow.Address)) *Accounts_DeleteContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_DeleteContract_Call) Return(err error) *Accounts_DeleteContract_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Accounts_DeleteContract_Call) RunAndReturn(run func(contractName string, address flow.Address) error) *Accounts_DeleteContract_Call { + _c.Call.Return(run) + return _c +} + +// Exists provides a mock function for the type Accounts +func (_mock *Accounts) Exists(address flow.Address) (bool, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for Exists") @@ -137,27 +346,59 @@ func (_m *Accounts) Exists(address flow.Address) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (bool, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) (bool, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) bool); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) bool); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GenerateAccountLocalID provides a mock function with given fields: address -func (_m *Accounts) GenerateAccountLocalID(address flow.Address) (uint64, error) { - ret := _m.Called(address) +// Accounts_Exists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Exists' +type Accounts_Exists_Call struct { + *mock.Call +} + +// Exists is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) Exists(address interface{}) *Accounts_Exists_Call { + return &Accounts_Exists_Call{Call: _e.mock.On("Exists", address)} +} + +func (_c *Accounts_Exists_Call) Run(run func(address flow.Address)) *Accounts_Exists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_Exists_Call) Return(b bool, err error) *Accounts_Exists_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Accounts_Exists_Call) RunAndReturn(run func(address flow.Address) (bool, error)) *Accounts_Exists_Call { + _c.Call.Return(run) + return _c +} + +// GenerateAccountLocalID provides a mock function for the type Accounts +func (_mock *Accounts) GenerateAccountLocalID(address flow.Address) (uint64, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GenerateAccountLocalID") @@ -165,27 +406,59 @@ func (_m *Accounts) GenerateAccountLocalID(address flow.Address) (uint64, error) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (uint64, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) (uint64, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) uint64); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) uint64); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// Get provides a mock function with given fields: address -func (_m *Accounts) Get(address flow.Address) (*flow.Account, error) { - ret := _m.Called(address) +// Accounts_GenerateAccountLocalID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateAccountLocalID' +type Accounts_GenerateAccountLocalID_Call struct { + *mock.Call +} + +// GenerateAccountLocalID is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) GenerateAccountLocalID(address interface{}) *Accounts_GenerateAccountLocalID_Call { + return &Accounts_GenerateAccountLocalID_Call{Call: _e.mock.On("GenerateAccountLocalID", address)} +} + +func (_c *Accounts_GenerateAccountLocalID_Call) Run(run func(address flow.Address)) *Accounts_GenerateAccountLocalID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_GenerateAccountLocalID_Call) Return(v uint64, err error) *Accounts_GenerateAccountLocalID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Accounts_GenerateAccountLocalID_Call) RunAndReturn(run func(address flow.Address) (uint64, error)) *Accounts_GenerateAccountLocalID_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type Accounts +func (_mock *Accounts) Get(address flow.Address) (*flow.Account, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for Get") @@ -193,29 +466,61 @@ func (_m *Accounts) Get(address flow.Address) (*flow.Account, error) { var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (*flow.Account, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) (*flow.Account, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) *flow.Account); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) *flow.Account); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountPublicKey provides a mock function with given fields: address, keyIndex -func (_m *Accounts) GetAccountPublicKey(address flow.Address, keyIndex uint32) (flow.AccountPublicKey, error) { - ret := _m.Called(address, keyIndex) +// Accounts_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Accounts_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) Get(address interface{}) *Accounts_Get_Call { + return &Accounts_Get_Call{Call: _e.mock.On("Get", address)} +} + +func (_c *Accounts_Get_Call) Run(run func(address flow.Address)) *Accounts_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_Get_Call) Return(account *flow.Account, err error) *Accounts_Get_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *Accounts_Get_Call) RunAndReturn(run func(address flow.Address) (*flow.Account, error)) *Accounts_Get_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountPublicKey provides a mock function for the type Accounts +func (_mock *Accounts) GetAccountPublicKey(address flow.Address, keyIndex uint32) (flow.AccountPublicKey, error) { + ret := _mock.Called(address, keyIndex) if len(ret) == 0 { panic("no return value specified for GetAccountPublicKey") @@ -223,27 +528,65 @@ func (_m *Accounts) GetAccountPublicKey(address flow.Address, keyIndex uint32) ( var r0 flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(flow.Address, uint32) (flow.AccountPublicKey, error)); ok { - return rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) (flow.AccountPublicKey, error)); ok { + return returnFunc(address, keyIndex) } - if rf, ok := ret.Get(0).(func(flow.Address, uint32) flow.AccountPublicKey); ok { - r0 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) flow.AccountPublicKey); ok { + r0 = returnFunc(address, keyIndex) } else { r0 = ret.Get(0).(flow.AccountPublicKey) } - - if rf, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { - r1 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { + r1 = returnFunc(address, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountPublicKeyCount provides a mock function with given fields: address -func (_m *Accounts) GetAccountPublicKeyCount(address flow.Address) (uint32, error) { - ret := _m.Called(address) +// Accounts_GetAccountPublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountPublicKey' +type Accounts_GetAccountPublicKey_Call struct { + *mock.Call +} + +// GetAccountPublicKey is a helper method to define mock.On call +// - address flow.Address +// - keyIndex uint32 +func (_e *Accounts_Expecter) GetAccountPublicKey(address interface{}, keyIndex interface{}) *Accounts_GetAccountPublicKey_Call { + return &Accounts_GetAccountPublicKey_Call{Call: _e.mock.On("GetAccountPublicKey", address, keyIndex)} +} + +func (_c *Accounts_GetAccountPublicKey_Call) Run(run func(address flow.Address, keyIndex uint32)) *Accounts_GetAccountPublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_GetAccountPublicKey_Call) Return(accountPublicKey flow.AccountPublicKey, err error) *Accounts_GetAccountPublicKey_Call { + _c.Call.Return(accountPublicKey, err) + return _c +} + +func (_c *Accounts_GetAccountPublicKey_Call) RunAndReturn(run func(address flow.Address, keyIndex uint32) (flow.AccountPublicKey, error)) *Accounts_GetAccountPublicKey_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountPublicKeyCount provides a mock function for the type Accounts +func (_mock *Accounts) GetAccountPublicKeyCount(address flow.Address) (uint32, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GetAccountPublicKeyCount") @@ -251,27 +594,59 @@ func (_m *Accounts) GetAccountPublicKeyCount(address flow.Address) (uint32, erro var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (uint32, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) (uint32, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) uint32); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) uint32); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(uint32) } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountPublicKeyRevokedStatus provides a mock function with given fields: address, keyIndex -func (_m *Accounts) GetAccountPublicKeyRevokedStatus(address flow.Address, keyIndex uint32) (bool, error) { - ret := _m.Called(address, keyIndex) +// Accounts_GetAccountPublicKeyCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountPublicKeyCount' +type Accounts_GetAccountPublicKeyCount_Call struct { + *mock.Call +} + +// GetAccountPublicKeyCount is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) GetAccountPublicKeyCount(address interface{}) *Accounts_GetAccountPublicKeyCount_Call { + return &Accounts_GetAccountPublicKeyCount_Call{Call: _e.mock.On("GetAccountPublicKeyCount", address)} +} + +func (_c *Accounts_GetAccountPublicKeyCount_Call) Run(run func(address flow.Address)) *Accounts_GetAccountPublicKeyCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_GetAccountPublicKeyCount_Call) Return(v uint32, err error) *Accounts_GetAccountPublicKeyCount_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Accounts_GetAccountPublicKeyCount_Call) RunAndReturn(run func(address flow.Address) (uint32, error)) *Accounts_GetAccountPublicKeyCount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountPublicKeyRevokedStatus provides a mock function for the type Accounts +func (_mock *Accounts) GetAccountPublicKeyRevokedStatus(address flow.Address, keyIndex uint32) (bool, error) { + ret := _mock.Called(address, keyIndex) if len(ret) == 0 { panic("no return value specified for GetAccountPublicKeyRevokedStatus") @@ -279,27 +654,65 @@ func (_m *Accounts) GetAccountPublicKeyRevokedStatus(address flow.Address, keyIn var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(flow.Address, uint32) (bool, error)); ok { - return rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) (bool, error)); ok { + return returnFunc(address, keyIndex) } - if rf, ok := ret.Get(0).(func(flow.Address, uint32) bool); ok { - r0 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) bool); ok { + r0 = returnFunc(address, keyIndex) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { - r1 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { + r1 = returnFunc(address, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountPublicKeySequenceNumber provides a mock function with given fields: address, keyIndex -func (_m *Accounts) GetAccountPublicKeySequenceNumber(address flow.Address, keyIndex uint32) (uint64, error) { - ret := _m.Called(address, keyIndex) +// Accounts_GetAccountPublicKeyRevokedStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountPublicKeyRevokedStatus' +type Accounts_GetAccountPublicKeyRevokedStatus_Call struct { + *mock.Call +} + +// GetAccountPublicKeyRevokedStatus is a helper method to define mock.On call +// - address flow.Address +// - keyIndex uint32 +func (_e *Accounts_Expecter) GetAccountPublicKeyRevokedStatus(address interface{}, keyIndex interface{}) *Accounts_GetAccountPublicKeyRevokedStatus_Call { + return &Accounts_GetAccountPublicKeyRevokedStatus_Call{Call: _e.mock.On("GetAccountPublicKeyRevokedStatus", address, keyIndex)} +} + +func (_c *Accounts_GetAccountPublicKeyRevokedStatus_Call) Run(run func(address flow.Address, keyIndex uint32)) *Accounts_GetAccountPublicKeyRevokedStatus_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_GetAccountPublicKeyRevokedStatus_Call) Return(b bool, err error) *Accounts_GetAccountPublicKeyRevokedStatus_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Accounts_GetAccountPublicKeyRevokedStatus_Call) RunAndReturn(run func(address flow.Address, keyIndex uint32) (bool, error)) *Accounts_GetAccountPublicKeyRevokedStatus_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountPublicKeySequenceNumber provides a mock function for the type Accounts +func (_mock *Accounts) GetAccountPublicKeySequenceNumber(address flow.Address, keyIndex uint32) (uint64, error) { + ret := _mock.Called(address, keyIndex) if len(ret) == 0 { panic("no return value specified for GetAccountPublicKeySequenceNumber") @@ -307,27 +720,65 @@ func (_m *Accounts) GetAccountPublicKeySequenceNumber(address flow.Address, keyI var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Address, uint32) (uint64, error)); ok { - return rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) (uint64, error)); ok { + return returnFunc(address, keyIndex) } - if rf, ok := ret.Get(0).(func(flow.Address, uint32) uint64); ok { - r0 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) uint64); ok { + r0 = returnFunc(address, keyIndex) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { - r1 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { + r1 = returnFunc(address, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountPublicKeys provides a mock function with given fields: address -func (_m *Accounts) GetAccountPublicKeys(address flow.Address) ([]flow.AccountPublicKey, error) { - ret := _m.Called(address) +// Accounts_GetAccountPublicKeySequenceNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountPublicKeySequenceNumber' +type Accounts_GetAccountPublicKeySequenceNumber_Call struct { + *mock.Call +} + +// GetAccountPublicKeySequenceNumber is a helper method to define mock.On call +// - address flow.Address +// - keyIndex uint32 +func (_e *Accounts_Expecter) GetAccountPublicKeySequenceNumber(address interface{}, keyIndex interface{}) *Accounts_GetAccountPublicKeySequenceNumber_Call { + return &Accounts_GetAccountPublicKeySequenceNumber_Call{Call: _e.mock.On("GetAccountPublicKeySequenceNumber", address, keyIndex)} +} + +func (_c *Accounts_GetAccountPublicKeySequenceNumber_Call) Run(run func(address flow.Address, keyIndex uint32)) *Accounts_GetAccountPublicKeySequenceNumber_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_GetAccountPublicKeySequenceNumber_Call) Return(v uint64, err error) *Accounts_GetAccountPublicKeySequenceNumber_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Accounts_GetAccountPublicKeySequenceNumber_Call) RunAndReturn(run func(address flow.Address, keyIndex uint32) (uint64, error)) *Accounts_GetAccountPublicKeySequenceNumber_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountPublicKeys provides a mock function for the type Accounts +func (_mock *Accounts) GetAccountPublicKeys(address flow.Address) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GetAccountPublicKeys") @@ -335,29 +786,61 @@ func (_m *Accounts) GetAccountPublicKeys(address flow.Address) ([]flow.AccountPu var r0 []flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) ([]flow.AccountPublicKey, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) []flow.AccountPublicKey); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) []flow.AccountPublicKey); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetContract provides a mock function with given fields: contractName, address -func (_m *Accounts) GetContract(contractName string, address flow.Address) ([]byte, error) { - ret := _m.Called(contractName, address) +// Accounts_GetAccountPublicKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountPublicKeys' +type Accounts_GetAccountPublicKeys_Call struct { + *mock.Call +} + +// GetAccountPublicKeys is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) GetAccountPublicKeys(address interface{}) *Accounts_GetAccountPublicKeys_Call { + return &Accounts_GetAccountPublicKeys_Call{Call: _e.mock.On("GetAccountPublicKeys", address)} +} + +func (_c *Accounts_GetAccountPublicKeys_Call) Run(run func(address flow.Address)) *Accounts_GetAccountPublicKeys_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_GetAccountPublicKeys_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *Accounts_GetAccountPublicKeys_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *Accounts_GetAccountPublicKeys_Call) RunAndReturn(run func(address flow.Address) ([]flow.AccountPublicKey, error)) *Accounts_GetAccountPublicKeys_Call { + _c.Call.Return(run) + return _c +} + +// GetContract provides a mock function for the type Accounts +func (_mock *Accounts) GetContract(contractName string, address flow.Address) ([]byte, error) { + ret := _mock.Called(contractName, address) if len(ret) == 0 { panic("no return value specified for GetContract") @@ -365,29 +848,67 @@ func (_m *Accounts) GetContract(contractName string, address flow.Address) ([]by var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(string, flow.Address) ([]byte, error)); ok { - return rf(contractName, address) + if returnFunc, ok := ret.Get(0).(func(string, flow.Address) ([]byte, error)); ok { + return returnFunc(contractName, address) } - if rf, ok := ret.Get(0).(func(string, flow.Address) []byte); ok { - r0 = rf(contractName, address) + if returnFunc, ok := ret.Get(0).(func(string, flow.Address) []byte); ok { + r0 = returnFunc(contractName, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(string, flow.Address) error); ok { - r1 = rf(contractName, address) + if returnFunc, ok := ret.Get(1).(func(string, flow.Address) error); ok { + r1 = returnFunc(contractName, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetContractNames provides a mock function with given fields: address -func (_m *Accounts) GetContractNames(address flow.Address) ([]string, error) { - ret := _m.Called(address) +// Accounts_GetContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContract' +type Accounts_GetContract_Call struct { + *mock.Call +} + +// GetContract is a helper method to define mock.On call +// - contractName string +// - address flow.Address +func (_e *Accounts_Expecter) GetContract(contractName interface{}, address interface{}) *Accounts_GetContract_Call { + return &Accounts_GetContract_Call{Call: _e.mock.On("GetContract", contractName, address)} +} + +func (_c *Accounts_GetContract_Call) Run(run func(contractName string, address flow.Address)) *Accounts_GetContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_GetContract_Call) Return(bytes []byte, err error) *Accounts_GetContract_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Accounts_GetContract_Call) RunAndReturn(run func(contractName string, address flow.Address) ([]byte, error)) *Accounts_GetContract_Call { + _c.Call.Return(run) + return _c +} + +// GetContractNames provides a mock function for the type Accounts +func (_mock *Accounts) GetContractNames(address flow.Address) ([]string, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GetContractNames") @@ -395,29 +916,61 @@ func (_m *Accounts) GetContractNames(address flow.Address) ([]string, error) { var r0 []string var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) ([]string, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) ([]string, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) []string); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) []string); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]string) } } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetRuntimeAccountPublicKey provides a mock function with given fields: address, keyIndex -func (_m *Accounts) GetRuntimeAccountPublicKey(address flow.Address, keyIndex uint32) (flow.RuntimeAccountPublicKey, error) { - ret := _m.Called(address, keyIndex) +// Accounts_GetContractNames_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContractNames' +type Accounts_GetContractNames_Call struct { + *mock.Call +} + +// GetContractNames is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) GetContractNames(address interface{}) *Accounts_GetContractNames_Call { + return &Accounts_GetContractNames_Call{Call: _e.mock.On("GetContractNames", address)} +} + +func (_c *Accounts_GetContractNames_Call) Run(run func(address flow.Address)) *Accounts_GetContractNames_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_GetContractNames_Call) Return(strings []string, err error) *Accounts_GetContractNames_Call { + _c.Call.Return(strings, err) + return _c +} + +func (_c *Accounts_GetContractNames_Call) RunAndReturn(run func(address flow.Address) ([]string, error)) *Accounts_GetContractNames_Call { + _c.Call.Return(run) + return _c +} + +// GetRuntimeAccountPublicKey provides a mock function for the type Accounts +func (_mock *Accounts) GetRuntimeAccountPublicKey(address flow.Address, keyIndex uint32) (flow.RuntimeAccountPublicKey, error) { + ret := _mock.Called(address, keyIndex) if len(ret) == 0 { panic("no return value specified for GetRuntimeAccountPublicKey") @@ -425,27 +978,65 @@ func (_m *Accounts) GetRuntimeAccountPublicKey(address flow.Address, keyIndex ui var r0 flow.RuntimeAccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(flow.Address, uint32) (flow.RuntimeAccountPublicKey, error)); ok { - return rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) (flow.RuntimeAccountPublicKey, error)); ok { + return returnFunc(address, keyIndex) } - if rf, ok := ret.Get(0).(func(flow.Address, uint32) flow.RuntimeAccountPublicKey); ok { - r0 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) flow.RuntimeAccountPublicKey); ok { + r0 = returnFunc(address, keyIndex) } else { r0 = ret.Get(0).(flow.RuntimeAccountPublicKey) } - - if rf, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { - r1 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Address, uint32) error); ok { + r1 = returnFunc(address, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetStorageUsed provides a mock function with given fields: address -func (_m *Accounts) GetStorageUsed(address flow.Address) (uint64, error) { - ret := _m.Called(address) +// Accounts_GetRuntimeAccountPublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRuntimeAccountPublicKey' +type Accounts_GetRuntimeAccountPublicKey_Call struct { + *mock.Call +} + +// GetRuntimeAccountPublicKey is a helper method to define mock.On call +// - address flow.Address +// - keyIndex uint32 +func (_e *Accounts_Expecter) GetRuntimeAccountPublicKey(address interface{}, keyIndex interface{}) *Accounts_GetRuntimeAccountPublicKey_Call { + return &Accounts_GetRuntimeAccountPublicKey_Call{Call: _e.mock.On("GetRuntimeAccountPublicKey", address, keyIndex)} +} + +func (_c *Accounts_GetRuntimeAccountPublicKey_Call) Run(run func(address flow.Address, keyIndex uint32)) *Accounts_GetRuntimeAccountPublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_GetRuntimeAccountPublicKey_Call) Return(runtimeAccountPublicKey flow.RuntimeAccountPublicKey, err error) *Accounts_GetRuntimeAccountPublicKey_Call { + _c.Call.Return(runtimeAccountPublicKey, err) + return _c +} + +func (_c *Accounts_GetRuntimeAccountPublicKey_Call) RunAndReturn(run func(address flow.Address, keyIndex uint32) (flow.RuntimeAccountPublicKey, error)) *Accounts_GetRuntimeAccountPublicKey_Call { + _c.Call.Return(run) + return _c +} + +// GetStorageUsed provides a mock function for the type Accounts +func (_mock *Accounts) GetStorageUsed(address flow.Address) (uint64, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for GetStorageUsed") @@ -453,27 +1044,59 @@ func (_m *Accounts) GetStorageUsed(address flow.Address) (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (uint64, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) (uint64, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(flow.Address) uint64); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(flow.Address) uint64); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetValue provides a mock function with given fields: id -func (_m *Accounts) GetValue(id flow.RegisterID) (flow.RegisterValue, error) { - ret := _m.Called(id) +// Accounts_GetStorageUsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStorageUsed' +type Accounts_GetStorageUsed_Call struct { + *mock.Call +} + +// GetStorageUsed is a helper method to define mock.On call +// - address flow.Address +func (_e *Accounts_Expecter) GetStorageUsed(address interface{}) *Accounts_GetStorageUsed_Call { + return &Accounts_GetStorageUsed_Call{Call: _e.mock.On("GetStorageUsed", address)} +} + +func (_c *Accounts_GetStorageUsed_Call) Run(run func(address flow.Address)) *Accounts_GetStorageUsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_GetStorageUsed_Call) Return(v uint64, err error) *Accounts_GetStorageUsed_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Accounts_GetStorageUsed_Call) RunAndReturn(run func(address flow.Address) (uint64, error)) *Accounts_GetStorageUsed_Call { + _c.Call.Return(run) + return _c +} + +// GetValue provides a mock function for the type Accounts +func (_mock *Accounts) GetValue(id flow.RegisterID) (flow.RegisterValue, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for GetValue") @@ -481,108 +1104,288 @@ func (_m *Accounts) GetValue(id flow.RegisterID) (flow.RegisterValue, error) { var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterID) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// IncrementAccountPublicKeySequenceNumber provides a mock function with given fields: address, keyIndex -func (_m *Accounts) IncrementAccountPublicKeySequenceNumber(address flow.Address, keyIndex uint32) error { - ret := _m.Called(address, keyIndex) +// Accounts_GetValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetValue' +type Accounts_GetValue_Call struct { + *mock.Call +} + +// GetValue is a helper method to define mock.On call +// - id flow.RegisterID +func (_e *Accounts_Expecter) GetValue(id interface{}) *Accounts_GetValue_Call { + return &Accounts_GetValue_Call{Call: _e.mock.On("GetValue", id)} +} + +func (_c *Accounts_GetValue_Call) Run(run func(id flow.RegisterID)) *Accounts_GetValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Accounts_GetValue_Call) Return(v flow.RegisterValue, err error) *Accounts_GetValue_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Accounts_GetValue_Call) RunAndReturn(run func(id flow.RegisterID) (flow.RegisterValue, error)) *Accounts_GetValue_Call { + _c.Call.Return(run) + return _c +} + +// IncrementAccountPublicKeySequenceNumber provides a mock function for the type Accounts +func (_mock *Accounts) IncrementAccountPublicKeySequenceNumber(address flow.Address, keyIndex uint32) error { + ret := _mock.Called(address, keyIndex) if len(ret) == 0 { panic("no return value specified for IncrementAccountPublicKeySequenceNumber") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Address, uint32) error); ok { - r0 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) error); ok { + r0 = returnFunc(address, keyIndex) } else { r0 = ret.Error(0) } - return r0 } -// RevokeAccountPublicKey provides a mock function with given fields: address, keyIndex -func (_m *Accounts) RevokeAccountPublicKey(address flow.Address, keyIndex uint32) error { - ret := _m.Called(address, keyIndex) +// Accounts_IncrementAccountPublicKeySequenceNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IncrementAccountPublicKeySequenceNumber' +type Accounts_IncrementAccountPublicKeySequenceNumber_Call struct { + *mock.Call +} + +// IncrementAccountPublicKeySequenceNumber is a helper method to define mock.On call +// - address flow.Address +// - keyIndex uint32 +func (_e *Accounts_Expecter) IncrementAccountPublicKeySequenceNumber(address interface{}, keyIndex interface{}) *Accounts_IncrementAccountPublicKeySequenceNumber_Call { + return &Accounts_IncrementAccountPublicKeySequenceNumber_Call{Call: _e.mock.On("IncrementAccountPublicKeySequenceNumber", address, keyIndex)} +} + +func (_c *Accounts_IncrementAccountPublicKeySequenceNumber_Call) Run(run func(address flow.Address, keyIndex uint32)) *Accounts_IncrementAccountPublicKeySequenceNumber_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_IncrementAccountPublicKeySequenceNumber_Call) Return(err error) *Accounts_IncrementAccountPublicKeySequenceNumber_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Accounts_IncrementAccountPublicKeySequenceNumber_Call) RunAndReturn(run func(address flow.Address, keyIndex uint32) error) *Accounts_IncrementAccountPublicKeySequenceNumber_Call { + _c.Call.Return(run) + return _c +} + +// RevokeAccountPublicKey provides a mock function for the type Accounts +func (_mock *Accounts) RevokeAccountPublicKey(address flow.Address, keyIndex uint32) error { + ret := _mock.Called(address, keyIndex) if len(ret) == 0 { panic("no return value specified for RevokeAccountPublicKey") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Address, uint32) error); ok { - r0 = rf(address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint32) error); ok { + r0 = returnFunc(address, keyIndex) } else { r0 = ret.Error(0) } - return r0 } -// SetContract provides a mock function with given fields: contractName, address, contract -func (_m *Accounts) SetContract(contractName string, address flow.Address, contract []byte) error { - ret := _m.Called(contractName, address, contract) +// Accounts_RevokeAccountPublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RevokeAccountPublicKey' +type Accounts_RevokeAccountPublicKey_Call struct { + *mock.Call +} + +// RevokeAccountPublicKey is a helper method to define mock.On call +// - address flow.Address +// - keyIndex uint32 +func (_e *Accounts_Expecter) RevokeAccountPublicKey(address interface{}, keyIndex interface{}) *Accounts_RevokeAccountPublicKey_Call { + return &Accounts_RevokeAccountPublicKey_Call{Call: _e.mock.On("RevokeAccountPublicKey", address, keyIndex)} +} + +func (_c *Accounts_RevokeAccountPublicKey_Call) Run(run func(address flow.Address, keyIndex uint32)) *Accounts_RevokeAccountPublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_RevokeAccountPublicKey_Call) Return(err error) *Accounts_RevokeAccountPublicKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Accounts_RevokeAccountPublicKey_Call) RunAndReturn(run func(address flow.Address, keyIndex uint32) error) *Accounts_RevokeAccountPublicKey_Call { + _c.Call.Return(run) + return _c +} + +// SetContract provides a mock function for the type Accounts +func (_mock *Accounts) SetContract(contractName string, address flow.Address, contract []byte) error { + ret := _mock.Called(contractName, address, contract) if len(ret) == 0 { panic("no return value specified for SetContract") } var r0 error - if rf, ok := ret.Get(0).(func(string, flow.Address, []byte) error); ok { - r0 = rf(contractName, address, contract) + if returnFunc, ok := ret.Get(0).(func(string, flow.Address, []byte) error); ok { + r0 = returnFunc(contractName, address, contract) } else { r0 = ret.Error(0) } - return r0 } -// SetValue provides a mock function with given fields: id, value -func (_m *Accounts) SetValue(id flow.RegisterID, value flow.RegisterValue) error { - ret := _m.Called(id, value) +// Accounts_SetContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetContract' +type Accounts_SetContract_Call struct { + *mock.Call +} + +// SetContract is a helper method to define mock.On call +// - contractName string +// - address flow.Address +// - contract []byte +func (_e *Accounts_Expecter) SetContract(contractName interface{}, address interface{}, contract interface{}) *Accounts_SetContract_Call { + return &Accounts_SetContract_Call{Call: _e.mock.On("SetContract", contractName, address, contract)} +} + +func (_c *Accounts_SetContract_Call) Run(run func(contractName string, address flow.Address, contract []byte)) *Accounts_SetContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Accounts_SetContract_Call) Return(err error) *Accounts_SetContract_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Accounts_SetContract_Call) RunAndReturn(run func(contractName string, address flow.Address, contract []byte) error) *Accounts_SetContract_Call { + _c.Call.Return(run) + return _c +} + +// SetValue provides a mock function for the type Accounts +func (_mock *Accounts) SetValue(id flow.RegisterID, value flow.RegisterValue) error { + ret := _mock.Called(id, value) if len(ret) == 0 { panic("no return value specified for SetValue") } var r0 error - if rf, ok := ret.Get(0).(func(flow.RegisterID, flow.RegisterValue) error); ok { - r0 = rf(id, value) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, flow.RegisterValue) error); ok { + r0 = returnFunc(id, value) } else { r0 = ret.Error(0) } - return r0 } -// NewAccounts creates a new instance of Accounts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccounts(t interface { - mock.TestingT - Cleanup(func()) -}) *Accounts { - mock := &Accounts{} - mock.Mock.Test(t) +// Accounts_SetValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetValue' +type Accounts_SetValue_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SetValue is a helper method to define mock.On call +// - id flow.RegisterID +// - value flow.RegisterValue +func (_e *Accounts_Expecter) SetValue(id interface{}, value interface{}) *Accounts_SetValue_Call { + return &Accounts_SetValue_Call{Call: _e.mock.On("SetValue", id, value)} +} - return mock +func (_c *Accounts_SetValue_Call) Run(run func(id flow.RegisterID, value flow.RegisterValue)) *Accounts_SetValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + var arg1 flow.RegisterValue + if args[1] != nil { + arg1 = args[1].(flow.RegisterValue) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Accounts_SetValue_Call) Return(err error) *Accounts_SetValue_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Accounts_SetValue_Call) RunAndReturn(run func(id flow.RegisterID, value flow.RegisterValue) error) *Accounts_SetValue_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/address_generator.go b/fvm/environment/mock/address_generator.go index f952d9bfa71..730e2d5c12c 100644 --- a/fvm/environment/mock/address_generator.go +++ b/fvm/environment/mock/address_generator.go @@ -1,78 +1,180 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewAddressGenerator creates a new instance of AddressGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAddressGenerator(t interface { + mock.TestingT + Cleanup(func()) +}) *AddressGenerator { + mock := &AddressGenerator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AddressGenerator is an autogenerated mock type for the AddressGenerator type type AddressGenerator struct { mock.Mock } -// AddressCount provides a mock function with no fields -func (_m *AddressGenerator) AddressCount() uint64 { - ret := _m.Called() +type AddressGenerator_Expecter struct { + mock *mock.Mock +} + +func (_m *AddressGenerator) EXPECT() *AddressGenerator_Expecter { + return &AddressGenerator_Expecter{mock: &_m.Mock} +} + +// AddressCount provides a mock function for the type AddressGenerator +func (_mock *AddressGenerator) AddressCount() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for AddressCount") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Bytes provides a mock function with no fields -func (_m *AddressGenerator) Bytes() []byte { - ret := _m.Called() +// AddressGenerator_AddressCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddressCount' +type AddressGenerator_AddressCount_Call struct { + *mock.Call +} + +// AddressCount is a helper method to define mock.On call +func (_e *AddressGenerator_Expecter) AddressCount() *AddressGenerator_AddressCount_Call { + return &AddressGenerator_AddressCount_Call{Call: _e.mock.On("AddressCount")} +} + +func (_c *AddressGenerator_AddressCount_Call) Run(run func()) *AddressGenerator_AddressCount_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AddressGenerator_AddressCount_Call) Return(v uint64) *AddressGenerator_AddressCount_Call { + _c.Call.Return(v) + return _c +} + +func (_c *AddressGenerator_AddressCount_Call) RunAndReturn(run func() uint64) *AddressGenerator_AddressCount_Call { + _c.Call.Return(run) + return _c +} + +// Bytes provides a mock function for the type AddressGenerator +func (_mock *AddressGenerator) Bytes() []byte { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Bytes") } var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - return r0 } -// CurrentAddress provides a mock function with no fields -func (_m *AddressGenerator) CurrentAddress() flow.Address { - ret := _m.Called() +// AddressGenerator_Bytes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Bytes' +type AddressGenerator_Bytes_Call struct { + *mock.Call +} + +// Bytes is a helper method to define mock.On call +func (_e *AddressGenerator_Expecter) Bytes() *AddressGenerator_Bytes_Call { + return &AddressGenerator_Bytes_Call{Call: _e.mock.On("Bytes")} +} + +func (_c *AddressGenerator_Bytes_Call) Run(run func()) *AddressGenerator_Bytes_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AddressGenerator_Bytes_Call) Return(bytes []byte) *AddressGenerator_Bytes_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *AddressGenerator_Bytes_Call) RunAndReturn(run func() []byte) *AddressGenerator_Bytes_Call { + _c.Call.Return(run) + return _c +} + +// CurrentAddress provides a mock function for the type AddressGenerator +func (_mock *AddressGenerator) CurrentAddress() flow.Address { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for CurrentAddress") } var r0 flow.Address - if rf, ok := ret.Get(0).(func() flow.Address); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Address); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Address) } } - return r0 } -// NextAddress provides a mock function with no fields -func (_m *AddressGenerator) NextAddress() (flow.Address, error) { - ret := _m.Called() +// AddressGenerator_CurrentAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CurrentAddress' +type AddressGenerator_CurrentAddress_Call struct { + *mock.Call +} + +// CurrentAddress is a helper method to define mock.On call +func (_e *AddressGenerator_Expecter) CurrentAddress() *AddressGenerator_CurrentAddress_Call { + return &AddressGenerator_CurrentAddress_Call{Call: _e.mock.On("CurrentAddress")} +} + +func (_c *AddressGenerator_CurrentAddress_Call) Run(run func()) *AddressGenerator_CurrentAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AddressGenerator_CurrentAddress_Call) Return(address flow.Address) *AddressGenerator_CurrentAddress_Call { + _c.Call.Return(address) + return _c +} + +func (_c *AddressGenerator_CurrentAddress_Call) RunAndReturn(run func() flow.Address) *AddressGenerator_CurrentAddress_Call { + _c.Call.Return(run) + return _c +} + +// NextAddress provides a mock function for the type AddressGenerator +func (_mock *AddressGenerator) NextAddress() (flow.Address, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NextAddress") @@ -80,36 +182,47 @@ func (_m *AddressGenerator) NextAddress() (flow.Address, error) { var r0 flow.Address var r1 error - if rf, ok := ret.Get(0).(func() (flow.Address, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.Address, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.Address); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Address); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Address) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewAddressGenerator creates a new instance of AddressGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAddressGenerator(t interface { - mock.TestingT - Cleanup(func()) -}) *AddressGenerator { - mock := &AddressGenerator{} - mock.Mock.Test(t) +// AddressGenerator_NextAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NextAddress' +type AddressGenerator_NextAddress_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NextAddress is a helper method to define mock.On call +func (_e *AddressGenerator_Expecter) NextAddress() *AddressGenerator_NextAddress_Call { + return &AddressGenerator_NextAddress_Call{Call: _e.mock.On("NextAddress")} +} - return mock +func (_c *AddressGenerator_NextAddress_Call) Run(run func()) *AddressGenerator_NextAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AddressGenerator_NextAddress_Call) Return(address flow.Address, err error) *AddressGenerator_NextAddress_Call { + _c.Call.Return(address, err) + return _c +} + +func (_c *AddressGenerator_NextAddress_Call) RunAndReturn(run func() (flow.Address, error)) *AddressGenerator_NextAddress_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/block_info.go b/fvm/environment/mock/block_info.go index bbcc1caeb7c..3f97cb82120 100644 --- a/fvm/environment/mock/block_info.go +++ b/fvm/environment/mock/block_info.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - runtime "github.com/onflow/cadence/runtime" + "github.com/onflow/cadence/runtime" mock "github.com/stretchr/testify/mock" ) +// NewBlockInfo creates a new instance of BlockInfo. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockInfo(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockInfo { + mock := &BlockInfo{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BlockInfo is an autogenerated mock type for the BlockInfo type type BlockInfo struct { mock.Mock } -// GetBlockAtHeight provides a mock function with given fields: height -func (_m *BlockInfo) GetBlockAtHeight(height uint64) (runtime.Block, bool, error) { - ret := _m.Called(height) +type BlockInfo_Expecter struct { + mock *mock.Mock +} + +func (_m *BlockInfo) EXPECT() *BlockInfo_Expecter { + return &BlockInfo_Expecter{mock: &_m.Mock} +} + +// GetBlockAtHeight provides a mock function for the type BlockInfo +func (_mock *BlockInfo) GetBlockAtHeight(height uint64) (runtime.Block, bool, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for GetBlockAtHeight") @@ -23,33 +47,64 @@ func (_m *BlockInfo) GetBlockAtHeight(height uint64) (runtime.Block, bool, error var r0 runtime.Block var r1 bool var r2 error - if rf, ok := ret.Get(0).(func(uint64) (runtime.Block, bool, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) (runtime.Block, bool, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) runtime.Block); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) runtime.Block); ok { + r0 = returnFunc(height) } else { r0 = ret.Get(0).(runtime.Block) } - - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(height) } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(height) + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(height) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetCurrentBlockHeight provides a mock function with no fields -func (_m *BlockInfo) GetCurrentBlockHeight() (uint64, error) { - ret := _m.Called() +// BlockInfo_GetBlockAtHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockAtHeight' +type BlockInfo_GetBlockAtHeight_Call struct { + *mock.Call +} + +// GetBlockAtHeight is a helper method to define mock.On call +// - height uint64 +func (_e *BlockInfo_Expecter) GetBlockAtHeight(height interface{}) *BlockInfo_GetBlockAtHeight_Call { + return &BlockInfo_GetBlockAtHeight_Call{Call: _e.mock.On("GetBlockAtHeight", height)} +} + +func (_c *BlockInfo_GetBlockAtHeight_Call) Run(run func(height uint64)) *BlockInfo_GetBlockAtHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockInfo_GetBlockAtHeight_Call) Return(v runtime.Block, b bool, err error) *BlockInfo_GetBlockAtHeight_Call { + _c.Call.Return(v, b, err) + return _c +} + +func (_c *BlockInfo_GetBlockAtHeight_Call) RunAndReturn(run func(height uint64) (runtime.Block, bool, error)) *BlockInfo_GetBlockAtHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetCurrentBlockHeight provides a mock function for the type BlockInfo +func (_mock *BlockInfo) GetCurrentBlockHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetCurrentBlockHeight") @@ -57,34 +112,45 @@ func (_m *BlockInfo) GetCurrentBlockHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBlockInfo creates a new instance of BlockInfo. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockInfo(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockInfo { - mock := &BlockInfo{} - mock.Mock.Test(t) +// BlockInfo_GetCurrentBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCurrentBlockHeight' +type BlockInfo_GetCurrentBlockHeight_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetCurrentBlockHeight is a helper method to define mock.On call +func (_e *BlockInfo_Expecter) GetCurrentBlockHeight() *BlockInfo_GetCurrentBlockHeight_Call { + return &BlockInfo_GetCurrentBlockHeight_Call{Call: _e.mock.On("GetCurrentBlockHeight")} +} - return mock +func (_c *BlockInfo_GetCurrentBlockHeight_Call) Run(run func()) *BlockInfo_GetCurrentBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BlockInfo_GetCurrentBlockHeight_Call) Return(v uint64, err error) *BlockInfo_GetCurrentBlockHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BlockInfo_GetCurrentBlockHeight_Call) RunAndReturn(run func() (uint64, error)) *BlockInfo_GetCurrentBlockHeight_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/blocks.go b/fvm/environment/mock/blocks.go index 22f67e90dea..477541a1519 100644 --- a/fvm/environment/mock/blocks.go +++ b/fvm/environment/mock/blocks.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBlocks creates a new instance of Blocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlocks(t interface { + mock.TestingT + Cleanup(func()) +}) *Blocks { + mock := &Blocks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Blocks is an autogenerated mock type for the Blocks type type Blocks struct { mock.Mock } -// ByHeightFrom provides a mock function with given fields: height, header -func (_m *Blocks) ByHeightFrom(height uint64, header *flow.Header) (*flow.Header, error) { - ret := _m.Called(height, header) +type Blocks_Expecter struct { + mock *mock.Mock +} + +func (_m *Blocks) EXPECT() *Blocks_Expecter { + return &Blocks_Expecter{mock: &_m.Mock} +} + +// ByHeightFrom provides a mock function for the type Blocks +func (_mock *Blocks) ByHeightFrom(height uint64, header *flow.Header) (*flow.Header, error) { + ret := _mock.Called(height, header) if len(ret) == 0 { panic("no return value specified for ByHeightFrom") @@ -22,36 +46,60 @@ func (_m *Blocks) ByHeightFrom(height uint64, header *flow.Header) (*flow.Header var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func(uint64, *flow.Header) (*flow.Header, error)); ok { - return rf(height, header) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.Header) (*flow.Header, error)); ok { + return returnFunc(height, header) } - if rf, ok := ret.Get(0).(func(uint64, *flow.Header) *flow.Header); ok { - r0 = rf(height, header) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.Header) *flow.Header); ok { + r0 = returnFunc(height, header) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(uint64, *flow.Header) error); ok { - r1 = rf(height, header) + if returnFunc, ok := ret.Get(1).(func(uint64, *flow.Header) error); ok { + r1 = returnFunc(height, header) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBlocks creates a new instance of Blocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlocks(t interface { - mock.TestingT - Cleanup(func()) -}) *Blocks { - mock := &Blocks{} - mock.Mock.Test(t) +// Blocks_ByHeightFrom_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByHeightFrom' +type Blocks_ByHeightFrom_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByHeightFrom is a helper method to define mock.On call +// - height uint64 +// - header *flow.Header +func (_e *Blocks_Expecter) ByHeightFrom(height interface{}, header interface{}) *Blocks_ByHeightFrom_Call { + return &Blocks_ByHeightFrom_Call{Call: _e.mock.On("ByHeightFrom", height, header)} +} - return mock +func (_c *Blocks_ByHeightFrom_Call) Run(run func(height uint64, header *flow.Header)) *Blocks_ByHeightFrom_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Blocks_ByHeightFrom_Call) Return(header1 *flow.Header, err error) *Blocks_ByHeightFrom_Call { + _c.Call.Return(header1, err) + return _c +} + +func (_c *Blocks_ByHeightFrom_Call) RunAndReturn(run func(height uint64, header *flow.Header) (*flow.Header, error)) *Blocks_ByHeightFrom_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/bootstrap_account_creator.go b/fvm/environment/mock/bootstrap_account_creator.go index a6da607bc35..bced56a7596 100644 --- a/fvm/environment/mock/bootstrap_account_creator.go +++ b/fvm/environment/mock/bootstrap_account_creator.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBootstrapAccountCreator creates a new instance of BootstrapAccountCreator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBootstrapAccountCreator(t interface { + mock.TestingT + Cleanup(func()) +}) *BootstrapAccountCreator { + mock := &BootstrapAccountCreator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BootstrapAccountCreator is an autogenerated mock type for the BootstrapAccountCreator type type BootstrapAccountCreator struct { mock.Mock } -// CreateBootstrapAccount provides a mock function with given fields: publicKeys -func (_m *BootstrapAccountCreator) CreateBootstrapAccount(publicKeys []flow.AccountPublicKey) (flow.Address, error) { - ret := _m.Called(publicKeys) +type BootstrapAccountCreator_Expecter struct { + mock *mock.Mock +} + +func (_m *BootstrapAccountCreator) EXPECT() *BootstrapAccountCreator_Expecter { + return &BootstrapAccountCreator_Expecter{mock: &_m.Mock} +} + +// CreateBootstrapAccount provides a mock function for the type BootstrapAccountCreator +func (_mock *BootstrapAccountCreator) CreateBootstrapAccount(publicKeys []flow.AccountPublicKey) (flow.Address, error) { + ret := _mock.Called(publicKeys) if len(ret) == 0 { panic("no return value specified for CreateBootstrapAccount") @@ -22,36 +46,54 @@ func (_m *BootstrapAccountCreator) CreateBootstrapAccount(publicKeys []flow.Acco var r0 flow.Address var r1 error - if rf, ok := ret.Get(0).(func([]flow.AccountPublicKey) (flow.Address, error)); ok { - return rf(publicKeys) + if returnFunc, ok := ret.Get(0).(func([]flow.AccountPublicKey) (flow.Address, error)); ok { + return returnFunc(publicKeys) } - if rf, ok := ret.Get(0).(func([]flow.AccountPublicKey) flow.Address); ok { - r0 = rf(publicKeys) + if returnFunc, ok := ret.Get(0).(func([]flow.AccountPublicKey) flow.Address); ok { + r0 = returnFunc(publicKeys) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Address) } } - - if rf, ok := ret.Get(1).(func([]flow.AccountPublicKey) error); ok { - r1 = rf(publicKeys) + if returnFunc, ok := ret.Get(1).(func([]flow.AccountPublicKey) error); ok { + r1 = returnFunc(publicKeys) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBootstrapAccountCreator creates a new instance of BootstrapAccountCreator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBootstrapAccountCreator(t interface { - mock.TestingT - Cleanup(func()) -}) *BootstrapAccountCreator { - mock := &BootstrapAccountCreator{} - mock.Mock.Test(t) +// BootstrapAccountCreator_CreateBootstrapAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateBootstrapAccount' +type BootstrapAccountCreator_CreateBootstrapAccount_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// CreateBootstrapAccount is a helper method to define mock.On call +// - publicKeys []flow.AccountPublicKey +func (_e *BootstrapAccountCreator_Expecter) CreateBootstrapAccount(publicKeys interface{}) *BootstrapAccountCreator_CreateBootstrapAccount_Call { + return &BootstrapAccountCreator_CreateBootstrapAccount_Call{Call: _e.mock.On("CreateBootstrapAccount", publicKeys)} +} - return mock +func (_c *BootstrapAccountCreator_CreateBootstrapAccount_Call) Run(run func(publicKeys []flow.AccountPublicKey)) *BootstrapAccountCreator_CreateBootstrapAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.AccountPublicKey + if args[0] != nil { + arg0 = args[0].([]flow.AccountPublicKey) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BootstrapAccountCreator_CreateBootstrapAccount_Call) Return(address flow.Address, err error) *BootstrapAccountCreator_CreateBootstrapAccount_Call { + _c.Call.Return(address, err) + return _c +} + +func (_c *BootstrapAccountCreator_CreateBootstrapAccount_Call) RunAndReturn(run func(publicKeys []flow.AccountPublicKey) (flow.Address, error)) *BootstrapAccountCreator_CreateBootstrapAccount_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/cadence_runtime_provider.go b/fvm/environment/mock/cadence_runtime_provider.go new file mode 100644 index 00000000000..2f33139872a --- /dev/null +++ b/fvm/environment/mock/cadence_runtime_provider.go @@ -0,0 +1,163 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/fvm/environment" + mock "github.com/stretchr/testify/mock" +) + +// NewCadenceRuntimeProvider creates a new instance of CadenceRuntimeProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCadenceRuntimeProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *CadenceRuntimeProvider { + mock := &CadenceRuntimeProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// CadenceRuntimeProvider is an autogenerated mock type for the CadenceRuntimeProvider type +type CadenceRuntimeProvider struct { + mock.Mock +} + +type CadenceRuntimeProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *CadenceRuntimeProvider) EXPECT() *CadenceRuntimeProvider_Expecter { + return &CadenceRuntimeProvider_Expecter{mock: &_m.Mock} +} + +// BorrowCadenceRuntime provides a mock function for the type CadenceRuntimeProvider +func (_mock *CadenceRuntimeProvider) BorrowCadenceRuntime() environment.ReusableCadenceRuntime { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for BorrowCadenceRuntime") + } + + var r0 environment.ReusableCadenceRuntime + if returnFunc, ok := ret.Get(0).(func() environment.ReusableCadenceRuntime); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(environment.ReusableCadenceRuntime) + } + } + return r0 +} + +// CadenceRuntimeProvider_BorrowCadenceRuntime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BorrowCadenceRuntime' +type CadenceRuntimeProvider_BorrowCadenceRuntime_Call struct { + *mock.Call +} + +// BorrowCadenceRuntime is a helper method to define mock.On call +func (_e *CadenceRuntimeProvider_Expecter) BorrowCadenceRuntime() *CadenceRuntimeProvider_BorrowCadenceRuntime_Call { + return &CadenceRuntimeProvider_BorrowCadenceRuntime_Call{Call: _e.mock.On("BorrowCadenceRuntime")} +} + +func (_c *CadenceRuntimeProvider_BorrowCadenceRuntime_Call) Run(run func()) *CadenceRuntimeProvider_BorrowCadenceRuntime_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CadenceRuntimeProvider_BorrowCadenceRuntime_Call) Return(reusableCadenceRuntime environment.ReusableCadenceRuntime) *CadenceRuntimeProvider_BorrowCadenceRuntime_Call { + _c.Call.Return(reusableCadenceRuntime) + return _c +} + +func (_c *CadenceRuntimeProvider_BorrowCadenceRuntime_Call) RunAndReturn(run func() environment.ReusableCadenceRuntime) *CadenceRuntimeProvider_BorrowCadenceRuntime_Call { + _c.Call.Return(run) + return _c +} + +// ReturnCadenceRuntime provides a mock function for the type CadenceRuntimeProvider +func (_mock *CadenceRuntimeProvider) ReturnCadenceRuntime(reusable environment.ReusableCadenceRuntime) { + _mock.Called(reusable) + return +} + +// CadenceRuntimeProvider_ReturnCadenceRuntime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReturnCadenceRuntime' +type CadenceRuntimeProvider_ReturnCadenceRuntime_Call struct { + *mock.Call +} + +// ReturnCadenceRuntime is a helper method to define mock.On call +// - reusable environment.ReusableCadenceRuntime +func (_e *CadenceRuntimeProvider_Expecter) ReturnCadenceRuntime(reusable interface{}) *CadenceRuntimeProvider_ReturnCadenceRuntime_Call { + return &CadenceRuntimeProvider_ReturnCadenceRuntime_Call{Call: _e.mock.On("ReturnCadenceRuntime", reusable)} +} + +func (_c *CadenceRuntimeProvider_ReturnCadenceRuntime_Call) Run(run func(reusable environment.ReusableCadenceRuntime)) *CadenceRuntimeProvider_ReturnCadenceRuntime_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.ReusableCadenceRuntime + if args[0] != nil { + arg0 = args[0].(environment.ReusableCadenceRuntime) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CadenceRuntimeProvider_ReturnCadenceRuntime_Call) Return() *CadenceRuntimeProvider_ReturnCadenceRuntime_Call { + _c.Call.Return() + return _c +} + +func (_c *CadenceRuntimeProvider_ReturnCadenceRuntime_Call) RunAndReturn(run func(reusable environment.ReusableCadenceRuntime)) *CadenceRuntimeProvider_ReturnCadenceRuntime_Call { + _c.Run(run) + return _c +} + +// SetEnvironment provides a mock function for the type CadenceRuntimeProvider +func (_mock *CadenceRuntimeProvider) SetEnvironment(env environment.Environment) { + _mock.Called(env) + return +} + +// CadenceRuntimeProvider_SetEnvironment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetEnvironment' +type CadenceRuntimeProvider_SetEnvironment_Call struct { + *mock.Call +} + +// SetEnvironment is a helper method to define mock.On call +// - env environment.Environment +func (_e *CadenceRuntimeProvider_Expecter) SetEnvironment(env interface{}) *CadenceRuntimeProvider_SetEnvironment_Call { + return &CadenceRuntimeProvider_SetEnvironment_Call{Call: _e.mock.On("SetEnvironment", env)} +} + +func (_c *CadenceRuntimeProvider_SetEnvironment_Call) Run(run func(env environment.Environment)) *CadenceRuntimeProvider_SetEnvironment_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.Environment + if args[0] != nil { + arg0 = args[0].(environment.Environment) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CadenceRuntimeProvider_SetEnvironment_Call) Return() *CadenceRuntimeProvider_SetEnvironment_Call { + _c.Call.Return() + return _c +} + +func (_c *CadenceRuntimeProvider_SetEnvironment_Call) RunAndReturn(run func(env environment.Environment)) *CadenceRuntimeProvider_SetEnvironment_Call { + _c.Run(run) + return _c +} diff --git a/fvm/environment/mock/contract_function_invoker.go b/fvm/environment/mock/contract_function_invoker.go index 357f29f3bda..5ca07d68a6e 100644 --- a/fvm/environment/mock/contract_function_invoker.go +++ b/fvm/environment/mock/contract_function_invoker.go @@ -1,21 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cadence "github.com/onflow/cadence" - environment "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/cadence" + "github.com/onflow/flow-go/fvm/environment" mock "github.com/stretchr/testify/mock" ) +// NewContractFunctionInvoker creates a new instance of ContractFunctionInvoker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractFunctionInvoker(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractFunctionInvoker { + mock := &ContractFunctionInvoker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ContractFunctionInvoker is an autogenerated mock type for the ContractFunctionInvoker type type ContractFunctionInvoker struct { mock.Mock } -// Invoke provides a mock function with given fields: spec, arguments -func (_m *ContractFunctionInvoker) Invoke(spec environment.ContractFunctionSpec, arguments []cadence.Value) (cadence.Value, error) { - ret := _m.Called(spec, arguments) +type ContractFunctionInvoker_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractFunctionInvoker) EXPECT() *ContractFunctionInvoker_Expecter { + return &ContractFunctionInvoker_Expecter{mock: &_m.Mock} +} + +// Invoke provides a mock function for the type ContractFunctionInvoker +func (_mock *ContractFunctionInvoker) Invoke(spec environment.ContractFunctionSpec, arguments []cadence.Value) (cadence.Value, error) { + ret := _mock.Called(spec, arguments) if len(ret) == 0 { panic("no return value specified for Invoke") @@ -23,36 +47,60 @@ func (_m *ContractFunctionInvoker) Invoke(spec environment.ContractFunctionSpec, var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) (cadence.Value, error)); ok { - return rf(spec, arguments) + if returnFunc, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) (cadence.Value, error)); ok { + return returnFunc(spec, arguments) } - if rf, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) cadence.Value); ok { - r0 = rf(spec, arguments) + if returnFunc, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) cadence.Value); ok { + r0 = returnFunc(spec, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(environment.ContractFunctionSpec, []cadence.Value) error); ok { - r1 = rf(spec, arguments) + if returnFunc, ok := ret.Get(1).(func(environment.ContractFunctionSpec, []cadence.Value) error); ok { + r1 = returnFunc(spec, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewContractFunctionInvoker creates a new instance of ContractFunctionInvoker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewContractFunctionInvoker(t interface { - mock.TestingT - Cleanup(func()) -}) *ContractFunctionInvoker { - mock := &ContractFunctionInvoker{} - mock.Mock.Test(t) +// ContractFunctionInvoker_Invoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Invoke' +type ContractFunctionInvoker_Invoke_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Invoke is a helper method to define mock.On call +// - spec environment.ContractFunctionSpec +// - arguments []cadence.Value +func (_e *ContractFunctionInvoker_Expecter) Invoke(spec interface{}, arguments interface{}) *ContractFunctionInvoker_Invoke_Call { + return &ContractFunctionInvoker_Invoke_Call{Call: _e.mock.On("Invoke", spec, arguments)} +} - return mock +func (_c *ContractFunctionInvoker_Invoke_Call) Run(run func(spec environment.ContractFunctionSpec, arguments []cadence.Value)) *ContractFunctionInvoker_Invoke_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.ContractFunctionSpec + if args[0] != nil { + arg0 = args[0].(environment.ContractFunctionSpec) + } + var arg1 []cadence.Value + if args[1] != nil { + arg1 = args[1].([]cadence.Value) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractFunctionInvoker_Invoke_Call) Return(value cadence.Value, err error) *ContractFunctionInvoker_Invoke_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *ContractFunctionInvoker_Invoke_Call) RunAndReturn(run func(spec environment.ContractFunctionSpec, arguments []cadence.Value) (cadence.Value, error)) *ContractFunctionInvoker_Invoke_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/contract_updater.go b/fvm/environment/mock/contract_updater.go index 99a545f3f7e..7d595a525d3 100644 --- a/fvm/environment/mock/contract_updater.go +++ b/fvm/environment/mock/contract_updater.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - environment "github.com/onflow/flow-go/fvm/environment" - + "github.com/onflow/cadence/common" + "github.com/onflow/flow-go/fvm/environment" mock "github.com/stretchr/testify/mock" ) +// NewContractUpdater creates a new instance of ContractUpdater. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractUpdater(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractUpdater { + mock := &ContractUpdater{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ContractUpdater is an autogenerated mock type for the ContractUpdater type type ContractUpdater struct { mock.Mock } -// Commit provides a mock function with no fields -func (_m *ContractUpdater) Commit() (environment.ContractUpdates, error) { - ret := _m.Called() +type ContractUpdater_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractUpdater) EXPECT() *ContractUpdater_Expecter { + return &ContractUpdater_Expecter{mock: &_m.Mock} +} + +// Commit provides a mock function for the type ContractUpdater +func (_mock *ContractUpdater) Commit() (environment.ContractUpdates, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Commit") @@ -24,75 +47,186 @@ func (_m *ContractUpdater) Commit() (environment.ContractUpdates, error) { var r0 environment.ContractUpdates var r1 error - if rf, ok := ret.Get(0).(func() (environment.ContractUpdates, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (environment.ContractUpdates, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() environment.ContractUpdates); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() environment.ContractUpdates); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(environment.ContractUpdates) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// RemoveAccountContractCode provides a mock function with given fields: location -func (_m *ContractUpdater) RemoveAccountContractCode(location common.AddressLocation) error { - ret := _m.Called(location) +// ContractUpdater_Commit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Commit' +type ContractUpdater_Commit_Call struct { + *mock.Call +} + +// Commit is a helper method to define mock.On call +func (_e *ContractUpdater_Expecter) Commit() *ContractUpdater_Commit_Call { + return &ContractUpdater_Commit_Call{Call: _e.mock.On("Commit")} +} + +func (_c *ContractUpdater_Commit_Call) Run(run func()) *ContractUpdater_Commit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractUpdater_Commit_Call) Return(contractUpdates environment.ContractUpdates, err error) *ContractUpdater_Commit_Call { + _c.Call.Return(contractUpdates, err) + return _c +} + +func (_c *ContractUpdater_Commit_Call) RunAndReturn(run func() (environment.ContractUpdates, error)) *ContractUpdater_Commit_Call { + _c.Call.Return(run) + return _c +} + +// RemoveAccountContractCode provides a mock function for the type ContractUpdater +func (_mock *ContractUpdater) RemoveAccountContractCode(location common.AddressLocation) error { + ret := _mock.Called(location) if len(ret) == 0 { panic("no return value specified for RemoveAccountContractCode") } var r0 error - if rf, ok := ret.Get(0).(func(common.AddressLocation) error); ok { - r0 = rf(location) + if returnFunc, ok := ret.Get(0).(func(common.AddressLocation) error); ok { + r0 = returnFunc(location) } else { r0 = ret.Error(0) } - return r0 } -// Reset provides a mock function with no fields -func (_m *ContractUpdater) Reset() { - _m.Called() +// ContractUpdater_RemoveAccountContractCode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemoveAccountContractCode' +type ContractUpdater_RemoveAccountContractCode_Call struct { + *mock.Call +} + +// RemoveAccountContractCode is a helper method to define mock.On call +// - location common.AddressLocation +func (_e *ContractUpdater_Expecter) RemoveAccountContractCode(location interface{}) *ContractUpdater_RemoveAccountContractCode_Call { + return &ContractUpdater_RemoveAccountContractCode_Call{Call: _e.mock.On("RemoveAccountContractCode", location)} } -// UpdateAccountContractCode provides a mock function with given fields: location, code -func (_m *ContractUpdater) UpdateAccountContractCode(location common.AddressLocation, code []byte) error { - ret := _m.Called(location, code) +func (_c *ContractUpdater_RemoveAccountContractCode_Call) Run(run func(location common.AddressLocation)) *ContractUpdater_RemoveAccountContractCode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.AddressLocation + if args[0] != nil { + arg0 = args[0].(common.AddressLocation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ContractUpdater_RemoveAccountContractCode_Call) Return(err error) *ContractUpdater_RemoveAccountContractCode_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ContractUpdater_RemoveAccountContractCode_Call) RunAndReturn(run func(location common.AddressLocation) error) *ContractUpdater_RemoveAccountContractCode_Call { + _c.Call.Return(run) + return _c +} + +// Reset provides a mock function for the type ContractUpdater +func (_mock *ContractUpdater) Reset() { + _mock.Called() + return +} + +// ContractUpdater_Reset_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reset' +type ContractUpdater_Reset_Call struct { + *mock.Call +} + +// Reset is a helper method to define mock.On call +func (_e *ContractUpdater_Expecter) Reset() *ContractUpdater_Reset_Call { + return &ContractUpdater_Reset_Call{Call: _e.mock.On("Reset")} +} + +func (_c *ContractUpdater_Reset_Call) Run(run func()) *ContractUpdater_Reset_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractUpdater_Reset_Call) Return() *ContractUpdater_Reset_Call { + _c.Call.Return() + return _c +} + +func (_c *ContractUpdater_Reset_Call) RunAndReturn(run func()) *ContractUpdater_Reset_Call { + _c.Run(run) + return _c +} + +// UpdateAccountContractCode provides a mock function for the type ContractUpdater +func (_mock *ContractUpdater) UpdateAccountContractCode(location common.AddressLocation, code []byte) error { + ret := _mock.Called(location, code) if len(ret) == 0 { panic("no return value specified for UpdateAccountContractCode") } var r0 error - if rf, ok := ret.Get(0).(func(common.AddressLocation, []byte) error); ok { - r0 = rf(location, code) + if returnFunc, ok := ret.Get(0).(func(common.AddressLocation, []byte) error); ok { + r0 = returnFunc(location, code) } else { r0 = ret.Error(0) } - return r0 } -// NewContractUpdater creates a new instance of ContractUpdater. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewContractUpdater(t interface { - mock.TestingT - Cleanup(func()) -}) *ContractUpdater { - mock := &ContractUpdater{} - mock.Mock.Test(t) +// ContractUpdater_UpdateAccountContractCode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateAccountContractCode' +type ContractUpdater_UpdateAccountContractCode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UpdateAccountContractCode is a helper method to define mock.On call +// - location common.AddressLocation +// - code []byte +func (_e *ContractUpdater_Expecter) UpdateAccountContractCode(location interface{}, code interface{}) *ContractUpdater_UpdateAccountContractCode_Call { + return &ContractUpdater_UpdateAccountContractCode_Call{Call: _e.mock.On("UpdateAccountContractCode", location, code)} +} - return mock +func (_c *ContractUpdater_UpdateAccountContractCode_Call) Run(run func(location common.AddressLocation, code []byte)) *ContractUpdater_UpdateAccountContractCode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.AddressLocation + if args[0] != nil { + arg0 = args[0].(common.AddressLocation) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractUpdater_UpdateAccountContractCode_Call) Return(err error) *ContractUpdater_UpdateAccountContractCode_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ContractUpdater_UpdateAccountContractCode_Call) RunAndReturn(run func(location common.AddressLocation, code []byte) error) *ContractUpdater_UpdateAccountContractCode_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/contract_updater_stubs.go b/fvm/environment/mock/contract_updater_stubs.go index 5579a9b1e92..7bc957497d0 100644 --- a/fvm/environment/mock/contract_updater_stubs.go +++ b/fvm/environment/mock/contract_updater_stubs.go @@ -1,86 +1,179 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cadence "github.com/onflow/cadence" - - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/cadence" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewContractUpdaterStubs creates a new instance of ContractUpdaterStubs. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractUpdaterStubs(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractUpdaterStubs { + mock := &ContractUpdaterStubs{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ContractUpdaterStubs is an autogenerated mock type for the ContractUpdaterStubs type type ContractUpdaterStubs struct { mock.Mock } -// GetAuthorizedAccounts provides a mock function with given fields: path -func (_m *ContractUpdaterStubs) GetAuthorizedAccounts(path cadence.Path) []flow.Address { - ret := _m.Called(path) +type ContractUpdaterStubs_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractUpdaterStubs) EXPECT() *ContractUpdaterStubs_Expecter { + return &ContractUpdaterStubs_Expecter{mock: &_m.Mock} +} + +// GetAuthorizedAccounts provides a mock function for the type ContractUpdaterStubs +func (_mock *ContractUpdaterStubs) GetAuthorizedAccounts(path cadence.Path) []flow.Address { + ret := _mock.Called(path) if len(ret) == 0 { panic("no return value specified for GetAuthorizedAccounts") } var r0 []flow.Address - if rf, ok := ret.Get(0).(func(cadence.Path) []flow.Address); ok { - r0 = rf(path) + if returnFunc, ok := ret.Get(0).(func(cadence.Path) []flow.Address); ok { + r0 = returnFunc(path) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Address) } } - return r0 } -// RestrictedDeploymentEnabled provides a mock function with no fields -func (_m *ContractUpdaterStubs) RestrictedDeploymentEnabled() bool { - ret := _m.Called() +// ContractUpdaterStubs_GetAuthorizedAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizedAccounts' +type ContractUpdaterStubs_GetAuthorizedAccounts_Call struct { + *mock.Call +} + +// GetAuthorizedAccounts is a helper method to define mock.On call +// - path cadence.Path +func (_e *ContractUpdaterStubs_Expecter) GetAuthorizedAccounts(path interface{}) *ContractUpdaterStubs_GetAuthorizedAccounts_Call { + return &ContractUpdaterStubs_GetAuthorizedAccounts_Call{Call: _e.mock.On("GetAuthorizedAccounts", path)} +} + +func (_c *ContractUpdaterStubs_GetAuthorizedAccounts_Call) Run(run func(path cadence.Path)) *ContractUpdaterStubs_GetAuthorizedAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 cadence.Path + if args[0] != nil { + arg0 = args[0].(cadence.Path) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ContractUpdaterStubs_GetAuthorizedAccounts_Call) Return(addresss []flow.Address) *ContractUpdaterStubs_GetAuthorizedAccounts_Call { + _c.Call.Return(addresss) + return _c +} + +func (_c *ContractUpdaterStubs_GetAuthorizedAccounts_Call) RunAndReturn(run func(path cadence.Path) []flow.Address) *ContractUpdaterStubs_GetAuthorizedAccounts_Call { + _c.Call.Return(run) + return _c +} + +// RestrictedDeploymentEnabled provides a mock function for the type ContractUpdaterStubs +func (_mock *ContractUpdaterStubs) RestrictedDeploymentEnabled() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RestrictedDeploymentEnabled") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// RestrictedRemovalEnabled provides a mock function with no fields -func (_m *ContractUpdaterStubs) RestrictedRemovalEnabled() bool { - ret := _m.Called() +// ContractUpdaterStubs_RestrictedDeploymentEnabled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RestrictedDeploymentEnabled' +type ContractUpdaterStubs_RestrictedDeploymentEnabled_Call struct { + *mock.Call +} + +// RestrictedDeploymentEnabled is a helper method to define mock.On call +func (_e *ContractUpdaterStubs_Expecter) RestrictedDeploymentEnabled() *ContractUpdaterStubs_RestrictedDeploymentEnabled_Call { + return &ContractUpdaterStubs_RestrictedDeploymentEnabled_Call{Call: _e.mock.On("RestrictedDeploymentEnabled")} +} + +func (_c *ContractUpdaterStubs_RestrictedDeploymentEnabled_Call) Run(run func()) *ContractUpdaterStubs_RestrictedDeploymentEnabled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractUpdaterStubs_RestrictedDeploymentEnabled_Call) Return(b bool) *ContractUpdaterStubs_RestrictedDeploymentEnabled_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ContractUpdaterStubs_RestrictedDeploymentEnabled_Call) RunAndReturn(run func() bool) *ContractUpdaterStubs_RestrictedDeploymentEnabled_Call { + _c.Call.Return(run) + return _c +} + +// RestrictedRemovalEnabled provides a mock function for the type ContractUpdaterStubs +func (_mock *ContractUpdaterStubs) RestrictedRemovalEnabled() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RestrictedRemovalEnabled") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewContractUpdaterStubs creates a new instance of ContractUpdaterStubs. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewContractUpdaterStubs(t interface { - mock.TestingT - Cleanup(func()) -}) *ContractUpdaterStubs { - mock := &ContractUpdaterStubs{} - mock.Mock.Test(t) +// ContractUpdaterStubs_RestrictedRemovalEnabled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RestrictedRemovalEnabled' +type ContractUpdaterStubs_RestrictedRemovalEnabled_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RestrictedRemovalEnabled is a helper method to define mock.On call +func (_e *ContractUpdaterStubs_Expecter) RestrictedRemovalEnabled() *ContractUpdaterStubs_RestrictedRemovalEnabled_Call { + return &ContractUpdaterStubs_RestrictedRemovalEnabled_Call{Call: _e.mock.On("RestrictedRemovalEnabled")} +} - return mock +func (_c *ContractUpdaterStubs_RestrictedRemovalEnabled_Call) Run(run func()) *ContractUpdaterStubs_RestrictedRemovalEnabled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractUpdaterStubs_RestrictedRemovalEnabled_Call) Return(b bool) *ContractUpdaterStubs_RestrictedRemovalEnabled_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ContractUpdaterStubs_RestrictedRemovalEnabled_Call) RunAndReturn(run func() bool) *ContractUpdaterStubs_RestrictedRemovalEnabled_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/crypto_library.go b/fvm/environment/mock/crypto_library.go index d0d5d91e039..4fb5308b38a 100644 --- a/fvm/environment/mock/crypto_library.go +++ b/fvm/environment/mock/crypto_library.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - runtime "github.com/onflow/cadence/runtime" + "github.com/onflow/cadence/runtime" mock "github.com/stretchr/testify/mock" ) +// NewCryptoLibrary creates a new instance of CryptoLibrary. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCryptoLibrary(t interface { + mock.TestingT + Cleanup(func()) +}) *CryptoLibrary { + mock := &CryptoLibrary{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CryptoLibrary is an autogenerated mock type for the CryptoLibrary type type CryptoLibrary struct { mock.Mock } -// BLSAggregatePublicKeys provides a mock function with given fields: keys -func (_m *CryptoLibrary) BLSAggregatePublicKeys(keys []*runtime.PublicKey) (*runtime.PublicKey, error) { - ret := _m.Called(keys) +type CryptoLibrary_Expecter struct { + mock *mock.Mock +} + +func (_m *CryptoLibrary) EXPECT() *CryptoLibrary_Expecter { + return &CryptoLibrary_Expecter{mock: &_m.Mock} +} + +// BLSAggregatePublicKeys provides a mock function for the type CryptoLibrary +func (_mock *CryptoLibrary) BLSAggregatePublicKeys(keys []*runtime.PublicKey) (*runtime.PublicKey, error) { + ret := _mock.Called(keys) if len(ret) == 0 { panic("no return value specified for BLSAggregatePublicKeys") @@ -22,29 +46,61 @@ func (_m *CryptoLibrary) BLSAggregatePublicKeys(keys []*runtime.PublicKey) (*run var r0 *runtime.PublicKey var r1 error - if rf, ok := ret.Get(0).(func([]*runtime.PublicKey) (*runtime.PublicKey, error)); ok { - return rf(keys) + if returnFunc, ok := ret.Get(0).(func([]*runtime.PublicKey) (*runtime.PublicKey, error)); ok { + return returnFunc(keys) } - if rf, ok := ret.Get(0).(func([]*runtime.PublicKey) *runtime.PublicKey); ok { - r0 = rf(keys) + if returnFunc, ok := ret.Get(0).(func([]*runtime.PublicKey) *runtime.PublicKey); ok { + r0 = returnFunc(keys) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*runtime.PublicKey) } } - - if rf, ok := ret.Get(1).(func([]*runtime.PublicKey) error); ok { - r1 = rf(keys) + if returnFunc, ok := ret.Get(1).(func([]*runtime.PublicKey) error); ok { + r1 = returnFunc(keys) } else { r1 = ret.Error(1) } - return r0, r1 } -// BLSAggregateSignatures provides a mock function with given fields: sigs -func (_m *CryptoLibrary) BLSAggregateSignatures(sigs [][]byte) ([]byte, error) { - ret := _m.Called(sigs) +// CryptoLibrary_BLSAggregatePublicKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BLSAggregatePublicKeys' +type CryptoLibrary_BLSAggregatePublicKeys_Call struct { + *mock.Call +} + +// BLSAggregatePublicKeys is a helper method to define mock.On call +// - keys []*runtime.PublicKey +func (_e *CryptoLibrary_Expecter) BLSAggregatePublicKeys(keys interface{}) *CryptoLibrary_BLSAggregatePublicKeys_Call { + return &CryptoLibrary_BLSAggregatePublicKeys_Call{Call: _e.mock.On("BLSAggregatePublicKeys", keys)} +} + +func (_c *CryptoLibrary_BLSAggregatePublicKeys_Call) Run(run func(keys []*runtime.PublicKey)) *CryptoLibrary_BLSAggregatePublicKeys_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []*runtime.PublicKey + if args[0] != nil { + arg0 = args[0].([]*runtime.PublicKey) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CryptoLibrary_BLSAggregatePublicKeys_Call) Return(v *runtime.PublicKey, err error) *CryptoLibrary_BLSAggregatePublicKeys_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *CryptoLibrary_BLSAggregatePublicKeys_Call) RunAndReturn(run func(keys []*runtime.PublicKey) (*runtime.PublicKey, error)) *CryptoLibrary_BLSAggregatePublicKeys_Call { + _c.Call.Return(run) + return _c +} + +// BLSAggregateSignatures provides a mock function for the type CryptoLibrary +func (_mock *CryptoLibrary) BLSAggregateSignatures(sigs [][]byte) ([]byte, error) { + ret := _mock.Called(sigs) if len(ret) == 0 { panic("no return value specified for BLSAggregateSignatures") @@ -52,29 +108,61 @@ func (_m *CryptoLibrary) BLSAggregateSignatures(sigs [][]byte) ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func([][]byte) ([]byte, error)); ok { - return rf(sigs) + if returnFunc, ok := ret.Get(0).(func([][]byte) ([]byte, error)); ok { + return returnFunc(sigs) } - if rf, ok := ret.Get(0).(func([][]byte) []byte); ok { - r0 = rf(sigs) + if returnFunc, ok := ret.Get(0).(func([][]byte) []byte); ok { + r0 = returnFunc(sigs) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func([][]byte) error); ok { - r1 = rf(sigs) + if returnFunc, ok := ret.Get(1).(func([][]byte) error); ok { + r1 = returnFunc(sigs) } else { r1 = ret.Error(1) } - return r0, r1 } -// BLSVerifyPOP provides a mock function with given fields: pk, sig -func (_m *CryptoLibrary) BLSVerifyPOP(pk *runtime.PublicKey, sig []byte) (bool, error) { - ret := _m.Called(pk, sig) +// CryptoLibrary_BLSAggregateSignatures_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BLSAggregateSignatures' +type CryptoLibrary_BLSAggregateSignatures_Call struct { + *mock.Call +} + +// BLSAggregateSignatures is a helper method to define mock.On call +// - sigs [][]byte +func (_e *CryptoLibrary_Expecter) BLSAggregateSignatures(sigs interface{}) *CryptoLibrary_BLSAggregateSignatures_Call { + return &CryptoLibrary_BLSAggregateSignatures_Call{Call: _e.mock.On("BLSAggregateSignatures", sigs)} +} + +func (_c *CryptoLibrary_BLSAggregateSignatures_Call) Run(run func(sigs [][]byte)) *CryptoLibrary_BLSAggregateSignatures_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 [][]byte + if args[0] != nil { + arg0 = args[0].([][]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CryptoLibrary_BLSAggregateSignatures_Call) Return(bytes []byte, err error) *CryptoLibrary_BLSAggregateSignatures_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *CryptoLibrary_BLSAggregateSignatures_Call) RunAndReturn(run func(sigs [][]byte) ([]byte, error)) *CryptoLibrary_BLSAggregateSignatures_Call { + _c.Call.Return(run) + return _c +} + +// BLSVerifyPOP provides a mock function for the type CryptoLibrary +func (_mock *CryptoLibrary) BLSVerifyPOP(pk *runtime.PublicKey, sig []byte) (bool, error) { + ret := _mock.Called(pk, sig) if len(ret) == 0 { panic("no return value specified for BLSVerifyPOP") @@ -82,27 +170,65 @@ func (_m *CryptoLibrary) BLSVerifyPOP(pk *runtime.PublicKey, sig []byte) (bool, var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) (bool, error)); ok { - return rf(pk, sig) + if returnFunc, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) (bool, error)); ok { + return returnFunc(pk, sig) } - if rf, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) bool); ok { - r0 = rf(pk, sig) + if returnFunc, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) bool); ok { + r0 = returnFunc(pk, sig) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*runtime.PublicKey, []byte) error); ok { - r1 = rf(pk, sig) + if returnFunc, ok := ret.Get(1).(func(*runtime.PublicKey, []byte) error); ok { + r1 = returnFunc(pk, sig) } else { r1 = ret.Error(1) } - return r0, r1 } -// Hash provides a mock function with given fields: data, tag, hashAlgorithm -func (_m *CryptoLibrary) Hash(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm) ([]byte, error) { - ret := _m.Called(data, tag, hashAlgorithm) +// CryptoLibrary_BLSVerifyPOP_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BLSVerifyPOP' +type CryptoLibrary_BLSVerifyPOP_Call struct { + *mock.Call +} + +// BLSVerifyPOP is a helper method to define mock.On call +// - pk *runtime.PublicKey +// - sig []byte +func (_e *CryptoLibrary_Expecter) BLSVerifyPOP(pk interface{}, sig interface{}) *CryptoLibrary_BLSVerifyPOP_Call { + return &CryptoLibrary_BLSVerifyPOP_Call{Call: _e.mock.On("BLSVerifyPOP", pk, sig)} +} + +func (_c *CryptoLibrary_BLSVerifyPOP_Call) Run(run func(pk *runtime.PublicKey, sig []byte)) *CryptoLibrary_BLSVerifyPOP_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *runtime.PublicKey + if args[0] != nil { + arg0 = args[0].(*runtime.PublicKey) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *CryptoLibrary_BLSVerifyPOP_Call) Return(b bool, err error) *CryptoLibrary_BLSVerifyPOP_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *CryptoLibrary_BLSVerifyPOP_Call) RunAndReturn(run func(pk *runtime.PublicKey, sig []byte) (bool, error)) *CryptoLibrary_BLSVerifyPOP_Call { + _c.Call.Return(run) + return _c +} + +// Hash provides a mock function for the type CryptoLibrary +func (_mock *CryptoLibrary) Hash(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm) ([]byte, error) { + ret := _mock.Called(data, tag, hashAlgorithm) if len(ret) == 0 { panic("no return value specified for Hash") @@ -110,47 +236,124 @@ func (_m *CryptoLibrary) Hash(data []byte, tag string, hashAlgorithm runtime.Has var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) ([]byte, error)); ok { - return rf(data, tag, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) ([]byte, error)); ok { + return returnFunc(data, tag, hashAlgorithm) } - if rf, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) []byte); ok { - r0 = rf(data, tag, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) []byte); ok { + r0 = returnFunc(data, tag, hashAlgorithm) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func([]byte, string, runtime.HashAlgorithm) error); ok { - r1 = rf(data, tag, hashAlgorithm) + if returnFunc, ok := ret.Get(1).(func([]byte, string, runtime.HashAlgorithm) error); ok { + r1 = returnFunc(data, tag, hashAlgorithm) } else { r1 = ret.Error(1) } - return r0, r1 } -// ValidatePublicKey provides a mock function with given fields: pk -func (_m *CryptoLibrary) ValidatePublicKey(pk *runtime.PublicKey) error { - ret := _m.Called(pk) +// CryptoLibrary_Hash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Hash' +type CryptoLibrary_Hash_Call struct { + *mock.Call +} + +// Hash is a helper method to define mock.On call +// - data []byte +// - tag string +// - hashAlgorithm runtime.HashAlgorithm +func (_e *CryptoLibrary_Expecter) Hash(data interface{}, tag interface{}, hashAlgorithm interface{}) *CryptoLibrary_Hash_Call { + return &CryptoLibrary_Hash_Call{Call: _e.mock.On("Hash", data, tag, hashAlgorithm)} +} + +func (_c *CryptoLibrary_Hash_Call) Run(run func(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm)) *CryptoLibrary_Hash_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 runtime.HashAlgorithm + if args[2] != nil { + arg2 = args[2].(runtime.HashAlgorithm) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *CryptoLibrary_Hash_Call) Return(bytes []byte, err error) *CryptoLibrary_Hash_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *CryptoLibrary_Hash_Call) RunAndReturn(run func(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm) ([]byte, error)) *CryptoLibrary_Hash_Call { + _c.Call.Return(run) + return _c +} + +// ValidatePublicKey provides a mock function for the type CryptoLibrary +func (_mock *CryptoLibrary) ValidatePublicKey(pk *runtime.PublicKey) error { + ret := _mock.Called(pk) if len(ret) == 0 { panic("no return value specified for ValidatePublicKey") } var r0 error - if rf, ok := ret.Get(0).(func(*runtime.PublicKey) error); ok { - r0 = rf(pk) + if returnFunc, ok := ret.Get(0).(func(*runtime.PublicKey) error); ok { + r0 = returnFunc(pk) } else { r0 = ret.Error(0) } - return r0 } -// VerifySignature provides a mock function with given fields: signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm -func (_m *CryptoLibrary) VerifySignature(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm) (bool, error) { - ret := _m.Called(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) +// CryptoLibrary_ValidatePublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidatePublicKey' +type CryptoLibrary_ValidatePublicKey_Call struct { + *mock.Call +} + +// ValidatePublicKey is a helper method to define mock.On call +// - pk *runtime.PublicKey +func (_e *CryptoLibrary_Expecter) ValidatePublicKey(pk interface{}) *CryptoLibrary_ValidatePublicKey_Call { + return &CryptoLibrary_ValidatePublicKey_Call{Call: _e.mock.On("ValidatePublicKey", pk)} +} + +func (_c *CryptoLibrary_ValidatePublicKey_Call) Run(run func(pk *runtime.PublicKey)) *CryptoLibrary_ValidatePublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *runtime.PublicKey + if args[0] != nil { + arg0 = args[0].(*runtime.PublicKey) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CryptoLibrary_ValidatePublicKey_Call) Return(err error) *CryptoLibrary_ValidatePublicKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CryptoLibrary_ValidatePublicKey_Call) RunAndReturn(run func(pk *runtime.PublicKey) error) *CryptoLibrary_ValidatePublicKey_Call { + _c.Call.Return(run) + return _c +} + +// VerifySignature provides a mock function for the type CryptoLibrary +func (_mock *CryptoLibrary) VerifySignature(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm) (bool, error) { + ret := _mock.Called(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) if len(ret) == 0 { panic("no return value specified for VerifySignature") @@ -158,34 +361,82 @@ func (_m *CryptoLibrary) VerifySignature(signature []byte, tag string, signedDat var r0 bool var r1 error - if rf, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) (bool, error)); ok { - return rf(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) (bool, error)); ok { + return returnFunc(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) } - if rf, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) bool); ok { - r0 = rf(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) bool); ok { + r0 = returnFunc(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) error); ok { - r1 = rf(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) + if returnFunc, ok := ret.Get(1).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) error); ok { + r1 = returnFunc(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewCryptoLibrary creates a new instance of CryptoLibrary. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCryptoLibrary(t interface { - mock.TestingT - Cleanup(func()) -}) *CryptoLibrary { - mock := &CryptoLibrary{} - mock.Mock.Test(t) +// CryptoLibrary_VerifySignature_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifySignature' +type CryptoLibrary_VerifySignature_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VerifySignature is a helper method to define mock.On call +// - signature []byte +// - tag string +// - signedData []byte +// - publicKey []byte +// - signatureAlgorithm runtime.SignatureAlgorithm +// - hashAlgorithm runtime.HashAlgorithm +func (_e *CryptoLibrary_Expecter) VerifySignature(signature interface{}, tag interface{}, signedData interface{}, publicKey interface{}, signatureAlgorithm interface{}, hashAlgorithm interface{}) *CryptoLibrary_VerifySignature_Call { + return &CryptoLibrary_VerifySignature_Call{Call: _e.mock.On("VerifySignature", signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm)} +} - return mock +func (_c *CryptoLibrary_VerifySignature_Call) Run(run func(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm)) *CryptoLibrary_VerifySignature_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 []byte + if args[3] != nil { + arg3 = args[3].([]byte) + } + var arg4 runtime.SignatureAlgorithm + if args[4] != nil { + arg4 = args[4].(runtime.SignatureAlgorithm) + } + var arg5 runtime.HashAlgorithm + if args[5] != nil { + arg5 = args[5].(runtime.HashAlgorithm) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + ) + }) + return _c +} + +func (_c *CryptoLibrary_VerifySignature_Call) Return(b bool, err error) *CryptoLibrary_VerifySignature_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *CryptoLibrary_VerifySignature_Call) RunAndReturn(run func(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm) (bool, error)) *CryptoLibrary_VerifySignature_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/entropy_provider.go b/fvm/environment/mock/entropy_provider.go index 75c94d26177..480efaea216 100644 --- a/fvm/environment/mock/entropy_provider.go +++ b/fvm/environment/mock/entropy_provider.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewEntropyProvider creates a new instance of EntropyProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEntropyProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *EntropyProvider { + mock := &EntropyProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EntropyProvider is an autogenerated mock type for the EntropyProvider type type EntropyProvider struct { mock.Mock } -// RandomSource provides a mock function with no fields -func (_m *EntropyProvider) RandomSource() ([]byte, error) { - ret := _m.Called() +type EntropyProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *EntropyProvider) EXPECT() *EntropyProvider_Expecter { + return &EntropyProvider_Expecter{mock: &_m.Mock} +} + +// RandomSource provides a mock function for the type EntropyProvider +func (_mock *EntropyProvider) RandomSource() ([]byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RandomSource") @@ -19,36 +45,47 @@ func (_m *EntropyProvider) RandomSource() ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func() ([]byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEntropyProvider creates a new instance of EntropyProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEntropyProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *EntropyProvider { - mock := &EntropyProvider{} - mock.Mock.Test(t) +// EntropyProvider_RandomSource_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RandomSource' +type EntropyProvider_RandomSource_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RandomSource is a helper method to define mock.On call +func (_e *EntropyProvider_Expecter) RandomSource() *EntropyProvider_RandomSource_Call { + return &EntropyProvider_RandomSource_Call{Call: _e.mock.On("RandomSource")} +} - return mock +func (_c *EntropyProvider_RandomSource_Call) Run(run func()) *EntropyProvider_RandomSource_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EntropyProvider_RandomSource_Call) Return(bytes []byte, err error) *EntropyProvider_RandomSource_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *EntropyProvider_RandomSource_Call) RunAndReturn(run func() ([]byte, error)) *EntropyProvider_RandomSource_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/environment.go b/fvm/environment/mock/environment.go index 2c7809dc48f..510bcedb796 100644 --- a/fvm/environment/mock/environment.go +++ b/fvm/environment/mock/environment.go @@ -1,52 +1,62 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - atree "github.com/onflow/atree" - ast "github.com/onflow/cadence/ast" - - attribute "go.opentelemetry.io/otel/attribute" - - cadence "github.com/onflow/cadence" - - common "github.com/onflow/cadence/common" - - environment "github.com/onflow/flow-go/fvm/environment" - - flow "github.com/onflow/flow-go/model/flow" - - fvmruntime "github.com/onflow/flow-go/fvm/runtime" - - interpreter "github.com/onflow/cadence/interpreter" - - meter "github.com/onflow/flow-go/fvm/meter" - + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/onflow/atree" + "github.com/onflow/cadence" + "github.com/onflow/cadence/ast" + common0 "github.com/onflow/cadence/common" + "github.com/onflow/cadence/interpreter" + "github.com/onflow/cadence/runtime" + "github.com/onflow/cadence/sema" + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm/types" + "github.com/onflow/flow-go/fvm/meter" + "github.com/onflow/flow-go/fvm/tracing" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/trace" + "github.com/rs/zerolog" mock "github.com/stretchr/testify/mock" + "go.opentelemetry.io/otel/attribute" + trace0 "go.opentelemetry.io/otel/trace" +) - oteltrace "go.opentelemetry.io/otel/trace" - - runtime "github.com/onflow/cadence/runtime" - - sema "github.com/onflow/cadence/sema" - - time "time" - - trace "github.com/onflow/flow-go/module/trace" +// NewEnvironment creates a new instance of Environment. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEnvironment(t interface { + mock.TestingT + Cleanup(func()) +}) *Environment { + mock := &Environment{} + mock.Mock.Test(t) - tracing "github.com/onflow/flow-go/fvm/tracing" + t.Cleanup(func() { mock.AssertExpectations(t) }) - zerolog "github.com/rs/zerolog" -) + return mock +} // Environment is an autogenerated mock type for the Environment type type Environment struct { mock.Mock } -// AccountKeysCount provides a mock function with given fields: address -func (_m *Environment) AccountKeysCount(address runtime.Address) (uint32, error) { - ret := _m.Called(address) +type Environment_Expecter struct { + mock *mock.Mock +} + +func (_m *Environment) EXPECT() *Environment_Expecter { + return &Environment_Expecter{mock: &_m.Mock} +} + +// AccountKeysCount provides a mock function for the type Environment +func (_mock *Environment) AccountKeysCount(address runtime.Address) (uint32, error) { + ret := _mock.Called(address) if len(ret) == 0 { panic("no return value specified for AccountKeysCount") @@ -54,27 +64,59 @@ func (_m *Environment) AccountKeysCount(address runtime.Address) (uint32, error) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address) (uint32, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(runtime.Address) (uint32, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(runtime.Address) uint32); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(runtime.Address) uint32); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(uint32) } - - if rf, ok := ret.Get(1).(func(runtime.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(runtime.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// AccountsStorageCapacity provides a mock function with given fields: addresses, payer, maxTxFees -func (_m *Environment) AccountsStorageCapacity(addresses []flow.Address, payer flow.Address, maxTxFees uint64) (cadence.Value, error) { - ret := _m.Called(addresses, payer, maxTxFees) +// Environment_AccountKeysCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AccountKeysCount' +type Environment_AccountKeysCount_Call struct { + *mock.Call +} + +// AccountKeysCount is a helper method to define mock.On call +// - address runtime.Address +func (_e *Environment_Expecter) AccountKeysCount(address interface{}) *Environment_AccountKeysCount_Call { + return &Environment_AccountKeysCount_Call{Call: _e.mock.On("AccountKeysCount", address)} +} + +func (_c *Environment_AccountKeysCount_Call) Run(run func(address runtime.Address)) *Environment_AccountKeysCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_AccountKeysCount_Call) Return(v uint32, err error) *Environment_AccountKeysCount_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_AccountKeysCount_Call) RunAndReturn(run func(address runtime.Address) (uint32, error)) *Environment_AccountKeysCount_Call { + _c.Call.Return(run) + return _c +} + +// AccountsStorageCapacity provides a mock function for the type Environment +func (_mock *Environment) AccountsStorageCapacity(addresses []flow.Address, payer flow.Address, maxTxFees uint64) (cadence.Value, error) { + ret := _mock.Called(addresses, payer, maxTxFees) if len(ret) == 0 { panic("no return value specified for AccountsStorageCapacity") @@ -82,29 +124,73 @@ func (_m *Environment) AccountsStorageCapacity(addresses []flow.Address, payer f var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func([]flow.Address, flow.Address, uint64) (cadence.Value, error)); ok { - return rf(addresses, payer, maxTxFees) + if returnFunc, ok := ret.Get(0).(func([]flow.Address, flow.Address, uint64) (cadence.Value, error)); ok { + return returnFunc(addresses, payer, maxTxFees) } - if rf, ok := ret.Get(0).(func([]flow.Address, flow.Address, uint64) cadence.Value); ok { - r0 = rf(addresses, payer, maxTxFees) + if returnFunc, ok := ret.Get(0).(func([]flow.Address, flow.Address, uint64) cadence.Value); ok { + r0 = returnFunc(addresses, payer, maxTxFees) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func([]flow.Address, flow.Address, uint64) error); ok { - r1 = rf(addresses, payer, maxTxFees) + if returnFunc, ok := ret.Get(1).(func([]flow.Address, flow.Address, uint64) error); ok { + r1 = returnFunc(addresses, payer, maxTxFees) } else { r1 = ret.Error(1) } - return r0, r1 } -// AddAccountKey provides a mock function with given fields: address, publicKey, hashAlgo, weight -func (_m *Environment) AddAccountKey(address runtime.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int) (*runtime.AccountKey, error) { - ret := _m.Called(address, publicKey, hashAlgo, weight) +// Environment_AccountsStorageCapacity_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AccountsStorageCapacity' +type Environment_AccountsStorageCapacity_Call struct { + *mock.Call +} + +// AccountsStorageCapacity is a helper method to define mock.On call +// - addresses []flow.Address +// - payer flow.Address +// - maxTxFees uint64 +func (_e *Environment_Expecter) AccountsStorageCapacity(addresses interface{}, payer interface{}, maxTxFees interface{}) *Environment_AccountsStorageCapacity_Call { + return &Environment_AccountsStorageCapacity_Call{Call: _e.mock.On("AccountsStorageCapacity", addresses, payer, maxTxFees)} +} + +func (_c *Environment_AccountsStorageCapacity_Call) Run(run func(addresses []flow.Address, payer flow.Address, maxTxFees uint64)) *Environment_AccountsStorageCapacity_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.Address + if args[0] != nil { + arg0 = args[0].([]flow.Address) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Environment_AccountsStorageCapacity_Call) Return(value cadence.Value, err error) *Environment_AccountsStorageCapacity_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Environment_AccountsStorageCapacity_Call) RunAndReturn(run func(addresses []flow.Address, payer flow.Address, maxTxFees uint64) (cadence.Value, error)) *Environment_AccountsStorageCapacity_Call { + _c.Call.Return(run) + return _c +} + +// AddAccountKey provides a mock function for the type Environment +func (_mock *Environment) AddAccountKey(address runtime.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int) (*runtime.AccountKey, error) { + ret := _mock.Called(address, publicKey, hashAlgo, weight) if len(ret) == 0 { panic("no return value specified for AddAccountKey") @@ -112,29 +198,79 @@ func (_m *Environment) AddAccountKey(address runtime.Address, publicKey *runtime var r0 *runtime.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) (*runtime.AccountKey, error)); ok { - return rf(address, publicKey, hashAlgo, weight) + if returnFunc, ok := ret.Get(0).(func(runtime.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) (*runtime.AccountKey, error)); ok { + return returnFunc(address, publicKey, hashAlgo, weight) } - if rf, ok := ret.Get(0).(func(runtime.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) *runtime.AccountKey); ok { - r0 = rf(address, publicKey, hashAlgo, weight) + if returnFunc, ok := ret.Get(0).(func(runtime.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) *runtime.AccountKey); ok { + r0 = returnFunc(address, publicKey, hashAlgo, weight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*runtime.AccountKey) } } - - if rf, ok := ret.Get(1).(func(runtime.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) error); ok { - r1 = rf(address, publicKey, hashAlgo, weight) + if returnFunc, ok := ret.Get(1).(func(runtime.Address, *runtime.PublicKey, runtime.HashAlgorithm, int) error); ok { + r1 = returnFunc(address, publicKey, hashAlgo, weight) } else { r1 = ret.Error(1) } - return r0, r1 } -// AllocateSlabIndex provides a mock function with given fields: owner -func (_m *Environment) AllocateSlabIndex(owner []byte) (atree.SlabIndex, error) { - ret := _m.Called(owner) +// Environment_AddAccountKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddAccountKey' +type Environment_AddAccountKey_Call struct { + *mock.Call +} + +// AddAccountKey is a helper method to define mock.On call +// - address runtime.Address +// - publicKey *runtime.PublicKey +// - hashAlgo runtime.HashAlgorithm +// - weight int +func (_e *Environment_Expecter) AddAccountKey(address interface{}, publicKey interface{}, hashAlgo interface{}, weight interface{}) *Environment_AddAccountKey_Call { + return &Environment_AddAccountKey_Call{Call: _e.mock.On("AddAccountKey", address, publicKey, hashAlgo, weight)} +} + +func (_c *Environment_AddAccountKey_Call) Run(run func(address runtime.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int)) *Environment_AddAccountKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) + } + var arg1 *runtime.PublicKey + if args[1] != nil { + arg1 = args[1].(*runtime.PublicKey) + } + var arg2 runtime.HashAlgorithm + if args[2] != nil { + arg2 = args[2].(runtime.HashAlgorithm) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Environment_AddAccountKey_Call) Return(v *runtime.AccountKey, err error) *Environment_AddAccountKey_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_AddAccountKey_Call) RunAndReturn(run func(address runtime.Address, publicKey *runtime.PublicKey, hashAlgo runtime.HashAlgorithm, weight int) (*runtime.AccountKey, error)) *Environment_AddAccountKey_Call { + _c.Call.Return(run) + return _c +} + +// AllocateSlabIndex provides a mock function for the type Environment +func (_mock *Environment) AllocateSlabIndex(owner []byte) (atree.SlabIndex, error) { + ret := _mock.Called(owner) if len(ret) == 0 { panic("no return value specified for AllocateSlabIndex") @@ -142,29 +278,61 @@ func (_m *Environment) AllocateSlabIndex(owner []byte) (atree.SlabIndex, error) var r0 atree.SlabIndex var r1 error - if rf, ok := ret.Get(0).(func([]byte) (atree.SlabIndex, error)); ok { - return rf(owner) + if returnFunc, ok := ret.Get(0).(func([]byte) (atree.SlabIndex, error)); ok { + return returnFunc(owner) } - if rf, ok := ret.Get(0).(func([]byte) atree.SlabIndex); ok { - r0 = rf(owner) + if returnFunc, ok := ret.Get(0).(func([]byte) atree.SlabIndex); ok { + r0 = returnFunc(owner) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(atree.SlabIndex) } } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(owner) + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(owner) } else { r1 = ret.Error(1) } - return r0, r1 } -// BLSAggregatePublicKeys provides a mock function with given fields: publicKeys -func (_m *Environment) BLSAggregatePublicKeys(publicKeys []*runtime.PublicKey) (*runtime.PublicKey, error) { - ret := _m.Called(publicKeys) +// Environment_AllocateSlabIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllocateSlabIndex' +type Environment_AllocateSlabIndex_Call struct { + *mock.Call +} + +// AllocateSlabIndex is a helper method to define mock.On call +// - owner []byte +func (_e *Environment_Expecter) AllocateSlabIndex(owner interface{}) *Environment_AllocateSlabIndex_Call { + return &Environment_AllocateSlabIndex_Call{Call: _e.mock.On("AllocateSlabIndex", owner)} +} + +func (_c *Environment_AllocateSlabIndex_Call) Run(run func(owner []byte)) *Environment_AllocateSlabIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_AllocateSlabIndex_Call) Return(slabIndex atree.SlabIndex, err error) *Environment_AllocateSlabIndex_Call { + _c.Call.Return(slabIndex, err) + return _c +} + +func (_c *Environment_AllocateSlabIndex_Call) RunAndReturn(run func(owner []byte) (atree.SlabIndex, error)) *Environment_AllocateSlabIndex_Call { + _c.Call.Return(run) + return _c +} + +// BLSAggregatePublicKeys provides a mock function for the type Environment +func (_mock *Environment) BLSAggregatePublicKeys(publicKeys []*runtime.PublicKey) (*runtime.PublicKey, error) { + ret := _mock.Called(publicKeys) if len(ret) == 0 { panic("no return value specified for BLSAggregatePublicKeys") @@ -172,29 +340,61 @@ func (_m *Environment) BLSAggregatePublicKeys(publicKeys []*runtime.PublicKey) ( var r0 *runtime.PublicKey var r1 error - if rf, ok := ret.Get(0).(func([]*runtime.PublicKey) (*runtime.PublicKey, error)); ok { - return rf(publicKeys) + if returnFunc, ok := ret.Get(0).(func([]*runtime.PublicKey) (*runtime.PublicKey, error)); ok { + return returnFunc(publicKeys) } - if rf, ok := ret.Get(0).(func([]*runtime.PublicKey) *runtime.PublicKey); ok { - r0 = rf(publicKeys) + if returnFunc, ok := ret.Get(0).(func([]*runtime.PublicKey) *runtime.PublicKey); ok { + r0 = returnFunc(publicKeys) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*runtime.PublicKey) } } - - if rf, ok := ret.Get(1).(func([]*runtime.PublicKey) error); ok { - r1 = rf(publicKeys) + if returnFunc, ok := ret.Get(1).(func([]*runtime.PublicKey) error); ok { + r1 = returnFunc(publicKeys) } else { r1 = ret.Error(1) } - return r0, r1 } -// BLSAggregateSignatures provides a mock function with given fields: signatures -func (_m *Environment) BLSAggregateSignatures(signatures [][]byte) ([]byte, error) { - ret := _m.Called(signatures) +// Environment_BLSAggregatePublicKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BLSAggregatePublicKeys' +type Environment_BLSAggregatePublicKeys_Call struct { + *mock.Call +} + +// BLSAggregatePublicKeys is a helper method to define mock.On call +// - publicKeys []*runtime.PublicKey +func (_e *Environment_Expecter) BLSAggregatePublicKeys(publicKeys interface{}) *Environment_BLSAggregatePublicKeys_Call { + return &Environment_BLSAggregatePublicKeys_Call{Call: _e.mock.On("BLSAggregatePublicKeys", publicKeys)} +} + +func (_c *Environment_BLSAggregatePublicKeys_Call) Run(run func(publicKeys []*runtime.PublicKey)) *Environment_BLSAggregatePublicKeys_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []*runtime.PublicKey + if args[0] != nil { + arg0 = args[0].([]*runtime.PublicKey) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_BLSAggregatePublicKeys_Call) Return(v *runtime.PublicKey, err error) *Environment_BLSAggregatePublicKeys_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_BLSAggregatePublicKeys_Call) RunAndReturn(run func(publicKeys []*runtime.PublicKey) (*runtime.PublicKey, error)) *Environment_BLSAggregatePublicKeys_Call { + _c.Call.Return(run) + return _c +} + +// BLSAggregateSignatures provides a mock function for the type Environment +func (_mock *Environment) BLSAggregateSignatures(signatures [][]byte) ([]byte, error) { + ret := _mock.Called(signatures) if len(ret) == 0 { panic("no return value specified for BLSAggregateSignatures") @@ -202,29 +402,61 @@ func (_m *Environment) BLSAggregateSignatures(signatures [][]byte) ([]byte, erro var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func([][]byte) ([]byte, error)); ok { - return rf(signatures) + if returnFunc, ok := ret.Get(0).(func([][]byte) ([]byte, error)); ok { + return returnFunc(signatures) } - if rf, ok := ret.Get(0).(func([][]byte) []byte); ok { - r0 = rf(signatures) + if returnFunc, ok := ret.Get(0).(func([][]byte) []byte); ok { + r0 = returnFunc(signatures) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func([][]byte) error); ok { - r1 = rf(signatures) + if returnFunc, ok := ret.Get(1).(func([][]byte) error); ok { + r1 = returnFunc(signatures) } else { r1 = ret.Error(1) } - return r0, r1 } -// BLSVerifyPOP provides a mock function with given fields: publicKey, signature -func (_m *Environment) BLSVerifyPOP(publicKey *runtime.PublicKey, signature []byte) (bool, error) { - ret := _m.Called(publicKey, signature) +// Environment_BLSAggregateSignatures_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BLSAggregateSignatures' +type Environment_BLSAggregateSignatures_Call struct { + *mock.Call +} + +// BLSAggregateSignatures is a helper method to define mock.On call +// - signatures [][]byte +func (_e *Environment_Expecter) BLSAggregateSignatures(signatures interface{}) *Environment_BLSAggregateSignatures_Call { + return &Environment_BLSAggregateSignatures_Call{Call: _e.mock.On("BLSAggregateSignatures", signatures)} +} + +func (_c *Environment_BLSAggregateSignatures_Call) Run(run func(signatures [][]byte)) *Environment_BLSAggregateSignatures_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 [][]byte + if args[0] != nil { + arg0 = args[0].([][]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_BLSAggregateSignatures_Call) Return(bytes []byte, err error) *Environment_BLSAggregateSignatures_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Environment_BLSAggregateSignatures_Call) RunAndReturn(run func(signatures [][]byte) ([]byte, error)) *Environment_BLSAggregateSignatures_Call { + _c.Call.Return(run) + return _c +} + +// BLSVerifyPOP provides a mock function for the type Environment +func (_mock *Environment) BLSVerifyPOP(publicKey *runtime.PublicKey, signature []byte) (bool, error) { + ret := _mock.Called(publicKey, signature) if len(ret) == 0 { panic("no return value specified for BLSVerifyPOP") @@ -232,1381 +464,3884 @@ func (_m *Environment) BLSVerifyPOP(publicKey *runtime.PublicKey, signature []by var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) (bool, error)); ok { - return rf(publicKey, signature) + if returnFunc, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) (bool, error)); ok { + return returnFunc(publicKey, signature) } - if rf, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) bool); ok { - r0 = rf(publicKey, signature) + if returnFunc, ok := ret.Get(0).(func(*runtime.PublicKey, []byte) bool); ok { + r0 = returnFunc(publicKey, signature) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*runtime.PublicKey, []byte) error); ok { - r1 = rf(publicKey, signature) + if returnFunc, ok := ret.Get(1).(func(*runtime.PublicKey, []byte) error); ok { + r1 = returnFunc(publicKey, signature) } else { r1 = ret.Error(1) } - return r0, r1 } -// BorrowCadenceRuntime provides a mock function with no fields -func (_m *Environment) BorrowCadenceRuntime() *fvmruntime.ReusableCadenceRuntime { - ret := _m.Called() +// Environment_BLSVerifyPOP_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BLSVerifyPOP' +type Environment_BLSVerifyPOP_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for BorrowCadenceRuntime") - } +// BLSVerifyPOP is a helper method to define mock.On call +// - publicKey *runtime.PublicKey +// - signature []byte +func (_e *Environment_Expecter) BLSVerifyPOP(publicKey interface{}, signature interface{}) *Environment_BLSVerifyPOP_Call { + return &Environment_BLSVerifyPOP_Call{Call: _e.mock.On("BLSVerifyPOP", publicKey, signature)} +} - var r0 *fvmruntime.ReusableCadenceRuntime - if rf, ok := ret.Get(0).(func() *fvmruntime.ReusableCadenceRuntime); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*fvmruntime.ReusableCadenceRuntime) +func (_c *Environment_BLSVerifyPOP_Call) Run(run func(publicKey *runtime.PublicKey, signature []byte)) *Environment_BLSVerifyPOP_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *runtime.PublicKey + if args[0] != nil { + arg0 = args[0].(*runtime.PublicKey) } - } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return r0 +func (_c *Environment_BLSVerifyPOP_Call) Return(b bool, err error) *Environment_BLSVerifyPOP_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Environment_BLSVerifyPOP_Call) RunAndReturn(run func(publicKey *runtime.PublicKey, signature []byte) (bool, error)) *Environment_BLSVerifyPOP_Call { + _c.Call.Return(run) + return _c } -// CheckPayerBalanceAndGetMaxTxFees provides a mock function with given fields: payer, inclusionEffort, executionEffort -func (_m *Environment) CheckPayerBalanceAndGetMaxTxFees(payer flow.Address, inclusionEffort uint64, executionEffort uint64) (cadence.Value, error) { - ret := _m.Called(payer, inclusionEffort, executionEffort) +// BlockHash provides a mock function for the type Environment +func (_mock *Environment) BlockHash(height uint64) (common.Hash, error) { + ret := _mock.Called(height) if len(ret) == 0 { - panic("no return value specified for CheckPayerBalanceAndGetMaxTxFees") + panic("no return value specified for BlockHash") } - var r0 cadence.Value + var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(flow.Address, uint64, uint64) (cadence.Value, error)); ok { - return rf(payer, inclusionEffort, executionEffort) + if returnFunc, ok := ret.Get(0).(func(uint64) (common.Hash, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(flow.Address, uint64, uint64) cadence.Value); ok { - r0 = rf(payer, inclusionEffort, executionEffort) + if returnFunc, ok := ret.Get(0).(func(uint64) common.Hash); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(cadence.Value) + r0 = ret.Get(0).(common.Hash) } } - - if rf, ok := ret.Get(1).(func(flow.Address, uint64, uint64) error); ok { - r1 = rf(payer, inclusionEffort, executionEffort) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// ComputationAvailable provides a mock function with given fields: _a0 -func (_m *Environment) ComputationAvailable(_a0 common.ComputationUsage) bool { - ret := _m.Called(_a0) - - if len(ret) == 0 { - panic("no return value specified for ComputationAvailable") - } - - var r0 bool - if rf, ok := ret.Get(0).(func(common.ComputationUsage) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - return r0 +// Environment_BlockHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockHash' +type Environment_BlockHash_Call struct { + *mock.Call } -// ComputationIntensities provides a mock function with no fields -func (_m *Environment) ComputationIntensities() meter.MeteredComputationIntensities { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for ComputationIntensities") - } +// BlockHash is a helper method to define mock.On call +// - height uint64 +func (_e *Environment_Expecter) BlockHash(height interface{}) *Environment_BlockHash_Call { + return &Environment_BlockHash_Call{Call: _e.mock.On("BlockHash", height)} +} - var r0 meter.MeteredComputationIntensities - if rf, ok := ret.Get(0).(func() meter.MeteredComputationIntensities); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(meter.MeteredComputationIntensities) +func (_c *Environment_BlockHash_Call) Run(run func(height uint64)) *Environment_BlockHash_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) } - } - - return r0 + run( + arg0, + ) + }) + return _c } -// ComputationRemaining provides a mock function with given fields: kind -func (_m *Environment) ComputationRemaining(kind common.ComputationKind) uint64 { - ret := _m.Called(kind) - - if len(ret) == 0 { - panic("no return value specified for ComputationRemaining") - } - - var r0 uint64 - if rf, ok := ret.Get(0).(func(common.ComputationKind) uint64); ok { - r0 = rf(kind) - } else { - r0 = ret.Get(0).(uint64) - } +func (_c *Environment_BlockHash_Call) Return(hash common.Hash, err error) *Environment_BlockHash_Call { + _c.Call.Return(hash, err) + return _c +} - return r0 +func (_c *Environment_BlockHash_Call) RunAndReturn(run func(height uint64) (common.Hash, error)) *Environment_BlockHash_Call { + _c.Call.Return(run) + return _c } -// ComputationUsed provides a mock function with no fields -func (_m *Environment) ComputationUsed() (uint64, error) { - ret := _m.Called() +// BlockProposal provides a mock function for the type Environment +func (_mock *Environment) BlockProposal() (*types.BlockProposal, error) { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for ComputationUsed") + panic("no return value specified for BlockProposal") } - var r0 uint64 + var r0 *types.BlockProposal var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*types.BlockProposal, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *types.BlockProposal); ok { + r0 = returnFunc() } else { - r0 = ret.Get(0).(uint64) + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.BlockProposal) + } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// ConvertedServiceEvents provides a mock function with no fields -func (_m *Environment) ConvertedServiceEvents() flow.ServiceEventList { - ret := _m.Called() +// Environment_BlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProposal' +type Environment_BlockProposal_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for ConvertedServiceEvents") - } +// BlockProposal is a helper method to define mock.On call +func (_e *Environment_Expecter) BlockProposal() *Environment_BlockProposal_Call { + return &Environment_BlockProposal_Call{Call: _e.mock.On("BlockProposal")} +} - var r0 flow.ServiceEventList - if rf, ok := ret.Get(0).(func() flow.ServiceEventList); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(flow.ServiceEventList) - } - } +func (_c *Environment_BlockProposal_Call) Run(run func()) *Environment_BlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return r0 +func (_c *Environment_BlockProposal_Call) Return(blockProposal *types.BlockProposal, err error) *Environment_BlockProposal_Call { + _c.Call.Return(blockProposal, err) + return _c +} + +func (_c *Environment_BlockProposal_Call) RunAndReturn(run func() (*types.BlockProposal, error)) *Environment_BlockProposal_Call { + _c.Call.Return(run) + return _c } -// CreateAccount provides a mock function with given fields: payer -func (_m *Environment) CreateAccount(payer runtime.Address) (runtime.Address, error) { - ret := _m.Called(payer) +// BorrowCadenceRuntime provides a mock function for the type Environment +func (_mock *Environment) BorrowCadenceRuntime() environment.ReusableCadenceRuntime { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for CreateAccount") + panic("no return value specified for BorrowCadenceRuntime") } - var r0 runtime.Address - var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address) (runtime.Address, error)); ok { - return rf(payer) - } - if rf, ok := ret.Get(0).(func(runtime.Address) runtime.Address); ok { - r0 = rf(payer) + var r0 environment.ReusableCadenceRuntime + if returnFunc, ok := ret.Get(0).(func() environment.ReusableCadenceRuntime); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(runtime.Address) + r0 = ret.Get(0).(environment.ReusableCadenceRuntime) } } + return r0 +} - if rf, ok := ret.Get(1).(func(runtime.Address) error); ok { - r1 = rf(payer) - } else { - r1 = ret.Error(1) - } +// Environment_BorrowCadenceRuntime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BorrowCadenceRuntime' +type Environment_BorrowCadenceRuntime_Call struct { + *mock.Call +} - return r0, r1 +// BorrowCadenceRuntime is a helper method to define mock.On call +func (_e *Environment_Expecter) BorrowCadenceRuntime() *Environment_BorrowCadenceRuntime_Call { + return &Environment_BorrowCadenceRuntime_Call{Call: _e.mock.On("BorrowCadenceRuntime")} +} + +func (_c *Environment_BorrowCadenceRuntime_Call) Run(run func()) *Environment_BorrowCadenceRuntime_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_BorrowCadenceRuntime_Call) Return(reusableCadenceRuntime environment.ReusableCadenceRuntime) *Environment_BorrowCadenceRuntime_Call { + _c.Call.Return(reusableCadenceRuntime) + return _c +} + +func (_c *Environment_BorrowCadenceRuntime_Call) RunAndReturn(run func() environment.ReusableCadenceRuntime) *Environment_BorrowCadenceRuntime_Call { + _c.Call.Return(run) + return _c } -// DecodeArgument provides a mock function with given fields: argument, argumentType -func (_m *Environment) DecodeArgument(argument []byte, argumentType cadence.Type) (cadence.Value, error) { - ret := _m.Called(argument, argumentType) +// CheckPayerBalanceAndGetMaxTxFees provides a mock function for the type Environment +func (_mock *Environment) CheckPayerBalanceAndGetMaxTxFees(payer flow.Address, inclusionEffort uint64, executionEffort uint64) (cadence.Value, error) { + ret := _mock.Called(payer, inclusionEffort, executionEffort) if len(ret) == 0 { - panic("no return value specified for DecodeArgument") + panic("no return value specified for CheckPayerBalanceAndGetMaxTxFees") } var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func([]byte, cadence.Type) (cadence.Value, error)); ok { - return rf(argument, argumentType) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint64, uint64) (cadence.Value, error)); ok { + return returnFunc(payer, inclusionEffort, executionEffort) } - if rf, ok := ret.Get(0).(func([]byte, cadence.Type) cadence.Value); ok { - r0 = rf(argument, argumentType) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint64, uint64) cadence.Value); ok { + r0 = returnFunc(payer, inclusionEffort, executionEffort) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func([]byte, cadence.Type) error); ok { - r1 = rf(argument, argumentType) + if returnFunc, ok := ret.Get(1).(func(flow.Address, uint64, uint64) error); ok { + r1 = returnFunc(payer, inclusionEffort, executionEffort) } else { r1 = ret.Error(1) } - return r0, r1 } -// DeductTransactionFees provides a mock function with given fields: payer, inclusionEffort, executionEffort -func (_m *Environment) DeductTransactionFees(payer flow.Address, inclusionEffort uint64, executionEffort uint64) (cadence.Value, error) { - ret := _m.Called(payer, inclusionEffort, executionEffort) +// Environment_CheckPayerBalanceAndGetMaxTxFees_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckPayerBalanceAndGetMaxTxFees' +type Environment_CheckPayerBalanceAndGetMaxTxFees_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for DeductTransactionFees") - } +// CheckPayerBalanceAndGetMaxTxFees is a helper method to define mock.On call +// - payer flow.Address +// - inclusionEffort uint64 +// - executionEffort uint64 +func (_e *Environment_Expecter) CheckPayerBalanceAndGetMaxTxFees(payer interface{}, inclusionEffort interface{}, executionEffort interface{}) *Environment_CheckPayerBalanceAndGetMaxTxFees_Call { + return &Environment_CheckPayerBalanceAndGetMaxTxFees_Call{Call: _e.mock.On("CheckPayerBalanceAndGetMaxTxFees", payer, inclusionEffort, executionEffort)} +} - var r0 cadence.Value - var r1 error - if rf, ok := ret.Get(0).(func(flow.Address, uint64, uint64) (cadence.Value, error)); ok { - return rf(payer, inclusionEffort, executionEffort) - } - if rf, ok := ret.Get(0).(func(flow.Address, uint64, uint64) cadence.Value); ok { - r0 = rf(payer, inclusionEffort, executionEffort) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(cadence.Value) +func (_c *Environment_CheckPayerBalanceAndGetMaxTxFees_Call) Run(run func(payer flow.Address, inclusionEffort uint64, executionEffort uint64)) *Environment_CheckPayerBalanceAndGetMaxTxFees_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) } - } - - if rf, ok := ret.Get(1).(func(flow.Address, uint64, uint64) error); ok { - r1 = rf(payer, inclusionEffort, executionEffort) - } else { - r1 = ret.Error(1) - } - - return r0, r1 + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// EVMBlockExecuted provides a mock function with given fields: txCount, totalGasUsed, totalSupplyInFlow -func (_m *Environment) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { - _m.Called(txCount, totalGasUsed, totalSupplyInFlow) +func (_c *Environment_CheckPayerBalanceAndGetMaxTxFees_Call) Return(value cadence.Value, err error) *Environment_CheckPayerBalanceAndGetMaxTxFees_Call { + _c.Call.Return(value, err) + return _c } -// EVMTransactionExecuted provides a mock function with given fields: gasUsed, isDirectCall, failed -func (_m *Environment) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { - _m.Called(gasUsed, isDirectCall, failed) +func (_c *Environment_CheckPayerBalanceAndGetMaxTxFees_Call) RunAndReturn(run func(payer flow.Address, inclusionEffort uint64, executionEffort uint64) (cadence.Value, error)) *Environment_CheckPayerBalanceAndGetMaxTxFees_Call { + _c.Call.Return(run) + return _c } -// EmitEvent provides a mock function with given fields: _a0 -func (_m *Environment) EmitEvent(_a0 cadence.Event) error { - ret := _m.Called(_a0) +// CommitBlockProposal provides a mock function for the type Environment +func (_mock *Environment) CommitBlockProposal(blockProposal *types.BlockProposal) error { + ret := _mock.Called(blockProposal) if len(ret) == 0 { - panic("no return value specified for EmitEvent") + panic("no return value specified for CommitBlockProposal") } var r0 error - if rf, ok := ret.Get(0).(func(cadence.Event) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*types.BlockProposal) error); ok { + r0 = returnFunc(blockProposal) } else { r0 = ret.Error(0) } - return r0 } -// Events provides a mock function with no fields -func (_m *Environment) Events() flow.EventsList { - ret := _m.Called() +// Environment_CommitBlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CommitBlockProposal' +type Environment_CommitBlockProposal_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for Events") - } +// CommitBlockProposal is a helper method to define mock.On call +// - blockProposal *types.BlockProposal +func (_e *Environment_Expecter) CommitBlockProposal(blockProposal interface{}) *Environment_CommitBlockProposal_Call { + return &Environment_CommitBlockProposal_Call{Call: _e.mock.On("CommitBlockProposal", blockProposal)} +} - var r0 flow.EventsList - if rf, ok := ret.Get(0).(func() flow.EventsList); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(flow.EventsList) +func (_c *Environment_CommitBlockProposal_Call) Run(run func(blockProposal *types.BlockProposal)) *Environment_CommitBlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *types.BlockProposal + if args[0] != nil { + arg0 = args[0].(*types.BlockProposal) } - } + run( + arg0, + ) + }) + return _c +} - return r0 +func (_c *Environment_CommitBlockProposal_Call) Return(err error) *Environment_CommitBlockProposal_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_CommitBlockProposal_Call) RunAndReturn(run func(blockProposal *types.BlockProposal) error) *Environment_CommitBlockProposal_Call { + _c.Call.Return(run) + return _c } -// FlushPendingUpdates provides a mock function with no fields -func (_m *Environment) FlushPendingUpdates() (environment.ContractUpdates, error) { - ret := _m.Called() +// ComputationAvailable provides a mock function for the type Environment +func (_mock *Environment) ComputationAvailable(computationUsage common0.ComputationUsage) bool { + ret := _mock.Called(computationUsage) if len(ret) == 0 { - panic("no return value specified for FlushPendingUpdates") + panic("no return value specified for ComputationAvailable") } - var r0 environment.ContractUpdates - var r1 error - if rf, ok := ret.Get(0).(func() (environment.ContractUpdates, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() environment.ContractUpdates); ok { - r0 = rf() + var r0 bool + if returnFunc, ok := ret.Get(0).(func(common0.ComputationUsage) bool); ok { + r0 = returnFunc(computationUsage) } else { - r0 = ret.Get(0).(environment.ContractUpdates) + r0 = ret.Get(0).(bool) } + return r0 +} - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } +// Environment_ComputationAvailable_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationAvailable' +type Environment_ComputationAvailable_Call struct { + *mock.Call +} - return r0, r1 +// ComputationAvailable is a helper method to define mock.On call +// - computationUsage common0.ComputationUsage +func (_e *Environment_Expecter) ComputationAvailable(computationUsage interface{}) *Environment_ComputationAvailable_Call { + return &Environment_ComputationAvailable_Call{Call: _e.mock.On("ComputationAvailable", computationUsage)} +} + +func (_c *Environment_ComputationAvailable_Call) Run(run func(computationUsage common0.ComputationUsage)) *Environment_ComputationAvailable_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.ComputationUsage + if args[0] != nil { + arg0 = args[0].(common0.ComputationUsage) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_ComputationAvailable_Call) Return(b bool) *Environment_ComputationAvailable_Call { + _c.Call.Return(b) + return _c } -// GenerateAccountID provides a mock function with given fields: address -func (_m *Environment) GenerateAccountID(address common.Address) (uint64, error) { - ret := _m.Called(address) +func (_c *Environment_ComputationAvailable_Call) RunAndReturn(run func(computationUsage common0.ComputationUsage) bool) *Environment_ComputationAvailable_Call { + _c.Call.Return(run) + return _c +} + +// ComputationIntensities provides a mock function for the type Environment +func (_mock *Environment) ComputationIntensities() meter.MeteredComputationIntensities { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for GenerateAccountID") + panic("no return value specified for ComputationIntensities") } - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(address) - } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(address) + var r0 meter.MeteredComputationIntensities + if returnFunc, ok := ret.Get(0).(func() meter.MeteredComputationIntensities); ok { + r0 = returnFunc() } else { - r0 = ret.Get(0).(uint64) + if ret.Get(0) != nil { + r0 = ret.Get(0).(meter.MeteredComputationIntensities) + } } + return r0 +} - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(address) - } else { - r1 = ret.Error(1) - } +// Environment_ComputationIntensities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationIntensities' +type Environment_ComputationIntensities_Call struct { + *mock.Call +} - return r0, r1 +// ComputationIntensities is a helper method to define mock.On call +func (_e *Environment_Expecter) ComputationIntensities() *Environment_ComputationIntensities_Call { + return &Environment_ComputationIntensities_Call{Call: _e.mock.On("ComputationIntensities")} +} + +func (_c *Environment_ComputationIntensities_Call) Run(run func()) *Environment_ComputationIntensities_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_ComputationIntensities_Call) Return(meteredComputationIntensities meter.MeteredComputationIntensities) *Environment_ComputationIntensities_Call { + _c.Call.Return(meteredComputationIntensities) + return _c +} + +func (_c *Environment_ComputationIntensities_Call) RunAndReturn(run func() meter.MeteredComputationIntensities) *Environment_ComputationIntensities_Call { + _c.Call.Return(run) + return _c } -// GenerateUUID provides a mock function with no fields -func (_m *Environment) GenerateUUID() (uint64, error) { - ret := _m.Called() +// ComputationRemaining provides a mock function for the type Environment +func (_mock *Environment) ComputationRemaining(kind common0.ComputationKind) uint64 { + ret := _mock.Called(kind) if len(ret) == 0 { - panic("no return value specified for GenerateUUID") + panic("no return value specified for ComputationRemaining") } var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func(common0.ComputationKind) uint64); ok { + r0 = returnFunc(kind) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 + return r0 } -// GetAccount provides a mock function with given fields: address -func (_m *Environment) GetAccount(address flow.Address) (*flow.Account, error) { - ret := _m.Called(address) +// Environment_ComputationRemaining_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationRemaining' +type Environment_ComputationRemaining_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetAccount") - } +// ComputationRemaining is a helper method to define mock.On call +// - kind common0.ComputationKind +func (_e *Environment_Expecter) ComputationRemaining(kind interface{}) *Environment_ComputationRemaining_Call { + return &Environment_ComputationRemaining_Call{Call: _e.mock.On("ComputationRemaining", kind)} +} - var r0 *flow.Account - var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) (*flow.Account, error)); ok { - return rf(address) - } - if rf, ok := ret.Get(0).(func(flow.Address) *flow.Account); ok { - r0 = rf(address) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*flow.Account) +func (_c *Environment_ComputationRemaining_Call) Run(run func(kind common0.ComputationKind)) *Environment_ComputationRemaining_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.ComputationKind + if args[0] != nil { + arg0 = args[0].(common0.ComputationKind) } - } + run( + arg0, + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) - } else { - r1 = ret.Error(1) - } +func (_c *Environment_ComputationRemaining_Call) Return(v uint64) *Environment_ComputationRemaining_Call { + _c.Call.Return(v) + return _c +} - return r0, r1 +func (_c *Environment_ComputationRemaining_Call) RunAndReturn(run func(kind common0.ComputationKind) uint64) *Environment_ComputationRemaining_Call { + _c.Call.Return(run) + return _c } -// GetAccountAvailableBalance provides a mock function with given fields: address -func (_m *Environment) GetAccountAvailableBalance(address common.Address) (uint64, error) { - ret := _m.Called(address) +// ComputationUsed provides a mock function for the type Environment +func (_mock *Environment) ComputationUsed() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for GetAccountAvailableBalance") + panic("no return value specified for ComputationUsed") } var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalance provides a mock function with given fields: address -func (_m *Environment) GetAccountBalance(address common.Address) (uint64, error) { - ret := _m.Called(address) +// Environment_ComputationUsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationUsed' +type Environment_ComputationUsed_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetAccountBalance") - } +// ComputationUsed is a helper method to define mock.On call +func (_e *Environment_Expecter) ComputationUsed() *Environment_ComputationUsed_Call { + return &Environment_ComputationUsed_Call{Call: _e.mock.On("ComputationUsed")} +} - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(common.Address) (uint64, error)); ok { - return rf(address) - } - if rf, ok := ret.Get(0).(func(common.Address) uint64); ok { - r0 = rf(address) - } else { - r0 = ret.Get(0).(uint64) - } +func (_c *Environment_ComputationUsed_Call) Run(run func()) *Environment_ComputationUsed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - if rf, ok := ret.Get(1).(func(common.Address) error); ok { - r1 = rf(address) - } else { - r1 = ret.Error(1) - } +func (_c *Environment_ComputationUsed_Call) Return(v uint64, err error) *Environment_ComputationUsed_Call { + _c.Call.Return(v, err) + return _c +} - return r0, r1 +func (_c *Environment_ComputationUsed_Call) RunAndReturn(run func() (uint64, error)) *Environment_ComputationUsed_Call { + _c.Call.Return(run) + return _c } -// GetAccountContractCode provides a mock function with given fields: location -func (_m *Environment) GetAccountContractCode(location common.AddressLocation) ([]byte, error) { - ret := _m.Called(location) +// ConvertedServiceEvents provides a mock function for the type Environment +func (_mock *Environment) ConvertedServiceEvents() flow.ServiceEventList { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for GetAccountContractCode") + panic("no return value specified for ConvertedServiceEvents") } - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(common.AddressLocation) ([]byte, error)); ok { - return rf(location) - } - if rf, ok := ret.Get(0).(func(common.AddressLocation) []byte); ok { - r0 = rf(location) + var r0 flow.ServiceEventList + if returnFunc, ok := ret.Get(0).(func() flow.ServiceEventList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) + r0 = ret.Get(0).(flow.ServiceEventList) } } + return r0 +} - if rf, ok := ret.Get(1).(func(common.AddressLocation) error); ok { - r1 = rf(location) - } else { - r1 = ret.Error(1) - } +// Environment_ConvertedServiceEvents_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConvertedServiceEvents' +type Environment_ConvertedServiceEvents_Call struct { + *mock.Call +} - return r0, r1 +// ConvertedServiceEvents is a helper method to define mock.On call +func (_e *Environment_Expecter) ConvertedServiceEvents() *Environment_ConvertedServiceEvents_Call { + return &Environment_ConvertedServiceEvents_Call{Call: _e.mock.On("ConvertedServiceEvents")} +} + +func (_c *Environment_ConvertedServiceEvents_Call) Run(run func()) *Environment_ConvertedServiceEvents_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// GetAccountContractNames provides a mock function with given fields: address -func (_m *Environment) GetAccountContractNames(address runtime.Address) ([]string, error) { - ret := _m.Called(address) +func (_c *Environment_ConvertedServiceEvents_Call) Return(serviceEventList flow.ServiceEventList) *Environment_ConvertedServiceEvents_Call { + _c.Call.Return(serviceEventList) + return _c +} + +func (_c *Environment_ConvertedServiceEvents_Call) RunAndReturn(run func() flow.ServiceEventList) *Environment_ConvertedServiceEvents_Call { + _c.Call.Return(run) + return _c +} + +// CreateAccount provides a mock function for the type Environment +func (_mock *Environment) CreateAccount(payer runtime.Address, context interpreter.InvocationContext) (runtime.Address, error) { + ret := _mock.Called(payer, context) if len(ret) == 0 { - panic("no return value specified for GetAccountContractNames") + panic("no return value specified for CreateAccount") } - var r0 []string + var r0 runtime.Address var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address) ([]string, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func(runtime.Address, interpreter.InvocationContext) (runtime.Address, error)); ok { + return returnFunc(payer, context) } - if rf, ok := ret.Get(0).(func(runtime.Address) []string); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func(runtime.Address, interpreter.InvocationContext) runtime.Address); ok { + r0 = returnFunc(payer, context) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]string) + r0 = ret.Get(0).(runtime.Address) } } - - if rf, ok := ret.Get(1).(func(runtime.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func(runtime.Address, interpreter.InvocationContext) error); ok { + r1 = returnFunc(payer, context) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKey provides a mock function with given fields: address, index -func (_m *Environment) GetAccountKey(address runtime.Address, index uint32) (*runtime.AccountKey, error) { - ret := _m.Called(address, index) +// Environment_CreateAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateAccount' +type Environment_CreateAccount_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetAccountKey") - } +// CreateAccount is a helper method to define mock.On call +// - payer runtime.Address +// - context interpreter.InvocationContext +func (_e *Environment_Expecter) CreateAccount(payer interface{}, context interface{}) *Environment_CreateAccount_Call { + return &Environment_CreateAccount_Call{Call: _e.mock.On("CreateAccount", payer, context)} +} - var r0 *runtime.AccountKey - var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address, uint32) (*runtime.AccountKey, error)); ok { - return rf(address, index) - } - if rf, ok := ret.Get(0).(func(runtime.Address, uint32) *runtime.AccountKey); ok { - r0 = rf(address, index) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*runtime.AccountKey) +func (_c *Environment_CreateAccount_Call) Run(run func(payer runtime.Address, context interpreter.InvocationContext)) *Environment_CreateAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) } - } + var arg1 interpreter.InvocationContext + if args[1] != nil { + arg1 = args[1].(interpreter.InvocationContext) + } + run( + arg0, + arg1, + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func(runtime.Address, uint32) error); ok { - r1 = rf(address, index) - } else { - r1 = ret.Error(1) - } +func (_c *Environment_CreateAccount_Call) Return(address runtime.Address, err error) *Environment_CreateAccount_Call { + _c.Call.Return(address, err) + return _c +} - return r0, r1 +func (_c *Environment_CreateAccount_Call) RunAndReturn(run func(payer runtime.Address, context interpreter.InvocationContext) (runtime.Address, error)) *Environment_CreateAccount_Call { + _c.Call.Return(run) + return _c } -// GetAccountKeys provides a mock function with given fields: address -func (_m *Environment) GetAccountKeys(address flow.Address) ([]flow.AccountPublicKey, error) { - ret := _m.Called(address) +// DecodeArgument provides a mock function for the type Environment +func (_mock *Environment) DecodeArgument(argument []byte, argumentType cadence.Type) (cadence.Value, error) { + ret := _mock.Called(argument, argumentType) if len(ret) == 0 { - panic("no return value specified for GetAccountKeys") + panic("no return value specified for DecodeArgument") } - var r0 []flow.AccountPublicKey + var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(flow.Address) ([]flow.AccountPublicKey, error)); ok { - return rf(address) + if returnFunc, ok := ret.Get(0).(func([]byte, cadence.Type) (cadence.Value, error)); ok { + return returnFunc(argument, argumentType) } - if rf, ok := ret.Get(0).(func(flow.Address) []flow.AccountPublicKey); ok { - r0 = rf(address) + if returnFunc, ok := ret.Get(0).(func([]byte, cadence.Type) cadence.Value); ok { + r0 = returnFunc(argument, argumentType) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]flow.AccountPublicKey) + r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(flow.Address) error); ok { - r1 = rf(address) + if returnFunc, ok := ret.Get(1).(func([]byte, cadence.Type) error); ok { + r1 = returnFunc(argument, argumentType) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockAtHeight provides a mock function with given fields: height -func (_m *Environment) GetBlockAtHeight(height uint64) (runtime.Block, bool, error) { - ret := _m.Called(height) - - if len(ret) == 0 { - panic("no return value specified for GetBlockAtHeight") - } +// Environment_DecodeArgument_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DecodeArgument' +type Environment_DecodeArgument_Call struct { + *mock.Call +} - var r0 runtime.Block - var r1 bool - var r2 error - if rf, ok := ret.Get(0).(func(uint64) (runtime.Block, bool, error)); ok { - return rf(height) - } - if rf, ok := ret.Get(0).(func(uint64) runtime.Block); ok { - r0 = rf(height) - } else { - r0 = ret.Get(0).(runtime.Block) - } +// DecodeArgument is a helper method to define mock.On call +// - argument []byte +// - argumentType cadence.Type +func (_e *Environment_Expecter) DecodeArgument(argument interface{}, argumentType interface{}) *Environment_DecodeArgument_Call { + return &Environment_DecodeArgument_Call{Call: _e.mock.On("DecodeArgument", argument, argumentType)} +} - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(height) - } else { - r1 = ret.Get(1).(bool) - } +func (_c *Environment_DecodeArgument_Call) Run(run func(argument []byte, argumentType cadence.Type)) *Environment_DecodeArgument_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 cadence.Type + if args[1] != nil { + arg1 = args[1].(cadence.Type) + } + run( + arg0, + arg1, + ) + }) + return _c +} - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(height) - } else { - r2 = ret.Error(2) - } +func (_c *Environment_DecodeArgument_Call) Return(value cadence.Value, err error) *Environment_DecodeArgument_Call { + _c.Call.Return(value, err) + return _c +} - return r0, r1, r2 +func (_c *Environment_DecodeArgument_Call) RunAndReturn(run func(argument []byte, argumentType cadence.Type) (cadence.Value, error)) *Environment_DecodeArgument_Call { + _c.Call.Return(run) + return _c } -// GetCode provides a mock function with given fields: location -func (_m *Environment) GetCode(location runtime.Location) ([]byte, error) { - ret := _m.Called(location) +// DeductTransactionFees provides a mock function for the type Environment +func (_mock *Environment) DeductTransactionFees(payer flow.Address, inclusionEffort uint64, executionEffort uint64) (cadence.Value, error) { + ret := _mock.Called(payer, inclusionEffort, executionEffort) if len(ret) == 0 { - panic("no return value specified for GetCode") + panic("no return value specified for DeductTransactionFees") } - var r0 []byte + var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(runtime.Location) ([]byte, error)); ok { - return rf(location) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint64, uint64) (cadence.Value, error)); ok { + return returnFunc(payer, inclusionEffort, executionEffort) } - if rf, ok := ret.Get(0).(func(runtime.Location) []byte); ok { - r0 = rf(location) + if returnFunc, ok := ret.Get(0).(func(flow.Address, uint64, uint64) cadence.Value); ok { + r0 = returnFunc(payer, inclusionEffort, executionEffort) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) + r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(runtime.Location) error); ok { - r1 = rf(location) + if returnFunc, ok := ret.Get(1).(func(flow.Address, uint64, uint64) error); ok { + r1 = returnFunc(payer, inclusionEffort, executionEffort) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCurrentBlockHeight provides a mock function with no fields -func (_m *Environment) GetCurrentBlockHeight() (uint64, error) { - ret := _m.Called() +// Environment_DeductTransactionFees_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeductTransactionFees' +type Environment_DeductTransactionFees_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetCurrentBlockHeight") - } +// DeductTransactionFees is a helper method to define mock.On call +// - payer flow.Address +// - inclusionEffort uint64 +// - executionEffort uint64 +func (_e *Environment_Expecter) DeductTransactionFees(payer interface{}, inclusionEffort interface{}, executionEffort interface{}) *Environment_DeductTransactionFees_Call { + return &Environment_DeductTransactionFees_Call{Call: _e.mock.On("DeductTransactionFees", payer, inclusionEffort, executionEffort)} +} - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(uint64) - } +func (_c *Environment_DeductTransactionFees_Call) Run(run func(payer flow.Address, inclusionEffort uint64, executionEffort uint64)) *Environment_DeductTransactionFees_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } +func (_c *Environment_DeductTransactionFees_Call) Return(value cadence.Value, err error) *Environment_DeductTransactionFees_Call { + _c.Call.Return(value, err) + return _c +} - return r0, r1 +func (_c *Environment_DeductTransactionFees_Call) RunAndReturn(run func(payer flow.Address, inclusionEffort uint64, executionEffort uint64) (cadence.Value, error)) *Environment_DeductTransactionFees_Call { + _c.Call.Return(run) + return _c } -// GetOrLoadProgram provides a mock function with given fields: location, load -func (_m *Environment) GetOrLoadProgram(location runtime.Location, load func() (*runtime.Program, error)) (*runtime.Program, error) { - ret := _m.Called(location, load) +// EVMBlockExecuted provides a mock function for the type Environment +func (_mock *Environment) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { + _mock.Called(txCount, totalGasUsed, totalSupplyInFlow) + return +} - if len(ret) == 0 { - panic("no return value specified for GetOrLoadProgram") - } +// Environment_EVMBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMBlockExecuted' +type Environment_EVMBlockExecuted_Call struct { + *mock.Call +} - var r0 *runtime.Program - var r1 error - if rf, ok := ret.Get(0).(func(runtime.Location, func() (*runtime.Program, error)) (*runtime.Program, error)); ok { - return rf(location, load) - } - if rf, ok := ret.Get(0).(func(runtime.Location, func() (*runtime.Program, error)) *runtime.Program); ok { - r0 = rf(location, load) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*runtime.Program) +// EVMBlockExecuted is a helper method to define mock.On call +// - txCount int +// - totalGasUsed uint64 +// - totalSupplyInFlow float64 +func (_e *Environment_Expecter) EVMBlockExecuted(txCount interface{}, totalGasUsed interface{}, totalSupplyInFlow interface{}) *Environment_EVMBlockExecuted_Call { + return &Environment_EVMBlockExecuted_Call{Call: _e.mock.On("EVMBlockExecuted", txCount, totalGasUsed, totalSupplyInFlow)} +} + +func (_c *Environment_EVMBlockExecuted_Call) Run(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *Environment_EVMBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) } - } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 float64 + if args[2] != nil { + arg2 = args[2].(float64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func(runtime.Location, func() (*runtime.Program, error)) error); ok { - r1 = rf(location, load) - } else { - r1 = ret.Error(1) - } +func (_c *Environment_EVMBlockExecuted_Call) Return() *Environment_EVMBlockExecuted_Call { + _c.Call.Return() + return _c +} - return r0, r1 +func (_c *Environment_EVMBlockExecuted_Call) RunAndReturn(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *Environment_EVMBlockExecuted_Call { + _c.Run(run) + return _c } -// GetSigningAccounts provides a mock function with no fields -func (_m *Environment) GetSigningAccounts() ([]runtime.Address, error) { - ret := _m.Called() +// EVMTestOperationsAllowed provides a mock function for the type Environment +func (_mock *Environment) EVMTestOperationsAllowed() bool { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for GetSigningAccounts") - } - - var r0 []runtime.Address - var r1 error - if rf, ok := ret.Get(0).(func() ([]runtime.Address, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() []runtime.Address); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]runtime.Address) - } + panic("no return value specified for EVMTestOperationsAllowed") } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + var r0 bool + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { - r1 = ret.Error(1) + r0 = ret.Get(0).(bool) } + return r0 +} - return r0, r1 +// Environment_EVMTestOperationsAllowed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMTestOperationsAllowed' +type Environment_EVMTestOperationsAllowed_Call struct { + *mock.Call } -// GetStorageCapacity provides a mock function with given fields: address -func (_m *Environment) GetStorageCapacity(address runtime.Address) (uint64, error) { - ret := _m.Called(address) +// EVMTestOperationsAllowed is a helper method to define mock.On call +func (_e *Environment_Expecter) EVMTestOperationsAllowed() *Environment_EVMTestOperationsAllowed_Call { + return &Environment_EVMTestOperationsAllowed_Call{Call: _e.mock.On("EVMTestOperationsAllowed")} +} - if len(ret) == 0 { - panic("no return value specified for GetStorageCapacity") - } +func (_c *Environment_EVMTestOperationsAllowed_Call) Run(run func()) *Environment_EVMTestOperationsAllowed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address) (uint64, error)); ok { - return rf(address) - } - if rf, ok := ret.Get(0).(func(runtime.Address) uint64); ok { - r0 = rf(address) - } else { - r0 = ret.Get(0).(uint64) - } +func (_c *Environment_EVMTestOperationsAllowed_Call) Return(b bool) *Environment_EVMTestOperationsAllowed_Call { + _c.Call.Return(b) + return _c +} - if rf, ok := ret.Get(1).(func(runtime.Address) error); ok { - r1 = rf(address) - } else { - r1 = ret.Error(1) - } +func (_c *Environment_EVMTestOperationsAllowed_Call) RunAndReturn(run func() bool) *Environment_EVMTestOperationsAllowed_Call { + _c.Call.Return(run) + return _c +} - return r0, r1 +// EVMTransactionExecuted provides a mock function for the type Environment +func (_mock *Environment) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { + _mock.Called(gasUsed, isDirectCall, failed) + return } -// GetStorageUsed provides a mock function with given fields: address -func (_m *Environment) GetStorageUsed(address runtime.Address) (uint64, error) { - ret := _m.Called(address) +// Environment_EVMTransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMTransactionExecuted' +type Environment_EVMTransactionExecuted_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for GetStorageUsed") - } +// EVMTransactionExecuted is a helper method to define mock.On call +// - gasUsed uint64 +// - isDirectCall bool +// - failed bool +func (_e *Environment_Expecter) EVMTransactionExecuted(gasUsed interface{}, isDirectCall interface{}, failed interface{}) *Environment_EVMTransactionExecuted_Call { + return &Environment_EVMTransactionExecuted_Call{Call: _e.mock.On("EVMTransactionExecuted", gasUsed, isDirectCall, failed)} +} - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address) (uint64, error)); ok { - return rf(address) - } - if rf, ok := ret.Get(0).(func(runtime.Address) uint64); ok { - r0 = rf(address) - } else { - r0 = ret.Get(0).(uint64) +func (_c *Environment_EVMTransactionExecuted_Call) Run(run func(gasUsed uint64, isDirectCall bool, failed bool)) *Environment_EVMTransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + var arg2 bool + if args[2] != nil { + arg2 = args[2].(bool) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Environment_EVMTransactionExecuted_Call) Return() *Environment_EVMTransactionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_EVMTransactionExecuted_Call) RunAndReturn(run func(gasUsed uint64, isDirectCall bool, failed bool)) *Environment_EVMTransactionExecuted_Call { + _c.Run(run) + return _c +} + +// EmitEvent provides a mock function for the type Environment +func (_mock *Environment) EmitEvent(event cadence.Event) error { + ret := _mock.Called(event) + + if len(ret) == 0 { + panic("no return value specified for EmitEvent") } - if rf, ok := ret.Get(1).(func(runtime.Address) error); ok { - r1 = rf(address) + var r0 error + if returnFunc, ok := ret.Get(0).(func(cadence.Event) error); ok { + r0 = returnFunc(event) } else { - r1 = ret.Error(1) + r0 = ret.Error(0) } + return r0 +} - return r0, r1 +// Environment_EmitEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EmitEvent' +type Environment_EmitEvent_Call struct { + *mock.Call +} + +// EmitEvent is a helper method to define mock.On call +// - event cadence.Event +func (_e *Environment_Expecter) EmitEvent(event interface{}) *Environment_EmitEvent_Call { + return &Environment_EmitEvent_Call{Call: _e.mock.On("EmitEvent", event)} } -// GetValue provides a mock function with given fields: owner, key -func (_m *Environment) GetValue(owner []byte, key []byte) ([]byte, error) { - ret := _m.Called(owner, key) +func (_c *Environment_EmitEvent_Call) Run(run func(event cadence.Event)) *Environment_EmitEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 cadence.Event + if args[0] != nil { + arg0 = args[0].(cadence.Event) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_EmitEvent_Call) Return(err error) *Environment_EmitEvent_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_EmitEvent_Call) RunAndReturn(run func(event cadence.Event) error) *Environment_EmitEvent_Call { + _c.Call.Return(run) + return _c +} + +// Events provides a mock function for the type Environment +func (_mock *Environment) Events() flow.EventsList { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for GetValue") + panic("no return value specified for Events") } - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func([]byte, []byte) ([]byte, error)); ok { - return rf(owner, key) - } - if rf, ok := ret.Get(0).(func([]byte, []byte) []byte); ok { - r0 = rf(owner, key) + var r0 flow.EventsList + if returnFunc, ok := ret.Get(0).(func() flow.EventsList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) + r0 = ret.Get(0).(flow.EventsList) } } + return r0 +} - if rf, ok := ret.Get(1).(func([]byte, []byte) error); ok { - r1 = rf(owner, key) - } else { - r1 = ret.Error(1) - } +// Environment_Events_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Events' +type Environment_Events_Call struct { + *mock.Call +} - return r0, r1 +// Events is a helper method to define mock.On call +func (_e *Environment_Expecter) Events() *Environment_Events_Call { + return &Environment_Events_Call{Call: _e.mock.On("Events")} +} + +func (_c *Environment_Events_Call) Run(run func()) *Environment_Events_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// Hash provides a mock function with given fields: data, tag, hashAlgorithm -func (_m *Environment) Hash(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm) ([]byte, error) { - ret := _m.Called(data, tag, hashAlgorithm) +func (_c *Environment_Events_Call) Return(eventsList flow.EventsList) *Environment_Events_Call { + _c.Call.Return(eventsList) + return _c +} + +func (_c *Environment_Events_Call) RunAndReturn(run func() flow.EventsList) *Environment_Events_Call { + _c.Call.Return(run) + return _c +} + +// FlushPendingUpdates provides a mock function for the type Environment +func (_mock *Environment) FlushPendingUpdates() (environment.ContractUpdates, error) { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for Hash") + panic("no return value specified for FlushPendingUpdates") } - var r0 []byte + var r0 environment.ContractUpdates var r1 error - if rf, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) ([]byte, error)); ok { - return rf(data, tag, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func() (environment.ContractUpdates, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) []byte); ok { - r0 = rf(data, tag, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func() environment.ContractUpdates); ok { + r0 = returnFunc() } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } + r0 = ret.Get(0).(environment.ContractUpdates) } - - if rf, ok := ret.Get(1).(func([]byte, string, runtime.HashAlgorithm) error); ok { - r1 = rf(data, tag, hashAlgorithm) + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// ImplementationDebugLog provides a mock function with given fields: message -func (_m *Environment) ImplementationDebugLog(message string) error { - ret := _m.Called(message) +// Environment_FlushPendingUpdates_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FlushPendingUpdates' +type Environment_FlushPendingUpdates_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for ImplementationDebugLog") - } +// FlushPendingUpdates is a helper method to define mock.On call +func (_e *Environment_Expecter) FlushPendingUpdates() *Environment_FlushPendingUpdates_Call { + return &Environment_FlushPendingUpdates_Call{Call: _e.mock.On("FlushPendingUpdates")} +} - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(message) - } else { - r0 = ret.Error(0) - } +func (_c *Environment_FlushPendingUpdates_Call) Run(run func()) *Environment_FlushPendingUpdates_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return r0 +func (_c *Environment_FlushPendingUpdates_Call) Return(contractUpdates environment.ContractUpdates, err error) *Environment_FlushPendingUpdates_Call { + _c.Call.Return(contractUpdates, err) + return _c +} + +func (_c *Environment_FlushPendingUpdates_Call) RunAndReturn(run func() (environment.ContractUpdates, error)) *Environment_FlushPendingUpdates_Call { + _c.Call.Return(run) + return _c } -// Invoke provides a mock function with given fields: spec, arguments -func (_m *Environment) Invoke(spec environment.ContractFunctionSpec, arguments []cadence.Value) (cadence.Value, error) { - ret := _m.Called(spec, arguments) +// GenerateAccountID provides a mock function for the type Environment +func (_mock *Environment) GenerateAccountID(address common0.Address) (uint64, error) { + ret := _mock.Called(address) if len(ret) == 0 { - panic("no return value specified for Invoke") + panic("no return value specified for GenerateAccountID") } - var r0 cadence.Value + var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) (cadence.Value, error)); ok { - return rf(spec, arguments) + if returnFunc, ok := ret.Get(0).(func(common0.Address) (uint64, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) cadence.Value); ok { - r0 = rf(spec, arguments) + if returnFunc, ok := ret.Get(0).(func(common0.Address) uint64); ok { + r0 = returnFunc(address) } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(cadence.Value) - } + r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(environment.ContractFunctionSpec, []cadence.Value) error); ok { - r1 = rf(spec, arguments) + if returnFunc, ok := ret.Get(1).(func(common0.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// IsServiceAccountAuthorizer provides a mock function with no fields -func (_m *Environment) IsServiceAccountAuthorizer() bool { - ret := _m.Called() +// Environment_GenerateAccountID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateAccountID' +type Environment_GenerateAccountID_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for IsServiceAccountAuthorizer") - } +// GenerateAccountID is a helper method to define mock.On call +// - address common0.Address +func (_e *Environment_Expecter) GenerateAccountID(address interface{}) *Environment_GenerateAccountID_Call { + return &Environment_GenerateAccountID_Call{Call: _e.mock.On("GenerateAccountID", address)} +} - var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(bool) - } +func (_c *Environment_GenerateAccountID_Call) Run(run func(address common0.Address)) *Environment_GenerateAccountID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.Address + if args[0] != nil { + arg0 = args[0].(common0.Address) + } + run( + arg0, + ) + }) + return _c +} - return r0 +func (_c *Environment_GenerateAccountID_Call) Return(v uint64, err error) *Environment_GenerateAccountID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_GenerateAccountID_Call) RunAndReturn(run func(address common0.Address) (uint64, error)) *Environment_GenerateAccountID_Call { + _c.Call.Return(run) + return _c } -// LimitAccountStorage provides a mock function with no fields -func (_m *Environment) LimitAccountStorage() bool { - ret := _m.Called() +// GenerateUUID provides a mock function for the type Environment +func (_mock *Environment) GenerateUUID() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for LimitAccountStorage") + panic("no return value specified for GenerateUUID") } - var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { - r0 = ret.Get(0).(bool) + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) } + return r0, r1 +} - return r0 +// Environment_GenerateUUID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateUUID' +type Environment_GenerateUUID_Call struct { + *mock.Call } -// Logger provides a mock function with no fields -func (_m *Environment) Logger() zerolog.Logger { - ret := _m.Called() +// GenerateUUID is a helper method to define mock.On call +func (_e *Environment_Expecter) GenerateUUID() *Environment_GenerateUUID_Call { + return &Environment_GenerateUUID_Call{Call: _e.mock.On("GenerateUUID")} +} - if len(ret) == 0 { - panic("no return value specified for Logger") - } +func (_c *Environment_GenerateUUID_Call) Run(run func()) *Environment_GenerateUUID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - var r0 zerolog.Logger - if rf, ok := ret.Get(0).(func() zerolog.Logger); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(zerolog.Logger) - } +func (_c *Environment_GenerateUUID_Call) Return(v uint64, err error) *Environment_GenerateUUID_Call { + _c.Call.Return(v, err) + return _c +} - return r0 +func (_c *Environment_GenerateUUID_Call) RunAndReturn(run func() (uint64, error)) *Environment_GenerateUUID_Call { + _c.Call.Return(run) + return _c } -// Logs provides a mock function with no fields -func (_m *Environment) Logs() []string { - ret := _m.Called() +// GetAccount provides a mock function for the type Environment +func (_mock *Environment) GetAccount(address flow.Address) (*flow.Account, error) { + ret := _mock.Called(address) if len(ret) == 0 { - panic("no return value specified for Logs") + panic("no return value specified for GetAccount") } - var r0 []string - if rf, ok := ret.Get(0).(func() []string); ok { - r0 = rf() + var r0 *flow.Account + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address) (*flow.Account, error)); ok { + return returnFunc(address) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address) *flow.Account); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]string) + r0 = ret.Get(0).(*flow.Account) } } + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} - return r0 +// Environment_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type Environment_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - address flow.Address +func (_e *Environment_Expecter) GetAccount(address interface{}) *Environment_GetAccount_Call { + return &Environment_GetAccount_Call{Call: _e.mock.On("GetAccount", address)} +} + +func (_c *Environment_GetAccount_Call) Run(run func(address flow.Address)) *Environment_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_GetAccount_Call) Return(account *flow.Account, err error) *Environment_GetAccount_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *Environment_GetAccount_Call) RunAndReturn(run func(address flow.Address) (*flow.Account, error)) *Environment_GetAccount_Call { + _c.Call.Return(run) + return _c } -// MemoryUsed provides a mock function with no fields -func (_m *Environment) MemoryUsed() (uint64, error) { - ret := _m.Called() +// GetAccountAvailableBalance provides a mock function for the type Environment +func (_mock *Environment) GetAccountAvailableBalance(address common0.Address) (uint64, error) { + ret := _mock.Called(address) if len(ret) == 0 { - panic("no return value specified for MemoryUsed") + panic("no return value specified for GetAccountAvailableBalance") } var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func(common0.Address) (uint64, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func(common0.Address) uint64); ok { + r0 = returnFunc(address) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func(common0.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// MeterComputation provides a mock function with given fields: usage -func (_m *Environment) MeterComputation(usage common.ComputationUsage) error { - ret := _m.Called(usage) +// Environment_GetAccountAvailableBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAvailableBalance' +type Environment_GetAccountAvailableBalance_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for MeterComputation") - } +// GetAccountAvailableBalance is a helper method to define mock.On call +// - address common0.Address +func (_e *Environment_Expecter) GetAccountAvailableBalance(address interface{}) *Environment_GetAccountAvailableBalance_Call { + return &Environment_GetAccountAvailableBalance_Call{Call: _e.mock.On("GetAccountAvailableBalance", address)} +} - var r0 error - if rf, ok := ret.Get(0).(func(common.ComputationUsage) error); ok { - r0 = rf(usage) - } else { - r0 = ret.Error(0) - } +func (_c *Environment_GetAccountAvailableBalance_Call) Run(run func(address common0.Address)) *Environment_GetAccountAvailableBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.Address + if args[0] != nil { + arg0 = args[0].(common0.Address) + } + run( + arg0, + ) + }) + return _c +} - return r0 +func (_c *Environment_GetAccountAvailableBalance_Call) Return(value uint64, err error) *Environment_GetAccountAvailableBalance_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Environment_GetAccountAvailableBalance_Call) RunAndReturn(run func(address common0.Address) (uint64, error)) *Environment_GetAccountAvailableBalance_Call { + _c.Call.Return(run) + return _c } -// MeterEmittedEvent provides a mock function with given fields: byteSize -func (_m *Environment) MeterEmittedEvent(byteSize uint64) error { - ret := _m.Called(byteSize) +// GetAccountBalance provides a mock function for the type Environment +func (_mock *Environment) GetAccountBalance(address common0.Address) (uint64, error) { + ret := _mock.Called(address) if len(ret) == 0 { - panic("no return value specified for MeterEmittedEvent") + panic("no return value specified for GetAccountBalance") } - var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(byteSize) + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func(common0.Address) (uint64, error)); ok { + return returnFunc(address) + } + if returnFunc, ok := ret.Get(0).(func(common0.Address) uint64); ok { + r0 = returnFunc(address) } else { - r0 = ret.Error(0) + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func(common0.Address) error); ok { + r1 = returnFunc(address) + } else { + r1 = ret.Error(1) } + return r0, r1 +} - return r0 +// Environment_GetAccountBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalance' +type Environment_GetAccountBalance_Call struct { + *mock.Call } -// MeterMemory provides a mock function with given fields: usage -func (_m *Environment) MeterMemory(usage common.MemoryUsage) error { - ret := _m.Called(usage) +// GetAccountBalance is a helper method to define mock.On call +// - address common0.Address +func (_e *Environment_Expecter) GetAccountBalance(address interface{}) *Environment_GetAccountBalance_Call { + return &Environment_GetAccountBalance_Call{Call: _e.mock.On("GetAccountBalance", address)} +} - if len(ret) == 0 { - panic("no return value specified for MeterMemory") - } +func (_c *Environment_GetAccountBalance_Call) Run(run func(address common0.Address)) *Environment_GetAccountBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.Address + if args[0] != nil { + arg0 = args[0].(common0.Address) + } + run( + arg0, + ) + }) + return _c +} - var r0 error - if rf, ok := ret.Get(0).(func(common.MemoryUsage) error); ok { - r0 = rf(usage) - } else { - r0 = ret.Error(0) - } +func (_c *Environment_GetAccountBalance_Call) Return(value uint64, err error) *Environment_GetAccountBalance_Call { + _c.Call.Return(value, err) + return _c +} - return r0 +func (_c *Environment_GetAccountBalance_Call) RunAndReturn(run func(address common0.Address) (uint64, error)) *Environment_GetAccountBalance_Call { + _c.Call.Return(run) + return _c } -// MinimumRequiredVersion provides a mock function with no fields -func (_m *Environment) MinimumRequiredVersion() (string, error) { - ret := _m.Called() +// GetAccountContractCode provides a mock function for the type Environment +func (_mock *Environment) GetAccountContractCode(location common0.AddressLocation) ([]byte, error) { + ret := _mock.Called(location) if len(ret) == 0 { - panic("no return value specified for MinimumRequiredVersion") + panic("no return value specified for GetAccountContractCode") } - var r0 string + var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func() (string, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func(common0.AddressLocation) ([]byte, error)); ok { + return returnFunc(location) } - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func(common0.AddressLocation) []byte); ok { + r0 = returnFunc(location) } else { - r0 = ret.Get(0).(string) + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func(common0.AddressLocation) error); ok { + r1 = returnFunc(location) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProgramLog provides a mock function with given fields: _a0 -func (_m *Environment) ProgramLog(_a0 string) error { - ret := _m.Called(_a0) +// Environment_GetAccountContractCode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountContractCode' +type Environment_GetAccountContractCode_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for ProgramLog") - } +// GetAccountContractCode is a helper method to define mock.On call +// - location common0.AddressLocation +func (_e *Environment_Expecter) GetAccountContractCode(location interface{}) *Environment_GetAccountContractCode_Call { + return &Environment_GetAccountContractCode_Call{Call: _e.mock.On("GetAccountContractCode", location)} +} - var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } +func (_c *Environment_GetAccountContractCode_Call) Run(run func(location common0.AddressLocation)) *Environment_GetAccountContractCode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.AddressLocation + if args[0] != nil { + arg0 = args[0].(common0.AddressLocation) + } + run( + arg0, + ) + }) + return _c +} - return r0 +func (_c *Environment_GetAccountContractCode_Call) Return(code []byte, err error) *Environment_GetAccountContractCode_Call { + _c.Call.Return(code, err) + return _c +} + +func (_c *Environment_GetAccountContractCode_Call) RunAndReturn(run func(location common0.AddressLocation) ([]byte, error)) *Environment_GetAccountContractCode_Call { + _c.Call.Return(run) + return _c } -// RandomSourceHistory provides a mock function with no fields -func (_m *Environment) RandomSourceHistory() ([]byte, error) { - ret := _m.Called() +// GetAccountContractNames provides a mock function for the type Environment +func (_mock *Environment) GetAccountContractNames(address runtime.Address) ([]string, error) { + ret := _mock.Called(address) if len(ret) == 0 { - panic("no return value specified for RandomSourceHistory") + panic("no return value specified for GetAccountContractNames") } - var r0 []byte + var r0 []string var r1 error - if rf, ok := ret.Get(0).(func() ([]byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func(runtime.Address) ([]string, error)); ok { + return returnFunc(address) } - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func(runtime.Address) []string); ok { + r0 = returnFunc(address) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) + r0 = ret.Get(0).([]string) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func(runtime.Address) error); ok { + r1 = returnFunc(address) } else { r1 = ret.Error(1) } - return r0, r1 } -// ReadRandom provides a mock function with given fields: _a0 -func (_m *Environment) ReadRandom(_a0 []byte) error { - ret := _m.Called(_a0) +// Environment_GetAccountContractNames_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountContractNames' +type Environment_GetAccountContractNames_Call struct { + *mock.Call +} + +// GetAccountContractNames is a helper method to define mock.On call +// - address runtime.Address +func (_e *Environment_Expecter) GetAccountContractNames(address interface{}) *Environment_GetAccountContractNames_Call { + return &Environment_GetAccountContractNames_Call{Call: _e.mock.On("GetAccountContractNames", address)} +} + +func (_c *Environment_GetAccountContractNames_Call) Run(run func(address runtime.Address)) *Environment_GetAccountContractNames_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_GetAccountContractNames_Call) Return(strings []string, err error) *Environment_GetAccountContractNames_Call { + _c.Call.Return(strings, err) + return _c +} + +func (_c *Environment_GetAccountContractNames_Call) RunAndReturn(run func(address runtime.Address) ([]string, error)) *Environment_GetAccountContractNames_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKey provides a mock function for the type Environment +func (_mock *Environment) GetAccountKey(address runtime.Address, index uint32) (*runtime.AccountKey, error) { + ret := _mock.Called(address, index) if len(ret) == 0 { - panic("no return value specified for ReadRandom") + panic("no return value specified for GetAccountKey") } - var r0 error - if rf, ok := ret.Get(0).(func([]byte) error); ok { - r0 = rf(_a0) + var r0 *runtime.AccountKey + var r1 error + if returnFunc, ok := ret.Get(0).(func(runtime.Address, uint32) (*runtime.AccountKey, error)); ok { + return returnFunc(address, index) + } + if returnFunc, ok := ret.Get(0).(func(runtime.Address, uint32) *runtime.AccountKey); ok { + r0 = returnFunc(address, index) } else { - r0 = ret.Error(0) + if ret.Get(0) != nil { + r0 = ret.Get(0).(*runtime.AccountKey) + } } + if returnFunc, ok := ret.Get(1).(func(runtime.Address, uint32) error); ok { + r1 = returnFunc(address, index) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetAccountKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKey' +type Environment_GetAccountKey_Call struct { + *mock.Call +} + +// GetAccountKey is a helper method to define mock.On call +// - address runtime.Address +// - index uint32 +func (_e *Environment_Expecter) GetAccountKey(address interface{}, index interface{}) *Environment_GetAccountKey_Call { + return &Environment_GetAccountKey_Call{Call: _e.mock.On("GetAccountKey", address, index)} +} + +func (_c *Environment_GetAccountKey_Call) Run(run func(address runtime.Address, index uint32)) *Environment_GetAccountKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_GetAccountKey_Call) Return(v *runtime.AccountKey, err error) *Environment_GetAccountKey_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_GetAccountKey_Call) RunAndReturn(run func(address runtime.Address, index uint32) (*runtime.AccountKey, error)) *Environment_GetAccountKey_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeys provides a mock function for the type Environment +func (_mock *Environment) GetAccountKeys(address flow.Address) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(address) + + if len(ret) == 0 { + panic("no return value specified for GetAccountKeys") + } + + var r0 []flow.AccountPublicKey + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(address) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address) []flow.AccountPublicKey); ok { + r0 = returnFunc(address) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]flow.AccountPublicKey) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address) error); ok { + r1 = returnFunc(address) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetAccountKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeys' +type Environment_GetAccountKeys_Call struct { + *mock.Call +} + +// GetAccountKeys is a helper method to define mock.On call +// - address flow.Address +func (_e *Environment_Expecter) GetAccountKeys(address interface{}) *Environment_GetAccountKeys_Call { + return &Environment_GetAccountKeys_Call{Call: _e.mock.On("GetAccountKeys", address)} +} + +func (_c *Environment_GetAccountKeys_Call) Run(run func(address flow.Address)) *Environment_GetAccountKeys_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_GetAccountKeys_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *Environment_GetAccountKeys_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *Environment_GetAccountKeys_Call) RunAndReturn(run func(address flow.Address) ([]flow.AccountPublicKey, error)) *Environment_GetAccountKeys_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockAtHeight provides a mock function for the type Environment +func (_mock *Environment) GetBlockAtHeight(height uint64) (runtime.Block, bool, error) { + ret := _mock.Called(height) + + if len(ret) == 0 { + panic("no return value specified for GetBlockAtHeight") + } + + var r0 runtime.Block + var r1 bool + var r2 error + if returnFunc, ok := ret.Get(0).(func(uint64) (runtime.Block, bool, error)); ok { + return returnFunc(height) + } + if returnFunc, ok := ret.Get(0).(func(uint64) runtime.Block); ok { + r0 = returnFunc(height) + } else { + r0 = ret.Get(0).(runtime.Block) + } + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(height) + } else { + r1 = ret.Get(1).(bool) + } + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(height) + } else { + r2 = ret.Error(2) + } + return r0, r1, r2 +} + +// Environment_GetBlockAtHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockAtHeight' +type Environment_GetBlockAtHeight_Call struct { + *mock.Call +} + +// GetBlockAtHeight is a helper method to define mock.On call +// - height uint64 +func (_e *Environment_Expecter) GetBlockAtHeight(height interface{}) *Environment_GetBlockAtHeight_Call { + return &Environment_GetBlockAtHeight_Call{Call: _e.mock.On("GetBlockAtHeight", height)} +} + +func (_c *Environment_GetBlockAtHeight_Call) Run(run func(height uint64)) *Environment_GetBlockAtHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_GetBlockAtHeight_Call) Return(block runtime.Block, exists bool, err error) *Environment_GetBlockAtHeight_Call { + _c.Call.Return(block, exists, err) + return _c +} + +func (_c *Environment_GetBlockAtHeight_Call) RunAndReturn(run func(height uint64) (runtime.Block, bool, error)) *Environment_GetBlockAtHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetCode provides a mock function for the type Environment +func (_mock *Environment) GetCode(location runtime.Location) ([]byte, error) { + ret := _mock.Called(location) + + if len(ret) == 0 { + panic("no return value specified for GetCode") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func(runtime.Location) ([]byte, error)); ok { + return returnFunc(location) + } + if returnFunc, ok := ret.Get(0).(func(runtime.Location) []byte); ok { + r0 = returnFunc(location) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func(runtime.Location) error); ok { + r1 = returnFunc(location) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetCode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCode' +type Environment_GetCode_Call struct { + *mock.Call +} + +// GetCode is a helper method to define mock.On call +// - location runtime.Location +func (_e *Environment_Expecter) GetCode(location interface{}) *Environment_GetCode_Call { + return &Environment_GetCode_Call{Call: _e.mock.On("GetCode", location)} +} + +func (_c *Environment_GetCode_Call) Run(run func(location runtime.Location)) *Environment_GetCode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Location + if args[0] != nil { + arg0 = args[0].(runtime.Location) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_GetCode_Call) Return(bytes []byte, err error) *Environment_GetCode_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Environment_GetCode_Call) RunAndReturn(run func(location runtime.Location) ([]byte, error)) *Environment_GetCode_Call { + _c.Call.Return(run) + return _c +} + +// GetCurrentBlockHeight provides a mock function for the type Environment +func (_mock *Environment) GetCurrentBlockHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for GetCurrentBlockHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetCurrentBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCurrentBlockHeight' +type Environment_GetCurrentBlockHeight_Call struct { + *mock.Call +} + +// GetCurrentBlockHeight is a helper method to define mock.On call +func (_e *Environment_Expecter) GetCurrentBlockHeight() *Environment_GetCurrentBlockHeight_Call { + return &Environment_GetCurrentBlockHeight_Call{Call: _e.mock.On("GetCurrentBlockHeight")} +} + +func (_c *Environment_GetCurrentBlockHeight_Call) Run(run func()) *Environment_GetCurrentBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_GetCurrentBlockHeight_Call) Return(v uint64, err error) *Environment_GetCurrentBlockHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_GetCurrentBlockHeight_Call) RunAndReturn(run func() (uint64, error)) *Environment_GetCurrentBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetOrLoadProgram provides a mock function for the type Environment +func (_mock *Environment) GetOrLoadProgram(location runtime.Location, load func() (*runtime.Program, error)) (*runtime.Program, error) { + ret := _mock.Called(location, load) + + if len(ret) == 0 { + panic("no return value specified for GetOrLoadProgram") + } + + var r0 *runtime.Program + var r1 error + if returnFunc, ok := ret.Get(0).(func(runtime.Location, func() (*runtime.Program, error)) (*runtime.Program, error)); ok { + return returnFunc(location, load) + } + if returnFunc, ok := ret.Get(0).(func(runtime.Location, func() (*runtime.Program, error)) *runtime.Program); ok { + r0 = returnFunc(location, load) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*runtime.Program) + } + } + if returnFunc, ok := ret.Get(1).(func(runtime.Location, func() (*runtime.Program, error)) error); ok { + r1 = returnFunc(location, load) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetOrLoadProgram_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOrLoadProgram' +type Environment_GetOrLoadProgram_Call struct { + *mock.Call +} + +// GetOrLoadProgram is a helper method to define mock.On call +// - location runtime.Location +// - load func() (*runtime.Program, error) +func (_e *Environment_Expecter) GetOrLoadProgram(location interface{}, load interface{}) *Environment_GetOrLoadProgram_Call { + return &Environment_GetOrLoadProgram_Call{Call: _e.mock.On("GetOrLoadProgram", location, load)} +} + +func (_c *Environment_GetOrLoadProgram_Call) Run(run func(location runtime.Location, load func() (*runtime.Program, error))) *Environment_GetOrLoadProgram_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Location + if args[0] != nil { + arg0 = args[0].(runtime.Location) + } + var arg1 func() (*runtime.Program, error) + if args[1] != nil { + arg1 = args[1].(func() (*runtime.Program, error)) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_GetOrLoadProgram_Call) Return(program *runtime.Program, err error) *Environment_GetOrLoadProgram_Call { + _c.Call.Return(program, err) + return _c +} + +func (_c *Environment_GetOrLoadProgram_Call) RunAndReturn(run func(location runtime.Location, load func() (*runtime.Program, error)) (*runtime.Program, error)) *Environment_GetOrLoadProgram_Call { + _c.Call.Return(run) + return _c +} + +// GetSigningAccounts provides a mock function for the type Environment +func (_mock *Environment) GetSigningAccounts() ([]runtime.Address, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for GetSigningAccounts") + } + + var r0 []runtime.Address + var r1 error + if returnFunc, ok := ret.Get(0).(func() ([]runtime.Address, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() []runtime.Address); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]runtime.Address) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetSigningAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSigningAccounts' +type Environment_GetSigningAccounts_Call struct { + *mock.Call +} + +// GetSigningAccounts is a helper method to define mock.On call +func (_e *Environment_Expecter) GetSigningAccounts() *Environment_GetSigningAccounts_Call { + return &Environment_GetSigningAccounts_Call{Call: _e.mock.On("GetSigningAccounts")} +} + +func (_c *Environment_GetSigningAccounts_Call) Run(run func()) *Environment_GetSigningAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_GetSigningAccounts_Call) Return(vs []runtime.Address, err error) *Environment_GetSigningAccounts_Call { + _c.Call.Return(vs, err) + return _c +} + +func (_c *Environment_GetSigningAccounts_Call) RunAndReturn(run func() ([]runtime.Address, error)) *Environment_GetSigningAccounts_Call { + _c.Call.Return(run) + return _c +} + +// GetStorageCapacity provides a mock function for the type Environment +func (_mock *Environment) GetStorageCapacity(address runtime.Address) (uint64, error) { + ret := _mock.Called(address) + + if len(ret) == 0 { + panic("no return value specified for GetStorageCapacity") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func(runtime.Address) (uint64, error)); ok { + return returnFunc(address) + } + if returnFunc, ok := ret.Get(0).(func(runtime.Address) uint64); ok { + r0 = returnFunc(address) + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func(runtime.Address) error); ok { + r1 = returnFunc(address) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetStorageCapacity_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStorageCapacity' +type Environment_GetStorageCapacity_Call struct { + *mock.Call +} + +// GetStorageCapacity is a helper method to define mock.On call +// - address runtime.Address +func (_e *Environment_Expecter) GetStorageCapacity(address interface{}) *Environment_GetStorageCapacity_Call { + return &Environment_GetStorageCapacity_Call{Call: _e.mock.On("GetStorageCapacity", address)} +} + +func (_c *Environment_GetStorageCapacity_Call) Run(run func(address runtime.Address)) *Environment_GetStorageCapacity_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_GetStorageCapacity_Call) Return(value uint64, err error) *Environment_GetStorageCapacity_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Environment_GetStorageCapacity_Call) RunAndReturn(run func(address runtime.Address) (uint64, error)) *Environment_GetStorageCapacity_Call { + _c.Call.Return(run) + return _c +} + +// GetStorageUsed provides a mock function for the type Environment +func (_mock *Environment) GetStorageUsed(address runtime.Address) (uint64, error) { + ret := _mock.Called(address) + + if len(ret) == 0 { + panic("no return value specified for GetStorageUsed") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func(runtime.Address) (uint64, error)); ok { + return returnFunc(address) + } + if returnFunc, ok := ret.Get(0).(func(runtime.Address) uint64); ok { + r0 = returnFunc(address) + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func(runtime.Address) error); ok { + r1 = returnFunc(address) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetStorageUsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStorageUsed' +type Environment_GetStorageUsed_Call struct { + *mock.Call +} + +// GetStorageUsed is a helper method to define mock.On call +// - address runtime.Address +func (_e *Environment_Expecter) GetStorageUsed(address interface{}) *Environment_GetStorageUsed_Call { + return &Environment_GetStorageUsed_Call{Call: _e.mock.On("GetStorageUsed", address)} +} + +func (_c *Environment_GetStorageUsed_Call) Run(run func(address runtime.Address)) *Environment_GetStorageUsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_GetStorageUsed_Call) Return(value uint64, err error) *Environment_GetStorageUsed_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Environment_GetStorageUsed_Call) RunAndReturn(run func(address runtime.Address) (uint64, error)) *Environment_GetStorageUsed_Call { + _c.Call.Return(run) + return _c +} + +// GetValue provides a mock function for the type Environment +func (_mock *Environment) GetValue(owner []byte, key []byte) ([]byte, error) { + ret := _mock.Called(owner, key) + + if len(ret) == 0 { + panic("no return value specified for GetValue") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) ([]byte, error)); ok { + return returnFunc(owner, key) + } + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) []byte); ok { + r0 = returnFunc(owner, key) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func([]byte, []byte) error); ok { + r1 = returnFunc(owner, key) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_GetValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetValue' +type Environment_GetValue_Call struct { + *mock.Call +} + +// GetValue is a helper method to define mock.On call +// - owner []byte +// - key []byte +func (_e *Environment_Expecter) GetValue(owner interface{}, key interface{}) *Environment_GetValue_Call { + return &Environment_GetValue_Call{Call: _e.mock.On("GetValue", owner, key)} +} + +func (_c *Environment_GetValue_Call) Run(run func(owner []byte, key []byte)) *Environment_GetValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_GetValue_Call) Return(value []byte, err error) *Environment_GetValue_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Environment_GetValue_Call) RunAndReturn(run func(owner []byte, key []byte) ([]byte, error)) *Environment_GetValue_Call { + _c.Call.Return(run) + return _c +} + +// Hash provides a mock function for the type Environment +func (_mock *Environment) Hash(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm) ([]byte, error) { + ret := _mock.Called(data, tag, hashAlgorithm) + + if len(ret) == 0 { + panic("no return value specified for Hash") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) ([]byte, error)); ok { + return returnFunc(data, tag, hashAlgorithm) + } + if returnFunc, ok := ret.Get(0).(func([]byte, string, runtime.HashAlgorithm) []byte); ok { + r0 = returnFunc(data, tag, hashAlgorithm) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func([]byte, string, runtime.HashAlgorithm) error); ok { + r1 = returnFunc(data, tag, hashAlgorithm) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_Hash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Hash' +type Environment_Hash_Call struct { + *mock.Call +} + +// Hash is a helper method to define mock.On call +// - data []byte +// - tag string +// - hashAlgorithm runtime.HashAlgorithm +func (_e *Environment_Expecter) Hash(data interface{}, tag interface{}, hashAlgorithm interface{}) *Environment_Hash_Call { + return &Environment_Hash_Call{Call: _e.mock.On("Hash", data, tag, hashAlgorithm)} +} + +func (_c *Environment_Hash_Call) Run(run func(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm)) *Environment_Hash_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 runtime.HashAlgorithm + if args[2] != nil { + arg2 = args[2].(runtime.HashAlgorithm) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Environment_Hash_Call) Return(bytes []byte, err error) *Environment_Hash_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Environment_Hash_Call) RunAndReturn(run func(data []byte, tag string, hashAlgorithm runtime.HashAlgorithm) ([]byte, error)) *Environment_Hash_Call { + _c.Call.Return(run) + return _c +} + +// ImplementationDebugLog provides a mock function for the type Environment +func (_mock *Environment) ImplementationDebugLog(message string) error { + ret := _mock.Called(message) + + if len(ret) == 0 { + panic("no return value specified for ImplementationDebugLog") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(string) error); ok { + r0 = returnFunc(message) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Environment_ImplementationDebugLog_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ImplementationDebugLog' +type Environment_ImplementationDebugLog_Call struct { + *mock.Call +} + +// ImplementationDebugLog is a helper method to define mock.On call +// - message string +func (_e *Environment_Expecter) ImplementationDebugLog(message interface{}) *Environment_ImplementationDebugLog_Call { + return &Environment_ImplementationDebugLog_Call{Call: _e.mock.On("ImplementationDebugLog", message)} +} + +func (_c *Environment_ImplementationDebugLog_Call) Run(run func(message string)) *Environment_ImplementationDebugLog_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_ImplementationDebugLog_Call) Return(err error) *Environment_ImplementationDebugLog_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_ImplementationDebugLog_Call) RunAndReturn(run func(message string) error) *Environment_ImplementationDebugLog_Call { + _c.Call.Return(run) + return _c +} + +// Invoke provides a mock function for the type Environment +func (_mock *Environment) Invoke(spec environment.ContractFunctionSpec, arguments []cadence.Value) (cadence.Value, error) { + ret := _mock.Called(spec, arguments) + + if len(ret) == 0 { + panic("no return value specified for Invoke") + } + + var r0 cadence.Value + var r1 error + if returnFunc, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) (cadence.Value, error)); ok { + return returnFunc(spec, arguments) + } + if returnFunc, ok := ret.Get(0).(func(environment.ContractFunctionSpec, []cadence.Value) cadence.Value); ok { + r0 = returnFunc(spec, arguments) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(cadence.Value) + } + } + if returnFunc, ok := ret.Get(1).(func(environment.ContractFunctionSpec, []cadence.Value) error); ok { + r1 = returnFunc(spec, arguments) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_Invoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Invoke' +type Environment_Invoke_Call struct { + *mock.Call +} + +// Invoke is a helper method to define mock.On call +// - spec environment.ContractFunctionSpec +// - arguments []cadence.Value +func (_e *Environment_Expecter) Invoke(spec interface{}, arguments interface{}) *Environment_Invoke_Call { + return &Environment_Invoke_Call{Call: _e.mock.On("Invoke", spec, arguments)} +} + +func (_c *Environment_Invoke_Call) Run(run func(spec environment.ContractFunctionSpec, arguments []cadence.Value)) *Environment_Invoke_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.ContractFunctionSpec + if args[0] != nil { + arg0 = args[0].(environment.ContractFunctionSpec) + } + var arg1 []cadence.Value + if args[1] != nil { + arg1 = args[1].([]cadence.Value) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_Invoke_Call) Return(value cadence.Value, err error) *Environment_Invoke_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Environment_Invoke_Call) RunAndReturn(run func(spec environment.ContractFunctionSpec, arguments []cadence.Value) (cadence.Value, error)) *Environment_Invoke_Call { + _c.Call.Return(run) + return _c +} + +// IsServiceAccountAuthorizer provides a mock function for the type Environment +func (_mock *Environment) IsServiceAccountAuthorizer() bool { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for IsServiceAccountAuthorizer") + } + + var r0 bool + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(bool) + } + return r0 +} + +// Environment_IsServiceAccountAuthorizer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsServiceAccountAuthorizer' +type Environment_IsServiceAccountAuthorizer_Call struct { + *mock.Call +} + +// IsServiceAccountAuthorizer is a helper method to define mock.On call +func (_e *Environment_Expecter) IsServiceAccountAuthorizer() *Environment_IsServiceAccountAuthorizer_Call { + return &Environment_IsServiceAccountAuthorizer_Call{Call: _e.mock.On("IsServiceAccountAuthorizer")} +} + +func (_c *Environment_IsServiceAccountAuthorizer_Call) Run(run func()) *Environment_IsServiceAccountAuthorizer_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_IsServiceAccountAuthorizer_Call) Return(b bool) *Environment_IsServiceAccountAuthorizer_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Environment_IsServiceAccountAuthorizer_Call) RunAndReturn(run func() bool) *Environment_IsServiceAccountAuthorizer_Call { + _c.Call.Return(run) + return _c +} + +// LatestBlock provides a mock function for the type Environment +func (_mock *Environment) LatestBlock() (*types.Block, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestBlock") + } + + var r0 *types.Block + var r1 error + if returnFunc, ok := ret.Get(0).(func() (*types.Block, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() *types.Block); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Block) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_LatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestBlock' +type Environment_LatestBlock_Call struct { + *mock.Call +} + +// LatestBlock is a helper method to define mock.On call +func (_e *Environment_Expecter) LatestBlock() *Environment_LatestBlock_Call { + return &Environment_LatestBlock_Call{Call: _e.mock.On("LatestBlock")} +} + +func (_c *Environment_LatestBlock_Call) Run(run func()) *Environment_LatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_LatestBlock_Call) Return(block *types.Block, err error) *Environment_LatestBlock_Call { + _c.Call.Return(block, err) + return _c +} + +func (_c *Environment_LatestBlock_Call) RunAndReturn(run func() (*types.Block, error)) *Environment_LatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// LimitAccountStorage provides a mock function for the type Environment +func (_mock *Environment) LimitAccountStorage() bool { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LimitAccountStorage") + } + + var r0 bool + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(bool) + } + return r0 +} + +// Environment_LimitAccountStorage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LimitAccountStorage' +type Environment_LimitAccountStorage_Call struct { + *mock.Call +} + +// LimitAccountStorage is a helper method to define mock.On call +func (_e *Environment_Expecter) LimitAccountStorage() *Environment_LimitAccountStorage_Call { + return &Environment_LimitAccountStorage_Call{Call: _e.mock.On("LimitAccountStorage")} +} + +func (_c *Environment_LimitAccountStorage_Call) Run(run func()) *Environment_LimitAccountStorage_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_LimitAccountStorage_Call) Return(b bool) *Environment_LimitAccountStorage_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Environment_LimitAccountStorage_Call) RunAndReturn(run func() bool) *Environment_LimitAccountStorage_Call { + _c.Call.Return(run) + return _c +} + +// Logger provides a mock function for the type Environment +func (_mock *Environment) Logger() zerolog.Logger { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Logger") + } + + var r0 zerolog.Logger + if returnFunc, ok := ret.Get(0).(func() zerolog.Logger); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(zerolog.Logger) + } + return r0 +} + +// Environment_Logger_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Logger' +type Environment_Logger_Call struct { + *mock.Call +} + +// Logger is a helper method to define mock.On call +func (_e *Environment_Expecter) Logger() *Environment_Logger_Call { + return &Environment_Logger_Call{Call: _e.mock.On("Logger")} +} + +func (_c *Environment_Logger_Call) Run(run func()) *Environment_Logger_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_Logger_Call) Return(logger zerolog.Logger) *Environment_Logger_Call { + _c.Call.Return(logger) + return _c +} + +func (_c *Environment_Logger_Call) RunAndReturn(run func() zerolog.Logger) *Environment_Logger_Call { + _c.Call.Return(run) + return _c +} + +// Logs provides a mock function for the type Environment +func (_mock *Environment) Logs() []string { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Logs") + } + + var r0 []string + if returnFunc, ok := ret.Get(0).(func() []string); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]string) + } + } + return r0 +} + +// Environment_Logs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Logs' +type Environment_Logs_Call struct { + *mock.Call +} + +// Logs is a helper method to define mock.On call +func (_e *Environment_Expecter) Logs() *Environment_Logs_Call { + return &Environment_Logs_Call{Call: _e.mock.On("Logs")} +} + +func (_c *Environment_Logs_Call) Run(run func()) *Environment_Logs_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_Logs_Call) Return(strings []string) *Environment_Logs_Call { + _c.Call.Return(strings) + return _c +} + +func (_c *Environment_Logs_Call) RunAndReturn(run func() []string) *Environment_Logs_Call { + _c.Call.Return(run) + return _c +} + +// MemoryUsed provides a mock function for the type Environment +func (_mock *Environment) MemoryUsed() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for MemoryUsed") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_MemoryUsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MemoryUsed' +type Environment_MemoryUsed_Call struct { + *mock.Call +} + +// MemoryUsed is a helper method to define mock.On call +func (_e *Environment_Expecter) MemoryUsed() *Environment_MemoryUsed_Call { + return &Environment_MemoryUsed_Call{Call: _e.mock.On("MemoryUsed")} +} + +func (_c *Environment_MemoryUsed_Call) Run(run func()) *Environment_MemoryUsed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_MemoryUsed_Call) Return(v uint64, err error) *Environment_MemoryUsed_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_MemoryUsed_Call) RunAndReturn(run func() (uint64, error)) *Environment_MemoryUsed_Call { + _c.Call.Return(run) + return _c +} + +// MeterComputation provides a mock function for the type Environment +func (_mock *Environment) MeterComputation(usage common0.ComputationUsage) error { + ret := _mock.Called(usage) + + if len(ret) == 0 { + panic("no return value specified for MeterComputation") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(common0.ComputationUsage) error); ok { + r0 = returnFunc(usage) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Environment_MeterComputation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MeterComputation' +type Environment_MeterComputation_Call struct { + *mock.Call +} + +// MeterComputation is a helper method to define mock.On call +// - usage common0.ComputationUsage +func (_e *Environment_Expecter) MeterComputation(usage interface{}) *Environment_MeterComputation_Call { + return &Environment_MeterComputation_Call{Call: _e.mock.On("MeterComputation", usage)} +} + +func (_c *Environment_MeterComputation_Call) Run(run func(usage common0.ComputationUsage)) *Environment_MeterComputation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.ComputationUsage + if args[0] != nil { + arg0 = args[0].(common0.ComputationUsage) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_MeterComputation_Call) Return(err error) *Environment_MeterComputation_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_MeterComputation_Call) RunAndReturn(run func(usage common0.ComputationUsage) error) *Environment_MeterComputation_Call { + _c.Call.Return(run) + return _c +} + +// MeterEmittedEvent provides a mock function for the type Environment +func (_mock *Environment) MeterEmittedEvent(byteSize uint64) error { + ret := _mock.Called(byteSize) + + if len(ret) == 0 { + panic("no return value specified for MeterEmittedEvent") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(byteSize) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Environment_MeterEmittedEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MeterEmittedEvent' +type Environment_MeterEmittedEvent_Call struct { + *mock.Call +} + +// MeterEmittedEvent is a helper method to define mock.On call +// - byteSize uint64 +func (_e *Environment_Expecter) MeterEmittedEvent(byteSize interface{}) *Environment_MeterEmittedEvent_Call { + return &Environment_MeterEmittedEvent_Call{Call: _e.mock.On("MeterEmittedEvent", byteSize)} +} + +func (_c *Environment_MeterEmittedEvent_Call) Run(run func(byteSize uint64)) *Environment_MeterEmittedEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_MeterEmittedEvent_Call) Return(err error) *Environment_MeterEmittedEvent_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_MeterEmittedEvent_Call) RunAndReturn(run func(byteSize uint64) error) *Environment_MeterEmittedEvent_Call { + _c.Call.Return(run) + return _c +} + +// MeterMemory provides a mock function for the type Environment +func (_mock *Environment) MeterMemory(usage common0.MemoryUsage) error { + ret := _mock.Called(usage) + + if len(ret) == 0 { + panic("no return value specified for MeterMemory") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(common0.MemoryUsage) error); ok { + r0 = returnFunc(usage) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Environment_MeterMemory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MeterMemory' +type Environment_MeterMemory_Call struct { + *mock.Call +} + +// MeterMemory is a helper method to define mock.On call +// - usage common0.MemoryUsage +func (_e *Environment_Expecter) MeterMemory(usage interface{}) *Environment_MeterMemory_Call { + return &Environment_MeterMemory_Call{Call: _e.mock.On("MeterMemory", usage)} +} + +func (_c *Environment_MeterMemory_Call) Run(run func(usage common0.MemoryUsage)) *Environment_MeterMemory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.MemoryUsage + if args[0] != nil { + arg0 = args[0].(common0.MemoryUsage) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_MeterMemory_Call) Return(err error) *Environment_MeterMemory_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_MeterMemory_Call) RunAndReturn(run func(usage common0.MemoryUsage) error) *Environment_MeterMemory_Call { + _c.Call.Return(run) + return _c +} + +// MinimumRequiredVersion provides a mock function for the type Environment +func (_mock *Environment) MinimumRequiredVersion() (string, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for MinimumRequiredVersion") + } + + var r0 string + var r1 error + if returnFunc, ok := ret.Get(0).(func() (string, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(string) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_MinimumRequiredVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MinimumRequiredVersion' +type Environment_MinimumRequiredVersion_Call struct { + *mock.Call +} + +// MinimumRequiredVersion is a helper method to define mock.On call +func (_e *Environment_Expecter) MinimumRequiredVersion() *Environment_MinimumRequiredVersion_Call { + return &Environment_MinimumRequiredVersion_Call{Call: _e.mock.On("MinimumRequiredVersion")} +} + +func (_c *Environment_MinimumRequiredVersion_Call) Run(run func()) *Environment_MinimumRequiredVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_MinimumRequiredVersion_Call) Return(s string, err error) *Environment_MinimumRequiredVersion_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *Environment_MinimumRequiredVersion_Call) RunAndReturn(run func() (string, error)) *Environment_MinimumRequiredVersion_Call { + _c.Call.Return(run) + return _c +} + +// ProgramLog provides a mock function for the type Environment +func (_mock *Environment) ProgramLog(s string) error { + ret := _mock.Called(s) + + if len(ret) == 0 { + panic("no return value specified for ProgramLog") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(string) error); ok { + r0 = returnFunc(s) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Environment_ProgramLog_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProgramLog' +type Environment_ProgramLog_Call struct { + *mock.Call +} + +// ProgramLog is a helper method to define mock.On call +// - s string +func (_e *Environment_Expecter) ProgramLog(s interface{}) *Environment_ProgramLog_Call { + return &Environment_ProgramLog_Call{Call: _e.mock.On("ProgramLog", s)} +} + +func (_c *Environment_ProgramLog_Call) Run(run func(s string)) *Environment_ProgramLog_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_ProgramLog_Call) Return(err error) *Environment_ProgramLog_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_ProgramLog_Call) RunAndReturn(run func(s string) error) *Environment_ProgramLog_Call { + _c.Call.Return(run) + return _c +} + +// RandomSourceHistory provides a mock function for the type Environment +func (_mock *Environment) RandomSourceHistory() ([]byte, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for RandomSourceHistory") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func() ([]byte, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_RandomSourceHistory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RandomSourceHistory' +type Environment_RandomSourceHistory_Call struct { + *mock.Call +} + +// RandomSourceHistory is a helper method to define mock.On call +func (_e *Environment_Expecter) RandomSourceHistory() *Environment_RandomSourceHistory_Call { + return &Environment_RandomSourceHistory_Call{Call: _e.mock.On("RandomSourceHistory")} +} + +func (_c *Environment_RandomSourceHistory_Call) Run(run func()) *Environment_RandomSourceHistory_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_RandomSourceHistory_Call) Return(bytes []byte, err error) *Environment_RandomSourceHistory_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Environment_RandomSourceHistory_Call) RunAndReturn(run func() ([]byte, error)) *Environment_RandomSourceHistory_Call { + _c.Call.Return(run) + return _c +} + +// ReadRandom provides a mock function for the type Environment +func (_mock *Environment) ReadRandom(bytes []byte) error { + ret := _mock.Called(bytes) + + if len(ret) == 0 { + panic("no return value specified for ReadRandom") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func([]byte) error); ok { + r0 = returnFunc(bytes) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Environment_ReadRandom_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadRandom' +type Environment_ReadRandom_Call struct { + *mock.Call +} + +// ReadRandom is a helper method to define mock.On call +// - bytes []byte +func (_e *Environment_Expecter) ReadRandom(bytes interface{}) *Environment_ReadRandom_Call { + return &Environment_ReadRandom_Call{Call: _e.mock.On("ReadRandom", bytes)} +} + +func (_c *Environment_ReadRandom_Call) Run(run func(bytes []byte)) *Environment_ReadRandom_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_ReadRandom_Call) Return(err error) *Environment_ReadRandom_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_ReadRandom_Call) RunAndReturn(run func(bytes []byte) error) *Environment_ReadRandom_Call { + _c.Call.Return(run) + return _c +} + +// RecordTrace provides a mock function for the type Environment +func (_mock *Environment) RecordTrace(operation string, duration time.Duration, attrs []attribute.KeyValue) { + _mock.Called(operation, duration, attrs) + return +} + +// Environment_RecordTrace_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RecordTrace' +type Environment_RecordTrace_Call struct { + *mock.Call +} + +// RecordTrace is a helper method to define mock.On call +// - operation string +// - duration time.Duration +// - attrs []attribute.KeyValue +func (_e *Environment_Expecter) RecordTrace(operation interface{}, duration interface{}, attrs interface{}) *Environment_RecordTrace_Call { + return &Environment_RecordTrace_Call{Call: _e.mock.On("RecordTrace", operation, duration, attrs)} +} + +func (_c *Environment_RecordTrace_Call) Run(run func(operation string, duration time.Duration, attrs []attribute.KeyValue)) *Environment_RecordTrace_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + var arg2 []attribute.KeyValue + if args[2] != nil { + arg2 = args[2].([]attribute.KeyValue) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Environment_RecordTrace_Call) Return() *Environment_RecordTrace_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_RecordTrace_Call) RunAndReturn(run func(operation string, duration time.Duration, attrs []attribute.KeyValue)) *Environment_RecordTrace_Call { + _c.Run(run) + return _c +} + +// RecoverProgram provides a mock function for the type Environment +func (_mock *Environment) RecoverProgram(program *ast.Program, location common0.Location) ([]byte, error) { + ret := _mock.Called(program, location) + + if len(ret) == 0 { + panic("no return value specified for RecoverProgram") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func(*ast.Program, common0.Location) ([]byte, error)); ok { + return returnFunc(program, location) + } + if returnFunc, ok := ret.Get(0).(func(*ast.Program, common0.Location) []byte); ok { + r0 = returnFunc(program, location) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func(*ast.Program, common0.Location) error); ok { + r1 = returnFunc(program, location) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_RecoverProgram_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RecoverProgram' +type Environment_RecoverProgram_Call struct { + *mock.Call +} + +// RecoverProgram is a helper method to define mock.On call +// - program *ast.Program +// - location common0.Location +func (_e *Environment_Expecter) RecoverProgram(program interface{}, location interface{}) *Environment_RecoverProgram_Call { + return &Environment_RecoverProgram_Call{Call: _e.mock.On("RecoverProgram", program, location)} +} + +func (_c *Environment_RecoverProgram_Call) Run(run func(program *ast.Program, location common0.Location)) *Environment_RecoverProgram_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *ast.Program + if args[0] != nil { + arg0 = args[0].(*ast.Program) + } + var arg1 common0.Location + if args[1] != nil { + arg1 = args[1].(common0.Location) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_RecoverProgram_Call) Return(bytes []byte, err error) *Environment_RecoverProgram_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Environment_RecoverProgram_Call) RunAndReturn(run func(program *ast.Program, location common0.Location) ([]byte, error)) *Environment_RecoverProgram_Call { + _c.Call.Return(run) + return _c +} + +// RemoveAccountContractCode provides a mock function for the type Environment +func (_mock *Environment) RemoveAccountContractCode(location common0.AddressLocation) error { + ret := _mock.Called(location) + + if len(ret) == 0 { + panic("no return value specified for RemoveAccountContractCode") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(common0.AddressLocation) error); ok { + r0 = returnFunc(location) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Environment_RemoveAccountContractCode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemoveAccountContractCode' +type Environment_RemoveAccountContractCode_Call struct { + *mock.Call +} + +// RemoveAccountContractCode is a helper method to define mock.On call +// - location common0.AddressLocation +func (_e *Environment_Expecter) RemoveAccountContractCode(location interface{}) *Environment_RemoveAccountContractCode_Call { + return &Environment_RemoveAccountContractCode_Call{Call: _e.mock.On("RemoveAccountContractCode", location)} +} + +func (_c *Environment_RemoveAccountContractCode_Call) Run(run func(location common0.AddressLocation)) *Environment_RemoveAccountContractCode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.AddressLocation + if args[0] != nil { + arg0 = args[0].(common0.AddressLocation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_RemoveAccountContractCode_Call) Return(err error) *Environment_RemoveAccountContractCode_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_RemoveAccountContractCode_Call) RunAndReturn(run func(location common0.AddressLocation) error) *Environment_RemoveAccountContractCode_Call { + _c.Call.Return(run) + return _c +} + +// Reset provides a mock function for the type Environment +func (_mock *Environment) Reset() { + _mock.Called() + return +} + +// Environment_Reset_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reset' +type Environment_Reset_Call struct { + *mock.Call +} + +// Reset is a helper method to define mock.On call +func (_e *Environment_Expecter) Reset() *Environment_Reset_Call { + return &Environment_Reset_Call{Call: _e.mock.On("Reset")} +} + +func (_c *Environment_Reset_Call) Run(run func()) *Environment_Reset_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_Reset_Call) Return() *Environment_Reset_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_Reset_Call) RunAndReturn(run func()) *Environment_Reset_Call { + _c.Run(run) + return _c +} + +// ResolveLocation provides a mock function for the type Environment +func (_mock *Environment) ResolveLocation(identifiers []runtime.Identifier, location runtime.Location) ([]runtime.ResolvedLocation, error) { + ret := _mock.Called(identifiers, location) + + if len(ret) == 0 { + panic("no return value specified for ResolveLocation") + } + + var r0 []runtime.ResolvedLocation + var r1 error + if returnFunc, ok := ret.Get(0).(func([]runtime.Identifier, runtime.Location) ([]runtime.ResolvedLocation, error)); ok { + return returnFunc(identifiers, location) + } + if returnFunc, ok := ret.Get(0).(func([]runtime.Identifier, runtime.Location) []runtime.ResolvedLocation); ok { + r0 = returnFunc(identifiers, location) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]runtime.ResolvedLocation) + } + } + if returnFunc, ok := ret.Get(1).(func([]runtime.Identifier, runtime.Location) error); ok { + r1 = returnFunc(identifiers, location) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_ResolveLocation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResolveLocation' +type Environment_ResolveLocation_Call struct { + *mock.Call +} + +// ResolveLocation is a helper method to define mock.On call +// - identifiers []runtime.Identifier +// - location runtime.Location +func (_e *Environment_Expecter) ResolveLocation(identifiers interface{}, location interface{}) *Environment_ResolveLocation_Call { + return &Environment_ResolveLocation_Call{Call: _e.mock.On("ResolveLocation", identifiers, location)} +} + +func (_c *Environment_ResolveLocation_Call) Run(run func(identifiers []runtime.Identifier, location runtime.Location)) *Environment_ResolveLocation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []runtime.Identifier + if args[0] != nil { + arg0 = args[0].([]runtime.Identifier) + } + var arg1 runtime.Location + if args[1] != nil { + arg1 = args[1].(runtime.Location) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_ResolveLocation_Call) Return(vs []runtime.ResolvedLocation, err error) *Environment_ResolveLocation_Call { + _c.Call.Return(vs, err) + return _c +} + +func (_c *Environment_ResolveLocation_Call) RunAndReturn(run func(identifiers []runtime.Identifier, location runtime.Location) ([]runtime.ResolvedLocation, error)) *Environment_ResolveLocation_Call { + _c.Call.Return(run) + return _c +} + +// ResourceOwnerChanged provides a mock function for the type Environment +func (_mock *Environment) ResourceOwnerChanged(interpreter1 *interpreter.Interpreter, resource *interpreter.CompositeValue, oldOwner common0.Address, newOwner common0.Address) { + _mock.Called(interpreter1, resource, oldOwner, newOwner) + return +} + +// Environment_ResourceOwnerChanged_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResourceOwnerChanged' +type Environment_ResourceOwnerChanged_Call struct { + *mock.Call +} + +// ResourceOwnerChanged is a helper method to define mock.On call +// - interpreter1 *interpreter.Interpreter +// - resource *interpreter.CompositeValue +// - oldOwner common0.Address +// - newOwner common0.Address +func (_e *Environment_Expecter) ResourceOwnerChanged(interpreter1 interface{}, resource interface{}, oldOwner interface{}, newOwner interface{}) *Environment_ResourceOwnerChanged_Call { + return &Environment_ResourceOwnerChanged_Call{Call: _e.mock.On("ResourceOwnerChanged", interpreter1, resource, oldOwner, newOwner)} +} + +func (_c *Environment_ResourceOwnerChanged_Call) Run(run func(interpreter1 *interpreter.Interpreter, resource *interpreter.CompositeValue, oldOwner common0.Address, newOwner common0.Address)) *Environment_ResourceOwnerChanged_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *interpreter.Interpreter + if args[0] != nil { + arg0 = args[0].(*interpreter.Interpreter) + } + var arg1 *interpreter.CompositeValue + if args[1] != nil { + arg1 = args[1].(*interpreter.CompositeValue) + } + var arg2 common0.Address + if args[2] != nil { + arg2 = args[2].(common0.Address) + } + var arg3 common0.Address + if args[3] != nil { + arg3 = args[3].(common0.Address) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Environment_ResourceOwnerChanged_Call) Return() *Environment_ResourceOwnerChanged_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_ResourceOwnerChanged_Call) RunAndReturn(run func(interpreter1 *interpreter.Interpreter, resource *interpreter.CompositeValue, oldOwner common0.Address, newOwner common0.Address)) *Environment_ResourceOwnerChanged_Call { + _c.Run(run) + return _c +} + +// ReturnCadenceRuntime provides a mock function for the type Environment +func (_mock *Environment) ReturnCadenceRuntime(reusableCadenceRuntime environment.ReusableCadenceRuntime) { + _mock.Called(reusableCadenceRuntime) + return +} + +// Environment_ReturnCadenceRuntime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReturnCadenceRuntime' +type Environment_ReturnCadenceRuntime_Call struct { + *mock.Call +} + +// ReturnCadenceRuntime is a helper method to define mock.On call +// - reusableCadenceRuntime environment.ReusableCadenceRuntime +func (_e *Environment_Expecter) ReturnCadenceRuntime(reusableCadenceRuntime interface{}) *Environment_ReturnCadenceRuntime_Call { + return &Environment_ReturnCadenceRuntime_Call{Call: _e.mock.On("ReturnCadenceRuntime", reusableCadenceRuntime)} +} + +func (_c *Environment_ReturnCadenceRuntime_Call) Run(run func(reusableCadenceRuntime environment.ReusableCadenceRuntime)) *Environment_ReturnCadenceRuntime_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.ReusableCadenceRuntime + if args[0] != nil { + arg0 = args[0].(environment.ReusableCadenceRuntime) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_ReturnCadenceRuntime_Call) Return() *Environment_ReturnCadenceRuntime_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_ReturnCadenceRuntime_Call) RunAndReturn(run func(reusableCadenceRuntime environment.ReusableCadenceRuntime)) *Environment_ReturnCadenceRuntime_Call { + _c.Run(run) + return _c +} + +// RevokeAccountKey provides a mock function for the type Environment +func (_mock *Environment) RevokeAccountKey(address runtime.Address, index uint32) (*runtime.AccountKey, error) { + ret := _mock.Called(address, index) + + if len(ret) == 0 { + panic("no return value specified for RevokeAccountKey") + } + + var r0 *runtime.AccountKey + var r1 error + if returnFunc, ok := ret.Get(0).(func(runtime.Address, uint32) (*runtime.AccountKey, error)); ok { + return returnFunc(address, index) + } + if returnFunc, ok := ret.Get(0).(func(runtime.Address, uint32) *runtime.AccountKey); ok { + r0 = returnFunc(address, index) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*runtime.AccountKey) + } + } + if returnFunc, ok := ret.Get(1).(func(runtime.Address, uint32) error); ok { + r1 = returnFunc(address, index) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Environment_RevokeAccountKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RevokeAccountKey' +type Environment_RevokeAccountKey_Call struct { + *mock.Call +} + +// RevokeAccountKey is a helper method to define mock.On call +// - address runtime.Address +// - index uint32 +func (_e *Environment_Expecter) RevokeAccountKey(address interface{}, index interface{}) *Environment_RevokeAccountKey_Call { + return &Environment_RevokeAccountKey_Call{Call: _e.mock.On("RevokeAccountKey", address, index)} +} + +func (_c *Environment_RevokeAccountKey_Call) Run(run func(address runtime.Address, index uint32)) *Environment_RevokeAccountKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Address + if args[0] != nil { + arg0 = args[0].(runtime.Address) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_RevokeAccountKey_Call) Return(v *runtime.AccountKey, err error) *Environment_RevokeAccountKey_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Environment_RevokeAccountKey_Call) RunAndReturn(run func(address runtime.Address, index uint32) (*runtime.AccountKey, error)) *Environment_RevokeAccountKey_Call { + _c.Call.Return(run) + return _c +} + +// RunWithMeteringDisabled provides a mock function for the type Environment +func (_mock *Environment) RunWithMeteringDisabled(f func()) { + _mock.Called(f) + return +} + +// Environment_RunWithMeteringDisabled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RunWithMeteringDisabled' +type Environment_RunWithMeteringDisabled_Call struct { + *mock.Call +} + +// RunWithMeteringDisabled is a helper method to define mock.On call +// - f func() +func (_e *Environment_Expecter) RunWithMeteringDisabled(f interface{}) *Environment_RunWithMeteringDisabled_Call { + return &Environment_RunWithMeteringDisabled_Call{Call: _e.mock.On("RunWithMeteringDisabled", f)} +} + +func (_c *Environment_RunWithMeteringDisabled_Call) Run(run func(f func())) *Environment_RunWithMeteringDisabled_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func() + if args[0] != nil { + arg0 = args[0].(func()) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_RunWithMeteringDisabled_Call) Return() *Environment_RunWithMeteringDisabled_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_RunWithMeteringDisabled_Call) RunAndReturn(run func(f func())) *Environment_RunWithMeteringDisabled_Call { + _c.Run(run) + return _c +} + +// RuntimeSetNumberOfAccounts provides a mock function for the type Environment +func (_mock *Environment) RuntimeSetNumberOfAccounts(count uint64) { + _mock.Called(count) + return +} + +// Environment_RuntimeSetNumberOfAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeSetNumberOfAccounts' +type Environment_RuntimeSetNumberOfAccounts_Call struct { + *mock.Call +} + +// RuntimeSetNumberOfAccounts is a helper method to define mock.On call +// - count uint64 +func (_e *Environment_Expecter) RuntimeSetNumberOfAccounts(count interface{}) *Environment_RuntimeSetNumberOfAccounts_Call { + return &Environment_RuntimeSetNumberOfAccounts_Call{Call: _e.mock.On("RuntimeSetNumberOfAccounts", count)} +} + +func (_c *Environment_RuntimeSetNumberOfAccounts_Call) Run(run func(count uint64)) *Environment_RuntimeSetNumberOfAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_RuntimeSetNumberOfAccounts_Call) Return() *Environment_RuntimeSetNumberOfAccounts_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_RuntimeSetNumberOfAccounts_Call) RunAndReturn(run func(count uint64)) *Environment_RuntimeSetNumberOfAccounts_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionChecked provides a mock function for the type Environment +func (_mock *Environment) RuntimeTransactionChecked(duration time.Duration) { + _mock.Called(duration) + return +} + +// Environment_RuntimeTransactionChecked_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionChecked' +type Environment_RuntimeTransactionChecked_Call struct { + *mock.Call +} + +// RuntimeTransactionChecked is a helper method to define mock.On call +// - duration time.Duration +func (_e *Environment_Expecter) RuntimeTransactionChecked(duration interface{}) *Environment_RuntimeTransactionChecked_Call { + return &Environment_RuntimeTransactionChecked_Call{Call: _e.mock.On("RuntimeTransactionChecked", duration)} +} + +func (_c *Environment_RuntimeTransactionChecked_Call) Run(run func(duration time.Duration)) *Environment_RuntimeTransactionChecked_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_RuntimeTransactionChecked_Call) Return() *Environment_RuntimeTransactionChecked_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_RuntimeTransactionChecked_Call) RunAndReturn(run func(duration time.Duration)) *Environment_RuntimeTransactionChecked_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionInterpreted provides a mock function for the type Environment +func (_mock *Environment) RuntimeTransactionInterpreted(duration time.Duration) { + _mock.Called(duration) + return +} + +// Environment_RuntimeTransactionInterpreted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionInterpreted' +type Environment_RuntimeTransactionInterpreted_Call struct { + *mock.Call +} + +// RuntimeTransactionInterpreted is a helper method to define mock.On call +// - duration time.Duration +func (_e *Environment_Expecter) RuntimeTransactionInterpreted(duration interface{}) *Environment_RuntimeTransactionInterpreted_Call { + return &Environment_RuntimeTransactionInterpreted_Call{Call: _e.mock.On("RuntimeTransactionInterpreted", duration)} +} + +func (_c *Environment_RuntimeTransactionInterpreted_Call) Run(run func(duration time.Duration)) *Environment_RuntimeTransactionInterpreted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_RuntimeTransactionInterpreted_Call) Return() *Environment_RuntimeTransactionInterpreted_Call { + _c.Call.Return() + return _c +} - return r0 +func (_c *Environment_RuntimeTransactionInterpreted_Call) RunAndReturn(run func(duration time.Duration)) *Environment_RuntimeTransactionInterpreted_Call { + _c.Run(run) + return _c } -// RecordTrace provides a mock function with given fields: operation, duration, attrs -func (_m *Environment) RecordTrace(operation string, duration time.Duration, attrs []attribute.KeyValue) { - _m.Called(operation, duration, attrs) +// RuntimeTransactionParsed provides a mock function for the type Environment +func (_mock *Environment) RuntimeTransactionParsed(duration time.Duration) { + _mock.Called(duration) + return } -// RecoverProgram provides a mock function with given fields: program, location -func (_m *Environment) RecoverProgram(program *ast.Program, location common.Location) ([]byte, error) { - ret := _m.Called(program, location) +// Environment_RuntimeTransactionParsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionParsed' +type Environment_RuntimeTransactionParsed_Call struct { + *mock.Call +} - if len(ret) == 0 { - panic("no return value specified for RecoverProgram") - } +// RuntimeTransactionParsed is a helper method to define mock.On call +// - duration time.Duration +func (_e *Environment_Expecter) RuntimeTransactionParsed(duration interface{}) *Environment_RuntimeTransactionParsed_Call { + return &Environment_RuntimeTransactionParsed_Call{Call: _e.mock.On("RuntimeTransactionParsed", duration)} +} - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(*ast.Program, common.Location) ([]byte, error)); ok { - return rf(program, location) - } - if rf, ok := ret.Get(0).(func(*ast.Program, common.Location) []byte); ok { - r0 = rf(program, location) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) +func (_c *Environment_RuntimeTransactionParsed_Call) Run(run func(duration time.Duration)) *Environment_RuntimeTransactionParsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) } - } + run( + arg0, + ) + }) + return _c +} - if rf, ok := ret.Get(1).(func(*ast.Program, common.Location) error); ok { - r1 = rf(program, location) - } else { - r1 = ret.Error(1) - } +func (_c *Environment_RuntimeTransactionParsed_Call) Return() *Environment_RuntimeTransactionParsed_Call { + _c.Call.Return() + return _c +} - return r0, r1 +func (_c *Environment_RuntimeTransactionParsed_Call) RunAndReturn(run func(duration time.Duration)) *Environment_RuntimeTransactionParsed_Call { + _c.Run(run) + return _c } -// RemoveAccountContractCode provides a mock function with given fields: location -func (_m *Environment) RemoveAccountContractCode(location common.AddressLocation) error { - ret := _m.Called(location) +// RuntimeTransactionProgramsCacheHit provides a mock function for the type Environment +func (_mock *Environment) RuntimeTransactionProgramsCacheHit() { + _mock.Called() + return +} - if len(ret) == 0 { - panic("no return value specified for RemoveAccountContractCode") - } +// Environment_RuntimeTransactionProgramsCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheHit' +type Environment_RuntimeTransactionProgramsCacheHit_Call struct { + *mock.Call +} - var r0 error - if rf, ok := ret.Get(0).(func(common.AddressLocation) error); ok { - r0 = rf(location) - } else { - r0 = ret.Error(0) - } +// RuntimeTransactionProgramsCacheHit is a helper method to define mock.On call +func (_e *Environment_Expecter) RuntimeTransactionProgramsCacheHit() *Environment_RuntimeTransactionProgramsCacheHit_Call { + return &Environment_RuntimeTransactionProgramsCacheHit_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheHit")} +} - return r0 +func (_c *Environment_RuntimeTransactionProgramsCacheHit_Call) Run(run func()) *Environment_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// Reset provides a mock function with no fields -func (_m *Environment) Reset() { - _m.Called() +func (_c *Environment_RuntimeTransactionProgramsCacheHit_Call) Return() *Environment_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Return() + return _c } -// ResolveLocation provides a mock function with given fields: identifiers, location -func (_m *Environment) ResolveLocation(identifiers []runtime.Identifier, location runtime.Location) ([]runtime.ResolvedLocation, error) { - ret := _m.Called(identifiers, location) +func (_c *Environment_RuntimeTransactionProgramsCacheHit_Call) RunAndReturn(run func()) *Environment_RuntimeTransactionProgramsCacheHit_Call { + _c.Run(run) + return _c +} - if len(ret) == 0 { - panic("no return value specified for ResolveLocation") - } +// RuntimeTransactionProgramsCacheMiss provides a mock function for the type Environment +func (_mock *Environment) RuntimeTransactionProgramsCacheMiss() { + _mock.Called() + return +} - var r0 []runtime.ResolvedLocation - var r1 error - if rf, ok := ret.Get(0).(func([]runtime.Identifier, runtime.Location) ([]runtime.ResolvedLocation, error)); ok { - return rf(identifiers, location) - } - if rf, ok := ret.Get(0).(func([]runtime.Identifier, runtime.Location) []runtime.ResolvedLocation); ok { - r0 = rf(identifiers, location) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]runtime.ResolvedLocation) - } - } +// Environment_RuntimeTransactionProgramsCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheMiss' +type Environment_RuntimeTransactionProgramsCacheMiss_Call struct { + *mock.Call +} - if rf, ok := ret.Get(1).(func([]runtime.Identifier, runtime.Location) error); ok { - r1 = rf(identifiers, location) - } else { - r1 = ret.Error(1) - } +// RuntimeTransactionProgramsCacheMiss is a helper method to define mock.On call +func (_e *Environment_Expecter) RuntimeTransactionProgramsCacheMiss() *Environment_RuntimeTransactionProgramsCacheMiss_Call { + return &Environment_RuntimeTransactionProgramsCacheMiss_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheMiss")} +} - return r0, r1 +func (_c *Environment_RuntimeTransactionProgramsCacheMiss_Call) Run(run func()) *Environment_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// ResourceOwnerChanged provides a mock function with given fields: _a0, resource, oldOwner, newOwner -func (_m *Environment) ResourceOwnerChanged(_a0 *interpreter.Interpreter, resource *interpreter.CompositeValue, oldOwner common.Address, newOwner common.Address) { - _m.Called(_a0, resource, oldOwner, newOwner) +func (_c *Environment_RuntimeTransactionProgramsCacheMiss_Call) Return() *Environment_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Return() + return _c } -// ReturnCadenceRuntime provides a mock function with given fields: _a0 -func (_m *Environment) ReturnCadenceRuntime(_a0 *fvmruntime.ReusableCadenceRuntime) { - _m.Called(_a0) +func (_c *Environment_RuntimeTransactionProgramsCacheMiss_Call) RunAndReturn(run func()) *Environment_RuntimeTransactionProgramsCacheMiss_Call { + _c.Run(run) + return _c } -// RevokeAccountKey provides a mock function with given fields: address, index -func (_m *Environment) RevokeAccountKey(address runtime.Address, index uint32) (*runtime.AccountKey, error) { - ret := _m.Called(address, index) +// ServiceEvents provides a mock function for the type Environment +func (_mock *Environment) ServiceEvents() flow.EventsList { + ret := _mock.Called() if len(ret) == 0 { - panic("no return value specified for RevokeAccountKey") + panic("no return value specified for ServiceEvents") } - var r0 *runtime.AccountKey - var r1 error - if rf, ok := ret.Get(0).(func(runtime.Address, uint32) (*runtime.AccountKey, error)); ok { - return rf(address, index) - } - if rf, ok := ret.Get(0).(func(runtime.Address, uint32) *runtime.AccountKey); ok { - r0 = rf(address, index) + var r0 flow.EventsList + if returnFunc, ok := ret.Get(0).(func() flow.EventsList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*runtime.AccountKey) + r0 = ret.Get(0).(flow.EventsList) } } - - if rf, ok := ret.Get(1).(func(runtime.Address, uint32) error); ok { - r1 = rf(address, index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 + return r0 } -// RunWithMeteringDisabled provides a mock function with given fields: f -func (_m *Environment) RunWithMeteringDisabled(f func()) { - _m.Called(f) +// Environment_ServiceEvents_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ServiceEvents' +type Environment_ServiceEvents_Call struct { + *mock.Call } -// RuntimeSetNumberOfAccounts provides a mock function with given fields: count -func (_m *Environment) RuntimeSetNumberOfAccounts(count uint64) { - _m.Called(count) +// ServiceEvents is a helper method to define mock.On call +func (_e *Environment_Expecter) ServiceEvents() *Environment_ServiceEvents_Call { + return &Environment_ServiceEvents_Call{Call: _e.mock.On("ServiceEvents")} } -// RuntimeTransactionChecked provides a mock function with given fields: _a0 -func (_m *Environment) RuntimeTransactionChecked(_a0 time.Duration) { - _m.Called(_a0) +func (_c *Environment_ServiceEvents_Call) Run(run func()) *Environment_ServiceEvents_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// RuntimeTransactionInterpreted provides a mock function with given fields: _a0 -func (_m *Environment) RuntimeTransactionInterpreted(_a0 time.Duration) { - _m.Called(_a0) +func (_c *Environment_ServiceEvents_Call) Return(eventsList flow.EventsList) *Environment_ServiceEvents_Call { + _c.Call.Return(eventsList) + return _c } -// RuntimeTransactionParsed provides a mock function with given fields: _a0 -func (_m *Environment) RuntimeTransactionParsed(_a0 time.Duration) { - _m.Called(_a0) +func (_c *Environment_ServiceEvents_Call) RunAndReturn(run func() flow.EventsList) *Environment_ServiceEvents_Call { + _c.Call.Return(run) + return _c } -// RuntimeTransactionProgramsCacheHit provides a mock function with no fields -func (_m *Environment) RuntimeTransactionProgramsCacheHit() { - _m.Called() +// SetNumberOfDeployedCOAs provides a mock function for the type Environment +func (_mock *Environment) SetNumberOfDeployedCOAs(count uint64) { + _mock.Called(count) + return } -// RuntimeTransactionProgramsCacheMiss provides a mock function with no fields -func (_m *Environment) RuntimeTransactionProgramsCacheMiss() { - _m.Called() +// Environment_SetNumberOfDeployedCOAs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetNumberOfDeployedCOAs' +type Environment_SetNumberOfDeployedCOAs_Call struct { + *mock.Call } -// ServiceEvents provides a mock function with no fields -func (_m *Environment) ServiceEvents() flow.EventsList { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for ServiceEvents") - } +// SetNumberOfDeployedCOAs is a helper method to define mock.On call +// - count uint64 +func (_e *Environment_Expecter) SetNumberOfDeployedCOAs(count interface{}) *Environment_SetNumberOfDeployedCOAs_Call { + return &Environment_SetNumberOfDeployedCOAs_Call{Call: _e.mock.On("SetNumberOfDeployedCOAs", count)} +} - var r0 flow.EventsList - if rf, ok := ret.Get(0).(func() flow.EventsList); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(flow.EventsList) +func (_c *Environment_SetNumberOfDeployedCOAs_Call) Run(run func(count uint64)) *Environment_SetNumberOfDeployedCOAs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) } - } + run( + arg0, + ) + }) + return _c +} - return r0 +func (_c *Environment_SetNumberOfDeployedCOAs_Call) Return() *Environment_SetNumberOfDeployedCOAs_Call { + _c.Call.Return() + return _c } -// SetNumberOfDeployedCOAs provides a mock function with given fields: count -func (_m *Environment) SetNumberOfDeployedCOAs(count uint64) { - _m.Called(count) +func (_c *Environment_SetNumberOfDeployedCOAs_Call) RunAndReturn(run func(count uint64)) *Environment_SetNumberOfDeployedCOAs_Call { + _c.Run(run) + return _c } -// SetValue provides a mock function with given fields: owner, key, value -func (_m *Environment) SetValue(owner []byte, key []byte, value []byte) error { - ret := _m.Called(owner, key, value) +// SetValue provides a mock function for the type Environment +func (_mock *Environment) SetValue(owner []byte, key []byte, value []byte) error { + ret := _mock.Called(owner, key, value) if len(ret) == 0 { panic("no return value specified for SetValue") } var r0 error - if rf, ok := ret.Get(0).(func([]byte, []byte, []byte) error); ok { - r0 = rf(owner, key, value) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte, []byte) error); ok { + r0 = returnFunc(owner, key, value) } else { r0 = ret.Error(0) } - return r0 } -// StartChildSpan provides a mock function with given fields: name, options -func (_m *Environment) StartChildSpan(name trace.SpanName, options ...oteltrace.SpanStartOption) tracing.TracerSpan { +// Environment_SetValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetValue' +type Environment_SetValue_Call struct { + *mock.Call +} + +// SetValue is a helper method to define mock.On call +// - owner []byte +// - key []byte +// - value []byte +func (_e *Environment_Expecter) SetValue(owner interface{}, key interface{}, value interface{}) *Environment_SetValue_Call { + return &Environment_SetValue_Call{Call: _e.mock.On("SetValue", owner, key, value)} +} + +func (_c *Environment_SetValue_Call) Run(run func(owner []byte, key []byte, value []byte)) *Environment_SetValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Environment_SetValue_Call) Return(err error) *Environment_SetValue_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_SetValue_Call) RunAndReturn(run func(owner []byte, key []byte, value []byte) error) *Environment_SetValue_Call { + _c.Call.Return(run) + return _c +} + +// StageBlockProposal provides a mock function for the type Environment +func (_mock *Environment) StageBlockProposal(blockProposal *types.BlockProposal) { + _mock.Called(blockProposal) + return +} + +// Environment_StageBlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StageBlockProposal' +type Environment_StageBlockProposal_Call struct { + *mock.Call +} + +// StageBlockProposal is a helper method to define mock.On call +// - blockProposal *types.BlockProposal +func (_e *Environment_Expecter) StageBlockProposal(blockProposal interface{}) *Environment_StageBlockProposal_Call { + return &Environment_StageBlockProposal_Call{Call: _e.mock.On("StageBlockProposal", blockProposal)} +} + +func (_c *Environment_StageBlockProposal_Call) Run(run func(blockProposal *types.BlockProposal)) *Environment_StageBlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *types.BlockProposal + if args[0] != nil { + arg0 = args[0].(*types.BlockProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_StageBlockProposal_Call) Return() *Environment_StageBlockProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *Environment_StageBlockProposal_Call) RunAndReturn(run func(blockProposal *types.BlockProposal)) *Environment_StageBlockProposal_Call { + _c.Run(run) + return _c +} + +// StartChildSpan provides a mock function for the type Environment +func (_mock *Environment) StartChildSpan(name trace.SpanName, options ...trace0.SpanStartOption) tracing.TracerSpan { + // trace0.SpanStartOption _va := make([]interface{}, len(options)) for _i := range options { _va[_i] = options[_i] @@ -1614,117 +4349,304 @@ func (_m *Environment) StartChildSpan(name trace.SpanName, options ...oteltrace. var _ca []interface{} _ca = append(_ca, name) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartChildSpan") } var r0 tracing.TracerSpan - if rf, ok := ret.Get(0).(func(trace.SpanName, ...oteltrace.SpanStartOption) tracing.TracerSpan); ok { - r0 = rf(name, options...) + if returnFunc, ok := ret.Get(0).(func(trace.SpanName, ...trace0.SpanStartOption) tracing.TracerSpan); ok { + r0 = returnFunc(name, options...) } else { r0 = ret.Get(0).(tracing.TracerSpan) } - return r0 } -// TotalEmittedEventBytes provides a mock function with no fields -func (_m *Environment) TotalEmittedEventBytes() uint64 { - ret := _m.Called() +// Environment_StartChildSpan_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartChildSpan' +type Environment_StartChildSpan_Call struct { + *mock.Call +} + +// StartChildSpan is a helper method to define mock.On call +// - name trace.SpanName +// - options ...trace0.SpanStartOption +func (_e *Environment_Expecter) StartChildSpan(name interface{}, options ...interface{}) *Environment_StartChildSpan_Call { + return &Environment_StartChildSpan_Call{Call: _e.mock.On("StartChildSpan", + append([]interface{}{name}, options...)...)} +} + +func (_c *Environment_StartChildSpan_Call) Run(run func(name trace.SpanName, options ...trace0.SpanStartOption)) *Environment_StartChildSpan_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 trace.SpanName + if args[0] != nil { + arg0 = args[0].(trace.SpanName) + } + var arg1 []trace0.SpanStartOption + variadicArgs := make([]trace0.SpanStartOption, len(args)-1) + for i, a := range args[1:] { + if a != nil { + variadicArgs[i] = a.(trace0.SpanStartOption) + } + } + arg1 = variadicArgs + run( + arg0, + arg1..., + ) + }) + return _c +} + +func (_c *Environment_StartChildSpan_Call) Return(tracerSpan tracing.TracerSpan) *Environment_StartChildSpan_Call { + _c.Call.Return(tracerSpan) + return _c +} + +func (_c *Environment_StartChildSpan_Call) RunAndReturn(run func(name trace.SpanName, options ...trace0.SpanStartOption) tracing.TracerSpan) *Environment_StartChildSpan_Call { + _c.Call.Return(run) + return _c +} + +// TotalEmittedEventBytes provides a mock function for the type Environment +func (_mock *Environment) TotalEmittedEventBytes() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TotalEmittedEventBytes") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// TransactionFeesEnabled provides a mock function with no fields -func (_m *Environment) TransactionFeesEnabled() bool { - ret := _m.Called() +// Environment_TotalEmittedEventBytes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TotalEmittedEventBytes' +type Environment_TotalEmittedEventBytes_Call struct { + *mock.Call +} + +// TotalEmittedEventBytes is a helper method to define mock.On call +func (_e *Environment_Expecter) TotalEmittedEventBytes() *Environment_TotalEmittedEventBytes_Call { + return &Environment_TotalEmittedEventBytes_Call{Call: _e.mock.On("TotalEmittedEventBytes")} +} + +func (_c *Environment_TotalEmittedEventBytes_Call) Run(run func()) *Environment_TotalEmittedEventBytes_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_TotalEmittedEventBytes_Call) Return(v uint64) *Environment_TotalEmittedEventBytes_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Environment_TotalEmittedEventBytes_Call) RunAndReturn(run func() uint64) *Environment_TotalEmittedEventBytes_Call { + _c.Call.Return(run) + return _c +} + +// TransactionFeesEnabled provides a mock function for the type Environment +func (_mock *Environment) TransactionFeesEnabled() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TransactionFeesEnabled") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// TxID provides a mock function with no fields -func (_m *Environment) TxID() flow.Identifier { - ret := _m.Called() +// Environment_TransactionFeesEnabled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionFeesEnabled' +type Environment_TransactionFeesEnabled_Call struct { + *mock.Call +} + +// TransactionFeesEnabled is a helper method to define mock.On call +func (_e *Environment_Expecter) TransactionFeesEnabled() *Environment_TransactionFeesEnabled_Call { + return &Environment_TransactionFeesEnabled_Call{Call: _e.mock.On("TransactionFeesEnabled")} +} + +func (_c *Environment_TransactionFeesEnabled_Call) Run(run func()) *Environment_TransactionFeesEnabled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_TransactionFeesEnabled_Call) Return(b bool) *Environment_TransactionFeesEnabled_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Environment_TransactionFeesEnabled_Call) RunAndReturn(run func() bool) *Environment_TransactionFeesEnabled_Call { + _c.Call.Return(run) + return _c +} + +// TxID provides a mock function for the type Environment +func (_mock *Environment) TxID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TxID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// TxIndex provides a mock function with no fields -func (_m *Environment) TxIndex() uint32 { - ret := _m.Called() +// Environment_TxID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxID' +type Environment_TxID_Call struct { + *mock.Call +} + +// TxID is a helper method to define mock.On call +func (_e *Environment_Expecter) TxID() *Environment_TxID_Call { + return &Environment_TxID_Call{Call: _e.mock.On("TxID")} +} + +func (_c *Environment_TxID_Call) Run(run func()) *Environment_TxID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_TxID_Call) Return(identifier flow.Identifier) *Environment_TxID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *Environment_TxID_Call) RunAndReturn(run func() flow.Identifier) *Environment_TxID_Call { + _c.Call.Return(run) + return _c +} + +// TxIndex provides a mock function for the type Environment +func (_mock *Environment) TxIndex() uint32 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TxIndex") } var r0 uint32 - if rf, ok := ret.Get(0).(func() uint32); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint32); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint32) } - return r0 } -// UpdateAccountContractCode provides a mock function with given fields: location, code -func (_m *Environment) UpdateAccountContractCode(location common.AddressLocation, code []byte) error { - ret := _m.Called(location, code) +// Environment_TxIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxIndex' +type Environment_TxIndex_Call struct { + *mock.Call +} + +// TxIndex is a helper method to define mock.On call +func (_e *Environment_Expecter) TxIndex() *Environment_TxIndex_Call { + return &Environment_TxIndex_Call{Call: _e.mock.On("TxIndex")} +} + +func (_c *Environment_TxIndex_Call) Run(run func()) *Environment_TxIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Environment_TxIndex_Call) Return(v uint32) *Environment_TxIndex_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Environment_TxIndex_Call) RunAndReturn(run func() uint32) *Environment_TxIndex_Call { + _c.Call.Return(run) + return _c +} + +// UpdateAccountContractCode provides a mock function for the type Environment +func (_mock *Environment) UpdateAccountContractCode(location common0.AddressLocation, code []byte) error { + ret := _mock.Called(location, code) if len(ret) == 0 { panic("no return value specified for UpdateAccountContractCode") } var r0 error - if rf, ok := ret.Get(0).(func(common.AddressLocation, []byte) error); ok { - r0 = rf(location, code) + if returnFunc, ok := ret.Get(0).(func(common0.AddressLocation, []byte) error); ok { + r0 = returnFunc(location, code) } else { r0 = ret.Error(0) } - return r0 } -// ValidateAccountCapabilitiesGet provides a mock function with given fields: context, address, path, wantedBorrowType, capabilityBorrowType -func (_m *Environment) ValidateAccountCapabilitiesGet(context interpreter.AccountCapabilityGetValidationContext, address interpreter.AddressValue, path interpreter.PathValue, wantedBorrowType *sema.ReferenceType, capabilityBorrowType *sema.ReferenceType) (bool, error) { - ret := _m.Called(context, address, path, wantedBorrowType, capabilityBorrowType) +// Environment_UpdateAccountContractCode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateAccountContractCode' +type Environment_UpdateAccountContractCode_Call struct { + *mock.Call +} + +// UpdateAccountContractCode is a helper method to define mock.On call +// - location common0.AddressLocation +// - code []byte +func (_e *Environment_Expecter) UpdateAccountContractCode(location interface{}, code interface{}) *Environment_UpdateAccountContractCode_Call { + return &Environment_UpdateAccountContractCode_Call{Call: _e.mock.On("UpdateAccountContractCode", location, code)} +} + +func (_c *Environment_UpdateAccountContractCode_Call) Run(run func(location common0.AddressLocation, code []byte)) *Environment_UpdateAccountContractCode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common0.AddressLocation + if args[0] != nil { + arg0 = args[0].(common0.AddressLocation) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_UpdateAccountContractCode_Call) Return(err error) *Environment_UpdateAccountContractCode_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_UpdateAccountContractCode_Call) RunAndReturn(run func(location common0.AddressLocation, code []byte) error) *Environment_UpdateAccountContractCode_Call { + _c.Call.Return(run) + return _c +} + +// ValidateAccountCapabilitiesGet provides a mock function for the type Environment +func (_mock *Environment) ValidateAccountCapabilitiesGet(context interpreter.AccountCapabilityGetValidationContext, address interpreter.AddressValue, path interpreter.PathValue, wantedBorrowType *sema.ReferenceType, capabilityBorrowType *sema.ReferenceType) (bool, error) { + ret := _mock.Called(context, address, path, wantedBorrowType, capabilityBorrowType) if len(ret) == 0 { panic("no return value specified for ValidateAccountCapabilitiesGet") @@ -1732,27 +4654,83 @@ func (_m *Environment) ValidateAccountCapabilitiesGet(context interpreter.Accoun var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(interpreter.AccountCapabilityGetValidationContext, interpreter.AddressValue, interpreter.PathValue, *sema.ReferenceType, *sema.ReferenceType) (bool, error)); ok { - return rf(context, address, path, wantedBorrowType, capabilityBorrowType) + if returnFunc, ok := ret.Get(0).(func(interpreter.AccountCapabilityGetValidationContext, interpreter.AddressValue, interpreter.PathValue, *sema.ReferenceType, *sema.ReferenceType) (bool, error)); ok { + return returnFunc(context, address, path, wantedBorrowType, capabilityBorrowType) } - if rf, ok := ret.Get(0).(func(interpreter.AccountCapabilityGetValidationContext, interpreter.AddressValue, interpreter.PathValue, *sema.ReferenceType, *sema.ReferenceType) bool); ok { - r0 = rf(context, address, path, wantedBorrowType, capabilityBorrowType) + if returnFunc, ok := ret.Get(0).(func(interpreter.AccountCapabilityGetValidationContext, interpreter.AddressValue, interpreter.PathValue, *sema.ReferenceType, *sema.ReferenceType) bool); ok { + r0 = returnFunc(context, address, path, wantedBorrowType, capabilityBorrowType) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(interpreter.AccountCapabilityGetValidationContext, interpreter.AddressValue, interpreter.PathValue, *sema.ReferenceType, *sema.ReferenceType) error); ok { - r1 = rf(context, address, path, wantedBorrowType, capabilityBorrowType) + if returnFunc, ok := ret.Get(1).(func(interpreter.AccountCapabilityGetValidationContext, interpreter.AddressValue, interpreter.PathValue, *sema.ReferenceType, *sema.ReferenceType) error); ok { + r1 = returnFunc(context, address, path, wantedBorrowType, capabilityBorrowType) } else { r1 = ret.Error(1) } - return r0, r1 } -// ValidateAccountCapabilitiesPublish provides a mock function with given fields: context, address, path, capabilityBorrowType -func (_m *Environment) ValidateAccountCapabilitiesPublish(context interpreter.AccountCapabilityPublishValidationContext, address interpreter.AddressValue, path interpreter.PathValue, capabilityBorrowType *interpreter.ReferenceStaticType) (bool, error) { - ret := _m.Called(context, address, path, capabilityBorrowType) +// Environment_ValidateAccountCapabilitiesGet_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidateAccountCapabilitiesGet' +type Environment_ValidateAccountCapabilitiesGet_Call struct { + *mock.Call +} + +// ValidateAccountCapabilitiesGet is a helper method to define mock.On call +// - context interpreter.AccountCapabilityGetValidationContext +// - address interpreter.AddressValue +// - path interpreter.PathValue +// - wantedBorrowType *sema.ReferenceType +// - capabilityBorrowType *sema.ReferenceType +func (_e *Environment_Expecter) ValidateAccountCapabilitiesGet(context interface{}, address interface{}, path interface{}, wantedBorrowType interface{}, capabilityBorrowType interface{}) *Environment_ValidateAccountCapabilitiesGet_Call { + return &Environment_ValidateAccountCapabilitiesGet_Call{Call: _e.mock.On("ValidateAccountCapabilitiesGet", context, address, path, wantedBorrowType, capabilityBorrowType)} +} + +func (_c *Environment_ValidateAccountCapabilitiesGet_Call) Run(run func(context interpreter.AccountCapabilityGetValidationContext, address interpreter.AddressValue, path interpreter.PathValue, wantedBorrowType *sema.ReferenceType, capabilityBorrowType *sema.ReferenceType)) *Environment_ValidateAccountCapabilitiesGet_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 interpreter.AccountCapabilityGetValidationContext + if args[0] != nil { + arg0 = args[0].(interpreter.AccountCapabilityGetValidationContext) + } + var arg1 interpreter.AddressValue + if args[1] != nil { + arg1 = args[1].(interpreter.AddressValue) + } + var arg2 interpreter.PathValue + if args[2] != nil { + arg2 = args[2].(interpreter.PathValue) + } + var arg3 *sema.ReferenceType + if args[3] != nil { + arg3 = args[3].(*sema.ReferenceType) + } + var arg4 *sema.ReferenceType + if args[4] != nil { + arg4 = args[4].(*sema.ReferenceType) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *Environment_ValidateAccountCapabilitiesGet_Call) Return(b bool, err error) *Environment_ValidateAccountCapabilitiesGet_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Environment_ValidateAccountCapabilitiesGet_Call) RunAndReturn(run func(context interpreter.AccountCapabilityGetValidationContext, address interpreter.AddressValue, path interpreter.PathValue, wantedBorrowType *sema.ReferenceType, capabilityBorrowType *sema.ReferenceType) (bool, error)) *Environment_ValidateAccountCapabilitiesGet_Call { + _c.Call.Return(run) + return _c +} + +// ValidateAccountCapabilitiesPublish provides a mock function for the type Environment +func (_mock *Environment) ValidateAccountCapabilitiesPublish(context interpreter.AccountCapabilityPublishValidationContext, address interpreter.AddressValue, path interpreter.PathValue, capabilityBorrowType *interpreter.ReferenceStaticType) (bool, error) { + ret := _mock.Called(context, address, path, capabilityBorrowType) if len(ret) == 0 { panic("no return value specified for ValidateAccountCapabilitiesPublish") @@ -1760,45 +4738,128 @@ func (_m *Environment) ValidateAccountCapabilitiesPublish(context interpreter.Ac var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(interpreter.AccountCapabilityPublishValidationContext, interpreter.AddressValue, interpreter.PathValue, *interpreter.ReferenceStaticType) (bool, error)); ok { - return rf(context, address, path, capabilityBorrowType) + if returnFunc, ok := ret.Get(0).(func(interpreter.AccountCapabilityPublishValidationContext, interpreter.AddressValue, interpreter.PathValue, *interpreter.ReferenceStaticType) (bool, error)); ok { + return returnFunc(context, address, path, capabilityBorrowType) } - if rf, ok := ret.Get(0).(func(interpreter.AccountCapabilityPublishValidationContext, interpreter.AddressValue, interpreter.PathValue, *interpreter.ReferenceStaticType) bool); ok { - r0 = rf(context, address, path, capabilityBorrowType) + if returnFunc, ok := ret.Get(0).(func(interpreter.AccountCapabilityPublishValidationContext, interpreter.AddressValue, interpreter.PathValue, *interpreter.ReferenceStaticType) bool); ok { + r0 = returnFunc(context, address, path, capabilityBorrowType) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(interpreter.AccountCapabilityPublishValidationContext, interpreter.AddressValue, interpreter.PathValue, *interpreter.ReferenceStaticType) error); ok { - r1 = rf(context, address, path, capabilityBorrowType) + if returnFunc, ok := ret.Get(1).(func(interpreter.AccountCapabilityPublishValidationContext, interpreter.AddressValue, interpreter.PathValue, *interpreter.ReferenceStaticType) error); ok { + r1 = returnFunc(context, address, path, capabilityBorrowType) } else { r1 = ret.Error(1) } - return r0, r1 } -// ValidatePublicKey provides a mock function with given fields: key -func (_m *Environment) ValidatePublicKey(key *runtime.PublicKey) error { - ret := _m.Called(key) +// Environment_ValidateAccountCapabilitiesPublish_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidateAccountCapabilitiesPublish' +type Environment_ValidateAccountCapabilitiesPublish_Call struct { + *mock.Call +} + +// ValidateAccountCapabilitiesPublish is a helper method to define mock.On call +// - context interpreter.AccountCapabilityPublishValidationContext +// - address interpreter.AddressValue +// - path interpreter.PathValue +// - capabilityBorrowType *interpreter.ReferenceStaticType +func (_e *Environment_Expecter) ValidateAccountCapabilitiesPublish(context interface{}, address interface{}, path interface{}, capabilityBorrowType interface{}) *Environment_ValidateAccountCapabilitiesPublish_Call { + return &Environment_ValidateAccountCapabilitiesPublish_Call{Call: _e.mock.On("ValidateAccountCapabilitiesPublish", context, address, path, capabilityBorrowType)} +} + +func (_c *Environment_ValidateAccountCapabilitiesPublish_Call) Run(run func(context interpreter.AccountCapabilityPublishValidationContext, address interpreter.AddressValue, path interpreter.PathValue, capabilityBorrowType *interpreter.ReferenceStaticType)) *Environment_ValidateAccountCapabilitiesPublish_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 interpreter.AccountCapabilityPublishValidationContext + if args[0] != nil { + arg0 = args[0].(interpreter.AccountCapabilityPublishValidationContext) + } + var arg1 interpreter.AddressValue + if args[1] != nil { + arg1 = args[1].(interpreter.AddressValue) + } + var arg2 interpreter.PathValue + if args[2] != nil { + arg2 = args[2].(interpreter.PathValue) + } + var arg3 *interpreter.ReferenceStaticType + if args[3] != nil { + arg3 = args[3].(*interpreter.ReferenceStaticType) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Environment_ValidateAccountCapabilitiesPublish_Call) Return(b bool, err error) *Environment_ValidateAccountCapabilitiesPublish_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Environment_ValidateAccountCapabilitiesPublish_Call) RunAndReturn(run func(context interpreter.AccountCapabilityPublishValidationContext, address interpreter.AddressValue, path interpreter.PathValue, capabilityBorrowType *interpreter.ReferenceStaticType) (bool, error)) *Environment_ValidateAccountCapabilitiesPublish_Call { + _c.Call.Return(run) + return _c +} + +// ValidatePublicKey provides a mock function for the type Environment +func (_mock *Environment) ValidatePublicKey(key *runtime.PublicKey) error { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for ValidatePublicKey") } var r0 error - if rf, ok := ret.Get(0).(func(*runtime.PublicKey) error); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(*runtime.PublicKey) error); ok { + r0 = returnFunc(key) } else { r0 = ret.Error(0) } - return r0 } -// ValueExists provides a mock function with given fields: owner, key -func (_m *Environment) ValueExists(owner []byte, key []byte) (bool, error) { - ret := _m.Called(owner, key) +// Environment_ValidatePublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidatePublicKey' +type Environment_ValidatePublicKey_Call struct { + *mock.Call +} + +// ValidatePublicKey is a helper method to define mock.On call +// - key *runtime.PublicKey +func (_e *Environment_Expecter) ValidatePublicKey(key interface{}) *Environment_ValidatePublicKey_Call { + return &Environment_ValidatePublicKey_Call{Call: _e.mock.On("ValidatePublicKey", key)} +} + +func (_c *Environment_ValidatePublicKey_Call) Run(run func(key *runtime.PublicKey)) *Environment_ValidatePublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *runtime.PublicKey + if args[0] != nil { + arg0 = args[0].(*runtime.PublicKey) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Environment_ValidatePublicKey_Call) Return(err error) *Environment_ValidatePublicKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Environment_ValidatePublicKey_Call) RunAndReturn(run func(key *runtime.PublicKey) error) *Environment_ValidatePublicKey_Call { + _c.Call.Return(run) + return _c +} + +// ValueExists provides a mock function for the type Environment +func (_mock *Environment) ValueExists(owner []byte, key []byte) (bool, error) { + ret := _mock.Called(owner, key) if len(ret) == 0 { panic("no return value specified for ValueExists") @@ -1806,27 +4867,65 @@ func (_m *Environment) ValueExists(owner []byte, key []byte) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func([]byte, []byte) (bool, error)); ok { - return rf(owner, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) (bool, error)); ok { + return returnFunc(owner, key) } - if rf, ok := ret.Get(0).(func([]byte, []byte) bool); ok { - r0 = rf(owner, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) bool); ok { + r0 = returnFunc(owner, key) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func([]byte, []byte) error); ok { - r1 = rf(owner, key) + if returnFunc, ok := ret.Get(1).(func([]byte, []byte) error); ok { + r1 = returnFunc(owner, key) } else { r1 = ret.Error(1) } - return r0, r1 } -// VerifySignature provides a mock function with given fields: signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm -func (_m *Environment) VerifySignature(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm) (bool, error) { - ret := _m.Called(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) +// Environment_ValueExists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValueExists' +type Environment_ValueExists_Call struct { + *mock.Call +} + +// ValueExists is a helper method to define mock.On call +// - owner []byte +// - key []byte +func (_e *Environment_Expecter) ValueExists(owner interface{}, key interface{}) *Environment_ValueExists_Call { + return &Environment_ValueExists_Call{Call: _e.mock.On("ValueExists", owner, key)} +} + +func (_c *Environment_ValueExists_Call) Run(run func(owner []byte, key []byte)) *Environment_ValueExists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Environment_ValueExists_Call) Return(exists bool, err error) *Environment_ValueExists_Call { + _c.Call.Return(exists, err) + return _c +} + +func (_c *Environment_ValueExists_Call) RunAndReturn(run func(owner []byte, key []byte) (bool, error)) *Environment_ValueExists_Call { + _c.Call.Return(run) + return _c +} + +// VerifySignature provides a mock function for the type Environment +func (_mock *Environment) VerifySignature(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm) (bool, error) { + ret := _mock.Called(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) if len(ret) == 0 { panic("no return value specified for VerifySignature") @@ -1834,34 +4933,82 @@ func (_m *Environment) VerifySignature(signature []byte, tag string, signedData var r0 bool var r1 error - if rf, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) (bool, error)); ok { - return rf(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) (bool, error)); ok { + return returnFunc(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) } - if rf, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) bool); ok { - r0 = rf(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) + if returnFunc, ok := ret.Get(0).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) bool); ok { + r0 = returnFunc(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) error); ok { - r1 = rf(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) + if returnFunc, ok := ret.Get(1).(func([]byte, string, []byte, []byte, runtime.SignatureAlgorithm, runtime.HashAlgorithm) error); ok { + r1 = returnFunc(signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEnvironment creates a new instance of Environment. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEnvironment(t interface { - mock.TestingT - Cleanup(func()) -}) *Environment { - mock := &Environment{} - mock.Mock.Test(t) +// Environment_VerifySignature_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifySignature' +type Environment_VerifySignature_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VerifySignature is a helper method to define mock.On call +// - signature []byte +// - tag string +// - signedData []byte +// - publicKey []byte +// - signatureAlgorithm runtime.SignatureAlgorithm +// - hashAlgorithm runtime.HashAlgorithm +func (_e *Environment_Expecter) VerifySignature(signature interface{}, tag interface{}, signedData interface{}, publicKey interface{}, signatureAlgorithm interface{}, hashAlgorithm interface{}) *Environment_VerifySignature_Call { + return &Environment_VerifySignature_Call{Call: _e.mock.On("VerifySignature", signature, tag, signedData, publicKey, signatureAlgorithm, hashAlgorithm)} +} - return mock +func (_c *Environment_VerifySignature_Call) Run(run func(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm)) *Environment_VerifySignature_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 []byte + if args[3] != nil { + arg3 = args[3].([]byte) + } + var arg4 runtime.SignatureAlgorithm + if args[4] != nil { + arg4 = args[4].(runtime.SignatureAlgorithm) + } + var arg5 runtime.HashAlgorithm + if args[5] != nil { + arg5 = args[5].(runtime.HashAlgorithm) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + ) + }) + return _c +} + +func (_c *Environment_VerifySignature_Call) Return(b bool, err error) *Environment_VerifySignature_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Environment_VerifySignature_Call) RunAndReturn(run func(signature []byte, tag string, signedData []byte, publicKey []byte, signatureAlgorithm runtime.SignatureAlgorithm, hashAlgorithm runtime.HashAlgorithm) (bool, error)) *Environment_VerifySignature_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/event_emitter.go b/fvm/environment/mock/event_emitter.go index 3bc17f8bf14..2a847634082 100644 --- a/fvm/environment/mock/event_emitter.go +++ b/fvm/environment/mock/event_emitter.go @@ -1,113 +1,260 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cadence "github.com/onflow/cadence" - - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/cadence" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewEventEmitter creates a new instance of EventEmitter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEventEmitter(t interface { + mock.TestingT + Cleanup(func()) +}) *EventEmitter { + mock := &EventEmitter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EventEmitter is an autogenerated mock type for the EventEmitter type type EventEmitter struct { mock.Mock } -// ConvertedServiceEvents provides a mock function with no fields -func (_m *EventEmitter) ConvertedServiceEvents() flow.ServiceEventList { - ret := _m.Called() +type EventEmitter_Expecter struct { + mock *mock.Mock +} + +func (_m *EventEmitter) EXPECT() *EventEmitter_Expecter { + return &EventEmitter_Expecter{mock: &_m.Mock} +} + +// ConvertedServiceEvents provides a mock function for the type EventEmitter +func (_mock *EventEmitter) ConvertedServiceEvents() flow.ServiceEventList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ConvertedServiceEvents") } var r0 flow.ServiceEventList - if rf, ok := ret.Get(0).(func() flow.ServiceEventList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ServiceEventList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.ServiceEventList) } } - return r0 } -// EmitEvent provides a mock function with given fields: event -func (_m *EventEmitter) EmitEvent(event cadence.Event) error { - ret := _m.Called(event) +// EventEmitter_ConvertedServiceEvents_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConvertedServiceEvents' +type EventEmitter_ConvertedServiceEvents_Call struct { + *mock.Call +} + +// ConvertedServiceEvents is a helper method to define mock.On call +func (_e *EventEmitter_Expecter) ConvertedServiceEvents() *EventEmitter_ConvertedServiceEvents_Call { + return &EventEmitter_ConvertedServiceEvents_Call{Call: _e.mock.On("ConvertedServiceEvents")} +} + +func (_c *EventEmitter_ConvertedServiceEvents_Call) Run(run func()) *EventEmitter_ConvertedServiceEvents_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EventEmitter_ConvertedServiceEvents_Call) Return(serviceEventList flow.ServiceEventList) *EventEmitter_ConvertedServiceEvents_Call { + _c.Call.Return(serviceEventList) + return _c +} + +func (_c *EventEmitter_ConvertedServiceEvents_Call) RunAndReturn(run func() flow.ServiceEventList) *EventEmitter_ConvertedServiceEvents_Call { + _c.Call.Return(run) + return _c +} + +// EmitEvent provides a mock function for the type EventEmitter +func (_mock *EventEmitter) EmitEvent(event cadence.Event) error { + ret := _mock.Called(event) if len(ret) == 0 { panic("no return value specified for EmitEvent") } var r0 error - if rf, ok := ret.Get(0).(func(cadence.Event) error); ok { - r0 = rf(event) + if returnFunc, ok := ret.Get(0).(func(cadence.Event) error); ok { + r0 = returnFunc(event) } else { r0 = ret.Error(0) } - return r0 } -// Events provides a mock function with no fields -func (_m *EventEmitter) Events() flow.EventsList { - ret := _m.Called() +// EventEmitter_EmitEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EmitEvent' +type EventEmitter_EmitEvent_Call struct { + *mock.Call +} + +// EmitEvent is a helper method to define mock.On call +// - event cadence.Event +func (_e *EventEmitter_Expecter) EmitEvent(event interface{}) *EventEmitter_EmitEvent_Call { + return &EventEmitter_EmitEvent_Call{Call: _e.mock.On("EmitEvent", event)} +} + +func (_c *EventEmitter_EmitEvent_Call) Run(run func(event cadence.Event)) *EventEmitter_EmitEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 cadence.Event + if args[0] != nil { + arg0 = args[0].(cadence.Event) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventEmitter_EmitEvent_Call) Return(err error) *EventEmitter_EmitEvent_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EventEmitter_EmitEvent_Call) RunAndReturn(run func(event cadence.Event) error) *EventEmitter_EmitEvent_Call { + _c.Call.Return(run) + return _c +} + +// Events provides a mock function for the type EventEmitter +func (_mock *EventEmitter) Events() flow.EventsList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Events") } var r0 flow.EventsList - if rf, ok := ret.Get(0).(func() flow.EventsList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.EventsList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.EventsList) } } - return r0 } -// Reset provides a mock function with no fields -func (_m *EventEmitter) Reset() { - _m.Called() +// EventEmitter_Events_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Events' +type EventEmitter_Events_Call struct { + *mock.Call +} + +// Events is a helper method to define mock.On call +func (_e *EventEmitter_Expecter) Events() *EventEmitter_Events_Call { + return &EventEmitter_Events_Call{Call: _e.mock.On("Events")} +} + +func (_c *EventEmitter_Events_Call) Run(run func()) *EventEmitter_Events_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EventEmitter_Events_Call) Return(eventsList flow.EventsList) *EventEmitter_Events_Call { + _c.Call.Return(eventsList) + return _c +} + +func (_c *EventEmitter_Events_Call) RunAndReturn(run func() flow.EventsList) *EventEmitter_Events_Call { + _c.Call.Return(run) + return _c +} + +// Reset provides a mock function for the type EventEmitter +func (_mock *EventEmitter) Reset() { + _mock.Called() + return +} + +// EventEmitter_Reset_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reset' +type EventEmitter_Reset_Call struct { + *mock.Call +} + +// Reset is a helper method to define mock.On call +func (_e *EventEmitter_Expecter) Reset() *EventEmitter_Reset_Call { + return &EventEmitter_Reset_Call{Call: _e.mock.On("Reset")} +} + +func (_c *EventEmitter_Reset_Call) Run(run func()) *EventEmitter_Reset_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EventEmitter_Reset_Call) Return() *EventEmitter_Reset_Call { + _c.Call.Return() + return _c +} + +func (_c *EventEmitter_Reset_Call) RunAndReturn(run func()) *EventEmitter_Reset_Call { + _c.Run(run) + return _c } -// ServiceEvents provides a mock function with no fields -func (_m *EventEmitter) ServiceEvents() flow.EventsList { - ret := _m.Called() +// ServiceEvents provides a mock function for the type EventEmitter +func (_mock *EventEmitter) ServiceEvents() flow.EventsList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ServiceEvents") } var r0 flow.EventsList - if rf, ok := ret.Get(0).(func() flow.EventsList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.EventsList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.EventsList) } } - return r0 } -// NewEventEmitter creates a new instance of EventEmitter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEventEmitter(t interface { - mock.TestingT - Cleanup(func()) -}) *EventEmitter { - mock := &EventEmitter{} - mock.Mock.Test(t) +// EventEmitter_ServiceEvents_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ServiceEvents' +type EventEmitter_ServiceEvents_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ServiceEvents is a helper method to define mock.On call +func (_e *EventEmitter_Expecter) ServiceEvents() *EventEmitter_ServiceEvents_Call { + return &EventEmitter_ServiceEvents_Call{Call: _e.mock.On("ServiceEvents")} +} - return mock +func (_c *EventEmitter_ServiceEvents_Call) Run(run func()) *EventEmitter_ServiceEvents_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EventEmitter_ServiceEvents_Call) Return(eventsList flow.EventsList) *EventEmitter_ServiceEvents_Call { + _c.Call.Return(eventsList) + return _c +} + +func (_c *EventEmitter_ServiceEvents_Call) RunAndReturn(run func() flow.EventsList) *EventEmitter_ServiceEvents_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/event_encoder.go b/fvm/environment/mock/event_encoder.go index 40c429b83ba..3af05b866e3 100644 --- a/fvm/environment/mock/event_encoder.go +++ b/fvm/environment/mock/event_encoder.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cadence "github.com/onflow/cadence" - + "github.com/onflow/cadence" mock "github.com/stretchr/testify/mock" ) +// NewEventEncoder creates a new instance of EventEncoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEventEncoder(t interface { + mock.TestingT + Cleanup(func()) +}) *EventEncoder { + mock := &EventEncoder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EventEncoder is an autogenerated mock type for the EventEncoder type type EventEncoder struct { mock.Mock } -// Encode provides a mock function with given fields: event -func (_m *EventEncoder) Encode(event cadence.Event) ([]byte, error) { - ret := _m.Called(event) +type EventEncoder_Expecter struct { + mock *mock.Mock +} + +func (_m *EventEncoder) EXPECT() *EventEncoder_Expecter { + return &EventEncoder_Expecter{mock: &_m.Mock} +} + +// Encode provides a mock function for the type EventEncoder +func (_mock *EventEncoder) Encode(event cadence.Event) ([]byte, error) { + ret := _mock.Called(event) if len(ret) == 0 { panic("no return value specified for Encode") @@ -23,36 +46,54 @@ func (_m *EventEncoder) Encode(event cadence.Event) ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(cadence.Event) ([]byte, error)); ok { - return rf(event) + if returnFunc, ok := ret.Get(0).(func(cadence.Event) ([]byte, error)); ok { + return returnFunc(event) } - if rf, ok := ret.Get(0).(func(cadence.Event) []byte); ok { - r0 = rf(event) + if returnFunc, ok := ret.Get(0).(func(cadence.Event) []byte); ok { + r0 = returnFunc(event) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(cadence.Event) error); ok { - r1 = rf(event) + if returnFunc, ok := ret.Get(1).(func(cadence.Event) error); ok { + r1 = returnFunc(event) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEventEncoder creates a new instance of EventEncoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEventEncoder(t interface { - mock.TestingT - Cleanup(func()) -}) *EventEncoder { - mock := &EventEncoder{} - mock.Mock.Test(t) +// EventEncoder_Encode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Encode' +type EventEncoder_Encode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Encode is a helper method to define mock.On call +// - event cadence.Event +func (_e *EventEncoder_Expecter) Encode(event interface{}) *EventEncoder_Encode_Call { + return &EventEncoder_Encode_Call{Call: _e.mock.On("Encode", event)} +} - return mock +func (_c *EventEncoder_Encode_Call) Run(run func(event cadence.Event)) *EventEncoder_Encode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 cadence.Event + if args[0] != nil { + arg0 = args[0].(cadence.Event) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventEncoder_Encode_Call) Return(bytes []byte, err error) *EventEncoder_Encode_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *EventEncoder_Encode_Call) RunAndReturn(run func(event cadence.Event) ([]byte, error)) *EventEncoder_Encode_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/evm_block_store.go b/fvm/environment/mock/evm_block_store.go new file mode 100644 index 00000000000..0c59382f5ea --- /dev/null +++ b/fvm/environment/mock/evm_block_store.go @@ -0,0 +1,301 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/onflow/flow-go/fvm/evm/types" + mock "github.com/stretchr/testify/mock" +) + +// NewEVMBlockStore creates a new instance of EVMBlockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEVMBlockStore(t interface { + mock.TestingT + Cleanup(func()) +}) *EVMBlockStore { + mock := &EVMBlockStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// EVMBlockStore is an autogenerated mock type for the EVMBlockStore type +type EVMBlockStore struct { + mock.Mock +} + +type EVMBlockStore_Expecter struct { + mock *mock.Mock +} + +func (_m *EVMBlockStore) EXPECT() *EVMBlockStore_Expecter { + return &EVMBlockStore_Expecter{mock: &_m.Mock} +} + +// BlockHash provides a mock function for the type EVMBlockStore +func (_mock *EVMBlockStore) BlockHash(height uint64) (common.Hash, error) { + ret := _mock.Called(height) + + if len(ret) == 0 { + panic("no return value specified for BlockHash") + } + + var r0 common.Hash + var r1 error + if returnFunc, ok := ret.Get(0).(func(uint64) (common.Hash, error)); ok { + return returnFunc(height) + } + if returnFunc, ok := ret.Get(0).(func(uint64) common.Hash); ok { + r0 = returnFunc(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(common.Hash) + } + } + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// EVMBlockStore_BlockHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockHash' +type EVMBlockStore_BlockHash_Call struct { + *mock.Call +} + +// BlockHash is a helper method to define mock.On call +// - height uint64 +func (_e *EVMBlockStore_Expecter) BlockHash(height interface{}) *EVMBlockStore_BlockHash_Call { + return &EVMBlockStore_BlockHash_Call{Call: _e.mock.On("BlockHash", height)} +} + +func (_c *EVMBlockStore_BlockHash_Call) Run(run func(height uint64)) *EVMBlockStore_BlockHash_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EVMBlockStore_BlockHash_Call) Return(hash common.Hash, err error) *EVMBlockStore_BlockHash_Call { + _c.Call.Return(hash, err) + return _c +} + +func (_c *EVMBlockStore_BlockHash_Call) RunAndReturn(run func(height uint64) (common.Hash, error)) *EVMBlockStore_BlockHash_Call { + _c.Call.Return(run) + return _c +} + +// BlockProposal provides a mock function for the type EVMBlockStore +func (_mock *EVMBlockStore) BlockProposal() (*types.BlockProposal, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for BlockProposal") + } + + var r0 *types.BlockProposal + var r1 error + if returnFunc, ok := ret.Get(0).(func() (*types.BlockProposal, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() *types.BlockProposal); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.BlockProposal) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// EVMBlockStore_BlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProposal' +type EVMBlockStore_BlockProposal_Call struct { + *mock.Call +} + +// BlockProposal is a helper method to define mock.On call +func (_e *EVMBlockStore_Expecter) BlockProposal() *EVMBlockStore_BlockProposal_Call { + return &EVMBlockStore_BlockProposal_Call{Call: _e.mock.On("BlockProposal")} +} + +func (_c *EVMBlockStore_BlockProposal_Call) Run(run func()) *EVMBlockStore_BlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EVMBlockStore_BlockProposal_Call) Return(blockProposal *types.BlockProposal, err error) *EVMBlockStore_BlockProposal_Call { + _c.Call.Return(blockProposal, err) + return _c +} + +func (_c *EVMBlockStore_BlockProposal_Call) RunAndReturn(run func() (*types.BlockProposal, error)) *EVMBlockStore_BlockProposal_Call { + _c.Call.Return(run) + return _c +} + +// CommitBlockProposal provides a mock function for the type EVMBlockStore +func (_mock *EVMBlockStore) CommitBlockProposal(blockProposal *types.BlockProposal) error { + ret := _mock.Called(blockProposal) + + if len(ret) == 0 { + panic("no return value specified for CommitBlockProposal") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(*types.BlockProposal) error); ok { + r0 = returnFunc(blockProposal) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// EVMBlockStore_CommitBlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CommitBlockProposal' +type EVMBlockStore_CommitBlockProposal_Call struct { + *mock.Call +} + +// CommitBlockProposal is a helper method to define mock.On call +// - blockProposal *types.BlockProposal +func (_e *EVMBlockStore_Expecter) CommitBlockProposal(blockProposal interface{}) *EVMBlockStore_CommitBlockProposal_Call { + return &EVMBlockStore_CommitBlockProposal_Call{Call: _e.mock.On("CommitBlockProposal", blockProposal)} +} + +func (_c *EVMBlockStore_CommitBlockProposal_Call) Run(run func(blockProposal *types.BlockProposal)) *EVMBlockStore_CommitBlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *types.BlockProposal + if args[0] != nil { + arg0 = args[0].(*types.BlockProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EVMBlockStore_CommitBlockProposal_Call) Return(err error) *EVMBlockStore_CommitBlockProposal_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EVMBlockStore_CommitBlockProposal_Call) RunAndReturn(run func(blockProposal *types.BlockProposal) error) *EVMBlockStore_CommitBlockProposal_Call { + _c.Call.Return(run) + return _c +} + +// LatestBlock provides a mock function for the type EVMBlockStore +func (_mock *EVMBlockStore) LatestBlock() (*types.Block, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestBlock") + } + + var r0 *types.Block + var r1 error + if returnFunc, ok := ret.Get(0).(func() (*types.Block, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() *types.Block); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Block) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// EVMBlockStore_LatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestBlock' +type EVMBlockStore_LatestBlock_Call struct { + *mock.Call +} + +// LatestBlock is a helper method to define mock.On call +func (_e *EVMBlockStore_Expecter) LatestBlock() *EVMBlockStore_LatestBlock_Call { + return &EVMBlockStore_LatestBlock_Call{Call: _e.mock.On("LatestBlock")} +} + +func (_c *EVMBlockStore_LatestBlock_Call) Run(run func()) *EVMBlockStore_LatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EVMBlockStore_LatestBlock_Call) Return(block *types.Block, err error) *EVMBlockStore_LatestBlock_Call { + _c.Call.Return(block, err) + return _c +} + +func (_c *EVMBlockStore_LatestBlock_Call) RunAndReturn(run func() (*types.Block, error)) *EVMBlockStore_LatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// StageBlockProposal provides a mock function for the type EVMBlockStore +func (_mock *EVMBlockStore) StageBlockProposal(blockProposal *types.BlockProposal) { + _mock.Called(blockProposal) + return +} + +// EVMBlockStore_StageBlockProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StageBlockProposal' +type EVMBlockStore_StageBlockProposal_Call struct { + *mock.Call +} + +// StageBlockProposal is a helper method to define mock.On call +// - blockProposal *types.BlockProposal +func (_e *EVMBlockStore_Expecter) StageBlockProposal(blockProposal interface{}) *EVMBlockStore_StageBlockProposal_Call { + return &EVMBlockStore_StageBlockProposal_Call{Call: _e.mock.On("StageBlockProposal", blockProposal)} +} + +func (_c *EVMBlockStore_StageBlockProposal_Call) Run(run func(blockProposal *types.BlockProposal)) *EVMBlockStore_StageBlockProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *types.BlockProposal + if args[0] != nil { + arg0 = args[0].(*types.BlockProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EVMBlockStore_StageBlockProposal_Call) Return() *EVMBlockStore_StageBlockProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *EVMBlockStore_StageBlockProposal_Call) RunAndReturn(run func(blockProposal *types.BlockProposal)) *EVMBlockStore_StageBlockProposal_Call { + _c.Run(run) + return _c +} diff --git a/fvm/environment/mock/evm_metrics_reporter.go b/fvm/environment/mock/evm_metrics_reporter.go index a509235f64e..94c0723b051 100644 --- a/fvm/environment/mock/evm_metrics_reporter.go +++ b/fvm/environment/mock/evm_metrics_reporter.go @@ -1,39 +1,180 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewEVMMetricsReporter creates a new instance of EVMMetricsReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEVMMetricsReporter(t interface { + mock.TestingT + Cleanup(func()) +}) *EVMMetricsReporter { + mock := &EVMMetricsReporter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EVMMetricsReporter is an autogenerated mock type for the EVMMetricsReporter type type EVMMetricsReporter struct { mock.Mock } -// EVMBlockExecuted provides a mock function with given fields: txCount, totalGasUsed, totalSupplyInFlow -func (_m *EVMMetricsReporter) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { - _m.Called(txCount, totalGasUsed, totalSupplyInFlow) +type EVMMetricsReporter_Expecter struct { + mock *mock.Mock } -// EVMTransactionExecuted provides a mock function with given fields: gasUsed, isDirectCall, failed -func (_m *EVMMetricsReporter) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { - _m.Called(gasUsed, isDirectCall, failed) +func (_m *EVMMetricsReporter) EXPECT() *EVMMetricsReporter_Expecter { + return &EVMMetricsReporter_Expecter{mock: &_m.Mock} } -// SetNumberOfDeployedCOAs provides a mock function with given fields: count -func (_m *EVMMetricsReporter) SetNumberOfDeployedCOAs(count uint64) { - _m.Called(count) +// EVMBlockExecuted provides a mock function for the type EVMMetricsReporter +func (_mock *EVMMetricsReporter) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { + _mock.Called(txCount, totalGasUsed, totalSupplyInFlow) + return } -// NewEVMMetricsReporter creates a new instance of EVMMetricsReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEVMMetricsReporter(t interface { - mock.TestingT - Cleanup(func()) -}) *EVMMetricsReporter { - mock := &EVMMetricsReporter{} - mock.Mock.Test(t) +// EVMMetricsReporter_EVMBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMBlockExecuted' +type EVMMetricsReporter_EVMBlockExecuted_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// EVMBlockExecuted is a helper method to define mock.On call +// - txCount int +// - totalGasUsed uint64 +// - totalSupplyInFlow float64 +func (_e *EVMMetricsReporter_Expecter) EVMBlockExecuted(txCount interface{}, totalGasUsed interface{}, totalSupplyInFlow interface{}) *EVMMetricsReporter_EVMBlockExecuted_Call { + return &EVMMetricsReporter_EVMBlockExecuted_Call{Call: _e.mock.On("EVMBlockExecuted", txCount, totalGasUsed, totalSupplyInFlow)} +} - return mock +func (_c *EVMMetricsReporter_EVMBlockExecuted_Call) Run(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *EVMMetricsReporter_EVMBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 float64 + if args[2] != nil { + arg2 = args[2].(float64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *EVMMetricsReporter_EVMBlockExecuted_Call) Return() *EVMMetricsReporter_EVMBlockExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *EVMMetricsReporter_EVMBlockExecuted_Call) RunAndReturn(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *EVMMetricsReporter_EVMBlockExecuted_Call { + _c.Run(run) + return _c +} + +// EVMTransactionExecuted provides a mock function for the type EVMMetricsReporter +func (_mock *EVMMetricsReporter) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { + _mock.Called(gasUsed, isDirectCall, failed) + return +} + +// EVMMetricsReporter_EVMTransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMTransactionExecuted' +type EVMMetricsReporter_EVMTransactionExecuted_Call struct { + *mock.Call +} + +// EVMTransactionExecuted is a helper method to define mock.On call +// - gasUsed uint64 +// - isDirectCall bool +// - failed bool +func (_e *EVMMetricsReporter_Expecter) EVMTransactionExecuted(gasUsed interface{}, isDirectCall interface{}, failed interface{}) *EVMMetricsReporter_EVMTransactionExecuted_Call { + return &EVMMetricsReporter_EVMTransactionExecuted_Call{Call: _e.mock.On("EVMTransactionExecuted", gasUsed, isDirectCall, failed)} +} + +func (_c *EVMMetricsReporter_EVMTransactionExecuted_Call) Run(run func(gasUsed uint64, isDirectCall bool, failed bool)) *EVMMetricsReporter_EVMTransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + var arg2 bool + if args[2] != nil { + arg2 = args[2].(bool) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *EVMMetricsReporter_EVMTransactionExecuted_Call) Return() *EVMMetricsReporter_EVMTransactionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *EVMMetricsReporter_EVMTransactionExecuted_Call) RunAndReturn(run func(gasUsed uint64, isDirectCall bool, failed bool)) *EVMMetricsReporter_EVMTransactionExecuted_Call { + _c.Run(run) + return _c +} + +// SetNumberOfDeployedCOAs provides a mock function for the type EVMMetricsReporter +func (_mock *EVMMetricsReporter) SetNumberOfDeployedCOAs(count uint64) { + _mock.Called(count) + return +} + +// EVMMetricsReporter_SetNumberOfDeployedCOAs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetNumberOfDeployedCOAs' +type EVMMetricsReporter_SetNumberOfDeployedCOAs_Call struct { + *mock.Call +} + +// SetNumberOfDeployedCOAs is a helper method to define mock.On call +// - count uint64 +func (_e *EVMMetricsReporter_Expecter) SetNumberOfDeployedCOAs(count interface{}) *EVMMetricsReporter_SetNumberOfDeployedCOAs_Call { + return &EVMMetricsReporter_SetNumberOfDeployedCOAs_Call{Call: _e.mock.On("SetNumberOfDeployedCOAs", count)} +} + +func (_c *EVMMetricsReporter_SetNumberOfDeployedCOAs_Call) Run(run func(count uint64)) *EVMMetricsReporter_SetNumberOfDeployedCOAs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EVMMetricsReporter_SetNumberOfDeployedCOAs_Call) Return() *EVMMetricsReporter_SetNumberOfDeployedCOAs_Call { + _c.Call.Return() + return _c +} + +func (_c *EVMMetricsReporter_SetNumberOfDeployedCOAs_Call) RunAndReturn(run func(count uint64)) *EVMMetricsReporter_SetNumberOfDeployedCOAs_Call { + _c.Run(run) + return _c } diff --git a/fvm/environment/mock/execution_version_provider.go b/fvm/environment/mock/execution_version_provider.go index 102942e50ab..aaf7d942d57 100644 --- a/fvm/environment/mock/execution_version_provider.go +++ b/fvm/environment/mock/execution_version_provider.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - semver "github.com/coreos/go-semver/semver" + "github.com/coreos/go-semver/semver" mock "github.com/stretchr/testify/mock" ) +// NewExecutionVersionProvider creates a new instance of ExecutionVersionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionVersionProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionVersionProvider { + mock := &ExecutionVersionProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionVersionProvider is an autogenerated mock type for the ExecutionVersionProvider type type ExecutionVersionProvider struct { mock.Mock } -// ExecutionVersion provides a mock function with no fields -func (_m *ExecutionVersionProvider) ExecutionVersion() (semver.Version, error) { - ret := _m.Called() +type ExecutionVersionProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionVersionProvider) EXPECT() *ExecutionVersionProvider_Expecter { + return &ExecutionVersionProvider_Expecter{mock: &_m.Mock} +} + +// ExecutionVersion provides a mock function for the type ExecutionVersionProvider +func (_mock *ExecutionVersionProvider) ExecutionVersion() (semver.Version, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ExecutionVersion") @@ -22,34 +46,45 @@ func (_m *ExecutionVersionProvider) ExecutionVersion() (semver.Version, error) { var r0 semver.Version var r1 error - if rf, ok := ret.Get(0).(func() (semver.Version, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (semver.Version, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() semver.Version); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() semver.Version); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(semver.Version) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionVersionProvider creates a new instance of ExecutionVersionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionVersionProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionVersionProvider { - mock := &ExecutionVersionProvider{} - mock.Mock.Test(t) +// ExecutionVersionProvider_ExecutionVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionVersion' +type ExecutionVersionProvider_ExecutionVersion_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ExecutionVersion is a helper method to define mock.On call +func (_e *ExecutionVersionProvider_Expecter) ExecutionVersion() *ExecutionVersionProvider_ExecutionVersion_Call { + return &ExecutionVersionProvider_ExecutionVersion_Call{Call: _e.mock.On("ExecutionVersion")} +} - return mock +func (_c *ExecutionVersionProvider_ExecutionVersion_Call) Run(run func()) *ExecutionVersionProvider_ExecutionVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionVersionProvider_ExecutionVersion_Call) Return(version semver.Version, err error) *ExecutionVersionProvider_ExecutionVersion_Call { + _c.Call.Return(version, err) + return _c +} + +func (_c *ExecutionVersionProvider_ExecutionVersion_Call) RunAndReturn(run func() (semver.Version, error)) *ExecutionVersionProvider_ExecutionVersion_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/logger_provider.go b/fvm/environment/mock/logger_provider.go index 5807cc20fa3..a28a15a5024 100644 --- a/fvm/environment/mock/logger_provider.go +++ b/fvm/environment/mock/logger_provider.go @@ -1,45 +1,81 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - zerolog "github.com/rs/zerolog" + "github.com/rs/zerolog" mock "github.com/stretchr/testify/mock" ) +// NewLoggerProvider creates a new instance of LoggerProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLoggerProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *LoggerProvider { + mock := &LoggerProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LoggerProvider is an autogenerated mock type for the LoggerProvider type type LoggerProvider struct { mock.Mock } -// Logger provides a mock function with no fields -func (_m *LoggerProvider) Logger() zerolog.Logger { - ret := _m.Called() +type LoggerProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *LoggerProvider) EXPECT() *LoggerProvider_Expecter { + return &LoggerProvider_Expecter{mock: &_m.Mock} +} + +// Logger provides a mock function for the type LoggerProvider +func (_mock *LoggerProvider) Logger() zerolog.Logger { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Logger") } var r0 zerolog.Logger - if rf, ok := ret.Get(0).(func() zerolog.Logger); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() zerolog.Logger); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(zerolog.Logger) } - return r0 } -// NewLoggerProvider creates a new instance of LoggerProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLoggerProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *LoggerProvider { - mock := &LoggerProvider{} - mock.Mock.Test(t) +// LoggerProvider_Logger_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Logger' +type LoggerProvider_Logger_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Logger is a helper method to define mock.On call +func (_e *LoggerProvider_Expecter) Logger() *LoggerProvider_Logger_Call { + return &LoggerProvider_Logger_Call{Call: _e.mock.On("Logger")} +} - return mock +func (_c *LoggerProvider_Logger_Call) Run(run func()) *LoggerProvider_Logger_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LoggerProvider_Logger_Call) Return(logger zerolog.Logger) *LoggerProvider_Logger_Call { + _c.Call.Return(logger) + return _c +} + +func (_c *LoggerProvider_Logger_Call) RunAndReturn(run func() zerolog.Logger) *LoggerProvider_Logger_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/meter.go b/fvm/environment/mock/meter.go index f8ef18130b5..e450f76270f 100644 --- a/fvm/environment/mock/meter.go +++ b/fvm/environment/mock/meter.go @@ -1,79 +1,193 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - - meter "github.com/onflow/flow-go/fvm/meter" - + "github.com/onflow/cadence/common" + "github.com/onflow/flow-go/fvm/meter" mock "github.com/stretchr/testify/mock" ) +// NewMeter creates a new instance of Meter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMeter(t interface { + mock.TestingT + Cleanup(func()) +}) *Meter { + mock := &Meter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Meter is an autogenerated mock type for the Meter type type Meter struct { mock.Mock } -// ComputationAvailable provides a mock function with given fields: _a0 -func (_m *Meter) ComputationAvailable(_a0 common.ComputationUsage) bool { - ret := _m.Called(_a0) +type Meter_Expecter struct { + mock *mock.Mock +} + +func (_m *Meter) EXPECT() *Meter_Expecter { + return &Meter_Expecter{mock: &_m.Mock} +} + +// ComputationAvailable provides a mock function for the type Meter +func (_mock *Meter) ComputationAvailable(computationUsage common.ComputationUsage) bool { + ret := _mock.Called(computationUsage) if len(ret) == 0 { panic("no return value specified for ComputationAvailable") } var r0 bool - if rf, ok := ret.Get(0).(func(common.ComputationUsage) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(common.ComputationUsage) bool); ok { + r0 = returnFunc(computationUsage) } else { r0 = ret.Get(0).(bool) } - return r0 } -// ComputationIntensities provides a mock function with no fields -func (_m *Meter) ComputationIntensities() meter.MeteredComputationIntensities { - ret := _m.Called() +// Meter_ComputationAvailable_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationAvailable' +type Meter_ComputationAvailable_Call struct { + *mock.Call +} + +// ComputationAvailable is a helper method to define mock.On call +// - computationUsage common.ComputationUsage +func (_e *Meter_Expecter) ComputationAvailable(computationUsage interface{}) *Meter_ComputationAvailable_Call { + return &Meter_ComputationAvailable_Call{Call: _e.mock.On("ComputationAvailable", computationUsage)} +} + +func (_c *Meter_ComputationAvailable_Call) Run(run func(computationUsage common.ComputationUsage)) *Meter_ComputationAvailable_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.ComputationUsage + if args[0] != nil { + arg0 = args[0].(common.ComputationUsage) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Meter_ComputationAvailable_Call) Return(b bool) *Meter_ComputationAvailable_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Meter_ComputationAvailable_Call) RunAndReturn(run func(computationUsage common.ComputationUsage) bool) *Meter_ComputationAvailable_Call { + _c.Call.Return(run) + return _c +} + +// ComputationIntensities provides a mock function for the type Meter +func (_mock *Meter) ComputationIntensities() meter.MeteredComputationIntensities { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ComputationIntensities") } var r0 meter.MeteredComputationIntensities - if rf, ok := ret.Get(0).(func() meter.MeteredComputationIntensities); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() meter.MeteredComputationIntensities); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(meter.MeteredComputationIntensities) } } - return r0 } -// ComputationRemaining provides a mock function with given fields: kind -func (_m *Meter) ComputationRemaining(kind common.ComputationKind) uint64 { - ret := _m.Called(kind) +// Meter_ComputationIntensities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationIntensities' +type Meter_ComputationIntensities_Call struct { + *mock.Call +} + +// ComputationIntensities is a helper method to define mock.On call +func (_e *Meter_Expecter) ComputationIntensities() *Meter_ComputationIntensities_Call { + return &Meter_ComputationIntensities_Call{Call: _e.mock.On("ComputationIntensities")} +} + +func (_c *Meter_ComputationIntensities_Call) Run(run func()) *Meter_ComputationIntensities_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Meter_ComputationIntensities_Call) Return(meteredComputationIntensities meter.MeteredComputationIntensities) *Meter_ComputationIntensities_Call { + _c.Call.Return(meteredComputationIntensities) + return _c +} + +func (_c *Meter_ComputationIntensities_Call) RunAndReturn(run func() meter.MeteredComputationIntensities) *Meter_ComputationIntensities_Call { + _c.Call.Return(run) + return _c +} + +// ComputationRemaining provides a mock function for the type Meter +func (_mock *Meter) ComputationRemaining(kind common.ComputationKind) uint64 { + ret := _mock.Called(kind) if len(ret) == 0 { panic("no return value specified for ComputationRemaining") } var r0 uint64 - if rf, ok := ret.Get(0).(func(common.ComputationKind) uint64); ok { - r0 = rf(kind) + if returnFunc, ok := ret.Get(0).(func(common.ComputationKind) uint64); ok { + r0 = returnFunc(kind) } else { r0 = ret.Get(0).(uint64) } - return r0 } -// ComputationUsed provides a mock function with no fields -func (_m *Meter) ComputationUsed() (uint64, error) { - ret := _m.Called() +// Meter_ComputationRemaining_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationRemaining' +type Meter_ComputationRemaining_Call struct { + *mock.Call +} + +// ComputationRemaining is a helper method to define mock.On call +// - kind common.ComputationKind +func (_e *Meter_Expecter) ComputationRemaining(kind interface{}) *Meter_ComputationRemaining_Call { + return &Meter_ComputationRemaining_Call{Call: _e.mock.On("ComputationRemaining", kind)} +} + +func (_c *Meter_ComputationRemaining_Call) Run(run func(kind common.ComputationKind)) *Meter_ComputationRemaining_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.ComputationKind + if args[0] != nil { + arg0 = args[0].(common.ComputationKind) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Meter_ComputationRemaining_Call) Return(v uint64) *Meter_ComputationRemaining_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Meter_ComputationRemaining_Call) RunAndReturn(run func(kind common.ComputationKind) uint64) *Meter_ComputationRemaining_Call { + _c.Call.Return(run) + return _c +} + +// ComputationUsed provides a mock function for the type Meter +func (_mock *Meter) ComputationUsed() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ComputationUsed") @@ -81,27 +195,52 @@ func (_m *Meter) ComputationUsed() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// MemoryUsed provides a mock function with no fields -func (_m *Meter) MemoryUsed() (uint64, error) { - ret := _m.Called() +// Meter_ComputationUsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationUsed' +type Meter_ComputationUsed_Call struct { + *mock.Call +} + +// ComputationUsed is a helper method to define mock.On call +func (_e *Meter_Expecter) ComputationUsed() *Meter_ComputationUsed_Call { + return &Meter_ComputationUsed_Call{Call: _e.mock.On("ComputationUsed")} +} + +func (_c *Meter_ComputationUsed_Call) Run(run func()) *Meter_ComputationUsed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Meter_ComputationUsed_Call) Return(v uint64, err error) *Meter_ComputationUsed_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Meter_ComputationUsed_Call) RunAndReturn(run func() (uint64, error)) *Meter_ComputationUsed_Call { + _c.Call.Return(run) + return _c +} + +// MemoryUsed provides a mock function for the type Meter +func (_mock *Meter) MemoryUsed() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MemoryUsed") @@ -109,111 +248,282 @@ func (_m *Meter) MemoryUsed() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// MeterComputation provides a mock function with given fields: usage -func (_m *Meter) MeterComputation(usage common.ComputationUsage) error { - ret := _m.Called(usage) +// Meter_MemoryUsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MemoryUsed' +type Meter_MemoryUsed_Call struct { + *mock.Call +} + +// MemoryUsed is a helper method to define mock.On call +func (_e *Meter_Expecter) MemoryUsed() *Meter_MemoryUsed_Call { + return &Meter_MemoryUsed_Call{Call: _e.mock.On("MemoryUsed")} +} + +func (_c *Meter_MemoryUsed_Call) Run(run func()) *Meter_MemoryUsed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Meter_MemoryUsed_Call) Return(v uint64, err error) *Meter_MemoryUsed_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Meter_MemoryUsed_Call) RunAndReturn(run func() (uint64, error)) *Meter_MemoryUsed_Call { + _c.Call.Return(run) + return _c +} + +// MeterComputation provides a mock function for the type Meter +func (_mock *Meter) MeterComputation(usage common.ComputationUsage) error { + ret := _mock.Called(usage) if len(ret) == 0 { panic("no return value specified for MeterComputation") } var r0 error - if rf, ok := ret.Get(0).(func(common.ComputationUsage) error); ok { - r0 = rf(usage) + if returnFunc, ok := ret.Get(0).(func(common.ComputationUsage) error); ok { + r0 = returnFunc(usage) } else { r0 = ret.Error(0) } - return r0 } -// MeterEmittedEvent provides a mock function with given fields: byteSize -func (_m *Meter) MeterEmittedEvent(byteSize uint64) error { - ret := _m.Called(byteSize) +// Meter_MeterComputation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MeterComputation' +type Meter_MeterComputation_Call struct { + *mock.Call +} + +// MeterComputation is a helper method to define mock.On call +// - usage common.ComputationUsage +func (_e *Meter_Expecter) MeterComputation(usage interface{}) *Meter_MeterComputation_Call { + return &Meter_MeterComputation_Call{Call: _e.mock.On("MeterComputation", usage)} +} + +func (_c *Meter_MeterComputation_Call) Run(run func(usage common.ComputationUsage)) *Meter_MeterComputation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.ComputationUsage + if args[0] != nil { + arg0 = args[0].(common.ComputationUsage) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Meter_MeterComputation_Call) Return(err error) *Meter_MeterComputation_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Meter_MeterComputation_Call) RunAndReturn(run func(usage common.ComputationUsage) error) *Meter_MeterComputation_Call { + _c.Call.Return(run) + return _c +} + +// MeterEmittedEvent provides a mock function for the type Meter +func (_mock *Meter) MeterEmittedEvent(byteSize uint64) error { + ret := _mock.Called(byteSize) if len(ret) == 0 { panic("no return value specified for MeterEmittedEvent") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(byteSize) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(byteSize) } else { r0 = ret.Error(0) } - return r0 } -// MeterMemory provides a mock function with given fields: usage -func (_m *Meter) MeterMemory(usage common.MemoryUsage) error { - ret := _m.Called(usage) +// Meter_MeterEmittedEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MeterEmittedEvent' +type Meter_MeterEmittedEvent_Call struct { + *mock.Call +} + +// MeterEmittedEvent is a helper method to define mock.On call +// - byteSize uint64 +func (_e *Meter_Expecter) MeterEmittedEvent(byteSize interface{}) *Meter_MeterEmittedEvent_Call { + return &Meter_MeterEmittedEvent_Call{Call: _e.mock.On("MeterEmittedEvent", byteSize)} +} + +func (_c *Meter_MeterEmittedEvent_Call) Run(run func(byteSize uint64)) *Meter_MeterEmittedEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Meter_MeterEmittedEvent_Call) Return(err error) *Meter_MeterEmittedEvent_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Meter_MeterEmittedEvent_Call) RunAndReturn(run func(byteSize uint64) error) *Meter_MeterEmittedEvent_Call { + _c.Call.Return(run) + return _c +} + +// MeterMemory provides a mock function for the type Meter +func (_mock *Meter) MeterMemory(usage common.MemoryUsage) error { + ret := _mock.Called(usage) if len(ret) == 0 { panic("no return value specified for MeterMemory") } var r0 error - if rf, ok := ret.Get(0).(func(common.MemoryUsage) error); ok { - r0 = rf(usage) + if returnFunc, ok := ret.Get(0).(func(common.MemoryUsage) error); ok { + r0 = returnFunc(usage) } else { r0 = ret.Error(0) } - return r0 } -// RunWithMeteringDisabled provides a mock function with given fields: f -func (_m *Meter) RunWithMeteringDisabled(f func()) { - _m.Called(f) +// Meter_MeterMemory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MeterMemory' +type Meter_MeterMemory_Call struct { + *mock.Call } -// TotalEmittedEventBytes provides a mock function with no fields -func (_m *Meter) TotalEmittedEventBytes() uint64 { - ret := _m.Called() +// MeterMemory is a helper method to define mock.On call +// - usage common.MemoryUsage +func (_e *Meter_Expecter) MeterMemory(usage interface{}) *Meter_MeterMemory_Call { + return &Meter_MeterMemory_Call{Call: _e.mock.On("MeterMemory", usage)} +} + +func (_c *Meter_MeterMemory_Call) Run(run func(usage common.MemoryUsage)) *Meter_MeterMemory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.MemoryUsage + if args[0] != nil { + arg0 = args[0].(common.MemoryUsage) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Meter_MeterMemory_Call) Return(err error) *Meter_MeterMemory_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Meter_MeterMemory_Call) RunAndReturn(run func(usage common.MemoryUsage) error) *Meter_MeterMemory_Call { + _c.Call.Return(run) + return _c +} + +// RunWithMeteringDisabled provides a mock function for the type Meter +func (_mock *Meter) RunWithMeteringDisabled(f func()) { + _mock.Called(f) + return +} + +// Meter_RunWithMeteringDisabled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RunWithMeteringDisabled' +type Meter_RunWithMeteringDisabled_Call struct { + *mock.Call +} + +// RunWithMeteringDisabled is a helper method to define mock.On call +// - f func() +func (_e *Meter_Expecter) RunWithMeteringDisabled(f interface{}) *Meter_RunWithMeteringDisabled_Call { + return &Meter_RunWithMeteringDisabled_Call{Call: _e.mock.On("RunWithMeteringDisabled", f)} +} + +func (_c *Meter_RunWithMeteringDisabled_Call) Run(run func(f func())) *Meter_RunWithMeteringDisabled_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func() + if args[0] != nil { + arg0 = args[0].(func()) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Meter_RunWithMeteringDisabled_Call) Return() *Meter_RunWithMeteringDisabled_Call { + _c.Call.Return() + return _c +} + +func (_c *Meter_RunWithMeteringDisabled_Call) RunAndReturn(run func(f func())) *Meter_RunWithMeteringDisabled_Call { + _c.Run(run) + return _c +} + +// TotalEmittedEventBytes provides a mock function for the type Meter +func (_mock *Meter) TotalEmittedEventBytes() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TotalEmittedEventBytes") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewMeter creates a new instance of Meter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMeter(t interface { - mock.TestingT - Cleanup(func()) -}) *Meter { - mock := &Meter{} - mock.Mock.Test(t) +// Meter_TotalEmittedEventBytes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TotalEmittedEventBytes' +type Meter_TotalEmittedEventBytes_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TotalEmittedEventBytes is a helper method to define mock.On call +func (_e *Meter_Expecter) TotalEmittedEventBytes() *Meter_TotalEmittedEventBytes_Call { + return &Meter_TotalEmittedEventBytes_Call{Call: _e.mock.On("TotalEmittedEventBytes")} +} - return mock +func (_c *Meter_TotalEmittedEventBytes_Call) Run(run func()) *Meter_TotalEmittedEventBytes_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Meter_TotalEmittedEventBytes_Call) Return(v uint64) *Meter_TotalEmittedEventBytes_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Meter_TotalEmittedEventBytes_Call) RunAndReturn(run func() uint64) *Meter_TotalEmittedEventBytes_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/metrics_reporter.go b/fvm/environment/mock/metrics_reporter.go index 9f9ddd48463..f26086db27b 100644 --- a/fvm/environment/mock/metrics_reporter.go +++ b/fvm/environment/mock/metrics_reporter.go @@ -1,73 +1,408 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - time "time" + "time" mock "github.com/stretchr/testify/mock" ) +// NewMetricsReporter creates a new instance of MetricsReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMetricsReporter(t interface { + mock.TestingT + Cleanup(func()) +}) *MetricsReporter { + mock := &MetricsReporter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MetricsReporter is an autogenerated mock type for the MetricsReporter type type MetricsReporter struct { mock.Mock } -// EVMBlockExecuted provides a mock function with given fields: txCount, totalGasUsed, totalSupplyInFlow -func (_m *MetricsReporter) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { - _m.Called(txCount, totalGasUsed, totalSupplyInFlow) +type MetricsReporter_Expecter struct { + mock *mock.Mock } -// EVMTransactionExecuted provides a mock function with given fields: gasUsed, isDirectCall, failed -func (_m *MetricsReporter) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { - _m.Called(gasUsed, isDirectCall, failed) +func (_m *MetricsReporter) EXPECT() *MetricsReporter_Expecter { + return &MetricsReporter_Expecter{mock: &_m.Mock} } -// RuntimeSetNumberOfAccounts provides a mock function with given fields: count -func (_m *MetricsReporter) RuntimeSetNumberOfAccounts(count uint64) { - _m.Called(count) +// EVMBlockExecuted provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { + _mock.Called(txCount, totalGasUsed, totalSupplyInFlow) + return } -// RuntimeTransactionChecked provides a mock function with given fields: _a0 -func (_m *MetricsReporter) RuntimeTransactionChecked(_a0 time.Duration) { - _m.Called(_a0) +// MetricsReporter_EVMBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMBlockExecuted' +type MetricsReporter_EVMBlockExecuted_Call struct { + *mock.Call } -// RuntimeTransactionInterpreted provides a mock function with given fields: _a0 -func (_m *MetricsReporter) RuntimeTransactionInterpreted(_a0 time.Duration) { - _m.Called(_a0) +// EVMBlockExecuted is a helper method to define mock.On call +// - txCount int +// - totalGasUsed uint64 +// - totalSupplyInFlow float64 +func (_e *MetricsReporter_Expecter) EVMBlockExecuted(txCount interface{}, totalGasUsed interface{}, totalSupplyInFlow interface{}) *MetricsReporter_EVMBlockExecuted_Call { + return &MetricsReporter_EVMBlockExecuted_Call{Call: _e.mock.On("EVMBlockExecuted", txCount, totalGasUsed, totalSupplyInFlow)} } -// RuntimeTransactionParsed provides a mock function with given fields: _a0 -func (_m *MetricsReporter) RuntimeTransactionParsed(_a0 time.Duration) { - _m.Called(_a0) +func (_c *MetricsReporter_EVMBlockExecuted_Call) Run(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *MetricsReporter_EVMBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 float64 + if args[2] != nil { + arg2 = args[2].(float64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// RuntimeTransactionProgramsCacheHit provides a mock function with no fields -func (_m *MetricsReporter) RuntimeTransactionProgramsCacheHit() { - _m.Called() +func (_c *MetricsReporter_EVMBlockExecuted_Call) Return() *MetricsReporter_EVMBlockExecuted_Call { + _c.Call.Return() + return _c } -// RuntimeTransactionProgramsCacheMiss provides a mock function with no fields -func (_m *MetricsReporter) RuntimeTransactionProgramsCacheMiss() { - _m.Called() +func (_c *MetricsReporter_EVMBlockExecuted_Call) RunAndReturn(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *MetricsReporter_EVMBlockExecuted_Call { + _c.Run(run) + return _c } -// SetNumberOfDeployedCOAs provides a mock function with given fields: count -func (_m *MetricsReporter) SetNumberOfDeployedCOAs(count uint64) { - _m.Called(count) +// EVMTransactionExecuted provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { + _mock.Called(gasUsed, isDirectCall, failed) + return } -// NewMetricsReporter creates a new instance of MetricsReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMetricsReporter(t interface { - mock.TestingT - Cleanup(func()) -}) *MetricsReporter { - mock := &MetricsReporter{} - mock.Mock.Test(t) +// MetricsReporter_EVMTransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMTransactionExecuted' +type MetricsReporter_EVMTransactionExecuted_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// EVMTransactionExecuted is a helper method to define mock.On call +// - gasUsed uint64 +// - isDirectCall bool +// - failed bool +func (_e *MetricsReporter_Expecter) EVMTransactionExecuted(gasUsed interface{}, isDirectCall interface{}, failed interface{}) *MetricsReporter_EVMTransactionExecuted_Call { + return &MetricsReporter_EVMTransactionExecuted_Call{Call: _e.mock.On("EVMTransactionExecuted", gasUsed, isDirectCall, failed)} +} - return mock +func (_c *MetricsReporter_EVMTransactionExecuted_Call) Run(run func(gasUsed uint64, isDirectCall bool, failed bool)) *MetricsReporter_EVMTransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + var arg2 bool + if args[2] != nil { + arg2 = args[2].(bool) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *MetricsReporter_EVMTransactionExecuted_Call) Return() *MetricsReporter_EVMTransactionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_EVMTransactionExecuted_Call) RunAndReturn(run func(gasUsed uint64, isDirectCall bool, failed bool)) *MetricsReporter_EVMTransactionExecuted_Call { + _c.Run(run) + return _c +} + +// RuntimeSetNumberOfAccounts provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) RuntimeSetNumberOfAccounts(count uint64) { + _mock.Called(count) + return +} + +// MetricsReporter_RuntimeSetNumberOfAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeSetNumberOfAccounts' +type MetricsReporter_RuntimeSetNumberOfAccounts_Call struct { + *mock.Call +} + +// RuntimeSetNumberOfAccounts is a helper method to define mock.On call +// - count uint64 +func (_e *MetricsReporter_Expecter) RuntimeSetNumberOfAccounts(count interface{}) *MetricsReporter_RuntimeSetNumberOfAccounts_Call { + return &MetricsReporter_RuntimeSetNumberOfAccounts_Call{Call: _e.mock.On("RuntimeSetNumberOfAccounts", count)} +} + +func (_c *MetricsReporter_RuntimeSetNumberOfAccounts_Call) Run(run func(count uint64)) *MetricsReporter_RuntimeSetNumberOfAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MetricsReporter_RuntimeSetNumberOfAccounts_Call) Return() *MetricsReporter_RuntimeSetNumberOfAccounts_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_RuntimeSetNumberOfAccounts_Call) RunAndReturn(run func(count uint64)) *MetricsReporter_RuntimeSetNumberOfAccounts_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionChecked provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) RuntimeTransactionChecked(duration time.Duration) { + _mock.Called(duration) + return +} + +// MetricsReporter_RuntimeTransactionChecked_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionChecked' +type MetricsReporter_RuntimeTransactionChecked_Call struct { + *mock.Call +} + +// RuntimeTransactionChecked is a helper method to define mock.On call +// - duration time.Duration +func (_e *MetricsReporter_Expecter) RuntimeTransactionChecked(duration interface{}) *MetricsReporter_RuntimeTransactionChecked_Call { + return &MetricsReporter_RuntimeTransactionChecked_Call{Call: _e.mock.On("RuntimeTransactionChecked", duration)} +} + +func (_c *MetricsReporter_RuntimeTransactionChecked_Call) Run(run func(duration time.Duration)) *MetricsReporter_RuntimeTransactionChecked_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionChecked_Call) Return() *MetricsReporter_RuntimeTransactionChecked_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionChecked_Call) RunAndReturn(run func(duration time.Duration)) *MetricsReporter_RuntimeTransactionChecked_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionInterpreted provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) RuntimeTransactionInterpreted(duration time.Duration) { + _mock.Called(duration) + return +} + +// MetricsReporter_RuntimeTransactionInterpreted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionInterpreted' +type MetricsReporter_RuntimeTransactionInterpreted_Call struct { + *mock.Call +} + +// RuntimeTransactionInterpreted is a helper method to define mock.On call +// - duration time.Duration +func (_e *MetricsReporter_Expecter) RuntimeTransactionInterpreted(duration interface{}) *MetricsReporter_RuntimeTransactionInterpreted_Call { + return &MetricsReporter_RuntimeTransactionInterpreted_Call{Call: _e.mock.On("RuntimeTransactionInterpreted", duration)} +} + +func (_c *MetricsReporter_RuntimeTransactionInterpreted_Call) Run(run func(duration time.Duration)) *MetricsReporter_RuntimeTransactionInterpreted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionInterpreted_Call) Return() *MetricsReporter_RuntimeTransactionInterpreted_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionInterpreted_Call) RunAndReturn(run func(duration time.Duration)) *MetricsReporter_RuntimeTransactionInterpreted_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionParsed provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) RuntimeTransactionParsed(duration time.Duration) { + _mock.Called(duration) + return +} + +// MetricsReporter_RuntimeTransactionParsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionParsed' +type MetricsReporter_RuntimeTransactionParsed_Call struct { + *mock.Call +} + +// RuntimeTransactionParsed is a helper method to define mock.On call +// - duration time.Duration +func (_e *MetricsReporter_Expecter) RuntimeTransactionParsed(duration interface{}) *MetricsReporter_RuntimeTransactionParsed_Call { + return &MetricsReporter_RuntimeTransactionParsed_Call{Call: _e.mock.On("RuntimeTransactionParsed", duration)} +} + +func (_c *MetricsReporter_RuntimeTransactionParsed_Call) Run(run func(duration time.Duration)) *MetricsReporter_RuntimeTransactionParsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionParsed_Call) Return() *MetricsReporter_RuntimeTransactionParsed_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionParsed_Call) RunAndReturn(run func(duration time.Duration)) *MetricsReporter_RuntimeTransactionParsed_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheHit provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) RuntimeTransactionProgramsCacheHit() { + _mock.Called() + return +} + +// MetricsReporter_RuntimeTransactionProgramsCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheHit' +type MetricsReporter_RuntimeTransactionProgramsCacheHit_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheHit is a helper method to define mock.On call +func (_e *MetricsReporter_Expecter) RuntimeTransactionProgramsCacheHit() *MetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + return &MetricsReporter_RuntimeTransactionProgramsCacheHit_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheHit")} +} + +func (_c *MetricsReporter_RuntimeTransactionProgramsCacheHit_Call) Run(run func()) *MetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionProgramsCacheHit_Call) Return() *MetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionProgramsCacheHit_Call) RunAndReturn(run func()) *MetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheMiss provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) RuntimeTransactionProgramsCacheMiss() { + _mock.Called() + return +} + +// MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheMiss' +type MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheMiss is a helper method to define mock.On call +func (_e *MetricsReporter_Expecter) RuntimeTransactionProgramsCacheMiss() *MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + return &MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheMiss")} +} + +func (_c *MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call) Run(run func()) *MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call) Return() *MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call) RunAndReturn(run func()) *MetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + _c.Run(run) + return _c +} + +// SetNumberOfDeployedCOAs provides a mock function for the type MetricsReporter +func (_mock *MetricsReporter) SetNumberOfDeployedCOAs(count uint64) { + _mock.Called(count) + return +} + +// MetricsReporter_SetNumberOfDeployedCOAs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetNumberOfDeployedCOAs' +type MetricsReporter_SetNumberOfDeployedCOAs_Call struct { + *mock.Call +} + +// SetNumberOfDeployedCOAs is a helper method to define mock.On call +// - count uint64 +func (_e *MetricsReporter_Expecter) SetNumberOfDeployedCOAs(count interface{}) *MetricsReporter_SetNumberOfDeployedCOAs_Call { + return &MetricsReporter_SetNumberOfDeployedCOAs_Call{Call: _e.mock.On("SetNumberOfDeployedCOAs", count)} +} + +func (_c *MetricsReporter_SetNumberOfDeployedCOAs_Call) Run(run func(count uint64)) *MetricsReporter_SetNumberOfDeployedCOAs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MetricsReporter_SetNumberOfDeployedCOAs_Call) Return() *MetricsReporter_SetNumberOfDeployedCOAs_Call { + _c.Call.Return() + return _c +} + +func (_c *MetricsReporter_SetNumberOfDeployedCOAs_Call) RunAndReturn(run func(count uint64)) *MetricsReporter_SetNumberOfDeployedCOAs_Call { + _c.Run(run) + return _c } diff --git a/fvm/environment/mock/minimum_cadence_required_version.go b/fvm/environment/mock/minimum_cadence_required_version.go index d1634776e33..b9f045cf856 100644 --- a/fvm/environment/mock/minimum_cadence_required_version.go +++ b/fvm/environment/mock/minimum_cadence_required_version.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewMinimumCadenceRequiredVersion creates a new instance of MinimumCadenceRequiredVersion. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMinimumCadenceRequiredVersion(t interface { + mock.TestingT + Cleanup(func()) +}) *MinimumCadenceRequiredVersion { + mock := &MinimumCadenceRequiredVersion{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // MinimumCadenceRequiredVersion is an autogenerated mock type for the MinimumCadenceRequiredVersion type type MinimumCadenceRequiredVersion struct { mock.Mock } -// MinimumRequiredVersion provides a mock function with no fields -func (_m *MinimumCadenceRequiredVersion) MinimumRequiredVersion() (string, error) { - ret := _m.Called() +type MinimumCadenceRequiredVersion_Expecter struct { + mock *mock.Mock +} + +func (_m *MinimumCadenceRequiredVersion) EXPECT() *MinimumCadenceRequiredVersion_Expecter { + return &MinimumCadenceRequiredVersion_Expecter{mock: &_m.Mock} +} + +// MinimumRequiredVersion provides a mock function for the type MinimumCadenceRequiredVersion +func (_mock *MinimumCadenceRequiredVersion) MinimumRequiredVersion() (string, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MinimumRequiredVersion") @@ -19,34 +45,45 @@ func (_m *MinimumCadenceRequiredVersion) MinimumRequiredVersion() (string, error var r0 string var r1 error - if rf, ok := ret.Get(0).(func() (string, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (string, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewMinimumCadenceRequiredVersion creates a new instance of MinimumCadenceRequiredVersion. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMinimumCadenceRequiredVersion(t interface { - mock.TestingT - Cleanup(func()) -}) *MinimumCadenceRequiredVersion { - mock := &MinimumCadenceRequiredVersion{} - mock.Mock.Test(t) +// MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MinimumRequiredVersion' +type MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// MinimumRequiredVersion is a helper method to define mock.On call +func (_e *MinimumCadenceRequiredVersion_Expecter) MinimumRequiredVersion() *MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call { + return &MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call{Call: _e.mock.On("MinimumRequiredVersion")} +} - return mock +func (_c *MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call) Run(run func()) *MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call) Return(s string, err error) *MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call { + _c.Call.Return(s, err) + return _c +} + +func (_c *MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call) RunAndReturn(run func() (string, error)) *MinimumCadenceRequiredVersion_MinimumRequiredVersion_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/random_generator.go b/fvm/environment/mock/random_generator.go index 7bc137e00ab..2c4dda0017b 100644 --- a/fvm/environment/mock/random_generator.go +++ b/fvm/environment/mock/random_generator.go @@ -1,42 +1,87 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewRandomGenerator creates a new instance of RandomGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRandomGenerator(t interface { + mock.TestingT + Cleanup(func()) +}) *RandomGenerator { + mock := &RandomGenerator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // RandomGenerator is an autogenerated mock type for the RandomGenerator type type RandomGenerator struct { mock.Mock } -// ReadRandom provides a mock function with given fields: _a0 -func (_m *RandomGenerator) ReadRandom(_a0 []byte) error { - ret := _m.Called(_a0) +type RandomGenerator_Expecter struct { + mock *mock.Mock +} + +func (_m *RandomGenerator) EXPECT() *RandomGenerator_Expecter { + return &RandomGenerator_Expecter{mock: &_m.Mock} +} + +// ReadRandom provides a mock function for the type RandomGenerator +func (_mock *RandomGenerator) ReadRandom(bytes []byte) error { + ret := _mock.Called(bytes) if len(ret) == 0 { panic("no return value specified for ReadRandom") } var r0 error - if rf, ok := ret.Get(0).(func([]byte) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func([]byte) error); ok { + r0 = returnFunc(bytes) } else { r0 = ret.Error(0) } - return r0 } -// NewRandomGenerator creates a new instance of RandomGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRandomGenerator(t interface { - mock.TestingT - Cleanup(func()) -}) *RandomGenerator { - mock := &RandomGenerator{} - mock.Mock.Test(t) +// RandomGenerator_ReadRandom_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadRandom' +type RandomGenerator_ReadRandom_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ReadRandom is a helper method to define mock.On call +// - bytes []byte +func (_e *RandomGenerator_Expecter) ReadRandom(bytes interface{}) *RandomGenerator_ReadRandom_Call { + return &RandomGenerator_ReadRandom_Call{Call: _e.mock.On("ReadRandom", bytes)} +} - return mock +func (_c *RandomGenerator_ReadRandom_Call) Run(run func(bytes []byte)) *RandomGenerator_ReadRandom_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RandomGenerator_ReadRandom_Call) Return(err error) *RandomGenerator_ReadRandom_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RandomGenerator_ReadRandom_Call) RunAndReturn(run func(bytes []byte) error) *RandomGenerator_ReadRandom_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/random_source_history_provider.go b/fvm/environment/mock/random_source_history_provider.go index 15c04515782..5e74b01af5a 100644 --- a/fvm/environment/mock/random_source_history_provider.go +++ b/fvm/environment/mock/random_source_history_provider.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewRandomSourceHistoryProvider creates a new instance of RandomSourceHistoryProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRandomSourceHistoryProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *RandomSourceHistoryProvider { + mock := &RandomSourceHistoryProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // RandomSourceHistoryProvider is an autogenerated mock type for the RandomSourceHistoryProvider type type RandomSourceHistoryProvider struct { mock.Mock } -// RandomSourceHistory provides a mock function with no fields -func (_m *RandomSourceHistoryProvider) RandomSourceHistory() ([]byte, error) { - ret := _m.Called() +type RandomSourceHistoryProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *RandomSourceHistoryProvider) EXPECT() *RandomSourceHistoryProvider_Expecter { + return &RandomSourceHistoryProvider_Expecter{mock: &_m.Mock} +} + +// RandomSourceHistory provides a mock function for the type RandomSourceHistoryProvider +func (_mock *RandomSourceHistoryProvider) RandomSourceHistory() ([]byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RandomSourceHistory") @@ -19,36 +45,47 @@ func (_m *RandomSourceHistoryProvider) RandomSourceHistory() ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func() ([]byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewRandomSourceHistoryProvider creates a new instance of RandomSourceHistoryProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRandomSourceHistoryProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *RandomSourceHistoryProvider { - mock := &RandomSourceHistoryProvider{} - mock.Mock.Test(t) +// RandomSourceHistoryProvider_RandomSourceHistory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RandomSourceHistory' +type RandomSourceHistoryProvider_RandomSourceHistory_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RandomSourceHistory is a helper method to define mock.On call +func (_e *RandomSourceHistoryProvider_Expecter) RandomSourceHistory() *RandomSourceHistoryProvider_RandomSourceHistory_Call { + return &RandomSourceHistoryProvider_RandomSourceHistory_Call{Call: _e.mock.On("RandomSourceHistory")} +} - return mock +func (_c *RandomSourceHistoryProvider_RandomSourceHistory_Call) Run(run func()) *RandomSourceHistoryProvider_RandomSourceHistory_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RandomSourceHistoryProvider_RandomSourceHistory_Call) Return(bytes []byte, err error) *RandomSourceHistoryProvider_RandomSourceHistory_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *RandomSourceHistoryProvider_RandomSourceHistory_Call) RunAndReturn(run func() ([]byte, error)) *RandomSourceHistoryProvider_RandomSourceHistory_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/reusable_cadence_runtime.go b/fvm/environment/mock/reusable_cadence_runtime.go new file mode 100644 index 00000000000..e8ebd3cecb2 --- /dev/null +++ b/fvm/environment/mock/reusable_cadence_runtime.go @@ -0,0 +1,448 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/cadence" + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/runtime" + "github.com/onflow/cadence/sema" + "github.com/onflow/flow-go/fvm/environment" + mock "github.com/stretchr/testify/mock" +) + +// NewReusableCadenceRuntime creates a new instance of ReusableCadenceRuntime. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReusableCadenceRuntime(t interface { + mock.TestingT + Cleanup(func()) +}) *ReusableCadenceRuntime { + mock := &ReusableCadenceRuntime{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ReusableCadenceRuntime is an autogenerated mock type for the ReusableCadenceRuntime type +type ReusableCadenceRuntime struct { + mock.Mock +} + +type ReusableCadenceRuntime_Expecter struct { + mock *mock.Mock +} + +func (_m *ReusableCadenceRuntime) EXPECT() *ReusableCadenceRuntime_Expecter { + return &ReusableCadenceRuntime_Expecter{mock: &_m.Mock} +} + +// CadenceScriptEnv provides a mock function for the type ReusableCadenceRuntime +func (_mock *ReusableCadenceRuntime) CadenceScriptEnv() runtime.Environment { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for CadenceScriptEnv") + } + + var r0 runtime.Environment + if returnFunc, ok := ret.Get(0).(func() runtime.Environment); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(runtime.Environment) + } + } + return r0 +} + +// ReusableCadenceRuntime_CadenceScriptEnv_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CadenceScriptEnv' +type ReusableCadenceRuntime_CadenceScriptEnv_Call struct { + *mock.Call +} + +// CadenceScriptEnv is a helper method to define mock.On call +func (_e *ReusableCadenceRuntime_Expecter) CadenceScriptEnv() *ReusableCadenceRuntime_CadenceScriptEnv_Call { + return &ReusableCadenceRuntime_CadenceScriptEnv_Call{Call: _e.mock.On("CadenceScriptEnv")} +} + +func (_c *ReusableCadenceRuntime_CadenceScriptEnv_Call) Run(run func()) *ReusableCadenceRuntime_CadenceScriptEnv_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReusableCadenceRuntime_CadenceScriptEnv_Call) Return(environment runtime.Environment) *ReusableCadenceRuntime_CadenceScriptEnv_Call { + _c.Call.Return(environment) + return _c +} + +func (_c *ReusableCadenceRuntime_CadenceScriptEnv_Call) RunAndReturn(run func() runtime.Environment) *ReusableCadenceRuntime_CadenceScriptEnv_Call { + _c.Call.Return(run) + return _c +} + +// CadenceTXEnv provides a mock function for the type ReusableCadenceRuntime +func (_mock *ReusableCadenceRuntime) CadenceTXEnv() runtime.Environment { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for CadenceTXEnv") + } + + var r0 runtime.Environment + if returnFunc, ok := ret.Get(0).(func() runtime.Environment); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(runtime.Environment) + } + } + return r0 +} + +// ReusableCadenceRuntime_CadenceTXEnv_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CadenceTXEnv' +type ReusableCadenceRuntime_CadenceTXEnv_Call struct { + *mock.Call +} + +// CadenceTXEnv is a helper method to define mock.On call +func (_e *ReusableCadenceRuntime_Expecter) CadenceTXEnv() *ReusableCadenceRuntime_CadenceTXEnv_Call { + return &ReusableCadenceRuntime_CadenceTXEnv_Call{Call: _e.mock.On("CadenceTXEnv")} +} + +func (_c *ReusableCadenceRuntime_CadenceTXEnv_Call) Run(run func()) *ReusableCadenceRuntime_CadenceTXEnv_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReusableCadenceRuntime_CadenceTXEnv_Call) Return(environment runtime.Environment) *ReusableCadenceRuntime_CadenceTXEnv_Call { + _c.Call.Return(environment) + return _c +} + +func (_c *ReusableCadenceRuntime_CadenceTXEnv_Call) RunAndReturn(run func() runtime.Environment) *ReusableCadenceRuntime_CadenceTXEnv_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScript provides a mock function for the type ReusableCadenceRuntime +func (_mock *ReusableCadenceRuntime) ExecuteScript(script runtime.Script, location common.Location) (cadence.Value, error) { + ret := _mock.Called(script, location) + + if len(ret) == 0 { + panic("no return value specified for ExecuteScript") + } + + var r0 cadence.Value + var r1 error + if returnFunc, ok := ret.Get(0).(func(runtime.Script, common.Location) (cadence.Value, error)); ok { + return returnFunc(script, location) + } + if returnFunc, ok := ret.Get(0).(func(runtime.Script, common.Location) cadence.Value); ok { + r0 = returnFunc(script, location) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(cadence.Value) + } + } + if returnFunc, ok := ret.Get(1).(func(runtime.Script, common.Location) error); ok { + r1 = returnFunc(script, location) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ReusableCadenceRuntime_ExecuteScript_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScript' +type ReusableCadenceRuntime_ExecuteScript_Call struct { + *mock.Call +} + +// ExecuteScript is a helper method to define mock.On call +// - script runtime.Script +// - location common.Location +func (_e *ReusableCadenceRuntime_Expecter) ExecuteScript(script interface{}, location interface{}) *ReusableCadenceRuntime_ExecuteScript_Call { + return &ReusableCadenceRuntime_ExecuteScript_Call{Call: _e.mock.On("ExecuteScript", script, location)} +} + +func (_c *ReusableCadenceRuntime_ExecuteScript_Call) Run(run func(script runtime.Script, location common.Location)) *ReusableCadenceRuntime_ExecuteScript_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Script + if args[0] != nil { + arg0 = args[0].(runtime.Script) + } + var arg1 common.Location + if args[1] != nil { + arg1 = args[1].(common.Location) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReusableCadenceRuntime_ExecuteScript_Call) Return(value cadence.Value, err error) *ReusableCadenceRuntime_ExecuteScript_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *ReusableCadenceRuntime_ExecuteScript_Call) RunAndReturn(run func(script runtime.Script, location common.Location) (cadence.Value, error)) *ReusableCadenceRuntime_ExecuteScript_Call { + _c.Call.Return(run) + return _c +} + +// InvokeContractFunction provides a mock function for the type ReusableCadenceRuntime +func (_mock *ReusableCadenceRuntime) InvokeContractFunction(contractLocation common.AddressLocation, functionName string, arguments []cadence.Value, argumentTypes []sema.Type) (cadence.Value, error) { + ret := _mock.Called(contractLocation, functionName, arguments, argumentTypes) + + if len(ret) == 0 { + panic("no return value specified for InvokeContractFunction") + } + + var r0 cadence.Value + var r1 error + if returnFunc, ok := ret.Get(0).(func(common.AddressLocation, string, []cadence.Value, []sema.Type) (cadence.Value, error)); ok { + return returnFunc(contractLocation, functionName, arguments, argumentTypes) + } + if returnFunc, ok := ret.Get(0).(func(common.AddressLocation, string, []cadence.Value, []sema.Type) cadence.Value); ok { + r0 = returnFunc(contractLocation, functionName, arguments, argumentTypes) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(cadence.Value) + } + } + if returnFunc, ok := ret.Get(1).(func(common.AddressLocation, string, []cadence.Value, []sema.Type) error); ok { + r1 = returnFunc(contractLocation, functionName, arguments, argumentTypes) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ReusableCadenceRuntime_InvokeContractFunction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InvokeContractFunction' +type ReusableCadenceRuntime_InvokeContractFunction_Call struct { + *mock.Call +} + +// InvokeContractFunction is a helper method to define mock.On call +// - contractLocation common.AddressLocation +// - functionName string +// - arguments []cadence.Value +// - argumentTypes []sema.Type +func (_e *ReusableCadenceRuntime_Expecter) InvokeContractFunction(contractLocation interface{}, functionName interface{}, arguments interface{}, argumentTypes interface{}) *ReusableCadenceRuntime_InvokeContractFunction_Call { + return &ReusableCadenceRuntime_InvokeContractFunction_Call{Call: _e.mock.On("InvokeContractFunction", contractLocation, functionName, arguments, argumentTypes)} +} + +func (_c *ReusableCadenceRuntime_InvokeContractFunction_Call) Run(run func(contractLocation common.AddressLocation, functionName string, arguments []cadence.Value, argumentTypes []sema.Type)) *ReusableCadenceRuntime_InvokeContractFunction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.AddressLocation + if args[0] != nil { + arg0 = args[0].(common.AddressLocation) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 []cadence.Value + if args[2] != nil { + arg2 = args[2].([]cadence.Value) + } + var arg3 []sema.Type + if args[3] != nil { + arg3 = args[3].([]sema.Type) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ReusableCadenceRuntime_InvokeContractFunction_Call) Return(value cadence.Value, err error) *ReusableCadenceRuntime_InvokeContractFunction_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *ReusableCadenceRuntime_InvokeContractFunction_Call) RunAndReturn(run func(contractLocation common.AddressLocation, functionName string, arguments []cadence.Value, argumentTypes []sema.Type) (cadence.Value, error)) *ReusableCadenceRuntime_InvokeContractFunction_Call { + _c.Call.Return(run) + return _c +} + +// NewTransactionExecutor provides a mock function for the type ReusableCadenceRuntime +func (_mock *ReusableCadenceRuntime) NewTransactionExecutor(script runtime.Script, location common.Location) runtime.Executor { + ret := _mock.Called(script, location) + + if len(ret) == 0 { + panic("no return value specified for NewTransactionExecutor") + } + + var r0 runtime.Executor + if returnFunc, ok := ret.Get(0).(func(runtime.Script, common.Location) runtime.Executor); ok { + r0 = returnFunc(script, location) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(runtime.Executor) + } + } + return r0 +} + +// ReusableCadenceRuntime_NewTransactionExecutor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewTransactionExecutor' +type ReusableCadenceRuntime_NewTransactionExecutor_Call struct { + *mock.Call +} + +// NewTransactionExecutor is a helper method to define mock.On call +// - script runtime.Script +// - location common.Location +func (_e *ReusableCadenceRuntime_Expecter) NewTransactionExecutor(script interface{}, location interface{}) *ReusableCadenceRuntime_NewTransactionExecutor_Call { + return &ReusableCadenceRuntime_NewTransactionExecutor_Call{Call: _e.mock.On("NewTransactionExecutor", script, location)} +} + +func (_c *ReusableCadenceRuntime_NewTransactionExecutor_Call) Run(run func(script runtime.Script, location common.Location)) *ReusableCadenceRuntime_NewTransactionExecutor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 runtime.Script + if args[0] != nil { + arg0 = args[0].(runtime.Script) + } + var arg1 common.Location + if args[1] != nil { + arg1 = args[1].(common.Location) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReusableCadenceRuntime_NewTransactionExecutor_Call) Return(executor runtime.Executor) *ReusableCadenceRuntime_NewTransactionExecutor_Call { + _c.Call.Return(executor) + return _c +} + +func (_c *ReusableCadenceRuntime_NewTransactionExecutor_Call) RunAndReturn(run func(script runtime.Script, location common.Location) runtime.Executor) *ReusableCadenceRuntime_NewTransactionExecutor_Call { + _c.Call.Return(run) + return _c +} + +// ReadStored provides a mock function for the type ReusableCadenceRuntime +func (_mock *ReusableCadenceRuntime) ReadStored(address common.Address, path cadence.Path) (cadence.Value, error) { + ret := _mock.Called(address, path) + + if len(ret) == 0 { + panic("no return value specified for ReadStored") + } + + var r0 cadence.Value + var r1 error + if returnFunc, ok := ret.Get(0).(func(common.Address, cadence.Path) (cadence.Value, error)); ok { + return returnFunc(address, path) + } + if returnFunc, ok := ret.Get(0).(func(common.Address, cadence.Path) cadence.Value); ok { + r0 = returnFunc(address, path) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(cadence.Value) + } + } + if returnFunc, ok := ret.Get(1).(func(common.Address, cadence.Path) error); ok { + r1 = returnFunc(address, path) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ReusableCadenceRuntime_ReadStored_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadStored' +type ReusableCadenceRuntime_ReadStored_Call struct { + *mock.Call +} + +// ReadStored is a helper method to define mock.On call +// - address common.Address +// - path cadence.Path +func (_e *ReusableCadenceRuntime_Expecter) ReadStored(address interface{}, path interface{}) *ReusableCadenceRuntime_ReadStored_Call { + return &ReusableCadenceRuntime_ReadStored_Call{Call: _e.mock.On("ReadStored", address, path)} +} + +func (_c *ReusableCadenceRuntime_ReadStored_Call) Run(run func(address common.Address, path cadence.Path)) *ReusableCadenceRuntime_ReadStored_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 common.Address + if args[0] != nil { + arg0 = args[0].(common.Address) + } + var arg1 cadence.Path + if args[1] != nil { + arg1 = args[1].(cadence.Path) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReusableCadenceRuntime_ReadStored_Call) Return(value cadence.Value, err error) *ReusableCadenceRuntime_ReadStored_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *ReusableCadenceRuntime_ReadStored_Call) RunAndReturn(run func(address common.Address, path cadence.Path) (cadence.Value, error)) *ReusableCadenceRuntime_ReadStored_Call { + _c.Call.Return(run) + return _c +} + +// SetFvmEnvironment provides a mock function for the type ReusableCadenceRuntime +func (_mock *ReusableCadenceRuntime) SetFvmEnvironment(fvmEnv environment.Environment) { + _mock.Called(fvmEnv) + return +} + +// ReusableCadenceRuntime_SetFvmEnvironment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetFvmEnvironment' +type ReusableCadenceRuntime_SetFvmEnvironment_Call struct { + *mock.Call +} + +// SetFvmEnvironment is a helper method to define mock.On call +// - fvmEnv environment.Environment +func (_e *ReusableCadenceRuntime_Expecter) SetFvmEnvironment(fvmEnv interface{}) *ReusableCadenceRuntime_SetFvmEnvironment_Call { + return &ReusableCadenceRuntime_SetFvmEnvironment_Call{Call: _e.mock.On("SetFvmEnvironment", fvmEnv)} +} + +func (_c *ReusableCadenceRuntime_SetFvmEnvironment_Call) Run(run func(fvmEnv environment.Environment)) *ReusableCadenceRuntime_SetFvmEnvironment_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.Environment + if args[0] != nil { + arg0 = args[0].(environment.Environment) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReusableCadenceRuntime_SetFvmEnvironment_Call) Return() *ReusableCadenceRuntime_SetFvmEnvironment_Call { + _c.Call.Return() + return _c +} + +func (_c *ReusableCadenceRuntime_SetFvmEnvironment_Call) RunAndReturn(run func(fvmEnv environment.Environment)) *ReusableCadenceRuntime_SetFvmEnvironment_Call { + _c.Run(run) + return _c +} diff --git a/fvm/environment/mock/reusable_cadence_runtime_pool.go b/fvm/environment/mock/reusable_cadence_runtime_pool.go new file mode 100644 index 00000000000..844fe26da3d --- /dev/null +++ b/fvm/environment/mock/reusable_cadence_runtime_pool.go @@ -0,0 +1,136 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/fvm/environment" + mock "github.com/stretchr/testify/mock" +) + +// NewReusableCadenceRuntimePool creates a new instance of ReusableCadenceRuntimePool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReusableCadenceRuntimePool(t interface { + mock.TestingT + Cleanup(func()) +}) *ReusableCadenceRuntimePool { + mock := &ReusableCadenceRuntimePool{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ReusableCadenceRuntimePool is an autogenerated mock type for the ReusableCadenceRuntimePool type +type ReusableCadenceRuntimePool struct { + mock.Mock +} + +type ReusableCadenceRuntimePool_Expecter struct { + mock *mock.Mock +} + +func (_m *ReusableCadenceRuntimePool) EXPECT() *ReusableCadenceRuntimePool_Expecter { + return &ReusableCadenceRuntimePool_Expecter{mock: &_m.Mock} +} + +// Borrow provides a mock function for the type ReusableCadenceRuntimePool +func (_mock *ReusableCadenceRuntimePool) Borrow(fvmEnv environment.Environment, runtimeType environment.CadenceRuntimeType) environment.ReusableCadenceRuntime { + ret := _mock.Called(fvmEnv, runtimeType) + + if len(ret) == 0 { + panic("no return value specified for Borrow") + } + + var r0 environment.ReusableCadenceRuntime + if returnFunc, ok := ret.Get(0).(func(environment.Environment, environment.CadenceRuntimeType) environment.ReusableCadenceRuntime); ok { + r0 = returnFunc(fvmEnv, runtimeType) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(environment.ReusableCadenceRuntime) + } + } + return r0 +} + +// ReusableCadenceRuntimePool_Borrow_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Borrow' +type ReusableCadenceRuntimePool_Borrow_Call struct { + *mock.Call +} + +// Borrow is a helper method to define mock.On call +// - fvmEnv environment.Environment +// - runtimeType environment.CadenceRuntimeType +func (_e *ReusableCadenceRuntimePool_Expecter) Borrow(fvmEnv interface{}, runtimeType interface{}) *ReusableCadenceRuntimePool_Borrow_Call { + return &ReusableCadenceRuntimePool_Borrow_Call{Call: _e.mock.On("Borrow", fvmEnv, runtimeType)} +} + +func (_c *ReusableCadenceRuntimePool_Borrow_Call) Run(run func(fvmEnv environment.Environment, runtimeType environment.CadenceRuntimeType)) *ReusableCadenceRuntimePool_Borrow_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.Environment + if args[0] != nil { + arg0 = args[0].(environment.Environment) + } + var arg1 environment.CadenceRuntimeType + if args[1] != nil { + arg1 = args[1].(environment.CadenceRuntimeType) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReusableCadenceRuntimePool_Borrow_Call) Return(reusableCadenceRuntime environment.ReusableCadenceRuntime) *ReusableCadenceRuntimePool_Borrow_Call { + _c.Call.Return(reusableCadenceRuntime) + return _c +} + +func (_c *ReusableCadenceRuntimePool_Borrow_Call) RunAndReturn(run func(fvmEnv environment.Environment, runtimeType environment.CadenceRuntimeType) environment.ReusableCadenceRuntime) *ReusableCadenceRuntimePool_Borrow_Call { + _c.Call.Return(run) + return _c +} + +// Return provides a mock function for the type ReusableCadenceRuntimePool +func (_mock *ReusableCadenceRuntimePool) Return(reusable environment.ReusableCadenceRuntime) { + _mock.Called(reusable) + return +} + +// ReusableCadenceRuntimePool_Return_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Return' +type ReusableCadenceRuntimePool_Return_Call struct { + *mock.Call +} + +// Return is a helper method to define mock.On call +// - reusable environment.ReusableCadenceRuntime +func (_e *ReusableCadenceRuntimePool_Expecter) Return(reusable interface{}) *ReusableCadenceRuntimePool_Return_Call { + return &ReusableCadenceRuntimePool_Return_Call{Call: _e.mock.On("Return", reusable)} +} + +func (_c *ReusableCadenceRuntimePool_Return_Call) Run(run func(reusable environment.ReusableCadenceRuntime)) *ReusableCadenceRuntimePool_Return_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 environment.ReusableCadenceRuntime + if args[0] != nil { + arg0 = args[0].(environment.ReusableCadenceRuntime) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReusableCadenceRuntimePool_Return_Call) Return() *ReusableCadenceRuntimePool_Return_Call { + _c.Call.Return() + return _c +} + +func (_c *ReusableCadenceRuntimePool_Return_Call) RunAndReturn(run func(reusable environment.ReusableCadenceRuntime)) *ReusableCadenceRuntimePool_Return_Call { + _c.Run(run) + return _c +} diff --git a/fvm/environment/mock/runtime_metrics_reporter.go b/fvm/environment/mock/runtime_metrics_reporter.go index 0e895937e4c..06d75385f1c 100644 --- a/fvm/environment/mock/runtime_metrics_reporter.go +++ b/fvm/environment/mock/runtime_metrics_reporter.go @@ -1,58 +1,264 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - time "time" + "time" mock "github.com/stretchr/testify/mock" ) +// NewRuntimeMetricsReporter creates a new instance of RuntimeMetricsReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRuntimeMetricsReporter(t interface { + mock.TestingT + Cleanup(func()) +}) *RuntimeMetricsReporter { + mock := &RuntimeMetricsReporter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RuntimeMetricsReporter is an autogenerated mock type for the RuntimeMetricsReporter type type RuntimeMetricsReporter struct { mock.Mock } -// RuntimeSetNumberOfAccounts provides a mock function with given fields: count -func (_m *RuntimeMetricsReporter) RuntimeSetNumberOfAccounts(count uint64) { - _m.Called(count) +type RuntimeMetricsReporter_Expecter struct { + mock *mock.Mock } -// RuntimeTransactionChecked provides a mock function with given fields: _a0 -func (_m *RuntimeMetricsReporter) RuntimeTransactionChecked(_a0 time.Duration) { - _m.Called(_a0) +func (_m *RuntimeMetricsReporter) EXPECT() *RuntimeMetricsReporter_Expecter { + return &RuntimeMetricsReporter_Expecter{mock: &_m.Mock} } -// RuntimeTransactionInterpreted provides a mock function with given fields: _a0 -func (_m *RuntimeMetricsReporter) RuntimeTransactionInterpreted(_a0 time.Duration) { - _m.Called(_a0) +// RuntimeSetNumberOfAccounts provides a mock function for the type RuntimeMetricsReporter +func (_mock *RuntimeMetricsReporter) RuntimeSetNumberOfAccounts(count uint64) { + _mock.Called(count) + return } -// RuntimeTransactionParsed provides a mock function with given fields: _a0 -func (_m *RuntimeMetricsReporter) RuntimeTransactionParsed(_a0 time.Duration) { - _m.Called(_a0) +// RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeSetNumberOfAccounts' +type RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call struct { + *mock.Call } -// RuntimeTransactionProgramsCacheHit provides a mock function with no fields -func (_m *RuntimeMetricsReporter) RuntimeTransactionProgramsCacheHit() { - _m.Called() +// RuntimeSetNumberOfAccounts is a helper method to define mock.On call +// - count uint64 +func (_e *RuntimeMetricsReporter_Expecter) RuntimeSetNumberOfAccounts(count interface{}) *RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call { + return &RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call{Call: _e.mock.On("RuntimeSetNumberOfAccounts", count)} } -// RuntimeTransactionProgramsCacheMiss provides a mock function with no fields -func (_m *RuntimeMetricsReporter) RuntimeTransactionProgramsCacheMiss() { - _m.Called() +func (_c *RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call) Run(run func(count uint64)) *RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c } -// NewRuntimeMetricsReporter creates a new instance of RuntimeMetricsReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRuntimeMetricsReporter(t interface { - mock.TestingT - Cleanup(func()) -}) *RuntimeMetricsReporter { - mock := &RuntimeMetricsReporter{} - mock.Mock.Test(t) +func (_c *RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call) Return() *RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call { + _c.Call.Return() + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call) RunAndReturn(run func(count uint64)) *RuntimeMetricsReporter_RuntimeSetNumberOfAccounts_Call { + _c.Run(run) + return _c +} - return mock +// RuntimeTransactionChecked provides a mock function for the type RuntimeMetricsReporter +func (_mock *RuntimeMetricsReporter) RuntimeTransactionChecked(duration time.Duration) { + _mock.Called(duration) + return +} + +// RuntimeMetricsReporter_RuntimeTransactionChecked_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionChecked' +type RuntimeMetricsReporter_RuntimeTransactionChecked_Call struct { + *mock.Call +} + +// RuntimeTransactionChecked is a helper method to define mock.On call +// - duration time.Duration +func (_e *RuntimeMetricsReporter_Expecter) RuntimeTransactionChecked(duration interface{}) *RuntimeMetricsReporter_RuntimeTransactionChecked_Call { + return &RuntimeMetricsReporter_RuntimeTransactionChecked_Call{Call: _e.mock.On("RuntimeTransactionChecked", duration)} +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionChecked_Call) Run(run func(duration time.Duration)) *RuntimeMetricsReporter_RuntimeTransactionChecked_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionChecked_Call) Return() *RuntimeMetricsReporter_RuntimeTransactionChecked_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionChecked_Call) RunAndReturn(run func(duration time.Duration)) *RuntimeMetricsReporter_RuntimeTransactionChecked_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionInterpreted provides a mock function for the type RuntimeMetricsReporter +func (_mock *RuntimeMetricsReporter) RuntimeTransactionInterpreted(duration time.Duration) { + _mock.Called(duration) + return +} + +// RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionInterpreted' +type RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call struct { + *mock.Call +} + +// RuntimeTransactionInterpreted is a helper method to define mock.On call +// - duration time.Duration +func (_e *RuntimeMetricsReporter_Expecter) RuntimeTransactionInterpreted(duration interface{}) *RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call { + return &RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call{Call: _e.mock.On("RuntimeTransactionInterpreted", duration)} +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call) Run(run func(duration time.Duration)) *RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call) Return() *RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call) RunAndReturn(run func(duration time.Duration)) *RuntimeMetricsReporter_RuntimeTransactionInterpreted_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionParsed provides a mock function for the type RuntimeMetricsReporter +func (_mock *RuntimeMetricsReporter) RuntimeTransactionParsed(duration time.Duration) { + _mock.Called(duration) + return +} + +// RuntimeMetricsReporter_RuntimeTransactionParsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionParsed' +type RuntimeMetricsReporter_RuntimeTransactionParsed_Call struct { + *mock.Call +} + +// RuntimeTransactionParsed is a helper method to define mock.On call +// - duration time.Duration +func (_e *RuntimeMetricsReporter_Expecter) RuntimeTransactionParsed(duration interface{}) *RuntimeMetricsReporter_RuntimeTransactionParsed_Call { + return &RuntimeMetricsReporter_RuntimeTransactionParsed_Call{Call: _e.mock.On("RuntimeTransactionParsed", duration)} +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionParsed_Call) Run(run func(duration time.Duration)) *RuntimeMetricsReporter_RuntimeTransactionParsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionParsed_Call) Return() *RuntimeMetricsReporter_RuntimeTransactionParsed_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionParsed_Call) RunAndReturn(run func(duration time.Duration)) *RuntimeMetricsReporter_RuntimeTransactionParsed_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheHit provides a mock function for the type RuntimeMetricsReporter +func (_mock *RuntimeMetricsReporter) RuntimeTransactionProgramsCacheHit() { + _mock.Called() + return +} + +// RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheHit' +type RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheHit is a helper method to define mock.On call +func (_e *RuntimeMetricsReporter_Expecter) RuntimeTransactionProgramsCacheHit() *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + return &RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheHit")} +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call) Run(run func()) *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call) Return() *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call) RunAndReturn(run func()) *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheHit_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheMiss provides a mock function for the type RuntimeMetricsReporter +func (_mock *RuntimeMetricsReporter) RuntimeTransactionProgramsCacheMiss() { + _mock.Called() + return +} + +// RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheMiss' +type RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheMiss is a helper method to define mock.On call +func (_e *RuntimeMetricsReporter_Expecter) RuntimeTransactionProgramsCacheMiss() *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + return &RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheMiss")} +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call) Run(run func()) *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call) Return() *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call) RunAndReturn(run func()) *RuntimeMetricsReporter_RuntimeTransactionProgramsCacheMiss_Call { + _c.Run(run) + return _c } diff --git a/fvm/environment/mock/tracer.go b/fvm/environment/mock/tracer.go index c6dc6507cc9..b0eb5e33bc7 100644 --- a/fvm/environment/mock/tracer.go +++ b/fvm/environment/mock/tracer.go @@ -1,23 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/onflow/flow-go/fvm/tracing" + "github.com/onflow/flow-go/module/trace" mock "github.com/stretchr/testify/mock" - oteltrace "go.opentelemetry.io/otel/trace" + trace0 "go.opentelemetry.io/otel/trace" +) + +// NewTracer creates a new instance of Tracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTracer(t interface { + mock.TestingT + Cleanup(func()) +}) *Tracer { + mock := &Tracer{} + mock.Mock.Test(t) - trace "github.com/onflow/flow-go/module/trace" + t.Cleanup(func() { mock.AssertExpectations(t) }) - tracing "github.com/onflow/flow-go/fvm/tracing" -) + return mock +} // Tracer is an autogenerated mock type for the Tracer type type Tracer struct { mock.Mock } -// StartChildSpan provides a mock function with given fields: name, options -func (_m *Tracer) StartChildSpan(name trace.SpanName, options ...oteltrace.SpanStartOption) tracing.TracerSpan { +type Tracer_Expecter struct { + mock *mock.Mock +} + +func (_m *Tracer) EXPECT() *Tracer_Expecter { + return &Tracer_Expecter{mock: &_m.Mock} +} + +// StartChildSpan provides a mock function for the type Tracer +func (_mock *Tracer) StartChildSpan(name trace.SpanName, options ...trace0.SpanStartOption) tracing.TracerSpan { + // trace0.SpanStartOption _va := make([]interface{}, len(options)) for _i := range options { _va[_i] = options[_i] @@ -25,32 +48,62 @@ func (_m *Tracer) StartChildSpan(name trace.SpanName, options ...oteltrace.SpanS var _ca []interface{} _ca = append(_ca, name) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartChildSpan") } var r0 tracing.TracerSpan - if rf, ok := ret.Get(0).(func(trace.SpanName, ...oteltrace.SpanStartOption) tracing.TracerSpan); ok { - r0 = rf(name, options...) + if returnFunc, ok := ret.Get(0).(func(trace.SpanName, ...trace0.SpanStartOption) tracing.TracerSpan); ok { + r0 = returnFunc(name, options...) } else { r0 = ret.Get(0).(tracing.TracerSpan) } - return r0 } -// NewTracer creates a new instance of Tracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTracer(t interface { - mock.TestingT - Cleanup(func()) -}) *Tracer { - mock := &Tracer{} - mock.Mock.Test(t) +// Tracer_StartChildSpan_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartChildSpan' +type Tracer_StartChildSpan_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StartChildSpan is a helper method to define mock.On call +// - name trace.SpanName +// - options ...trace0.SpanStartOption +func (_e *Tracer_Expecter) StartChildSpan(name interface{}, options ...interface{}) *Tracer_StartChildSpan_Call { + return &Tracer_StartChildSpan_Call{Call: _e.mock.On("StartChildSpan", + append([]interface{}{name}, options...)...)} +} - return mock +func (_c *Tracer_StartChildSpan_Call) Run(run func(name trace.SpanName, options ...trace0.SpanStartOption)) *Tracer_StartChildSpan_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 trace.SpanName + if args[0] != nil { + arg0 = args[0].(trace.SpanName) + } + var arg1 []trace0.SpanStartOption + variadicArgs := make([]trace0.SpanStartOption, len(args)-1) + for i, a := range args[1:] { + if a != nil { + variadicArgs[i] = a.(trace0.SpanStartOption) + } + } + arg1 = variadicArgs + run( + arg0, + arg1..., + ) + }) + return _c +} + +func (_c *Tracer_StartChildSpan_Call) Return(tracerSpan tracing.TracerSpan) *Tracer_StartChildSpan_Call { + _c.Call.Return(tracerSpan) + return _c +} + +func (_c *Tracer_StartChildSpan_Call) RunAndReturn(run func(name trace.SpanName, options ...trace0.SpanStartOption) tracing.TracerSpan) *Tracer_StartChildSpan_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/transaction_info.go b/fvm/environment/mock/transaction_info.go index f996a3b5ec1..0fe301eeeae 100644 --- a/fvm/environment/mock/transaction_info.go +++ b/fvm/environment/mock/transaction_info.go @@ -1,23 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - common "github.com/onflow/cadence/common" - - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/cadence/common" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTransactionInfo creates a new instance of TransactionInfo. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionInfo(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionInfo { + mock := &TransactionInfo{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionInfo is an autogenerated mock type for the TransactionInfo type type TransactionInfo struct { mock.Mock } -// GetSigningAccounts provides a mock function with no fields -func (_m *TransactionInfo) GetSigningAccounts() ([]common.Address, error) { - ret := _m.Called() +type TransactionInfo_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionInfo) EXPECT() *TransactionInfo_Expecter { + return &TransactionInfo_Expecter{mock: &_m.Mock} +} + +// GetSigningAccounts provides a mock function for the type TransactionInfo +func (_mock *TransactionInfo) GetSigningAccounts() ([]common.Address, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetSigningAccounts") @@ -25,128 +47,269 @@ func (_m *TransactionInfo) GetSigningAccounts() ([]common.Address, error) { var r0 []common.Address var r1 error - if rf, ok := ret.Get(0).(func() ([]common.Address, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]common.Address, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []common.Address); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []common.Address); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]common.Address) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// IsServiceAccountAuthorizer provides a mock function with no fields -func (_m *TransactionInfo) IsServiceAccountAuthorizer() bool { - ret := _m.Called() +// TransactionInfo_GetSigningAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSigningAccounts' +type TransactionInfo_GetSigningAccounts_Call struct { + *mock.Call +} + +// GetSigningAccounts is a helper method to define mock.On call +func (_e *TransactionInfo_Expecter) GetSigningAccounts() *TransactionInfo_GetSigningAccounts_Call { + return &TransactionInfo_GetSigningAccounts_Call{Call: _e.mock.On("GetSigningAccounts")} +} + +func (_c *TransactionInfo_GetSigningAccounts_Call) Run(run func()) *TransactionInfo_GetSigningAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionInfo_GetSigningAccounts_Call) Return(addresss []common.Address, err error) *TransactionInfo_GetSigningAccounts_Call { + _c.Call.Return(addresss, err) + return _c +} + +func (_c *TransactionInfo_GetSigningAccounts_Call) RunAndReturn(run func() ([]common.Address, error)) *TransactionInfo_GetSigningAccounts_Call { + _c.Call.Return(run) + return _c +} + +// IsServiceAccountAuthorizer provides a mock function for the type TransactionInfo +func (_mock *TransactionInfo) IsServiceAccountAuthorizer() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for IsServiceAccountAuthorizer") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// LimitAccountStorage provides a mock function with no fields -func (_m *TransactionInfo) LimitAccountStorage() bool { - ret := _m.Called() +// TransactionInfo_IsServiceAccountAuthorizer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsServiceAccountAuthorizer' +type TransactionInfo_IsServiceAccountAuthorizer_Call struct { + *mock.Call +} + +// IsServiceAccountAuthorizer is a helper method to define mock.On call +func (_e *TransactionInfo_Expecter) IsServiceAccountAuthorizer() *TransactionInfo_IsServiceAccountAuthorizer_Call { + return &TransactionInfo_IsServiceAccountAuthorizer_Call{Call: _e.mock.On("IsServiceAccountAuthorizer")} +} + +func (_c *TransactionInfo_IsServiceAccountAuthorizer_Call) Run(run func()) *TransactionInfo_IsServiceAccountAuthorizer_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionInfo_IsServiceAccountAuthorizer_Call) Return(b bool) *TransactionInfo_IsServiceAccountAuthorizer_Call { + _c.Call.Return(b) + return _c +} + +func (_c *TransactionInfo_IsServiceAccountAuthorizer_Call) RunAndReturn(run func() bool) *TransactionInfo_IsServiceAccountAuthorizer_Call { + _c.Call.Return(run) + return _c +} + +// LimitAccountStorage provides a mock function for the type TransactionInfo +func (_mock *TransactionInfo) LimitAccountStorage() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LimitAccountStorage") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// TransactionFeesEnabled provides a mock function with no fields -func (_m *TransactionInfo) TransactionFeesEnabled() bool { - ret := _m.Called() +// TransactionInfo_LimitAccountStorage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LimitAccountStorage' +type TransactionInfo_LimitAccountStorage_Call struct { + *mock.Call +} + +// LimitAccountStorage is a helper method to define mock.On call +func (_e *TransactionInfo_Expecter) LimitAccountStorage() *TransactionInfo_LimitAccountStorage_Call { + return &TransactionInfo_LimitAccountStorage_Call{Call: _e.mock.On("LimitAccountStorage")} +} + +func (_c *TransactionInfo_LimitAccountStorage_Call) Run(run func()) *TransactionInfo_LimitAccountStorage_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionInfo_LimitAccountStorage_Call) Return(b bool) *TransactionInfo_LimitAccountStorage_Call { + _c.Call.Return(b) + return _c +} + +func (_c *TransactionInfo_LimitAccountStorage_Call) RunAndReturn(run func() bool) *TransactionInfo_LimitAccountStorage_Call { + _c.Call.Return(run) + return _c +} + +// TransactionFeesEnabled provides a mock function for the type TransactionInfo +func (_mock *TransactionInfo) TransactionFeesEnabled() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TransactionFeesEnabled") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// TxID provides a mock function with no fields -func (_m *TransactionInfo) TxID() flow.Identifier { - ret := _m.Called() +// TransactionInfo_TransactionFeesEnabled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionFeesEnabled' +type TransactionInfo_TransactionFeesEnabled_Call struct { + *mock.Call +} + +// TransactionFeesEnabled is a helper method to define mock.On call +func (_e *TransactionInfo_Expecter) TransactionFeesEnabled() *TransactionInfo_TransactionFeesEnabled_Call { + return &TransactionInfo_TransactionFeesEnabled_Call{Call: _e.mock.On("TransactionFeesEnabled")} +} + +func (_c *TransactionInfo_TransactionFeesEnabled_Call) Run(run func()) *TransactionInfo_TransactionFeesEnabled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionInfo_TransactionFeesEnabled_Call) Return(b bool) *TransactionInfo_TransactionFeesEnabled_Call { + _c.Call.Return(b) + return _c +} + +func (_c *TransactionInfo_TransactionFeesEnabled_Call) RunAndReturn(run func() bool) *TransactionInfo_TransactionFeesEnabled_Call { + _c.Call.Return(run) + return _c +} + +// TxID provides a mock function for the type TransactionInfo +func (_mock *TransactionInfo) TxID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TxID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// TxIndex provides a mock function with no fields -func (_m *TransactionInfo) TxIndex() uint32 { - ret := _m.Called() +// TransactionInfo_TxID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxID' +type TransactionInfo_TxID_Call struct { + *mock.Call +} + +// TxID is a helper method to define mock.On call +func (_e *TransactionInfo_Expecter) TxID() *TransactionInfo_TxID_Call { + return &TransactionInfo_TxID_Call{Call: _e.mock.On("TxID")} +} + +func (_c *TransactionInfo_TxID_Call) Run(run func()) *TransactionInfo_TxID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionInfo_TxID_Call) Return(identifier flow.Identifier) *TransactionInfo_TxID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *TransactionInfo_TxID_Call) RunAndReturn(run func() flow.Identifier) *TransactionInfo_TxID_Call { + _c.Call.Return(run) + return _c +} + +// TxIndex provides a mock function for the type TransactionInfo +func (_mock *TransactionInfo) TxIndex() uint32 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TxIndex") } var r0 uint32 - if rf, ok := ret.Get(0).(func() uint32); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint32); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint32) } - return r0 } -// NewTransactionInfo creates a new instance of TransactionInfo. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionInfo(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionInfo { - mock := &TransactionInfo{} - mock.Mock.Test(t) +// TransactionInfo_TxIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxIndex' +type TransactionInfo_TxIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TxIndex is a helper method to define mock.On call +func (_e *TransactionInfo_Expecter) TxIndex() *TransactionInfo_TxIndex_Call { + return &TransactionInfo_TxIndex_Call{Call: _e.mock.On("TxIndex")} +} - return mock +func (_c *TransactionInfo_TxIndex_Call) Run(run func()) *TransactionInfo_TxIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionInfo_TxIndex_Call) Return(v uint32) *TransactionInfo_TxIndex_Call { + _c.Call.Return(v) + return _c +} + +func (_c *TransactionInfo_TxIndex_Call) RunAndReturn(run func() uint32) *TransactionInfo_TxIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/uuid_generator.go b/fvm/environment/mock/uuid_generator.go index 5d67496b422..b3136c04f7c 100644 --- a/fvm/environment/mock/uuid_generator.go +++ b/fvm/environment/mock/uuid_generator.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewUUIDGenerator creates a new instance of UUIDGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewUUIDGenerator(t interface { + mock.TestingT + Cleanup(func()) +}) *UUIDGenerator { + mock := &UUIDGenerator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // UUIDGenerator is an autogenerated mock type for the UUIDGenerator type type UUIDGenerator struct { mock.Mock } -// GenerateUUID provides a mock function with no fields -func (_m *UUIDGenerator) GenerateUUID() (uint64, error) { - ret := _m.Called() +type UUIDGenerator_Expecter struct { + mock *mock.Mock +} + +func (_m *UUIDGenerator) EXPECT() *UUIDGenerator_Expecter { + return &UUIDGenerator_Expecter{mock: &_m.Mock} +} + +// GenerateUUID provides a mock function for the type UUIDGenerator +func (_mock *UUIDGenerator) GenerateUUID() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GenerateUUID") @@ -19,34 +45,45 @@ func (_m *UUIDGenerator) GenerateUUID() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewUUIDGenerator creates a new instance of UUIDGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewUUIDGenerator(t interface { - mock.TestingT - Cleanup(func()) -}) *UUIDGenerator { - mock := &UUIDGenerator{} - mock.Mock.Test(t) +// UUIDGenerator_GenerateUUID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateUUID' +type UUIDGenerator_GenerateUUID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GenerateUUID is a helper method to define mock.On call +func (_e *UUIDGenerator_Expecter) GenerateUUID() *UUIDGenerator_GenerateUUID_Call { + return &UUIDGenerator_GenerateUUID_Call{Call: _e.mock.On("GenerateUUID")} +} - return mock +func (_c *UUIDGenerator_GenerateUUID_Call) Run(run func()) *UUIDGenerator_GenerateUUID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *UUIDGenerator_GenerateUUID_Call) Return(v uint64, err error) *UUIDGenerator_GenerateUUID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *UUIDGenerator_GenerateUUID_Call) RunAndReturn(run func() (uint64, error)) *UUIDGenerator_GenerateUUID_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/mock/value_store.go b/fvm/environment/mock/value_store.go index ad00d31f97f..330071b2b92 100644 --- a/fvm/environment/mock/value_store.go +++ b/fvm/environment/mock/value_store.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - atree "github.com/onflow/atree" - + "github.com/onflow/atree" mock "github.com/stretchr/testify/mock" ) +// NewValueStore creates a new instance of ValueStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewValueStore(t interface { + mock.TestingT + Cleanup(func()) +}) *ValueStore { + mock := &ValueStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ValueStore is an autogenerated mock type for the ValueStore type type ValueStore struct { mock.Mock } -// AllocateSlabIndex provides a mock function with given fields: owner -func (_m *ValueStore) AllocateSlabIndex(owner []byte) (atree.SlabIndex, error) { - ret := _m.Called(owner) +type ValueStore_Expecter struct { + mock *mock.Mock +} + +func (_m *ValueStore) EXPECT() *ValueStore_Expecter { + return &ValueStore_Expecter{mock: &_m.Mock} +} + +// AllocateSlabIndex provides a mock function for the type ValueStore +func (_mock *ValueStore) AllocateSlabIndex(owner []byte) (atree.SlabIndex, error) { + ret := _mock.Called(owner) if len(ret) == 0 { panic("no return value specified for AllocateSlabIndex") @@ -23,29 +46,61 @@ func (_m *ValueStore) AllocateSlabIndex(owner []byte) (atree.SlabIndex, error) { var r0 atree.SlabIndex var r1 error - if rf, ok := ret.Get(0).(func([]byte) (atree.SlabIndex, error)); ok { - return rf(owner) + if returnFunc, ok := ret.Get(0).(func([]byte) (atree.SlabIndex, error)); ok { + return returnFunc(owner) } - if rf, ok := ret.Get(0).(func([]byte) atree.SlabIndex); ok { - r0 = rf(owner) + if returnFunc, ok := ret.Get(0).(func([]byte) atree.SlabIndex); ok { + r0 = returnFunc(owner) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(atree.SlabIndex) } } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(owner) + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(owner) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetValue provides a mock function with given fields: owner, key -func (_m *ValueStore) GetValue(owner []byte, key []byte) ([]byte, error) { - ret := _m.Called(owner, key) +// ValueStore_AllocateSlabIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllocateSlabIndex' +type ValueStore_AllocateSlabIndex_Call struct { + *mock.Call +} + +// AllocateSlabIndex is a helper method to define mock.On call +// - owner []byte +func (_e *ValueStore_Expecter) AllocateSlabIndex(owner interface{}) *ValueStore_AllocateSlabIndex_Call { + return &ValueStore_AllocateSlabIndex_Call{Call: _e.mock.On("AllocateSlabIndex", owner)} +} + +func (_c *ValueStore_AllocateSlabIndex_Call) Run(run func(owner []byte)) *ValueStore_AllocateSlabIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ValueStore_AllocateSlabIndex_Call) Return(slabIndex atree.SlabIndex, err error) *ValueStore_AllocateSlabIndex_Call { + _c.Call.Return(slabIndex, err) + return _c +} + +func (_c *ValueStore_AllocateSlabIndex_Call) RunAndReturn(run func(owner []byte) (atree.SlabIndex, error)) *ValueStore_AllocateSlabIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetValue provides a mock function for the type ValueStore +func (_mock *ValueStore) GetValue(owner []byte, key []byte) ([]byte, error) { + ret := _mock.Called(owner, key) if len(ret) == 0 { panic("no return value specified for GetValue") @@ -53,47 +108,130 @@ func (_m *ValueStore) GetValue(owner []byte, key []byte) ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func([]byte, []byte) ([]byte, error)); ok { - return rf(owner, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) ([]byte, error)); ok { + return returnFunc(owner, key) } - if rf, ok := ret.Get(0).(func([]byte, []byte) []byte); ok { - r0 = rf(owner, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) []byte); ok { + r0 = returnFunc(owner, key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func([]byte, []byte) error); ok { - r1 = rf(owner, key) + if returnFunc, ok := ret.Get(1).(func([]byte, []byte) error); ok { + r1 = returnFunc(owner, key) } else { r1 = ret.Error(1) } - return r0, r1 } -// SetValue provides a mock function with given fields: owner, key, value -func (_m *ValueStore) SetValue(owner []byte, key []byte, value []byte) error { - ret := _m.Called(owner, key, value) +// ValueStore_GetValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetValue' +type ValueStore_GetValue_Call struct { + *mock.Call +} + +// GetValue is a helper method to define mock.On call +// - owner []byte +// - key []byte +func (_e *ValueStore_Expecter) GetValue(owner interface{}, key interface{}) *ValueStore_GetValue_Call { + return &ValueStore_GetValue_Call{Call: _e.mock.On("GetValue", owner, key)} +} + +func (_c *ValueStore_GetValue_Call) Run(run func(owner []byte, key []byte)) *ValueStore_GetValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ValueStore_GetValue_Call) Return(bytes []byte, err error) *ValueStore_GetValue_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ValueStore_GetValue_Call) RunAndReturn(run func(owner []byte, key []byte) ([]byte, error)) *ValueStore_GetValue_Call { + _c.Call.Return(run) + return _c +} + +// SetValue provides a mock function for the type ValueStore +func (_mock *ValueStore) SetValue(owner []byte, key []byte, value []byte) error { + ret := _mock.Called(owner, key, value) if len(ret) == 0 { panic("no return value specified for SetValue") } var r0 error - if rf, ok := ret.Get(0).(func([]byte, []byte, []byte) error); ok { - r0 = rf(owner, key, value) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte, []byte) error); ok { + r0 = returnFunc(owner, key, value) } else { r0 = ret.Error(0) } - return r0 } -// ValueExists provides a mock function with given fields: owner, key -func (_m *ValueStore) ValueExists(owner []byte, key []byte) (bool, error) { - ret := _m.Called(owner, key) +// ValueStore_SetValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetValue' +type ValueStore_SetValue_Call struct { + *mock.Call +} + +// SetValue is a helper method to define mock.On call +// - owner []byte +// - key []byte +// - value []byte +func (_e *ValueStore_Expecter) SetValue(owner interface{}, key interface{}, value interface{}) *ValueStore_SetValue_Call { + return &ValueStore_SetValue_Call{Call: _e.mock.On("SetValue", owner, key, value)} +} + +func (_c *ValueStore_SetValue_Call) Run(run func(owner []byte, key []byte, value []byte)) *ValueStore_SetValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ValueStore_SetValue_Call) Return(err error) *ValueStore_SetValue_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ValueStore_SetValue_Call) RunAndReturn(run func(owner []byte, key []byte, value []byte) error) *ValueStore_SetValue_Call { + _c.Call.Return(run) + return _c +} + +// ValueExists provides a mock function for the type ValueStore +func (_mock *ValueStore) ValueExists(owner []byte, key []byte) (bool, error) { + ret := _mock.Called(owner, key) if len(ret) == 0 { panic("no return value specified for ValueExists") @@ -101,34 +239,58 @@ func (_m *ValueStore) ValueExists(owner []byte, key []byte) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func([]byte, []byte) (bool, error)); ok { - return rf(owner, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) (bool, error)); ok { + return returnFunc(owner, key) } - if rf, ok := ret.Get(0).(func([]byte, []byte) bool); ok { - r0 = rf(owner, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) bool); ok { + r0 = returnFunc(owner, key) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func([]byte, []byte) error); ok { - r1 = rf(owner, key) + if returnFunc, ok := ret.Get(1).(func([]byte, []byte) error); ok { + r1 = returnFunc(owner, key) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewValueStore creates a new instance of ValueStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewValueStore(t interface { - mock.TestingT - Cleanup(func()) -}) *ValueStore { - mock := &ValueStore{} - mock.Mock.Test(t) +// ValueStore_ValueExists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValueExists' +type ValueStore_ValueExists_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ValueExists is a helper method to define mock.On call +// - owner []byte +// - key []byte +func (_e *ValueStore_Expecter) ValueExists(owner interface{}, key interface{}) *ValueStore_ValueExists_Call { + return &ValueStore_ValueExists_Call{Call: _e.mock.On("ValueExists", owner, key)} +} - return mock +func (_c *ValueStore_ValueExists_Call) Run(run func(owner []byte, key []byte)) *ValueStore_ValueExists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ValueStore_ValueExists_Call) Return(b bool, err error) *ValueStore_ValueExists_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ValueStore_ValueExists_Call) RunAndReturn(run func(owner []byte, key []byte) (bool, error)) *ValueStore_ValueExists_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/environment/programs.go b/fvm/environment/programs.go index 4fefd5be84a..46eeb821c22 100644 --- a/fvm/environment/programs.go +++ b/fvm/environment/programs.go @@ -93,14 +93,12 @@ func (programs *Programs) GetOrLoadProgram( load func() (*runtime.Program, error), ) (*runtime.Program, error) { span := programs.tracer.StartChildSpan(trace.FVMEnvGetOrLoadProgram) - defer func() { - if span.Tracer != nil { - span.SetAttributes( - attribute.String("location", location.ID()), - ) - } - span.End() - }() + if span.Tracer != nil { + span.SetAttributes( + attribute.String("location", location.ID()), + ) + } + defer span.End() err := programs.meter.MeterComputation( common.ComputationUsage{ diff --git a/fvm/environment/programs_test.go b/fvm/environment/programs_test.go index eef0f526a01..36516a4bb00 100644 --- a/fvm/environment/programs_test.go +++ b/fvm/environment/programs_test.go @@ -27,21 +27,17 @@ var ( addressC = flow.HexToAddress("0c") contractALocation = common.AddressLocation{ - Address: common.MustBytesToAddress(addressA.Bytes()), + Address: common.Address(addressA), Name: "A", } - contractA2Location = common.AddressLocation{ - Address: common.MustBytesToAddress(addressA.Bytes()), - Name: "A2", - } contractBLocation = common.AddressLocation{ - Address: common.MustBytesToAddress(addressB.Bytes()), + Address: common.Address(addressB), Name: "B", } contractCLocation = common.AddressLocation{ - Address: common.MustBytesToAddress(addressC.Bytes()), + Address: common.Address(addressC), Name: "C", } @@ -65,16 +61,6 @@ var ( } ` - contractA2Code = ` - access(all) contract A2 { - access(all) struct interface Foo{} - - access(all) fun hello(): String { - return "hello from A2" - } - } - ` - contractABreakingCode = ` access(all) contract A { access(all) struct interface Foo{ @@ -88,7 +74,7 @@ var ( ` contractBCode = ` - import 0xa + import A from 0xa access(all) contract B { access(all) struct Bar : A.Foo {} @@ -143,7 +129,7 @@ func getTestContract( error, ) { env := environment.NewScriptEnvironmentFromStorageSnapshot( - environment.DefaultEnvironmentParams(), + fvm.DefaultEnvironmentParams(flow.Mainnet.Chain()), snapshot) return env.GetAccountContractCode(location) } @@ -157,11 +143,13 @@ func Test_Programs(t *testing.T) { mainSnapshot := setupProgramsTest(t) context := fvm.NewContext( + flow.Mainnet.Chain(), fvm.WithContractDeploymentRestricted(false), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), fvm.WithCadenceLogging(true), - fvm.WithDerivedBlockData(derivedBlockData)) + fvm.WithDerivedBlockData(derivedBlockData), + ) var contractASnapshot *snapshot.ExecutionSnapshot var contractBSnapshot *snapshot.ExecutionSnapshot @@ -409,119 +397,6 @@ func Test_Programs(t *testing.T) { assertExecutionSnapshotsEqual(t, executionSnapshotB, executionSnapshotB2) }) - t.Run("deploying new contract A2 invalidates B because of * imports", func(t *testing.T) { - // deploy contract A2 - txBody, err := contractDeployTx("A2", contractA2Code, addressA) - require.NoError(t, err) - executionSnapshot, output, err := vm.Run( - context, - fvm.Transaction( - txBody, - derivedBlockData.NextTxIndexForTestingOnly()), - mainSnapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - mainSnapshot = mainSnapshot.Append(executionSnapshot) - - // a, b and c are invalid - entryB := derivedBlockData.GetProgramForTestingOnly(contractBLocation) - entryC := derivedBlockData.GetProgramForTestingOnly(contractCLocation) - entryA := derivedBlockData.GetProgramForTestingOnly(contractALocation) - - require.Nil(t, entryB) // B could have star imports to 0xa, so it's invalidated - require.Nil(t, entryC) // still invalid - require.Nil(t, entryA) // A could have star imports to 0xa, so it's invalidated - - cached := derivedBlockData.CachedPrograms() - require.Equal(t, 0, cached) - }) - - t.Run("contract B imports contract A and A2 because of * import", func(t *testing.T) { - - // programs should have no entries for A and B, as per previous test - - // run a TX using contract B - txBody, err := callTx("B", addressB) - require.NoError(t, err) - executionSnapshotB, output, err := vm.Run( - context, - fvm.Transaction( - txBody, - derivedBlockData.NextTxIndexForTestingOnly()), - mainSnapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - require.Contains(t, output.Logs, "\"hello from B but also hello from A\"") - - mainSnapshot = mainSnapshot.Append(executionSnapshotB) - - entry := derivedBlockData.GetProgramForTestingOnly(contractALocation) - require.NotNil(t, entry) - - // state should be essentially the same as one which we got in tx with contract A - require.Equal(t, contractASnapshot, entry.ExecutionSnapshot) - - entryB := derivedBlockData.GetProgramForTestingOnly(contractBLocation) - require.NotNil(t, entryB) - - // assert dependencies are correct - require.Equal(t, 3, entryB.Value.Dependencies.Count()) - require.NotNil(t, entryB.Value.Dependencies.ContainsLocation(contractALocation)) - require.NotNil(t, entryB.Value.Dependencies.ContainsLocation(contractBLocation)) - require.NotNil(t, entryB.Value.Dependencies.ContainsLocation(contractA2Location)) - - // program B should contain all the registers used by program A, as it depends on it - contractBSnapshot = entryB.ExecutionSnapshot - - require.Empty(t, contractASnapshot.WriteSet) - - for id := range contractASnapshot.ReadSet { - _, ok := contractBSnapshot.ReadSet[id] - require.True(t, ok) - } - - // rerun transaction - - // execute transaction again, this time make sure it doesn't load code - execB2Snapshot := snapshot.NewReadFuncStorageSnapshot( - func(id flow.RegisterID) (flow.RegisterValue, error) { - idA := flow.ContractRegisterID( - flow.BytesToAddress([]byte(id.Owner)), - "A") - idA2 := flow.ContractRegisterID( - flow.BytesToAddress([]byte(id.Owner)), - "A2") - idB := flow.ContractRegisterID( - flow.BytesToAddress([]byte(id.Owner)), - "B") - // this time we fail if a read of code occurs - require.NotEqual(t, id.Key, idA.Key) - require.NotEqual(t, id.Key, idA2.Key) - require.NotEqual(t, id.Key, idB.Key) - - return mainSnapshot.Get(id) - }) - - txBody, err = callTx("B", addressB) - require.NoError(t, err) - executionSnapshotB2, output, err := vm.Run( - context, - fvm.Transaction( - txBody, - derivedBlockData.NextTxIndexForTestingOnly()), - execB2Snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - require.Contains(t, output.Logs, "\"hello from B but also hello from A\"") - - mainSnapshot = mainSnapshot.Append(executionSnapshotB2) - - assertExecutionSnapshotsEqual(t, executionSnapshotB, executionSnapshotB2) - }) - t.Run("contract A runs from cache after program B has been loaded", func(t *testing.T) { // at this point programs cache should contain data for contract A @@ -573,17 +448,15 @@ func Test_Programs(t *testing.T) { mainSnapshot = mainSnapshot.Append(executionSnapshot) entryA := derivedBlockData.GetProgramForTestingOnly(contractALocation) - entryA2 := derivedBlockData.GetProgramForTestingOnly(contractA2Location) entryB := derivedBlockData.GetProgramForTestingOnly(contractBLocation) entryC := derivedBlockData.GetProgramForTestingOnly(contractCLocation) require.NotNil(t, entryA) - require.NotNil(t, entryA2) require.NotNil(t, entryB) require.Nil(t, entryC) cached := derivedBlockData.CachedPrograms() - require.Equal(t, 3, cached) + require.Equal(t, 2, cached) }) t.Run("importing C should chain-import B and A", func(t *testing.T) { @@ -619,13 +492,13 @@ func Test_Programs(t *testing.T) { require.NotNil(t, entryC) // assert dependencies are correct - require.Equal(t, 4, entryC.Value.Dependencies.Count()) + require.Equal(t, 3, entryC.Value.Dependencies.Count()) require.NotNil(t, entryC.Value.Dependencies.ContainsLocation(contractALocation)) require.NotNil(t, entryC.Value.Dependencies.ContainsLocation(contractBLocation)) require.NotNil(t, entryC.Value.Dependencies.ContainsLocation(contractCLocation)) cached := derivedBlockData.CachedPrograms() - require.Equal(t, 4, cached) + require.Equal(t, 3, cached) }) } @@ -644,14 +517,17 @@ func Test_ProgramsDoubleCounting(t *testing.T) { metrics := &metricsReporter{} context := fvm.NewContext( + flow.Mainnet.Chain(), fvm.WithContractDeploymentRestricted(false), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), fvm.WithCadenceLogging(true), fvm.WithDerivedBlockData(derivedBlockData), - fvm.WithMetricsReporter(metrics)) + fvm.WithMetricsReporter(metrics), + ) t.Run("deploy contracts and ensure cache is empty", func(t *testing.T) { + // deploy contract A txBody, err := contractDeployTx("A", contractACode, addressA) require.NoError(t, err) @@ -694,8 +570,8 @@ func Test_ProgramsDoubleCounting(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) - // deploy contract A2 last to clear any cache so far - txBody, err = contractDeployTx("A2", contractA2Code, addressA) + // update contract A last to clear any cache so far + txBody, err = updateContractTx("A", contractACode, addressA) require.NoError(t, err) executionSnapshot, output, err = vm.Run( context, @@ -709,12 +585,10 @@ func Test_ProgramsDoubleCounting(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) entryA := derivedBlockData.GetProgramForTestingOnly(contractALocation) - entryA2 := derivedBlockData.GetProgramForTestingOnly(contractA2Location) entryB := derivedBlockData.GetProgramForTestingOnly(contractBLocation) entryC := derivedBlockData.GetProgramForTestingOnly(contractCLocation) require.Nil(t, entryA) - require.Nil(t, entryA2) require.Nil(t, entryB) require.Nil(t, entryC) @@ -753,23 +627,21 @@ func Test_ProgramsDoubleCounting(t *testing.T) { t, uint64( 1+ // import A - 3+ // import B (import A, import A2) - 4, // import C (import B (3), import A (already imported in this scope)) + 2+ // import B (import A) + 3, // import C (import B (2), import A (already imported in this scope)) ), output.ComputationIntensities[environment.ComputationKindGetCode]) entryA := derivedBlockData.GetProgramForTestingOnly(contractALocation) - entryA2 := derivedBlockData.GetProgramForTestingOnly(contractA2Location) entryB := derivedBlockData.GetProgramForTestingOnly(contractBLocation) entryC := derivedBlockData.GetProgramForTestingOnly(contractCLocation) require.NotNil(t, entryA) - require.NotNil(t, entryA2) // loaded due to "*" import require.NotNil(t, entryB) require.NotNil(t, entryC) cached := derivedBlockData.CachedPrograms() - require.Equal(t, 4, cached) + require.Equal(t, 3, cached) return snapshotTree.Append(executionSnapshot) } @@ -780,7 +652,6 @@ func Test_ProgramsDoubleCounting(t *testing.T) { // miss A because loading transaction // hit A because loading B because loading transaction - // miss A2 because loading B because loading transaction // miss B because loading transaction // hit B because loading C because loading transaction // hit A because loading C because loading transaction @@ -789,9 +660,8 @@ func Test_ProgramsDoubleCounting(t *testing.T) { // hit C because interpreting transaction // hit B because interpreting C because interpreting transaction // hit A because interpreting B because interpreting C because interpreting transaction - // hit A2 because interpreting B because interpreting C because interpreting transaction - require.Equal(t, ifCompile(23, 7), metrics.CacheHits) - require.Equal(t, 4, metrics.CacheMisses) + require.Equal(t, ifCompile(25, 6), metrics.CacheHits) + require.Equal(t, ifCompile(3, 3), metrics.CacheMisses) }) t.Run("Call C Again", func(t *testing.T) { @@ -805,8 +675,7 @@ func Test_ProgramsDoubleCounting(t *testing.T) { // hit C because interpreting transaction // hit B because interpreting C because interpreting transaction // hit A because interpreting B because interpreting C because interpreting transaction - // hit A2 because interpreting B because interpreting C because interpreting transaction - require.Equal(t, ifCompile(15, 7), metrics.CacheHits) + require.Equal(t, ifCompile(18, 6), metrics.CacheHits) require.Equal(t, 0, metrics.CacheMisses) }) @@ -834,7 +703,7 @@ func Test_ProgramsDoubleCounting(t *testing.T) { require.Nil(t, entryC) cached := derivedBlockData.CachedPrograms() - require.Equal(t, 1, cached) + require.Equal(t, 0, cached) }) callCAfterItsBroken := func(snapshotTree snapshot.SnapshotTree) snapshot.SnapshotTree { @@ -864,17 +733,15 @@ func Test_ProgramsDoubleCounting(t *testing.T) { require.Error(t, output.Err) entryA := derivedBlockData.GetProgramForTestingOnly(contractALocation) - entryA2 := derivedBlockData.GetProgramForTestingOnly(contractA2Location) entryB := derivedBlockData.GetProgramForTestingOnly(contractBLocation) entryC := derivedBlockData.GetProgramForTestingOnly(contractCLocation) require.NotNil(t, entryA) - require.NotNil(t, entryA2) // loaded due to "*" import in B - require.Nil(t, entryB) // failed to load - require.Nil(t, entryC) // failed to load + require.Nil(t, entryB) // failed to load + require.Nil(t, entryC) // failed to load cached := derivedBlockData.CachedPrograms() - require.Equal(t, 2, cached) + require.Equal(t, 1, cached) return snapshotTree.Append(executionSnapshot) } @@ -883,8 +750,8 @@ func Test_ProgramsDoubleCounting(t *testing.T) { metrics.Reset() snapshotTree = callCAfterItsBroken(snapshotTree) - // miss A, hit A, hit A2, hit A, hit A2, hit A - require.Equal(t, 5, metrics.CacheHits) + // miss A, hit A, hit A, hit A + require.Equal(t, 3, metrics.CacheHits) require.Equal(t, 1, metrics.CacheMisses) }) diff --git a/fvm/environment/runtime.go b/fvm/environment/runtime.go index 7e68098e918..5261f74b7a4 100644 --- a/fvm/environment/runtime.go +++ b/fvm/environment/runtime.go @@ -1,60 +1,72 @@ package environment -import ( - cadenceRuntime "github.com/onflow/cadence/runtime" - - "github.com/onflow/flow-go/fvm/runtime" -) - -type RuntimeParams struct { - runtime.ReusableCadenceRuntimePool - ConfigureCadenceRuntime func( - reusableCadenceRuntime *runtime.ReusableCadenceRuntime, - env Environment, +// ReusableCadenceRuntimePool is the pool that holds ReusableCadenceRuntime-s so that they +// can be reused between procedures +type ReusableCadenceRuntimePool interface { + Borrow( + fvmEnv Environment, + runtimeType CadenceRuntimeType, + ) ReusableCadenceRuntime + Return( + reusable ReusableCadenceRuntime, ) } -func DefaultRuntimeParams() RuntimeParams { - return RuntimeParams{ - ReusableCadenceRuntimePool: runtime.NewReusableCadenceRuntimePool( - 0, - cadenceRuntime.Config{}, - ), - } +type RuntimeParams struct { + ReusableCadenceRuntimePool } -// Runtime expose the cadence runtime to the rest of the envionment package. -type Runtime struct { +type cadenceRuntimeProvider struct { RuntimeParams - env Environment + env Environment + runtimeType CadenceRuntimeType +} + +// CadenceRuntimeProvider exposes the cadence runtime to the rest of the environment package. +type CadenceRuntimeProvider interface { + // SetEnvironment sets the fvm Environment that will be injected into a ReusableCadenceRuntime + // when it is borrowed + SetEnvironment(env Environment) + // BorrowCadenceRuntime borrows a runtime from the ReusableCadenceRuntimePool moving it so its only used in + // this procedure until returned + BorrowCadenceRuntime() ReusableCadenceRuntime + // ReturnCadenceRuntime returns a runtime from the ReusableCadenceRuntimePool so that it can be reused + // for a different procedure later. + ReturnCadenceRuntime(reusable ReusableCadenceRuntime) } -func NewRuntime(params RuntimeParams) *Runtime { - return &Runtime{ +// CadenceRuntimeType is used to specify if a runtime will be used for scripts or transactions +type CadenceRuntimeType int + +const ( + // CadenceScriptRuntime is a marker to indicate to use the cadence interpreter runtime set up for scripts + CadenceScriptRuntime CadenceRuntimeType = iota + // CadenceTransactionRuntime is a marker to indicate to use the cadence interpreter runtime set up for transactions + CadenceTransactionRuntime + // CadenceScriptVMRuntime is a marker to indicate to use the cadence VM runtime set up for scripts + CadenceScriptVMRuntime + // CadenceTransactionVMRuntime is a marker to indicate to use the cadence VM runtime set up for transactions + CadenceTransactionVMRuntime +) + +func NewRuntime(params RuntimeParams, runtimeType CadenceRuntimeType) *cadenceRuntimeProvider { + return &cadenceRuntimeProvider{ RuntimeParams: params, + runtimeType: runtimeType, } } -func (runtime *Runtime) SetEnvironment(env Environment) { +func (runtime *cadenceRuntimeProvider) SetEnvironment(env Environment) { runtime.env = env } -func (runtime *Runtime) BorrowCadenceRuntime() *runtime.ReusableCadenceRuntime { - env := runtime.env - - reusableCadenceRuntime := runtime.ReusableCadenceRuntimePool.Borrow(env) - - configure := runtime.ConfigureCadenceRuntime - if configure != nil { - configure(reusableCadenceRuntime, env) - } - - return reusableCadenceRuntime +func (runtime *cadenceRuntimeProvider) BorrowCadenceRuntime() ReusableCadenceRuntime { + return runtime.ReusableCadenceRuntimePool.Borrow(runtime.env, runtime.runtimeType) } -func (runtime *Runtime) ReturnCadenceRuntime( - reusable *runtime.ReusableCadenceRuntime, +func (runtime *cadenceRuntimeProvider) ReturnCadenceRuntime( + reusable ReusableCadenceRuntime, ) { runtime.ReusableCadenceRuntimePool.Return(reusable) } diff --git a/fvm/environment/system_contracts.go b/fvm/environment/system_contracts.go index c1a2f6bc571..5d8ac52eba6 100644 --- a/fvm/environment/system_contracts.go +++ b/fvm/environment/system_contracts.go @@ -15,23 +15,21 @@ import ( // SystemContracts provides methods for invoking system contract functions as // service account. type SystemContracts struct { - chain flow.Chain - useVM bool + chain flow.Chain + tracer tracing.TracerSpan logger *ProgramLogger - runtime *Runtime + runtime CadenceRuntimeProvider } func NewSystemContracts( chain flow.Chain, - useVM bool, tracer tracing.TracerSpan, logger *ProgramLogger, - runtime *Runtime, + runtime CadenceRuntimeProvider, ) *SystemContracts { return &SystemContracts{ chain: chain, - useVM: useVM, tracer: tracer, logger: logger, runtime: runtime, @@ -51,10 +49,12 @@ func (sys *SystemContracts) Invoke( } span := sys.tracer.StartChildSpan(trace.FVMInvokeContractFunction) - span.SetAttributes( - attribute.String( - "transaction.ContractFunctionCall", - contractLocation.String()+"."+spec.FunctionName)) + if span.Tracer != nil { + span.SetAttributes( + attribute.String( + "transaction.ContractFunctionCall", + contractLocation.String()+"."+spec.FunctionName)) + } defer span.End() runtime := sys.runtime.BorrowCadenceRuntime() @@ -65,7 +65,6 @@ func (sys *SystemContracts) Invoke( spec.FunctionName, arguments, spec.ArgumentTypes, - sys.useVM, ) if err != nil { log := sys.logger.Logger() @@ -121,7 +120,7 @@ func (sys *SystemContracts) CheckPayerBalanceAndGetMaxTxFees( return sys.Invoke( verifyPayersBalanceForTransactionExecutionSpec, []cadence.Value{ - cadence.Address(payer), + cadence.BytesToAddress(payer.Bytes()), cadence.UFix64(inclusionEffort), cadence.UFix64(maxExecutionEffort), }, @@ -158,59 +157,13 @@ func (sys *SystemContracts) DeductTransactionFees( return sys.Invoke( deductTransactionFeeSpec, []cadence.Value{ - cadence.Address(payer), + cadence.BytesToAddress(payer.Bytes()), cadence.UFix64(inclusionEffort), cadence.UFix64(executionEffort), }, ) } -// uses `FlowServiceAccount.setupNewAccount` from https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowServiceAccount.cdc -var setupNewAccountSpec = ContractFunctionSpec{ - AddressFromChain: ServiceAddress, - LocationName: systemcontracts.ContractNameServiceAccount, - FunctionName: systemcontracts.ContractServiceAccountFunction_setupNewAccount, - ArgumentTypes: []sema.Type{ - sema.NewReferenceType( - nil, - sema.NewEntitlementSetAccess( - []*sema.EntitlementType{ - sema.SaveValueType, - sema.BorrowValueType, - sema.CapabilitiesType, - }, - sema.Conjunction, - ), - sema.AccountType, - ), - sema.NewReferenceType( - nil, - sema.NewEntitlementSetAccess( - []*sema.EntitlementType{ - sema.BorrowValueType, - }, - sema.Conjunction, - ), - sema.AccountType, - ), - }, -} - -// SetupNewAccount executes the new account setup contract on the service -// account. -func (sys *SystemContracts) SetupNewAccount( - flowAddress flow.Address, - payer flow.Address, -) (cadence.Value, error) { - return sys.Invoke( - setupNewAccountSpec, - []cadence.Value{ - cadence.Address(flowAddress), - cadence.Address(payer), - }, - ) -} - var accountAvailableBalanceSpec = ContractFunctionSpec{ AddressFromChain: ServiceAddress, LocationName: systemcontracts.ContractNameStorageFees, @@ -228,12 +181,12 @@ func (sys *SystemContracts) AccountAvailableBalance( return sys.Invoke( accountAvailableBalanceSpec, []cadence.Value{ - cadence.Address(address), + cadence.BytesToAddress(address.Bytes()), }, ) } -var accountBalanceSpec = ContractFunctionSpec{ +var accountBalanceInvocationSpec = ContractFunctionSpec{ AddressFromChain: ServiceAddress, LocationName: systemcontracts.ContractNameServiceAccount, FunctionName: systemcontracts.ContractServiceAccountFunction_defaultTokenBalance, @@ -252,9 +205,9 @@ func (sys *SystemContracts) AccountBalance( address flow.Address, ) (cadence.Value, error) { return sys.Invoke( - accountBalanceSpec, + accountBalanceInvocationSpec, []cadence.Value{ - cadence.Address(address), + cadence.BytesToAddress(address.Bytes()), }, ) } @@ -276,7 +229,7 @@ func (sys *SystemContracts) AccountStorageCapacity( return sys.Invoke( accountStorageCapacitySpec, []cadence.Value{ - cadence.Address(address), + cadence.BytesToAddress(address.Bytes()), }, ) } @@ -289,7 +242,7 @@ func (sys *SystemContracts) AccountsStorageCapacity( ) (cadence.Value, error) { arrayValues := make([]cadence.Value, len(addresses)) for i, address := range addresses { - arrayValues[i] = cadence.Address(address) + arrayValues[i] = cadence.BytesToAddress(address.Bytes()) } return sys.Invoke( @@ -298,10 +251,9 @@ func (sys *SystemContracts) AccountsStorageCapacity( LocationName: systemcontracts.ContractNameStorageFees, FunctionName: systemcontracts.ContractStorageFeesFunction_getAccountsCapacityForTransactionStorageCheck, ArgumentTypes: []sema.Type{ - sema.NewConstantSizedType( + sema.NewVariableSizedType( nil, sema.TheAddressType, - int64(len(arrayValues)), ), sema.TheAddressType, sema.UFix64Type, @@ -309,7 +261,7 @@ func (sys *SystemContracts) AccountsStorageCapacity( }, []cadence.Value{ cadence.NewArray(arrayValues), - cadence.Address(payer), + cadence.BytesToAddress(payer.Bytes()), cadence.UFix64(maxTxFees), }, ) diff --git a/fvm/environment/system_contracts_test.go b/fvm/environment/system_contracts_test.go index b50c6cca4aa..1162a5f71e3 100644 --- a/fvm/environment/system_contracts_test.go +++ b/fvm/environment/system_contracts_test.go @@ -9,7 +9,6 @@ import ( "github.com/onflow/cadence/sema" "github.com/stretchr/testify/require" - "github.com/onflow/flow-go/fvm/cadence_vm" "github.com/onflow/flow-go/fvm/environment" reusableRuntime "github.com/onflow/flow-go/fvm/runtime" "github.com/onflow/flow-go/fvm/runtime/testutil" @@ -60,6 +59,7 @@ func TestSystemContractsInvoke(t *testing.T) { tracer := tracing.NewTracerSpan() runtimePool := reusableRuntime.NewCustomReusableCadenceRuntimePool( 0, + chainID.Chain(), runtime.Config{}, func(_ runtime.Config) runtime.Runtime { return &testutil.TestRuntime{ @@ -71,10 +71,10 @@ func TestSystemContractsInvoke(t *testing.T) { environment.RuntimeParams{ ReusableCadenceRuntimePool: runtimePool, }, + environment.CadenceTransactionRuntime, ) invoker := environment.NewSystemContracts( chainID.Chain(), - cadence_vm.DefaultEnabled, tracer, environment.NewProgramLogger( tracer, diff --git a/fvm/environment/transaction_info.go b/fvm/environment/transaction_info.go index 6abfb367962..062efe542e3 100644 --- a/fvm/environment/transaction_info.go +++ b/fvm/environment/transaction_info.go @@ -17,9 +17,14 @@ type TransactionInfoParams struct { TransactionFeesEnabled bool LimitAccountStorage bool + // RandomSourceHistoryCallAllowed is true if the transaction is allowed to call the `entropy` // cadence function to get the entropy of that block. RandomSourceHistoryCallAllowed bool + + // EVMTestOperationsAllowed is true if the transaction is allowed to call EVM test operations, + // which should only be used for testing and should not be enabled in production. + EVMTestOperationsAllowed bool } func DefaultTransactionInfoParams() TransactionInfoParams { @@ -29,6 +34,7 @@ func DefaultTransactionInfoParams() TransactionInfoParams { TransactionFeesEnabled: false, LimitAccountStorage: false, RandomSourceHistoryCallAllowed: false, + EVMTestOperationsAllowed: false, } } @@ -122,7 +128,7 @@ func NewTransactionInfo( for _, auth := range params.TxBody.Authorizers { runtimeAddresses = append( runtimeAddresses, - common.MustBytesToAddress(auth.Bytes())) + common.Address(auth)) if auth == serviceAccount { isServiceAccountAuthorizer = true } diff --git a/fvm/environment/value_store.go b/fvm/environment/value_store.go index 596777e8455..9b468317e9e 100644 --- a/fvm/environment/value_store.go +++ b/fvm/environment/value_store.go @@ -127,15 +127,13 @@ func (store *valueStore) GetValue( error, ) { span := store.tracer.StartChildSpan(trace.FVMEnvGetValue) - defer func() { - if span.Tracer != nil { - span.SetAttributes( - attribute.String("owner", hex.EncodeToString(owner)), - attribute.String("key", hex.EncodeToString(keyBytes)), - ) - } - span.End() - }() + if span.Tracer != nil { + span.SetAttributes( + attribute.String("owner", hex.EncodeToString(owner)), + attribute.String("key", hex.EncodeToString(keyBytes)), + ) + } + defer span.End() id := flow.CadenceRegisterID(owner, keyBytes) if id.IsInternalState() { @@ -165,16 +163,14 @@ func (store *valueStore) SetValue( value []byte, ) error { span := store.tracer.StartChildSpan(trace.FVMEnvSetValue) - defer func() { - if span.Tracer != nil { - span.SetAttributes( - attribute.String("owner", hex.EncodeToString(owner)), - attribute.String("key", hex.EncodeToString(keyBytes)), - attribute.String("value", hex.EncodeToString(value)), - ) - } - span.End() - }() + if span.Tracer != nil { + span.SetAttributes( + attribute.String("owner", hex.EncodeToString(owner)), + attribute.String("key", hex.EncodeToString(keyBytes)), + attribute.String("value", hex.EncodeToString(value)), + ) + } + defer span.End() id := flow.CadenceRegisterID(owner, keyBytes) if id.IsInternalState() { diff --git a/fvm/errors/base.go b/fvm/errors/base.go index 8bb2265eac6..3eb91771f21 100644 --- a/fvm/errors/base.go +++ b/fvm/errors/base.go @@ -12,12 +12,12 @@ import ( func NewInvalidAddressErrorf( address flow.Address, msg string, - args ...interface{}, + args ...any, ) CodedError { return NewCodedError( ErrCodeInvalidAddressError, "invalid address (%s): "+msg, - append([]interface{}{address.String()}, args...)...) + append([]any{address.String()}, args...)...) } // NewInvalidArgumentErrorf constructs a new CodedError which indicates that a @@ -26,7 +26,7 @@ func NewInvalidAddressErrorf( // - number of arguments doesn't match the template // // TODO add more cases like argument size -func NewInvalidArgumentErrorf(msg string, args ...interface{}) CodedError { +func NewInvalidArgumentErrorf(msg string, args ...any) CodedError { return NewCodedError( ErrCodeInvalidArgumentError, "transaction arguments are invalid: ("+msg+")", @@ -42,7 +42,7 @@ func IsInvalidArgumentError(err error) bool { func NewInvalidLocationErrorf( location runtime.Location, msg string, - args ...interface{}, + args ...any, ) CodedError { locationStr := "" if location != nil { @@ -52,7 +52,7 @@ func NewInvalidLocationErrorf( return NewCodedError( ErrCodeInvalidLocationError, "location (%s) is not a valid location: "+msg, - append([]interface{}{locationStr}, args...)...) + append([]any{locationStr}, args...)...) } // NewValueErrorf constructs a new CodedError which indicates a value is not @@ -60,12 +60,12 @@ func NewInvalidLocationErrorf( func NewValueErrorf( valueStr string, msg string, - args ...interface{}, + args ...any, ) CodedError { return NewCodedError( ErrCodeValueError, "invalid value (%s): "+msg, - append([]interface{}{valueStr}, args...)...) + append([]any{valueStr}, args...)...) } func IsValueError(err error) bool { @@ -78,12 +78,12 @@ func IsValueError(err error) bool { func NewOperationAuthorizationErrorf( operation string, msg string, - args ...interface{}, + args ...any, ) CodedError { return NewCodedError( ErrCodeOperationAuthorizationError, "(%s) is not authorized: "+msg, - append([]interface{}{operation}, args...)...) + append([]any{operation}, args...)...) } // NewAccountAuthorizationErrorf constructs a new CodedError which indicates @@ -95,10 +95,10 @@ func NewOperationAuthorizationErrorf( func NewAccountAuthorizationErrorf( address flow.Address, msg string, - args ...interface{}, + args ...any, ) CodedError { return NewCodedError( ErrCodeAccountAuthorizationError, "authorization failed for account %s: "+msg, - append([]interface{}{address}, args...)...) + append([]any{address}, args...)...) } diff --git a/fvm/errors/codes.go b/fvm/errors/codes.go index e73ee94dc2b..c5af9b56e34 100644 --- a/fvm/errors/codes.go +++ b/fvm/errors/codes.go @@ -70,7 +70,8 @@ const ( ErrCodeAccountAuthorizationError ErrorCode = 1055 ErrCodeOperationAuthorizationError ErrorCode = 1056 ErrCodeOperationNotSupportedError ErrorCode = 1057 - ErrCodeBlockHeightOutOfRangeError ErrorCode = 1058 + // Deprecated: No longer used. + ErrCodeBlockHeightOutOfRangeError ErrorCode = 1058 // execution errors 1100 - 1200 // Deprecated: No longer used. diff --git a/fvm/errors/errors.go b/fvm/errors/errors.go index ea8f3825864..e2109899648 100644 --- a/fvm/errors/errors.go +++ b/fvm/errors/errors.go @@ -42,7 +42,7 @@ func Is(err error, target error) bool { // As finds the first error in err's chain that matches target, // and if so, sets target to that error value and returns true. Otherwise, it returns false. // The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap. -func As(err error, target interface{}) bool { +func As(err error, target any) bool { return stdErrors.As(err, target) } @@ -249,7 +249,7 @@ func WrapCodedError( code ErrorCode, err error, prefixMsgFormat string, - formatArguments ...interface{}, + formatArguments ...any, ) codedError { if prefixMsgFormat != "" { msg := fmt.Sprintf(prefixMsgFormat, formatArguments...) @@ -261,7 +261,7 @@ func WrapCodedError( func NewCodedError( code ErrorCode, format string, - formatArguments ...interface{}, + formatArguments ...any, ) codedError { return newError(code, fmt.Errorf(format, formatArguments...)) } @@ -299,7 +299,7 @@ func WrapCodedFailure( code FailureCode, err error, prefixMsgFormat string, - formatArguments ...interface{}, + formatArguments ...any, ) codedFailure { if prefixMsgFormat != "" { msg := fmt.Sprintf(prefixMsgFormat, formatArguments...) @@ -311,7 +311,7 @@ func WrapCodedFailure( func NewCodedFailure( code FailureCode, format string, - formatArguments ...interface{}, + formatArguments ...any, ) codedFailure { return newFailure(code, fmt.Errorf(format, formatArguments...)) } @@ -320,7 +320,7 @@ func NewCodedFailuref( code FailureCode, msgPrefix string, format string, - formatArguments ...interface{}, + formatArguments ...any, ) codedFailure { err := fmt.Errorf(format, formatArguments...) if msgPrefix != "" { diff --git a/fvm/errors/execution.go b/fvm/errors/execution.go index ec2f1c3d3fd..eeb752d9692 100644 --- a/fvm/errors/execution.go +++ b/fvm/errors/execution.go @@ -248,17 +248,6 @@ func IsOperationNotSupportedError(err error) bool { return HasErrorCode(err, ErrCodeOperationNotSupportedError) } -func NewBlockHeightOutOfRangeError(height uint64) CodedError { - return NewCodedError( - ErrCodeBlockHeightOutOfRangeError, - "block height (%v) is out of queriable range", - height) -} - -func IsBlockHeightOutOfRangeError(err error) bool { - return HasErrorCode(err, ErrCodeBlockHeightOutOfRangeError) -} - // NewScriptExecutionCancelledError construct a new CodedError which indicates // that Cadence Script execution has been cancelled (e.g. request connection // has been droped) diff --git a/fvm/errors/failures.go b/fvm/errors/failures.go index df9b2c1104b..6ba681c261a 100644 --- a/fvm/errors/failures.go +++ b/fvm/errors/failures.go @@ -15,7 +15,7 @@ func NewUnknownFailure(err error) CodedFailure { func NewEncodingFailuref( err error, msg string, - args ...interface{}, + args ...any, ) CodedFailure { return WrapCodedFailure( FailureCodeEncodingFailure, diff --git a/fvm/evm/types/backend.go b/fvm/evm/backends/backend.go similarity index 89% rename from fvm/evm/types/backend.go rename to fvm/evm/backends/backend.go index 985a8bc29e1..cc538ea3d6e 100644 --- a/fvm/evm/types/backend.go +++ b/fvm/evm/backends/backend.go @@ -1,4 +1,4 @@ -package types +package backends import ( "github.com/onflow/flow-go/fvm/environment" @@ -23,4 +23,6 @@ type Backend interface { environment.Tracer environment.EVMMetricsReporter environment.LoggerProvider + environment.EVMBlockStore + EVMTestOperationsAllowed() bool } diff --git a/fvm/evm/backends/wrappedEnv.go b/fvm/evm/backends/wrappedEnv.go index b7309f29cdb..ff4a491a931 100644 --- a/fvm/evm/backends/wrappedEnv.go +++ b/fvm/evm/backends/wrappedEnv.go @@ -1,6 +1,7 @@ package backends import ( + gocommon "github.com/ethereum/go-ethereum/common" "github.com/onflow/atree" "github.com/onflow/cadence" "github.com/onflow/cadence/common" @@ -24,11 +25,11 @@ type WrappedEnvironment struct { } // NewWrappedEnvironment constructs a new wrapped environment -func NewWrappedEnvironment(env environment.Environment) types.Backend { +func NewWrappedEnvironment(env environment.Environment) *WrappedEnvironment { return &WrappedEnvironment{env} } -var _ types.Backend = &WrappedEnvironment{} +var _ Backend = &WrappedEnvironment{} // GetValue gets a value from the storage for the given owner and key pair, // if value not found empty slice and no error is returned. @@ -209,6 +210,10 @@ func (we *WrappedEnvironment) Logger() zerolog.Logger { return we.env.Logger() } +func (we *WrappedEnvironment) EVMTestOperationsAllowed() bool { + return we.env.EVMTestOperationsAllowed() +} + func handleEnvironmentError(err error) error { if err == nil { return nil @@ -221,3 +226,32 @@ func handleEnvironmentError(err error) error { return types.NewBackendError(err) } + +// BlockHash implements [Backend]. +func (we *WrappedEnvironment) BlockHash(height uint64) (gocommon.Hash, error) { + hash, err := we.env.BlockHash(height) + return hash, handleEnvironmentError(err) +} + +// BlockProposal implements [Backend]. +func (we *WrappedEnvironment) BlockProposal() (*types.BlockProposal, error) { + bp, err := we.env.BlockProposal() + return bp, handleEnvironmentError(err) +} + +// CommitBlockProposal implements [Backend]. +func (we *WrappedEnvironment) CommitBlockProposal(bp *types.BlockProposal) error { + err := we.env.CommitBlockProposal(bp) + return handleEnvironmentError(err) +} + +// LatestBlock implements [Backend]. +func (we *WrappedEnvironment) LatestBlock() (*types.Block, error) { + block, err := we.env.LatestBlock() + return block, handleEnvironmentError(err) +} + +// StageBlockProposal implements [Backend]. +func (we *WrappedEnvironment) StageBlockProposal(bp *types.BlockProposal) { + we.env.StageBlockProposal(bp) +} diff --git a/fvm/evm/emulator/emulator.go b/fvm/evm/emulator/emulator.go index 8404e9bf73b..2a7f4409d2e 100644 --- a/fvm/evm/emulator/emulator.go +++ b/fvm/evm/emulator/emulator.go @@ -58,7 +58,7 @@ func newConfig(ctx types.BlockContext) *Config { } // NewReadOnlyBlockView constructs a new read-only block view -func (em *Emulator) NewReadOnlyBlockView(ctx types.BlockContext) (types.ReadOnlyBlockView, error) { +func (em *Emulator) NewReadOnlyBlockView() (types.ReadOnlyBlockView, error) { execState, err := state.NewStateDB(em.ledger, em.rootAddr) return &ReadOnlyBlockView{ state: execState, @@ -189,7 +189,7 @@ func (bl *BlockView) RunTransaction( if err != nil { // this is not a fatal error (e.g. due to bad signature) // not a valid transaction - return types.NewInvalidResult(tx, err), nil + return types.NewInvalidResult(tx.Type(), tx.Hash(), err), nil } // call tracer @@ -244,7 +244,7 @@ func (bl *BlockView) BatchRunTransactions(txs []*gethTypes.Transaction) ([]*type GetSigner(bl.config), proc.config.BlockContext.BaseFee) if err != nil { - batchResults[i] = types.NewInvalidResult(tx, err) + batchResults[i] = types.NewInvalidResult(tx.Type(), tx.Hash(), err) continue } @@ -381,12 +381,14 @@ func (proc *procedure) commit(finalize bool) (hash.Hash, error) { func (proc *procedure) mintTo( call *types.DirectCall, ) (*types.Result, error) { - // convert and check value - isValid, value := convertAndCheckValue(call.Value) + // check and convert value + value, isValid := checkAndConvertValue(call.Value) if !isValid { return types.NewInvalidResult( - call.Transaction(), - types.ErrInvalidBalance), nil + call.Type, + call.Hash(), + types.ErrInvalidBalance, + ), nil } // create bridge account if not exist @@ -425,19 +427,23 @@ func (proc *procedure) mintTo( func (proc *procedure) withdrawFrom( call *types.DirectCall, ) (*types.Result, error) { - // convert and check value - isValid, value := convertAndCheckValue(call.Value) + // check and convert value + value, isValid := checkAndConvertValue(call.Value) if !isValid { return types.NewInvalidResult( - call.Transaction(), - types.ErrInvalidBalance), nil + call.Type, + call.Hash(), + types.ErrInvalidBalance, + ), nil } // check balance is not prone to rounding error - if types.BalanceConversionToUFix64ProneToRoundingError(call.Value) { + if !types.AttoFlowBalanceIsValidForFlowVault(call.Value) { return types.NewInvalidResult( - call.Transaction(), - types.ErrWithdrawBalanceRounding), nil + call.Type, + call.Hash(), + types.ErrWithdrawBalanceRounding, + ), nil } // create bridge account if not exist @@ -479,12 +485,14 @@ func (proc *procedure) withdrawFrom( func (proc *procedure) deployAt( call *types.DirectCall, ) (*types.Result, error) { - // convert and check value - isValid, castedValue := convertAndCheckValue(call.Value) + // check and convert value + castedValue, isValid := checkAndConvertValue(call.Value) if !isValid { return types.NewInvalidResult( - call.Transaction(), - types.ErrInvalidBalance), nil + call.Type, + call.Hash(), + types.ErrInvalidBalance, + ), nil } txHash := call.Hash() @@ -729,15 +737,15 @@ func (proc *procedure) run( return &res, nil } -func convertAndCheckValue(input *big.Int) (isValid bool, converted *uint256.Int) { +func checkAndConvertValue(input *big.Int) (converted *uint256.Int, isValid bool) { // check for negative input if input.Sign() < 0 { - return false, nil + return nil, false } // convert value into uint256 value, overflow := uint256.FromBig(input) if overflow { - return true, nil + return nil, false } - return true, value + return value, true } diff --git a/fvm/evm/emulator/emulator_test.go b/fvm/evm/emulator/emulator_test.go index ce919fad03d..78f3d73c65e 100644 --- a/fvm/evm/emulator/emulator_test.go +++ b/fvm/evm/emulator/emulator_test.go @@ -38,7 +38,7 @@ func RunWithNewBlockView(t testing.TB, em *emulator.Emulator, f func(blk types.B } func RunWithNewReadOnlyBlockView(t testing.TB, em *emulator.Emulator, f func(blk types.ReadOnlyBlockView)) { - blk, err := em.NewReadOnlyBlockView(defaultCtx) + blk, err := em.NewReadOnlyBlockView() require.NoError(t, err) f(blk) } @@ -50,7 +50,7 @@ func requireSuccessfulExecution(t testing.TB, err error, res *types.Result) { } func TestNativeTokenBridging(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { originalBalance := types.MakeBigIntInFlow(3) testAccount := types.NewAddressFromString("test") @@ -152,10 +152,73 @@ func TestNativeTokenBridging(t *testing.T) { t.Run("tokens withdraw that results in rounding error", func(t *testing.T) { RunWithNewEmulator(t, backend, rootAddr, func(env *emulator.Emulator) { RunWithNewBlockView(t, env, func(blk types.BlockView) { - call := types.NewWithdrawCall(bridgeAccount, testAccount, big.NewInt(1000), testAccountNonce) + // Happy path, withdraw amount fits in Flow vault + call := types.NewWithdrawCall(bridgeAccount, testAccount, types.OneFlow(), testAccountNonce) + res, err := blk.DirectCall(call) + requireSuccessfulExecution(t, err, res) + require.Equal(t, defaultCtx.DirectCallBaseGasUsage, res.GasConsumed) + require.Equal(t, call.Hash(), res.TxHash) + testAccountNonce += 1 + }) + }) + RunWithNewEmulator(t, backend, rootAddr, func(env *emulator.Emulator) { + RunWithNewBlockView(t, env, func(blk types.BlockView) { + // Unhappy path, withdraw amount is 1e9, less than the minimum + // of 1e10. + call := types.NewWithdrawCall(bridgeAccount, testAccount, big.NewInt(1000000000), testAccountNonce) + res, err := blk.DirectCall(call) + require.NoError(t, err) + require.ErrorContains( + t, + res.ValidationError, + types.ErrWithdrawBalanceRounding.Error(), + ) + testAccountNonce += 1 + }) + }) + RunWithNewEmulator(t, backend, rootAddr, func(env *emulator.Emulator) { + RunWithNewBlockView(t, env, func(blk types.BlockView) { + // Happy path, withdraw amount is 1e10, equal to the minimum + // of 1e10. + call := types.NewWithdrawCall(bridgeAccount, testAccount, big.NewInt(10000000000), testAccountNonce) + res, err := blk.DirectCall(call) + requireSuccessfulExecution(t, err, res) + require.Equal(t, defaultCtx.DirectCallBaseGasUsage, res.GasConsumed) + require.Equal(t, call.Hash(), res.TxHash) + testAccountNonce += 1 + }) + }) + RunWithNewEmulator(t, backend, rootAddr, func(env *emulator.Emulator) { + RunWithNewBlockView(t, env, func(blk types.BlockView) { + // Test withdraw amounts that overflow the UInt256 range + amount := big.NewInt(1) + amount.Lsh(amount, 256) + + call := types.NewWithdrawCall(bridgeAccount, testAccount, amount, testAccountNonce) res, err := blk.DirectCall(call) require.NoError(t, err) - require.Equal(t, res.ValidationError, types.ErrWithdrawBalanceRounding) + require.ErrorContains( + t, + res.ValidationError, + "invalid amount for transfer or balance change", + ) + testAccountNonce += 1 + }) + }) + RunWithNewEmulator(t, backend, rootAddr, func(env *emulator.Emulator) { + RunWithNewBlockView(t, env, func(blk types.BlockView) { + // Test withdraw amounts within the max range of UInt256 + amount := big.NewInt(1) + amount.Lsh(amount, 255) + + call := types.NewWithdrawCall(bridgeAccount, testAccount, amount, testAccountNonce) + res, err := blk.DirectCall(call) + require.NoError(t, err) + require.ErrorContains( + t, + res.ValidationError, + "insufficient funds for gas * price + value", + ) testAccountNonce += 1 }) }) @@ -182,7 +245,7 @@ func TestNativeTokenBridging(t *testing.T) { func TestContractInteraction(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testContract := testutils.GetStorageTestContract(t) @@ -572,7 +635,7 @@ func TestContractInteraction(t *testing.T) { } func TestDeployAtFunctionality(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testContract := testutils.GetStorageTestContract(t) testAccount := types.NewAddressFromString("test") @@ -661,7 +724,7 @@ func TestDeployAtFunctionality(t *testing.T) { // EIP 6780 https://eips.ethereum.org/EIPS/eip-6780 in case where the selfdestruct // is not called in the same transaction as deployment. func TestSelfdestruct(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(testAccount *testutils.EOATestAccount) { @@ -745,7 +808,7 @@ func TestSelfdestruct(t *testing.T) { // test factory patterns func TestFactoryPatterns(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { var factoryAddress types.Address @@ -1004,7 +1067,7 @@ func TestFactoryPatterns(t *testing.T) { } func TestTransfers(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testAccount1 := types.NewAddressFromString("test1") @@ -1044,7 +1107,7 @@ func TestTransfers(t *testing.T) { } func TestStorageNoSideEffect(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(flowEVMRoot flow.Address) { var err error em := emulator.NewEmulator(backend, flowEVMRoot) @@ -1068,7 +1131,7 @@ func TestStorageNoSideEffect(t *testing.T) { } func TestCallingExtraPrecompiles(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(flowEVMRoot flow.Address) { RunWithNewEmulator(t, backend, flowEVMRoot, func(em *emulator.Emulator) { @@ -1135,7 +1198,7 @@ func TestCallingExtraPrecompiles(t *testing.T) { } func TestTxIndex(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { RunWithNewEmulator(t, backend, rootAddr, func(em *emulator.Emulator) { ctx := types.NewDefaultBlockContext(blockNumber.Uint64()) diff --git a/fvm/evm/emulator/state/base.go b/fvm/evm/emulator/state/base.go index a0e85fee22e..3ae602e9c00 100644 --- a/fvm/evm/emulator/state/base.go +++ b/fvm/evm/emulator/state/base.go @@ -3,7 +3,6 @@ package state import ( "fmt" - "github.com/ethereum/go-ethereum/common" gethCommon "github.com/ethereum/go-ethereum/common" gethTypes "github.com/ethereum/go-ethereum/core/types" gethCrypto "github.com/ethereum/go-ethereum/crypto" @@ -178,7 +177,7 @@ func (v *BaseView) GetState(sk types.SlotAddress) (gethCommon.Hash, error) { // if account doesn't exist we return empty hash // if account exist but not a smart contract we return EmptyRootHash // if is a contract we return the hash of the root slab content (some sort of commitment). -func (v *BaseView) GetStorageRoot(addr common.Address) (common.Hash, error) { +func (v *BaseView) GetStorageRoot(addr gethCommon.Address) (gethCommon.Hash, error) { account, err := v.getAccount(addr) if err != nil { return gethCommon.Hash{}, err diff --git a/fvm/evm/emulator/state/collection.go b/fvm/evm/emulator/state/collection.go index 69d0cfda791..9390b11f953 100644 --- a/fvm/evm/emulator/state/collection.go +++ b/fvm/evm/emulator/state/collection.go @@ -253,17 +253,28 @@ func (v ByteStringValue) ChildStorables() []atree.Storable { return nil } +func (v ByteStringValue) CanCopyNonRefSimple() bool { + return true +} + +func (v ByteStringValue) CopyNonRefSimple() (atree.Storable, error) { + data := make([]byte, len(v.data)) + copy(data, v.data) + return NewByteStringValue(data), nil +} + func (v ByteStringValue) StoredValue(_ atree.SlabStorage) (atree.Value, error) { return v, nil } func (v ByteStringValue) Storable(storage atree.SlabStorage, address atree.Address, maxInlineSize uint32) (atree.Storable, error) { - if v.ByteSize() <= maxInlineSize { + byteSize := v.ByteSize() + if byteSize <= maxInlineSize { return v, nil } // Create StorableSlab - return atree.NewStorableSlab(storage, address, v) + return atree.NewStorableSlab(storage, address, v, byteSize) } func (v ByteStringValue) Encode(enc *atree.Encoder) error { diff --git a/fvm/evm/emulator/state/stateDB.go b/fvm/evm/emulator/state/stateDB.go index 6411c205d27..08a60146751 100644 --- a/fvm/evm/emulator/state/stateDB.go +++ b/fvm/evm/emulator/state/stateDB.go @@ -9,7 +9,6 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" gethState "github.com/ethereum/go-ethereum/core/state" gethStateless "github.com/ethereum/go-ethereum/core/stateless" - "github.com/ethereum/go-ethereum/core/tracing" gethTracing "github.com/ethereum/go-ethereum/core/tracing" gethTypes "github.com/ethereum/go-ethereum/core/types" gethParams "github.com/ethereum/go-ethereum/params" @@ -227,7 +226,7 @@ func (db *StateDB) GetCodeSize(addr gethCommon.Address) int { func (db *StateDB) SetCode( addr gethCommon.Address, code []byte, - reason tracing.CodeChangeReason, + reason gethTracing.CodeChangeReason, ) (prev []byte) { prev = db.GetCode(addr) err := db.latestView().SetCode(addr, code) diff --git a/fvm/evm/events/utils.go b/fvm/evm/events/utils.go index c03fc240cae..a5e5a2177b8 100644 --- a/fvm/evm/events/utils.go +++ b/fvm/evm/events/utils.go @@ -39,7 +39,7 @@ var checksumType = cadence.NewConstantSizedArrayType(types.ChecksumLength, caden // checksumToCadenceArrayValue converts a checksum ([4]byte) into a Cadence array of type [UInt8;4] func checksumToCadenceArrayValue(checksum [types.ChecksumLength]byte) cadence.Array { values := make([]cadence.Value, types.ChecksumLength) - for i := 0; i < types.ChecksumLength; i++ { + for i := range types.ChecksumLength { values[i] = cadence.NewUInt8(checksum[i]) } return cadence.NewArray(values). diff --git a/fvm/evm/evm.go b/fvm/evm/evm.go index f7952dcef89..4365d630124 100644 --- a/fvm/evm/evm.go +++ b/fvm/evm/evm.go @@ -1,15 +1,6 @@ package evm import ( - "github.com/onflow/cadence/common" - "github.com/onflow/cadence/runtime" - - "github.com/onflow/flow-go/fvm/environment" - "github.com/onflow/flow-go/fvm/evm/backends" - evm "github.com/onflow/flow-go/fvm/evm/emulator" - "github.com/onflow/flow-go/fvm/evm/handler" - "github.com/onflow/flow-go/fvm/evm/impl" - "github.com/onflow/flow-go/fvm/evm/stdlib" "github.com/onflow/flow-go/fvm/systemcontracts" "github.com/onflow/flow-go/model/flow" ) @@ -21,49 +12,3 @@ func ContractAccountAddress(chainID flow.ChainID) flow.Address { func StorageAccountAddress(chainID flow.ChainID) flow.Address { return systemcontracts.SystemContractsForChain(chainID).EVMStorage.Address } - -func SetupEnvironment( - chainID flow.ChainID, - fvmEnv environment.Environment, - runtimeEnv runtime.Environment, -) { - sc := systemcontracts.SystemContractsForChain(chainID) - randomBeaconAddress := sc.RandomBeaconHistory.Address - flowTokenAddress := sc.FlowToken.Address - - backend := backends.NewWrappedEnvironment(fvmEnv) - emulator := evm.NewEmulator(backend, StorageAccountAddress(chainID)) - blockStore := handler.NewBlockStore(chainID, backend, StorageAccountAddress(chainID)) - addressAllocator := handler.NewAddressAllocator() - - evmContractAddress := ContractAccountAddress(chainID) - - contractHandler := handler.NewContractHandler( - chainID, - evmContractAddress, - common.Address(flowTokenAddress), - randomBeaconAddress, - blockStore, - addressAllocator, - backend, - emulator, - ) - - internalEVMContractValue := impl.NewInternalEVMContractValue( - nil, - contractHandler, - evmContractAddress, - ) - - internalEVMFunctions := impl.NewInternalEVMFunctions( - contractHandler, - evmContractAddress, - ) - - stdlib.SetupEnvironment( - runtimeEnv, - internalEVMContractValue, - internalEVMFunctions, - evmContractAddress, - ) -} diff --git a/fvm/evm/evm_test.go b/fvm/evm/evm_test.go index df5d76a9cd9..f7f89778bdd 100644 --- a/fvm/evm/evm_test.go +++ b/fvm/evm/evm_test.go @@ -3,11 +3,13 @@ package evm_test import ( "bytes" "encoding/binary" + "encoding/hex" "fmt" "math" "math/big" "testing" + "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" gethTypes "github.com/ethereum/go-ethereum/core/types" gethParams "github.com/ethereum/go-ethereum/params" @@ -168,7 +170,7 @@ func TestEVMRun(t *testing.T) { assert(res.status == EVM.Status.successful, message: "unexpected status") assert(res.errorCode == 0, message: "unexpected error code") - + return res } `, @@ -211,8 +213,9 @@ func TestEVMRun(t *testing.T) { }) }) - t.Run("testing EVM.run (failed)", func(t *testing.T) { + t.Run("testing EVM.runTxAs (happy case)", func(t *testing.T) { t.Parallel() + RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -226,107 +229,95 @@ func TestEVMRun(t *testing.T) { ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + transaction(from: String, to: String, data: [UInt8]){ prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) + let res = EVM.runTxAs( + from: EVM.addressFromString(from), + to: EVM.addressFromString(to), + data: data, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) - assert(res.status == EVM.Status.failed, message: "unexpected status") - // ExecutionErrCodeExecutionReverted - assert(res.errorCode == %d, message: "unexpected error code") + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + assert(res.deployedContract == nil, message: "unexpected deployed contract") } } `, sc.EVMContract.Address.HexWithPrefix(), - types.ExecutionErrCodeExecutionReverted, )) - num := int64(12) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "storeButRevert", big.NewInt(num)), - big.NewInt(0), - uint64(100_000), - big.NewInt(0), - ) - - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), + num := int64(42) + callData := cadence.NewArray( + unittest.BytesToCdcUInt8( + testContract.MakeCallData(t, "store", big.NewInt(num)), + ), ).WithType(stdlib.EVMTransactionBytesCadenceType) - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + fromAddress := "0xF376A6849184571fEEdD246a1Ba2D331cfe56c8c" + from, err := cadence.NewString(fromAddress) + require.NoError(t, err) + + to, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(innerTx)). - AddArgument(json.MustEncode(coinbase)). + AddArgument(json.MustEncode(from)). + AddArgument(json.MustEncode(to)). + AddArgument(json.MustEncode(callData)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run( - ctx, - tx, - snapshot) + ctx.EVMTestOperationsAllowed = true + + state, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) require.NoError(t, output.Err) require.NotEmpty(t, state.WriteSet) - snapshot = snapshot.Append(state) - // query the value - code = []byte(fmt.Sprintf( - ` - import EVM from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) - } - `, - sc.EVMContract.Address.HexWithPrefix(), - )) + // assert event fields are correct + require.Len(t, output.Events, 1) + txEvent := output.Events[0] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + require.NoError(t, err) - innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "retrieve"), - big.NewInt(0), - uint64(100_000), - big.NewInt(0), + // commit block + blockEventPayload, _ := callEVMHeartBeat(t, + ctx, + vm, + snapshot, ) - innerTx = cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) + require.NotEmpty(t, blockEventPayload.Hash) + require.Equal(t, uint64(43785), blockEventPayload.TotalGasUsed) + require.NotEmpty(t, blockEventPayload.Hash) - script := fvm.Script(code).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), - ) + require.Equal(t, uint16(types.ErrCodeNoError), txEventPayload.ErrorCode) + require.Equal(t, uint16(0), txEventPayload.Index) + require.Equal(t, blockEventPayload.Height, txEventPayload.BlockHeight) + require.Empty(t, txEventPayload.ContractAddress) - _, output, err = vm.Run( - ctx, - script, - snapshot) + directCall, err := types.DirectCallFromEncoded(txEventPayload.Payload) require.NoError(t, err) - require.NoError(t, output.Err) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) - require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Empty(t, res.ErrorMessage) - require.Equal(t, int64(0), new(big.Int).SetBytes(res.ReturnedData).Int64()) - }) + require.Equal(t, fromAddress, directCall.From.String()) + require.Equal(t, testContract.DeployedAt.String(), directCall.To.String()) + require.Equal(t, uint64(100_000), directCall.GasLimit) + }, + fvm.WithEVMTestHelpersEnabled(true), + ) }) - t.Run("testing EVM.run (with event emitted)", func(t *testing.T) { + t.Run("testing EVM.runTxAs when context option not enabled", func(t *testing.T) { t.Parallel() + RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -340,72 +331,65 @@ func TestEVMRun(t *testing.T) { ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + transaction(from: String, to: String, data: [UInt8]){ prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) + let res = EVM.runTxAs( + from: EVM.addressFromString(from), + to: EVM.addressFromString(to), + data: data, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) assert(res.status == EVM.Status.successful, message: "unexpected status") assert(res.errorCode == 0, message: "unexpected error code") + assert(res.deployedContract == nil, message: "unexpected deployed contract") } } `, sc.EVMContract.Address.HexWithPrefix(), )) - num := int64(12) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "storeWithLog", big.NewInt(num)), - big.NewInt(0), - uint64(100_000), - big.NewInt(0), - ) - - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), + num := int64(42) + callData := cadence.NewArray( + unittest.BytesToCdcUInt8( + testContract.MakeCallData(t, "store", big.NewInt(num)), + ), ).WithType(stdlib.EVMTransactionBytesCadenceType) - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + fromAddress := "0xF376A6849184571fEEdD246a1Ba2D331cfe56c8c" + from, err := cadence.NewString(fromAddress) + require.NoError(t, err) + + to, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(innerTx)). - AddArgument(json.MustEncode(coinbase)). + AddArgument(json.MustEncode(from)). + AddArgument(json.MustEncode(to)). + AddArgument(json.MustEncode(callData)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run( - ctx, - tx, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - require.NotEmpty(t, state.WriteSet) - - txEvent := output.Events[0] - txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) - - require.NotEmpty(t, txEventPayload.Hash) - - var logs []*gethTypes.Log - err = rlp.DecodeBytes(txEventPayload.Logs, &logs) + _, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) - require.Len(t, logs, 1) - log := logs[0] - last := log.Topics[len(log.Topics)-1] // last topic is the value set in the store method - assert.Equal(t, num, last.Big().Int64()) - }) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "evm runtime error: operation is not supported", + ) + }, + fvm.WithEVMTestHelpersEnabled(true), + ) }) - t.Run("testing EVM.run execution reverted with assert error", func(t *testing.T) { - + t.Run("testing EVM.runTxAs when setting not bootstrapped", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, @@ -421,13 +405,18 @@ func TestEVMRun(t *testing.T) { ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + transaction(from: String, to: String, data: [UInt8]){ prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) + let res = EVM.runTxAs( + from: EVM.addressFromString(from), + to: EVM.addressFromString(to), + data: data, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) - assert(res.status == EVM.Status.failed, message: "unexpected status") - assert(res.errorCode == 306, message: "unexpected error code") + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") assert(res.deployedContract == nil, message: "unexpected deployed contract") } } @@ -435,63 +424,46 @@ func TestEVMRun(t *testing.T) { sc.EVMContract.Address.HexWithPrefix(), )) - coinbaseAddr := types.Address{1, 2, 3} - coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) - require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "assertError"), - big.NewInt(0), - uint64(100_000), - big.NewInt(1), - ) - - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), + num := int64(42) + callData := cadence.NewArray( + unittest.BytesToCdcUInt8( + testContract.MakeCallData(t, "store", big.NewInt(num)), + ), ).WithType(stdlib.EVMTransactionBytesCadenceType) - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + fromAddress := "0xF376A6849184571fEEdD246a1Ba2D331cfe56c8c" + from, err := cadence.NewString(fromAddress) + require.NoError(t, err) + + to, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(innerTx)). - AddArgument(json.MustEncode(coinbase)). + AddArgument(json.MustEncode(from)). + AddArgument(json.MustEncode(to)). + AddArgument(json.MustEncode(callData)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run( - ctx, - tx, - snapshot, - ) - require.NoError(t, err) - require.NoError(t, output.Err) - require.NotEmpty(t, state.WriteSet) - - // assert event fields are correct - require.Len(t, output.Events, 2) - txEvent := output.Events[0] - txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + _, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) - - assert.Equal( + require.Error(t, output.Err) + require.ErrorContains( t, - "execution reverted: Assert Error Message", - txEventPayload.ErrorMessage, + output.Err, + "value of type `&EVM` has no member `runTxAs`", ) }, + fvm.WithEVMTestHelpersEnabled(false), ) }) - t.Run("testing EVM.run execution reverted with custom error", func(t *testing.T) { - + t.Run("testing EVM.store and EVM.load (happy case)", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, @@ -507,14 +479,33 @@ func TestEVMRun(t *testing.T) { ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + transaction(tx: [UInt8], target: String, coinbaseBytes: [UInt8; 20]){ prepare(account: &Account) { + let targetAddr = EVM.addressFromString(target) + let slotValue = "00000000000000000000000000000000000000000000000000000000000003e8" + EVM.store( + target: targetAddr, + slot: "0x0000000000000000000000000000000000000000000000000000000000000000", + value: slotValue + ) let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) + let res = EVM.dryRun(tx: tx, from: coinbase) - assert(res.status == EVM.Status.failed, message: "unexpected status") - assert(res.errorCode == 306, message: "unexpected error code") + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") assert(res.deployedContract == nil, message: "unexpected deployed contract") + + let values = EVM.decodeABI(types: [Type()], data: res.data) + assert(values.length == 1) + + let number = values[0] as! UInt256 + assert(number == 1000, message: String.encodeHex(res.data)) + + let stateValue = EVM.load( + target: targetAddr, + slot: "0x0000000000000000000000000000000000000000000000000000000000000000" + ) + assert(String.encodeHex(stateValue) == slotValue, message: slotValue) } } `, @@ -525,13 +516,16 @@ func TestEVMRun(t *testing.T) { coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + evmTx := gethTypes.NewTransaction( + 0, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "customError"), big.NewInt(0), uint64(100_000), - big.NewInt(1), + big.NewInt(0), + testContract.MakeCallData(t, "retrieve"), ) + innerTxBytes, err := evmTx.MarshalBinary() + require.NoError(t, err) innerTx := cadence.NewArray( unittest.BytesToCdcUInt8(innerTxBytes), @@ -540,18 +534,23 @@ func TestEVMRun(t *testing.T) { coinbase := cadence.NewArray( unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) + target, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(target)). AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) + ctx.EVMTestOperationsAllowed = true + state, output, err := vm.Run( ctx, tx, @@ -560,25 +559,12 @@ func TestEVMRun(t *testing.T) { require.NoError(t, err) require.NoError(t, output.Err) require.NotEmpty(t, state.WriteSet) - - // assert event fields are correct - require.Len(t, output.Events, 2) - txEvent := output.Events[0] - txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) - require.NoError(t, err) - - // Unlike assert errors, custom errors cannot be further examined - // or ABI decoded, as we do not have access to the contract's ABI. - assert.Equal( - t, - "execution reverted", - txEventPayload.ErrorMessage, - ) }, + fvm.WithEVMTestHelpersEnabled(true), ) }) - t.Run("testing EVM.run failed with gas limit validation error", func(t *testing.T) { + t.Run("testing EVM.store when context option not enabled", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, @@ -593,13 +579,16 @@ func TestEVMRun(t *testing.T) { code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + + transaction(tx: [UInt8], target: String, coinbaseBytes: [UInt8; 20]){ prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.invalid, message: "unexpected status") - assert(res.errorCode == 100, message: "unexpected error code: \(res.errorCode)") - assert(res.errorMessage == "transaction gas limit too high (cap: 16777216, tx: 16777220)") + let targetAddr = EVM.addressFromString(target) + let slotValue = "00000000000000000000000000000000000000000000000000000000000003e8" + EVM.store( + target: targetAddr, + slot: "0x0000000000000000000000000000000000000000000000000000000000000000", + value: slotValue + ) } } `, @@ -610,14 +599,16 @@ func TestEVMRun(t *testing.T) { coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - num := int64(12) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + evmTx := gethTypes.NewTransaction( + 0, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "store", big.NewInt(num)), big.NewInt(0), - uint64(16_777_220), // max is 16,777,216 - big.NewInt(1), + uint64(100_000), + big.NewInt(0), + testContract.MakeCallData(t, "retrieve"), ) + innerTxBytes, err := evmTx.MarshalBinary() + require.NoError(t, err) innerTx := cadence.NewArray( unittest.BytesToCdcUInt8(innerTxBytes), @@ -626,33 +617,35 @@ func TestEVMRun(t *testing.T) { coinbase := cadence.NewArray( unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) + target, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(target)). AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run( - ctx, - tx, - snapshot, - ) + _, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) - require.NoError(t, output.Err) - require.NotEmpty(t, state.WriteSet) - - // assert no events were produced from an invalid EVM transaction - require.Len(t, output.Events, 0) - }) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "evm runtime error: operation is not supported", + ) + }, + fvm.WithEVMTestHelpersEnabled(true), + ) }) - t.Run("testing EVM.run with max gas limit cap", func(t *testing.T) { + t.Run("testing EVM.store when setting not bootstrapped", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, @@ -667,12 +660,16 @@ func TestEVMRun(t *testing.T) { code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + + transaction(tx: [UInt8], target: String, coinbaseBytes: [UInt8; 20]){ prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.successful, message: "unexpected status") - assert(res.errorCode == 0, message: "unexpected error code: \(res.errorCode)") + let targetAddr = EVM.addressFromString(target) + let slotValue = "00000000000000000000000000000000000000000000000000000000000003e8" + EVM.store( + target: targetAddr, + slot: "0x0000000000000000000000000000000000000000000000000000000000000000", + value: slotValue + ) } } `, @@ -683,14 +680,16 @@ func TestEVMRun(t *testing.T) { coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - num := int64(12) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + evmTx := gethTypes.NewTransaction( + 0, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "store", big.NewInt(num)), big.NewInt(0), - uint64(16_777_216), - big.NewInt(1), + uint64(100_000), + big.NewInt(0), + testContract.MakeCallData(t, "retrieve"), ) + innerTxBytes, err := evmTx.MarshalBinary() + require.NoError(t, err) innerTx := cadence.NewArray( unittest.BytesToCdcUInt8(innerTxBytes), @@ -699,78 +698,37 @@ func TestEVMRun(t *testing.T) { coinbase := cadence.NewArray( unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) + target, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(target)). AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run( - ctx, - tx, - snapshot, - ) - require.NoError(t, err) - require.NoError(t, output.Err) - require.NotEmpty(t, state.WriteSet) - snapshot = snapshot.Append(state) - - // assert event fields are correct - require.Len(t, output.Events, 2) - txEvent := output.Events[0] - txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) - require.NoError(t, err) - - // fee transfer event - feeTransferEvent := output.Events[1] - feeTranferEventPayload := TxEventToPayload(t, feeTransferEvent, sc.EVMContract.Address) + _, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) - require.Equal(t, uint16(types.ErrCodeNoError), feeTranferEventPayload.ErrorCode) - require.Equal(t, uint16(1), feeTranferEventPayload.Index) - require.Equal(t, uint64(21000), feeTranferEventPayload.GasConsumed) - - // commit block - blockEventPayload, _ := callEVMHeartBeat(t, - ctx, - vm, - snapshot, - ) - - require.NotEmpty(t, blockEventPayload.Hash) - require.Equal(t, uint64(64785), blockEventPayload.TotalGasUsed) - require.NotEmpty(t, blockEventPayload.Hash) - - txHashes := types.TransactionHashes{txEventPayload.Hash, feeTranferEventPayload.Hash} - require.Equal(t, - txHashes.RootHash(), - blockEventPayload.TransactionHashRoot, + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "value of type `&EVM` has no member `store`", ) - require.NotEmpty(t, blockEventPayload.ReceiptRoot) - - require.Equal(t, innerTxBytes, txEventPayload.Payload) - require.Equal(t, uint16(types.ErrCodeNoError), txEventPayload.ErrorCode) - require.Equal(t, uint16(0), txEventPayload.Index) - require.Equal(t, blockEventPayload.Height, txEventPayload.BlockHeight) - require.Equal(t, blockEventPayload.TotalGasUsed-feeTranferEventPayload.GasConsumed, txEventPayload.GasConsumed) - require.Empty(t, txEventPayload.ContractAddress) - }) + }, + fvm.WithEVMTestHelpersEnabled(false), + ) }) -} -func TestEVMBatchRun(t *testing.T) { - chain := flow.Emulator.Chain() - - // run a batch of valid transactions which update a value on the contract - // after the batch is run check that the value updated on the contract matches - // the last transaction update in the batch. - t.Run("Batch run multiple valid transactions", func(t *testing.T) { + t.Run("testing EVM.load when context option not enabled", func(t *testing.T) { t.Parallel() + RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -780,20 +738,19 @@ func TestEVMBatchRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := []byte(fmt.Sprintf( + code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { + transaction(tx: [UInt8], target: String, coinbaseBytes: [UInt8; 20]){ prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) - - assert(batchResults.length == txs.length, message: "invalid result length") - for res in batchResults { - assert(res.status == EVM.Status.successful, message: "unexpected status") - assert(res.errorCode == 0, message: "unexpected error code") - } + let targetAddr = EVM.addressFromString(target) + let slotValue = "00000000000000000000000000000000000000000000000000000000000003e8" + let stateValue = EVM.load( + target: targetAddr, + slot: "0x0000000000000000000000000000000000000000000000000000000000000000" + ) + assert(String.encodeHex(stateValue) == slotValue, message: slotValue) } } `, @@ -804,162 +761,134 @@ func TestEVMBatchRun(t *testing.T) { coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - batchCount := 5 - var storedValues []int64 - txBytes := make([]cadence.Value, batchCount) - for i := 0; i < batchCount; i++ { - num := int64(i) - storedValues = append(storedValues, num) - // prepare batch of transaction payloads - tx := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "storeWithLog", big.NewInt(num)), - big.NewInt(0), - uint64(100_000), - big.NewInt(1), - ) + evmTx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + testContract.MakeCallData(t, "retrieve"), + ) + innerTxBytes, err := evmTx.MarshalBinary() + require.NoError(t, err) - // build txs argument - txBytes[i] = cadence.NewArray( - unittest.BytesToCdcUInt8(tx), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - } + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) coinbase := cadence.NewArray( unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) - - txs := cadence.NewArray(txBytes). - WithType(cadence.NewVariableSizedArrayType( - stdlib.EVMTransactionBytesCadenceType, - )) + target, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(batchRunCode). + SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(txs)). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(target)). AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run(ctx, tx, snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - require.NotEmpty(t, state.WriteSet) - - // append the state - snapshot = snapshot.Append(state) - - require.Len(t, output.Events, batchCount+1) - txHashes := make(types.TransactionHashes, 0) - totalGasUsed := uint64(0) - for i, event := range output.Events { - if i == batchCount { // skip last one - continue - } - - ev, err := ccf.Decode(nil, event.Payload) - require.NoError(t, err) - cadenceEvent, ok := ev.(cadence.Event) - require.True(t, ok) - - event, err := events.DecodeTransactionEventPayload(cadenceEvent) - require.NoError(t, err) - - txHashes = append(txHashes, event.Hash) - var logs []*gethTypes.Log - err = rlp.DecodeBytes(event.Logs, &logs) - require.NoError(t, err) - - require.Len(t, logs, 1) - - log := logs[0] - last := log.Topics[len(log.Topics)-1] // last topic is the value set in the store method - assert.Equal(t, storedValues[i], last.Big().Int64()) - totalGasUsed += event.GasConsumed - } - - // last event is fee transfer event - feeTransferEvent := output.Events[batchCount] - feeTranferEventPayload := TxEventToPayload(t, feeTransferEvent, sc.EVMContract.Address) + _, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) - require.Equal(t, uint16(types.ErrCodeNoError), feeTranferEventPayload.ErrorCode) - require.Equal(t, uint16(batchCount), feeTranferEventPayload.Index) - require.Equal(t, uint64(21000), feeTranferEventPayload.GasConsumed) - txHashes = append(txHashes, feeTranferEventPayload.Hash) - - // check coinbase balance (note the gas price is 1) - coinbaseBalance = getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) - require.Equal(t, types.BalanceToBigInt(coinbaseBalance).Uint64(), totalGasUsed) - - // commit block - blockEventPayload, snapshot := callEVMHeartBeat(t, - ctx, - vm, - snapshot) - - require.NotEmpty(t, blockEventPayload.Hash) - require.Equal(t, uint64(176_513), blockEventPayload.TotalGasUsed) - require.Equal(t, - txHashes.RootHash(), - blockEventPayload.TransactionHashRoot, + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "evm runtime error: operation is not supported", ) + }, + fvm.WithEVMTestHelpersEnabled(true), + ) + }) - // retrieve the values - retrieveCode := []byte(fmt.Sprintf( + t.Run("testing EVM.load when setting not bootstrapped", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( ` - import EVM from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) + import EVM from %s + + transaction(tx: [UInt8], target: String, coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let targetAddr = EVM.addressFromString(target) + let slotValue = "00000000000000000000000000000000000000000000000000000000000003e8" + let stateValue = EVM.load( + target: targetAddr, + slot: "0x0000000000000000000000000000000000000000000000000000000000000000" + ) + assert(String.encodeHex(stateValue) == slotValue, message: slotValue) } + } `, sc.EVMContract.Address.HexWithPrefix(), )) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + evmTx := gethTypes.NewTransaction( + 0, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "retrieve"), big.NewInt(0), uint64(100_000), big.NewInt(0), + testContract.MakeCallData(t, "retrieve"), ) + innerTxBytes, err := evmTx.MarshalBinary() + require.NoError(t, err) innerTx := cadence.NewArray( unittest.BytesToCdcUInt8(innerTxBytes), ).WithType(stdlib.EVMTransactionBytesCadenceType) - script := fvm.Script(retrieveCode).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), - ) + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + target, err := cadence.NewString(testContract.DeployedAt.String()) + require.NoError(t, err) - _, output, err = vm.Run( - ctx, - script, - snapshot) + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(target)). + AddArgument(json.MustEncode(coinbase)). + Build() require.NoError(t, err) - require.NoError(t, output.Err) - // make sure the retrieved value is the same as the last value - // that was stored by transaction batch - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Empty(t, res.ErrorMessage) - require.Equal(t, storedValues[len(storedValues)-1], new(big.Int).SetBytes(res.ReturnedData).Int64()) - }) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "value of type `&EVM` has no member `load`", + ) + }, + fvm.WithEVMTestHelpersEnabled(false), + ) }) - // run batch with one invalid transaction that has an invalid nonce - // this should produce invalid result on that specific transaction - // but other transaction should successfuly update the value on the contract - t.Run("Batch run with one invalid transaction", func(t *testing.T) { + t.Run("testing EVM.run (failed)", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, chain, func( @@ -969,102 +898,78 @@ func TestEVMBatchRun(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - // we make transaction at specific index invalid to fail - const failedTxIndex = 3 sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := []byte(fmt.Sprintf( + code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ prepare(account: &Account) { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) - - assert(batchResults.length == txs.length, message: "invalid result length") - for i, res in batchResults { - if i != %d { - assert(res.status == EVM.Status.successful, message: "unexpected status") - assert(res.errorCode == 0, message: "unexpected error code") - } else { - assert(res.status == EVM.Status.invalid, message: "unexpected status") - assert(res.errorCode == 201, message: "unexpected error code") - } - } + let res = EVM.run(tx: tx, coinbase: coinbase) + + assert(res.status == EVM.Status.failed, message: "unexpected status") + // ExecutionErrCodeExecutionReverted + assert(res.errorCode == %d, message: "unexpected error code") } } `, sc.EVMContract.Address.HexWithPrefix(), - failedTxIndex, + types.ExecutionErrCodeExecutionReverted, )) - batchCount := 5 - var num int64 - txBytes := make([]cadence.Value, batchCount) - for i := 0; i < batchCount; i++ { - num = int64(i) - - if i == failedTxIndex { - // make one transaction in the batch have an invalid nonce - testAccount.SetNonce(testAccount.Nonce() - 1) - } - // prepare batch of transaction payloads - tx := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "store", big.NewInt(num)), - big.NewInt(0), - uint64(100_000), - big.NewInt(0), - ) + num := int64(12) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "storeButRevert", big.NewInt(num)), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) - // build txs argument - txBytes[i] = cadence.NewArray( - unittest.BytesToCdcUInt8(tx), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - } + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) coinbase := cadence.NewArray( unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) - txs := cadence.NewArray(txBytes). - WithType(cadence.NewVariableSizedArrayType( - stdlib.EVMTransactionBytesCadenceType, - )) - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(batchRunCode). + SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(txs)). + AddArgument(json.MustEncode(innerTx)). AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run(ctx, tx, snapshot) + state, output, err := vm.Run( + ctx, + tx, + snapshot) require.NoError(t, err) require.NoError(t, output.Err) require.NotEmpty(t, state.WriteSet) - // append the state snapshot = snapshot.Append(state) - // retrieve the values - retrieveCode := []byte(fmt.Sprintf( + // query the value + code = []byte(fmt.Sprintf( ` - import EVM from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) - } - `, + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, sc.EVMContract.Address.HexWithPrefix(), )) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), testContract.MakeCallData(t, "retrieve"), big.NewInt(0), @@ -1072,11 +977,11 @@ func TestEVMBatchRun(t *testing.T) { big.NewInt(0), ) - innerTx := cadence.NewArray( + innerTx = cadence.NewArray( unittest.BytesToCdcUInt8(innerTxBytes), ).WithType(stdlib.EVMTransactionBytesCadenceType) - script := fvm.Script(retrieveCode).WithArguments( + script := fvm.Script(code).WithArguments( json.MustEncode(innerTx), json.MustEncode(coinbase), ) @@ -1088,21 +993,16 @@ func TestEVMBatchRun(t *testing.T) { require.NoError(t, err) require.NoError(t, output.Err) - // make sure the retrieved value is the same as the last value - // that was stored by transaction batch res, err := impl.ResultSummaryFromEVMResultValue(output.Value) require.NoError(t, err) require.Equal(t, types.StatusSuccessful, res.Status) require.Equal(t, types.ErrCodeNoError, res.ErrorCode) require.Empty(t, res.ErrorMessage) - require.Equal(t, num, new(big.Int).SetBytes(res.ReturnedData).Int64()) + require.Equal(t, int64(0), new(big.Int).SetBytes(res.ReturnedData).Int64()) }) }) - // fail every other transaction with gas set too low for execution to succeed - // but high enough to pass intristic gas check, then check the updated values on the - // contract to match the last successful transaction execution - t.Run("Batch run with with failed transactions", func(t *testing.T) { + t.Run("testing EVM.run (with event emitted)", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, chain, func( @@ -1113,143 +1013,78 @@ func TestEVMBatchRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := []byte(fmt.Sprintf( + code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { - execute { + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) - - log("results") - log(batchResults) - assert(batchResults.length == txs.length, message: "invalid result length") + let res = EVM.run(tx: tx, coinbase: coinbase) - for i, res in batchResults { - if i %% 2 != 0 { - assert(res.status == EVM.Status.successful, message: "unexpected success status") - assert(res.errorCode == 0, message: "unexpected error code") - assert(res.errorMessage == "", message: "unexpected error msg") - } else { - assert(res.status == EVM.Status.failed, message: "unexpected failed status") - assert(res.errorCode == 400, message: "unexpected error code") - } - } + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") } } `, sc.EVMContract.Address.HexWithPrefix(), )) - batchCount := 6 - var num int64 - txBytes := make([]cadence.Value, batchCount) - for i := 0; i < batchCount; i++ { - gas := uint64(100_000) - if i%2 == 0 { - // fail with too low gas limit - gas = 22_000 - } else { - // update number with only valid transactions - num = int64(i) - } - - // prepare batch of transaction payloads - tx := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "store", big.NewInt(num)), - big.NewInt(0), - gas, - big.NewInt(0), - ) + num := int64(12) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "storeWithLog", big.NewInt(num)), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) - // build txs argument - txBytes[i] = cadence.NewArray( - unittest.BytesToCdcUInt8(tx), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - } + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) coinbase := cadence.NewArray( unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) - txs := cadence.NewArray(txBytes). - WithType(cadence.NewVariableSizedArrayType( - stdlib.EVMTransactionBytesCadenceType, - )) - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(batchRunCode). + SetScript(code). SetPayer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(txs)). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - state, output, err := vm.Run(ctx, tx, snapshot) - + state, output, err := vm.Run( + ctx, + tx, + snapshot) require.NoError(t, err) require.NoError(t, output.Err) - //require.NotEmpty(t, state.WriteSet) - - // append the state - snapshot = snapshot.Append(state) - - // retrieve the values - retrieveCode := []byte(fmt.Sprintf( - ` - import EVM from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) - } - `, - sc.EVMContract.Address.HexWithPrefix(), - )) + require.NotEmpty(t, state.WriteSet) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "retrieve"), - big.NewInt(0), - uint64(100_000), - big.NewInt(0), - ) + txEvent := output.Events[0] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) + require.NotEmpty(t, txEventPayload.Hash) - script := fvm.Script(retrieveCode).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), - ) - - _, output, err = vm.Run( - ctx, - script, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - // make sure the retrieved value is the same as the last value - // that was stored by transaction batch - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + var logs []*gethTypes.Log + err = rlp.DecodeBytes(txEventPayload.Logs, &logs) require.NoError(t, err) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Empty(t, res.ErrorMessage) - require.Equal(t, num, new(big.Int).SetBytes(res.ReturnedData).Int64()) + require.Len(t, logs, 1) + log := logs[0] + last := log.Topics[len(log.Topics)-1] // last topic is the value set in the store method + assert.Equal(t, num, last.Big().Int64()) }) }) - // run a batch of two transactions. The sum of their gas usage would overflow an uint46 - // so the batch run should fail with an overflow error. - t.Run("Batch run evm gas overflow", func(t *testing.T) { + t.Run("testing EVM.run execution reverted with assert error", func(t *testing.T) { + t.Parallel() + RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -1259,14 +1094,18 @@ func TestEVMBatchRun(t *testing.T) { testAccount *EOATestAccount, ) { sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - batchRunCode := []byte(fmt.Sprintf( + code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { - execute { + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) + let res = EVM.run(tx: tx, coinbase: coinbase) + + assert(res.status == EVM.Status.failed, message: "unexpected status") + assert(res.errorCode == 306, message: "unexpected error code") + assert(res.deployedContract == nil, message: "unexpected deployed contract") } } `, @@ -1277,324 +1116,146 @@ func TestEVMBatchRun(t *testing.T) { coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - batchCount := 2 - txBytes := make([]cadence.Value, batchCount) - - tx := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "storeWithLog", big.NewInt(0)), - big.NewInt(0), - uint64(200_000), - big.NewInt(1), - ) - - txBytes[0] = cadence.NewArray( - unittest.BytesToCdcUInt8(tx), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - - tx = testAccount.PrepareSignAndEncodeTx(t, + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "storeWithLog", big.NewInt(1)), + testContract.MakeCallData(t, "assertError"), big.NewInt(0), - math.MaxUint64-uint64(100_000), + uint64(100_000), big.NewInt(1), ) - txBytes[1] = cadence.NewArray( - unittest.BytesToCdcUInt8(tx), + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), ).WithType(stdlib.EVMTransactionBytesCadenceType) coinbase := cadence.NewArray( unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) - txs := cadence.NewArray(txBytes). - WithType(cadence.NewVariableSizedArrayType( - stdlib.EVMTransactionBytesCadenceType, - )) - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(batchRunCode). + SetScript(code). SetPayer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(txs)). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) - state, output, err := vm.Run(ctx, fvm.Transaction(txBody, 0), snapshot) + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run( + ctx, + tx, + snapshot, + ) require.NoError(t, err) - require.Error(t, output.Err) - require.ErrorContains(t, output.Err, "insufficient computation") - require.Empty(t, state.WriteSet) - }) - }) -} + require.NoError(t, output.Err) + require.NotEmpty(t, state.WriteSet) -func TestEVMBlockData(t *testing.T) { - t.Parallel() - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - RunWithNewEnvironment(t, - chain, func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { + // assert event fields are correct + require.Len(t, output.Events, 2) + txEvent := output.Events[0] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + require.NoError(t, err) - // query the block timestamp - code := []byte(fmt.Sprintf( - ` - import EVM from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) - } - `, - sc.EVMContract.Address.HexWithPrefix(), - )) + assert.Equal( + t, + "execution reverted: Assert Error Message", + txEventPayload.ErrorMessage, + ) + }, + ) + }) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "blockTime"), - big.NewInt(0), - uint64(100_000), - big.NewInt(0), - ) + t.Run("testing EVM.run execution reverted with custom error", func(t *testing.T) { - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + t.Parallel() - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s - script := fvm.Script(code).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), - ) + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) - _, output, err := vm.Run( - ctx, - script, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) + assert(res.status == EVM.Status.failed, message: "unexpected status") + assert(res.errorCode == 306, message: "unexpected error code") + assert(res.deployedContract == nil, message: "unexpected deployed contract") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) - require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Empty(t, res.ErrorMessage) - require.Equal(t, ctx.BlockHeader.Timestamp/1000, new(big.Int).SetBytes(res.ReturnedData).Uint64()) // EVM reports block time as Unix time in seconds + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - }) -} + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "customError"), + big.NewInt(0), + uint64(100_000), + big.NewInt(1), + ) -func TestEVMAddressDeposit(t *testing.T) { + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) - t.Parallel() - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - RunWithNewEnvironment(t, - chain, func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) - code := []byte(fmt.Sprintf( - ` - import EVM from %s - import FlowToken from %s + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) - transaction(addr: [UInt8; 20]) { - prepare(account: auth(BorrowValue) &Account) { - let admin = account.storage - .borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + tx := fvm.Transaction(txBody, 0) - let minter <- admin.createNewMinter(allowedAmount: 1.0) - let vault <- minter.mintTokens(amount: 1.0) - destroy minter + state, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + require.NotEmpty(t, state.WriteSet) - let address = EVM.EVMAddress(bytes: addr) - address.deposit(from: <-vault) - } - } - `, - sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - )) + // assert event fields are correct + require.Len(t, output.Events, 2) + txEvent := output.Events[0] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + require.NoError(t, err) - addr := RandomAddress(t) - - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(code). - SetPayer(sc.FlowServiceAccount.Address). - AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(cadence.NewArray( - unittest.BytesToCdcUInt8(addr.Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType))). - Build() - require.NoError(t, err) - - tx := fvm.Transaction(txBody, 0) - - execSnap, output, err := vm.Run( - ctx, - tx, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - snapshot = snapshot.Append(execSnap) - - expectedBalance := types.OneFlowBalance() - bal := getEVMAccountBalance(t, ctx, vm, snapshot, addr) - require.Equal(t, expectedBalance, bal) - - // tx executed event - txEvent := output.Events[2] - txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) - - // deposit event - depositEvent := output.Events[3] - depEv, err := events.FlowEventToCadenceEvent(depositEvent) - require.NoError(t, err) - - depEvPayload, err := events.DecodeFLOWTokensDepositedEventPayload(depEv) - require.NoError(t, err) - - require.Equal(t, types.OneFlow(), depEvPayload.BalanceAfterInAttoFlow.Value) - - // commit block - blockEventPayload, _ := callEVMHeartBeat(t, - ctx, - vm, - snapshot) - - require.NotEmpty(t, blockEventPayload.Hash) - require.Equal(t, uint64(21000), blockEventPayload.TotalGasUsed) - - txHashes := types.TransactionHashes{txEventPayload.Hash} - require.Equal(t, - txHashes.RootHash(), - blockEventPayload.TransactionHashRoot, - ) - }) -} - -func TestCOAAddressDeposit(t *testing.T) { - t.Parallel() - - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - RunWithNewEnvironment(t, - chain, func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { - code := []byte(fmt.Sprintf( - ` - import EVM from %s - import FlowToken from %s - - access(all) - fun main() { - let admin = getAuthAccount(%s) - .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! - let minter <- admin.createNewMinter(allowedAmount: 1.23) - let vault <- minter.mintTokens(amount: 1.23) - destroy minter - - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - cadenceOwnedAccount.deposit(from: <-vault) - destroy cadenceOwnedAccount - } - `, - sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - sc.FlowServiceAccount.Address.HexWithPrefix(), - )) - - script := fvm.Script(code) - - _, output, err := vm.Run( - ctx, - script, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - }) -} - -func TestCadenceOwnedAccountFunctionalities(t *testing.T) { - t.Parallel() - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - - t.Run("test coa setup", func(t *testing.T) { - t.Parallel() - - RunWithNewEnvironment(t, - chain, func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { - // create a flow account - flowAccount, _, snapshot := createAndFundFlowAccount( + // Unlike assert errors, custom errors cannot be further examined + // or ABI decoded, as we do not have access to the contract's ABI. + assert.Equal( t, - ctx, - vm, - snapshot, + "execution reverted", + txEventPayload.ErrorMessage, ) - - var coaAddress types.Address - - initNonce := uint64(1) - // 10 Flow in UFix64 - initBalanceInUFix64 := uint64(1_000_000_000) - initBalance := types.NewBalanceFromUFix64(cadence.UFix64(initBalanceInUFix64)) - - coaAddress, snapshot = setupCOA( - t, - ctx, - vm, - snapshot, - flowAccount, - initBalanceInUFix64) - - bal := getEVMAccountBalance( - t, - ctx, - vm, - snapshot, - coaAddress) - require.Equal(t, initBalance, bal) - - nonce := getEVMAccountNonce( - t, - ctx, - vm, - snapshot, - coaAddress) - require.Equal(t, initNonce, nonce) - }) + }, + ) }) - t.Run("test coa withdraw", func(t *testing.T) { + t.Run("testing EVM.run failed with gas limit validation error", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, @@ -1605,67 +1266,70 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) code := []byte(fmt.Sprintf( ` - import EVM from %s - import FlowToken from %s + import EVM from %s + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + assert(res.status == EVM.Status.invalid, message: "unexpected status") + assert(res.errorCode == 100, message: "unexpected error code: \(res.errorCode)") + assert(res.errorMessage == "transaction gas limit too high (cap: 16777216, tx: 16777220)") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - transaction() { - prepare(account: auth(BorrowValue) &Account) { - let admin = account.storage - .borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - let minter <- admin.createNewMinter(allowedAmount: 2.34) - let vault <- minter.mintTokens(amount: 2.34) - destroy minter + num := int64(12) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(16_777_220), // max is 16,777,216 + big.NewInt(1), + ) - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - cadenceOwnedAccount.deposit(from: <-vault) + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) - let bal = EVM.Balance(attoflow: 0) - bal.setFLOW(flow: 1.23) - let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) - let balance = vault2.balance - destroy cadenceOwnedAccount - destroy vault2 - } - } - `, - sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - )) + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) tx := fvm.Transaction(txBody, 0) - _, output, err := vm.Run( + state, output, err := vm.Run( ctx, tx, - snapshot) + snapshot, + ) require.NoError(t, err) require.NoError(t, output.Err) + require.NotEmpty(t, state.WriteSet) - withdrawEvent := output.Events[7] - - ev, err := events.FlowEventToCadenceEvent(withdrawEvent) - require.NoError(t, err) - - evPayload, err := events.DecodeFLOWTokensWithdrawnEventPayload(ev) - require.NoError(t, err) - - // 2.34 - 1.23 = 1.11 - expectedBalanceAfterWithdraw := big.NewInt(1_110_000_000_000_000_000) - require.Equal(t, expectedBalanceAfterWithdraw, evPayload.BalanceAfterInAttoFlow.Value) + // assert no events were produced from an invalid EVM transaction + require.Len(t, output.Events, 0) }) }) - t.Run("test coa transfer", func(t *testing.T) { + t.Run("testing EVM.run with max gas limit cap", func(t *testing.T) { t.Parallel() RunWithNewEnvironment(t, @@ -1676,66 +1340,2690 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) code := []byte(fmt.Sprintf( ` - import EVM from %s - import FlowToken from %s + import EVM from %s + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code: \(res.errorCode)") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - access(all) + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + num := int64(12) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(16_777_216), + big.NewInt(1), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + require.NotEmpty(t, state.WriteSet) + snapshot = snapshot.Append(state) + + // assert event fields are correct + require.Len(t, output.Events, 2) + txEvent := output.Events[0] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + require.NoError(t, err) + + // fee transfer event + feeTransferEvent := output.Events[1] + feeTranferEventPayload := TxEventToPayload(t, feeTransferEvent, sc.EVMContract.Address) + require.NoError(t, err) + require.Equal(t, uint16(types.ErrCodeNoError), feeTranferEventPayload.ErrorCode) + require.Equal(t, uint16(1), feeTranferEventPayload.Index) + require.Equal(t, uint64(21000), feeTranferEventPayload.GasConsumed) + + // commit block + blockEventPayload, _ := callEVMHeartBeat(t, + ctx, + vm, + snapshot, + ) + + require.NotEmpty(t, blockEventPayload.Hash) + require.Equal(t, uint64(64785), blockEventPayload.TotalGasUsed) + require.NotEmpty(t, blockEventPayload.Hash) + + txHashes := types.TransactionHashes{txEventPayload.Hash, feeTranferEventPayload.Hash} + require.Equal(t, + txHashes.RootHash(), + blockEventPayload.TransactionHashRoot, + ) + require.NotEmpty(t, blockEventPayload.ReceiptRoot) + + require.Equal(t, innerTxBytes, txEventPayload.Payload) + require.Equal(t, uint16(types.ErrCodeNoError), txEventPayload.ErrorCode) + require.Equal(t, uint16(0), txEventPayload.Index) + require.Equal(t, blockEventPayload.Height, txEventPayload.BlockHeight) + require.Equal(t, blockEventPayload.TotalGasUsed-feeTranferEventPayload.GasConsumed, txEventPayload.GasConsumed) + require.Empty(t, txEventPayload.ContractAddress) + }) + }) +} + +func TestEVMBatchRun(t *testing.T) { + chain := flow.Emulator.Chain() + + // run a batch of valid transactions which update a value on the contract + // after the batch is run check that the value updated on the contract matches + // the last transaction update in the batch. + t.Run("Batch run multiple valid transactions", func(t *testing.T) { + t.Parallel() + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + batchRunCode := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) + + assert(batchResults.length == txs.length, message: "invalid result length") + for res in batchResults { + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + batchCount := 5 + var storedValues []int64 + txBytes := make([]cadence.Value, batchCount) + for i := 0; i < batchCount; i++ { + num := int64(i) + storedValues = append(storedValues, num) + // prepare batch of transaction payloads + tx := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "storeWithLog", big.NewInt(num)), + big.NewInt(0), + uint64(100_000), + big.NewInt(1), + ) + + // build txs argument + txBytes[i] = cadence.NewArray( + unittest.BytesToCdcUInt8(tx), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + } + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txs := cadence.NewArray(txBytes). + WithType(cadence.NewVariableSizedArrayType( + stdlib.EVMTransactionBytesCadenceType, + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(batchRunCode). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(txs)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + require.NotEmpty(t, state.WriteSet) + + // append the state + snapshot = snapshot.Append(state) + + require.Len(t, output.Events, batchCount+1) + txHashes := make(types.TransactionHashes, 0) + totalGasUsed := uint64(0) + for i, event := range output.Events { + if i == batchCount { // skip last one + continue + } + + ev, err := ccf.Decode(nil, event.Payload) + require.NoError(t, err) + cadenceEvent, ok := ev.(cadence.Event) + require.True(t, ok) + + event, err := events.DecodeTransactionEventPayload(cadenceEvent) + require.NoError(t, err) + + txHashes = append(txHashes, event.Hash) + var logs []*gethTypes.Log + err = rlp.DecodeBytes(event.Logs, &logs) + require.NoError(t, err) + + require.Len(t, logs, 1) + + log := logs[0] + last := log.Topics[len(log.Topics)-1] // last topic is the value set in the store method + assert.Equal(t, storedValues[i], last.Big().Int64()) + totalGasUsed += event.GasConsumed + } + + // last event is fee transfer event + feeTransferEvent := output.Events[batchCount] + feeTranferEventPayload := TxEventToPayload(t, feeTransferEvent, sc.EVMContract.Address) + require.NoError(t, err) + require.Equal(t, uint16(types.ErrCodeNoError), feeTranferEventPayload.ErrorCode) + require.Equal(t, uint16(batchCount), feeTranferEventPayload.Index) + require.Equal(t, uint64(21000), feeTranferEventPayload.GasConsumed) + txHashes = append(txHashes, feeTranferEventPayload.Hash) + + // check coinbase balance (note the gas price is 1) + coinbaseBalance = getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Equal(t, types.BalanceToBigInt(coinbaseBalance).Uint64(), totalGasUsed) + + // commit block + blockEventPayload, snapshot := callEVMHeartBeat(t, + ctx, + vm, + snapshot) + + require.NotEmpty(t, blockEventPayload.Hash) + require.Equal(t, uint64(176_513), blockEventPayload.TotalGasUsed) + require.Equal(t, + txHashes.RootHash(), + blockEventPayload.TransactionHashRoot, + ) + + // retrieve the values + retrieveCode := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "retrieve"), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + script := fvm.Script(retrieveCode).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err = vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + // make sure the retrieved value is the same as the last value + // that was stored by transaction batch + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Empty(t, res.ErrorMessage) + require.Equal(t, storedValues[len(storedValues)-1], new(big.Int).SetBytes(res.ReturnedData).Int64()) + }) + }) + + // run batch with one invalid transaction that has an invalid nonce + // this should produce invalid result on that specific transaction + // but other transaction should successfuly update the value on the contract + t.Run("Batch run with one invalid transaction", func(t *testing.T) { + t.Parallel() + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + // we make transaction at specific index invalid to fail + const failedTxIndex = 3 + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + batchRunCode := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) + + assert(batchResults.length == txs.length, message: "invalid result length") + for i, res in batchResults { + if i != %d { + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } else { + assert(res.status == EVM.Status.invalid, message: "unexpected status") + assert(res.errorCode == 201, message: "unexpected error code") + } + } + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + failedTxIndex, + )) + + batchCount := 5 + var num int64 + txBytes := make([]cadence.Value, batchCount) + for i := 0; i < batchCount; i++ { + num = int64(i) + + if i == failedTxIndex { + // make one transaction in the batch have an invalid nonce + testAccount.SetNonce(testAccount.Nonce() - 1) + } + // prepare batch of transaction payloads + tx := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) + + // build txs argument + txBytes[i] = cadence.NewArray( + unittest.BytesToCdcUInt8(tx), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + } + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txs := cadence.NewArray(txBytes). + WithType(cadence.NewVariableSizedArrayType( + stdlib.EVMTransactionBytesCadenceType, + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(batchRunCode). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(txs)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + require.NotEmpty(t, state.WriteSet) + + // append the state + snapshot = snapshot.Append(state) + + // retrieve the values + retrieveCode := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "retrieve"), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + script := fvm.Script(retrieveCode).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err = vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + // make sure the retrieved value is the same as the last value + // that was stored by transaction batch + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Empty(t, res.ErrorMessage) + require.Equal(t, num, new(big.Int).SetBytes(res.ReturnedData).Int64()) + }) + }) + + // fail every other transaction with gas set too low for execution to succeed + // but high enough to pass intristic gas check, then check the updated values on the + // contract to match the last successful transaction execution + t.Run("Batch run with with failed transactions", func(t *testing.T) { + t.Parallel() + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + batchRunCode := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { + execute { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) + + log("results") + log(batchResults) + assert(batchResults.length == txs.length, message: "invalid result length") + + for i, res in batchResults { + if i %% 2 != 0 { + assert(res.status == EVM.Status.successful, message: "unexpected success status") + assert(res.errorCode == 0, message: "unexpected error code") + assert(res.errorMessage == "", message: "unexpected error msg") + } else { + assert(res.status == EVM.Status.failed, message: "unexpected failed status") + assert(res.errorCode == 400, message: "unexpected error code") + } + } + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + batchCount := 6 + var num int64 + txBytes := make([]cadence.Value, batchCount) + for i := 0; i < batchCount; i++ { + gas := uint64(100_000) + if i%2 == 0 { + // fail with too low gas limit + gas = 22_000 + } else { + // update number with only valid transactions + num = int64(i) + } + + // prepare batch of transaction payloads + tx := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + gas, + big.NewInt(0), + ) + + // build txs argument + txBytes[i] = cadence.NewArray( + unittest.BytesToCdcUInt8(tx), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + } + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txs := cadence.NewArray(txBytes). + WithType(cadence.NewVariableSizedArrayType( + stdlib.EVMTransactionBytesCadenceType, + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(batchRunCode). + SetPayer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(txs)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run(ctx, tx, snapshot) + + require.NoError(t, err) + require.NoError(t, output.Err) + //require.NotEmpty(t, state.WriteSet) + + // append the state + snapshot = snapshot.Append(state) + + // retrieve the values + retrieveCode := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "retrieve"), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + script := fvm.Script(retrieveCode).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err = vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + // make sure the retrieved value is the same as the last value + // that was stored by transaction batch + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Empty(t, res.ErrorMessage) + require.Equal(t, num, new(big.Int).SetBytes(res.ReturnedData).Int64()) + }) + }) + + // run a batch of two transactions. The sum of their gas usage would overflow an uint46 + // so the batch run should fail with an overflow error. + t.Run("Batch run evm gas overflow", func(t *testing.T) { + t.Parallel() + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + batchRunCode := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { + execute { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + batchCount := 2 + txBytes := make([]cadence.Value, batchCount) + + tx := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "storeWithLog", big.NewInt(0)), + big.NewInt(0), + uint64(200_000), + big.NewInt(1), + ) + + txBytes[0] = cadence.NewArray( + unittest.BytesToCdcUInt8(tx), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + tx = testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "storeWithLog", big.NewInt(1)), + big.NewInt(0), + math.MaxUint64-uint64(100_000), + big.NewInt(1), + ) + + txBytes[1] = cadence.NewArray( + unittest.BytesToCdcUInt8(tx), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txs := cadence.NewArray(txBytes). + WithType(cadence.NewVariableSizedArrayType( + stdlib.EVMTransactionBytesCadenceType, + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(batchRunCode). + SetPayer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(txs)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + state, output, err := vm.Run(ctx, fvm.Transaction(txBody, 0), snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains(t, output.Err, "insufficient computation") + require.Empty(t, state.WriteSet) + }) + }) +} + +func TestEVMBlockData(t *testing.T) { + t.Parallel() + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + + // query the block timestamp + code := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "blockTime"), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + script := fvm.Script(code).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Empty(t, res.ErrorMessage) + require.Equal(t, ctx.BlockHeader.Timestamp/1000, new(big.Int).SetBytes(res.ReturnedData).Uint64()) // EVM reports block time as Unix time in seconds + + }) +} + +func TestEVMAddressDeposit(t *testing.T) { + + t.Parallel() + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + + transaction(addr: [UInt8; 20]) { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage + .borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + + let minter <- admin.createNewMinter(allowedAmount: 1.0) + let vault <- minter.mintTokens(amount: 1.0) + destroy minter + + let address = EVM.EVMAddress(bytes: addr) + address.deposit(from: <-vault) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) + + addr := RandomAddress(t) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(cadence.NewArray( + unittest.BytesToCdcUInt8(addr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType))). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + execSnap, output, err := vm.Run( + ctx, + tx, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + snapshot = snapshot.Append(execSnap) + + expectedBalance := types.OneFlowBalance() + bal := getEVMAccountBalance(t, ctx, vm, snapshot, addr) + require.Equal(t, expectedBalance, bal) + + // tx executed event + txEvent := output.Events[2] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + + // deposit event + depositEvent := output.Events[3] + depEv, err := events.FlowEventToCadenceEvent(depositEvent) + require.NoError(t, err) + + depEvPayload, err := events.DecodeFLOWTokensDepositedEventPayload(depEv) + require.NoError(t, err) + + require.Equal(t, types.OneFlow(), depEvPayload.BalanceAfterInAttoFlow.Value) + + // commit block + blockEventPayload, _ := callEVMHeartBeat(t, + ctx, + vm, + snapshot) + + require.NotEmpty(t, blockEventPayload.Hash) + require.Equal(t, uint64(21000), blockEventPayload.TotalGasUsed) + + txHashes := types.TransactionHashes{txEventPayload.Hash} + require.Equal(t, + txHashes.RootHash(), + blockEventPayload.TransactionHashRoot, + ) + }) +} + +func TestCOAAddressDeposit(t *testing.T) { + t.Parallel() + + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + + access(all) + fun main() { + let admin = getAuthAccount(%s) + .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + let minter <- admin.createNewMinter(allowedAmount: 1.23) + let vault <- minter.mintTokens(amount: 1.23) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + destroy cadenceOwnedAccount + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + sc.FlowServiceAccount.Address.HexWithPrefix(), + )) + + script := fvm.Script(code) + + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + }) +} + +func TestCadenceOwnedAccountFunctionalities(t *testing.T) { + t.Parallel() + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + + t.Run("test coa setup", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + // create a flow account + flowAccount, _, snapshot := createAndFundFlowAccount( + t, + ctx, + vm, + snapshot, + ) + + var coaAddress types.Address + + initNonce := uint64(1) + // 10 Flow in UFix64 + initBalanceInUFix64 := uint64(1_000_000_000) + initBalance := types.NewBalanceFromUFix64(cadence.UFix64(initBalanceInUFix64)) + + coaAddress, snapshot = setupCOA( + t, + ctx, + vm, + snapshot, + flowAccount, + initBalanceInUFix64) + + bal := getEVMAccountBalance( + t, + ctx, + vm, + snapshot, + coaAddress) + require.Equal(t, initBalance, bal) + + nonce := getEVMAccountNonce( + t, + ctx, + vm, + snapshot, + coaAddress) + require.Equal(t, initNonce, nonce) + }) + }) + + t.Run("test coa withdraw with rounding error", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + + transaction() { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage.borrow<&FlowToken.Administrator>( + from: /storage/flowTokenAdmin + )! + + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + // since 1e10 attoFlow is the minimum withdrawable amount, + // verify any amount below 1e10 can not be withdrawn. + let bal = EVM.Balance(attoflow: 9999999999) + let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) + let balance = vault2.balance + destroy cadenceOwnedAccount + destroy vault2 + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + types.ErrWithdrawBalanceRounding.Error(), + ) + }, + ) + }) + + t.Run("test coa withdraw with minimum allowed transfer", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + transaction() { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage.borrow<&FlowToken.Administrator>( + from: /storage/flowTokenAdmin + )! + + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let bal = EVM.Balance(attoflow: 10000000000) + let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) + let balance = vault2.balance + assert(balance == 0.00000001, message: "mismatching vault balance") + destroy cadenceOwnedAccount + destroy vault2 + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + withdrawEvent := output.Events[7] + + ev, err := events.FlowEventToCadenceEvent(withdrawEvent) + require.NoError(t, err) + + evPayload, err := events.DecodeFLOWTokensWithdrawnEventPayload(ev) + require.NoError(t, err) + + // 2.34000000 - 0.00000001 = 2.33999999 + expectedBalanceAfterWithdraw := big.NewInt(2_339_999_990_000_000_000) + require.Equal(t, expectedBalanceAfterWithdraw, evPayload.BalanceAfterInAttoFlow.Value) + }, + ) + }) + + t.Run("test coa withdraw with success", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + transaction() { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage.borrow<&FlowToken.Administrator>( + from: /storage/flowTokenAdmin + )! + + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let bal = EVM.Balance(attoflow: 1230000780000000000) + let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) + let balance = vault2.balance + assert(balance == 1.23000078, message: "mismatching vault balance") + destroy cadenceOwnedAccount + destroy vault2 + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + withdrawEvent := output.Events[7] + + ev, err := events.FlowEventToCadenceEvent(withdrawEvent) + require.NoError(t, err) + + evPayload, err := events.DecodeFLOWTokensWithdrawnEventPayload(ev) + require.NoError(t, err) + + // 2.34000000 - 1.23000078 = 1.10999922 + expectedBalanceAfterWithdraw := big.NewInt(1_109_999_220_000_000_000) + require.Equal(t, expectedBalanceAfterWithdraw, evPayload.BalanceAfterInAttoFlow.Value) + }, + ) + }) + + t.Run("test coa withdraw with fraction-only amount", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + transaction() { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage.borrow<&FlowToken.Administrator>( + from: /storage/flowTokenAdmin + )! + + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let bal = EVM.Balance(attoflow: 230050780900000000) + let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) + let balance = vault2.balance + assert(balance == 0.23005078, message: "mismatching vault balance") + destroy cadenceOwnedAccount + destroy vault2 + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + withdrawEvent := output.Events[7] + + ev, err := events.FlowEventToCadenceEvent(withdrawEvent) + require.NoError(t, err) + + evPayload, err := events.DecodeFLOWTokensWithdrawnEventPayload(ev) + require.NoError(t, err) + + // 2.34000000 - 0.2300078 = 2.10994922 + expectedBalanceAfterWithdraw := big.NewInt(2_109_949_220_000_000_000) + require.Equal(t, expectedBalanceAfterWithdraw, evPayload.BalanceAfterInAttoFlow.Value) + }, + ) + }) + + t.Run("test coa withdraw with value bigger than uint256", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + transaction() { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage.borrow<&FlowToken.Administrator>( + from: /storage/flowTokenAdmin + )! + + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let bal = EVM.Balance(attoflow: 115792089237316195423570985008687907853269984665640564039457584007913129639936) + let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) + let balance = vault2.balance + assert(balance == 1.23000078, message: "mismatching vault balance") + destroy cadenceOwnedAccount + destroy vault2 + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + types.ErrInvalidBalance.Error(), + ) + }, + ) + }) + + t.Run("test coa withdraw with remainder truncation", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + transaction() { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage.borrow<&FlowToken.Administrator>( + from: /storage/flowTokenAdmin + )! + + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let bal = EVM.Balance(attoflow: 1230000789912345678) + let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) + let balance = vault2.balance + assert(balance == 1.23000078, message: "mismatching vault balance") + destroy cadenceOwnedAccount + destroy vault2 + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + withdrawEvent := output.Events[7] + + ev, err := events.FlowEventToCadenceEvent(withdrawEvent) + require.NoError(t, err) + + evPayload, err := events.DecodeFLOWTokensWithdrawnEventPayload(ev) + require.NoError(t, err) + + // 2.34000000 - 1.23000078 = 1.10999922 + expectedBalanceAfterWithdraw := big.NewInt(1_109_999_220_000_000_000) + require.Equal(t, expectedBalanceAfterWithdraw, evPayload.BalanceAfterInAttoFlow.Value) + }, + ) + }) + + t.Run("test coa transfer", func(t *testing.T) { + t.Parallel() + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + + access(all) fun main(address: [UInt8; 20]): UFix64 { let admin = getAuthAccount(%s) .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! - let minter <- admin.createNewMinter(allowedAmount: 2.34) - let vault <- minter.mintTokens(amount: 2.34) - destroy minter + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + + let recipientEVMAddress = EVM.EVMAddress(bytes: address) + + let res = cadenceOwnedAccount.call( + to: recipientEVMAddress, + data: [], + gasLimit: 100_000, + value: bal, + ) + + assert(res.status == EVM.Status.successful, message: "transfer call was not successful") + + destroy cadenceOwnedAccount + return recipientEVMAddress.balance().inFLOW() + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + sc.FlowServiceAccount.Address.HexWithPrefix(), + )) + + addr := cadence.NewArray( + unittest.BytesToCdcUInt8(RandomAddress(t).Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + script := fvm.Script(code).WithArguments( + json.MustEncode(addr), + ) + + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + require.Equal(t, uint64(123000000), uint64(output.Value.(cadence.UFix64))) + }) + }) + + t.Run("test coa deposit and withdraw in a single transaction", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + + access(all) + fun main(): UFix64 { + let admin = getAuthAccount(%s) + .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) + let balance = vault2.balance + destroy cadenceOwnedAccount + destroy vault2 + + return balance + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + sc.FlowServiceAccount.Address.HexWithPrefix(), + )) + + script := fvm.Script(code) + + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + }) + }) + + t.Run("test coa deploy", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + + access(all) + fun main(code: [UInt8]): EVM.Result { + let admin = getAuthAccount(%s) + .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + + let res = cadenceOwnedAccount.deploy( + code: code, + gasLimit: 2_000_000, + value: EVM.Balance(attoflow: 1230000000000000000) + ) + destroy cadenceOwnedAccount + return res + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + sc.FlowServiceAccount.Address.HexWithPrefix(), + )) + + script := fvm.Script(code). + WithArguments(json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.ByteCode), + ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), + )) + + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Empty(t, res.ErrorMessage) + require.NotNil(t, res.DeployedContractAddress) + // we strip away first few bytes because they contain deploy code + require.Equal(t, testContract.ByteCode[17:], []byte(res.ReturnedData)) + }) + }) + + t.Run("test coa dryCall", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: auth(Storage) &Account ) { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + account.storage.save(<- cadenceOwnedAccount, to: /storage/evmCOA) + + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + num := int64(42) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Len(t, output.Events, 3) + assert.Len(t, state.UpdatedRegisterIDs(), 13) + assert.Equal( + t, + flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), + output.Events[0].Type, + ) + assert.Equal( + t, + flow.EventType("A.f8d6e0586b0a20c7.EVM.CadenceOwnedAccountCreated"), + output.Events[1].Type, + ) + assert.Equal( + t, + flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), + output.Events[2].Type, + ) + snapshot = snapshot.Append(state) + + code = []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt){ + prepare(account: auth(Storage) &Account) { + let coa = account.storage.borrow<&EVM.CadenceOwnedAccount>( + from: /storage/evmCOA + ) ?? panic("could not borrow COA reference!") + let res = coa.dryCall( + to: EVM.addressFromString(to), + data: data, + gasLimit: gasLimit, + value: EVM.Balance(attoflow: value) + ) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + + let values = EVM.decodeABI(types: [Type()], data: res.data) + assert(values.length == 1) + + let number = values[0] as! UInt256 + assert(number == 42, message: String.encodeHex(res.data)) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + data := json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.MakeCallData(t, "retrieve")), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ) + toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) + require.NoError(t, err) + to := json.MustEncode(toAddress) + + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(data). + AddArgument(to). + AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). + AddArgument(json.MustEncode(cadence.NewUInt(0))). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + + state, output, err = vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Len(t, output.Events, 0) + assert.Len(t, state.UpdatedRegisterIDs(), 0) + }) + }) + + t.Run("test coa dryCallWithSigAndArgs", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: auth(Storage) &Account ) { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + account.storage.save(<- cadenceOwnedAccount, to: /storage/evmCOA) + + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + num := int64(42) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Len(t, output.Events, 3) + assert.Len(t, state.UpdatedRegisterIDs(), 13) + assert.Equal( + t, + flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), + output.Events[0].Type, + ) + assert.Equal( + t, + flow.EventType("A.f8d6e0586b0a20c7.EVM.CadenceOwnedAccountCreated"), + output.Events[1].Type, + ) + assert.Equal( + t, + flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), + output.Events[2].Type, + ) + snapshot = snapshot.Append(state) + + code = []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(signature: String, args: [AnyStruct], to: String, gasLimit: UInt64, value: UInt){ + prepare(account: auth(Storage) &Account) { + let coa = account.storage.borrow<&EVM.CadenceOwnedAccount>( + from: /storage/evmCOA + ) ?? panic("could not borrow COA reference!") + let res = coa.dryCallWithSigAndArgs( + to: EVM.addressFromString(to), + signature: signature, + args: args, + gasLimit: gasLimit, + value: value, + resultTypes: [Type()], + ) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + + assert(res.results!.length == 1) + + let number = res.results![0] as! UInt256 + assert(number == 42, message: number.toString()) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + signatureValue, err := cadence.NewString("retrieve()") + require.NoError(t, err) + signature := json.MustEncode(signatureValue) + + args := json.MustEncode(cadence.NewArray(nil)) + + toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) + require.NoError(t, err) + to := json.MustEncode(toAddress) + + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(signature). + AddArgument(args). + AddArgument(to). + AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). + AddArgument(json.MustEncode(cadence.NewUInt(0))). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + + state, output, err = vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Len(t, output.Events, 0) + assert.Len(t, state.UpdatedRegisterIDs(), 0) + }) + }) + + t.Run("test coa deploy with max gas limit cap", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + access(all) + fun main(code: [UInt8]): EVM.Result { + let admin = getAuthAccount(%s) + .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + let res = cadenceOwnedAccount.deploy( + code: code, + gasLimit: 16_777_216, + value: EVM.Balance(attoflow: 1230000000000000000) + ) + destroy cadenceOwnedAccount + return res + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + sc.FlowServiceAccount.Address.HexWithPrefix(), + )) + + script := fvm.Script(code). + WithArguments(json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.ByteCode), + ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), + )) + + _, output, err := vm.Run( + ctx, + script, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Empty(t, res.ErrorMessage) + require.NotNil(t, res.DeployedContractAddress) + // we strip away first few bytes because they contain deploy code + require.Equal(t, testContract.ByteCode[17:], []byte(res.ReturnedData)) + }) + }) + + t.Run("test coa deploy with bigger than max gas limit cap", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + access(all) + fun main(code: [UInt8]): EVM.Result { + let admin = getAuthAccount(%s) + .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + cadenceOwnedAccount.deposit(from: <-vault) + let res = cadenceOwnedAccount.deploy( + code: code, + gasLimit: 16_777_226, + value: EVM.Balance(attoflow: 1230000000000000000) + ) + destroy cadenceOwnedAccount + return res + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + sc.FlowServiceAccount.Address.HexWithPrefix(), + )) + + script := fvm.Script(code). + WithArguments(json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.ByteCode), + ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), + )) + + _, output, err := vm.Run( + ctx, + script, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusInvalid, res.Status) + require.Equal(t, types.ValidationErrCodeMisc, res.ErrorCode) + require.Equal( + t, + "transaction gas limit too high (cap: 16777216, tx: 16777226)", + res.ErrorMessage, + ) + require.Nil(t, res.DeployedContractAddress) + // we strip away first few bytes because they contain deploy code + require.Empty(t, []byte(res.ReturnedData)) + }) + }) +} + +func TestDryRun(t *testing.T) { + t.Parallel() + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + evmAddress := sc.EVMContract.Address.HexWithPrefix() + + dryRunTx := func( + t *testing.T, + tx *gethTypes.Transaction, + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + ) *types.ResultSummary { + code := []byte(fmt.Sprintf(` + import EVM from %s + + access(all) + fun main(tx: [UInt8]): EVM.Result { + return EVM.dryRun( + tx: tx, + from: EVM.EVMAddress(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) + ) + }`, + evmAddress, + )) + + innerTxBytes, err := tx.MarshalBinary() + require.NoError(t, err) + + script := fvm.Script(code).WithArguments( + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ), + ) + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + result, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + return result + } + + // this test checks that gas limit is correctly used and gas usage correctly reported + t.Run("test dry run storing a value with different gas limits", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + data := testContract.MakeCallData(t, "store", big.NewInt(1337)) + + // EVM.dryRun must not be limited by the `gethParams.MaxTxGas` + limit := gethParams.MaxTxGas + 1_000 + tx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + limit, + big.NewInt(0), + data, + ) + result := dryRunTx(t, tx, ctx, vm, snapshot) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + require.Less(t, result.GasConsumed, limit) + + // gas limit too low, but still bigger than intrinsic gas value + limit = uint64(24_216) + tx = gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + limit, + big.NewInt(0), + data, + ) + result = dryRunTx(t, tx, ctx, vm, snapshot) + require.Equal(t, types.ExecutionErrCodeOutOfGas, result.ErrorCode) + require.Equal(t, types.StatusFailed, result.Status) + require.Equal(t, result.GasConsumed, limit) // burn it all!!! + }) + }) + + t.Run("test dry run store current value", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + data := testContract.MakeCallData(t, "store", big.NewInt(0)) + tx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + data, + ) + dryRunResult := dryRunTx(t, tx, ctx, vm, snapshot) + + require.Equal(t, types.ErrCodeNoError, dryRunResult.ErrorCode) + require.Equal(t, types.StatusSuccessful, dryRunResult.Status) + require.Greater(t, dryRunResult.GasConsumed, uint64(0)) + + code := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + evmAddress, + )) + + // Use the gas estimation from Evm.dryRun with some buffer + gasLimit := dryRunResult.GasConsumed + gethParams.SstoreSentryGasEIP2200 + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + data, + big.NewInt(0), + gasLimit, + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + script := fvm.Script(code).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err := vm.Run( + ctx, + script, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Equal(t, res.GasConsumed, dryRunResult.GasConsumed) + }) + }) + + t.Run("test dry run store new value", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + num := int64(12) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + _, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + data := testContract.MakeCallData(t, "store", big.NewInt(100)) + tx1 := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + data, + ) + dryRunResult := dryRunTx(t, tx1, ctx, vm, snapshot) + + require.Equal(t, types.ErrCodeNoError, dryRunResult.ErrorCode) + require.Equal(t, types.StatusSuccessful, dryRunResult.Status) + require.Greater(t, dryRunResult.GasConsumed, uint64(0)) + + code = []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + evmAddress, + )) + + // Decrease nonce because we are Cadence using scripts, and not + // transactions, which means that no state change is happening. + testAccount.SetNonce(testAccount.Nonce() - 1) + innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + data, + big.NewInt(0), + dryRunResult.GasConsumed, // use the gas estimation from Evm.dryRun + big.NewInt(0), + ) + + innerTx = cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase = cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + script := fvm.Script(code).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err = vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Equal(t, res.GasConsumed, dryRunResult.GasConsumed) + }) + }) + + t.Run("test dry run clear current value", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + num := int64(100) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + snapshot = snapshot.Append(state) + + data := testContract.MakeCallData(t, "store", big.NewInt(0)) + tx1 := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + data, + ) + dryRunResult := dryRunTx(t, tx1, ctx, vm, snapshot) + + require.Equal(t, types.ErrCodeNoError, dryRunResult.ErrorCode) + require.Equal(t, types.StatusSuccessful, dryRunResult.Status) + require.Greater(t, dryRunResult.GasConsumed, uint64(0)) + + code = []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + evmAddress, + )) + + // use the gas estimation from Evm.dryRun with the necessary buffer gas + gasLimit := dryRunResult.GasConsumed + gethParams.SstoreClearsScheduleRefundEIP3529 + innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + data, + big.NewInt(0), + gasLimit, + big.NewInt(0), + ) + + innerTx = cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase = cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + script := fvm.Script(code).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err = vm.Run( + ctx, + script, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + require.Equal(t, res.GasConsumed, dryRunResult.GasConsumed) + }) + }) + + // this test makes sure the dry-run that updates the value on the contract + // doesn't persist the change, and after when the value is read it isn't updated. + t.Run("test dry run for any side-effects", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + updatedValue := int64(1337) + data := testContract.MakeCallData(t, "store", big.NewInt(updatedValue)) + tx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(1000000), + big.NewInt(0), + data, + ) + + result := dryRunTx(t, tx, ctx, vm, snapshot) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + + // query the value make sure it's not updated + code := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + evmAddress, + )) + + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "retrieve"), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + script := fvm.Script(code).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + // make sure the value we used in the dry-run is not the same as the value stored in contract + require.NotEqual(t, updatedValue, new(big.Int).SetBytes(res.ReturnedData).Int64()) + }) + }) + + t.Run("test dry run contract deployment", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + tx := gethTypes.NewContractCreation( + 0, + big.NewInt(0), + uint64(10_000_000), + big.NewInt(0), + testContract.ByteCode, + ) + + result := dryRunTx(t, tx, ctx, vm, snapshot) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + require.NotNil(t, result.ReturnedData) + require.NotNil(t, result.DeployedContractAddress) + require.NotEmpty(t, result.DeployedContractAddress.String()) + }) + }) + + t.Run("test dry run validation error", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + tx := gethTypes.NewContractCreation( + 0, + big.NewInt(100), // more than available + uint64(1000000), + big.NewInt(0), + nil, + ) + + result := dryRunTx(t, tx, ctx, vm, snapshot) + assert.Equal(t, types.ValidationErrCodeInsufficientFunds, result.ErrorCode) + assert.Equal(t, types.StatusInvalid, result.Status) + assert.Equal(t, types.InvalidTransactionGasCost, int(result.GasConsumed)) + }) + }) + + t.Run("test EVM.dryRun with insufficient computation limit", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(tx: [UInt8], fromBytes: [UInt8; 20]) { + prepare(account: &Account) { + let from = EVM.EVMAddress(bytes: fromBytes) + let res = EVM.dryRun(tx: tx, from: from) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + num := int64(100) + evmTx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(25_000_000), + big.NewInt(0), + testContract.MakeCallData(t, "store", big.NewInt(num)), + ) + innerTxBytes, err := evmTx.MarshalBinary() + require.NoError(t, err) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + from := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(from)). + SetComputeLimit(250). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + _, output, err := vm.Run(ctx, tx, snapshot) + + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains(t, output.Err, "insufficient computation") + }, + ) + }) + + t.Run("test EVM.dryRun is properly metered", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(tx: [UInt8], fromBytes: [UInt8; 20], iterations: UInt) { + prepare(account: &Account) { + let from = EVM.EVMAddress(bytes: fromBytes) + var i = UInt(0) + while i < iterations { + let res = EVM.dryRun(tx: tx, from: from) + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + i = i + 1 + } + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + num := int64(100) + evmTx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + testContract.MakeCallData(t, "store", big.NewInt(num)), + ) + innerTxBytes, err := evmTx.MarshalBinary() + require.NoError(t, err) - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - cadenceOwnedAccount.deposit(from: <-vault) + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) - let bal = EVM.Balance(attoflow: 0) - bal.setFLOW(flow: 1.23) + from := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) - let recipientEVMAddress = EVM.EVMAddress(bytes: address) + iterations := cadence.NewUInt(5) - let res = cadenceOwnedAccount.call( - to: recipientEVMAddress, - data: [], - gasLimit: 100_000, - value: bal, - ) + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(from)). + AddArgument(json.MustEncode(iterations)). + SetComputeLimit(1_000). + Build() + require.NoError(t, err) - assert(res.status == EVM.Status.successful, message: "transfer call was not successful") + tx := fvm.Transaction(txBody, 0) + _, output, err := vm.Run(ctx, tx, snapshot) - destroy cadenceOwnedAccount - return recipientEVMAddress.balance().inFLOW() - } - `, - sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - sc.FlowServiceAccount.Address.HexWithPrefix(), - )) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Equal(t, uint64(28), output.ComputationUsed) - addr := cadence.NewArray( - unittest.BytesToCdcUInt8(RandomAddress(t).Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + // Increase call count of EVM.dryRun to 15 + iterations = cadence.NewUInt(15) + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(from)). + AddArgument(json.MustEncode(iterations)). + SetComputeLimit(1_000). + Build() + require.NoError(t, err) - script := fvm.Script(code).WithArguments( - json.MustEncode(addr), - ) + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) - _, output, err := vm.Run( - ctx, - script, - snapshot) require.NoError(t, err) require.NoError(t, output.Err) - - require.Equal(t, uint64(123000000), uint64(output.Value.(cadence.UFix64))) - }) + assert.Equal(t, uint64(81), output.ComputationUsed) + }, + ) }) - t.Run("test coa deposit and withdraw in a single transaction", func(t *testing.T) { + // Regression test: dryRun reads the block proposal into the cache. A subsequent + // EVM.run in the same Cadence transaction must still see a clean proposal (not + // one tainted by the dry-run read) and complete successfully. + t.Run("test EVM.dryRun followed by EVM.run in same transaction", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -1744,50 +4032,141 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := []byte(fmt.Sprintf( - ` - import EVM from %s - import FlowToken from %s + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - access(all) - fun main(): UFix64 { - let admin = getAuthAccount(%s) - .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + data := testContract.MakeCallData(t, "store", big.NewInt(42)) - let minter <- admin.createNewMinter(allowedAmount: 2.34) - let vault <- minter.mintTokens(amount: 2.34) - destroy minter + // The dry-run tx uses nonce 0 (doesn't consume it). + dryTx := gethTypes.NewTransaction( + testAccount.Nonce(), + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + data, + ) + dryTxBytes, err := dryTx.MarshalBinary() + require.NoError(t, err) - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - cadenceOwnedAccount.deposit(from: <-vault) + // The real tx is signed and uses the same nonce. + realTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + data, + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + ) - let bal = EVM.Balance(attoflow: 0) - bal.setFLOW(flow: 1.23) - let vault2 <- cadenceOwnedAccount.withdraw(balance: bal) - let balance = vault2.balance - destroy cadenceOwnedAccount - destroy vault2 + code := []byte(fmt.Sprintf(` + import EVM from %s - return balance - } - `, - sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - sc.FlowServiceAccount.Address.HexWithPrefix(), - )) + transaction(dryTx: [UInt8], realTx: [UInt8], coinbaseBytes: [UInt8; 20]) { + prepare(account: &Account) { + let from = EVM.EVMAddress(bytes: coinbaseBytes) + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - script := fvm.Script(code) + let dryResult = EVM.dryRun(tx: dryTx, from: from) + assert(dryResult.status == EVM.Status.successful, message: "dry run failed") - _, output, err := vm.Run( - ctx, - script, - snapshot) + let runResult = EVM.run(tx: realTx, coinbase: coinbase) + assert(runResult.status == EVM.Status.successful, message: "run after dry run failed") + } + } + `, sc.EVMContract.Address.HexWithPrefix())) + + dryTxArg := cadence.NewArray( + unittest.BytesToCdcUInt8(dryTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + realTxArg := cadence.NewArray( + unittest.BytesToCdcUInt8(realTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(dryTxArg)). + AddArgument(json.MustEncode(realTxArg)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + _, output, err := vm.Run(ctx, tx, snapshot) require.NoError(t, err) require.NoError(t, output.Err) - }) + assert.Equal(t, uint64(15), output.ComputationUsed) + }, + ) }) +} - t.Run("test coa deploy", func(t *testing.T) { +func TestDryCall(t *testing.T) { + t.Parallel() + + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + evmAddress := sc.EVMContract.Address.HexWithPrefix() + + dryCall := func( + t *testing.T, + tx *gethTypes.Transaction, + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + ) (*types.ResultSummary, *snapshot.ExecutionSnapshot) { + code := []byte(fmt.Sprintf(` + import EVM from %s + + access(all) + fun main(data: [UInt8], to: String, gasLimit: UInt64, value: UInt): EVM.Result { + return EVM.dryCall( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + to: EVM.addressFromString(to), + data: data, + gasLimit: gasLimit, + value: EVM.Balance(attoflow: value) + ) + }`, + evmAddress, + )) + + require.NotNil(t, tx.To()) + to := tx.To().Hex() + toAddress, err := cadence.NewString(to) + require.NoError(t, err) + + script := fvm.Script(code).WithArguments( + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(tx.Data()), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ), + json.MustEncode(toAddress), + json.MustEncode(cadence.NewUInt64(tx.Gas())), + json.MustEncode(cadence.NewUInt(uint(tx.Value().Uint64()))), + ) + execSnapshot, output, err := vm.Run( + ctx, + script, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + require.Len(t, output.Events, 0) + + result, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + return result, execSnapshot + } + + // this test checks that gas limit is correctly used and gas usage correctly reported + t.Run("test dryCall with different gas limits", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -1796,62 +4175,57 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - code := []byte(fmt.Sprintf( - ` - import EVM from %s - import FlowToken from %s - - access(all) - fun main(code: [UInt8]): EVM.Result { - let admin = getAuthAccount(%s) - .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! - let minter <- admin.createNewMinter(allowedAmount: 2.34) - let vault <- minter.mintTokens(amount: 2.34) - destroy minter - - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - cadenceOwnedAccount.deposit(from: <-vault) - - let res = cadenceOwnedAccount.deploy( - code: code, - gasLimit: 2_000_000, - value: EVM.Balance(attoflow: 1230000000000000000) - ) - destroy cadenceOwnedAccount - return res - } - `, - sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - sc.FlowServiceAccount.Address.HexWithPrefix(), - )) + data := testContract.MakeCallData(t, "store", big.NewInt(1337)) - script := fvm.Script(code). - WithArguments(json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testContract.ByteCode), - ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), - )) + limit := uint64(50_000) + tx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + limit, + big.NewInt(0), + data, + ) + result, _ := dryCall(t, tx, ctx, vm, snapshot) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + require.Less(t, result.GasConsumed, limit) - _, output, err := vm.Run( - ctx, - script, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) + // gas limit too low, but still bigger than intrinsic gas value + limit = uint64(24_216) + tx = gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + limit, + big.NewInt(0), + data, + ) + result, _ = dryCall(t, tx, ctx, vm, snapshot) + require.Equal(t, types.ExecutionErrCodeOutOfGas, result.ErrorCode) + require.Equal(t, types.StatusFailed, result.Status) + require.Equal(t, result.GasConsumed, limit) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) - require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Empty(t, res.ErrorMessage) - require.NotNil(t, res.DeployedContractAddress) - // we strip away first few bytes because they contain deploy code - require.Equal(t, testContract.ByteCode[17:], []byte(res.ReturnedData)) + // EVM.dryCall must not be limited to `gethParams.MaxTxGas` + limit = gethParams.MaxTxGas + 1_000 + tx = gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + limit, + big.NewInt(0), + data, + ) + result, _ = dryCall(t, tx, ctx, vm, snapshot) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + require.Less(t, result.GasConsumed, limit) }) }) - t.Run("test coa dryCall", func(t *testing.T) { + t.Run("test dryCall does not form EVM transactions", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -1866,10 +4240,7 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { import EVM from %s transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ - prepare(account: auth(Storage) &Account ) { - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - account.storage.save(<- cadenceOwnedAccount, to: /storage/evmCOA) - + prepare(account: &Account) { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) let res = EVM.run(tx: tx, coinbase: coinbase) @@ -1916,35 +4287,217 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { ) require.NoError(t, err) require.NoError(t, output.Err) - assert.Len(t, output.Events, 3) - assert.Len(t, state.UpdatedRegisterIDs(), 13) + assert.Len(t, output.Events, 1) + assert.Len(t, state.UpdatedRegisterIDs(), 4) assert.Equal( t, flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), output.Events[0].Type, ) - assert.Equal( - t, - flow.EventType("A.f8d6e0586b0a20c7.EVM.CadenceOwnedAccountCreated"), - output.Events[1].Type, - ) - assert.Equal( - t, - flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), - output.Events[2].Type, - ) snapshot = snapshot.Append(state) code = []byte(fmt.Sprintf( ` import EVM from %s - transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt){ - prepare(account: auth(Storage) &Account) { - let coa = account.storage.borrow<&EVM.CadenceOwnedAccount>( - from: /storage/evmCOA - ) ?? panic("could not borrow COA reference!") - let res = coa.dryCall( + transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt){ + prepare(account: &Account) { + let res = EVM.dryCall( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + to: EVM.addressFromString(to), + data: data, + gasLimit: gasLimit, + value: EVM.Balance(attoflow: value) + ) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + + let values = EVM.decodeABI(types: [Type()], data: res.data) + assert(values.length == 1) + + let number = values[0] as! UInt256 + assert(number == 42, message: String.encodeHex(res.data)) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + data := json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.MakeCallData(t, "retrieve")), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ) + toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) + require.NoError(t, err) + to := json.MustEncode(toAddress) + + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(data). + AddArgument(to). + AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). + AddArgument(json.MustEncode(cadence.NewUInt(0))). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + + state, output, err = vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Len(t, output.Events, 0) + assert.Len(t, state.UpdatedRegisterIDs(), 0) + }) + }) + + // this test makes sure the dryCall that updates the value on the contract + // doesn't persist the change, and after when the value is read it isn't updated. + t.Run("test dryCall has no side-effects", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + updatedValue := int64(1337) + data := testContract.MakeCallData(t, "store", big.NewInt(updatedValue)) + tx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(1000000), + big.NewInt(0), + data, + ) + + result, state := dryCall(t, tx, ctx, vm, snapshot) + require.Len(t, state.UpdatedRegisterIDs(), 0) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + + // query the value make sure it's not updated + code := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + evmAddress, + )) + + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "retrieve"), + big.NewInt(0), + uint64(100_000), + big.NewInt(0), + ) + + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + script := fvm.Script(code).WithArguments( + json.MustEncode(innerTx), + json.MustEncode(coinbase), + ) + + state, output, err := vm.Run( + ctx, + script, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + require.Len(t, state.UpdatedRegisterIDs(), 0) + + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + require.Equal(t, types.StatusSuccessful, res.Status) + require.Equal(t, types.ErrCodeNoError, res.ErrorCode) + // make sure the value we used in the dryCall is not the same as the value stored in contract + require.NotEqual(t, updatedValue, new(big.Int).SetBytes(res.ReturnedData).Int64()) + }) + }) + + t.Run("test dryCall validation error", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + data := testContract.MakeCallData(t, "store", big.NewInt(10337)) + tx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(1000), // more than available + uint64(35_000), + big.NewInt(0), + data, + ) + + result, _ := dryCall(t, tx, ctx, vm, snapshot) + assert.Equal(t, types.ValidationErrCodeInsufficientFunds, result.ErrorCode) + assert.Equal(t, types.StatusInvalid, result.Status) + assert.Equal(t, types.InvalidTransactionGasCost, int(result.GasConsumed)) + + // random function selector + data = []byte{254, 234, 101, 199} + tx = gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(25_000), + big.NewInt(0), + data, + ) + + result, _ = dryCall(t, tx, ctx, vm, snapshot) + assert.Equal(t, types.ExecutionErrCodeExecutionReverted, result.ErrorCode) + assert.Equal(t, types.StatusFailed, result.Status) + assert.Equal(t, uint64(21331), result.GasConsumed) + }) + }) + + t.Run("test EVM.dryCall with insufficient computation limit", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt) { + prepare(account: &Account) { + let res = EVM.dryCall( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), to: EVM.addressFromString(to), data: data, gasLimit: gasLimit, @@ -1953,53 +4506,52 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { assert(res.status == EVM.Status.successful, message: "unexpected status") assert(res.errorCode == 0, message: "unexpected error code") - - let values = EVM.decodeABI(types: [Type()], data: res.data) - assert(values.length == 1) - - let number = values[0] as! UInt256 - assert(number == 42, message: String.encodeHex(res.data)) } } `, sc.EVMContract.Address.HexWithPrefix(), )) - data := json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testContract.MakeCallData(t, "retrieve")), - ).WithType(stdlib.EVMTransactionBytesCadenceType), + num := int64(100) + evmTx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(25_000_000), + big.NewInt(0), + testContract.MakeCallData(t, "store", big.NewInt(num)), ) - toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) + + toAddress, err := cadence.NewString(evmTx.To().Hex()) require.NoError(t, err) - to := json.MustEncode(toAddress) - txBody, err = flow.NewTransactionBodyBuilder(). + callData := cadence.NewArray( + unittest.BytesToCdcUInt8(evmTx.Data()), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(data). - AddArgument(to). - AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). - AddArgument(json.MustEncode(cadence.NewUInt(0))). + AddArgument(json.MustEncode(callData)). + AddArgument(json.MustEncode(toAddress)). + AddArgument(json.MustEncode(cadence.NewUInt64(evmTx.Gas()))). + AddArgument(json.MustEncode(cadence.NewUInt(uint(evmTx.Value().Uint64())))). + SetComputeLimit(250). Build() require.NoError(t, err) - tx = fvm.Transaction(txBody, 0) + tx := fvm.Transaction(txBody, 0) + _, output, err := vm.Run(ctx, tx, snapshot) - state, output, err = vm.Run( - ctx, - tx, - snapshot, - ) require.NoError(t, err) - require.NoError(t, output.Err) - assert.Len(t, output.Events, 0) - assert.Len(t, state.UpdatedRegisterIDs(), 0) - }) + require.Error(t, output.Err) + require.ErrorContains(t, output.Err, "insufficient computation") + }, + ) }) - t.Run("test coa deploy with max gas limit cap", func(t *testing.T) { + t.Run("test EVM.dryCall is properly metered", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2008,176 +4560,299 @@ func TestCadenceOwnedAccountFunctionalities(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) code := []byte(fmt.Sprintf( ` import EVM from %s - import FlowToken from %s - access(all) - fun main(code: [UInt8]): EVM.Result { - let admin = getAuthAccount(%s) - .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! - let minter <- admin.createNewMinter(allowedAmount: 2.34) - let vault <- minter.mintTokens(amount: 2.34) - destroy minter - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - cadenceOwnedAccount.deposit(from: <-vault) - let res = cadenceOwnedAccount.deploy( - code: code, - gasLimit: 16_777_216, - value: EVM.Balance(attoflow: 1230000000000000000) - ) - destroy cadenceOwnedAccount - return res + + transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt, iterations: UInt) { + prepare(account: &Account) { + var i = UInt(0) + while i < iterations { + let res = EVM.dryCall( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + to: EVM.addressFromString(to), + data: data, + gasLimit: gasLimit, + value: EVM.Balance(attoflow: value) + ) + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + i = i + 1 + } + } } `, sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - sc.FlowServiceAccount.Address.HexWithPrefix(), )) - script := fvm.Script(code). - WithArguments(json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testContract.ByteCode), - ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), - )) - - _, output, err := vm.Run( - ctx, - script, - snapshot, + num := int64(100) + evmTx := gethTypes.NewTransaction( + 0, + testContract.DeployedAt.ToCommon(), + big.NewInt(0), + uint64(50_000), + big.NewInt(0), + testContract.MakeCallData(t, "store", big.NewInt(num)), ) + + toAddress, err := cadence.NewString(evmTx.To().Hex()) + require.NoError(t, err) + + callData := cadence.NewArray( + unittest.BytesToCdcUInt8(evmTx.Data()), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + iterations := cadence.NewUInt(5) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(callData)). + AddArgument(json.MustEncode(toAddress)). + AddArgument(json.MustEncode(cadence.NewUInt64(evmTx.Gas()))). + AddArgument(json.MustEncode(cadence.NewUInt(uint(evmTx.Value().Uint64())))). + AddArgument(json.MustEncode(iterations)). + SetComputeLimit(1_000). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + _, output, err := vm.Run(ctx, tx, snapshot) + require.NoError(t, err) require.NoError(t, output.Err) + assert.Equal(t, uint64(36), output.ComputationUsed) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + // Increase call count of EVM.dryCall to 15 + iterations = cadence.NewUInt(15) + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(callData)). + AddArgument(json.MustEncode(toAddress)). + AddArgument(json.MustEncode(cadence.NewUInt64(evmTx.Gas()))). + AddArgument(json.MustEncode(cadence.NewUInt(uint(evmTx.Value().Uint64())))). + AddArgument(json.MustEncode(iterations)). + SetComputeLimit(1_000). + Build() require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Empty(t, res.ErrorMessage) - require.NotNil(t, res.DeployedContractAddress) - // we strip away first few bytes because they contain deploy code - require.Equal(t, testContract.ByteCode[17:], []byte(res.ReturnedData)) - }) + + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Equal(t, uint64(105), output.ComputationUsed) + }, + ) }) +} - t.Run("test coa deploy with bigger than max gas limit cap", func(t *testing.T) { - RunWithNewEnvironment(t, - chain, func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { - code := []byte(fmt.Sprintf( - ` - import EVM from %s - import FlowToken from %s - access(all) - fun main(code: [UInt8]): EVM.Result { - let admin = getAuthAccount(%s) - .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! - let minter <- admin.createNewMinter(allowedAmount: 2.34) - let vault <- minter.mintTokens(amount: 2.34) +func TestDryCallCacheInvalidationAfterDeposit(t *testing.T) { + t.Parallel() + + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + addr := RandomAddress(t) + + checkBalanceZeroData := testContract.MakeCallData(t, "checkBalance", addr.ToCommon(), big.NewInt(0)) + oneFlow := new(big.Int).SetUint64(1e18) + checkBalanceOneFlowData := testContract.MakeCallData(t, "checkBalance", addr.ToCommon(), oneFlow) + + code := []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s + + transaction( + depositAddrBytes: [UInt8; 20], + contractAddrBytes: [UInt8; 20], + checkBalanceZeroData: [UInt8], + checkBalanceOneFlowData: [UInt8], + ) { + prepare(account: auth(BorrowValue) &Account) { + let depositAddr = EVM.EVMAddress(bytes: depositAddrBytes) + let contractAddr = EVM.EVMAddress(bytes: contractAddrBytes) + + // 1. checkBalance(addr, 0) — cache miss, executes on contract + var res = EVM.dryCall( + from: depositAddr, + to: contractAddr, + data: checkBalanceZeroData, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) + assert(res.status == EVM.Status.successful, message: "step 1 failed") + + // 2. checkBalance(addr, 0) — cache hit (same key) + res = EVM.dryCall( + from: depositAddr, + to: contractAddr, + data: checkBalanceZeroData, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) + assert(res.status == EVM.Status.successful, message: "step 2 failed") + + // Mint FLOW + let admin = account.storage + .borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + let minter <- admin.createNewMinter(allowedAmount: 1.0) + let vault <- minter.mintTokens(amount: 1.0) destroy minter - let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - cadenceOwnedAccount.deposit(from: <-vault) - let res = cadenceOwnedAccount.deploy( - code: code, - gasLimit: 16_777_226, - value: EVM.Balance(attoflow: 1230000000000000000) + + // 3. Deposit FLOW to addr (invalidates cache) + depositAddr.deposit(from: <-vault) + + // 4. checkBalance(addr, 0) — must be cache miss (not stale hit), + // re-executes and reverts because balance is now 1 FLOW + res = EVM.dryCall( + from: depositAddr, + to: contractAddr, + data: checkBalanceZeroData, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) ) - destroy cadenceOwnedAccount - return res + assert(res.status == EVM.Status.failed, message: "step 4: stale cache returned success for zero balance after deposit") + + // 5. checkBalance(addr, 1 FLOW) — cache miss, succeeds with updated balance + res = EVM.dryCall( + from: depositAddr, + to: contractAddr, + data: checkBalanceOneFlowData, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) + assert(res.status == EVM.Status.successful, message: "step 5 failed") + + // 6. checkBalance(addr, 1 FLOW) — cache hit + res = EVM.dryCall( + from: depositAddr, + to: contractAddr, + data: checkBalanceOneFlowData, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) + assert(res.status == EVM.Status.successful, message: "step 6 failed") } - `, - sc.EVMContract.Address.HexWithPrefix(), - sc.FlowToken.Address.HexWithPrefix(), - sc.FlowServiceAccount.Address.HexWithPrefix(), - )) - - script := fvm.Script(code). - WithArguments(json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testContract.ByteCode), - ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), - )) + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) - _, output, err := vm.Run( - ctx, - script, - snapshot, - ) - require.NoError(t, err) - require.NoError(t, output.Err) + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(cadence.NewArray( + unittest.BytesToCdcUInt8(addr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType))). + AddArgument(json.MustEncode(cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.DeployedAt.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType))). + AddArgument(json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(checkBalanceZeroData), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + )). + AddArgument(json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(checkBalanceOneFlowData), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + )). + Build() + require.NoError(t, err) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) - require.NoError(t, err) - require.Equal(t, types.StatusInvalid, res.Status) - require.Equal(t, types.ValidationErrCodeMisc, res.ErrorCode) - require.Equal( - t, - "transaction gas limit too high (cap: 16777216, tx: 16777226)", - res.ErrorMessage, - ) - require.Nil(t, res.DeployedContractAddress) - // we strip away first few bytes because they contain deploy code - require.Empty(t, []byte(res.ReturnedData)) - }) - }) + tx := fvm.Transaction(txBody, 0) + _, output, err := vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + }) } -func TestDryRun(t *testing.T) { +func TestDryCallWithSigAndArgs(t *testing.T) { t.Parallel() + chain := flow.Emulator.Chain() sc := systemcontracts.SystemContractsForChain(chain.ChainID()) evmAddress := sc.EVMContract.Address.HexWithPrefix() - dryRunTx := func( + dryCallWithSigAndArgs := func( t *testing.T, - tx *gethTypes.Transaction, + signature string, + args []cadence.Value, + to common.Address, + gas uint64, + value uint, ctx fvm.Context, vm fvm.VM, snapshot snapshot.SnapshotTree, - ) *types.ResultSummary { + ) (*ResultDecoded, *snapshot.ExecutionSnapshot) { code := []byte(fmt.Sprintf(` - import EVM from %s + import EVM from %s - access(all) - fun main(tx: [UInt8]): EVM.Result { - return EVM.dryRun( - tx: tx, - from: EVM.EVMAddress(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) - ) - }`, + access(all) + fun main(signature: String, args: [AnyStruct], to: String, gasLimit: UInt64, value: UInt): EVM.ResultDecoded { + return EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + to: EVM.addressFromString(to), + signature: signature, + args: args, + gasLimit: gasLimit, + value: value, + resultTypes: nil, + ) + }`, evmAddress, )) - innerTxBytes, err := tx.MarshalBinary() + toAddress, err := cadence.NewString(to.Hex()) + require.NoError(t, err) + + signatureValue, err := cadence.NewString(signature) require.NoError(t, err) + argsValue := cadence.NewArray( + args, + ).WithType(cadence.NewVariableSizedArrayType(cadence.AnyStructType)) + script := fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType), - ), + json.MustEncode(signatureValue), + json.MustEncode(argsValue), + json.MustEncode(toAddress), + json.MustEncode(cadence.NewUInt64(gas)), + json.MustEncode(cadence.NewUInt(value)), ) - _, output, err := vm.Run( + + execSnapshot, output, err := vm.Run( ctx, script, - snapshot) + snapshot, + ) require.NoError(t, err) require.NoError(t, output.Err) + require.Len(t, output.Events, 0) - result, err := impl.ResultSummaryFromEVMResultValue(output.Value) + result, err := ResultDecodedFromEVMResultValue(output.Value) require.NoError(t, err) - return result + return result, execSnapshot } - // this test checks that gas limit is correctly used and gas usage correctly reported - t.Run("test dry run storing a value with different gas limits", func(t *testing.T) { + // This test checks that gas limit is correctly used and gas usage correctly reported. + t.Run("test dryCallWithSigAndArgs with different gas limits", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2186,42 +4861,72 @@ func TestDryRun(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - data := testContract.MakeCallData(t, "store", big.NewInt(1337)) + signature := "store(uint256)" + args := []cadence.Value{ + cadence.NewUInt256(1337), + } - // EVM.dryRun must not be limited by the `gethParams.MaxTxGas` - limit := gethParams.MaxTxGas + 1_000 - tx := gethTypes.NewTransaction( - 0, + limit := uint64(50_000) + + result, _ := dryCallWithSigAndArgs( + t, + signature, + args, testContract.DeployedAt.ToCommon(), - big.NewInt(0), limit, - big.NewInt(0), - data, + 0, + ctx, + vm, + snapshot, ) - result := dryRunTx(t, tx, ctx, vm, snapshot) require.Equal(t, types.ErrCodeNoError, result.ErrorCode) require.Equal(t, types.StatusSuccessful, result.Status) require.Greater(t, result.GasConsumed, uint64(0)) require.Less(t, result.GasConsumed, limit) + require.True(t, len(result.Results) == 0) // gas limit too low, but still bigger than intrinsic gas value limit = uint64(24_216) - tx = gethTypes.NewTransaction( - 0, + + result, _ = dryCallWithSigAndArgs( + t, + signature, + args, testContract.DeployedAt.ToCommon(), - big.NewInt(0), limit, - big.NewInt(0), - data, + 0, + ctx, + vm, + snapshot, ) - result = dryRunTx(t, tx, ctx, vm, snapshot) require.Equal(t, types.ExecutionErrCodeOutOfGas, result.ErrorCode) require.Equal(t, types.StatusFailed, result.Status) - require.Equal(t, result.GasConsumed, limit) // burn it all!!! + require.Equal(t, result.GasConsumed, limit) + require.True(t, len(result.Results) == 0) + + // EVM.dryCall must not be limited to `gethParams.MaxTxGas` + limit = gethParams.MaxTxGas + 1_000 + + result, _ = dryCallWithSigAndArgs( + t, + signature, + args, + testContract.DeployedAt.ToCommon(), + limit, + 0, + ctx, + vm, + snapshot, + ) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + require.Less(t, result.GasConsumed, limit) + require.True(t, len(result.Results) == 0) }) }) - t.Run("test dry run store current value", func(t *testing.T) { + t.Run("test dryCallWithSigAndArgs does not form EVM transactions", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2230,40 +4935,184 @@ func TestDryRun(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - data := testContract.MakeCallData(t, "store", big.NewInt(0)) - tx := gethTypes.NewTransaction( - 0, + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + code := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + num := int64(42) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), big.NewInt(0), uint64(50_000), big.NewInt(0), - data, ) - dryRunResult := dryRunTx(t, tx, ctx, vm, snapshot) - require.Equal(t, types.ErrCodeNoError, dryRunResult.ErrorCode) - require.Equal(t, types.StatusSuccessful, dryRunResult.Status) - require.Greater(t, dryRunResult.GasConsumed, uint64(0)) + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + state, output, err := vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Len(t, output.Events, 1) + assert.Len(t, state.UpdatedRegisterIDs(), 4) + assert.Equal( + t, + flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), + output.Events[0].Type, + ) + snapshot = snapshot.Append(state) + + code = []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(signature: String, args: [AnyStruct], to: String, gasLimit: UInt64, value: UInt){ + prepare(account: &Account) { + let res = EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + to: EVM.addressFromString(to), + signature: signature, + args: args, + gasLimit: gasLimit, + value: value, + resultTypes: [Type()], + ) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + + assert(res.results!.length == 1) + + let number = res.results![0] as! UInt256 + assert(number == 42, message: number.toString()) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + signatureValue, err := cadence.NewString("retrieve()") + require.NoError(t, err) + + argsValue := cadence.NewArray(nil).WithType(cadence.NewVariableSizedArrayType(cadence.AnyStructType)) + + toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) + require.NoError(t, err) + to := json.MustEncode(toAddress) + + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(signatureValue)). + AddArgument(json.MustEncode(argsValue)). + AddArgument(to). + AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). + AddArgument(json.MustEncode(cadence.NewUInt(0))). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + + state, output, err = vm.Run( + ctx, + tx, + snapshot, + ) + require.NoError(t, err) + require.NoError(t, output.Err) + assert.Len(t, output.Events, 0) + assert.Len(t, state.UpdatedRegisterIDs(), 0) + }) + }) + + // this test makes sure the dryCallWithSigAndArgs that updates the value on the contract + // doesn't persist the change, and after when the value is read it isn't updated. + t.Run("test dryCallWithSigAndArgs has no side-effects", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + updatedValue := int64(1337) + + signature := "store(uint256)" + args := []cadence.Value{ + cadence.NewUInt256(1337), + } + + result, state := dryCallWithSigAndArgs( + t, + signature, + args, + testContract.DeployedAt.ToCommon(), + 1000000, + 0, + ctx, + vm, + snapshot, + ) + require.Len(t, state.UpdatedRegisterIDs(), 0) + require.Equal(t, types.ErrCodeNoError, result.ErrorCode) + require.Equal(t, types.StatusSuccessful, result.Status) + require.Greater(t, result.GasConsumed, uint64(0)) + // query the value make sure it's not updated code := []byte(fmt.Sprintf( ` - import EVM from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) - } - `, + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, evmAddress, )) - // Use the gas estimation from Evm.dryRun with some buffer - gasLimit := dryRunResult.GasConsumed + gethParams.SstoreSentryGasEIP2200 innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), - data, + testContract.MakeCallData(t, "retrieve"), big.NewInt(0), - gasLimit, + uint64(100_000), big.NewInt(0), ) @@ -2280,23 +5129,81 @@ func TestDryRun(t *testing.T) { json.MustEncode(coinbase), ) - _, output, err := vm.Run( + state, output, err := vm.Run( ctx, script, snapshot, ) require.NoError(t, err) require.NoError(t, output.Err) + require.Len(t, state.UpdatedRegisterIDs(), 0) res, err := impl.ResultSummaryFromEVMResultValue(output.Value) require.NoError(t, err) require.Equal(t, types.StatusSuccessful, res.Status) require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Equal(t, res.GasConsumed, dryRunResult.GasConsumed) + // make sure the value we used in the dryCallWithSigAndArgs is not the same as the value stored in contract + require.NotEqual(t, updatedValue, new(big.Int).SetBytes(res.ReturnedData).Int64()) + }) + }) + + t.Run("test dryCallWithSigAndArgs validation error", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + signature := "store(uint256)" + args := []cadence.Value{ + cadence.NewUInt256(10337), + } + + result, _ := dryCallWithSigAndArgs( + t, + signature, + args, + testContract.DeployedAt.ToCommon(), + 35_000, + 1000, + ctx, + vm, + snapshot, + ) + assert.Equal(t, types.ValidationErrCodeInsufficientFunds, result.ErrorCode) + assert.Equal(t, types.StatusInvalid, result.Status) + assert.Equal(t, types.InvalidTransactionGasCost, int(result.GasConsumed)) + + // random function selector + signature = "test()" + args = []cadence.Value{} + + result, _ = dryCallWithSigAndArgs( + t, + signature, + args, + testContract.DeployedAt.ToCommon(), + 25_000, + 0, + ctx, + vm, + snapshot, + ) + assert.Equal(t, types.ExecutionErrCodeExecutionReverted, result.ErrorCode) + assert.Equal(t, types.StatusFailed, result.Status) + assert.Equal(t, uint64(21331), result.GasConsumed) }) }) +} - t.Run("test dry run store new value", func(t *testing.T) { +func TestCadenceArch(t *testing.T) { + t.Parallel() + + t.Run("testing calling Cadence arch - flow block height (happy case)", func(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2305,127 +5212,117 @@ func TestDryRun(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ - prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - - assert(res.status == EVM.Status.successful, message: "unexpected status") - assert(res.errorCode == 0, message: "unexpected error code") - } + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + assert(res.status == EVM.Status.successful, message: "test failed: ".concat(res.errorCode.toString())) } - `, + `, sc.EVMContract.Address.HexWithPrefix(), )) - - num := int64(12) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "store", big.NewInt(num)), + testContract.MakeCallData(t, "verifyArchCallToFlowBlockHeight", ctx.BlockHeader.Height), big.NewInt(0), - uint64(50_000), + uint64(10_000_000), big.NewInt(0), ) - - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) - - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(code). - SetPayer(sc.FlowServiceAccount.Address). - AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(innerTx)). - AddArgument(json.MustEncode(coinbase)). - Build() - require.NoError(t, err) - - tx := fvm.Transaction(txBody, 0) - + script := fvm.Script(code).WithArguments( + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType), + ), + ) _, output, err := vm.Run( ctx, - tx, - snapshot, - ) + script, + snapshot) require.NoError(t, err) require.NoError(t, output.Err) + }) + }) - data := testContract.MakeCallData(t, "store", big.NewInt(100)) - tx1 := gethTypes.NewTransaction( - 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(0), - uint64(50_000), - big.NewInt(0), - data, - ) - dryRunResult := dryRunTx(t, tx1, ctx, vm, snapshot) - - require.Equal(t, types.ErrCodeNoError, dryRunResult.ErrorCode) - require.Equal(t, types.StatusSuccessful, dryRunResult.Status) - require.Greater(t, dryRunResult.GasConsumed, uint64(0)) - - code = []byte(fmt.Sprintf( + t.Run("testing calling Cadence arch - revertible random", func(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + code := []byte(fmt.Sprintf( ` import EVM from %s + access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): [UInt8] { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) + let res = EVM.run(tx: tx, coinbase: coinbase) + assert(res.status == EVM.Status.successful, message: "test failed: ".concat(res.errorCode.toString())) + return res.data } - `, - evmAddress, + `, + sc.EVMContract.Address.HexWithPrefix(), )) - - // Decrease nonce because we are Cadence using scripts, and not - // transactions, which means that no state change is happening. - testAccount.SetNonce(testAccount.Nonce() - 1) - innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), - data, + testContract.MakeCallData(t, "verifyArchCallToRevertibleRandom"), big.NewInt(0), - dryRunResult.GasConsumed, // use the gas estimation from Evm.dryRun + uint64(10_000_000), big.NewInt(0), ) - - innerTx = cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - - coinbase = cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) - script := fvm.Script(code).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType), + ), ) - - _, output, err = vm.Run( + _, output, err := vm.Run( ctx, script, snapshot) require.NoError(t, err) require.NoError(t, output.Err) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) - require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Equal(t, res.GasConsumed, dryRunResult.GasConsumed) + res := make([]byte, 8) + vals := output.Value.(cadence.Array).Values + vals = vals[len(vals)-8:] // only last 8 bytes is the value + for i := range res { + res[i] = byte(vals[i].(cadence.UInt8)) + } + + actualRand := binary.BigEndian.Uint64(res) + // because PRG uses script ID and random source we can not predict the random + // we can set the random source but since script ID is generated by hashing + // script and args, and since arg is a signed transaction which always changes + // we can't fix the value + require.Greater(t, actualRand, uint64(0)) }) }) - t.Run("test dry run clear current value", func(t *testing.T) { + t.Run("testing calling Cadence arch - random source (happy case)", func(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2434,130 +5331,202 @@ func TestDryRun(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + entropy := []byte{13, 37} + // coresponding out to the above entropy + source := []byte{0x5b, 0xa1, 0xce, 0xab, 0x64, 0x11, 0x8d, 0x2c, 0xd8, 0xae, 0x8c, 0xbb, 0xf7, 0x50, 0x5e, 0xf5, 0xdf, 0xad, 0xfc, 0xf7, 0x2d, 0x3a, 0x46, 0x78, 0xd5, 0xe5, 0x1d, 0xb7, 0xf2, 0xb8, 0xe5, 0xd6} + + // we must record a new heartbeat with a fixed block, we manually execute a transaction to do so, + // since doing this automatically would require a block computer and whole execution setup + height := uint64(1) + block1 := unittest.BlockFixture( + unittest.Block.WithHeight(height), + ) + ctx.BlockHeader = block1.ToHeader() + ctx.EntropyProvider = testutil.EntropyProviderFixture(entropy) // fix the entropy + + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript([]byte(fmt.Sprintf(` + import RandomBeaconHistory from %s + + transaction { + prepare(serviceAccount: auth(Capabilities, Storage) &Account) { + let randomBeaconHistoryHeartbeat = serviceAccount.storage.borrow<&RandomBeaconHistory.Heartbeat>( + from: RandomBeaconHistory.HeartbeatStoragePath) + ?? panic("Couldn't borrow RandomBeaconHistory.Heartbeat Resource") + randomBeaconHistoryHeartbeat.heartbeat(randomSourceHistory: randomSourceHistory()) + } + }`, sc.RandomBeaconHistory.Address.HexWithPrefix())), + ). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) + + s, out, err := vm.Run(ctx, fvm.Transaction(txBody, 0), snapshot) + require.NoError(t, err) + require.NoError(t, out.Err) + + snapshot = snapshot.Append(s) + code := []byte(fmt.Sprintf( ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ - prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - - assert(res.status == EVM.Status.successful, message: "unexpected status") - assert(res.errorCode == 0, message: "unexpected error code") - } + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): [UInt8] { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) + assert(res.status == EVM.Status.successful, message: "evm tx wrong status") + return res.data } - `, + `, sc.EVMContract.Address.HexWithPrefix(), )) - num := int64(100) + // we fake progressing to new block height since random beacon does the check the + // current height (2) is bigger than the height requested (1) + block1.Height = 2 + ctx.BlockHeader = block1.ToHeader() + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "store", big.NewInt(num)), + testContract.MakeCallData(t, "verifyArchCallToRandomSource", height), big.NewInt(0), - uint64(50_000), + uint64(10_000_000), big.NewInt(0), ) + script := fvm.Script(code).WithArguments( + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType), + ), + ) + _, output, err := vm.Run( + ctx, + script, + snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) + res := make([]byte, environment.RandomSourceHistoryLength) + vals := output.Value.(cadence.Array).Values + require.Len(t, vals, environment.RandomSourceHistoryLength) + + for i := range res { + res[i] = byte(vals[i].(cadence.UInt8)) + } + require.Equal(t, source, res) + }) + }) - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + t.Run("testing calling Cadence arch - random source (failed due to incorrect height)", func(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + // we must record a new heartbeat with a fixed block, we manually execute a transaction to do so, + // since doing this automatically would require a block computer and whole execution setup + height := uint64(1) + block1 := unittest.BlockFixture( + unittest.Block.WithHeight(height), + ) + ctx.BlockHeader = block1.ToHeader() txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(code). + SetScript([]byte(fmt.Sprintf(` + import RandomBeaconHistory from %s + + transaction { + prepare(serviceAccount: auth(Capabilities, Storage) &Account) { + let randomBeaconHistoryHeartbeat = serviceAccount.storage.borrow<&RandomBeaconHistory.Heartbeat>( + from: RandomBeaconHistory.HeartbeatStoragePath) + ?? panic("Couldn't borrow RandomBeaconHistory.Heartbeat Resource") + randomBeaconHistoryHeartbeat.heartbeat(randomSourceHistory: randomSourceHistory()) + } + }`, sc.RandomBeaconHistory.Address.HexWithPrefix())), + ). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(innerTx)). - AddArgument(json.MustEncode(coinbase)). Build() require.NoError(t, err) - tx := fvm.Transaction(txBody, 0) - - state, output, err := vm.Run( - ctx, - tx, - snapshot, - ) + s, out, err := vm.Run(ctx, fvm.Transaction(txBody, 0), snapshot) require.NoError(t, err) - require.NoError(t, output.Err) - snapshot = snapshot.Append(state) - - data := testContract.MakeCallData(t, "store", big.NewInt(0)) - tx1 := gethTypes.NewTransaction( - 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(0), - uint64(50_000), - big.NewInt(0), - data, - ) - dryRunResult := dryRunTx(t, tx1, ctx, vm, snapshot) + require.NoError(t, out.Err) - require.Equal(t, types.ErrCodeNoError, dryRunResult.ErrorCode) - require.Equal(t, types.StatusSuccessful, dryRunResult.Status) - require.Greater(t, dryRunResult.GasConsumed, uint64(0)) + snapshot = snapshot.Append(s) - code = []byte(fmt.Sprintf( + height = 1337 // invalid + // we make sure the transaction fails, due to requested height being invalid + code := []byte(fmt.Sprintf( ` import EVM from %s + access(all) fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) return EVM.run(tx: tx, coinbase: coinbase) } `, - evmAddress, + sc.EVMContract.Address.HexWithPrefix(), )) - // use the gas estimation from Evm.dryRun with the necessary buffer gas - gasLimit := dryRunResult.GasConsumed + gethParams.SstoreClearsScheduleRefundEIP3529 - innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, + // we fake progressing to new block height since random beacon does the check the + // current height (2) is bigger than the height requested (1) + block1.Height = 2 + ctx.BlockHeader = block1.ToHeader() + + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), - data, + testContract.MakeCallData(t, "verifyArchCallToRandomSource", height), big.NewInt(0), - gasLimit, + uint64(10_000_000), big.NewInt(0), ) - - innerTx = cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - - coinbase = cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) - script := fvm.Script(code).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType), + ), ) - - _, output, err = vm.Run( + _, output, err := vm.Run( ctx, script, - snapshot, - ) + snapshot) require.NoError(t, err) require.NoError(t, output.Err) + // make sure the error is correct res, err := impl.ResultSummaryFromEVMResultValue(output.Value) require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - require.Equal(t, res.GasConsumed, dryRunResult.GasConsumed) + + revertReason, err := abi.UnpackRevert(res.ReturnedData) + require.NoError(t, err) + require.Equal(t, "unsuccessful call to arch ", revertReason) }) }) - // this test makes sure the dry-run that updates the value on the contract - // doesn't persist the change, and after when the value is read it isn't updated. - t.Run("test dry run for any side-effects", func(t *testing.T) { + t.Run("testing calling Cadence arch - COA ownership proof (happy case)", func(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2566,100 +5535,149 @@ func TestDryRun(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - updatedValue := int64(1337) - data := testContract.MakeCallData(t, "store", big.NewInt(updatedValue)) - tx := gethTypes.NewTransaction( + // create a flow account + privateKey, err := testutil.GenerateAccountPrivateKey() + require.NoError(t, err) + + snapshot, accounts, err := testutil.CreateAccounts( + vm, + snapshot, + []flow.AccountPrivateKey{privateKey}, + chain) + require.NoError(t, err) + flowAccount := accounts[0] + + // create/store/link coa + coaAddress, snapshot := setupCOA( + t, + ctx, + vm, + snapshot, + flowAccount, 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(0), - uint64(1000000), - big.NewInt(0), - data, ) - result := dryRunTx(t, tx, ctx, vm, snapshot) - require.Equal(t, types.ErrCodeNoError, result.ErrorCode) - require.Equal(t, types.StatusSuccessful, result.Status) - require.Greater(t, result.GasConsumed, uint64(0)) + data := RandomCommonHash(t) - // query the value make sure it's not updated + hasher, err := crypto.NewPrefixedHashing(privateKey.HashAlgo, "FLOW-V0.0-user") + require.NoError(t, err) + + sig, err := privateKey.PrivateKey.Sign(data.Bytes(), hasher) + require.NoError(t, err) + + validProof := types.COAOwnershipProof{ + KeyIndices: []uint64{0}, + Address: types.FlowAddress(flowAccount), + CapabilityPath: "coa", + Signatures: []types.Signature{types.Signature(sig)}, + } + + encodedValidProof, err := validProof.Encode() + require.NoError(t, err) + + // create transaction for proof verification code := []byte(fmt.Sprintf( ` import EVM from %s + access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]) { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) + let res = EVM.run(tx: tx, coinbase: coinbase) + assert(res.status == EVM.Status.successful, message: "test failed: ".concat(res.errorCode.toString())) } - `, - evmAddress, + `, + sc.EVMContract.Address.HexWithPrefix(), )) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "retrieve"), + testContract.MakeCallData(t, "verifyArchCallToVerifyCOAOwnershipProof", + true, + coaAddress.ToCommon(), + data, + encodedValidProof), big.NewInt(0), - uint64(100_000), + uint64(10_000_000), big.NewInt(0), ) - - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) - - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) - - script := fvm.Script(code).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), + verifyScript := fvm.Script(code).WithArguments( + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType( + stdlib.EVMTransactionBytesCadenceType, + )), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8( + testAccount.Address().Bytes(), + ), + ).WithType( + stdlib.EVMAddressBytesCadenceType, + ), + ), ) - + // run proof transaction _, output, err := vm.Run( ctx, - script, + verifyScript, snapshot) require.NoError(t, err) require.NoError(t, output.Err) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + invalidProof := types.COAOwnershipProof{ + KeyIndices: []uint64{1000}, + Address: types.FlowAddress(flowAccount), + CapabilityPath: "coa", + Signatures: []types.Signature{types.Signature(sig)}, + } + + encodedInvalidProof, err := invalidProof.Encode() require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - // make sure the value we used in the dry-run is not the same as the value stored in contract - require.NotEqual(t, updatedValue, new(big.Int).SetBytes(res.ReturnedData).Int64()) - }) - }) - t.Run("test dry run contract deployment", func(t *testing.T) { - RunWithNewEnvironment(t, - chain, func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { - tx := gethTypes.NewContractCreation( - 0, + // invalid proof tx + innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "verifyArchCallToVerifyCOAOwnershipProof", + true, + coaAddress.ToCommon(), + data, + encodedInvalidProof), big.NewInt(0), uint64(10_000_000), big.NewInt(0), - testContract.ByteCode, ) - result := dryRunTx(t, tx, ctx, vm, snapshot) - require.Equal(t, types.ErrCodeNoError, result.ErrorCode) - require.Equal(t, types.StatusSuccessful, result.Status) - require.Greater(t, result.GasConsumed, uint64(0)) - require.NotNil(t, result.ReturnedData) - require.NotNil(t, result.DeployedContractAddress) - require.NotEmpty(t, result.DeployedContractAddress.String()) + verifyScript = fvm.Script(code).WithArguments( + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType( + stdlib.EVMTransactionBytesCadenceType, + )), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8( + testAccount.Address().Bytes(), + ), + ).WithType( + stdlib.EVMAddressBytesCadenceType, + ), + ), + ) + // run proof transaction + _, output, err = vm.Run( + ctx, + verifyScript, + snapshot) + require.NoError(t, err) + require.Error(t, output.Err) }) }) - t.Run("test dry run validation error", func(t *testing.T) { + t.Run("testing calling Cadence arch - COA ownership proof (index overflow)", func(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2668,83 +5686,97 @@ func TestDryRun(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - tx := gethTypes.NewContractCreation( - 0, - big.NewInt(100), // more than available - uint64(1000000), - big.NewInt(0), - nil, - ) + code := []byte(fmt.Sprintf( + ` + import EVM from %s - result := dryRunTx(t, tx, ctx, vm, snapshot) - assert.Equal(t, types.ValidationErrCodeInsufficientFunds, result.ErrorCode) - assert.Equal(t, types.StatusInvalid, result.Status) - assert.Equal(t, types.InvalidTransactionGasCost, int(result.GasConsumed)) - }) - }) -} + transaction { + let coa: @EVM.CadenceOwnedAccount -func TestDryCall(t *testing.T) { - t.Parallel() + prepare(signer: auth(Storage) &Account) { + self.coa <- EVM.createCadenceOwnedAccount() + } - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - evmAddress := sc.EVMContract.Address.HexWithPrefix() + execute { + let cadenceArchAddress = EVM.EVMAddress( + bytes: [ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 + ] + ) - dryCall := func( - t *testing.T, - tx *gethTypes.Transaction, - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - ) (*types.ResultSummary, *snapshot.ExecutionSnapshot) { - code := []byte(fmt.Sprintf(` - import EVM from %s + var calldata: [UInt8] = [] + + // Function selector for verifyCOAOwnershipProof = 0x5ee837e7 + calldata = calldata.concat([0x5e, 0xe8, 0x37, 0xe7]) + + // Address parameter (32 bytes) + var i = 0 + while i < 31 { calldata = calldata.concat([0x00]); i = i + 1 } + calldata = calldata.concat([0x01]) + + // bytes32 parameter (32 bytes) + i = 0 + while i < 32 { calldata = calldata.concat([0x00]); i = i + 1 } + + // MALICIOUS offset: 0x7FFFFFFFFFFFFFFF (MaxInt64) + // When ReadBytes does: index + 32, this overflows to negative + // MaxInt64 + 32 = -9223372036854775777 (wraps around) + i = 0 + while i < 24 { calldata = calldata.concat([0x00]); i = i + 1 } + calldata = calldata.concat([0x7F]) // High byte = 0x7F + calldata = calldata.concat([0xFF]) + calldata = calldata.concat([0xFF]) + calldata = calldata.concat([0xFF]) + calldata = calldata.concat([0xFF]) + calldata = calldata.concat([0xFF]) + calldata = calldata.concat([0xFF]) + calldata = calldata.concat([0xFF]) // = 0x7FFFFFFFFFFFFFFF + + // Length (32 bytes) + i = 0 + while i < 31 { calldata = calldata.concat([0x00]); i = i + 1 } + calldata = calldata.concat([0x20]) + + // Dummy data (32 bytes) + i = 0 + while i < 32 { calldata = calldata.concat([0x00]); i = i + 1 } + + let result = self.coa.call( + to: cadenceArchAddress, + data: calldata, + gasLimit: 100_000, + value: EVM.Balance(attoflow: 0) + ) + assert(result.status == EVM.Status.failed, message: "unexpected status") + assert(result.errorMessage == "input data is too small for decoding", message: result.errorMessage) - access(all) - fun main(data: [UInt8], to: String, gasLimit: UInt64, value: UInt): EVM.Result { - return EVM.dryCall( - from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), - to: EVM.addressFromString(to), - data: data, - gasLimit: gasLimit, - value: EVM.Balance(attoflow: value) - ) - }`, - evmAddress, - )) + destroy self.coa + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - require.NotNil(t, tx.To()) - to := tx.To().Hex() - toAddress, err := cadence.NewString(to) - require.NoError(t, err) + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) - script := fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(tx.Data()), - ).WithType(stdlib.EVMTransactionBytesCadenceType), - ), - json.MustEncode(toAddress), - json.MustEncode(cadence.NewUInt64(tx.Gas())), - json.MustEncode(cadence.NewUInt(uint(tx.Value().Uint64()))), - ) - execSnapshot, output, err := vm.Run( - ctx, - script, - snapshot, - ) - require.NoError(t, err) - require.NoError(t, output.Err) - require.Len(t, output.Events, 0) + tx := fvm.Transaction(txBody, 0) - result, err := impl.ResultSummaryFromEVMResultValue(output.Value) - require.NoError(t, err) - return result, execSnapshot - } + _, output, err := vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + }, + ) + }) - // this test checks that gas limit is correctly used and gas usage correctly reported - t.Run("test dryCall with different gas limits", func(t *testing.T) { + t.Run("testing calling Cadence arch - COA ownership proof (empty proof list)", func(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2753,57 +5785,99 @@ func TestDryCall(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - data := testContract.MakeCallData(t, "store", big.NewInt(1337)) + // create a flow account + privateKey, err := testutil.GenerateAccountPrivateKey() + require.NoError(t, err) - limit := uint64(50_000) - tx := gethTypes.NewTransaction( - 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(0), - limit, - big.NewInt(0), - data, - ) - result, _ := dryCall(t, tx, ctx, vm, snapshot) - require.Equal(t, types.ErrCodeNoError, result.ErrorCode) - require.Equal(t, types.StatusSuccessful, result.Status) - require.Greater(t, result.GasConsumed, uint64(0)) - require.Less(t, result.GasConsumed, limit) + snapshot, accounts, err := testutil.CreateAccounts( + vm, + snapshot, + []flow.AccountPrivateKey{privateKey}, + chain) + require.NoError(t, err) + flowAccount := accounts[0] - // gas limit too low, but still bigger than intrinsic gas value - limit = uint64(24_216) - tx = gethTypes.NewTransaction( + // create/store/link coa + coaAddress, snapshot := setupCOA( + t, + ctx, + vm, + snapshot, + flowAccount, 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(0), - limit, - big.NewInt(0), - data, ) - result, _ = dryCall(t, tx, ctx, vm, snapshot) - require.Equal(t, types.ExecutionErrCodeOutOfGas, result.ErrorCode) - require.Equal(t, types.StatusFailed, result.Status) - require.Equal(t, result.GasConsumed, limit) - // EVM.dryCall must not be limited to `gethParams.MaxTxGas` - limit = gethParams.MaxTxGas + 1_000 - tx = gethTypes.NewTransaction( - 0, + data := RandomCommonHash(t) + + emptyProofList, err := hex.DecodeString("c0") // empty RLP list + require.NoError(t, err) + + // create transaction for proof verification + code := []byte(fmt.Sprintf( + ` + import EVM from %s + access(all) + fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.run(tx: tx, coinbase: coinbase) + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "verifyArchCallToVerifyCOAOwnershipProof", + true, + coaAddress.ToCommon(), + data, + emptyProofList), big.NewInt(0), - limit, + uint64(10_000_000), big.NewInt(0), - data, ) - result, _ = dryCall(t, tx, ctx, vm, snapshot) - require.Equal(t, types.ErrCodeNoError, result.ErrorCode) - require.Equal(t, types.StatusSuccessful, result.Status) - require.Greater(t, result.GasConsumed, uint64(0)) - require.Less(t, result.GasConsumed, limit) - }) + verifyScript := fvm.Script(code).WithArguments( + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType( + stdlib.EVMTransactionBytesCadenceType, + )), + json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8( + testAccount.Address().Bytes(), + ), + ).WithType( + stdlib.EVMAddressBytesCadenceType, + ), + ), + ) + + // run proof transaction + _, output, err := vm.Run(ctx, verifyScript, snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + + // make sure the error is correct + res, err := impl.ResultSummaryFromEVMResultValue(output.Value) + require.NoError(t, err) + + revertReason, err := abi.UnpackRevert(res.ReturnedData) + require.NoError(t, err) + require.Equal(t, "unsuccessful call to arch", revertReason) + }, + ) }) +} + +func TestNativePrecompiles(t *testing.T) { + t.Parallel() + + chain := flow.Emulator.Chain() + + t.Run("testing out of gas precompile call", func(t *testing.T) { + t.Parallel() - t.Run("test dryCall does not form EVM transactions", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -2822,21 +5896,28 @@ func TestDryCall(t *testing.T) { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.successful, message: "unexpected status") - assert(res.errorCode == 0, message: "unexpected error code") + assert(res.status == EVM.Status.failed, message: "unexpected status") + assert(res.errorCode == 301, message: "unexpected error code: \(res.errorCode)") + assert(res.errorMessage == "out of gas", message: "unexpected error message: \(res.errorMessage)") } } `, sc.EVMContract.Address.HexWithPrefix(), )) - num := int64(42) + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + // The address below is the latest precompile on the Prague hard-fork: + // https://github.com/ethereum/go-ethereum/blob/v1.16.3/core/vm/contracts.go#L140 . + to := common.HexToAddress("0x00000000000000000000000000000000000000011") innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "store", big.NewInt(num)), - big.NewInt(0), - uint64(50_000), - big.NewInt(0), + to, + nil, + big.NewInt(1_000_000), + uint64(21_000), + big.NewInt(1), ) innerTx := cadence.NewArray( @@ -2844,7 +5925,7 @@ func TestDryCall(t *testing.T) { ).WithType(stdlib.EVMTransactionBytesCadenceType) coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) txBody, err := flow.NewTransactionBodyBuilder(). @@ -2865,206 +5946,208 @@ func TestDryCall(t *testing.T) { ) require.NoError(t, err) require.NoError(t, output.Err) - assert.Len(t, output.Events, 1) - assert.Len(t, state.UpdatedRegisterIDs(), 4) - assert.Equal( - t, - flow.EventType("A.f8d6e0586b0a20c7.EVM.TransactionExecuted"), - output.Events[0].Type, - ) - snapshot = snapshot.Append(state) - - code = []byte(fmt.Sprintf( - ` - import EVM from %s + require.NotEmpty(t, state.WriteSet) - transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt){ - prepare(account: &Account) { - let res = EVM.dryCall( - from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), - to: EVM.addressFromString(to), - data: data, - gasLimit: gasLimit, - value: EVM.Balance(attoflow: value) - ) + // assert event fields are correct + require.Len(t, output.Events, 2) + txEvent := output.Events[0] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + require.Equal(t, uint16(types.ExecutionErrCodeOutOfGas), txEventPayload.ErrorCode) + require.Equal(t, uint16(0), txEventPayload.Index) + require.Equal(t, uint64(21000), txEventPayload.GasConsumed) + require.NoError(t, err) + }) + }) +} - assert(res.status == EVM.Status.successful, message: "unexpected status") - assert(res.errorCode == 0, message: "unexpected error code") +func TestEVMFileSystemContract(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - let values = EVM.decodeABI(types: [Type()], data: res.data) - assert(values.length == 1) + runFileSystemContract := func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + computeLimit uint64, + ) ( + *snapshot.ExecutionSnapshot, + fvm.ProcedureOutput, + ) { + code := []byte(fmt.Sprintf( + ` + import EVM from %s - let number = values[0] as! UInt256 - assert(number == 42, message: String.encodeHex(res.data)) + transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let res = EVM.run(tx: tx, coinbase: coinbase) } } `, - sc.EVMContract.Address.HexWithPrefix(), - )) + sc.EVMContract.Address.HexWithPrefix(), + )) - data := json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testContract.MakeCallData(t, "retrieve")), - ).WithType(stdlib.EVMTransactionBytesCadenceType), - ) - toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) - require.NoError(t, err) - to := json.MustEncode(toAddress) + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - txBody, err = flow.NewTransactionBodyBuilder(). - SetScript(code). - SetPayer(sc.FlowServiceAccount.Address). - AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(data). - AddArgument(to). - AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). - AddArgument(json.MustEncode(cadence.NewUInt(0))). - Build() - require.NoError(t, err) + var buffer bytes.Buffer + address := common.HexToAddress("0xea02F564664A477286B93712829180be4764fAe2") + chunkHash := "0x2521660d04da85198d1cc71c20a69b7e875ebbf1682f6a5c6a3fec69068ccc13" + index := int64(0) + chunk := "T1ARYBYsPOJPVYoU7wVp+PYuXmdS6bgkLf2egcxa+1hP64wAxfkLXtnllU6DmEuj+Id4oWl1ZV4ftQ+ofQ3DQhOoxNlPZGOYbhoMLuzE" + for i := 0; i <= 500; i++ { + buffer.WriteString(chunk) + } + innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData( + t, + "publishChunk", + address, + chunkHash, + big.NewInt(index), + buffer.String(), + ), + big.NewInt(0), + uint64(2_132_171), + big.NewInt(1), + ) - tx = fvm.Transaction(txBody, 0) + innerTx := cadence.NewArray( + unittest.BytesToCdcUInt8(innerTxBytes), + ).WithType(stdlib.EVMTransactionBytesCadenceType) - state, output, err = vm.Run( - ctx, - tx, - snapshot, - ) - require.NoError(t, err) - require.NoError(t, output.Err) - assert.Len(t, output.Events, 0) - assert.Len(t, state.UpdatedRegisterIDs(), 0) - }) - }) + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) - // this test makes sure the dryCall that updates the value on the contract - // doesn't persist the change, and after when the value is read it isn't updated. - t.Run("test dryCall has no side-effects", func(t *testing.T) { - RunWithNewEnvironment(t, - chain, func( + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetComputeLimit(computeLimit). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(innerTx)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx := fvm.Transaction( + txBody, + 0, + ) + + state, output, err := vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + return state, output + } + + t.Run("happy case", func(t *testing.T) { + RunContractWithNewEnvironment( + t, + chain, + GetFileSystemContract(t), + func( ctx fvm.Context, vm fvm.VM, snapshot snapshot.SnapshotTree, testContract *TestContract, testAccount *EOATestAccount, ) { - updatedValue := int64(1337) - data := testContract.MakeCallData(t, "store", big.NewInt(updatedValue)) - tx := gethTypes.NewTransaction( - 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(0), - uint64(1000000), - big.NewInt(0), - data, - ) - - result, state := dryCall(t, tx, ctx, vm, snapshot) - require.Len(t, state.UpdatedRegisterIDs(), 0) - require.Equal(t, types.ErrCodeNoError, result.ErrorCode) - require.Equal(t, types.StatusSuccessful, result.Status) - require.Greater(t, result.GasConsumed, uint64(0)) - - // query the value make sure it's not updated - code := []byte(fmt.Sprintf( - ` - import EVM from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): EVM.Result { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.run(tx: tx, coinbase: coinbase) - } - `, - evmAddress, - )) - - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "retrieve"), - big.NewInt(0), - uint64(100_000), - big.NewInt(0), - ) - - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) + state, output := runFileSystemContract(ctx, vm, snapshot, testContract, testAccount, 10001) - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + require.NoError(t, output.Err) + require.NotEmpty(t, state.WriteSet) + snapshot = snapshot.Append(state) - script := fvm.Script(code).WithArguments( - json.MustEncode(innerTx), - json.MustEncode(coinbase), - ) + // assert event fields are correct + require.Len(t, output.Events, 2) + txEvent := output.Events[0] + txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) - state, output, err := vm.Run( + // fee transfer event + feeTransferEvent := output.Events[1] + feeTranferEventPayload := TxEventToPayload(t, feeTransferEvent, sc.EVMContract.Address) + require.Equal(t, uint16(types.ErrCodeNoError), feeTranferEventPayload.ErrorCode) + require.Equal(t, uint16(1), feeTranferEventPayload.Index) + require.Equal(t, uint64(21000), feeTranferEventPayload.GasConsumed) + // + //// commit block + blockEventPayload, _ := callEVMHeartBeat(t, ctx, - script, + vm, snapshot, ) - require.NoError(t, err) - require.NoError(t, output.Err) - require.Len(t, state.UpdatedRegisterIDs(), 0) + // + require.NotEmpty(t, blockEventPayload.Hash) + require.Equal(t, uint64(2_132_170), blockEventPayload.TotalGasUsed) + + txHashes := types.TransactionHashes{txEventPayload.Hash, feeTranferEventPayload.Hash} + require.Equal(t, + txHashes.RootHash(), + blockEventPayload.TransactionHashRoot, + ) + require.NotEmpty(t, blockEventPayload.ReceiptRoot) - res, err := impl.ResultSummaryFromEVMResultValue(output.Value) - require.NoError(t, err) - require.Equal(t, types.StatusSuccessful, res.Status) - require.Equal(t, types.ErrCodeNoError, res.ErrorCode) - // make sure the value we used in the dryCall is not the same as the value stored in contract - require.NotEqual(t, updatedValue, new(big.Int).SetBytes(res.ReturnedData).Int64()) - }) + require.Equal(t, uint16(types.ErrCodeNoError), txEventPayload.ErrorCode) + require.Equal(t, uint16(0), txEventPayload.Index) + require.Equal(t, blockEventPayload.Height, txEventPayload.BlockHeight) + require.Equal(t, blockEventPayload.TotalGasUsed-feeTranferEventPayload.GasConsumed, txEventPayload.GasConsumed) + require.Empty(t, txEventPayload.ContractAddress) + + require.Greater(t, int(output.ComputationUsed), 900) + }, + fvm.WithExecutionEffortWeights( + environment.MainnetExecutionEffortWeights, + ), + ) }) - t.Run("test dryCall validation error", func(t *testing.T) { - RunWithNewEnvironment(t, - chain, func( + t.Run("insufficient FVM computation to execute EVM transaction", func(t *testing.T) { + RunContractWithNewEnvironment( + t, + chain, + GetFileSystemContract(t), + func( ctx fvm.Context, vm fvm.VM, snapshot snapshot.SnapshotTree, testContract *TestContract, testAccount *EOATestAccount, ) { - data := testContract.MakeCallData(t, "store", big.NewInt(10337)) - tx := gethTypes.NewTransaction( - 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(1000), // more than available - uint64(35_000), - big.NewInt(0), - data, - ) + state, output := runFileSystemContract(ctx, vm, snapshot, testContract, testAccount, 500) + snapshot = snapshot.Append(state) - result, _ := dryCall(t, tx, ctx, vm, snapshot) - assert.Equal(t, types.ValidationErrCodeInsufficientFunds, result.ErrorCode) - assert.Equal(t, types.StatusInvalid, result.Status) - assert.Equal(t, types.InvalidTransactionGasCost, int(result.GasConsumed)) + require.Len(t, output.Events, 0) - // random function selector - data = []byte{254, 234, 101, 199} - tx = gethTypes.NewTransaction( - 0, - testContract.DeployedAt.ToCommon(), - big.NewInt(0), - uint64(25_000), - big.NewInt(0), - data, + //// commit block + blockEventPayload, _ := callEVMHeartBeat(t, + ctx, + vm, + snapshot, ) + // + require.NotEmpty(t, blockEventPayload.Hash) + require.Equal(t, uint64(0), blockEventPayload.TotalGasUsed) - result, _ = dryCall(t, tx, ctx, vm, snapshot) - assert.Equal(t, types.ExecutionErrCodeExecutionReverted, result.ErrorCode) - assert.Equal(t, types.StatusFailed, result.Status) - assert.Equal(t, uint64(21331), result.GasConsumed) - }) + // only a small amount of computation was used due to the EVM transaction never being executed + require.Less(t, int(output.ComputationUsed), 900) + }, + fvm.WithExecutionEffortWeights( + environment.MainnetExecutionEffortWeights, + ), + ) }) } -func TestCadenceArch(t *testing.T) { +func TestEVMaddressFromString(t *testing.T) { t.Parallel() - t.Run("testing calling Cadence arch - flow block height (happy case)", func(t *testing.T) { - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + + t.Run("valid EVM address without prefix", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -3078,45 +6161,27 @@ func TestCadenceArch(t *testing.T) { import EVM from %s access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.successful, message: "test failed: ".concat(res.errorCode.toString())) + fun main(): Bool { + let address = EVM.addressFromString("E62340807933BCFC3b89FE121dDC0ae5DA9599a0") + assert( + address.toString() == "e62340807933bcfc3b89fe121ddc0ae5da9599a0", + message: "unexpected EVM address" + ) + return true } - `, + `, sc.EVMContract.Address.HexWithPrefix(), )) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "verifyArchCallToFlowBlockHeight", ctx.BlockHeader.Height), - big.NewInt(0), - uint64(10_000_000), - big.NewInt(0), - ) - script := fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType), - ), - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType), - ), - ) - _, output, err := vm.Run( - ctx, - script, - snapshot) + + script := fvm.Script(code) + _, output, err := vm.Run(ctx, script, snapshot) require.NoError(t, err) require.NoError(t, output.Err) - }) + }, + ) }) - t.Run("testing calling Cadence arch - revertible random", func(t *testing.T) { - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + t.Run("valid EVM address with prefix", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -3130,60 +6195,27 @@ func TestCadenceArch(t *testing.T) { import EVM from %s access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): [UInt8] { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.successful, message: "test failed: ".concat(res.errorCode.toString())) - return res.data + fun main(): Bool { + let address = EVM.addressFromString("0xE62340807933BCFC3b89FE121dDC0ae5DA9599a0") + assert( + address.toString() == "e62340807933bcfc3b89fe121ddc0ae5da9599a0", + message: "unexpected EVM address" + ) + return true } - `, + `, sc.EVMContract.Address.HexWithPrefix(), )) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "verifyArchCallToRevertibleRandom"), - big.NewInt(0), - uint64(10_000_000), - big.NewInt(0), - ) - script := fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType), - ), - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType), - ), - ) - _, output, err := vm.Run( - ctx, - script, - snapshot) + + script := fvm.Script(code) + _, output, err := vm.Run(ctx, script, snapshot) require.NoError(t, err) require.NoError(t, output.Err) - - res := make([]byte, 8) - vals := output.Value.(cadence.Array).Values - vals = vals[len(vals)-8:] // only last 8 bytes is the value - for i := range res { - res[i] = byte(vals[i].(cadence.UInt8)) - } - - actualRand := binary.BigEndian.Uint64(res) - // because PRG uses script ID and random source we can not predict the random - // we can set the random source but since script ID is generated by hashing - // script and args, and since arg is a signed transaction which always changes - // we can't fix the value - require.Greater(t, actualRand, uint64(0)) - }) + }, + ) }) - t.Run("testing calling Cadence arch - random source (happy case)", func(t *testing.T) { - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + t.Run("invalid EVM address with non-hex prefix", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -3192,103 +6224,37 @@ func TestCadenceArch(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - entropy := []byte{13, 37} - // coresponding out to the above entropy - source := []byte{0x5b, 0xa1, 0xce, 0xab, 0x64, 0x11, 0x8d, 0x2c, 0xd8, 0xae, 0x8c, 0xbb, 0xf7, 0x50, 0x5e, 0xf5, 0xdf, 0xad, 0xfc, 0xf7, 0x2d, 0x3a, 0x46, 0x78, 0xd5, 0xe5, 0x1d, 0xb7, 0xf2, 0xb8, 0xe5, 0xd6} - - // we must record a new heartbeat with a fixed block, we manually execute a transaction to do so, - // since doing this automatically would require a block computer and whole execution setup - height := uint64(1) - block1 := unittest.BlockFixture( - unittest.Block.WithHeight(height), - ) - ctx.BlockHeader = block1.ToHeader() - ctx.EntropyProvider = testutil.EntropyProviderFixture(entropy) // fix the entropy - - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript([]byte(fmt.Sprintf(` - import RandomBeaconHistory from %s - - transaction { - prepare(serviceAccount: auth(Capabilities, Storage) &Account) { - let randomBeaconHistoryHeartbeat = serviceAccount.storage.borrow<&RandomBeaconHistory.Heartbeat>( - from: RandomBeaconHistory.HeartbeatStoragePath) - ?? panic("Couldn't borrow RandomBeaconHistory.Heartbeat Resource") - randomBeaconHistoryHeartbeat.heartbeat(randomSourceHistory: randomSourceHistory()) - } - }`, sc.RandomBeaconHistory.Address.HexWithPrefix())), - ). - SetPayer(sc.FlowServiceAccount.Address). - AddAuthorizer(sc.FlowServiceAccount.Address). - Build() - require.NoError(t, err) - - s, out, err := vm.Run(ctx, fvm.Transaction(txBody, 0), snapshot) - require.NoError(t, err) - require.NoError(t, out.Err) - - snapshot = snapshot.Append(s) - code := []byte(fmt.Sprintf( ` import EVM from %s access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]): [UInt8] { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.successful, message: "evm tx wrong status") - return res.data + fun main(): Bool { + let address = EVM.addressFromString("2xE62340807933BCFC3b89FE121dDC0ae5DA9599a0") + assert( + address.toString() == "e62340807933bcfc3b89fe121ddc0ae5da9599a0", + message: "unexpected EVM address" + ) + return true } - `, + `, sc.EVMContract.Address.HexWithPrefix(), )) - // we fake progressing to new block height since random beacon does the check the - // current height (2) is bigger than the height requested (1) - block1.Height = 2 - ctx.BlockHeader = block1.ToHeader() - - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "verifyArchCallToRandomSource", height), - big.NewInt(0), - uint64(10_000_000), - big.NewInt(0), - ) - script := fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType), - ), - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType), - ), - ) - _, output, err := vm.Run( - ctx, - script, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - res := make([]byte, environment.RandomSourceHistoryLength) - vals := output.Value.(cadence.Array).Values - require.Len(t, vals, environment.RandomSourceHistoryLength) - - for i := range res { - res[i] = byte(vals[i].(cadence.UInt8)) - } - require.Equal(t, source, res) - }) + script := fvm.Script(code) + _, output, err := vm.Run(ctx, script, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM.addressFromString(): The 42-character EVM address string must have a '0x' prefix", + ) + }, + ) }) - t.Run("testing calling Cadence arch - random source (failed due to incorrect height)", func(t *testing.T) { - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + t.Run("invalid EVM address with non-hex characters", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -3297,90 +6263,72 @@ func TestCadenceArch(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - // we must record a new heartbeat with a fixed block, we manually execute a transaction to do so, - // since doing this automatically would require a block computer and whole execution setup - height := uint64(1) - block1 := unittest.BlockFixture( - unittest.Block.WithHeight(height), - ) - ctx.BlockHeader = block1.ToHeader() - - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript([]byte(fmt.Sprintf(` - import RandomBeaconHistory from %s + code := []byte(fmt.Sprintf( + ` + import EVM from %s - transaction { - prepare(serviceAccount: auth(Capabilities, Storage) &Account) { - let randomBeaconHistoryHeartbeat = serviceAccount.storage.borrow<&RandomBeaconHistory.Heartbeat>( - from: RandomBeaconHistory.HeartbeatStoragePath) - ?? panic("Couldn't borrow RandomBeaconHistory.Heartbeat Resource") - randomBeaconHistoryHeartbeat.heartbeat(randomSourceHistory: randomSourceHistory()) - } - }`, sc.RandomBeaconHistory.Address.HexWithPrefix())), - ). - SetPayer(sc.FlowServiceAccount.Address). - AddAuthorizer(sc.FlowServiceAccount.Address). - Build() - require.NoError(t, err) + access(all) + fun main(): Bool { + let address = EVM.addressFromString("0xGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") + return false + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - s, out, err := vm.Run(ctx, fvm.Transaction(txBody, 0), snapshot) + script := fvm.Script(code) + _, output, err := vm.Run(ctx, script, snapshot) require.NoError(t, err) - require.NoError(t, out.Err) - - snapshot = snapshot.Append(s) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "invalid byte in hex string: 47", + ) + }, + ) + }) - height = 1337 // invalid - // we make sure the transaction fails, due to requested height being invalid + t.Run("invalid EVM address with insufficient length", func(t *testing.T) { + RunWithNewEnvironment(t, + chain, func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { code := []byte(fmt.Sprintf( ` import EVM from %s access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) + fun main(): Bool { + let address = EVM.addressFromString("0xE62340807933BCFC3b89FE121dDC0ae5DA95") + assert( + address.toString() == "e62340807933bcfc3b89fe121ddc0ae5da95", + message: "unexpected EVM address" + ) + return true } - `, + `, sc.EVMContract.Address.HexWithPrefix(), )) - // we fake progressing to new block height since random beacon does the check the - // current height (2) is bigger than the height requested (1) - block1.Height = 2 - ctx.BlockHeader = block1.ToHeader() - - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "verifyArchCallToRandomSource", height), - big.NewInt(0), - uint64(10_000_000), - big.NewInt(0), - ) - script := fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType), - ), - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(testAccount.Address().Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType), - ), - ) - _, output, err := vm.Run( - ctx, - script, - snapshot) + script := fvm.Script(code) + _, output, err := vm.Run(ctx, script, snapshot) require.NoError(t, err) - // make sure the error is correct - require.ErrorContains(t, output.Err, "Source of randomness not yet recorded") - }) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "Invalid hex string length for an EVM address. The provided string is 38, but the length must be 40 or 42", + ) + }, + ) }) - t.Run("testing calling Cadence arch - COA ownership proof (happy case)", func(t *testing.T) { - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + t.Run("invalid EVM address with superfluous length", func(t *testing.T) { RunWithNewEnvironment(t, chain, func( ctx fvm.Context, @@ -3389,165 +6337,131 @@ func TestCadenceArch(t *testing.T) { testContract *TestContract, testAccount *EOATestAccount, ) { - // create a flow account - privateKey, err := testutil.GenerateAccountPrivateKey() - require.NoError(t, err) + code := []byte(fmt.Sprintf( + ` + import EVM from %s - snapshot, accounts, err := testutil.CreateAccounts( - vm, - snapshot, - []flow.AccountPrivateKey{privateKey}, - chain) - require.NoError(t, err) - flowAccount := accounts[0] + access(all) + fun main(): Bool { + let address = EVM.addressFromString("0xE62340807933BCFC3b89FE121dDC0ae5DA9599a0a1") + assert( + address.toString() == "e62340807933bcfc3b89fe121ddc0ae5da9599a0a1", + message: "unexpected EVM address" + ) + return true + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - // create/store/link coa - coaAddress, snapshot := setupCOA( + script := fvm.Script(code) + _, output, err := vm.Run(ctx, script, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( t, - ctx, - vm, - snapshot, - flowAccount, - 0, + output.Err, + "Invalid hex string length for an EVM address. The provided string is 44, but the length must be 40 or 42", ) + }, + ) + }) +} - data := RandomCommonHash(t) +func TestEVMPauseFunctionality(t *testing.T) { + t.Parallel() - hasher, err := crypto.NewPrefixedHashing(privateKey.HashAlgo, "FLOW-V0.0-user") - require.NoError(t, err) + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - sig, err := privateKey.PrivateKey.Sign(data.Bytes(), hasher) - require.NoError(t, err) + code := []byte(fmt.Sprintf( + ` + import EVM from %s - validProof := types.COAOwnershipProof{ - KeyIndices: []uint64{0}, - Address: types.FlowAddress(flowAccount), - CapabilityPath: "coa", - Signatures: []types.Signature{types.Signature(sig)}, - } + transaction(){ + prepare(account: auth(Storage) &Account) { + account.storage.save(<- EVM.createCadenceOwnedAccount(), to: /storage/coa) + account.storage.save(true, to: /storage/evmOperationsPaused) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - encodedValidProof, err := validProof.Encode() - require.NoError(t, err) + txBody, err := flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() - // create transaction for proof verification - code := []byte(fmt.Sprintf( + require.NoError(t, err) + + tx := fvm.Transaction(txBody, 0) + + RunWithNewEnvironment( + t, + chain, + func( + ctx fvm.Context, + vm fvm.VM, + snapshot snapshot.SnapshotTree, + testContract *TestContract, + testAccount *EOATestAccount, + ) { + state, output, err := vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.NoError(t, output.Err) + // append the state + snapshot = snapshot.Append(state) + + t.Run("testing EOA deposit when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( ` import EVM from %s + import FlowToken from %s - access(all) - fun main(tx: [UInt8], coinbaseBytes: [UInt8; 20]) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.successful, message: "test failed: ".concat(res.errorCode.toString())) - } - `, - sc.EVMContract.Address.HexWithPrefix(), - )) - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "verifyArchCallToVerifyCOAOwnershipProof", - true, - coaAddress.ToCommon(), - data, - encodedValidProof), - big.NewInt(0), - uint64(10_000_000), - big.NewInt(0), - ) - verifyScript := fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType( - stdlib.EVMTransactionBytesCadenceType, - )), - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8( - testAccount.Address().Bytes(), - ), - ).WithType( - stdlib.EVMAddressBytesCadenceType, - ), - ), - ) - // run proof transaction - _, output, err := vm.Run( - ctx, - verifyScript, - snapshot) - require.NoError(t, err) - require.NoError(t, output.Err) - - invalidProof := types.COAOwnershipProof{ - KeyIndices: []uint64{1000}, - Address: types.FlowAddress(flowAccount), - CapabilityPath: "coa", - Signatures: []types.Signature{types.Signature(sig)}, - } + transaction(addr: [UInt8; 20]) { + prepare(account: auth(BorrowValue) &Account) { + let admin = account.storage + .borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! - encodedInvalidProof, err := invalidProof.Encode() - require.NoError(t, err) + let minter <- admin.createNewMinter(allowedAmount: 1.0) + let vault <- minter.mintTokens(amount: 1.0) + destroy minter - // invalid proof tx - innerTxBytes = testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData(t, "verifyArchCallToVerifyCOAOwnershipProof", - true, - coaAddress.ToCommon(), - data, - encodedInvalidProof), - big.NewInt(0), - uint64(10_000_000), - big.NewInt(0), - ) + let address = EVM.EVMAddress(bytes: addr) + address.deposit(from: <-vault) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) - verifyScript = fvm.Script(code).WithArguments( - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType( - stdlib.EVMTransactionBytesCadenceType, - )), - json.MustEncode( - cadence.NewArray( - unittest.BytesToCdcUInt8( - testAccount.Address().Bytes(), - ), - ).WithType( - stdlib.EVMAddressBytesCadenceType, - ), - ), - ) - // run proof transaction - _, output, err = vm.Run( - ctx, - verifyScript, - snapshot) + addr := RandomAddress(t) + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(cadence.NewArray( + unittest.BytesToCdcUInt8(addr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType))). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) require.NoError(t, err) require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) }) - }) -} - -func TestNativePrecompiles(t *testing.T) { - t.Parallel() - chain := flow.Emulator.Chain() - - t.Run("testing out of gas precompile call", func(t *testing.T) { - t.Parallel() - - RunWithNewEnvironment(t, - chain, func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - code := []byte(fmt.Sprintf( + t.Run("testing EVM.run when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( ` import EVM from %s @@ -3556,9 +6470,9 @@ func TestNativePrecompiles(t *testing.T) { let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) let res = EVM.run(tx: tx, coinbase: coinbase) - assert(res.status == EVM.Status.failed, message: "unexpected status") - assert(res.errorCode == 301, message: "unexpected error code: \(res.errorCode)") - assert(res.errorMessage == "out of gas", message: "unexpected error message: \(res.errorMessage)") + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + assert(res.deployedContract == nil, message: "unexpected deployed contract") } } `, @@ -3569,14 +6483,12 @@ func TestNativePrecompiles(t *testing.T) { coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) - // The address below is the latest precompile on the Prague hard-fork: - // https://github.com/ethereum/go-ethereum/blob/v1.16.3/core/vm/contracts.go#L140 . - to := common.HexToAddress("0x00000000000000000000000000000000000000011") + num := int64(12) innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - to, - nil, - big.NewInt(1_000_000), - uint64(21_000), + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "store", big.NewInt(num)), + big.NewInt(0), + uint64(100_000), big.NewInt(1), ) @@ -3588,7 +6500,7 @@ func TestNativePrecompiles(t *testing.T) { unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), ).WithType(stdlib.EVMAddressBytesCadenceType) - txBody, err := flow.NewTransactionBodyBuilder(). + txBody, err = flow.NewTransactionBodyBuilder(). SetScript(code). SetPayer(sc.FlowServiceAccount.Address). AddAuthorizer(sc.FlowServiceAccount.Address). @@ -3597,208 +6509,387 @@ func TestNativePrecompiles(t *testing.T) { Build() require.NoError(t, err) - tx := fvm.Transaction(txBody, 0) + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) + }) - state, output, err := vm.Run( - ctx, - tx, - snapshot, + t.Run("testing EVM.batchRun when EVM is paused", func(t *testing.T) { + batchRunCode := []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]) { + prepare(account: &Account) { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + let batchResults = EVM.batchRun(txs: txs, coinbase: coinbase) + + assert(batchResults.length == txs.length, message: "invalid result length") + for res in batchResults { + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + batchCount := 5 + txBytes := make([]cadence.Value, batchCount) + for i := 0; i < batchCount; i++ { + num := int64(i) + // prepare batch of transaction payloads + tx := testAccount.PrepareSignAndEncodeTx(t, + testContract.DeployedAt.ToCommon(), + testContract.MakeCallData(t, "storeWithLog", big.NewInt(num)), + big.NewInt(0), + uint64(100_000), + big.NewInt(1), + ) + + // build txs argument + txBytes[i] = cadence.NewArray( + unittest.BytesToCdcUInt8(tx), + ).WithType(stdlib.EVMTransactionBytesCadenceType) + } + + coinbase := cadence.NewArray( + unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), + ).WithType(stdlib.EVMAddressBytesCadenceType) + + txs := cadence.NewArray(txBytes). + WithType(cadence.NewVariableSizedArrayType( + stdlib.EVMTransactionBytesCadenceType, + )) + + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(batchRunCode). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(json.MustEncode(txs)). + AddArgument(json.MustEncode(coinbase)). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) + }) + + t.Run("testing EVM.createCadenceOwnedAccount when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( + ` + import EVM from %s + + transaction(code: [UInt8]){ + prepare(account: auth(BorrowValue) &Account) { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let res = cadenceOwnedAccount.deploy( + code: code, + gasLimit: 16_777_216, + value: EVM.Balance(attoflow: 1230000000000000000) + ) + destroy <- cadenceOwnedAccount + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + contractCode := json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.ByteCode), + ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), ) + + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(contractCode). + Build() require.NoError(t, err) - require.NoError(t, output.Err) - require.NotEmpty(t, state.WriteSet) - // assert event fields are correct - require.Len(t, output.Events, 2) - txEvent := output.Events[0] - txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) - require.Equal(t, uint16(types.ExecutionErrCodeOutOfGas), txEventPayload.ErrorCode) - require.Equal(t, uint16(0), txEventPayload.Index) - require.Equal(t, uint64(21000), txEventPayload.GasConsumed) + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) }) - }) -} -func TestEVMFileSystemContract(t *testing.T) { - chain := flow.Emulator.Chain() - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + t.Run("testing CadenceOwnedAccount.deploy when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( + ` + import EVM from %s - runFileSystemContract := func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - computeLimit uint64, - ) ( - *snapshot.ExecutionSnapshot, - fvm.ProcedureOutput, - ) { - code := []byte(fmt.Sprintf( - ` + transaction(code: [UInt8]){ + prepare(account: auth(BorrowValue) &Account) { + let cadenceOwnedAccount = account.storage.borrow( + from: /storage/coa + )! + let res = cadenceOwnedAccount.deploy( + code: code, + gasLimit: 16_777_216, + value: EVM.Balance(attoflow: 1230000000000000000) + ) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) + + coinbaseAddr := types.Address{1, 2, 3} + coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) + require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + + contractCode := json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.ByteCode), + ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)), + ) + + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(contractCode). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) + }) + + t.Run("testing CadenceOwnedAccount.call when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( + ` import EVM from %s - transaction(tx: [UInt8], coinbaseBytes: [UInt8; 20]){ - prepare(account: &Account) { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - let res = EVM.run(tx: tx, coinbase: coinbase) + transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt){ + prepare(account: auth(Storage) &Account) { + let coa = account.storage.borrow( + from: /storage/coa + )! + let res = coa.call( + to: EVM.addressFromString(to), + data: data, + gasLimit: gasLimit, + value: EVM.Balance(attoflow: value) + ) + + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") } } `, - sc.EVMContract.Address.HexWithPrefix(), - )) + sc.EVMContract.Address.HexWithPrefix(), + )) - coinbaseAddr := types.Address{1, 2, 3} - coinbaseBalance := getEVMAccountBalance(t, ctx, vm, snapshot, coinbaseAddr) - require.Zero(t, types.BalanceToBigInt(coinbaseBalance).Uint64()) + data := json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.MakeCallData(t, "retrieve")), + ).WithType(stdlib.EVMTransactionBytesCadenceType), + ) + toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) + require.NoError(t, err) + to := json.MustEncode(toAddress) - var buffer bytes.Buffer - address := common.HexToAddress("0xea02F564664A477286B93712829180be4764fAe2") - chunkHash := "0x2521660d04da85198d1cc71c20a69b7e875ebbf1682f6a5c6a3fec69068ccc13" - index := int64(0) - chunk := "T1ARYBYsPOJPVYoU7wVp+PYuXmdS6bgkLf2egcxa+1hP64wAxfkLXtnllU6DmEuj+Id4oWl1ZV4ftQ+ofQ3DQhOoxNlPZGOYbhoMLuzE" - for i := 0; i <= 500; i++ { - buffer.WriteString(chunk) - } - innerTxBytes := testAccount.PrepareSignAndEncodeTx(t, - testContract.DeployedAt.ToCommon(), - testContract.MakeCallData( - t, - "publishChunk", - address, - chunkHash, - big.NewInt(index), - buffer.String(), - ), - big.NewInt(0), - uint64(2_132_171), - big.NewInt(1), - ) + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(data). + AddArgument(to). + AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). + AddArgument(json.MustEncode(cadence.NewUInt(0))). + Build() + require.NoError(t, err) - innerTx := cadence.NewArray( - unittest.BytesToCdcUInt8(innerTxBytes), - ).WithType(stdlib.EVMTransactionBytesCadenceType) + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) + }) - coinbase := cadence.NewArray( - unittest.BytesToCdcUInt8(coinbaseAddr.Bytes()), - ).WithType(stdlib.EVMAddressBytesCadenceType) + t.Run("testing CadenceOwnedAccount.deposit when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s - txBody, err := flow.NewTransactionBodyBuilder(). - SetScript(code). - SetComputeLimit(computeLimit). - AddAuthorizer(sc.FlowServiceAccount.Address). - AddArgument(json.MustEncode(innerTx)). - AddArgument(json.MustEncode(coinbase)). - Build() - require.NoError(t, err) + transaction { + prepare(account: auth(Storage) &Account) { + let admin = account + .storage.borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin)! + let minter <- admin.createNewMinter(allowedAmount: 2.34) + let vault <- minter.mintTokens(amount: 2.34) + destroy minter - tx := fvm.Transaction( - txBody, - 0, - ) + let coa = account.storage.borrow<&EVM.CadenceOwnedAccount>( + from: /storage/coa + )! + coa.deposit(from: <-vault) + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) - state, output, err := vm.Run(ctx, tx, snapshot) - require.NoError(t, err) - return state, output - } + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) - t.Run("happy case", func(t *testing.T) { - RunContractWithNewEnvironment( - t, - chain, - GetFileSystemContract(t), - func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { - state, output := runFileSystemContract(ctx, vm, snapshot, testContract, testAccount, 10001) + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) + }) - require.NoError(t, output.Err) - require.NotEmpty(t, state.WriteSet) - snapshot = snapshot.Append(state) + t.Run("testing CadenceOwnedAccount.withdraw when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( + ` + import EVM from %s + import FlowToken from %s - // assert event fields are correct - require.Len(t, output.Events, 2) - txEvent := output.Events[0] - txEventPayload := TxEventToPayload(t, txEvent, sc.EVMContract.Address) + transaction { + prepare(account: auth(Storage) &Account) { + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let coa = account.storage.borrow( + from: /storage/coa + )! + let vault2 <- coa.withdraw(balance: bal) + destroy <- vault2 + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + )) - // fee transfer event - feeTransferEvent := output.Events[1] - feeTranferEventPayload := TxEventToPayload(t, feeTransferEvent, sc.EVMContract.Address) - require.Equal(t, uint16(types.ErrCodeNoError), feeTranferEventPayload.ErrorCode) - require.Equal(t, uint16(1), feeTranferEventPayload.Index) - require.Equal(t, uint64(21000), feeTranferEventPayload.GasConsumed) - // - //// commit block - blockEventPayload, _ := callEVMHeartBeat(t, - ctx, - vm, - snapshot, - ) - // - require.NotEmpty(t, blockEventPayload.Hash) - require.Equal(t, uint64(2_132_170), blockEventPayload.TotalGasUsed) + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + Build() + require.NoError(t, err) - txHashes := types.TransactionHashes{txEventPayload.Hash, feeTranferEventPayload.Hash} - require.Equal(t, - txHashes.RootHash(), - blockEventPayload.TransactionHashRoot, + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", ) - require.NotEmpty(t, blockEventPayload.ReceiptRoot) - - require.Equal(t, uint16(types.ErrCodeNoError), txEventPayload.ErrorCode) - require.Equal(t, uint16(0), txEventPayload.Index) - require.Equal(t, blockEventPayload.Height, txEventPayload.BlockHeight) - require.Equal(t, blockEventPayload.TotalGasUsed-feeTranferEventPayload.GasConsumed, txEventPayload.GasConsumed) - require.Empty(t, txEventPayload.ContractAddress) + }) - require.Greater(t, int(output.ComputationUsed), 900) - }, - fvm.WithExecutionEffortWeights( - environment.MainnetExecutionEffortWeights, - ), - ) - }) + t.Run("testing CadenceOwnedAccount.callWithSigAndArgs when EVM is paused", func(t *testing.T) { + code = []byte(fmt.Sprintf( + ` + import EVM from %s - t.Run("insufficient FVM computation to execute EVM transaction", func(t *testing.T) { - RunContractWithNewEnvironment( - t, - chain, - GetFileSystemContract(t), - func( - ctx fvm.Context, - vm fvm.VM, - snapshot snapshot.SnapshotTree, - testContract *TestContract, - testAccount *EOATestAccount, - ) { - state, output := runFileSystemContract(ctx, vm, snapshot, testContract, testAccount, 500) - snapshot = snapshot.Append(state) + transaction(data: [UInt8], to: String, gasLimit: UInt64, value: UInt){ + prepare(account: auth(Storage) &Account) { + let coa = account.storage.borrow( + from: /storage/coa + )! + let res = coa.callWithSigAndArgs( + to: EVM.addressFromString(to), + signature: "store(uint256)", + args: data, + gasLimit: gasLimit, + value: value, + resultTypes: [Type()], + ) - require.Len(t, output.Events, 0) + assert(res.status == EVM.Status.successful, message: "unexpected status") + assert(res.errorCode == 0, message: "unexpected error code") + } + } + `, + sc.EVMContract.Address.HexWithPrefix(), + )) - //// commit block - blockEventPayload, _ := callEVMHeartBeat(t, - ctx, - vm, - snapshot, + data := json.MustEncode( + cadence.NewArray( + unittest.BytesToCdcUInt8(testContract.MakeCallData(t, "retrieve")), + ).WithType(stdlib.EVMTransactionBytesCadenceType), ) - // - require.NotEmpty(t, blockEventPayload.Hash) - require.Equal(t, uint64(0), blockEventPayload.TotalGasUsed) + toAddress, err := cadence.NewString(testContract.DeployedAt.ToCommon().Hex()) + require.NoError(t, err) + to := json.MustEncode(toAddress) - // only a small amount of computation was used due to the EVM transaction never being executed - require.Less(t, int(output.ComputationUsed), 900) - }, - fvm.WithExecutionEffortWeights( - environment.MainnetExecutionEffortWeights, - ), - ) - }) + txBody, err = flow.NewTransactionBodyBuilder(). + SetScript(code). + SetPayer(sc.FlowServiceAccount.Address). + AddAuthorizer(sc.FlowServiceAccount.Address). + AddArgument(data). + AddArgument(to). + AddArgument(json.MustEncode(cadence.NewUInt64(50_000))). + AddArgument(json.MustEncode(cadence.NewUInt(0))). + Build() + require.NoError(t, err) + + tx = fvm.Transaction(txBody, 0) + _, output, err = vm.Run(ctx, tx, snapshot) + require.NoError(t, err) + require.Error(t, output.Err) + require.ErrorContains( + t, + output.Err, + "EVM operations are temporarily paused", + ) + }) + }, + ) } func createAndFundFlowAccount( @@ -3824,7 +6915,7 @@ func createAndFundFlowAccount( code := []byte(fmt.Sprintf( ` import FlowToken from %s - import FungibleToken from %s + import FungibleToken from %s transaction { prepare(account: auth(BorrowValue) &Account) { @@ -3894,7 +6985,7 @@ func setupCOA( transaction(amount: UFix64) { prepare(account: auth(Capabilities, Storage) &Account) { let cadenceOwnedAccount1 <- EVM.createCadenceOwnedAccount() - + let vaultRef = account.storage .borrow(from: /storage/flowTokenVault) ?? panic("Could not borrow reference to the owner's Vault!") @@ -3903,7 +6994,7 @@ func setupCOA( let vault <- vaultRef.withdraw(amount: amount) as! @FlowToken.Vault cadenceOwnedAccount1.deposit(from: <-vault) } - + account.storage.save<@EVM.CadenceOwnedAccount>( <-cadenceOwnedAccount1, to: /storage/coa @@ -4092,9 +7183,10 @@ func RunWithNewEnvironment( t *testing.T, chain flow.Chain, f func(fvm.Context, fvm.VM, snapshot.SnapshotTree, *TestContract, *EOATestAccount), + bootstrapOpts ...fvm.BootstrapProcedureOption, ) { rootAddr := evm.StorageAccountAddress(chain.ChainID()) - RunWithTestBackend(t, func(backend *TestBackend) { + RunWithTestBackend(t, chain.ChainID(), func(backend *TestBackend) { RunWithDeployedContract(t, GetStorageTestContract(t), backend, rootAddr, func(testContract *TestContract) { RunWithEOATestAccount(t, backend, rootAddr, func(testAccount *EOATestAccount) { blocks := new(envMock.Blocks) @@ -4104,8 +7196,7 @@ func RunWithNewEnvironment( block1.ToHeader(), ).Return(block1.ToHeader(), nil) - ctx := fvm.NewContext( - fvm.WithChain(chain), + opts := []fvm.Option{ fvm.WithBlockHeader(block1.ToHeader()), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), @@ -4113,14 +7204,19 @@ func RunWithNewEnvironment( fvm.WithRandomSourceHistoryCallAllowed(true), fvm.WithBlocks(blocks), fvm.WithCadenceLogging(true), - ) + } + ctx := fvm.NewContext(chain, opts...) vm := fvm.NewVirtualMachine() snapshotTree := snapshot.NewSnapshotTree(backend) baseBootstrapOpts := []fvm.BootstrapProcedureOption{ fvm.WithInitialTokenSupply(unittest.GenesisTokenSupply), + fvm.WithExecutionEffortWeights( + environment.MainnetExecutionEffortWeights, + ), } + baseBootstrapOpts = append(baseBootstrapOpts, bootstrapOpts...) executionSnapshot, _, err := vm.Run( ctx, @@ -4131,7 +7227,7 @@ func RunWithNewEnvironment( snapshotTree = snapshotTree.Append(executionSnapshot) f( - fvm.NewContextFromParent(ctx, fvm.WithEVMEnabled(true)), + ctx, vm, snapshotTree, testContract, @@ -4151,7 +7247,7 @@ func RunContractWithNewEnvironment( ) { rootAddr := evm.StorageAccountAddress(chain.ChainID()) - RunWithTestBackend(t, func(backend *TestBackend) { + RunWithTestBackend(t, chain.ChainID(), func(backend *TestBackend) { RunWithDeployedContract(t, tc, backend, rootAddr, func(testContract *TestContract) { RunWithEOATestAccount(t, backend, rootAddr, func(testAccount *EOATestAccount) { @@ -4164,7 +7260,6 @@ func RunContractWithNewEnvironment( ).Return(header1, nil) opts := []fvm.Option{ - fvm.WithChain(chain), fvm.WithBlockHeader(header1), fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), @@ -4173,7 +7268,7 @@ func RunContractWithNewEnvironment( fvm.WithBlocks(blocks), fvm.WithCadenceLogging(true), } - ctx := fvm.NewContext(opts...) + ctx := fvm.NewContext(chain, opts...) vm := fvm.NewVirtualMachine() snapshotTree := snapshot.NewSnapshotTree(backend) @@ -4192,7 +7287,7 @@ func RunContractWithNewEnvironment( snapshotTree = snapshotTree.Append(executionSnapshot) f( - fvm.NewContextFromParent(ctx, fvm.WithEVMEnabled(true)), + ctx, vm, snapshotTree, testContract, diff --git a/fvm/evm/handler/blockstore.go b/fvm/evm/handler/blockstore.go deleted file mode 100644 index 3e1f2581c02..00000000000 --- a/fvm/evm/handler/blockstore.go +++ /dev/null @@ -1,203 +0,0 @@ -package handler - -import ( - "fmt" - "time" - - gethCommon "github.com/ethereum/go-ethereum/common" - - "github.com/onflow/flow-go/fvm/evm/types" - "github.com/onflow/flow-go/model/flow" -) - -const ( - BlockHashListCapacity = 256 - BlockStoreLatestBlockKey = "LatestBlock" - BlockStoreLatestBlockProposalKey = "LatestBlockProposal" -) - -type BlockStore struct { - chainID flow.ChainID - backend types.Backend - rootAddress flow.Address -} - -var _ types.BlockStore = &BlockStore{} - -// NewBlockStore constructs a new block store -func NewBlockStore( - chainID flow.ChainID, - backend types.Backend, - rootAddress flow.Address, -) *BlockStore { - return &BlockStore{ - chainID: chainID, - backend: backend, - rootAddress: rootAddress, - } -} - -// BlockProposal returns the block proposal to be updated by the handler -func (bs *BlockStore) BlockProposal() (*types.BlockProposal, error) { - // first fetch it from the storage - data, err := bs.backend.GetValue(bs.rootAddress[:], []byte(BlockStoreLatestBlockProposalKey)) - if err != nil { - return nil, err - } - if len(data) != 0 { - return types.NewBlockProposalFromBytes(data) - } - bp, err := bs.constructBlockProposal() - if err != nil { - return nil, err - } - // store block proposal - err = bs.UpdateBlockProposal(bp) - if err != nil { - return nil, err - } - return bp, nil -} - -func (bs *BlockStore) constructBlockProposal() (*types.BlockProposal, error) { - // if available construct a new one - cadenceHeight, err := bs.backend.GetCurrentBlockHeight() - if err != nil { - return nil, err - } - - cadenceBlock, found, err := bs.backend.GetBlockAtHeight(cadenceHeight) - if err != nil { - return nil, err - } - if !found { - return nil, fmt.Errorf("cadence block not found") - } - - lastExecutedBlock, err := bs.LatestBlock() - if err != nil { - return nil, err - } - - parentHash, err := lastExecutedBlock.Hash() - if err != nil { - return nil, err - } - - // cadence block timestamp is unix nanoseconds but evm blocks - // expect timestamps in unix seconds so we convert here - timestamp := uint64(cadenceBlock.Timestamp / int64(time.Second)) - - // read a random value for block proposal - prevrandao := gethCommon.Hash{} - err = bs.backend.ReadRandom(prevrandao[:]) - if err != nil { - return nil, err - } - - blockProposal := types.NewBlockProposal( - parentHash, - lastExecutedBlock.Height+1, - timestamp, - lastExecutedBlock.TotalSupply, - prevrandao, - ) - - return blockProposal, nil -} - -// UpdateBlockProposal updates the block proposal -func (bs *BlockStore) UpdateBlockProposal(bp *types.BlockProposal) error { - blockProposalBytes, err := bp.ToBytes() - if err != nil { - return types.NewFatalError(err) - } - - return bs.backend.SetValue( - bs.rootAddress[:], - []byte(BlockStoreLatestBlockProposalKey), - blockProposalBytes, - ) -} - -// CommitBlockProposal commits the block proposal to the chain -func (bs *BlockStore) CommitBlockProposal(bp *types.BlockProposal) error { - bp.PopulateRoots() - - blockBytes, err := bp.Block.ToBytes() - if err != nil { - return types.NewFatalError(err) - } - - err = bs.backend.SetValue(bs.rootAddress[:], []byte(BlockStoreLatestBlockKey), blockBytes) - if err != nil { - return err - } - - hash, err := bp.Block.Hash() - if err != nil { - return err - } - - bhl, err := bs.getBlockHashList() - if err != nil { - return err - } - err = bhl.Push(bp.Block.Height, hash) - if err != nil { - return err - } - - // construct a new block proposal and store - newBP, err := bs.constructBlockProposal() - if err != nil { - return err - } - err = bs.UpdateBlockProposal(newBP) - if err != nil { - return err - } - - return nil -} - -// LatestBlock returns the latest executed block -func (bs *BlockStore) LatestBlock() (*types.Block, error) { - data, err := bs.backend.GetValue(bs.rootAddress[:], []byte(BlockStoreLatestBlockKey)) - if err != nil { - return nil, err - } - if len(data) == 0 { - return types.GenesisBlock(bs.chainID), nil - } - return types.NewBlockFromBytes(data) -} - -// BlockHash returns the block hash for the last x blocks -func (bs *BlockStore) BlockHash(height uint64) (gethCommon.Hash, error) { - bhl, err := bs.getBlockHashList() - if err != nil { - return gethCommon.Hash{}, err - } - _, hash, err := bhl.BlockHashByHeight(height) - return hash, err -} - -func (bs *BlockStore) getBlockHashList() (*BlockHashList, error) { - bhl, err := NewBlockHashList(bs.backend, bs.rootAddress, BlockHashListCapacity) - if err != nil { - return nil, err - } - - if bhl.IsEmpty() { - err = bhl.Push( - types.GenesisBlock(bs.chainID).Height, - types.GenesisBlockHash(bs.chainID), - ) - if err != nil { - return nil, err - } - } - - return bhl, nil -} diff --git a/fvm/evm/handler/blockstore_test.go b/fvm/evm/handler/blockstore_test.go deleted file mode 100644 index c2e40135949..00000000000 --- a/fvm/evm/handler/blockstore_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package handler_test - -import ( - "math/big" - "testing" - - gethCommon "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" - - "github.com/onflow/flow-go/fvm/evm/handler" - "github.com/onflow/flow-go/fvm/evm/testutils" - "github.com/onflow/flow-go/fvm/evm/types" - "github.com/onflow/flow-go/model/flow" -) - -func TestBlockStore(t *testing.T) { - - var chainID = flow.Testnet - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { - testutils.RunWithTestFlowEVMRootAddress(t, backend, func(root flow.Address) { - bs := handler.NewBlockStore(chainID, backend, root) - - // check the Genesis block - b, err := bs.LatestBlock() - require.NoError(t, err) - require.Equal(t, types.GenesisBlock(chainID), b) - h, err := bs.BlockHash(0) - require.NoError(t, err) - require.Equal(t, types.GenesisBlockHash(chainID), h) - - // test block proposal construction from the Genesis block - bp, err := bs.BlockProposal() - require.NoError(t, err) - require.Equal(t, uint64(1), bp.Height) - expectedParentHash, err := types.GenesisBlock(chainID).Hash() - require.NoError(t, err) - require.Equal(t, expectedParentHash, bp.ParentBlockHash) - - // if no commit and again block proposal call should return the same - retbp, err := bs.BlockProposal() - require.NoError(t, err) - require.Equal(t, bp, retbp) - - // update the block proposal - bp.TotalGasUsed += 100 - err = bs.UpdateBlockProposal(bp) - require.NoError(t, err) - - // reset the bs and check if it still return the block proposal - bs = handler.NewBlockStore(chainID, backend, root) - retbp, err = bs.BlockProposal() - require.NoError(t, err) - require.Equal(t, bp, retbp) - - // update the block proposal again - supply := big.NewInt(100) - bp.TotalSupply = supply - err = bs.UpdateBlockProposal(bp) - require.NoError(t, err) - // this should still return the genesis block - retb, err := bs.LatestBlock() - require.NoError(t, err) - require.Equal(t, types.GenesisBlock(chainID), retb) - - // commit the changes - err = bs.CommitBlockProposal(bp) - require.NoError(t, err) - retb, err = bs.LatestBlock() - require.NoError(t, err) - require.Equal(t, supply, retb.TotalSupply) - require.Equal(t, uint64(1), retb.Height) - - retbp, err = bs.BlockProposal() - require.NoError(t, err) - require.Equal(t, uint64(2), retbp.Height) - - // check block hashes - // genesis - h, err = bs.BlockHash(0) - require.NoError(t, err) - require.Equal(t, types.GenesisBlockHash(chainID), h) - - // block 1 - h, err = bs.BlockHash(1) - require.NoError(t, err) - expected, err := bp.Hash() - require.NoError(t, err) - require.Equal(t, expected, h) - - // block 2 - h, err = bs.BlockHash(2) - require.NoError(t, err) - require.Equal(t, gethCommon.Hash{}, h) - }) - - }) - -} diff --git a/fvm/evm/handler/handler.go b/fvm/evm/handler/handler.go index abd110c774e..3f935bc87a1 100644 --- a/fvm/evm/handler/handler.go +++ b/fvm/evm/handler/handler.go @@ -11,6 +11,9 @@ import ( "github.com/onflow/flow-go/fvm/environment" fvmErrors "github.com/onflow/flow-go/fvm/errors" + "github.com/onflow/flow-go/fvm/evm" + "github.com/onflow/flow-go/fvm/evm/backends" + "github.com/onflow/flow-go/fvm/evm/emulator/state" "github.com/onflow/flow-go/fvm/evm/events" "github.com/onflow/flow-go/fvm/evm/handler/coa" "github.com/onflow/flow-go/fvm/evm/types" @@ -18,17 +21,31 @@ import ( "github.com/onflow/flow-go/module/trace" ) +const ( + maxDryCallCacheResultDataSize = 1024 + maxDryCallCacheCount = 16 +) + +type evmDryCallCacheKey struct { + from types.Address + txHash gethCommon.Hash +} + // ContractHandler is responsible for triggering calls to emulator, metering, // event emission and updating the block type ContractHandler struct { flowChainID flow.ChainID evmContractAddress flow.Address flowTokenAddress common.Address - blockStore types.BlockStore addressAllocator types.AddressAllocator - backend types.Backend + backend backends.Backend emulator types.Emulator precompiledContracts []types.PrecompiledContract + // evmDryCallCache caches EVM drycall results in a transaction. + // evmDryCallCache is cleared when the EVM state is changed via + // COA.deploy(), COA.call(), Run(), BatchRun(), etc., or + // at the end of a transaction. + evmDryCallCache map[evmDryCallCacheKey]*types.ResultSummary } var _ types.ContractHandler = &ContractHandler{} @@ -39,16 +56,14 @@ func NewContractHandler( evmContractAddress flow.Address, flowTokenAddress common.Address, randomBeaconAddress flow.Address, - blockStore types.BlockStore, addressAllocator types.AddressAllocator, - backend types.Backend, + backend backends.Backend, emulator types.Emulator, ) *ContractHandler { return &ContractHandler{ flowChainID: flowChainID, evmContractAddress: evmContractAddress, flowTokenAddress: flowTokenAddress, - blockStore: blockStore, addressAllocator: addressAllocator, backend: backend, emulator: emulator, @@ -61,6 +76,18 @@ func NewContractHandler( } } +// ResetCaches resets caches. It is called by the runtime pool via +// SwappableEnvironment.onSwap when the runtime is borrowed or returned. +func (h *ContractHandler) ResetCaches() { + h.evmDryCallCache = nil +} + +// invalidateDryCallCache clear evmDryCallCache. It is called when +// the EVM state is about to change via COA.deploy(), COA.call(), Run(), BatchRun(), etc. +func (h *ContractHandler) invalidateDryCallCache() { + clear(h.evmDryCallCache) +} + // FlowTokenAddress returns the address where the FlowToken contract is deployed func (h *ContractHandler) FlowTokenAddress() common.Address { return h.flowTokenAddress @@ -71,6 +98,67 @@ func (h *ContractHandler) EVMContractAddress() common.Address { return common.Address(h.evmContractAddress) } +func (h *ContractHandler) validateTestOperation() { + if !h.backend.EVMTestOperationsAllowed() { + panicOnError(types.ErrUnsupportedOperation) + } +} + +// SetState sets a value for the given storage slot. +// It returns the previous value in any case. +// The operation is only allowed for testing purposes. +func (h *ContractHandler) SetState( + address types.Address, + slot gethCommon.Hash, + value gethCommon.Hash, +) gethCommon.Hash { + + h.validateTestOperation() + + execState, err := state.NewStateDB(h.backend, evm.StorageAccountAddress(h.flowChainID)) + panicOnError(err) + + prevValue := execState.SetState(address.ToCommon(), slot, value) + _, err = execState.Commit(true) + panicOnError(err) + + h.invalidateDryCallCache() + + return prevValue +} + +// GetState returns the value for the given storage slot. +// The operation is only allowed for testing purposes. +func (h *ContractHandler) GetState( + address types.Address, + slot gethCommon.Hash, +) gethCommon.Hash { + + h.validateTestOperation() + + execState, err := state.NewStateDB(h.backend, evm.StorageAccountAddress(h.flowChainID)) + panicOnError(err) + + return execState.GetState(address.ToCommon(), slot) +} + +// RunTxAs runs a transaction by setting the call's `msg.sender` +// to be the `from` address. +// The operation is only allowed for testing purposes. +func (h *ContractHandler) RunTxAs( + from types.Address, + to types.Address, + txData types.Data, + gasLimit types.GasLimit, + balance types.Balance, +) *types.ResultSummary { + + h.validateTestOperation() + + account := h.AccountByAddress(from, true) + return account.Call(to, txData, gasLimit, balance) +} + // DeployCOA deploys a cadence-owned-account and returns the address func (h *ContractHandler) DeployCOA(uuid uint64) types.Address { // capture open tracing traces @@ -125,7 +213,7 @@ func (h *ContractHandler) AccountByAddress(addr types.Address, isAuthorized bool // LastExecutedBlock returns the last executed block func (h *ContractHandler) LastExecutedBlock() *types.Block { - block, err := h.blockStore.LatestBlock() + block, err := h.backend.LatestBlock() panicOnError(err) return block } @@ -184,7 +272,9 @@ func (h *ContractHandler) runWithGasFeeRefund(gasFeeCollector types.Address, f f func (h *ContractHandler) BatchRun(rlpEncodedTxs [][]byte, gasFeeCollector types.Address) []*types.ResultSummary { // capture open tracing span := h.backend.StartChildSpan(trace.FVMEVMBatchRun) - span.SetAttributes(attribute.Int("tx_counts", len(rlpEncodedTxs))) + if span.Tracer != nil { + span.SetAttributes(attribute.Int("tx_counts", len(rlpEncodedTxs))) + } defer span.End() var results []*types.Result @@ -203,7 +293,14 @@ func (h *ContractHandler) BatchRun(rlpEncodedTxs [][]byte, gasFeeCollector types return resSummaries } -func (h *ContractHandler) batchRun(rlpEncodedTxs [][]byte) ([]*types.Result, error) { +func (h *ContractHandler) batchRun(rlpEncodedTxs [][]byte) (_ []*types.Result, err error) { + defer func() { + if err == nil { + // Invalidate drycall cache if EVM state is changed (batchRun is successful). + h.invalidateDryCallCache() + } + }() + // step 1 - transaction decoding and check that enough evm gas is available in the FVM transaction // remainingGasLimit is the remaining EVM gas available in hte FVM transaction @@ -309,10 +406,7 @@ func (h *ContractHandler) batchRun(rlpEncodedTxs [][]byte) ([]*types.Result, err } // update the block proposal - err = h.blockStore.UpdateBlockProposal(bp) - if err != nil { - return nil, err - } + h.backend.StageBlockProposal(bp) return res, nil } @@ -323,15 +417,22 @@ func (h *ContractHandler) CommitBlockProposal() { panicOnError(h.commitBlockProposal()) } -func (h *ContractHandler) commitBlockProposal() error { +func (h *ContractHandler) commitBlockProposal() (err error) { + defer func() { + if err == nil { + // Invalidate drycall cache if EVM state is changed (commitBlockProposal is successful). + h.invalidateDryCallCache() + } + }() + // load latest block proposal - bp, err := h.blockStore.BlockProposal() + bp, err := h.backend.BlockProposal() if err != nil { return err } // commit the proposal - err = h.blockStore.CommitBlockProposal(bp) + err = h.backend.CommitBlockProposal(bp) if err != nil { return err } @@ -361,7 +462,14 @@ func (h *ContractHandler) commitBlockProposal() error { return nil } -func (h *ContractHandler) run(rlpEncodedTx []byte) (*types.Result, error) { +func (h *ContractHandler) run(rlpEncodedTx []byte) (_ *types.Result, err error) { + defer func() { + if err == nil { + // Invalidate drycall cache if EVM state is changed (run is successful). + h.invalidateDryCallCache() + } + }() + // step 1 - transaction decoding tx, err := h.decodeTransaction(rlpEncodedTx) if err != nil { @@ -418,10 +526,7 @@ func (h *ContractHandler) run(rlpEncodedTx []byte) (*types.Result, error) { // step 8 - update the block proposal bp.AppendTransaction(res) - err = h.blockStore.UpdateBlockProposal(bp) - if err != nil { - return nil, err - } + h.backend.StageBlockProposal(bp) // step 9 - emit transaction event err = h.emitEvent( @@ -449,16 +554,16 @@ func (h *ContractHandler) DryRun( ) *types.ResultSummary { defer h.backend.StartChildSpan(trace.FVMEVMDryRun).End() - res, err := h.dryRun(rlpEncodedTx, from) + resSummary, err := h.dryRun(rlpEncodedTx, from) panicOnError(err) - return res.ResultSummary() + return resSummary } func (h *ContractHandler) dryRun( rlpEncodedTx []byte, from types.Address, -) (*types.Result, error) { +) (*types.ResultSummary, error) { // step 1 - transaction decoding err := h.backend.MeterComputation( common.ComputationUsage{ @@ -476,6 +581,30 @@ func (h *ContractHandler) dryRun( return nil, err } + return h.dryRunTx(&tx, from) +} + +func (h *ContractHandler) dryRunTx( + tx *gethTypes.Transaction, + from types.Address, +) (*types.ResultSummary, error) { + // check if enough computation is available + err := h.checkGasLimit(types.GasLimit(tx.Gas())) + if err != nil { + return nil, err + } + + // Cache lookup + key := evmDryCallCacheKey{from: from, txHash: tx.Hash()} + if cached, ok := h.evmDryCallCache[key]; ok { + // Meter cached gas + panicOnError(h.backend.MeterComputation(common.ComputationUsage{ + Kind: environment.ComputationKindEVMGasUsage, + Intensity: cached.GasConsumed, + })) + return cached, nil + } + bp, err := h.getBlockProposal() if err != nil { return nil, err @@ -490,7 +619,13 @@ func (h *ContractHandler) dryRun( return nil, err } - res, err := blk.DryRunTransaction(&tx, from.ToCommon()) + var res *types.Result + // just like with EVM.run / EVM.batchRun / COA.call, we disable metering + // so we can fully meter the gas usage in the next step, even in case + // of unhandled errors/exceptions. + h.backend.RunWithMeteringDisabled(func() { + res, err = blk.DryRunTransaction(tx, from.ToCommon()) + }) if err != nil { return nil, err } @@ -498,7 +633,49 @@ func (h *ContractHandler) dryRun( return nil, types.ErrUnexpectedEmptyResult } - return res, nil + // gas meter even invalid or failed status + if err = h.meterGasUsage(res); err != nil { + return nil, err + } + + resSummary := res.ResultSummary() + + // Skip caching results if they are too large or if the cache has reached its limit. + // These safeguards prevent excessive memory usage from large return data and + // uncontrolled cache growth within a single transaction. + if len(resSummary.ReturnedData) > maxDryCallCacheResultDataSize || + len(h.evmDryCallCache) >= maxDryCallCacheCount { + return resSummary, nil + } + + // Store in cache + if h.evmDryCallCache == nil { + h.evmDryCallCache = make(map[evmDryCallCacheKey]*types.ResultSummary) + } + h.evmDryCallCache[key] = resSummary + + return resSummary, nil +} + +// DryRunWithTxData simulates execution of the provided transaction data. +// The from address is required since the transaction is unsigned. +// The function should not have any persisted changes made to the state. +func (h *ContractHandler) DryRunWithTxData( + txData gethTypes.TxData, + from types.Address, +) *types.ResultSummary { + if txData == nil { + panicOnError(types.ErrUnexpectedEmptyTransactionData) + } + + defer h.backend.StartChildSpan(trace.FVMEVMDryRun).End() + + tx := gethTypes.NewTx(txData) + + resSummary, err := h.dryRunTx(tx, from) + panicOnError(err) + + return resSummary } // checkGasLimit checks if enough computation is left in the environment @@ -560,7 +737,7 @@ func (h *ContractHandler) getBlockContext(bp *types.BlockProposal) ( BlockTimestamp: bp.Timestamp, DirectCallBaseGasUsage: types.DefaultDirectCallBaseGasUsage, GetHashFunc: func(n uint64) gethCommon.Hash { - hash, err := h.blockStore.BlockHash(n) + hash, err := h.backend.BlockHash(n) panicOnError(err) // we have to handle it here given we can't continue with it even in try case return hash }, @@ -573,14 +750,21 @@ func (h *ContractHandler) getBlockContext(bp *types.BlockProposal) ( } func (h *ContractHandler) getBlockProposal() (*types.BlockProposal, error) { - return h.blockStore.BlockProposal() + return h.backend.BlockProposal() } func (h *ContractHandler) executeAndHandleCall( call *types.DirectCall, totalSupplyDiff *big.Int, deductSupplyDiff bool, -) (*types.Result, error) { +) (_ *types.Result, err error) { + defer func() { + if err == nil { + // Invalidate drycall cache if EVM state is changed (executeAndHandleCall is successful). + h.invalidateDryCallCache() + } + }() + // step 1 - check enough computation is available if err := h.checkGasLimit(types.GasLimit(call.GasLimit)); err != nil { return nil, err @@ -645,10 +829,7 @@ func (h *ContractHandler) executeAndHandleCall( } // update the block proposal - err = h.blockStore.UpdateBlockProposal(bp) - if err != nil { - return nil, err - } + h.backend.StageBlockProposal(bp) // step 8 - emit transaction event encoded, err := call.Encode() @@ -709,16 +890,7 @@ func (a *Account) Nonce() uint64 { } func (a *Account) nonce() (uint64, error) { - bp, err := a.fch.getBlockProposal() - if err != nil { - return 0, err - } - ctx, err := a.fch.getBlockContext(bp) - if err != nil { - return 0, err - } - - blk, err := a.fch.emulator.NewReadOnlyBlockView(ctx) + blk, err := a.fch.emulator.NewReadOnlyBlockView() if err != nil { return 0, err } @@ -737,17 +909,7 @@ func (a *Account) Balance() types.Balance { } func (a *Account) balance() (types.Balance, error) { - bp, err := a.fch.getBlockProposal() - if err != nil { - return nil, err - } - - ctx, err := a.fch.getBlockContext(bp) - if err != nil { - return nil, err - } - - blk, err := a.fch.emulator.NewReadOnlyBlockView(ctx) + blk, err := a.fch.emulator.NewReadOnlyBlockView() if err != nil { return nil, err } @@ -767,17 +929,7 @@ func (a *Account) Code() types.Code { } func (a *Account) code() (types.Code, error) { - bp, err := a.fch.getBlockProposal() - if err != nil { - return nil, err - } - - ctx, err := a.fch.getBlockContext(bp) - if err != nil { - return nil, err - } - - blk, err := a.fch.emulator.NewReadOnlyBlockView(ctx) + blk, err := a.fch.emulator.NewReadOnlyBlockView() if err != nil { return nil, err } @@ -795,17 +947,7 @@ func (a *Account) CodeHash() []byte { } func (a *Account) codeHash() ([]byte, error) { - bp, err := a.fch.getBlockProposal() - if err != nil { - return nil, err - } - - ctx, err := a.fch.getBlockContext(bp) - if err != nil { - return nil, err - } - - blk, err := a.fch.emulator.NewReadOnlyBlockView(ctx) + blk, err := a.fch.emulator.NewReadOnlyBlockView() if err != nil { return nil, err } diff --git a/fvm/evm/handler/handler_benchmark_test.go b/fvm/evm/handler/handler_benchmark_test.go index 136a431aec7..7fe9326014f 100644 --- a/fvm/evm/handler/handler_benchmark_test.go +++ b/fvm/evm/handler/handler_benchmark_test.go @@ -14,7 +14,7 @@ func BenchmarkStorage(b *testing.B) { benchmarkStorageGrowth(b, 100, 100, 100) } // benchmark func benchmarkStorageGrowth(b *testing.B, accountCount, setupKittyCount, txPerBlock int) { - testutils.RunWithTestBackend(b, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(b, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(b, backend, func(rootAddr flow.Address) { testutils.RunWithDeployedContract(b, testutils.GetDummyKittyTestContract(b), diff --git a/fvm/evm/handler/handler_test.go b/fvm/evm/handler/handler_test.go index c80c3d5adbe..49435a2d9f7 100644 --- a/fvm/evm/handler/handler_test.go +++ b/fvm/evm/handler/handler_test.go @@ -16,7 +16,10 @@ import ( "github.com/stretchr/testify/require" "github.com/onflow/flow-go/fvm/errors" + "github.com/onflow/flow-go/fvm/evm" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/emulator" + "github.com/onflow/flow-go/fvm/evm/emulator/state" "github.com/onflow/flow-go/fvm/evm/handler" "github.com/onflow/flow-go/fvm/evm/handler/coa" "github.com/onflow/flow-go/fvm/evm/precompiles" @@ -27,7 +30,7 @@ import ( "github.com/onflow/flow-go/module/trace" ) -var flowTokenAddress = common.MustBytesToAddress(systemcontracts.SystemContractsForChain(flow.Emulator).FlowToken.Address.Bytes()) +var flowTokenAddress = common.Address(systemcontracts.SystemContractsForChain(flow.Emulator).FlowToken.Address) var randomBeaconAddress = systemcontracts.SystemContractsForChain(flow.Emulator).RandomBeaconHistory.Address const defaultChainID = flow.Testnet @@ -38,14 +41,12 @@ func TestHandler_TransactionRunOrPanic(t *testing.T) { t.Run("test RunOrPanic run (happy case)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { sc := systemcontracts.SystemContractsForChain(flow.Emulator) - bs := handler.NewBlockStore(defaultChainID, backend, rootAddr) - aa := handler.NewAddressAllocator() result := &types.Result{ @@ -66,7 +67,7 @@ func TestHandler_TransactionRunOrPanic(t *testing.T) { return new(big.Int), nil }, } - handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) coinbase := types.NewAddress(gethCommon.Address{}) @@ -123,10 +124,9 @@ func TestHandler_TransactionRunOrPanic(t *testing.T) { t.Run("test RunOrPanic (unhappy non-fatal cases)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(defaultChainID, backend, rootAddr) aa := handler.NewAddressAllocator() em := &testutils.TestEmulator{ RunTransactionFunc: func(tx *gethTypes.Transaction) (*types.Result, error) { @@ -139,7 +139,7 @@ func TestHandler_TransactionRunOrPanic(t *testing.T) { return new(big.Int), nil }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) coinbase := types.NewAddress(gethCommon.Address{}) @@ -186,10 +186,9 @@ func TestHandler_TransactionRunOrPanic(t *testing.T) { t.Run("test RunOrPanic (fatal cases)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(defaultChainID, backend, rootAddr) aa := handler.NewAddressAllocator() em := &testutils.TestEmulator{ RunTransactionFunc: func(tx *gethTypes.Transaction) (*types.Result, error) { @@ -200,7 +199,7 @@ func TestHandler_TransactionRunOrPanic(t *testing.T) { return new(big.Int), nil }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) assertPanic(t, errors.IsFailure, func() { tx := eoa.PrepareSignAndEncodeTx( t, @@ -221,7 +220,7 @@ func TestHandler_TransactionRunOrPanic(t *testing.T) { t.Run("test RunOrPanic (with integrated emulator)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { handler := SetupHandler(t, backend, rootAddr) @@ -281,7 +280,7 @@ func TestHandler_OpsWithoutEmulator(t *testing.T) { t.Run("test last executed block call", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { handler := SetupHandler(t, backend, rootAddr) @@ -306,7 +305,7 @@ func TestHandler_OpsWithoutEmulator(t *testing.T) { t.Run("test address allocation", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { h := SetupHandler(t, backend, rootAddr) @@ -324,7 +323,7 @@ func TestHandler_COA(t *testing.T) { t.Parallel() t.Run("test deposit/withdraw (with integrated emulator)", func(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { sc := systemcontracts.SystemContractsForChain(flow.Emulator) @@ -400,7 +399,7 @@ func TestHandler_COA(t *testing.T) { require.Greater(t, computationUsed, types.DefaultDirectCallBaseGasUsage*3) // Withdraw with invalid balance - assertPanic(t, types.IsWithdrawBalanceRoundingError, func() { + assertPanic(t, types.IsAWithdrawBalanceRoundingError, func() { // deposit some money foa.Deposit(vault) // then withdraw invalid balance @@ -411,7 +410,7 @@ func TestHandler_COA(t *testing.T) { }) t.Run("test coa deployment", func(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { h := SetupHandler(t, backend, rootAddr) @@ -458,10 +457,9 @@ func TestHandler_COA(t *testing.T) { }) t.Run("test withdraw (unhappy case)", func(t *testing.T) { - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(defaultChainID, backend, rootAddr) aa := handler.NewAddressAllocator() // Withdraw calls are only possible within FOA accounts @@ -472,7 +470,7 @@ func TestHandler_COA(t *testing.T) { }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) account := handler.AccountByAddress(testutils.RandomAddress(t), false) account.Withdraw(types.NewBalanceFromUFix64(1)) @@ -489,7 +487,7 @@ func TestHandler_COA(t *testing.T) { }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) account := handler.AccountByAddress(testutils.RandomAddress(t), true) account.Withdraw(types.NewBalanceFromUFix64(1)) @@ -506,7 +504,7 @@ func TestHandler_COA(t *testing.T) { }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) account := handler.AccountByAddress(testutils.RandomAddress(t), true) account.Withdraw(types.NewBalanceFromUFix64(0)) @@ -523,7 +521,7 @@ func TestHandler_COA(t *testing.T) { }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) account := handler.AccountByAddress(testutils.RandomAddress(t), true) account.Withdraw(types.NewBalanceFromUFix64(0)) @@ -536,10 +534,9 @@ func TestHandler_COA(t *testing.T) { t.Run("test deposit (unhappy case)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(defaultChainID, backend, rootAddr) aa := handler.NewAddressAllocator() // test non fatal error of emulator @@ -553,7 +550,7 @@ func TestHandler_COA(t *testing.T) { }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) account := handler.AccountByAddress(testutils.RandomAddress(t), true) account.Deposit(types.NewFlowTokenVault(types.NewBalanceFromUFix64(1))) @@ -570,7 +567,7 @@ func TestHandler_COA(t *testing.T) { }, } - handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(flow.Testnet, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) account := handler.AccountByAddress(testutils.RandomAddress(t), true) account.Deposit(types.NewFlowTokenVault(types.NewBalanceFromUFix64(1))) @@ -584,7 +581,7 @@ func TestHandler_COA(t *testing.T) { t.Parallel() // TODO update this test with events, gas metering, etc - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { handler := SetupHandler(t, backend, rootAddr) @@ -626,7 +623,7 @@ func TestHandler_COA(t *testing.T) { t.Run("test call to cadence arch", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { blockHeight := uint64(123) backend.GetCurrentBlockHeightFunc = func() (uint64, error) { return blockHeight, nil @@ -680,7 +677,7 @@ func TestHandler_COA(t *testing.T) { t.Run("test block.random call (with integrated emulator)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { random := testutils.RandomCommonHash(t) backend.ReadRandomFunc = func(buffer []byte) error { copy(buffer, random.Bytes()) @@ -724,11 +721,10 @@ func TestHandler_TransactionRun(t *testing.T) { t.Run("test - transaction run (success)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(chainID, backend, rootAddr) aa := handler.NewAddressAllocator() result := &types.Result{ @@ -770,7 +766,7 @@ func TestHandler_TransactionRun(t *testing.T) { }, nil }, } - handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) tx := eoa.PrepareSignAndEncodeTx( t, gethCommon.Address{}, @@ -794,11 +790,10 @@ func TestHandler_TransactionRun(t *testing.T) { t.Run("test - transaction run (failed)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(chainID, backend, rootAddr) aa := handler.NewAddressAllocator() result := &types.Result{ @@ -819,7 +814,7 @@ func TestHandler_TransactionRun(t *testing.T) { return new(big.Int), nil }, } - handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) tx := eoa.PrepareSignAndEncodeTx( t, @@ -843,10 +838,9 @@ func TestHandler_TransactionRun(t *testing.T) { t.Run("test - transaction run (unhappy cases)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(chainID, backend, rootAddr) aa := handler.NewAddressAllocator() evmErr := fmt.Errorf("%w: next nonce %v, tx nonce %v", gethCore.ErrNonceTooLow, 1, 0) em := &testutils.TestEmulator{ @@ -857,7 +851,7 @@ func TestHandler_TransactionRun(t *testing.T) { return new(big.Int), nil }, } - handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, rootAddr, bs, aa, backend, em) + handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) coinbase := types.NewAddress(gethCommon.Address{}) @@ -896,12 +890,11 @@ func TestHandler_TransactionRun(t *testing.T) { t.Run("test - transaction batch run (success)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { sc := systemcontracts.SystemContractsForChain(chainID) - bs := handler.NewBlockStore(chainID, backend, rootAddr) aa := handler.NewAddressAllocator() gasConsumed := testutils.RandomGas(1000) @@ -954,7 +947,7 @@ func TestHandler_TransactionRun(t *testing.T) { }, nil }, } - handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, randomBeaconAddress, bs, aa, backend, em) + handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, randomBeaconAddress, aa, backend, em) gasLimit := uint64(100_000) @@ -1025,10 +1018,9 @@ func TestHandler_TransactionRun(t *testing.T) { t.Run("test - transaction batch run (unhappy case)", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(chainID, backend, rootAddr) aa := handler.NewAddressAllocator() gasConsumed := testutils.RandomGas(1000) @@ -1058,7 +1050,7 @@ func TestHandler_TransactionRun(t *testing.T) { return new(big.Int), nil }, } - handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, randomBeaconAddress, bs, aa, backend, em) + handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, randomBeaconAddress, aa, backend, em) coinbase := types.NewAddress(gethCommon.Address{}) // batch run empty transactions @@ -1075,11 +1067,10 @@ func TestHandler_TransactionRun(t *testing.T) { t.Run("test dry run successful", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { - bs := handler.NewBlockStore(defaultChainID, backend, rootAddr) aa := handler.NewAddressAllocator() nonce := uint64(1) @@ -1126,7 +1117,7 @@ func TestHandler_TransactionRun(t *testing.T) { }, } - handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, randomBeaconAddress, bs, aa, backend, em) + handler := handler.NewContractHandler(chainID, rootAddr, flowTokenAddress, randomBeaconAddress, aa, backend, em) rs := handler.DryRun(rlpTx, from) require.Equal(t, types.StatusSuccessful, rs.Status) @@ -1141,7 +1132,7 @@ func TestHandler_TransactionRun(t *testing.T) { t.Run("test - open tracing", func(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { @@ -1177,10 +1168,10 @@ func TestHandler_TransactionRun(t *testing.T) { acc.Call(types.EmptyAddress, nil, 1000, types.EmptyBalance) backend.ExpectedSpan(t, trace.FVMEVMDeposit) - acc.Deposit(types.NewFlowTokenVault(types.EmptyBalance)) + acc.Deposit(types.NewFlowTokenVault(types.OneFlow())) backend.ExpectedSpan(t, trace.FVMEVMWithdraw) - acc.Withdraw(types.EmptyBalance) + acc.Withdraw(types.OneFlow()) backend.ExpectedSpan(t, trace.FVMEVMDeploy) acc.Deploy(nil, 1, types.EmptyBalance) @@ -1193,7 +1184,7 @@ func TestHandler_TransactionRun(t *testing.T) { func TestHandler_Metrics(t *testing.T) { t.Parallel() - testutils.RunWithTestBackend(t, func(backend *testutils.TestBackend) { + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { gasUsed := testutils.RandomGas(1000) @@ -1224,7 +1215,6 @@ func TestHandler_Metrics(t *testing.T) { rootAddr, flowTokenAddress, rootAddr, - handler.NewBlockStore(defaultChainID, backend, rootAddr), handler.NewAddressAllocator(), backend, em, @@ -1288,6 +1278,206 @@ func TestHandler_Metrics(t *testing.T) { }) } +func TestHandler_GetState(t *testing.T) { + t.Parallel() + + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { + backend.SetEVMTestOperationsAllowed(true) + + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { + testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { + + aa := handler.NewAddressAllocator() + + em := &testutils.TestEmulator{} + handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) + + address := types.NewAddressFromString("0x7e093BA1474b79481f9B87D66c99a819F25e82E2") + slot := gethCommon.HexToHash("0x5591cf37b43a6cc1c6a0b89114c8779fca21c866d7fc4a827ce040428eb28b78") + + handler.GetState(address, slot) + }) + }) + }) +} + +func TestHandler_GetState_Disabled(t *testing.T) { + t.Parallel() + + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { + backend.SetEVMTestOperationsAllowed(false) + + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { + testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { + + aa := handler.NewAddressAllocator() + + em := &testutils.TestEmulator{} + handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) + + address := types.NewAddressFromString("0x7e093BA1474b79481f9B87D66c99a819F25e82E2") + slot := gethCommon.HexToHash("0x5591cf37b43a6cc1c6a0b89114c8779fca21c866d7fc4a827ce040428eb28b78") + + assertPanic(t, types.IsAUnsupportedOperationError, func() { + handler.GetState(address, slot) + }) + }) + }) + }) +} + +func TestHandler_SetState(t *testing.T) { + t.Parallel() + + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { + backend.SetEVMTestOperationsAllowed(true) + + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { + testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { + + aa := handler.NewAddressAllocator() + + execState, err := state.NewStateDB(backend, evm.StorageAccountAddress(flow.Emulator)) + require.NoError(t, err) + + address := types.NewAddressFromString("0x7e093BA1474b79481f9B87D66c99a819F25e82E2") + slot := gethCommon.HexToHash("0x5591cf37b43a6cc1c6a0b89114c8779fca21c866d7fc4a827ce040428eb28b78") + value := gethCommon.HexToHash("0x00000000000000000000000000000000000000000000000000000000000003e8") + + execState.CreateAccount(address.ToCommon()) + prevValue := execState.SetState(address.ToCommon(), slot, value) + _, err = execState.Commit(true) + require.NoError(t, err) + require.Equal(t, gethCommon.Hash{}, prevValue) + + em := &testutils.TestEmulator{} + handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) + + handler.SetState(address, slot, value) + }) + }) + }) +} + +func TestHandler_SetState_Disabled(t *testing.T) { + t.Parallel() + + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { + backend.SetEVMTestOperationsAllowed(false) + + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { + testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { + + aa := handler.NewAddressAllocator() + + execState, err := state.NewStateDB(backend, evm.StorageAccountAddress(flow.Emulator)) + require.NoError(t, err) + + address := types.NewAddressFromString("0x7e093BA1474b79481f9B87D66c99a819F25e82E2") + slot := gethCommon.HexToHash("0x5591cf37b43a6cc1c6a0b89114c8779fca21c866d7fc4a827ce040428eb28b78") + value := gethCommon.HexToHash("0x00000000000000000000000000000000000000000000000000000000000003e8") + + execState.CreateAccount(address.ToCommon()) + prevValue := execState.SetState(address.ToCommon(), slot, value) + _, err = execState.Commit(true) + require.NoError(t, err) + require.Equal(t, gethCommon.Hash{}, prevValue) + + em := &testutils.TestEmulator{} + handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) + + assertPanic(t, types.IsAUnsupportedOperationError, func() { + handler.SetState(address, slot, value) + }) + }) + }) + }) +} + +func TestHandler_RunTxAs(t *testing.T) { + t.Parallel() + + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { + backend.SetEVMTestOperationsAllowed(true) + + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { + testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { + + aa := handler.NewAddressAllocator() + result := &types.Result{ + ReturnedData: testutils.RandomData(t), + GasConsumed: testutils.RandomGas(1000), + Logs: []*gethTypes.Log{ + testutils.GetRandomLogFixture(t), + testutils.GetRandomLogFixture(t), + }, + } + + em := &testutils.TestEmulator{ + NonceOfFunc: func(address types.Address) (uint64, error) { + return 1, nil + }, + DirectCallFunc: func(call *types.DirectCall) (*types.Result, error) { + return result, nil + }, + } + handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) + + from := types.NewAddressFromString("0x7e093BA1474b79481f9B87D66c99a819F25e82E2") + to := types.NewAddressFromString("0x7A038Ec292505B94d20004d3761Db0d1623bb45b") + data := types.Data{10, 50, 20, 30, 50} + gasLimit := types.GasLimit(25_000) + balance := types.Balance(big.NewInt(150)) + + handler.RunTxAs(from, to, data, gasLimit, balance) + }) + }) + }) +} + +func TestHandler_RunTxAs_Disabled(t *testing.T) { + t.Parallel() + + testutils.RunWithTestBackend(t, flow.Testnet, func(backend *testutils.TestBackend) { + backend.SetEVMTestOperationsAllowed(false) + + testutils.RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { + testutils.RunWithEOATestAccount(t, backend, rootAddr, func(eoa *testutils.EOATestAccount) { + + aa := handler.NewAddressAllocator() + result := &types.Result{ + ReturnedData: testutils.RandomData(t), + GasConsumed: testutils.RandomGas(1000), + Logs: []*gethTypes.Log{ + testutils.GetRandomLogFixture(t), + testutils.GetRandomLogFixture(t), + }, + } + + em := &testutils.TestEmulator{ + NonceOfFunc: func(address types.Address) (uint64, error) { + return 1, nil + }, + DirectCallFunc: func(call *types.DirectCall) (*types.Result, error) { + return result, nil + }, + } + handler := handler.NewContractHandler(flow.Emulator, rootAddr, flowTokenAddress, rootAddr, aa, backend, em) + + from := types.NewAddressFromString("0x7e093BA1474b79481f9B87D66c99a819F25e82E2") + to := types.NewAddressFromString("0x7A038Ec292505B94d20004d3761Db0d1623bb45b") + data := types.Data{10, 50, 20, 30, 50} + gasLimit := types.GasLimit(25_000) + balance := types.Balance(big.NewInt(150)) + + assertPanic(t, types.IsAUnsupportedOperationError, func() { + handler.RunTxAs(from, to, data, gasLimit, balance) + }) + }) + }) + }) +} + // returns true if error passes the checks type checkError func(error) bool @@ -1310,13 +1500,12 @@ func assertPanic(t *testing.T, check checkError, f func()) { f() } -func SetupHandler(t testing.TB, backend types.Backend, rootAddr flow.Address) *handler.ContractHandler { +func SetupHandler(t testing.TB, backend backends.Backend, rootAddr flow.Address) *handler.ContractHandler { return handler.NewContractHandler( flow.Emulator, rootAddr, flowTokenAddress, rootAddr, - handler.NewBlockStore(defaultChainID, backend, rootAddr), handler.NewAddressAllocator(), backend, emulator.NewEmulator(backend, rootAddr), diff --git a/fvm/evm/handler/precompiles.go b/fvm/evm/handler/precompiles.go index 7919749cdfc..ae45208e5c5 100644 --- a/fvm/evm/handler/precompiles.go +++ b/fvm/evm/handler/precompiles.go @@ -8,16 +8,33 @@ import ( "github.com/onflow/cadence/sema" "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/precompiles" "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/model/flow" ) +// The Cadence Arch precompiled contract that is injected in the EVM environment, +// implements the following functions: +// - `flowBlockHeight()` +// - `revertibleRandom()` +// - `getRandomSource(uint64)` +// - `verifyCOAOwnershipProof(address,bytes32,bytes)` +// +// By design, all errors that are the result of user input, will be propagated +// in the EVM environment, and can be handled by developers, as they see fit. +// However, all FVM fatal errors, will cause a panic and abort the outer Cadence +// transaction. The reason behind this is that we want to have visibility when +// such special errors occur. This way, any potential bugs will not go unnoticed. +// The Cadence runtime recovers any Go crashers (index out of bounds, nil +// dereferences, etc.) and fails the transaction gracefully, so a panic in the +// precompiled contract does not indicate a node/runtime crash. + func preparePrecompiledContracts( evmContractAddress flow.Address, randomBeaconAddress flow.Address, addressAllocator types.AddressAllocator, - backend types.Backend, + backend backends.Backend, ) []types.PrecompiledContract { archAddress := addressAllocator.AllocatePrecompileAddress(1) archContract := precompiles.ArchContract( @@ -30,10 +47,10 @@ func preparePrecompiledContracts( return []types.PrecompiledContract{archContract} } -func blockHeightProvider(backend types.Backend) func() (uint64, error) { +func blockHeightProvider(backend backends.Backend) func() (uint64, error) { return func() (uint64, error) { h, err := backend.GetCurrentBlockHeight() - if types.IsAFatalError(err) || types.IsABackendError(err) { + if types.IsAFatalError(err) { panic(err) } return h, err @@ -42,7 +59,7 @@ func blockHeightProvider(backend types.Backend) func() (uint64, error) { const RandomSourceTypeValueFieldName = "value" -func randomSourceProvider(contractAddress flow.Address, backend types.Backend) func(uint64) ([]byte, error) { +func randomSourceProvider(contractAddress flow.Address, backend backends.Backend) func(uint64) ([]byte, error) { return func(blockHeight uint64) ([]byte, error) { value, err := backend.Invoke( environment.ContractFunctionSpec{ @@ -60,7 +77,7 @@ func randomSourceProvider(contractAddress flow.Address, backend types.Backend) f }, ) if err != nil { - if types.IsAFatalError(err) || types.IsABackendError(err) { + if types.IsAFatalError(err) { panic(err) } return nil, err @@ -81,7 +98,7 @@ func randomSourceProvider(contractAddress flow.Address, backend types.Backend) f } } -func revertibleRandomGenerator(backend types.Backend) func() (uint64, error) { +func revertibleRandomGenerator(backend backends.Backend) func() (uint64, error) { return func() (uint64, error) { rand := make([]byte, 8) err := backend.ReadRandom(rand) @@ -95,7 +112,7 @@ func revertibleRandomGenerator(backend types.Backend) func() (uint64, error) { const ValidationResultTypeIsValidFieldName = "isValid" -func coaOwnershipProofValidator(contractAddress flow.Address, backend types.Backend) func(proof *types.COAOwnershipProofInContext) (bool, error) { +func coaOwnershipProofValidator(contractAddress flow.Address, backend backends.Backend) func(proof *types.COAOwnershipProofInContext) (bool, error) { return func(proof *types.COAOwnershipProofInContext) (bool, error) { value, err := backend.Invoke( environment.ContractFunctionSpec{ @@ -116,7 +133,7 @@ func coaOwnershipProofValidator(contractAddress flow.Address, backend types.Back proof.ToCadenceValues(), ) if err != nil { - if types.IsAFatalError(err) || types.IsABackendError(err) { + if types.IsAFatalError(err) { panic(err) } return false, err diff --git a/fvm/evm/impl/abi.go b/fvm/evm/impl/abi.go index 68433e9bf95..48a86690152 100644 --- a/fvm/evm/impl/abi.go +++ b/fvm/evm/impl/abi.go @@ -89,8 +89,8 @@ type evmSpecialTypeIDs struct { func NewEVMSpecialTypeIDs( gauge common.MemoryGauge, location common.AddressLocation, -) evmSpecialTypeIDs { - return evmSpecialTypeIDs{ +) *evmSpecialTypeIDs { + return &evmSpecialTypeIDs{ AddressTypeID: location.TypeID(gauge, stdlib.EVMAddressTypeQualifiedIdentifier), BytesTypeID: location.TypeID(gauge, stdlib.EVMBytesTypeQualifiedIdentifier), Bytes4TypeID: location.TypeID(gauge, stdlib.EVMBytes4TypeQualifiedIdentifier), @@ -103,124 +103,167 @@ type abiEncodingContext interface { interpreter.ValueTransferContext } -func reportABIEncodingComputation( +func reportArrayABIEncodingComputation( context abiEncodingContext, values *interpreter.ArrayValue, - evmTypeIDs evmSpecialTypeIDs, + evmTypeIDs *evmSpecialTypeIDs, reportComputation func(intensity uint64), ) { - values.Iterate( context, func(element interpreter.Value) (resume bool) { - switch value := element.(type) { - case *interpreter.StringValue: - // Dynamic variables, such as strings, are encoded - // in 2+ chunks of 32 bytes. The first chunk contains - // the index where information for the string begin, - // the second chunk contains the number of bytes the - // string occupies, and the third chunk contains the - // value of the string itself. - computation := uint64(2 * abiEncodingByteSize) - stringLength := len(value.Str) - chunks := math.Ceil(float64(stringLength) / float64(abiEncodingByteSize)) - computation += uint64(chunks * abiEncodingByteSize) - reportComputation(computation) - - case interpreter.BoolValue, - interpreter.UIntValue, - interpreter.UInt8Value, - interpreter.UInt16Value, - interpreter.UInt32Value, - interpreter.UInt64Value, - interpreter.UInt128Value, - interpreter.UInt256Value, - interpreter.IntValue, - interpreter.Int8Value, - interpreter.Int16Value, - interpreter.Int32Value, - interpreter.Int64Value, - interpreter.Int128Value, - interpreter.Int256Value: - - // Numeric and bool variables are also static variables - // with a fixed size of 32 bytes. - reportComputation(abiEncodingByteSize) - - case *interpreter.CompositeValue: - switch value.TypeID() { - case evmTypeIDs.AddressTypeID: - // EVM addresses are static variables with a fixed - // size of 32 bytes. - reportComputation(abiEncodingByteSize) - - case evmTypeIDs.BytesTypeID: - computation := uint64(2 * abiEncodingByteSize) - valueMember := value.GetMember(context, stdlib.EVMBytesTypeValueFieldName) - bytesArray, ok := valueMember.(*interpreter.ArrayValue) - if !ok { - panic(abiEncodingError{ - Type: value.StaticType(context), - Message: "could not convert value field to array", - }) - } - bytesLength := bytesArray.Count() - chunks := math.Ceil(float64(bytesLength) / float64(abiEncodingByteSize)) - computation += uint64(chunks * abiEncodingByteSize) - reportComputation(computation) + reportABIEncodingComputation( + context, + element, + evmTypeIDs, + reportComputation, + ) - case evmTypeIDs.Bytes4TypeID: - reportComputation(abiEncodingByteSize) + // continue iteration + return true + }, + false, + ) +} - case evmTypeIDs.Bytes32TypeID: - reportComputation(abiEncodingByteSize) +func reportABIEncodingComputation( + context abiEncodingContext, + value interpreter.Value, + evmTypeIDs *evmSpecialTypeIDs, + reportComputation func(intensity uint64), +) { + switch value := value.(type) { + case *interpreter.StringValue: + // Dynamic variables, such as strings, are encoded + // in 2+ chunks of 32 bytes. The first chunk contains + // the index where information for the string begin, + // the second chunk contains the number of bytes the + // string occupies, and the third chunk contains the + // value of the string itself. + computation := uint64(2 * abiEncodingByteSize) + stringLength := len(value.Str) + chunks := math.Ceil(float64(stringLength) / float64(abiEncodingByteSize)) + computation += uint64(chunks * abiEncodingByteSize) + reportComputation(computation) + + case interpreter.BoolValue, + interpreter.UIntValue, + interpreter.UInt8Value, + interpreter.UInt16Value, + interpreter.UInt32Value, + interpreter.UInt64Value, + interpreter.UInt128Value, + interpreter.UInt256Value, + interpreter.IntValue, + interpreter.Int8Value, + interpreter.Int16Value, + interpreter.Int32Value, + interpreter.Int64Value, + interpreter.Int128Value, + interpreter.Int256Value: + + // Numeric and bool variables are also static variables + // with a fixed size of 32 bytes. + reportComputation(abiEncodingByteSize) - default: - panic(abiEncodingError{ - Type: value.StaticType(context), - }) - } + case *interpreter.CompositeValue: + switch value.TypeID() { + case evmTypeIDs.AddressTypeID: + // EVM addresses are static variables with a fixed + // size of 32 bytes. + reportComputation(abiEncodingByteSize) - case *interpreter.ArrayValue: - // Dynamic variables, such as arrays & slices, are encoded - // in 2+ chunks of 32 bytes. The first chunk contains - // the index where information for the array begin, - // the second chunk contains the number of bytes the - // array occupies, and the third chunk contains the - // values of the array itself. - computation := uint64(2 * abiEncodingByteSize) - reportComputation(computation) - reportABIEncodingComputation( - context, - value, - evmTypeIDs, - reportComputation, - ) + case evmTypeIDs.BytesTypeID: + computation := uint64(2 * abiEncodingByteSize) + valueMember := value.GetMember( + context, + stdlib.EVMBytesTypeValueFieldName, + common.DeclarationKindField, + nil, + ) + bytesArray, ok := valueMember.(*interpreter.ArrayValue) + if !ok { + panic(abiEncodingError{ + Type: value.StaticType(context), + Message: "could not convert value field to array", + }) + } + bytesLength := bytesArray.Count() + chunks := math.Ceil(float64(bytesLength) / float64(abiEncodingByteSize)) + computation += uint64(chunks * abiEncodingByteSize) + reportComputation(computation) + + case evmTypeIDs.Bytes4TypeID: + reportComputation(abiEncodingByteSize) - default: + case evmTypeIDs.Bytes32TypeID: + reportComputation(abiEncodingByteSize) + + default: + staticType := value.StaticType(context) + semaType := context.SemaTypeFromStaticType(staticType) + if compositeType := asTupleEncodableCompositeType(semaType); compositeType != nil { + + compositeType.Members.Foreach(func(name string, member *sema.Member) { + + if member.DeclarationKind != common.DeclarationKindField { + return + } + + fieldValue := value.GetMember( + context, + name, + common.DeclarationKindField, + nil, + ) + reportABIEncodingComputation( + context, + fieldValue, + evmTypeIDs, + reportComputation, + ) + }) + + } else { panic(abiEncodingError{ - Type: element.StaticType(context), + Type: value.StaticType(context), }) } + } - // continue iteration - return true - }, - false, - ) + case *interpreter.ArrayValue: + // Dynamic variables, such as arrays & slices, are encoded + // in 2+ chunks of 32 bytes. The first chunk contains + // the index where information for the array begin, + // the second chunk contains the number of bytes the + // array occupies, and the third chunk contains the + // values of the array itself. + computation := uint64(2 * abiEncodingByteSize) + reportComputation(computation) + reportArrayABIEncodingComputation( + context, + value, + evmTypeIDs, + reportComputation, + ) + + default: + panic(abiEncodingError{ + Type: value.StaticType(context), + }) + } } +// encodeABI + func newInterpreterInternalEVMTypeEncodeABIFunction( gauge common.MemoryGauge, location common.AddressLocation, ) *interpreter.HostFunctionValue { - - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeEncodeABIFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeEncodeABIFunction(gauge, location), - ), + newInternalEVMTypeEncodeABIFunction(gauge, location), ) } @@ -233,8 +276,9 @@ func newInternalEVMTypeEncodeABIFunction( return func( context interpreter.NativeFunctionContext, - typeArguments interpreter.TypeArgumentsIterator, - receiver interpreter.Value, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -245,56 +289,7 @@ func newInternalEVMTypeEncodeABIFunction( panic(errors.NewUnreachableError()) } - reportABIEncodingComputation( - context, - valuesArray, - evmSpecialTypeIDs, - func(intensity uint64) { - common.UseComputation( - context, - common.ComputationUsage{ - Kind: environment.ComputationKindEVMEncodeABI, - Intensity: intensity, - }, - ) - }, - ) - - size := valuesArray.Count() - - values := make([]any, 0, size) - arguments := make(gethABI.Arguments, 0, size) - - valuesArray.Iterate( - context, - func(element interpreter.Value) (resume bool) { - value, ty, err := encodeABI( - context, - element, - element.StaticType(context), - evmSpecialTypeIDs, - ) - if err != nil { - panic(err) - } - - values = append(values, value) - arguments = append(arguments, gethABI.Argument{Type: ty}) - - // continue iteration - return true - }, - false, - ) - - encodedValues, err := arguments.Pack(values...) - if err != nil { - panic( - abiEncodingError{ - Message: err.Error(), - }, - ) - } + encodedValues := encodeABIs(context, evmSpecialTypeIDs, valuesArray) return interpreter.ByteSliceToByteArrayValue(context, encodedValues) } @@ -310,6 +305,66 @@ func newVMInternalEVMTypeEncodeABIFunction( ) } +func encodeABIs( + context interpreter.InvocationContext, + evmSpecialTypeIDs *evmSpecialTypeIDs, + valuesArray *interpreter.ArrayValue, +) []byte { + size := valuesArray.Count() + + values := make([]any, 0, size) + arguments := make(gethABI.Arguments, 0, size) + + valuesArray.Iterate( + context, + func(element interpreter.Value) (resume bool) { + + reportABIEncodingComputation( + context, + element, + evmSpecialTypeIDs, + func(intensity uint64) { + common.UseComputation( + context, + common.ComputationUsage{ + Kind: environment.ComputationKindEVMEncodeABI, + Intensity: intensity, + }, + ) + }, + ) + + value, ty, err := encodeABI( + context, + element, + element.StaticType(context), + evmSpecialTypeIDs, + ) + if err != nil { + panic(err) + } + + values = append(values, value) + arguments = append(arguments, gethABI.Argument{Type: ty}) + + // continue iteration + return true + }, + false, + ) + + encodedValues, err := arguments.Pack(values...) + if err != nil { + panic( + abiEncodingError{ + Message: err.Error(), + }, + ) + } + + return encodedValues +} + var gethTypeString = gethABI.Type{T: gethABI.StringTy} var gethTypeBool = gethABI.Type{T: gethABI.BoolTy} @@ -350,9 +405,14 @@ var gethTypeBytes4 = gethABI.Type{T: gethABI.FixedBytesTy, Size: 4} var gethTypeBytes32 = gethABI.Type{T: gethABI.FixedBytesTy, Size: 32} +func exportedName(name string) string { + return strings.ToUpper(name[:1]) + name[1:] +} + func gethABIType( + context abiEncodingContext, staticType interpreter.StaticType, - evmTypeIDs evmSpecialTypeIDs, + evmTypeIDs *evmSpecialTypeIDs, ) (gethABI.Type, bool) { switch staticType { case interpreter.PrimitiveStaticTypeString: @@ -404,8 +464,71 @@ func gethABIType( return gethTypeBytes32, true } + semaType := context.SemaTypeFromStaticType(staticType) + if compositeType := asTupleEncodableCompositeType(semaType); compositeType != nil { + + var ( + fieldTypeIsInvalid bool + goStructFields []reflect.StructField + gethABITupleElements []*gethABI.Type + gethABITupleNames []string + ) + + compositeType.Members.Foreach(func(name string, member *sema.Member) { + if fieldTypeIsInvalid { + return + } + + if member.DeclarationKind != common.DeclarationKindField { + return + } + + fieldStaticType := interpreter.ConvertSemaToStaticType( + context, + member.TypeAnnotation.Type, + ) + + fieldGethABIType, ok := gethABIType( + context, + fieldStaticType, + evmTypeIDs, + ) + if !ok { + fieldTypeIsInvalid = true + return + } + + gethABITupleElements = append(gethABITupleElements, &fieldGethABIType) + + // reflect.StructField.Name must be exported (start with uppercase) + goStructFieldName := exportedName(name) + + gethABITupleNames = append(gethABITupleNames, goStructFieldName) + + goStructFields = append( + goStructFields, + reflect.StructField{ + Name: goStructFieldName, + Type: fieldGethABIType.GetType(), + }, + ) + }) + + if fieldTypeIsInvalid { + break + } + + return gethABI.Type{ + T: gethABI.TupleTy, + TupleType: reflect.StructOf(goStructFields), + TupleElems: gethABITupleElements, + TupleRawNames: gethABITupleNames, + }, true + } + case *interpreter.ConstantSizedStaticType: elementGethABIType, ok := gethABIType( + context, staticType.ElementType(), evmTypeIDs, ) @@ -421,6 +544,7 @@ func gethABIType( case *interpreter.VariableSizedStaticType: elementGethABIType, ok := gethABIType( + context, staticType.ElementType(), evmTypeIDs, ) @@ -438,50 +562,69 @@ func gethABIType( return gethABI.Type{}, false } +var ( + goStringType = reflect.TypeFor[string]() + goBoolType = reflect.TypeFor[bool]() + goUint8Type = reflect.TypeFor[uint8]() + goUint16Type = reflect.TypeFor[uint16]() + goUint32Type = reflect.TypeFor[uint32]() + goUint64Type = reflect.TypeFor[uint64]() + goInt8Type = reflect.TypeFor[int8]() + goInt16Type = reflect.TypeFor[int16]() + goInt32Type = reflect.TypeFor[int32]() + goInt64Type = reflect.TypeFor[int64]() + goBigIntType = reflect.TypeFor[*big.Int]() + gethAddressType = reflect.TypeFor[gethCommon.Address]() + goByteSliceType = reflect.TypeFor[[]byte]() + evmBytes4Type = reflect.TypeFor[[stdlib.EVMBytes4Length]byte]() + evmBytes32Type = reflect.TypeFor[[stdlib.EVMBytes32Length]byte]() +) + func goType( + context abiEncodingContext, staticType interpreter.StaticType, - evmTypeIDs evmSpecialTypeIDs, + evmTypeIDs *evmSpecialTypeIDs, ) (reflect.Type, bool) { switch staticType { case interpreter.PrimitiveStaticTypeString: - return reflect.TypeOf(""), true + return goStringType, true case interpreter.PrimitiveStaticTypeBool: - return reflect.TypeOf(true), true + return goBoolType, true case interpreter.PrimitiveStaticTypeUInt: - return reflect.TypeOf((*big.Int)(nil)), true + return goBigIntType, true case interpreter.PrimitiveStaticTypeUInt8: - return reflect.TypeOf(uint8(0)), true + return goUint8Type, true case interpreter.PrimitiveStaticTypeUInt16: - return reflect.TypeOf(uint16(0)), true + return goUint16Type, true case interpreter.PrimitiveStaticTypeUInt32: - return reflect.TypeOf(uint32(0)), true + return goUint32Type, true case interpreter.PrimitiveStaticTypeUInt64: - return reflect.TypeOf(uint64(0)), true + return goUint64Type, true case interpreter.PrimitiveStaticTypeUInt128: - return reflect.TypeOf((*big.Int)(nil)), true + return goBigIntType, true case interpreter.PrimitiveStaticTypeUInt256: - return reflect.TypeOf((*big.Int)(nil)), true + return goBigIntType, true case interpreter.PrimitiveStaticTypeInt: - return reflect.TypeOf((*big.Int)(nil)), true + return goBigIntType, true case interpreter.PrimitiveStaticTypeInt8: - return reflect.TypeOf(int8(0)), true + return goInt8Type, true case interpreter.PrimitiveStaticTypeInt16: - return reflect.TypeOf(int16(0)), true + return goInt16Type, true case interpreter.PrimitiveStaticTypeInt32: - return reflect.TypeOf(int32(0)), true + return goInt32Type, true case interpreter.PrimitiveStaticTypeInt64: - return reflect.TypeOf(int64(0)), true + return goInt64Type, true case interpreter.PrimitiveStaticTypeInt128: - return reflect.TypeOf((*big.Int)(nil)), true + return goBigIntType, true case interpreter.PrimitiveStaticTypeInt256: - return reflect.TypeOf((*big.Int)(nil)), true + return goBigIntType, true case interpreter.PrimitiveStaticTypeAddress: - return reflect.TypeOf((*big.Int)(nil)), true + return goBigIntType, true } switch staticType := staticType.(type) { case *interpreter.ConstantSizedStaticType: - elementType, ok := goType(staticType.ElementType(), evmTypeIDs) + elementType, ok := goType(context, staticType.ElementType(), evmTypeIDs) if !ok { break } @@ -489,7 +632,7 @@ func goType( return reflect.ArrayOf(int(staticType.Size), elementType), true case *interpreter.VariableSizedStaticType: - elementType, ok := goType(staticType.ElementType(), evmTypeIDs) + elementType, ok := goType(context, staticType.ElementType(), evmTypeIDs) if !ok { break } @@ -499,13 +642,29 @@ func goType( switch staticType.ID() { case evmTypeIDs.AddressTypeID: - return reflect.TypeOf(gethCommon.Address{}), true + return gethAddressType, true case evmTypeIDs.BytesTypeID: - return reflect.SliceOf(reflect.TypeOf(byte(0))), true + return goByteSliceType, true case evmTypeIDs.Bytes4TypeID: - return reflect.ArrayOf(stdlib.EVMBytes4Length, reflect.TypeOf(byte(0))), true + return evmBytes4Type, true case evmTypeIDs.Bytes32TypeID: - return reflect.ArrayOf(stdlib.EVMBytes32Length, reflect.TypeOf(byte(0))), true + return evmBytes32Type, true + } + + gethABIType, ok := gethABIType( + context, + staticType, + evmTypeIDs, + ) + // All user-defined Cadence structs, are ABI encoded/decoded as Solidity tuples. + // Except for the structs defined in the EVM system contract: + // - `EVM.EVMAddress` + // - `EVM.EVMBytes` + // - `EVM.EVMBytes4` + // - `EVM.EVMBytes32` + // These have their own ABI encoding/decoding format. + if ok && gethABIType.T == gethABI.TupleTy { + return gethABIType.TupleType, true } return nil, false @@ -515,7 +674,7 @@ func encodeABI( context abiEncodingContext, value interpreter.Value, staticType interpreter.StaticType, - evmTypeIDs evmSpecialTypeIDs, + evmTypeIDs *evmSpecialTypeIDs, ) ( any, gethABI.Type, @@ -618,7 +777,12 @@ func encodeABI( case *interpreter.CompositeValue: switch value.TypeID() { case evmTypeIDs.AddressTypeID: - addressBytesArrayValue := value.GetMember(context, stdlib.EVMAddressTypeBytesFieldName) + addressBytesArrayValue := value.GetMember( + context, + stdlib.EVMAddressTypeBytesFieldName, + common.DeclarationKindField, + nil, + ) bytes, err := interpreter.ByteArrayValueToByteSlice(context, addressBytesArrayValue) if err != nil { panic(err) @@ -626,7 +790,12 @@ func encodeABI( return gethCommon.Address(bytes), gethTypeAddress, nil case evmTypeIDs.BytesTypeID: - bytesValue := value.GetMember(context, stdlib.EVMBytesTypeValueFieldName) + bytesValue := value.GetMember( + context, + stdlib.EVMBytesTypeValueFieldName, + common.DeclarationKindField, + nil, + ) bytes, err := interpreter.ByteArrayValueToByteSlice(context, bytesValue) if err != nil { panic(err) @@ -634,7 +803,12 @@ func encodeABI( return bytes, gethTypeBytes, nil case evmTypeIDs.Bytes4TypeID: - bytesValue := value.GetMember(context, stdlib.EVMBytesTypeValueFieldName) + bytesValue := value.GetMember( + context, + stdlib.EVMBytesTypeValueFieldName, + common.DeclarationKindField, + nil, + ) bytes, err := interpreter.ByteArrayValueToByteSlice(context, bytesValue) if err != nil { panic(err) @@ -642,7 +816,12 @@ func encodeABI( return [stdlib.EVMBytes4Length]byte(bytes), gethTypeBytes4, nil case evmTypeIDs.Bytes32TypeID: - bytesValue := value.GetMember(context, stdlib.EVMBytesTypeValueFieldName) + bytesValue := value.GetMember( + context, + stdlib.EVMBytesTypeValueFieldName, + common.DeclarationKindField, + nil, + ) bytes, err := interpreter.ByteArrayValueToByteSlice(context, bytesValue) if err != nil { panic(err) @@ -650,17 +829,78 @@ func encodeABI( return [stdlib.EVMBytes32Length]byte(bytes), gethTypeBytes32, nil } + staticType := value.StaticType(context) + semaType := context.SemaTypeFromStaticType(staticType) + + if compositeType := asTupleEncodableCompositeType(semaType); compositeType != nil { + + tupleGethABIType, ok := gethABIType( + context, + staticType, + evmTypeIDs, + ) + if !ok { + break + } + + result := reflect.New(tupleGethABIType.TupleType) + + var index int + + compositeType.Members.Foreach(func(name string, member *sema.Member) { + + if member.DeclarationKind != common.DeclarationKindField { + return + } + + goStructFieldName := tupleGethABIType.TupleRawNames[index] + + if exportedName(name) != goStructFieldName { + // Continue to next member + return + } + + index++ + + fieldValue := value.GetMember( + context, + name, + common.DeclarationKindField, + nil, + ) + + fieldElement, _, err := encodeABI( + context, + fieldValue, + fieldValue.StaticType(context), + evmTypeIDs, + ) + if err != nil { + panic(err) + } + + field := result.Elem().FieldByName(goStructFieldName) + field.Set(reflect.ValueOf(fieldElement)) + }) + + return result.Interface(), tupleGethABIType, nil + } + case *interpreter.ArrayValue: arrayStaticType := value.Type - arrayGethABIType, ok := gethABIType(arrayStaticType, evmTypeIDs) + arrayGethABIType, ok := gethABIType( + context, + arrayStaticType, + evmTypeIDs, + ) if !ok { break } elementStaticType := arrayStaticType.ElementType() - elementGoType, ok := goType(elementStaticType, evmTypeIDs) + elementGoType, ok := goType(context, elementStaticType, evmTypeIDs) if !ok { break } @@ -677,6 +917,9 @@ func encodeABI( result = reflect.MakeSlice(reflect.SliceOf(elementGoType), size, size) } + semaType := context.SemaTypeFromStaticType(elementStaticType) + isTuple := asTupleEncodableCompositeType(semaType) != nil + var index int value.Iterate( context, @@ -692,7 +935,16 @@ func encodeABI( panic(err) } - result.Index(index).Set(reflect.ValueOf(arrayElement)) + if isTuple { + // For tuples, the underlying `arrayElement` is a value of + // type *struct { X,Y,Z fields }, so we need to indirect + // the pointer + result.Index(index).Set( + reflect.Indirect(reflect.ValueOf(arrayElement)), + ) + } else { + result.Index(index).Set(reflect.ValueOf(arrayElement)) + } index++ @@ -710,16 +962,30 @@ func encodeABI( } } +// asTupleEncodableCompositeType determines if the given type can be encoded as a tuple +// (when the type is user-defined (location != nil) struct type) +func asTupleEncodableCompositeType(ty sema.Type) *sema.CompositeType { + compositeType, ok := ty.(*sema.CompositeType) + if !ok || + compositeType.Location == nil || + compositeType.IsResourceType() { + + return nil + } + + return compositeType +} + +// decodeABI + func newInterpreterInternalEVMTypeDecodeABIFunction( gauge common.MemoryGauge, location common.AddressLocation, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeDecodeABIFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeDecodeABIFunction(gauge, location), - ), + newInternalEVMTypeDecodeABIFunction(gauge, location), ) } @@ -732,6 +998,7 @@ func newInternalEVMTypeDecodeABIFunction( return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -750,113 +1017,113 @@ func newInternalEVMTypeDecodeABIFunction( panic(errors.NewUnreachableError()) } - common.UseComputation( - context, - common.ComputationUsage{ - Kind: environment.ComputationKindEVMDecodeABI, - Intensity: uint64(dataValue.Count()), - }, - ) - data, err := interpreter.ByteArrayValueToByteSlice(context, dataValue) if err != nil { panic(err) } - var arguments gethABI.Arguments - typesArray.Iterate( - context, - func(element interpreter.Value) (resume bool) { - typeValue, ok := element.(interpreter.TypeValue) - if !ok { - panic(errors.NewUnreachableError()) - } - - staticType := typeValue.Type - - gethABITy, ok := gethABIType(staticType, evmSpecialTypeIDs) - if !ok { - panic(abiDecodingError{ - Type: staticType, - }) - } + return decodeABIs(context, location, evmSpecialTypeIDs, typesArray, data) + } +} - arguments = append( - arguments, - gethABI.Argument{ - Type: gethABITy, - }, - ) +func newVMInternalEVMTypeDecodeABIFunction( + location common.AddressLocation, +) *vm.NativeFunctionValue { + return vm.NewNativeFunctionValue( + stdlib.InternalEVMTypeDecodeABIFunctionName, + stdlib.InternalEVMTypeDecodeABIFunctionType, + newInternalEVMTypeDecodeABIFunction(nil, location), + ) +} - // continue iteration - return true - }, - false, - ) +func decodeABIs( + context interpreter.InvocationContext, + location common.AddressLocation, + evmSpecialTypeIDs *evmSpecialTypeIDs, + typesArray *interpreter.ArrayValue, + data []byte, +) interpreter.Value { + common.UseComputation( + context, + common.ComputationUsage{ + Kind: environment.ComputationKindEVMDecodeABI, + Intensity: uint64(len(data)), + }, + ) - decodedValues, err := arguments.Unpack(data) - if err != nil { - panic(abiDecodingError{}) - } + arguments := make(gethABI.Arguments, 0, typesArray.Count()) + staticTypes := make([]interpreter.StaticType, 0, typesArray.Count()) + typesArray.Iterate( + context, + func(element interpreter.Value) (resume bool) { + typeValue, ok := element.(interpreter.TypeValue) + if !ok { + panic(errors.NewUnreachableError()) + } - var index int - values := make([]interpreter.Value, 0, len(decodedValues)) + staticType := typeValue.Type - typesArray.Iterate( - context, - func(element interpreter.Value) (resume bool) { - typeValue, ok := element.(interpreter.TypeValue) - if !ok { - panic(errors.NewUnreachableError()) - } + gethABITy, ok := gethABIType( + context, + staticType, + evmSpecialTypeIDs, + ) + if !ok { + panic(abiDecodingError{ + Type: staticType, + }) + } - staticType := typeValue.Type + arguments = append( + arguments, + gethABI.Argument{ + Type: gethABITy, + }, + ) - value, err := decodeABI( - context, - decodedValues[index], - staticType, - location, - evmSpecialTypeIDs, - ) - if err != nil { - panic(err) - } + staticTypes = append(staticTypes, staticType) - index++ + // continue iteration + return true + }, + false, + ) - values = append(values, value) + decodedValues, err := arguments.Unpack(data) + if err != nil { + panic(abiDecodingError{Message: err.Error()}) + } - // continue iteration - return true - }, - false, - ) + values := make([]interpreter.Value, 0, len(decodedValues)) - arrayType := interpreter.NewVariableSizedStaticType( + for i, staticType := range staticTypes { + value, err := decodeABI( context, - interpreter.NewPrimitiveStaticType( - context, - interpreter.PrimitiveStaticTypeAnyStruct, - ), + decodedValues[i], + staticType, + location, + evmSpecialTypeIDs, ) + if err != nil { + panic(err) + } - return interpreter.NewArrayValue( - context, - arrayType, - common.ZeroAddress, - values..., - ) + values = append(values, value) } -} -func newVMInternalEVMTypeDecodeABIFunction( - location common.AddressLocation, -) *vm.NativeFunctionValue { - return vm.NewNativeFunctionValue( - stdlib.InternalEVMTypeEncodeABIFunctionName, - stdlib.InternalEVMTypeEncodeABIFunctionType, - newInternalEVMTypeDecodeABIFunction(nil, location), + arrayType := interpreter.NewVariableSizedStaticType( + context, + interpreter.NewPrimitiveStaticType( + context, + interpreter.PrimitiveStaticTypeAnyStruct, + ), + ) + + return interpreter.NewArrayValue( + context, + arrayType, + common.ZeroAddress, + values..., ) } @@ -870,7 +1137,7 @@ func decodeABI( value any, staticType interpreter.StaticType, location common.AddressLocation, - evmTypeIDs evmSpecialTypeIDs, + evmTypeIDs *evmSpecialTypeIDs, ) ( interpreter.Value, error, @@ -1088,6 +1355,51 @@ func decodeABI( location, bytes, ), nil + + default: + semaType := context.SemaTypeFromStaticType(staticType) + if compositeType := asTupleEncodableCompositeType(semaType); compositeType != nil { + + valueStruct := reflect.ValueOf(value) + + fields := make([]interpreter.CompositeField, 0, compositeType.Members.Len()) + + compositeType.Members.Foreach(func(name string, member *sema.Member) { + if member.DeclarationKind != common.DeclarationKindField { + return + } + + fieldValue := valueStruct.FieldByName(exportedName(name)).Interface() + + fieldStaticType := interpreter.ConvertSemaToStaticType( + context, + member.TypeAnnotation.Type, + ) + + decodedFieldValue, err := decodeABI( + context, + fieldValue, + fieldStaticType, + location, + evmTypeIDs, + ) + if err != nil { + panic(err) + } + + field := interpreter.NewCompositeField(context, name, decodedFieldValue) + fields = append(fields, field) + }) + + return interpreter.NewCompositeValue( + context, + compositeType.Location, + compositeType.QualifiedIdentifier(), + compositeType.Kind, + fields, + common.ZeroAddress, + ), nil + } } } diff --git a/fvm/evm/impl/impl.go b/fvm/evm/impl/impl.go index aca6db95cf7..ee85608b89a 100644 --- a/fvm/evm/impl/impl.go +++ b/fvm/evm/impl/impl.go @@ -4,6 +4,7 @@ import ( "fmt" "math/big" + "github.com/holiman/uint256" "github.com/onflow/cadence" "github.com/onflow/cadence/bbq/vm" "github.com/onflow/cadence/common" @@ -15,7 +16,9 @@ import ( "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/model/flow" + gethCommon "github.com/ethereum/go-ethereum/common" gethTypes "github.com/ethereum/go-ethereum/core/types" + gethCrypto "github.com/ethereum/go-ethereum/crypto" ) var internalEVMContractStaticType = interpreter.ConvertSemaCompositeTypeToStaticCompositeType( @@ -23,46 +26,105 @@ var internalEVMContractStaticType = interpreter.ConvertSemaCompositeTypeToStatic stdlib.InternalEVMContractType, ) +// NewInternalEVMContractValue creates the interpreter-side value for the InternalEVM contract. +// Its methods are the interpreter forms of the internal EVM functions. func NewInternalEVMContractValue( gauge common.MemoryGauge, handler types.ContractHandler, contractAddress flow.Address, ) *interpreter.SimpleCompositeValue { - location := common.NewAddressLocation(gauge, common.Address(contractAddress), stdlib.ContractName) + location := common.NewAddressLocation(nil, common.Address(contractAddress), stdlib.ContractName) + + methods := map[string]interpreter.FunctionValue{} + + computeLazyStoredMethod := func(name string) interpreter.FunctionValue { + switch name { + case stdlib.InternalEVMTypeRunFunctionName: + return newInterpreterInternalEVMTypeRunFunction(gauge, handler) + case stdlib.InternalEVMTypeBatchRunFunctionName: + return newInterpreterInternalEVMTypeBatchRunFunction(gauge, handler) + case stdlib.InternalEVMTypeCreateCadenceOwnedAccountFunctionName: + return newInterpreterInternalEVMTypeCreateCadenceOwnedAccountFunction(gauge, handler) + case stdlib.InternalEVMTypeCallFunctionName: + return newInterpreterInternalEVMTypeCallFunction(gauge, handler) + case stdlib.InternalEVMTypeCallWithSigAndArgsFunctionName: + return newInterpreterInternalEVMTypeCallWithSigAndArgsFunction(gauge, handler, location) + case stdlib.InternalEVMTypeDepositFunctionName: + return newInterpreterInternalEVMTypeDepositFunction(gauge, handler) + case stdlib.InternalEVMTypeWithdrawFunctionName: + return newInterpreterInternalEVMTypeWithdrawFunction(gauge, handler) + case stdlib.InternalEVMTypeDeployFunctionName: + return newInterpreterInternalEVMTypeDeployFunction(gauge, handler) + case stdlib.InternalEVMTypeBalanceFunctionName: + return newInterpreterInternalEVMTypeBalanceFunction(gauge, handler) + case stdlib.InternalEVMTypeNonceFunctionName: + return newInterpreterInternalEVMTypeNonceFunction(gauge, handler) + case stdlib.InternalEVMTypeCodeFunctionName: + return newInterpreterInternalEVMTypeCodeFunction(gauge, handler) + case stdlib.InternalEVMTypeCodeHashFunctionName: + return newInterpreterInternalEVMTypeCodeHashFunction(gauge, handler) + case stdlib.InternalEVMTypeEncodeABIFunctionName: + return newInterpreterInternalEVMTypeEncodeABIFunction(gauge, location) + case stdlib.InternalEVMTypeDecodeABIFunctionName: + return newInterpreterInternalEVMTypeDecodeABIFunction(gauge, location) + case stdlib.InternalEVMTypeCastToAttoFLOWFunctionName: + return newInterpreterInternalEVMTypeCastToAttoFLOWFunction(gauge) + case stdlib.InternalEVMTypeCastToFLOWFunctionName: + return newInterpreterInternalEVMTypeCastToFLOWFunction(gauge) + case stdlib.InternalEVMTypeGetLatestBlockFunctionName: + return newInterpreterInternalEVMTypeGetLatestBlockFunction(gauge, handler) + case stdlib.InternalEVMTypeDryRunFunctionName: + return newInterpreterInternalEVMTypeDryRunFunction(gauge, handler) + case stdlib.InternalEVMTypeDryCallFunctionName: + return newInterpreterInternalEVMTypeDryCallFunction(gauge, handler) + case stdlib.InternalEVMTypeDryCallWithSigAndArgsFunctionName: + return newInterpreterInternalEVMTypeDryCallWithSigAndArgsFunction(gauge, handler, location) + case stdlib.InternalEVMTypeCommitBlockProposalFunctionName: + return newInterpreterInternalEVMTypeCommitBlockProposalFunction(gauge, handler) + case stdlib.InternalEVMTypeStoreFunctionName: + return newInterpreterInternalEVMTypeStoreFunction(gauge, handler) + case stdlib.InternalEVMTypeLoadFunctionName: + return newInterpreterInternalEVMTypeLoadFunction(gauge, handler) + case stdlib.InternalEVMTypeRunTxAsFunctionName: + return newInterpreterInternalEVMTypeRunTxAsFunction(gauge, handler) + } + + return nil + } + + // Given all methods of InternalEVM are essentially "static" functions, + // we can cache them and avoid recomputing them on every access. + + methodGetter := func( + name string, + _ interpreter.MemberAccessibleContext, + _ interpreter.ReferenceValue, + ) interpreter.FunctionValue { + method, ok := methods[name] + if !ok { + method = computeLazyStoredMethod(name) + if method != nil { + methods[name] = method + } + } + + return method + } return interpreter.NewSimpleCompositeValue( gauge, stdlib.InternalEVMContractType.ID(), internalEVMContractStaticType, stdlib.InternalEVMContractType.Fields, - map[string]interpreter.Value{ - stdlib.InternalEVMTypeRunFunctionName: newInterpreterInternalEVMTypeRunFunction(gauge, handler), - stdlib.InternalEVMTypeBatchRunFunctionName: newInterpreterInternalEVMTypeBatchRunFunction(gauge, handler), - stdlib.InternalEVMTypeCreateCadenceOwnedAccountFunctionName: newInterpreterInternalEVMTypeCreateCadenceOwnedAccountFunction(gauge, handler), - stdlib.InternalEVMTypeCallFunctionName: newInterpreterInternalEVMTypeCallFunction(gauge, handler), - stdlib.InternalEVMTypeDepositFunctionName: newInterpreterInternalEVMTypeDepositFunction(gauge, handler), - stdlib.InternalEVMTypeWithdrawFunctionName: newInterpreterInternalEVMTypeWithdrawFunction(gauge, handler), - stdlib.InternalEVMTypeDeployFunctionName: newInterpreterInternalEVMTypeDeployFunction(gauge, handler), - stdlib.InternalEVMTypeBalanceFunctionName: newInterpreterInternalEVMTypeBalanceFunction(gauge, handler), - stdlib.InternalEVMTypeNonceFunctionName: newInterpreterInternalEVMTypeNonceFunction(gauge, handler), - stdlib.InternalEVMTypeCodeFunctionName: newInterpreterInternalEVMTypeCodeFunction(gauge, handler), - stdlib.InternalEVMTypeCodeHashFunctionName: newInterpreterInternalEVMTypeCodeHashFunction(gauge, handler), - stdlib.InternalEVMTypeEncodeABIFunctionName: newInterpreterInternalEVMTypeEncodeABIFunction(gauge, location), - stdlib.InternalEVMTypeDecodeABIFunctionName: newInterpreterInternalEVMTypeDecodeABIFunction(gauge, location), - stdlib.InternalEVMTypeCastToAttoFLOWFunctionName: newInterpreterInternalEVMTypeCastToAttoFLOWFunction(gauge), - stdlib.InternalEVMTypeCastToFLOWFunctionName: newInterpreterInternalEVMTypeCastToFLOWFunction(gauge), - stdlib.InternalEVMTypeGetLatestBlockFunctionName: newInterpreterInternalEVMTypeGetLatestBlockFunction(gauge, handler), - stdlib.InternalEVMTypeDryRunFunctionName: newInterpreterInternalEVMTypeDryRunFunction(gauge, handler), - stdlib.InternalEVMTypeDryCallFunctionName: newInterpreterInternalEVMTypeDryCallFunction(gauge, handler), - stdlib.InternalEVMTypeCommitBlockProposalFunctionName: newInterpreterInternalEVMTypeCommitBlockProposalFunction(gauge, handler), - }, nil, nil, + methodGetter, nil, nil, ) } +// NewInternalEVMFunctions creates the VM-side native function values for the InternalEVM contract. func NewInternalEVMFunctions( handler types.ContractHandler, contractAddress flow.Address, @@ -71,9 +133,14 @@ func NewInternalEVMFunctions( return stdlib.InternalEVMFunctions{ Run: newVMInternalEVMTypeRunFunction(handler), + DryRun: newVMInternalEVMTypeDryRunFunction(handler), BatchRun: newVMInternalEVMTypeBatchRunFunction(handler), CreateCadenceOwnedAccount: newVMInternalEVMTypeCreateCadenceOwnedAccountFunction(handler), Call: newVMInternalEVMTypeCallFunction(handler), + CallWithSigAndArgs: newVMInternalEVMTypeCallWithSigAndArgsFunction(handler, location), + RunTxAs: newVMInternalEVMTypeRunTxAsFunction(handler), + DryCall: newVMInternalEVMTypeDryCallFunction(handler), + DryCallWithSigAndArgs: newVMInternalEVMTypeDryCallWithSigAndArgsFunction(handler, location), Deposit: newVMInternalEVMTypeDepositFunction(handler), Withdraw: newVMInternalEVMTypeWithdrawFunction(handler), Deploy: newVMInternalEVMTypeDeployFunction(handler), @@ -86,23 +153,22 @@ func NewInternalEVMFunctions( CastToAttoFLOW: vmInternalEVMTypeCastToAttoFLOWFunction, CastToFLOW: vmInternalEVMTypeCastToFLOWFunction, GetLatestBlock: newVMInternalEVMTypeGetLatestBlockFunction(handler), - DryRun: newVMInternalEVMTypeDryRunFunction(handler), - DryCall: newVMInternalEVMTypeDryCallFunction(handler), CommitBlockProposal: newVMInternalEVMTypeCommitBlockProposalFunction(handler), + Store: newVMInternalEVMTypeStoreFunction(handler), + Load: newVMInternalEVMTypeLoadFunction(handler), } - } +// getLatestBlock + func newInterpreterInternalEVMTypeGetLatestBlockFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeGetLatestBlockFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeGetLatestBlockFunction(handler), - ), + newInternalEVMTypeGetLatestBlockFunction(handler), ) } @@ -112,6 +178,7 @@ func newInternalEVMTypeGetLatestBlockFunction( return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, _ []interpreter.Value, ) interpreter.Value { @@ -304,22 +371,10 @@ func EVMAddressToAddressBytesArrayValue( context interpreter.ArrayCreationContext, address types.Address, ) *interpreter.ArrayValue { - var index int - return interpreter.NewArrayValueWithIterator( + return interpreter.ByteSliceToByteArrayValueWithType( context, stdlib.EVMAddressBytesStaticType, - common.ZeroAddress, - types.AddressLength, - func() interpreter.Value { - if index >= types.AddressLength { - return nil - } - result := interpreter.NewUInt8Value(context, func() uint8 { - return address[index] - }) - index++ - return result - }, + address[:], ) } @@ -327,22 +382,10 @@ func EVMBytesToBytesArrayValue( context interpreter.ArrayCreationContext, bytes []byte, ) *interpreter.ArrayValue { - var index int - return interpreter.NewArrayValueWithIterator( + return interpreter.ByteSliceToByteArrayValueWithType( context, stdlib.EVMBytesValueStaticType, - common.ZeroAddress, - uint64(len(bytes)), - func() interpreter.Value { - if index >= len(bytes) { - return nil - } - result := interpreter.NewUInt8Value(context, func() uint8 { - return bytes[index] - }) - index++ - return result - }, + bytes, ) } @@ -350,22 +393,10 @@ func EVMBytes4ToBytesArrayValue( context interpreter.ArrayCreationContext, bytes [4]byte, ) *interpreter.ArrayValue { - var index int - return interpreter.NewArrayValueWithIterator( + return interpreter.ByteSliceToByteArrayValueWithType( context, stdlib.EVMBytes4ValueStaticType, - common.ZeroAddress, - stdlib.EVMBytes4Length, - func() interpreter.Value { - if index >= stdlib.EVMBytes4Length { - return nil - } - result := interpreter.NewUInt8Value(context, func() uint8 { - return bytes[index] - }) - index++ - return result - }, + bytes[:], ) } @@ -373,42 +404,33 @@ func EVMBytes32ToBytesArrayValue( context interpreter.ArrayCreationContext, bytes [32]byte, ) *interpreter.ArrayValue { - var index int - return interpreter.NewArrayValueWithIterator( + return interpreter.ByteSliceToByteArrayValueWithType( context, stdlib.EVMBytes32ValueStaticType, - common.ZeroAddress, - stdlib.EVMBytes32Length, - func() interpreter.Value { - if index >= stdlib.EVMBytes32Length { - return nil - } - result := interpreter.NewUInt8Value(context, func() uint8 { - return bytes[index] - }) - index++ - return result - }, + bytes[:], ) } +// createCadenceOwnedAccount + func newInterpreterInternalEVMTypeCreateCadenceOwnedAccountFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeCreateCadenceOwnedAccountFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeCreateCadenceOwnedAccountFunction(handler), - ), + newInternalEVMTypeCreateCadenceOwnedAccountFunction(handler), ) } -func newInternalEVMTypeCreateCadenceOwnedAccountFunction(handler types.ContractHandler) interpreter.NativeFunction { +func newInternalEVMTypeCreateCadenceOwnedAccountFunction( + handler types.ContractHandler, +) interpreter.NativeFunction { return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -434,17 +456,17 @@ func newVMInternalEVMTypeCreateCadenceOwnedAccountFunction( ) } +// code + // newInterpreterInternalEVMTypeCodeFunction returns the code of the account func newInterpreterInternalEVMTypeCodeFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeCodeFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeCodeFunction(handler), - ), + newInternalEVMTypeCodeFunction(handler), ) } @@ -452,6 +474,7 @@ func newInternalEVMTypeCodeFunction(handler types.ContractHandler) interpreter.N return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -483,17 +506,17 @@ func newVMInternalEVMTypeCodeFunction( ) } +// nonce + // newInterpreterInternalEVMTypeNonceFunction returns the nonce of the account func newInterpreterInternalEVMTypeNonceFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeNonceFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeNonceFunction(handler), - ), + newInternalEVMTypeNonceFunction(handler), ) } @@ -501,6 +524,7 @@ func newInternalEVMTypeNonceFunction(handler types.ContractHandler) interpreter. return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -531,16 +555,16 @@ func newVMInternalEVMTypeNonceFunction( ) } +// call + func newInterpreterInternalEVMTypeCallFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeCallFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeCallFunction(handler), - ), + newInternalEVMTypeCallFunction(handler), ) } @@ -548,6 +572,7 @@ func newInternalEVMTypeCallFunction(handler types.ContractHandler) interpreter.N return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -582,16 +607,143 @@ func newVMInternalEVMTypeCallFunction( ) } +// runTxAs + +func newInterpreterInternalEVMTypeRunTxAsFunction( + gauge common.MemoryGauge, + handler types.ContractHandler, +) *interpreter.HostFunctionValue { + return interpreter.NewStaticHostFunctionValueFromNativeFunction( + gauge, + stdlib.InternalEVMTypeRunTxAsFunctionType, + newInternalEVMTypeRunTxAsFunction(handler), + ) +} + +func newInternalEVMTypeRunTxAsFunction(handler types.ContractHandler) interpreter.NativeFunction { + return func( + context interpreter.NativeFunctionContext, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, + args []interpreter.Value, + ) interpreter.Value { + + callArgs, err := parseCallArguments(context, args) + if err != nil { + panic(err) + } + + // Call + + result := handler.RunTxAs( + callArgs.from, + callArgs.to, + callArgs.data, + callArgs.gasLimit, + callArgs.balance, + ) + + return NewResultValue( + handler, + context, + context, + result, + ) + } +} + +func newVMInternalEVMTypeRunTxAsFunction( + handler types.ContractHandler, +) *vm.NativeFunctionValue { + return vm.NewNativeFunctionValue( + stdlib.InternalEVMTypeRunTxAsFunctionName, + stdlib.InternalEVMTypeRunTxAsFunctionType, + newInternalEVMTypeRunTxAsFunction(handler), + ) +} + +// callWithSigAndArgs + +func newInterpreterInternalEVMTypeCallWithSigAndArgsFunction( + gauge common.MemoryGauge, + handler types.ContractHandler, + location common.AddressLocation, +) *interpreter.HostFunctionValue { + return interpreter.NewStaticHostFunctionValueFromNativeFunction( + gauge, + stdlib.InternalEVMTypeCallWithSigAndArgsFunctionType, + newInternalEVMTypeCallWithSigAndArgsFunction(handler, location), + ) +} + +func newInternalEVMTypeCallWithSigAndArgsFunction( + handler types.ContractHandler, + location common.AddressLocation, +) interpreter.NativeFunction { + evmSpecialTypeIDs := NewEVMSpecialTypeIDs(nil, location) + + return func( + context interpreter.NativeFunctionContext, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, + args []interpreter.Value, + ) interpreter.Value { + + // Parse arguments + + callArgs, err := parseCallArgumentsWithSigAndArgs(context, args) + if err != nil { + panic(err) + } + + // Encode signature and arguments + + data, err := encodeABIWithSigAndArgs(context, evmSpecialTypeIDs, callArgs.signature, callArgs.args) + if err != nil { + panic(err) + } + + // Call + + const isAuthorized = true + account := handler.AccountByAddress(callArgs.from, isAuthorized) + result := account.Call(callArgs.to, data, callArgs.gasLimit, callArgs.value) + + return NewResultDecodedValue( + handler, + context, + context, + location, + evmSpecialTypeIDs, + callArgs.resultTypes, + result, + ) + } +} + +func newVMInternalEVMTypeCallWithSigAndArgsFunction( + handler types.ContractHandler, + location common.AddressLocation, +) *vm.NativeFunctionValue { + return vm.NewNativeFunctionValue( + stdlib.InternalEVMTypeCallWithSigAndArgsFunctionName, + stdlib.InternalEVMTypeCallWithSigAndArgsFunctionType, + newInternalEVMTypeCallWithSigAndArgsFunction(handler, location), + ) +} + +// dryCall + func newInterpreterInternalEVMTypeDryCallFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeDryCallFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeDryCallFunction(handler), - ), + newInternalEVMTypeDryCallFunction(handler), ) } @@ -601,6 +753,7 @@ func newInternalEVMTypeDryCallFunction( return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -611,55 +764,122 @@ func newInternalEVMTypeDryCallFunction( } to := callArgs.to.ToCommon() - tx := gethTypes.NewTx(&gethTypes.LegacyTx{ + txData := &gethTypes.LegacyTx{ Nonce: 0, To: &to, Gas: uint64(callArgs.gasLimit), Data: callArgs.data, GasPrice: big.NewInt(0), Value: callArgs.balance, - }) + } + + // call contract function + + res := handler.DryRunWithTxData(txData, callArgs.from) - txPayload, err := tx.MarshalBinary() + return NewResultValue(handler, context, context, res) + } +} + +func newVMInternalEVMTypeDryCallFunction( + handler types.ContractHandler, +) *vm.NativeFunctionValue { + return vm.NewNativeFunctionValue( + stdlib.InternalEVMTypeDryCallFunctionName, + stdlib.InternalEVMTypeDryCallFunctionType, + newInternalEVMTypeDryCallFunction(handler), + ) +} + +// dryCallWithSigAndArgs + +func newInterpreterInternalEVMTypeDryCallWithSigAndArgsFunction( + gauge common.MemoryGauge, + handler types.ContractHandler, + location common.AddressLocation, +) *interpreter.HostFunctionValue { + return interpreter.NewStaticHostFunctionValueFromNativeFunction( + gauge, + stdlib.InternalEVMTypeDryCallWithSigAndArgsFunctionType, + newInternalEVMTypeDryCallWithSigAndArgsFunction(handler, location), + ) +} + +func newInternalEVMTypeDryCallWithSigAndArgsFunction( + handler types.ContractHandler, + location common.AddressLocation, +) interpreter.NativeFunction { + evmSpecialTypeIDs := NewEVMSpecialTypeIDs(nil, location) + + return func( + context interpreter.NativeFunctionContext, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, + args []interpreter.Value, + ) interpreter.Value { + + // Parse arguments + + callArgs, err := parseCallArgumentsWithSigAndArgs(context, args) if err != nil { panic(err) } + to := callArgs.to.ToCommon() - // call contract function + data, err := encodeABIWithSigAndArgs(context, evmSpecialTypeIDs, callArgs.signature, callArgs.args) + if err != nil { + panic(err) + } - res := handler.DryRun(txPayload, callArgs.from) + txData := &gethTypes.LegacyTx{ + Nonce: 0, + To: &to, + Gas: uint64(callArgs.gasLimit), + Data: data, + GasPrice: big.NewInt(0), + Value: callArgs.value, + } - return NewResultValue( + // Call contract function + + res := handler.DryRunWithTxData(txData, callArgs.from) + + return NewResultDecodedValue( handler, context, context, + location, + evmSpecialTypeIDs, + callArgs.resultTypes, res, ) } } -func newVMInternalEVMTypeDryCallFunction( +func newVMInternalEVMTypeDryCallWithSigAndArgsFunction( handler types.ContractHandler, + location common.AddressLocation, ) *vm.NativeFunctionValue { return vm.NewNativeFunctionValue( - stdlib.InternalEVMTypeDryCallFunctionName, - stdlib.InternalEVMTypeDryCallFunctionType, - newInternalEVMTypeDryCallFunction(handler), + stdlib.InternalEVMTypeDryCallWithSigAndArgsFunctionName, + stdlib.InternalEVMTypeDryCallWithSigAndArgsFunctionType, + newInternalEVMTypeDryCallWithSigAndArgsFunction(handler, location), ) } const fungibleTokenVaultTypeBalanceFieldName = "balance" +// deposit + func newInterpreterInternalEVMTypeDepositFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeDepositFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeDepositFunction(handler), - ), + newInternalEVMTypeDepositFunction(handler), ) } @@ -667,6 +887,7 @@ func newInternalEVMTypeDepositFunction(handler types.ContractHandler) interprete return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -724,17 +945,17 @@ func newVMInternalEVMTypeDepositFunction( ) } +// balance + // newInterpreterInternalEVMTypeBalanceFunction returns the Flow balance of the account func newInterpreterInternalEVMTypeBalanceFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeBalanceFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeBalanceFunction(handler), - ), + newInternalEVMTypeBalanceFunction(handler), ) } @@ -742,6 +963,7 @@ func newInternalEVMTypeBalanceFunction(handler types.ContractHandler) interprete return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -773,17 +995,17 @@ func newVMInternalEVMTypeBalanceFunction( ) } +// codeHash + // newInterpreterInternalEVMTypeCodeHashFunction returns the code hash of the account func newInterpreterInternalEVMTypeCodeHashFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeCodeHashFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeCodeHashFunction(handler), - ), + newInternalEVMTypeCodeHashFunction(handler), ) } @@ -791,6 +1013,7 @@ func newInternalEVMTypeCodeHashFunction(handler types.ContractHandler) interpret return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -822,16 +1045,16 @@ func newVMInternalEVMTypeCodeHashFunction( ) } +// withdraw + func newInterpreterInternalEVMTypeWithdrawFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeWithdrawFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeWithdrawFunction(handler), - ), + newInternalEVMTypeWithdrawFunction(handler), ) } @@ -839,6 +1062,7 @@ func newInternalEVMTypeWithdrawFunction(handler types.ContractHandler) interpret return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -862,7 +1086,19 @@ func newInternalEVMTypeWithdrawFunction(handler types.ContractHandler) interpret panic(errors.NewUnreachableError()) } - amount := types.NewBalance(amountValue.BigInt) + _, overflow := uint256.FromBig(amountValue.BigInt) + if overflow { + panic(types.ErrInvalidBalance) + } + + // check balance is not prone to rounding error + if !types.AttoFlowBalanceIsValidForFlowVault(amountValue.BigInt) { + panic(types.ErrWithdrawBalanceRounding) + } + + // this is where rounding from Atto scale to UFix scale happens. + value := new(big.Int).Div(amountValue.BigInt, types.UFixToAttoConversionMultiplier) + amount := types.NewBalanceFromUFix64(cadence.UFix64(value.Uint64())) // Withdraw @@ -874,6 +1110,8 @@ func newInternalEVMTypeWithdrawFunction(handler types.ContractHandler) interpret if err != nil { panic(err) } + // We have already truncated the remainder above, but we still leave + // the rounding check in as a redundancy. if roundedOff { panic(types.ErrWithdrawBalanceRounding) } @@ -881,11 +1119,7 @@ func newInternalEVMTypeWithdrawFunction(handler types.ContractHandler) interpret // TODO: improve: maybe call actual constructor return interpreter.NewCompositeValue( context, - common.NewAddressLocation( - context, - handler.FlowTokenAddress(), - "FlowToken", - ), + common.NewAddressLocation(context, handler.FlowTokenAddress(), "FlowToken"), "FlowToken.Vault", common.CompositeKindResource, []interpreter.CompositeField{ @@ -917,16 +1151,16 @@ func newVMInternalEVMTypeWithdrawFunction( ) } +// deploy + func newInterpreterInternalEVMTypeDeployFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeDeployFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeDeployFunction(handler), - ), + newInternalEVMTypeDeployFunction(handler), ) } @@ -936,6 +1170,7 @@ func newInternalEVMTypeDeployFunction( return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -1007,22 +1242,23 @@ func newVMInternalEVMTypeDeployFunction( ) } +// castToAttoFLOW + func newInterpreterInternalEVMTypeCastToAttoFLOWFunction( gauge common.MemoryGauge, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeCastToAttoFLOWFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - internalEVMTypeCastToAttoFLOWFunction, - ), + internalEVMTypeCastToAttoFLOWFunction, ) } var internalEVMTypeCastToAttoFLOWFunction = interpreter.NativeFunction( func( - context interpreter.NativeFunctionContext, + _ interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -1041,15 +1277,15 @@ var vmInternalEVMTypeCastToAttoFLOWFunction = vm.NewNativeFunctionValue( internalEVMTypeCastToAttoFLOWFunction, ) +// castToFLOW + func newInterpreterInternalEVMTypeCastToFLOWFunction( gauge common.MemoryGauge, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeCastToFLOWFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - internalEVMTypeCastToFLOWFunction, - ), + internalEVMTypeCastToFLOWFunction, ) } @@ -1057,6 +1293,7 @@ var internalEVMTypeCastToFLOWFunction = interpreter.NativeFunction( func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -1085,16 +1322,16 @@ var vmInternalEVMTypeCastToFLOWFunction = vm.NewNativeFunctionValue( internalEVMTypeCastToFLOWFunction, ) +// commitBlockProposal + func newInterpreterInternalEVMTypeCommitBlockProposalFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeCommitBlockProposalFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeCommitBlockProposalFunction(handler), - ), + newInternalEVMTypeCommitBlockProposalFunction(handler), ) } @@ -1102,8 +1339,9 @@ func newInternalEVMTypeCommitBlockProposalFunction( handler types.ContractHandler, ) interpreter.NativeFunction { return func( - context interpreter.NativeFunctionContext, + _ interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, _ []interpreter.Value, ) interpreter.Value { @@ -1122,16 +1360,146 @@ func newVMInternalEVMTypeCommitBlockProposalFunction( ) } +// load + +func newInterpreterInternalEVMTypeLoadFunction( + gauge common.MemoryGauge, + handler types.ContractHandler, +) *interpreter.HostFunctionValue { + return interpreter.NewStaticHostFunctionValueFromNativeFunction( + gauge, + stdlib.InternalEVMTypeLoadFunctionType, + newInternalEVMTypeLoadFunction(handler), + ) +} + +func newInternalEVMTypeLoadFunction(handler types.ContractHandler) interpreter.NativeFunction { + return func( + context interpreter.NativeFunctionContext, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, + args []interpreter.Value, + ) interpreter.Value { + + // Get target argument + targetValue, ok := args[0].(*interpreter.ArrayValue) + if !ok { + panic(errors.NewUnreachableError()) + } + + addr, err := AddressBytesArrayValueToEVMAddress(context, targetValue) + if err != nil { + panic(err) + } + + // Get slot argument + slotValue, ok := args[1].(*interpreter.StringValue) + if !ok { + panic(errors.NewUnreachableError()) + } + + if !isHexHash(slotValue.Str) { + panic(fmt.Errorf("invalid input: slot is not a valid hex-encoded Ethereum hash")) + } + slot := gethCommon.HexToHash(slotValue.Str) + + value := handler.GetState(addr, slot) + return interpreter.ByteSliceToByteArrayValue(context, value.Bytes()) + } +} + +func newVMInternalEVMTypeLoadFunction( + handler types.ContractHandler, +) *vm.NativeFunctionValue { + return vm.NewNativeFunctionValue( + stdlib.InternalEVMTypeLoadFunctionName, + stdlib.InternalEVMTypeLoadFunctionType, + newInternalEVMTypeLoadFunction(handler), + ) +} + +// store + +func newInterpreterInternalEVMTypeStoreFunction( + gauge common.MemoryGauge, + handler types.ContractHandler, +) *interpreter.HostFunctionValue { + return interpreter.NewStaticHostFunctionValueFromNativeFunction( + gauge, + stdlib.InternalEVMTypeStoreFunctionType, + newInternalEVMTypeStoreFunction(handler), + ) +} + +func newInternalEVMTypeStoreFunction(handler types.ContractHandler) interpreter.NativeFunction { + return func( + context interpreter.NativeFunctionContext, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, + args []interpreter.Value, + ) interpreter.Value { + + // Get target argument + targetValue, ok := args[0].(*interpreter.ArrayValue) + if !ok { + panic(errors.NewUnreachableError()) + } + + addr, err := AddressBytesArrayValueToEVMAddress(context, targetValue) + if err != nil { + panic(err) + } + + // Get slot argument + slotValue, ok := args[1].(*interpreter.StringValue) + if !ok { + panic(errors.NewUnreachableError()) + } + + if !isHexHash(slotValue.Str) { + panic(fmt.Errorf("invalid input: slot is not a valid hex-encoded Ethereum hash")) + } + slot := gethCommon.HexToHash(slotValue.Str) + + // Get value argument + valueValue, ok := args[2].(*interpreter.StringValue) + if !ok { + panic(errors.NewUnreachableError()) + } + + if !isHexHash(valueValue.Str) { + panic(fmt.Errorf("invalid input: value is not a valid hex-encoded Ethereum hash")) + } + value := gethCommon.HexToHash(valueValue.Str) + + handler.SetState(addr, slot, value) + + return interpreter.Void + } +} + +func newVMInternalEVMTypeStoreFunction( + handler types.ContractHandler, +) *vm.NativeFunctionValue { + return vm.NewNativeFunctionValue( + stdlib.InternalEVMTypeStoreFunctionName, + stdlib.InternalEVMTypeStoreFunctionType, + newInternalEVMTypeStoreFunction(handler), + ) +} + +// run + func newInterpreterInternalEVMTypeRunFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeRunFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeRunFunction(handler), - ), + newInternalEVMTypeRunFunction(handler), ) } @@ -1141,6 +1509,7 @@ func newInternalEVMTypeRunFunction( return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -1191,16 +1560,16 @@ func newVMInternalEVMTypeRunFunction( ) } +// dryRun + func newInterpreterInternalEVMTypeDryRunFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeDryRunFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeDryRunFunction(handler), - ), + newInternalEVMTypeDryRunFunction(handler), ) } @@ -1210,6 +1579,7 @@ func newInternalEVMTypeDryRunFunction( return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -1260,16 +1630,16 @@ func newVMInternalEVMTypeDryRunFunction( ) } +// batchRun + func newInterpreterInternalEVMTypeBatchRunFunction( gauge common.MemoryGauge, handler types.ContractHandler, ) *interpreter.HostFunctionValue { - return interpreter.NewStaticHostFunctionValue( + return interpreter.NewStaticHostFunctionValueFromNativeFunction( gauge, stdlib.InternalEVMTypeBatchRunFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - newInternalEVMTypeBatchRunFunction(handler), - ), + newInternalEVMTypeBatchRunFunction(handler), ) } @@ -1279,6 +1649,7 @@ func newInternalEVMTypeBatchRunFunction( return func( context interpreter.NativeFunctionContext, _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, _ interpreter.Value, args []interpreter.Value, ) interpreter.Value { @@ -1325,11 +1696,7 @@ func newInternalEVMTypeBatchRunFunction( values := newResultValues(handler, context, context, batchResults) - loc := common.NewAddressLocation( - context, - handler.EVMContractAddress(), - stdlib.ContractName, - ) + loc := common.NewAddressLocation(context, handler.EVMContractAddress(), stdlib.ContractName) evmResultType := interpreter.NewVariableSizedStaticType( context, interpreter.NewCompositeStaticType( @@ -1470,6 +1837,115 @@ func NewResultValue( ) } +func NewResultDecodedValue( + handler types.ContractHandler, + gauge common.MemoryGauge, + context interpreter.InvocationContext, + location common.AddressLocation, + evmSpecialTypeIDs *evmSpecialTypeIDs, + resultTypes *interpreter.ArrayValue, + result *types.ResultSummary, +) *interpreter.CompositeValue { + + evmContractLocation := common.NewAddressLocation( + gauge, + handler.EVMContractAddress(), + stdlib.ContractName, + ) + + deployedContractAddress := result.DeployedContractAddress + deployedContractValue := interpreter.NilOptionalValue + if deployedContractAddress != nil { + deployedContractValue = interpreter.NewSomeValueNonCopying( + context, + NewEVMAddress( + context, + evmContractLocation, + *deployedContractAddress, + ), + ) + } + + results, err := decodeResultData(context, location, evmSpecialTypeIDs, resultTypes, result) + if err != nil { + panic(err) + } + + fields := []interpreter.CompositeField{ + { + Name: "status", + Value: interpreter.NewEnumCaseValue( + context, + &sema.CompositeType{ + Location: evmContractLocation, + Identifier: stdlib.EVMStatusTypeQualifiedIdentifier, + Kind: common.CompositeKindEnum, + }, + interpreter.NewUInt8Value(gauge, func() uint8 { + return uint8(result.Status) + }), + nil, + ), + }, + { + Name: "errorCode", + Value: interpreter.NewUInt64Value(gauge, func() uint64 { + return uint64(result.ErrorCode) + }), + }, + { + Name: "errorMessage", + Value: interpreter.NewStringValue( + context, + common.NewStringMemoryUsage(len(result.ErrorMessage)), + func() string { + return result.ErrorMessage + }, + ), + }, + { + Name: "gasUsed", + Value: interpreter.NewUInt64Value(gauge, func() uint64 { + return result.GasConsumed + }), + }, + { + Name: "results", + Value: results, + }, + { + Name: "deployedContract", + Value: deployedContractValue, + }, + } + + return interpreter.NewCompositeValue( + context, + evmContractLocation, + stdlib.EVMResultDecodedTypeQualifiedIdentifier, + common.CompositeKindStructure, + fields, + common.ZeroAddress, + ) +} + +func decodeResultData( + context interpreter.InvocationContext, + location common.AddressLocation, + evmSpecialTypeIDs *evmSpecialTypeIDs, + resultTypes *interpreter.ArrayValue, + result *types.ResultSummary, +) (interpreter.Value, error) { + + if result.Status != types.StatusSuccessful || resultTypes == nil || resultTypes.Count() == 0 { + resultValue := interpreter.ByteSliceToByteArrayValue(context, result.ReturnedData) + return resultValue, nil + } + + resultValue := decodeABIs(context, location, evmSpecialTypeIDs, resultTypes, result.ReturnedData) + return resultValue, nil +} + func ResultSummaryFromEVMResultValue(val cadence.Value) (*types.ResultSummary, error) { str, ok := val.(cadence.Struct) if !ok { @@ -1615,7 +2091,7 @@ func parseCallArguments( gasLimitValue, ok := args[3].(interpreter.UInt64Value) if !ok { - panic(errors.NewUnreachableError()) + return nil, errors.NewUnreachableError() } gasLimit := types.GasLimit(gasLimitValue) @@ -1637,3 +2113,161 @@ func parseCallArguments( balance: balance, }, nil } + +type callArgumentsWithSigAndArgs struct { + from types.Address + to types.Address + signature string + args *interpreter.ArrayValue + gasLimit types.GasLimit + value types.Balance + resultTypes *interpreter.ArrayValue +} + +func parseCallArgumentsWithSigAndArgs( + context interpreter.InvocationContext, + args []interpreter.Value, +) (*callArgumentsWithSigAndArgs, error) { + // Get from address + + fromAddressValue, ok := args[0].(*interpreter.ArrayValue) + if !ok { + return nil, errors.NewUnreachableError() + } + + fromAddress, err := AddressBytesArrayValueToEVMAddress(context, fromAddressValue) + if err != nil { + return nil, err + } + + // Get to address + + toAddressValue, ok := args[1].(*interpreter.ArrayValue) + if !ok { + return nil, errors.NewUnreachableError() + } + + toAddress, err := AddressBytesArrayValueToEVMAddress(context, toAddressValue) + if err != nil { + return nil, err + } + + // Get signature + + signature, ok := args[2].(*interpreter.StringValue) + if !ok { + return nil, errors.NewUnreachableError() + } + + // Get arguments + + argsValue, ok := args[3].(*interpreter.ArrayValue) + if !ok { + return nil, errors.NewUnreachableError() + } + + // Get gas limit + + gasLimitValue, ok := args[4].(interpreter.UInt64Value) + if !ok { + return nil, errors.NewUnreachableError() + } + + gasLimit := types.GasLimit(gasLimitValue) + + // Get value + + valueValue, ok := args[5].(interpreter.UIntValue) + if !ok { + return nil, errors.NewUnreachableError() + } + + value := types.NewBalance(valueValue.BigInt) + + // Get resultTypes + + var resultTypes *interpreter.ArrayValue + switch resultTypesField := args[6].(type) { + case *interpreter.SomeValue: + if innerTypes := resultTypesField.InnerValue(); innerTypes != nil { + resultTypes, ok = innerTypes.(*interpreter.ArrayValue) + if !ok { + return nil, errors.NewUnreachableError() + } + } else { + return nil, errors.NewUnreachableError() + } + case interpreter.NilValue: + default: + return nil, errors.NewUnreachableError() + } + + return &callArgumentsWithSigAndArgs{ + from: fromAddress, + to: toAddress, + signature: signature.Str, + args: argsValue, + gasLimit: gasLimit, + value: value, + resultTypes: resultTypes, + }, nil +} + +func encodeABIWithSigAndArgs( + context interpreter.InvocationContext, + evmSpecialTypeIDs *evmSpecialTypeIDs, + signature string, + args *interpreter.ArrayValue, +) ([]byte, error) { + sig := gethCrypto.Keccak256([]byte(signature)) + + if len(sig) < 4 { + return nil, errors.NewUnreachableError() + } + + sig = sig[:4] + + if args.Count() == 0 { + return sig, nil + } + + encodedArguments := encodeABIs(context, evmSpecialTypeIDs, args) + + data := make([]byte, len(sig)+len(encodedArguments)) + n := copy(data, sig) + copy(data[n:], encodedArguments) + + return data, nil +} + +// isHexHash verifies whether a string can represent a valid hex-encoded +// Ethereum hash or not. +func isHexHash(s string) bool { + if has0xPrefix(s) { + s = s[2:] + } + return len(s) == 2*gethCommon.HashLength && isHex(s) +} + +// has0xPrefix validates str begins with '0x' or '0X'. +func has0xPrefix(str string) bool { + return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') +} + +// isHexCharacter returns bool of c being a valid hexadecimal. +func isHexCharacter(c byte) bool { + return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') +} + +// isHex validates whether each byte is valid hexadecimal string. +func isHex(str string) bool { + if len(str)%2 != 0 { + return false + } + for _, c := range []byte(str) { + if !isHexCharacter(c) { + return false + } + } + return true +} diff --git a/fvm/evm/offchain/blocks/block_context.go b/fvm/evm/offchain/blocks/block_context.go index 680a0e04e34..6144be87910 100644 --- a/fvm/evm/offchain/blocks/block_context.go +++ b/fvm/evm/offchain/blocks/block_context.go @@ -101,7 +101,7 @@ func generateFixedHashes() { testnetHashes := []string{"fa857cb5d4b774e975d149a91dc47687ab6400301bba7fab1a70e82bd57ab33b", "57c87eeb449e976020fb60b3366b867ffc9d88ec5c0f10171af4c7c771462130", "1af58b777b8054a15f3e0c60ec1c0501bd7626003a4fabb2017e16f1f4f9b0aa", "155eb38e56a75c59863434446071a29df399e0b79a0f7627f3c0def08c0dee4a", "fc541a457aaacc00c4bbf2ddd296c212c7c7436a1b15fdf40971436f4679060b", "22461d010d68d2b67a7a3373782af7f75eb240a845c4b1fa1c399c48f7d3eaad", "e62881132d705937c2a0f88cd0e94f595e922e752f5a3225ecbb4e4f91f242e5", "61084954ebe8d12d9ac71a9ce32f2f72c5ab819ab3382215e0122b98ef98bf6d", "b65786186ff332a66cf502565101ed3fdf0a005d8ea847829a909cafc948cdb7", "6ec4b77f75ce5bd028a22f88049d856dbf83b34480f24eb13ed567de839e06f9", "c1db0ccc2f546863cda1e14da73d951e4fa4c788427f13500a1a7557709de271", "b8a6f83f59913bece208fbc481bdf8a0ac332433f8cb01a3c5c1b7ae377f2700", "9a8c588bb81d8c622b8c6d9073233c176440da4dce49433b56398c30239cfe8d", "a84205d415780ed3c0566f9f4578efeb6ec4ca51f8a93cc7f89a00ccce8dcb39", "c5d6591d91eef2ca446351e95dc4134438360c1b7389d975d636cbacba435280", "7be74dcff396c8abf98c6727659575a5b157c9ec98c6f1c9504732054f09aaf5", "a7dcad11df6d5778824decb3624953440a2e8f01036083c10adb36b4465ee14a", "ac6e904295a3d736e7f22ecb5698c1fd8964e3f0afc07ee2487e63ee606b9bbf", "d7c2cff7f8a08373b8aed134fe1fa80899ddaaa8dd7722fca9b2954228b25803", "580cf925b0d2ec1617e17f0be43402381d537e789bd5a08c3a681dcdcae2d731", "c71cde092dddca890f9f44567a651434a801119dfca6fa6a8ad6daa26ce4d6a2", "b010526b4edd19af408eae841184d97f1ad6e8955c4a6ac8240e32f75a26e5f9", "9278a4d8204e7b937c41c71b9f03c97c49203d4cc6e4e6d429be80ff1d11bf02", "d57366198709ee6be52ea72cb54cfb6282ddd6708e487839f74b93c06c9a994a", "1d17a3f34d23425ad6fa3b1f57cb1276d988c3064c727995cd6966af22323830", "660a0a66a46fae20c0a4f2b1a5f11c246ce39bc1338f641ea304cf2dc9bd0940", "e4562f14b6464d2ee4e92764b6126fab3b37b12c8b0ccb0cbc539a0f1d54318f", "3ed39df06d960213a978379790386ec1c6df288a524c9bc11dbc869d1133e86d", "f09abfcf424b6bcb7a54fc613828e5ff756b619c957c51457d833efbbfd9c601", "58b6fe973b269639c2a6dc768e1f1f328c3c1d098b6ded3511b1f8e3393f8344", "398fd65258285061025e5b53043496832acca2a6b61906046605df18767a9da3", "b933d1d819cdbeff8e3acf9cba0fe7b3e6db3bb582da027a0f1e432219bd6033", "99baada49d56352f2e221cf62116c70485a83c1174bcd50cf5ba62b35d1661a9", "19a47884389d1f995a37c7e2b19525d44a27a32a5df2c0b9c2954fe458655baf", "3820ea36958821d31b8f2eee80fc17e72dcf361f052c0399931ce979e9a10293", "3a3655c7bb4fb1814002b468d63f72c0626d4c7df4ceac28a68c970a3686712a", "bc181caec490ade2d715e7d0c82cb9ad3fd685dc962d8ffca00861d88f5366b4", "da92ccf74d37b40738c41222cee137c149889966c54d62d91472d2ea81be37f2", "e51d0d81a40598e0d6281d2bbc56a1d8c5aa3c8233f2bd9be2316ad6a24a2dc3", "6cb2e1aea92658471cc40ec0a4bfd64d8e76bc0b9bb5707306fe89d93158e7c4", "e4bb2e67f5ff721ecfac0df301bf3db9704d47a9d33c2f952be17dc23a113c45", "7d29bf4f9796573cf5274900ec667bced39cb0377409d281a2dbceaf99ec8fd9", "45b32bbc856daf25ad81206623f8a7fb53f0afbb488f72ffef4d8f0a9431e62b", "b5aca33f4af1f65d9e9e35035597b58896d99abd5b7954593ffc70c86a90c94d", "7a21bc1136bd1b288fb5be1fd43b39cdfeae9b424e3da274e241dbc1ac780d72", "95bd53bea9d44609b8b24ff5c30feb08c91d92f239632f8093fbb8f37a704112", "61551f4fb10bd3b97870af25c6c18d8582d6badef8e87e3c5297befd1331003a", "ba43a4bd43dcdf44ce163b58d35df3def39f2a2ed29cfcf76f3d7571827b8bc1", "329c277c2f0555d33e294377bf906c404a163ee653d0894661714a25b1d3c8fb", "6e143a6cf96b0b8eb695bd77b1e28f2a61f4dac8a47b3cf2b69d6737d8441242", "991bc0911f5914677f4ba476717a53b0b889b91cf178ae66c0625167f7ac0801", "541fb4e3a4fc928a017bdce01393ea8113b2236dafbb3809973f7b8352442d32", "9c9181ad53d6506666187974b6b9e3a9c0bee8d085d10cc79f50bfb4248ca129", "1cb89bb5668ac284574be9118a78d3fa5d674c84579c75d5596a47d2acce29f6", "116b1c4d1a8fef4cd852a8841b689fff4f1df3a0f5bbeb545942150f4b806646", "b54f3b2b235b816bda74453e228378fcf9b79a293534aac71dbfeb6b0ee1ecad", "9acb23972960f0b4c5d3c6b061a2a1c4af4f7a6d4a0cdd8ec7134ae7bd59f95d", "17f3d6c720bc5efd5ee8226d353d1b347828e621400a2a282a190f5b7bbdd0f0", "1838dc6001bb37cff89aa8675ec0ae8efdfd35c5dc8a793538c31d08df4b8232", "ad362ed3de8ac036d4a89d31282f26e10cb50fa900c6ad76f7ab06cb7155d234", "2bd6a5464607a39d0bcdd07e15d4752d1a52b644bf9a81d8d7e5f9cff0af30af", "44124bbba59755b9004d53c3e721820c40c1cc163b7639b4c1a03ce6955e292b", "f19520a13533371cea4cc20daeef421c31c0a88d4604e58b56ebef82288cdaaf", "c1796053a6e8847cf3d8a545670dd953d1273dd3d9a6e4df6e59e33950cc2890", "49aeb76ef737a04fe91c3a61dc8c7b87adad5978d8951f8d033ddeae6fa2b720", "bed2427fb70a9a9a576528569ccfd8fc86ab0ecd4ca7a932d5a8f39316f887a0", "a8da98fa12885b4165f7635906d9bc240c2eaa66079bf18f496dbecb68c7c49e", "cd7e523f67b5ab520d1c8972f78db9a8d283c66ccf000aa31cda8216fe2e508b", "1e29c627ce7b6402eb5115c59a48d561f4420c44748d7de2ed185142beab4a29", "5ddf101e94858f06934c6019eaa22b93d88eca16592720e9dcd982894ac27060", "c408705873fb0ab3fc4f5811e69ee20b0a1600f52bb4663e29362f4391601ebe", "ddf70a2c37e60622148124c22f8f0e96b4eba0af4d5b8b18015d574f33923a7e", "d6e1f406e0d96c486c1bcbb09768ff0e5577f18c97cdf2c3e86dda54b4007448", "656b861ba19271a6591c7468af61a9d29e331eccc9e526a3d25517d29bd69809", "24372783456ac149b4fd0dc41ee16d55500a3c433fc3b1bd3c1c45c8a93c89c5", "2bbbb4392ab7f1fd8a160a80163b69b5f8db16fdf97c2d8ee9e29df1d9ebd9fe", "cc9fd404792808740bdee891c8e93e3d41bfe56c2438396d1ca8a692dd5fb990", "38080ff661e3142133b82633be87af6db2d33f386d05f8439672a1984aa88d13", "22b7125bf763c17087306776783ab6d1c50084e8a7435b015207f99295aa1af9", "570c31b148e5f909873e8d2253401a64eace826993948cd2f3f4d03a798c6c54", "f0cb29da50bff805a3a1736dbe33ea139893534d0e25a98f354aa5f279adbc97", "cd6b07cee12ae00058b20a6d31173c934933e6339a00885554ccefde008b12e3", "323fa87c41960355883ada3b85bbc13303d8202761ea70d015841060c7f7fde7", "01c7c87db4a01af781695e2984e68b72f04a0f7859749bcfdcbee73466bf0990", "a79003be6397a1fac1d183ebd14d72f69cfd9ab310cd8f9cc9c3d835b05d7556", "50dcfbe053447768b56f6c3159cc6d37aa5791d87abfad32b2952e36de8a20c7", "21647bb0680b8b09b357a54518a50d6c4163d78889f26ef48bc93cfe43acb16d", "96dfe03bc8aa7dd74ef98b4cb7cad866c851b8fd145f4b5bdb54c7b799e58adf", "87037ff5508a2a31c62cbef1feb19f3ec22f44ade292e0a036e8a7d8ef3d13bd", "6e7336d4e63a744ae45cfd320ca237ba4b194d930bcbfbfde2d172616df367b8", "780126f3f77af11cac4a71371812160e436d50f09ee01eb312d6839b7dd4e3a3", "9373a2bdc426bc5bf3242c7f3ecc83a19f2cfc0772ecdeb846e423fc8ec40b5e", "0339e7901bccba1e3c8e05956536823b2b0e7189c66f5796b7602b63a8fd1ff9", "b213bb94b274991d4288a6405954059e99b4c4b891a74a1abcd83ea295331b18", "d0a7195ec0cd987709b4dc6416e0ed6fc9939054ecbf502da8c4c6a09836ed9c", "7b9c334b3aeb75a795f9d6c7c0ee01ab219f31860880eb3480921dcd2a057d2b", "9c4e722d126467603530d242fe91a19fa90ebd3a461ee38f36ef5eefa07e996c", "4306ac8ccd2ce6a880350f95c7d59635371ba3d78bb13353c5b7ff06f7c6fc40", "4b9360e2d86f20850d2c6ff222ed16c6a4252c00afad8d488c30c162b3a10da7", "927f20b9dcfbb80f4a6b5d6067a586835bdcb5f3e921ed87bec67fb5160181d1", "e620bc51fbeb8011f57324b0a7ae6f45c46050cd624887f0a50879880632fdaa", "ee7b749b81e86d46fa3e93b9aba29285bae38a91f175dbf7c619d05fcf91e857", "573d5039fa570ceb3fa136be73c432b49a19af00a7f109325b78160f7dc13db1", "9ab1936825e830d4eab7a945701528579f78a8d1702a76a774e7456ddd3a254e", "2b3538a6fed897c0143f51b82f7e9e1929cb698e7de8d88aa8b1d23cabd58fa9", "21e2f8ae0522da985262ccf8422d98d75068ccd448d15c4bfec9f793713c7644", "c02a276e24fbb64f5b35d4b6555d1d873095e076868cea8dcfdad9e606612f9b", "7756adb6b470c5126693a4de57c1d5b38afab4f7ffc4f982374e8466051bcfca", "f82cbe9343e63fa4bf486f8e4113f91abef7c994e6f7068b500942fede79f095", "782f9df4e3f669149a575922a7318d523b1ab8a5911a2b1c2850839d5762cf03", "89ef33e05604e28f762b3cdf2f20d876adcb104a87c2636c5facb61ec47d020c", "59e374462a0c7e32df5e087d4d250936ef54aa19ca824ebaa63b66406180719d", "11fc2b68e458f12e93398a453c5efac599691bd89d40c35e003dc594d87bf51d", "5f793edc159efab968da834bd44187fff951cec822ca1b8982b1f36d966956be", "da0d474d5e0ec5d0966e1986a5de3f085e0f491da67cdb43d52fdc9848b14314", "8d4eec56231819d18f3fb3ec6e6881b269c0ccb881eedecb5916d2b4ef82c6cf", "137e7ea7c47a724f8a4494a3e73e74f146282382935d64d25385dd720f537e98", "1a2a9c7707443c848897141a4f659fbd0b7fefa47365f2af43183777dcb4a8ef", "7747a6f738959e6d75f16fe6d0782b455258b9c93d0380a230722cd6ae11e0bb", "314e30caef6c7c09b2a85056610949febb6abbbf7702c5d6706cef658123d782", "9ab42848b175c62790b5aa4f256899bb609d05723d364b8d349160afadfd9f95", "853b07dda09eb155dcebbac23e2fa5d76c5f619f3cabfa5e25fd82706485bd25", "a2b0053632aafe21d4dff287c03c362cae2a1d3267cd87d82a7ba9a3795129c9", "7918541145cb2c5918b8fa20a31298a7bc9b8f43aebb69f046f78d070a7f22ef", "0827e91cf9ec4dbb95966d68cdeb90dc8399457f47922d1e53eb2972c87756ef", "6121dac0131fc1fe0f7652d6c2195141c0e6a9b7e5cb555647ec3bb2f90b912d", "134fae4eec772042a832efc19e2f3e449db962f3573c070f2920591c306967b1", "b9a716636f3d1dd47e61aa1216f55317230cf734e06c9f740552f2bbd6e8210a", "d5caa5c0bb57e75c78de5f6f132e19776b777dd205d37ff6c2179412caa32c40", "e11c15139b71e7078a664d430e115c631ac8cdd89a8f4b35e4bbbeb9ec85dc17", "cbff909b284e4b1858adff2a0cee75032a2b2411d805604dfe820e40e855d6b5", "5b4ce1b89dde6b8b5cbec1b454306b7f53a9dadcdbe5df429ea5a33635d989d3", "c06a55411e962e0bf9cc11c14e854be084906b374cc181868c29ebcab0b66775", "ad16c4f73055baa8c0c6f69e294019ea90e3e97ee90923c4478156e15180d19c", "76866d7b50747a469e9891c529b7a58a4b9082d113b7acbe2b46f6049a8d36c7", "df96c9eba4763a1c3a8a0d2eb14e57847ce679adeda80b04cb86ef4f40cf290a", "6421d33aed4529b00db819051abed4ae78f28778feab921177c24378d48b427b", "cb76cbf3c146f5890eef6a8e78349b9291b75d2ca3b947b027f52dab0acbcdd4", "cb9a9e1606d5d6cc59bce096733be7e6902d8c8de19d22cc0f5435ad4e719015", "d3b9005c6b93a657d8edd2312d4d59b8807ea7c509079dfd1e4a8cef3d6852ba", "ebc705fd3ee20a69c5e99b1bf063acff8c926eec9358a36294b8df0fdcd31eb5", "c99e64329e066cc19b2e9962bfa2eb474bb7f9bd1c797421878209c16ca85d80", "55a081aab8afb0cfe83873b812c4495a762bdfc866d74c038d64f73d26944db3", "d830b389b67743e2a2cec5d64af37ce1b991b2781bf2a3fb1e8283bc78e98495", "558d06ff221f4d6e5265465ef2928828a80b498f95d7b1853c4a93d842931ccd", "e967f7ac0177971566b44535eed88a5ffcd0b2ec09de03edbf817f8e110eaf5b", "404df2a8bcf278cae68d9a43b86ff9c2781461ccd227c20aa5e0c5b1db2c0cb1", "f8f5160a6d1e91a3cae676b1e8f8563da2e1cb92869df51c190f0d91f62c81b2", "30a23be3cb0e3feab447217745d537e6c5299f3a95172c234bb84de54169b694", "7c5e66106c5e7cb9e68cd6bec431acdb4b0c9394f2c000a60f0ec558b1667750", "be103be330df170331a747138325af15173704afb808abfd6fc5742c677de241", "d711f0d3914c1bee36324e055ade9058750f2b3d0206f516382702de8eda3757", "519658c8746832821044b074a40661ea1497ca50426888303d8eec43ae8b9d6a", "87cd56d2f6ff774a0c75b029c2a888df7b41319380336f3e4663fe5417229687", "2efe240e7018fd0443262223d286c04120199063f4ef194bdef9af0ab34fa4a8", "8c9a69c950bea4e4beecc286124bf44e2cc78614f767580d59dc22cf94bd23f6", "e7641851ddf32f8fa1937528a2c88a2ef512d45f0a7296c232df6584471ad7ba", "a5beb770e26085eb45a6c5e15acb5844fdda167261e92b20c87dc72c1e0d0a1d", "f54988150d2ba3327251b7a4672ec9bff6fe93f06a7a9f19030f17e693281f11", "6cbfa48ae32ef9b3798f0afe4b86798497a758735dc3ac3e0aa6b42710476f58", "35130215ec7db0e57d5964dacb9aa2ea858e70fc864edd08cf062334823a3ce8", "a935e9ddece310c12baa815a0077e151b300a293f88651d7715ea33151d4016e", "167e10bb4d35aa27a4916de2f846ff5d323a0090c9d37b9c35ca455272ab07be", "a85a1222927f535ca37587d38ab4db2bc940bfc0c6d703003119329d05469a75", "826ab7e279754c009dcd86421f3bdaaa3325bdfff8352788c9f8cfbdddfcfafe", "8336015f3f6ca5d69d5af6dfd521a3e3c024c08121bd42de3a25e5bffb417d42", "194125cbe3f428afbf59da1dd144062ad288011e10beca10ca534f935ea7290d", "3bb36e7a0165d3b6f51b628c18e6b4d9e355b05c5be7a616c881dc395c623c66", "c092f7add11cee0facec22c78badba46fb8688538df1443b7356ceea83bae10d", "31552a2bb308a5778e815fee39b007ce5a633d2e7ba27f08eee2bec6f8d387b7", "373533933e0aae2d2dcffb59b09c49fa64506606aa0359eddf00326ee7bbcc7e", "0f580299cabe89b2dc9809735d14fdabf60cc1b65824bb5f6b5cf283b68210ee", "138c02ce7b36a4d7e82f942a3291bbb357b2e8845b579189ce4c35e01e6b859f", "9dc184037f271c4043b1a6d01d9fbed5d2f156fb561ec2612e5b1cd6aa486083", "cb2ae942cd73059bfe666d9ef78cee5a557cda842c9503df0f7d6b00be815cc5", "f941433597eaa923318023f040798918f743db7bf6d33bc6a13bc8c2e8d3e711", "02a1f2c523e2705b1ab122a06c08bd64080ef76d09d517c56c4e64a3f6626021", "ac3dda90e10c66d26ebb6911924713785f48e8e3d2150aa06ae90db456e1c9a0", "61a39a58e915f953d1ea5c0483f3f45b33ed6f097d76ea6d03d7cf81616f33bd", "b3ff677201fa7543da2f635753305a128c4076409268f1ee53ee824989193e90", "3a2cf44822616731ce40cde80365738e4a4d9af161de3cc2bb3e4f4d3ced8009", "b1a3f23c441a6afece152c4b2e1f1da6fc952f997bc8711a6122e26afafeb5b1", "87123bd9968d64fead15b346ad4ef3b0918aebc596fb7ce8c016c09085985bbd", "eae98597fc685154c882a62073157e1538e37270573de17e7f9bd1af724e1164", "e6dc4cfe6c4b77ebc2a915a49157447a65f85c275ba6c888fddbfae95a2d1c2b", "45ffffa2166eff3624a6b83e5d953669e3639188556330a58656d51ac9008f15", "2b5658b7d00f6d34890e71cf1d57b520e934f6b4087cca5c50604a7c8190488d", "d9b516ec359cccafc8cd2c5721bed137cb0d4b7bb21ba4772baed786a9f059a6", "5005e282fff3675ff3ac18906d5cf9df5b992d0bd95fc9cd3258f386f1c5b5ea", "2dea763455c4ae2c662bd9db6529b85cfd397744cb3da1a639925b0fa2b048b4", "497399dc295066a487984ab67cbfec9bf3d65184bc424a7b96268f2c03e6557f", "8f87e5ab712b41e1bc6f74fd74bb8e96323f62f62bedb35ed578992ddbbd5f47", "a5504fbce2afcd7277b0bd94581050195607d5c6701cff8d8e25f05a2d50d81c", "205b534ee10a3633f87c8ab36590d114f516985470ef5851077ac5c95aa83f16", "0d2093c088c08840643f542a44d9e8c389694f03dc9c62a264445de5758e73c3", "b32c1de573b72b62ce6b77d628f758acbfe89ecaa17d3c4c94cad8dff45dd0c9", "6d75d744de2e5dd7ebd3fa47b22ca0d99d4255ee36b5e767567479e0134e0697", "d3228e2e8e5de7178f2afc4b6f86b13287469b55410a164397bc602a0e3bd2db", "5d0a5e9e280f90c7d1f69b69ff3b5bfb94bce299dde8799520fe92912afd2cff", "aafabddd3fe15559af9138aa113c2473fed25a41ee52877a05dc2f9b24416827", "00a9160b3ae08d4066e53992f3cc004b3f6bf3d840613d6e847fb16323ddb270", "1473078fe8d18a5e3f791064c1083783fdc19517a3f2af47777d8778bb2b2f89", "aa2b720f1b7fd016086641fa0c3a6f8133c5f7eb3e9a65cd01ad0b51e7c35719", "ecdd45371e9a284e97416f414d665afa0aec864277a03c333e785e4d6ba6d439", "66a7301e8f3d54360b15fc64610398888301a3caeb685dc71e0ec0fdd175937f", "bd156dc25f23d82eaef927957d4c8c883ec0c80de4c58310313764ccc701d281", "3e8aa53535920d5886779d30687c2350800e9c712c5c2414db463b9c99f3052e", "308a237dad23fa158e7590ce7c75e788ec3ae6be8f6972a867f2eb94f6417c96", "4b12d020e1df286f672fe5d2eac74d95f817d0bbb8bee15a7913ebd9c3a8014a", "303c6f66eaff75bf2145e3bcc343245bcbedb2df46af1fb1e8382473fd2ab402", "d21e974892bd9209a0e2333b22acb55ec2a4abc015755379640cb81d4ba38d82", "40bdb0c10ce735f5e6abf18bf46dd8ef5625ea828fbfc6e380b70809d7cf76dd", "c0b4d28f557f71bcc41eb3573e2afb6da0c127639972bbcb8f4962cff0896f7a", "d2e36f3773f4c313fafb160ac753f1a11b53783920d45552b693f7a37b80bbe2", "3fd160ad0045137801256a22fed09f5f31aacf31f1681fbf6d70bc03972d2253", "2c0c05796774bdbb27c0a6ec5559817b4cd48feee80dff2c540257f86733e397", "5f17ad7ebf06c9ee5f7c86716e2392fd65b773eb6c94f47ac1ea1e12afbacfd0", "0dc16b207a0a9a722cd0b6ce18419eeb2c7809a9f90f3ebca7cc084d6714469d", "8f576a107b37c1309055282825effed4d57dd7e96fd69595ad300c26f77b07a5", "b433f6a339e84a5dbd8e6638a4547dd029b642d1007199948678d7574350b64e", "738768e552067738d3ba97fabe8ea93c0a6ba3b64cc24fab0e9b0c2ce4842982", "533020acb857afd489d4766280665cc484d184ed8eeaacd031e8a5e70b5c4a88", "1d84007a810cb751a5f7207b36cffb1a7f50c1553cbcb0c922c7cb1ada8bb409", "a0b398eb392174cfa24948edcf03c50553a7367c7f6ed50970456484ea09680b", "f156f642f5fd502eb9d0fff911981506c32e6c40b12362e6b3082dffb7fc6550", "2338e90aafd734d44bd50aad3f4d0f4255e2d2505546925e810798626c79f4f4", "c141f87ed878c297468d5be367ce8df0c7d90be4b6be070059eb9345f8250b62", "57106030bb89bd435844ef9baf318c9696af10784a4cf09359bff4b22a4d74eb", "2419aa33614ded3307173c53d6f614b6567d6f50fdc9a99fd32a299efc3de982", "07e60b9438f0b0fc97151c34b781b2a6370cb4d6c48ecbbfe0016a24ebe7bf31", "c09518a1b22c36e3d599af9f956090609fff015a794680a12f730364c721aae4", "65ddb5cf2927237525c5b3d3613eb346660cba60d0478ea917b6f0aa4907d7d9", "1c8935ede01448904447520b90c742615062e404f3525fe5bd667e06f7341c13", "fcb9e121eb526413ec8c827a3dda5e619a85ffbcb7508f0525ac22a121a100f5", "6d0a6422309f64d722ba79f621a4fe3db0ecf16b40366313b146a97d95667307", "4ad7e9d2a199b2eb3cc1cf7bb35e7b03a0ca18bd7382ed29a18b97ed01cd63a0", "69e377941f0263ce3c585789ae6106782d1f15db0b1942a9627b2bd6fe83e13d", "bb51ed5948d59b0dcb2f5cb5f8a27d3f70b8c71660b0d6d4ab658b6a7ca2356c", "6695e79e0e07fde8c05da60736ba373d55271d5a7c6da2a2c7d30e957a46e7e7", "48bd888c98b158b5c82b148f091a91bb1881b9a1931227f0a5269649a8eebaff", "771382cfa5138ccd32fdddad18e3eb8f1a06eee10704248d1e4d49f32872afe6", "176bb2e118aeb292912fa1903470621ae385e819a50c580301b33165666f3c7d", "15596f8c5f8fb397e5214e6f5eaf286a813b6e5d8bebae2bad1d550511f92840", "bdacbb2d763783f1ac51fd2477276543f79db13a434697a2aedd8523a1427e1f", "ca0e3b746890e8d626840d445989bb0e703f3e4c792aaa49a6b8952ea7696063", "1319af4c3801a463f0e1b7a9cfe2cfbb79e769fb0daed1a2868ade7665765ea6", "172f67582c5270cf0ef8264ef64bc5e17a53aac87693eff1860dfe56aea4209e", "0462589f719e853654d1ca00038dfc806ae7acb9bb5a3f9e6d458f3d4206f532", "f7480a6f46b553517f41238cbd5a6069eab164fd1512e1685f9bddf5c1afa59c", "a5cfdbe5c0b38b0904b5fe6afc2ce583dce1dbc7b4cd88224cbd88efa30b0291", "6f07b548ced6405ef78693332d516d041780f85f0771cfbaba8bbb86a6cdfb7d", "de0184abac150e780e26f1e7de09da64dfee433e8c9a9efe8d93a673350016b8", "8e7cee539c6315ad939a9495e40e7e70e2d07f6b2920cdbcc689457cd9e11997", "0088ccc025bf814e8098607bfbd17448024495a62610700b6000ec448afc1ca3", "d3a0503fdb8802e979871dca7d3c10a928cedf1978e44f42ecb72b96ada13dc3", "add0b405d079dd0c682a1e5026ef1a5b989b0bdf044d2db28249b4d51a74c5dc"} // Convert each string to a [32]byte - for i := 0; i < 256; i++ { + for i := range 256 { // Decode hex string to bytes mainnetFixedHashes[i] = gethCommon.HexToHash(mainnetHashes[i]) testnetFixedHashes[i] = gethCommon.HexToHash(testnetHashes[i]) diff --git a/fvm/evm/offchain/blocks/blocks.go b/fvm/evm/offchain/blocks/blocks.go index 35b8c39638f..781acd939bf 100644 --- a/fvm/evm/offchain/blocks/blocks.go +++ b/fvm/evm/offchain/blocks/blocks.go @@ -5,7 +5,8 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" - "github.com/onflow/flow-go/fvm/evm/handler" + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/model/flow" ) @@ -16,9 +17,9 @@ const BlockStoreLatestBlockMetaKey = "LatestBlockMeta" // and also the latest executed block meta data type Blocks struct { chainID flow.ChainID - storage types.BackendStorage + storage backends.BackendStorage rootAddress flow.Address - bhl *handler.BlockHashList + bhl *environment.BlockHashList } var _ types.BlockSnapshot = (*Blocks)(nil) @@ -27,7 +28,7 @@ var _ types.BlockSnapshot = (*Blocks)(nil) func NewBlocks( chainID flow.ChainID, rootAddress flow.Address, - storage types.BackendStorage, + storage backends.BackendStorage, ) (*Blocks, error) { var err error blocks := &Blocks{ @@ -35,10 +36,10 @@ func NewBlocks( storage: storage, rootAddress: rootAddress, } - blocks.bhl, err = handler.NewBlockHashList( + blocks.bhl, err = environment.NewBlockHashList( storage, rootAddress, - handler.BlockHashListCapacity, + environment.BlockHashListCapacity, ) if err != nil { return nil, err @@ -83,7 +84,7 @@ func (b *Blocks) PushBlockMeta( return b.storeBlockMetaData(meta) } -// PushBlockHash pushes a new block block hash into the storage +// PushBlockHash pushes a new block hash into the storage func (b *Blocks) PushBlockHash( height uint64, hash gethCommon.Hash, diff --git a/fvm/evm/offchain/blocks/provider.go b/fvm/evm/offchain/blocks/provider.go index b9da39bd468..e14b566e6d3 100644 --- a/fvm/evm/offchain/blocks/provider.go +++ b/fvm/evm/offchain/blocks/provider.go @@ -3,8 +3,9 @@ package blocks import ( "fmt" + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/events" - "github.com/onflow/flow-go/fvm/evm/handler" "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/model/flow" ) @@ -17,7 +18,7 @@ type BasicProvider struct { chainID flow.ChainID blks *Blocks rootAddr flow.Address - storage types.BackendStorage + storage backends.BackendStorage latestBlockPayload *events.BlockEventPayload } @@ -25,7 +26,7 @@ var _ types.BlockSnapshotProvider = (*BasicProvider)(nil) func NewBasicProvider( chainID flow.ChainID, - storage types.BackendStorage, + storage backends.BackendStorage, rootAddr flow.Address, ) (*BasicProvider, error) { blks, err := NewBlocks(chainID, rootAddr, storage) @@ -87,7 +88,7 @@ func (p *BasicProvider) OnBlockExecuted( // do the same as handler.CommitBlockProposal err = p.storage.SetValue( p.rootAddr[:], - []byte(handler.BlockStoreLatestBlockKey), + []byte(environment.BlockStoreLatestBlockKey), blockBytes, ) if err != nil { @@ -103,7 +104,7 @@ func (p *BasicProvider) OnBlockExecuted( // update block proposal err = p.storage.SetValue( p.rootAddr[:], - []byte(handler.BlockStoreLatestBlockProposalKey), + []byte(environment.BlockStoreLatestBlockProposalKey), blockProposalBytes, ) if err != nil { diff --git a/fvm/evm/offchain/query/view_test.go b/fvm/evm/offchain/query/view_test.go index ec172f98cce..ba3438fe225 100644 --- a/fvm/evm/offchain/query/view_test.go +++ b/fvm/evm/offchain/query/view_test.go @@ -26,7 +26,7 @@ import ( func TestView(t *testing.T) { const chainID = flow.Emulator - RunWithTestBackend(t, func(backend *TestBackend) { + RunWithTestBackend(t, chainID, func(backend *TestBackend) { RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { RunWithDeployedContract(t, GetStorageTestContract(t), backend, rootAddr, func(testContract *TestContract) { @@ -189,7 +189,7 @@ func TestView(t *testing.T) { func TestViewStateOverrides(t *testing.T) { const chainID = flow.Emulator - RunWithTestBackend(t, func(backend *TestBackend) { + RunWithTestBackend(t, chainID, func(backend *TestBackend) { RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { RunWithDeployedContract(t, GetStorageTestContract(t), backend, rootAddr, func(testContract *TestContract) { diff --git a/fvm/evm/offchain/storage/ephemeral.go b/fvm/evm/offchain/storage/ephemeral.go index a1687460526..be5eedc4866 100644 --- a/fvm/evm/offchain/storage/ephemeral.go +++ b/fvm/evm/offchain/storage/ephemeral.go @@ -6,6 +6,7 @@ import ( "github.com/onflow/atree" "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/model/flow" ) @@ -14,19 +15,19 @@ import ( // the provided backend storage. It can be used for dry running transaction/calls // or batching updates for atomic operations. type EphemeralStorage struct { - parent types.BackendStorage + parent backends.BackendStorage deltas map[flow.RegisterID]flow.RegisterValue } // NewEphemeralStorage constructs a new EphemeralStorage -func NewEphemeralStorage(parent types.BackendStorage) *EphemeralStorage { +func NewEphemeralStorage(parent backends.BackendStorage) *EphemeralStorage { return &EphemeralStorage{ parent: parent, deltas: make(map[flow.RegisterID]flow.RegisterValue), } } -var _ types.BackendStorage = (*EphemeralStorage)(nil) +var _ backends.BackendStorage = (*EphemeralStorage)(nil) var _ types.ReplayResultCollector = (*EphemeralStorage)(nil) diff --git a/fvm/evm/offchain/storage/readonly.go b/fvm/evm/offchain/storage/readonly.go index 6c66e7c1e43..daecced2bcd 100644 --- a/fvm/evm/offchain/storage/readonly.go +++ b/fvm/evm/offchain/storage/readonly.go @@ -5,6 +5,7 @@ import ( "github.com/onflow/atree" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/types" ) @@ -13,7 +14,7 @@ type ReadOnlyStorage struct { snapshot types.BackendStorageSnapshot } -var _ types.BackendStorage = &ReadOnlyStorage{} +var _ backends.BackendStorage = &ReadOnlyStorage{} // NewReadOnlyStorage constructs a new ReadOnlyStorage using the given snapshot func NewReadOnlyStorage(snapshot types.BackendStorageSnapshot) *ReadOnlyStorage { diff --git a/fvm/evm/offchain/sync/replay.go b/fvm/evm/offchain/sync/replay.go index a9fe6b2f955..c83535362cf 100644 --- a/fvm/evm/offchain/sync/replay.go +++ b/fvm/evm/offchain/sync/replay.go @@ -9,6 +9,7 @@ import ( gethTrie "github.com/ethereum/go-ethereum/trie" "github.com/onflow/atree" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/emulator" "github.com/onflow/flow-go/fvm/evm/events" "github.com/onflow/flow-go/fvm/evm/precompiles" @@ -24,7 +25,7 @@ var emptyChecksum = [types.ChecksumLength]byte{0, 0, 0, 0} func ReplayBlockExecution( chainID flow.ChainID, rootAddr flow.Address, - storage types.BackendStorage, + storage backends.BackendStorage, blockSnapshot types.BlockSnapshot, tracer *gethTracer.Tracer, transactionEvents []events.TransactionEventPayload, diff --git a/fvm/evm/offchain/sync/replayer_test.go b/fvm/evm/offchain/sync/replayer_test.go index 6297a7e2531..d92a12bb644 100644 --- a/fvm/evm/offchain/sync/replayer_test.go +++ b/fvm/evm/offchain/sync/replayer_test.go @@ -23,7 +23,7 @@ func TestChainReplay(t *testing.T) { const chainID = flow.Emulator var snapshot *TestValueStore - RunWithTestBackend(t, func(backend *TestBackend) { + RunWithTestBackend(t, chainID, func(backend *TestBackend) { RunWithTestFlowEVMRootAddress(t, backend, func(rootAddr flow.Address) { RunWithDeployedContract(t, GetStorageTestContract(t), backend, rootAddr, func(testContract *TestContract) { diff --git a/fvm/evm/precompiles/abi.go b/fvm/evm/precompiles/abi.go index 3d805d9475f..49e5f027fc2 100644 --- a/fvm/evm/precompiles/abi.go +++ b/fvm/evm/precompiles/abi.go @@ -8,6 +8,22 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" ) +// The Cadence Arch precompiled contract that is injected in the EVM environment, +// implements the following functions: +// - `flowBlockHeight()` +// - `revertibleRandom()` +// - `getRandomSource(uint64)` +// - `verifyCOAOwnershipProof(address,bytes32,bytes)` +// +// By design, all errors that are the result of user input, will be propagated +// in the EVM environment, and can be handled by developers, as they see fit. +// However, all FVM fatal errors, will cause a panic and abort the outer Cadence +// transaction. The reason behind this is that we want to have visibility when +// such special errors occur. This way, any potential bugs will not go unnoticed. +// The Cadence runtime recovers any Go crashers (index out of bounds, nil +// dereferences, etc.) and fails the transaction gracefully, so a panic in the +// precompiled contract does not indicate a node/runtime crash. + // This package provides fast and efficient // utilities needed for abi encoding and decoding // encodings are mostly used for testing purpose @@ -30,9 +46,11 @@ const ( EncodedUint256Size = FixedSizeUnitDataReadSize ) -var ErrInputDataTooSmall = errors.New("input data is too small for decoding") -var ErrBufferTooSmall = errors.New("buffer too small for encoding") -var ErrDataTooLarge = errors.New("input data is too large for encoding") +var ( + ErrInputDataTooSmall = errors.New("input data is too small for decoding") + ErrBufferTooSmall = errors.New("buffer too small for encoding") + ErrDataTooLarge = errors.New("input data is too large for encoding") +) // ReadAddress reads an address from the buffer at index func ReadAddress(buffer []byte, index int) (gethCommon.Address, error) { @@ -72,7 +90,7 @@ func EncodeBool(bitSet bool, buffer []byte, index int) error { return ErrBufferTooSmall } // bit set with left padding - for i := 0; i < EncodedBoolSize; i++ { + for i := range EncodedBoolSize { buffer[index+i] = 0 } if bitSet { @@ -158,11 +176,16 @@ func ReadBytes(buffer []byte, index int) ([]byte, error) { if len(buffer) < index+EncodedUint64Size { return nil, ErrInputDataTooSmall } + // reading offset (we read into uint64) and adjust index offset, err := ReadUint64(buffer, index) if err != nil { return nil, err } + if offset > uint64(len(buffer)) { + return nil, ErrInputDataTooSmall + } + index = int(offset) if len(buffer) < index+EncodedUint64Size { return nil, ErrInputDataTooSmall @@ -172,6 +195,10 @@ func ReadBytes(buffer []byte, index int) ([]byte, error) { if err != nil { return nil, err } + if length > uint64(len(buffer)) { + return nil, ErrInputDataTooSmall + } + index += EncodedUint64Size if len(buffer) < index+int(length) { return nil, ErrInputDataTooSmall @@ -181,30 +208,19 @@ func ReadBytes(buffer []byte, index int) ([]byte, error) { // SizeNeededForBytesEncoding computes the number of bytes needed for bytes encoding func SizeNeededForBytesEncoding(data []byte) int { - if len(data) == 0 { - return EncodedUint64Size + EncodedUint64Size + FixedSizeUnitDataReadSize - } - paddedSize := (len(data) / FixedSizeUnitDataReadSize) - if len(data)%FixedSizeUnitDataReadSize != 0 { - paddedSize += 1 + dataSize := len(data) + if dataSize == 0 { + return EncodedUint64Size + EncodedUint64Size } - return EncodedUint64Size + EncodedUint64Size + paddedSize*FixedSizeUnitDataReadSize + + paddedSize := computePaddedSize(dataSize) + return EncodedUint64Size + EncodedUint64Size + paddedSize } // EncodeBytes encodes the data into the buffer at index and append payload to the // end of buffer func EncodeBytes(data []byte, buffer []byte, headerIndex, payloadIndex int) error { - //// updating offset - if len(buffer) < headerIndex+EncodedUint64Size { - return ErrBufferTooSmall - } - dataSize := len(data) - // compute padded data size - paddedSize := (dataSize / FixedSizeUnitDataReadSize) - if dataSize%FixedSizeUnitDataReadSize != 0 { - paddedSize += FixedSizeUnitDataReadSize - } - if len(buffer) < payloadIndex+EncodedUint64Size+paddedSize { + if len(buffer) < headerIndex+SizeNeededForBytesEncoding(data) { return ErrBufferTooSmall } @@ -213,9 +229,10 @@ func EncodeBytes(data []byte, buffer []byte, headerIndex, payloadIndex int) erro return err } - //// updating payload // padding data - if dataSize%FixedSizeUnitDataReadSize != 0 { + dataSize := len(data) + paddedSize := computePaddedSize(dataSize) + if dataSize < paddedSize { data = gethCommon.RightPadBytes(data, paddedSize) } @@ -226,6 +243,18 @@ func EncodeBytes(data []byte, buffer []byte, headerIndex, payloadIndex int) erro } payloadIndex += EncodedUint64Size // adding data - copy(buffer[payloadIndex:payloadIndex+len(data)], data) + copy(buffer[payloadIndex:payloadIndex+dataSize], data) return nil } + +// computePaddedSize computes the 32-byte padding needed for data of the +// given size +func computePaddedSize(dataSize int) int { + // compute padded data size + chunks := (dataSize / FixedSizeUnitDataReadSize) + if dataSize%FixedSizeUnitDataReadSize != 0 { + chunks += 1 + } + + return chunks * FixedSizeUnitDataReadSize +} diff --git a/fvm/evm/precompiles/abi_test.go b/fvm/evm/precompiles/abi_test.go index f77804017ee..44c760d1cfd 100644 --- a/fvm/evm/precompiles/abi_test.go +++ b/fvm/evm/precompiles/abi_test.go @@ -101,18 +101,50 @@ func TestABIEncodingDecodingFunctions(t *testing.T) { require.Equal(t, encodedData, buffer) }) + t.Run("test encode bytes (buffer too small)", func(t *testing.T) { + encodedData, err := hex.DecodeString("e27d73dc3adb81aeea2e5bd35b863fe3f234e1a603fd3bdbaf657c179e67871d") + require.NoError(t, err) + + bufferSize := precompiles.SizeNeededForBytesEncoding(encodedData) + require.Equal(t, 3*32, bufferSize) + + buffer := make([]byte, bufferSize-5) + original := append([]byte(nil), buffer...) + err = precompiles.EncodeBytes(encodedData, buffer, 0, precompiles.EncodedUint64Size) + require.Error(t, err) + require.ErrorContains(t, err, "buffer too small for encoding") + require.Equal(t, original, buffer) + }) + + t.Run("test encode bytes (multiple chunks)", func(t *testing.T) { + // The following data needs more than a 32-byte chunk to fit in. + encodedData, err := hex.DecodeString("e27d73dc3adb81aeea2e5bd35b863fe3f234e1a603fd3bdbaf657c179e67871df1") + require.NoError(t, err) + require.Len(t, encodedData, 33) + + bufferSize := precompiles.SizeNeededForBytesEncoding(encodedData) + require.Equal(t, 4*32, bufferSize) + + buffer := make([]byte, bufferSize) + err = precompiles.EncodeBytes(encodedData, buffer, 0, precompiles.EncodedUint64Size) + require.NoError(t, err) + + expectedData, err := hex.DecodeString("00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000021e27d73dc3adb81aeea2e5bd35b863fe3f234e1a603fd3bdbaf657c179e67871df100000000000000000000000000000000000000000000000000000000000000") + require.NoError(t, err) + require.Equal(t, expectedData, buffer) + }) + t.Run("test size needed for encoding bytes", func(t *testing.T) { // len zero data := []byte{} ret := precompiles.SizeNeededForBytesEncoding(data) offsetAndLenEncodingSize := precompiles.EncodedUint64Size + precompiles.EncodedUint64Size - expectedSize := offsetAndLenEncodingSize + precompiles.FixedSizeUnitDataReadSize - require.Equal(t, expectedSize, ret) + require.Equal(t, offsetAndLenEncodingSize, ret) // data size 1 data = []byte{1} ret = precompiles.SizeNeededForBytesEncoding(data) - expectedSize = offsetAndLenEncodingSize + precompiles.FixedSizeUnitDataReadSize + expectedSize := offsetAndLenEncodingSize + precompiles.FixedSizeUnitDataReadSize require.Equal(t, expectedSize, ret) // data size 32 diff --git a/fvm/evm/precompiles/arch.go b/fvm/evm/precompiles/arch.go index bdbe7b0a621..40e21bf00b6 100644 --- a/fvm/evm/precompiles/arch.go +++ b/fvm/evm/precompiles/arch.go @@ -6,6 +6,22 @@ import ( "github.com/onflow/flow-go/fvm/evm/types" ) +// The Cadence Arch precompiled contract that is injected in the EVM environment, +// implements the following functions: +// - `flowBlockHeight()` +// - `revertibleRandom()` +// - `getRandomSource(uint64)` +// - `verifyCOAOwnershipProof(address,bytes32,bytes)` +// +// By design, all errors that are the result of user input, will be propagated +// in the EVM environment, and can be handled by developers, as they see fit. +// However, all FVM fatal errors, will cause a panic and abort the outer Cadence +// transaction. The reason behind this is that we want to have visibility when +// such special errors occur. This way, any potential bugs will not go unnoticed. +// The Cadence runtime recovers any Go crashers (index out of bounds, nil +// dereferences, etc.) and fails the transaction gracefully, so a panic in the +// precompiled contract does not indicate a node/runtime crash. + const CADENCE_ARCH_PRECOMPILE_NAME = "CADENCE_ARCH" var ( diff --git a/fvm/evm/stdlib/contract.cdc b/fvm/evm/stdlib/contract.cdc index 66eb01b40a7..397b25613b3 100644 --- a/fvm/evm/stdlib/contract.cdc +++ b/fvm/evm/stdlib/contract.cdc @@ -7,7 +7,7 @@ import "FlowToken" The Flow EVM contract defines important types and functionality to allow Cadence code and Flow SDKs to interface - with the Etherem Virtual Machine environment on Flow. + with the Ethereum Virtual Machine environment on Flow. The EVM contract emits events when relevant actions happen in Flow EVM such as creating new blocks, executing transactions, and bridging FLOW @@ -22,7 +22,7 @@ import "FlowToken" and many of its functionality is directly connected to the protocol software to allow interaction with the EVM. - See additional EVM documentation here: https://developers.flow.com/evm/about + See additional EVM documentation here: https://developers.flow.com/build/evm/how-it-works */ @@ -175,7 +175,7 @@ access(all) contract EVM { /// Nonce of the address access(all) - fun nonce(): UInt64 { + view fun nonce(): UInt64 { return InternalEVM.nonce( address: self.bytes ) @@ -183,7 +183,7 @@ access(all) contract EVM { /// Code of the address access(all) - fun code(): [UInt8] { + view fun code(): [UInt8] { return InternalEVM.code( address: self.bytes ) @@ -191,7 +191,7 @@ access(all) contract EVM { /// CodeHash of the address access(all) - fun codeHash(): [UInt8] { + view fun codeHash(): [UInt8] { return InternalEVM.codeHash( address: self.bytes ) @@ -200,6 +200,10 @@ access(all) contract EVM { /// Deposits the given vault into the EVM account with the given address access(all) fun deposit(from: @FlowToken.Vault) { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } + let amount = from.balance if amount == 0.0 { destroy from @@ -241,9 +245,18 @@ access(all) contract EVM { "EVM.addressFromString(): Invalid hex string length for an EVM address. The provided string is \(asHex.length), but the length must be 40 or 42." } // Strip the 0x prefix if it exists - var withoutPrefix = (asHex[1] == "x" ? asHex.slice(from: 2, upTo: asHex.length) : asHex).toLower() - let bytes = withoutPrefix.decodeHex().toConstantSized<[UInt8; 20]>()! - return EVMAddress(bytes: bytes) + var withoutPrefix = asHex + if asHex.length == 42 { + assert( + asHex[0] == "0" && asHex[1] == "x", + message: "EVM.addressFromString(): The 42-character EVM address string must have a '0x' prefix" + ) + withoutPrefix = asHex.slice(from: 2, upTo: asHex.length) + } + + return EVMAddress( + bytes: withoutPrefix.decodeHex().toConstantSized<[UInt8; 20]>()! + ) } /// EVMBytes is a type wrapper used for ABI encoding/decoding into @@ -306,7 +319,7 @@ access(all) contract EVM { /// Casts the balance to a UFix64 (rounding down) /// Warning! casting a balance to a UFix64 which supports a lower level of precision /// (8 decimal points in compare to 18) might result in rounding down error. - /// Use the inAttoFlow function if you need more accuracy. + /// Use the inAttoFLOW function if you need more accuracy. access(all) view fun inFLOW(): UFix64 { return InternalEVM.castToFLOW(balance: self.attoflow) @@ -320,7 +333,7 @@ access(all) contract EVM { /// Returns true if the balance is zero access(all) - fun isZero(): Bool { + view fun isZero(): Bool { return self.attoflow == 0 } } @@ -401,6 +414,55 @@ access(all) contract EVM { } } + /// Reports the outcome of an evm transaction/call execution attempt. + /// The results field has the decoded evm transaction/call results if + /// result types are provided; otherwise, the results field is nil. + access(all) struct ResultDecoded { + /// status of the execution + access(all) let status: Status + + /// error code (error code zero means no error) + access(all) let errorCode: UInt64 + + /// error message + access(all) let errorMessage: String + + /// returns the amount of gas metered during + /// evm execution + access(all) let gasUsed: UInt64 + + /// Returns the decoded results from the evm call if + /// the evm call is successful and resultTypes are provided. + /// Otherwise, returns raw result data from the evm call. + access(all) let results: [AnyStruct] + + /// returns the newly deployed contract address + /// if the transaction caused such a deployment + /// otherwise the value is nil. + access(all) let deployedContract: EVMAddress? + + init( + status: Status, + errorCode: UInt64, + errorMessage: String, + gasUsed: UInt64, + results: [AnyStruct], + contractAddress: [UInt8; 20]? + ) { + self.status = status + self.errorCode = errorCode + self.errorMessage = errorMessage + self.gasUsed = gasUsed + self.results = results + + if let addressBytes = contractAddress { + self.deployedContract = EVMAddress(bytes: addressBytes) + } else { + self.deployedContract = nil + } + } + } + /* Cadence-Owned Accounts (COA) A COA is a natively supported EVM smart contract wallet type @@ -468,8 +530,6 @@ access(all) contract EVM { /// Sets the EVM address for the COA. Only callable once on initial creation. /// /// @param addressBytes: The 20 byte EVM address - /// - /// @return the token decimals of the ERC20 access(contract) fun initAddress(addressBytes: [UInt8; 20]) { // only allow set address for the first time @@ -493,14 +553,12 @@ access(all) contract EVM { /// access(all) view fun balance(): Balance { - return self.address().balance() + return Balance(attoflow: InternalEVM.balance(address: self.addressBytes)) } /// Deposits the given vault into the cadence owned account's balance /// /// @param from: The FlowToken Vault to deposit to this cadence owned account - /// - /// @return the token decimals of the ERC20 access(all) fun deposit(from: @FlowToken.Vault) { self.address().deposit(from: <-from) @@ -513,17 +571,24 @@ access(all) contract EVM { return self.address() } - /// Withdraws the balance from the cadence owned account's balance - /// Note that amounts smaller than 10nF (10e-8) can't be withdrawn - /// given that Flow Token Vaults use UFix64s to store balances. - /// If the given balance conversion to UFix64 results in - /// rounding error, this function would fail. + /// Withdraws the balance from the cadence owned account's balance. + /// Note that amounts smaller than 1e10 attoFlow can't be withdrawn, + /// given that Flow Token Vaults use UFix64 to store balances. + /// In other words, the smallest withdrawable amount is 1e10 attoFlow. + /// Amounts smaller than 1e10 attoFlow, will cause the function to panic + /// with: "withdraw failed! smallest unit allowed to transfer is 1e10 attoFlow". + /// If the given balance conversion to UFix64 results in rounding loss, + /// the withdrawal amount will be truncated to the maximum precision for UFix64. /// /// @param balance: The EVM balance to withdraw /// /// @return A FlowToken Vault with the requested balance access(Owner | Withdraw) fun withdraw(balance: Balance): @FlowToken.Vault { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } + if balance.isZero() { return <-FlowToken.createEmptyVault(vaultType: Type<@FlowToken.Vault>()) } @@ -555,6 +620,9 @@ access(all) contract EVM { gasLimit: UInt64, value: Balance ): Result { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } return InternalEVM.deploy( from: self.addressBytes, code: code, @@ -572,6 +640,9 @@ access(all) contract EVM { gasLimit: UInt64, value: Balance ): Result { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } return InternalEVM.call( from: self.addressBytes, to: to.bytes, @@ -581,6 +652,34 @@ access(all) contract EVM { ) as! Result } + /// Calls a contract function with the given signature and args. + /// The execution is limited by the given amount of gas. + /// The value is attoflow. If the resultTypes is provided, + /// the evm call results are decoded and returned in ResultDecoded.results; + /// otherwise, the evm call results are discarded and not returned. + access(Owner | Call) + fun callWithSigAndArgs( + to: EVMAddress, + signature: String, + args: [AnyStruct], + gasLimit: UInt64, + value: UInt, + resultTypes: [Type]? + ): ResultDecoded { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } + return InternalEVM.callWithSigAndArgs( + from: self.addressBytes, + to: to.bytes, + signature: signature, + args: args, + gasLimit: gasLimit, + value: value, + resultTypes: resultTypes + ) as! ResultDecoded + } + /// Calls a contract function with the given data. /// The execution is limited by the given amount of gas. /// The transaction state changes are not persisted. @@ -600,6 +699,32 @@ access(all) contract EVM { ) as! Result } + /// Calls a contract function with the given signature and args. + /// The execution is limited by the given amount of gas. + /// The value is attoflow. If the resultTypes is provided, + /// the evm call results are decoded and returned in ResultDecoded.results; + /// otherwise, the evm call results are discarded and not returned. + /// The transaction state changes are not persisted. + access(all) + fun dryCallWithSigAndArgs( + to: EVMAddress, + signature: String, + args: [AnyStruct], + gasLimit: UInt64, + value: UInt, + resultTypes: [Type]? + ): ResultDecoded { + return InternalEVM.dryCallWithSigAndArgs( + from: self.addressBytes, + to: to.bytes, + signature: signature, + args: args, + gasLimit: gasLimit, + value: value, + resultTypes: resultTypes, + ) as! ResultDecoded + } + /// Bridges the given NFT to the EVM environment, requiring a Provider /// from which to withdraw a fee to fulfill the bridge request /// @@ -611,6 +736,9 @@ access(all) contract EVM { nft: @{NonFungibleToken.NFT}, feeProvider: auth(FungibleToken.Withdraw) &{FungibleToken.Provider} ) { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } EVM.borrowBridgeAccessor().depositNFT(nft: <-nft, to: self.address(), feeProvider: feeProvider) } @@ -630,6 +758,9 @@ access(all) contract EVM { id: UInt256, feeProvider: auth(FungibleToken.Withdraw) &{FungibleToken.Provider} ): @{NonFungibleToken.NFT} { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } return <- EVM.borrowBridgeAccessor().withdrawNFT( caller: &self as auth(Call) &CadenceOwnedAccount, type: type, @@ -644,6 +775,9 @@ access(all) contract EVM { vault: @{FungibleToken.Vault}, feeProvider: auth(FungibleToken.Withdraw) &{FungibleToken.Provider} ) { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } EVM.borrowBridgeAccessor().depositTokens(vault: <-vault, to: self.address(), feeProvider: feeProvider) } @@ -656,6 +790,9 @@ access(all) contract EVM { amount: UInt256, feeProvider: auth(FungibleToken.Withdraw) &{FungibleToken.Provider} ): @{FungibleToken.Vault} { + pre { + !EVM.isPaused(): "EVM operations are temporarily paused" + } return <- EVM.borrowBridgeAccessor().withdrawTokens( caller: &self as auth(Call) &CadenceOwnedAccount, type: type, @@ -668,6 +805,9 @@ access(all) contract EVM { /// Creates a new cadence owned account access(all) fun createCadenceOwnedAccount(): @CadenceOwnedAccount { + pre { + !self.isPaused(): "EVM operations are temporarily paused" + } let acc <-create CadenceOwnedAccount() let addr = InternalEVM.createCadenceOwnedAccount(uuid: acc.uuid) acc.initAddress(addressBytes: addr) @@ -686,9 +826,12 @@ access(all) contract EVM { /// @return: The transaction result access(all) fun run(tx: [UInt8], coinbase: EVMAddress): Result { + pre { + !self.isPaused(): "EVM operations are temporarily paused" + } return InternalEVM.run( - tx: tx, - coinbase: coinbase.bytes + tx: tx, + coinbase: coinbase.bytes ) as! Result } @@ -711,6 +854,8 @@ access(all) contract EVM { /// the from address as the signer. /// The transaction state changes are not persisted. /// This is useful for gas estimation or calling view contract functions. + /// Note: dry-run functions are intentionally exempt from the isPaused() guard — + /// they perform no state mutations and remain available in read-only mode. access(all) fun dryRun(tx: [UInt8], from: EVMAddress): Result { return InternalEVM.dryRun( @@ -739,22 +884,62 @@ access(all) contract EVM { ) as! Result } + /// Calls a contract function with the given signature and args. + /// The execution is limited by the given amount of gas. + /// The value is attoflow. If the resultTypes is provided, + /// the evm call results are decoded and returned in ResultDecoded.results; + /// otherwise, the evm call results are discarded and not returned. + /// The transaction state changes are not persisted. + access(all) + fun dryCallWithSigAndArgs( + from: EVMAddress, + to: EVMAddress, + signature: String, + args: [AnyStruct], + gasLimit: UInt64, + value: UInt, + resultTypes: [Type]?, + ): ResultDecoded { + return InternalEVM.dryCallWithSigAndArgs( + from: from.bytes, + to: to.bytes, + signature: signature, + args: args, + gasLimit: gasLimit, + value: value, + resultTypes: resultTypes + ) as! ResultDecoded + } + /// Runs a batch of RLP-encoded EVM transactions, deducts the gas fees, /// and deposits the gas fees into the provided coinbase address. /// An invalid transaction is not executed and not included in the block. access(all) fun batchRun(txs: [[UInt8]], coinbase: EVMAddress): [Result] { + pre { + !self.isPaused(): "EVM operations are temporarily paused" + } return InternalEVM.batchRun( txs: txs, coinbase: coinbase.bytes, ) as! [Result] } + /// Encodes the given values into an ABI-encoded byte array according to + /// the Solidity ABI specification. Cadence types are mapped to their + /// corresponding Solidity types (e.g. UInt256 → uint256, [UInt8] → bytes). + /// + /// No error returns are expected during normal operation. access(all) fun encodeABI(_ values: [AnyStruct]): [UInt8] { return InternalEVM.encodeABI(values) } + /// Decodes an ABI-encoded byte array into Cadence values according to + /// the Solidity ABI specification. The provided types must match the + /// encoding of data exactly; a mismatch will panic. + /// + /// No error returns are expected during normal operation. access(all) fun decodeABI(types: [Type], data: [UInt8]): [AnyStruct] { return InternalEVM.decodeABI(types: types, data: data) @@ -779,17 +964,23 @@ access(all) contract EVM { types: [Type], data: [UInt8] ): [AnyStruct] { + pre { + data.length >= 4: "EVM.decodeABIWithSignature(): Cannot decode! The provided data does not contain a signature." + } let methodID = HashAlgorithm.KECCAK_256.hash( signature.utf8 ).slice(from: 0, upTo: 4) - for byte in methodID { - if byte != data.removeFirst() { + // Compare the 4-byte method ID prefix using index access rather than removeFirst(), + // since removeFirst() is O(n) and would shift the entire array on each call. + // data.slice() is then used to pass only the ABI-encoded arguments to decodeABI. + for i, byte in methodID { + if byte != data[i] { panic("EVM.decodeABIWithSignature(): Cannot decode! The signature does not match the provided data.") } } - return InternalEVM.decodeABI(types: types, data: data) + return InternalEVM.decodeABI(types: types, data: data.slice(from: 4, upTo: data.length)) } /// ValidationResult returns the result of COA ownership proof validation @@ -807,7 +998,15 @@ access(all) contract EVM { } } - /// validateCOAOwnershipProof validates a COA ownership proof + /// validateCOAOwnershipProof validates a COA ownership proof. + /// + /// Note: this function does not enforce that `signedData` includes `evmAddress`. + /// In principle, a signature produced for one purpose could be replayed here against + /// a different COA owned by the same Cadence account. In practice this is low-risk: + /// the EVM-side precompile (verifyCOAOwnershipProof) always passes the calling COA's + /// address as the evmAddress argument, and Flow wallets historically create at most one + /// COA per account. Callers building off-chain authentication flows on top of this + /// function should ensure `signedData` encodes `evmAddress` to prevent cross-address replay. access(all) fun validateCOAOwnershipProof( address: Address, @@ -822,8 +1021,7 @@ access(all) contract EVM { if keyIndices.length != signatures.length { return ValidationResult( isValid: false, - problem: "EVM.validateCOAOwnershipProof(): Key indices array length" - .concat(" doesn't match the signatures array length!") + problem: "EVM.validateCOAOwnershipProof(): Key indices array length doesn't match the signatures array length!" ) } @@ -846,8 +1044,7 @@ access(all) contract EVM { if key.isRevoked { return ValidationResult( isValid: false, - problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership" - .concat(" for Cadence account \(address). The account key at index \(accountKeyIndex) is revoked.") + problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership for Cadence account \(address). The account key at index \(accountKeyIndex) is revoked." ) } @@ -866,8 +1063,7 @@ access(all) contract EVM { } else { return ValidationResult( isValid: false, - problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership" - .concat(" for Cadence account \(address). The key index \(accountKeyIndex) is invalid.") + problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership for Cadence account \(address). The key index \(accountKeyIndex) is invalid." ) } } else { @@ -892,35 +1088,30 @@ access(all) contract EVM { if !isValid{ return ValidationResult( isValid: false, - problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership" - .concat(" for Cadence account \(address). The given signatures are not valid or provide enough weight.") + problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership for Cadence account \(address). The given signatures are not valid or provide enough weight." ) } - let coaRef = acc.capabilities.borrow<&EVM.CadenceOwnedAccount>(path) - if coaRef == nil { - return ValidationResult( - isValid: false, - problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership. " - .concat("Could not borrow the COA resource for account \(address).") - ) - } - - // verify evm address matching - var addr = coaRef!.address() - for index, item in coaRef!.address().bytes { - if item != evmAddress[index] { - return ValidationResult( - isValid: false, - problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership." - .concat("The provided evm address does not match the account's COA address.") - ) + if let coaRef = acc.capabilities.borrow<&EVM.CadenceOwnedAccount>(path) { + // verify evm address matching — capture bytes once to avoid redundant borrow + let coaAddressBytes = coaRef.address().bytes + for index, item in coaAddressBytes { + if item != evmAddress[index] { + return ValidationResult( + isValid: false, + problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership. The provided evm address does not match the account's COA address." + ) + } } + return ValidationResult( + isValid: true, + problem: nil + ) } return ValidationResult( - isValid: true, - problem: nil + isValid: false, + problem: "EVM.validateCOAOwnershipProof(): Cannot validate COA ownership. Could not borrow the COA resource for account \(address)." ) } @@ -973,8 +1164,10 @@ access(all) contract EVM { /// Sets the BridgeAccessor Capability in the BridgeRouter access(Bridge) fun setBridgeAccessor(_ accessor: Capability) { pre { - accessor.check(): + accessor.check(): "EVM.setBridgeAccessor(): Invalid BridgeAccessor Capability provided" + } + post { emit BridgeAccessorUpdated( routerType: self.getType(), routerUUID: self.uuid, @@ -1015,8 +1208,10 @@ access(all) contract EVM { /// The heartbeat resource is used to control the block production, /// and used in the Flow protocol to call the heartbeat function once per block. /// - /// The function can be called by anyone, but only once: - /// the function will fail if the resource already exists. + /// The function is access(all) because it is called during contract initialization + /// before account-level access is available. It is safe to be public because + /// it can only succeed once: any subsequent call will panic because the storage + /// path is already occupied. /// /// The resulting resource is stored in the account storage, /// and is only accessible by the account, not the caller of the function. @@ -1025,7 +1220,25 @@ access(all) contract EVM { self.account.storage.save(<-create Heartbeat(), to: /storage/EVMHeartbeat) } + /// Returns whether EVM transactions have been paused, either for + /// maintenance or any situation that requires special governance + /// handling. + /// + /// Only the Governance Committee can pause the EVM transactions, with + /// a multi-sig Cadence transaction. The EVM enters a read-only mode, + /// where all EVM state is available for reading, but no state updates + /// are executed. + access(all) + view fun isPaused(): Bool { + return self.account.storage.copy( + from: /storage/evmOperationsPaused + ) ?? false + } + init() { self.setupHeartbeat() } + + // Placeholder to load test helpers available only on Flow Emulator network + // #loadTestHelpers } diff --git a/fvm/evm/stdlib/contract.go b/fvm/evm/stdlib/contract.go index 7e189dd6b4d..de333f0710a 100644 --- a/fvm/evm/stdlib/contract.go +++ b/fvm/evm/stdlib/contract.go @@ -23,11 +23,20 @@ var contractCode string //go:embed contract_minimal.cdc var ContractMinimalCode string +//go:embed contract_test_helpers.cdc +var contractTestHelpers string + var nftImportPattern = regexp.MustCompile(`(?m)^import "NonFungibleToken"`) var fungibleTokenImportPattern = regexp.MustCompile(`(?m)^import "FungibleToken"`) var flowTokenImportPattern = regexp.MustCompile(`(?m)^import "FlowToken"`) - -func ContractCode(nonFungibleTokenAddress, fungibleTokenAddress, flowTokenAddress flow.Address) []byte { +var loadTestHelpersPattern = regexp.MustCompile(`(?m)\/\/ #loadTestHelpers`) + +func ContractCode( + nonFungibleTokenAddress, + fungibleTokenAddress, + flowTokenAddress flow.Address, + evmTestHelpersEnabled bool, +) []byte { evmContract := nftImportPattern.ReplaceAllString( contractCode, fmt.Sprintf("import NonFungibleToken from %s", nonFungibleTokenAddress.HexWithPrefix()), @@ -40,6 +49,20 @@ func ContractCode(nonFungibleTokenAddress, fungibleTokenAddress, flowTokenAddres evmContract, fmt.Sprintf("import FlowToken from %s", flowTokenAddress.HexWithPrefix()), ) + + // Inject the contract_test_helpers.cdc code, only if the + // bootstrapping option was specified. + if evmTestHelpersEnabled { + replaced := loadTestHelpersPattern.ReplaceAllLiteralString( + evmContract, + contractTestHelpers, + ) + if replaced == evmContract { + panic("missing // `#loadTestHelpers` marker in contract.cdc") + } + evmContract = replaced + } + return []byte(evmContract) } @@ -60,13 +83,15 @@ const ( EVMBytes32TypeQualifiedIdentifier = "EVM.EVMBytes32" - EVMResultTypeQualifiedIdentifier = "EVM.Result" - EVMResultTypeStatusFieldName = "status" - EVMResultTypeErrorCodeFieldName = "errorCode" - EVMResultTypeErrorMessageFieldName = "errorMessage" - EVMResultTypeGasUsedFieldName = "gasUsed" - EVMResultTypeDataFieldName = "data" - EVMResultTypeDeployedContractFieldName = "deployedContract" + EVMResultTypeQualifiedIdentifier = "EVM.Result" + EVMResultDecodedTypeQualifiedIdentifier = "EVM.ResultDecoded" + EVMResultTypeStatusFieldName = "status" + EVMResultTypeErrorCodeFieldName = "errorCode" + EVMResultTypeErrorMessageFieldName = "errorMessage" + EVMResultTypeGasUsedFieldName = "gasUsed" + EVMResultTypeResultsFieldName = "results" + EVMResultTypeDataFieldName = "data" + EVMResultTypeDeployedContractFieldName = "deployedContract" EVMStatusTypeQualifiedIdentifier = "EVM.Status" @@ -230,6 +255,81 @@ var InternalEVMTypeCallFunctionType = &sema.FunctionType{ ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.AnyStructType), } +// InternalEVM.runTxAs + +const InternalEVMTypeRunTxAsFunctionName = "runTxAs" + +var InternalEVMTypeRunTxAsFunctionType = &sema.FunctionType{ + Parameters: []sema.Parameter{ + { + Label: "from", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "to", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "data", + TypeAnnotation: sema.NewTypeAnnotation(sema.ByteArrayType), + }, + { + Label: "gasLimit", + TypeAnnotation: sema.NewTypeAnnotation(sema.UInt64Type), + }, + { + Label: "value", + TypeAnnotation: sema.NewTypeAnnotation(sema.UIntType), + }, + }, + // Actually EVM.Result, but cannot refer to it here + ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.AnyStructType), +} + +// InternalEVM.callWithSigAndArgs + +const InternalEVMTypeCallWithSigAndArgsFunctionName = "callWithSigAndArgs" + +var InternalEVMTypeCallWithSigAndArgsFunctionType = &sema.FunctionType{ + Parameters: []sema.Parameter{ + { + Label: "from", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "to", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "signature", + TypeAnnotation: sema.NewTypeAnnotation(sema.StringType), + }, + { + Label: "args", + TypeAnnotation: sema.NewTypeAnnotation(sema.NewVariableSizedType(nil, sema.AnyStructType)), + }, + { + Label: "gasLimit", + TypeAnnotation: sema.NewTypeAnnotation(sema.UInt64Type), + }, + { + Label: "value", + TypeAnnotation: sema.NewTypeAnnotation(sema.UIntType), + }, + { + Label: "resultTypes", + TypeAnnotation: sema.NewTypeAnnotation( + sema.NewOptionalType( + nil, + sema.NewVariableSizedType(nil, sema.MetaType), + ), + ), + }, + }, + // Actually EVM.ResultDecoded, but cannot refer to it here + ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.AnyStructType), +} + // InternalEVM.dryCall const InternalEVMTypeDryCallFunctionName = "dryCall" @@ -261,6 +361,50 @@ var InternalEVMTypeDryCallFunctionType = &sema.FunctionType{ ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.AnyStructType), } +// InternalEVM.dryCallWithSigAndArgs + +const InternalEVMTypeDryCallWithSigAndArgsFunctionName = "dryCallWithSigAndArgs" + +var InternalEVMTypeDryCallWithSigAndArgsFunctionType = &sema.FunctionType{ + Parameters: []sema.Parameter{ + { + Label: "from", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "to", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "signature", + TypeAnnotation: sema.NewTypeAnnotation(sema.StringType), + }, + { + Label: "args", + TypeAnnotation: sema.NewTypeAnnotation(sema.NewVariableSizedType(nil, sema.AnyStructType)), + }, + { + Label: "gasLimit", + TypeAnnotation: sema.NewTypeAnnotation(sema.UInt64Type), + }, + { + Label: "value", + TypeAnnotation: sema.NewTypeAnnotation(sema.UIntType), + }, + { + Label: "resultTypes", + TypeAnnotation: sema.NewTypeAnnotation( + sema.NewOptionalType( + nil, + sema.NewVariableSizedType(nil, sema.MetaType), + ), + ), + }, + }, + // Actually EVM.ResultDecoded, but cannot refer to it here + ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.AnyStructType), +} + // InternalEVM.createCadenceOwnedAccount const InternalEVMTypeCreateCadenceOwnedAccountFunctionName = "createCadenceOwnedAccount" @@ -313,6 +457,7 @@ var InternalEVMTypeBalanceFunctionType = &sema.FunctionType{ const InternalEVMTypeNonceFunctionName = "nonce" var InternalEVMTypeNonceFunctionType = &sema.FunctionType{ + Purity: sema.FunctionPurityView, Parameters: []sema.Parameter{ { Label: "address", @@ -327,6 +472,7 @@ var InternalEVMTypeNonceFunctionType = &sema.FunctionType{ const InternalEVMTypeCodeFunctionName = "code" var InternalEVMTypeCodeFunctionType = &sema.FunctionType{ + Purity: sema.FunctionPurityView, Parameters: []sema.Parameter{ { Label: "address", @@ -341,6 +487,7 @@ var InternalEVMTypeCodeFunctionType = &sema.FunctionType{ const InternalEVMTypeCodeHashFunctionName = "codeHash" var InternalEVMTypeCodeHashFunctionType = &sema.FunctionType{ + Purity: sema.FunctionPurityView, Parameters: []sema.Parameter{ { Label: "address", @@ -444,6 +591,47 @@ var InternalEVMTypeGetLatestBlockFunctionType = &sema.FunctionType{ ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.AnyStructType), } +// InternalEVM.store + +const InternalEVMTypeStoreFunctionName = "store" + +var InternalEVMTypeStoreFunctionType = &sema.FunctionType{ + Parameters: []sema.Parameter{ + { + Label: "target", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "slot", + TypeAnnotation: sema.NewTypeAnnotation(sema.StringType), + }, + { + Label: "value", + TypeAnnotation: sema.NewTypeAnnotation(sema.StringType), + }, + }, + ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.VoidType), +} + +// InternalEVM.load + +const InternalEVMTypeLoadFunctionName = "load" + +var InternalEVMTypeLoadFunctionType = &sema.FunctionType{ + Purity: sema.FunctionPurityView, + Parameters: []sema.Parameter{ + { + Label: "target", + TypeAnnotation: sema.NewTypeAnnotation(EVMAddressBytesType), + }, + { + Label: "slot", + TypeAnnotation: sema.NewTypeAnnotation(sema.StringType), + }, + }, + ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.ByteArrayType), +} + // InternalEVM const InternalEVMContractName = "InternalEVM" @@ -485,12 +673,24 @@ var InternalEVMContractType = func() *sema.CompositeType { InternalEVMTypeCallFunctionType, "", ), + sema.NewUnmeteredPublicFunctionMember( + ty, + InternalEVMTypeCallWithSigAndArgsFunctionName, + InternalEVMTypeCallWithSigAndArgsFunctionType, + "", + ), sema.NewUnmeteredPublicFunctionMember( ty, InternalEVMTypeDryCallFunctionName, InternalEVMTypeDryCallFunctionType, "", ), + sema.NewUnmeteredPublicFunctionMember( + ty, + InternalEVMTypeDryCallWithSigAndArgsFunctionName, + InternalEVMTypeDryCallWithSigAndArgsFunctionType, + "", + ), sema.NewUnmeteredPublicFunctionMember( ty, InternalEVMTypeDepositFunctionName, @@ -569,6 +769,24 @@ var InternalEVMContractType = func() *sema.CompositeType { InternalEVMTypeCommitBlockProposalFunctionType, "", ), + sema.NewUnmeteredPublicFunctionMember( + ty, + InternalEVMTypeStoreFunctionName, + InternalEVMTypeStoreFunctionType, + "", + ), + sema.NewUnmeteredPublicFunctionMember( + ty, + InternalEVMTypeLoadFunctionName, + InternalEVMTypeLoadFunctionType, + "", + ), + sema.NewUnmeteredPublicFunctionMember( + ty, + InternalEVMTypeRunTxAsFunctionName, + InternalEVMTypeRunTxAsFunctionType, + "", + ), }) return ty }() @@ -595,6 +813,8 @@ type InternalEVMFunctions struct { BatchRun *vm.NativeFunctionValue CreateCadenceOwnedAccount *vm.NativeFunctionValue Call *vm.NativeFunctionValue + CallWithSigAndArgs *vm.NativeFunctionValue + RunTxAs *vm.NativeFunctionValue Deposit *vm.NativeFunctionValue Withdraw *vm.NativeFunctionValue Deploy *vm.NativeFunctionValue @@ -609,7 +829,10 @@ type InternalEVMFunctions struct { GetLatestBlock *vm.NativeFunctionValue DryRun *vm.NativeFunctionValue DryCall *vm.NativeFunctionValue + DryCallWithSigAndArgs *vm.NativeFunctionValue CommitBlockProposal *vm.NativeFunctionValue + Store *vm.NativeFunctionValue + Load *vm.NativeFunctionValue } func SetupEnvironment( @@ -676,6 +899,30 @@ func SetupEnvironment( }, location, ) + env.DeclareValue( + stdlib.StandardLibraryValue{ + Name: commons.QualifiedName( + InternalEVMContractName, + InternalEVMTypeCallWithSigAndArgsFunctionName, + ), + Type: InternalEVMTypeCallWithSigAndArgsFunctionType, + Value: internalEVMFunctions.CallWithSigAndArgs, + Kind: common.DeclarationKindFunction, + }, + location, + ) + env.DeclareValue( + stdlib.StandardLibraryValue{ + Name: commons.QualifiedName( + InternalEVMContractName, + InternalEVMTypeRunTxAsFunctionName, + ), + Type: InternalEVMTypeRunTxAsFunctionType, + Value: internalEVMFunctions.RunTxAs, + Kind: common.DeclarationKindFunction, + }, + location, + ) env.DeclareValue( stdlib.StandardLibraryValue{ Name: commons.QualifiedName( @@ -844,6 +1091,18 @@ func SetupEnvironment( }, location, ) + env.DeclareValue( + stdlib.StandardLibraryValue{ + Name: commons.QualifiedName( + InternalEVMContractName, + InternalEVMTypeDryCallWithSigAndArgsFunctionName, + ), + Type: InternalEVMTypeDryCallWithSigAndArgsFunctionType, + Value: internalEVMFunctions.DryCallWithSigAndArgs, + Kind: common.DeclarationKindFunction, + }, + location, + ) env.DeclareValue( stdlib.StandardLibraryValue{ Name: commons.QualifiedName( @@ -856,6 +1115,30 @@ func SetupEnvironment( }, location, ) + env.DeclareValue( + stdlib.StandardLibraryValue{ + Name: commons.QualifiedName( + InternalEVMContractName, + InternalEVMTypeStoreFunctionName, + ), + Type: InternalEVMTypeStoreFunctionType, + Value: internalEVMFunctions.Store, + Kind: common.DeclarationKindFunction, + }, + location, + ) + env.DeclareValue( + stdlib.StandardLibraryValue{ + Name: commons.QualifiedName( + InternalEVMContractName, + InternalEVMTypeLoadFunctionName, + ), + Type: InternalEVMTypeLoadFunctionType, + Value: internalEVMFunctions.Load, + Kind: common.DeclarationKindFunction, + }, + location, + ) } func NewEVMAddressCadenceType(address common.Address) *cadence.StructType { diff --git a/fvm/evm/stdlib/contract_test.go b/fvm/evm/stdlib/contract_test.go index 8b419f4804d..9c054ef4b6f 100644 --- a/fvm/evm/stdlib/contract_test.go +++ b/fvm/evm/stdlib/contract_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" + gethABI "github.com/ethereum/go-ethereum/accounts/abi" + gethCommon "github.com/ethereum/go-ethereum/common" gethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/onflow/cadence" @@ -64,7 +66,11 @@ type testContractHandler struct { batchRun func(txs [][]byte, coinbase types.Address) []*types.ResultSummary generateResourceUUID func() uint64 dryRun func(tx []byte, from types.Address) *types.ResultSummary + dryRunWithTxData func(txData gethTypes.TxData, from types.Address) *types.ResultSummary commitBlockProposal func() + getState func(target types.Address, slot gethCommon.Hash) gethCommon.Hash + setState func(target types.Address, slot gethCommon.Hash, value gethCommon.Hash) gethCommon.Hash + runTxAs func(from types.Address, to types.Address, txData types.Data, gasLimit types.GasLimit, balance types.Balance) *types.ResultSummary } var _ types.ContractHandler = &testContractHandler{} @@ -114,6 +120,13 @@ func (t *testContractHandler) DryRun(tx []byte, from types.Address) *types.Resul return t.dryRun(tx, from) } +func (t *testContractHandler) DryRunWithTxData(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + if t.dryRunWithTxData == nil { + panic("unexpected DryRunWithTxData") + } + return t.dryRunWithTxData(txData, from) +} + func (t *testContractHandler) BatchRun(txs [][]byte, coinbase types.Address) []*types.ResultSummary { if t.batchRun == nil { panic("unexpected BatchRun") @@ -135,6 +148,40 @@ func (t *testContractHandler) CommitBlockProposal() { t.commitBlockProposal() } +func (t *testContractHandler) SetState( + target types.Address, + slot gethCommon.Hash, + value gethCommon.Hash, +) gethCommon.Hash { + if t.setState == nil { + panic("unexpected SetState") + } + return t.setState(target, slot, value) +} + +func (t *testContractHandler) GetState( + target types.Address, + slot gethCommon.Hash, +) gethCommon.Hash { + if t.getState == nil { + panic("unexpected GetState") + } + return t.getState(target, slot) +} + +func (t *testContractHandler) RunTxAs( + from types.Address, + to types.Address, + txData types.Data, + gasLimit types.GasLimit, + balance types.Balance, +) *types.ResultSummary { + if t.runTxAs == nil { + panic("unexpected RunTxAs") + } + return t.runTxAs(from, to, txData, gasLimit, balance) +} + type testFlowAccount struct { address types.Address balance func() types.Balance @@ -305,7 +352,12 @@ func deployContracts( }, { name: stdlib.ContractName, - code: stdlib.ContractCode(contractsAddress, contractsAddress, contractsAddress), + code: stdlib.ContractCode( + contractsAddress, + contractsAddress, + contractsAddress, + true, + ), }, } @@ -1022,7 +1074,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let bytes: EVM.EVMBytes = EVM.EVMBytes(value: [5, 10, 15, 20, 25]) let encodedData = EVM.encodeABI([bytes]) let types = [Type()] @@ -1031,8 +1083,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { assert(values.length == 1) let evmBytes = values[0] as! EVM.EVMBytes assert(evmBytes.value == [5, 10, 15, 20, 25]) - - return true } `) @@ -1041,7 +1091,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { })) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1056,11 +1106,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, - cadence.Bool(true), - result, - ) - assert.Equal(t, uint64(96), gauge.TotalComputationUsed()) }) @@ -1069,7 +1114,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let bytes: EVM.EVMBytes = EVM.EVMBytes(value: [5, 10, 15, 20, 25]) let bytesArray: [EVM.EVMBytes] = [bytes] let encodedData = EVM.encodeABI([bytesArray]) @@ -1079,8 +1124,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { assert(values.length == 1) let evmBytes = values[0] as! [EVM.EVMBytes] assert(evmBytes[0].value == [5, 10, 15, 20, 25]) - - return true } `) @@ -1089,7 +1132,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { })) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1104,11 +1147,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, - cadence.Bool(true), - result, - ) - assert.Equal(t, uint64(160), gauge.TotalComputationUsed()) }) @@ -1117,7 +1155,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let bytes: EVM.EVMBytes4 = EVM.EVMBytes4(value: [5, 10, 15, 20]) let encodedData = EVM.encodeABI([bytes]) let types = [Type()] @@ -1126,8 +1164,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { assert(values.length == 1) let evmBytes = values[0] as! EVM.EVMBytes4 assert(evmBytes.value == [5, 10, 15, 20]) - - return true } `) gauge := meter.NewMeter(meter.DefaultParameters().WithComputationWeights(meter.ExecutionEffortWeights{ @@ -1135,7 +1171,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { })) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1150,11 +1186,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, - cadence.Bool(true), - result, - ) - assert.Equal(t, uint64(32), gauge.TotalComputationUsed()) }) @@ -1163,7 +1194,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let bytes: EVM.EVMBytes4 = EVM.EVMBytes4(value: [5, 10, 15, 20]) let bytesArray: [EVM.EVMBytes4] = [bytes] let encodedData = EVM.encodeABI([bytesArray]) @@ -1173,8 +1204,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { assert(values.length == 1) let evmBytes = values[0] as! [EVM.EVMBytes4] assert(evmBytes[0].value == [5, 10, 15, 20]) - - return true } `) gauge := meter.NewMeter(meter.DefaultParameters().WithComputationWeights(meter.ExecutionEffortWeights{ @@ -1182,7 +1211,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { })) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1197,11 +1226,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, - cadence.Bool(true), - result, - ) - assert.Equal(t, uint64(96), gauge.TotalComputationUsed()) }) @@ -1210,7 +1234,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let bytes: EVM.EVMBytes32 = EVM.EVMBytes32( value: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, @@ -1229,8 +1253,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]) - - return true } `) gauge := meter.NewMeter(meter.DefaultParameters().WithComputationWeights(meter.ExecutionEffortWeights{ @@ -1238,7 +1260,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { })) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1253,11 +1275,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, - cadence.Bool(true), - result, - ) - assert.Equal(t, uint64(32), gauge.TotalComputationUsed()) }) @@ -1266,7 +1283,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let bytes: EVM.EVMBytes32 = EVM.EVMBytes32( value: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, @@ -1286,8 +1303,6 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]) - - return true } `) gauge := meter.NewMeter(meter.DefaultParameters().WithComputationWeights(meter.ExecutionEffortWeights{ @@ -1295,7 +1310,7 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { })) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1310,12 +1325,135 @@ func TestEVMEncodeABIBytesRoundtrip(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, - cadence.Bool(true), - result, + assert.Equal(t, uint64(96), gauge.TotalComputationUsed()) + }) + + t.Run("ABI encode struct into tuple Solidity type", func(t *testing.T) { + script := []byte(` + import EVM from 0x1 + + access(all) + struct S { + access(all) let x: UInt8 + access(all) let y: Int16 + + init(x: UInt8, y: Int16) { + self.x = x + self.y = y + } + + access(all) fun toString(): String { + return "S(x: \(self.x), y: \(self.y))" + } + } + + access(all) + fun main() { + let s = S(x: 4, y: 2) + let encodedData = EVM.encodeABI([s]) + assert(encodedData == [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x4, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2 + ]) + + let values = EVM.decodeABI(types: [Type()], data: encodedData) + assert(values.length == 1) + let s2 = values[0] as! S + assert(s2.x == 4) + assert(s2.y == 2) + } + `) + + gauge := meter.NewMeter(meter.DefaultParameters().WithComputationWeights(meter.ExecutionEffortWeights{ + environment.ComputationKindEVMEncodeABI: 1 << meter.MeterExecutionInternalPrecisionBytes, + })) + + // Run script + _, err := rt.ExecuteScript( + runtime.Script{ + Source: script, + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + MemoryGauge: gauge, + ComputationGauge: gauge, + UseVM: cadence_vm.DefaultEnabled, + }, ) + require.NoError(t, err) - assert.Equal(t, uint64(96), gauge.TotalComputationUsed()) + assert.Equal(t, uint64(64), gauge.TotalComputationUsed()) + }) + + t.Run("ABI encode array of structs into tuple Solidity type", func(t *testing.T) { + script := []byte(` + import EVM from 0x1 + + access(all) + struct S { + access(all) let x: UInt8 + access(all) let y: Int16 + + init(x: UInt8, y: Int16) { + self.x = x + self.y = y + } + + access(all) fun toString(): String { + return "S(x: \(self.x), y: \(self.y))" + } + } + + access(all) + fun main() { + let s1 = S(x: 4, y: 2) + let s2 = S(x: 5, y: 9) + let structArray = [s1, s2] + let encodedData = EVM.encodeABI([structArray]) + assert(encodedData == [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x20, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x4, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x5, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x9 + ], message: String.encodeHex(encodedData)) + + let values = EVM.decodeABI(types: [Type<[S]>()], data: encodedData) + assert(values.length == 1) + let decodedStructArray = values[0] as! [S] + assert(decodedStructArray.length == 2) + + assert(decodedStructArray[0].x == 4) + assert(decodedStructArray[0].y == 2) + assert(decodedStructArray[1].x == 5) + assert(decodedStructArray[1].y == 9) + } + `) + + gauge := meter.NewMeter(meter.DefaultParameters().WithComputationWeights(meter.ExecutionEffortWeights{ + environment.ComputationKindEVMEncodeABI: 1 << meter.MeterExecutionInternalPrecisionBytes, + })) + + // Run script + _, err := rt.ExecuteScript( + runtime.Script{ + Source: script, + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + MemoryGauge: gauge, + ComputationGauge: gauge, + UseVM: cadence_vm.DefaultEnabled, + }, + ) + require.NoError(t, err) + + assert.Equal(t, uint64(192), gauge.TotalComputationUsed()) }) } @@ -1634,7 +1772,7 @@ func TestEVMDecodeABI(t *testing.T) { import EVM from 0x1 access(all) - fun main(data: [UInt8]): Bool { + fun main(data: [UInt8]) { let types = [Type(), Type(), Type()] let values = EVM.decodeABI(types: types, data: data) @@ -1642,8 +1780,6 @@ func TestEVMDecodeABI(t *testing.T) { assert((values[0] as! String) == "John Doe") assert((values[1] as! UInt64) == UInt64(33)) assert((values[2] as! Bool) == false) - - return true } `) @@ -1714,7 +1850,7 @@ func TestEVMDecodeABI(t *testing.T) { cdcBytes, ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, Arguments: EncodeArgs([]cadence.Value{ @@ -1732,7 +1868,6 @@ func TestEVMDecodeABI(t *testing.T) { ) require.NoError(t, err) - assert.Equal(t, cadence.NewBool(true), result) assert.Equal(t, uint64(len(cdcBytes)), gauge.TotalComputationUsed()) } @@ -1910,7 +2045,7 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { // Check UInt/Int encode/decode let amount: UInt256 = 18446744073709551615 let minBalance: Int256 = -18446744073709551615 @@ -1925,14 +2060,12 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { ) assert((values[0] as! UInt) == UInt(amount)) assert((values[1] as! Int) == Int(minBalance)) - - return true } `) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1944,8 +2077,6 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { }, ) require.NoError(t, err) - - assert.Equal(t, cadence.Bool(true), result) }) t.Run("with values at the boundaries", func(t *testing.T) { @@ -1954,11 +2085,11 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { // Check UInt*/Int* encode/decode let data = EVM.encodeABIWithSignature( "withdraw(uint,int,uint,int)", - [UInt(UInt256.max), Int(Int256.max),UInt(UInt256.min), Int(Int256.min)] + [UInt(UInt256.max), Int(Int256.max), UInt(UInt256.min), Int(Int256.min)] ) let values = EVM.decodeABIWithSignature( "withdraw(uint,int,uint,int)", @@ -1969,14 +2100,12 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { assert((values[1] as! Int) == Int(Int256.max)) assert((values[2] as! UInt) == UInt(UInt256.min)) assert((values[3] as! Int) == Int(Int256.min)) - - return true } `) // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -1988,8 +2117,6 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { }, ) require.NoError(t, err) - - assert.Equal(t, cadence.Bool(true), result) }) t.Run("with UInt values outside the boundaries", func(t *testing.T) { @@ -1998,13 +2125,11 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABIWithSignature( "withdraw(uint)", [UInt(UInt256.max)+10] ) - - return true } `) @@ -2036,13 +2161,11 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABIWithSignature( "withdraw(int)", [Int(Int256.max)+10] ) - - return true } `) @@ -2074,13 +2197,11 @@ func TestEVMEncodeDecodeABIRoundtripForUintIntTypes(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABIWithSignature( "withdraw(int)", [Int(Int256.min)-10] ) - - return true } `) @@ -2124,7 +2245,7 @@ func TestEVMEncodeDecodeABIRoundtrip(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { // Check EVM.EVMAddress encode/decode let address = EVM.EVMAddress( bytes: "7A58c0Be72BE218B41C608b7Fe7C5bB630736C71" @@ -2318,8 +2439,6 @@ func TestEVMEncodeDecodeABIRoundtrip(t *testing.T) { values = EVM.decodeABI(types: [Type<[[String]]>()], data: data) assert(values.length == 1) assert((values[0] as! [[String]]) == [["Foo", "Bar"], ["Baz", "Qux"]]) - - return true } `) @@ -2365,7 +2484,7 @@ func TestEVMEncodeDecodeABIRoundtrip(t *testing.T) { // Run script - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, }, @@ -2377,11 +2496,6 @@ func TestEVMEncodeDecodeABIRoundtrip(t *testing.T) { }, ) require.NoError(t, err) - - assert.Equal(t, - cadence.Bool(true), - result, - ) } func TestEVMEncodeDecodeABIErrors(t *testing.T) { @@ -2447,11 +2561,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let address: Address = 0x045a1763c93006ca - let data = EVM.encodeABI([address]) - - return true + EVM.encodeABI([address]) } `) @@ -2533,10 +2645,8 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { - let data = EVM.encodeABI([0.2]) - - return true + fun main() { + EVM.encodeABI([0.2]) } `) @@ -2618,11 +2728,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let dict: {Int: Bool} = {0: false, 1: true} - let data = EVM.encodeABI([dict]) - - return true + EVM.encodeABI([dict]) } `) @@ -2704,11 +2812,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let chars: [Character] = ["a", "b", "c"] - let data = EVM.encodeABI([chars]) - - return true + EVM.encodeABI([chars]) } `) @@ -2789,22 +2895,17 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { script := []byte(` import EVM from 0x1 - access(all) struct Token { - access(all) let id: Int - access(all) var balance: UInt + access(all) struct Fun { + access(all) let f: fun(): Void - init(id: Int, balance: UInt) { - self.id = id - self.balance = balance - } + init() { + self.f = fun(): Void {} + } } access(all) - fun main(): Bool { - let token = Token(id: 9, balance: 150) - let data = EVM.encodeABI([token]) - - return true + fun main() { + EVM.encodeABI([Fun()]) } `) @@ -2823,7 +2924,7 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { assert.ErrorContains( t, err, - "failed to ABI encode value of type s.0100000000000000000000000000000000000000000000000000000000000000.Token", + "failed to ABI encode value of type fun(): Void", ) }) @@ -2886,11 +2987,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABI(["Peter"]) - let values = EVM.decodeABI(types: [Type()], data: data) - - return true + EVM.decodeABI(types: [Type()], data: data) } `) @@ -2972,11 +3071,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABI(["Peter"]) - let values = EVM.decodeABI(types: [Type(), Type()], data: data) - - return true + EVM.decodeABI(types: [Type(), Type()], data: data) } `) @@ -3058,11 +3155,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABI(["Peter"]) - let values = EVM.decodeABI(types: [Type()], data: data) - - return true + EVM.decodeABI(types: [Type()], data: data) } `) @@ -3144,11 +3239,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABI(["Peter"]) - let values = EVM.decodeABI(types: [Type<{Int: Bool}>()], data: data) - - return true + EVM.decodeABI(types: [Type<{Int: Bool}>()], data: data) } `) @@ -3230,11 +3323,9 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { import EVM from 0x1 access(all) - fun main(): Bool { + fun main() { let data = EVM.encodeABI(["Peter"]) - let values = EVM.decodeABI(types: [Type<[Character]>()], data: data) - - return true + EVM.decodeABI(types: [Type<[Character]>()], data: data) } `) @@ -3315,22 +3406,24 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { script := []byte(` import EVM from 0x1 - access(all) struct Token { - access(all) let id: Int - access(all) var balance: UInt + access(all) struct S { + access(all) let x: UInt8 + init() { + self.x = 42 + } + } - init(id: Int, balance: UInt) { - self.id = id - self.balance = balance + access(all) resource R { + access(all) let x: UInt8 + init() { + self.x = 42 } } access(all) - fun main(): Bool { - let data = EVM.encodeABI(["Peter"]) - let values = EVM.decodeABI(types: [Type()], data: data) - - return true + fun main() { + let data = EVM.encodeABI([S()]) + EVM.decodeABI(types: [Type<@R>()], data: data) } `) @@ -3349,7 +3442,7 @@ func TestEVMEncodeDecodeABIErrors(t *testing.T) { assert.ErrorContains( t, err, - "failed to ABI decode data with type s.0100000000000000000000000000000000000000000000000000000000000000.Token", + "failed to ABI decode data with type s.0100000000000000000000000000000000000000000000000000000000000000.R", ) }) } @@ -3493,7 +3586,7 @@ func TestEVMDecodeABIWithSignature(t *testing.T) { import EVM from 0x1 access(all) - fun main(data: [UInt8]): Bool { + fun main(data: [UInt8]) { let values = EVM.decodeABIWithSignature( "withdraw(address,uint256)", types: [Type(), Type()], @@ -3511,8 +3604,6 @@ func TestEVMDecodeABIWithSignature(t *testing.T) { assert(values.length == 2) assert((values[0] as! EVM.EVMAddress).bytes == address.bytes) assert((values[1] as! UInt256) == UInt256(250)) - - return true } `) @@ -3584,7 +3675,7 @@ func TestEVMDecodeABIWithSignature(t *testing.T) { cdcBytes, ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, Arguments: EncodeArgs([]cadence.Value{ @@ -3601,8 +3692,6 @@ func TestEVMDecodeABIWithSignature(t *testing.T) { }, ) require.NoError(t, err) - - assert.Equal(t, cadence.NewBool(true), result) // The method ID is a byte array of length 4 assert.Equal(t, uint64(len(cdcBytes)), gauge.TotalComputationUsed()+4) } @@ -3624,7 +3713,7 @@ func TestEVMDecodeABIWithSignatureMismatch(t *testing.T) { import EVM from 0x1 access(all) - fun main(data: [UInt8]): Bool { + fun main(data: [UInt8]) { // The data was encoded for the function "withdraw(address,uint256)", // but we pass a different function signature let values = EVM.decodeABIWithSignature( @@ -3632,8 +3721,6 @@ func TestEVMDecodeABIWithSignatureMismatch(t *testing.T) { types: [Type(), Type()], data: data ) - - return true } `) @@ -3719,7 +3806,7 @@ func TestEVMDecodeABIWithSignatureMismatch(t *testing.T) { assert.ErrorContains(t, err, "EVM.decodeABIWithSignature(): Cannot decode! The signature does not match the provided data.") } -func TestEVMAddressConstructionAndReturn(t *testing.T) { +func TestEVMDecodeABIWithInsufficientData(t *testing.T) { t.Parallel() @@ -3727,7 +3814,7 @@ func TestEVMAddressConstructionAndReturn(t *testing.T) { contractsAddress := flow.BytesToAddress([]byte{0x1}) - deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + transactionEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) rt := runtime.NewRuntime(runtime.Config{}) @@ -3736,10 +3823,16 @@ func TestEVMAddressConstructionAndReturn(t *testing.T) { import EVM from 0x1 access(all) - fun main(_ bytes: [UInt8; 20]): EVM.EVMAddress { - return EVM.EVMAddress(bytes: bytes) + fun main(data: [UInt8]) { + // We are passing less than 4 bytes, which is the minimum bytes needed + // for the function selector. + let values = EVM.decodeABIWithSignature( + "deposit(uint256, address)", + types: [Type(), Type()], + data: data + ) } - `) + `) accountCodes := map[common.Location][]byte{} var events []cadence.Event @@ -3765,21 +3858,15 @@ func TestEVMAddressConstructionAndReturn(t *testing.T) { OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { return json.Decode(nil, b) }, + OnHash: func( + data []byte, + tag string, + hashAlgorithm runtime.HashAlgorithm, + ) ([]byte, error) { + return crypto.Keccak256(data), nil + }, } - addressBytesArray := cadence.NewArray([]cadence.Value{ - cadence.UInt8(1), cadence.UInt8(1), - cadence.UInt8(2), cadence.UInt8(2), - cadence.UInt8(3), cadence.UInt8(3), - cadence.UInt8(4), cadence.UInt8(4), - cadence.UInt8(5), cadence.UInt8(5), - cadence.UInt8(6), cadence.UInt8(6), - cadence.UInt8(7), cadence.UInt8(7), - cadence.UInt8(8), cadence.UInt8(8), - cadence.UInt8(9), cadence.UInt8(9), - cadence.UInt8(10), cadence.UInt8(10), - }).WithType(stdlib.EVMAddressBytesCadenceType) - nextTransactionLocation := NewTransactionLocationGenerator() nextScriptLocation := NewScriptLocationGenerator() @@ -3790,17 +3877,25 @@ func TestEVMAddressConstructionAndReturn(t *testing.T) { rt, contractsAddress, runtimeInterface, - deploymentEnvironment, + transactionEnvironment, nextTransactionLocation, ) // Run script + abiBytes := []byte{0xf3, 0xfe, 0xa3} + cdcBytes := make([]cadence.Value, 0) + for _, bt := range abiBytes { + cdcBytes = append(cdcBytes, cadence.UInt8(bt)) + } + encodedABI := cadence.NewArray( + cdcBytes, + ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) - result, err := rt.ExecuteScript( + _, err := rt.ExecuteScript( runtime.Script{ Source: script, Arguments: EncodeArgs([]cadence.Value{ - addressBytesArray, + encodedABI, }), }, runtime.Context{ @@ -3810,19 +3905,11 @@ func TestEVMAddressConstructionAndReturn(t *testing.T) { UseVM: cadence_vm.DefaultEnabled, }, ) - require.NoError(t, err) - - evmAddressCadenceType := stdlib.NewEVMAddressCadenceType(common.Address(contractsAddress)) - - assert.Equal(t, - cadence.NewStruct([]cadence.Value{ - addressBytesArray, - }).WithType(evmAddressCadenceType), - result, - ) + require.Error(t, err) + assert.ErrorContains(t, err, "EVM.decodeABIWithSignature(): Cannot decode! The provided data does not contain a signature.") } -func TestEVMAddressSerializationAndDeserialization(t *testing.T) { +func TestEVMAddressConstructionAndReturn(t *testing.T) { t.Parallel() @@ -3835,7 +3922,7 @@ func TestEVMAddressSerializationAndDeserialization(t *testing.T) { rt := runtime.NewRuntime(runtime.Config{}) - addressFromBytesScript := []byte(` + script := []byte(` import EVM from 0x1 access(all) @@ -3870,23 +3957,17 @@ func TestEVMAddressSerializationAndDeserialization(t *testing.T) { }, } - sourceBytes := []byte{ - 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, - 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, - } - - // construct the address as a cadence value from sourceBytes addressBytesArray := cadence.NewArray([]cadence.Value{ - cadence.UInt8(sourceBytes[0]), cadence.UInt8(sourceBytes[1]), - cadence.UInt8(sourceBytes[2]), cadence.UInt8(sourceBytes[3]), - cadence.UInt8(sourceBytes[4]), cadence.UInt8(sourceBytes[5]), - cadence.UInt8(sourceBytes[6]), cadence.UInt8(sourceBytes[7]), - cadence.UInt8(sourceBytes[8]), cadence.UInt8(sourceBytes[9]), - cadence.UInt8(sourceBytes[10]), cadence.UInt8(sourceBytes[11]), - cadence.UInt8(sourceBytes[12]), cadence.UInt8(sourceBytes[13]), - cadence.UInt8(sourceBytes[14]), cadence.UInt8(sourceBytes[15]), - cadence.UInt8(sourceBytes[16]), cadence.UInt8(sourceBytes[17]), - cadence.UInt8(sourceBytes[18]), cadence.UInt8(sourceBytes[19]), + cadence.UInt8(1), cadence.UInt8(1), + cadence.UInt8(2), cadence.UInt8(2), + cadence.UInt8(3), cadence.UInt8(3), + cadence.UInt8(4), cadence.UInt8(4), + cadence.UInt8(5), cadence.UInt8(5), + cadence.UInt8(6), cadence.UInt8(6), + cadence.UInt8(7), cadence.UInt8(7), + cadence.UInt8(8), cadence.UInt8(8), + cadence.UInt8(9), cadence.UInt8(9), + cadence.UInt8(10), cadence.UInt8(10), }).WithType(stdlib.EVMAddressBytesCadenceType) nextTransactionLocation := NewTransactionLocationGenerator() @@ -3905,9 +3986,118 @@ func TestEVMAddressSerializationAndDeserialization(t *testing.T) { // Run script - constructAddrResult, err := rt.ExecuteScript( + result, err := rt.ExecuteScript( runtime.Script{ - Source: addressFromBytesScript, + Source: script, + Arguments: EncodeArgs([]cadence.Value{ + addressBytesArray, + }), + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + UseVM: cadence_vm.DefaultEnabled, + }, + ) + require.NoError(t, err) + + evmAddressCadenceType := stdlib.NewEVMAddressCadenceType(common.Address(contractsAddress)) + + assert.Equal(t, + cadence.NewStruct([]cadence.Value{ + addressBytesArray, + }).WithType(evmAddressCadenceType), + result, + ) +} + +func TestEVMAddressSerializationAndDeserialization(t *testing.T) { + + t.Parallel() + + handler := &testContractHandler{} + + contractsAddress := flow.BytesToAddress([]byte{0x1}) + + deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + + rt := runtime.NewRuntime(runtime.Config{}) + + addressFromBytesScript := []byte(` + import EVM from 0x1 + + access(all) + fun main(_ bytes: [UInt8; 20]): EVM.EVMAddress { + return EVM.EVMAddress(bytes: bytes) + } + `) + + accountCodes := map[common.Location][]byte{} + var events []cadence.Event + + runtimeInterface := &TestRuntimeInterface{ + Storage: NewTestLedger(nil, nil), + OnGetSigningAccounts: func() ([]runtime.Address, error) { + return []runtime.Address{runtime.Address(contractsAddress)}, nil + }, + OnResolveLocation: newLocationResolver(contractsAddress), + OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { + accountCodes[location] = code + return nil + }, + OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { + code = accountCodes[location] + return code, nil + }, + OnEmitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { + return json.Decode(nil, b) + }, + } + + sourceBytes := []byte{ + 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, + 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, + } + + // construct the address as a cadence value from sourceBytes + addressBytesArray := cadence.NewArray([]cadence.Value{ + cadence.UInt8(sourceBytes[0]), cadence.UInt8(sourceBytes[1]), + cadence.UInt8(sourceBytes[2]), cadence.UInt8(sourceBytes[3]), + cadence.UInt8(sourceBytes[4]), cadence.UInt8(sourceBytes[5]), + cadence.UInt8(sourceBytes[6]), cadence.UInt8(sourceBytes[7]), + cadence.UInt8(sourceBytes[8]), cadence.UInt8(sourceBytes[9]), + cadence.UInt8(sourceBytes[10]), cadence.UInt8(sourceBytes[11]), + cadence.UInt8(sourceBytes[12]), cadence.UInt8(sourceBytes[13]), + cadence.UInt8(sourceBytes[14]), cadence.UInt8(sourceBytes[15]), + cadence.UInt8(sourceBytes[16]), cadence.UInt8(sourceBytes[17]), + cadence.UInt8(sourceBytes[18]), cadence.UInt8(sourceBytes[19]), + }).WithType(stdlib.EVMAddressBytesCadenceType) + + nextTransactionLocation := NewTransactionLocationGenerator() + nextScriptLocation := NewScriptLocationGenerator() + + // Deploy contracts + + deployContracts( + t, + rt, + contractsAddress, + runtimeInterface, + deploymentEnvironment, + nextTransactionLocation, + ) + + // Run script + + constructAddrResult, err := rt.ExecuteScript( + runtime.Script{ + Source: addressFromBytesScript, Arguments: EncodeArgs([]cadence.Value{ addressBytesArray, }), @@ -4356,12 +4546,9 @@ func TestEVMDryCall(t *testing.T) { contractsAddress := flow.BytesToAddress([]byte{0x1}) handler := &testContractHandler{ evmContractAddress: common.Address(contractsAddress), - dryRun: func(tx []byte, from types.Address) *types.ResultSummary { + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { dryCallCalled = true - gethTx := &gethTypes.Transaction{} - if err := gethTx.UnmarshalBinary(tx); err != nil { - require.Fail(t, err.Error()) - } + gethTx := gethTypes.NewTx(txData) require.NotNil(t, gethTx.To()) @@ -4466,101 +4653,564 @@ func TestEVMDryCall(t *testing.T) { assert.True(t, dryCallCalled) } -func TestEVMBatchRun(t *testing.T) { +func TestEVMDryCallWithSigAndArgs(t *testing.T) { t.Parallel() - evmTxs := cadence.NewArray([]cadence.Value{ - cadence.NewArray([]cadence.Value{cadence.UInt8(1), cadence.UInt8(2), cadence.UInt8(3)}), - cadence.NewArray([]cadence.Value{cadence.UInt8(4), cadence.UInt8(5), cadence.UInt8(6)}), - cadence.NewArray([]cadence.Value{cadence.UInt8(7), cadence.UInt8(8), cadence.UInt8(9)}), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewVariableSizedArrayType(cadence.UInt8Type))) + contractsAddress := flow.BytesToAddress([]byte{0x1}) - coinbase := cadence.NewArray([]cadence.Value{ - cadence.UInt8(1), cadence.UInt8(1), - cadence.UInt8(2), cadence.UInt8(2), - cadence.UInt8(3), cadence.UInt8(3), - cadence.UInt8(4), cadence.UInt8(4), - cadence.UInt8(5), cadence.UInt8(5), - cadence.UInt8(6), cadence.UInt8(6), - cadence.UInt8(7), cadence.UInt8(7), - cadence.UInt8(8), cadence.UInt8(8), - cadence.UInt8(9), cadence.UInt8(9), - cadence.UInt8(10), cadence.UInt8(10), - }).WithType(stdlib.EVMAddressBytesCadenceType) + executeScript := func(handler types.ContractHandler, script []byte) (cadence.Value, error) { - runCalled := false + rt := runtime.NewRuntime(runtime.Config{}) - contractsAddress := flow.BytesToAddress([]byte{0x1}) - handler := &testContractHandler{ - evmContractAddress: common.Address(contractsAddress), - batchRun: func(txs [][]byte, coinbase types.Address) []*types.ResultSummary { - runCalled = true + accountCodes := map[common.Location][]byte{} + var events []cadence.Event - assert.EqualValues(t, [][]byte{ - {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, - }, txs) - assert.Equal(t, - types.Address{ - 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, - }, - coinbase, - ) + runtimeInterface := &TestRuntimeInterface{ + Storage: NewTestLedger(nil, nil), + OnGetSigningAccounts: func() ([]runtime.Address, error) { + return []runtime.Address{runtime.Address(contractsAddress)}, nil + }, + OnResolveLocation: newLocationResolver(contractsAddress), + OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { + accountCodes[location] = code + return nil + }, + OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { + code = accountCodes[location] + return code, nil + }, + OnEmitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { + return json.Decode(nil, b) + }, + } - results := make([]*types.ResultSummary, 3) - for i := range results { - results[i] = &types.ResultSummary{ - Status: types.StatusSuccessful, - } - } + nextTransactionLocation := NewTransactionLocationGenerator() + nextScriptLocation := NewScriptLocationGenerator() - return results - }, + transactionEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + + // Deploy contracts + + deployContracts( + t, + rt, + contractsAddress, + runtimeInterface, + transactionEnvironment, + nextTransactionLocation, + ) + + // Run script + + return rt.ExecuteScript( + runtime.Script{ + Source: script, + Arguments: nil, + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + UseVM: cadence_vm.DefaultEnabled, + }, + ) } - deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) - scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + t.Run("dryCall includes result types, tx fails", func(t *testing.T) { + dryCallCalled := false - rt := runtime.NewRuntime(runtime.Config{}) + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true - script := []byte(` + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + + expectedData := []byte{0xcc, 0x43, 0x5b, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(150), gethTx.Value()) + + return &types.ResultSummary{ + Status: types.StatusFailed, + ReturnedData: types.Data([]byte{0, 1, 2}), + } + }, + } + + script := []byte(` import EVM from 0x1 access(all) - fun main(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]): [EVM.Result] { - let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) - return EVM.batchRun(txs: txs, coinbase: coinbase) + fun main(): EVM.ResultDecoded { + return EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10]), + to: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + signature: "isValidAsset(address)", + args: [EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20])], + gasLimit: 33000, + value: 150, + resultTypes: [Type()], + ) } `) + val, err := executeScript(handler, script) + require.NoError(t, err) + assert.True(t, dryCallCalled) - accountCodes := map[common.Location][]byte{} - var events []cadence.Event + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusFailed, res.Status) + assert.True(t, len(res.Results) == 3) + assert.Equal(t, cadence.UInt8(0), res.Results[0]) + assert.Equal(t, cadence.UInt8(1), res.Results[1]) + assert.Equal(t, cadence.UInt8(2), res.Results[2]) + }) - runtimeInterface := &TestRuntimeInterface{ - Storage: NewTestLedger(nil, nil), - OnGetSigningAccounts: func() ([]runtime.Address, error) { - return []runtime.Address{runtime.Address(contractsAddress)}, nil - }, - OnResolveLocation: newLocationResolver(contractsAddress), - OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { - accountCodes[location] = code - return nil - }, - OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { - code = accountCodes[location] - return code, nil - }, - OnEmitEvent: func(event cadence.Event) error { - events = append(events, event) - return nil - }, - OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { - return json.Decode(nil, b) - }, - } + t.Run("dryCall includes result types, tx result data is empty", func(t *testing.T) { + dryCallCalled := false - nextTransactionLocation := NewTransactionLocationGenerator() - nextScriptLocation := NewScriptLocationGenerator() + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{0xcc, 0x43, 0x5b, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(150), gethTx.Value()) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + return EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10]), + to: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + signature: "isValidAsset(address)", + args: [EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20])], + gasLimit: 33000, + value: 150, + resultTypes: [Type()], + ) + } + `) + + _, err := executeScript(handler, script) + require.ErrorContains(t, err, "failed to ABI decode data") + assert.True(t, dryCallCalled) + }) + + t.Run("dryCall includes result types, tx result data doesn't match result types", func(t *testing.T) { + dryCallCalled := false + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{0xcc, 0x43, 0x5b, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(150), gethTx.Value()) + + // Result data is uint64(42) + + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.UintTy, Size: 64}}, + } + + encodedValues, err := arguments.Pack(uint64(42)) + assert.NoError(t, err) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + return EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10]), + to: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + signature: "isValidAsset(address)", + args: [EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20])], + gasLimit: 33000, + value: 150, + resultTypes: [Type()], + ) + } + `) + + _, err := executeScript(handler, script) + require.ErrorContains(t, err, "failed to ABI decode data") + assert.True(t, dryCallCalled) + }) + + t.Run("dryCall includes result types, tx result data matches provided result types", func(t *testing.T) { + dryCallCalled := false + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{0xcc, 0x43, 0x5b, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(150), gethTx.Value()) + + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.BoolTy}}, + } + + encodedValues, err := arguments.Pack(true) + assert.NoError(t, err) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + return EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10]), + to: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + signature: "isValidAsset(address)", + args: [EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20])], + gasLimit: 33000, + value: 150, + resultTypes: [Type()], + ) + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + assert.True(t, dryCallCalled) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusSuccessful, res.Status) + assert.True(t, len(res.Results) == 1) + assert.Equal(t, cadence.Bool(true), res.Results[0]) + }) + + t.Run("dryCall doesn't result types, tx fails", func(t *testing.T) { + dryCallCalled := false + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + + expectedData := []byte{0xcc, 0x43, 0x5b, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(150), gethTx.Value()) + + return &types.ResultSummary{ + Status: types.StatusFailed, + ReturnedData: types.Data([]byte{0, 1, 2}), + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + return EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10]), + to: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + signature: "isValidAsset(address)", + args: [EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20])], + gasLimit: 33000, + value: 150, + resultTypes: nil, + ) + } + `) + val, err := executeScript(handler, script) + require.NoError(t, err) + assert.True(t, dryCallCalled) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusFailed, res.Status) + assert.True(t, len(res.Results) == 3) + assert.Equal(t, cadence.UInt8(0), res.Results[0]) + assert.Equal(t, cadence.UInt8(1), res.Results[1]) + assert.Equal(t, cadence.UInt8(2), res.Results[2]) + }) + + t.Run("dryCall doesn't include result types, tx is successful", func(t *testing.T) { + dryCallCalled := false + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{0xcc, 0x43, 0x5b, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(150), gethTx.Value()) + + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.BoolTy}}, + } + + encodedValues, err := arguments.Pack(true) + assert.NoError(t, err) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + return EVM.dryCallWithSigAndArgs( + from: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10]), + to: EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15]), + signature: "isValidAsset(address)", + args: [EVM.EVMAddress(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20])], + gasLimit: 33000, + value: 150, + resultTypes: nil, + ) + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + assert.True(t, dryCallCalled) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusSuccessful, res.Status) + assert.True(t, len(res.Results) == 32) + for i, v := range res.Results { + if i == len(res.Results)-1 { + assert.Equal(t, cadence.UInt8(1), v) + } else { + assert.Equal(t, cadence.UInt8(0), v) + } + } + }) +} + +func TestEVMBatchRun(t *testing.T) { + + t.Parallel() + + evmTxs := cadence.NewArray([]cadence.Value{ + cadence.NewArray([]cadence.Value{cadence.UInt8(1), cadence.UInt8(2), cadence.UInt8(3)}), + cadence.NewArray([]cadence.Value{cadence.UInt8(4), cadence.UInt8(5), cadence.UInt8(6)}), + cadence.NewArray([]cadence.Value{cadence.UInt8(7), cadence.UInt8(8), cadence.UInt8(9)}), + }).WithType(cadence.NewVariableSizedArrayType(cadence.NewVariableSizedArrayType(cadence.UInt8Type))) + + coinbase := cadence.NewArray([]cadence.Value{ + cadence.UInt8(1), cadence.UInt8(1), + cadence.UInt8(2), cadence.UInt8(2), + cadence.UInt8(3), cadence.UInt8(3), + cadence.UInt8(4), cadence.UInt8(4), + cadence.UInt8(5), cadence.UInt8(5), + cadence.UInt8(6), cadence.UInt8(6), + cadence.UInt8(7), cadence.UInt8(7), + cadence.UInt8(8), cadence.UInt8(8), + cadence.UInt8(9), cadence.UInt8(9), + cadence.UInt8(10), cadence.UInt8(10), + }).WithType(stdlib.EVMAddressBytesCadenceType) + + runCalled := false + + contractsAddress := flow.BytesToAddress([]byte{0x1}) + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + batchRun: func(txs [][]byte, coinbase types.Address) []*types.ResultSummary { + runCalled = true + + assert.EqualValues(t, + [][]byte{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + }, + txs, + ) + assert.Equal(t, + types.Address{ + 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, + }, + coinbase, + ) + + results := make([]*types.ResultSummary, 3) + for i := range results { + results[i] = &types.ResultSummary{ + Status: types.StatusSuccessful, + } + } + + return results + }, + } + + deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + + rt := runtime.NewRuntime(runtime.Config{}) + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(txs: [[UInt8]], coinbaseBytes: [UInt8; 20]): [EVM.Result] { + let coinbase = EVM.EVMAddress(bytes: coinbaseBytes) + return EVM.batchRun(txs: txs, coinbase: coinbase) + } + `) + + accountCodes := map[common.Location][]byte{} + var events []cadence.Event + + runtimeInterface := &TestRuntimeInterface{ + Storage: NewTestLedger(nil, nil), + OnGetSigningAccounts: func() ([]runtime.Address, error) { + return []runtime.Address{runtime.Address(contractsAddress)}, nil + }, + OnResolveLocation: newLocationResolver(contractsAddress), + OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { + accountCodes[location] = code + return nil + }, + OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { + code = accountCodes[location] + return code, nil + }, + OnEmitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { + return json.Decode(nil, b) + }, + } + + nextTransactionLocation := NewTransactionLocationGenerator() + nextScriptLocation := NewScriptLocationGenerator() // Deploy contracts @@ -4757,234 +5407,1197 @@ func TestCadenceOwnedAccountCall(t *testing.T) { assert.Equal(t, types.GasLimit(9999), limit) assert.Equal(t, types.NewBalanceFromUFix64(expectedBalance), balance) - return &types.ResultSummary{ - Status: types.StatusSuccessful, - ReturnedData: types.Data{3, 1, 4}, - } - }, - } - }, - } + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: types.Data{3, 1, 4}, + } + }, + } + }, + } + + deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + + rt := runtime.NewRuntime(runtime.Config{}) + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): [UInt8] { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.call( + to: EVM.EVMAddress( + bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ), + data: [4, 5, 6], + gasLimit: 9999, + value: bal + ) + destroy cadenceOwnedAccount + return response.data + } + `) + + accountCodes := map[common.Location][]byte{} + var events []cadence.Event + + runtimeInterface := &TestRuntimeInterface{ + Storage: NewTestLedger(nil, nil), + OnGetSigningAccounts: func() ([]runtime.Address, error) { + return []runtime.Address{runtime.Address(contractsAddress)}, nil + }, + OnResolveLocation: newLocationResolver(contractsAddress), + OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { + accountCodes[location] = code + return nil + }, + OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { + code = accountCodes[location] + return code, nil + }, + OnEmitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { + return json.Decode(nil, b) + }, + } + + nextTransactionLocation := NewTransactionLocationGenerator() + nextScriptLocation := NewScriptLocationGenerator() + + // Deploy contracts + + deployContracts( + t, + rt, + contractsAddress, + runtimeInterface, + deploymentEnvironment, + nextTransactionLocation, + ) + + // Run script + + actual, err := rt.ExecuteScript( + runtime.Script{ + Source: script, + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + UseVM: cadence_vm.DefaultEnabled, + }, + ) + require.NoError(t, err) + + expected := cadence.NewArray([]cadence.Value{ + cadence.UInt8(3), + cadence.UInt8(1), + cadence.UInt8(4), + }).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) + + require.Equal(t, expected, actual) +} + +func TestCadenceOwnedAccountCallWithSigAndArgs(t *testing.T) { + + t.Parallel() + + expectedBalance, err := cadence.NewUFix64FromParts(1, 23000000) + require.NoError(t, err) + + contractsAddress := flow.BytesToAddress([]byte{0x1}) + + executeScript := func(handler types.ContractHandler, script []byte) (cadence.Value, error) { + + transactionEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + + accountCodes := map[common.Location][]byte{} + var events []cadence.Event + + runtimeInterface := &TestRuntimeInterface{ + Storage: NewTestLedger(nil, nil), + OnGetSigningAccounts: func() ([]runtime.Address, error) { + return []runtime.Address{runtime.Address(contractsAddress)}, nil + }, + OnResolveLocation: newLocationResolver(contractsAddress), + OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { + accountCodes[location] = code + return nil + }, + OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { + code = accountCodes[location] + return code, nil + }, + OnEmitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { + return json.Decode(nil, b) + }, + } + + nextTransactionLocation := NewTransactionLocationGenerator() + nextScriptLocation := NewScriptLocationGenerator() + + rt := runtime.NewRuntime(runtime.Config{}) + + // Deploy contracts + + deployContracts( + t, + rt, + contractsAddress, + runtimeInterface, + transactionEnvironment, + nextTransactionLocation, + ) + + // Run script + + return rt.ExecuteScript( + runtime.Script{ + Source: script, + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + UseVM: cadence_vm.DefaultEnabled, + }, + ) + } + + t.Run("call includes result types, tx fails", func(t *testing.T) { + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + accountByAddress: func(fromAddress types.Address, isAuthorized bool) types.Account { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, fromAddress) + assert.True(t, isAuthorized) + + return &testFlowAccount{ + address: fromAddress, + call: func( + toAddress types.Address, + data types.Data, + limit types.GasLimit, + balance types.Balance, + ) *types.ResultSummary { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, toAddress) + assert.Equal(t, types.Data{54, 9, 29, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, data) + assert.Equal(t, types.GasLimit(9999), limit) + assert.Equal(t, types.NewBalanceFromUFix64(expectedBalance), balance) + + return &types.ResultSummary{ + Status: types.StatusFailed, + ReturnedData: types.Data([]byte{0, 1, 2}), + } + }, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.callWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ), + signature: "test(bool)", + args: [true], + gasLimit: 9999, + value: bal.attoflow, + resultTypes: [Type()], + ) + destroy cadenceOwnedAccount + return response + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusFailed, res.Status) + assert.True(t, len(res.Results) == 3) + assert.Equal(t, cadence.UInt8(0), res.Results[0]) + assert.Equal(t, cadence.UInt8(1), res.Results[1]) + assert.Equal(t, cadence.UInt8(2), res.Results[2]) + }) + + t.Run("call includes result types, tx result data is empty", func(t *testing.T) { + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + accountByAddress: func(fromAddress types.Address, isAuthorized bool) types.Account { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, fromAddress) + assert.True(t, isAuthorized) + + return &testFlowAccount{ + address: fromAddress, + call: func( + toAddress types.Address, + data types.Data, + limit types.GasLimit, + balance types.Balance, + ) *types.ResultSummary { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, toAddress) + assert.Equal(t, types.Data{54, 9, 29, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, data) + assert.Equal(t, types.GasLimit(9999), limit) + assert.Equal(t, types.NewBalanceFromUFix64(expectedBalance), balance) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + } + }, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.callWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ), + signature: "test(bool)", + args: [true], + gasLimit: 9999, + value: bal.attoflow, + resultTypes: [Type()], + ) + destroy cadenceOwnedAccount + return response + } + `) + + _, err := executeScript(handler, script) + require.ErrorContains(t, err, "failed to ABI decode data") + }) + + t.Run("call includes result types, tx result data doesn't match result types", func(t *testing.T) { + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + accountByAddress: func(fromAddress types.Address, isAuthorized bool) types.Account { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, fromAddress) + assert.True(t, isAuthorized) + + return &testFlowAccount{ + address: fromAddress, + call: func( + toAddress types.Address, + data types.Data, + limit types.GasLimit, + balance types.Balance, + ) *types.ResultSummary { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, toAddress) + assert.Equal(t, types.Data{54, 9, 29, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, data) + assert.Equal(t, types.GasLimit(9999), limit) + assert.Equal(t, types.NewBalanceFromUFix64(expectedBalance), balance) + + // Result data is uint64(42) + + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.UintTy, Size: 64}}, + } + + encodedValues, err := arguments.Pack(uint64(42)) + assert.NoError(t, err) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.callWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ), + signature: "test(bool)", + args: [true], + gasLimit: 9999, + value: bal.attoflow, + resultTypes: [Type()], + ) + destroy cadenceOwnedAccount + return response + } + `) + + _, err := executeScript(handler, script) + require.ErrorContains(t, err, "failed to ABI decode data") + }) + + t.Run("call includes result types, tx result data matches", func(t *testing.T) { + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + accountByAddress: func(fromAddress types.Address, isAuthorized bool) types.Account { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, fromAddress) + assert.True(t, isAuthorized) + + return &testFlowAccount{ + address: fromAddress, + call: func( + toAddress types.Address, + data types.Data, + limit types.GasLimit, + balance types.Balance, + ) *types.ResultSummary { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, toAddress) + assert.Equal(t, types.Data{54, 9, 29, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, data) + assert.Equal(t, types.GasLimit(9999), limit) + assert.Equal(t, types.NewBalanceFromUFix64(expectedBalance), balance) + + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.BoolTy}}, + } + + encodedValues, err := arguments.Pack(true) + assert.NoError(t, err) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.callWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ), + signature: "test(bool)", + args: [true], + gasLimit: 9999, + value: bal.attoflow, + resultTypes: [Type()], + ) + destroy cadenceOwnedAccount + return response + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusSuccessful, res.Status) + assert.True(t, len(res.Results) == 1) + assert.Equal(t, cadence.Bool(true), res.Results[0]) + }) + + t.Run("call doesn't result types, tx failed", func(t *testing.T) { + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + accountByAddress: func(fromAddress types.Address, isAuthorized bool) types.Account { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, fromAddress) + assert.True(t, isAuthorized) + + return &testFlowAccount{ + address: fromAddress, + call: func( + toAddress types.Address, + data types.Data, + limit types.GasLimit, + balance types.Balance, + ) *types.ResultSummary { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, toAddress) + assert.Equal(t, types.Data{54, 9, 29, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, data) + assert.Equal(t, types.GasLimit(9999), limit) + assert.Equal(t, types.NewBalanceFromUFix64(expectedBalance), balance) + + return &types.ResultSummary{ + Status: types.StatusFailed, + ReturnedData: types.Data([]byte{0, 1, 2}), + } + }, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.callWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ), + signature: "test(bool)", + args: [true], + gasLimit: 9999, + value: bal.attoflow, + resultTypes: nil, + ) + destroy cadenceOwnedAccount + return response + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusFailed, res.Status) + assert.True(t, len(res.Results) == 3) + assert.Equal(t, cadence.UInt8(0), res.Results[0]) + assert.Equal(t, cadence.UInt8(1), res.Results[1]) + assert.Equal(t, cadence.UInt8(2), res.Results[2]) + }) + + t.Run("call doesn't result types, tx is successful", func(t *testing.T) { + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + accountByAddress: func(fromAddress types.Address, isAuthorized bool) types.Account { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, fromAddress) + assert.True(t, isAuthorized) + + return &testFlowAccount{ + address: fromAddress, + call: func( + toAddress types.Address, + data types.Data, + limit types.GasLimit, + balance types.Balance, + ) *types.ResultSummary { + assert.Equal(t, types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, toAddress) + assert.Equal(t, types.Data{54, 9, 29, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, data) + assert.Equal(t, types.GasLimit(9999), limit) + assert.Equal(t, types.NewBalanceFromUFix64(expectedBalance), balance) + + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.BoolTy}}, + } + + encodedValues, err := arguments.Pack(true) + assert.NoError(t, err) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.callWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ), + signature: "test(bool)", + args: [true], + gasLimit: 9999, + value: bal.attoflow, + resultTypes: nil, + ) + destroy cadenceOwnedAccount + return response + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusSuccessful, res.Status) + assert.True(t, len(res.Results) == 32) + for i, v := range res.Results { + if i == len(res.Results)-1 { + assert.Equal(t, cadence.UInt8(1), v) + } else { + assert.Equal(t, cadence.UInt8(0), v) + } + } + }) +} + +func TestCadenceOwnedAccountDryCall(t *testing.T) { + + t.Parallel() + + dryCallCalled := false + + contractsAddress := flow.BytesToAddress([]byte{0x1}) + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + assert.Equal(t, []byte{4, 5, 6}, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: []byte{3, 1, 4}, + } + }, + } + + deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + + rt := runtime.NewRuntime(runtime.Config{}) + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): [UInt8] { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.dryCall( + to: EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15] + ), + data: [4, 5, 6], + gasLimit: 33000, + value: bal + ) + destroy cadenceOwnedAccount + return response.data + } + `) + + accountCodes := map[common.Location][]byte{} + var events []cadence.Event + + runtimeInterface := &TestRuntimeInterface{ + Storage: NewTestLedger(nil, nil), + OnGetSigningAccounts: func() ([]runtime.Address, error) { + return []runtime.Address{runtime.Address(contractsAddress)}, nil + }, + OnResolveLocation: newLocationResolver(contractsAddress), + OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { + accountCodes[location] = code + return nil + }, + OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { + code = accountCodes[location] + return code, nil + }, + OnEmitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { + return json.Decode(nil, b) + }, + } + + nextTransactionLocation := NewTransactionLocationGenerator() + nextScriptLocation := NewScriptLocationGenerator() + + // Deploy contracts + + deployContracts( + t, + rt, + contractsAddress, + runtimeInterface, + deploymentEnvironment, + nextTransactionLocation, + ) + + // Run script + + actual, err := rt.ExecuteScript( + runtime.Script{ + Source: script, + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + UseVM: cadence_vm.DefaultEnabled, + }, + ) + require.NoError(t, err) + + expected := cadence.NewArray([]cadence.Value{ + cadence.UInt8(3), + cadence.UInt8(1), + cadence.UInt8(4), + }).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) + + require.Equal(t, expected, actual) + require.True(t, dryCallCalled) +} + +func TestCadenceOwnedAccountDryCallWithSigAndArgs(t *testing.T) { + + t.Parallel() + + contractsAddress := flow.BytesToAddress([]byte{0x1}) + + executeScript := func(handler types.ContractHandler, script []byte) (cadence.Value, error) { + transactionEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) + scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + + rt := runtime.NewRuntime(runtime.Config{}) + + accountCodes := map[common.Location][]byte{} + var events []cadence.Event + + runtimeInterface := &TestRuntimeInterface{ + Storage: NewTestLedger(nil, nil), + OnGetSigningAccounts: func() ([]runtime.Address, error) { + return []runtime.Address{runtime.Address(contractsAddress)}, nil + }, + OnResolveLocation: newLocationResolver(contractsAddress), + OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { + accountCodes[location] = code + return nil + }, + OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { + code = accountCodes[location] + return code, nil + }, + OnEmitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { + return json.Decode(nil, b) + }, + } + + nextTransactionLocation := NewTransactionLocationGenerator() + nextScriptLocation := NewScriptLocationGenerator() + + // Deploy contracts + + deployContracts( + t, + rt, + contractsAddress, + runtimeInterface, + transactionEnvironment, + nextTransactionLocation, + ) + + // Run script + + return rt.ExecuteScript( + runtime.Script{ + Source: script, + }, + runtime.Context{ + Interface: runtimeInterface, + Environment: scriptEnvironment, + Location: nextScriptLocation(), + UseVM: cadence_vm.DefaultEnabled, + }, + ) + } + + t.Run("dryCall includes result types, tx fails", func(t *testing.T) { + dryCallCalled := false + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{223, 225, 172, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) + + return &types.ResultSummary{ + Status: types.StatusFailed, + ReturnedData: types.Data([]byte{0, 1, 2}), + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.dryCallWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15] + ), + signature: "isBridgeDeployed(address)", + args: [EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20] + )], + gasLimit: 33000, + value: bal.attoflow, + resultTypes: [Type()], + ) + destroy cadenceOwnedAccount + return response + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + require.True(t, dryCallCalled) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusFailed, res.Status) + assert.True(t, len(res.Results) == 3) + assert.Equal(t, cadence.UInt8(0), res.Results[0]) + assert.Equal(t, cadence.UInt8(1), res.Results[1]) + assert.Equal(t, cadence.UInt8(2), res.Results[2]) + }) + + t.Run("dryCall includes result types, tx result data is empty", func(t *testing.T) { + dryCallCalled := false + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{223, 225, 172, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.dryCallWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15] + ), + signature: "isBridgeDeployed(address)", + args: [EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20] + )], + gasLimit: 33000, + value: bal.attoflow, + resultTypes: [Type()], + ) + destroy cadenceOwnedAccount + return response + } + `) + + _, err := executeScript(handler, script) + require.ErrorContains(t, err, "failed to ABI decode data") + assert.True(t, dryCallCalled) + }) + + t.Run("dryCall includes result types, tx result data doesn't match result types", func(t *testing.T) { + dryCallCalled := false + + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) + + require.NotNil(t, gethTx.To()) + + assert.Equal( + t, + types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{223, 225, 172, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) - deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) - scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + // Result data is uint64(42) - rt := runtime.NewRuntime(runtime.Config{}) + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.UintTy, Size: 64}}, + } - script := []byte(` + encodedValues, err := arguments.Pack(uint64(42)) + assert.NoError(t, err) + + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + + script := []byte(` import EVM from 0x1 access(all) - fun main(): [UInt8] { + fun main(): EVM.ResultDecoded { let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() - let bal = EVM.Balance(attoflow: 0) - bal.setFLOW(flow: 1.23) - let response = cadenceOwnedAccount.call( + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.dryCallWithSigAndArgs( to: EVM.EVMAddress( - bytes: [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15] ), - data: [4, 5, 6], - gasLimit: 9999, - value: bal + signature: "isBridgeDeployed(address)", + args: [EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20] + )], + gasLimit: 33000, + value: bal.attoflow, + resultTypes: [Type()], ) destroy cadenceOwnedAccount - return response.data + return response } - `) - - accountCodes := map[common.Location][]byte{} - var events []cadence.Event - - runtimeInterface := &TestRuntimeInterface{ - Storage: NewTestLedger(nil, nil), - OnGetSigningAccounts: func() ([]runtime.Address, error) { - return []runtime.Address{runtime.Address(contractsAddress)}, nil - }, - OnResolveLocation: newLocationResolver(contractsAddress), - OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { - accountCodes[location] = code - return nil - }, - OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { - code = accountCodes[location] - return code, nil - }, - OnEmitEvent: func(event cadence.Event) error { - events = append(events, event) - return nil - }, - OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { - return json.Decode(nil, b) - }, - } - - nextTransactionLocation := NewTransactionLocationGenerator() - nextScriptLocation := NewScriptLocationGenerator() + `) - // Deploy contracts + _, err := executeScript(handler, script) + require.ErrorContains(t, err, "failed to ABI decode data") + assert.True(t, dryCallCalled) + }) - deployContracts( - t, - rt, - contractsAddress, - runtimeInterface, - deploymentEnvironment, - nextTransactionLocation, - ) + t.Run("dryCall includes result types, tx result data matches", func(t *testing.T) { + dryCallCalled := false - // Run script + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) - actual, err := rt.ExecuteScript( - runtime.Script{ - Source: script, - }, - runtime.Context{ - Interface: runtimeInterface, - Environment: scriptEnvironment, - Location: nextScriptLocation(), - UseVM: cadence_vm.DefaultEnabled, - }, - ) - require.NoError(t, err) + require.NotNil(t, gethTx.To()) - expected := cadence.NewArray([]cadence.Value{ - cadence.UInt8(3), - cadence.UInt8(1), - cadence.UInt8(4), - }).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) + assert.Equal( + t, + types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{223, 225, 172, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) - require.Equal(t, expected, actual) -} + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.BoolTy}}, + } -func TestCadenceOwnedAccountDryCall(t *testing.T) { + encodedValues, err := arguments.Pack(true) + assert.NoError(t, err) - t.Parallel() + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } - dryCallCalled := false + script := []byte(` + import EVM from 0x1 - contractsAddress := flow.BytesToAddress([]byte{0x1}) + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.dryCallWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15] + ), + signature: "isBridgeDeployed(address)", + args: [EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20] + )], + gasLimit: 33000, + value: bal.attoflow, + resultTypes: [Type()], + ) + destroy cadenceOwnedAccount + return response + } + `) - handler := &testContractHandler{ - evmContractAddress: common.Address(contractsAddress), - dryRun: func(tx []byte, from types.Address) *types.ResultSummary { - dryCallCalled = true - gethTx := &gethTypes.Transaction{} - if err := gethTx.UnmarshalBinary(tx); err != nil { - require.Fail(t, err.Error()) - } + val, err := executeScript(handler, script) + require.NoError(t, err) + assert.True(t, dryCallCalled) - require.NotNil(t, gethTx.To()) + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusSuccessful, res.Status) + assert.True(t, len(res.Results) == 1) + assert.Equal(t, cadence.Bool(true), res.Results[0]) + }) - assert.Equal( - t, - types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - from, - ) - assert.Equal( - t, - types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, - types.NewAddress(*gethTx.To()), - ) - assert.Equal(t, []byte{4, 5, 6}, gethTx.Data()) - assert.Equal(t, uint64(33_000), gethTx.Gas()) - assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) + t.Run("dryCall doesn't result types, tx fails", func(t *testing.T) { + dryCallCalled := false - return &types.ResultSummary{ - Status: types.StatusSuccessful, - ReturnedData: []byte{3, 1, 4}, - } - }, - } + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) - deploymentEnvironment := newEVMTransactionEnvironment(handler, contractsAddress) - scriptEnvironment := newEVMScriptEnvironment(handler, contractsAddress) + require.NotNil(t, gethTx.To()) - rt := runtime.NewRuntime(runtime.Config{}) + assert.Equal( + t, + types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{223, 225, 172, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) + + return &types.ResultSummary{ + Status: types.StatusFailed, + ReturnedData: types.Data([]byte{0, 1, 2}), + } + }, + } - script := []byte(` + script := []byte(` import EVM from 0x1 access(all) - fun main(): [UInt8] { + fun main(): EVM.ResultDecoded { let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() let bal = EVM.Balance(attoflow: 0) bal.setFLOW(flow: 1.23) - let response = cadenceOwnedAccount.dryCall( + let response = cadenceOwnedAccount.dryCallWithSigAndArgs( to: EVM.EVMAddress( bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15] ), - data: [4, 5, 6], + signature: "isBridgeDeployed(address)", + args: [EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20] + )], gasLimit: 33000, - value: bal + value: bal.attoflow, + resultTypes: nil, ) destroy cadenceOwnedAccount - return response.data + return response } `) - accountCodes := map[common.Location][]byte{} - var events []cadence.Event + val, err := executeScript(handler, script) + require.NoError(t, err) + assert.True(t, dryCallCalled) - runtimeInterface := &TestRuntimeInterface{ - Storage: NewTestLedger(nil, nil), - OnGetSigningAccounts: func() ([]runtime.Address, error) { - return []runtime.Address{runtime.Address(contractsAddress)}, nil - }, - OnResolveLocation: newLocationResolver(contractsAddress), - OnUpdateAccountContractCode: func(location common.AddressLocation, code []byte) error { - accountCodes[location] = code - return nil - }, - OnGetAccountContractCode: func(location common.AddressLocation) (code []byte, err error) { - code = accountCodes[location] - return code, nil - }, - OnEmitEvent: func(event cadence.Event) error { - events = append(events, event) - return nil - }, - OnDecodeArgument: func(b []byte, t cadence.Type) (cadence.Value, error) { - return json.Decode(nil, b) - }, - } + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusFailed, res.Status) + assert.True(t, len(res.Results) == 3) + assert.Equal(t, cadence.UInt8(0), res.Results[0]) + assert.Equal(t, cadence.UInt8(1), res.Results[1]) + assert.Equal(t, cadence.UInt8(2), res.Results[2]) + }) - nextTransactionLocation := NewTransactionLocationGenerator() - nextScriptLocation := NewScriptLocationGenerator() + t.Run("dryCall doesn't result types, tx is successful", func(t *testing.T) { + dryCallCalled := false - // Deploy contracts + handler := &testContractHandler{ + evmContractAddress: common.Address(contractsAddress), + dryRunWithTxData: func(txData gethTypes.TxData, from types.Address) *types.ResultSummary { + dryCallCalled = true + gethTx := gethTypes.NewTx(txData) - deployContracts( - t, - rt, - contractsAddress, - runtimeInterface, - deploymentEnvironment, - nextTransactionLocation, - ) + require.NotNil(t, gethTx.To()) - // Run script + assert.Equal( + t, + types.Address{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + from, + ) + assert.Equal( + t, + types.Address{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15}, + types.NewAddress(*gethTx.To()), + ) + expectedData := []byte{223, 225, 172, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20} + assert.Equal(t, expectedData, gethTx.Data()) + assert.Equal(t, uint64(33_000), gethTx.Gas()) + assert.Equal(t, big.NewInt(1230000000000000000), gethTx.Value()) - actual, err := rt.ExecuteScript( - runtime.Script{ - Source: script, - }, - runtime.Context{ - Interface: runtimeInterface, - Environment: scriptEnvironment, - Location: nextScriptLocation(), - UseVM: cadence_vm.DefaultEnabled, - }, - ) - require.NoError(t, err) + arguments := gethABI.Arguments{ + gethABI.Argument{Type: gethABI.Type{T: gethABI.BoolTy}}, + } - expected := cadence.NewArray([]cadence.Value{ - cadence.UInt8(3), - cadence.UInt8(1), - cadence.UInt8(4), - }).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) + encodedValues, err := arguments.Pack(true) + assert.NoError(t, err) - require.Equal(t, expected, actual) - require.True(t, dryCallCalled) + return &types.ResultSummary{ + Status: types.StatusSuccessful, + ReturnedData: encodedValues, + } + }, + } + + script := []byte(` + import EVM from 0x1 + + access(all) + fun main(): EVM.ResultDecoded { + let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() + let bal = EVM.Balance(attoflow: 0) + bal.setFLOW(flow: 1.23) + let response = cadenceOwnedAccount.dryCallWithSigAndArgs( + to: EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 15] + ), + signature: "isBridgeDeployed(address)", + args: [EVM.EVMAddress( + bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 20] + )], + gasLimit: 33000, + value: bal.attoflow, + resultTypes: nil, + ) + destroy cadenceOwnedAccount + return response + } + `) + + val, err := executeScript(handler, script) + require.NoError(t, err) + assert.True(t, dryCallCalled) + + res, err := ResultDecodedFromEVMResultValue(val) + require.NoError(t, err) + assert.Equal(t, types.StatusSuccessful, res.Status) + assert.True(t, len(res.Results) == 32) + for i, v := range res.Results { + if i == len(res.Results)-1 { + assert.Equal(t, cadence.UInt8(1), v) + } else { + assert.Equal(t, cadence.UInt8(0), v) + } + } + }) } func TestEVMAddressDeposit(t *testing.T) { @@ -5317,8 +6930,9 @@ func TestCadenceOwnedAccountWithdraw(t *testing.T) { let cadenceOwnedAccount <- EVM.createCadenceOwnedAccount() cadenceOwnedAccount.deposit(from: <-vault) - let vault2 <- cadenceOwnedAccount.withdraw(balance: EVM.Balance(attoflow: 1230000000000000000)) + let vault2 <- cadenceOwnedAccount.withdraw(balance: EVM.Balance(attoflow: 1230000000900000000)) let balance = vault2.balance + assert(balance == 1.23000000, message: "mismatching vault balance") log(vault2.uuid) destroy cadenceOwnedAccount @@ -5737,9 +7351,13 @@ func TestEVMAccountCodeHash(t *testing.T) { t.Parallel() contractsAddress := flow.BytesToAddress([]byte{0x1}) - expectedCodeHashRaw := []byte{1, 2, 3} + expectedCodeHashRaw := gethCommon.HexToHash("0x5edac053e2bb5dc30d05a4dcdc5a31e0717212966cb1e8225daa4105f1dabf9c") + byteValues := []cadence.Value{} + for _, val := range expectedCodeHashRaw.Bytes() { + byteValues = append(byteValues, cadence.NewUInt8(val)) + } expectedCodeHashValue := cadence.NewArray( - []cadence.Value{cadence.UInt8(1), cadence.UInt8(2), cadence.UInt8(3)}, + byteValues, ).WithType(cadence.NewVariableSizedArrayType(cadence.UInt8Type)) handler := &testContractHandler{ @@ -5752,7 +7370,7 @@ func TestEVMAccountCodeHash(t *testing.T) { return &testFlowAccount{ address: fromAddress, codeHash: func() []byte { - return expectedCodeHashRaw + return expectedCodeHashRaw.Bytes() }, } }, diff --git a/fvm/evm/stdlib/contract_test_helpers.cdc b/fvm/evm/stdlib/contract_test_helpers.cdc new file mode 100644 index 00000000000..8671396f6b3 --- /dev/null +++ b/fvm/evm/stdlib/contract_test_helpers.cdc @@ -0,0 +1,39 @@ + /// Stores a value to an address' storage slot. + access(all) + fun store(target: EVM.EVMAddress, slot: String, value: String) { + pre { + slot.length == 64 || slot.length == 66: + "EVM.store(): Invalid hex string length for EVM slot. The provided string is \(slot.length), but the length must be 64 or 66." + value.length == 64 || value.length == 66: + "EVM.store(): Invalid hex string length for EVM value. The provided string is \(value.length), but the length must be 64 or 66." + } + InternalEVM.store(target: target.bytes, slot: slot, value: value) + } + + /// Loads a storage slot from an address. + access(all) + view fun load(target: EVM.EVMAddress, slot: String): [UInt8] { + pre { + slot.length == 64 || slot.length == 66: + "EVM.load(): Invalid hex string length for EVM slot. The provided string is \(slot.length), but the length must be 64 or 66." + } + return InternalEVM.load(target: target.bytes, slot: slot) + } + + /// Runs a transaction by setting the call's `msg.sender` to be the `from` address. + access(all) + fun runTxAs( + from: EVM.EVMAddress, + to: EVM.EVMAddress, + data: [UInt8], + gasLimit: UInt64, + value: EVM.Balance, + ): Result { + return InternalEVM.runTxAs( + from: from.bytes, + to: to.bytes, + data: data, + gasLimit: gasLimit, + value: value.attoflow + ) as! Result + } diff --git a/fvm/evm/stdlib/type.go b/fvm/evm/stdlib/type.go index 198f8c04253..07467bcce73 100644 --- a/fvm/evm/stdlib/type.go +++ b/fvm/evm/stdlib/type.go @@ -13,7 +13,7 @@ import ( "github.com/onflow/flow-go/model/flow" ) -func newContractType(chainID flow.ChainID) *sema.CompositeType { +func newContractType(chainID flow.ChainID, evmTestHelpersEnabled bool) *sema.CompositeType { contracts := systemcontracts.SystemContractsForChain(chainID) @@ -21,6 +21,7 @@ func newContractType(chainID flow.ChainID) *sema.CompositeType { contracts.NonFungibleToken.Address, contracts.FungibleToken.Address, contracts.FlowToken.Address, + evmTestHelpersEnabled, ) evmContractAddress := contracts.EVMContract.Address @@ -106,7 +107,7 @@ func exportCadenceEventType(contractType *sema.CompositeType, name string) (*cad func init() { for _, chain := range flow.AllChainIDs() { - contractType := newContractType(chain) + contractType := newContractType(chain, true) contractTypes[chain] = contractType transactionExecutedEvent, err := exportCadenceEventType(contractType, "TransactionExecuted") diff --git a/fvm/evm/testutils/accounts.go b/fvm/evm/testutils/accounts.go index ea24d351c89..336dfe2f580 100644 --- a/fvm/evm/testutils/accounts.go +++ b/fvm/evm/testutils/accounts.go @@ -144,7 +144,7 @@ func FundAndGetEOATestAccount(t testing.TB, led atree.Ledger, flowEVMRootAddress ) require.NoError(t, err) - blk2, err := e.NewReadOnlyBlockView(types.NewDefaultBlockContext(2)) + blk2, err := e.NewReadOnlyBlockView() require.NoError(t, err) bal, err := blk2.BalanceOf(account.Address()) diff --git a/fvm/evm/testutils/backend.go b/fvm/evm/testutils/backend.go index 0a4c4361302..428c74504e2 100644 --- a/fvm/evm/testutils/backend.go +++ b/fvm/evm/testutils/backend.go @@ -6,6 +6,7 @@ import ( "fmt" "testing" + gocommon "github.com/ethereum/go-ethereum/common" "github.com/onflow/cadence/stdlib" "github.com/rs/zerolog" otelTrace "go.opentelemetry.io/otel/trace" @@ -19,6 +20,7 @@ import ( "golang.org/x/exp/maps" "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm" "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/fvm/meter" "github.com/onflow/flow-go/fvm/tracing" @@ -37,17 +39,21 @@ func RunWithTestFlowEVMRootAddress(t testing.TB, backend atree.Ledger, f func(fl f(TestFlowEVMRootAddress) } -func RunWithTestBackend(t testing.TB, f func(*TestBackend)) { +func RunWithTestBackend(t testing.TB, chain flow.ChainID, f func(*TestBackend)) { + vs := GetSimpleValueStore() + bi := getSimpleBlockInfo() + rg := getSimpleRandomGenerator() tb := &TestBackend{ - TestValueStore: GetSimpleValueStore(), + TestValueStore: vs, testEventEmitter: getSimpleEventEmitter(), testMeter: getSimpleMeter(), - TestBlockInfo: getSimpleBlockStore(), - TestRandomGenerator: getSimpleRandomGenerator(), + TestBlockInfo: bi, + TestRandomGenerator: rg, TestContractFunctionInvoker: &TestContractFunctionInvoker{}, TestTracer: &TestTracer{}, TestMetricsReporter: &TestMetricsReporter{}, TestLoggerProvider: &TestLoggerProvider{}, + TestBlockStore: getSimpleBlockStore(chain, vs, bi, rg), } f(tb) } @@ -209,7 +215,7 @@ func getSimpleMeter() *testMeter { } } -func getSimpleBlockStore() *TestBlockInfo { +func getSimpleBlockInfo() *TestBlockInfo { var index int64 = 1 return &TestBlockInfo{ GetCurrentBlockHeightFunc: func() (uint64, error) { @@ -227,6 +233,34 @@ func getSimpleBlockStore() *TestBlockInfo { } } +func getSimpleBlockStore(chain flow.ChainID, vs *TestValueStore, bi *TestBlockInfo, rg *TestRandomGenerator) *TestBlockStore { + bs := environment.NewBlockStore( + chain, + vs, + bi, + rg, + evm.StorageAccountAddress(chain), + ) + + return &TestBlockStore{ + LatestBlockFunc: func() (*types.Block, error) { + return bs.LatestBlock() + }, + BlockHashFunc: func(height uint64) (gocommon.Hash, error) { + return bs.BlockHash(height) + }, + BlockProposalFunc: func() (*types.BlockProposal, error) { + return bs.BlockProposal() + }, + StageBlockProposalFunc: func(_bp *types.BlockProposal) { + bs.StageBlockProposal(_bp) + }, + CommitBlockProposalFunc: func(_bp *types.BlockProposal) error { + return bs.CommitBlockProposal(_bp) + }, + } +} + type TestBackend struct { *TestValueStore *testMeter @@ -238,9 +272,13 @@ type TestBackend struct { *TestTracer *TestMetricsReporter *TestLoggerProvider + *TestBlockStore + evmTestOperationsAllowed bool } -var _ types.Backend = &TestBackend{} +func (tb *TestBackend) EVMTestOperationsAllowed() bool { + return tb.evmTestOperationsAllowed +} func (tb *TestBackend) TotalStorageSize() int { if tb.TotalStorageSizeFunc == nil { @@ -260,6 +298,10 @@ func (tb *TestBackend) Get(id flow.RegisterID) (flow.RegisterValue, error) { return tb.GetValue([]byte(id.Owner), []byte(id.Key)) } +func (tb *TestBackend) SetEVMTestOperationsAllowed(allowed bool) { + tb.evmTestOperationsAllowed = allowed +} + type TestValueStore struct { GetValueFunc func(owner, key []byte) ([]byte, error) SetValueFunc func(owner, key, value []byte) error @@ -690,3 +732,53 @@ func (tlp *TestLoggerProvider) Logger() zerolog.Logger { } return zerolog.Nop() } + +type TestBlockStore struct { + BlockHashFunc func(height uint64) (gocommon.Hash, error) + BlockProposalFunc func() (*types.BlockProposal, error) + CommitBlockProposalFunc func(*types.BlockProposal) error + LatestBlockFunc func() (*types.Block, error) + StageBlockProposalFunc func(*types.BlockProposal) +} + +var _ environment.EVMBlockStore = &TestBlockStore{} + +func (tb *TestBlockStore) BlockHash(height uint64) (gocommon.Hash, error) { + blockHashFunc := tb.BlockHashFunc + if blockHashFunc == nil { + panic("BlockHashFunc method is not set") + } + return blockHashFunc(height) +} + +func (tb *TestBlockStore) BlockProposal() (*types.BlockProposal, error) { + blockProposalFunc := tb.BlockProposalFunc + if blockProposalFunc == nil { + panic("BlockProposalFunc method is not set") + } + return blockProposalFunc() +} + +func (tb *TestBlockStore) CommitBlockProposal(bp *types.BlockProposal) error { + commitBlockProposalFunc := tb.CommitBlockProposalFunc + if commitBlockProposalFunc == nil { + panic("CommitBlockProposalFunc method is not set") + } + return commitBlockProposalFunc(bp) +} + +func (tb *TestBlockStore) LatestBlock() (*types.Block, error) { + latestBlockFunc := tb.LatestBlockFunc + if latestBlockFunc == nil { + panic("LatestBlockFunc method is not set") + } + return latestBlockFunc() +} + +func (tb *TestBlockStore) StageBlockProposal(bp *types.BlockProposal) { + stageBlockProposalFunc := tb.StageBlockProposalFunc + if stageBlockProposalFunc == nil { + panic("StageBlockProposalFunc method is not set") + } + stageBlockProposalFunc(bp) +} diff --git a/fvm/evm/testutils/contract.go b/fvm/evm/testutils/contract.go index 45a9f36c7c3..b73e5463417 100644 --- a/fvm/evm/testutils/contract.go +++ b/fvm/evm/testutils/contract.go @@ -84,7 +84,7 @@ func DeployContract(t testing.TB, caller types.Address, tc *TestContract, led at ctx := types.NewDefaultBlockContext(2) - bl, err := e.NewReadOnlyBlockView(ctx) + bl, err := e.NewReadOnlyBlockView() require.NoError(t, err) nonce, err := bl.NonceOf(caller) diff --git a/fvm/evm/testutils/emulator.go b/fvm/evm/testutils/emulator.go index 37d3f9fcb5e..f201b306df6 100644 --- a/fvm/evm/testutils/emulator.go +++ b/fvm/evm/testutils/emulator.go @@ -29,7 +29,7 @@ func (em *TestEmulator) NewBlockView(_ types.BlockContext) (types.BlockView, err } // NewBlock returns a new block view -func (em *TestEmulator) NewReadOnlyBlockView(_ types.BlockContext) (types.ReadOnlyBlockView, error) { +func (em *TestEmulator) NewReadOnlyBlockView() (types.ReadOnlyBlockView, error) { return em, nil } diff --git a/fvm/evm/testutils/handler.go b/fvm/evm/testutils/handler.go index ba9085ee2c5..d266bb57e49 100644 --- a/fvm/evm/testutils/handler.go +++ b/fvm/evm/testutils/handler.go @@ -3,6 +3,7 @@ package testutils import ( "github.com/onflow/cadence/common" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/emulator" "github.com/onflow/flow-go/fvm/evm/handler" "github.com/onflow/flow-go/fvm/evm/precompiles" @@ -13,15 +14,14 @@ import ( func SetupHandler( chainID flow.ChainID, - backend types.Backend, + backend backends.Backend, rootAddr flow.Address, ) *handler.ContractHandler { return handler.NewContractHandler( chainID, rootAddr, - common.MustBytesToAddress(systemcontracts.SystemContractsForChain(chainID).FlowToken.Address.Bytes()), + common.Address(systemcontracts.SystemContractsForChain(chainID).FlowToken.Address), rootAddr, - handler.NewBlockStore(chainID, backend, rootAddr), handler.NewAddressAllocator(), backend, emulator.NewEmulator(backend, rootAddr), diff --git a/fvm/evm/testutils/offchain.go b/fvm/evm/testutils/offchain.go index 5a5e675798a..ecd2b97b00d 100644 --- a/fvm/evm/testutils/offchain.go +++ b/fvm/evm/testutils/offchain.go @@ -3,6 +3,7 @@ package testutils import ( "fmt" + "github.com/onflow/flow-go/fvm/evm/backends" "github.com/onflow/flow-go/fvm/evm/offchain/storage" "github.com/onflow/flow-go/fvm/evm/types" ) @@ -11,7 +12,7 @@ import ( // storage provider that only provides // storage for an specific height type TestStorageProvider struct { - storage types.BackendStorage + storage backends.BackendStorage height uint64 } diff --git a/fvm/evm/testutils/result.go b/fvm/evm/testutils/result.go new file mode 100644 index 00000000000..1266d2c990f --- /dev/null +++ b/fvm/evm/testutils/result.go @@ -0,0 +1,106 @@ +package testutils + +import ( + "fmt" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/sema" + + "github.com/onflow/flow-go/fvm/evm/stdlib" + "github.com/onflow/flow-go/fvm/evm/types" +) + +type ResultDecoded struct { + Status types.Status + ErrorCode types.ErrorCode + ErrorMessage string + GasConsumed uint64 + DeployedContractAddress *types.Address + Results []cadence.Value +} + +func ResultDecodedFromEVMResultValue(val cadence.Value) (*ResultDecoded, error) { + str, ok := val.(cadence.Struct) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected value type") + } + + fields := cadence.FieldsMappedByName(str) + + const expectedFieldCount = 6 + if len(fields) != expectedFieldCount { + return nil, fmt.Errorf( + "invalid input: field count mismatch: expected %d, got %d", + expectedFieldCount, + len(fields), + ) + } + + statusEnum, ok := fields[stdlib.EVMResultTypeStatusFieldName].(cadence.Enum) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for status field") + } + + status, ok := cadence.FieldsMappedByName(statusEnum)[sema.EnumRawValueFieldName].(cadence.UInt8) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for status field") + } + + errorCode, ok := fields[stdlib.EVMResultTypeErrorCodeFieldName].(cadence.UInt64) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for error code field") + } + + errorMsg, ok := fields[stdlib.EVMResultTypeErrorMessageFieldName].(cadence.String) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for error msg field") + } + + gasUsed, ok := fields[stdlib.EVMResultTypeGasUsedFieldName].(cadence.UInt64) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for gas field") + } + + resultsField, ok := fields[stdlib.EVMResultTypeResultsFieldName].(cadence.Array) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for data field") + } + + results := resultsField.Values + + var convertedDeployedAddress *types.Address + + deployedAddressField, ok := fields[stdlib.EVMResultTypeDeployedContractFieldName].(cadence.Optional) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for deployed contract field") + } + + if deployedAddressField.Value != nil { + evmAddress, ok := deployedAddressField.Value.(cadence.Struct) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for deployed contract field") + } + + bytes, ok := cadence.SearchFieldByName(evmAddress, stdlib.EVMAddressTypeBytesFieldName).(cadence.Array) + if !ok { + return nil, fmt.Errorf("invalid input: unexpected type for deployed contract field") + } + + convertedAddress := make([]byte, len(bytes.Values)) + for i, value := range bytes.Values { + convertedAddress[i] = byte(value.(cadence.UInt8)) + } + addr := types.Address(convertedAddress) + convertedDeployedAddress = &addr + } + + return &ResultDecoded{ + Status: types.Status(status), + ErrorCode: types.ErrorCode(errorCode), + ErrorMessage: string(errorMsg), + GasConsumed: uint64(gasUsed), + Results: results, + DeployedContractAddress: convertedDeployedAddress, + }, nil + +} diff --git a/fvm/evm/types/address.go b/fvm/evm/types/address.go index cc27dac5577..3f599a031f8 100644 --- a/fvm/evm/types/address.go +++ b/fvm/evm/types/address.go @@ -122,7 +122,7 @@ func NewAddressFromString(str string) Address { } var AddressBytesCadenceType = cadence.NewConstantSizedArrayType(AddressLength, cadence.UInt8Type) -var AddressBytesSemaType = sema.ByteArrayType +var AddressBytesSemaType = sema.NewConstantSizedType(nil, sema.UInt8Type, AddressLength) func (a Address) ToCadenceValue() cadence.Array { values := make([]cadence.Value, len(a)) diff --git a/fvm/evm/types/balance.go b/fvm/evm/types/balance.go index 2dfdfc53ca6..f147cb7d5e1 100644 --- a/fvm/evm/types/balance.go +++ b/fvm/evm/types/balance.go @@ -94,6 +94,18 @@ func BalanceConversionToUFix64ProneToRoundingError(bal Balance) bool { return new(big.Int).Mod(bal, UFixToAttoConversionMultiplier).BitLen() != 0 } +// AttoFlowBalanceIsValidForFlowVault returns true if the given balance, +// represented as atto-flow, can be stored in a Flow Vault, without loss +// in precision. +// +// Warning! The smallest unit of Flow token that a Flow Vault (Cadence) +// can store, is 1e-8 . +// This means the minimum balance, in atto-flow, that can be stored in a +// Flow Vault, is 1e10 . +func AttoFlowBalanceIsValidForFlowVault(bal *big.Int) bool { + return bal.Cmp(UFixToAttoConversionMultiplier) >= 0 +} + // Subtract balance 2 from balance 1 and returns the result as a new balance func SubBalance(bal1 Balance, bal2 Balance) (Balance, error) { if (*big.Int)(bal1).Cmp(bal2) == -1 { diff --git a/fvm/evm/types/emulator.go b/fvm/evm/types/emulator.go index 9ec1636acf6..5d6b32f3a68 100644 --- a/fvm/evm/types/emulator.go +++ b/fvm/evm/types/emulator.go @@ -102,7 +102,7 @@ type BlockView interface { // Emulator emulates an evm-compatible chain type Emulator interface { // constructs a new block view - NewReadOnlyBlockView(ctx BlockContext) (ReadOnlyBlockView, error) + NewReadOnlyBlockView() (ReadOnlyBlockView, error) // constructs a new block NewBlockView(ctx BlockContext) (BlockView, error) diff --git a/fvm/evm/types/errors.go b/fvm/evm/types/errors.go index 420da1be689..4a974362d3a 100644 --- a/fvm/evm/types/errors.go +++ b/fvm/evm/types/errors.go @@ -99,7 +99,7 @@ var ( // ErrWithdrawBalanceRounding is returned when withdraw call has a balance that could // result in rounding error, i.e. the balance contains fractions smaller than 10^8 Flow (smallest unit allowed to transfer). - ErrWithdrawBalanceRounding = errors.New("withdraw failed! the balance is susceptible to the rounding error") + ErrWithdrawBalanceRounding = errors.New("withdraw failed! smallest unit allowed to transfer is 1e10 attoFlow") // ErrUnexpectedEmptyResult is returned when a result is expected to be returned by the emulator // but nil has been returned. This should never happen and is a safety error. @@ -112,6 +112,17 @@ var ( // ErrNotImplemented is a fatal error when something is called that is not implemented ErrNotImplemented = NewFatalError(errors.New("a functionality is called that is not implemented")) + + // ErrEmptyRLPEncodedProof is returned when the RLP encoded COA Ownership proof is + // an empty list + ErrEmptyRLPEncodedProof = errors.New("invalid encoded proof: expected list with key indices, got empty list") + + // ErrUnexpectedEmptyTransactionData is returned when empty transaction data is received. + // This should never happen and is a safety error. + ErrUnexpectedEmptyTransactionData = errors.New("unexpected empty transaction data has been received") + + // ErrUnsupportedOperation is returned when the operation is not supported. + ErrUnsupportedOperation = errors.New("operation is not supported") ) // StateError is a non-fatal error, returned when a state operation @@ -177,18 +188,24 @@ func IsAInsufficientTotalSupplyError(err error) bool { return errors.Is(err, ErrInsufficientTotalSupply) } -// IsWithdrawBalanceRoundingError returns true if the error type is +// IsAWithdrawBalanceRoundingError returns true if the error type is // ErrWithdrawBalanceRounding -func IsWithdrawBalanceRoundingError(err error) bool { +func IsAWithdrawBalanceRoundingError(err error) bool { return errors.Is(err, ErrWithdrawBalanceRounding) } // IsAUnauthorizedMethodCallError returns true if the error type is -// UnauthorizedMethodCallError +// ErrUnauthorizedMethodCall func IsAUnauthorizedMethodCallError(err error) bool { return errors.Is(err, ErrUnauthorizedMethodCall) } +// IsAUnsupportedOperationError returns true if the error type is +// ErrUnsupportedOperation +func IsAUnsupportedOperationError(err error) bool { + return errors.Is(err, ErrUnsupportedOperation) +} + // BackendError is a non-fatal error wraps errors returned from the backend type BackendError struct { err error diff --git a/fvm/evm/types/handler.go b/fvm/evm/types/handler.go index 4e4548e9c93..b93aece4a70 100644 --- a/fvm/evm/types/handler.go +++ b/fvm/evm/types/handler.go @@ -2,6 +2,7 @@ package types import ( gethCommon "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" "github.com/onflow/cadence/common" ) @@ -43,6 +44,11 @@ type ContractHandler interface { // The function should not have any persisted changes made to the state. DryRun(tx []byte, from Address) *ResultSummary + // DryRunWithTxData simulates execution of the provided transaction data. + // The from address is required since the transaction is unsigned. + // The function should not have any persisted changes made to the state. + DryRunWithTxData(txData types.TxData, from Address) *ResultSummary + // BatchRun runs transaction batch in the evm environment, // collect all the gas fees and transfers the gas fees to the gasFeeCollector account. BatchRun(txs [][]byte, gasFeeCollector Address) []*ResultSummary @@ -58,6 +64,15 @@ type ContractHandler interface { // Constructs and commits a new block from the block proposal CommitBlockProposal() + + // SetState sets a value for the given storage slot + SetState(target Address, slot gethCommon.Hash, value gethCommon.Hash) gethCommon.Hash + + // GetState returns the value for the given storage slot + GetState(target Address, slot gethCommon.Hash) gethCommon.Hash + + // RunTxAs runs a transaction by setting the call's `msg.sender` to be the `from` address + RunTxAs(from Address, to Address, txData Data, gasLimit GasLimit, balance Balance) *ResultSummary } // AddressAllocator allocates addresses, used by the handler @@ -75,21 +90,3 @@ type AddressAllocator interface { // AllocateAddress allocates an address by index to be used by a precompile contract AllocatePrecompileAddress(index uint64) Address } - -// BlockStore stores the chain of blocks -type BlockStore interface { - // LatestBlock returns the latest appended block - LatestBlock() (*Block, error) - - // BlockHash returns the hash of the block at the given height - BlockHash(height uint64) (gethCommon.Hash, error) - - // BlockProposal returns the active block proposal - BlockProposal() (*BlockProposal, error) - - // UpdateBlockProposal replaces the current block proposal with the ones passed - UpdateBlockProposal(*BlockProposal) error - - // CommitBlockProposal commits the block proposal and update the chain of blocks - CommitBlockProposal(*BlockProposal) error -} diff --git a/fvm/evm/types/proof.go b/fvm/evm/types/proof.go index 6d2ed3803ab..f07dacd1c7f 100644 --- a/fvm/evm/types/proof.go +++ b/fvm/evm/types/proof.go @@ -153,6 +153,12 @@ func COAOwnershipProofSignatureCountFromEncoded(data []byte) (int, error) { if err != nil { return 0, err } + + // Ensure at least one element exists before accessing encodedItems[0] + if len(encodedItems) == 0 { + return 0, ErrEmptyRLPEncodedProof + } + // first encoded item is KeyIndices // so reading number of elements in the key indices // should return the count without the need to fully decode diff --git a/fvm/evm/types/result.go b/fvm/evm/types/result.go index 19e54311957..a585eb11655 100644 --- a/fvm/evm/types/result.go +++ b/fvm/evm/types/result.go @@ -54,10 +54,10 @@ type ResultSummary struct { // NewInvalidResult creates a new result that hold transaction validation // error as well as the defined gas cost for validation. -func NewInvalidResult(tx *gethTypes.Transaction, err error) *Result { +func NewInvalidResult(txType uint8, txHash gethCommon.Hash, err error) *Result { return &Result{ - TxType: tx.Type(), - TxHash: tx.Hash(), + TxType: txType, + TxHash: txHash, ValidationError: err, GasConsumed: InvalidTransactionGasCost, } diff --git a/fvm/executionParameters_test.go b/fvm/executionParameters_test.go index d9331478679..10baf6e7147 100644 --- a/fvm/executionParameters_test.go +++ b/fvm/executionParameters_test.go @@ -19,139 +19,37 @@ import ( "github.com/onflow/flow-go/fvm/meter" reusableRuntime "github.com/onflow/flow-go/fvm/runtime" "github.com/onflow/flow-go/fvm/runtime/testutil" + "github.com/onflow/flow-go/model/flow" ) -func TestGetExecutionMemoryWeights(t *testing.T) { - address := common.Address{} - - setupEnvMock := func(readStored func( - address common.Address, - path cadence.Path, - context runtime.Context, - ) (cadence.Value, error)) environment.Environment { - envMock := &fvmmock.Environment{} - envMock.On("BorrowCadenceRuntime", mock.Anything).Return( - reusableRuntime.NewReusableCadenceRuntime( - &testutil.TestRuntime{ - ReadStoredFunc: readStored, - }, - runtime.Config{}, - ), +func TestGetWeights(t *testing.T) { + t.Run("memory", func(t *testing.T) { + runTests[common.MemoryKind]( + t, + func(env environment.Environment, service common.Address) (map[common.MemoryKind]uint64, error) { + return fvm.GetExecutionMemoryWeights(env, service) + }, + blueprints.TransactionFeesExecutionMemoryWeightsPath, + meter.DefaultMemoryWeights, ) - envMock.On("ReturnCadenceRuntime", mock.Anything).Return() - return envMock - } - - t.Run("return error if nothing is stored", - func(t *testing.T) { - envMock := setupEnvMock( - func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { - return nil, nil - }) - _, err := fvm.GetExecutionMemoryWeights(envMock, address) - require.Error(t, err) - require.EqualError(t, err, errors.NewCouldNotGetExecutionParameterFromStateError( - address.Hex(), - blueprints.TransactionFeesExecutionMemoryWeightsPath.String()).Error()) - }, - ) - t.Run("return error if can't parse stored", - func(t *testing.T) { - envMock := setupEnvMock( - func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { - return cadence.NewBool(false), nil - }) - _, err := fvm.GetExecutionMemoryWeights(envMock, address) - require.Error(t, err) - require.EqualError(t, err, errors.NewCouldNotGetExecutionParameterFromStateError( - address.Hex(), - blueprints.TransactionFeesExecutionMemoryWeightsPath.String()).Error()) - }, - ) - t.Run("return error if get stored returns error", - func(t *testing.T) { - someErr := fmt.Errorf("some error") - envMock := setupEnvMock( - func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { - return nil, someErr - }) - _, err := fvm.GetExecutionMemoryWeights(envMock, address) - require.Error(t, err) - require.EqualError(t, err, someErr.Error()) - }, - ) - t.Run("return error if get stored returns error", - func(t *testing.T) { - someErr := fmt.Errorf("some error") - envMock := setupEnvMock( - func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { - return nil, someErr - }) - _, err := fvm.GetExecutionMemoryWeights(envMock, address) - require.Error(t, err) - require.EqualError(t, err, someErr.Error()) - }, - ) - t.Run("no error if a dictionary is stored", - func(t *testing.T) { - envMock := setupEnvMock( - func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { - return cadence.NewDictionary([]cadence.KeyValuePair{}), nil - }) - _, err := fvm.GetExecutionMemoryWeights(envMock, address) - require.NoError(t, err) - }, - ) - t.Run("return defaults if empty dict is stored", - func(t *testing.T) { - envMock := setupEnvMock( - func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { - return cadence.NewDictionary([]cadence.KeyValuePair{}), nil - }) - weights, err := fvm.GetExecutionMemoryWeights(envMock, address) - require.NoError(t, err) - require.InDeltaMapValues(t, meter.DefaultMemoryWeights, weights, 0) - }, - ) - t.Run("return merged if some dict is stored", - func(t *testing.T) { - expectedWeights := meter.ExecutionMemoryWeights{} - var existingWeightKey common.MemoryKind - var existingWeightValue uint64 - for k, v := range meter.DefaultMemoryWeights { - expectedWeights[k] = v - } - // change one existing value - for kind, u := range meter.DefaultMemoryWeights { - existingWeightKey = kind - existingWeightValue = u - expectedWeights[kind] = u + 1 - break - } - expectedWeights[0] = 0 - - envMock := setupEnvMock( - func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { - return cadence.NewDictionary([]cadence.KeyValuePair{ - { - Value: cadence.UInt64(0), - Key: cadence.UInt64(0), - }, // a new key - { - Value: cadence.UInt64(existingWeightValue + 1), - Key: cadence.UInt64(existingWeightKey), - }, // existing key with new value - }), nil - }) - - weights, err := fvm.GetExecutionMemoryWeights(envMock, address) - require.NoError(t, err) - require.InDeltaMapValues(t, expectedWeights, weights, 0) - }, - ) + }) + t.Run("execution effort", func(t *testing.T) { + runTests[common.ComputationKind]( + t, + func(env environment.Environment, service common.Address) (map[common.ComputationKind]uint64, error) { + return fvm.GetExecutionEffortWeights(env, service) + }, + blueprints.TransactionFeesExecutionEffortWeightsPath, + meter.DefaultComputationWeights, + ) + }) } -func TestGetExecutionEffortWeights(t *testing.T) { +func runTests[T common.ComputationKind | common.MemoryKind]( + t *testing.T, + f func(env environment.Environment, service common.Address) (map[T]uint64, error), + path cadence.Path, + defaultWeights map[T]uint64) { address := common.Address{} setupEnvMock := func(readStored func( @@ -159,14 +57,20 @@ func TestGetExecutionEffortWeights(t *testing.T) { path cadence.Path, context runtime.Context, ) (cadence.Value, error)) environment.Environment { + pool := reusableRuntime.NewCustomReusableCadenceRuntimePool( + 0, + flow.Mainnet.Chain(), + runtime.Config{}, + func(config runtime.Config) runtime.Runtime { + return &testutil.TestRuntime{ + ReadStoredFunc: readStored, + } + }, + ) + envMock := &fvmmock.Environment{} envMock.On("BorrowCadenceRuntime", mock.Anything).Return( - reusableRuntime.NewReusableCadenceRuntime( - &testutil.TestRuntime{ - ReadStoredFunc: readStored, - }, - runtime.Config{}, - ), + pool.Borrow(envMock, environment.CadenceTransactionRuntime), ) envMock.On("ReturnCadenceRuntime", mock.Anything).Return() return envMock @@ -178,11 +82,11 @@ func TestGetExecutionEffortWeights(t *testing.T) { func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { return nil, nil }) - _, err := fvm.GetExecutionEffortWeights(envMock, address) + _, err := f(envMock, address) require.Error(t, err) require.EqualError(t, err, errors.NewCouldNotGetExecutionParameterFromStateError( address.Hex(), - blueprints.TransactionFeesExecutionEffortWeightsPath.String()).Error()) + path.String()).Error()) }, ) t.Run("return error if can't parse stored", @@ -191,11 +95,11 @@ func TestGetExecutionEffortWeights(t *testing.T) { func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { return cadence.NewBool(false), nil }) - _, err := fvm.GetExecutionEffortWeights(envMock, address) + _, err := f(envMock, address) require.Error(t, err) require.EqualError(t, err, errors.NewCouldNotGetExecutionParameterFromStateError( address.Hex(), - blueprints.TransactionFeesExecutionEffortWeightsPath.String()).Error()) + path.String()).Error()) }, ) t.Run("return error if get stored returns error", @@ -205,9 +109,9 @@ func TestGetExecutionEffortWeights(t *testing.T) { func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { return nil, someErr }) - _, err := fvm.GetExecutionEffortWeights(envMock, address) + _, err := f(envMock, address) require.Error(t, err) - require.EqualError(t, err, someErr.Error()) + require.ErrorContains(t, err, someErr.Error()) }, ) t.Run("return error if get stored returns error", @@ -217,9 +121,9 @@ func TestGetExecutionEffortWeights(t *testing.T) { func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { return nil, someErr }) - _, err := fvm.GetExecutionEffortWeights(envMock, address) + _, err := f(envMock, address) require.Error(t, err) - require.EqualError(t, err, someErr.Error()) + require.ErrorContains(t, err, someErr.Error()) }, ) t.Run("no error if a dictionary is stored", @@ -228,7 +132,7 @@ func TestGetExecutionEffortWeights(t *testing.T) { func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { return cadence.NewDictionary([]cadence.KeyValuePair{}), nil }) - _, err := fvm.GetExecutionEffortWeights(envMock, address) + _, err := f(envMock, address) require.NoError(t, err) }, ) @@ -238,26 +142,27 @@ func TestGetExecutionEffortWeights(t *testing.T) { func(address common.Address, path cadence.Path, context runtime.Context) (cadence.Value, error) { return cadence.NewDictionary([]cadence.KeyValuePair{}), nil }) - weights, err := fvm.GetExecutionEffortWeights(envMock, address) + weights, err := f(envMock, address) require.NoError(t, err) - require.InDeltaMapValues(t, meter.DefaultComputationWeights, weights, 0) + require.InDeltaMapValues(t, defaultWeights, weights, 0) }, ) t.Run("return merged if some dict is stored", func(t *testing.T) { - expectedWeights := meter.ExecutionEffortWeights{} - var existingWeightKey common.ComputationKind + expectedWeights := make(map[T]uint64) + var existingWeightKey T var existingWeightValue uint64 - for k, v := range meter.DefaultComputationWeights { + for k, v := range defaultWeights { expectedWeights[k] = v } // change one existing value - for kind, u := range meter.DefaultComputationWeights { + for kind, u := range defaultWeights { existingWeightKey = kind existingWeightValue = u expectedWeights[kind] = u + 1 break } + expectedWeights[0] = 0 envMock := setupEnvMock( @@ -274,7 +179,7 @@ func TestGetExecutionEffortWeights(t *testing.T) { }), nil }) - weights, err := fvm.GetExecutionEffortWeights(envMock, address) + weights, err := f(envMock, address) require.NoError(t, err) require.InDeltaMapValues(t, expectedWeights, weights, 0) }, diff --git a/fvm/fvm.go b/fvm/fvm.go index ae92d08d945..f4edff5c50f 100644 --- a/fvm/fvm.go +++ b/fvm/fvm.go @@ -6,6 +6,9 @@ import ( "github.com/onflow/cadence" "github.com/onflow/cadence/common" + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/fvm/inspection" "github.com/onflow/flow-go/fvm/environment" "github.com/onflow/flow-go/fvm/errors" @@ -35,6 +38,7 @@ type ProcedureOutput struct { ComputationIntensities meter.MeteredComputationIntensities MemoryEstimate uint64 Err errors.CodedError + InspectionResults []inspection.Result // Output only by script. Value cadence.Value @@ -67,6 +71,56 @@ func (output *ProcedureOutput) PopulateEnvironmentValues( return nil } +func (output *ProcedureOutput) PopulateInspectionResults( + log zerolog.Logger, + ctx Context, + env environment.Environment, + storageSnapshot snapshot.StorageSnapshot, + executionSnapshot *snapshot.ExecutionSnapshot, +) { + + evts := make([]flow.Event, 0, len(output.Events)+len(output.ServiceEvents)) + evts = append(evts, output.Events...) + evts = append(evts, output.ServiceEvents...) + + log = log.With().Str("module", "transaction-inspection").Logger() + + log.Debug(). + Int("inspectors", len(ctx.Inspectors)). + Msg("running transaction inspection") + + inspectionResults := inspectProcedureResults(log, ctx, storageSnapshot, executionSnapshot, evts) + output.InspectionResults = inspectionResults +} + +func inspectProcedureResults( + log zerolog.Logger, + context Context, + storageSnapshot snapshot.StorageSnapshot, + executionSnapshot *snapshot.ExecutionSnapshot, + events []flow.Event, +) []inspection.Result { + inspectionResults := make([]inspection.Result, 0, len(context.Inspectors)) + + for i, inspector := range context.Inspectors { + log := log.With().Str("inspector", inspector.Name()).Int("inspector-num", i).Logger() + log.Debug().Msg("starting inspection") + + result, err := inspector.Inspect(log, storageSnapshot, executionSnapshot, events) + if err != nil { + log.Error().Err(err).Msg("failed to inspect procedure results") + } + + if result == nil { + log.Error().Msg("inspection results are nil") + continue + } + inspectionResults = append(inspectionResults, result) + } + + return inspectionResults +} + type ProcedureExecutor interface { Preprocess() error Execute() error @@ -237,7 +291,7 @@ func GetAccountBalance( ) { env, _ := getScriptEnvironment(ctx, storageSnapshot) - accountBalance, err := env.GetAccountBalance(common.MustBytesToAddress(address.Bytes())) + accountBalance, err := env.GetAccountBalance(common.Address(address)) if err != nil { return 0, fmt.Errorf("cannot get account balance: %w", err) @@ -256,7 +310,7 @@ func GetAccountAvailableBalance( ) { env, _ := getScriptEnvironment(ctx, storageSnapshot) - accountBalance, err := env.GetAccountAvailableBalance(common.MustBytesToAddress(address.Bytes())) + accountBalance, err := env.GetAccountAvailableBalance(common.Address(address)) if err != nil { return 0, fmt.Errorf("cannot get account balance: %w", err) @@ -302,6 +356,25 @@ func GetAccountKey( return accountKey, nil } +// GetAccountCode returns contract code by location or an error if none exists. +func GetAccountCode( + ctx Context, + location common.AddressLocation, + storageSnapshot snapshot.StorageSnapshot, +) ( + []byte, + error, +) { + scriptEnv, _ := getScriptEnvironment(ctx, storageSnapshot) + code, err := scriptEnv.GetAccountContractCode(location) + + if err != nil { + return nil, fmt.Errorf("failed to get account code (%s): %w", location.String(), err) + } + + return code, nil +} + // Helper function to initialize common components. func getScriptEnvironment( ctx Context, diff --git a/fvm/fvm_bench_test.go b/fvm/fvm_bench_test.go index 77f9c851b67..5cdfabeab08 100644 --- a/fvm/fvm_bench_test.go +++ b/fvm/fvm_bench_test.go @@ -161,18 +161,17 @@ func NewBasicBlockExecutor(tb testing.TB, chain flow.Chain, logger zerolog.Logge opts := []fvm.Option{ fvm.WithTransactionFeesEnabled(true), fvm.WithAccountStorageLimit(true), - fvm.WithChain(chain), fvm.WithLogger(logger), fvm.WithMaxStateInteractionSize(interactionLimit), fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewReusableCadenceRuntimePool( computation.ReusableCadenceRuntimePoolSize, + chain, runtime.Config{}, ), ), - fvm.WithEVMEnabled(true), } - fvmContext := fvm.NewContext(opts...) + fvmContext := fvm.NewContext(chain, opts...) collector := metrics.NewNoopCollector() tracer := trace.NewNoopTracer() @@ -237,7 +236,6 @@ func NewBasicBlockExecutor(tb testing.TB, chain flow.Chain, logger zerolog.Logge ledgerCommitter, me, prov, - nil, testutil.ProtocolStateWithSourceFixture(nil), 1) // We're interested in fvm's serial execution time require.NoError(tb, err) @@ -356,7 +354,7 @@ func (b *BasicBlockExecutor) SetupAccounts(tb testing.TB, privateKeys []flow.Acc stdlib.AccountEventAddressParameter.Identifier, ).(cadence.Address) - addr = flow.ConvertAddress(address) + addr = flow.Address(address) break } } diff --git a/fvm/fvm_blockcontext_test.go b/fvm/fvm_blockcontext_test.go index 90ed8045470..4e320b2fe71 100644 --- a/fvm/fvm_blockcontext_test.go +++ b/fvm/fvm_blockcontext_test.go @@ -98,7 +98,7 @@ func TestBlockContext_ExecuteTransaction(t *testing.T) { chain, vm := createChainAndVm(flow.Testnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -221,7 +221,7 @@ func TestBlockContext_DeployContract(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -477,7 +477,7 @@ func TestBlockContext_DeployContract(t *testing.T) { t.Run("account update with set code fails if not signed by service account if dis-allowed in the state", func(t *testing.T) { ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), fvm.WithContractDeploymentRestricted(false), ) @@ -811,7 +811,7 @@ func TestBlockContext_ExecuteTransaction_WithArguments(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -920,7 +920,7 @@ func TestBlockContext_ExecuteTransaction_GasLimit(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -1343,7 +1343,7 @@ func TestBlockContext_ExecuteScript(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -1491,7 +1491,7 @@ func TestBlockContext_GetBlockInfo(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -1652,7 +1652,7 @@ func TestBlockContext_GetAccount(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -1700,7 +1700,7 @@ func TestBlockContext_GetAccount(t *testing.T) { data, err := ccf.Decode(nil, accountCreatedEvents[0].Payload) require.NoError(t, err) - address := flow.ConvertAddress( + address := flow.Address( cadence.SearchFieldByName( data.(cadence.Event), stdlib.AccountEventAddressParameter.Identifier, @@ -1756,12 +1756,7 @@ func TestBlockContext_Random(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) header := &flow.Header{HeaderBody: flow.HeaderBody{Height: 42}} source := testutil.EntropyProviderFixture(nil) - ctx := fvm.NewContext( - fvm.WithChain(chain), - fvm.WithBlockHeader(header), - fvm.WithEntropyProvider(source), - fvm.WithCadenceLogging(true), - ) + ctx := fvm.NewContext(chain, fvm.WithBlockHeader(header), fvm.WithEntropyProvider(source), fvm.WithCadenceLogging(true)) txCode := []byte(` transaction { @@ -1868,9 +1863,7 @@ func TestBlockContext_ExecuteTransaction_CreateAccount_WithMonotonicAddresses(t chain, vm := createChainAndVm(flow.MonotonicEmulator) - ctx := fvm.NewContext( - fvm.WithChain(chain), - ) + ctx := fvm.NewContext(chain) txBodyBuilder := flow.NewTransactionBodyBuilder(). SetScript(createAccountScript). @@ -1895,7 +1888,7 @@ func TestBlockContext_ExecuteTransaction_CreateAccount_WithMonotonicAddresses(t data, err := ccf.Decode(nil, accountCreatedEvents[0].Payload) require.NoError(t, err) - address := flow.ConvertAddress( + address := flow.Address( cadence.SearchFieldByName( data.(cadence.Event), stdlib.AccountEventAddressParameter.Identifier, diff --git a/fvm/fvm_fuzz_test.go b/fvm/fvm_fuzz_test.go index 1adf52cc6e7..86f2c01f832 100644 --- a/fvm/fvm_fuzz_test.go +++ b/fvm/fvm_fuzz_test.go @@ -308,7 +308,7 @@ func bootstrapFuzzStateAndTxContext(tb testing.TB) (bootstrappedVmTest, transact data, err := ccf.Decode(nil, accountCreatedEvents[0].Payload) require.NoError(tb, err) - address = flow.ConvertAddress( + address = flow.Address( cadence.SearchFieldByName( data.(cadence.Event), stdlib.AccountEventAddressParameter.Identifier, diff --git a/fvm/fvm_test.go b/fvm/fvm_test.go index dfcff872fed..53c3716a270 100644 --- a/fvm/fvm_test.go +++ b/fvm/fvm_test.go @@ -7,13 +7,17 @@ import ( "encoding/hex" "fmt" "math" + "strconv" "strings" "testing" + "github.com/onflow/flow-core-contracts/lib/go/templates" "github.com/stretchr/testify/assert" mockery "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/onflow/flow-go/fvm/inspection" + "github.com/onflow/cadence" "github.com/onflow/cadence/common" "github.com/onflow/cadence/encoding/ccf" @@ -29,6 +33,7 @@ import ( bridge "github.com/onflow/flow-evm-bridge" flowsdk "github.com/onflow/flow-go-sdk" "github.com/onflow/flow-go-sdk/test" + nftcontracts "github.com/onflow/flow-nft/lib/go/contracts" "github.com/onflow/flow-go/engine/execution/testutil" exeUtils "github.com/onflow/flow-go/engine/execution/utils" @@ -40,7 +45,6 @@ import ( envMock "github.com/onflow/flow-go/fvm/environment/mock" "github.com/onflow/flow-go/fvm/errors" "github.com/onflow/flow-go/fvm/evm/events" - "github.com/onflow/flow-go/fvm/evm/handler" "github.com/onflow/flow-go/fvm/evm/types" "github.com/onflow/flow-go/fvm/meter" reusableRuntime "github.com/onflow/flow-go/fvm/runtime" @@ -57,10 +61,18 @@ import ( type vmTest struct { bootstrapOptions []fvm.BootstrapProcedureOption contextOptions []fvm.Option + chain flow.Chain } func newVMTest() vmTest { - return vmTest{} + return vmTest{ + chain: flow.Testnet.Chain(), + } +} + +func (vmt vmTest) withChain(chain flow.Chain) vmTest { + vmt.chain = chain + return vmt } func (vmt vmTest) withBootstrapProcedureOptions(opts ...fvm.BootstrapProcedureOption) vmTest { @@ -83,12 +95,11 @@ func (vmt vmTest) run( return func(t *testing.T) { baseOpts := []fvm.Option{ // default chain is Testnet - fvm.WithChain(flow.Testnet.Chain()), fvm.WithEntropyProvider(testutil.EntropyProviderFixture(nil)), } opts := append(baseOpts, vmt.contextOptions...) - ctx := fvm.NewContext(opts...) + ctx := fvm.NewContext(vmt.chain, opts...) chain := ctx.Chain vm := fvm.NewVirtualMachine() @@ -119,13 +130,10 @@ func (vmt vmTest) bootstrapWith( bootstrap func(vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) (snapshot.SnapshotTree, error), ) (bootstrappedVmTest, error) { - baseOpts := []fvm.Option{ - // default chain is Testnet - fvm.WithChain(flow.Testnet.Chain()), - } + var baseOpts []fvm.Option opts := append(baseOpts, vmt.contextOptions...) - ctx := fvm.NewContext(opts...) + ctx := fvm.NewContext(vmt.chain, opts...) chain := ctx.Chain vm := fvm.NewVirtualMachine() @@ -178,7 +186,7 @@ func TestHashing(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -430,7 +438,7 @@ func TestWithServiceAccount(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctxA := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), ) @@ -479,7 +487,7 @@ func TestEventLimits(t *testing.T) { chain, vm := createChainAndVm(flow.Mainnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), ) @@ -1020,7 +1028,7 @@ func TestTransactionFeeDeduction(t *testing.T) { data, err := ccf.Decode(nil, accountCreatedEvents[0].Payload) require.NoError(t, err) - address := flow.ConvertAddress( + address := flow.Address( cadence.SearchFieldByName( data.(cadence.Event), cadenceStdlib.AccountEventAddressParameter.Identifier, @@ -1099,33 +1107,37 @@ func TestTransactionFeeDeduction(t *testing.T) { } for i, tc := range testCases { - t.Run(fmt.Sprintf("Transaction Fees %d: %s", i, tc.name), newVMTest().withBootstrapProcedureOptions( - fvm.WithTransactionFee(fvm.DefaultTransactionFees), - fvm.WithExecutionMemoryLimit(math.MaxUint64), - fvm.WithExecutionEffortWeights(environment.MainnetExecutionEffortWeights), - fvm.WithExecutionMemoryWeights(meter.DefaultMemoryWeights), - ).withContextOptions( - fvm.WithTransactionFeesEnabled(true), - fvm.WithChain(chain), - ).run( + t.Run(fmt.Sprintf("Transaction Fees %d: %s", i, tc.name), newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithTransactionFee(fvm.DefaultTransactionFees), + fvm.WithExecutionMemoryLimit(math.MaxUint64), + fvm.WithExecutionEffortWeights(environment.MainnetExecutionEffortWeights), + fvm.WithExecutionMemoryWeights(meter.DefaultMemoryWeights), + ). + withContextOptions( + fvm.WithTransactionFeesEnabled(true), + ).run( runTx(tc)), ) } for i, tc := range testCasesWithStorageEnabled { - t.Run(fmt.Sprintf("Transaction Fees with storage %d: %s", i, tc.name), newVMTest().withBootstrapProcedureOptions( - fvm.WithTransactionFee(fvm.DefaultTransactionFees), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithExecutionMemoryLimit(math.MaxUint64), - fvm.WithExecutionEffortWeights(environment.MainnetExecutionEffortWeights), - fvm.WithExecutionMemoryWeights(meter.DefaultMemoryWeights), - ).withContextOptions( - fvm.WithTransactionFeesEnabled(true), - fvm.WithAccountStorageLimit(true), - fvm.WithChain(chain), - ).run( + t.Run(fmt.Sprintf("Transaction Fees with storage %d: %s", i, tc.name), newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithTransactionFee(fvm.DefaultTransactionFees), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithExecutionMemoryLimit(math.MaxUint64), + fvm.WithExecutionEffortWeights(environment.MainnetExecutionEffortWeights), + fvm.WithExecutionMemoryWeights(meter.DefaultMemoryWeights), + ). + withContextOptions( + fvm.WithTransactionFeesEnabled(true), + fvm.WithAccountStorageLimit(true), + ).run( runTx(tc)), ) } @@ -1137,23 +1149,23 @@ func TestSettingExecutionWeights(t *testing.T) { // change the chain so that the metering settings are read from the service account chain := flow.Emulator.Chain() - t.Run("transaction should fail with high weights", newVMTest().withBootstrapProcedureOptions( - - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithExecutionEffortWeights( - meter.ExecutionEffortWeights{ - common.ComputationKindLoop: 100_000 << meter.MeterExecutionInternalPrecisionBytes, - }, - ), - ).withContextOptions( - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + t.Run("transaction should fail with high weights", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithExecutionEffortWeights( + meter.ExecutionEffortWeights{ + common.ComputationKindLoop: 100_000 << meter.MeterExecutionInternalPrecisionBytes, + }, + ), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(` + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` transaction { prepare(signer: &Account) { var a = 0 @@ -1163,25 +1175,25 @@ func TestSettingExecutionWeights(t *testing.T) { } } `)). - SetProposalKey(chain.ServiceAddress(), 0, 0). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()) + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) - err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) - require.NoError(t, err) + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) - require.True(t, errors.IsComputationLimitExceededError(output.Err)) - }, - )) + require.True(t, errors.IsComputationLimitExceededError(output.Err)) + }, + )) memoryWeights := make(map[common.MemoryKind]uint64) for k, v := range meter.DefaultMemoryWeights { @@ -1191,136 +1203,143 @@ func TestSettingExecutionWeights(t *testing.T) { const highWeight = 20_000_000_000 memoryWeights[common.MemoryKindIntegerExpression] = highWeight - t.Run("normal transactions should fail with high memory weights", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithExecutionMemoryWeights( - memoryWeights, - ), - ).withContextOptions( - fvm.WithMemoryLimit(10_000_000_000), - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - // Create an account private key. - privateKeys, err := testutil.GenerateAccountPrivateKeys(1) - require.NoError(t, err) + t.Run("normal transactions should fail with high memory weights", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithExecutionMemoryWeights( + memoryWeights, + ), + ). + withContextOptions( + fvm.WithMemoryLimit(10_000_000_000), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + // Create an account private key. + privateKeys, err := testutil.GenerateAccountPrivateKeys(1) + require.NoError(t, err) - // Bootstrap a ledger, creating accounts with the provided private - // keys and the root account. - snapshotTree, accounts, err := testutil.CreateAccounts( - vm, - snapshotTree, - privateKeys, - chain) - require.NoError(t, err) + // Bootstrap a ledger, creating accounts with the provided private + // keys and the root account. + snapshotTree, accounts, err := testutil.CreateAccounts( + vm, + snapshotTree, + privateKeys, + chain) + require.NoError(t, err) - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(` + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` transaction { prepare(signer: &Account) { var a = 1 } } `)). - SetProposalKey(accounts[0], 0, 0). - AddAuthorizer(accounts[0]). - SetPayer(accounts[0]) + SetProposalKey(accounts[0], 0, 0). + AddAuthorizer(accounts[0]). + SetPayer(accounts[0]) - err = testutil.SignTransaction(txBodyBuilder, accounts[0], privateKeys[0], 0) - require.NoError(t, err) + err = testutil.SignTransaction(txBodyBuilder, accounts[0], privateKeys[0], 0) + require.NoError(t, err) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) - require.Greater(t, output.MemoryEstimate, uint64(highWeight)) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) + require.Greater(t, output.MemoryEstimate, uint64(highWeight)) - require.True(t, errors.IsMemoryLimitExceededError(output.Err)) - }, - )) + require.True(t, errors.IsMemoryLimitExceededError(output.Err)) + }, + )) - t.Run("service account transactions should not fail with high memory weights", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithExecutionMemoryWeights( - memoryWeights, - ), - ).withContextOptions( - fvm.WithMemoryLimit(10_000_000_000), - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + t.Run("service account transactions should not fail with high memory weights", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithExecutionMemoryWeights( + memoryWeights, + ), + ). + withContextOptions( + fvm.WithMemoryLimit(10_000_000_000), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(` + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` transaction { prepare(signer: &Account) { var a = 1 } } `)). - SetProposalKey(chain.ServiceAddress(), 0, 0). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()) + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) - err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) - require.NoError(t, err) + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) - require.Greater(t, output.MemoryEstimate, uint64(highWeight)) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) + require.Greater(t, output.MemoryEstimate, uint64(highWeight)) - require.NoError(t, output.Err) - }, - )) + require.NoError(t, output.Err) + }, + )) memoryWeights = make(map[common.MemoryKind]uint64) for k, v := range meter.DefaultMemoryWeights { memoryWeights[k] = v } memoryWeights[common.MemoryKindBreakStatement] = 1_000_000 - t.Run("transaction should fail with low memory limit (set in the state)", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithExecutionMemoryLimit( - 100_000_000, - ), - fvm.WithExecutionMemoryWeights( - memoryWeights, - ), - ).withContextOptions( - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - privateKeys, err := testutil.GenerateAccountPrivateKeys(1) - require.NoError(t, err) + t.Run("transaction should fail with low memory limit (set in the state)", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithExecutionMemoryLimit( + 100_000_000, + ), + fvm.WithExecutionMemoryWeights( + memoryWeights, + ), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + privateKeys, err := testutil.GenerateAccountPrivateKeys(1) + require.NoError(t, err) - snapshotTree, accounts, err := testutil.CreateAccounts( - vm, - snapshotTree, - privateKeys, - chain) - require.NoError(t, err) + snapshotTree, accounts, err := testutil.CreateAccounts( + vm, + snapshotTree, + privateKeys, + chain) + require.NoError(t, err) - // This transaction is specially designed to use a lot of breaks - // as the weight for breaks is much higher than usual. - // putting a `while true {break}` in a loop does not use the same amount of memory. - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(` + // This transaction is specially designed to use a lot of breaks + // as the weight for breaks is much higher than usual. + // putting a `while true {break}` in a loop does not use the same amount of memory. + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` transaction { prepare(signer: &Account) { while true {break};while true {break};while true {break};while true {break};while true {break}; @@ -1347,311 +1366,294 @@ func TestSettingExecutionWeights(t *testing.T) { } `)) - err = testutil.SignTransaction(txBodyBuilder, accounts[0], privateKeys[0], 0) - require.NoError(t, err) - - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + err = testutil.SignTransaction(txBodyBuilder, accounts[0], privateKeys[0], 0) + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) - // There are 100 breaks and each break uses 1_000_000 memory - require.Greater(t, output.MemoryEstimate, uint64(100_000_000)) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - require.True(t, errors.IsMemoryLimitExceededError(output.Err)) - }, - )) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) + // There are 100 breaks and each break uses 1_000_000 memory + require.Greater(t, output.MemoryEstimate, uint64(100_000_000)) - t.Run("transaction should fail if create account weight is high", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithExecutionEffortWeights( - meter.ExecutionEffortWeights{ - environment.ComputationKindCreateAccount: (fvm.DefaultComputationLimit + 1) << meter.MeterExecutionInternalPrecisionBytes, + require.True(t, errors.IsMemoryLimitExceededError(output.Err)) }, - ), - ).withContextOptions( - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(` + )) + + t.Run("transaction should fail if create account weight is high", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithExecutionEffortWeights( + meter.ExecutionEffortWeights{ + environment.ComputationKindCreateAccount: (fvm.DefaultComputationLimit + 1) << meter.MeterExecutionInternalPrecisionBytes, + }, + ), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` transaction { prepare(signer: auth(BorrowValue) &Account) { Account(payer: signer) } } `)). - SetProposalKey(chain.ServiceAddress(), 0, 0). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()) - - err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) - require.NoError(t, err) + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - require.True(t, errors.IsComputationLimitExceededError(output.Err)) - }, - )) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) - t.Run("transaction should fail if create account weight is high", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithExecutionEffortWeights( - meter.ExecutionEffortWeights{ - environment.ComputationKindCreateAccount: 100_000_000 << meter.MeterExecutionInternalPrecisionBytes, + require.True(t, errors.IsComputationLimitExceededError(output.Err)) }, - ), - ).withContextOptions( - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + )) - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(` + t.Run("transaction should fail if create account weight is high", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithExecutionEffortWeights( + meter.ExecutionEffortWeights{ + environment.ComputationKindCreateAccount: 100_000_000 << meter.MeterExecutionInternalPrecisionBytes, + }, + ), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` transaction { prepare(signer: auth(BorrowValue) &Account) { Account(payer: signer) } } `)). - SetProposalKey(chain.ServiceAddress(), 0, 0). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()) - - err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) - require.NoError(t, err) + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - require.True(t, errors.IsComputationLimitExceededError(output.Err)) - }, - )) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) - t.Run("transaction should fail if create account weight is high", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithExecutionEffortWeights( - meter.ExecutionEffortWeights{ - environment.ComputationKindCreateAccount: 100_000_000 << meter.MeterExecutionInternalPrecisionBytes, + require.True(t, errors.IsComputationLimitExceededError(output.Err)) }, - ), - ).withContextOptions( - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(` + )) + + t.Run("transaction should fail if create account weight is high", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithExecutionEffortWeights( + meter.ExecutionEffortWeights{ + environment.ComputationKindCreateAccount: 100_000_000 << meter.MeterExecutionInternalPrecisionBytes, + }, + ), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` transaction { prepare(signer: auth(BorrowValue) &Account) { Account(payer: signer) } } `)). - SetProposalKey(chain.ServiceAddress(), 0, 0). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()) - - err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) - require.NoError(t, err) + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - require.True(t, errors.IsComputationLimitExceededError(output.Err)) - }, - )) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) - t.Run("transaction should not use up more computation that the transaction body itself", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithTransactionFee(fvm.DefaultTransactionFees), - fvm.WithExecutionEffortWeights( - meter.ExecutionEffortWeights{ - common.ComputationKindStatement: 0, - common.ComputationKindLoop: 1 << meter.MeterExecutionInternalPrecisionBytes, - common.ComputationKindFunctionInvocation: 0, + require.True(t, errors.IsComputationLimitExceededError(output.Err)) }, - ), - ).withContextOptions( - fvm.WithAccountStorageLimit(true), - fvm.WithTransactionFeesEnabled(true), - fvm.WithMemoryLimit(math.MaxUint64), - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - // Use the maximum amount of computation so that the transaction still passes. - loops := uint64(996) - executionEffortNeededToCheckStorage := uint64(1) - maxExecutionEffort := uint64(997) - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte( - fmt.Sprintf(` - transaction() { - prepare(signer: &Account) { - var i = 0 - while i < %d { - i = i + 1 - } - } - - execute{} - } - `, - loops, - ), - )). - SetProposalKey(chain.ServiceAddress(), 0, 0). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()). - SetComputeLimit(maxExecutionEffort) + )) - err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) - require.NoError(t, err) + t.Run("transaction should not use up more computation that the transaction body itself", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithTransactionFee(fvm.DefaultTransactionFees), + fvm.WithExecutionEffortWeights( + meter.ExecutionEffortWeights{ + common.ComputationKindStatement: 0, + common.ComputationKindLoop: 1 << meter.MeterExecutionInternalPrecisionBytes, + common.ComputationKindFunctionInvocation: 0, + }, + ), + ). + withContextOptions( + fvm.WithAccountStorageLimit(true), + fvm.WithTransactionFeesEnabled(true), + fvm.WithMemoryLimit(math.MaxUint64), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + // Use the maximum amount of computation so that the transaction still passes. + loops := uint64(996) + executionEffortNeededToCheckStorage := uint64(1) + maxExecutionEffort := uint64(997) + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(fmt.Sprintf(` + transaction() {prepare(signer: &Account){var i=0; while i < %d {i = i +1 } } execute{}} + `, loops))). + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()). + SetComputeLimit(maxExecutionEffort) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) - executionSnapshot, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) - require.NoError(t, output.Err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - snapshotTree = snapshotTree.Append(executionSnapshot) + executionSnapshot, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) + require.NoError(t, output.Err) - // expected computation used is number of loops + 1 (from the storage limit check). - require.Equal(t, loops+executionEffortNeededToCheckStorage, output.ComputationUsed) + snapshotTree = snapshotTree.Append(executionSnapshot) - // increasing the number of loops should fail the transaction. - loops = loops + 1 - txBodyBuilder = flow.NewTransactionBodyBuilder(). - SetScript([]byte( - fmt.Sprintf(` - transaction() { - prepare(signer: &Account) { - var i = 0 - while i < %d { - i = i + 1 - } - } + // expected computation used is number of loops + 1 (from the storage limit check). + require.Equal(t, loops+executionEffortNeededToCheckStorage, output.ComputationUsed) - execute{} - } - `, - loops, - ), - )). - SetProposalKey(chain.ServiceAddress(), 0, 1). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()). - SetComputeLimit(maxExecutionEffort) + // increasing the number of loops should fail the transaction. + loops = loops + 1 + txBodyBuilder = flow.NewTransactionBodyBuilder(). + SetScript([]byte(fmt.Sprintf(` + transaction() {prepare(signer: &Account){var i=0; while i < %d {i = i +1 } } execute{}} + `, loops))). + SetProposalKey(chain.ServiceAddress(), 0, 1). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()). + SetComputeLimit(maxExecutionEffort) - err = testutil.SignTransactionAsServiceAccount(txBodyBuilder, 1, chain) - require.NoError(t, err) + err = testutil.SignTransactionAsServiceAccount(txBodyBuilder, 1, chain) + require.NoError(t, err) - txBody, err = txBodyBuilder.Build() - require.NoError(t, err) + txBody, err = txBodyBuilder.Build() + require.NoError(t, err) - _, output, err = vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) + _, output, err = vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) - require.ErrorContains(t, output.Err, "computation exceeds limit (997)") - // expected computation used is still number of loops + 1 (from the storage limit check). - require.Equal(t, loops+executionEffortNeededToCheckStorage, output.ComputationUsed) + require.ErrorContains(t, output.Err, "computation exceeds limit (997)") + // expected computation used is still number of loops + 1 (from the storage limit check). + require.Equal(t, loops+executionEffortNeededToCheckStorage, output.ComputationUsed) - for _, event := range output.Events { - // the fee deduction event should only contain the max gas worth of execution effort. - if strings.Contains(string(event.Type), "FlowFees.FeesDeducted") { - v, err := ccf.Decode(nil, event.Payload) - require.NoError(t, err) + for _, event := range output.Events { + // the fee deduction event should only contain the max gas worth of execution effort. + if strings.Contains(string(event.Type), "FlowFees.FeesDeducted") { + v, err := ccf.Decode(nil, event.Payload) + require.NoError(t, err) - ev := v.(cadence.Event) + ev := v.(cadence.Event) - actualExecutionEffort := cadence.SearchFieldByName(ev, "executionEffort") + actualExecutionEffort := cadence.SearchFieldByName(ev, "executionEffort") - require.Equal( - t, - maxExecutionEffort, - uint64(actualExecutionEffort.(cadence.UFix64)), - ) + require.Equal( + t, + maxExecutionEffort, + uint64(actualExecutionEffort.(cadence.UFix64)), + ) + } } - } - unittest.EnsureEventsIndexSeq(t, output.Events, chain.ChainID()) - }, - )) - - t.Run("transaction with more accounts touched uses more computation", newVMTest().withBootstrapProcedureOptions( - fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), - fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), - fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), - fvm.WithTransactionFee(fvm.DefaultTransactionFees), - fvm.WithExecutionEffortWeights( - meter.ExecutionEffortWeights{ - common.ComputationKindStatement: 0, - // only count loops - // the storage check has a loop - common.ComputationKindLoop: 1 << meter.MeterExecutionInternalPrecisionBytes, - common.ComputationKindFunctionInvocation: 0, + unittest.EnsureEventsIndexSeq(t, output.Events, chain.ChainID()) }, - ), - ).withContextOptions( - fvm.WithAccountStorageLimit(true), - fvm.WithTransactionFeesEnabled(true), - fvm.WithMemoryLimit(math.MaxUint64), - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - // Create an account private key. - privateKeys, err := testutil.GenerateAccountPrivateKeys(5) - require.NoError(t, err) + )) - // Bootstrap a ledger, creating accounts with the provided - // private keys and the root account. - snapshotTree, accounts, err := testutil.CreateAccounts( - vm, - snapshotTree, - privateKeys, - chain) - require.NoError(t, err) + t.Run("transaction with more accounts touched uses more computation", newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithTransactionFee(fvm.DefaultTransactionFees), + fvm.WithExecutionEffortWeights( + meter.ExecutionEffortWeights{ + common.ComputationKindStatement: 0, + // only count loops + // the storage check has a loop + common.ComputationKindLoop: 1 << meter.MeterExecutionInternalPrecisionBytes, + common.ComputationKindFunctionInvocation: 0, + }, + ), + ). + withContextOptions( + fvm.WithAccountStorageLimit(true), + fvm.WithTransactionFeesEnabled(true), + fvm.WithMemoryLimit(math.MaxUint64), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + // Create an account private key. + privateKeys, err := testutil.GenerateAccountPrivateKeys(5) + require.NoError(t, err) - sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + // Bootstrap a ledger, creating accounts with the provided + // private keys and the root account. + snapshotTree, accounts, err := testutil.CreateAccounts( + vm, + snapshotTree, + privateKeys, + chain) + require.NoError(t, err) - // create a transaction without loops so only the looping in the storage check is counted. - txBodyBuilder := flow.NewTransactionBodyBuilder(). - SetScript([]byte(fmt.Sprintf(` + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + + // create a transaction without loops so only the looping in the storage check is counted. + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(fmt.Sprintf(` import FungibleToken from 0x%s import FlowToken from 0x%s @@ -1692,36 +1694,36 @@ func TestSettingExecutionWeights(t *testing.T) { destroy self.sentVault } }`, - sc.FungibleToken.Address, - sc.FlowToken.Address, - accounts[0].HexWithPrefix(), - accounts[1].HexWithPrefix(), - accounts[2].HexWithPrefix(), - accounts[3].HexWithPrefix(), - accounts[4].HexWithPrefix(), - ))). - SetProposalKey(chain.ServiceAddress(), 0, 0). - AddAuthorizer(chain.ServiceAddress()). - SetPayer(chain.ServiceAddress()) + sc.FungibleToken.Address, + sc.FlowToken.Address, + accounts[0].HexWithPrefix(), + accounts[1].HexWithPrefix(), + accounts[2].HexWithPrefix(), + accounts[3].HexWithPrefix(), + accounts[4].HexWithPrefix(), + ))). + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) - err = testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) - require.NoError(t, err) + err = testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) - txBody, err := txBodyBuilder.Build() - require.NoError(t, err) + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) - _, output, err := vm.Run( - ctx, - fvm.Transaction(txBody, 0), - snapshotTree) - require.NoError(t, err) - require.NoError(t, output.Err) + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + require.NoError(t, err) + require.NoError(t, output.Err) - // The storage check should loop once for each of the five accounts created + - // once for the service account - require.Equal(t, uint64(5+1), output.ComputationUsed) - }, - )) + // The storage check should loop once for each of the five accounts created + + // once for the service account + require.Equal(t, uint64(5+1), output.ComputationUsed) + }, + )) } func TestStorageUsed(t *testing.T) { @@ -1730,7 +1732,7 @@ func TestStorageUsed(t *testing.T) { chain, vm := createChainAndVm(flow.Testnet) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -1841,7 +1843,7 @@ func TestEnforcingComputationLimit(t *testing.T) { `, payerIsServAcc: true, ok: true, - expCompUsed: ifCompile[uint64](13, 11), + expCompUsed: ifCompile[uint64](13, 12), }, { name: "some for-in loop iterations", @@ -1850,18 +1852,14 @@ func TestEnforcingComputationLimit(t *testing.T) { `, payerIsServAcc: false, ok: true, - expCompUsed: ifCompile[uint64](6, 4), + expCompUsed: ifCompile[uint64](6, 5), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - ctx := fvm.NewContext( - fvm.WithChain(chain), - fvm.WithAuthorizationChecksEnabled(false), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - ) + ctx := fvm.NewContext(chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false)) script := []byte( fmt.Sprintf( @@ -2353,55 +2351,61 @@ func TestScriptExecutionLimit(t *testing.T) { } t.Run("Exceeding computation limit", - newVMTest().withBootstrapProcedureOptions( - bootstrapProcedureOptions..., - ).withContextOptions( - fvm.WithTransactionFeesEnabled(true), - fvm.WithAccountStorageLimit(true), - fvm.WithComputationLimit(10000), - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - scriptCtx := fvm.NewContextFromParent(ctx) + newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + bootstrapProcedureOptions..., + ). + withContextOptions( + fvm.WithTransactionFeesEnabled(true), + fvm.WithAccountStorageLimit(true), + fvm.WithComputationLimit(10000), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + scriptCtx := fvm.NewContextFromParent(ctx) - _, output, err := vm.Run(scriptCtx, script, snapshotTree) - require.NoError(t, err) - require.Error(t, output.Err) - require.True(t, errors.IsComputationLimitExceededError(output.Err)) - require.ErrorContains(t, output.Err, "computation exceeds limit (10000)") - require.GreaterOrEqual(t, output.ComputationUsed, uint64(10000)) - if cadence_vm.DefaultEnabled { - require.GreaterOrEqual(t, output.MemoryEstimate, uint64(540000979)) - } else { - require.GreaterOrEqual(t, output.MemoryEstimate, uint64(456687216)) - } - }, - ), + _, output, err := vm.Run(scriptCtx, script, snapshotTree) + require.NoError(t, err) + require.Error(t, output.Err) + require.True(t, errors.IsComputationLimitExceededError(output.Err)) + require.ErrorContains(t, output.Err, "computation exceeds limit (10000)") + require.GreaterOrEqual(t, output.ComputationUsed, uint64(10000)) + if cadence_vm.DefaultEnabled { + require.GreaterOrEqual(t, output.MemoryEstimate, uint64(540000979)) + } else { + require.GreaterOrEqual(t, output.MemoryEstimate, uint64(456687216)) + } + }, + ), ) t.Run("Sufficient computation limit", - newVMTest().withBootstrapProcedureOptions( - bootstrapProcedureOptions..., - ).withContextOptions( - fvm.WithTransactionFeesEnabled(true), - fvm.WithAccountStorageLimit(true), - fvm.WithComputationLimit(25000), - fvm.WithChain(chain), - ).run( - func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { - scriptCtx := fvm.NewContextFromParent(ctx) + newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + bootstrapProcedureOptions..., + ). + withContextOptions( + fvm.WithTransactionFeesEnabled(true), + fvm.WithAccountStorageLimit(true), + fvm.WithComputationLimit(25000), + ). + run( + func(t *testing.T, vm fvm.VM, chain flow.Chain, ctx fvm.Context, snapshotTree snapshot.SnapshotTree) { + scriptCtx := fvm.NewContextFromParent(ctx) - _, output, err := vm.Run(scriptCtx, script, snapshotTree) - require.NoError(t, err) - require.NoError(t, output.Err) - require.GreaterOrEqual(t, output.ComputationUsed, uint64(17955)) - if cadence_vm.DefaultEnabled { - require.GreaterOrEqual(t, output.MemoryEstimate, uint64(969617812)) - } else { - require.GreaterOrEqual(t, output.MemoryEstimate, uint64(984017413)) - } - }, - ), + _, output, err := vm.Run(scriptCtx, script, snapshotTree) + require.NoError(t, err) + require.NoError(t, output.Err) + require.GreaterOrEqual(t, output.ComputationUsed, uint64(17955)) + if cadence_vm.DefaultEnabled { + require.GreaterOrEqual(t, output.MemoryEstimate, uint64(969617812)) + } else { + require.GreaterOrEqual(t, output.MemoryEstimate, uint64(984017413)) + } + }, + ), ) } @@ -2502,7 +2506,7 @@ func TestInteractionLimit(t *testing.T) { return snapshotTree, err } - address = flow.ConvertAddress( + address = flow.Address( cadence.SearchFieldByName( data.(cadence.Event), cadenceStdlib.AccountEventAddressParameter.Identifier, @@ -2621,6 +2625,8 @@ func TestCapabilityControllers(t *testing.T) { fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewReusableCadenceRuntimePool( 1, + // TODO(JanezP): remove the need to initialize NewReusableCadenceRuntimePool like this + flow.Testnet.Chain(), runtime.Config{}, ), ), @@ -2669,7 +2675,6 @@ func TestCapabilityControllers(t *testing.T) { } func TestStorageIterationWithBrokenValues(t *testing.T) { - t.Parallel() newVMTest(). @@ -2678,6 +2683,8 @@ func TestStorageIterationWithBrokenValues(t *testing.T) { fvm.WithReusableCadenceRuntimePool( reusableRuntime.NewReusableCadenceRuntimePool( 1, + // TODO(JanezP): remove the need to initialize NewReusableCadenceRuntimePool like this + flow.Testnet.Chain(), runtime.Config{}, ), ), @@ -3020,12 +3027,12 @@ func TestFlowCallbackScheduler(t *testing.T) { ctxOpts := []fvm.Option{ fvm.WithScheduledTransactionsEnabled(true), - // use localnet to ensure the scheduled transaction executor account - // is created during bootstrap, since testnet is manually created - fvm.WithChain(flow.Localnet.Chain()), } newVMTest(). + // use localnet to ensure the scheduled transaction executor account + // is created during bootstrap, since testnet is manually created + withChain(flow.Localnet.Chain()). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3102,19 +3109,17 @@ func TestEVM(t *testing.T) { block1.ToHeader(), ).Return(block1.ToHeader(), nil) - ctxOpts := []fvm.Option{ - // default is testnet, but testnet has a special EVM storage contract location - // so we have to use emulator here so that the EVM storage contract is deployed - // to the 5th address - fvm.WithChain(flow.Emulator.Chain()), - fvm.WithEVMEnabled(true), + ctxOpts := []fvm.Option{ fvm.WithBlocks(blocks), fvm.WithBlockHeader(block1.ToHeader()), fvm.WithCadenceLogging(true), } t.Run("successful transaction", newVMTest(). - withBootstrapProcedureOptions(fvm.WithSetupEVMEnabled(true)). + // default is testnet, but testnet has a special EVM storage contract location + // so we have to use emulator here so that the EVM storage contract is deployed + // to the 5th address + withChain(flow.Emulator.Chain()). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3160,7 +3165,7 @@ func TestEVM(t *testing.T) { ) t.Run("successful script", newVMTest(). - withBootstrapProcedureOptions(fvm.WithSetupEVMEnabled(true)). + withChain(flow.Emulator.Chain()). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3196,7 +3201,10 @@ func TestEVM(t *testing.T) { // this test makes sure the execution error is correctly handled and returned as a correct type t.Run("execution reverted", newVMTest(). - withBootstrapProcedureOptions(fvm.WithSetupEVMEnabled(true)). + // default is testnet, but testnet has a special EVM storage contract location + // so we have to use emulator here so that the EVM storage contract is deployed + // to the 5th address + withChain(flow.Emulator.Chain()). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3234,7 +3242,10 @@ func TestEVM(t *testing.T) { // this test makes sure the EVM error is correctly returned as an error and has a correct type // we have implemented a snapshot wrapper to return an error from the EVM t.Run("internal evm error handling", newVMTest(). - withBootstrapProcedureOptions(fvm.WithSetupEVMEnabled(true)). + // default is testnet, but testnet has a special EVM storage contract location + // so we have to use emulator here so that the EVM storage contract is deployed + // to the 5th address + withChain(flow.Emulator.Chain()). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3289,7 +3300,10 @@ func TestEVM(t *testing.T) { ) t.Run("deploy contract code", newVMTest(). - withBootstrapProcedureOptions(fvm.WithSetupEVMEnabled(true)). + // default is testnet, but testnet has a special EVM storage contract location + // so we have to use emulator here so that the EVM storage contract is deployed + // to the 5th address + withChain(flow.Emulator.Chain()). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3339,7 +3353,6 @@ func TestEVM(t *testing.T) { txBody, err := txBodyBuilder.Build() require.NoError(t, err) - ctx = fvm.NewContextFromParent(ctx, fvm.WithEVMEnabled(true)) _, output, err := vm.Run( ctx, fvm.Transaction(txBody, 0), @@ -3397,11 +3410,6 @@ func TestVMBridge(t *testing.T) { ).Return(block1.ToHeader(), nil) ctxOpts := []fvm.Option{ - // default is testnet, but testnet has a special EVM storage contract location - // so we have to use emulator here so that the EVM storage contract is deployed - // to the 5th address - fvm.WithChain(flow.Emulator.Chain()), - fvm.WithEVMEnabled(true), fvm.WithBlocks(blocks), fvm.WithBlockHeader(block1.ToHeader()), fvm.WithCadenceLogging(true), @@ -3409,7 +3417,11 @@ func TestVMBridge(t *testing.T) { } t.Run("successful FT Type Onboarding and Bridging", newVMTest(). - withBootstrapProcedureOptions(fvm.WithSetupEVMEnabled(true), fvm.WithSetupVMBridgeEnabled(true)). + // default is testnet, but testnet has a special EVM storage contract location + // so we have to use emulator here so that the EVM storage contract is deployed + // to the 5th address + withChain(flow.Emulator.Chain()). + withBootstrapProcedureOptions(fvm.WithSetupVMBridgeEnabled(true)). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3424,30 +3436,32 @@ func TestVMBridge(t *testing.T) { env := sc.AsTemplateEnv() bridgeEnv := bridge.Environment{ - CrossVMNFTAddress: env.ServiceAccountAddress, - CrossVMTokenAddress: env.ServiceAccountAddress, - FlowEVMBridgeHandlerInterfacesAddress: env.ServiceAccountAddress, - IBridgePermissionsAddress: env.ServiceAccountAddress, - ICrossVMAddress: env.ServiceAccountAddress, - ICrossVMAssetAddress: env.ServiceAccountAddress, - IEVMBridgeNFTMinterAddress: env.ServiceAccountAddress, - IEVMBridgeTokenMinterAddress: env.ServiceAccountAddress, - IFlowEVMNFTBridgeAddress: env.ServiceAccountAddress, - IFlowEVMTokenBridgeAddress: env.ServiceAccountAddress, - FlowEVMBridgeAddress: env.ServiceAccountAddress, - FlowEVMBridgeAccessorAddress: env.ServiceAccountAddress, - FlowEVMBridgeConfigAddress: env.ServiceAccountAddress, - FlowEVMBridgeHandlersAddress: env.ServiceAccountAddress, - FlowEVMBridgeNFTEscrowAddress: env.ServiceAccountAddress, - FlowEVMBridgeResolverAddress: env.ServiceAccountAddress, - FlowEVMBridgeTemplatesAddress: env.ServiceAccountAddress, - FlowEVMBridgeTokenEscrowAddress: env.ServiceAccountAddress, - FlowEVMBridgeUtilsAddress: env.ServiceAccountAddress, - ArrayUtilsAddress: env.ServiceAccountAddress, - ScopedFTProvidersAddress: env.ServiceAccountAddress, - SerializeAddress: env.ServiceAccountAddress, - SerializeMetadataAddress: env.ServiceAccountAddress, - StringUtilsAddress: env.ServiceAccountAddress, + CrossVMNFTAddress: env.ServiceAccountAddress, + CrossVMTokenAddress: env.ServiceAccountAddress, + FlowEVMBridgeHandlerInterfacesAddress: env.ServiceAccountAddress, + IBridgePermissionsAddress: env.ServiceAccountAddress, + ICrossVMAddress: env.ServiceAccountAddress, + ICrossVMAssetAddress: env.ServiceAccountAddress, + IEVMBridgeNFTMinterAddress: env.ServiceAccountAddress, + IEVMBridgeTokenMinterAddress: env.ServiceAccountAddress, + IFlowEVMNFTBridgeAddress: env.ServiceAccountAddress, + IFlowEVMTokenBridgeAddress: env.ServiceAccountAddress, + FlowEVMBridgeAddress: env.ServiceAccountAddress, + FlowEVMBridgeAccessorAddress: env.ServiceAccountAddress, + FlowEVMBridgeCustomAssociationTypesAddress: env.ServiceAccountAddress, + FlowEVMBridgeCustomAssociationsAddress: env.ServiceAccountAddress, + FlowEVMBridgeConfigAddress: env.ServiceAccountAddress, + FlowEVMBridgeHandlersAddress: env.ServiceAccountAddress, + FlowEVMBridgeNFTEscrowAddress: env.ServiceAccountAddress, + FlowEVMBridgeResolverAddress: env.ServiceAccountAddress, + FlowEVMBridgeTemplatesAddress: env.ServiceAccountAddress, + FlowEVMBridgeTokenEscrowAddress: env.ServiceAccountAddress, + FlowEVMBridgeUtilsAddress: env.ServiceAccountAddress, + ArrayUtilsAddress: env.ServiceAccountAddress, + ScopedFTProvidersAddress: env.ServiceAccountAddress, + SerializeAddress: env.ServiceAccountAddress, + SerializeMetadataAddress: env.ServiceAccountAddress, + StringUtilsAddress: env.ServiceAccountAddress, } // Create an account private key. @@ -3647,7 +3661,11 @@ func TestVMBridge(t *testing.T) { ) t.Run("successful NFT Type Onboarding and Bridging", newVMTest(). - withBootstrapProcedureOptions(fvm.WithSetupEVMEnabled(true), fvm.WithSetupVMBridgeEnabled(true)). + // default is testnet, but testnet has a special EVM storage contract location + // so we have to use emulator here so that the EVM storage contract is deployed + // to the 5th address + withChain(flow.Emulator.Chain()). + withBootstrapProcedureOptions(fvm.WithSetupVMBridgeEnabled(true)). withContextOptions(ctxOpts...). run(func( t *testing.T, @@ -3662,30 +3680,32 @@ func TestVMBridge(t *testing.T) { env := sc.AsTemplateEnv() bridgeEnv := bridge.Environment{ - CrossVMNFTAddress: env.ServiceAccountAddress, - CrossVMTokenAddress: env.ServiceAccountAddress, - FlowEVMBridgeHandlerInterfacesAddress: env.ServiceAccountAddress, - IBridgePermissionsAddress: env.ServiceAccountAddress, - ICrossVMAddress: env.ServiceAccountAddress, - ICrossVMAssetAddress: env.ServiceAccountAddress, - IEVMBridgeNFTMinterAddress: env.ServiceAccountAddress, - IEVMBridgeTokenMinterAddress: env.ServiceAccountAddress, - IFlowEVMNFTBridgeAddress: env.ServiceAccountAddress, - IFlowEVMTokenBridgeAddress: env.ServiceAccountAddress, - FlowEVMBridgeAddress: env.ServiceAccountAddress, - FlowEVMBridgeAccessorAddress: env.ServiceAccountAddress, - FlowEVMBridgeConfigAddress: env.ServiceAccountAddress, - FlowEVMBridgeHandlersAddress: env.ServiceAccountAddress, - FlowEVMBridgeNFTEscrowAddress: env.ServiceAccountAddress, - FlowEVMBridgeResolverAddress: env.ServiceAccountAddress, - FlowEVMBridgeTemplatesAddress: env.ServiceAccountAddress, - FlowEVMBridgeTokenEscrowAddress: env.ServiceAccountAddress, - FlowEVMBridgeUtilsAddress: env.ServiceAccountAddress, - ArrayUtilsAddress: env.ServiceAccountAddress, - ScopedFTProvidersAddress: env.ServiceAccountAddress, - SerializeAddress: env.ServiceAccountAddress, - SerializeMetadataAddress: env.ServiceAccountAddress, - StringUtilsAddress: env.ServiceAccountAddress, + CrossVMNFTAddress: env.ServiceAccountAddress, + CrossVMTokenAddress: env.ServiceAccountAddress, + FlowEVMBridgeHandlerInterfacesAddress: env.ServiceAccountAddress, + IBridgePermissionsAddress: env.ServiceAccountAddress, + ICrossVMAddress: env.ServiceAccountAddress, + ICrossVMAssetAddress: env.ServiceAccountAddress, + IEVMBridgeNFTMinterAddress: env.ServiceAccountAddress, + IEVMBridgeTokenMinterAddress: env.ServiceAccountAddress, + IFlowEVMNFTBridgeAddress: env.ServiceAccountAddress, + IFlowEVMTokenBridgeAddress: env.ServiceAccountAddress, + FlowEVMBridgeAddress: env.ServiceAccountAddress, + FlowEVMBridgeAccessorAddress: env.ServiceAccountAddress, + FlowEVMBridgeCustomAssociationTypesAddress: env.ServiceAccountAddress, + FlowEVMBridgeCustomAssociationsAddress: env.ServiceAccountAddress, + FlowEVMBridgeConfigAddress: env.ServiceAccountAddress, + FlowEVMBridgeHandlersAddress: env.ServiceAccountAddress, + FlowEVMBridgeNFTEscrowAddress: env.ServiceAccountAddress, + FlowEVMBridgeResolverAddress: env.ServiceAccountAddress, + FlowEVMBridgeTemplatesAddress: env.ServiceAccountAddress, + FlowEVMBridgeTokenEscrowAddress: env.ServiceAccountAddress, + FlowEVMBridgeUtilsAddress: env.ServiceAccountAddress, + ArrayUtilsAddress: env.ServiceAccountAddress, + ScopedFTProvidersAddress: env.ServiceAccountAddress, + SerializeAddress: env.ServiceAccountAddress, + SerializeMetadataAddress: env.ServiceAccountAddress, + StringUtilsAddress: env.ServiceAccountAddress, } // Create an account private key. @@ -3719,8 +3739,13 @@ func TestVMBridge(t *testing.T) { snapshotTree = snapshotTree.Append(executionSnapshot) - // Deploy the ExampleNFT contract - nftContract := contracts.ExampleNFT(env) + // Deploy the ExampleNFT contract (pre-CrossVM version, since + // this test exercises basic bridge onboarding without a pre-deployed EVM contract) + nftContract := nftcontracts.ExampleNFT( + flowsdk.HexToAddress(env.NonFungibleTokenAddress), + flowsdk.HexToAddress(env.MetadataViewsAddress), + flowsdk.HexToAddress(env.ViewResolverAddress), + ) nftContractName := "ExampleNFT" txBodyBuilder = blueprints.DeployContractTransaction( accounts[0], @@ -3865,10 +3890,10 @@ func TestVMBridge(t *testing.T) { id := cadence.UInt64(0) for _, event := range output.Events { - if strings.Contains(string(event.Type), "Minted") { + if strings.Contains(string(event.Type), "Deposited") { // decode the event payload data, _ := ccf.Decode(nil, event.Payload) - // get the contractAddress field from the event + // get the id field from the event id = cadence.SearchFieldByName( data.(cadence.Event), "id", @@ -3968,7 +3993,7 @@ func TestAccountCapabilitiesGetEntitledRejection(t *testing.T) { env := environment.NewScriptEnv( context.TODO(), tracing.NewMockTracerSpan(), - environment.DefaultEnvironmentParams(), + fvm.DefaultEnvironmentParams(flow.Mainnet.Chain()), nil, ) @@ -3997,7 +4022,7 @@ func TestAccountCapabilitiesGetEntitledRejection(t *testing.T) { env := environment.NewScriptEnv( context.TODO(), tracing.NewMockTracerSpan(), - environment.DefaultEnvironmentParams(), + fvm.DefaultEnvironmentParams(flow.Mainnet.Chain()), nil, ) @@ -4113,7 +4138,7 @@ func TestCrypto(t *testing.T) { chain, vm := createChainAndVm(chainID) ctx := fvm.NewContext( - fvm.WithChain(chain), + chain, fvm.WithCadenceLogging(true), ) @@ -4281,7 +4306,7 @@ func Test_BlockHashListShouldWriteOnPush(t *testing.T) { chain := flow.Emulator.Chain() sc := systemcontracts.SystemContractsForChain(chain.ChainID()) - push := func(bhl *handler.BlockHashList, height uint64) { + push := func(bhl *environment.BlockHashList, height uint64) { buffer := make([]byte, 32) pos := 0 @@ -4292,9 +4317,8 @@ func Test_BlockHashListShouldWriteOnPush(t *testing.T) { } t.Run("block hash list write on push", newVMTest(). - withContextOptions( - fvm.WithChain(chain), - fvm.WithEVMEnabled(true), + withChain( + chain, ). run(func( t *testing.T, @@ -4317,7 +4341,7 @@ func Test_BlockHashListShouldWriteOnPush(t *testing.T) { accounts, ) - bhl, err := handler.NewBlockHashList(valueStore, sc.EVMStorage.Address, capacity) + bhl, err := environment.NewBlockHashList(valueStore, sc.EVMStorage.Address, capacity) require.NoError(t, err) // fill the block hash list @@ -4342,7 +4366,7 @@ func Test_BlockHashListShouldWriteOnPush(t *testing.T) { accounts, ) - bhl, err = handler.NewBlockHashList(valueStore, sc.EVMStorage.Address, capacity) + bhl, err = environment.NewBlockHashList(valueStore, sc.EVMStorage.Address, capacity) require.NoError(t, err) // after we push the changes should be applied and the first block hash in the bucket should be capacity+1 instead of 0 @@ -4378,3 +4402,556 @@ func Test_BlockHashListShouldWriteOnPush(t *testing.T) { require.Equal(t, expectedBlockHashListBucket, newBlockHashListBucket) })) } + +func TestTransactionIndexCall(t *testing.T) { + t.Parallel() + + t.Run("in transactions", + newVMTest(). + run( + func( + t *testing.T, + vm fvm.VM, + chain flow.Chain, + ctx fvm.Context, + snapshotTree snapshot.SnapshotTree, + ) { + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(` + transaction { + prepare() { + let idx = getTransactionIndex() + log(idx) + } + } + `)). + SetProposalKey(chain.ServiceAddress(), 0, 0). + SetPayer(chain.ServiceAddress()) + + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) + + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) + + ctx = fvm.NewContextFromParent(ctx, fvm.WithCadenceLogging(true)) + + txIndex := uint32(3) + + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, txIndex), + snapshotTree) + require.NoError(t, err) + require.NoError(t, output.Err) + require.Len(t, output.Logs, 1) + + idx, err := strconv.Atoi(output.Logs[0]) + require.NoError(t, err) + require.Equal(t, txIndex, uint32(idx)) + }, + ), + ) + + t.Run("in scripts", + newVMTest(). + run( + func( + t *testing.T, + vm fvm.VM, + chain flow.Chain, + ctx fvm.Context, + snapshotTree snapshot.SnapshotTree, + ) { + script := fvm.Script( + []byte(` + access(all) fun main(): UInt32 { + return getTransactionIndex() + }`)) + + _, output, err := vm.Run( + ctx, + script, + snapshotTree) + require.NoError(t, err) + require.NoError(t, output.Err) + + require.Equal(t, cadence.UInt32(0), output.Value) + }, + ), + ) +} + +func TestFlowTokenChangesInspector(t *testing.T) { + t.Parallel() + + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + flowTokenVaultID := fmt.Sprintf("A.%s.FlowToken.Vault", sc.FlowToken.Address.Hex()) + flowTokenMintedEventID := fmt.Sprintf("A.%s.FlowToken.TokensMinted", sc.FlowToken.Address.Hex()) + + type testCase struct { + txBody func(*testing.T, flow.Chain, []flow.Address) *flow.TransactionBody + txErrorExpected bool + resultChecker func(*testing.T, inspection.TokenDiffResult) + tokenDefinitions map[string]inspection.SearchToken + name string + } + + // blocks mock needed for EVM test case + blocks := new(envMock.Blocks) + block1 := unittest.BlockFixture() + blocks.On("ByHeightFrom", + block1.Height, + block1.ToHeader(), + ).Return(block1.ToHeader(), nil) + + vaultOnlyTokenDefs := map[string]inspection.SearchToken{ + flowTokenVaultID: { + ID: flowTokenVaultID, + GetBalance: func(value *interpreter.CompositeValue) uint64 { + return uint64(value.GetField(nil, "balance").(interpreter.UFix64Value).UFix64Value) + }, + }, + } + + testCases := []testCase{ + { + name: "transfer", + tokenDefinitions: vaultOnlyTokenDefs, + txBody: func(t *testing.T, chain flow.Chain, accounts []flow.Address) *flow.TransactionBody { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + env := sc.AsTemplateEnv() + + txBodyBuilder := blueprints.TransferFlowTokenTransaction(env, chain.ServiceAddress(), accounts[0], "2.0") + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) + + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) + return txBody + }, + resultChecker: func(t *testing.T, result inspection.TokenDiffResult) { + require.Len(t, result.UnaccountedTokens(), 0, "no tokens were created or destroyed") + require.Len(t, result.Changes, 3, "change should be on 3 addresses: sender, receiver, fees") + }, + }, + { + name: "mint without mint event monitoring", + tokenDefinitions: vaultOnlyTokenDefs, + txBody: func(t *testing.T, chain flow.Chain, accounts []flow.Address) *flow.TransactionBody { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + env := sc.AsTemplateEnv() + + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript(templates.GenerateMintFlowScript(env)). + AddArgument(jsoncdc.MustEncode(cadence.Address(accounts[0]))). + AddArgument(jsoncdc.MustEncode(cadence.UFix64(10_000_000))). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) + + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) + + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) + + return txBody + }, + resultChecker: func(t *testing.T, result inspection.TokenDiffResult) { + unaccounted := result.UnaccountedTokens() + require.Len(t, unaccounted, 1, "expectation: some tokens were created and are unaccounted for") + require.Equal(t, unaccounted[flowTokenVaultID], int64(10000000)) + require.Len(t, result.Changes, 3, "change should be on 3 addresses: sender, receiver, fees") + }, + }, + { + name: "mint with mint event monitoring", + tokenDefinitions: map[string]inspection.SearchToken{ + flowTokenVaultID: { + ID: flowTokenVaultID, + GetBalance: func(value *interpreter.CompositeValue) uint64 { + return uint64(value.GetField(nil, "balance").(interpreter.UFix64Value).UFix64Value) + }, + SinksSources: map[string]func(flow.Event) (int64, error){ + flowTokenMintedEventID: func(evt flow.Event) (int64, error) { + payload, err := ccf.Decode(nil, evt.Payload) + require.NoError(t, err) + return int64(payload.(cadence.Event).SearchFieldByName("amount").(cadence.UFix64)), nil + }, + }, + }, + }, + txBody: func(t *testing.T, chain flow.Chain, accounts []flow.Address) *flow.TransactionBody { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + env := sc.AsTemplateEnv() + + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript(templates.GenerateMintFlowScript(env)). + AddArgument(jsoncdc.MustEncode(cadence.Address(accounts[0]))). + AddArgument(jsoncdc.MustEncode(cadence.UFix64(10_000_000))). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) + + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) + + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) + + return txBody + }, + resultChecker: func(t *testing.T, result inspection.TokenDiffResult) { + unaccounted := result.UnaccountedTokens() + require.Len(t, unaccounted, 0, "expectation: all tokens were accounted for") + require.Len(t, result.Changes, 3, "change should be on 3 addresses: sender, receiver, fees") + }, + }, + { + name: "mint with default tracking", + tokenDefinitions: inspection.DefaultTokenDiffSearchTokens(chain), + txBody: func(t *testing.T, chain flow.Chain, accounts []flow.Address) *flow.TransactionBody { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + env := sc.AsTemplateEnv() + + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript(templates.GenerateMintFlowScript(env)). + AddArgument(jsoncdc.MustEncode(cadence.Address(accounts[0]))). + AddArgument(jsoncdc.MustEncode(cadence.UFix64(10_000_000))). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) + + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) + + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) + + return txBody + }, + resultChecker: func(t *testing.T, result inspection.TokenDiffResult) { + unaccounted := result.UnaccountedTokens() + require.Len(t, unaccounted, 0, "expectation: all tokens were accounted for") + require.Len(t, result.Changes, 3, "change should be on 3 addresses: sender, receiver, fees") + }, + }, { + name: "create account", + tokenDefinitions: inspection.DefaultTokenDiffSearchTokens(chain), + txBody: func(t *testing.T, chain flow.Chain, accounts []flow.Address) *flow.TransactionBody { + _, txBodyBuilder := testutil.CreateAccountCreationTransaction(t, chain) + + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) + + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) + + return txBody + }, + resultChecker: func(t *testing.T, result inspection.TokenDiffResult) { + unaccounted := result.UnaccountedTokens() + require.Len(t, unaccounted, 0, "no tokens were created or destroyed") + require.Len(t, result.Changes, 3, "change should be on 3 addresses: sender, receiver, fees") + }, + }, { + name: "evm transaction", + tokenDefinitions: inspection.DefaultTokenDiffSearchTokens(chain), + txBody: func(t *testing.T, chain flow.Chain, _ []flow.Address) *flow.TransactionBody { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + + txBodyBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(fmt.Sprintf(` + import FungibleToken from %s + import FlowToken from %s + import EVM from %s + + transaction() { + prepare(acc: auth(Storage) &Account) { + let vaultRef = acc.storage + .borrow(from: /storage/flowTokenVault) + ?? panic("Could not borrow reference to the owner's Vault!") + + let evmHeartbeat = acc.storage + .borrow<&EVM.Heartbeat>(from: /storage/EVMHeartbeat) + ?? panic("Couldn't borrow EVM.Heartbeat Resource") + + let evmAccount <- EVM.createCadenceOwnedAccount() + let amount <- vaultRef.withdraw(amount: 1.0) as! @FlowToken.Vault + evmAccount.deposit(from: <- amount) + destroy evmAccount + + evmHeartbeat.heartbeat() + } + }`, + sc.FungibleToken.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + sc.FlowServiceAccount.Address.HexWithPrefix(), + ))). + SetProposalKey(chain.ServiceAddress(), 0, 0). + AddAuthorizer(chain.ServiceAddress()). + SetPayer(chain.ServiceAddress()) + + err := testutil.SignTransactionAsServiceAccount(txBodyBuilder, 0, chain) + require.NoError(t, err) + + txBody, err := txBodyBuilder.Build() + require.NoError(t, err) + return txBody + }, + resultChecker: func(t *testing.T, result inspection.TokenDiffResult) { + unaccounted := result.UnaccountedTokens() + require.Len(t, unaccounted, 0, "all tokens should be accounted for (EVM deposit is a known sink)") + }, + }, + } + + runAndCheckTransactionTest := func(tc testCase) func(t *testing.T) { + return newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithTransactionFee(fvm.DefaultTransactionFees), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithExecutionMemoryLimit(math.MaxUint64), + fvm.WithExecutionEffortWeights(environment.MainnetExecutionEffortWeights), + fvm.WithExecutionMemoryWeights(meter.DefaultMemoryWeights), + ). + withContextOptions( + fvm.WithTransactionFeesEnabled(true), + fvm.WithAccountStorageLimit(true), + fvm.WithAuthorizationChecksEnabled(false), + fvm.WithBlocks(blocks), + fvm.WithBlockHeader(block1.ToHeader()), + ). + run( + func( + t *testing.T, + vm fvm.VM, + chain flow.Chain, + ctx fvm.Context, + snapshotTree snapshot.SnapshotTree, + ) { + t.Parallel() + + differ := inspection.NewTokenChangesInspector(tc.tokenDefinitions, chain.ChainID()) + + // Add the inspector to the context so inspection runs + // as part of the transaction execution pipeline. + ctx = fvm.NewContextFromParent(ctx, fvm.WithInspectors([]inspection.Inspector{differ})) + + // Create an account private key. + privateKey, err := testutil.GenerateAccountPrivateKey() + require.NoError(t, err) + + // Create accounts with the provided private + // key and the root account. + snapshotTree, accounts, err := testutil.CreateAccounts( + vm, + snapshotTree, + []flow.AccountPrivateKey{privateKey, privateKey, privateKey}, + chain) + require.NoError(t, err) + + txBody := tc.txBody(t, chain, accounts) + + _, output, err := vm.Run( + ctx, + fvm.Transaction(txBody, 0), + snapshotTree) + + require.NoError(t, err) + if tc.txErrorExpected { + require.Error(t, output.Err) + } else { + require.NoError(t, output.Err) + } + + require.Len(t, output.InspectionResults, 1, "expected one inspection result") + tc.resultChecker(t, output.InspectionResults[0].(inspection.TokenDiffResult)) + }, + ) + } + + for _, tc := range testCases { + t.Run(tc.name, runAndCheckTransactionTest(tc)) + } +} + +// TestTokenInspectorCreateAndFundNewAccount is a regression test for the account-creation +// storage-sharing fix, derived from mainnet tx +// c5f3d77c1b86a9b4ce36e214278aca695702f26bd00e6c93b01d88f706456597. +// +// Creating and funding a new account in one transaction used to run `Account(payer:)`'s setup in +// separate Cadence storage. When the payer's vault was borrowed before `Account(payer:)`, its stale +// balance overwrote the 0.001 FLOW reservation deduction on commit, creating FLOW with no +// `TokensMinted` event, which the inspector flagged as unaccounted. +// +// The test asserts that both borrow orderings now charge the payer the funding plus the reservation +// and leave nothing unaccounted. +func TestTokenInspectorCreateAndFundNewAccount(t *testing.T) { + chain := flow.Emulator.Chain() + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + + feesDeductedEventID := fmt.Sprintf("A.%s.FlowFees.FeesDeducted", sc.FlowFees.Address.Hex()) + + // reservation is the minimum storage reservation funded into every newly created account. + reservation := uint64(fvm.DefaultMinimumStorageReservation) // 0.001 FLOW + const funding = uint64(50_000_000) // 0.5 FLOW deposited into the new account + + // borrowBeforeCreate borrows the payer's vault before `Account(payer:)` — the mainnet + // ordering that originally exposed the lost-reservation bug. + // Both orderings must now be safe. + makeScript := func(borrowBeforeCreate bool) string { + borrow := ` + let flowVaultRef = acct.storage + .borrow(from: /storage/flowTokenVault) + ?? panic("Could not borrow reference to the owner's Vault!")` + create := `let newAcct = Account(payer: acct)` + + preamble := create + "\n" + borrow + if borrowBeforeCreate { + preamble = borrow + "\n\t\t\t\t" + create + } + + return fmt.Sprintf(` + import FungibleToken from %s + import FlowToken from %s + + transaction() { + prepare(acct: auth(Storage, Capabilities) &Account) { + %s + + let receiverRef = newAcct.capabilities + .get<&{FungibleToken.Receiver}>(/public/flowTokenReceiver) + .borrow() + ?? panic("Could not borrow receiver reference to the newly created account") + receiverRef.deposit(from: <- flowVaultRef.withdraw(amount: 0.5)) + } + }`, + sc.FungibleToken.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + preamble, + ) + } + + // expectedPayerDebit is the FlowToken amount the payer's balance should drop by (excluding + // transaction fees, which are deducted from the same account): the funding plus the reservation, + // regardless of borrow ordering. + expectedPayerDebit := funding + reservation + + type testCase struct { + name string + borrowBeforeCreate bool + } + + testCases := []testCase{ + { + name: "borrow before create (mainnet pattern)", + borrowBeforeCreate: true, + }, + { + name: "borrow after create", + borrowBeforeCreate: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, newVMTest(). + withChain(chain). + withBootstrapProcedureOptions( + fvm.WithTransactionFee(fvm.DefaultTransactionFees), + fvm.WithStorageMBPerFLOW(fvm.DefaultStorageMBPerFLOW), + fvm.WithMinimumStorageReservation(fvm.DefaultMinimumStorageReservation), + fvm.WithAccountCreationFee(fvm.DefaultAccountCreationFee), + fvm.WithExecutionMemoryLimit(math.MaxUint64), + fvm.WithExecutionEffortWeights(environment.MainnetExecutionEffortWeights), + fvm.WithExecutionMemoryWeights(meter.DefaultMemoryWeights), + ). + withContextOptions( + fvm.WithTransactionFeesEnabled(true), + fvm.WithAccountStorageLimit(true), + fvm.WithAuthorizationChecksEnabled(false), + fvm.WithSequenceNumberCheckAndIncrementEnabled(false), + ). + run(func( + t *testing.T, + vm fvm.VM, + chain flow.Chain, + ctx fvm.Context, + snapshotTree snapshot.SnapshotTree, + ) { + privateKey, err := testutil.GenerateAccountPrivateKey() + require.NoError(t, err) + snapshotTree, accounts, err := testutil.CreateAccounts( + vm, snapshotTree, []flow.AccountPrivateKey{privateKey}, chain) + require.NoError(t, err) + payer := accounts[0] + + env := sc.AsTemplateEnv() + balanceOf := func(snap snapshot.SnapshotTree, addr flow.Address) uint64 { + code := fmt.Sprintf(` + import FungibleToken from %s + import FlowToken from %s + access(all) fun main(addr: Address): UFix64 { + return getAccount(addr).capabilities + .borrow<&FlowToken.Vault>(/public/flowTokenBalance)!.balance + }`, + sc.FungibleToken.Address.HexWithPrefix(), + sc.FlowToken.Address.HexWithPrefix(), + ) + arg, err := jsoncdc.Encode(cadence.Address(addr)) + require.NoError(t, err) + _, out, serr := vm.Run(ctx, fvm.Script([]byte(code)).WithArguments(arg), snap) + require.NoError(t, serr) + require.NoError(t, out.Err) + return uint64(out.Value.(cadence.UFix64)) + } + + // Fund the (regular) payer account with 10 FLOW from the service account, so the + // payer is a normal account just like the mainnet authorizer. + fundTx := blueprints.TransferFlowTokenTransaction(env, chain.ServiceAddress(), payer, "10.0") + require.NoError(t, testutil.SignTransactionAsServiceAccount(fundTx, 0, chain)) + fundBody, err := fundTx.Build() + require.NoError(t, err) + fundSnap, fundOut, err := vm.Run(ctx, fvm.Transaction(fundBody, 0), snapshotTree) + require.NoError(t, err) + require.NoError(t, fundOut.Err) + snapshotTree = snapshotTree.Append(fundSnap) + + txBuilder := flow.NewTransactionBodyBuilder(). + SetScript([]byte(makeScript(tc.borrowBeforeCreate))). + AddAuthorizer(payer) + require.NoError(t, testutil.SignTransaction(txBuilder, payer, privateKey, 0)) + txBody, err := txBuilder.Build() + require.NoError(t, err) + + differ := inspection.NewTokenChangesInspector( + inspection.DefaultTokenDiffSearchTokens(chain), chain.ChainID()) + inspectCtx := fvm.NewContextFromParent(ctx, fvm.WithInspectors([]inspection.Inspector{differ})) + + payerBefore := balanceOf(snapshotTree, payer) + execSnap, output, err := vm.Run(inspectCtx, fvm.Transaction(txBody, 0), snapshotTree) + require.NoError(t, err) + require.NoError(t, output.Err) + payerAfter := balanceOf(snapshotTree.Append(execSnap), payer) + + // The transaction fee is deducted from the payer in addition to the funding/reservation. + var txFee uint64 + for _, e := range output.Events { + if string(e.Type) == feesDeductedEventID { + payload, err := ccf.Decode(nil, e.Payload) + require.NoError(t, err) + txFee = uint64(payload.(cadence.Event).SearchFieldByName("amount").(cadence.UFix64)) + } + } + payerDebit := payerBefore - payerAfter + require.Equal(t, expectedPayerDebit+txFee, payerDebit, + "payer balance change should equal expected debit plus the transaction fee") + + require.Len(t, output.InspectionResults, 1, "expected one inspection result") + result := output.InspectionResults[0].(inspection.TokenDiffResult) + require.Empty(t, result.UnaccountedTokens(), "all token movements should be accounted for") + })) + } +} diff --git a/fvm/initialize/options.go b/fvm/initialize/options.go index e484dcaccfd..8b6990fc12b 100644 --- a/fvm/initialize/options.go +++ b/fvm/initialize/options.go @@ -17,7 +17,6 @@ func InitFvmOptions( ) []fvm.Option { blockFinder := environment.NewBlockFinder(headers) vmOpts := []fvm.Option{ - fvm.WithChain(chainID.Chain()), fvm.WithBlocks(blockFinder), fvm.WithAccountStorageLimit(true), } diff --git a/fvm/inspection/inspector.go b/fvm/inspection/inspector.go new file mode 100644 index 00000000000..e253e7d060d --- /dev/null +++ b/fvm/inspection/inspector.go @@ -0,0 +1,33 @@ +package inspection + +import ( + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" +) + +// Inspector is run after each procedure on the procedure output and the starting state of a procedure +// It will then fill out the ProcedureOutput.Inspection results +type Inspector interface { + // Inspect + // - storage is the execution state before the procedure was executed. + // only the executionSnapshot.Reads, will be read + // - executionSnapshot is the reads and writes of the procedure + // - events are all of the events the procedure is emitting + Inspect( + logger zerolog.Logger, + storage snapshot.StorageSnapshot, + executionSnapshot *snapshot.ExecutionSnapshot, + events []flow.Event, + ) (Result, error) + + // Name is the name of the inspector + Name() string +} + +// Result is the result of a procedure inspector +type Result interface { + InspectionName() string + AsLogEvent() (zerolog.Level, func(e *zerolog.Event)) +} diff --git a/fvm/inspection/token_changes.go b/fvm/inspection/token_changes.go new file mode 100644 index 00000000000..78112db40aa --- /dev/null +++ b/fvm/inspection/token_changes.go @@ -0,0 +1,790 @@ +package inspection + +import ( + "fmt" + "math" + "runtime/debug" + "sync" + + "github.com/onflow/atree" + "github.com/onflow/cadence" + "github.com/onflow/cadence/bbq/vm" + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/encoding/ccf" + "github.com/onflow/cadence/interpreter" + "github.com/onflow/cadence/runtime" + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/fvm/systemcontracts" + + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" +) + +type TokenChanges struct { + // searchedTokens holds a reference to the map of tokens to search + // its shallow copied from whatever is specified from the outside, so that the locking + // should work properly + searchedTokens TokenChangesSearchTokens + searchedTokensMu sync.RWMutex + + evmStorageAccount string +} + +var _ Inspector = (*TokenChanges)(nil) + +// NewTokenChangesInspector return a TokenChanges inspector, that will be run +// after transaction execution and analyze if any unaccounted tokens were created or +// destroy. +func NewTokenChangesInspector(searchedTokens TokenChangesSearchTokens, chain flow.ChainID) *TokenChanges { + sc := systemcontracts.SystemContractsForChain(chain) + + return &TokenChanges{ + searchedTokens: searchedTokens, + evmStorageAccount: string(sc.EVMStorage.Address.Bytes()), + } +} + +func (td *TokenChanges) Name() string { + return "TokenChanges" +} + +// SetSearchedTokens are safe to replace whenever. +// The change will not affect the inspections already in progress. +// TODO: this can be tied into the admin commands +func (td *TokenChanges) SetSearchedTokens(searchedTokens TokenChangesSearchTokens) { + // copy the map in case the user tries to modify the map + st := make(map[string]SearchToken, len(searchedTokens)) + for k, v := range searchedTokens { + st[k] = v + } + td.searchedTokensMu.Lock() + defer td.searchedTokensMu.Unlock() + td.searchedTokens = st +} + +func (td *TokenChanges) getSearchedTokensRef() TokenChangesSearchTokens { + td.searchedTokensMu.RLock() + defer td.searchedTokensMu.RUnlock() + return td.searchedTokens +} + +// Inspect gets the token diff from a state diff +// - thread safe +// - not deterministic (iterates over maps)! So it should not be used to affect execution! +// - will not panic +// - might return an error, but it is safe to ignore since this for information/reporting +// +// Inspect could technically be run on chunk data packs. +func (td *TokenChanges) Inspect( + log zerolog.Logger, + storage snapshot.StorageSnapshot, + executionSnapshot *snapshot.ExecutionSnapshot, + events []flow.Event, +) (diff Result, err error) { + log.Debug(). + Int("events", len(events)). + Int("read_set", len(executionSnapshot.ReadSet)). + Int("write_set", len(executionSnapshot.WriteSet)). + Msg("starting token inspection for transaction") + + defer func() { + if r := recover(); r != nil { + // info level is sufficient since the error is already getting logged outside of this function + log.Info().Msgf("trace=%s", string(debug.Stack())) + err = fmt.Errorf("panic: %v", r) + } + + if err != nil { + err = fmt.Errorf("failed to get token diff: %w", err) + } + }() + + diff, err = td.getTokenDiff(log, storage, executionSnapshot, events, td.getSearchedTokensRef()) + return +} + +func (td *TokenChanges) getTokenDiff( + log zerolog.Logger, + storage snapshot.StorageSnapshot, + executionSnapshot *snapshot.ExecutionSnapshot, + events []flow.Event, + searchedTokens map[string]SearchToken, +) (TokenDiffResult, error) { + executionSnapshotLedgers := executionSnapshotLedgers{ + StorageSnapshot: storage, + ExecutionSnapshot: executionSnapshot, + } + + // get all distinct addresses + addresses := make(map[common.Address]struct{}) + allTouched := executionSnapshotLedgers.allTouchedRegisters() + for k := range allTouched { + // skip special registers + // none of them can hold resources + if len(k.Owner) == 0 { + continue + } + addresses[common.Address([]byte(k.Owner))] = struct{}{} + } + + log.Debug(). + Int("touched_registers", len(allTouched)). + Int("addresses_to_inspect", len(addresses)). + Int("searched_tokens", len(searchedTokens)). + Msg("inspecting token movements") + + if len(addresses) == 0 { + log.Debug().Msg("no addresses touched, skipping token inspection") + return TokenDiffResult{ + Changes: make(map[flow.Address]AccountChange), + KnownSourcesSinks: make(map[string]int64), + }, nil + } + + oldRegistersLedger := executionSnapshotLedgers.OldValuesLedger() + newValuesRegister := executionSnapshotLedgers.NewValuesLedger() + + // TODO(janezp): possible optimisation: run both at the same time + before, err := td.getTokens(log, oldRegistersLedger, addresses, tokenDiffSearchDomains, searchedTokens) + if err != nil { + return TokenDiffResult{}, fmt.Errorf("failed to get tokens before: %w", err) + } + after, err := td.getTokens(log, newValuesRegister, addresses, tokenDiffSearchDomains, searchedTokens) + if err != nil { + return TokenDiffResult{}, fmt.Errorf("failed to get tokens after: %w", err) + } + + typicalDiffSize := 4 // from, to, payer and fees + tokenDiffResult := TokenDiffResult{ + Changes: make(map[flow.Address]AccountChange, typicalDiffSize), + } + + for a := range addresses { + // Copy beforeTokens before calling diffAccountTokens, which mutates the before map + beforeTokens := make(accountTokens, len(before[a])) + for k, v := range before[a] { + beforeTokens[k] = v + } + afterTokens := after[a] + diff := diffAccountTokens(before[a], after[a]) + if len(diff) == 0 { + // Only log if the account had tokens before or after + if len(beforeTokens) > 0 || len(afterTokens) > 0 { + log.Debug(). + Str("account", a.String()). + Interface("before", beforeTokens). + Interface("after", afterTokens). + Msg("account token balance unchanged") + } + continue + } + log.Debug(). + Str("account", a.String()). + Interface("before", beforeTokens). + Interface("after", afterTokens). + Interface("diff", diff). + Msg("account token balance changed") + tokenDiffResult.Changes[flow.Address(a)] = diff + } + + sourcesSinks, err := td.findSourcesSinks(events, searchedTokens) + if err != nil { + return TokenDiffResult{}, fmt.Errorf("failed to find sources/sinks: %w", err) + } + tokenDiffResult.KnownSourcesSinks = sourcesSinks + + // Log summary of token movements + // Only log as debug because it's going to get properly logged in `TokenDiffResult.AsLogEvent()` + unaccounted := tokenDiffResult.UnaccountedTokens() + if len(unaccounted) > 0 { + log.Debug(). + Int("accounts_changed", len(tokenDiffResult.Changes)). + Interface("sources_sinks", sourcesSinks). + Interface("unaccounted", unaccounted). + Msg("token inspection complete - unaccounted token movements detected") + } else if len(tokenDiffResult.Changes) > 0 { + log.Debug(). + Int("accounts_changed", len(tokenDiffResult.Changes)). + Interface("sources_sinks", sourcesSinks). + Msg("token inspection complete - all movements accounted for") + } + + return tokenDiffResult, nil +} + +func (td *TokenChanges) getTokens( + logger zerolog.Logger, + storage ledgerSnapshot, + addresses map[common.Address]struct{}, + domains []common.StorageDomain, + searchedTokens map[string]SearchToken, +) (map[common.Address]accountTokens, error) { + storageConfig := runtime.StorageConfig{} + runtimeStorage := runtime.NewStorage(storage, nil, nil, storageConfig) + + // without this the tokens are not properly detected! + // TODO: choose a good number for the workers + err := td.loadAtreeSlabsInStorage(runtimeStorage, storage, 1) + if err != nil { + return nil, fmt.Errorf("failed to load atree slabs: %w", err) + } + + storageRuntime, err := newReadonlyStorageRuntimeWithStorage(runtimeStorage, runtimeStorage.Count()) + if err != nil { + return nil, fmt.Errorf("failed to create storage runtime: %w", err) + } + + tokens := make(map[common.Address]accountTokens, len(addresses)) + for a := range addresses { + tkns := make(accountTokens, len(searchedTokens)) + for _, d := range domains { + // We are making the assumption that if a register was changed, the registers read to make that change + // are enough to read that register before the change (if it existed) + + // It seems that GetDomainStorageMap() tries to load domain storage map if it isn't loaded. + // This causes a "slab not found" panic because we only included loaded registers in the underlying storage. + // This workaround is to catch the panic gracefully so we can continue to inspect the next domain storage map. + storageMap := getDomainStorageMap(logger, storageRuntime, storageRuntime.Interpreter, a, d) + if storageMap == nil { + continue + } + + iter := storageMap.ReadOnlyLoadedValueIterator() + for { + interpreterValue := iter.NextValue(nil) + + if interpreterValue == nil { + break + } + + walkLoaded(interpreterValue, searchedTokens, tkns) + } + } + if len(tkns) > 0 { + logger.Debug(). + Str("account", a.String()). + Interface("tokens", tkns). + Msg("found tokens in account") + } + tokens[a] = tkns + } + return tokens, nil +} + +func getDomainStorageMap( + log zerolog.Logger, + storageRuntime *readonlyStorageRuntime, + storageMutationTracker interpreter.StorageMutationTracker, + address common.Address, + domain common.StorageDomain, +) (dm *interpreter.DomainStorageMap) { + defer func() { + if r := recover(); r != nil { + log.Warn().Msgf("failed to get domain storage map %s.%s: %v", address.String(), domain.Identifier(), r) + dm = nil + } + }() + return storageRuntime.Storage.GetDomainStorageMap(storageMutationTracker, address, domain, false) +} + +func walkLoaded( + value interpreter.Value, + searchedTokens map[string]SearchToken, + tkns accountTokens, +) { + // The context is not needed for the walk, + // but a context of nil produces an error. + c := &vm.Context{ + Config: &vm.Config{}, + } + + var f func(value interpreter.Value) + f = func(value interpreter.Value) { + switch v := value.(type) { + case *interpreter.CompositeValue: + t, ok := searchedTokens[string(v.TypeID())] + if ok { + tkns.add(t.ID, t.GetBalance(v)) + } + + // technically nothing is stopping you from putting a vault into a vault, so we have to continue walking + v.ForEachReadOnlyLoadedField(c, func(fieldName string, fieldValue interpreter.Value) (resume bool) { + f(fieldValue) + return true + }) + case *interpreter.DictionaryValue: + v.IterateReadOnlyLoaded(c, func(key interpreter.Value, value interpreter.Value) (resume bool) { + f(key) + f(value) + return true + }) + case *interpreter.ArrayValue: + v.IterateReadOnlyLoaded(c, func(value interpreter.Value) (resume bool) { + f(value) + return true + }) + case interpreter.PathLinkValue, interpreter.AccountLinkValue: + // Link values are deprecated legacy types that don't contain tokens. + // PathLinkValue.Walk and AccountLinkValue.Walk panic with "unreachable", + // so we skip them. + return + default: + // This assumes all other types cannot be partially loaded. + v.Walk(c, f) + } + } + f(value) +} + +func (td *TokenChanges) findSourcesSinks(events []flow.Event, tokens map[string]SearchToken) (map[string]int64, error) { + // create a map of all sinks and sources + // TODO: could be created once + type tokenSourceSink struct { + tokenID string + f func(flow.Event) (int64, error) + } + sourcesSinks := make(map[string]tokenSourceSink) + results := make(map[string]int64) + for _, token := range tokens { + for evt, ss := range token.SinksSources { + // Each event ID should be unique across all tokens. If two tokens register + // handlers for the same event ID, the second handler would silently overwrite + // the first, causing incorrect token accounting. This should not happen with + // the current token definitions, but we guard against it defensively. + if existing, ok := sourcesSinks[evt]; ok { + return nil, fmt.Errorf( + "event %s is registered by both token %s and token %s", + evt, existing.tokenID, token.ID, + ) + } + sourcesSinks[evt] = tokenSourceSink{tokenID: token.ID, f: ss} + } + } + + for _, evt := range events { + id := string(evt.Type) + if ss, ok := sourcesSinks[id]; ok { + v, err := ss.f(evt) + if err != nil { + return nil, fmt.Errorf("failed to parse source/sink event %s: %w", id, err) + } + results[ss.tokenID] += v + } + } + + return results, nil +} + +func newReadonlyStorageRuntimeWithStorage(storage *runtime.Storage, payloadCount int) (*readonlyStorageRuntime, error) { + inter, err := interpreter.NewInterpreter( + nil, + nil, + &interpreter.Config{ + Storage: storage, + }, + ) + if err != nil { + return nil, err + } + + return &readonlyStorageRuntime{ + Interpreter: inter, + Storage: storage, + PayloadCount: payloadCount, + }, nil +} + +type executionSnapshotLedgers struct { + snapshot.StorageSnapshot + *snapshot.ExecutionSnapshot +} + +func (l executionSnapshotLedgers) SetValue(owner, key, value []byte) (err error) { + panic("unexpected call of SetValue.") +} + +func (l executionSnapshotLedgers) AllocateSlabIndex(owner []byte) (atree.SlabIndex, error) { + panic("unexpected call of AllocateSlabIndex") +} + +type executionSnapshotLedgersOld struct { + executionSnapshotLedgers +} + +func (o executionSnapshotLedgersOld) Get(owner string, key string) ([]byte, error) { + return o.GetValue([]byte(owner), []byte(key)) +} + +func (o executionSnapshotLedgersOld) Set(owner string, key string, value []byte) error { + return o.SetValue([]byte(owner), []byte(key), value) +} + +func (o executionSnapshotLedgersOld) ForEach(f forEachCallback) error { + for key := range o.ExecutionSnapshot.ReadSet { + id := flow.NewRegisterID(flow.BytesToAddress([]byte(key.Owner)), key.Key) + + v, err := o.StorageSnapshot.Get(id) + if err != nil { + return err + } + + err = f(key.Owner, key.Key, v) + if err != nil { + return err + } + } + return nil +} + +func (o executionSnapshotLedgersOld) Count() int { + return len(o.ExecutionSnapshot.ReadSet) +} + +func (n executionSnapshotLedgersNew) Get(owner string, key string) ([]byte, error) { + return n.GetValue([]byte(owner), []byte(key)) +} + +func (n executionSnapshotLedgersNew) Set(owner string, key string, value []byte) error { + return n.SetValue([]byte(owner), []byte(key), value) +} + +func (n executionSnapshotLedgersNew) ForEach(f forEachCallback) error { + for key := range n.allTouchedRegisters() { + v, err := n.GetValue([]byte(key.Owner), []byte(key.Key)) + if err != nil { + return err + } + + err = f(key.Owner, key.Key, v) + if err != nil { + return err + } + } + return nil +} + +func (n executionSnapshotLedgersNew) Count() int { + return len(n.allTouchedRegisters()) +} + +// allTouchedRegisters returns both read and written to registers. +func (l executionSnapshotLedgers) allTouchedRegisters() map[flow.RegisterID]struct{} { + fullSet := make(map[flow.RegisterID]struct{}) + for key := range l.ExecutionSnapshot.ReadSet { + fullSet[flow.NewRegisterID(flow.BytesToAddress([]byte(key.Owner)), key.Key)] = struct{}{} + } + for key := range l.ExecutionSnapshot.WriteSet { + fullSet[flow.NewRegisterID(flow.BytesToAddress([]byte(key.Owner)), key.Key)] = struct{}{} + } + return fullSet +} + +type ledgerSnapshot interface { + atree.Ledger + registers +} + +type executionSnapshotLedgersNew struct { + executionSnapshotLedgers +} + +func (l executionSnapshotLedgers) OldValuesLedger() ledgerSnapshot { + return executionSnapshotLedgersOld{l} +} + +func (l executionSnapshotLedgers) NewValuesLedger() ledgerSnapshot { + return executionSnapshotLedgersNew{l} +} + +var _ registers = &executionSnapshotLedgersOld{} + +func (o executionSnapshotLedgersOld) GetValue(owner, key []byte) (value []byte, err error) { + id := flow.NewRegisterID(flow.BytesToAddress(owner), string(key)) + _, ok := o.ExecutionSnapshot.ReadSet[id] + if !ok { + return nil, nil + } + + v, err := o.StorageSnapshot.Get(id) + return v, err +} + +func (o executionSnapshotLedgersOld) ValueExists(owner, key []byte) (exists bool, err error) { + v, err := o.GetValue(owner, key) + return len(v) > 0, err +} + +func (n executionSnapshotLedgersNew) GetValue(owner, key []byte) (value []byte, err error) { + id := flow.NewRegisterID(flow.BytesToAddress(owner), string(key)) + + v, ok := n.ExecutionSnapshot.WriteSet[id] + + if ok { + return v, nil + } + + _, ok = n.ExecutionSnapshot.ReadSet[id] + if !ok { + return nil, nil + } + + v, err = n.StorageSnapshot.Get(id) + return v, err +} + +func (n executionSnapshotLedgersNew) ValueExists(owner, key []byte) (exists bool, err error) { + v, err := n.GetValue(owner, key) + return len(v) > 0, err +} + +type readonlyStorageRuntime struct { + Interpreter *interpreter.Interpreter + Storage *runtime.Storage + PayloadCount int +} + +type SearchToken struct { + ID string + GetBalance func(value *interpreter.CompositeValue) uint64 + // TODO: optimize by using decoded events + SinksSources map[string]func(flow.Event) (int64, error) +} + +// TokenDiffResult is the result of the inspection +type TokenDiffResult struct { + // Changes in token balances per account + // parsed from the state changes + Changes map[flow.Address]AccountChange + + // KnownSourcesSinks is a map (by token id) of + // know mints/burns for the token parsed from predetermined events + KnownSourcesSinks map[string]int64 +} + +var _ Result = TokenDiffResult{} + +func (r TokenDiffResult) InspectionName() string { + return "token-tracker-inspection" +} + +func (r TokenDiffResult) AsLogEvent() (zerolog.Level, func(e *zerolog.Event)) { + unaccountedTokens := r.UnaccountedTokens() + + if len(unaccountedTokens) == 0 { + // everything is ok: log no issues with debug logging + return zerolog.InfoLevel, func(e *zerolog.Event) { e.Str(r.InspectionName(), "no issues") } + } + + anyPositive := false + for _, v := range unaccountedTokens { + if v > 0 { + anyPositive = true + break + } + } + + level := zerolog.WarnLevel + if anyPositive { + // if any tracked token increase in supply + // log at error level + // otherwise just use warn level + level = zerolog.ErrorLevel + } + + return level, func(e *zerolog.Event) { + dict := zerolog.Dict() + for k, v := range unaccountedTokens { + dict = dict.Int64(k, v) + } + e.Dict(r.InspectionName(), dict) + } +} + +func (r TokenDiffResult) UnaccountedTokens() map[string]int64 { + sum := make(map[string]int64) + for _, change := range r.Changes { + for token, amount := range change { + sum[token] += amount + } + } + + for k, v := range r.KnownSourcesSinks { + // Yes this should be -. + // If we mint 100 tokens, that will be a source of +100 and the sum will contain + // the +100 we minted. We need to account for that +100 in the sum by **subtracting** + // the +100 we expected from the mint event. + sum[k] -= v + } + + // delete empty entries + for k, v := range sum { + if v == 0 { + delete(sum, k) + } + } + return sum +} + +type AccountChange map[string]int64 + +type accountTokens map[string]uint64 + +func (t accountTokens) add(id string, value uint64) { + t[id] += value +} + +// diffAccountTokens will potentially modify before and after, so they should not be reused +// after this call. +func diffAccountTokens(before accountTokens, after accountTokens) AccountChange { + change := make(AccountChange) + + for k, a := range after { + if b, ok := before[k]; ok { + if a > b { + change[k] = safeUint64ToInt64(a - b) + } else if b > a { + change[k] = -safeUint64ToInt64(b - a) + } + delete(before, k) + } else { + change[k] = safeUint64ToInt64(a) + } + } + + for k, v := range before { + change[k] = -safeUint64ToInt64(v) + } + + return change +} + +// safeUint64ToInt64 converts a uint64 to int64, capping at math.MaxInt64 if the value +// would overflow. If a value is capped, it will cause a mismatch in the token accounting +// which will be logged and raise attention anyway. +func safeUint64ToInt64(v uint64) int64 { + if v > math.MaxInt64 { + return math.MaxInt64 + } + return int64(v) +} + +type forEachCallback func(owner string, key string, value []byte) error + +type registers interface { + Get(owner string, key string) ([]byte, error) + Set(owner string, key string, value []byte) error + ForEach(f forEachCallback) error + Count() int +} + +func (td *TokenChanges) loadAtreeSlabsInStorage( + storage *runtime.Storage, + registers registers, + nWorkers int, +) error { + + storageIDs, err := td.getSlabIDsFromRegisters(registers) + if err != nil { + return err + } + + return storage.PersistentSlabStorage.BatchPreload(storageIDs, nWorkers) +} + +func (td *TokenChanges) getSlabIDsFromRegisters(registers registers) ([]atree.SlabID, error) { + storageIDs := make([]atree.SlabID, 0, registers.Count()) + + err := registers.ForEach(func(owner string, key string, _ []byte) error { + if !td.isRelevantSlabIndexKey(owner, key) { + return nil + } + + slabID := atree.NewSlabID( + atree.Address([]byte(owner)), + atree.SlabIndex([]byte(key[1:])), + ) + + storageIDs = append(storageIDs, slabID) + + return nil + }) + if err != nil { + return nil, err + } + + return storageIDs, nil +} + +func (td *TokenChanges) isRelevantSlabIndexKey(owner, key string) bool { + if owner == td.evmStorageAccount { + // skip EVM slabs for now + return false + } + + return flow.IsSlabIndexKey(key) +} + +var tokenDiffSearchDomains = []common.StorageDomain{ + common.StorageDomainPathStorage, + common.StorageDomainContract, + common.StorageDomainInbox, +} + +type TokenChangesSearchTokens map[string]SearchToken + +// DefaultTokenDiffSearchTokens returns the default settings for token inspection +func DefaultTokenDiffSearchTokens(chain flow.Chain) TokenChangesSearchTokens { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + flowTokenID := fmt.Sprintf("A.%s.FlowToken.Vault", sc.FlowToken.Address.Hex()) + flowTokenMintedEventID := fmt.Sprintf("A.%s.FlowToken.TokensMinted", sc.FlowToken.Address.Hex()) + + searchTokens := map[string]SearchToken{ + flowTokenID: { + ID: flowTokenID, + GetBalance: func(value *interpreter.CompositeValue) uint64 { + return uint64(value.GetField(nil, "balance").(interpreter.UFix64Value).UFix64Value) + }, + SinksSources: map[string]func(flow.Event) (int64, error){}, + }, + } + searchTokens[flowTokenID].SinksSources[flowTokenMintedEventID] = decodeFlowEventAmount(false) + + // EVM bridge events: FLOW tokens moving between Cadence and EVM. + // Deposited = tokens leave Cadence into EVM (sink, negative). + // Withdrawn = tokens leave EVM into Cadence (source, positive). + evmDepositedEventID := fmt.Sprintf("A.%s.EVM.FLOWTokensDeposited", sc.EVMContract.Address.Hex()) + evmWithdrawnEventID := fmt.Sprintf("A.%s.EVM.FLOWTokensWithdrawn", sc.EVMContract.Address.Hex()) + + searchTokens[flowTokenID].SinksSources[evmDepositedEventID] = decodeFlowEventAmount(true) + searchTokens[flowTokenID].SinksSources[evmWithdrawnEventID] = decodeFlowEventAmount(false) + + return searchTokens +} + +// decodeFlowEventAmount returns a function that decodes the "amount" field from a +// CCF-encoded event as a UFix64. If isSink is true, the returned value is negated +// (tokens leaving Cadence). If isSink is false, the value is positive (tokens +// entering Cadence). +func decodeFlowEventAmount(isSink bool) func(flow.Event) (int64, error) { + return func(evt flow.Event) (int64, error) { + payload, err := ccf.Decode(nil, evt.Payload) + if err != nil { + return 0, err + } + + ufix, ok := payload.(cadence.Event).SearchFieldByName("amount").(cadence.UFix64) + if !ok { + return 0, fmt.Errorf("amount field is not a cadence.UFix64") + } + + if ufix > math.MaxInt64 { + return 0, fmt.Errorf("amount field is too large") + } + + if isSink { + return -int64(ufix), nil + } + return int64(ufix), nil + } +} diff --git a/fvm/meter/memory_meter.go b/fvm/meter/memory_meter.go index d600abf9b4a..2ba7ba288d0 100644 --- a/fvm/meter/memory_meter.go +++ b/fvm/meter/memory_meter.go @@ -38,8 +38,10 @@ var ( common.MemoryKindInterpretedFunctionValue: 128, common.MemoryKindHostFunctionValue: 41, common.MemoryKindBoundFunctionValue: 25, + common.MemoryKindWrappedFunctionValue: 25, common.MemoryKindBigInt: 50, common.MemoryKindVoidExpression: 1, + common.MemoryKindStringBuilder: 138, // Atree @@ -184,6 +186,7 @@ var ( common.MemoryKindSwitchStatement: 41, common.MemoryKindWhileStatement: 25, common.MemoryKindRemoveStatement: 33, + common.MemoryKindGuardStatement: 25, common.MemoryKindBooleanExpression: 9, common.MemoryKindNilExpression: 1, diff --git a/fvm/mock/procedure.go b/fvm/mock/procedure.go index 51420176b0a..967b76af008 100644 --- a/fvm/mock/procedure.go +++ b/fvm/mock/procedure.go @@ -1,140 +1,339 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - fvm "github.com/onflow/flow-go/fvm" - logical "github.com/onflow/flow-go/fvm/storage/logical" + "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm/storage" + "github.com/onflow/flow-go/fvm/storage/logical" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/fvm/storage" ) +// NewProcedure creates a new instance of Procedure. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProcedure(t interface { + mock.TestingT + Cleanup(func()) +}) *Procedure { + mock := &Procedure{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Procedure is an autogenerated mock type for the Procedure type type Procedure struct { mock.Mock } -// ComputationLimit provides a mock function with given fields: ctx -func (_m *Procedure) ComputationLimit(ctx fvm.Context) uint64 { - ret := _m.Called(ctx) +type Procedure_Expecter struct { + mock *mock.Mock +} + +func (_m *Procedure) EXPECT() *Procedure_Expecter { + return &Procedure_Expecter{mock: &_m.Mock} +} + +// ComputationLimit provides a mock function for the type Procedure +func (_mock *Procedure) ComputationLimit(ctx fvm.Context) uint64 { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for ComputationLimit") } var r0 uint64 - if rf, ok := ret.Get(0).(func(fvm.Context) uint64); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(fvm.Context) uint64); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Get(0).(uint64) } - return r0 } -// ExecutionTime provides a mock function with no fields -func (_m *Procedure) ExecutionTime() logical.Time { - ret := _m.Called() +// Procedure_ComputationLimit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ComputationLimit' +type Procedure_ComputationLimit_Call struct { + *mock.Call +} + +// ComputationLimit is a helper method to define mock.On call +// - ctx fvm.Context +func (_e *Procedure_Expecter) ComputationLimit(ctx interface{}) *Procedure_ComputationLimit_Call { + return &Procedure_ComputationLimit_Call{Call: _e.mock.On("ComputationLimit", ctx)} +} + +func (_c *Procedure_ComputationLimit_Call) Run(run func(ctx fvm.Context)) *Procedure_ComputationLimit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 fvm.Context + if args[0] != nil { + arg0 = args[0].(fvm.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Procedure_ComputationLimit_Call) Return(v uint64) *Procedure_ComputationLimit_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Procedure_ComputationLimit_Call) RunAndReturn(run func(ctx fvm.Context) uint64) *Procedure_ComputationLimit_Call { + _c.Call.Return(run) + return _c +} + +// ExecutionTime provides a mock function for the type Procedure +func (_mock *Procedure) ExecutionTime() logical.Time { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ExecutionTime") } var r0 logical.Time - if rf, ok := ret.Get(0).(func() logical.Time); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() logical.Time); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(logical.Time) } - return r0 } -// MemoryLimit provides a mock function with given fields: ctx -func (_m *Procedure) MemoryLimit(ctx fvm.Context) uint64 { - ret := _m.Called(ctx) +// Procedure_ExecutionTime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionTime' +type Procedure_ExecutionTime_Call struct { + *mock.Call +} + +// ExecutionTime is a helper method to define mock.On call +func (_e *Procedure_Expecter) ExecutionTime() *Procedure_ExecutionTime_Call { + return &Procedure_ExecutionTime_Call{Call: _e.mock.On("ExecutionTime")} +} + +func (_c *Procedure_ExecutionTime_Call) Run(run func()) *Procedure_ExecutionTime_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Procedure_ExecutionTime_Call) Return(time logical.Time) *Procedure_ExecutionTime_Call { + _c.Call.Return(time) + return _c +} + +func (_c *Procedure_ExecutionTime_Call) RunAndReturn(run func() logical.Time) *Procedure_ExecutionTime_Call { + _c.Call.Return(run) + return _c +} + +// MemoryLimit provides a mock function for the type Procedure +func (_mock *Procedure) MemoryLimit(ctx fvm.Context) uint64 { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for MemoryLimit") } var r0 uint64 - if rf, ok := ret.Get(0).(func(fvm.Context) uint64); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(fvm.Context) uint64); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewExecutor provides a mock function with given fields: ctx, txnState -func (_m *Procedure) NewExecutor(ctx fvm.Context, txnState storage.TransactionPreparer) fvm.ProcedureExecutor { - ret := _m.Called(ctx, txnState) +// Procedure_MemoryLimit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MemoryLimit' +type Procedure_MemoryLimit_Call struct { + *mock.Call +} + +// MemoryLimit is a helper method to define mock.On call +// - ctx fvm.Context +func (_e *Procedure_Expecter) MemoryLimit(ctx interface{}) *Procedure_MemoryLimit_Call { + return &Procedure_MemoryLimit_Call{Call: _e.mock.On("MemoryLimit", ctx)} +} + +func (_c *Procedure_MemoryLimit_Call) Run(run func(ctx fvm.Context)) *Procedure_MemoryLimit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 fvm.Context + if args[0] != nil { + arg0 = args[0].(fvm.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Procedure_MemoryLimit_Call) Return(v uint64) *Procedure_MemoryLimit_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Procedure_MemoryLimit_Call) RunAndReturn(run func(ctx fvm.Context) uint64) *Procedure_MemoryLimit_Call { + _c.Call.Return(run) + return _c +} + +// NewExecutor provides a mock function for the type Procedure +func (_mock *Procedure) NewExecutor(ctx fvm.Context, txnState storage.TransactionPreparer) fvm.ProcedureExecutor { + ret := _mock.Called(ctx, txnState) if len(ret) == 0 { panic("no return value specified for NewExecutor") } var r0 fvm.ProcedureExecutor - if rf, ok := ret.Get(0).(func(fvm.Context, storage.TransactionPreparer) fvm.ProcedureExecutor); ok { - r0 = rf(ctx, txnState) + if returnFunc, ok := ret.Get(0).(func(fvm.Context, storage.TransactionPreparer) fvm.ProcedureExecutor); ok { + r0 = returnFunc(ctx, txnState) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(fvm.ProcedureExecutor) } } - return r0 } -// ShouldDisableMemoryAndInteractionLimits provides a mock function with given fields: ctx -func (_m *Procedure) ShouldDisableMemoryAndInteractionLimits(ctx fvm.Context) bool { - ret := _m.Called(ctx) +// Procedure_NewExecutor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewExecutor' +type Procedure_NewExecutor_Call struct { + *mock.Call +} + +// NewExecutor is a helper method to define mock.On call +// - ctx fvm.Context +// - txnState storage.TransactionPreparer +func (_e *Procedure_Expecter) NewExecutor(ctx interface{}, txnState interface{}) *Procedure_NewExecutor_Call { + return &Procedure_NewExecutor_Call{Call: _e.mock.On("NewExecutor", ctx, txnState)} +} + +func (_c *Procedure_NewExecutor_Call) Run(run func(ctx fvm.Context, txnState storage.TransactionPreparer)) *Procedure_NewExecutor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 fvm.Context + if args[0] != nil { + arg0 = args[0].(fvm.Context) + } + var arg1 storage.TransactionPreparer + if args[1] != nil { + arg1 = args[1].(storage.TransactionPreparer) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Procedure_NewExecutor_Call) Return(procedureExecutor fvm.ProcedureExecutor) *Procedure_NewExecutor_Call { + _c.Call.Return(procedureExecutor) + return _c +} + +func (_c *Procedure_NewExecutor_Call) RunAndReturn(run func(ctx fvm.Context, txnState storage.TransactionPreparer) fvm.ProcedureExecutor) *Procedure_NewExecutor_Call { + _c.Call.Return(run) + return _c +} + +// ShouldDisableMemoryAndInteractionLimits provides a mock function for the type Procedure +func (_mock *Procedure) ShouldDisableMemoryAndInteractionLimits(ctx fvm.Context) bool { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for ShouldDisableMemoryAndInteractionLimits") } var r0 bool - if rf, ok := ret.Get(0).(func(fvm.Context) bool); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(fvm.Context) bool); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Type provides a mock function with no fields -func (_m *Procedure) Type() fvm.ProcedureType { - ret := _m.Called() +// Procedure_ShouldDisableMemoryAndInteractionLimits_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShouldDisableMemoryAndInteractionLimits' +type Procedure_ShouldDisableMemoryAndInteractionLimits_Call struct { + *mock.Call +} + +// ShouldDisableMemoryAndInteractionLimits is a helper method to define mock.On call +// - ctx fvm.Context +func (_e *Procedure_Expecter) ShouldDisableMemoryAndInteractionLimits(ctx interface{}) *Procedure_ShouldDisableMemoryAndInteractionLimits_Call { + return &Procedure_ShouldDisableMemoryAndInteractionLimits_Call{Call: _e.mock.On("ShouldDisableMemoryAndInteractionLimits", ctx)} +} + +func (_c *Procedure_ShouldDisableMemoryAndInteractionLimits_Call) Run(run func(ctx fvm.Context)) *Procedure_ShouldDisableMemoryAndInteractionLimits_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 fvm.Context + if args[0] != nil { + arg0 = args[0].(fvm.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Procedure_ShouldDisableMemoryAndInteractionLimits_Call) Return(b bool) *Procedure_ShouldDisableMemoryAndInteractionLimits_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Procedure_ShouldDisableMemoryAndInteractionLimits_Call) RunAndReturn(run func(ctx fvm.Context) bool) *Procedure_ShouldDisableMemoryAndInteractionLimits_Call { + _c.Call.Return(run) + return _c +} + +// Type provides a mock function for the type Procedure +func (_mock *Procedure) Type() fvm.ProcedureType { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Type") } var r0 fvm.ProcedureType - if rf, ok := ret.Get(0).(func() fvm.ProcedureType); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() fvm.ProcedureType); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(fvm.ProcedureType) } - return r0 } -// NewProcedure creates a new instance of Procedure. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProcedure(t interface { - mock.TestingT - Cleanup(func()) -}) *Procedure { - mock := &Procedure{} - mock.Mock.Test(t) +// Procedure_Type_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Type' +type Procedure_Type_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Type is a helper method to define mock.On call +func (_e *Procedure_Expecter) Type() *Procedure_Type_Call { + return &Procedure_Type_Call{Call: _e.mock.On("Type")} +} - return mock +func (_c *Procedure_Type_Call) Run(run func()) *Procedure_Type_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Procedure_Type_Call) Return(procedureType fvm.ProcedureType) *Procedure_Type_Call { + _c.Call.Return(procedureType) + return _c +} + +func (_c *Procedure_Type_Call) RunAndReturn(run func() fvm.ProcedureType) *Procedure_Type_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/mock/procedure_executor.go b/fvm/mock/procedure_executor.go index 14fb580b89b..a2bd1a4f697 100644 --- a/fvm/mock/procedure_executor.go +++ b/fvm/mock/procedure_executor.go @@ -1,86 +1,202 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - fvm "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm" mock "github.com/stretchr/testify/mock" ) +// NewProcedureExecutor creates a new instance of ProcedureExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProcedureExecutor(t interface { + mock.TestingT + Cleanup(func()) +}) *ProcedureExecutor { + mock := &ProcedureExecutor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ProcedureExecutor is an autogenerated mock type for the ProcedureExecutor type type ProcedureExecutor struct { mock.Mock } -// Cleanup provides a mock function with no fields -func (_m *ProcedureExecutor) Cleanup() { - _m.Called() +type ProcedureExecutor_Expecter struct { + mock *mock.Mock +} + +func (_m *ProcedureExecutor) EXPECT() *ProcedureExecutor_Expecter { + return &ProcedureExecutor_Expecter{mock: &_m.Mock} +} + +// Cleanup provides a mock function for the type ProcedureExecutor +func (_mock *ProcedureExecutor) Cleanup() { + _mock.Called() + return } -// Execute provides a mock function with no fields -func (_m *ProcedureExecutor) Execute() error { - ret := _m.Called() +// ProcedureExecutor_Cleanup_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Cleanup' +type ProcedureExecutor_Cleanup_Call struct { + *mock.Call +} + +// Cleanup is a helper method to define mock.On call +func (_e *ProcedureExecutor_Expecter) Cleanup() *ProcedureExecutor_Cleanup_Call { + return &ProcedureExecutor_Cleanup_Call{Call: _e.mock.On("Cleanup")} +} + +func (_c *ProcedureExecutor_Cleanup_Call) Run(run func()) *ProcedureExecutor_Cleanup_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ProcedureExecutor_Cleanup_Call) Return() *ProcedureExecutor_Cleanup_Call { + _c.Call.Return() + return _c +} + +func (_c *ProcedureExecutor_Cleanup_Call) RunAndReturn(run func()) *ProcedureExecutor_Cleanup_Call { + _c.Run(run) + return _c +} + +// Execute provides a mock function for the type ProcedureExecutor +func (_mock *ProcedureExecutor) Execute() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Execute") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Output provides a mock function with no fields -func (_m *ProcedureExecutor) Output() fvm.ProcedureOutput { - ret := _m.Called() +// ProcedureExecutor_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type ProcedureExecutor_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *ProcedureExecutor_Expecter) Execute() *ProcedureExecutor_Execute_Call { + return &ProcedureExecutor_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *ProcedureExecutor_Execute_Call) Run(run func()) *ProcedureExecutor_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ProcedureExecutor_Execute_Call) Return(err error) *ProcedureExecutor_Execute_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ProcedureExecutor_Execute_Call) RunAndReturn(run func() error) *ProcedureExecutor_Execute_Call { + _c.Call.Return(run) + return _c +} + +// Output provides a mock function for the type ProcedureExecutor +func (_mock *ProcedureExecutor) Output() fvm.ProcedureOutput { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Output") } var r0 fvm.ProcedureOutput - if rf, ok := ret.Get(0).(func() fvm.ProcedureOutput); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() fvm.ProcedureOutput); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(fvm.ProcedureOutput) } - return r0 } -// Preprocess provides a mock function with no fields -func (_m *ProcedureExecutor) Preprocess() error { - ret := _m.Called() +// ProcedureExecutor_Output_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Output' +type ProcedureExecutor_Output_Call struct { + *mock.Call +} + +// Output is a helper method to define mock.On call +func (_e *ProcedureExecutor_Expecter) Output() *ProcedureExecutor_Output_Call { + return &ProcedureExecutor_Output_Call{Call: _e.mock.On("Output")} +} + +func (_c *ProcedureExecutor_Output_Call) Run(run func()) *ProcedureExecutor_Output_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ProcedureExecutor_Output_Call) Return(procedureOutput fvm.ProcedureOutput) *ProcedureExecutor_Output_Call { + _c.Call.Return(procedureOutput) + return _c +} + +func (_c *ProcedureExecutor_Output_Call) RunAndReturn(run func() fvm.ProcedureOutput) *ProcedureExecutor_Output_Call { + _c.Call.Return(run) + return _c +} + +// Preprocess provides a mock function for the type ProcedureExecutor +func (_mock *ProcedureExecutor) Preprocess() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Preprocess") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// NewProcedureExecutor creates a new instance of ProcedureExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProcedureExecutor(t interface { - mock.TestingT - Cleanup(func()) -}) *ProcedureExecutor { - mock := &ProcedureExecutor{} - mock.Mock.Test(t) +// ProcedureExecutor_Preprocess_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Preprocess' +type ProcedureExecutor_Preprocess_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Preprocess is a helper method to define mock.On call +func (_e *ProcedureExecutor_Expecter) Preprocess() *ProcedureExecutor_Preprocess_Call { + return &ProcedureExecutor_Preprocess_Call{Call: _e.mock.On("Preprocess")} +} - return mock +func (_c *ProcedureExecutor_Preprocess_Call) Run(run func()) *ProcedureExecutor_Preprocess_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ProcedureExecutor_Preprocess_Call) Return(err error) *ProcedureExecutor_Preprocess_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ProcedureExecutor_Preprocess_Call) RunAndReturn(run func() error) *ProcedureExecutor_Preprocess_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/mock/vm.go b/fvm/mock/vm.go index 12e27262997..1faa116eeee 100644 --- a/fvm/mock/vm.go +++ b/fvm/mock/vm.go @@ -1,44 +1,111 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - fvm "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm" + "github.com/onflow/flow-go/fvm/storage" + "github.com/onflow/flow-go/fvm/storage/snapshot" mock "github.com/stretchr/testify/mock" +) + +// NewVM creates a new instance of VM. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVM(t interface { + mock.TestingT + Cleanup(func()) +}) *VM { + mock := &VM{} + mock.Mock.Test(t) - snapshot "github.com/onflow/flow-go/fvm/storage/snapshot" + t.Cleanup(func() { mock.AssertExpectations(t) }) - storage "github.com/onflow/flow-go/fvm/storage" -) + return mock +} // VM is an autogenerated mock type for the VM type type VM struct { mock.Mock } -// NewExecutor provides a mock function with given fields: _a0, _a1, _a2 -func (_m *VM) NewExecutor(_a0 fvm.Context, _a1 fvm.Procedure, _a2 storage.TransactionPreparer) fvm.ProcedureExecutor { - ret := _m.Called(_a0, _a1, _a2) +type VM_Expecter struct { + mock *mock.Mock +} + +func (_m *VM) EXPECT() *VM_Expecter { + return &VM_Expecter{mock: &_m.Mock} +} + +// NewExecutor provides a mock function for the type VM +func (_mock *VM) NewExecutor(context fvm.Context, procedure fvm.Procedure, transactionPreparer storage.TransactionPreparer) fvm.ProcedureExecutor { + ret := _mock.Called(context, procedure, transactionPreparer) if len(ret) == 0 { panic("no return value specified for NewExecutor") } var r0 fvm.ProcedureExecutor - if rf, ok := ret.Get(0).(func(fvm.Context, fvm.Procedure, storage.TransactionPreparer) fvm.ProcedureExecutor); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(fvm.Context, fvm.Procedure, storage.TransactionPreparer) fvm.ProcedureExecutor); ok { + r0 = returnFunc(context, procedure, transactionPreparer) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(fvm.ProcedureExecutor) } } - return r0 } -// Run provides a mock function with given fields: _a0, _a1, _a2 -func (_m *VM) Run(_a0 fvm.Context, _a1 fvm.Procedure, _a2 snapshot.StorageSnapshot) (*snapshot.ExecutionSnapshot, fvm.ProcedureOutput, error) { - ret := _m.Called(_a0, _a1, _a2) +// VM_NewExecutor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewExecutor' +type VM_NewExecutor_Call struct { + *mock.Call +} + +// NewExecutor is a helper method to define mock.On call +// - context fvm.Context +// - procedure fvm.Procedure +// - transactionPreparer storage.TransactionPreparer +func (_e *VM_Expecter) NewExecutor(context interface{}, procedure interface{}, transactionPreparer interface{}) *VM_NewExecutor_Call { + return &VM_NewExecutor_Call{Call: _e.mock.On("NewExecutor", context, procedure, transactionPreparer)} +} + +func (_c *VM_NewExecutor_Call) Run(run func(context fvm.Context, procedure fvm.Procedure, transactionPreparer storage.TransactionPreparer)) *VM_NewExecutor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 fvm.Context + if args[0] != nil { + arg0 = args[0].(fvm.Context) + } + var arg1 fvm.Procedure + if args[1] != nil { + arg1 = args[1].(fvm.Procedure) + } + var arg2 storage.TransactionPreparer + if args[2] != nil { + arg2 = args[2].(storage.TransactionPreparer) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *VM_NewExecutor_Call) Return(procedureExecutor fvm.ProcedureExecutor) *VM_NewExecutor_Call { + _c.Call.Return(procedureExecutor) + return _c +} + +func (_c *VM_NewExecutor_Call) RunAndReturn(run func(context fvm.Context, procedure fvm.Procedure, transactionPreparer storage.TransactionPreparer) fvm.ProcedureExecutor) *VM_NewExecutor_Call { + _c.Call.Return(run) + return _c +} + +// Run provides a mock function for the type VM +func (_mock *VM) Run(context fvm.Context, procedure fvm.Procedure, storageSnapshot snapshot.StorageSnapshot) (*snapshot.ExecutionSnapshot, fvm.ProcedureOutput, error) { + ret := _mock.Called(context, procedure, storageSnapshot) if len(ret) == 0 { panic("no return value specified for Run") @@ -47,42 +114,71 @@ func (_m *VM) Run(_a0 fvm.Context, _a1 fvm.Procedure, _a2 snapshot.StorageSnapsh var r0 *snapshot.ExecutionSnapshot var r1 fvm.ProcedureOutput var r2 error - if rf, ok := ret.Get(0).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) (*snapshot.ExecutionSnapshot, fvm.ProcedureOutput, error)); ok { - return rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) (*snapshot.ExecutionSnapshot, fvm.ProcedureOutput, error)); ok { + return returnFunc(context, procedure, storageSnapshot) } - if rf, ok := ret.Get(0).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) *snapshot.ExecutionSnapshot); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) *snapshot.ExecutionSnapshot); ok { + r0 = returnFunc(context, procedure, storageSnapshot) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*snapshot.ExecutionSnapshot) } } - - if rf, ok := ret.Get(1).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) fvm.ProcedureOutput); ok { - r1 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(1).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) fvm.ProcedureOutput); ok { + r1 = returnFunc(context, procedure, storageSnapshot) } else { r1 = ret.Get(1).(fvm.ProcedureOutput) } - - if rf, ok := ret.Get(2).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) error); ok { - r2 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(2).(func(fvm.Context, fvm.Procedure, snapshot.StorageSnapshot) error); ok { + r2 = returnFunc(context, procedure, storageSnapshot) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewVM creates a new instance of VM. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVM(t interface { - mock.TestingT - Cleanup(func()) -}) *VM { - mock := &VM{} - mock.Mock.Test(t) +// VM_Run_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Run' +type VM_Run_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Run is a helper method to define mock.On call +// - context fvm.Context +// - procedure fvm.Procedure +// - storageSnapshot snapshot.StorageSnapshot +func (_e *VM_Expecter) Run(context interface{}, procedure interface{}, storageSnapshot interface{}) *VM_Run_Call { + return &VM_Run_Call{Call: _e.mock.On("Run", context, procedure, storageSnapshot)} +} - return mock +func (_c *VM_Run_Call) Run(run func(context fvm.Context, procedure fvm.Procedure, storageSnapshot snapshot.StorageSnapshot)) *VM_Run_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 fvm.Context + if args[0] != nil { + arg0 = args[0].(fvm.Context) + } + var arg1 fvm.Procedure + if args[1] != nil { + arg1 = args[1].(fvm.Procedure) + } + var arg2 snapshot.StorageSnapshot + if args[2] != nil { + arg2 = args[2].(snapshot.StorageSnapshot) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *VM_Run_Call) Return(executionSnapshot *snapshot.ExecutionSnapshot, procedureOutput fvm.ProcedureOutput, err error) *VM_Run_Call { + _c.Call.Return(executionSnapshot, procedureOutput, err) + return _c +} + +func (_c *VM_Run_Call) RunAndReturn(run func(context fvm.Context, procedure fvm.Procedure, storageSnapshot snapshot.StorageSnapshot) (*snapshot.ExecutionSnapshot, fvm.ProcedureOutput, error)) *VM_Run_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/runtime/cadence_function_declarations.go b/fvm/runtime/cadence_function_declarations.go new file mode 100644 index 00000000000..2a7e50848a6 --- /dev/null +++ b/fvm/runtime/cadence_function_declarations.go @@ -0,0 +1,210 @@ +package runtime + +import ( + "github.com/onflow/cadence/bbq/vm" + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/interpreter" + "github.com/onflow/cadence/sema" + "github.com/onflow/cadence/stdlib" + + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm" + "github.com/onflow/flow-go/fvm/evm/backends" + "github.com/onflow/flow-go/fvm/evm/emulator" + "github.com/onflow/flow-go/fvm/evm/handler" + "github.com/onflow/flow-go/fvm/evm/impl" + evmstdlib "github.com/onflow/flow-go/fvm/evm/stdlib" + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/flow" +) + +// randomSourceHistoryFunctionName is the name of the `randomSourceHistory` function. +const randomSourceHistoryFunctionName = "randomSourceHistory" + +// getTransactionIndexFunctionName is the name of the `getTransactionIndex` function. +const getTransactionIndexFunctionName = "getTransactionIndex" + +// randomSourceFunctionType is the type of the `randomSourceHistory` function. +// This defines the signature as `func(): [UInt8]` +var randomSourceFunctionType = &sema.FunctionType{ + ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.ByteArrayType), +} + +// transactionIndexFunctionType is the type of the `getTransactionIndex` function. +// This defines the signature as `func(): UInt32` +var transactionIndexFunctionType = &sema.FunctionType{ + ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.UInt32Type), +} + +// randomSourceHistoryNativeFunction returns the native function backing the +// `randomSourceHistory` declaration. It is usable in both the interpreter and the VM. +// +// The `randomSourceHistory` function is **only** used by the System transaction, +// to fill the `RandomBeaconHistory` contract via the heartbeat resource. +// This allows the `RandomBeaconHistory` contract to be a standard contract, +// without any special parts. +// Since the `randomSourceHistory` function is only used by the System transaction, +// it is not part of the cadence standard library, and can just be injected from here. +// It also doesn't need user documentation, since it is not (and should not) +// be called by the user. If it is called by the user it will panic. +func randomSourceHistoryNativeFunction(fvmEnv environment.Environment) interpreter.NativeFunction { + return func( + context interpreter.NativeFunctionContext, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, + _ []interpreter.Value, + ) interpreter.Value { + source, err := fvmEnv.RandomSourceHistory() + if err != nil { + panic(err) + } + + return interpreter.ByteSliceToByteArrayValue(context, source) + } +} + +// InterpreterBlockRandomSourceDeclaration returns the interpreter declaration for the +// `randomSourceHistory` function. +// If the environment is a SwappableEnvironment the underlying environment can be swapped without +// causing issues. +func InterpreterBlockRandomSourceDeclaration(fvmEnv environment.Environment) stdlib.StandardLibraryValue { + return stdlib.StandardLibraryValue{ + Name: randomSourceHistoryFunctionName, + Type: randomSourceFunctionType, + Kind: common.DeclarationKindFunction, + Value: interpreter.NewUnmeteredStaticHostFunctionValueFromNativeFunction( + randomSourceFunctionType, + randomSourceHistoryNativeFunction(fvmEnv), + ), + } +} + +// VMBlockRandomSourceDeclaration returns the VM declaration for the `randomSourceHistory` function. +// If the environment is a SwappableEnvironment the underlying environment can be swapped without +// causing issues. +func VMBlockRandomSourceDeclaration(fvmEnv environment.Environment) stdlib.StandardLibraryValue { + return stdlib.StandardLibraryValue{ + Name: randomSourceHistoryFunctionName, + Type: randomSourceFunctionType, + Kind: common.DeclarationKindFunction, + Value: vm.NewNativeFunctionValue( + randomSourceHistoryFunctionName, + randomSourceFunctionType, + randomSourceHistoryNativeFunction(fvmEnv), + ), + } +} + +// transactionIndexNativeFunction returns the native function backing the `getTransactionIndex` +// declaration. It is usable in both the interpreter and the VM. +func transactionIndexNativeFunction(fvmEnv environment.Environment) interpreter.NativeFunction { + return func( + context interpreter.NativeFunctionContext, + _ interpreter.TypeArgumentsIterator, + _ interpreter.ArgumentTypesIterator, + _ interpreter.Value, + _ []interpreter.Value, + ) interpreter.Value { + return interpreter.NewUInt32Value( + context, + func() uint32 { + return fvmEnv.TxIndex() + }, + ) + } +} + +// transactionIndexDocString documents the `getTransactionIndex` function. +const transactionIndexDocString = `Returns the transaction index in the current block, i.e. first transaction in a block has index of 0, second has index of 1...` + +// InterpreterTransactionIndexDeclaration returns the interpreter declaration for the +// `getTransactionIndex` function. +// If the environment is a SwappableEnvironment the underlying environment can be swapped without +// causing issues. +func InterpreterTransactionIndexDeclaration(fvmEnv environment.Environment) stdlib.StandardLibraryValue { + return stdlib.StandardLibraryValue{ + Name: getTransactionIndexFunctionName, + DocString: transactionIndexDocString, + Type: transactionIndexFunctionType, + Kind: common.DeclarationKindFunction, + Value: interpreter.NewUnmeteredStaticHostFunctionValueFromNativeFunction( + transactionIndexFunctionType, + transactionIndexNativeFunction(fvmEnv), + ), + } +} + +// VMTransactionIndexDeclaration returns the VM declaration for the `getTransactionIndex` function. +// If the environment is a SwappableEnvironment the underlying environment can be swapped without +// causing issues. +func VMTransactionIndexDeclaration(fvmEnv environment.Environment) stdlib.StandardLibraryValue { + return stdlib.StandardLibraryValue{ + Name: getTransactionIndexFunctionName, + DocString: transactionIndexDocString, + Type: transactionIndexFunctionType, + Kind: common.DeclarationKindFunction, + Value: vm.NewNativeFunctionValue( + getTransactionIndexFunctionName, + transactionIndexFunctionType, + transactionIndexNativeFunction(fvmEnv), + ), + } +} + +// EVMInternalEVMContract creates the internal EVM contract value (used by the interpreter) and the +// internal EVM functions (used by the VM) for the specified ChainID and environment. Both share a +// single underlying contract handler so that EVM state and caches are consistent regardless of +// whether a procedure executes via the interpreter or the VM. +// +// If the environment is a SwappableEnvironment the underlying environment can be swapped without +// causing issues. +// +// Returns a nil contract value and a zero-valued functions struct if fvmEnv is nil. +func EVMInternalEVMContract( + chainID flow.ChainID, + fvmEnv environment.Environment, +) (*interpreter.SimpleCompositeValue, evmstdlib.InternalEVMFunctions) { + if fvmEnv == nil { + return nil, evmstdlib.InternalEVMFunctions{} + } + sc := systemcontracts.SystemContractsForChain(chainID) + randomBeaconAddress := sc.RandomBeaconHistory.Address + flowTokenAddress := sc.FlowToken.Address + + evmBackend := backends.NewWrappedEnvironment(fvmEnv) + evmEmulator := emulator.NewEmulator(evmBackend, evm.StorageAccountAddress(chainID)) + addressAllocator := handler.NewAddressAllocator() + + evmContractAddress := evm.ContractAccountAddress(chainID) + + contractHandler := handler.NewContractHandler( + chainID, + evmContractAddress, + common.Address(flowTokenAddress), + randomBeaconAddress, + addressAllocator, + evmBackend, + evmEmulator, + ) + + // Register cache cleanup callback on the SwappableEnvironment. + // This ensures the cache is cleared whenever the runtime is + // borrowed for a new transaction or returned to the pool. + if se, ok := fvmEnv.(*SwappableEnvironment); ok { + se.RegisterOnSwapCallback(contractHandler.ResetCaches) + } + + internalEVMValue := impl.NewInternalEVMContractValue( + nil, + contractHandler, + evmContractAddress, + ) + + internalEVMFunctions := impl.NewInternalEVMFunctions( + contractHandler, + evmContractAddress, + ) + + return internalEVMValue, internalEVMFunctions +} diff --git a/fvm/runtime/reusable_cadence_runtime.go b/fvm/runtime/reusable_cadence_runtime.go index f24392cad85..ccffcf8e527 100644 --- a/fvm/runtime/reusable_cadence_runtime.go +++ b/fvm/runtime/reusable_cadence_runtime.go @@ -2,142 +2,178 @@ package runtime import ( "github.com/onflow/cadence" - "github.com/onflow/cadence/bbq/vm" "github.com/onflow/cadence/common" - "github.com/onflow/cadence/interpreter" "github.com/onflow/cadence/runtime" "github.com/onflow/cadence/sema" - "github.com/onflow/cadence/stdlib" - "github.com/onflow/flow-go/fvm/errors" + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/evm" + "github.com/onflow/flow-go/fvm/evm/stdlib" + "github.com/onflow/flow-go/model/flow" ) -// Note: this is a subset of environment.Environment, redeclared to handle -// circular dependency. -type Environment interface { - runtime.Interface - common.Gauge - - RandomSourceHistory() ([]byte, error) -} - -const randomSourceHistoryFunctionName = "randomSourceHistory" - -// randomSourceHistoryFunctionType is the type of the `randomSourceHistory` function. -// This defines the signature as `func(): [UInt8]` -var randomSourceHistoryFunctionType = &sema.FunctionType{ - ReturnTypeAnnotation: sema.NewTypeAnnotation(sema.ByteArrayType), -} - -type ReusableCadenceRuntime struct { +// TODO(JanezP): unexport all types in this file +// They are just used by some test + +// reusableCadenceRuntime is a wrapper around cadence Runtime and cadence Environment +// with pre-injected cadence context for: EVM, getTransactionIndex, ... +// it can be reused by changing the fvmEnv. The reuse happens accross blocks and between scripts and transactions +// +// This exists because creating and setting up a cadence runtime and environment is a costly operation. +// This assumes that the following objects are safe to reuse across blocks: +// - cadence runtime +// - cadence environment +// - evm emulator (and related objects) +// +// There are four cadence runtime.Environments, one for each combination of +// {transaction, script} x {interpreter, VM}. The wrapper struct selected by the pool determines +// which environment is used (see reusableCadence{Transaction,Script}{,VM}Runtime). +type reusableCadenceRuntime struct { runtime.Runtime + chain flow.Chain + TxRuntimeEnv runtime.Environment ScriptRuntimeEnv runtime.Environment VMTxRuntimeEnv runtime.Environment VMScriptRuntimeEnv runtime.Environment - fvmEnv Environment + fvmEnv *SwappableEnvironment } -func NewReusableCadenceRuntime( +// SwappableEnvironment is a wrapper type that extends the functionality of environment.Environment. +// It is designed to allow dynamic replacement of the underlying environment implementation. +type SwappableEnvironment struct { + environment.Environment + onSwap []func() // Callbacks triggered on every SetFvmEnvironment call. +} + +// RegisterOnSwapCallback registers a callback that is invoked whenever +// the underlying Environment is swapped (during pool Borrow and Return). +// This enables long-lived, reusable objects to clear per-transaction +// caches at transaction boundaries. +func (se *SwappableEnvironment) RegisterOnSwapCallback(cb func()) { + se.onSwap = append(se.onSwap, cb) +} + +func newReusableCadenceRuntime( rt runtime.Runtime, + chain flow.Chain, config runtime.Config, -) *ReusableCadenceRuntime { - reusable := &ReusableCadenceRuntime{ +) *reusableCadenceRuntime { + reusable := &reusableCadenceRuntime{ Runtime: rt, + chain: chain, TxRuntimeEnv: runtime.NewBaseInterpreterEnvironment(config), ScriptRuntimeEnv: runtime.NewScriptInterpreterEnvironment(config), VMTxRuntimeEnv: runtime.NewBaseVMEnvironment(config), VMScriptRuntimeEnv: runtime.NewScriptVMEnvironment(config), + fvmEnv: &SwappableEnvironment{}, } - reusable.declareRandomSourceHistory() + reusable.declareStandardLibraryFunctions() return reusable } -func (reusable *ReusableCadenceRuntime) declareRandomSourceHistory() { - - // Declare the `randomSourceHistory` function. - // This function is **only** used by the System transaction, - // to fill the `RandomBeaconHistory` contract via the heartbeat resource. - // This allows the `RandomBeaconHistory` contract to be a standard contract, - // without any special parts. - // - // Since the `randomSourceHistory` function is only used by the System transaction, - // it is not part of the cadence standard library, and can just be injected from here. - // It also doesn't need user documentation, since it is not (and should not) - // be called by the user. If it is called by the user it will panic. - - randomSourceHistoryFunction := interpreter.NativeFunction( - func( - context interpreter.NativeFunctionContext, - _ interpreter.TypeArgumentsIterator, - _ interpreter.Value, - _ []interpreter.Value, - ) interpreter.Value { - return reusable.randomSourceHistory(context) - }, - ) - - reusable.TxRuntimeEnv.DeclareValue( - newRandomSourceHistoryFunctionValue( - interpreter.NewUnmeteredStaticHostFunctionValue( - randomSourceHistoryFunctionType, - interpreter.AdaptNativeFunctionForInterpreter( - randomSourceHistoryFunction, - ), - ), - ), - nil, - ) +func (reusable *reusableCadenceRuntime) declareStandardLibraryFunctions() { + fvmEnv := reusable.fvmEnv - reusable.VMTxRuntimeEnv.DeclareValue( - newRandomSourceHistoryFunctionValue( - vm.NewNativeFunctionValue( - randomSourceHistoryFunctionName, - randomSourceHistoryFunctionType, - randomSourceHistoryFunction, - ), - ), - nil, - ) + // random source for transactions (system transaction only) + reusable.TxRuntimeEnv.DeclareValue(InterpreterBlockRandomSourceDeclaration(fvmEnv), nil) + reusable.VMTxRuntimeEnv.DeclareValue(VMBlockRandomSourceDeclaration(fvmEnv), nil) + + // transaction index (transactions and scripts) + reusable.TxRuntimeEnv.DeclareValue(InterpreterTransactionIndexDeclaration(fvmEnv), nil) + reusable.ScriptRuntimeEnv.DeclareValue(InterpreterTransactionIndexDeclaration(fvmEnv), nil) + reusable.VMTxRuntimeEnv.DeclareValue(VMTransactionIndexDeclaration(fvmEnv), nil) + reusable.VMScriptRuntimeEnv.DeclareValue(VMTransactionIndexDeclaration(fvmEnv), nil) + + // EVM: the interpreter contract value and the VM functions share a single contract handler. + evmInternalContractValue, evmInternalFunctions := EVMInternalEVMContract(reusable.chain.ChainID(), fvmEnv) + evmContractAddress := evm.ContractAccountAddress(reusable.chain.ChainID()) + + for _, env := range []runtime.Environment{ + reusable.TxRuntimeEnv, + reusable.ScriptRuntimeEnv, + reusable.VMTxRuntimeEnv, + reusable.VMScriptRuntimeEnv, + } { + stdlib.SetupEnvironment( + env, + evmInternalContractValue, + evmInternalFunctions, + evmContractAddress, + ) + } } -func newRandomSourceHistoryFunctionValue(functionValue interpreter.FunctionValue) stdlib.StandardLibraryValue { - return stdlib.StandardLibraryValue{ - Name: randomSourceHistoryFunctionName, - Type: randomSourceHistoryFunctionType, - Kind: common.DeclarationKindFunction, - Value: functionValue, +func (reusable *reusableCadenceRuntime) SetFvmEnvironment(fvmEnv environment.Environment) { + for _, fn := range reusable.fvmEnv.onSwap { + fn() } + reusable.fvmEnv.Environment = fvmEnv } -func (reusable *ReusableCadenceRuntime) randomSourceHistory(context interpreter.InvocationContext) interpreter.Value { - fvmEnv := reusable.fvmEnv - if fvmEnv == nil { - panic(errors.NewOperationNotSupportedError(randomSourceHistoryFunctionName)) - } +func (reusable *reusableCadenceRuntime) CadenceTXEnv() runtime.Environment { + return reusable.TxRuntimeEnv +} - source, err := fvmEnv.RandomSourceHistory() - if err != nil { - panic(err) - } +func (reusable *reusableCadenceRuntime) CadenceScriptEnv() runtime.Environment { + return reusable.ScriptRuntimeEnv +} - return interpreter.ByteSliceToByteArrayValue( - context, - source, +// newTransactionExecutor returns a cadence transaction executor using the given environment. +// When useVM is true, the cadence VM is used to execute the transaction. +func (reusable *reusableCadenceRuntime) newTransactionExecutor( + script runtime.Script, + location common.Location, + env runtime.Environment, + useVM bool, +) runtime.Executor { + return reusable.Runtime.NewTransactionExecutor( + script, + runtime.Context{ + Interface: reusable.fvmEnv, + Location: location, + Environment: env, + UseVM: useVM, + MemoryGauge: reusable.fvmEnv, + ComputationGauge: reusable.fvmEnv, + }, ) } -func (reusable *ReusableCadenceRuntime) SetFvmEnvironment(fvmEnv Environment) { - reusable.fvmEnv = fvmEnv +// executeScript executes the given script using the given environment. +// When useVM is true, the cadence VM is used to execute the script. +func (reusable *reusableCadenceRuntime) executeScript( + script runtime.Script, + location common.Location, + env runtime.Environment, + useVM bool, +) ( + cadence.Value, + error, +) { + return reusable.Runtime.ExecuteScript( + script, + runtime.Context{ + Interface: reusable.fvmEnv, + Location: location, + Environment: env, + UseVM: useVM, + MemoryGauge: reusable.fvmEnv, + ComputationGauge: reusable.fvmEnv, + }, + ) } -func (reusable *ReusableCadenceRuntime) ReadStored( +// readStored reads the stored value at the given path using the given environment. +// Reading stored values does not differ between the interpreter and the VM, so UseVM is not set. +func (reusable *reusableCadenceRuntime) readStored( address common.Address, path cadence.Path, + env runtime.Environment, ) ( cadence.Value, error, @@ -146,33 +182,27 @@ func (reusable *ReusableCadenceRuntime) ReadStored( address, path, runtime.Context{ - Interface: reusable.fvmEnv, - // No difference between VM and interpreter environments here, - // and UseVM is ignored. - Environment: reusable.TxRuntimeEnv, + Interface: reusable.fvmEnv, + Environment: env, MemoryGauge: reusable.fvmEnv, ComputationGauge: reusable.fvmEnv, }, ) } -func (reusable *ReusableCadenceRuntime) InvokeContractFunction( +// invokeContractFunction invokes the given contract function using the given environment. +// When useVM is true, the cadence VM is used to invoke the function. +func (reusable *reusableCadenceRuntime) invokeContractFunction( contractLocation common.AddressLocation, functionName string, arguments []cadence.Value, argumentTypes []sema.Type, + env runtime.Environment, useVM bool, ) ( cadence.Value, error, ) { - var environment runtime.Environment - if useVM { - environment = reusable.VMTxRuntimeEnv - } else { - environment = reusable.TxRuntimeEnv - } - return reusable.Runtime.InvokeContractFunction( contractLocation, functionName, @@ -180,7 +210,7 @@ func (reusable *ReusableCadenceRuntime) InvokeContractFunction( argumentTypes, runtime.Context{ Interface: reusable.fvmEnv, - Environment: environment, + Environment: env, UseVM: useVM, MemoryGauge: reusable.fvmEnv, ComputationGauge: reusable.fvmEnv, @@ -188,149 +218,224 @@ func (reusable *ReusableCadenceRuntime) InvokeContractFunction( ) } -func (reusable *ReusableCadenceRuntime) NewTransactionExecutor( +// reusableCadenceTransactionRuntime is a wrapper around reusableCadenceRuntime +// that is meant to be used in transactions executed by the cadence interpreter. +// see: reusableCadenceRuntime +type reusableCadenceTransactionRuntime struct { + *reusableCadenceRuntime +} + +var _ environment.ReusableCadenceRuntime = reusableCadenceTransactionRuntime{} + +func (reusable reusableCadenceTransactionRuntime) NewTransactionExecutor( script runtime.Script, location common.Location, - useVM bool, ) runtime.Executor { - var environment runtime.Environment - if useVM { - environment = reusable.VMTxRuntimeEnv - } else { - environment = reusable.TxRuntimeEnv - } + return reusable.newTransactionExecutor(script, location, reusable.TxRuntimeEnv, false) +} - return reusable.Runtime.NewTransactionExecutor( - script, - runtime.Context{ - Interface: reusable.fvmEnv, - Location: location, - UseVM: useVM, - Environment: environment, - MemoryGauge: reusable.fvmEnv, - ComputationGauge: reusable.fvmEnv, - }, +func (reusable reusableCadenceTransactionRuntime) ExecuteScript( + script runtime.Script, + location common.Location, +) ( + cadence.Value, + error, +) { + return reusable.executeScript(script, location, reusable.ScriptRuntimeEnv, false) +} + +func (reusable reusableCadenceTransactionRuntime) ReadStored( + address common.Address, + path cadence.Path, +) ( + cadence.Value, + error, +) { + return reusable.readStored(address, path, reusable.TxRuntimeEnv) +} + +func (reusable reusableCadenceTransactionRuntime) InvokeContractFunction( + contractLocation common.AddressLocation, + functionName string, + arguments []cadence.Value, + argumentTypes []sema.Type, +) ( + cadence.Value, + error, +) { + return reusable.invokeContractFunction( + contractLocation, + functionName, + arguments, + argumentTypes, + reusable.TxRuntimeEnv, + false, ) } -func (reusable *ReusableCadenceRuntime) ExecuteScript( +// reusableCadenceScriptRuntime is a wrapper around reusableCadenceRuntime +// that is meant to be used in scripts executed by the cadence interpreter. +// see: reusableCadenceRuntime +type reusableCadenceScriptRuntime struct { + *reusableCadenceRuntime +} + +var _ environment.ReusableCadenceRuntime = reusableCadenceScriptRuntime{} + +func (reusable reusableCadenceScriptRuntime) NewTransactionExecutor( + script runtime.Script, + location common.Location, +) runtime.Executor { + return reusable.newTransactionExecutor(script, location, reusable.TxRuntimeEnv, false) +} + +func (reusable reusableCadenceScriptRuntime) ExecuteScript( script runtime.Script, location common.Location, - useVM bool, ) ( cadence.Value, error, ) { - var environment runtime.Environment - if useVM { - environment = reusable.VMScriptRuntimeEnv - } else { - environment = reusable.ScriptRuntimeEnv - } + return reusable.executeScript(script, location, reusable.ScriptRuntimeEnv, false) +} - return reusable.Runtime.ExecuteScript( - script, - runtime.Context{ - Interface: reusable.fvmEnv, - Location: location, - Environment: environment, - UseVM: useVM, - MemoryGauge: reusable.fvmEnv, - ComputationGauge: reusable.fvmEnv, - }, - ) +func (reusable reusableCadenceScriptRuntime) ReadStored( + address common.Address, + path cadence.Path, +) ( + cadence.Value, + error, +) { + return reusable.readStored(address, path, reusable.ScriptRuntimeEnv) } -type CadenceRuntimeConstructor func(config runtime.Config) runtime.Runtime +func (reusable reusableCadenceScriptRuntime) InvokeContractFunction( + contractLocation common.AddressLocation, + functionName string, + arguments []cadence.Value, + argumentTypes []sema.Type, +) ( + cadence.Value, + error, +) { + return reusable.invokeContractFunction( + contractLocation, + functionName, + arguments, + argumentTypes, + reusable.ScriptRuntimeEnv, + false, + ) +} -type ReusableCadenceRuntimePool struct { - pool chan *ReusableCadenceRuntime +// reusableCadenceTransactionVMRuntime is a wrapper around reusableCadenceRuntime +// that is meant to be used in transactions executed by the cadence VM. +// see: reusableCadenceRuntime +type reusableCadenceTransactionVMRuntime struct { + *reusableCadenceRuntime +} - config runtime.Config +var _ environment.ReusableCadenceRuntime = reusableCadenceTransactionVMRuntime{} - // When newCustomRuntime is nil, the pool will create standard cadence - // interpreter runtimes via runtime.NewRuntime. Otherwise, the - // pool will create runtimes using this function. - // - // Note that this is primarily used for testing. - newCustomRuntime CadenceRuntimeConstructor +func (reusable reusableCadenceTransactionVMRuntime) NewTransactionExecutor( + script runtime.Script, + location common.Location, +) runtime.Executor { + return reusable.newTransactionExecutor(script, location, reusable.VMTxRuntimeEnv, true) } -func newReusableCadenceRuntimePool( - poolSize int, - config runtime.Config, - newCustomRuntime CadenceRuntimeConstructor, -) ReusableCadenceRuntimePool { - var pool chan *ReusableCadenceRuntime - if poolSize > 0 { - pool = make(chan *ReusableCadenceRuntime, poolSize) - } +func (reusable reusableCadenceTransactionVMRuntime) ExecuteScript( + script runtime.Script, + location common.Location, +) ( + cadence.Value, + error, +) { + return reusable.executeScript(script, location, reusable.VMScriptRuntimeEnv, true) +} - return ReusableCadenceRuntimePool{ - pool: pool, - config: config, - newCustomRuntime: newCustomRuntime, - } +func (reusable reusableCadenceTransactionVMRuntime) ReadStored( + address common.Address, + path cadence.Path, +) ( + cadence.Value, + error, +) { + // Reading stored values does not differ between the interpreter and the VM. + return reusable.readStored(address, path, reusable.TxRuntimeEnv) } -func NewReusableCadenceRuntimePool( - poolSize int, - config runtime.Config, -) ReusableCadenceRuntimePool { - return newReusableCadenceRuntimePool( - poolSize, - config, - nil, +func (reusable reusableCadenceTransactionVMRuntime) InvokeContractFunction( + contractLocation common.AddressLocation, + functionName string, + arguments []cadence.Value, + argumentTypes []sema.Type, +) ( + cadence.Value, + error, +) { + return reusable.invokeContractFunction( + contractLocation, + functionName, + arguments, + argumentTypes, + reusable.VMTxRuntimeEnv, + true, ) } -func NewCustomReusableCadenceRuntimePool( - poolSize int, - config runtime.Config, - newCustomRuntime CadenceRuntimeConstructor, -) ReusableCadenceRuntimePool { - return newReusableCadenceRuntimePool( - poolSize, - config, - newCustomRuntime, - ) +// reusableCadenceScriptVMRuntime is a wrapper around reusableCadenceRuntime +// that is meant to be used in scripts executed by the cadence VM. +// see: reusableCadenceRuntime +type reusableCadenceScriptVMRuntime struct { + *reusableCadenceRuntime } -func (pool ReusableCadenceRuntimePool) newRuntime() runtime.Runtime { - if pool.newCustomRuntime != nil { - return pool.newCustomRuntime(pool.config) - } - return runtime.NewRuntime(pool.config) -} - -func (pool ReusableCadenceRuntimePool) Borrow( - fvmEnv Environment, -) *ReusableCadenceRuntime { - var reusable *ReusableCadenceRuntime - select { - case reusable = <-pool.pool: - // Do nothing. - default: - reusable = NewReusableCadenceRuntime( - WrappedCadenceRuntime{ - pool.newRuntime(), - }, - pool.config, - ) - } +var _ environment.ReusableCadenceRuntime = reusableCadenceScriptVMRuntime{} - reusable.SetFvmEnvironment(fvmEnv) - return reusable +func (reusable reusableCadenceScriptVMRuntime) NewTransactionExecutor( + script runtime.Script, + location common.Location, +) runtime.Executor { + return reusable.newTransactionExecutor(script, location, reusable.VMTxRuntimeEnv, true) } -func (pool ReusableCadenceRuntimePool) Return( - reusable *ReusableCadenceRuntime, +func (reusable reusableCadenceScriptVMRuntime) ExecuteScript( + script runtime.Script, + location common.Location, +) ( + cadence.Value, + error, ) { - reusable.SetFvmEnvironment(nil) - select { - case pool.pool <- reusable: - // Do nothing. - default: - // Do nothing. Discard the overflow entry. - } + return reusable.executeScript(script, location, reusable.VMScriptRuntimeEnv, true) +} + +func (reusable reusableCadenceScriptVMRuntime) ReadStored( + address common.Address, + path cadence.Path, +) ( + cadence.Value, + error, +) { + // Reading stored values does not differ between the interpreter and the VM. + return reusable.readStored(address, path, reusable.ScriptRuntimeEnv) +} + +func (reusable reusableCadenceScriptVMRuntime) InvokeContractFunction( + contractLocation common.AddressLocation, + functionName string, + arguments []cadence.Value, + argumentTypes []sema.Type, +) ( + cadence.Value, + error, +) { + return reusable.invokeContractFunction( + contractLocation, + functionName, + arguments, + argumentTypes, + reusable.VMScriptRuntimeEnv, + true, + ) } diff --git a/fvm/runtime/reusable_cadence_runtime_pool.go b/fvm/runtime/reusable_cadence_runtime_pool.go new file mode 100644 index 00000000000..785c78ff8e5 --- /dev/null +++ b/fvm/runtime/reusable_cadence_runtime_pool.go @@ -0,0 +1,163 @@ +package runtime + +import ( + "github.com/onflow/cadence/runtime" + + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/model/flow" +) + +type CadenceRuntimeConstructor func(config runtime.Config) runtime.Runtime + +type ReusableCadenceRuntimePool struct { + pool chan *reusableCadenceRuntime + + runtimeConfig runtime.Config + + // When customRuntimeConstructor is nil, the pool will create standard cadence + // interpreter runtimes via runtime.NewRuntime. Otherwise, the + // pool will create runtimes using this function. + // + // Note that this is primarily used for testing. + customRuntimeConstructor CadenceRuntimeConstructor + + // chain is the chain the RuntimePool was made for + // while cadence runtime is chain agnostic, some injected (into cadence) FVM definitions + // are chain dependant. The pool should not be used cross chain. + // Using the pool to execute procedures of a different chain will produce errors + chain flow.Chain +} + +var _ environment.ReusableCadenceRuntimePool = (*ReusableCadenceRuntimePool)(nil) + +func newReusableCadenceRuntimePool( + poolSize int, + chain flow.Chain, + config runtime.Config, + newCustomRuntime CadenceRuntimeConstructor, +) ReusableCadenceRuntimePool { + var pool chan *reusableCadenceRuntime + if poolSize > 0 { + pool = make(chan *reusableCadenceRuntime, poolSize) + } + + return ReusableCadenceRuntimePool{ + pool: pool, + chain: chain, + runtimeConfig: config, + customRuntimeConstructor: newCustomRuntime, + } +} + +func NewReusableCadenceRuntimePool( + poolSize int, + chain flow.Chain, + config runtime.Config, +) ReusableCadenceRuntimePool { + return newReusableCadenceRuntimePool( + poolSize, + chain, + config, + nil, + ) +} + +func NewCustomReusableCadenceRuntimePool( + poolSize int, + chain flow.Chain, + config runtime.Config, + newCustomRuntime CadenceRuntimeConstructor, +) ReusableCadenceRuntimePool { + return newReusableCadenceRuntimePool( + poolSize, + chain, + config, + newCustomRuntime, + ) +} + +func (pool ReusableCadenceRuntimePool) newRuntime() runtime.Runtime { + if pool.customRuntimeConstructor != nil { + return pool.customRuntimeConstructor(pool.runtimeConfig) + } + return runtime.NewRuntime(pool.runtimeConfig) +} + +func (pool ReusableCadenceRuntimePool) Borrow( + fvmEnv environment.Environment, + runtimeType environment.CadenceRuntimeType, +) environment.ReusableCadenceRuntime { + var reusable *reusableCadenceRuntime + select { + case reusable = <-pool.pool: + // Do nothing. + default: + reusable = newReusableCadenceRuntime( + WrappedCadenceRuntime{ + pool.newRuntime(), + }, + pool.chain, + pool.runtimeConfig, + ) + } + + reusable.SetFvmEnvironment(fvmEnv) + + switch runtimeType { + case environment.CadenceScriptRuntime: + return reusableCadenceScriptRuntime{ + reusableCadenceRuntime: reusable, + } + case environment.CadenceTransactionRuntime: + return reusableCadenceTransactionRuntime{ + reusableCadenceRuntime: reusable, + } + case environment.CadenceScriptVMRuntime: + return reusableCadenceScriptVMRuntime{ + reusableCadenceRuntime: reusable, + } + case environment.CadenceTransactionVMRuntime: + return reusableCadenceTransactionVMRuntime{ + reusableCadenceRuntime: reusable, + } + default: + panic("unreachable") + + } +} + +func (pool ReusableCadenceRuntimePool) Return( + reusable environment.ReusableCadenceRuntime, +) { + var inner *reusableCadenceRuntime + switch v := reusable.(type) { + case reusableCadenceScriptRuntime: + inner = v.reusableCadenceRuntime + case reusableCadenceTransactionRuntime: + inner = v.reusableCadenceRuntime + case reusableCadenceScriptVMRuntime: + inner = v.reusableCadenceRuntime + case reusableCadenceTransactionVMRuntime: + inner = v.reusableCadenceRuntime + default: + panic("unreachable") + } + inner.SetFvmEnvironment(nil) + + select { + case pool.pool <- inner: + // Do nothing. + default: + // Do nothing. Discard the overflow entry. + } +} + +func DefaultRuntimeParams(chain flow.Chain) environment.RuntimeParams { + return environment.RuntimeParams{ + ReusableCadenceRuntimePool: NewReusableCadenceRuntimePool( + 0, + chain, + runtime.Config{}, + ), + } +} diff --git a/fvm/runtime/reusable_cadence_runtime_test.go b/fvm/runtime/reusable_cadence_runtime_test.go index cf6a2a44867..ce4e2bda6c2 100644 --- a/fvm/runtime/reusable_cadence_runtime_test.go +++ b/fvm/runtime/reusable_cadence_runtime_test.go @@ -3,27 +3,31 @@ package runtime import ( "testing" - "github.com/onflow/cadence/runtime" "github.com/stretchr/testify/require" + + "github.com/onflow/cadence/runtime" + + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/model/flow" ) func TestReusableCadenceRuntimePoolUnbuffered(t *testing.T) { - pool := NewReusableCadenceRuntimePool(0, runtime.Config{}) + pool := NewReusableCadenceRuntimePool(0, flow.Mainnet.Chain(), runtime.Config{}) require.Nil(t, pool.pool) - entry := pool.Borrow(nil) + entry := pool.Borrow(nil, environment.CadenceTransactionRuntime).(reusableCadenceTransactionRuntime) require.NotNil(t, entry) pool.Return(entry) - entry2 := pool.Borrow(nil) + entry2 := pool.Borrow(nil, environment.CadenceTransactionRuntime).(reusableCadenceTransactionRuntime) require.NotNil(t, entry2) - require.NotSame(t, entry, entry2) + require.NotSame(t, entry.reusableCadenceRuntime, entry2.reusableCadenceRuntime) } func TestReusableCadenceRuntimePoolBuffered(t *testing.T) { - pool := NewReusableCadenceRuntimePool(100, runtime.Config{}) + pool := NewReusableCadenceRuntimePool(100, flow.Mainnet.Chain(), runtime.Config{}) require.NotNil(t, pool.pool) select { @@ -32,7 +36,7 @@ func TestReusableCadenceRuntimePoolBuffered(t *testing.T) { default: } - entry := pool.Borrow(nil) + entry := pool.Borrow(nil, environment.CadenceTransactionRuntime).(reusableCadenceTransactionRuntime) require.NotNil(t, entry) select { @@ -43,14 +47,14 @@ func TestReusableCadenceRuntimePoolBuffered(t *testing.T) { pool.Return(entry) - entry2 := pool.Borrow(nil) + entry2 := pool.Borrow(nil, environment.CadenceTransactionRuntime).(reusableCadenceTransactionRuntime) require.NotNil(t, entry2) - require.Same(t, entry, entry2) + require.Same(t, entry.reusableCadenceRuntime, entry2.reusableCadenceRuntime) } func TestReusableCadenceRuntimePoolSharing(t *testing.T) { - pool := NewReusableCadenceRuntimePool(100, runtime.Config{}) + pool := NewReusableCadenceRuntimePool(100, flow.Mainnet.Chain(), runtime.Config{}) require.NotNil(t, pool.pool) select { @@ -61,7 +65,7 @@ func TestReusableCadenceRuntimePoolSharing(t *testing.T) { var otherPool = pool - entry := otherPool.Borrow(nil) + entry := otherPool.Borrow(nil, environment.CadenceTransactionRuntime).(reusableCadenceTransactionRuntime) require.NotNil(t, entry) select { @@ -72,8 +76,8 @@ func TestReusableCadenceRuntimePoolSharing(t *testing.T) { otherPool.Return(entry) - entry2 := pool.Borrow(nil) + entry2 := pool.Borrow(nil, environment.CadenceTransactionRuntime).(reusableCadenceTransactionRuntime) require.NotNil(t, entry2) - require.Same(t, entry, entry2) + require.Same(t, entry.reusableCadenceRuntime, entry2.reusableCadenceRuntime) } diff --git a/fvm/script.go b/fvm/script.go index 75d2fdcf18b..a1b9e529778 100644 --- a/fvm/script.go +++ b/fvm/script.go @@ -10,8 +10,6 @@ import ( "github.com/onflow/flow-go/fvm/environment" "github.com/onflow/flow-go/fvm/errors" - "github.com/onflow/flow-go/fvm/evm" - "github.com/onflow/flow-go/fvm/runtime" "github.com/onflow/flow-go/fvm/storage" "github.com/onflow/flow-go/fvm/storage/logical" "github.com/onflow/flow-go/model/flow" @@ -135,42 +133,6 @@ func newScriptExecutor( txnState, ) - if ctx.EVMEnabled { - chainID := ctx.Chain.ChainID() - - cadenceVMEnabled := ctx.CadenceVMEnabled - - env.Runtime.ConfigureCadenceRuntime = func( - reusableCadenceRuntime *runtime.ReusableCadenceRuntime, - env environment.Environment, - ) { - // Setup EVM environment in both script and transaction environments. - // We also need to set up the transaction environment, - // because it is used for nested contract invocations - - var scriptRuntimeEnv, txRuntimeEnv cadenceRuntime.Environment - if cadenceVMEnabled { - scriptRuntimeEnv = reusableCadenceRuntime.VMScriptRuntimeEnv - txRuntimeEnv = reusableCadenceRuntime.VMTxRuntimeEnv - } else { - scriptRuntimeEnv = reusableCadenceRuntime.ScriptRuntimeEnv - txRuntimeEnv = reusableCadenceRuntime.TxRuntimeEnv - } - - evm.SetupEnvironment( - chainID, - env, - scriptRuntimeEnv, - ) - - evm.SetupEnvironment( - chainID, - env, - txRuntimeEnv, - ) - } - } - return &scriptExecutor{ ctx: ctx, proc: proc, @@ -247,7 +209,6 @@ func (executor *scriptExecutor) executeScript() error { Arguments: executor.proc.Arguments, }, common.ScriptLocation(executor.proc.ID), - executor.ctx.CadenceVMEnabled, ) populateErr := executor.output.PopulateEnvironmentValues(executor.env) if err != nil { diff --git a/fvm/storage/derived/derived_chain_data_test.go b/fvm/storage/derived/derived_chain_data_test.go index 959874928f1..e3b0598ac25 100644 --- a/fvm/storage/derived/derived_chain_data_test.go +++ b/fvm/storage/derived/derived_chain_data_test.go @@ -21,7 +21,7 @@ func TestDerivedChainData(t *testing.T) { testLocation := func(hex string) common.AddressLocation { return common.AddressLocation{ - Address: common.MustBytesToAddress(flow.HexToAddress(hex).Bytes()), + Address: common.Address(flow.HexToAddress(hex)), Name: hex, } } diff --git a/fvm/storage/errors/errors.go b/fvm/storage/errors/errors.go index 4f6fca25015..874a9755be9 100644 --- a/fvm/storage/errors/errors.go +++ b/fvm/storage/errors/errors.go @@ -42,7 +42,7 @@ type retryableConflictError struct { func NewRetryableConflictError( msg string, - vals ...interface{}, + vals ...any, ) error { return &retryableConflictError{ error: fmt.Errorf(msg, vals...), diff --git a/fvm/storage/primary/block_data_test.go b/fvm/storage/primary/block_data_test.go index 8c20e301b0b..4acf865ceb6 100644 --- a/fvm/storage/primary/block_data_test.go +++ b/fvm/storage/primary/block_data_test.go @@ -398,7 +398,7 @@ func TestBlockDataCommit(t *testing.T) { // Commit a bunch of unrelated updates - for i := logical.Time(0); i < 3; i++ { + for i := range logical.Time(3) { testSetupTxn, err := block.NewTransactionData( i, state.DefaultParameters()) @@ -616,7 +616,7 @@ func TestBlockDataCommitRejectNonIncreasingExecutionTime1(t *testing.T) { require.NoError(t, err) // Commit a bunch of unrelated transactions. - for i := logical.Time(0); i < 10; i++ { + for i := range logical.Time(10) { txn, err := block.NewTransactionData(i, state.DefaultParameters()) require.NoError(t, err) diff --git a/fvm/storage/primary/snapshot_tree_test.go b/fvm/storage/primary/snapshot_tree_test.go index 1c8db612632..08bc77d5131 100644 --- a/fvm/storage/primary/snapshot_tree_test.go +++ b/fvm/storage/primary/snapshot_tree_test.go @@ -146,7 +146,7 @@ func TestTimestampedSnapshotTree(t *testing.T) { _, err = tree4.UpdatesSince(baseSnapshotTime - 1) require.ErrorContains(t, err, "missing update log range [4, 5)") - for i := 0; i < 5; i++ { + for i := range 5 { updates, err = tree4.UpdatesSince(baseSnapshotTime + logical.Time(i)) require.NoError(t, err) require.Equal(t, logs[i:], updates) diff --git a/fvm/storage/snapshot/mock/peeker.go b/fvm/storage/snapshot/mock/peeker.go index d20fc001ac3..9174c22ac4c 100644 --- a/fvm/storage/snapshot/mock/peeker.go +++ b/fvm/storage/snapshot/mock/peeker.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewPeeker creates a new instance of Peeker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeeker(t interface { + mock.TestingT + Cleanup(func()) +}) *Peeker { + mock := &Peeker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Peeker is an autogenerated mock type for the Peeker type type Peeker struct { mock.Mock } -// Peek provides a mock function with given fields: id -func (_m *Peeker) Peek(id flow.RegisterID) (flow.RegisterValue, error) { - ret := _m.Called(id) +type Peeker_Expecter struct { + mock *mock.Mock +} + +func (_m *Peeker) EXPECT() *Peeker_Expecter { + return &Peeker_Expecter{mock: &_m.Mock} +} + +// Peek provides a mock function for the type Peeker +func (_mock *Peeker) Peek(id flow.RegisterID) (flow.RegisterValue, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for Peek") @@ -22,36 +46,54 @@ func (_m *Peeker) Peek(id flow.RegisterID) (flow.RegisterValue, error) { var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterID) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewPeeker creates a new instance of Peeker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPeeker(t interface { - mock.TestingT - Cleanup(func()) -}) *Peeker { - mock := &Peeker{} - mock.Mock.Test(t) +// Peeker_Peek_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Peek' +type Peeker_Peek_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Peek is a helper method to define mock.On call +// - id flow.RegisterID +func (_e *Peeker_Expecter) Peek(id interface{}) *Peeker_Peek_Call { + return &Peeker_Peek_Call{Call: _e.mock.On("Peek", id)} +} - return mock +func (_c *Peeker_Peek_Call) Run(run func(id flow.RegisterID)) *Peeker_Peek_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Peeker_Peek_Call) Return(v flow.RegisterValue, err error) *Peeker_Peek_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Peeker_Peek_Call) RunAndReturn(run func(id flow.RegisterID) (flow.RegisterValue, error)) *Peeker_Peek_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/storage/snapshot/mock/storage_snapshot.go b/fvm/storage/snapshot/mock/storage_snapshot.go index 4164561d381..420b6e2c322 100644 --- a/fvm/storage/snapshot/mock/storage_snapshot.go +++ b/fvm/storage/snapshot/mock/storage_snapshot.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewStorageSnapshot creates a new instance of StorageSnapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStorageSnapshot(t interface { + mock.TestingT + Cleanup(func()) +}) *StorageSnapshot { + mock := &StorageSnapshot{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // StorageSnapshot is an autogenerated mock type for the StorageSnapshot type type StorageSnapshot struct { mock.Mock } -// Get provides a mock function with given fields: id -func (_m *StorageSnapshot) Get(id flow.RegisterID) (flow.RegisterValue, error) { - ret := _m.Called(id) +type StorageSnapshot_Expecter struct { + mock *mock.Mock +} + +func (_m *StorageSnapshot) EXPECT() *StorageSnapshot_Expecter { + return &StorageSnapshot_Expecter{mock: &_m.Mock} +} + +// Get provides a mock function for the type StorageSnapshot +func (_mock *StorageSnapshot) Get(id flow.RegisterID) (flow.RegisterValue, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for Get") @@ -22,36 +46,54 @@ func (_m *StorageSnapshot) Get(id flow.RegisterID) (flow.RegisterValue, error) { var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) (flow.RegisterValue, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID) flow.RegisterValue); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterID) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewStorageSnapshot creates a new instance of StorageSnapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStorageSnapshot(t interface { - mock.TestingT - Cleanup(func()) -}) *StorageSnapshot { - mock := &StorageSnapshot{} - mock.Mock.Test(t) +// StorageSnapshot_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type StorageSnapshot_Get_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Get is a helper method to define mock.On call +// - id flow.RegisterID +func (_e *StorageSnapshot_Expecter) Get(id interface{}) *StorageSnapshot_Get_Call { + return &StorageSnapshot_Get_Call{Call: _e.mock.On("Get", id)} +} - return mock +func (_c *StorageSnapshot_Get_Call) Run(run func(id flow.RegisterID)) *StorageSnapshot_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StorageSnapshot_Get_Call) Return(v flow.RegisterValue, err error) *StorageSnapshot_Get_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *StorageSnapshot_Get_Call) RunAndReturn(run func(id flow.RegisterID) (flow.RegisterValue, error)) *StorageSnapshot_Get_Call { + _c.Call.Return(run) + return _c } diff --git a/fvm/storage/snapshot/snapshot_tree.go b/fvm/storage/snapshot/snapshot_tree.go index 7c91b9a5c1a..cc57843b3ae 100644 --- a/fvm/storage/snapshot/snapshot_tree.go +++ b/fvm/storage/snapshot/snapshot_tree.go @@ -28,7 +28,7 @@ func NewSnapshotTree(base StorageSnapshot) SnapshotTree { } // Append returns a new tree with updates from the execution snapshot "applied" -// to the original original tree. +// to the original tree. func (tree SnapshotTree) Append( update *ExecutionSnapshot, ) SnapshotTree { diff --git a/fvm/storage/snapshot/snapshot_tree_test.go b/fvm/storage/snapshot/snapshot_tree_test.go index 0395e861a7f..4a8479405a9 100644 --- a/fvm/storage/snapshot/snapshot_tree_test.go +++ b/fvm/storage/snapshot/snapshot_tree_test.go @@ -90,7 +90,7 @@ func TestSnapshotTree(t *testing.T) { compactedTree := tree3 numExtraUpdates := 2*compactThreshold + 1 - for i := 0; i < numExtraUpdates; i++ { + for i := range numExtraUpdates { value := []byte(fmt.Sprintf("compacted %d", i)) expectedCompacted[id3] = value compactedTree = compactedTree.Append( diff --git a/fvm/storage/state/storage_state.go b/fvm/storage/state/storage_state.go index e4b92e16969..da5ad4a9b08 100644 --- a/fvm/storage/state/storage_state.go +++ b/fvm/storage/state/storage_state.go @@ -131,3 +131,9 @@ func (state *storageState) interimReadSet( accumulator[id] = struct{}{} } } + +// BaseStorageSnapshot gives access to the storage snapshot as it was without changes +// WARNING: this should not be read mid-transaction as reads to it are not recorded in the spocks +func (state *storageState) BaseStorageSnapshot() snapshot.StorageSnapshot { + return state.baseStorage +} diff --git a/fvm/storage/state/transaction_state.go b/fvm/storage/state/transaction_state.go index 57b37d5c9b2..60e1fd4a038 100644 --- a/fvm/storage/state/transaction_state.go +++ b/fvm/storage/state/transaction_state.go @@ -160,6 +160,10 @@ type NestedTransactionPreparer interface { Get(id flow.RegisterID) (flow.RegisterValue, error) Set(id flow.RegisterID, value flow.RegisterValue) error + + // BaseStorageSnapshot gives access to the storage snapshot as it was without changes + // WARNING: this should not be read mid-transaction as reads to it are not recorded in the spocks + BaseStorageSnapshot() snapshot.StorageSnapshot } type nestedTransactionStackFrame struct { @@ -450,6 +454,10 @@ func (txnState *transactionState) Set( return txnState.current().Set(id, value) } +func (txnState *transactionState) BaseStorageSnapshot() snapshot.StorageSnapshot { + return txnState.nestedTransactions[0].ExecutionState.BaseStorageSnapshot() +} + func (txnState *transactionState) MeterComputation(usage common.ComputationUsage) error { return txnState.current().MeterComputation(usage) } diff --git a/fvm/systemcontracts/system_contracts.go b/fvm/systemcontracts/system_contracts.go index 3e34e985b4b..ddb3d9e7998 100644 --- a/fvm/systemcontracts/system_contracts.go +++ b/fvm/systemcontracts/system_contracts.go @@ -56,6 +56,8 @@ const ( // It is a separate account on all networks in order to separate it away // from the frequently changing data on the service account. AccountNameExecutionParametersAccount = "ExecutionParametersAccount" + // AccountNameFlowFeesReceivers is not a contract, but a special account that is used to store flow fees receivers + AccountNameFlowFeesReceivers = "FlowFeesReceiversAccount" // Unqualified names of service events (not including address prefix or contract name) @@ -124,6 +126,16 @@ var ( executionParametersAddressTestnet = flow.HexToAddress("6997a2f2cf57b73a") // executionParametersAddressMainnet is the address of the Execution Parameters contract on Mainnet executionParametersAddressMainnet = flow.HexToAddress("f426ff57ee8f6110") + + // flowFeesReceiversAddressTestnet is the address of the Flow Fees Receivers contract on Testnet + // See tx be210889dd26a320f530595bd369093e866e26c3941bf7a3d01f861db3eeda81 + flowFeesReceiversAddressesTestnet = []flow.Address{ + flow.HexToAddress("912d5440f7e3769e"), + flow.HexToAddress("e1ac6b2740d204c2"), + flow.HexToAddress("05cbd2fa5128041d"), + flow.HexToAddress("139fb7c9c82c0e7c"), + } + // TODO: add mainnet addresses once they are created ) // SystemContract represents a system contract on a particular chain. @@ -185,6 +197,7 @@ type SystemContracts struct { FungibleToken SystemContract FungibleTokenSwitchboard SystemContract FungibleTokenMetadataViews SystemContract + FlowFeesReceivers []SystemAccount // NFT related contracts NonFungibleToken SystemContract @@ -469,6 +482,26 @@ func init() { } } + flowFeesReceiversAddressesFunc := func(chainID flow.ChainID) []SystemAccount { + var addresses []flow.Address + if chainID == flow.Testnet { + addresses = flowFeesReceiversAddressesTestnet + } else { + // otherwise, just use the flow fees contract address + contract := addressOfContract(ContractNameFlowFees) + addresses = append(addresses, contract.Address) + } + + receivers := make([]SystemAccount, len(addresses)) + for i, address := range addresses { + receivers[i] = SystemAccount{ + Address: address, + Name: AccountNameFlowFeesReceivers, + } + } + return receivers + } + contracts := &SystemContracts{ Epoch: addressOfContract(ContractNameEpoch), IDTableStaking: addressOfContract(ContractNameIDTableStaking), @@ -486,6 +519,7 @@ func init() { FungibleToken: addressOfContract(ContractNameFungibleToken), FungibleTokenMetadataViews: addressOfContract(ContractNameFungibleTokenMetadataViews), FungibleTokenSwitchboard: addressOfContract(ContractNameFungibleTokenSwitchboard), + FlowFeesReceivers: flowFeesReceiversAddressesFunc(chainID), NonFungibleToken: addressOfContract(ContractNameNonFungibleToken), MetadataViews: addressOfContract(ContractNameMetadataViews), diff --git a/fvm/systemcontracts/system_contracts_test.go b/fvm/systemcontracts/system_contracts_test.go index 0c42b9b6508..82333577b9c 100644 --- a/fvm/systemcontracts/system_contracts_test.go +++ b/fvm/systemcontracts/system_contracts_test.go @@ -63,6 +63,15 @@ func TestServiceEvents_InvalidChainID(t *testing.T) { require.Panics(t, func() { ServiceEventsForChain(invalidChain) }) } +// TestFlowFeesReceivers_NotEmpty verifies that FlowFeesReceivers is non-empty for +// mainnet and testnet. +func TestFlowFeesReceivers_NotEmpty(t *testing.T) { + for _, chain := range []flow.ChainID{flow.Mainnet, flow.Testnet, flow.Emulator} { + contracts := SystemContractsForChain(chain) + assert.NotEmpty(t, contracts.FlowFeesReceivers, "FlowFeesReceivers must not be empty for chain %s", chain) + } +} + func checkSystemContracts(t *testing.T, chainID flow.ChainID) { contracts := SystemContractsForChain(chainID) diff --git a/fvm/transactionInvoker.go b/fvm/transactionInvoker.go index f4a9e5843fb..4329cca3c9e 100644 --- a/fvm/transactionInvoker.go +++ b/fvm/transactionInvoker.go @@ -12,8 +12,6 @@ import ( "github.com/onflow/flow-go/fvm/environment" "github.com/onflow/flow-go/fvm/errors" - "github.com/onflow/flow-go/fvm/evm" - "github.com/onflow/flow-go/fvm/runtime" "github.com/onflow/flow-go/fvm/storage" "github.com/onflow/flow-go/fvm/storage/derived" "github.com/onflow/flow-go/fvm/storage/snapshot" @@ -70,7 +68,7 @@ type transactionExecutor struct { // writes to any of those registers executionStateRead *snapshot.ExecutionSnapshot - cadenceRuntime *runtime.ReusableCadenceRuntime + cadenceRuntime environment.ReusableCadenceRuntime txnBodyExecutor cadenceRuntime.Executor output ProcedureOutput @@ -93,30 +91,6 @@ func newTransactionExecutor( ctx.EnvironmentParams, txnState) - if ctx.EVMEnabled { - chainID := ctx.Chain.ChainID() - - cadenceVMEnabled := ctx.CadenceVMEnabled - - env.Runtime.ConfigureCadenceRuntime = func( - reusableCadenceRuntime *runtime.ReusableCadenceRuntime, - env environment.Environment, - ) { - var txRuntimeEnv cadenceRuntime.Environment - if cadenceVMEnabled { - txRuntimeEnv = reusableCadenceRuntime.VMTxRuntimeEnv - } else { - txRuntimeEnv = reusableCadenceRuntime.TxRuntimeEnv - } - - evm.SetupEnvironment( - chainID, - env, - txRuntimeEnv, - ) - } - } - return &transactionExecutor{ TransactionExecutorParams: ctx.TransactionExecutorParams, TransactionVerifier: TransactionVerifier{ @@ -210,8 +184,6 @@ func (executor *transactionExecutor) preprocess() error { // infrequently modified and are expensive to compute. For now this includes // reading meter parameter overrides and parsing programs. func (executor *transactionExecutor) preprocessTransactionBody() error { - - // setup EVM // get meter parameters executionParameters, executionStateRead, err := getExecutionParameters( executor.env.Logger(), @@ -245,7 +217,6 @@ func (executor *transactionExecutor) preprocessTransactionBody() error { Arguments: executor.proc.Transaction.Arguments, }, common.TransactionLocation(executor.proc.ID), - executor.ctx.CadenceVMEnabled, ) // This initializes various cadence variables and parses the programs used @@ -269,7 +240,6 @@ func (executor *transactionExecutor) execute() error { } func (executor *transactionExecutor) ExecuteTransactionBody() error { - var invalidator derived.TransactionInvalidator if !executor.errs.CollectedError() { @@ -488,7 +458,7 @@ func (executor *transactionExecutor) commit( // the same as a successful transaction without any updates. executor.txnState.AddInvalidator(invalidator) - _, commitErr := executor.txnState.CommitNestedTransaction( + executionSnapshot, commitErr := executor.txnState.CommitNestedTransaction( executor.nestedTxnId) if commitErr != nil { return fmt.Errorf( @@ -496,5 +466,7 @@ func (executor *transactionExecutor) commit( commitErr) } + executor.output.PopulateInspectionResults(executor.ctx.Logger, executor.ctx, executor.env, executor.txnState.BaseStorageSnapshot(), executionSnapshot) + return nil } diff --git a/fvm/transactionInvoker_test.go b/fvm/transactionInvoker_test.go index 78feb7f3ce4..3e6c5e38f3b 100644 --- a/fvm/transactionInvoker_test.go +++ b/fvm/transactionInvoker_test.go @@ -28,9 +28,11 @@ func TestSafetyCheck(t *testing.T) { proc := fvm.Transaction(&flow.TransactionBody{Script: []byte(code)}, 0) context := fvm.NewContext( + flow.Mainnet.Chain(), fvm.WithLogger(log), fvm.WithAuthorizationChecksEnabled(false), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false)) + fvm.WithSequenceNumberCheckAndIncrementEnabled(false), + ) txnState := testutils.NewSimpleTransaction(nil) @@ -54,9 +56,11 @@ func TestSafetyCheck(t *testing.T) { proc := fvm.Transaction(&flow.TransactionBody{Script: []byte(code)}, 0) context := fvm.NewContext( + flow.Mainnet.Chain(), fvm.WithLogger(log), fvm.WithAuthorizationChecksEnabled(false), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false)) + fvm.WithSequenceNumberCheckAndIncrementEnabled(false), + ) txnState := testutils.NewSimpleTransaction(nil) diff --git a/fvm/transactionStorageLimiter.go b/fvm/transactionStorageLimiter.go index 37ebf12ddee..7d257e08009 100644 --- a/fvm/transactionStorageLimiter.go +++ b/fvm/transactionStorageLimiter.go @@ -173,9 +173,5 @@ func (limiter TransactionStorageLimiter) shouldSkipSpecialAddress( address flow.Address, sc *systemcontracts.SystemContracts, ) bool { - if !ctx.EVMEnabled { - return false - } - return sc.EVMStorage.Address == address } diff --git a/fvm/transactionStorageLimiter_test.go b/fvm/transactionStorageLimiter_test.go index aa97fd2b4cd..a4cc1df0eb9 100644 --- a/fvm/transactionStorageLimiter_test.go +++ b/fvm/transactionStorageLimiter_test.go @@ -209,13 +209,7 @@ func TestTransactionStorageLimiter(t *testing.T) { d := &fvm.TransactionStorageLimiter{} - // if EVM is disabled don't skip the storage check err := d.CheckStorageLimits(ctx, env, executionSnapshot, flow.EmptyAddress, 0) - require.Error(t, err) - - // if EVM is enabled skip the storage check - ctx := fvm.NewContextFromParent(ctx, fvm.WithEVMEnabled(true)) - err = d.CheckStorageLimits(ctx, env, executionSnapshot, flow.EmptyAddress, 0) require.NoError(t, err) }) } diff --git a/fvm/transactionVerifier.go b/fvm/transactionVerifier.go index c8e1a4f1a3b..897efa615cc 100644 --- a/fvm/transactionVerifier.go +++ b/fvm/transactionVerifier.go @@ -37,13 +37,13 @@ type signatureContinuation struct { // signatureEntry is the initial input. signatureEntry - // accountKey is set by getAccountKeys(). + // accountKey is set by getAccountKeysAndAggregateWeights(). accountKey flow.RuntimeAccountPublicKey - // invokedVerify and verifyErr are set by verifyAccountSignatures(). Note - // that verifyAccountSignatures() is always called after getAccountKeys() + // invokedVerify and verifyErr are set by verifySignatures(). Note + // that verifySignatures() is always called after getAccountKeysAndAggregateWeights() // (i.e., accountKey is always initialized by the time - // verifyAccountSignatures is called). + // verifySignatures is called). invokedVerify bool verifyErr errors.CodedError } @@ -69,6 +69,7 @@ func (entry *signatureContinuation) verify() errors.CodedError { valid, message := entry.ValidateExtensionDataAndReconstructMessage(entry.payload) if !valid { entry.verifyErr = entry.newError(fmt.Errorf("signature extension data is not valid")) + return entry.verifyErr } valid, err := crypto.VerifySignatureFromTransaction( @@ -86,19 +87,27 @@ func (entry *signatureContinuation) verify() errors.CodedError { return entry.verifyErr } -func newSignatureEntries( - payloadSignatures []flow.TransactionSignature, - payloadMessage []byte, - envelopeSignatures []flow.TransactionSignature, - envelopeMessage []byte, -) ( +// newSignatureEntries creates a list of signatureContinuation entries and deduplicate signatures +// per account key. +// The function returns an error if: +// - there are duplicate signatures for the same account key (address and key index pair) +// - a signature is provided for an account that is not a payer, proposer or authorizer +func newSignatureEntries(tx *flow.TransactionBody) ( []*signatureContinuation, map[flow.Address]int, map[flow.Address]int, error, ) { - payloadWeights := make(map[flow.Address]int, len(payloadSignatures)) - envelopeWeights := make(map[flow.Address]int, len(envelopeSignatures)) + transactionAddresses := make(map[flow.Address]struct{}) + transactionAddresses[tx.Payer] = struct{}{} + transactionAddresses[tx.ProposalKey.Address] = struct{}{} + for _, addr := range tx.Authorizers { + transactionAddresses[addr] = struct{}{} + } + + // weight maps are assigned to entries in this function, but are returned as empty maps + payloadWeights := make(map[flow.Address]int, len(tx.PayloadSignatures)) + envelopeWeights := make(map[flow.Address]int, len(tx.EnvelopeSignatures)) type pair struct { signatureType @@ -108,24 +117,24 @@ func newSignatureEntries( list := []pair{ { signatureType{ - payloadMessage, + tx.PayloadMessage(), errors.NewInvalidPayloadSignatureError, payloadWeights, }, - payloadSignatures, + tx.PayloadSignatures, }, { signatureType{ - envelopeMessage, + tx.EnvelopeMessage(), errors.NewInvalidEnvelopeSignatureError, envelopeWeights, }, - envelopeSignatures, + tx.EnvelopeSignatures, }, } - numSignatures := len(payloadSignatures) + len(envelopeSignatures) - signatures := make([]*signatureContinuation, 0, numSignatures) + numSignatures := len(tx.PayloadSignatures) + len(tx.EnvelopeSignatures) + signatureContinuations := make([]*signatureContinuation, 0, numSignatures) type uniqueKey struct { address flow.Address @@ -142,22 +151,29 @@ func newSignatureEntries( }, } + // check signature address is either payer, proposer or authorizer + _, ok := transactionAddresses[signature.Address] + if !ok { + return nil, nil, nil, entry.newError( + fmt.Errorf("signature is provided for account %s that is neither payer nor authorizer nor proposer", signature.Address)) + } + key := uniqueKey{ address: signature.Address, index: signature.KeyIndex, } - _, ok := duplicate[key] + _, ok = duplicate[key] if ok { return nil, nil, nil, entry.newError( fmt.Errorf("duplicate signatures are provided for the same key")) } duplicate[key] = struct{}{} - signatures = append(signatures, entry) + signatureContinuations = append(signatureContinuations, entry) } } - return signatures, payloadWeights, envelopeWeights, nil + return signatureContinuations, payloadWeights, envelopeWeights, nil } // TransactionVerifier verifies the content of the transaction by @@ -197,9 +213,11 @@ func (v *TransactionVerifier) verifyTransaction( keyWeightThreshold int, ) error { span := tracer.StartChildSpan(trace.FVMVerifyTransaction) - span.SetAttributes( - attribute.String("transaction.ID", proc.ID.String()), - ) + if span.Tracer != nil { + span.SetAttributes( + attribute.String("transaction.ID", proc.ID.String()), + ) + } defer span.End() tx := proc.Transaction @@ -207,12 +225,10 @@ func (v *TransactionVerifier) verifyTransaction( return errors.NewInvalidAddressErrorf(tx.Payer, "payer address is invalid") } - signatures, payloadWeights, envelopeWeights, err := newSignatureEntries( - tx.PayloadSignatures, - tx.PayloadMessage(), - tx.EnvelopeSignatures, - tx.EnvelopeMessage(), - ) + // return the signature entries (both payload and envelope) and empty weight maps + // that will be used to aggregate weights. + // the account keys are deduplicated during this call. + signatures, payloadWeights, envelopeWeights, err := newSignatureEntries(tx) if err != nil { return err } @@ -223,16 +239,13 @@ func (v *TransactionVerifier) verifyTransaction( return nil } - err = v.getAccountKeys(txnState, accounts, signatures, tx.ProposalKey) - if err != nil { - return errors.NewInvalidProposalSignatureError(tx.ProposalKey, err) - } - - err = v.verifyAccountSignatures(signatures) + // at this point, account keys are guaranteed to be unique across all signatures + err = v.getAccountKeysAndAggregateWeights(txnState, accounts, signatures, tx.ProposalKey) if err != nil { return errors.NewInvalidProposalSignatureError(tx.ProposalKey, err) } + // all authorizers must have sufficient weights for _, addr := range tx.Authorizers { // Skip this authorizer if it is also the payer. In the case where an account is // both a PAYER as well as an AUTHORIZER or PROPOSER, that account is required @@ -250,6 +263,7 @@ func (v *TransactionVerifier) verifyTransaction( } } + // payer must have sufficient weights if !v.hasSufficientKeyWeight(envelopeWeights, tx.Payer, keyWeightThreshold) { // TODO change this to payer error (needed for fees) return errors.NewAccountAuthorizationErrorf( @@ -259,12 +273,21 @@ func (v *TransactionVerifier) verifyTransaction( keyWeightThreshold) } + // Verify all cryptographic signatures against account public keys (concurrently) + // and fail if at least one signature is invalid. + // (at this point, signatures have been deduplicated and weights have been checked, + // we wouldn't verify the signatures if any of those checks failed) + err = v.verifySignatures(signatures) + if err != nil { + return errors.NewInvalidProposalSignatureError(tx.ProposalKey, err) + } + return nil } -// getAccountKeys gets the signatures' account keys and populate the account -// keys into the signature continuation structs. -func (v *TransactionVerifier) getAccountKeys( +// getAccountKeysAndAggregateWeights gets the signatures' account keys and populate the +// keys and their weights into the signature continuation structs. +func (v *TransactionVerifier) getAccountKeysAndAggregateWeights( _ storage.TransactionPreparer, accounts environment.Accounts, signatures []*signatureContinuation, @@ -285,6 +308,8 @@ func (v *TransactionVerifier) getAccountKeys( } signature.accountKey = accountKey + // aggregateWeight + signature.aggregateWeights[signature.Address] += accountKey.Weight if !foundProposalSignature && signature.matches(proposalKey) { foundProposalSignature = true @@ -300,9 +325,9 @@ func (v *TransactionVerifier) getAccountKeys( return nil } -// verifyAccountSignatures verifies the given signature continuations and -// aggregate the valid signatures' weights. -func (v *TransactionVerifier) verifyAccountSignatures( +// verifySignatures verifies the given cryptographic signature continuations (concurrently). +// It returns an error if at least one signature is invalid and no error if all signatures are valid. +func (v *TransactionVerifier) verifySignatures( signatures []*signatureContinuation, ) error { toVerifyChan := make(chan *signatureContinuation, len(signatures)) @@ -351,7 +376,7 @@ func (v *TransactionVerifier) verifyAccountSignatures( close(toVerifyChan) foundError := false - for i := 0; i < len(signatures); i++ { + for range signatures { entry := <-verifiedChan if !entry.invokedVerify { @@ -366,8 +391,6 @@ func (v *TransactionVerifier) verifyAccountSignatures( foundError = true break } - - entry.aggregateWeights[entry.Address] += entry.accountKey.Weight } if !foundError { diff --git a/fvm/transactionVerifier_test.go b/fvm/transactionVerifier_test.go index e1b5aba4808..98bf7dfd6d7 100644 --- a/fvm/transactionVerifier_test.go +++ b/fvm/transactionVerifier_test.go @@ -4,6 +4,8 @@ import ( "fmt" "testing" + "github.com/onflow/crypto/hash" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/onflow/flow-go/fvm" @@ -16,25 +18,39 @@ import ( "github.com/onflow/flow-go/utils/unittest" ) +const fullWeight = 1000 + +func newContext() fvm.Context { + return fvm.NewContext( + flow.Mainnet.Chain(), + fvm.WithAuthorizationChecksEnabled(true), + fvm.WithAccountKeyWeightThreshold(fullWeight), + fvm.WithSequenceNumberCheckAndIncrementEnabled(false), + fvm.WithTransactionBodyExecutionEnabled(false)) +} + +func newAccount(t *testing.T, accounts *environment.StatefulAccounts) (flow.Address, *flow.AccountPrivateKey) { + address := unittest.RandomAddressFixture() + privKey, err := unittest.AccountKeyDefaultFixture() + require.NoError(t, err) + err = accounts.Create([]flow.AccountPublicKey{privKey.PublicKey(fullWeight)}, address) + require.NoError(t, err) + return address, privKey +} + func TestTransactionVerification(t *testing.T) { t.Parallel() txnState := testutils.NewSimpleTransaction(nil) accounts := environment.NewAccounts(txnState) - // create 2 accounts - address1 := flow.HexToAddress("1234") - privKey1, err := unittest.AccountKeyDefaultFixture() - require.NoError(t, err) - - err = accounts.Create([]flow.AccountPublicKey{privKey1.PublicKey(1000)}, address1) - require.NoError(t, err) + // create 4 accounts + address1, privKey1 := newAccount(t, accounts) + address2, privKey2 := newAccount(t, accounts) + address3, privKey3 := newAccount(t, accounts) - address2 := flow.HexToAddress("1235") - privKey2, err := unittest.AccountKeyDefaultFixture() - require.NoError(t, err) - - err = accounts.Create([]flow.AccountPublicKey{privKey2.PublicKey(1000)}, address2) + // add a partial weight key for address1 for later tests + err := accounts.AppendAccountPublicKey(address1, privKey1.PublicKey(fullWeight/2)) require.NoError(t, err) run := func( @@ -66,12 +82,8 @@ func TestTransactionVerification(t *testing.T) { PayloadSignatures: []flow.TransactionSignature{sig, sig}, } - ctx := fvm.NewContext( - fvm.WithAuthorizationChecksEnabled(true), - fvm.WithAccountKeyWeightThreshold(1000), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - fvm.WithTransactionBodyExecutionEnabled(false)) - err = run(tx, ctx, txnState) + ctx := newContext() + err := run(tx, ctx, txnState) require.ErrorContains( t, err, @@ -96,12 +108,8 @@ func TestTransactionVerification(t *testing.T) { EnvelopeSignatures: []flow.TransactionSignature{sig}, } - ctx := fvm.NewContext( - fvm.WithAuthorizationChecksEnabled(true), - fvm.WithAccountKeyWeightThreshold(1000), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - fvm.WithTransactionBodyExecutionEnabled(false)) - err = run(tx, ctx, txnState) + ctx := newContext() + err := run(tx, ctx, txnState) require.ErrorContains( t, err, @@ -109,13 +117,16 @@ func TestTransactionVerification(t *testing.T) { }) t.Run("invalid envelope signature", func(t *testing.T) { + proposer := address1 + payer := address2 + tx := &flow.TransactionBody{ ProposalKey: flow.ProposalKey{ - Address: address1, + Address: proposer, KeyIndex: 0, SequenceNumber: 0, }, - Payer: address2, + Payer: payer, } // assign a valid payload signature @@ -125,14 +136,14 @@ func TestTransactionVerification(t *testing.T) { require.NoError(t, err) sig1 := flow.TransactionSignature{ - Address: address1, + Address: proposer, SignerIndex: 0, KeyIndex: 0, Signature: validSig, } sig2 := flow.TransactionSignature{ - Address: address2, + Address: payer, SignerIndex: 0, KeyIndex: 0, // invalid signature @@ -141,20 +152,20 @@ func TestTransactionVerification(t *testing.T) { tx.PayloadSignatures = []flow.TransactionSignature{sig1} tx.EnvelopeSignatures = []flow.TransactionSignature{sig2} - ctx := fvm.NewContext( - fvm.WithAuthorizationChecksEnabled(true), - fvm.WithAccountKeyWeightThreshold(1000), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - fvm.WithTransactionBodyExecutionEnabled(false)) + ctx := newContext() err = run(tx, ctx, txnState) - require.Error(t, err) + require.True(t, errors.IsInvalidEnvelopeSignatureError(err)) + assert.ErrorContainsf(t, err, fmt.Sprintf("on account %s", payer), "should mention the proposer address %s", payer) }) t.Run("invalid payload signature", func(t *testing.T) { + proposer := address1 + payer := address2 + sig1 := flow.TransactionSignature{ - Address: address1, + Address: proposer, SignerIndex: 0, KeyIndex: 0, // invalid signature @@ -162,11 +173,11 @@ func TestTransactionVerification(t *testing.T) { tx := &flow.TransactionBody{ ProposalKey: flow.ProposalKey{ - Address: address1, + Address: proposer, KeyIndex: 0, SequenceNumber: 0, }, - Payer: address2, + Payer: payer, } // assign a valid envelope signature @@ -176,7 +187,7 @@ func TestTransactionVerification(t *testing.T) { require.NoError(t, err) sig2 := flow.TransactionSignature{ - Address: address2, + Address: payer, SignerIndex: 0, KeyIndex: 0, Signature: validSig, @@ -185,14 +196,10 @@ func TestTransactionVerification(t *testing.T) { tx.PayloadSignatures = []flow.TransactionSignature{sig1} tx.EnvelopeSignatures = []flow.TransactionSignature{sig2} - ctx := fvm.NewContext( - fvm.WithAuthorizationChecksEnabled(true), - fvm.WithAccountKeyWeightThreshold(1000), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - fvm.WithTransactionBodyExecutionEnabled(false)) + ctx := newContext() err = run(tx, ctx, txnState) - require.Error(t, err) require.True(t, errors.IsInvalidPayloadSignatureError(err)) + assert.ErrorContainsf(t, err, fmt.Sprintf("on account %s", proposer), "should mention the proposer address %s", proposer) }) t.Run("invalid payload and envelope signatures", func(t *testing.T) { @@ -200,15 +207,18 @@ func TestTransactionVerification(t *testing.T) { // The test should be updated once the FVM updates the order of validating signatures: // envelope needs to be checked first and payload later. + proposer := address1 + payer := address2 + sig1 := flow.TransactionSignature{ - Address: address1, + Address: proposer, SignerIndex: 0, KeyIndex: 0, // invalid signature } sig2 := flow.TransactionSignature{ - Address: address2, + Address: payer, SignerIndex: 0, KeyIndex: 0, // invalid signature @@ -216,7 +226,7 @@ func TestTransactionVerification(t *testing.T) { tx := &flow.TransactionBody{ ProposalKey: flow.ProposalKey{ - Address: address1, + Address: proposer, KeyIndex: 0, SequenceNumber: 0, }, @@ -225,16 +235,279 @@ func TestTransactionVerification(t *testing.T) { EnvelopeSignatures: []flow.TransactionSignature{sig2}, } - ctx := fvm.NewContext( - fvm.WithAuthorizationChecksEnabled(true), - fvm.WithAccountKeyWeightThreshold(1000), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - fvm.WithTransactionBodyExecutionEnabled(false)) - err = run(tx, ctx, txnState) - require.Error(t, err) + ctx := newContext() + err := run(tx, ctx, txnState) // TODO: update to InvalidEnvelopeSignatureError once FVM verifier is updated. require.True(t, errors.IsInvalidPayloadSignatureError(err)) + assert.ErrorContainsf(t, err, fmt.Sprintf("on account %s", proposer), "should mention the proposer address %s", proposer) + }) + + t.Run("missing authorizer signatures", func(t *testing.T) { + payer := address1 + address4 := unittest.RandomAddressFixture() + authorizers := []flow.Address{address2, address3, address4} + + tx := &flow.TransactionBody{ + ProposalKey: flow.ProposalKey{ + Address: payer, + KeyIndex: 0, + SequenceNumber: 0, + }, + Payer: payer, + Authorizers: authorizers, + } + + // assign a valid payload signature + hasher, err := crypto.NewPrefixedHashing(hash.SHA3_256, flow.TransactionTagString) + require.NoError(t, err) + + validSig, err := privKey2.PrivateKey.Sign(tx.PayloadMessage(), hasher) // valid signature + require.NoError(t, err) + sig2 := flow.TransactionSignature{ + Address: address2, + SignerIndex: 0, + KeyIndex: 0, + Signature: validSig, + } + + validSig, err = privKey3.PrivateKey.Sign(tx.PayloadMessage(), hasher) // valid signature + require.NoError(t, err) + sig3 := flow.TransactionSignature{ + Address: address3, + SignerIndex: 0, + KeyIndex: 0, + Signature: validSig, + } + + tx.PayloadSignatures = []flow.TransactionSignature{sig2, sig3} // address from address4 is missing + + validSig, err = privKey1.PrivateKey.Sign(tx.EnvelopeMessage(), hasher) // valid signature + require.NoError(t, err) + + sig1 := flow.TransactionSignature{ + Address: payer, + SignerIndex: 0, + KeyIndex: 0, + Signature: validSig, + } + + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + ctx := newContext() + err = run(tx, ctx, txnState) + assert.ErrorContainsf(t, err, fmt.Sprintf("authorization failed for account %s", address4), "should mention an authorizer error") + }) + + t.Run("one authorizer with not enough weights", func(t *testing.T) { + payer := address1 + authorizers := []flow.Address{address2, address3} + + // use partial weight key for address3 + err := accounts.AppendAccountPublicKey(address3, privKey3.PublicKey(fullWeight/2)) + require.NoError(t, err) + + tx := &flow.TransactionBody{ + ProposalKey: flow.ProposalKey{ + Address: payer, + KeyIndex: 0, + SequenceNumber: 0, + }, + Payer: payer, + Authorizers: authorizers, + } + + // assign a valid payload signature + hasher, err := crypto.NewPrefixedHashing(hash.SHA3_256, flow.TransactionTagString) + require.NoError(t, err) + + validSig, err := privKey2.PrivateKey.Sign(tx.PayloadMessage(), hasher) // valid signature + require.NoError(t, err) + sig2 := flow.TransactionSignature{ + Address: address2, + SignerIndex: 0, + KeyIndex: 0, + Signature: validSig, + } + + validSig, err = privKey3.PrivateKey.Sign(tx.PayloadMessage(), hasher) // valid signature + require.NoError(t, err) + sig3 := flow.TransactionSignature{ + Address: address3, + SignerIndex: 0, + KeyIndex: 1, // partial weight key + Signature: validSig, + } + + tx.PayloadSignatures = []flow.TransactionSignature{sig2, sig3} + validSig, err = privKey1.PrivateKey.Sign(tx.EnvelopeMessage(), hasher) // valid signature + require.NoError(t, err) + + sig1 := flow.TransactionSignature{ + Address: payer, + SignerIndex: 0, + KeyIndex: 0, + Signature: validSig, + } + + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + ctx := newContext() + err = run(tx, ctx, txnState) + assert.ErrorContains(t, err, "authorizer account does not have sufficient signatures", "error should be about insufficient authorizer weights") + }) + + t.Run("payer with not enough weights", func(t *testing.T) { + payer := address1 + + tx := &flow.TransactionBody{ + ProposalKey: flow.ProposalKey{ + Address: payer, + KeyIndex: 1, // partial weight key + SequenceNumber: 0, + }, + Payer: payer, + } + + // assign a valid payload signature + hasher, err := crypto.NewPrefixedHashing(hash.SHA3_256, flow.TransactionTagString) + require.NoError(t, err) + + validSig, err := privKey1.PrivateKey.Sign(tx.EnvelopeMessage(), hasher) // valid signature + require.NoError(t, err) + + sig1 := flow.TransactionSignature{ + Address: payer, + SignerIndex: 0, + KeyIndex: 1, // partial weight key + Signature: validSig, + } + + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + ctx := newContext() + err = run(tx, ctx, txnState) + assert.ErrorContains(t, err, "payer account does not have sufficient signatures", "error should be about insufficient payer weights") + }) + + t.Run("payer signing the payload only", func(t *testing.T) { + payer := address1 + + tx := &flow.TransactionBody{ + ProposalKey: flow.ProposalKey{ + Address: payer, + KeyIndex: 0, + SequenceNumber: 0, + }, + Payer: payer, + } + + // assign a valid payload signature + hasher, err := crypto.NewPrefixedHashing(hash.SHA3_256, flow.TransactionTagString) + require.NoError(t, err) + + validSig, err := privKey1.PrivateKey.Sign(tx.PayloadMessage(), hasher) // valid signature + require.NoError(t, err) + + sig := flow.TransactionSignature{ + Address: payer, + SignerIndex: 0, + KeyIndex: 0, + Signature: validSig, + } + + tx.PayloadSignatures = []flow.TransactionSignature{sig} + + ctx := newContext() + err = run(tx, ctx, txnState) + assert.ErrorContains(t, err, "payer account does not have sufficient signatures", "error should be about insufficient payer weights") + }) + + t.Run("weights are checked before signatures", func(t *testing.T) { + // use a key with partial weight and an invalid signature and make sure + // the weight error is returned before the signature error + payer := address1 + + tx := &flow.TransactionBody{ + ProposalKey: flow.ProposalKey{ + Address: payer, + KeyIndex: 1, // partial weight key + SequenceNumber: 0, + }, + Payer: payer, + } + + sig1 := flow.TransactionSignature{ + Address: payer, + SignerIndex: 0, + KeyIndex: 1, // partial weight key + // empty signature is invalid signature + } + + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + ctx := newContext() + err = run(tx, ctx, txnState) + assert.ErrorContains(t, err, "payer account does not have sufficient signatures", "error should be about insufficient payer weights not invalid signature") + }) + + t.Run("signature from unrelated address", func(t *testing.T) { + payer := address1 + proposer := address2 + authorizers := []flow.Address{address3} + unrelated := unittest.RandomAddressFixture() + + tx := &flow.TransactionBody{ + ProposalKey: flow.ProposalKey{ + Address: proposer, + KeyIndex: 0, + SequenceNumber: 0, + }, + Payer: payer, + Authorizers: authorizers, + } + + // proposer signature + sig2 := flow.TransactionSignature{ + Address: proposer, + SignerIndex: 0, + KeyIndex: 0, + } + + // authorizer signature + sig3 := flow.TransactionSignature{ + Address: authorizers[0], + SignerIndex: 0, + KeyIndex: 0, + } + + // unrelated account signature + sig4 := flow.TransactionSignature{ + Address: unrelated, + SignerIndex: 0, + KeyIndex: 0, + } + + sig1 := flow.TransactionSignature{ + Address: payer, + SignerIndex: 0, + KeyIndex: 0, + } + + // unrelated account signature is included as a payload signature + tx.PayloadSignatures = []flow.TransactionSignature{sig2, sig3, sig4} + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1} + + ctx := newContext() + err = run(tx, ctx, txnState) + assert.ErrorContains(t, err, "that is neither payer nor authorizer nor proposer", "error should be about unrelated account signature") + + // unrelated account signature is included as an envelope signature + tx.PayloadSignatures = []flow.TransactionSignature{sig2, sig3} + tx.EnvelopeSignatures = []flow.TransactionSignature{sig1, sig4} + + err = run(tx, ctx, txnState) + assert.ErrorContains(t, err, "that is neither payer nor authorizer nor proposer", "error should be about unrelated account signature") }) // test that Transaction Signature verification uses the correct domain tag for verification @@ -285,11 +558,7 @@ func TestTransactionVerification(t *testing.T) { // set the signature into the transaction tx.EnvelopeSignatures[0].Signature = sig - ctx := fvm.NewContext( - fvm.WithAuthorizationChecksEnabled(true), - fvm.WithAccountKeyWeightThreshold(1000), - fvm.WithSequenceNumberCheckAndIncrementEnabled(false), - fvm.WithTransactionBodyExecutionEnabled(false)) + ctx := newContext() err = run(tx, ctx, txnState) if c.validity { require.NoError(t, err) diff --git a/go.mod b/go.mod index 4f2a4c2d698..c9afbeb8053 100644 --- a/go.mod +++ b/go.mod @@ -1,13 +1,13 @@ module github.com/onflow/flow-go -go 1.25.0 +go 1.25.1 require ( cloud.google.com/go/compute/metadata v0.9.0 cloud.google.com/go/profiler v0.3.0 - cloud.google.com/go/storage v1.50.0 + cloud.google.com/go/storage v1.56.0 github.com/antihax/optional v1.0.0 - github.com/aws/aws-sdk-go-v2/config v1.31.20 + github.com/aws/aws-sdk-go-v2/config v1.32.7 github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1 github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0 github.com/btcsuite/btcd/btcec/v2 v2.3.4 @@ -15,8 +15,8 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc github.com/dgraph-io/badger/v2 v2.2007.4 github.com/ef-ds/deque v1.0.4 - github.com/ethereum/go-ethereum v1.16.7 - github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013 + github.com/ethereum/go-ethereum v1.16.8 + github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e github.com/gammazero/workerpool v1.1.3 github.com/gogo/protobuf v1.3.2 github.com/golang/mock v1.6.0 @@ -27,7 +27,7 @@ require ( github.com/gorilla/mux v1.8.1 github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 - github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 github.com/hashicorp/go-multierror v1.1.1 github.com/improbable-eng/grpc-web v0.15.0 github.com/ipfs/go-block-format v0.2.0 @@ -46,14 +46,14 @@ require ( github.com/multiformats/go-multiaddr v0.14.0 github.com/multiformats/go-multiaddr-dns v0.4.1 github.com/multiformats/go-multihash v0.2.3 - github.com/onflow/atree v0.12.0 - github.com/onflow/cadence v1.9.2 - github.com/onflow/crypto v0.25.3 - github.com/onflow/flow v0.4.15 - github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2 - github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2 - github.com/onflow/flow-go-sdk v1.9.7 - github.com/onflow/flow/protobuf/go/flow v0.4.18 + github.com/onflow/atree v0.16.1 + github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382 + github.com/onflow/crypto v0.25.4 + github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b + github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 + github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 + github.com/onflow/flow-go-sdk v1.10.3 + github.com/onflow/flow/protobuf/go/flow v0.4.20 github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 github.com/pkg/errors v0.9.1 github.com/pkg/profile v1.7.0 @@ -68,24 +68,24 @@ require ( github.com/spf13/viper v1.15.0 github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v4 v4.3.11 - go.opentelemetry.io/otel v1.38.0 + go.opentelemetry.io/otel v1.39.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 - go.opentelemetry.io/otel/sdk v1.38.0 - go.opentelemetry.io/otel/trace v1.38.0 + go.opentelemetry.io/otel/sdk v1.39.0 + go.opentelemetry.io/otel/trace v1.39.0 go.uber.org/atomic v1.11.0 go.uber.org/multierr v1.11.0 - golang.org/x/crypto v0.45.0 + golang.org/x/crypto v0.47.0 golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 - golang.org/x/sync v0.18.0 - golang.org/x/sys v0.38.0 - golang.org/x/text v0.31.0 - golang.org/x/time v0.12.0 - golang.org/x/tools v0.39.0 - google.golang.org/api v0.247.0 - google.golang.org/genproto v0.0.0-20250603155806-513f23925822 - google.golang.org/grpc v1.77.0 + golang.org/x/sync v0.19.0 + golang.org/x/sys v0.40.0 + golang.org/x/text v0.33.0 + golang.org/x/time v0.14.0 + golang.org/x/tools v0.40.0 + google.golang.org/api v0.267.0 + google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 + google.golang.org/grpc v1.79.3 google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0 - google.golang.org/protobuf v1.36.10 + google.golang.org/protobuf v1.36.11 gotest.tools v2.2.0+incompatible pgregory.net/rapid v1.1.0 ) @@ -102,62 +102,64 @@ require ( github.com/holiman/uint256 v1.3.2 github.com/huandu/go-clone/generic v1.7.2 github.com/ipfs/boxo v0.17.1-0.20240131173518-89bceff34bf1 - github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956 + github.com/jordanschalm/lockctx v0.1.0 github.com/libp2p/go-libp2p-routing-helpers v0.7.4 github.com/mitchellh/mapstructure v1.5.0 - github.com/onflow/flow-evm-bridge v0.1.0 + github.com/onflow/flow-evm-bridge v0.2.1 github.com/onflow/go-ethereum v1.13.4 - github.com/onflow/nft-storefront/lib/go/contracts v1.0.0 + github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066 github.com/onflow/wal v1.0.2 github.com/pierrec/lz4/v4 v4.1.22 github.com/slok/go-http-metrics v0.12.0 github.com/sony/gobreaker v0.5.0 go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.21.0 golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da - google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 - google.golang.org/genproto/googleapis/bytestream v0.0.0-20250804133106-a7a43d27e69b + google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20 + google.golang.org/genproto/googleapis/bytestream v0.0.0-20260203192932-546029d2fa20 gopkg.in/yaml.v2 v2.4.0 ) require ( github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20251001021608-1fe7b43fc4d6 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect github.com/crate-crypto/go-eth-kzg v1.4.0 // indirect github.com/emicklei/dot v1.6.2 // indirect github.com/ethereum/c-kzg-4844/v2 v2.1.5 // indirect github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab // indirect github.com/ferranbt/fastssz v0.1.4 // indirect - golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc // indirect ) require ( - cel.dev/expr v0.24.0 // indirect - cloud.google.com/go v0.120.0 // indirect - cloud.google.com/go/auth v0.16.4 // indirect + cel.dev/expr v0.25.1 // indirect + cloud.google.com/go v0.123.0 // indirect + cloud.google.com/go/auth v0.18.1 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - cloud.google.com/go/iam v1.5.2 // indirect - cloud.google.com/go/monitoring v1.24.2 // indirect + cloud.google.com/go/iam v1.5.3 // indirect + cloud.google.com/go/monitoring v1.24.3 // indirect github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect github.com/Jorropo/jsync v1.0.1 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/OneOfOne/xxhash v1.2.8 // indirect github.com/SaveTheRbtz/mph v0.1.1-0.20240117162131-4166ec7869bc // indirect github.com/StackExchange/wmi v1.2.1 // indirect github.com/VictoriaMetrics/fastcache v1.13.0 // indirect - github.com/aws/aws-sdk-go-v2 v1.40.1 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.18.24 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14 // indirect + github.com/aws/aws-sdk-go-v2 v1.41.1 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.19.7 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.40.2 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect github.com/aws/smithy-go v1.24.0 // indirect github.com/benbjohnson/clock v1.3.5 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -165,7 +167,7 @@ require ( github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f // indirect + github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 // indirect github.com/cockroachdb/errors v1.11.3 // indirect github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect @@ -173,7 +175,7 @@ require ( github.com/cockroachdb/redact v1.1.5 // indirect github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect - github.com/consensys/gnark-crypto v0.18.0 // indirect + github.com/consensys/gnark-crypto v0.18.1 // indirect github.com/containerd/cgroups v1.1.0 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect @@ -185,8 +187,8 @@ require ( github.com/dgraph-io/ristretto v0.1.0 // indirect github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 // indirect github.com/elastic/gosigar v0.14.3 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.35.0 // indirect - github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect github.com/ethereum/go-verkle v0.2.2 // indirect github.com/felixge/fgprof v0.9.3 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect @@ -209,12 +211,12 @@ require ( github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect - github.com/gofrs/flock v0.12.1 // indirect + github.com/gofrs/flock v0.12.1 github.com/golang/glog v1.2.5 // indirect github.com/google/gopacket v1.1.19 // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect - github.com/googleapis/gax-go/v2 v2.15.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect + github.com/googleapis/gax-go/v2 v2.17.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect @@ -274,10 +276,10 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/onflow/fixed-point v0.1.1 // indirect - github.com/onflow/flow-ft/lib/go/contracts v1.0.1 // indirect - github.com/onflow/flow-ft/lib/go/templates v1.0.1 // indirect - github.com/onflow/flow-nft/lib/go/contracts v1.3.0 // indirect - github.com/onflow/flow-nft/lib/go/templates v1.3.0 // indirect + github.com/onflow/flow-ft/lib/go/contracts v1.1.1 // indirect + github.com/onflow/flow-ft/lib/go/templates v1.1.1 // indirect + github.com/onflow/flow-nft/lib/go/contracts v1.4.1 + github.com/onflow/flow-nft/lib/go/templates v1.4.1 // indirect github.com/onflow/sdks v0.6.0-preview.1 // indirect github.com/onsi/ginkgo/v2 v2.22.0 // indirect github.com/opencontainers/runtime-spec v1.2.0 // indirect @@ -305,7 +307,7 @@ require ( github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/polydawn/refmt v0.89.0 // indirect github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect - github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/client_model v0.6.2 github.com/prometheus/common v0.61.0 // indirect github.com/prometheus/procfs v0.15.1 // indirect github.com/psiemens/sconfig v0.1.0 // indirect @@ -337,24 +339,24 @@ require ( github.com/zeebo/blake3 v0.2.4 // indirect go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.38.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 // indirect - go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect - go.opentelemetry.io/proto/otlp v1.7.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 // indirect + go.opentelemetry.io/otel/metric v1.39.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.39.0 // indirect + go.opentelemetry.io/proto/otlp v1.9.0 // indirect go.uber.org/dig v1.18.0 // indirect go.uber.org/fx v1.23.0 // indirect go.uber.org/mock v0.5.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/mod v0.30.0 // indirect - golang.org/x/net v0.47.0 // indirect - golang.org/x/oauth2 v0.32.0 // indirect - golang.org/x/term v0.37.0 // indirect + golang.org/x/mod v0.31.0 // indirect + golang.org/x/net v0.49.0 // indirect + golang.org/x/oauth2 v0.35.0 // indirect + golang.org/x/term v0.39.0 // indirect gonum.org/v1/gonum v0.16.0 // indirect google.golang.org/appengine v1.6.8 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect lukechampine.com/blake3 v1.4.1 // indirect diff --git a/go.sum b/go.sum index d62f5953555..adbceb6b7b5 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= -cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= +cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= @@ -33,10 +33,10 @@ cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= -cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= -cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= -cloud.google.com/go/auth v0.16.4 h1:fXOAIQmkApVvcIn7Pc2+5J8QTMVbUGLscnSVNl11su8= -cloud.google.com/go/auth v0.16.4/go.mod h1:j10ncYwjX/g3cdX7GpEzsdM+d+ZNsXAbb6qXA7p1Y5M= +cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= +cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= +cloud.google.com/go/auth v0.18.1 h1:IwTEx92GFUo2pJ6Qea0EU3zYvKnTAeRCODxfA/G5UWs= +cloud.google.com/go/auth v0.18.1/go.mod h1:GfTYoS9G3CWpRA3Va9doKN9mjPGRS+v41jmZAhBzbrA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= @@ -55,14 +55,14 @@ cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCB cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= -cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= -cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= -cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= -cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= -cloud.google.com/go/longrunning v0.6.7 h1:IGtfDWHhQCgCjwQjV9iiLnUta9LBCo8R9QmAFsS/PrE= -cloud.google.com/go/longrunning v0.6.7/go.mod h1:EAFV3IZAKmM56TyiE6VAP3VoTzhZzySwI/YI1s/nRsY= -cloud.google.com/go/monitoring v1.24.2 h1:5OTsoJ1dXYIiMiuL+sYscLc9BumrL3CarVLL7dd7lHM= -cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= +cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= +cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= +cloud.google.com/go/logging v1.13.1 h1:O7LvmO0kGLaHY/gq8cV7T0dyp6zJhYAOtZPX4TF3QtY= +cloud.google.com/go/logging v1.13.1/go.mod h1:XAQkfkMBxQRjQek96WLPNze7vsOmay9H5PqfsNYDqvw= +cloud.google.com/go/longrunning v0.8.0 h1:LiKK77J3bx5gDLi4SMViHixjD2ohlkwBi+mKA7EhfW8= +cloud.google.com/go/longrunning v0.8.0/go.mod h1:UmErU2Onzi+fKDg2gR7dusz11Pe26aknR4kHmJJqIfk= +cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE= +cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= cloud.google.com/go/profiler v0.3.0 h1:R6y/xAeifaUXxd2x6w+jIwKxoKl8Cv5HJvcvASTPWJo= cloud.google.com/go/profiler v0.3.0/go.mod h1:9wYk9eY4iZHsev8TQb61kh3wiOiSyz/xOYixWPzweCU= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= @@ -76,10 +76,10 @@ cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RX cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq6kuBTW58Y= -cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= -cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= -cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4= -cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= +cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI= +cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU= +cloud.google.com/go/trace v1.11.7 h1:kDNDX8JkaAG3R2nq1lIdkb7FCSi1rCmsEtKVsty7p+U= +cloud.google.com/go/trace v1.11.7/go.mod h1:TNn9d5V3fQVf6s4SCveVMIBS2LJUqo73GACmq/Tky0s= dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= @@ -92,12 +92,12 @@ github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e h1:ZIWapoIRN1VqT8GR github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0/go.mod h1:ZV4VOm0/eHR06JLrXWe09068dHpr3TRpY9Uo7T+anuA= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0 h1:nNMpRpnkWDAaqcpxMJvxa/Ud98gjbYwayJY4/9bdjiU= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0/go.mod h1:SZiPHWGOOk3bl8tkevxkoiwPgsIl6CwrWcbwjfHZpdM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 h1:ig/FpDD2JofP/NExKQUbn7uOSZzJAQqogfqluZK4ed4= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 h1:owcC2UnmsZycprQ5RfRgjydWhuoxg71LUfyiQdijZuM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0 h1:4LP6hvB4I5ouTbGgWtixJhgED6xdf67twf9PoY96Tbg= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0/go.mod h1:jUZ5LYlw40WMd07qxcQJD5M40aUxrfwqQX1g7zxYnrQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= github.com/Jorropo/jsync v1.0.1 h1:6HgRolFZnsdfzRUj+ImB9og1JYOxQoReSywkHOGSaUU= github.com/Jorropo/jsync v1.0.1/go.mod h1:jCOZj3vrBCri3bSU3ErUYvevKlnbssrXeCivybS5ABQ= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= @@ -141,44 +141,46 @@ github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQ github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= -github.com/aws/aws-sdk-go-v2 v1.40.1 h1:difXb4maDZkRH0x//Qkwcfpdg1XQVXEAEs2DdXldFFc= -github.com/aws/aws-sdk-go-v2 v1.40.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= +github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= +github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= github.com/aws/aws-sdk-go-v2/config v1.8.0/go.mod h1:w9+nMZ7soXCe5nT46Ri354SNhXDQ6v+V5wqDjnZE+GY= -github.com/aws/aws-sdk-go-v2/config v1.31.20 h1:/jWF4Wu90EhKCgjTdy1DGxcbcbNrjfBHvksEL79tfQc= -github.com/aws/aws-sdk-go-v2/config v1.31.20/go.mod h1:95Hh1Tc5VYKL9NJ7tAkDcqeKt+MCXQB1hQZaRdJIZE0= +github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY= +github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY= github.com/aws/aws-sdk-go-v2/credentials v1.4.0/go.mod h1:dgGR+Qq7Wjcd4AOAW5Rf5Tnv3+x7ed6kETXyS9WCuAY= -github.com/aws/aws-sdk-go-v2/credentials v1.18.24 h1:iJ2FmPT35EaIB0+kMa6TnQ+PwG5A1prEdAw+PsMzfHg= -github.com/aws/aws-sdk-go-v2/credentials v1.18.24/go.mod h1:U91+DrfjAiXPDEGYhh/x29o4p0qHX5HDqG7y5VViv64= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0/go.mod h1:CpNzHK9VEFUCknu50kkB8z58AH2B5DvPP7ea1LHve/Y= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 h1:T1brd5dR3/fzNFAQch/iBKeX07/ffu/cLu+q+RuzEWk= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13/go.mod h1:Peg/GBAQ6JDt+RoBf4meB1wylmAipb7Kg2ZFakZTlwk= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1 h1:VGkV9KmhGqOQWnHyi4gLG98kE6OecT42fdrCGFWxJsc= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1/go.mod h1:PLlnMiki//sGnCJiW+aVpvP/C8Kcm8mEj/IVm9+9qk4= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14 h1:PZHqQACxYb8mYgms4RZbhZG0a7dPW06xOjmaH0EJC/I= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14/go.mod h1:VymhrMJUWs69D8u0/lZ7jSB6WgaG/NqHi3gX0aYf6U0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14 h1:bOS19y6zlJwagBfHxs0ESzr1XCOU2KXJCWcq3E2vfjY= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14/go.mod h1:1ipeGBMAxZ0xcTm6y6paC2C/J6f6OO7LBODV9afuAyM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2/go.mod h1:BQV0agm+JEhqR+2RT5e1XTFIDcAAV0eW6z2trp+iduw= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0/go.mod h1:v8ygadNyATSm6elwJ/4gzJwcFhri9RqS8skgHKiwXPU= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 h1:x2Ibm/Af8Fi+BH+Hsn9TXGdT+hKbDd5XOTZxTMxDk7o= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3/go.mod h1:IW1jwyrQgMdhisceG8fQLmQIydcT/jWY21rFhzgaKwo= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0/go.mod h1:R1KK+vY8AfalhG1AOu5e35pOD2SdoPKQCFLTvnxiohk= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 h1:kDqdFvMY4AtKoACfzIGD8A0+hbT41KTKF//gq7jITfM= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13/go.mod h1:lmKuogqSU3HzQCwZ9ZtcqOc5XGMqtDK7OIc2+DxiUEg= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0 h1:HWsM0YQWX76V6MOp07YuTYacm8k7h69ObJuw7Nck+og= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0/go.mod h1:LKb3cKNQIMh+itGnEpKGcnL/6OIjPZqrtYah1w5f+3o= github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0 h1:nPLfLPfglacc29Y949sDxpr3X/blaY40s3B85WT2yZU= github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0/go.mod h1:Iv2aJVtVSm/D22rFoX99cLG4q4uB7tppuCsulGe98k4= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M= github.com/aws/aws-sdk-go-v2/service/sso v1.4.0/go.mod h1:+1fpWnL96DL23aXPpMGbsmKe8jLTEfbjuQoA4WS1VaA= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 h1:NjShtS1t8r5LUfFVtFeI8xLAHQNTa7UI0VawXlrBMFQ= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.3/go.mod h1:fKvyjJcz63iL/ftA6RaM8sRCtN4r4zl4tjL3qw5ec7k= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 h1:gTsnx0xXNQ6SBbymoDvcoRHL+q4l/dAFsQuKfDWSaGc= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7/go.mod h1:klO+ejMvYsB4QATfEOIXk8WAEwN4N0aBfJpvC+5SZBo= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo= github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= -github.com/aws/aws-sdk-go-v2/service/sts v1.40.2 h1:HK5ON3KmQV2HcAunnx4sKLB9aPf3gKGwVAf7xnx0QT0= -github.com/aws/aws-sdk-go-v2/service/sts v1.40.2/go.mod h1:E19xDjpzPZC7LS2knI9E6BaRFDK43Eul7vd6rSq2HWk= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= @@ -233,8 +235,8 @@ github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f h1:Y8xYupdHxryycyPlc9Y+bSQAYZnetRJ70VMVKm5CKI0= -github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f/go.mod h1:HlzOvOjVBOfTGSRXRyY0OiCS/3J1akRGQQpRO/7zyF4= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 h1:bvJv505UUfjzbaIPdNS4AEkHreDqQk6yuNpsdRHpwFA= github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94/go.mod h1:Gq51ZeKaFCXk6QwuGM0w1dnaOqc/F5zKT2zA9D6Xeac= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= @@ -259,8 +261,8 @@ github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961/go.mod h1:yBRu/c github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= -github.com/consensys/gnark-crypto v0.18.0 h1:vIye/FqI50VeAr0B3dx+YjeIvmc3LWz4yEfbWBpTUf0= -github.com/consensys/gnark-crypto v0.18.0/go.mod h1:L3mXGFTe1ZN+RSJ+CLjUt9x7PNdx8ubaYfDROyp2Z8c= +github.com/consensys/gnark-crypto v0.18.1 h1:RyLV6UhPRoYYzaFnPQA4qK3DyuDgkTgskDdoGqFt3fI= +github.com/consensys/gnark-crypto v0.18.1/go.mod h1:L3mXGFTe1ZN+RSJ+CLjUt9x7PNdx8ubaYfDROyp2Z8c= github.com/containerd/cgroups v0.0.0-20201119153540-4cbc285b3327/go.mod h1:ZJeTFisyysqgcCdecO57Dj79RfL0LNeGiFUqLYQRYLE= github.com/containerd/cgroups v1.1.0 h1:v8rEWFl6EoqHB+swVNjVoCJE8o3jX7e8nqBGPLaDFBM= github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw= @@ -342,21 +344,21 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= -github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329 h1:K+fnvUM0VZ7ZFJf0n4L/BRlnsb9pL/GuDG6FqaH+PwM= -github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329/go.mod h1:Alz8LEClvR7xKsrq3qzoc4N0guvVNSS8KmSChGYr9hs= -github.com/envoyproxy/go-control-plane/envoy v1.35.0 h1:ixjkELDE+ru6idPxcHLj8LBVc2bFP7iBytj353BoHUo= -github.com/envoyproxy/go-control-plane/envoy v1.35.0/go.mod h1:09qwbGVuSWWAyN5t/b3iyVfz5+z8QWGrzkoqm/8SbEs= +github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= +github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= +github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g= +github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= -github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4= +github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= github.com/ethereum/c-kzg-4844/v2 v2.1.5 h1:aVtoLK5xwJ6c5RiqO8g8ptJ5KU+2Hdquf6G3aXiHh5s= github.com/ethereum/c-kzg-4844/v2 v2.1.5/go.mod h1:u59hRTTah4Co6i9fDWtiCjTrblJv0UwsqZKCc0GfgUs= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab h1:rvv6MJhy07IMfEKuARQ9TKojGqLVNxQajaXEp/BoqSk= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab/go.mod h1:IuLm4IsPipXKF7CW5Lzf68PIbZ5yl7FFd74l/E0o9A8= -github.com/ethereum/go-ethereum v1.16.7 h1:qeM4TvbrWK0UC0tgkZ7NiRsmBGwsjqc64BHo20U59UQ= -github.com/ethereum/go-ethereum v1.16.7/go.mod h1:Fs6QebQbavneQTYcA39PEKv2+zIjX7rPUZ14DER46wk= +github.com/ethereum/go-ethereum v1.16.8 h1:LLLfkZWijhR5m6yrAXbdlTeXoqontH+Ga2f9igY7law= +github.com/ethereum/go-ethereum v1.16.8/go.mod h1:Fs6QebQbavneQTYcA39PEKv2+zIjX7rPUZ14DER46wk= github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cnFk8= github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -381,8 +383,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013 h1:jcwW+JBYGe3qgiPQ4deXaannYxVdxjMw57/dw+gcEfQ= -github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e h1:AqsamU9dS+/RNjgvDOqFUT7qXApcmnw7zJLLqJkx860= +github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/fxamacker/circlehash v0.3.0 h1:XKdvTtIJV9t7DDUtsf0RIpC1OcxZtPbmgIH7ekx28WA= github.com/fxamacker/circlehash v0.3.0/go.mod h1:3aq3OfVvsWtkWMb6A1owjOQFA+TLsD5FgJflnaQwtMM= github.com/fxamacker/golang-lru/v2 v2.0.0-20250716153046-22c8d17dc4ee h1:9RFHOj6xUdQRi1lz/BJXwi0IloXtv6Y2tp7rdSC7SQk= @@ -578,8 +580,8 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= -github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= @@ -589,8 +591,8 @@ github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0 github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM= github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM= github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= -github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= -github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= +github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc= +github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= @@ -618,8 +620,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpg github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4= github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -720,8 +722,8 @@ github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956 h1:4iii8SOozVG1lpkdPELRsjPEBhU4DeFPz2r2Fjj3UDU= -github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956/go.mod h1:qsnXMryYP9X7JbzskIn0+N40sE6XNXLr9kYRRP6rwXU= +github.com/jordanschalm/lockctx v0.1.0 h1:2ZziSl5zejl5VSRUjl+UtYV94QPFQgO9bekqWPOKUQw= +github.com/jordanschalm/lockctx v0.1.0/go.mod h1:qsnXMryYP9X7JbzskIn0+N40sE6XNXLr9kYRRP6rwXU= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -936,42 +938,42 @@ github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onflow/atree v0.12.0 h1:X7/UEPyCaaEQ1gCg11KDvfyEtEeQLhtRtxMHjAiH/Co= -github.com/onflow/atree v0.12.0/go.mod h1:qdZcfLQwPirHcNpLiK+2t3KAo+SAb9Si6TqurE6pykE= +github.com/onflow/atree v0.16.1 h1:EmlaIz/GwQ39o5agAb2KT2ynt4SHRBkgMMWU5bp6iTs= +github.com/onflow/atree v0.16.1/go.mod h1:hiOT/vKK/Zyw34Ru9OFbfEemC5NnQ7SHFB43bN9/4qI= github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483 h1:LpiQhTAfM9CAmNVEs0n//cBBgCg+vJSiIxTHYUklZ84= github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483/go.mod h1:pIZgTWdm3k3pLF9Uq6MB8JEcW07UDwNJjlXW1HELW80= -github.com/onflow/cadence v1.9.2 h1:r1hKhbrFJgrLCHj8N0Bp8/gfG9Vc5WTYOtDjdcWqEk4= -github.com/onflow/cadence v1.9.2/go.mod h1:MlJsCwhCZwdnAUd24XHzcsizZfG7a2leab1PztabUsE= -github.com/onflow/crypto v0.25.3 h1:XQ3HtLsw8h1+pBN+NQ1JYM9mS2mVXTyg55OldaAIF7U= -github.com/onflow/crypto v0.25.3/go.mod h1:+1igaXiK6Tjm9wQOBD1EGwW7bYWMUGKtwKJ/2QL/OWs= +github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382 h1:3lnbPpMxrNsZLN6uUwZy5zbIc2PlaOefjlOKm2PunYk= +github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382/go.mod h1:hoz+FnPPL+FJFt9kzl0ZSnDj7qLHBG7JdhEs1AAjzYo= +github.com/onflow/crypto v0.25.4 h1:R615PWPdSoA5RATNb/j3cYaloBIZlSXVNgS7BjwHiwM= +github.com/onflow/crypto v0.25.4/go.mod h1:DlkW/1SPUvLHYvUcjWa9PkLIRgSBKR4EDc3i+ATQKW4= github.com/onflow/fixed-point v0.1.1 h1:j0jYZVO8VGyk1476alGudEg7XqCkeTVxb5ElRJRKS90= github.com/onflow/fixed-point v0.1.1/go.mod h1:gJdoHqKtToKdOZbvryJvDZfcpzC7d2fyWuo3ZmLtcGY= -github.com/onflow/flow v0.4.15 h1:MdrhULSE5iSYNyLCihH8DI4uab5VciVZUKDFON6zylY= -github.com/onflow/flow v0.4.15/go.mod h1:lzyAYmbu1HfkZ9cfnL5/sjrrsnJiUU8fRL26CqLP7+c= -github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2 h1:mkd1NSv74+OnCHwrFqI2c5VETS1j06xf0ZuOto7gMio= -github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2/go.mod h1:jBDqVep0ICzhXky56YlyO4aiV2Jl/5r7wnqUPpvi7zE= -github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2 h1:semxeVLwC6xFG1G/7egUmaf7F1C8eBnc7NxNTVfBHTs= -github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2/go.mod h1:twSVyUt3rNrgzAmxtBX+1Gw64QlPemy17cyvnXYy1Ug= -github.com/onflow/flow-evm-bridge v0.1.0 h1:7X2osvo4NnQgHj8aERUmbYtv9FateX8liotoLnPL9nM= -github.com/onflow/flow-evm-bridge v0.1.0/go.mod h1:5UYwsnu6WcBNrwitGFxphCl5yq7fbWYGYuiCSTVF6pk= -github.com/onflow/flow-ft/lib/go/contracts v1.0.1 h1:Ts5ob+CoCY2EjEd0W6vdLJ7hLL3SsEftzXG2JlmSe24= -github.com/onflow/flow-ft/lib/go/contracts v1.0.1/go.mod h1:PwsL8fC81cjnUnTfmyL/HOIyHnyaw/JA474Wfj2tl6A= -github.com/onflow/flow-ft/lib/go/templates v1.0.1 h1:FDYKAiGowABtoMNusLuRCILIZDtVqJ/5tYI4VkF5zfM= -github.com/onflow/flow-ft/lib/go/templates v1.0.1/go.mod h1:uQ8XFqmMK2jxyBSVrmyuwdWjTEb+6zGjRYotfDJ5pAE= -github.com/onflow/flow-go-sdk v1.9.7 h1:eUDfXeIEghEe/cYCviGMnjD00kJm5SmIbtb+Q3xss6s= -github.com/onflow/flow-go-sdk v1.9.7/go.mod h1:027+x42RUqfraz9ojUKF0riHa/jm1bTdkjuTvYnZQ8c= -github.com/onflow/flow-nft/lib/go/contracts v1.3.0 h1:DmNop+O0EMyicZvhgdWboFG57xz5t9Qp81FKlfKyqJc= -github.com/onflow/flow-nft/lib/go/contracts v1.3.0/go.mod h1:eZ9VMMNfCq0ho6kV25xJn1kXeCfxnkhj3MwF3ed08gY= -github.com/onflow/flow-nft/lib/go/templates v1.3.0 h1:uGIBy4GEY6Z9hKP7sm5nA5kwvbvLWW4nWx5NN9Wg0II= -github.com/onflow/flow-nft/lib/go/templates v1.3.0/go.mod h1:gVbb5fElaOwKhV5UEUjM+JQTjlsguHg2jwRupfM/nng= -github.com/onflow/flow/protobuf/go/flow v0.4.18 h1:KOujA6lg9kTXCV6oK0eErD1rwRnM9taKZss3Szi+T3Q= -github.com/onflow/flow/protobuf/go/flow v0.4.18/go.mod h1:NA2pX2nw8zuaxfKphhKsk00kWLwfd+tv8mS23YXO4Sk= +github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b h1:Pr+Vxdr/J0V+1mOKfOvC3+Ik6I9ogJGXDYkW0FIYS/g= +github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b/go.mod h1:lzyAYmbu1HfkZ9cfnL5/sjrrsnJiUU8fRL26CqLP7+c= +github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 h1:OTJo6PzE8F0EtvBsBvXKVqSA8eCm1uzN+aWwV5gtjPs= +github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3/go.mod h1:fn0eOOINlOdQSOWptENC92MpPorB7dHzZaC3VTAmiQY= +github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 h1:MA0tiuQo69AhaMh8TgEMyJwuKKO3UK8PB8W+Fg1YVt4= +github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3/go.mod h1:bXe+VkZmvM3QYGjfizprStRfasLA/7ii7l6+LHP5V1U= +github.com/onflow/flow-evm-bridge v0.2.1 h1:S32kk+UV7/COdQZakIMsJw6vxShel0s8lI3FyGFl9jM= +github.com/onflow/flow-evm-bridge v0.2.1/go.mod h1:ExhTZax2F+boo13dzT/uAI7rvwewAoz9v+dEXhhFjYg= +github.com/onflow/flow-ft/lib/go/contracts v1.1.1 h1:BNbP3CrTIgScpx2NS9snq9XDESFjgXrMXTrwk5H4iSs= +github.com/onflow/flow-ft/lib/go/contracts v1.1.1/go.mod h1:PwsL8fC81cjnUnTfmyL/HOIyHnyaw/JA474Wfj2tl6A= +github.com/onflow/flow-ft/lib/go/templates v1.1.1 h1:X+EGTWKeVlsF33JD5QBFZLr8KW2apl6Oh1AXRWHmzLI= +github.com/onflow/flow-ft/lib/go/templates v1.1.1/go.mod h1:uQ8XFqmMK2jxyBSVrmyuwdWjTEb+6zGjRYotfDJ5pAE= +github.com/onflow/flow-go-sdk v1.10.3 h1:4zJYkdDNqeQqUJmdQJXlHIZuEjOLp8lsu8dRz5GZ/Cc= +github.com/onflow/flow-go-sdk v1.10.3/go.mod h1:cnpuCUvKLGqVrhz6yPEv0+LdsT9ib+cbn0YxfAJxHEI= +github.com/onflow/flow-nft/lib/go/contracts v1.4.1 h1:iQ8s4W5HNWd92MVRZbKxYpQ6UJn9snHLKQ9hFFNCiys= +github.com/onflow/flow-nft/lib/go/contracts v1.4.1/go.mod h1:XUsJjlbVoI0kebgv87xsO70U/ITGYbSEgTwbyg1RcOs= +github.com/onflow/flow-nft/lib/go/templates v1.4.1 h1:P+FN51waQrACpyVeXzLl1cnlD5J8bUYiemHXgeZBM+8= +github.com/onflow/flow-nft/lib/go/templates v1.4.1/go.mod h1:Z5kaMh/3SKSNx9tJj/nvc87iUap9b5L26UnU0Y4xy+0= +github.com/onflow/flow/protobuf/go/flow v0.4.20 h1:Ndq2l7Nu8p/RWNSRIRrpnBUpzfc5fYLEmHCFpJ9JGgo= +github.com/onflow/flow/protobuf/go/flow v0.4.20/go.mod h1:NA2pX2nw8zuaxfKphhKsk00kWLwfd+tv8mS23YXO4Sk= github.com/onflow/go-ds-pebble v0.0.0-20251003225212-131edca3a897 h1:ZtFYJ3OSR00aiKMMxgm3fRYWqYzjvDXeoBGQm6yC8DE= github.com/onflow/go-ds-pebble v0.0.0-20251003225212-131edca3a897/go.mod h1:aiCRVcj3K60sxc6k5C+HO9C6rouqiSkjR/WKnbTcMfQ= github.com/onflow/go-ethereum v1.13.4 h1:iNO86fm8RbBbhZ87ZulblInqCdHnAQVY8okBrNsTevc= github.com/onflow/go-ethereum v1.13.4/go.mod h1:cE/gEUkAffhwbVmMJYz+t1dAfVNHNwZCgc3BWtZxBGY= -github.com/onflow/nft-storefront/lib/go/contracts v1.0.0 h1:sxyWLqGm/p4EKT6DUlQESDG1ZNMN9GjPCm1gTq7NGfc= -github.com/onflow/nft-storefront/lib/go/contracts v1.0.0/go.mod h1:kMeq9zUwCrgrSojEbTUTTJpZ4WwacVm2pA7LVFr+glk= +github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066 h1:nQZ8wIvjPnxY8AAnyQDd+Pf9pJalbKjGZhMNtTnTUqc= +github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066/go.mod h1:kMeq9zUwCrgrSojEbTUTTJpZ4WwacVm2pA7LVFr+glk= github.com/onflow/sdks v0.6.0-preview.1 h1:mb/cUezuqWEP1gFZNAgUI4boBltudv4nlfxke1KBp9k= github.com/onflow/sdks v0.6.0-preview.1/go.mod h1:F0dj0EyHC55kknLkeD10js4mo14yTdMotnWMslPirrU= github.com/onflow/wal v1.0.2 h1:5bgsJVf2O3cfMNK12fiiTyYZ8cOrUiELt3heBJfHOhc= @@ -1339,33 +1341,33 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.38.0 h1:ZoYbqX7OaA/TAikspPl3ozPI6iY6LiIY9I8cUfm+pJs= -go.opentelemetry.io/contrib/detectors/gcp v1.38.0/go.mod h1:SU+iU7nu5ud4oCb3LQOhIZ3nRLj6FNVrKgtflbaf2ts= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= -go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 h1:K0XaT3DwHAcV4nKLzcQvwAgSyisUghWoY20I7huthMk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0/go.mod h1:B5Ki776z/MBnVha1Nzwp5arlzBbE3+1jk+pGmaP5HME= +go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48= +go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 h1:f0cb2XPmrqn4XMy9PNliTgRKJgS5WcL/u0/WRYGz4t0= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0/go.mod h1:vnakAaFckOMiMtOIhFI2MNH4FYrZzXCYxmb1LlhoGz8= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 h1:FFeLy03iVTXP6ffeN2iXrxfGsZGCjVx0/4KlizjyBwU= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0/go.mod h1:TMu73/k1CP8nBUpDLc71Wj/Kf7ZS9FK5b53VapRsP9o= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.21.0 h1:VhlEQAPp9R1ktYfrPk5SOryw1e9LDDTZCbIPFrho0ec= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.21.0/go.mod h1:kB3ufRbfU+CQ4MlUcqtW8Z7YEOBeK2DJ6CmR5rYYF3E= -go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= -go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= -go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= -go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= -go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= -go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= -go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0= +go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs= +go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18= +go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE= +go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8= +go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew= +go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI= +go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= -go.opentelemetry.io/proto/otlp v1.7.0 h1:jX1VolD6nHuFzOYso2E73H85i92Mv8JQYk0K9vz09os= -go.opentelemetry.io/proto/otlp v1.7.0/go.mod h1:fSKjH6YJ7HDlwzltzyMj036AJ3ejJLCgCSHGj4efDDo= +go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A= +go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= @@ -1395,6 +1397,8 @@ go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= @@ -1419,8 +1423,8 @@ golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0 golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1462,8 +1466,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= -golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1529,8 +1533,8 @@ golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -1552,8 +1556,8 @@ golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= -golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= -golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1568,8 +1572,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= -golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -1675,10 +1679,10 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54 h1:E2/AqCUMZGgd73TQkxUMcMla25GB9i/5HOdLr+uH7Vo= -golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc h1:bH6xUXay0AIFMElXG2rQ4uiE+7ncwtiOdPfYK1NK2XA= +golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -1686,8 +1690,8 @@ golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY= +golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1702,14 +1706,14 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -1774,8 +1778,8 @@ golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1826,8 +1830,8 @@ google.golang.org/api v0.71.0/go.mod h1:4PyU6e6JogV1f9eA4voyrTY2batOLdgZ5qZ5HOCc google.golang.org/api v0.74.0/go.mod h1:ZpfMZOVRMywNyvJFeqL9HRWBgAuRfSjJFpe9QtRRyDs= google.golang.org/api v0.75.0/go.mod h1:pU9QmyHLnzlpar1Mjt4IbapUCy8J+6HD6GeELN69ljA= google.golang.org/api v0.78.0/go.mod h1:1Sg78yoMLOhlQTeF+ARBoytAcH1NNyyl390YMy6rKmw= -google.golang.org/api v0.247.0 h1:tSd/e0QrUlLsrwMKmkbQhYVa109qIintOls2Wh6bngc= -google.golang.org/api v0.247.0/go.mod h1:r1qZOPmxXffXg6xS5uhx16Fa/UFY8QU/K4bfKrnvovM= +google.golang.org/api v0.267.0 h1:w+vfWPMPYeRs8qH1aYYsFX68jMls5acWl/jocfLomwE= +google.golang.org/api v0.267.0/go.mod h1:Jzc0+ZfLnyvXma3UtaTl023TdhZu6OMBP9tJ+0EmFD0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -1923,14 +1927,14 @@ google.golang.org/genproto v0.0.0-20220421151946-72621c1f0bd3/go.mod h1:8w6bsBMX google.golang.org/genproto v0.0.0-20220429170224-98d788798c3e/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= google.golang.org/genproto v0.0.0-20220505152158-f39f71e6c8f3/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= google.golang.org/genproto v0.0.0-20220518221133-4f43b3371335/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 h1:mepRgnBZa07I4TRuomDE4sTIYieg/osKmzIf4USdWS4= -google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8/go.mod h1:fDMmzKV90WSg1NbozdqrE64fkuTv6mlq2zxo9ad+3yo= -google.golang.org/genproto/googleapis/bytestream v0.0.0-20250804133106-a7a43d27e69b h1:YzmLjVBzUKrr0zPM1KkGPEicd3WHSccw1k9RivnvngU= -google.golang.org/genproto/googleapis/bytestream v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:h6yxum/C2qRb4txaZRLDHK8RyS0H/o2oEDeKY4onY/Y= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 h1:M1rk8KBnUsBDg1oPGHNCxG4vc1f49epmTO7xscSajMk= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM= +google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20 h1:7ei4lp52gK1uSejlA8AZl5AJjeLUOHBQscRQZUgAcu0= +google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20/go.mod h1:ZdbssH/1SOVnjnDlXzxDHK2MCidiqXtbYccJNzNYPEE= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260203192932-546029d2fa20 h1:zQTtWukWCqGTV6Pt60SqvPGnEi2CE3PeeIRlu4SYgAc= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260203192932-546029d2fa20/go.mod h1:Tej9lWiwVvQJP+b43pjJIsr/3mZycXWCIyoiXmbFf40= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 h1:Jr5R2J6F6qWyzINc+4AM8t5pfUz6beZpHp678GNrMbE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= @@ -1968,8 +1972,8 @@ google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9K google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= -google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= -google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig= +google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0 h1:TLkBREm4nIsEcexnCjgQd5GQWaHcqMzwQV0TX9pq8S0= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= @@ -1987,8 +1991,8 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/insecure/.mockery.yaml b/insecure/.mockery.yaml deleted file mode 100644 index e48e549f352..00000000000 --- a/insecure/.mockery.yaml +++ /dev/null @@ -1,16 +0,0 @@ -with-expecter: False -include-auto-generated: False -disable-func-mocks: True -dir: "{{.InterfaceDir}}/mock" -outpkg: "mock" -filename: "{{.InterfaceName | snakecase}}.go" -mockname: "{{.InterfaceName}}" -all: True - -# Suppress warnings -issue-845-fix: True -disable-version-string: True -resolve-type-alias: False - -packages: - github.com/onflow/flow-go/insecure: diff --git a/insecure/Makefile b/insecure/Makefile index 982676938f0..00f0d1be35b 100644 --- a/insecure/Makefile +++ b/insecure/Makefile @@ -22,7 +22,6 @@ test: .PHONY: lint lint: tidy - # revive -config revive.toml -exclude storage/ledger/trie ./... ../tools/custom-gcl run -v # this ensures there is no unused dependency being added by accident diff --git a/insecure/corruptlibp2p/fixtures.go b/insecure/corruptlibp2p/fixtures.go index e6cb9fac9a6..b480d82d3d3 100644 --- a/insecure/corruptlibp2p/fixtures.go +++ b/insecure/corruptlibp2p/fixtures.go @@ -1,7 +1,6 @@ package corruptlibp2p import ( - corrupt "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub" pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" "github.com/libp2p/go-libp2p/core/peer" @@ -9,16 +8,16 @@ import ( "github.com/onflow/flow-go/network/p2p" ) -// CorruptInspectorFunc wraps a normal RPC inspector with a corrupt inspector func by translating corrupt.RPC -> pubsubpb.RPC +// CorruptInspectorFunc wraps a normal RPC inspector with a corrupt inspector func by translating pubsub.RPC -> pubsubpb.RPC // before calling Inspect func. -func CorruptInspectorFunc(inspector p2p.GossipSubRPCInspector) func(id peer.ID, rpc *corrupt.RPC) error { - return func(id peer.ID, rpc *corrupt.RPC) error { +func CorruptInspectorFunc(inspector p2p.GossipSubRPCInspector) func(id peer.ID, rpc *pubsub.RPC) error { + return func(id peer.ID, rpc *pubsub.RPC) error { return inspector.Inspect(id, CorruptRPCToPubSubRPC(rpc)) } } -// CorruptRPCToPubSubRPC translates a corrupt.RPC -> pubsub.RPC -func CorruptRPCToPubSubRPC(rpc *corrupt.RPC) *pubsub.RPC { +// CorruptRPCToPubSubRPC translates a pubsub.RPC -> pubsub.RPC +func CorruptRPCToPubSubRPC(rpc *pubsub.RPC) *pubsub.RPC { return &pubsub.RPC{ RPC: pubsubpb.RPC{ Subscriptions: rpc.Subscriptions, diff --git a/insecure/corruptlibp2p/pubsub_adapter.go b/insecure/corruptlibp2p/pubsub_adapter.go index 0a191dcfb56..18496f6b85c 100644 --- a/insecure/corruptlibp2p/pubsub_adapter.go +++ b/insecure/corruptlibp2p/pubsub_adapter.go @@ -4,7 +4,6 @@ import ( "context" "fmt" - corrupt "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/peer" @@ -24,8 +23,8 @@ import ( // observability. type CorruptGossipSubAdapter struct { component.Component - gossipSub *corrupt.PubSub - router *corrupt.GossipSubRouter + gossipSub *pubsub.PubSub + router *pubsub.GossipSubRouter logger zerolog.Logger clusterChangeConsumer p2p.CollectionClusterChangesConsumer peerScoreExposer p2p.PeerScoreExposer @@ -34,10 +33,10 @@ type CorruptGossipSubAdapter struct { var _ p2p.PubSubAdapter = (*CorruptGossipSubAdapter)(nil) func (c *CorruptGossipSubAdapter) RegisterTopicValidator(topic string, topicValidator p2p.TopicValidatorFunc) error { - // instantiates a corrupt.ValidatorEx that wraps the topicValidatorFunc - var corruptValidator corrupt.ValidatorEx = func(ctx context.Context, from peer.ID, message *corrupt.Message) corrupt.ValidationResult { + // instantiates a pubsub.ValidatorEx that wraps the topicValidatorFunc + var corruptValidator pubsub.ValidatorEx = func(ctx context.Context, from peer.ID, message *pubsub.Message) pubsub.ValidationResult { pubsubMsg := &pubsub.Message{ - Message: message.Message, // converting corrupt.Message to pubsub.Message + Message: message.Message, // converting pubsub.Message to pubsub.Message ID: message.ID, ReceivedFrom: message.ReceivedFrom, ValidatorData: message.ValidatorData, @@ -45,16 +44,16 @@ func (c *CorruptGossipSubAdapter) RegisterTopicValidator(topic string, topicVali } result := topicValidator(ctx, from, pubsubMsg) - // overriding the corrupt.ValidationResult with the result from pubsub.TopicValidatorFunc + // overriding the pubsub.ValidationResult with the result from pubsub.TopicValidatorFunc message.ValidatorData = pubsubMsg.ValidatorData switch result { case p2p.ValidationAccept: - return corrupt.ValidationAccept + return pubsub.ValidationAccept case p2p.ValidationIgnore: - return corrupt.ValidationIgnore + return pubsub.ValidationIgnore case p2p.ValidationReject: - return corrupt.ValidationReject + return pubsub.ValidationReject default: // should never happen, indicates a bug in the topic validator c.logger.Fatal(). @@ -73,9 +72,9 @@ func (c *CorruptGossipSubAdapter) RegisterTopicValidator(topic string, topicVali Str("result", fmt.Sprintf("%v", result)). Str("message_type", fmt.Sprintf("%T", message.Data)). Msg("invalid validation result, returning reject") - return corrupt.ValidationReject + return pubsub.ValidationReject } - err := c.gossipSub.RegisterTopicValidator(topic, corruptValidator, corrupt.WithValidatorInline(true)) + err := c.gossipSub.RegisterTopicValidator(topic, corruptValidator, pubsub.WithValidatorInline(true)) if err != nil { return fmt.Errorf("could not register topic validator on corrupt gossipsub: %w", err) } @@ -130,17 +129,17 @@ func NewCorruptGossipSubAdapter(ctx context.Context, logger zerolog.Logger, h host.Host, cfg p2p.PubSubAdapterConfig, - clusterChangeConsumer p2p.CollectionClusterChangesConsumer) (p2p.PubSubAdapter, *corrupt.GossipSubRouter, error) { + clusterChangeConsumer p2p.CollectionClusterChangesConsumer) (p2p.PubSubAdapter, *pubsub.GossipSubRouter, error) { gossipSubConfig, ok := cfg.(*CorruptPubSubAdapterConfig) if !ok { return nil, nil, fmt.Errorf("invalid gossipsub config type: %T", cfg) } // initializes a default gossipsub router and wraps it with the corrupt router. - router := corrupt.DefaultGossipSubRouter(h) + router := pubsub.DefaultGossipSubRouter(h) // injects the corrupt router into the gossipsub constructor - gossipSub, err := corrupt.NewGossipSubWithRouter(ctx, h, router, gossipSubConfig.Build()...) + gossipSub, err := pubsub.NewGossipSubWithRouter(ctx, h, router, gossipSubConfig.Build()...) if err != nil { return nil, nil, fmt.Errorf("failed to create corrupt gossipsub: %w", err) } diff --git a/insecure/go.mod b/insecure/go.mod index 3618b3f4c2c..0e11b80dd28 100644 --- a/insecure/go.mod +++ b/insecure/go.mod @@ -1,6 +1,6 @@ module github.com/onflow/flow-go/insecure -go 1.25.0 +go 1.25.1 require ( github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 @@ -10,50 +10,51 @@ require ( github.com/libp2p/go-libp2p v0.38.2 github.com/libp2p/go-libp2p-pubsub v0.13.0 github.com/multiformats/go-multiaddr-dns v0.4.1 - github.com/onflow/crypto v0.25.3 + github.com/onflow/crypto v0.25.4 github.com/onflow/flow-go v0.36.2-0.20240717162253-d5d2e606ef53 github.com/rs/zerolog v1.29.0 github.com/spf13/pflag v1.0.6 github.com/stretchr/testify v1.11.1 go.uber.org/atomic v1.11.0 - google.golang.org/grpc v1.77.0 - google.golang.org/protobuf v1.36.10 + google.golang.org/grpc v1.79.3 + google.golang.org/protobuf v1.36.11 ) require ( - cel.dev/expr v0.24.0 // indirect - cloud.google.com/go v0.120.0 // indirect - cloud.google.com/go/auth v0.16.4 // indirect + cel.dev/expr v0.25.1 // indirect + cloud.google.com/go v0.123.0 // indirect + cloud.google.com/go/auth v0.18.1 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect - cloud.google.com/go/iam v1.5.2 // indirect - cloud.google.com/go/monitoring v1.24.2 // indirect - cloud.google.com/go/storage v1.50.0 // indirect + cloud.google.com/go/iam v1.5.3 // indirect + cloud.google.com/go/monitoring v1.24.3 // indirect + cloud.google.com/go/storage v1.56.0 // indirect github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect github.com/Jorropo/jsync v1.0.1 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20251001021608-1fe7b43fc4d6 // indirect github.com/SaveTheRbtz/mph v0.1.1-0.20240117162131-4166ec7869bc // indirect github.com/StackExchange/wmi v1.2.1 // indirect github.com/VictoriaMetrics/fastcache v1.13.0 // indirect - github.com/aws/aws-sdk-go-v2 v1.40.1 // indirect - github.com/aws/aws-sdk-go-v2/config v1.31.20 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.18.24 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 // indirect + github.com/aws/aws-sdk-go-v2 v1.41.1 // indirect + github.com/aws/aws-sdk-go-v2/config v1.32.7 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.19.7 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0 // indirect github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.40.2 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect github.com/aws/smithy-go v1.24.0 // indirect github.com/benbjohnson/clock v1.3.5 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -62,7 +63,7 @@ require ( github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f // indirect + github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 // indirect github.com/cockroachdb/errors v1.11.3 // indirect github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect @@ -71,7 +72,7 @@ require ( github.com/cockroachdb/redact v1.1.5 // indirect github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect - github.com/consensys/gnark-crypto v0.18.0 // indirect + github.com/consensys/gnark-crypto v0.18.1 // indirect github.com/containerd/cgroups v1.1.0 // indirect github.com/coreos/go-semver v0.3.0 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect @@ -91,11 +92,11 @@ require ( github.com/ef-ds/deque v1.0.4 // indirect github.com/elastic/gosigar v0.14.3 // indirect github.com/emicklei/dot v1.6.2 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.35.0 // indirect - github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect github.com/ethereum/c-kzg-4844/v2 v2.1.5 // indirect github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab // indirect - github.com/ethereum/go-ethereum v1.16.7 // indirect + github.com/ethereum/go-ethereum v1.16.8 // indirect github.com/ethereum/go-verkle v0.2.2 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/ferranbt/fastssz v0.1.4 // indirect @@ -103,7 +104,7 @@ require ( github.com/flynn/noise v1.1.0 // indirect github.com/francoispqt/gojay v1.2.13 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013 // indirect + github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e // indirect github.com/fxamacker/circlehash v0.3.0 // indirect github.com/fxamacker/golang-lru/v2 v2.0.0-20250716153046-22c8d17dc4ee // indirect github.com/gabriel-vasile/mimetype v1.4.6 // indirect @@ -130,13 +131,13 @@ require ( github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect - github.com/googleapis/gax-go/v2 v2.15.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect + github.com/googleapis/gax-go/v2 v2.17.0 // indirect github.com/gorilla/mux v1.8.1 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect @@ -166,7 +167,7 @@ require ( github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect github.com/jbenet/goprocess v0.1.4 // indirect - github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956 // indirect + github.com/jordanschalm/lockctx v0.1.0 // indirect github.com/k0kubun/pp/v3 v3.5.0 // indirect github.com/kevinburke/go-bindata v3.24.0+incompatible // indirect github.com/klauspost/compress v1.17.11 // indirect @@ -214,20 +215,20 @@ require ( github.com/multiformats/go-varint v0.0.7 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/onflow/atree v0.12.0 // indirect - github.com/onflow/cadence v1.9.2 // indirect + github.com/onflow/atree v0.16.1 // indirect + github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382 // indirect github.com/onflow/fixed-point v0.1.1 // indirect - github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2 // indirect - github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2 // indirect - github.com/onflow/flow-evm-bridge v0.1.0 // indirect - github.com/onflow/flow-ft/lib/go/contracts v1.0.1 // indirect - github.com/onflow/flow-ft/lib/go/templates v1.0.1 // indirect - github.com/onflow/flow-go-sdk v1.9.7 // indirect - github.com/onflow/flow-nft/lib/go/contracts v1.3.0 // indirect - github.com/onflow/flow-nft/lib/go/templates v1.3.0 // indirect - github.com/onflow/flow/protobuf/go/flow v0.4.18 // indirect + github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 // indirect + github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 // indirect + github.com/onflow/flow-evm-bridge v0.2.1 // indirect + github.com/onflow/flow-ft/lib/go/contracts v1.1.1 // indirect + github.com/onflow/flow-ft/lib/go/templates v1.1.1 // indirect + github.com/onflow/flow-go-sdk v1.10.3 // indirect + github.com/onflow/flow-nft/lib/go/contracts v1.4.1 // indirect + github.com/onflow/flow-nft/lib/go/templates v1.4.1 // indirect + github.com/onflow/flow/protobuf/go/flow v0.4.20 // indirect github.com/onflow/go-ethereum v1.16.2 // indirect - github.com/onflow/nft-storefront/lib/go/contracts v1.0.0 // indirect + github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066 // indirect github.com/onflow/sdks v0.6.0-preview.1 // indirect github.com/onflow/wal v1.0.2 // indirect github.com/onsi/ginkgo/v2 v2.22.0 // indirect @@ -301,41 +302,42 @@ require ( github.com/zeebo/blake3 v0.2.4 // indirect go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.38.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect - go.opentelemetry.io/otel v1.38.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 // indirect + go.opentelemetry.io/otel v1.39.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 // indirect - go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/sdk v1.38.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect - go.opentelemetry.io/otel/trace v1.38.0 // indirect - go.opentelemetry.io/proto/otlp v1.7.0 // indirect + go.opentelemetry.io/otel/metric v1.39.0 // indirect + go.opentelemetry.io/otel/sdk v1.39.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.39.0 // indirect + go.opentelemetry.io/otel/trace v1.39.0 // indirect + go.opentelemetry.io/proto/otlp v1.9.0 // indirect go.uber.org/dig v1.18.0 // indirect go.uber.org/fx v1.23.0 // indirect go.uber.org/mock v0.5.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/crypto v0.45.0 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/crypto v0.47.0 // indirect golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 // indirect - golang.org/x/mod v0.30.0 // indirect - golang.org/x/net v0.47.0 // indirect - golang.org/x/oauth2 v0.32.0 // indirect - golang.org/x/sync v0.18.0 // indirect - golang.org/x/sys v0.38.0 // indirect - golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54 // indirect - golang.org/x/term v0.37.0 // indirect - golang.org/x/text v0.31.0 // indirect - golang.org/x/time v0.12.0 // indirect - golang.org/x/tools v0.39.0 // indirect + golang.org/x/mod v0.31.0 // indirect + golang.org/x/net v0.49.0 // indirect + golang.org/x/oauth2 v0.35.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.40.0 // indirect + golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc // indirect + golang.org/x/term v0.39.0 // indirect + golang.org/x/text v0.33.0 // indirect + golang.org/x/time v0.14.0 // indirect + golang.org/x/tools v0.40.0 // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect gonum.org/v1/gonum v0.16.0 // indirect - google.golang.org/api v0.247.0 // indirect + google.golang.org/api v0.267.0 // indirect google.golang.org/appengine v1.6.8 // indirect - google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 // indirect + google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/insecure/go.sum b/insecure/go.sum index 53b1f81cc7f..c9f12feebf2 100644 --- a/insecure/go.sum +++ b/insecure/go.sum @@ -1,5 +1,5 @@ -cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= -cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= +cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= @@ -21,10 +21,10 @@ cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHOb cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= -cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= -cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= -cloud.google.com/go/auth v0.16.4 h1:fXOAIQmkApVvcIn7Pc2+5J8QTMVbUGLscnSVNl11su8= -cloud.google.com/go/auth v0.16.4/go.mod h1:j10ncYwjX/g3cdX7GpEzsdM+d+ZNsXAbb6qXA7p1Y5M= +cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= +cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= +cloud.google.com/go/auth v0.18.1 h1:IwTEx92GFUo2pJ6Qea0EU3zYvKnTAeRCODxfA/G5UWs= +cloud.google.com/go/auth v0.18.1/go.mod h1:GfTYoS9G3CWpRA3Va9doKN9mjPGRS+v41jmZAhBzbrA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= @@ -37,14 +37,14 @@ cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdB cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= -cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= -cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= -cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= -cloud.google.com/go/longrunning v0.6.7 h1:IGtfDWHhQCgCjwQjV9iiLnUta9LBCo8R9QmAFsS/PrE= -cloud.google.com/go/longrunning v0.6.7/go.mod h1:EAFV3IZAKmM56TyiE6VAP3VoTzhZzySwI/YI1s/nRsY= -cloud.google.com/go/monitoring v1.24.2 h1:5OTsoJ1dXYIiMiuL+sYscLc9BumrL3CarVLL7dd7lHM= -cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= +cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= +cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= +cloud.google.com/go/logging v1.13.1 h1:O7LvmO0kGLaHY/gq8cV7T0dyp6zJhYAOtZPX4TF3QtY= +cloud.google.com/go/logging v1.13.1/go.mod h1:XAQkfkMBxQRjQek96WLPNze7vsOmay9H5PqfsNYDqvw= +cloud.google.com/go/longrunning v0.8.0 h1:LiKK77J3bx5gDLi4SMViHixjD2ohlkwBi+mKA7EhfW8= +cloud.google.com/go/longrunning v0.8.0/go.mod h1:UmErU2Onzi+fKDg2gR7dusz11Pe26aknR4kHmJJqIfk= +cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE= +cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= cloud.google.com/go/profiler v0.3.0 h1:R6y/xAeifaUXxd2x6w+jIwKxoKl8Cv5HJvcvASTPWJo= cloud.google.com/go/profiler v0.3.0/go.mod h1:9wYk9eY4iZHsev8TQb61kh3wiOiSyz/xOYixWPzweCU= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= @@ -57,10 +57,10 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= -cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= -cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= -cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4= -cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= +cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI= +cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU= +cloud.google.com/go/trace v1.11.7 h1:kDNDX8JkaAG3R2nq1lIdkb7FCSi1rCmsEtKVsty7p+U= +cloud.google.com/go/trace v1.11.7/go.mod h1:TNn9d5V3fQVf6s4SCveVMIBS2LJUqo73GACmq/Tky0s= dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= @@ -73,12 +73,12 @@ github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e h1:ZIWapoIRN1VqT8GR github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0/go.mod h1:ZV4VOm0/eHR06JLrXWe09068dHpr3TRpY9Uo7T+anuA= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0 h1:nNMpRpnkWDAaqcpxMJvxa/Ud98gjbYwayJY4/9bdjiU= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0/go.mod h1:SZiPHWGOOk3bl8tkevxkoiwPgsIl6CwrWcbwjfHZpdM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 h1:ig/FpDD2JofP/NExKQUbn7uOSZzJAQqogfqluZK4ed4= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 h1:owcC2UnmsZycprQ5RfRgjydWhuoxg71LUfyiQdijZuM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0 h1:4LP6hvB4I5ouTbGgWtixJhgED6xdf67twf9PoY96Tbg= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0/go.mod h1:jUZ5LYlw40WMd07qxcQJD5M40aUxrfwqQX1g7zxYnrQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= github.com/Jorropo/jsync v1.0.1 h1:6HgRolFZnsdfzRUj+ImB9og1JYOxQoReSywkHOGSaUU= github.com/Jorropo/jsync v1.0.1/go.mod h1:jCOZj3vrBCri3bSU3ErUYvevKlnbssrXeCivybS5ABQ= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= @@ -120,44 +120,46 @@ github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQ github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= -github.com/aws/aws-sdk-go-v2 v1.40.1 h1:difXb4maDZkRH0x//Qkwcfpdg1XQVXEAEs2DdXldFFc= -github.com/aws/aws-sdk-go-v2 v1.40.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= +github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= +github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= github.com/aws/aws-sdk-go-v2/config v1.8.0/go.mod h1:w9+nMZ7soXCe5nT46Ri354SNhXDQ6v+V5wqDjnZE+GY= -github.com/aws/aws-sdk-go-v2/config v1.31.20 h1:/jWF4Wu90EhKCgjTdy1DGxcbcbNrjfBHvksEL79tfQc= -github.com/aws/aws-sdk-go-v2/config v1.31.20/go.mod h1:95Hh1Tc5VYKL9NJ7tAkDcqeKt+MCXQB1hQZaRdJIZE0= +github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY= +github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY= github.com/aws/aws-sdk-go-v2/credentials v1.4.0/go.mod h1:dgGR+Qq7Wjcd4AOAW5Rf5Tnv3+x7ed6kETXyS9WCuAY= -github.com/aws/aws-sdk-go-v2/credentials v1.18.24 h1:iJ2FmPT35EaIB0+kMa6TnQ+PwG5A1prEdAw+PsMzfHg= -github.com/aws/aws-sdk-go-v2/credentials v1.18.24/go.mod h1:U91+DrfjAiXPDEGYhh/x29o4p0qHX5HDqG7y5VViv64= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0/go.mod h1:CpNzHK9VEFUCknu50kkB8z58AH2B5DvPP7ea1LHve/Y= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 h1:T1brd5dR3/fzNFAQch/iBKeX07/ffu/cLu+q+RuzEWk= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13/go.mod h1:Peg/GBAQ6JDt+RoBf4meB1wylmAipb7Kg2ZFakZTlwk= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1 h1:VGkV9KmhGqOQWnHyi4gLG98kE6OecT42fdrCGFWxJsc= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1/go.mod h1:PLlnMiki//sGnCJiW+aVpvP/C8Kcm8mEj/IVm9+9qk4= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14 h1:PZHqQACxYb8mYgms4RZbhZG0a7dPW06xOjmaH0EJC/I= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14/go.mod h1:VymhrMJUWs69D8u0/lZ7jSB6WgaG/NqHi3gX0aYf6U0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14 h1:bOS19y6zlJwagBfHxs0ESzr1XCOU2KXJCWcq3E2vfjY= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14/go.mod h1:1ipeGBMAxZ0xcTm6y6paC2C/J6f6OO7LBODV9afuAyM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2/go.mod h1:BQV0agm+JEhqR+2RT5e1XTFIDcAAV0eW6z2trp+iduw= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0/go.mod h1:v8ygadNyATSm6elwJ/4gzJwcFhri9RqS8skgHKiwXPU= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 h1:x2Ibm/Af8Fi+BH+Hsn9TXGdT+hKbDd5XOTZxTMxDk7o= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3/go.mod h1:IW1jwyrQgMdhisceG8fQLmQIydcT/jWY21rFhzgaKwo= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0/go.mod h1:R1KK+vY8AfalhG1AOu5e35pOD2SdoPKQCFLTvnxiohk= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 h1:kDqdFvMY4AtKoACfzIGD8A0+hbT41KTKF//gq7jITfM= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13/go.mod h1:lmKuogqSU3HzQCwZ9ZtcqOc5XGMqtDK7OIc2+DxiUEg= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0 h1:HWsM0YQWX76V6MOp07YuTYacm8k7h69ObJuw7Nck+og= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0/go.mod h1:LKb3cKNQIMh+itGnEpKGcnL/6OIjPZqrtYah1w5f+3o= github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0 h1:nPLfLPfglacc29Y949sDxpr3X/blaY40s3B85WT2yZU= github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0/go.mod h1:Iv2aJVtVSm/D22rFoX99cLG4q4uB7tppuCsulGe98k4= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M= github.com/aws/aws-sdk-go-v2/service/sso v1.4.0/go.mod h1:+1fpWnL96DL23aXPpMGbsmKe8jLTEfbjuQoA4WS1VaA= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 h1:NjShtS1t8r5LUfFVtFeI8xLAHQNTa7UI0VawXlrBMFQ= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.3/go.mod h1:fKvyjJcz63iL/ftA6RaM8sRCtN4r4zl4tjL3qw5ec7k= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 h1:gTsnx0xXNQ6SBbymoDvcoRHL+q4l/dAFsQuKfDWSaGc= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7/go.mod h1:klO+ejMvYsB4QATfEOIXk8WAEwN4N0aBfJpvC+5SZBo= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo= github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= -github.com/aws/aws-sdk-go-v2/service/sts v1.40.2 h1:HK5ON3KmQV2HcAunnx4sKLB9aPf3gKGwVAf7xnx0QT0= -github.com/aws/aws-sdk-go-v2/service/sts v1.40.2/go.mod h1:E19xDjpzPZC7LS2knI9E6BaRFDK43Eul7vd6rSq2HWk= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= @@ -208,8 +210,8 @@ github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQ github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f h1:Y8xYupdHxryycyPlc9Y+bSQAYZnetRJ70VMVKm5CKI0= -github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f/go.mod h1:HlzOvOjVBOfTGSRXRyY0OiCS/3J1akRGQQpRO/7zyF4= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 h1:bvJv505UUfjzbaIPdNS4AEkHreDqQk6yuNpsdRHpwFA= github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94/go.mod h1:Gq51ZeKaFCXk6QwuGM0w1dnaOqc/F5zKT2zA9D6Xeac= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= @@ -234,8 +236,8 @@ github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961/go.mod h1:yBRu/c github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= -github.com/consensys/gnark-crypto v0.18.0 h1:vIye/FqI50VeAr0B3dx+YjeIvmc3LWz4yEfbWBpTUf0= -github.com/consensys/gnark-crypto v0.18.0/go.mod h1:L3mXGFTe1ZN+RSJ+CLjUt9x7PNdx8ubaYfDROyp2Z8c= +github.com/consensys/gnark-crypto v0.18.1 h1:RyLV6UhPRoYYzaFnPQA4qK3DyuDgkTgskDdoGqFt3fI= +github.com/consensys/gnark-crypto v0.18.1/go.mod h1:L3mXGFTe1ZN+RSJ+CLjUt9x7PNdx8ubaYfDROyp2Z8c= github.com/containerd/cgroups v0.0.0-20201119153540-4cbc285b3327/go.mod h1:ZJeTFisyysqgcCdecO57Dj79RfL0LNeGiFUqLYQRYLE= github.com/containerd/cgroups v1.1.0 h1:v8rEWFl6EoqHB+swVNjVoCJE8o3jX7e8nqBGPLaDFBM= github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw= @@ -313,21 +315,21 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329 h1:K+fnvUM0VZ7ZFJf0n4L/BRlnsb9pL/GuDG6FqaH+PwM= -github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329/go.mod h1:Alz8LEClvR7xKsrq3qzoc4N0guvVNSS8KmSChGYr9hs= -github.com/envoyproxy/go-control-plane/envoy v1.35.0 h1:ixjkELDE+ru6idPxcHLj8LBVc2bFP7iBytj353BoHUo= -github.com/envoyproxy/go-control-plane/envoy v1.35.0/go.mod h1:09qwbGVuSWWAyN5t/b3iyVfz5+z8QWGrzkoqm/8SbEs= +github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= +github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= +github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g= +github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= -github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4= +github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= github.com/ethereum/c-kzg-4844/v2 v2.1.5 h1:aVtoLK5xwJ6c5RiqO8g8ptJ5KU+2Hdquf6G3aXiHh5s= github.com/ethereum/c-kzg-4844/v2 v2.1.5/go.mod h1:u59hRTTah4Co6i9fDWtiCjTrblJv0UwsqZKCc0GfgUs= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab h1:rvv6MJhy07IMfEKuARQ9TKojGqLVNxQajaXEp/BoqSk= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab/go.mod h1:IuLm4IsPipXKF7CW5Lzf68PIbZ5yl7FFd74l/E0o9A8= -github.com/ethereum/go-ethereum v1.16.7 h1:qeM4TvbrWK0UC0tgkZ7NiRsmBGwsjqc64BHo20U59UQ= -github.com/ethereum/go-ethereum v1.16.7/go.mod h1:Fs6QebQbavneQTYcA39PEKv2+zIjX7rPUZ14DER46wk= +github.com/ethereum/go-ethereum v1.16.8 h1:LLLfkZWijhR5m6yrAXbdlTeXoqontH+Ga2f9igY7law= +github.com/ethereum/go-ethereum v1.16.8/go.mod h1:Fs6QebQbavneQTYcA39PEKv2+zIjX7rPUZ14DER46wk= github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cnFk8= github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -350,8 +352,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013 h1:jcwW+JBYGe3qgiPQ4deXaannYxVdxjMw57/dw+gcEfQ= -github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e h1:AqsamU9dS+/RNjgvDOqFUT7qXApcmnw7zJLLqJkx860= +github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/fxamacker/circlehash v0.3.0 h1:XKdvTtIJV9t7DDUtsf0RIpC1OcxZtPbmgIH7ekx28WA= github.com/fxamacker/circlehash v0.3.0/go.mod h1:3aq3OfVvsWtkWMb6A1owjOQFA+TLsD5FgJflnaQwtMM= github.com/fxamacker/golang-lru/v2 v2.0.0-20250430153159-6f72f038a30f h1:/gqGg2NQVvwiLXs7ppw2uneC5AAd2Z9OTp0zgu42zNI= @@ -538,14 +540,14 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= -github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= -github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= +github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc= +github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gopherjs/gopherjs v0.0.0-20190430165422-3e4dfb77656c h1:7lF+Vz0LqiRidnzC1Oq86fpX1q/iEv2KJdrCtttYjT4= @@ -571,8 +573,8 @@ github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgf github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4= github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -672,8 +674,8 @@ github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956 h1:4iii8SOozVG1lpkdPELRsjPEBhU4DeFPz2r2Fjj3UDU= -github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956/go.mod h1:qsnXMryYP9X7JbzskIn0+N40sE6XNXLr9kYRRP6rwXU= +github.com/jordanschalm/lockctx v0.1.0 h1:2ZziSl5zejl5VSRUjl+UtYV94QPFQgO9bekqWPOKUQw= +github.com/jordanschalm/lockctx v0.1.0/go.mod h1:qsnXMryYP9X7JbzskIn0+N40sE6XNXLr9kYRRP6rwXU= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -886,40 +888,40 @@ github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onflow/atree v0.12.0 h1:X7/UEPyCaaEQ1gCg11KDvfyEtEeQLhtRtxMHjAiH/Co= -github.com/onflow/atree v0.12.0/go.mod h1:qdZcfLQwPirHcNpLiK+2t3KAo+SAb9Si6TqurE6pykE= +github.com/onflow/atree v0.16.1 h1:EmlaIz/GwQ39o5agAb2KT2ynt4SHRBkgMMWU5bp6iTs= +github.com/onflow/atree v0.16.1/go.mod h1:hiOT/vKK/Zyw34Ru9OFbfEemC5NnQ7SHFB43bN9/4qI= github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483 h1:LpiQhTAfM9CAmNVEs0n//cBBgCg+vJSiIxTHYUklZ84= github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483/go.mod h1:pIZgTWdm3k3pLF9Uq6MB8JEcW07UDwNJjlXW1HELW80= -github.com/onflow/cadence v1.9.2 h1:r1hKhbrFJgrLCHj8N0Bp8/gfG9Vc5WTYOtDjdcWqEk4= -github.com/onflow/cadence v1.9.2/go.mod h1:MlJsCwhCZwdnAUd24XHzcsizZfG7a2leab1PztabUsE= -github.com/onflow/crypto v0.25.3 h1:XQ3HtLsw8h1+pBN+NQ1JYM9mS2mVXTyg55OldaAIF7U= -github.com/onflow/crypto v0.25.3/go.mod h1:+1igaXiK6Tjm9wQOBD1EGwW7bYWMUGKtwKJ/2QL/OWs= +github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382 h1:3lnbPpMxrNsZLN6uUwZy5zbIc2PlaOefjlOKm2PunYk= +github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382/go.mod h1:hoz+FnPPL+FJFt9kzl0ZSnDj7qLHBG7JdhEs1AAjzYo= +github.com/onflow/crypto v0.25.4 h1:R615PWPdSoA5RATNb/j3cYaloBIZlSXVNgS7BjwHiwM= +github.com/onflow/crypto v0.25.4/go.mod h1:DlkW/1SPUvLHYvUcjWa9PkLIRgSBKR4EDc3i+ATQKW4= github.com/onflow/fixed-point v0.1.1 h1:j0jYZVO8VGyk1476alGudEg7XqCkeTVxb5ElRJRKS90= github.com/onflow/fixed-point v0.1.1/go.mod h1:gJdoHqKtToKdOZbvryJvDZfcpzC7d2fyWuo3ZmLtcGY= -github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2 h1:mkd1NSv74+OnCHwrFqI2c5VETS1j06xf0ZuOto7gMio= -github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2/go.mod h1:jBDqVep0ICzhXky56YlyO4aiV2Jl/5r7wnqUPpvi7zE= -github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2 h1:semxeVLwC6xFG1G/7egUmaf7F1C8eBnc7NxNTVfBHTs= -github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2/go.mod h1:twSVyUt3rNrgzAmxtBX+1Gw64QlPemy17cyvnXYy1Ug= -github.com/onflow/flow-evm-bridge v0.1.0 h1:7X2osvo4NnQgHj8aERUmbYtv9FateX8liotoLnPL9nM= -github.com/onflow/flow-evm-bridge v0.1.0/go.mod h1:5UYwsnu6WcBNrwitGFxphCl5yq7fbWYGYuiCSTVF6pk= -github.com/onflow/flow-ft/lib/go/contracts v1.0.1 h1:Ts5ob+CoCY2EjEd0W6vdLJ7hLL3SsEftzXG2JlmSe24= -github.com/onflow/flow-ft/lib/go/contracts v1.0.1/go.mod h1:PwsL8fC81cjnUnTfmyL/HOIyHnyaw/JA474Wfj2tl6A= -github.com/onflow/flow-ft/lib/go/templates v1.0.1 h1:FDYKAiGowABtoMNusLuRCILIZDtVqJ/5tYI4VkF5zfM= -github.com/onflow/flow-ft/lib/go/templates v1.0.1/go.mod h1:uQ8XFqmMK2jxyBSVrmyuwdWjTEb+6zGjRYotfDJ5pAE= -github.com/onflow/flow-go-sdk v1.9.7 h1:eUDfXeIEghEe/cYCviGMnjD00kJm5SmIbtb+Q3xss6s= -github.com/onflow/flow-go-sdk v1.9.7/go.mod h1:027+x42RUqfraz9ojUKF0riHa/jm1bTdkjuTvYnZQ8c= -github.com/onflow/flow-nft/lib/go/contracts v1.3.0 h1:DmNop+O0EMyicZvhgdWboFG57xz5t9Qp81FKlfKyqJc= -github.com/onflow/flow-nft/lib/go/contracts v1.3.0/go.mod h1:eZ9VMMNfCq0ho6kV25xJn1kXeCfxnkhj3MwF3ed08gY= -github.com/onflow/flow-nft/lib/go/templates v1.3.0 h1:uGIBy4GEY6Z9hKP7sm5nA5kwvbvLWW4nWx5NN9Wg0II= -github.com/onflow/flow-nft/lib/go/templates v1.3.0/go.mod h1:gVbb5fElaOwKhV5UEUjM+JQTjlsguHg2jwRupfM/nng= -github.com/onflow/flow/protobuf/go/flow v0.4.18 h1:KOujA6lg9kTXCV6oK0eErD1rwRnM9taKZss3Szi+T3Q= -github.com/onflow/flow/protobuf/go/flow v0.4.18/go.mod h1:NA2pX2nw8zuaxfKphhKsk00kWLwfd+tv8mS23YXO4Sk= +github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 h1:OTJo6PzE8F0EtvBsBvXKVqSA8eCm1uzN+aWwV5gtjPs= +github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3/go.mod h1:fn0eOOINlOdQSOWptENC92MpPorB7dHzZaC3VTAmiQY= +github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 h1:MA0tiuQo69AhaMh8TgEMyJwuKKO3UK8PB8W+Fg1YVt4= +github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3/go.mod h1:bXe+VkZmvM3QYGjfizprStRfasLA/7ii7l6+LHP5V1U= +github.com/onflow/flow-evm-bridge v0.2.1 h1:S32kk+UV7/COdQZakIMsJw6vxShel0s8lI3FyGFl9jM= +github.com/onflow/flow-evm-bridge v0.2.1/go.mod h1:ExhTZax2F+boo13dzT/uAI7rvwewAoz9v+dEXhhFjYg= +github.com/onflow/flow-ft/lib/go/contracts v1.1.1 h1:BNbP3CrTIgScpx2NS9snq9XDESFjgXrMXTrwk5H4iSs= +github.com/onflow/flow-ft/lib/go/contracts v1.1.1/go.mod h1:PwsL8fC81cjnUnTfmyL/HOIyHnyaw/JA474Wfj2tl6A= +github.com/onflow/flow-ft/lib/go/templates v1.1.1 h1:X+EGTWKeVlsF33JD5QBFZLr8KW2apl6Oh1AXRWHmzLI= +github.com/onflow/flow-ft/lib/go/templates v1.1.1/go.mod h1:uQ8XFqmMK2jxyBSVrmyuwdWjTEb+6zGjRYotfDJ5pAE= +github.com/onflow/flow-go-sdk v1.10.3 h1:4zJYkdDNqeQqUJmdQJXlHIZuEjOLp8lsu8dRz5GZ/Cc= +github.com/onflow/flow-go-sdk v1.10.3/go.mod h1:cnpuCUvKLGqVrhz6yPEv0+LdsT9ib+cbn0YxfAJxHEI= +github.com/onflow/flow-nft/lib/go/contracts v1.4.1 h1:iQ8s4W5HNWd92MVRZbKxYpQ6UJn9snHLKQ9hFFNCiys= +github.com/onflow/flow-nft/lib/go/contracts v1.4.1/go.mod h1:XUsJjlbVoI0kebgv87xsO70U/ITGYbSEgTwbyg1RcOs= +github.com/onflow/flow-nft/lib/go/templates v1.4.1 h1:P+FN51waQrACpyVeXzLl1cnlD5J8bUYiemHXgeZBM+8= +github.com/onflow/flow-nft/lib/go/templates v1.4.1/go.mod h1:Z5kaMh/3SKSNx9tJj/nvc87iUap9b5L26UnU0Y4xy+0= +github.com/onflow/flow/protobuf/go/flow v0.4.20 h1:Ndq2l7Nu8p/RWNSRIRrpnBUpzfc5fYLEmHCFpJ9JGgo= +github.com/onflow/flow/protobuf/go/flow v0.4.20/go.mod h1:NA2pX2nw8zuaxfKphhKsk00kWLwfd+tv8mS23YXO4Sk= github.com/onflow/go-ds-pebble v0.0.0-20251003225212-131edca3a897 h1:ZtFYJ3OSR00aiKMMxgm3fRYWqYzjvDXeoBGQm6yC8DE= github.com/onflow/go-ds-pebble v0.0.0-20251003225212-131edca3a897/go.mod h1:aiCRVcj3K60sxc6k5C+HO9C6rouqiSkjR/WKnbTcMfQ= github.com/onflow/go-ethereum v1.16.2 h1:yhC3DA5PTNmUmu7ziq8GmWyQ23KNjle4jCabxpKYyNk= github.com/onflow/go-ethereum v1.16.2/go.mod h1:1vsrG/9APHPqt+mVFni60hIXkqkVdU9WQayNjYi/Ah4= -github.com/onflow/nft-storefront/lib/go/contracts v1.0.0 h1:sxyWLqGm/p4EKT6DUlQESDG1ZNMN9GjPCm1gTq7NGfc= -github.com/onflow/nft-storefront/lib/go/contracts v1.0.0/go.mod h1:kMeq9zUwCrgrSojEbTUTTJpZ4WwacVm2pA7LVFr+glk= +github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066 h1:nQZ8wIvjPnxY8AAnyQDd+Pf9pJalbKjGZhMNtTnTUqc= +github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066/go.mod h1:kMeq9zUwCrgrSojEbTUTTJpZ4WwacVm2pA7LVFr+glk= github.com/onflow/sdks v0.6.0-preview.1 h1:mb/cUezuqWEP1gFZNAgUI4boBltudv4nlfxke1KBp9k= github.com/onflow/sdks v0.6.0-preview.1/go.mod h1:F0dj0EyHC55kknLkeD10js4mo14yTdMotnWMslPirrU= github.com/onflow/wal v1.0.2 h1:5bgsJVf2O3cfMNK12fiiTyYZ8cOrUiELt3heBJfHOhc= @@ -1282,30 +1284,30 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.38.0 h1:ZoYbqX7OaA/TAikspPl3ozPI6iY6LiIY9I8cUfm+pJs= -go.opentelemetry.io/contrib/detectors/gcp v1.38.0/go.mod h1:SU+iU7nu5ud4oCb3LQOhIZ3nRLj6FNVrKgtflbaf2ts= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= -go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 h1:K0XaT3DwHAcV4nKLzcQvwAgSyisUghWoY20I7huthMk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0/go.mod h1:B5Ki776z/MBnVha1Nzwp5arlzBbE3+1jk+pGmaP5HME= +go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48= +go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 h1:f0cb2XPmrqn4XMy9PNliTgRKJgS5WcL/u0/WRYGz4t0= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0/go.mod h1:vnakAaFckOMiMtOIhFI2MNH4FYrZzXCYxmb1LlhoGz8= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 h1:FFeLy03iVTXP6ffeN2iXrxfGsZGCjVx0/4KlizjyBwU= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0/go.mod h1:TMu73/k1CP8nBUpDLc71Wj/Kf7ZS9FK5b53VapRsP9o= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= -go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= -go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= -go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= -go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= -go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= -go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= -go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= -go.opentelemetry.io/proto/otlp v1.7.0 h1:jX1VolD6nHuFzOYso2E73H85i92Mv8JQYk0K9vz09os= -go.opentelemetry.io/proto/otlp v1.7.0/go.mod h1:fSKjH6YJ7HDlwzltzyMj036AJ3ejJLCgCSHGj4efDDo= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw= +go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0= +go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs= +go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18= +go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE= +go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8= +go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew= +go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI= +go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= +go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A= +go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= @@ -1335,6 +1337,8 @@ go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= @@ -1359,8 +1363,8 @@ golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0 golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1401,8 +1405,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= -golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1461,8 +1465,8 @@ golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -1474,8 +1478,8 @@ golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= -golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1490,8 +1494,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= -golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -1577,10 +1581,10 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54 h1:E2/AqCUMZGgd73TQkxUMcMla25GB9i/5HOdLr+uH7Vo= -golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc h1:bH6xUXay0AIFMElXG2rQ4uiE+7ncwtiOdPfYK1NK2XA= +golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -1588,8 +1592,8 @@ golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY= +golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1603,14 +1607,14 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -1671,8 +1675,8 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1704,8 +1708,8 @@ google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz513 google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= -google.golang.org/api v0.247.0 h1:tSd/e0QrUlLsrwMKmkbQhYVa109qIintOls2Wh6bngc= -google.golang.org/api v0.247.0/go.mod h1:r1qZOPmxXffXg6xS5uhx16Fa/UFY8QU/K4bfKrnvovM= +google.golang.org/api v0.267.0 h1:w+vfWPMPYeRs8qH1aYYsFX68jMls5acWl/jocfLomwE= +google.golang.org/api v0.267.0/go.mod h1:Jzc0+ZfLnyvXma3UtaTl023TdhZu6OMBP9tJ+0EmFD0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -1760,14 +1764,14 @@ google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 h1:mepRgnBZa07I4TRuomDE4sTIYieg/osKmzIf4USdWS4= -google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8/go.mod h1:fDMmzKV90WSg1NbozdqrE64fkuTv6mlq2zxo9ad+3yo= -google.golang.org/genproto/googleapis/bytestream v0.0.0-20250804133106-a7a43d27e69b h1:YzmLjVBzUKrr0zPM1KkGPEicd3WHSccw1k9RivnvngU= -google.golang.org/genproto/googleapis/bytestream v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:h6yxum/C2qRb4txaZRLDHK8RyS0H/o2oEDeKY4onY/Y= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 h1:M1rk8KBnUsBDg1oPGHNCxG4vc1f49epmTO7xscSajMk= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM= +google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20 h1:7ei4lp52gK1uSejlA8AZl5AJjeLUOHBQscRQZUgAcu0= +google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20/go.mod h1:ZdbssH/1SOVnjnDlXzxDHK2MCidiqXtbYccJNzNYPEE= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260203192932-546029d2fa20 h1:zQTtWukWCqGTV6Pt60SqvPGnEi2CE3PeeIRlu4SYgAc= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260203192932-546029d2fa20/go.mod h1:Tej9lWiwVvQJP+b43pjJIsr/3mZycXWCIyoiXmbFf40= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 h1:Jr5R2J6F6qWyzINc+4AM8t5pfUz6beZpHp678GNrMbE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= @@ -1792,8 +1796,8 @@ google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= -google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig= +google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0 h1:TLkBREm4nIsEcexnCjgQd5GQWaHcqMzwQV0TX9pq8S0= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= @@ -1809,8 +1813,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/insecure/integration/functional/test/gossipsub/rpc_inspector/validation_inspector_test.go b/insecure/integration/functional/test/gossipsub/rpc_inspector/validation_inspector_test.go index 8a5431adb2f..5226a5e588f 100644 --- a/insecure/integration/functional/test/gossipsub/rpc_inspector/validation_inspector_test.go +++ b/insecure/integration/functional/test/gossipsub/rpc_inspector/validation_inspector_test.go @@ -7,10 +7,8 @@ import ( "testing" "time" - corrupt "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub" pb "github.com/libp2p/go-libp2p-pubsub/pb" - pubsub_pb "github.com/libp2p/go-libp2p-pubsub/pb" "github.com/libp2p/go-libp2p/core/peer" mockery "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -706,7 +704,7 @@ func TestValidationInspector_UnstakedNode_Detection(t *testing.T) { t.Name(), idProvider, p2ptest.WithRole(role), - internal.WithCorruptGossipSub(corruptlibp2p.CorruptGossipSubFactory(), corruptlibp2p.CorruptGossipSubConfigFactoryWithInspector(func(id peer.ID, rpc *corrupt.RPC) error { + internal.WithCorruptGossipSub(corruptlibp2p.CorruptGossipSubFactory(), corruptlibp2p.CorruptGossipSubConfigFactoryWithInspector(func(id peer.ID, rpc *pubsub.RPC) error { if nodesConnected.Load() { // after nodes are connected invoke corrupt callback with an unstaked peer ID return corruptInspectorFunc(unstakedPeerID, rpc) @@ -1055,10 +1053,10 @@ func testGossipSubSpamMitigationIntegration(t *testing.T, msgType p2pmsg.Control return (*messages.Proposal)(unittest.ProposalFixture()) }) - var unknownTopicSpam []pubsub_pb.ControlMessage - var malformedTopicSpam []pubsub_pb.ControlMessage - var invalidSporkIDTopicSpam []pubsub_pb.ControlMessage - var duplicateTopicSpam []pubsub_pb.ControlMessage + var unknownTopicSpam []pb.ControlMessage + var malformedTopicSpam []pb.ControlMessage + var invalidSporkIDTopicSpam []pb.ControlMessage + var duplicateTopicSpam []pb.ControlMessage switch msgType { case p2pmsg.CtrlMsgGraft: unknownTopicSpam = spammer.GenerateCtlMessages(int(spamCtrlMsgCount), p2ptest.WithGraft(spamRpcCount, unknownTopic.String())) diff --git a/insecure/integration/functional/test/gossipsub/scoring/ihave_spam_test.go b/insecure/integration/functional/test/gossipsub/scoring/ihave_spam_test.go index 212c4394dd8..df3d5b48b35 100644 --- a/insecure/integration/functional/test/gossipsub/scoring/ihave_spam_test.go +++ b/insecure/integration/functional/test/gossipsub/scoring/ihave_spam_test.go @@ -6,7 +6,6 @@ import ( "testing" "time" - corrupt "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub" pb "github.com/libp2p/go-libp2p-pubsub/pb" "github.com/libp2p/go-libp2p/core/peer" @@ -40,7 +39,7 @@ func TestGossipSubIHaveBrokenPromises_Below_Threshold(t *testing.T) { receivedIWants := concurrentmap.New[string, struct{}]() idProvider := unittest.NewUpdatableIDProvider(flow.IdentityList{}) - spammer := corruptlibp2p.NewGossipSubRouterSpammerWithRpcInspector(t, sporkId, role, idProvider, func(id peer.ID, rpc *corrupt.RPC) error { + spammer := corruptlibp2p.NewGossipSubRouterSpammerWithRpcInspector(t, sporkId, role, idProvider, func(id peer.ID, rpc *pubsub.RPC) error { // override rpc inspector of the spammer node to keep track of the iwants it has received. if rpc.RPC.Control == nil || rpc.RPC.Control.Iwant == nil { return nil @@ -192,7 +191,7 @@ func TestGossipSubIHaveBrokenPromises_Above_Threshold(t *testing.T) { receivedIWants := concurrentmap.New[string, struct{}]() idProvider := unittest.NewUpdatableIDProvider(flow.IdentityList{}) - spammer := corruptlibp2p.NewGossipSubRouterSpammerWithRpcInspector(t, sporkId, role, idProvider, func(id peer.ID, rpc *corrupt.RPC) error { + spammer := corruptlibp2p.NewGossipSubRouterSpammerWithRpcInspector(t, sporkId, role, idProvider, func(id peer.ID, rpc *pubsub.RPC) error { // override rpc inspector of the spammer node to keep track of the iwants it has received. if rpc.RPC.Control == nil || rpc.RPC.Control.Iwant == nil { return nil diff --git a/insecure/internal/subscription.go b/insecure/internal/subscription.go index f0d1abdc952..626ceadbd83 100644 --- a/insecure/internal/subscription.go +++ b/insecure/internal/subscription.go @@ -3,7 +3,6 @@ package internal import ( "context" - corrupt "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/onflow/flow-go/network/p2p" @@ -13,12 +12,12 @@ import ( // This is previously needed because we used a forked pubsub module. This is no longer the case // so we could refactor this in the future to remove this wrapper. type CorruptSubscription struct { - s *corrupt.Subscription + s *pubsub.Subscription } var _ p2p.Subscription = (*CorruptSubscription)(nil) -func NewCorruptSubscription(s *corrupt.Subscription) p2p.Subscription { +func NewCorruptSubscription(s *pubsub.Subscription) p2p.Subscription { return &CorruptSubscription{ s: s, } @@ -34,10 +33,10 @@ func (c *CorruptSubscription) Next(ctx context.Context) (*pubsub.Message, error) return nil, err } - // we read a corrupt.Message from the corrupt.Subscription, however, we need to return - // a pubsub.Message to the caller of this function, so we need to convert the corrupt.Message. + // we read a pubsub.Message from the pubsub.Subscription, however, we need to return + // a pubsub.Message to the caller of this function, so we need to convert the pubsub.Message. // Flow codebase uses the original libp2p pubsub module, and the pubsub.Message is defined - // in the original libp2p pubsub module, so we cannot use the corrupt.Message in the Flow codebase. + // in the original libp2p pubsub module, so we cannot use the pubsub.Message in the Flow codebase. return &pubsub.Message{ Message: m.Message, ID: m.ID, diff --git a/insecure/mock/attack_orchestrator.go b/insecure/mock/attack_orchestrator.go index eefce7f82dc..eb11efd2df1 100644 --- a/insecure/mock/attack_orchestrator.go +++ b/insecure/mock/attack_orchestrator.go @@ -1,68 +1,179 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - insecure "github.com/onflow/flow-go/insecure" + "github.com/onflow/flow-go/insecure" mock "github.com/stretchr/testify/mock" ) +// NewAttackOrchestrator creates a new instance of AttackOrchestrator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAttackOrchestrator(t interface { + mock.TestingT + Cleanup(func()) +}) *AttackOrchestrator { + mock := &AttackOrchestrator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AttackOrchestrator is an autogenerated mock type for the AttackOrchestrator type type AttackOrchestrator struct { mock.Mock } -// HandleEgressEvent provides a mock function with given fields: _a0 -func (_m *AttackOrchestrator) HandleEgressEvent(_a0 *insecure.EgressEvent) error { - ret := _m.Called(_a0) +type AttackOrchestrator_Expecter struct { + mock *mock.Mock +} + +func (_m *AttackOrchestrator) EXPECT() *AttackOrchestrator_Expecter { + return &AttackOrchestrator_Expecter{mock: &_m.Mock} +} + +// HandleEgressEvent provides a mock function for the type AttackOrchestrator +func (_mock *AttackOrchestrator) HandleEgressEvent(egressEvent *insecure.EgressEvent) error { + ret := _mock.Called(egressEvent) if len(ret) == 0 { panic("no return value specified for HandleEgressEvent") } var r0 error - if rf, ok := ret.Get(0).(func(*insecure.EgressEvent) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*insecure.EgressEvent) error); ok { + r0 = returnFunc(egressEvent) } else { r0 = ret.Error(0) } - return r0 } -// HandleIngressEvent provides a mock function with given fields: _a0 -func (_m *AttackOrchestrator) HandleIngressEvent(_a0 *insecure.IngressEvent) error { - ret := _m.Called(_a0) +// AttackOrchestrator_HandleEgressEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleEgressEvent' +type AttackOrchestrator_HandleEgressEvent_Call struct { + *mock.Call +} + +// HandleEgressEvent is a helper method to define mock.On call +// - egressEvent *insecure.EgressEvent +func (_e *AttackOrchestrator_Expecter) HandleEgressEvent(egressEvent interface{}) *AttackOrchestrator_HandleEgressEvent_Call { + return &AttackOrchestrator_HandleEgressEvent_Call{Call: _e.mock.On("HandleEgressEvent", egressEvent)} +} + +func (_c *AttackOrchestrator_HandleEgressEvent_Call) Run(run func(egressEvent *insecure.EgressEvent)) *AttackOrchestrator_HandleEgressEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *insecure.EgressEvent + if args[0] != nil { + arg0 = args[0].(*insecure.EgressEvent) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AttackOrchestrator_HandleEgressEvent_Call) Return(err error) *AttackOrchestrator_HandleEgressEvent_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AttackOrchestrator_HandleEgressEvent_Call) RunAndReturn(run func(egressEvent *insecure.EgressEvent) error) *AttackOrchestrator_HandleEgressEvent_Call { + _c.Call.Return(run) + return _c +} + +// HandleIngressEvent provides a mock function for the type AttackOrchestrator +func (_mock *AttackOrchestrator) HandleIngressEvent(ingressEvent *insecure.IngressEvent) error { + ret := _mock.Called(ingressEvent) if len(ret) == 0 { panic("no return value specified for HandleIngressEvent") } var r0 error - if rf, ok := ret.Get(0).(func(*insecure.IngressEvent) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*insecure.IngressEvent) error); ok { + r0 = returnFunc(ingressEvent) } else { r0 = ret.Error(0) } - return r0 } -// Register provides a mock function with given fields: _a0 -func (_m *AttackOrchestrator) Register(_a0 insecure.OrchestratorNetwork) { - _m.Called(_a0) +// AttackOrchestrator_HandleIngressEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleIngressEvent' +type AttackOrchestrator_HandleIngressEvent_Call struct { + *mock.Call } -// NewAttackOrchestrator creates a new instance of AttackOrchestrator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAttackOrchestrator(t interface { - mock.TestingT - Cleanup(func()) -}) *AttackOrchestrator { - mock := &AttackOrchestrator{} - mock.Mock.Test(t) +// HandleIngressEvent is a helper method to define mock.On call +// - ingressEvent *insecure.IngressEvent +func (_e *AttackOrchestrator_Expecter) HandleIngressEvent(ingressEvent interface{}) *AttackOrchestrator_HandleIngressEvent_Call { + return &AttackOrchestrator_HandleIngressEvent_Call{Call: _e.mock.On("HandleIngressEvent", ingressEvent)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *AttackOrchestrator_HandleIngressEvent_Call) Run(run func(ingressEvent *insecure.IngressEvent)) *AttackOrchestrator_HandleIngressEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *insecure.IngressEvent + if args[0] != nil { + arg0 = args[0].(*insecure.IngressEvent) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *AttackOrchestrator_HandleIngressEvent_Call) Return(err error) *AttackOrchestrator_HandleIngressEvent_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AttackOrchestrator_HandleIngressEvent_Call) RunAndReturn(run func(ingressEvent *insecure.IngressEvent) error) *AttackOrchestrator_HandleIngressEvent_Call { + _c.Call.Return(run) + return _c +} + +// Register provides a mock function for the type AttackOrchestrator +func (_mock *AttackOrchestrator) Register(orchestratorNetwork insecure.OrchestratorNetwork) { + _mock.Called(orchestratorNetwork) + return +} + +// AttackOrchestrator_Register_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Register' +type AttackOrchestrator_Register_Call struct { + *mock.Call +} + +// Register is a helper method to define mock.On call +// - orchestratorNetwork insecure.OrchestratorNetwork +func (_e *AttackOrchestrator_Expecter) Register(orchestratorNetwork interface{}) *AttackOrchestrator_Register_Call { + return &AttackOrchestrator_Register_Call{Call: _e.mock.On("Register", orchestratorNetwork)} +} + +func (_c *AttackOrchestrator_Register_Call) Run(run func(orchestratorNetwork insecure.OrchestratorNetwork)) *AttackOrchestrator_Register_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 insecure.OrchestratorNetwork + if args[0] != nil { + arg0 = args[0].(insecure.OrchestratorNetwork) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AttackOrchestrator_Register_Call) Return() *AttackOrchestrator_Register_Call { + _c.Call.Return() + return _c +} + +func (_c *AttackOrchestrator_Register_Call) RunAndReturn(run func(orchestratorNetwork insecure.OrchestratorNetwork)) *AttackOrchestrator_Register_Call { + _c.Run(run) + return _c } diff --git a/insecure/mock/corrupt_conduit_factory.go b/insecure/mock/corrupt_conduit_factory.go index 6d66aa4f5ea..dfa58e5d57b 100644 --- a/insecure/mock/corrupt_conduit_factory.go +++ b/insecure/mock/corrupt_conduit_factory.go @@ -1,29 +1,49 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - channels "github.com/onflow/flow-go/network/channels" - - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/insecure" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" + mock "github.com/stretchr/testify/mock" +) - insecure "github.com/onflow/flow-go/insecure" +// NewCorruptConduitFactory creates a new instance of CorruptConduitFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCorruptConduitFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *CorruptConduitFactory { + mock := &CorruptConduitFactory{} + mock.Mock.Test(t) - mock "github.com/stretchr/testify/mock" + t.Cleanup(func() { mock.AssertExpectations(t) }) - network "github.com/onflow/flow-go/network" -) + return mock +} // CorruptConduitFactory is an autogenerated mock type for the CorruptConduitFactory type type CorruptConduitFactory struct { mock.Mock } -// NewConduit provides a mock function with given fields: _a0, _a1 -func (_m *CorruptConduitFactory) NewConduit(_a0 context.Context, _a1 channels.Channel) (network.Conduit, error) { - ret := _m.Called(_a0, _a1) +type CorruptConduitFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *CorruptConduitFactory) EXPECT() *CorruptConduitFactory_Expecter { + return &CorruptConduitFactory_Expecter{mock: &_m.Mock} +} + +// NewConduit provides a mock function for the type CorruptConduitFactory +func (_mock *CorruptConduitFactory) NewConduit(context1 context.Context, channel channels.Channel) (network.Conduit, error) { + ret := _mock.Called(context1, channel) if len(ret) == 0 { panic("no return value specified for NewConduit") @@ -31,115 +51,301 @@ func (_m *CorruptConduitFactory) NewConduit(_a0 context.Context, _a1 channels.Ch var r0 network.Conduit var r1 error - if rf, ok := ret.Get(0).(func(context.Context, channels.Channel) (network.Conduit, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, channels.Channel) (network.Conduit, error)); ok { + return returnFunc(context1, channel) } - if rf, ok := ret.Get(0).(func(context.Context, channels.Channel) network.Conduit); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, channels.Channel) network.Conduit); ok { + r0 = returnFunc(context1, channel) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.Conduit) } } - - if rf, ok := ret.Get(1).(func(context.Context, channels.Channel) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, channels.Channel) error); ok { + r1 = returnFunc(context1, channel) } else { r1 = ret.Error(1) } - return r0, r1 } -// RegisterAdapter provides a mock function with given fields: _a0 -func (_m *CorruptConduitFactory) RegisterAdapter(_a0 network.ConduitAdapter) error { - ret := _m.Called(_a0) +// CorruptConduitFactory_NewConduit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewConduit' +type CorruptConduitFactory_NewConduit_Call struct { + *mock.Call +} + +// NewConduit is a helper method to define mock.On call +// - context1 context.Context +// - channel channels.Channel +func (_e *CorruptConduitFactory_Expecter) NewConduit(context1 interface{}, channel interface{}) *CorruptConduitFactory_NewConduit_Call { + return &CorruptConduitFactory_NewConduit_Call{Call: _e.mock.On("NewConduit", context1, channel)} +} + +func (_c *CorruptConduitFactory_NewConduit_Call) Run(run func(context1 context.Context, channel channels.Channel)) *CorruptConduitFactory_NewConduit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 channels.Channel + if args[1] != nil { + arg1 = args[1].(channels.Channel) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *CorruptConduitFactory_NewConduit_Call) Return(conduit network.Conduit, err error) *CorruptConduitFactory_NewConduit_Call { + _c.Call.Return(conduit, err) + return _c +} + +func (_c *CorruptConduitFactory_NewConduit_Call) RunAndReturn(run func(context1 context.Context, channel channels.Channel) (network.Conduit, error)) *CorruptConduitFactory_NewConduit_Call { + _c.Call.Return(run) + return _c +} + +// RegisterAdapter provides a mock function for the type CorruptConduitFactory +func (_mock *CorruptConduitFactory) RegisterAdapter(conduitAdapter network.ConduitAdapter) error { + ret := _mock.Called(conduitAdapter) if len(ret) == 0 { panic("no return value specified for RegisterAdapter") } var r0 error - if rf, ok := ret.Get(0).(func(network.ConduitAdapter) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(network.ConduitAdapter) error); ok { + r0 = returnFunc(conduitAdapter) } else { r0 = ret.Error(0) } - return r0 } -// RegisterEgressController provides a mock function with given fields: _a0 -func (_m *CorruptConduitFactory) RegisterEgressController(_a0 insecure.EgressController) error { - ret := _m.Called(_a0) +// CorruptConduitFactory_RegisterAdapter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterAdapter' +type CorruptConduitFactory_RegisterAdapter_Call struct { + *mock.Call +} + +// RegisterAdapter is a helper method to define mock.On call +// - conduitAdapter network.ConduitAdapter +func (_e *CorruptConduitFactory_Expecter) RegisterAdapter(conduitAdapter interface{}) *CorruptConduitFactory_RegisterAdapter_Call { + return &CorruptConduitFactory_RegisterAdapter_Call{Call: _e.mock.On("RegisterAdapter", conduitAdapter)} +} + +func (_c *CorruptConduitFactory_RegisterAdapter_Call) Run(run func(conduitAdapter network.ConduitAdapter)) *CorruptConduitFactory_RegisterAdapter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.ConduitAdapter + if args[0] != nil { + arg0 = args[0].(network.ConduitAdapter) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CorruptConduitFactory_RegisterAdapter_Call) Return(err error) *CorruptConduitFactory_RegisterAdapter_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CorruptConduitFactory_RegisterAdapter_Call) RunAndReturn(run func(conduitAdapter network.ConduitAdapter) error) *CorruptConduitFactory_RegisterAdapter_Call { + _c.Call.Return(run) + return _c +} + +// RegisterEgressController provides a mock function for the type CorruptConduitFactory +func (_mock *CorruptConduitFactory) RegisterEgressController(egressController insecure.EgressController) error { + ret := _mock.Called(egressController) if len(ret) == 0 { panic("no return value specified for RegisterEgressController") } var r0 error - if rf, ok := ret.Get(0).(func(insecure.EgressController) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(insecure.EgressController) error); ok { + r0 = returnFunc(egressController) } else { r0 = ret.Error(0) } - return r0 } -// SendOnFlowNetwork provides a mock function with given fields: _a0, _a1, _a2, _a3, _a4 -func (_m *CorruptConduitFactory) SendOnFlowNetwork(_a0 interface{}, _a1 channels.Channel, _a2 insecure.Protocol, _a3 uint, _a4 ...flow.Identifier) error { - _va := make([]interface{}, len(_a4)) - for _i := range _a4 { - _va[_i] = _a4[_i] +// CorruptConduitFactory_RegisterEgressController_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterEgressController' +type CorruptConduitFactory_RegisterEgressController_Call struct { + *mock.Call +} + +// RegisterEgressController is a helper method to define mock.On call +// - egressController insecure.EgressController +func (_e *CorruptConduitFactory_Expecter) RegisterEgressController(egressController interface{}) *CorruptConduitFactory_RegisterEgressController_Call { + return &CorruptConduitFactory_RegisterEgressController_Call{Call: _e.mock.On("RegisterEgressController", egressController)} +} + +func (_c *CorruptConduitFactory_RegisterEgressController_Call) Run(run func(egressController insecure.EgressController)) *CorruptConduitFactory_RegisterEgressController_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 insecure.EgressController + if args[0] != nil { + arg0 = args[0].(insecure.EgressController) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CorruptConduitFactory_RegisterEgressController_Call) Return(err error) *CorruptConduitFactory_RegisterEgressController_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CorruptConduitFactory_RegisterEgressController_Call) RunAndReturn(run func(egressController insecure.EgressController) error) *CorruptConduitFactory_RegisterEgressController_Call { + _c.Call.Return(run) + return _c +} + +// SendOnFlowNetwork provides a mock function for the type CorruptConduitFactory +func (_mock *CorruptConduitFactory) SendOnFlowNetwork(ifaceVal interface{}, channel channels.Channel, protocol insecure.Protocol, v uint, identifiers ...flow.Identifier) error { + // flow.Identifier + _va := make([]interface{}, len(identifiers)) + for _i := range identifiers { + _va[_i] = identifiers[_i] } var _ca []interface{} - _ca = append(_ca, _a0, _a1, _a2, _a3) + _ca = append(_ca, ifaceVal, channel, protocol, v) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SendOnFlowNetwork") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}, channels.Channel, insecure.Protocol, uint, ...flow.Identifier) error); ok { - r0 = rf(_a0, _a1, _a2, _a3, _a4...) + if returnFunc, ok := ret.Get(0).(func(interface{}, channels.Channel, insecure.Protocol, uint, ...flow.Identifier) error); ok { + r0 = returnFunc(ifaceVal, channel, protocol, v, identifiers...) } else { r0 = ret.Error(0) } - return r0 } -// UnregisterChannel provides a mock function with given fields: _a0 -func (_m *CorruptConduitFactory) UnregisterChannel(_a0 channels.Channel) error { - ret := _m.Called(_a0) +// CorruptConduitFactory_SendOnFlowNetwork_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendOnFlowNetwork' +type CorruptConduitFactory_SendOnFlowNetwork_Call struct { + *mock.Call +} + +// SendOnFlowNetwork is a helper method to define mock.On call +// - ifaceVal interface{} +// - channel channels.Channel +// - protocol insecure.Protocol +// - v uint +// - identifiers ...flow.Identifier +func (_e *CorruptConduitFactory_Expecter) SendOnFlowNetwork(ifaceVal interface{}, channel interface{}, protocol interface{}, v interface{}, identifiers ...interface{}) *CorruptConduitFactory_SendOnFlowNetwork_Call { + return &CorruptConduitFactory_SendOnFlowNetwork_Call{Call: _e.mock.On("SendOnFlowNetwork", + append([]interface{}{ifaceVal, channel, protocol, v}, identifiers...)...)} +} + +func (_c *CorruptConduitFactory_SendOnFlowNetwork_Call) Run(run func(ifaceVal interface{}, channel channels.Channel, protocol insecure.Protocol, v uint, identifiers ...flow.Identifier)) *CorruptConduitFactory_SendOnFlowNetwork_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 interface{} + if args[0] != nil { + arg0 = args[0].(interface{}) + } + var arg1 channels.Channel + if args[1] != nil { + arg1 = args[1].(channels.Channel) + } + var arg2 insecure.Protocol + if args[2] != nil { + arg2 = args[2].(insecure.Protocol) + } + var arg3 uint + if args[3] != nil { + arg3 = args[3].(uint) + } + var arg4 []flow.Identifier + variadicArgs := make([]flow.Identifier, len(args)-4) + for i, a := range args[4:] { + if a != nil { + variadicArgs[i] = a.(flow.Identifier) + } + } + arg4 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3, + arg4..., + ) + }) + return _c +} + +func (_c *CorruptConduitFactory_SendOnFlowNetwork_Call) Return(err error) *CorruptConduitFactory_SendOnFlowNetwork_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CorruptConduitFactory_SendOnFlowNetwork_Call) RunAndReturn(run func(ifaceVal interface{}, channel channels.Channel, protocol insecure.Protocol, v uint, identifiers ...flow.Identifier) error) *CorruptConduitFactory_SendOnFlowNetwork_Call { + _c.Call.Return(run) + return _c +} + +// UnregisterChannel provides a mock function for the type CorruptConduitFactory +func (_mock *CorruptConduitFactory) UnregisterChannel(channel channels.Channel) error { + ret := _mock.Called(channel) if len(ret) == 0 { panic("no return value specified for UnregisterChannel") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) error); ok { + r0 = returnFunc(channel) } else { r0 = ret.Error(0) } - return r0 } -// NewCorruptConduitFactory creates a new instance of CorruptConduitFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCorruptConduitFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *CorruptConduitFactory { - mock := &CorruptConduitFactory{} - mock.Mock.Test(t) +// CorruptConduitFactory_UnregisterChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnregisterChannel' +type CorruptConduitFactory_UnregisterChannel_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UnregisterChannel is a helper method to define mock.On call +// - channel channels.Channel +func (_e *CorruptConduitFactory_Expecter) UnregisterChannel(channel interface{}) *CorruptConduitFactory_UnregisterChannel_Call { + return &CorruptConduitFactory_UnregisterChannel_Call{Call: _e.mock.On("UnregisterChannel", channel)} +} - return mock +func (_c *CorruptConduitFactory_UnregisterChannel_Call) Run(run func(channel channels.Channel)) *CorruptConduitFactory_UnregisterChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CorruptConduitFactory_UnregisterChannel_Call) Return(err error) *CorruptConduitFactory_UnregisterChannel_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CorruptConduitFactory_UnregisterChannel_Call) RunAndReturn(run func(channel channels.Channel) error) *CorruptConduitFactory_UnregisterChannel_Call { + _c.Call.Return(run) + return _c } diff --git a/insecure/mock/corrupted_node_connection.go b/insecure/mock/corrupted_node_connection.go index 102a76a57a0..4102d168166 100644 --- a/insecure/mock/corrupted_node_connection.go +++ b/insecure/mock/corrupted_node_connection.go @@ -1,63 +1,132 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - insecure "github.com/onflow/flow-go/insecure" + "github.com/onflow/flow-go/insecure" mock "github.com/stretchr/testify/mock" ) +// NewCorruptedNodeConnection creates a new instance of CorruptedNodeConnection. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCorruptedNodeConnection(t interface { + mock.TestingT + Cleanup(func()) +}) *CorruptedNodeConnection { + mock := &CorruptedNodeConnection{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CorruptedNodeConnection is an autogenerated mock type for the CorruptedNodeConnection type type CorruptedNodeConnection struct { mock.Mock } -// CloseConnection provides a mock function with no fields -func (_m *CorruptedNodeConnection) CloseConnection() error { - ret := _m.Called() +type CorruptedNodeConnection_Expecter struct { + mock *mock.Mock +} + +func (_m *CorruptedNodeConnection) EXPECT() *CorruptedNodeConnection_Expecter { + return &CorruptedNodeConnection_Expecter{mock: &_m.Mock} +} + +// CloseConnection provides a mock function for the type CorruptedNodeConnection +func (_mock *CorruptedNodeConnection) CloseConnection() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for CloseConnection") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// SendMessage provides a mock function with given fields: _a0 -func (_m *CorruptedNodeConnection) SendMessage(_a0 *insecure.Message) error { - ret := _m.Called(_a0) +// CorruptedNodeConnection_CloseConnection_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CloseConnection' +type CorruptedNodeConnection_CloseConnection_Call struct { + *mock.Call +} + +// CloseConnection is a helper method to define mock.On call +func (_e *CorruptedNodeConnection_Expecter) CloseConnection() *CorruptedNodeConnection_CloseConnection_Call { + return &CorruptedNodeConnection_CloseConnection_Call{Call: _e.mock.On("CloseConnection")} +} + +func (_c *CorruptedNodeConnection_CloseConnection_Call) Run(run func()) *CorruptedNodeConnection_CloseConnection_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CorruptedNodeConnection_CloseConnection_Call) Return(err error) *CorruptedNodeConnection_CloseConnection_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CorruptedNodeConnection_CloseConnection_Call) RunAndReturn(run func() error) *CorruptedNodeConnection_CloseConnection_Call { + _c.Call.Return(run) + return _c +} + +// SendMessage provides a mock function for the type CorruptedNodeConnection +func (_mock *CorruptedNodeConnection) SendMessage(message *insecure.Message) error { + ret := _mock.Called(message) if len(ret) == 0 { panic("no return value specified for SendMessage") } var r0 error - if rf, ok := ret.Get(0).(func(*insecure.Message) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*insecure.Message) error); ok { + r0 = returnFunc(message) } else { r0 = ret.Error(0) } - return r0 } -// NewCorruptedNodeConnection creates a new instance of CorruptedNodeConnection. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCorruptedNodeConnection(t interface { - mock.TestingT - Cleanup(func()) -}) *CorruptedNodeConnection { - mock := &CorruptedNodeConnection{} - mock.Mock.Test(t) +// CorruptedNodeConnection_SendMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendMessage' +type CorruptedNodeConnection_SendMessage_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SendMessage is a helper method to define mock.On call +// - message *insecure.Message +func (_e *CorruptedNodeConnection_Expecter) SendMessage(message interface{}) *CorruptedNodeConnection_SendMessage_Call { + return &CorruptedNodeConnection_SendMessage_Call{Call: _e.mock.On("SendMessage", message)} +} - return mock +func (_c *CorruptedNodeConnection_SendMessage_Call) Run(run func(message *insecure.Message)) *CorruptedNodeConnection_SendMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *insecure.Message + if args[0] != nil { + arg0 = args[0].(*insecure.Message) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CorruptedNodeConnection_SendMessage_Call) Return(err error) *CorruptedNodeConnection_SendMessage_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CorruptedNodeConnection_SendMessage_Call) RunAndReturn(run func(message *insecure.Message) error) *CorruptedNodeConnection_SendMessage_Call { + _c.Call.Return(run) + return _c } diff --git a/insecure/mock/corrupted_node_connector.go b/insecure/mock/corrupted_node_connector.go index e55c4852ef3..c323e6130fb 100644 --- a/insecure/mock/corrupted_node_connector.go +++ b/insecure/mock/corrupted_node_connector.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - insecure "github.com/onflow/flow-go/insecure" - flow "github.com/onflow/flow-go/model/flow" - - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/onflow/flow-go/insecure" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewCorruptedNodeConnector creates a new instance of CorruptedNodeConnector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCorruptedNodeConnector(t interface { + mock.TestingT + Cleanup(func()) +}) *CorruptedNodeConnector { + mock := &CorruptedNodeConnector{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CorruptedNodeConnector is an autogenerated mock type for the CorruptedNodeConnector type type CorruptedNodeConnector struct { mock.Mock } -// Connect provides a mock function with given fields: _a0, _a1 -func (_m *CorruptedNodeConnector) Connect(_a0 irrecoverable.SignalerContext, _a1 flow.Identifier) (insecure.CorruptedNodeConnection, error) { - ret := _m.Called(_a0, _a1) +type CorruptedNodeConnector_Expecter struct { + mock *mock.Mock +} + +func (_m *CorruptedNodeConnector) EXPECT() *CorruptedNodeConnector_Expecter { + return &CorruptedNodeConnector_Expecter{mock: &_m.Mock} +} + +// Connect provides a mock function for the type CorruptedNodeConnector +func (_mock *CorruptedNodeConnector) Connect(signalerContext irrecoverable.SignalerContext, identifier flow.Identifier) (insecure.CorruptedNodeConnection, error) { + ret := _mock.Called(signalerContext, identifier) if len(ret) == 0 { panic("no return value specified for Connect") @@ -26,41 +48,100 @@ func (_m *CorruptedNodeConnector) Connect(_a0 irrecoverable.SignalerContext, _a1 var r0 insecure.CorruptedNodeConnection var r1 error - if rf, ok := ret.Get(0).(func(irrecoverable.SignalerContext, flow.Identifier) (insecure.CorruptedNodeConnection, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(irrecoverable.SignalerContext, flow.Identifier) (insecure.CorruptedNodeConnection, error)); ok { + return returnFunc(signalerContext, identifier) } - if rf, ok := ret.Get(0).(func(irrecoverable.SignalerContext, flow.Identifier) insecure.CorruptedNodeConnection); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(irrecoverable.SignalerContext, flow.Identifier) insecure.CorruptedNodeConnection); ok { + r0 = returnFunc(signalerContext, identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(insecure.CorruptedNodeConnection) } } - - if rf, ok := ret.Get(1).(func(irrecoverable.SignalerContext, flow.Identifier) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(irrecoverable.SignalerContext, flow.Identifier) error); ok { + r1 = returnFunc(signalerContext, identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// WithIncomingMessageHandler provides a mock function with given fields: _a0 -func (_m *CorruptedNodeConnector) WithIncomingMessageHandler(_a0 func(*insecure.Message)) { - _m.Called(_a0) +// CorruptedNodeConnector_Connect_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Connect' +type CorruptedNodeConnector_Connect_Call struct { + *mock.Call } -// NewCorruptedNodeConnector creates a new instance of CorruptedNodeConnector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCorruptedNodeConnector(t interface { - mock.TestingT - Cleanup(func()) -}) *CorruptedNodeConnector { - mock := &CorruptedNodeConnector{} - mock.Mock.Test(t) +// Connect is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +// - identifier flow.Identifier +func (_e *CorruptedNodeConnector_Expecter) Connect(signalerContext interface{}, identifier interface{}) *CorruptedNodeConnector_Connect_Call { + return &CorruptedNodeConnector_Connect_Call{Call: _e.mock.On("Connect", signalerContext, identifier)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *CorruptedNodeConnector_Connect_Call) Run(run func(signalerContext irrecoverable.SignalerContext, identifier flow.Identifier)) *CorruptedNodeConnector_Connect_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return mock +func (_c *CorruptedNodeConnector_Connect_Call) Return(corruptedNodeConnection insecure.CorruptedNodeConnection, err error) *CorruptedNodeConnector_Connect_Call { + _c.Call.Return(corruptedNodeConnection, err) + return _c +} + +func (_c *CorruptedNodeConnector_Connect_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext, identifier flow.Identifier) (insecure.CorruptedNodeConnection, error)) *CorruptedNodeConnector_Connect_Call { + _c.Call.Return(run) + return _c +} + +// WithIncomingMessageHandler provides a mock function for the type CorruptedNodeConnector +func (_mock *CorruptedNodeConnector) WithIncomingMessageHandler(fn func(*insecure.Message)) { + _mock.Called(fn) + return +} + +// CorruptedNodeConnector_WithIncomingMessageHandler_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithIncomingMessageHandler' +type CorruptedNodeConnector_WithIncomingMessageHandler_Call struct { + *mock.Call +} + +// WithIncomingMessageHandler is a helper method to define mock.On call +// - fn func(*insecure.Message) +func (_e *CorruptedNodeConnector_Expecter) WithIncomingMessageHandler(fn interface{}) *CorruptedNodeConnector_WithIncomingMessageHandler_Call { + return &CorruptedNodeConnector_WithIncomingMessageHandler_Call{Call: _e.mock.On("WithIncomingMessageHandler", fn)} +} + +func (_c *CorruptedNodeConnector_WithIncomingMessageHandler_Call) Run(run func(fn func(*insecure.Message))) *CorruptedNodeConnector_WithIncomingMessageHandler_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(*insecure.Message) + if args[0] != nil { + arg0 = args[0].(func(*insecure.Message)) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CorruptedNodeConnector_WithIncomingMessageHandler_Call) Return() *CorruptedNodeConnector_WithIncomingMessageHandler_Call { + _c.Call.Return() + return _c +} + +func (_c *CorruptedNodeConnector_WithIncomingMessageHandler_Call) RunAndReturn(run func(fn func(*insecure.Message))) *CorruptedNodeConnector_WithIncomingMessageHandler_Call { + _c.Run(run) + return _c } diff --git a/insecure/mock/egress_controller.go b/insecure/mock/egress_controller.go index 9fd8e9f25a1..16986798a63 100644 --- a/insecure/mock/egress_controller.go +++ b/insecure/mock/egress_controller.go @@ -1,74 +1,178 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - - insecure "github.com/onflow/flow-go/insecure" - + "github.com/onflow/flow-go/insecure" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" ) +// NewEgressController creates a new instance of EgressController. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEgressController(t interface { + mock.TestingT + Cleanup(func()) +}) *EgressController { + mock := &EgressController{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EgressController is an autogenerated mock type for the EgressController type type EgressController struct { mock.Mock } -// EngineClosingChannel provides a mock function with given fields: _a0 -func (_m *EgressController) EngineClosingChannel(_a0 channels.Channel) error { - ret := _m.Called(_a0) +type EgressController_Expecter struct { + mock *mock.Mock +} + +func (_m *EgressController) EXPECT() *EgressController_Expecter { + return &EgressController_Expecter{mock: &_m.Mock} +} + +// EngineClosingChannel provides a mock function for the type EgressController +func (_mock *EgressController) EngineClosingChannel(channel channels.Channel) error { + ret := _mock.Called(channel) if len(ret) == 0 { panic("no return value specified for EngineClosingChannel") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) error); ok { + r0 = returnFunc(channel) } else { r0 = ret.Error(0) } - return r0 } -// HandleOutgoingEvent provides a mock function with given fields: _a0, _a1, _a2, _a3, _a4 -func (_m *EgressController) HandleOutgoingEvent(_a0 interface{}, _a1 channels.Channel, _a2 insecure.Protocol, _a3 uint32, _a4 ...flow.Identifier) error { - _va := make([]interface{}, len(_a4)) - for _i := range _a4 { - _va[_i] = _a4[_i] +// EgressController_EngineClosingChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EngineClosingChannel' +type EgressController_EngineClosingChannel_Call struct { + *mock.Call +} + +// EngineClosingChannel is a helper method to define mock.On call +// - channel channels.Channel +func (_e *EgressController_Expecter) EngineClosingChannel(channel interface{}) *EgressController_EngineClosingChannel_Call { + return &EgressController_EngineClosingChannel_Call{Call: _e.mock.On("EngineClosingChannel", channel)} +} + +func (_c *EgressController_EngineClosingChannel_Call) Run(run func(channel channels.Channel)) *EgressController_EngineClosingChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EgressController_EngineClosingChannel_Call) Return(err error) *EgressController_EngineClosingChannel_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EgressController_EngineClosingChannel_Call) RunAndReturn(run func(channel channels.Channel) error) *EgressController_EngineClosingChannel_Call { + _c.Call.Return(run) + return _c +} + +// HandleOutgoingEvent provides a mock function for the type EgressController +func (_mock *EgressController) HandleOutgoingEvent(ifaceVal interface{}, channel channels.Channel, protocol insecure.Protocol, v uint32, identifiers ...flow.Identifier) error { + // flow.Identifier + _va := make([]interface{}, len(identifiers)) + for _i := range identifiers { + _va[_i] = identifiers[_i] } var _ca []interface{} - _ca = append(_ca, _a0, _a1, _a2, _a3) + _ca = append(_ca, ifaceVal, channel, protocol, v) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for HandleOutgoingEvent") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}, channels.Channel, insecure.Protocol, uint32, ...flow.Identifier) error); ok { - r0 = rf(_a0, _a1, _a2, _a3, _a4...) + if returnFunc, ok := ret.Get(0).(func(interface{}, channels.Channel, insecure.Protocol, uint32, ...flow.Identifier) error); ok { + r0 = returnFunc(ifaceVal, channel, protocol, v, identifiers...) } else { r0 = ret.Error(0) } - return r0 } -// NewEgressController creates a new instance of EgressController. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEgressController(t interface { - mock.TestingT - Cleanup(func()) -}) *EgressController { - mock := &EgressController{} - mock.Mock.Test(t) +// EgressController_HandleOutgoingEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleOutgoingEvent' +type EgressController_HandleOutgoingEvent_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// HandleOutgoingEvent is a helper method to define mock.On call +// - ifaceVal interface{} +// - channel channels.Channel +// - protocol insecure.Protocol +// - v uint32 +// - identifiers ...flow.Identifier +func (_e *EgressController_Expecter) HandleOutgoingEvent(ifaceVal interface{}, channel interface{}, protocol interface{}, v interface{}, identifiers ...interface{}) *EgressController_HandleOutgoingEvent_Call { + return &EgressController_HandleOutgoingEvent_Call{Call: _e.mock.On("HandleOutgoingEvent", + append([]interface{}{ifaceVal, channel, protocol, v}, identifiers...)...)} +} - return mock +func (_c *EgressController_HandleOutgoingEvent_Call) Run(run func(ifaceVal interface{}, channel channels.Channel, protocol insecure.Protocol, v uint32, identifiers ...flow.Identifier)) *EgressController_HandleOutgoingEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 interface{} + if args[0] != nil { + arg0 = args[0].(interface{}) + } + var arg1 channels.Channel + if args[1] != nil { + arg1 = args[1].(channels.Channel) + } + var arg2 insecure.Protocol + if args[2] != nil { + arg2 = args[2].(insecure.Protocol) + } + var arg3 uint32 + if args[3] != nil { + arg3 = args[3].(uint32) + } + var arg4 []flow.Identifier + variadicArgs := make([]flow.Identifier, len(args)-4) + for i, a := range args[4:] { + if a != nil { + variadicArgs[i] = a.(flow.Identifier) + } + } + arg4 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3, + arg4..., + ) + }) + return _c +} + +func (_c *EgressController_HandleOutgoingEvent_Call) Return(err error) *EgressController_HandleOutgoingEvent_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EgressController_HandleOutgoingEvent_Call) RunAndReturn(run func(ifaceVal interface{}, channel channels.Channel, protocol insecure.Protocol, v uint32, identifiers ...flow.Identifier) error) *EgressController_HandleOutgoingEvent_Call { + _c.Call.Return(run) + return _c } diff --git a/insecure/mock/ingress_controller.go b/insecure/mock/ingress_controller.go index 8cdf1c0ab3d..4b4038c2b04 100644 --- a/insecure/mock/ingress_controller.go +++ b/insecure/mock/ingress_controller.go @@ -1,47 +1,101 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" ) +// NewIngressController creates a new instance of IngressController. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIngressController(t interface { + mock.TestingT + Cleanup(func()) +}) *IngressController { + mock := &IngressController{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IngressController is an autogenerated mock type for the IngressController type type IngressController struct { mock.Mock } -// HandleIncomingEvent provides a mock function with given fields: _a0, _a1, _a2 -func (_m *IngressController) HandleIncomingEvent(_a0 interface{}, _a1 channels.Channel, _a2 flow.Identifier) bool { - ret := _m.Called(_a0, _a1, _a2) +type IngressController_Expecter struct { + mock *mock.Mock +} + +func (_m *IngressController) EXPECT() *IngressController_Expecter { + return &IngressController_Expecter{mock: &_m.Mock} +} + +// HandleIncomingEvent provides a mock function for the type IngressController +func (_mock *IngressController) HandleIncomingEvent(ifaceVal interface{}, channel channels.Channel, identifier flow.Identifier) bool { + ret := _mock.Called(ifaceVal, channel, identifier) if len(ret) == 0 { panic("no return value specified for HandleIncomingEvent") } var r0 bool - if rf, ok := ret.Get(0).(func(interface{}, channels.Channel, flow.Identifier) bool); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(interface{}, channels.Channel, flow.Identifier) bool); ok { + r0 = returnFunc(ifaceVal, channel, identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewIngressController creates a new instance of IngressController. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIngressController(t interface { - mock.TestingT - Cleanup(func()) -}) *IngressController { - mock := &IngressController{} - mock.Mock.Test(t) +// IngressController_HandleIncomingEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleIncomingEvent' +type IngressController_HandleIncomingEvent_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// HandleIncomingEvent is a helper method to define mock.On call +// - ifaceVal interface{} +// - channel channels.Channel +// - identifier flow.Identifier +func (_e *IngressController_Expecter) HandleIncomingEvent(ifaceVal interface{}, channel interface{}, identifier interface{}) *IngressController_HandleIncomingEvent_Call { + return &IngressController_HandleIncomingEvent_Call{Call: _e.mock.On("HandleIncomingEvent", ifaceVal, channel, identifier)} +} - return mock +func (_c *IngressController_HandleIncomingEvent_Call) Run(run func(ifaceVal interface{}, channel channels.Channel, identifier flow.Identifier)) *IngressController_HandleIncomingEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 interface{} + if args[0] != nil { + arg0 = args[0].(interface{}) + } + var arg1 channels.Channel + if args[1] != nil { + arg1 = args[1].(channels.Channel) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *IngressController_HandleIncomingEvent_Call) Return(b bool) *IngressController_HandleIncomingEvent_Call { + _c.Call.Return(b) + return _c +} + +func (_c *IngressController_HandleIncomingEvent_Call) RunAndReturn(run func(ifaceVal interface{}, channel channels.Channel, identifier flow.Identifier) bool) *IngressController_HandleIncomingEvent_Call { + _c.Call.Return(run) + return _c } diff --git a/insecure/mock/orchestrator_network.go b/insecure/mock/orchestrator_network.go index 760bbe7a9d1..3686aadb34a 100644 --- a/insecure/mock/orchestrator_network.go +++ b/insecure/mock/orchestrator_network.go @@ -1,115 +1,312 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - insecure "github.com/onflow/flow-go/insecure" - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/onflow/flow-go/insecure" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewOrchestratorNetwork creates a new instance of OrchestratorNetwork. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewOrchestratorNetwork(t interface { + mock.TestingT + Cleanup(func()) +}) *OrchestratorNetwork { + mock := &OrchestratorNetwork{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // OrchestratorNetwork is an autogenerated mock type for the OrchestratorNetwork type type OrchestratorNetwork struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *OrchestratorNetwork) Done() <-chan struct{} { - ret := _m.Called() +type OrchestratorNetwork_Expecter struct { + mock *mock.Mock +} + +func (_m *OrchestratorNetwork) EXPECT() *OrchestratorNetwork_Expecter { + return &OrchestratorNetwork_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type OrchestratorNetwork +func (_mock *OrchestratorNetwork) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Observe provides a mock function with given fields: _a0 -func (_m *OrchestratorNetwork) Observe(_a0 *insecure.Message) { - _m.Called(_a0) +// OrchestratorNetwork_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type OrchestratorNetwork_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *OrchestratorNetwork_Expecter) Done() *OrchestratorNetwork_Done_Call { + return &OrchestratorNetwork_Done_Call{Call: _e.mock.On("Done")} } -// Ready provides a mock function with no fields -func (_m *OrchestratorNetwork) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *OrchestratorNetwork_Done_Call) Run(run func()) *OrchestratorNetwork_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OrchestratorNetwork_Done_Call) Return(valCh <-chan struct{}) *OrchestratorNetwork_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *OrchestratorNetwork_Done_Call) RunAndReturn(run func() <-chan struct{}) *OrchestratorNetwork_Done_Call { + _c.Call.Return(run) + return _c +} + +// Observe provides a mock function for the type OrchestratorNetwork +func (_mock *OrchestratorNetwork) Observe(message *insecure.Message) { + _mock.Called(message) + return +} + +// OrchestratorNetwork_Observe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Observe' +type OrchestratorNetwork_Observe_Call struct { + *mock.Call +} + +// Observe is a helper method to define mock.On call +// - message *insecure.Message +func (_e *OrchestratorNetwork_Expecter) Observe(message interface{}) *OrchestratorNetwork_Observe_Call { + return &OrchestratorNetwork_Observe_Call{Call: _e.mock.On("Observe", message)} +} + +func (_c *OrchestratorNetwork_Observe_Call) Run(run func(message *insecure.Message)) *OrchestratorNetwork_Observe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *insecure.Message + if args[0] != nil { + arg0 = args[0].(*insecure.Message) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *OrchestratorNetwork_Observe_Call) Return() *OrchestratorNetwork_Observe_Call { + _c.Call.Return() + return _c +} + +func (_c *OrchestratorNetwork_Observe_Call) RunAndReturn(run func(message *insecure.Message)) *OrchestratorNetwork_Observe_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type OrchestratorNetwork +func (_mock *OrchestratorNetwork) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// SendEgress provides a mock function with given fields: _a0 -func (_m *OrchestratorNetwork) SendEgress(_a0 *insecure.EgressEvent) error { - ret := _m.Called(_a0) +// OrchestratorNetwork_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type OrchestratorNetwork_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *OrchestratorNetwork_Expecter) Ready() *OrchestratorNetwork_Ready_Call { + return &OrchestratorNetwork_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *OrchestratorNetwork_Ready_Call) Run(run func()) *OrchestratorNetwork_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OrchestratorNetwork_Ready_Call) Return(valCh <-chan struct{}) *OrchestratorNetwork_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *OrchestratorNetwork_Ready_Call) RunAndReturn(run func() <-chan struct{}) *OrchestratorNetwork_Ready_Call { + _c.Call.Return(run) + return _c +} + +// SendEgress provides a mock function for the type OrchestratorNetwork +func (_mock *OrchestratorNetwork) SendEgress(egressEvent *insecure.EgressEvent) error { + ret := _mock.Called(egressEvent) if len(ret) == 0 { panic("no return value specified for SendEgress") } var r0 error - if rf, ok := ret.Get(0).(func(*insecure.EgressEvent) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*insecure.EgressEvent) error); ok { + r0 = returnFunc(egressEvent) } else { r0 = ret.Error(0) } - return r0 } -// SendIngress provides a mock function with given fields: _a0 -func (_m *OrchestratorNetwork) SendIngress(_a0 *insecure.IngressEvent) error { - ret := _m.Called(_a0) +// OrchestratorNetwork_SendEgress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendEgress' +type OrchestratorNetwork_SendEgress_Call struct { + *mock.Call +} + +// SendEgress is a helper method to define mock.On call +// - egressEvent *insecure.EgressEvent +func (_e *OrchestratorNetwork_Expecter) SendEgress(egressEvent interface{}) *OrchestratorNetwork_SendEgress_Call { + return &OrchestratorNetwork_SendEgress_Call{Call: _e.mock.On("SendEgress", egressEvent)} +} + +func (_c *OrchestratorNetwork_SendEgress_Call) Run(run func(egressEvent *insecure.EgressEvent)) *OrchestratorNetwork_SendEgress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *insecure.EgressEvent + if args[0] != nil { + arg0 = args[0].(*insecure.EgressEvent) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *OrchestratorNetwork_SendEgress_Call) Return(err error) *OrchestratorNetwork_SendEgress_Call { + _c.Call.Return(err) + return _c +} + +func (_c *OrchestratorNetwork_SendEgress_Call) RunAndReturn(run func(egressEvent *insecure.EgressEvent) error) *OrchestratorNetwork_SendEgress_Call { + _c.Call.Return(run) + return _c +} + +// SendIngress provides a mock function for the type OrchestratorNetwork +func (_mock *OrchestratorNetwork) SendIngress(ingressEvent *insecure.IngressEvent) error { + ret := _mock.Called(ingressEvent) if len(ret) == 0 { panic("no return value specified for SendIngress") } var r0 error - if rf, ok := ret.Get(0).(func(*insecure.IngressEvent) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*insecure.IngressEvent) error); ok { + r0 = returnFunc(ingressEvent) } else { r0 = ret.Error(0) } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *OrchestratorNetwork) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// OrchestratorNetwork_SendIngress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendIngress' +type OrchestratorNetwork_SendIngress_Call struct { + *mock.Call } -// NewOrchestratorNetwork creates a new instance of OrchestratorNetwork. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewOrchestratorNetwork(t interface { - mock.TestingT - Cleanup(func()) -}) *OrchestratorNetwork { - mock := &OrchestratorNetwork{} - mock.Mock.Test(t) +// SendIngress is a helper method to define mock.On call +// - ingressEvent *insecure.IngressEvent +func (_e *OrchestratorNetwork_Expecter) SendIngress(ingressEvent interface{}) *OrchestratorNetwork_SendIngress_Call { + return &OrchestratorNetwork_SendIngress_Call{Call: _e.mock.On("SendIngress", ingressEvent)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *OrchestratorNetwork_SendIngress_Call) Run(run func(ingressEvent *insecure.IngressEvent)) *OrchestratorNetwork_SendIngress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *insecure.IngressEvent + if args[0] != nil { + arg0 = args[0].(*insecure.IngressEvent) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *OrchestratorNetwork_SendIngress_Call) Return(err error) *OrchestratorNetwork_SendIngress_Call { + _c.Call.Return(err) + return _c +} + +func (_c *OrchestratorNetwork_SendIngress_Call) RunAndReturn(run func(ingressEvent *insecure.IngressEvent) error) *OrchestratorNetwork_SendIngress_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type OrchestratorNetwork +func (_mock *OrchestratorNetwork) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// OrchestratorNetwork_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type OrchestratorNetwork_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *OrchestratorNetwork_Expecter) Start(signalerContext interface{}) *OrchestratorNetwork_Start_Call { + return &OrchestratorNetwork_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *OrchestratorNetwork_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *OrchestratorNetwork_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *OrchestratorNetwork_Start_Call) Return() *OrchestratorNetwork_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *OrchestratorNetwork_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *OrchestratorNetwork_Start_Call { + _c.Run(run) + return _c } diff --git a/integration/benchmark/load/load_type_test.go b/integration/benchmark/load/load_type_test.go index d40385c87b6..26e66aeef2e 100644 --- a/integration/benchmark/load/load_type_test.go +++ b/integration/benchmark/load/load_type_test.go @@ -140,6 +140,7 @@ func bootstrapVM(t *testing.T, chain flow.Chain) (*fvm.VirtualMachine, fvm.Conte chain.ChainID(), false, false, + false, ) opts = append(opts, fvm.WithTransactionFeesEnabled(true), @@ -150,7 +151,7 @@ func bootstrapVM(t *testing.T, chain flow.Chain) (*fvm.VirtualMachine, fvm.Conte fvm.WithBlockHeader(block1.ToHeader()), ) - ctx := fvm.NewContext(opts...) + ctx := fvm.NewContext(chain, opts...) vm := fvm.NewVirtualMachine() snapshotTree := snapshot.NewSnapshotTree(nil) @@ -311,7 +312,7 @@ func (t *TestAccountLoader) Load( t.snapshot.Lock() defer t.snapshot.Unlock() - acc, err := fvm.GetAccount(t.ctx, flow.ConvertAddress(address), t.snapshot) + acc, err := fvm.GetAccount(t.ctx, flow.Address(address), t.snapshot) if err != nil { return nil, wrapErr(err) } diff --git a/integration/benchmark/load/token_transfer_load.go b/integration/benchmark/load/token_transfer_load.go index 703b013900b..132dd059b87 100644 --- a/integration/benchmark/load/token_transfer_load.go +++ b/integration/benchmark/load/token_transfer_load.go @@ -54,7 +54,7 @@ func (l *TokenTransferLoad) Load(log zerolog.Logger, lc LoadContext) error { // if no accounts are available, just send to the service account destinationAddress = sc.FlowServiceAccount.Address } else { - destinationAddress = flow.ConvertAddress(acc2.Address) + destinationAddress = flow.Address(acc2.Address) lc.ReturnAvailableAccount(acc2) } diff --git a/integration/benchmark/load/token_transfer_multiple_load.go b/integration/benchmark/load/token_transfer_multiple_load.go index 05bd4d6ca5b..2744eafd796 100644 --- a/integration/benchmark/load/token_transfer_multiple_load.go +++ b/integration/benchmark/load/token_transfer_multiple_load.go @@ -65,7 +65,7 @@ func (l *TokenTransferMultiLoad) Load(log zerolog.Logger, lc LoadContext) error l.destinationAddresses = apply( destinationSDKAddresses, func(a flowsdk.Address) flow.Address { - return flow.ConvertAddress(a) + return flow.Address(a) }) }) // get another account to send tokens to diff --git a/integration/benchmark/mock/client.go b/integration/benchmark/mock/client.go index 718c0d70cd0..3f342ce301d 100644 --- a/integration/benchmark/mock/client.go +++ b/integration/benchmark/mock/client.go @@ -1,44 +1,92 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cadence "github.com/onflow/cadence" - access "github.com/onflow/flow-go-sdk/access" - - context "context" - - flow "github.com/onflow/flow-go-sdk" + "context" + "github.com/onflow/cadence" + "github.com/onflow/flow-go-sdk" + "github.com/onflow/flow-go-sdk/access" mock "github.com/stretchr/testify/mock" ) +// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewClient(t interface { + mock.TestingT + Cleanup(func()) +}) *Client { + mock := &Client{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Client is an autogenerated mock type for the Client type type Client struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *Client) Close() error { - ret := _m.Called() +type Client_Expecter struct { + mock *mock.Mock +} + +func (_m *Client) EXPECT() *Client_Expecter { + return &Client_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type Client +func (_mock *Client) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// ExecuteScriptAtBlockHeight provides a mock function with given fields: ctx, height, script, arguments -func (_m *Client) ExecuteScriptAtBlockHeight(ctx context.Context, height uint64, script []byte, arguments []cadence.Value) (cadence.Value, error) { - ret := _m.Called(ctx, height, script, arguments) +// Client_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type Client_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *Client_Expecter) Close() *Client_Close_Call { + return &Client_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *Client_Close_Call) Run(run func()) *Client_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Client_Close_Call) Return(err error) *Client_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Client_Close_Call) RunAndReturn(run func() error) *Client_Close_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtBlockHeight provides a mock function for the type Client +func (_mock *Client) ExecuteScriptAtBlockHeight(ctx context.Context, height uint64, script []byte, arguments []cadence.Value) (cadence.Value, error) { + ret := _mock.Called(ctx, height, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockHeight") @@ -46,29 +94,79 @@ func (_m *Client) ExecuteScriptAtBlockHeight(ctx context.Context, height uint64, var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, []byte, []cadence.Value) (cadence.Value, error)); ok { - return rf(ctx, height, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, []byte, []cadence.Value) (cadence.Value, error)); ok { + return returnFunc(ctx, height, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, []byte, []cadence.Value) cadence.Value); ok { - r0 = rf(ctx, height, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, []byte, []cadence.Value) cadence.Value); ok { + r0 = returnFunc(ctx, height, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, []byte, []cadence.Value) error); ok { - r1 = rf(ctx, height, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, []byte, []cadence.Value) error); ok { + r1 = returnFunc(ctx, height, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtBlockID provides a mock function with given fields: ctx, blockID, script, arguments -func (_m *Client) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Identifier, script []byte, arguments []cadence.Value) (cadence.Value, error) { - ret := _m.Called(ctx, blockID, script, arguments) +// Client_ExecuteScriptAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockHeight' +type Client_ExecuteScriptAtBlockHeight_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - height uint64 +// - script []byte +// - arguments []cadence.Value +func (_e *Client_Expecter) ExecuteScriptAtBlockHeight(ctx interface{}, height interface{}, script interface{}, arguments interface{}) *Client_ExecuteScriptAtBlockHeight_Call { + return &Client_ExecuteScriptAtBlockHeight_Call{Call: _e.mock.On("ExecuteScriptAtBlockHeight", ctx, height, script, arguments)} +} + +func (_c *Client_ExecuteScriptAtBlockHeight_Call) Run(run func(ctx context.Context, height uint64, script []byte, arguments []cadence.Value)) *Client_ExecuteScriptAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 []cadence.Value + if args[3] != nil { + arg3 = args[3].([]cadence.Value) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Client_ExecuteScriptAtBlockHeight_Call) Return(value cadence.Value, err error) *Client_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Client_ExecuteScriptAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, height uint64, script []byte, arguments []cadence.Value) (cadence.Value, error)) *Client_ExecuteScriptAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtBlockID provides a mock function for the type Client +func (_mock *Client) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Identifier, script []byte, arguments []cadence.Value) (cadence.Value, error) { + ret := _mock.Called(ctx, blockID, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -76,29 +174,79 @@ func (_m *Client) ExecuteScriptAtBlockID(ctx context.Context, blockID flow.Ident var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) (cadence.Value, error)); ok { - return rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) (cadence.Value, error)); ok { + return returnFunc(ctx, blockID, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) cadence.Value); ok { - r0 = rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) cadence.Value); ok { + r0 = returnFunc(ctx, blockID, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, []cadence.Value) error); ok { - r1 = rf(ctx, blockID, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, []cadence.Value) error); ok { + r1 = returnFunc(ctx, blockID, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtLatestBlock provides a mock function with given fields: ctx, script, arguments -func (_m *Client) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, arguments []cadence.Value) (cadence.Value, error) { - ret := _m.Called(ctx, script, arguments) +// Client_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type Client_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - script []byte +// - arguments []cadence.Value +func (_e *Client_Expecter) ExecuteScriptAtBlockID(ctx interface{}, blockID interface{}, script interface{}, arguments interface{}) *Client_ExecuteScriptAtBlockID_Call { + return &Client_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", ctx, blockID, script, arguments)} +} + +func (_c *Client_ExecuteScriptAtBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier, script []byte, arguments []cadence.Value)) *Client_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 []cadence.Value + if args[3] != nil { + arg3 = args[3].([]cadence.Value) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Client_ExecuteScriptAtBlockID_Call) Return(value cadence.Value, err error) *Client_ExecuteScriptAtBlockID_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Client_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, script []byte, arguments []cadence.Value) (cadence.Value, error)) *Client_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtLatestBlock provides a mock function for the type Client +func (_mock *Client) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, arguments []cadence.Value) (cadence.Value, error) { + ret := _mock.Called(ctx, script, arguments) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtLatestBlock") @@ -106,29 +254,73 @@ func (_m *Client) ExecuteScriptAtLatestBlock(ctx context.Context, script []byte, var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) (cadence.Value, error)); ok { - return rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) (cadence.Value, error)); ok { + return returnFunc(ctx, script, arguments) } - if rf, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) cadence.Value); ok { - r0 = rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) cadence.Value); ok { + r0 = returnFunc(ctx, script, arguments) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, []cadence.Value) error); ok { - r1 = rf(ctx, script, arguments) + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, []cadence.Value) error); ok { + r1 = returnFunc(ctx, script, arguments) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccount provides a mock function with given fields: ctx, address -func (_m *Client) GetAccount(ctx context.Context, address flow.Address) (*flow.Account, error) { - ret := _m.Called(ctx, address) +// Client_ExecuteScriptAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtLatestBlock' +type Client_ExecuteScriptAtLatestBlock_Call struct { + *mock.Call +} + +// ExecuteScriptAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - script []byte +// - arguments []cadence.Value +func (_e *Client_Expecter) ExecuteScriptAtLatestBlock(ctx interface{}, script interface{}, arguments interface{}) *Client_ExecuteScriptAtLatestBlock_Call { + return &Client_ExecuteScriptAtLatestBlock_Call{Call: _e.mock.On("ExecuteScriptAtLatestBlock", ctx, script, arguments)} +} + +func (_c *Client_ExecuteScriptAtLatestBlock_Call) Run(run func(ctx context.Context, script []byte, arguments []cadence.Value)) *Client_ExecuteScriptAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 []cadence.Value + if args[2] != nil { + arg2 = args[2].([]cadence.Value) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_ExecuteScriptAtLatestBlock_Call) Return(value cadence.Value, err error) *Client_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Client_ExecuteScriptAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, script []byte, arguments []cadence.Value) (cadence.Value, error)) *Client_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccount provides a mock function for the type Client +func (_mock *Client) GetAccount(ctx context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -136,29 +328,67 @@ func (_m *Client) GetAccount(ctx context.Context, address flow.Address) (*flow.A var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockHeight provides a mock function with given fields: ctx, address, blockHeight -func (_m *Client) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, blockHeight uint64) (*flow.Account, error) { - ret := _m.Called(ctx, address, blockHeight) +// Client_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type Client_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *Client_Expecter) GetAccount(ctx interface{}, address interface{}) *Client_GetAccount_Call { + return &Client_GetAccount_Call{Call: _e.mock.On("GetAccount", ctx, address)} +} + +func (_c *Client_GetAccount_Call) Run(run func(ctx context.Context, address flow.Address)) *Client_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetAccount_Call) Return(account *flow.Account, err error) *Client_GetAccount_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *Client_GetAccount_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (*flow.Account, error)) *Client_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockHeight provides a mock function for the type Client +func (_mock *Client) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, blockHeight uint64) (*flow.Account, error) { + ret := _mock.Called(ctx, address, blockHeight) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockHeight") @@ -166,29 +396,73 @@ func (_m *Client) GetAccountAtBlockHeight(ctx context.Context, address flow.Addr var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { - return rf(ctx, address, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { + return returnFunc(ctx, address, blockHeight) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { - r0 = rf(ctx, address, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { + r0 = returnFunc(ctx, address, blockHeight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, blockHeight) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, blockHeight) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *Client) GetAccountAtLatestBlock(ctx context.Context, address flow.Address) (*flow.Account, error) { - ret := _m.Called(ctx, address) +// Client_GetAccountAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockHeight' +type Client_GetAccountAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - blockHeight uint64 +func (_e *Client_Expecter) GetAccountAtBlockHeight(ctx interface{}, address interface{}, blockHeight interface{}) *Client_GetAccountAtBlockHeight_Call { + return &Client_GetAccountAtBlockHeight_Call{Call: _e.mock.On("GetAccountAtBlockHeight", ctx, address, blockHeight)} +} + +func (_c *Client_GetAccountAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, blockHeight uint64)) *Client_GetAccountAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetAccountAtBlockHeight_Call) Return(account *flow.Account, err error) *Client_GetAccountAtBlockHeight_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *Client_GetAccountAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, blockHeight uint64) (*flow.Account, error)) *Client_GetAccountAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtLatestBlock provides a mock function for the type Client +func (_mock *Client) GetAccountAtLatestBlock(ctx context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountAtLatestBlock") @@ -196,29 +470,67 @@ func (_m *Client) GetAccountAtLatestBlock(ctx context.Context, address flow.Addr var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtBlockHeight provides a mock function with given fields: ctx, address, blockHeight -func (_m *Client) GetAccountBalanceAtBlockHeight(ctx context.Context, address flow.Address, blockHeight uint64) (uint64, error) { - ret := _m.Called(ctx, address, blockHeight) +// Client_GetAccountAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtLatestBlock' +type Client_GetAccountAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *Client_Expecter) GetAccountAtLatestBlock(ctx interface{}, address interface{}) *Client_GetAccountAtLatestBlock_Call { + return &Client_GetAccountAtLatestBlock_Call{Call: _e.mock.On("GetAccountAtLatestBlock", ctx, address)} +} + +func (_c *Client_GetAccountAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *Client_GetAccountAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetAccountAtLatestBlock_Call) Return(account *flow.Account, err error) *Client_GetAccountAtLatestBlock_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *Client_GetAccountAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (*flow.Account, error)) *Client_GetAccountAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtBlockHeight provides a mock function for the type Client +func (_mock *Client) GetAccountBalanceAtBlockHeight(ctx context.Context, address flow.Address, blockHeight uint64) (uint64, error) { + ret := _mock.Called(ctx, address, blockHeight) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtBlockHeight") @@ -226,27 +538,71 @@ func (_m *Client) GetAccountBalanceAtBlockHeight(ctx context.Context, address fl var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { - return rf(ctx, address, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { + return returnFunc(ctx, address, blockHeight) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { - r0 = rf(ctx, address, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { + r0 = returnFunc(ctx, address, blockHeight) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, blockHeight) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, blockHeight) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalanceAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *Client) GetAccountBalanceAtLatestBlock(ctx context.Context, address flow.Address) (uint64, error) { - ret := _m.Called(ctx, address) +// Client_GetAccountBalanceAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtBlockHeight' +type Client_GetAccountBalanceAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountBalanceAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - blockHeight uint64 +func (_e *Client_Expecter) GetAccountBalanceAtBlockHeight(ctx interface{}, address interface{}, blockHeight interface{}) *Client_GetAccountBalanceAtBlockHeight_Call { + return &Client_GetAccountBalanceAtBlockHeight_Call{Call: _e.mock.On("GetAccountBalanceAtBlockHeight", ctx, address, blockHeight)} +} + +func (_c *Client_GetAccountBalanceAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, blockHeight uint64)) *Client_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetAccountBalanceAtBlockHeight_Call) Return(v uint64, err error) *Client_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Client_GetAccountBalanceAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, blockHeight uint64) (uint64, error)) *Client_GetAccountBalanceAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalanceAtLatestBlock provides a mock function for the type Client +func (_mock *Client) GetAccountBalanceAtLatestBlock(ctx context.Context, address flow.Address) (uint64, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountBalanceAtLatestBlock") @@ -254,27 +610,65 @@ func (_m *Client) GetAccountBalanceAtLatestBlock(ctx context.Context, address fl var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (uint64, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (uint64, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) uint64); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) uint64); ok { + r0 = returnFunc(ctx, address) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtBlockHeight provides a mock function with given fields: ctx, address, keyIndex, height -func (_m *Client) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountKey, error) { - ret := _m.Called(ctx, address, keyIndex, height) +// Client_GetAccountBalanceAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalanceAtLatestBlock' +type Client_GetAccountBalanceAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountBalanceAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *Client_Expecter) GetAccountBalanceAtLatestBlock(ctx interface{}, address interface{}) *Client_GetAccountBalanceAtLatestBlock_Call { + return &Client_GetAccountBalanceAtLatestBlock_Call{Call: _e.mock.On("GetAccountBalanceAtLatestBlock", ctx, address)} +} + +func (_c *Client_GetAccountBalanceAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *Client_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetAccountBalanceAtLatestBlock_Call) Return(v uint64, err error) *Client_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Client_GetAccountBalanceAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) (uint64, error)) *Client_GetAccountBalanceAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtBlockHeight provides a mock function for the type Client +func (_mock *Client) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountKey, error) { + ret := _mock.Called(ctx, address, keyIndex, height) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtBlockHeight") @@ -282,29 +676,79 @@ func (_m *Client) GetAccountKeyAtBlockHeight(ctx context.Context, address flow.A var r0 *flow.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountKey, error)); ok { - return rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountKey, error)); ok { + return returnFunc(ctx, address, keyIndex, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountKey); ok { - r0 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountKey); ok { + r0 = returnFunc(ctx, address, keyIndex, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { - r1 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { + r1 = returnFunc(ctx, address, keyIndex, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeyAtLatestBlock provides a mock function with given fields: ctx, address, keyIndex -func (_m *Client) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountKey, error) { - ret := _m.Called(ctx, address, keyIndex) +// Client_GetAccountKeyAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtBlockHeight' +type Client_GetAccountKeyAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeyAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - keyIndex uint32 +// - height uint64 +func (_e *Client_Expecter) GetAccountKeyAtBlockHeight(ctx interface{}, address interface{}, keyIndex interface{}, height interface{}) *Client_GetAccountKeyAtBlockHeight_Call { + return &Client_GetAccountKeyAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeyAtBlockHeight", ctx, address, keyIndex, height)} +} + +func (_c *Client_GetAccountKeyAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64)) *Client_GetAccountKeyAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Client_GetAccountKeyAtBlockHeight_Call) Return(accountKey *flow.AccountKey, err error) *Client_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(accountKey, err) + return _c +} + +func (_c *Client_GetAccountKeyAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountKey, error)) *Client_GetAccountKeyAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeyAtLatestBlock provides a mock function for the type Client +func (_mock *Client) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountKey, error) { + ret := _mock.Called(ctx, address, keyIndex) if len(ret) == 0 { panic("no return value specified for GetAccountKeyAtLatestBlock") @@ -312,29 +756,73 @@ func (_m *Client) GetAccountKeyAtLatestBlock(ctx context.Context, address flow.A var r0 *flow.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) (*flow.AccountKey, error)); ok { - return rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) (*flow.AccountKey, error)); ok { + return returnFunc(ctx, address, keyIndex) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) *flow.AccountKey); ok { - r0 = rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32) *flow.AccountKey); ok { + r0 = returnFunc(ctx, address, keyIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32) error); ok { - r1 = rf(ctx, address, keyIndex) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32) error); ok { + r1 = returnFunc(ctx, address, keyIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *Client) GetAccountKeysAtBlockHeight(ctx context.Context, address flow.Address, height uint64) ([]*flow.AccountKey, error) { - ret := _m.Called(ctx, address, height) +// Client_GetAccountKeyAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeyAtLatestBlock' +type Client_GetAccountKeyAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeyAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - keyIndex uint32 +func (_e *Client_Expecter) GetAccountKeyAtLatestBlock(ctx interface{}, address interface{}, keyIndex interface{}) *Client_GetAccountKeyAtLatestBlock_Call { + return &Client_GetAccountKeyAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeyAtLatestBlock", ctx, address, keyIndex)} +} + +func (_c *Client_GetAccountKeyAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address, keyIndex uint32)) *Client_GetAccountKeyAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetAccountKeyAtLatestBlock_Call) Return(accountKey *flow.AccountKey, err error) *Client_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(accountKey, err) + return _c +} + +func (_c *Client_GetAccountKeyAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, keyIndex uint32) (*flow.AccountKey, error)) *Client_GetAccountKeyAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtBlockHeight provides a mock function for the type Client +func (_mock *Client) GetAccountKeysAtBlockHeight(ctx context.Context, address flow.Address, height uint64) ([]*flow.AccountKey, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtBlockHeight") @@ -342,29 +830,73 @@ func (_m *Client) GetAccountKeysAtBlockHeight(ctx context.Context, address flow. var r0 []*flow.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]*flow.AccountKey, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]*flow.AccountKey, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []*flow.AccountKey); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []*flow.AccountKey); ok { + r0 = returnFunc(ctx, address, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.AccountKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeysAtLatestBlock provides a mock function with given fields: ctx, address -func (_m *Client) GetAccountKeysAtLatestBlock(ctx context.Context, address flow.Address) ([]*flow.AccountKey, error) { - ret := _m.Called(ctx, address) +// Client_GetAccountKeysAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtBlockHeight' +type Client_GetAccountKeysAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountKeysAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *Client_Expecter) GetAccountKeysAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *Client_GetAccountKeysAtBlockHeight_Call { + return &Client_GetAccountKeysAtBlockHeight_Call{Call: _e.mock.On("GetAccountKeysAtBlockHeight", ctx, address, height)} +} + +func (_c *Client_GetAccountKeysAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *Client_GetAccountKeysAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetAccountKeysAtBlockHeight_Call) Return(accountKeys []*flow.AccountKey, err error) *Client_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(accountKeys, err) + return _c +} + +func (_c *Client_GetAccountKeysAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) ([]*flow.AccountKey, error)) *Client_GetAccountKeysAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeysAtLatestBlock provides a mock function for the type Client +func (_mock *Client) GetAccountKeysAtLatestBlock(ctx context.Context, address flow.Address) ([]*flow.AccountKey, error) { + ret := _mock.Called(ctx, address) if len(ret) == 0 { panic("no return value specified for GetAccountKeysAtLatestBlock") @@ -372,29 +904,67 @@ func (_m *Client) GetAccountKeysAtLatestBlock(ctx context.Context, address flow. var r0 []*flow.AccountKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) ([]*flow.AccountKey, error)); ok { - return rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) ([]*flow.AccountKey, error)); ok { + return returnFunc(ctx, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) []*flow.AccountKey); ok { - r0 = rf(ctx, address) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) []*flow.AccountKey); ok { + r0 = returnFunc(ctx, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.AccountKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(ctx, address) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(ctx, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockByHeight provides a mock function with given fields: ctx, height -func (_m *Client) GetBlockByHeight(ctx context.Context, height uint64) (*flow.Block, error) { - ret := _m.Called(ctx, height) +// Client_GetAccountKeysAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeysAtLatestBlock' +type Client_GetAccountKeysAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountKeysAtLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +func (_e *Client_Expecter) GetAccountKeysAtLatestBlock(ctx interface{}, address interface{}) *Client_GetAccountKeysAtLatestBlock_Call { + return &Client_GetAccountKeysAtLatestBlock_Call{Call: _e.mock.On("GetAccountKeysAtLatestBlock", ctx, address)} +} + +func (_c *Client_GetAccountKeysAtLatestBlock_Call) Run(run func(ctx context.Context, address flow.Address)) *Client_GetAccountKeysAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetAccountKeysAtLatestBlock_Call) Return(accountKeys []*flow.AccountKey, err error) *Client_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(accountKeys, err) + return _c +} + +func (_c *Client_GetAccountKeysAtLatestBlock_Call) RunAndReturn(run func(ctx context.Context, address flow.Address) ([]*flow.AccountKey, error)) *Client_GetAccountKeysAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByHeight provides a mock function for the type Client +func (_mock *Client) GetBlockByHeight(ctx context.Context, height uint64) (*flow.Block, error) { + ret := _mock.Called(ctx, height) if len(ret) == 0 { panic("no return value specified for GetBlockByHeight") @@ -402,29 +972,67 @@ func (_m *Client) GetBlockByHeight(ctx context.Context, height uint64) (*flow.Bl var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Block, error)); ok { - return rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Block, error)); ok { + return returnFunc(ctx, height) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.Block); ok { - r0 = rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.Block); ok { + r0 = returnFunc(ctx, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockByID provides a mock function with given fields: ctx, blockID -func (_m *Client) GetBlockByID(ctx context.Context, blockID flow.Identifier) (*flow.Block, error) { - ret := _m.Called(ctx, blockID) +// Client_GetBlockByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByHeight' +type Client_GetBlockByHeight_Call struct { + *mock.Call +} + +// GetBlockByHeight is a helper method to define mock.On call +// - ctx context.Context +// - height uint64 +func (_e *Client_Expecter) GetBlockByHeight(ctx interface{}, height interface{}) *Client_GetBlockByHeight_Call { + return &Client_GetBlockByHeight_Call{Call: _e.mock.On("GetBlockByHeight", ctx, height)} +} + +func (_c *Client_GetBlockByHeight_Call) Run(run func(ctx context.Context, height uint64)) *Client_GetBlockByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetBlockByHeight_Call) Return(block *flow.Block, err error) *Client_GetBlockByHeight_Call { + _c.Call.Return(block, err) + return _c +} + +func (_c *Client_GetBlockByHeight_Call) RunAndReturn(run func(ctx context.Context, height uint64) (*flow.Block, error)) *Client_GetBlockByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockByID provides a mock function for the type Client +func (_mock *Client) GetBlockByID(ctx context.Context, blockID flow.Identifier) (*flow.Block, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetBlockByID") @@ -432,29 +1040,67 @@ func (_m *Client) GetBlockByID(ctx context.Context, blockID flow.Identifier) (*f var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Block, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Block, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Block); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Block); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByHeight provides a mock function with given fields: ctx, height -func (_m *Client) GetBlockHeaderByHeight(ctx context.Context, height uint64) (*flow.BlockHeader, error) { - ret := _m.Called(ctx, height) +// Client_GetBlockByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockByID' +type Client_GetBlockByID_Call struct { + *mock.Call +} + +// GetBlockByID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetBlockByID(ctx interface{}, blockID interface{}) *Client_GetBlockByID_Call { + return &Client_GetBlockByID_Call{Call: _e.mock.On("GetBlockByID", ctx, blockID)} +} + +func (_c *Client_GetBlockByID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetBlockByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetBlockByID_Call) Return(block *flow.Block, err error) *Client_GetBlockByID_Call { + _c.Call.Return(block, err) + return _c +} + +func (_c *Client_GetBlockByID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*flow.Block, error)) *Client_GetBlockByID_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByHeight provides a mock function for the type Client +func (_mock *Client) GetBlockHeaderByHeight(ctx context.Context, height uint64) (*flow.BlockHeader, error) { + ret := _mock.Called(ctx, height) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByHeight") @@ -462,29 +1108,67 @@ func (_m *Client) GetBlockHeaderByHeight(ctx context.Context, height uint64) (*f var r0 *flow.BlockHeader var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*flow.BlockHeader, error)); ok { - return rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.BlockHeader, error)); ok { + return returnFunc(ctx, height) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *flow.BlockHeader); ok { - r0 = rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.BlockHeader); ok { + r0 = returnFunc(ctx, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.BlockHeader) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlockHeaderByID provides a mock function with given fields: ctx, blockID -func (_m *Client) GetBlockHeaderByID(ctx context.Context, blockID flow.Identifier) (*flow.BlockHeader, error) { - ret := _m.Called(ctx, blockID) +// Client_GetBlockHeaderByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByHeight' +type Client_GetBlockHeaderByHeight_Call struct { + *mock.Call +} + +// GetBlockHeaderByHeight is a helper method to define mock.On call +// - ctx context.Context +// - height uint64 +func (_e *Client_Expecter) GetBlockHeaderByHeight(ctx interface{}, height interface{}) *Client_GetBlockHeaderByHeight_Call { + return &Client_GetBlockHeaderByHeight_Call{Call: _e.mock.On("GetBlockHeaderByHeight", ctx, height)} +} + +func (_c *Client_GetBlockHeaderByHeight_Call) Run(run func(ctx context.Context, height uint64)) *Client_GetBlockHeaderByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetBlockHeaderByHeight_Call) Return(blockHeader *flow.BlockHeader, err error) *Client_GetBlockHeaderByHeight_Call { + _c.Call.Return(blockHeader, err) + return _c +} + +func (_c *Client_GetBlockHeaderByHeight_Call) RunAndReturn(run func(ctx context.Context, height uint64) (*flow.BlockHeader, error)) *Client_GetBlockHeaderByHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetBlockHeaderByID provides a mock function for the type Client +func (_mock *Client) GetBlockHeaderByID(ctx context.Context, blockID flow.Identifier) (*flow.BlockHeader, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetBlockHeaderByID") @@ -492,59 +1176,135 @@ func (_m *Client) GetBlockHeaderByID(ctx context.Context, blockID flow.Identifie var r0 *flow.BlockHeader var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.BlockHeader, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.BlockHeader, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.BlockHeader); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.BlockHeader); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.BlockHeader) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCollection provides a mock function with given fields: ctx, colID -func (_m *Client) GetCollection(ctx context.Context, colID flow.Identifier) (*flow.Collection, error) { - ret := _m.Called(ctx, colID) +// Client_GetBlockHeaderByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeaderByID' +type Client_GetBlockHeaderByID_Call struct { + *mock.Call +} - if len(ret) == 0 { +// GetBlockHeaderByID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetBlockHeaderByID(ctx interface{}, blockID interface{}) *Client_GetBlockHeaderByID_Call { + return &Client_GetBlockHeaderByID_Call{Call: _e.mock.On("GetBlockHeaderByID", ctx, blockID)} +} + +func (_c *Client_GetBlockHeaderByID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetBlockHeaderByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetBlockHeaderByID_Call) Return(blockHeader *flow.BlockHeader, err error) *Client_GetBlockHeaderByID_Call { + _c.Call.Return(blockHeader, err) + return _c +} + +func (_c *Client_GetBlockHeaderByID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*flow.BlockHeader, error)) *Client_GetBlockHeaderByID_Call { + _c.Call.Return(run) + return _c +} + +// GetCollection provides a mock function for the type Client +func (_mock *Client) GetCollection(ctx context.Context, colID flow.Identifier) (*flow.Collection, error) { + ret := _mock.Called(ctx, colID) + + if len(ret) == 0 { panic("no return value specified for GetCollection") } var r0 *flow.Collection var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Collection, error)); ok { - return rf(ctx, colID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Collection, error)); ok { + return returnFunc(ctx, colID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Collection); ok { - r0 = rf(ctx, colID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Collection); ok { + r0 = returnFunc(ctx, colID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Collection) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, colID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, colID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCollectionByID provides a mock function with given fields: ctx, id -func (_m *Client) GetCollectionByID(ctx context.Context, id flow.Identifier) (*flow.Collection, error) { - ret := _m.Called(ctx, id) +// Client_GetCollection_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCollection' +type Client_GetCollection_Call struct { + *mock.Call +} + +// GetCollection is a helper method to define mock.On call +// - ctx context.Context +// - colID flow.Identifier +func (_e *Client_Expecter) GetCollection(ctx interface{}, colID interface{}) *Client_GetCollection_Call { + return &Client_GetCollection_Call{Call: _e.mock.On("GetCollection", ctx, colID)} +} + +func (_c *Client_GetCollection_Call) Run(run func(ctx context.Context, colID flow.Identifier)) *Client_GetCollection_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetCollection_Call) Return(collection *flow.Collection, err error) *Client_GetCollection_Call { + _c.Call.Return(collection, err) + return _c +} + +func (_c *Client_GetCollection_Call) RunAndReturn(run func(ctx context.Context, colID flow.Identifier) (*flow.Collection, error)) *Client_GetCollection_Call { + _c.Call.Return(run) + return _c +} + +// GetCollectionByID provides a mock function for the type Client +func (_mock *Client) GetCollectionByID(ctx context.Context, id flow.Identifier) (*flow.Collection, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetCollectionByID") @@ -552,29 +1312,67 @@ func (_m *Client) GetCollectionByID(ctx context.Context, id flow.Identifier) (*f var r0 *flow.Collection var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Collection, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Collection, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Collection); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Collection); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Collection) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForBlockIDs provides a mock function with given fields: ctx, eventType, blockIDs -func (_m *Client) GetEventsForBlockIDs(ctx context.Context, eventType string, blockIDs []flow.Identifier) ([]flow.BlockEvents, error) { - ret := _m.Called(ctx, eventType, blockIDs) +// Client_GetCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCollectionByID' +type Client_GetCollectionByID_Call struct { + *mock.Call +} + +// GetCollectionByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *Client_Expecter) GetCollectionByID(ctx interface{}, id interface{}) *Client_GetCollectionByID_Call { + return &Client_GetCollectionByID_Call{Call: _e.mock.On("GetCollectionByID", ctx, id)} +} + +func (_c *Client_GetCollectionByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *Client_GetCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetCollectionByID_Call) Return(collection *flow.Collection, err error) *Client_GetCollectionByID_Call { + _c.Call.Return(collection, err) + return _c +} + +func (_c *Client_GetCollectionByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.Collection, error)) *Client_GetCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForBlockIDs provides a mock function for the type Client +func (_mock *Client) GetEventsForBlockIDs(ctx context.Context, eventType string, blockIDs []flow.Identifier) ([]flow.BlockEvents, error) { + ret := _mock.Called(ctx, eventType, blockIDs) if len(ret) == 0 { panic("no return value specified for GetEventsForBlockIDs") @@ -582,29 +1380,73 @@ func (_m *Client) GetEventsForBlockIDs(ctx context.Context, eventType string, bl var r0 []flow.BlockEvents var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier) ([]flow.BlockEvents, error)); ok { - return rf(ctx, eventType, blockIDs) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier) ([]flow.BlockEvents, error)); ok { + return returnFunc(ctx, eventType, blockIDs) } - if rf, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier) []flow.BlockEvents); ok { - r0 = rf(ctx, eventType, blockIDs) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, []flow.Identifier) []flow.BlockEvents); ok { + r0 = returnFunc(ctx, eventType, blockIDs) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.BlockEvents) } } - - if rf, ok := ret.Get(1).(func(context.Context, string, []flow.Identifier) error); ok { - r1 = rf(ctx, eventType, blockIDs) + if returnFunc, ok := ret.Get(1).(func(context.Context, string, []flow.Identifier) error); ok { + r1 = returnFunc(ctx, eventType, blockIDs) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetEventsForHeightRange provides a mock function with given fields: ctx, eventType, startHeight, endHeight -func (_m *Client) GetEventsForHeightRange(ctx context.Context, eventType string, startHeight uint64, endHeight uint64) ([]flow.BlockEvents, error) { - ret := _m.Called(ctx, eventType, startHeight, endHeight) +// Client_GetEventsForBlockIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForBlockIDs' +type Client_GetEventsForBlockIDs_Call struct { + *mock.Call +} + +// GetEventsForBlockIDs is a helper method to define mock.On call +// - ctx context.Context +// - eventType string +// - blockIDs []flow.Identifier +func (_e *Client_Expecter) GetEventsForBlockIDs(ctx interface{}, eventType interface{}, blockIDs interface{}) *Client_GetEventsForBlockIDs_Call { + return &Client_GetEventsForBlockIDs_Call{Call: _e.mock.On("GetEventsForBlockIDs", ctx, eventType, blockIDs)} +} + +func (_c *Client_GetEventsForBlockIDs_Call) Run(run func(ctx context.Context, eventType string, blockIDs []flow.Identifier)) *Client_GetEventsForBlockIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 []flow.Identifier + if args[2] != nil { + arg2 = args[2].([]flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetEventsForBlockIDs_Call) Return(blockEventss []flow.BlockEvents, err error) *Client_GetEventsForBlockIDs_Call { + _c.Call.Return(blockEventss, err) + return _c +} + +func (_c *Client_GetEventsForBlockIDs_Call) RunAndReturn(run func(ctx context.Context, eventType string, blockIDs []flow.Identifier) ([]flow.BlockEvents, error)) *Client_GetEventsForBlockIDs_Call { + _c.Call.Return(run) + return _c +} + +// GetEventsForHeightRange provides a mock function for the type Client +func (_mock *Client) GetEventsForHeightRange(ctx context.Context, eventType string, startHeight uint64, endHeight uint64) ([]flow.BlockEvents, error) { + ret := _mock.Called(ctx, eventType, startHeight, endHeight) if len(ret) == 0 { panic("no return value specified for GetEventsForHeightRange") @@ -612,29 +1454,79 @@ func (_m *Client) GetEventsForHeightRange(ctx context.Context, eventType string, var r0 []flow.BlockEvents var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, uint64) ([]flow.BlockEvents, error)); ok { - return rf(ctx, eventType, startHeight, endHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint64, uint64) ([]flow.BlockEvents, error)); ok { + return returnFunc(ctx, eventType, startHeight, endHeight) } - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, uint64) []flow.BlockEvents); ok { - r0 = rf(ctx, eventType, startHeight, endHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, string, uint64, uint64) []flow.BlockEvents); ok { + r0 = returnFunc(ctx, eventType, startHeight, endHeight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.BlockEvents) } } - - if rf, ok := ret.Get(1).(func(context.Context, string, uint64, uint64) error); ok { - r1 = rf(ctx, eventType, startHeight, endHeight) + if returnFunc, ok := ret.Get(1).(func(context.Context, string, uint64, uint64) error); ok { + r1 = returnFunc(ctx, eventType, startHeight, endHeight) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionDataByBlockID provides a mock function with given fields: ctx, blockID -func (_m *Client) GetExecutionDataByBlockID(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionData, error) { - ret := _m.Called(ctx, blockID) +// Client_GetEventsForHeightRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEventsForHeightRange' +type Client_GetEventsForHeightRange_Call struct { + *mock.Call +} + +// GetEventsForHeightRange is a helper method to define mock.On call +// - ctx context.Context +// - eventType string +// - startHeight uint64 +// - endHeight uint64 +func (_e *Client_Expecter) GetEventsForHeightRange(ctx interface{}, eventType interface{}, startHeight interface{}, endHeight interface{}) *Client_GetEventsForHeightRange_Call { + return &Client_GetEventsForHeightRange_Call{Call: _e.mock.On("GetEventsForHeightRange", ctx, eventType, startHeight, endHeight)} +} + +func (_c *Client_GetEventsForHeightRange_Call) Run(run func(ctx context.Context, eventType string, startHeight uint64, endHeight uint64)) *Client_GetEventsForHeightRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Client_GetEventsForHeightRange_Call) Return(blockEventss []flow.BlockEvents, err error) *Client_GetEventsForHeightRange_Call { + _c.Call.Return(blockEventss, err) + return _c +} + +func (_c *Client_GetEventsForHeightRange_Call) RunAndReturn(run func(ctx context.Context, eventType string, startHeight uint64, endHeight uint64) ([]flow.BlockEvents, error)) *Client_GetEventsForHeightRange_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionDataByBlockID provides a mock function for the type Client +func (_mock *Client) GetExecutionDataByBlockID(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionData, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetExecutionDataByBlockID") @@ -642,29 +1534,67 @@ func (_m *Client) GetExecutionDataByBlockID(ctx context.Context, blockID flow.Id var r0 *flow.ExecutionData var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionData, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionData, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionData); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionData); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionData) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionResultByID provides a mock function with given fields: ctx, id -func (_m *Client) GetExecutionResultByID(ctx context.Context, id flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(ctx, id) +// Client_GetExecutionDataByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionDataByBlockID' +type Client_GetExecutionDataByBlockID_Call struct { + *mock.Call +} + +// GetExecutionDataByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetExecutionDataByBlockID(ctx interface{}, blockID interface{}) *Client_GetExecutionDataByBlockID_Call { + return &Client_GetExecutionDataByBlockID_Call{Call: _e.mock.On("GetExecutionDataByBlockID", ctx, blockID)} +} + +func (_c *Client_GetExecutionDataByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetExecutionDataByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetExecutionDataByBlockID_Call) Return(executionData *flow.ExecutionData, err error) *Client_GetExecutionDataByBlockID_Call { + _c.Call.Return(executionData, err) + return _c +} + +func (_c *Client_GetExecutionDataByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionData, error)) *Client_GetExecutionDataByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultByID provides a mock function for the type Client +func (_mock *Client) GetExecutionResultByID(ctx context.Context, id flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetExecutionResultByID") @@ -672,29 +1602,67 @@ func (_m *Client) GetExecutionResultByID(ctx context.Context, id flow.Identifier var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionResultForBlockID provides a mock function with given fields: ctx, blockID -func (_m *Client) GetExecutionResultForBlockID(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(ctx, blockID) +// Client_GetExecutionResultByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultByID' +type Client_GetExecutionResultByID_Call struct { + *mock.Call +} + +// GetExecutionResultByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *Client_Expecter) GetExecutionResultByID(ctx interface{}, id interface{}) *Client_GetExecutionResultByID_Call { + return &Client_GetExecutionResultByID_Call{Call: _e.mock.On("GetExecutionResultByID", ctx, id)} +} + +func (_c *Client_GetExecutionResultByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *Client_GetExecutionResultByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetExecutionResultByID_Call) Return(executionResult *flow.ExecutionResult, err error) *Client_GetExecutionResultByID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *Client_GetExecutionResultByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.ExecutionResult, error)) *Client_GetExecutionResultByID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionResultForBlockID provides a mock function for the type Client +func (_mock *Client) GetExecutionResultForBlockID(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetExecutionResultForBlockID") @@ -702,29 +1670,67 @@ func (_m *Client) GetExecutionResultForBlockID(ctx context.Context, blockID flow var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetFullCollectionByID provides a mock function with given fields: ctx, id -func (_m *Client) GetFullCollectionByID(ctx context.Context, id flow.Identifier) (*flow.FullCollection, error) { - ret := _m.Called(ctx, id) +// Client_GetExecutionResultForBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionResultForBlockID' +type Client_GetExecutionResultForBlockID_Call struct { + *mock.Call +} + +// GetExecutionResultForBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetExecutionResultForBlockID(ctx interface{}, blockID interface{}) *Client_GetExecutionResultForBlockID_Call { + return &Client_GetExecutionResultForBlockID_Call{Call: _e.mock.On("GetExecutionResultForBlockID", ctx, blockID)} +} + +func (_c *Client_GetExecutionResultForBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetExecutionResultForBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetExecutionResultForBlockID_Call) Return(executionResult *flow.ExecutionResult, err error) *Client_GetExecutionResultForBlockID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *Client_GetExecutionResultForBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*flow.ExecutionResult, error)) *Client_GetExecutionResultForBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetFullCollectionByID provides a mock function for the type Client +func (_mock *Client) GetFullCollectionByID(ctx context.Context, id flow.Identifier) (*flow.FullCollection, error) { + ret := _mock.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for GetFullCollectionByID") @@ -732,29 +1738,67 @@ func (_m *Client) GetFullCollectionByID(ctx context.Context, id flow.Identifier) var r0 *flow.FullCollection var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.FullCollection, error)); ok { - return rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.FullCollection, error)); ok { + return returnFunc(ctx, id) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.FullCollection); ok { - r0 = rf(ctx, id) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.FullCollection); ok { + r0 = returnFunc(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.FullCollection) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, id) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, id) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlock provides a mock function with given fields: ctx, isSealed -func (_m *Client) GetLatestBlock(ctx context.Context, isSealed bool) (*flow.Block, error) { - ret := _m.Called(ctx, isSealed) +// Client_GetFullCollectionByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFullCollectionByID' +type Client_GetFullCollectionByID_Call struct { + *mock.Call +} + +// GetFullCollectionByID is a helper method to define mock.On call +// - ctx context.Context +// - id flow.Identifier +func (_e *Client_Expecter) GetFullCollectionByID(ctx interface{}, id interface{}) *Client_GetFullCollectionByID_Call { + return &Client_GetFullCollectionByID_Call{Call: _e.mock.On("GetFullCollectionByID", ctx, id)} +} + +func (_c *Client_GetFullCollectionByID_Call) Run(run func(ctx context.Context, id flow.Identifier)) *Client_GetFullCollectionByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetFullCollectionByID_Call) Return(fullCollection *flow.FullCollection, err error) *Client_GetFullCollectionByID_Call { + _c.Call.Return(fullCollection, err) + return _c +} + +func (_c *Client_GetFullCollectionByID_Call) RunAndReturn(run func(ctx context.Context, id flow.Identifier) (*flow.FullCollection, error)) *Client_GetFullCollectionByID_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlock provides a mock function for the type Client +func (_mock *Client) GetLatestBlock(ctx context.Context, isSealed bool) (*flow.Block, error) { + ret := _mock.Called(ctx, isSealed) if len(ret) == 0 { panic("no return value specified for GetLatestBlock") @@ -762,29 +1806,67 @@ func (_m *Client) GetLatestBlock(ctx context.Context, isSealed bool) (*flow.Bloc var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(context.Context, bool) (*flow.Block, error)); ok { - return rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) (*flow.Block, error)); ok { + return returnFunc(ctx, isSealed) } - if rf, ok := ret.Get(0).(func(context.Context, bool) *flow.Block); ok { - r0 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) *flow.Block); ok { + r0 = returnFunc(ctx, isSealed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, bool) error); ok { - r1 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(1).(func(context.Context, bool) error); ok { + r1 = returnFunc(ctx, isSealed) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlockHeader provides a mock function with given fields: ctx, isSealed -func (_m *Client) GetLatestBlockHeader(ctx context.Context, isSealed bool) (*flow.BlockHeader, error) { - ret := _m.Called(ctx, isSealed) +// Client_GetLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlock' +type Client_GetLatestBlock_Call struct { + *mock.Call +} + +// GetLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - isSealed bool +func (_e *Client_Expecter) GetLatestBlock(ctx interface{}, isSealed interface{}) *Client_GetLatestBlock_Call { + return &Client_GetLatestBlock_Call{Call: _e.mock.On("GetLatestBlock", ctx, isSealed)} +} + +func (_c *Client_GetLatestBlock_Call) Run(run func(ctx context.Context, isSealed bool)) *Client_GetLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetLatestBlock_Call) Return(block *flow.Block, err error) *Client_GetLatestBlock_Call { + _c.Call.Return(block, err) + return _c +} + +func (_c *Client_GetLatestBlock_Call) RunAndReturn(run func(ctx context.Context, isSealed bool) (*flow.Block, error)) *Client_GetLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlockHeader provides a mock function for the type Client +func (_mock *Client) GetLatestBlockHeader(ctx context.Context, isSealed bool) (*flow.BlockHeader, error) { + ret := _mock.Called(ctx, isSealed) if len(ret) == 0 { panic("no return value specified for GetLatestBlockHeader") @@ -792,29 +1874,67 @@ func (_m *Client) GetLatestBlockHeader(ctx context.Context, isSealed bool) (*flo var r0 *flow.BlockHeader var r1 error - if rf, ok := ret.Get(0).(func(context.Context, bool) (*flow.BlockHeader, error)); ok { - return rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) (*flow.BlockHeader, error)); ok { + return returnFunc(ctx, isSealed) } - if rf, ok := ret.Get(0).(func(context.Context, bool) *flow.BlockHeader); ok { - r0 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) *flow.BlockHeader); ok { + r0 = returnFunc(ctx, isSealed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.BlockHeader) } } - - if rf, ok := ret.Get(1).(func(context.Context, bool) error); ok { - r1 = rf(ctx, isSealed) + if returnFunc, ok := ret.Get(1).(func(context.Context, bool) error); ok { + r1 = returnFunc(ctx, isSealed) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestProtocolStateSnapshot provides a mock function with given fields: ctx -func (_m *Client) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, error) { - ret := _m.Called(ctx) +// Client_GetLatestBlockHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlockHeader' +type Client_GetLatestBlockHeader_Call struct { + *mock.Call +} + +// GetLatestBlockHeader is a helper method to define mock.On call +// - ctx context.Context +// - isSealed bool +func (_e *Client_Expecter) GetLatestBlockHeader(ctx interface{}, isSealed interface{}) *Client_GetLatestBlockHeader_Call { + return &Client_GetLatestBlockHeader_Call{Call: _e.mock.On("GetLatestBlockHeader", ctx, isSealed)} +} + +func (_c *Client_GetLatestBlockHeader_Call) Run(run func(ctx context.Context, isSealed bool)) *Client_GetLatestBlockHeader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetLatestBlockHeader_Call) Return(blockHeader *flow.BlockHeader, err error) *Client_GetLatestBlockHeader_Call { + _c.Call.Return(blockHeader, err) + return _c +} + +func (_c *Client_GetLatestBlockHeader_Call) RunAndReturn(run func(ctx context.Context, isSealed bool) (*flow.BlockHeader, error)) *Client_GetLatestBlockHeader_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestProtocolStateSnapshot provides a mock function for the type Client +func (_mock *Client) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for GetLatestProtocolStateSnapshot") @@ -822,29 +1942,61 @@ func (_m *Client) GetLatestProtocolStateSnapshot(ctx context.Context) ([]byte, e var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context) ([]byte, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) ([]byte, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) []byte); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) []byte); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetNetworkParameters provides a mock function with given fields: ctx -func (_m *Client) GetNetworkParameters(ctx context.Context) (*flow.NetworkParameters, error) { - ret := _m.Called(ctx) +// Client_GetLatestProtocolStateSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestProtocolStateSnapshot' +type Client_GetLatestProtocolStateSnapshot_Call struct { + *mock.Call +} + +// GetLatestProtocolStateSnapshot is a helper method to define mock.On call +// - ctx context.Context +func (_e *Client_Expecter) GetLatestProtocolStateSnapshot(ctx interface{}) *Client_GetLatestProtocolStateSnapshot_Call { + return &Client_GetLatestProtocolStateSnapshot_Call{Call: _e.mock.On("GetLatestProtocolStateSnapshot", ctx)} +} + +func (_c *Client_GetLatestProtocolStateSnapshot_Call) Run(run func(ctx context.Context)) *Client_GetLatestProtocolStateSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Client_GetLatestProtocolStateSnapshot_Call) Return(bytes []byte, err error) *Client_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Client_GetLatestProtocolStateSnapshot_Call) RunAndReturn(run func(ctx context.Context) ([]byte, error)) *Client_GetLatestProtocolStateSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// GetNetworkParameters provides a mock function for the type Client +func (_mock *Client) GetNetworkParameters(ctx context.Context) (*flow.NetworkParameters, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for GetNetworkParameters") @@ -852,29 +2004,61 @@ func (_m *Client) GetNetworkParameters(ctx context.Context) (*flow.NetworkParame var r0 *flow.NetworkParameters var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*flow.NetworkParameters, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) (*flow.NetworkParameters, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) *flow.NetworkParameters); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) *flow.NetworkParameters); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.NetworkParameters) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetNodeVersionInfo provides a mock function with given fields: ctx -func (_m *Client) GetNodeVersionInfo(ctx context.Context) (*flow.NodeVersionInfo, error) { - ret := _m.Called(ctx) +// Client_GetNetworkParameters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNetworkParameters' +type Client_GetNetworkParameters_Call struct { + *mock.Call +} + +// GetNetworkParameters is a helper method to define mock.On call +// - ctx context.Context +func (_e *Client_Expecter) GetNetworkParameters(ctx interface{}) *Client_GetNetworkParameters_Call { + return &Client_GetNetworkParameters_Call{Call: _e.mock.On("GetNetworkParameters", ctx)} +} + +func (_c *Client_GetNetworkParameters_Call) Run(run func(ctx context.Context)) *Client_GetNetworkParameters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Client_GetNetworkParameters_Call) Return(networkParameters *flow.NetworkParameters, err error) *Client_GetNetworkParameters_Call { + _c.Call.Return(networkParameters, err) + return _c +} + +func (_c *Client_GetNetworkParameters_Call) RunAndReturn(run func(ctx context.Context) (*flow.NetworkParameters, error)) *Client_GetNetworkParameters_Call { + _c.Call.Return(run) + return _c +} + +// GetNodeVersionInfo provides a mock function for the type Client +func (_mock *Client) GetNodeVersionInfo(ctx context.Context) (*flow.NodeVersionInfo, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for GetNodeVersionInfo") @@ -882,29 +2066,61 @@ func (_m *Client) GetNodeVersionInfo(ctx context.Context) (*flow.NodeVersionInfo var r0 *flow.NodeVersionInfo var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*flow.NodeVersionInfo, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) (*flow.NodeVersionInfo, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) *flow.NodeVersionInfo); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) *flow.NodeVersionInfo); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.NodeVersionInfo) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByBlockID provides a mock function with given fields: ctx, blockID -func (_m *Client) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID flow.Identifier) ([]byte, error) { - ret := _m.Called(ctx, blockID) +// Client_GetNodeVersionInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNodeVersionInfo' +type Client_GetNodeVersionInfo_Call struct { + *mock.Call +} + +// GetNodeVersionInfo is a helper method to define mock.On call +// - ctx context.Context +func (_e *Client_Expecter) GetNodeVersionInfo(ctx interface{}) *Client_GetNodeVersionInfo_Call { + return &Client_GetNodeVersionInfo_Call{Call: _e.mock.On("GetNodeVersionInfo", ctx)} +} + +func (_c *Client_GetNodeVersionInfo_Call) Run(run func(ctx context.Context)) *Client_GetNodeVersionInfo_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Client_GetNodeVersionInfo_Call) Return(nodeVersionInfo *flow.NodeVersionInfo, err error) *Client_GetNodeVersionInfo_Call { + _c.Call.Return(nodeVersionInfo, err) + return _c +} + +func (_c *Client_GetNodeVersionInfo_Call) RunAndReturn(run func(ctx context.Context) (*flow.NodeVersionInfo, error)) *Client_GetNodeVersionInfo_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByBlockID provides a mock function for the type Client +func (_mock *Client) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID flow.Identifier) ([]byte, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByBlockID") @@ -912,29 +2128,67 @@ func (_m *Client) GetProtocolStateSnapshotByBlockID(ctx context.Context, blockID var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]byte, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]byte, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []byte); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []byte); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetProtocolStateSnapshotByHeight provides a mock function with given fields: ctx, blockHeight -func (_m *Client) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHeight uint64) ([]byte, error) { - ret := _m.Called(ctx, blockHeight) +// Client_GetProtocolStateSnapshotByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByBlockID' +type Client_GetProtocolStateSnapshotByBlockID_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetProtocolStateSnapshotByBlockID(ctx interface{}, blockID interface{}) *Client_GetProtocolStateSnapshotByBlockID_Call { + return &Client_GetProtocolStateSnapshotByBlockID_Call{Call: _e.mock.On("GetProtocolStateSnapshotByBlockID", ctx, blockID)} +} + +func (_c *Client_GetProtocolStateSnapshotByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetProtocolStateSnapshotByBlockID_Call) Return(bytes []byte, err error) *Client_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Client_GetProtocolStateSnapshotByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]byte, error)) *Client_GetProtocolStateSnapshotByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateSnapshotByHeight provides a mock function for the type Client +func (_mock *Client) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHeight uint64) ([]byte, error) { + ret := _mock.Called(ctx, blockHeight) if len(ret) == 0 { panic("no return value specified for GetProtocolStateSnapshotByHeight") @@ -942,29 +2196,203 @@ func (_m *Client) GetProtocolStateSnapshotByHeight(ctx context.Context, blockHei var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) ([]byte, error)); ok { - return rf(ctx, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) ([]byte, error)); ok { + return returnFunc(ctx, blockHeight) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) []byte); ok { - r0 = rf(ctx, blockHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) []byte); ok { + r0 = returnFunc(ctx, blockHeight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, blockHeight) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Client_GetProtocolStateSnapshotByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateSnapshotByHeight' +type Client_GetProtocolStateSnapshotByHeight_Call struct { + *mock.Call +} + +// GetProtocolStateSnapshotByHeight is a helper method to define mock.On call +// - ctx context.Context +// - blockHeight uint64 +func (_e *Client_Expecter) GetProtocolStateSnapshotByHeight(ctx interface{}, blockHeight interface{}) *Client_GetProtocolStateSnapshotByHeight_Call { + return &Client_GetProtocolStateSnapshotByHeight_Call{Call: _e.mock.On("GetProtocolStateSnapshotByHeight", ctx, blockHeight)} +} + +func (_c *Client_GetProtocolStateSnapshotByHeight_Call) Run(run func(ctx context.Context, blockHeight uint64)) *Client_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetProtocolStateSnapshotByHeight_Call) Return(bytes []byte, err error) *Client_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Client_GetProtocolStateSnapshotByHeight_Call) RunAndReturn(run func(ctx context.Context, blockHeight uint64) ([]byte, error)) *Client_GetProtocolStateSnapshotByHeight_Call { + _c.Call.Return(run) + return _c +} - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, blockHeight) +// GetScheduledTransaction provides a mock function for the type Client +func (_mock *Client) GetScheduledTransaction(ctx context.Context, scheduledTxID uint64) (*flow.Transaction, error) { + ret := _mock.Called(ctx, scheduledTxID) + + if len(ret) == 0 { + panic("no return value specified for GetScheduledTransaction") + } + + var r0 *flow.Transaction + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.Transaction, error)); ok { + return returnFunc(ctx, scheduledTxID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.Transaction); ok { + r0 = returnFunc(ctx, scheduledTxID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*flow.Transaction) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, scheduledTxID) } else { r1 = ret.Error(1) } + return r0, r1 +} + +// Client_GetScheduledTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransaction' +type Client_GetScheduledTransaction_Call struct { + *mock.Call +} + +// GetScheduledTransaction is a helper method to define mock.On call +// - ctx context.Context +// - scheduledTxID uint64 +func (_e *Client_Expecter) GetScheduledTransaction(ctx interface{}, scheduledTxID interface{}) *Client_GetScheduledTransaction_Call { + return &Client_GetScheduledTransaction_Call{Call: _e.mock.On("GetScheduledTransaction", ctx, scheduledTxID)} +} + +func (_c *Client_GetScheduledTransaction_Call) Run(run func(ctx context.Context, scheduledTxID uint64)) *Client_GetScheduledTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetScheduledTransaction_Call) Return(transaction *flow.Transaction, err error) *Client_GetScheduledTransaction_Call { + _c.Call.Return(transaction, err) + return _c +} + +func (_c *Client_GetScheduledTransaction_Call) RunAndReturn(run func(ctx context.Context, scheduledTxID uint64) (*flow.Transaction, error)) *Client_GetScheduledTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetScheduledTransactionResult provides a mock function for the type Client +func (_mock *Client) GetScheduledTransactionResult(ctx context.Context, scheduledTxID uint64) (*flow.TransactionResult, error) { + ret := _mock.Called(ctx, scheduledTxID) + + if len(ret) == 0 { + panic("no return value specified for GetScheduledTransactionResult") + } + var r0 *flow.TransactionResult + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*flow.TransactionResult, error)); ok { + return returnFunc(ctx, scheduledTxID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *flow.TransactionResult); ok { + r0 = returnFunc(ctx, scheduledTxID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*flow.TransactionResult) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, scheduledTxID) + } else { + r1 = ret.Error(1) + } return r0, r1 } -// GetSystemTransaction provides a mock function with given fields: ctx, blockID -func (_m *Client) GetSystemTransaction(ctx context.Context, blockID flow.Identifier) (*flow.Transaction, error) { - ret := _m.Called(ctx, blockID) +// Client_GetScheduledTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScheduledTransactionResult' +type Client_GetScheduledTransactionResult_Call struct { + *mock.Call +} + +// GetScheduledTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - scheduledTxID uint64 +func (_e *Client_Expecter) GetScheduledTransactionResult(ctx interface{}, scheduledTxID interface{}) *Client_GetScheduledTransactionResult_Call { + return &Client_GetScheduledTransactionResult_Call{Call: _e.mock.On("GetScheduledTransactionResult", ctx, scheduledTxID)} +} + +func (_c *Client_GetScheduledTransactionResult_Call) Run(run func(ctx context.Context, scheduledTxID uint64)) *Client_GetScheduledTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetScheduledTransactionResult_Call) Return(transactionResult *flow.TransactionResult, err error) *Client_GetScheduledTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *Client_GetScheduledTransactionResult_Call) RunAndReturn(run func(ctx context.Context, scheduledTxID uint64) (*flow.TransactionResult, error)) *Client_GetScheduledTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransaction provides a mock function for the type Client +func (_mock *Client) GetSystemTransaction(ctx context.Context, blockID flow.Identifier) (*flow.Transaction, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetSystemTransaction") @@ -972,29 +2400,67 @@ func (_m *Client) GetSystemTransaction(ctx context.Context, blockID flow.Identif var r0 *flow.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Transaction, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Transaction, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Transaction); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Transaction); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Transaction) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransactionResult provides a mock function with given fields: ctx, blockID -func (_m *Client) GetSystemTransactionResult(ctx context.Context, blockID flow.Identifier) (*flow.TransactionResult, error) { - ret := _m.Called(ctx, blockID) +// Client_GetSystemTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransaction' +type Client_GetSystemTransaction_Call struct { + *mock.Call +} + +// GetSystemTransaction is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetSystemTransaction(ctx interface{}, blockID interface{}) *Client_GetSystemTransaction_Call { + return &Client_GetSystemTransaction_Call{Call: _e.mock.On("GetSystemTransaction", ctx, blockID)} +} + +func (_c *Client_GetSystemTransaction_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetSystemTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetSystemTransaction_Call) Return(transaction *flow.Transaction, err error) *Client_GetSystemTransaction_Call { + _c.Call.Return(transaction, err) + return _c +} + +func (_c *Client_GetSystemTransaction_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*flow.Transaction, error)) *Client_GetSystemTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransactionResult provides a mock function for the type Client +func (_mock *Client) GetSystemTransactionResult(ctx context.Context, blockID flow.Identifier) (*flow.TransactionResult, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetSystemTransactionResult") @@ -1002,29 +2468,67 @@ func (_m *Client) GetSystemTransactionResult(ctx context.Context, blockID flow.I var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionResult, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionResult, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionResult); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionResult); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransactionResultWithID provides a mock function with given fields: ctx, blockID, systemTxID -func (_m *Client) GetSystemTransactionResultWithID(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier) (*flow.TransactionResult, error) { - ret := _m.Called(ctx, blockID, systemTxID) +// Client_GetSystemTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransactionResult' +type Client_GetSystemTransactionResult_Call struct { + *mock.Call +} + +// GetSystemTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetSystemTransactionResult(ctx interface{}, blockID interface{}) *Client_GetSystemTransactionResult_Call { + return &Client_GetSystemTransactionResult_Call{Call: _e.mock.On("GetSystemTransactionResult", ctx, blockID)} +} + +func (_c *Client_GetSystemTransactionResult_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetSystemTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetSystemTransactionResult_Call) Return(transactionResult *flow.TransactionResult, err error) *Client_GetSystemTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *Client_GetSystemTransactionResult_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*flow.TransactionResult, error)) *Client_GetSystemTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransactionResultWithID provides a mock function for the type Client +func (_mock *Client) GetSystemTransactionResultWithID(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier) (*flow.TransactionResult, error) { + ret := _mock.Called(ctx, blockID, systemTxID) if len(ret) == 0 { panic("no return value specified for GetSystemTransactionResultWithID") @@ -1032,29 +2536,73 @@ func (_m *Client) GetSystemTransactionResultWithID(ctx context.Context, blockID var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.TransactionResult, error)); ok { - return rf(ctx, blockID, systemTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.TransactionResult, error)); ok { + return returnFunc(ctx, blockID, systemTxID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.TransactionResult); ok { - r0 = rf(ctx, blockID, systemTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.TransactionResult); ok { + r0 = returnFunc(ctx, blockID, systemTxID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { - r1 = rf(ctx, blockID, systemTxID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID, systemTxID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSystemTransactionWithID provides a mock function with given fields: ctx, blockID, systemTxID -func (_m *Client) GetSystemTransactionWithID(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier) (*flow.Transaction, error) { - ret := _m.Called(ctx, blockID, systemTxID) +// Client_GetSystemTransactionResultWithID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransactionResultWithID' +type Client_GetSystemTransactionResultWithID_Call struct { + *mock.Call +} + +// GetSystemTransactionResultWithID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - systemTxID flow.Identifier +func (_e *Client_Expecter) GetSystemTransactionResultWithID(ctx interface{}, blockID interface{}, systemTxID interface{}) *Client_GetSystemTransactionResultWithID_Call { + return &Client_GetSystemTransactionResultWithID_Call{Call: _e.mock.On("GetSystemTransactionResultWithID", ctx, blockID, systemTxID)} +} + +func (_c *Client_GetSystemTransactionResultWithID_Call) Run(run func(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier)) *Client_GetSystemTransactionResultWithID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetSystemTransactionResultWithID_Call) Return(transactionResult *flow.TransactionResult, err error) *Client_GetSystemTransactionResultWithID_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *Client_GetSystemTransactionResultWithID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier) (*flow.TransactionResult, error)) *Client_GetSystemTransactionResultWithID_Call { + _c.Call.Return(run) + return _c +} + +// GetSystemTransactionWithID provides a mock function for the type Client +func (_mock *Client) GetSystemTransactionWithID(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier) (*flow.Transaction, error) { + ret := _mock.Called(ctx, blockID, systemTxID) if len(ret) == 0 { panic("no return value specified for GetSystemTransactionWithID") @@ -1062,29 +2610,73 @@ func (_m *Client) GetSystemTransactionWithID(ctx context.Context, blockID flow.I var r0 *flow.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.Transaction, error)); ok { - return rf(ctx, blockID, systemTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) (*flow.Transaction, error)); ok { + return returnFunc(ctx, blockID, systemTxID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.Transaction); ok { - r0 = rf(ctx, blockID, systemTxID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.Identifier) *flow.Transaction); ok { + r0 = returnFunc(ctx, blockID, systemTxID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Transaction) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { - r1 = rf(ctx, blockID, systemTxID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID, systemTxID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransaction provides a mock function with given fields: ctx, txID -func (_m *Client) GetTransaction(ctx context.Context, txID flow.Identifier) (*flow.Transaction, error) { - ret := _m.Called(ctx, txID) +// Client_GetSystemTransactionWithID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSystemTransactionWithID' +type Client_GetSystemTransactionWithID_Call struct { + *mock.Call +} + +// GetSystemTransactionWithID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - systemTxID flow.Identifier +func (_e *Client_Expecter) GetSystemTransactionWithID(ctx interface{}, blockID interface{}, systemTxID interface{}) *Client_GetSystemTransactionWithID_Call { + return &Client_GetSystemTransactionWithID_Call{Call: _e.mock.On("GetSystemTransactionWithID", ctx, blockID, systemTxID)} +} + +func (_c *Client_GetSystemTransactionWithID_Call) Run(run func(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier)) *Client_GetSystemTransactionWithID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetSystemTransactionWithID_Call) Return(transaction *flow.Transaction, err error) *Client_GetSystemTransactionWithID_Call { + _c.Call.Return(transaction, err) + return _c +} + +func (_c *Client_GetSystemTransactionWithID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, systemTxID flow.Identifier) (*flow.Transaction, error)) *Client_GetSystemTransactionWithID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransaction provides a mock function for the type Client +func (_mock *Client) GetTransaction(ctx context.Context, txID flow.Identifier) (*flow.Transaction, error) { + ret := _mock.Called(ctx, txID) if len(ret) == 0 { panic("no return value specified for GetTransaction") @@ -1092,29 +2684,67 @@ func (_m *Client) GetTransaction(ctx context.Context, txID flow.Identifier) (*fl var r0 *flow.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Transaction, error)); ok { - return rf(ctx, txID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.Transaction, error)); ok { + return returnFunc(ctx, txID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Transaction); ok { - r0 = rf(ctx, txID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.Transaction); ok { + r0 = returnFunc(ctx, txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Transaction) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, txID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResult provides a mock function with given fields: ctx, txID -func (_m *Client) GetTransactionResult(ctx context.Context, txID flow.Identifier) (*flow.TransactionResult, error) { - ret := _m.Called(ctx, txID) +// Client_GetTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransaction' +type Client_GetTransaction_Call struct { + *mock.Call +} + +// GetTransaction is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +func (_e *Client_Expecter) GetTransaction(ctx interface{}, txID interface{}) *Client_GetTransaction_Call { + return &Client_GetTransaction_Call{Call: _e.mock.On("GetTransaction", ctx, txID)} +} + +func (_c *Client_GetTransaction_Call) Run(run func(ctx context.Context, txID flow.Identifier)) *Client_GetTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetTransaction_Call) Return(transaction *flow.Transaction, err error) *Client_GetTransaction_Call { + _c.Call.Return(transaction, err) + return _c +} + +func (_c *Client_GetTransaction_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier) (*flow.Transaction, error)) *Client_GetTransaction_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResult provides a mock function for the type Client +func (_mock *Client) GetTransactionResult(ctx context.Context, txID flow.Identifier) (*flow.TransactionResult, error) { + ret := _mock.Called(ctx, txID) if len(ret) == 0 { panic("no return value specified for GetTransactionResult") @@ -1122,29 +2752,67 @@ func (_m *Client) GetTransactionResult(ctx context.Context, txID flow.Identifier var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionResult, error)); ok { - return rf(ctx, txID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionResult, error)); ok { + return returnFunc(ctx, txID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionResult); ok { - r0 = rf(ctx, txID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionResult); ok { + r0 = returnFunc(ctx, txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, txID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultByIndex provides a mock function with given fields: ctx, blockID, index -func (_m *Client) GetTransactionResultByIndex(ctx context.Context, blockID flow.Identifier, index uint32) (*flow.TransactionResult, error) { - ret := _m.Called(ctx, blockID, index) +// Client_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type Client_GetTransactionResult_Call struct { + *mock.Call +} + +// GetTransactionResult is a helper method to define mock.On call +// - ctx context.Context +// - txID flow.Identifier +func (_e *Client_Expecter) GetTransactionResult(ctx interface{}, txID interface{}) *Client_GetTransactionResult_Call { + return &Client_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", ctx, txID)} +} + +func (_c *Client_GetTransactionResult_Call) Run(run func(ctx context.Context, txID flow.Identifier)) *Client_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetTransactionResult_Call) Return(transactionResult *flow.TransactionResult, err error) *Client_GetTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *Client_GetTransactionResult_Call) RunAndReturn(run func(ctx context.Context, txID flow.Identifier) (*flow.TransactionResult, error)) *Client_GetTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultByIndex provides a mock function for the type Client +func (_mock *Client) GetTransactionResultByIndex(ctx context.Context, blockID flow.Identifier, index uint32) (*flow.TransactionResult, error) { + ret := _mock.Called(ctx, blockID, index) if len(ret) == 0 { panic("no return value specified for GetTransactionResultByIndex") @@ -1152,29 +2820,73 @@ func (_m *Client) GetTransactionResultByIndex(ctx context.Context, blockID flow. var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32) (*flow.TransactionResult, error)); ok { - return rf(ctx, blockID, index) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32) (*flow.TransactionResult, error)); ok { + return returnFunc(ctx, blockID, index) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32) *flow.TransactionResult); ok { - r0 = rf(ctx, blockID, index) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, uint32) *flow.TransactionResult); ok { + r0 = returnFunc(ctx, blockID, index) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint32) error); ok { - r1 = rf(ctx, blockID, index) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, uint32) error); ok { + r1 = returnFunc(ctx, blockID, index) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResultsByBlockID provides a mock function with given fields: ctx, blockID -func (_m *Client) GetTransactionResultsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionResult, error) { - ret := _m.Called(ctx, blockID) +// Client_GetTransactionResultByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultByIndex' +type Client_GetTransactionResultByIndex_Call struct { + *mock.Call +} + +// GetTransactionResultByIndex is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - index uint32 +func (_e *Client_Expecter) GetTransactionResultByIndex(ctx interface{}, blockID interface{}, index interface{}) *Client_GetTransactionResultByIndex_Call { + return &Client_GetTransactionResultByIndex_Call{Call: _e.mock.On("GetTransactionResultByIndex", ctx, blockID, index)} +} + +func (_c *Client_GetTransactionResultByIndex_Call) Run(run func(ctx context.Context, blockID flow.Identifier, index uint32)) *Client_GetTransactionResultByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_GetTransactionResultByIndex_Call) Return(transactionResult *flow.TransactionResult, err error) *Client_GetTransactionResultByIndex_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *Client_GetTransactionResultByIndex_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, index uint32) (*flow.TransactionResult, error)) *Client_GetTransactionResultByIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResultsByBlockID provides a mock function for the type Client +func (_mock *Client) GetTransactionResultsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionResult, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetTransactionResultsByBlockID") @@ -1182,29 +2894,67 @@ func (_m *Client) GetTransactionResultsByBlockID(ctx context.Context, blockID fl var r0 []*flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.TransactionResult, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.TransactionResult, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.TransactionResult); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.TransactionResult); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionsByBlockID provides a mock function with given fields: ctx, blockID -func (_m *Client) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.Transaction, error) { - ret := _m.Called(ctx, blockID) +// Client_GetTransactionResultsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResultsByBlockID' +type Client_GetTransactionResultsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionResultsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetTransactionResultsByBlockID(ctx interface{}, blockID interface{}) *Client_GetTransactionResultsByBlockID_Call { + return &Client_GetTransactionResultsByBlockID_Call{Call: _e.mock.On("GetTransactionResultsByBlockID", ctx, blockID)} +} + +func (_c *Client_GetTransactionResultsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetTransactionResultsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetTransactionResultsByBlockID_Call) Return(transactionResults []*flow.TransactionResult, err error) *Client_GetTransactionResultsByBlockID_Call { + _c.Call.Return(transactionResults, err) + return _c +} + +func (_c *Client_GetTransactionResultsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]*flow.TransactionResult, error)) *Client_GetTransactionResultsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionsByBlockID provides a mock function for the type Client +func (_mock *Client) GetTransactionsByBlockID(ctx context.Context, blockID flow.Identifier) ([]*flow.Transaction, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for GetTransactionsByBlockID") @@ -1212,47 +2962,118 @@ func (_m *Client) GetTransactionsByBlockID(ctx context.Context, blockID flow.Ide var r0 []*flow.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.Transaction, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) ([]*flow.Transaction, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.Transaction); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) []*flow.Transaction); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.Transaction) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Ping provides a mock function with given fields: ctx -func (_m *Client) Ping(ctx context.Context) error { - ret := _m.Called(ctx) +// Client_GetTransactionsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionsByBlockID' +type Client_GetTransactionsByBlockID_Call struct { + *mock.Call +} + +// GetTransactionsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *Client_Expecter) GetTransactionsByBlockID(ctx interface{}, blockID interface{}) *Client_GetTransactionsByBlockID_Call { + return &Client_GetTransactionsByBlockID_Call{Call: _e.mock.On("GetTransactionsByBlockID", ctx, blockID)} +} + +func (_c *Client_GetTransactionsByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *Client_GetTransactionsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_GetTransactionsByBlockID_Call) Return(transactions []*flow.Transaction, err error) *Client_GetTransactionsByBlockID_Call { + _c.Call.Return(transactions, err) + return _c +} + +func (_c *Client_GetTransactionsByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) ([]*flow.Transaction, error)) *Client_GetTransactionsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Ping provides a mock function for the type Client +func (_mock *Client) Ping(ctx context.Context) error { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for Ping") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Error(0) } - return r0 } -// SendAndSubscribeTransactionStatuses provides a mock function with given fields: ctx, tx -func (_m *Client) SendAndSubscribeTransactionStatuses(ctx context.Context, tx flow.Transaction) (<-chan *flow.TransactionResult, <-chan error, error) { - ret := _m.Called(ctx, tx) +// Client_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping' +type Client_Ping_Call struct { + *mock.Call +} + +// Ping is a helper method to define mock.On call +// - ctx context.Context +func (_e *Client_Expecter) Ping(ctx interface{}) *Client_Ping_Call { + return &Client_Ping_Call{Call: _e.mock.On("Ping", ctx)} +} + +func (_c *Client_Ping_Call) Run(run func(ctx context.Context)) *Client_Ping_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Client_Ping_Call) Return(err error) *Client_Ping_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Client_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *Client_Ping_Call { + _c.Call.Return(run) + return _c +} + +// SendAndSubscribeTransactionStatuses provides a mock function for the type Client +func (_mock *Client) SendAndSubscribeTransactionStatuses(ctx context.Context, tx flow.Transaction) (<-chan *flow.TransactionResult, <-chan error, error) { + ret := _mock.Called(ctx, tx) if len(ret) == 0 { panic("no return value specified for SendAndSubscribeTransactionStatuses") @@ -1261,55 +3082,131 @@ func (_m *Client) SendAndSubscribeTransactionStatuses(ctx context.Context, tx fl var r0 <-chan *flow.TransactionResult var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Transaction) (<-chan *flow.TransactionResult, <-chan error, error)); ok { - return rf(ctx, tx) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Transaction) (<-chan *flow.TransactionResult, <-chan error, error)); ok { + return returnFunc(ctx, tx) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Transaction) <-chan *flow.TransactionResult); ok { - r0 = rf(ctx, tx) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Transaction) <-chan *flow.TransactionResult); ok { + r0 = returnFunc(ctx, tx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Transaction) <-chan error); ok { - r1 = rf(ctx, tx) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Transaction) <-chan error); ok { + r1 = returnFunc(ctx, tx) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Transaction) error); ok { - r2 = rf(ctx, tx) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Transaction) error); ok { + r2 = returnFunc(ctx, tx) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SendTransaction provides a mock function with given fields: ctx, tx -func (_m *Client) SendTransaction(ctx context.Context, tx flow.Transaction) error { - ret := _m.Called(ctx, tx) +// Client_SendAndSubscribeTransactionStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendAndSubscribeTransactionStatuses' +type Client_SendAndSubscribeTransactionStatuses_Call struct { + *mock.Call +} + +// SendAndSubscribeTransactionStatuses is a helper method to define mock.On call +// - ctx context.Context +// - tx flow.Transaction +func (_e *Client_Expecter) SendAndSubscribeTransactionStatuses(ctx interface{}, tx interface{}) *Client_SendAndSubscribeTransactionStatuses_Call { + return &Client_SendAndSubscribeTransactionStatuses_Call{Call: _e.mock.On("SendAndSubscribeTransactionStatuses", ctx, tx)} +} + +func (_c *Client_SendAndSubscribeTransactionStatuses_Call) Run(run func(ctx context.Context, tx flow.Transaction)) *Client_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Transaction + if args[1] != nil { + arg1 = args[1].(flow.Transaction) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SendAndSubscribeTransactionStatuses_Call) Return(transactionResultCh <-chan *flow.TransactionResult, errCh <-chan error, err error) *Client_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(transactionResultCh, errCh, err) + return _c +} + +func (_c *Client_SendAndSubscribeTransactionStatuses_Call) RunAndReturn(run func(ctx context.Context, tx flow.Transaction) (<-chan *flow.TransactionResult, <-chan error, error)) *Client_SendAndSubscribeTransactionStatuses_Call { + _c.Call.Return(run) + return _c +} + +// SendTransaction provides a mock function for the type Client +func (_mock *Client) SendTransaction(ctx context.Context, tx flow.Transaction) error { + ret := _mock.Called(ctx, tx) if len(ret) == 0 { panic("no return value specified for SendTransaction") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Transaction) error); ok { - r0 = rf(ctx, tx) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Transaction) error); ok { + r0 = returnFunc(ctx, tx) } else { r0 = ret.Error(0) } - return r0 } -// SubscribeAccountStatusesFromLatestBlock provides a mock function with given fields: ctx, filter -func (_m *Client) SubscribeAccountStatusesFromLatestBlock(ctx context.Context, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error) { - ret := _m.Called(ctx, filter) +// Client_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' +type Client_SendTransaction_Call struct { + *mock.Call +} + +// SendTransaction is a helper method to define mock.On call +// - ctx context.Context +// - tx flow.Transaction +func (_e *Client_Expecter) SendTransaction(ctx interface{}, tx interface{}) *Client_SendTransaction_Call { + return &Client_SendTransaction_Call{Call: _e.mock.On("SendTransaction", ctx, tx)} +} + +func (_c *Client_SendTransaction_Call) Run(run func(ctx context.Context, tx flow.Transaction)) *Client_SendTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Transaction + if args[1] != nil { + arg1 = args[1].(flow.Transaction) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SendTransaction_Call) Return(err error) *Client_SendTransaction_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Client_SendTransaction_Call) RunAndReturn(run func(ctx context.Context, tx flow.Transaction) error) *Client_SendTransaction_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeAccountStatusesFromLatestBlock provides a mock function for the type Client +func (_mock *Client) SubscribeAccountStatusesFromLatestBlock(ctx context.Context, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error) { + ret := _mock.Called(ctx, filter) if len(ret) == 0 { panic("no return value specified for SubscribeAccountStatusesFromLatestBlock") @@ -1318,37 +3215,74 @@ func (_m *Client) SubscribeAccountStatusesFromLatestBlock(ctx context.Context, f var r0 <-chan *flow.AccountStatus var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)); ok { - return rf(ctx, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)); ok { + return returnFunc(ctx, filter) } - if rf, ok := ret.Get(0).(func(context.Context, flow.AccountStatusFilter) <-chan *flow.AccountStatus); ok { - r0 = rf(ctx, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.AccountStatusFilter) <-chan *flow.AccountStatus); ok { + r0 = returnFunc(ctx, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.AccountStatus) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.AccountStatusFilter) <-chan error); ok { - r1 = rf(ctx, filter) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.AccountStatusFilter) <-chan error); ok { + r1 = returnFunc(ctx, filter) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.AccountStatusFilter) error); ok { - r2 = rf(ctx, filter) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.AccountStatusFilter) error); ok { + r2 = returnFunc(ctx, filter) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeAccountStatusesFromStartBlockID provides a mock function with given fields: ctx, startBlockID, filter -func (_m *Client) SubscribeAccountStatusesFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error) { - ret := _m.Called(ctx, startBlockID, filter) +// Client_SubscribeAccountStatusesFromLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeAccountStatusesFromLatestBlock' +type Client_SubscribeAccountStatusesFromLatestBlock_Call struct { + *mock.Call +} + +// SubscribeAccountStatusesFromLatestBlock is a helper method to define mock.On call +// - ctx context.Context +// - filter flow.AccountStatusFilter +func (_e *Client_Expecter) SubscribeAccountStatusesFromLatestBlock(ctx interface{}, filter interface{}) *Client_SubscribeAccountStatusesFromLatestBlock_Call { + return &Client_SubscribeAccountStatusesFromLatestBlock_Call{Call: _e.mock.On("SubscribeAccountStatusesFromLatestBlock", ctx, filter)} +} + +func (_c *Client_SubscribeAccountStatusesFromLatestBlock_Call) Run(run func(ctx context.Context, filter flow.AccountStatusFilter)) *Client_SubscribeAccountStatusesFromLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.AccountStatusFilter + if args[1] != nil { + arg1 = args[1].(flow.AccountStatusFilter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SubscribeAccountStatusesFromLatestBlock_Call) Return(accountStatusCh <-chan *flow.AccountStatus, errCh <-chan error, err error) *Client_SubscribeAccountStatusesFromLatestBlock_Call { + _c.Call.Return(accountStatusCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeAccountStatusesFromLatestBlock_Call) RunAndReturn(run func(ctx context.Context, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)) *Client_SubscribeAccountStatusesFromLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeAccountStatusesFromStartBlockID provides a mock function for the type Client +func (_mock *Client) SubscribeAccountStatusesFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error) { + ret := _mock.Called(ctx, startBlockID, filter) if len(ret) == 0 { panic("no return value specified for SubscribeAccountStatusesFromStartBlockID") @@ -1357,37 +3291,80 @@ func (_m *Client) SubscribeAccountStatusesFromStartBlockID(ctx context.Context, var r0 <-chan *flow.AccountStatus var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)); ok { - return rf(ctx, startBlockID, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)); ok { + return returnFunc(ctx, startBlockID, filter) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) <-chan *flow.AccountStatus); ok { - r0 = rf(ctx, startBlockID, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) <-chan *flow.AccountStatus); ok { + r0 = returnFunc(ctx, startBlockID, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.AccountStatus) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) <-chan error); ok { - r1 = rf(ctx, startBlockID, filter) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) <-chan error); ok { + r1 = returnFunc(ctx, startBlockID, filter) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) error); ok { - r2 = rf(ctx, startBlockID, filter) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.AccountStatusFilter) error); ok { + r2 = returnFunc(ctx, startBlockID, filter) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeAccountStatusesFromStartHeight provides a mock function with given fields: ctx, startBlockHeight, filter -func (_m *Client) SubscribeAccountStatusesFromStartHeight(ctx context.Context, startBlockHeight uint64, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error) { - ret := _m.Called(ctx, startBlockHeight, filter) +// Client_SubscribeAccountStatusesFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeAccountStatusesFromStartBlockID' +type Client_SubscribeAccountStatusesFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeAccountStatusesFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - filter flow.AccountStatusFilter +func (_e *Client_Expecter) SubscribeAccountStatusesFromStartBlockID(ctx interface{}, startBlockID interface{}, filter interface{}) *Client_SubscribeAccountStatusesFromStartBlockID_Call { + return &Client_SubscribeAccountStatusesFromStartBlockID_Call{Call: _e.mock.On("SubscribeAccountStatusesFromStartBlockID", ctx, startBlockID, filter)} +} + +func (_c *Client_SubscribeAccountStatusesFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, filter flow.AccountStatusFilter)) *Client_SubscribeAccountStatusesFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.AccountStatusFilter + if args[2] != nil { + arg2 = args[2].(flow.AccountStatusFilter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeAccountStatusesFromStartBlockID_Call) Return(accountStatusCh <-chan *flow.AccountStatus, errCh <-chan error, err error) *Client_SubscribeAccountStatusesFromStartBlockID_Call { + _c.Call.Return(accountStatusCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeAccountStatusesFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)) *Client_SubscribeAccountStatusesFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeAccountStatusesFromStartHeight provides a mock function for the type Client +func (_mock *Client) SubscribeAccountStatusesFromStartHeight(ctx context.Context, startBlockHeight uint64, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error) { + ret := _mock.Called(ctx, startBlockHeight, filter) if len(ret) == 0 { panic("no return value specified for SubscribeAccountStatusesFromStartHeight") @@ -1396,37 +3373,80 @@ func (_m *Client) SubscribeAccountStatusesFromStartHeight(ctx context.Context, s var r0 <-chan *flow.AccountStatus var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)); ok { - return rf(ctx, startBlockHeight, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)); ok { + return returnFunc(ctx, startBlockHeight, filter) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.AccountStatusFilter) <-chan *flow.AccountStatus); ok { - r0 = rf(ctx, startBlockHeight, filter) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.AccountStatusFilter) <-chan *flow.AccountStatus); ok { + r0 = returnFunc(ctx, startBlockHeight, filter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.AccountStatus) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, flow.AccountStatusFilter) <-chan error); ok { - r1 = rf(ctx, startBlockHeight, filter) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, flow.AccountStatusFilter) <-chan error); ok { + r1 = returnFunc(ctx, startBlockHeight, filter) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, uint64, flow.AccountStatusFilter) error); ok { - r2 = rf(ctx, startBlockHeight, filter) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64, flow.AccountStatusFilter) error); ok { + r2 = returnFunc(ctx, startBlockHeight, filter) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlockDigestsFromLatest provides a mock function with given fields: ctx, blockStatus -func (_m *Client) SubscribeBlockDigestsFromLatest(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error) { - ret := _m.Called(ctx, blockStatus) +// Client_SubscribeAccountStatusesFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeAccountStatusesFromStartHeight' +type Client_SubscribeAccountStatusesFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeAccountStatusesFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startBlockHeight uint64 +// - filter flow.AccountStatusFilter +func (_e *Client_Expecter) SubscribeAccountStatusesFromStartHeight(ctx interface{}, startBlockHeight interface{}, filter interface{}) *Client_SubscribeAccountStatusesFromStartHeight_Call { + return &Client_SubscribeAccountStatusesFromStartHeight_Call{Call: _e.mock.On("SubscribeAccountStatusesFromStartHeight", ctx, startBlockHeight, filter)} +} + +func (_c *Client_SubscribeAccountStatusesFromStartHeight_Call) Run(run func(ctx context.Context, startBlockHeight uint64, filter flow.AccountStatusFilter)) *Client_SubscribeAccountStatusesFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.AccountStatusFilter + if args[2] != nil { + arg2 = args[2].(flow.AccountStatusFilter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeAccountStatusesFromStartHeight_Call) Return(accountStatusCh <-chan *flow.AccountStatus, errCh <-chan error, err error) *Client_SubscribeAccountStatusesFromStartHeight_Call { + _c.Call.Return(accountStatusCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeAccountStatusesFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startBlockHeight uint64, filter flow.AccountStatusFilter) (<-chan *flow.AccountStatus, <-chan error, error)) *Client_SubscribeAccountStatusesFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromLatest provides a mock function for the type Client +func (_mock *Client) SubscribeBlockDigestsFromLatest(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error) { + ret := _mock.Called(ctx, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromLatest") @@ -1435,37 +3455,74 @@ func (_m *Client) SubscribeBlockDigestsFromLatest(ctx context.Context, blockStat var r0 <-chan *flow.BlockDigest var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)); ok { - return rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)); ok { + return returnFunc(ctx, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) <-chan *flow.BlockDigest); ok { - r0 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) <-chan *flow.BlockDigest); ok { + r0 = returnFunc(ctx, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.BlockDigest) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.BlockStatus) error); ok { - r2 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlockDigestsFromStartBlockID provides a mock function with given fields: ctx, startBlockID, blockStatus -func (_m *Client) SubscribeBlockDigestsFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error) { - ret := _m.Called(ctx, startBlockID, blockStatus) +// Client_SubscribeBlockDigestsFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromLatest' +type Client_SubscribeBlockDigestsFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlockDigestsFromLatest(ctx interface{}, blockStatus interface{}) *Client_SubscribeBlockDigestsFromLatest_Call { + return &Client_SubscribeBlockDigestsFromLatest_Call{Call: _e.mock.On("SubscribeBlockDigestsFromLatest", ctx, blockStatus)} +} + +func (_c *Client_SubscribeBlockDigestsFromLatest_Call) Run(run func(ctx context.Context, blockStatus flow.BlockStatus)) *Client_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.BlockStatus + if args[1] != nil { + arg1 = args[1].(flow.BlockStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlockDigestsFromLatest_Call) Return(blockDigestCh <-chan *flow.BlockDigest, errCh <-chan error, err error) *Client_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(blockDigestCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlockDigestsFromLatest_Call) RunAndReturn(run func(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)) *Client_SubscribeBlockDigestsFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartBlockID provides a mock function for the type Client +func (_mock *Client) SubscribeBlockDigestsFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error) { + ret := _mock.Called(ctx, startBlockID, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartBlockID") @@ -1474,37 +3531,80 @@ func (_m *Client) SubscribeBlockDigestsFromStartBlockID(ctx context.Context, sta var r0 <-chan *flow.BlockDigest var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)); ok { - return rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)); ok { + return returnFunc(ctx, startBlockID, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan *flow.BlockDigest); ok { - r0 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan *flow.BlockDigest); ok { + r0 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.BlockDigest) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.BlockStatus) error); ok { - r2 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, startBlockID, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlockDigestsFromStartHeight provides a mock function with given fields: ctx, startHeight, blockStatus -func (_m *Client) SubscribeBlockDigestsFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error) { - ret := _m.Called(ctx, startHeight, blockStatus) +// Client_SubscribeBlockDigestsFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartBlockID' +type Client_SubscribeBlockDigestsFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlockDigestsFromStartBlockID(ctx interface{}, startBlockID interface{}, blockStatus interface{}) *Client_SubscribeBlockDigestsFromStartBlockID_Call { + return &Client_SubscribeBlockDigestsFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartBlockID", ctx, startBlockID, blockStatus)} +} + +func (_c *Client_SubscribeBlockDigestsFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus)) *Client_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlockDigestsFromStartBlockID_Call) Return(blockDigestCh <-chan *flow.BlockDigest, errCh <-chan error, err error) *Client_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(blockDigestCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlockDigestsFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)) *Client_SubscribeBlockDigestsFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockDigestsFromStartHeight provides a mock function for the type Client +func (_mock *Client) SubscribeBlockDigestsFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error) { + ret := _mock.Called(ctx, startHeight, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockDigestsFromStartHeight") @@ -1513,37 +3613,80 @@ func (_m *Client) SubscribeBlockDigestsFromStartHeight(ctx context.Context, star var r0 <-chan *flow.BlockDigest var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)); ok { - return rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)); ok { + return returnFunc(ctx, startHeight, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) <-chan *flow.BlockDigest); ok { - r0 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) <-chan *flow.BlockDigest); ok { + r0 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.BlockDigest) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, uint64, flow.BlockStatus) error); ok { - r2 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, startHeight, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlockHeadersFromLatest provides a mock function with given fields: ctx, blockStatus -func (_m *Client) SubscribeBlockHeadersFromLatest(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error) { - ret := _m.Called(ctx, blockStatus) +// Client_SubscribeBlockDigestsFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockDigestsFromStartHeight' +type Client_SubscribeBlockDigestsFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockDigestsFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlockDigestsFromStartHeight(ctx interface{}, startHeight interface{}, blockStatus interface{}) *Client_SubscribeBlockDigestsFromStartHeight_Call { + return &Client_SubscribeBlockDigestsFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockDigestsFromStartHeight", ctx, startHeight, blockStatus)} +} + +func (_c *Client_SubscribeBlockDigestsFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus)) *Client_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlockDigestsFromStartHeight_Call) Return(blockDigestCh <-chan *flow.BlockDigest, errCh <-chan error, err error) *Client_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(blockDigestCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlockDigestsFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.BlockDigest, <-chan error, error)) *Client_SubscribeBlockDigestsFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromLatest provides a mock function for the type Client +func (_mock *Client) SubscribeBlockHeadersFromLatest(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error) { + ret := _mock.Called(ctx, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromLatest") @@ -1552,37 +3695,74 @@ func (_m *Client) SubscribeBlockHeadersFromLatest(ctx context.Context, blockStat var r0 <-chan *flow.BlockHeader var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)); ok { - return rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)); ok { + return returnFunc(ctx, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) <-chan *flow.BlockHeader); ok { - r0 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) <-chan *flow.BlockHeader); ok { + r0 = returnFunc(ctx, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.BlockHeader) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.BlockStatus) error); ok { - r2 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlockHeadersFromStartBlockID provides a mock function with given fields: ctx, startBlockID, blockStatus -func (_m *Client) SubscribeBlockHeadersFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error) { - ret := _m.Called(ctx, startBlockID, blockStatus) +// Client_SubscribeBlockHeadersFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromLatest' +type Client_SubscribeBlockHeadersFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlockHeadersFromLatest(ctx interface{}, blockStatus interface{}) *Client_SubscribeBlockHeadersFromLatest_Call { + return &Client_SubscribeBlockHeadersFromLatest_Call{Call: _e.mock.On("SubscribeBlockHeadersFromLatest", ctx, blockStatus)} +} + +func (_c *Client_SubscribeBlockHeadersFromLatest_Call) Run(run func(ctx context.Context, blockStatus flow.BlockStatus)) *Client_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.BlockStatus + if args[1] != nil { + arg1 = args[1].(flow.BlockStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlockHeadersFromLatest_Call) Return(blockHeaderCh <-chan *flow.BlockHeader, errCh <-chan error, err error) *Client_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(blockHeaderCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlockHeadersFromLatest_Call) RunAndReturn(run func(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)) *Client_SubscribeBlockHeadersFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartBlockID provides a mock function for the type Client +func (_mock *Client) SubscribeBlockHeadersFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error) { + ret := _mock.Called(ctx, startBlockID, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartBlockID") @@ -1591,37 +3771,80 @@ func (_m *Client) SubscribeBlockHeadersFromStartBlockID(ctx context.Context, sta var r0 <-chan *flow.BlockHeader var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)); ok { - return rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)); ok { + return returnFunc(ctx, startBlockID, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan *flow.BlockHeader); ok { - r0 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan *flow.BlockHeader); ok { + r0 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.BlockHeader) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.BlockStatus) error); ok { - r2 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, startBlockID, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlockHeadersFromStartHeight provides a mock function with given fields: ctx, startHeight, blockStatus -func (_m *Client) SubscribeBlockHeadersFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error) { - ret := _m.Called(ctx, startHeight, blockStatus) +// Client_SubscribeBlockHeadersFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartBlockID' +type Client_SubscribeBlockHeadersFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlockHeadersFromStartBlockID(ctx interface{}, startBlockID interface{}, blockStatus interface{}) *Client_SubscribeBlockHeadersFromStartBlockID_Call { + return &Client_SubscribeBlockHeadersFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartBlockID", ctx, startBlockID, blockStatus)} +} + +func (_c *Client_SubscribeBlockHeadersFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus)) *Client_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlockHeadersFromStartBlockID_Call) Return(blockHeaderCh <-chan *flow.BlockHeader, errCh <-chan error, err error) *Client_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(blockHeaderCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlockHeadersFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)) *Client_SubscribeBlockHeadersFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlockHeadersFromStartHeight provides a mock function for the type Client +func (_mock *Client) SubscribeBlockHeadersFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error) { + ret := _mock.Called(ctx, startHeight, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlockHeadersFromStartHeight") @@ -1630,37 +3853,80 @@ func (_m *Client) SubscribeBlockHeadersFromStartHeight(ctx context.Context, star var r0 <-chan *flow.BlockHeader var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)); ok { - return rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)); ok { + return returnFunc(ctx, startHeight, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) <-chan *flow.BlockHeader); ok { - r0 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) <-chan *flow.BlockHeader); ok { + r0 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.BlockHeader) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, uint64, flow.BlockStatus) error); ok { - r2 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, startHeight, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlocksFromLatest provides a mock function with given fields: ctx, blockStatus -func (_m *Client) SubscribeBlocksFromLatest(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error) { - ret := _m.Called(ctx, blockStatus) +// Client_SubscribeBlockHeadersFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlockHeadersFromStartHeight' +type Client_SubscribeBlockHeadersFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlockHeadersFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlockHeadersFromStartHeight(ctx interface{}, startHeight interface{}, blockStatus interface{}) *Client_SubscribeBlockHeadersFromStartHeight_Call { + return &Client_SubscribeBlockHeadersFromStartHeight_Call{Call: _e.mock.On("SubscribeBlockHeadersFromStartHeight", ctx, startHeight, blockStatus)} +} + +func (_c *Client_SubscribeBlockHeadersFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus)) *Client_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlockHeadersFromStartHeight_Call) Return(blockHeaderCh <-chan *flow.BlockHeader, errCh <-chan error, err error) *Client_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(blockHeaderCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlockHeadersFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.BlockHeader, <-chan error, error)) *Client_SubscribeBlockHeadersFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromLatest provides a mock function for the type Client +func (_mock *Client) SubscribeBlocksFromLatest(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error) { + ret := _mock.Called(ctx, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromLatest") @@ -1669,37 +3935,74 @@ func (_m *Client) SubscribeBlocksFromLatest(ctx context.Context, blockStatus flo var r0 <-chan *flow.Block var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)); ok { - return rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)); ok { + return returnFunc(ctx, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) <-chan *flow.Block); ok { - r0 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.BlockStatus) <-chan *flow.Block); ok { + r0 = returnFunc(ctx, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.BlockStatus) error); ok { - r2 = rf(ctx, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlocksFromStartBlockID provides a mock function with given fields: ctx, startBlockID, blockStatus -func (_m *Client) SubscribeBlocksFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error) { - ret := _m.Called(ctx, startBlockID, blockStatus) +// Client_SubscribeBlocksFromLatest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromLatest' +type Client_SubscribeBlocksFromLatest_Call struct { + *mock.Call +} + +// SubscribeBlocksFromLatest is a helper method to define mock.On call +// - ctx context.Context +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlocksFromLatest(ctx interface{}, blockStatus interface{}) *Client_SubscribeBlocksFromLatest_Call { + return &Client_SubscribeBlocksFromLatest_Call{Call: _e.mock.On("SubscribeBlocksFromLatest", ctx, blockStatus)} +} + +func (_c *Client_SubscribeBlocksFromLatest_Call) Run(run func(ctx context.Context, blockStatus flow.BlockStatus)) *Client_SubscribeBlocksFromLatest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.BlockStatus + if args[1] != nil { + arg1 = args[1].(flow.BlockStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlocksFromLatest_Call) Return(blockCh <-chan *flow.Block, errCh <-chan error, err error) *Client_SubscribeBlocksFromLatest_Call { + _c.Call.Return(blockCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlocksFromLatest_Call) RunAndReturn(run func(ctx context.Context, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)) *Client_SubscribeBlocksFromLatest_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartBlockID provides a mock function for the type Client +func (_mock *Client) SubscribeBlocksFromStartBlockID(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error) { + ret := _mock.Called(ctx, startBlockID, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartBlockID") @@ -1708,37 +4011,80 @@ func (_m *Client) SubscribeBlocksFromStartBlockID(ctx context.Context, startBloc var r0 <-chan *flow.Block var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)); ok { - return rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)); ok { + return returnFunc(ctx, startBlockID, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan *flow.Block); ok { - r0 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan *flow.Block); ok { + r0 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, startBlockID, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.BlockStatus) error); ok { - r2 = rf(ctx, startBlockID, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, startBlockID, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeBlocksFromStartHeight provides a mock function with given fields: ctx, startHeight, blockStatus -func (_m *Client) SubscribeBlocksFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error) { - ret := _m.Called(ctx, startHeight, blockStatus) +// Client_SubscribeBlocksFromStartBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartBlockID' +type Client_SubscribeBlocksFromStartBlockID_Call struct { + *mock.Call +} + +// SubscribeBlocksFromStartBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlocksFromStartBlockID(ctx interface{}, startBlockID interface{}, blockStatus interface{}) *Client_SubscribeBlocksFromStartBlockID_Call { + return &Client_SubscribeBlocksFromStartBlockID_Call{Call: _e.mock.On("SubscribeBlocksFromStartBlockID", ctx, startBlockID, blockStatus)} +} + +func (_c *Client_SubscribeBlocksFromStartBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus)) *Client_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlocksFromStartBlockID_Call) Return(blockCh <-chan *flow.Block, errCh <-chan error, err error) *Client_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(blockCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlocksFromStartBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)) *Client_SubscribeBlocksFromStartBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeBlocksFromStartHeight provides a mock function for the type Client +func (_mock *Client) SubscribeBlocksFromStartHeight(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error) { + ret := _mock.Called(ctx, startHeight, blockStatus) if len(ret) == 0 { panic("no return value specified for SubscribeBlocksFromStartHeight") @@ -1747,36 +4093,80 @@ func (_m *Client) SubscribeBlocksFromStartHeight(ctx context.Context, startHeigh var r0 <-chan *flow.Block var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)); ok { - return rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)); ok { + return returnFunc(ctx, startHeight, blockStatus) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) <-chan *flow.Block); ok { - r0 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.BlockStatus) <-chan *flow.Block); ok { + r0 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, flow.BlockStatus) <-chan error); ok { - r1 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, flow.BlockStatus) <-chan error); ok { + r1 = returnFunc(ctx, startHeight, blockStatus) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, uint64, flow.BlockStatus) error); ok { - r2 = rf(ctx, startHeight, blockStatus) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64, flow.BlockStatus) error); ok { + r2 = returnFunc(ctx, startHeight, blockStatus) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeEventsByBlockHeight provides a mock function with given fields: ctx, startHeight, filter, opts -func (_m *Client) SubscribeEventsByBlockHeight(ctx context.Context, startHeight uint64, filter flow.EventFilter, opts ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error) { +// Client_SubscribeBlocksFromStartHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeBlocksFromStartHeight' +type Client_SubscribeBlocksFromStartHeight_Call struct { + *mock.Call +} + +// SubscribeBlocksFromStartHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - blockStatus flow.BlockStatus +func (_e *Client_Expecter) SubscribeBlocksFromStartHeight(ctx interface{}, startHeight interface{}, blockStatus interface{}) *Client_SubscribeBlocksFromStartHeight_Call { + return &Client_SubscribeBlocksFromStartHeight_Call{Call: _e.mock.On("SubscribeBlocksFromStartHeight", ctx, startHeight, blockStatus)} +} + +func (_c *Client_SubscribeBlocksFromStartHeight_Call) Run(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus)) *Client_SubscribeBlocksFromStartHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.BlockStatus + if args[2] != nil { + arg2 = args[2].(flow.BlockStatus) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Client_SubscribeBlocksFromStartHeight_Call) Return(blockCh <-chan *flow.Block, errCh <-chan error, err error) *Client_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(blockCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeBlocksFromStartHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, blockStatus flow.BlockStatus) (<-chan *flow.Block, <-chan error, error)) *Client_SubscribeBlocksFromStartHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeEventsByBlockHeight provides a mock function for the type Client +func (_mock *Client) SubscribeEventsByBlockHeight(ctx context.Context, startHeight uint64, filter flow.EventFilter, opts ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error) { + // access.SubscribeOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1784,7 +4174,7 @@ func (_m *Client) SubscribeEventsByBlockHeight(ctx context.Context, startHeight var _ca []interface{} _ca = append(_ca, ctx, startHeight, filter) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeEventsByBlockHeight") @@ -1793,36 +4183,91 @@ func (_m *Client) SubscribeEventsByBlockHeight(ctx context.Context, startHeight var r0 <-chan flow.BlockEvents var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error)); ok { - return rf(ctx, startHeight, filter, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error)); ok { + return returnFunc(ctx, startHeight, filter, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) <-chan flow.BlockEvents); ok { - r0 = rf(ctx, startHeight, filter, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) <-chan flow.BlockEvents); ok { + r0 = returnFunc(ctx, startHeight, filter, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan flow.BlockEvents) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) <-chan error); ok { - r1 = rf(ctx, startHeight, filter, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) <-chan error); ok { + r1 = returnFunc(ctx, startHeight, filter, opts...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) error); ok { - r2 = rf(ctx, startHeight, filter, opts...) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64, flow.EventFilter, ...access.SubscribeOption) error); ok { + r2 = returnFunc(ctx, startHeight, filter, opts...) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeEventsByBlockID provides a mock function with given fields: ctx, startBlockID, filter, opts -func (_m *Client) SubscribeEventsByBlockID(ctx context.Context, startBlockID flow.Identifier, filter flow.EventFilter, opts ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error) { +// Client_SubscribeEventsByBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeEventsByBlockHeight' +type Client_SubscribeEventsByBlockHeight_Call struct { + *mock.Call +} + +// SubscribeEventsByBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +// - filter flow.EventFilter +// - opts ...access.SubscribeOption +func (_e *Client_Expecter) SubscribeEventsByBlockHeight(ctx interface{}, startHeight interface{}, filter interface{}, opts ...interface{}) *Client_SubscribeEventsByBlockHeight_Call { + return &Client_SubscribeEventsByBlockHeight_Call{Call: _e.mock.On("SubscribeEventsByBlockHeight", + append([]interface{}{ctx, startHeight, filter}, opts...)...)} +} + +func (_c *Client_SubscribeEventsByBlockHeight_Call) Run(run func(ctx context.Context, startHeight uint64, filter flow.EventFilter, opts ...access.SubscribeOption)) *Client_SubscribeEventsByBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 flow.EventFilter + if args[2] != nil { + arg2 = args[2].(flow.EventFilter) + } + var arg3 []access.SubscribeOption + variadicArgs := make([]access.SubscribeOption, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(access.SubscribeOption) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *Client_SubscribeEventsByBlockHeight_Call) Return(blockEventsCh <-chan flow.BlockEvents, errCh <-chan error, err error) *Client_SubscribeEventsByBlockHeight_Call { + _c.Call.Return(blockEventsCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeEventsByBlockHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64, filter flow.EventFilter, opts ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error)) *Client_SubscribeEventsByBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeEventsByBlockID provides a mock function for the type Client +func (_mock *Client) SubscribeEventsByBlockID(ctx context.Context, startBlockID flow.Identifier, filter flow.EventFilter, opts ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error) { + // access.SubscribeOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -1830,7 +4275,7 @@ func (_m *Client) SubscribeEventsByBlockID(ctx context.Context, startBlockID flo var _ca []interface{} _ca = append(_ca, ctx, startBlockID, filter) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for SubscribeEventsByBlockID") @@ -1839,37 +4284,91 @@ func (_m *Client) SubscribeEventsByBlockID(ctx context.Context, startBlockID flo var r0 <-chan flow.BlockEvents var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error)); ok { - return rf(ctx, startBlockID, filter, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error)); ok { + return returnFunc(ctx, startBlockID, filter, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) <-chan flow.BlockEvents); ok { - r0 = rf(ctx, startBlockID, filter, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) <-chan flow.BlockEvents); ok { + r0 = returnFunc(ctx, startBlockID, filter, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan flow.BlockEvents) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) <-chan error); ok { - r1 = rf(ctx, startBlockID, filter, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) <-chan error); ok { + r1 = returnFunc(ctx, startBlockID, filter, opts...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) error); ok { - r2 = rf(ctx, startBlockID, filter, opts...) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier, flow.EventFilter, ...access.SubscribeOption) error); ok { + r2 = returnFunc(ctx, startBlockID, filter, opts...) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeExecutionDataByBlockHeight provides a mock function with given fields: ctx, startHeight -func (_m *Client) SubscribeExecutionDataByBlockHeight(ctx context.Context, startHeight uint64) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error) { - ret := _m.Called(ctx, startHeight) +// Client_SubscribeEventsByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeEventsByBlockID' +type Client_SubscribeEventsByBlockID_Call struct { + *mock.Call +} + +// SubscribeEventsByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +// - filter flow.EventFilter +// - opts ...access.SubscribeOption +func (_e *Client_Expecter) SubscribeEventsByBlockID(ctx interface{}, startBlockID interface{}, filter interface{}, opts ...interface{}) *Client_SubscribeEventsByBlockID_Call { + return &Client_SubscribeEventsByBlockID_Call{Call: _e.mock.On("SubscribeEventsByBlockID", + append([]interface{}{ctx, startBlockID, filter}, opts...)...)} +} + +func (_c *Client_SubscribeEventsByBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier, filter flow.EventFilter, opts ...access.SubscribeOption)) *Client_SubscribeEventsByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.EventFilter + if args[2] != nil { + arg2 = args[2].(flow.EventFilter) + } + var arg3 []access.SubscribeOption + variadicArgs := make([]access.SubscribeOption, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(access.SubscribeOption) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *Client_SubscribeEventsByBlockID_Call) Return(blockEventsCh <-chan flow.BlockEvents, errCh <-chan error, err error) *Client_SubscribeEventsByBlockID_Call { + _c.Call.Return(blockEventsCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeEventsByBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier, filter flow.EventFilter, opts ...access.SubscribeOption) (<-chan flow.BlockEvents, <-chan error, error)) *Client_SubscribeEventsByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeExecutionDataByBlockHeight provides a mock function for the type Client +func (_mock *Client) SubscribeExecutionDataByBlockHeight(ctx context.Context, startHeight uint64) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error) { + ret := _mock.Called(ctx, startHeight) if len(ret) == 0 { panic("no return value specified for SubscribeExecutionDataByBlockHeight") @@ -1878,37 +4377,74 @@ func (_m *Client) SubscribeExecutionDataByBlockHeight(ctx context.Context, start var r0 <-chan *flow.ExecutionDataStreamResponse var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error)); ok { - return rf(ctx, startHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error)); ok { + return returnFunc(ctx, startHeight) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) <-chan *flow.ExecutionDataStreamResponse); ok { - r0 = rf(ctx, startHeight) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) <-chan *flow.ExecutionDataStreamResponse); ok { + r0 = returnFunc(ctx, startHeight) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.ExecutionDataStreamResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) <-chan error); ok { - r1 = rf(ctx, startHeight) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) <-chan error); ok { + r1 = returnFunc(ctx, startHeight) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, uint64) error); ok { - r2 = rf(ctx, startHeight) + if returnFunc, ok := ret.Get(2).(func(context.Context, uint64) error); ok { + r2 = returnFunc(ctx, startHeight) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SubscribeExecutionDataByBlockID provides a mock function with given fields: ctx, startBlockID -func (_m *Client) SubscribeExecutionDataByBlockID(ctx context.Context, startBlockID flow.Identifier) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error) { - ret := _m.Called(ctx, startBlockID) +// Client_SubscribeExecutionDataByBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeExecutionDataByBlockHeight' +type Client_SubscribeExecutionDataByBlockHeight_Call struct { + *mock.Call +} + +// SubscribeExecutionDataByBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - startHeight uint64 +func (_e *Client_Expecter) SubscribeExecutionDataByBlockHeight(ctx interface{}, startHeight interface{}) *Client_SubscribeExecutionDataByBlockHeight_Call { + return &Client_SubscribeExecutionDataByBlockHeight_Call{Call: _e.mock.On("SubscribeExecutionDataByBlockHeight", ctx, startHeight)} +} + +func (_c *Client_SubscribeExecutionDataByBlockHeight_Call) Run(run func(ctx context.Context, startHeight uint64)) *Client_SubscribeExecutionDataByBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SubscribeExecutionDataByBlockHeight_Call) Return(executionDataStreamResponseCh <-chan *flow.ExecutionDataStreamResponse, errCh <-chan error, err error) *Client_SubscribeExecutionDataByBlockHeight_Call { + _c.Call.Return(executionDataStreamResponseCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeExecutionDataByBlockHeight_Call) RunAndReturn(run func(ctx context.Context, startHeight uint64) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error)) *Client_SubscribeExecutionDataByBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// SubscribeExecutionDataByBlockID provides a mock function for the type Client +func (_mock *Client) SubscribeExecutionDataByBlockID(ctx context.Context, startBlockID flow.Identifier) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error) { + ret := _mock.Called(ctx, startBlockID) if len(ret) == 0 { panic("no return value specified for SubscribeExecutionDataByBlockID") @@ -1917,44 +4453,67 @@ func (_m *Client) SubscribeExecutionDataByBlockID(ctx context.Context, startBloc var r0 <-chan *flow.ExecutionDataStreamResponse var r1 <-chan error var r2 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error)); ok { - return rf(ctx, startBlockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error)); ok { + return returnFunc(ctx, startBlockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) <-chan *flow.ExecutionDataStreamResponse); ok { - r0 = rf(ctx, startBlockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) <-chan *flow.ExecutionDataStreamResponse); ok { + r0 = returnFunc(ctx, startBlockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan *flow.ExecutionDataStreamResponse) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) <-chan error); ok { - r1 = rf(ctx, startBlockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) <-chan error); ok { + r1 = returnFunc(ctx, startBlockID) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(<-chan error) } } - - if rf, ok := ret.Get(2).(func(context.Context, flow.Identifier) error); ok { - r2 = rf(ctx, startBlockID) + if returnFunc, ok := ret.Get(2).(func(context.Context, flow.Identifier) error); ok { + r2 = returnFunc(ctx, startBlockID) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClient(t interface { - mock.TestingT - Cleanup(func()) -}) *Client { - mock := &Client{} - mock.Mock.Test(t) +// Client_SubscribeExecutionDataByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeExecutionDataByBlockID' +type Client_SubscribeExecutionDataByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubscribeExecutionDataByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - startBlockID flow.Identifier +func (_e *Client_Expecter) SubscribeExecutionDataByBlockID(ctx interface{}, startBlockID interface{}) *Client_SubscribeExecutionDataByBlockID_Call { + return &Client_SubscribeExecutionDataByBlockID_Call{Call: _e.mock.On("SubscribeExecutionDataByBlockID", ctx, startBlockID)} +} - return mock +func (_c *Client_SubscribeExecutionDataByBlockID_Call) Run(run func(ctx context.Context, startBlockID flow.Identifier)) *Client_SubscribeExecutionDataByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Client_SubscribeExecutionDataByBlockID_Call) Return(executionDataStreamResponseCh <-chan *flow.ExecutionDataStreamResponse, errCh <-chan error, err error) *Client_SubscribeExecutionDataByBlockID_Call { + _c.Call.Return(executionDataStreamResponseCh, errCh, err) + return _c +} + +func (_c *Client_SubscribeExecutionDataByBlockID_Call) RunAndReturn(run func(ctx context.Context, startBlockID flow.Identifier) (<-chan *flow.ExecutionDataStreamResponse, <-chan error, error)) *Client_SubscribeExecutionDataByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/integration/client/execution_client.go b/integration/client/execution_client.go index d03e8d5e4fd..52ea73f9deb 100644 --- a/integration/client/execution_client.go +++ b/integration/client/execution_client.go @@ -15,7 +15,7 @@ type ExecutionClient struct { close func() error } -// NewExecutionClient initializes an execution client client with the default gRPC provider. +// NewExecutionClient initializes an execution client with the default gRPC provider. // // An error will be returned if the host is unreachable. func NewExecutionClient(addr string) (*ExecutionClient, error) { diff --git a/integration/dkg/dkg_client_wrapper.go b/integration/dkg/dkg_client_wrapper.go index e46a5fb52c8..15b87134e0e 100644 --- a/integration/dkg/dkg_client_wrapper.go +++ b/integration/dkg/dkg_client_wrapper.go @@ -14,7 +14,6 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/messages" - model "github.com/onflow/flow-go/model/messages" dkgmod "github.com/onflow/flow-go/module/dkg" ) @@ -65,7 +64,7 @@ func (c *DKGClientWrapper) WaitForSealed(ctx context.Context, txID sdk.Identifie } // Broadcast implements the DKGContractClient interface -func (c *DKGClientWrapper) Broadcast(msg model.BroadcastDKGMessage) error { +func (c *DKGClientWrapper) Broadcast(msg messages.BroadcastDKGMessage) error { if !c.enabled.Load() { return fmt.Errorf("failed to broadcast DKG message: %w", errClientDisabled) } diff --git a/integration/dkg/dkg_emulator_suite.go b/integration/dkg/dkg_emulator_suite.go index 5a7310aa901..9fb409ce502 100644 --- a/integration/dkg/dkg_emulator_suite.go +++ b/integration/dkg/dkg_emulator_suite.go @@ -356,8 +356,8 @@ func (s *EmulatorSuite) claimDKGParticipant(node *node) { signer, err := s.blockchain.ServiceKey().Signer() require.NoError(s.T(), err) _, err = s.prepareAndSubmit(createParticipantTx, - []sdk.Address{node.account.accountAddress, s.serviceAccountAddress, s.dkgAddress}, - []sdkcrypto.Signer{node.account.accountSigner, signer, s.dkgSigner}, + []sdk.Address{node.account.accountAddress, s.serviceAccountAddress}, + []sdkcrypto.Signer{node.account.accountSigner, signer}, ) require.NoError(s.T(), err) diff --git a/integration/go.mod b/integration/go.mod index 33dc7e5c996..6239c800750 100644 --- a/integration/go.mod +++ b/integration/go.mod @@ -1,18 +1,17 @@ module github.com/onflow/flow-go/integration -go 1.25.0 +go 1.25.1 require ( - cloud.google.com/go/bigquery v1.69.0 + cloud.google.com/go/bigquery v1.72.0 github.com/VividCortex/ewma v1.2.0 github.com/antihax/optional v1.0.0 github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 github.com/cockroachdb/pebble/v2 v2.0.6 github.com/coreos/go-semver v0.3.0 - github.com/dapperlabs/testingdock v0.4.5-0.20231020233342-a2853fe18724 - github.com/docker/docker v24.0.6+incompatible - github.com/docker/go-connections v0.4.0 - github.com/ethereum/go-ethereum v1.16.7 + github.com/docker/docker v28.5.2+incompatible + github.com/docker/go-connections v0.5.0 + github.com/ethereum/go-ethereum v1.16.8 github.com/go-git/go-git/v5 v5.11.0 github.com/go-yaml/yaml v2.1.0+incompatible github.com/gorilla/websocket v1.5.3 @@ -21,15 +20,18 @@ require ( github.com/ipfs/go-datastore v0.8.2 github.com/ipfs/go-ds-pebble v0.5.0 github.com/libp2p/go-libp2p v0.38.2 - github.com/onflow/cadence v1.9.2 - github.com/onflow/crypto v0.25.3 - github.com/onflow/flow v0.4.15 - github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2 - github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2 + github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382 + github.com/onflow/crypto v0.25.4 + github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b + github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 + github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 + github.com/onflow/flow-ft/lib/go/contracts v1.1.1 github.com/onflow/flow-go v0.38.0-preview.0.0.20241021221952-af9cd6e99de1 - github.com/onflow/flow-go-sdk v1.9.7 + github.com/onflow/flow-go-sdk v1.10.3 github.com/onflow/flow-go/insecure v0.0.0-00010101000000-000000000000 - github.com/onflow/flow/protobuf/go/flow v0.4.18 + github.com/onflow/flow-nft/lib/go/contracts v1.4.1 + github.com/onflow/flow/protobuf/go/flow v0.4.20 + github.com/onflow/testingdock v0.6.0 github.com/prometheus/client_golang v1.20.5 github.com/prometheus/client_model v0.6.2 github.com/prometheus/common v0.61.0 @@ -40,27 +42,27 @@ require ( go.uber.org/atomic v1.11.0 go.uber.org/mock v0.5.0 golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 - golang.org/x/sync v0.18.0 - google.golang.org/grpc v1.77.0 - google.golang.org/protobuf v1.36.10 + golang.org/x/sync v0.19.0 + google.golang.org/grpc v1.79.3 + google.golang.org/protobuf v1.36.11 gopkg.in/yaml.v3 v3.0.1 ) require ( - cel.dev/expr v0.24.0 // indirect - cloud.google.com/go v0.121.0 // indirect - cloud.google.com/go/auth v0.16.4 // indirect + cel.dev/expr v0.25.1 // indirect + cloud.google.com/go v0.123.0 // indirect + cloud.google.com/go/auth v0.18.1 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect - cloud.google.com/go/iam v1.5.2 // indirect - cloud.google.com/go/monitoring v1.24.2 // indirect - cloud.google.com/go/storage v1.53.0 // indirect + cloud.google.com/go/iam v1.5.3 // indirect + cloud.google.com/go/monitoring v1.24.3 // indirect + cloud.google.com/go/storage v1.56.0 // indirect dario.cat/mergo v1.0.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.51.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.51.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect github.com/Jorropo/jsync v1.0.1 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20251001021608-1fe7b43fc4d6 // indirect @@ -69,31 +71,33 @@ require ( github.com/StackExchange/wmi v1.2.1 // indirect github.com/VictoriaMetrics/fastcache v1.13.0 // indirect github.com/apache/arrow/go/v15 v15.0.2 // indirect - github.com/aws/aws-sdk-go-v2 v1.40.1 // indirect - github.com/aws/aws-sdk-go-v2/config v1.31.20 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.18.24 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 // indirect + github.com/aws/aws-sdk-go-v2 v1.41.1 // indirect + github.com/aws/aws-sdk-go-v2/config v1.32.7 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.19.7 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0 // indirect github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.40.2 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect github.com/aws/smithy-go v1.24.0 // indirect github.com/benbjohnson/clock v1.3.5 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bits-and-blooms/bitset v1.24.4 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudflare/circl v1.3.3 // indirect - github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f // indirect + github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 // indirect github.com/cockroachdb/errors v1.11.3 // indirect github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect @@ -101,14 +105,17 @@ require ( github.com/cockroachdb/redact v1.1.5 // indirect github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect - github.com/consensys/gnark-crypto v0.18.0 // indirect + github.com/consensys/gnark-crypto v0.18.1 // indirect github.com/containerd/cgroups v1.1.0 // indirect + github.com/containerd/errdefs v1.0.0 // indirect + github.com/containerd/errdefs/pkg v0.3.0 // indirect github.com/containerd/fifo v1.1.0 // indirect + github.com/containerd/log v0.1.0 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/crate-crypto/go-eth-kzg v1.4.0 // indirect github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect github.com/cskr/pubsub v1.0.2 // indirect - github.com/cyphar/filepath-securejoin v0.2.4 // indirect + github.com/cyphar/filepath-securejoin v0.5.1 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect github.com/deckarep/golang-set/v2 v2.6.0 // indirect @@ -116,9 +123,8 @@ require ( github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.0 // indirect github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect - github.com/distribution/reference v0.5.0 // indirect - github.com/docker/cli v24.0.6+incompatible // indirect - github.com/docker/distribution v2.8.3+incompatible // indirect + github.com/distribution/reference v0.6.0 // indirect + github.com/docker/cli v28.5.2+incompatible // indirect github.com/docker/docker-credential-helpers v0.8.0 // indirect github.com/docker/go-metrics v0.0.1 // indirect github.com/docker/go-units v0.5.0 // indirect @@ -127,8 +133,8 @@ require ( github.com/elastic/gosigar v0.14.3 // indirect github.com/emicklei/dot v1.6.2 // indirect github.com/emirpasic/gods v1.18.1 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.35.0 // indirect - github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect github.com/ethereum/c-kzg-4844/v2 v2.1.5 // indirect github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab // indirect github.com/ethereum/go-verkle v0.2.2 // indirect @@ -138,7 +144,7 @@ require ( github.com/flynn/noise v1.1.0 // indirect github.com/francoispqt/gojay v1.2.13 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013 // indirect + github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e // indirect github.com/fxamacker/circlehash v0.3.0 // indirect github.com/fxamacker/golang-lru/v2 v2.0.0-20250716153046-22c8d17dc4ee // indirect github.com/gabriel-vasile/mimetype v1.4.6 // indirect @@ -171,12 +177,12 @@ require ( github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect - github.com/googleapis/gax-go/v2 v2.15.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect + github.com/googleapis/gax-go/v2 v2.17.0 // indirect github.com/gorilla/mux v1.8.1 // indirect github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/golang-lru v1.0.2 // indirect @@ -204,7 +210,7 @@ require ( github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect github.com/jbenet/goprocess v0.1.4 // indirect - github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956 // indirect + github.com/jordanschalm/lockctx v0.1.0 // indirect github.com/k0kubun/pp/v3 v3.5.0 // indirect github.com/kevinburke/go-bindata v3.24.0+incompatible // indirect github.com/kevinburke/ssh_config v1.2.0 // indirect @@ -242,6 +248,10 @@ require ( github.com/minio/sha256-simd v1.0.1 // indirect github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/moby/docker-image-spec v1.3.1 // indirect + github.com/moby/sys/atomicwriter v0.1.0 // indirect + github.com/moby/sys/sequential v0.6.0 // indirect + github.com/moby/sys/userns v0.1.0 // indirect github.com/moby/term v0.5.0 // indirect github.com/morikuni/aec v1.0.0 // indirect github.com/mr-tron/base58 v1.2.0 // indirect @@ -257,20 +267,18 @@ require ( github.com/multiformats/go-varint v0.0.7 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/onflow/atree v0.12.0 // indirect + github.com/onflow/atree v0.16.1 // indirect github.com/onflow/fixed-point v0.1.1 // indirect - github.com/onflow/flow-evm-bridge v0.1.0 // indirect - github.com/onflow/flow-ft/lib/go/contracts v1.0.1 // indirect - github.com/onflow/flow-ft/lib/go/templates v1.0.1 // indirect - github.com/onflow/flow-nft/lib/go/contracts v1.3.0 // indirect - github.com/onflow/flow-nft/lib/go/templates v1.3.0 // indirect + github.com/onflow/flow-evm-bridge v0.2.1 // indirect + github.com/onflow/flow-ft/lib/go/templates v1.1.1 // indirect + github.com/onflow/flow-nft/lib/go/templates v1.4.1 // indirect github.com/onflow/go-ethereum v1.16.2 // indirect - github.com/onflow/nft-storefront/lib/go/contracts v1.0.0 // indirect + github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066 // indirect github.com/onflow/sdks v0.6.0-preview.1 // indirect github.com/onflow/wal v1.0.2 // indirect github.com/onsi/ginkgo/v2 v2.22.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.0.2 // indirect + github.com/opencontainers/image-spec v1.1.0 // indirect github.com/opencontainers/runtime-spec v1.2.0 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect @@ -308,7 +316,6 @@ require ( github.com/raulk/go-watchdog v1.3.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/rootless-containers/rootlesskit v1.1.1 // indirect github.com/schollz/progressbar/v3 v3.18.0 // indirect github.com/sergi/go-diff v1.2.0 // indirect github.com/sethvargo/go-retry v0.2.3 // indirect @@ -346,38 +353,39 @@ require ( github.com/zeebo/xxh3 v1.0.2 // indirect go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.38.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect - go.opentelemetry.io/otel v1.38.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.65.0 // indirect + go.opentelemetry.io/otel v1.40.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 // indirect - go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/sdk v1.38.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect - go.opentelemetry.io/otel/trace v1.38.0 // indirect - go.opentelemetry.io/proto/otlp v1.7.0 // indirect + go.opentelemetry.io/otel/metric v1.40.0 // indirect + go.opentelemetry.io/otel/sdk v1.40.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.40.0 // indirect + go.opentelemetry.io/otel/trace v1.40.0 // indirect + go.opentelemetry.io/proto/otlp v1.9.0 // indirect go.uber.org/dig v1.18.0 // indirect go.uber.org/fx v1.23.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/crypto v0.45.0 // indirect - golang.org/x/mod v0.30.0 // indirect - golang.org/x/net v0.47.0 // indirect - golang.org/x/oauth2 v0.32.0 // indirect - golang.org/x/sys v0.38.0 // indirect - golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54 // indirect - golang.org/x/term v0.37.0 // indirect - golang.org/x/text v0.31.0 // indirect - golang.org/x/time v0.12.0 // indirect - golang.org/x/tools v0.39.0 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/crypto v0.47.0 // indirect + golang.org/x/mod v0.31.0 // indirect + golang.org/x/net v0.49.0 // indirect + golang.org/x/oauth2 v0.35.0 // indirect + golang.org/x/sys v0.40.0 // indirect + golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc // indirect + golang.org/x/term v0.39.0 // indirect + golang.org/x/text v0.33.0 // indirect + golang.org/x/time v0.14.0 // indirect + golang.org/x/tools v0.40.0 // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect gonum.org/v1/gonum v0.16.0 // indirect - google.golang.org/api v0.247.0 // indirect + google.golang.org/api v0.267.0 // indirect google.golang.org/appengine v1.6.8 // indirect - google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 // indirect + google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect diff --git a/integration/go.sum b/integration/go.sum index bc6981aacda..09b14e13983 100644 --- a/integration/go.sum +++ b/integration/go.sum @@ -1,35 +1,35 @@ -cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= -cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= +cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo= -cloud.google.com/go v0.121.0 h1:pgfwva8nGw7vivjZiRfrmglGWiCJBP+0OmDpenG/Fwg= -cloud.google.com/go v0.121.0/go.mod h1:rS7Kytwheu/y9buoDmu5EIpMMCI4Mb8ND4aeN4Vwj7Q= -cloud.google.com/go/auth v0.16.4 h1:fXOAIQmkApVvcIn7Pc2+5J8QTMVbUGLscnSVNl11su8= -cloud.google.com/go/auth v0.16.4/go.mod h1:j10ncYwjX/g3cdX7GpEzsdM+d+ZNsXAbb6qXA7p1Y5M= +cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= +cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= +cloud.google.com/go/auth v0.18.1 h1:IwTEx92GFUo2pJ6Qea0EU3zYvKnTAeRCODxfA/G5UWs= +cloud.google.com/go/auth v0.18.1/go.mod h1:GfTYoS9G3CWpRA3Va9doKN9mjPGRS+v41jmZAhBzbrA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/bigquery v1.69.0 h1:rZvHnjSUs5sHK3F9awiuFk2PeOaB8suqNuim21GbaTc= -cloud.google.com/go/bigquery v1.69.0/go.mod h1:TdGLquA3h/mGg+McX+GsqG9afAzTAcldMjqhdjHTLew= +cloud.google.com/go/bigquery v1.72.0 h1:D/yLju+3Ens2IXx7ou1DJ62juBm+/coBInn4VVOg5Cw= +cloud.google.com/go/bigquery v1.72.0/go.mod h1:GUbRtmeCckOE85endLherHD9RsujY+gS7i++c1CqssQ= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= -cloud.google.com/go/datacatalog v1.26.0 h1:eFgygb3DTufTWWUB8ARk+dSuXz+aefNJXTlkWlQcWwE= -cloud.google.com/go/datacatalog v1.26.0/go.mod h1:bLN2HLBAwB3kLTFT5ZKLHVPj/weNz6bR0c7nYp0LE14= -cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= -cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= -cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= -cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= -cloud.google.com/go/longrunning v0.6.7 h1:IGtfDWHhQCgCjwQjV9iiLnUta9LBCo8R9QmAFsS/PrE= -cloud.google.com/go/longrunning v0.6.7/go.mod h1:EAFV3IZAKmM56TyiE6VAP3VoTzhZzySwI/YI1s/nRsY= -cloud.google.com/go/monitoring v1.24.2 h1:5OTsoJ1dXYIiMiuL+sYscLc9BumrL3CarVLL7dd7lHM= -cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= +cloud.google.com/go/datacatalog v1.26.1 h1:bCRKA8uSQN8wGW3Tw0gwko4E9a64GRmbW1nCblhgC2k= +cloud.google.com/go/datacatalog v1.26.1/go.mod h1:2Qcq8vsHNxMDgjgadRFmFG47Y+uuIVsyEGUrlrKEdrg= +cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= +cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= +cloud.google.com/go/logging v1.13.1 h1:O7LvmO0kGLaHY/gq8cV7T0dyp6zJhYAOtZPX4TF3QtY= +cloud.google.com/go/logging v1.13.1/go.mod h1:XAQkfkMBxQRjQek96WLPNze7vsOmay9H5PqfsNYDqvw= +cloud.google.com/go/longrunning v0.8.0 h1:LiKK77J3bx5gDLi4SMViHixjD2ohlkwBi+mKA7EhfW8= +cloud.google.com/go/longrunning v0.8.0/go.mod h1:UmErU2Onzi+fKDg2gR7dusz11Pe26aknR4kHmJJqIfk= +cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE= +cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= cloud.google.com/go/profiler v0.3.0 h1:R6y/xAeifaUXxd2x6w+jIwKxoKl8Cv5HJvcvASTPWJo= cloud.google.com/go/profiler v0.3.0/go.mod h1:9wYk9eY4iZHsev8TQb61kh3wiOiSyz/xOYixWPzweCU= -cloud.google.com/go/storage v1.53.0 h1:gg0ERZwL17pJ+Cz3cD2qS60w1WMDnwcm5YPAIQBHUAw= -cloud.google.com/go/storage v1.53.0/go.mod h1:7/eO2a/srr9ImZW9k5uufcNahT2+fPb8w5it1i5boaA= -cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4= -cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= +cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI= +cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU= +cloud.google.com/go/trace v1.11.7 h1:kDNDX8JkaAG3R2nq1lIdkb7FCSi1rCmsEtKVsty7p+U= +cloud.google.com/go/trace v1.11.7/go.mod h1:TNn9d5V3fQVf6s4SCveVMIBS2LJUqo73GACmq/Tky0s= dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= @@ -40,21 +40,19 @@ git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGy github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e h1:ZIWapoIRN1VqT8GR8jAwb1Ie9GyehWjVcGh32Y2MznE= github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.51.0 h1:fYE9p3esPxA/C0rQ0AHhP0drtPXDRhaWiwg1DPqO7IU= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.51.0/go.mod h1:BnBReJLvVYx2CS/UHOgVz2BXKXD9wsQPxZug20nZhd0= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.51.0 h1:OqVGm6Ei3x5+yZmSJG1Mh2NwHvpVmZ08CB5qJhT9Nuk= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.51.0/go.mod h1:SZiPHWGOOk3bl8tkevxkoiwPgsIl6CwrWcbwjfHZpdM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.51.0 h1:6/0iUd0xrnX7qt+mLNRwg5c0PGv8wpE8K90ryANQwMI= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.51.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 h1:owcC2UnmsZycprQ5RfRgjydWhuoxg71LUfyiQdijZuM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0 h1:4LP6hvB4I5ouTbGgWtixJhgED6xdf67twf9PoY96Tbg= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0/go.mod h1:jUZ5LYlw40WMd07qxcQJD5M40aUxrfwqQX1g7zxYnrQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= github.com/Jorropo/jsync v1.0.1 h1:6HgRolFZnsdfzRUj+ImB9og1JYOxQoReSywkHOGSaUU= github.com/Jorropo/jsync v1.0.1/go.mod h1:jCOZj3vrBCri3bSU3ErUYvevKlnbssrXeCivybS5ABQ= github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= -github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= @@ -89,44 +87,46 @@ github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5 github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= -github.com/aws/aws-sdk-go-v2 v1.40.1 h1:difXb4maDZkRH0x//Qkwcfpdg1XQVXEAEs2DdXldFFc= -github.com/aws/aws-sdk-go-v2 v1.40.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= +github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= +github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= github.com/aws/aws-sdk-go-v2/config v1.8.0/go.mod h1:w9+nMZ7soXCe5nT46Ri354SNhXDQ6v+V5wqDjnZE+GY= -github.com/aws/aws-sdk-go-v2/config v1.31.20 h1:/jWF4Wu90EhKCgjTdy1DGxcbcbNrjfBHvksEL79tfQc= -github.com/aws/aws-sdk-go-v2/config v1.31.20/go.mod h1:95Hh1Tc5VYKL9NJ7tAkDcqeKt+MCXQB1hQZaRdJIZE0= +github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY= +github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY= github.com/aws/aws-sdk-go-v2/credentials v1.4.0/go.mod h1:dgGR+Qq7Wjcd4AOAW5Rf5Tnv3+x7ed6kETXyS9WCuAY= -github.com/aws/aws-sdk-go-v2/credentials v1.18.24 h1:iJ2FmPT35EaIB0+kMa6TnQ+PwG5A1prEdAw+PsMzfHg= -github.com/aws/aws-sdk-go-v2/credentials v1.18.24/go.mod h1:U91+DrfjAiXPDEGYhh/x29o4p0qHX5HDqG7y5VViv64= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0/go.mod h1:CpNzHK9VEFUCknu50kkB8z58AH2B5DvPP7ea1LHve/Y= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 h1:T1brd5dR3/fzNFAQch/iBKeX07/ffu/cLu+q+RuzEWk= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13/go.mod h1:Peg/GBAQ6JDt+RoBf4meB1wylmAipb7Kg2ZFakZTlwk= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1 h1:VGkV9KmhGqOQWnHyi4gLG98kE6OecT42fdrCGFWxJsc= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.5.1/go.mod h1:PLlnMiki//sGnCJiW+aVpvP/C8Kcm8mEj/IVm9+9qk4= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14 h1:PZHqQACxYb8mYgms4RZbhZG0a7dPW06xOjmaH0EJC/I= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14/go.mod h1:VymhrMJUWs69D8u0/lZ7jSB6WgaG/NqHi3gX0aYf6U0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14 h1:bOS19y6zlJwagBfHxs0ESzr1XCOU2KXJCWcq3E2vfjY= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14/go.mod h1:1ipeGBMAxZ0xcTm6y6paC2C/J6f6OO7LBODV9afuAyM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2/go.mod h1:BQV0agm+JEhqR+2RT5e1XTFIDcAAV0eW6z2trp+iduw= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0/go.mod h1:v8ygadNyATSm6elwJ/4gzJwcFhri9RqS8skgHKiwXPU= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 h1:x2Ibm/Af8Fi+BH+Hsn9TXGdT+hKbDd5XOTZxTMxDk7o= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3/go.mod h1:IW1jwyrQgMdhisceG8fQLmQIydcT/jWY21rFhzgaKwo= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0/go.mod h1:R1KK+vY8AfalhG1AOu5e35pOD2SdoPKQCFLTvnxiohk= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 h1:kDqdFvMY4AtKoACfzIGD8A0+hbT41KTKF//gq7jITfM= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13/go.mod h1:lmKuogqSU3HzQCwZ9ZtcqOc5XGMqtDK7OIc2+DxiUEg= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0 h1:HWsM0YQWX76V6MOp07YuTYacm8k7h69ObJuw7Nck+og= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.7.0/go.mod h1:LKb3cKNQIMh+itGnEpKGcnL/6OIjPZqrtYah1w5f+3o= github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0 h1:nPLfLPfglacc29Y949sDxpr3X/blaY40s3B85WT2yZU= github.com/aws/aws-sdk-go-v2/service/s3 v1.15.0/go.mod h1:Iv2aJVtVSm/D22rFoX99cLG4q4uB7tppuCsulGe98k4= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M= github.com/aws/aws-sdk-go-v2/service/sso v1.4.0/go.mod h1:+1fpWnL96DL23aXPpMGbsmKe8jLTEfbjuQoA4WS1VaA= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 h1:NjShtS1t8r5LUfFVtFeI8xLAHQNTa7UI0VawXlrBMFQ= -github.com/aws/aws-sdk-go-v2/service/sso v1.30.3/go.mod h1:fKvyjJcz63iL/ftA6RaM8sRCtN4r4zl4tjL3qw5ec7k= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 h1:gTsnx0xXNQ6SBbymoDvcoRHL+q4l/dAFsQuKfDWSaGc= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7/go.mod h1:klO+ejMvYsB4QATfEOIXk8WAEwN4N0aBfJpvC+5SZBo= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo= github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= -github.com/aws/aws-sdk-go-v2/service/sts v1.40.2 h1:HK5ON3KmQV2HcAunnx4sKLB9aPf3gKGwVAf7xnx0QT0= -github.com/aws/aws-sdk-go-v2/service/sts v1.40.2/go.mod h1:E19xDjpzPZC7LS2knI9E6BaRFDK43Eul7vd6rSq2HWk= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= @@ -149,6 +149,8 @@ github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7 github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= @@ -162,8 +164,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cloudflare/circl v1.3.3 h1:fE/Qz0QdIGqeWfnwq0RE0R7MI51s0M2E4Ga9kq5AEMs= github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f h1:Y8xYupdHxryycyPlc9Y+bSQAYZnetRJ70VMVKm5CKI0= -github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f/go.mod h1:HlzOvOjVBOfTGSRXRyY0OiCS/3J1akRGQQpRO/7zyF4= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 h1:bvJv505UUfjzbaIPdNS4AEkHreDqQk6yuNpsdRHpwFA= github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94/go.mod h1:Gq51ZeKaFCXk6QwuGM0w1dnaOqc/F5zKT2zA9D6Xeac= github.com/cockroachdb/datadriven v1.0.3-0.20240530155848-7682d40af056 h1:slXychO2uDM6hYRu4c0pD0udNI8uObfeKN6UInWViS8= @@ -186,13 +188,19 @@ github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 h1:Nua446ru3juLH github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= -github.com/consensys/gnark-crypto v0.18.0 h1:vIye/FqI50VeAr0B3dx+YjeIvmc3LWz4yEfbWBpTUf0= -github.com/consensys/gnark-crypto v0.18.0/go.mod h1:L3mXGFTe1ZN+RSJ+CLjUt9x7PNdx8ubaYfDROyp2Z8c= +github.com/consensys/gnark-crypto v0.18.1 h1:RyLV6UhPRoYYzaFnPQA4qK3DyuDgkTgskDdoGqFt3fI= +github.com/consensys/gnark-crypto v0.18.1/go.mod h1:L3mXGFTe1ZN+RSJ+CLjUt9x7PNdx8ubaYfDROyp2Z8c= github.com/containerd/cgroups v0.0.0-20201119153540-4cbc285b3327/go.mod h1:ZJeTFisyysqgcCdecO57Dj79RfL0LNeGiFUqLYQRYLE= github.com/containerd/cgroups v1.1.0 h1:v8rEWFl6EoqHB+swVNjVoCJE8o3jX7e8nqBGPLaDFBM= github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= github.com/containerd/fifo v1.1.0 h1:4I2mbh5stb1u6ycIABlBw9zgtlK8viPI9QkQNRQEEmY= github.com/containerd/fifo v1.1.0/go.mod h1:bmC4NWMbXlt2EZ0Hc7Fx7QzTFxgPID13eH0Qu+MAb2o= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= @@ -209,7 +217,6 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/crate-crypto/go-eth-kzg v1.4.0 h1:WzDGjHk4gFg6YzV0rJOAsTK4z3Qkz5jd4RE3DAvPFkg= github.com/crate-crypto/go-eth-kzg v1.4.0/go.mod h1:J9/u5sWfznSObptgfa92Jq8rTswn6ahQWEuiLHOjCUI= @@ -220,11 +227,8 @@ github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/cskr/pubsub v1.0.2 h1:vlOzMhl6PFn60gRlTQQsIfVwaPB/B/8MziK8FhEPt/0= github.com/cskr/pubsub v1.0.2/go.mod h1:/8MzYXk/NJAz782G8RPkFzXTZVu63VotefPnR9TIRis= -github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= -github.com/cyphar/filepath-securejoin v0.2.4/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= -github.com/danieljoos/wincred v1.2.0/go.mod h1:FzQLLMKBFdvu+osBrnFODiv32YGwCfx0SkRa/eYHgec= -github.com/dapperlabs/testingdock v0.4.5-0.20231020233342-a2853fe18724 h1:zOOpPLu5VvH8ixyoDWHnQHWoEHtryT1ne31vwz0G7Fo= -github.com/dapperlabs/testingdock v0.4.5-0.20231020233342-a2853fe18724/go.mod h1:U0cEcbf9hAwPSuuoPVqXKhcWV+IU4CStK75cJ52f2/A= +github.com/cyphar/filepath-securejoin v0.5.1 h1:eYgfMq5yryL4fbWfkLpFFy2ukSELzaJOTaUTuh+oF48= +github.com/cyphar/filepath-securejoin v0.5.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -247,18 +251,16 @@ github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUn github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0= -github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/cli v24.0.6+incompatible h1:fF+XCQCgJjjQNIMjzaSmiKJSCcfcXb3TWTcc7GAneOY= -github.com/docker/cli v24.0.6+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= -github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk= -github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v24.0.6+incompatible h1:hceabKCtUgDqPu+qm0NgsaXf28Ljf4/pWFL7xjWWDgE= -github.com/docker/docker v24.0.6+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/cli v28.5.2+incompatible h1:XmG99IHcBmIAoC1PPg9eLBZPlTrNUAijsHLm8PjhBlg= +github.com/docker/cli v28.5.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM= +github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= -github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= +github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc= github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8= github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= @@ -281,24 +283,23 @@ github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FM github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329 h1:K+fnvUM0VZ7ZFJf0n4L/BRlnsb9pL/GuDG6FqaH+PwM= -github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329/go.mod h1:Alz8LEClvR7xKsrq3qzoc4N0guvVNSS8KmSChGYr9hs= -github.com/envoyproxy/go-control-plane/envoy v1.35.0 h1:ixjkELDE+ru6idPxcHLj8LBVc2bFP7iBytj353BoHUo= -github.com/envoyproxy/go-control-plane/envoy v1.35.0/go.mod h1:09qwbGVuSWWAyN5t/b3iyVfz5+z8QWGrzkoqm/8SbEs= +github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= +github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= +github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g= +github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= -github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4= +github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= github.com/ethereum/c-kzg-4844/v2 v2.1.5 h1:aVtoLK5xwJ6c5RiqO8g8ptJ5KU+2Hdquf6G3aXiHh5s= github.com/ethereum/c-kzg-4844/v2 v2.1.5/go.mod h1:u59hRTTah4Co6i9fDWtiCjTrblJv0UwsqZKCc0GfgUs= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab h1:rvv6MJhy07IMfEKuARQ9TKojGqLVNxQajaXEp/BoqSk= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab/go.mod h1:IuLm4IsPipXKF7CW5Lzf68PIbZ5yl7FFd74l/E0o9A8= -github.com/ethereum/go-ethereum v1.16.7 h1:qeM4TvbrWK0UC0tgkZ7NiRsmBGwsjqc64BHo20U59UQ= -github.com/ethereum/go-ethereum v1.16.7/go.mod h1:Fs6QebQbavneQTYcA39PEKv2+zIjX7rPUZ14DER46wk= +github.com/ethereum/go-ethereum v1.16.8 h1:LLLfkZWijhR5m6yrAXbdlTeXoqontH+Ga2f9igY7law= +github.com/ethereum/go-ethereum v1.16.8/go.mod h1:Fs6QebQbavneQTYcA39PEKv2+zIjX7rPUZ14DER46wk= github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cnFk8= github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk= -github.com/fanliao/go-promise v0.0.0-20141029170127-1890db352a72/go.mod h1:PjfxuH4FZdUyfMdtBio2lsRr1AKEaVPwelzuHuh8Lqc= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/ferranbt/fastssz v0.1.4 h1:OCDB+dYDEQDvAgtAGnTSidK1Pe2tW3nFV40XyMkTeDY= @@ -316,8 +317,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013 h1:jcwW+JBYGe3qgiPQ4deXaannYxVdxjMw57/dw+gcEfQ= -github.com/fxamacker/cbor/v2 v2.9.1-0.20251019205732-39888e6be013/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e h1:AqsamU9dS+/RNjgvDOqFUT7qXApcmnw7zJLLqJkx860= +github.com/fxamacker/cbor/v2 v2.9.2-0.20260331174317-a78e92ec038e/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/fxamacker/circlehash v0.3.0 h1:XKdvTtIJV9t7DDUtsf0RIpC1OcxZtPbmgIH7ekx28WA= github.com/fxamacker/circlehash v0.3.0/go.mod h1:3aq3OfVvsWtkWMb6A1owjOQFA+TLsD5FgJflnaQwtMM= github.com/fxamacker/golang-lru/v2 v2.0.0-20250430153159-6f72f038a30f h1:/gqGg2NQVvwiLXs7ppw2uneC5AAd2Z9OTp0zgu42zNI= @@ -388,7 +389,6 @@ github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5x github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= @@ -442,7 +442,6 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= @@ -463,20 +462,18 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4 github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= -github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= -github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= -github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= +github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc= +github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gopherjs/gopherjs v0.0.0-20190430165422-3e4dfb77656c h1:7lF+Vz0LqiRidnzC1Oq86fpX1q/iEv2KJdrCtttYjT4= github.com/gopherjs/gopherjs v0.0.0-20190430165422-3e4dfb77656c/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= @@ -490,8 +487,8 @@ github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92Bcuy github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -512,13 +509,11 @@ github.com/huandu/go-clone v1.7.2 h1:3+Aq0Ed8XK+zKkLjE2dfHg0XrpIfcohBE1K+c8Usxoo github.com/huandu/go-clone v1.7.2/go.mod h1:ReGivhG6op3GYr+UY3lS6mxjKp7MIGTknuU5TbTVaXE= github.com/huandu/go-clone/generic v1.7.2 h1:47pQphxs1Xc9cVADjOHN+Bm5D0hNagwH9UXErbxgVKA= github.com/huandu/go-clone/generic v1.7.2/go.mod h1:xgd9ZebcMsBWWcBx5mVMCoqMX24gLWr5lQicr+nVXNs= -github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714/go.mod h1:2Goc3h8EklBH5mspfHFxBnEoURQCGzQQH1ga9Myjvis= github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/insomniacslk/dhcp v0.0.0-20230516061539-49801966e6cb/go.mod h1:7474bZ1YNCvarT6WFKie4kEET6J0KYRDC4XJqqXzQW4= github.com/ipfs/bbloom v0.0.4 h1:Gi+8EGJ2y5qiD5FbsbpX/TMNcJw8gSqr7eyjHa4Fhvs= github.com/ipfs/bbloom v0.0.4/go.mod h1:cS9YprKXpoZ9lT0n/Mw/a6/aFV6DTjTLYHeA+gyqMG0= github.com/ipfs/go-block-format v0.2.0 h1:ZqrkxBA2ICbDRbK8KJs/u0O3dlp6gmAuuXUJNiW1Ycs= @@ -569,15 +564,8 @@ github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0 github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956 h1:4iii8SOozVG1lpkdPELRsjPEBhU4DeFPz2r2Fjj3UDU= -github.com/jordanschalm/lockctx v0.0.0-20250412215529-226f85c10956/go.mod h1:qsnXMryYP9X7JbzskIn0+N40sE6XNXLr9kYRRP6rwXU= -github.com/josharian/native v1.0.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= -github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= -github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= -github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+70psSo5OFh8DBl0Zv2ACw7Esh6pPUphlvZG9x7uw= -github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ= -github.com/jsimonetti/rtnetlink v0.0.0-20201009170750-9c6f07d100c1/go.mod h1:hqoO/u39cqLeBLebZ8fWdE96O7FxrAsRYhnVOdgHxok= -github.com/jsimonetti/rtnetlink v0.0.0-20201110080708-d2c240429e6c/go.mod h1:huN4d1phzjhlOsNIjFsw2SVRbwIHj3fJDMEU2SDPTmg= +github.com/jordanschalm/lockctx v0.1.0 h1:2ZziSl5zejl5VSRUjl+UtYV94QPFQgO9bekqWPOKUQw= +github.com/jordanschalm/lockctx v0.1.0/go.mod h1:qsnXMryYP9X7JbzskIn0+N40sE6XNXLr9kYRRP6rwXU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= @@ -678,12 +666,6 @@ github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/mdlayher/netlink v0.0.0-20190409211403-11939a169225/go.mod h1:eQB3mZE4aiYnlUsyGGCOpPETfdQq4Jhsgf1fk3cwQaA= -github.com/mdlayher/netlink v1.0.0/go.mod h1:KxeJAFOFLG6AjpyDkQ/iIhxygIUKD+vcwqcnu43w/+M= -github.com/mdlayher/netlink v1.1.0/go.mod h1:H4WCitaheIsdF9yOYu8CFmCgQthAPIWZmcKp9uZHgmY= -github.com/mdlayher/netlink v1.1.1/go.mod h1:WTYpFb/WTvlRJAyKhZL5/uy69TDDpHHu2VZmb2XgV7o= -github.com/mdlayher/packet v1.1.1/go.mod h1:DRvYY5mH4M4lUqAnMg04E60U4fjUKMZ/4g2cHElZkKo= -github.com/mdlayher/socket v0.4.0/go.mod h1:xxFqz5GRCUN3UEOm9CZqEJsAbe1C8OwSK46NlmWuVoc= github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= github.com/miekg/dns v1.1.62 h1:cN8OuEF1/x5Rq6Np+h1epln8OiyPWV+lROx9LxcGgIQ= github.com/miekg/dns v1.1.62/go.mod h1:mvDlcItzm+br7MToIKqkglaGhlFMHJ9DTNNWONWXbNQ= @@ -703,10 +685,16 @@ github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrk github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/moby/sys/mountinfo v0.6.2/go.mod h1:IJb6JQeOklcdMU9F5xQ8ZALD+CUr5VlGpwtX+VE0rpI= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw= +github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs= +github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU= +github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= -github.com/moby/vpnkit v0.5.0/go.mod h1:KyjUrL9cb6ZSNNAUwZfqRjhwwgJ3BJN+kXh0t43WTUQ= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= @@ -760,44 +748,46 @@ github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JX github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onflow/atree v0.12.0 h1:X7/UEPyCaaEQ1gCg11KDvfyEtEeQLhtRtxMHjAiH/Co= -github.com/onflow/atree v0.12.0/go.mod h1:qdZcfLQwPirHcNpLiK+2t3KAo+SAb9Si6TqurE6pykE= +github.com/onflow/atree v0.16.1 h1:EmlaIz/GwQ39o5agAb2KT2ynt4SHRBkgMMWU5bp6iTs= +github.com/onflow/atree v0.16.1/go.mod h1:hiOT/vKK/Zyw34Ru9OFbfEemC5NnQ7SHFB43bN9/4qI= github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483 h1:LpiQhTAfM9CAmNVEs0n//cBBgCg+vJSiIxTHYUklZ84= github.com/onflow/boxo v0.0.0-20240201202436-f2477b92f483/go.mod h1:pIZgTWdm3k3pLF9Uq6MB8JEcW07UDwNJjlXW1HELW80= -github.com/onflow/cadence v1.9.2 h1:r1hKhbrFJgrLCHj8N0Bp8/gfG9Vc5WTYOtDjdcWqEk4= -github.com/onflow/cadence v1.9.2/go.mod h1:MlJsCwhCZwdnAUd24XHzcsizZfG7a2leab1PztabUsE= -github.com/onflow/crypto v0.25.3 h1:XQ3HtLsw8h1+pBN+NQ1JYM9mS2mVXTyg55OldaAIF7U= -github.com/onflow/crypto v0.25.3/go.mod h1:+1igaXiK6Tjm9wQOBD1EGwW7bYWMUGKtwKJ/2QL/OWs= +github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382 h1:3lnbPpMxrNsZLN6uUwZy5zbIc2PlaOefjlOKm2PunYk= +github.com/onflow/cadence v1.10.4-0.20260708184308-214f06410382/go.mod h1:hoz+FnPPL+FJFt9kzl0ZSnDj7qLHBG7JdhEs1AAjzYo= +github.com/onflow/crypto v0.25.4 h1:R615PWPdSoA5RATNb/j3cYaloBIZlSXVNgS7BjwHiwM= +github.com/onflow/crypto v0.25.4/go.mod h1:DlkW/1SPUvLHYvUcjWa9PkLIRgSBKR4EDc3i+ATQKW4= github.com/onflow/fixed-point v0.1.1 h1:j0jYZVO8VGyk1476alGudEg7XqCkeTVxb5ElRJRKS90= github.com/onflow/fixed-point v0.1.1/go.mod h1:gJdoHqKtToKdOZbvryJvDZfcpzC7d2fyWuo3ZmLtcGY= -github.com/onflow/flow v0.4.15 h1:MdrhULSE5iSYNyLCihH8DI4uab5VciVZUKDFON6zylY= -github.com/onflow/flow v0.4.15/go.mod h1:lzyAYmbu1HfkZ9cfnL5/sjrrsnJiUU8fRL26CqLP7+c= -github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2 h1:mkd1NSv74+OnCHwrFqI2c5VETS1j06xf0ZuOto7gMio= -github.com/onflow/flow-core-contracts/lib/go/contracts v1.9.2/go.mod h1:jBDqVep0ICzhXky56YlyO4aiV2Jl/5r7wnqUPpvi7zE= -github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2 h1:semxeVLwC6xFG1G/7egUmaf7F1C8eBnc7NxNTVfBHTs= -github.com/onflow/flow-core-contracts/lib/go/templates v1.9.2/go.mod h1:twSVyUt3rNrgzAmxtBX+1Gw64QlPemy17cyvnXYy1Ug= -github.com/onflow/flow-evm-bridge v0.1.0 h1:7X2osvo4NnQgHj8aERUmbYtv9FateX8liotoLnPL9nM= -github.com/onflow/flow-evm-bridge v0.1.0/go.mod h1:5UYwsnu6WcBNrwitGFxphCl5yq7fbWYGYuiCSTVF6pk= -github.com/onflow/flow-ft/lib/go/contracts v1.0.1 h1:Ts5ob+CoCY2EjEd0W6vdLJ7hLL3SsEftzXG2JlmSe24= -github.com/onflow/flow-ft/lib/go/contracts v1.0.1/go.mod h1:PwsL8fC81cjnUnTfmyL/HOIyHnyaw/JA474Wfj2tl6A= -github.com/onflow/flow-ft/lib/go/templates v1.0.1 h1:FDYKAiGowABtoMNusLuRCILIZDtVqJ/5tYI4VkF5zfM= -github.com/onflow/flow-ft/lib/go/templates v1.0.1/go.mod h1:uQ8XFqmMK2jxyBSVrmyuwdWjTEb+6zGjRYotfDJ5pAE= -github.com/onflow/flow-go-sdk v1.9.7 h1:eUDfXeIEghEe/cYCviGMnjD00kJm5SmIbtb+Q3xss6s= -github.com/onflow/flow-go-sdk v1.9.7/go.mod h1:027+x42RUqfraz9ojUKF0riHa/jm1bTdkjuTvYnZQ8c= -github.com/onflow/flow-nft/lib/go/contracts v1.3.0 h1:DmNop+O0EMyicZvhgdWboFG57xz5t9Qp81FKlfKyqJc= -github.com/onflow/flow-nft/lib/go/contracts v1.3.0/go.mod h1:eZ9VMMNfCq0ho6kV25xJn1kXeCfxnkhj3MwF3ed08gY= -github.com/onflow/flow-nft/lib/go/templates v1.3.0 h1:uGIBy4GEY6Z9hKP7sm5nA5kwvbvLWW4nWx5NN9Wg0II= -github.com/onflow/flow-nft/lib/go/templates v1.3.0/go.mod h1:gVbb5fElaOwKhV5UEUjM+JQTjlsguHg2jwRupfM/nng= -github.com/onflow/flow/protobuf/go/flow v0.4.18 h1:KOujA6lg9kTXCV6oK0eErD1rwRnM9taKZss3Szi+T3Q= -github.com/onflow/flow/protobuf/go/flow v0.4.18/go.mod h1:NA2pX2nw8zuaxfKphhKsk00kWLwfd+tv8mS23YXO4Sk= +github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b h1:Pr+Vxdr/J0V+1mOKfOvC3+Ik6I9ogJGXDYkW0FIYS/g= +github.com/onflow/flow v0.4.20-0.20260303141511-b7c99b4fb01b/go.mod h1:lzyAYmbu1HfkZ9cfnL5/sjrrsnJiUU8fRL26CqLP7+c= +github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3 h1:OTJo6PzE8F0EtvBsBvXKVqSA8eCm1uzN+aWwV5gtjPs= +github.com/onflow/flow-core-contracts/lib/go/contracts v1.10.3/go.mod h1:fn0eOOINlOdQSOWptENC92MpPorB7dHzZaC3VTAmiQY= +github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3 h1:MA0tiuQo69AhaMh8TgEMyJwuKKO3UK8PB8W+Fg1YVt4= +github.com/onflow/flow-core-contracts/lib/go/templates v1.10.3/go.mod h1:bXe+VkZmvM3QYGjfizprStRfasLA/7ii7l6+LHP5V1U= +github.com/onflow/flow-evm-bridge v0.2.1 h1:S32kk+UV7/COdQZakIMsJw6vxShel0s8lI3FyGFl9jM= +github.com/onflow/flow-evm-bridge v0.2.1/go.mod h1:ExhTZax2F+boo13dzT/uAI7rvwewAoz9v+dEXhhFjYg= +github.com/onflow/flow-ft/lib/go/contracts v1.1.1 h1:BNbP3CrTIgScpx2NS9snq9XDESFjgXrMXTrwk5H4iSs= +github.com/onflow/flow-ft/lib/go/contracts v1.1.1/go.mod h1:PwsL8fC81cjnUnTfmyL/HOIyHnyaw/JA474Wfj2tl6A= +github.com/onflow/flow-ft/lib/go/templates v1.1.1 h1:X+EGTWKeVlsF33JD5QBFZLr8KW2apl6Oh1AXRWHmzLI= +github.com/onflow/flow-ft/lib/go/templates v1.1.1/go.mod h1:uQ8XFqmMK2jxyBSVrmyuwdWjTEb+6zGjRYotfDJ5pAE= +github.com/onflow/flow-go-sdk v1.10.3 h1:4zJYkdDNqeQqUJmdQJXlHIZuEjOLp8lsu8dRz5GZ/Cc= +github.com/onflow/flow-go-sdk v1.10.3/go.mod h1:cnpuCUvKLGqVrhz6yPEv0+LdsT9ib+cbn0YxfAJxHEI= +github.com/onflow/flow-nft/lib/go/contracts v1.4.1 h1:iQ8s4W5HNWd92MVRZbKxYpQ6UJn9snHLKQ9hFFNCiys= +github.com/onflow/flow-nft/lib/go/contracts v1.4.1/go.mod h1:XUsJjlbVoI0kebgv87xsO70U/ITGYbSEgTwbyg1RcOs= +github.com/onflow/flow-nft/lib/go/templates v1.4.1 h1:P+FN51waQrACpyVeXzLl1cnlD5J8bUYiemHXgeZBM+8= +github.com/onflow/flow-nft/lib/go/templates v1.4.1/go.mod h1:Z5kaMh/3SKSNx9tJj/nvc87iUap9b5L26UnU0Y4xy+0= +github.com/onflow/flow/protobuf/go/flow v0.4.20 h1:Ndq2l7Nu8p/RWNSRIRrpnBUpzfc5fYLEmHCFpJ9JGgo= +github.com/onflow/flow/protobuf/go/flow v0.4.20/go.mod h1:NA2pX2nw8zuaxfKphhKsk00kWLwfd+tv8mS23YXO4Sk= github.com/onflow/go-ds-pebble v0.0.0-20251003225212-131edca3a897 h1:ZtFYJ3OSR00aiKMMxgm3fRYWqYzjvDXeoBGQm6yC8DE= github.com/onflow/go-ds-pebble v0.0.0-20251003225212-131edca3a897/go.mod h1:aiCRVcj3K60sxc6k5C+HO9C6rouqiSkjR/WKnbTcMfQ= github.com/onflow/go-ethereum v1.16.2 h1:yhC3DA5PTNmUmu7ziq8GmWyQ23KNjle4jCabxpKYyNk= github.com/onflow/go-ethereum v1.16.2/go.mod h1:1vsrG/9APHPqt+mVFni60hIXkqkVdU9WQayNjYi/Ah4= -github.com/onflow/nft-storefront/lib/go/contracts v1.0.0 h1:sxyWLqGm/p4EKT6DUlQESDG1ZNMN9GjPCm1gTq7NGfc= -github.com/onflow/nft-storefront/lib/go/contracts v1.0.0/go.mod h1:kMeq9zUwCrgrSojEbTUTTJpZ4WwacVm2pA7LVFr+glk= +github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066 h1:nQZ8wIvjPnxY8AAnyQDd+Pf9pJalbKjGZhMNtTnTUqc= +github.com/onflow/nft-storefront/lib/go/contracts v1.1.1-0.20260409183916-cddb825ea066/go.mod h1:kMeq9zUwCrgrSojEbTUTTJpZ4WwacVm2pA7LVFr+glk= github.com/onflow/sdks v0.6.0-preview.1 h1:mb/cUezuqWEP1gFZNAgUI4boBltudv4nlfxke1KBp9k= github.com/onflow/sdks v0.6.0-preview.1/go.mod h1:F0dj0EyHC55kknLkeD10js4mo14yTdMotnWMslPirrU= +github.com/onflow/testingdock v0.6.0 h1:dXpzWs3O+0moJR4mh/9eO/PuA42ROS8yuqekgBQ9uDA= +github.com/onflow/testingdock v0.6.0/go.mod h1:hbffZJs/2BVmfKqBovHu82B6AWr/u2bdKMUClJJNx+s= github.com/onflow/wal v1.0.2 h1:5bgsJVf2O3cfMNK12fiiTyYZ8cOrUiELt3heBJfHOhc= github.com/onflow/wal v1.0.2/go.mod h1:iMC8gkLqu4nkbkAla5HkSBb+FGyQOZiWz3DYm2wSXCk= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -813,8 +803,8 @@ github.com/onsi/gomega v1.34.2 h1:pNCwDkzrsv7MS9kpaQvVb1aVLahQXyJ/Tv5oAZMI3i8= github.com/onsi/gomega v1.34.2/go.mod h1:v1xfxRgk0KIsG+QOdm7p8UosrOzPYRo60fd3B/1Dukc= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= -github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= +github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.2.0 h1:z97+pHb3uELt/yiAWD691HNHQIF07bE7dzrbT927iTk= github.com/opencontainers/runtime-spec v1.2.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= @@ -827,8 +817,6 @@ github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhM github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= -github.com/pierrec/lz4/v4 v4.1.14/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= -github.com/pierrec/lz4/v4 v4.1.17/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= @@ -903,7 +891,6 @@ github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/j github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= @@ -918,7 +905,6 @@ github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= -github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= @@ -944,8 +930,6 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/rootless-containers/rootlesskit v1.1.1 h1:F5psKWoWY9/VjZ3ifVcaosjvFZJOagX85U22M0/EQZE= -github.com/rootless-containers/rootlesskit v1.1.1/go.mod h1:UD5GoA3dqKCJrnvnhVgQQnweMF2qZnf9KLw8EewcMZI= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= @@ -992,22 +976,17 @@ github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYED github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/sirupsen/logrus v1.9.2/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/skeema/knownhosts v1.2.1 h1:SHWdIUa82uGZz+F+47k8SY4QhhI291cXCpopT1lK2AQ= github.com/skeema/knownhosts v1.2.1/go.mod h1:xYbVRSPxqBZFrdmDyMmsOs+uX1UZC3nTN3ThzgDxUwo= github.com/slok/go-http-metrics v0.12.0 h1:mAb7hrX4gB4ItU6NkFoKYdBslafg3o60/HbGBRsKaG8= github.com/slok/go-http-metrics v0.12.0/go.mod h1:Ee/mdT9BYvGrlGzlClkK05pP2hRHmVbRF9dtUVS8LNA= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8/go.mod h1:P5HUIBuIWKbyjl083/loAegFkfbFNx5i2qEP4CNbm7E= github.com/sony/gobreaker v0.5.0 h1:dRCvqm0P490vZPmy7ppEk2qCnCieBooFJ+YoXGYB+yg= github.com/sony/gobreaker v0.5.0/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= @@ -1046,7 +1025,6 @@ github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= @@ -1072,13 +1050,10 @@ github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9f github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/turbolent/prettier v0.0.0-20220320183459-661cc755135d h1:5JInRQbk5UBX8JfUvKh2oYTLMVwj3p6n+wapDDm7hko= github.com/turbolent/prettier v0.0.0-20220320183459-661cc755135d/go.mod h1:Nlx5Y115XQvNcIdIy7dZXaNSUpzwBSge4/Ivk93/Yog= -github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923/go.mod h1:eLL9Nub3yfAho7qB0MzZizFhTU2QkLeoVsWdHtDW264= -github.com/u-root/uio v0.0.0-20230305220412-3e8cd9d6bf63/go.mod h1:eLL9Nub3yfAho7qB0MzZizFhTU2QkLeoVsWdHtDW264= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.10/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/urfave/cli/v2 v2.25.5/go.mod h1:GHupkWPMM0M/sj1a2b4wUrWBPzazNrIjouW6fmdJLxc= github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU= github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM= github.com/vmihailenco/msgpack/v4 v4.3.12 h1:07s4sz9IReOgdikxLTKNbBdqDMLsjPKXwvCazn8G65U= @@ -1102,7 +1077,6 @@ github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= @@ -1125,30 +1099,32 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.38.0 h1:ZoYbqX7OaA/TAikspPl3ozPI6iY6LiIY9I8cUfm+pJs= -go.opentelemetry.io/contrib/detectors/gcp v1.38.0/go.mod h1:SU+iU7nu5ud4oCb3LQOhIZ3nRLj6FNVrKgtflbaf2ts= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= -go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 h1:K0XaT3DwHAcV4nKLzcQvwAgSyisUghWoY20I7huthMk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0/go.mod h1:B5Ki776z/MBnVha1Nzwp5arlzBbE3+1jk+pGmaP5HME= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.65.0 h1:7iP2uCb7sGddAr30RRS6xjKy7AZ2JtTOPA3oolgVSw8= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.65.0/go.mod h1:c7hN3ddxs/z6q9xwvfLPk+UHlWRQyaeR1LdgfL/66l0= +go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= +go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 h1:f0cb2XPmrqn4XMy9PNliTgRKJgS5WcL/u0/WRYGz4t0= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0/go.mod h1:vnakAaFckOMiMtOIhFI2MNH4FYrZzXCYxmb1LlhoGz8= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 h1:FFeLy03iVTXP6ffeN2iXrxfGsZGCjVx0/4KlizjyBwU= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0/go.mod h1:TMu73/k1CP8nBUpDLc71Wj/Kf7ZS9FK5b53VapRsP9o= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.35.0 h1:PB3Zrjs1sG1GBX51SXyTSoOTqcDglmsk7nT6tkKPb/k= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.35.0/go.mod h1:U2R3XyVPzn0WX7wOIypPuptulsMcPDPs/oiSVOMVnHY= -go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= -go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= -go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= -go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= -go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= -go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= -go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= -go.opentelemetry.io/proto/otlp v1.7.0 h1:jX1VolD6nHuFzOYso2E73H85i92Mv8JQYk0K9vz09os= -go.opentelemetry.io/proto/otlp v1.7.0/go.mod h1:fSKjH6YJ7HDlwzltzyMj036AJ3ejJLCgCSHGj4efDDo= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0 h1:wVZXIWjQSeSmMoxF74LzAnpVQOAFDo3pPji9Y4SOFKc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0/go.mod h1:khvBS2IggMFNwZK/6lEeHg/W57h/IX6J4URh57fuI40= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw= +go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g= +go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc= +go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8= +go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE= +go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4AtAlbuWdCYw= +go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg= +go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw= +go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA= +go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A= +go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= @@ -1174,6 +1150,8 @@ go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= @@ -1189,14 +1167,13 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 h1:1UoZQm6f0P/ZO0w1Ri+f+ifG/gXhegadRdwBIXEFWDo= golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c= @@ -1212,10 +1189,9 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= -golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1233,14 +1209,10 @@ golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= @@ -1248,23 +1220,21 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= -golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1276,9 +1246,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= -golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -1289,31 +1258,23 @@ golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201101102859-da207088b7d1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1323,7 +1284,6 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1336,15 +1296,13 @@ golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54 h1:E2/AqCUMZGgd73TQkxUMcMla25GB9i/5HOdLr+uH7Vo= -golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc h1:bH6xUXay0AIFMElXG2rQ4uiE+7ncwtiOdPfYK1NK2XA= +golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= @@ -1352,8 +1310,8 @@ golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY= +golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -1367,14 +1325,13 @@ golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -1393,13 +1350,11 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1411,8 +1366,8 @@ gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= -google.golang.org/api v0.247.0 h1:tSd/e0QrUlLsrwMKmkbQhYVa109qIintOls2Wh6bngc= -google.golang.org/api v0.247.0/go.mod h1:r1qZOPmxXffXg6xS5uhx16Fa/UFY8QU/K4bfKrnvovM= +google.golang.org/api v0.267.0 h1:w+vfWPMPYeRs8qH1aYYsFX68jMls5acWl/jocfLomwE= +google.golang.org/api v0.267.0/go.mod h1:Jzc0+ZfLnyvXma3UtaTl023TdhZu6OMBP9tJ+0EmFD0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -1427,14 +1382,14 @@ google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8 h1:mepRgnBZa07I4TRuomDE4sTIYieg/osKmzIf4USdWS4= -google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8/go.mod h1:fDMmzKV90WSg1NbozdqrE64fkuTv6mlq2zxo9ad+3yo= -google.golang.org/genproto/googleapis/bytestream v0.0.0-20250804133106-a7a43d27e69b h1:YzmLjVBzUKrr0zPM1KkGPEicd3WHSccw1k9RivnvngU= -google.golang.org/genproto/googleapis/bytestream v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:h6yxum/C2qRb4txaZRLDHK8RyS0H/o2oEDeKY4onY/Y= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 h1:M1rk8KBnUsBDg1oPGHNCxG4vc1f49epmTO7xscSajMk= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM= +google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20 h1:7ei4lp52gK1uSejlA8AZl5AJjeLUOHBQscRQZUgAcu0= +google.golang.org/genproto/googleapis/api v0.0.0-20260203192932-546029d2fa20/go.mod h1:ZdbssH/1SOVnjnDlXzxDHK2MCidiqXtbYccJNzNYPEE= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260203192932-546029d2fa20 h1:zQTtWukWCqGTV6Pt60SqvPGnEi2CE3PeeIRlu4SYgAc= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260203192932-546029d2fa20/go.mod h1:Tej9lWiwVvQJP+b43pjJIsr/3mZycXWCIyoiXmbFf40= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20 h1:Jr5R2J6F6qWyzINc+4AM8t5pfUz6beZpHp678GNrMbE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260203192932-546029d2fa20/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= @@ -1444,8 +1399,8 @@ google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyac google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= -google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig= +google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0 h1:TLkBREm4nIsEcexnCjgQd5GQWaHcqMzwQV0TX9pq8S0= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.2.0/go.mod h1:DNq5QpG7LJqD2AamLZ7zvKE0DEpVl2BSEVjFycAAjRY= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= @@ -1460,9 +1415,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -1494,7 +1448,6 @@ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= -gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g= gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= diff --git a/integration/internal/emulator/blockchain.go b/integration/internal/emulator/blockchain.go index c92288bda1a..ce308edc5f3 100644 --- a/integration/internal/emulator/blockchain.go +++ b/integration/internal/emulator/blockchain.go @@ -41,8 +41,6 @@ import ( "github.com/rs/zerolog" "github.com/onflow/cadence" - "github.com/onflow/cadence/runtime" - "github.com/onflow/flow-core-contracts/lib/go/templates" "github.com/onflow/flow-go/access/validator" @@ -50,7 +48,6 @@ import ( "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/environment" fvmerrors "github.com/onflow/flow-go/fvm/errors" - reusableRuntime "github.com/onflow/flow-go/fvm/runtime" accessmodel "github.com/onflow/flow-go/model/access" flowgo "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/metrics" @@ -118,22 +115,16 @@ func (b *Blockchain) ReloadBlockchain() (*Blockchain, error) { b.vm = fvm.NewVirtualMachine() b.vmCtx = fvm.NewContext( + b.conf.GetChainID().Chain(), fvm.WithLogger(b.conf.Logger), fvm.WithCadenceLogging(true), - fvm.WithChain(b.conf.GetChainID().Chain()), fvm.WithBlocks(b.storage), fvm.WithContractDeploymentRestricted(false), fvm.WithContractRemovalRestricted(!b.conf.ContractRemovalEnabled), fvm.WithComputationLimit(b.conf.ScriptGasLimit), fvm.WithAccountStorageLimit(b.conf.StorageLimitEnabled), fvm.WithTransactionFeesEnabled(b.conf.TransactionFeesEnabled), - fvm.WithReusableCadenceRuntimePool( - reusableRuntime.NewReusableCadenceRuntimePool( - 0, - runtime.Config{}), - ), fvm.WithEntropyProvider(b.entropyProvider), - fvm.WithEVMEnabled(true), fvm.WithAuthorizationChecksEnabled(b.conf.TransactionValidationEnabled), fvm.WithSequenceNumberCheckAndIncrementEnabled(b.conf.TransactionValidationEnabled), ) diff --git a/integration/internal/emulator/tests/accounts_test.go b/integration/internal/emulator/tests/accounts_test.go index 5102eb43f66..2a610944653 100644 --- a/integration/internal/emulator/tests/accounts_test.go +++ b/integration/internal/emulator/tests/accounts_test.go @@ -35,6 +35,7 @@ import ( fvmerrors "github.com/onflow/flow-go/fvm/errors" emulator "github.com/onflow/flow-go/integration/internal/emulator" flowgo "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" ) const testContract = "access(all) contract Test {}" @@ -992,6 +993,9 @@ func TestUpdateAccountCode(t *testing.T) { SetProposalKey(serviceAccountAddress, b.ServiceKey().Index, b.ServiceKey().SequenceNumber). SetPayer(serviceAccountAddress) + // invalid authorizer signature + tx.AddPayloadSignature(accountAddressB, 0, unittest.SignatureFixtureForTransactions()) + signer, err := b.ServiceKey().Signer() require.NoError(t, err) @@ -1004,7 +1008,7 @@ func TestUpdateAccountCode(t *testing.T) { result, err := b.ExecuteNextTransaction() assert.NoError(t, err) - assert.True(t, fvmerrors.HasErrorCode(result.Error, fvmerrors.ErrCodeAccountAuthorizationError)) + assert.True(t, fvmerrors.HasErrorCode(result.Error, fvmerrors.ErrCodeInvalidProposalSignatureError)) _, err = b.CommitBlock() assert.NoError(t, err) @@ -1041,7 +1045,7 @@ func TestImportAccountCode(t *testing.T) { script := []byte(fmt.Sprintf(` // address imports can omit leading zeros - import 0x%s + import Computer from 0x%s transaction { execute { diff --git a/integration/internal/emulator/tests/blockchain_test.go b/integration/internal/emulator/tests/blockchain_test.go index c42f81fa940..5ddfc101283 100644 --- a/integration/internal/emulator/tests/blockchain_test.go +++ b/integration/internal/emulator/tests/blockchain_test.go @@ -66,7 +66,7 @@ const counterScript = ` func GenerateAddTwoToCounterScript(counterAddress flowsdk.Address) string { return fmt.Sprintf( ` - import 0x%s + import Counting from 0x%s transaction { prepare(signer: auth(Storage, Capabilities) &Account) { @@ -109,7 +109,7 @@ func DeployAndGenerateAddTwoScript(t *testing.T, adapter *emulator.SDKAdapter) ( func GenerateGetCounterCountScript(counterAddress flowsdk.Address, accountAddress flowsdk.Address) string { return fmt.Sprintf( ` - import 0x%s + import Counting from 0x%s access(all) fun main(): Int { return getAccount(0x%s).capabilities.borrow<&Counting.Counter>(/public/counter)?.count ?? 0 diff --git a/integration/internal/emulator/tests/events_test.go b/integration/internal/emulator/tests/events_test.go index 0be7628a894..912d3d78a75 100644 --- a/integration/internal/emulator/tests/events_test.go +++ b/integration/internal/emulator/tests/events_test.go @@ -110,7 +110,7 @@ func TestEventEmitted(t *testing.T) { assert.NoError(t, err) script := []byte(fmt.Sprintf(` - import 0x%s + import Test from 0x%s transaction { execute { diff --git a/integration/internal/emulator/tests/memstore_test.go b/integration/internal/emulator/tests/memstore_test.go index a28696d14be..ae5f66bb4e2 100644 --- a/integration/internal/emulator/tests/memstore_test.go +++ b/integration/internal/emulator/tests/memstore_test.go @@ -29,7 +29,6 @@ import ( "github.com/onflow/flow-go/fvm/storage/snapshot" "github.com/onflow/flow-go/integration/internal/emulator" "github.com/onflow/flow-go/model/flow" - flowgo "github.com/onflow/flow-go/model/flow" ) func TestMemstore(t *testing.T) { @@ -37,14 +36,14 @@ func TestMemstore(t *testing.T) { t.Parallel() const blockHeight = 0 - key := flow.NewRegisterID(flowgo.EmptyAddress, "foo") + key := flow.NewRegisterID(flow.EmptyAddress, "foo") value := []byte("bar") store := emulator.NewMemoryStore() err := store.InsertExecutionSnapshot( blockHeight, &snapshot.ExecutionSnapshot{ - WriteSet: map[flowgo.RegisterID]flowgo.RegisterValue{ + WriteSet: map[flow.RegisterID]flow.RegisterValue{ key: value, }, }, @@ -77,7 +76,7 @@ func TestMemstoreSetValueToNil(t *testing.T) { t.Parallel() store := emulator.NewMemoryStore() - key := flow.NewRegisterID(flowgo.EmptyAddress, "foo") + key := flow.NewRegisterID(flow.EmptyAddress, "foo") value := []byte("bar") var nilByte []byte nilValue := nilByte @@ -86,7 +85,7 @@ func TestMemstoreSetValueToNil(t *testing.T) { err := store.InsertExecutionSnapshot( 0, &snapshot.ExecutionSnapshot{ - WriteSet: map[flowgo.RegisterID]flowgo.RegisterValue{ + WriteSet: map[flow.RegisterID]flow.RegisterValue{ key: value, }, }) @@ -103,7 +102,7 @@ func TestMemstoreSetValueToNil(t *testing.T) { err = store.InsertExecutionSnapshot( 1, &snapshot.ExecutionSnapshot{ - WriteSet: map[flowgo.RegisterID]flowgo.RegisterValue{ + WriteSet: map[flow.RegisterID]flow.RegisterValue{ key: nilValue, }, }) diff --git a/integration/internal/emulator/tests/store_test.go b/integration/internal/emulator/tests/store_test.go index 623bd92c738..f7330cc4fe1 100644 --- a/integration/internal/emulator/tests/store_test.go +++ b/integration/internal/emulator/tests/store_test.go @@ -33,7 +33,6 @@ import ( "github.com/onflow/flow-go/integration/internal/emulator" "github.com/onflow/flow-go/integration/internal/emulator/utils/unittest" "github.com/onflow/flow-go/model/flow" - flowgo "github.com/onflow/flow-go/model/flow" commonunittest "github.com/onflow/flow-go/utils/unittest" ) @@ -54,7 +53,7 @@ func TestBlocks(t *testing.T) { t.Run("should return error for not found", func(t *testing.T) { t.Run("BlockByID", func(t *testing.T) { freshId := test.IdentifierGenerator().New() - _, err := store.BlockByID(context.Background(), flowgo.Identifier(freshId)) + _, err := store.BlockByID(context.Background(), flow.Identifier(freshId)) if assert.Error(t, err) { assert.Equal(t, emulator.ErrNotFound, err) } @@ -214,7 +213,7 @@ func TestTransactionResults(t *testing.T) { result := unittest.StorableTransactionResultFixture(eventEncodingVersion) t.Run("should return error for not found", func(t *testing.T) { - txID := flowgo.Identifier(ids.New()) + txID := flow.Identifier(ids.New()) _, err := store.TransactionResultByID(context.Background(), txID) if assert.Error(t, err) { @@ -223,7 +222,7 @@ func TestTransactionResults(t *testing.T) { }) t.Run("should be able to insert result", func(t *testing.T) { - txID := flowgo.Identifier(ids.New()) + txID := flow.Identifier(ids.New()) err := store.InsertTransactionResult(txID, result) assert.NoError(t, err) @@ -366,7 +365,7 @@ func TestInsertEvents(t *testing.T) { event, err := emulator.SDKEventToFlow(events.New()) assert.NoError(t, err) - events := []flowgo.Event{*event} + events := []flow.Event{*event} var blockHeight uint64 = 1 @@ -403,9 +402,9 @@ func TestEventsByHeight(t *testing.T) { emptyBlockHeight uint64 = 2 nonExistentBlockHeight uint64 = 3 - allEvents = make([]flowgo.Event, 10) - eventsA = make([]flowgo.Event, 0, 5) - eventsB = make([]flowgo.Event, 0, 5) + allEvents = make([]flow.Event, 10) + eventsA = make([]flow.Event, 0, 5) + eventsB = make([]flow.Event, 0, 5) ) for i := range allEvents { diff --git a/integration/internal/emulator/tests/transaction_test.go b/integration/internal/emulator/tests/transaction_test.go index 13d515cf073..e1fafba73c3 100644 --- a/integration/internal/emulator/tests/transaction_test.go +++ b/integration/internal/emulator/tests/transaction_test.go @@ -37,7 +37,6 @@ import ( "github.com/onflow/cadence/common" "github.com/onflow/cadence/interpreter" - "github.com/onflow/flow-go-sdk" flowsdk "github.com/onflow/flow-go-sdk" "github.com/onflow/flow-go-sdk/crypto" "github.com/onflow/flow-go-sdk/templates" @@ -603,40 +602,6 @@ func TestSubmitTransaction_EnvelopeSignature(t *testing.T) { t.Parallel() - t.Run("Missing envelope signature", func(t *testing.T) { - - t.Parallel() - - b, adapter := setupTransactionTests( - t, - emulator.WithStorageLimitEnabled(false), - ) - serviceAccountAddress := flowsdk.Address(b.ServiceKey().Address) - - addTwoScript, _ := DeployAndGenerateAddTwoScript(t, adapter) - - tx := flowsdk.NewTransaction(). - SetScript([]byte(addTwoScript)). - SetComputeLimit(flowgo.DefaultMaxTransactionGasLimit). - SetProposalKey(serviceAccountAddress, b.ServiceKey().Index, b.ServiceKey().SequenceNumber). - SetPayer(serviceAccountAddress). - AddAuthorizer(serviceAccountAddress) - - signer, err := b.ServiceKey().Signer() - require.NoError(t, err) - - err = tx.SignPayload(serviceAccountAddress, b.ServiceKey().Index, signer) - require.NoError(t, err) - - err = adapter.SendTransaction(context.Background(), *tx) - assert.NoError(t, err) - - result, err := b.ExecuteNextTransaction() - assert.NoError(t, err) - - assert.True(t, fvmerrors.HasErrorCode(result.Error, fvmerrors.ErrCodeAccountAuthorizationError)) - }) - t.Run("Invalid account", func(t *testing.T) { t.Parallel() @@ -841,51 +806,6 @@ func TestSubmitTransaction_PayloadSignatures(t *testing.T) { t.Parallel() - t.Run("Missing payload signature", func(t *testing.T) { - - t.Parallel() - - b, adapter := setupTransactionTests( - t, - emulator.WithStorageLimitEnabled(false), - ) - serviceAccountAddress := flowsdk.Address(b.ServiceKey().Address) - - addTwoScript, _ := DeployAndGenerateAddTwoScript(t, adapter) - - // create a new account, - // authorizer must be different from payer - - accountKeys := test.AccountKeyGenerator() - - accountKeyB, _ := accountKeys.NewWithSigner() - accountKeyB.SetWeight(flowsdk.AccountKeyWeightThreshold) - - accountAddressB, err := adapter.CreateAccount(context.Background(), []*flowsdk.AccountKey{accountKeyB}, nil) - assert.NoError(t, err) - - tx := flowsdk.NewTransaction(). - SetScript([]byte(addTwoScript)). - SetComputeLimit(flowgo.DefaultMaxTransactionGasLimit). - SetProposalKey(serviceAccountAddress, b.ServiceKey().Index, b.ServiceKey().SequenceNumber). - SetPayer(serviceAccountAddress). - AddAuthorizer(accountAddressB) - - signer, err := b.ServiceKey().Signer() - require.NoError(t, err) - - err = tx.SignEnvelope(serviceAccountAddress, b.ServiceKey().Index, signer) - require.NoError(t, err) - - err = adapter.SendTransaction(context.Background(), *tx) - assert.NoError(t, err) - - result, err := b.ExecuteNextTransaction() - assert.NoError(t, err) - - assert.True(t, fvmerrors.HasErrorCode(result.Error, fvmerrors.ErrCodeAccountAuthorizationError)) - }) - t.Run("Multiple payload signers", func(t *testing.T) { t.Parallel() @@ -1445,7 +1365,7 @@ func TestGetTxByBlockIDMethods(t *testing.T) { assert.NoError(t, err) // added to fix tx matching (nil vs empty slice) - tx.PayloadSignatures = []flow.TransactionSignature{} + tx.PayloadSignatures = []flowsdk.TransactionSignature{} submittedTx = append(submittedTx, tx) diff --git a/integration/localnet/AGENTS.md b/integration/localnet/AGENTS.md new file mode 100644 index 00000000000..5981b398ef8 --- /dev/null +++ b/integration/localnet/AGENTS.md @@ -0,0 +1,75 @@ +# AGENTS.md + +## Localnet (Local Network Testing) + +A Docker-based local Flow network for manual end-to-end testing. Located in `integration/localnet/`. Particularly useful for API development and testing against a fully running network. + +### Quick Start + +All commands run from `integration/localnet/`: + +- `make bootstrap` - Generate network config and bootstrap data +- `make start` - Build images and start all nodes + metrics stack +- `make start-cached` - Start without rebuilding (faster iteration) +- `make stop` - Stop all services +- `make clean-data` - Remove all generated data and bootstrap filest + +### Network Configuration + +Node counts are configured via env vars during bootstrap: + +- `COLLECTION`, `CONSENSUS`, `EXECUTION`, `VERIFICATION`, `ACCESS`, `OBSERVER` +- Example: `make -e COLLECTION=2 CONSENSUS=3 ACCESS=2 bootstrap` +- Pre-configured variants: + - `make bootstrap-light` - Minimal network + - `make bootstrap-short-epochs` - Short epochs for epoch testing + +### Accessing the Access Node API + +Default ports for `access_1`: + +- gRPC: `localhost:4001` +- HTTP: `localhost:4003` +- REST API: `localhost:4004` +- Admin tool: `localhost:4000` +- Full port mappings: `integration/localnet/ports.nodes.json` + +### Testing Endpoints + +REST API: +```sh +curl -s http://localhost:4004/v1/blocks?height=latest +``` + +gRPC (via grpcurl): +```sh +grpcurl -plaintext localhost:4001 list +``` + +### Flow CLI + +Connect using network name `localnet` (config at `integration/localnet/client/flow-localnet.json`): + +- Service account address: `f8d6e0586b0a20c7` +- Example: `flow -n localnet accounts get f8d6e0586b0a20c7` + +### Observability + +- Grafana: `http://localhost:3000/` (no login required) +- Prometheus: `http://localhost:9090` + +### Development Iteration Workflow + +1. Make code changes +2. `make stop` +3. `make start` (or `make start-cached` if only config changed) + +For single-node rebuild: +``` +docker-compose -f docker-compose.nodes.yml build access_1 && docker-compose -f docker-compose.nodes.yml up -d access_1 +``` + +### Viewing Logs + +- All nodes: `make logs` +- Specific node: `docker-compose -f docker-compose.nodes.yml logs -f access_1` diff --git a/integration/localnet/Makefile b/integration/localnet/Makefile index 12a06fa29ab..4a2bb2a4413 100644 --- a/integration/localnet/Makefile +++ b/integration/localnet/Makefile @@ -3,6 +3,8 @@ CONSENSUS = 2 VALID_CONSENSUS := $(shell test $(CONSENSUS) -ge 2; echo $$?) EXECUTION = 2 VALID_EXECUTION := $(shell test $(EXECUTION) -ge 2; echo $$?) +LEDGER_EXECUTION = 0 +VALID_LEDGER_EXECUTION := $(shell test $(LEDGER_EXECUTION) -le $(EXECUTION); echo $$?) TEST_EXECUTION = 0 VERIFICATION = 1 ACCESS = 1 @@ -49,6 +51,8 @@ ifeq ($(strip $(VALID_EXECUTION)), 1) $(error Number of Execution nodes should be no less than 2) else ifeq ($(strip $(VALID_CONSENSUS)), 1) $(error Number of Consensus nodes should be no less than 2) +else ifeq ($(strip $(VALID_LEDGER_EXECUTION)), 1) + $(error LEDGER_EXECUTION ($(LEDGER_EXECUTION)) should not be greater than EXECUTION ($(EXECUTION))) else go run \ -ldflags="-X 'github.com/onflow/flow-go/cmd/build.commit=${COMMIT}' \ @@ -74,7 +78,8 @@ else -tracing=$(TRACING) \ -extensive-tracing=$(EXTENSIVE_TRACING) \ -consensus-delay=$(CONSENSUS_DELAY) \ - -collection-delay=$(COLLECTION_DELAY) + -collection-delay=$(COLLECTION_DELAY) \ + -ledger-execution=$(LEDGER_EXECUTION) endif # Creates a light version of the localnet with just 1 instance for each node type @@ -130,6 +135,10 @@ build-flow: stop: DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 docker compose -f docker-compose.metrics.yml -f docker-compose.nodes.yml down -v --remove-orphans +.PHONY: stop-flow +stop-flow: + DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 docker compose -f docker-compose.nodes.yml down -v + .PHONY: load load: go run ../benchmark/cmd/manual -log-level info -tps 1,1,1 -tps-durations 30s,30s @@ -152,6 +161,7 @@ clean-data: rm -rf ./bootstrap rm -rf ./trie rm -rf ./profiler + rm -rf ./sockets rm -f ./targets.nodes.json rm -f ./docker-compose.nodes.yml rm -f ./ports.nodes.json diff --git a/integration/localnet/README.md b/integration/localnet/README.md index c5846dabbf5..a61f5d7a363 100644 --- a/integration/localnet/README.md +++ b/integration/localnet/README.md @@ -32,7 +32,7 @@ FLITE is a tool for running a full version of the Flow blockchain. Before running the Flow network it is necessary to run a bootstrapping process. This generates keys for each of the nodes and a genesis block to build on. -Bootstrap a new network: +Bootstrap a new network (from [integration/localnet](https://github.com/onflow/flow-go/tree/master/integration/localnet) directory): ```sh make bootstrap diff --git a/integration/localnet/builder/bootstrap.go b/integration/localnet/builder/bootstrap.go index 539eae6a892..70be30ede2a 100644 --- a/integration/localnet/builder/bootstrap.go +++ b/integration/localnet/builder/bootstrap.go @@ -17,6 +17,8 @@ import ( "github.com/go-yaml/yaml" "github.com/onflow/flow-go/cmd/build" + "github.com/onflow/flow-go/ledger/complete/wal" + bootstrapFilenames "github.com/onflow/flow-go/model/bootstrap" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/state/protocol" "github.com/onflow/flow-go/state/protocol/protocol_state" @@ -30,6 +32,7 @@ const ( ProfilerDir = "./profiler" DataDir = "./data" TrieDir = "./trie" + SocketDir = "./sockets" DockerComposeFile = "./docker-compose.nodes.yml" DockerComposeFileVersion = "3.7" PrometheusTargetsFile = "./targets.nodes.json" @@ -62,6 +65,7 @@ var ( accessCount int observerCount int testExecutionCount int + ledgerExecutionCount int nClusters uint numViewsInStakingPhase uint64 numViewsInDKGPhase uint64 @@ -104,6 +108,7 @@ func init() { flag.DurationVar(&consensusDelay, "consensus-delay", DefaultConsensusDelay, "delay on consensus node block proposals") flag.DurationVar(&collectionDelay, "collection-delay", DefaultCollectionDelay, "delay on collection node block proposals") flag.StringVar(&logLevel, "loglevel", DefaultLogLevel, "log level for all nodes") + flag.IntVar(&ledgerExecutionCount, "ledger-execution", 0, "number of execution nodes that use remote ledger service (0 = all use local ledger, max = execution count)") } func generateBootstrapData(flowNetworkConf testnet.NetworkConfig) []testnet.ContainerConfig { @@ -176,6 +181,14 @@ func main() { flowNetworkConf := testnet.NewNetworkConfig("localnet", flowNodes, flowNetworkOpts...) displayFlowNetworkConf(flowNetworkConf) + // Validate ledger execution count + if ledgerExecutionCount < 0 { + panic(fmt.Sprintf("ledger-execution must be >= 0, got %d", ledgerExecutionCount)) + } + if ledgerExecutionCount > executionCount { + panic(fmt.Sprintf("ledger-execution (%d) must not be greater than execution count (%d)", ledgerExecutionCount, executionCount)) + } + // Generate the Flow network bootstrap files for this localnet flowNodeContainerConfigs := generateBootstrapData(flowNetworkConf) @@ -188,6 +201,10 @@ func main() { panic(err) } + // Only create ledger service if at least one execution node uses remote ledger + if ledgerExecutionCount > 0 { + dockerServices = prepareLedgerService(dockerServices, flowNodeContainerConfigs) + } dockerServices = prepareObserverServices(dockerServices, flowNodeContainerConfigs) dockerServices = prepareTestExecutionService(dockerServices, flowNodeContainerConfigs) @@ -217,7 +234,7 @@ func displayFlowNetworkConf(flowNetworkConf testnet.NetworkConfig) { } func prepareCommonHostFolders() { - for _, dir := range []string{BootstrapDir, ProfilerDir, DataDir, TrieDir} { + for _, dir := range []string{BootstrapDir, ProfilerDir, DataDir, TrieDir, SocketDir} { if err := os.RemoveAll(dir); err != nil && !errors.Is(err, fs.ErrNotExist) { panic(err) } @@ -440,9 +457,30 @@ func prepareExecutionService(container testnet.ContainerConfig, i int, n int) Se "--scheduled-callbacks-enabled=true", ) - service.Volumes = append(service.Volumes, - fmt.Sprintf("%s:/trie:z", trieDir), - ) + // Configure ledger service: execution nodes with index < ledgerExecutionCount use remote ledger + if i < ledgerExecutionCount { + // This execution node uses remote ledger service via Unix socket; mount shared socket dir (absolute path) + absSocketDir, err := filepath.Abs(SocketDir) + if err != nil { + panic(fmt.Errorf("socket dir absolute path: %w", err)) + } + service.Volumes = append(service.Volumes, + fmt.Sprintf("%s:/sockets:z", absSocketDir), + ) + service.Command = append(service.Command, + "--ledger-service-addr=unix:///sockets/ledger.sock", + ) + // Execution node depends on ledger service + service.DependsOn = append(service.DependsOn, "ledger_service_1") + // Execution nodes using remote ledger should NOT mount the trie directory + // because the ledger service manages it + } else { + // Execution nodes with index >= ledgerExecutionCount use local ledger by default (no flag needed) + // These nodes need to mount the trie directory for their local ledger + service.Volumes = append(service.Volumes, + fmt.Sprintf("%s:/trie:z", trieDir), + ) + } service.AddExposedPorts(testnet.GRPCPort) @@ -473,6 +511,8 @@ func prepareAccessService(container testnet.ContainerConfig, i int, n int) Servi "--event-query-mode=execution-nodes-only", "--tx-result-query-mode=execution-nodes-only", "--scheduled-callbacks-enabled=true", + "--extended-indexing-enabled=true", + "--extended-indexing-db-dir=/data/extended-index", ) service.AddExposedPorts( @@ -670,18 +710,16 @@ func writePrometheusConfig(serviceDisc PrometheusServiceDiscovery) error { } func openAndTruncate(filename string) (*os.File, error) { - f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0755) - if err != nil { - return nil, err - } - - // overwrite current file contents - err = f.Truncate(0) - if err != nil { - return nil, err + // Check if path exists and is a directory, remove it if so + if fi, err := os.Stat(filename); err == nil { + if fi.IsDir() { + if err := os.RemoveAll(filename); err != nil { + return nil, fmt.Errorf("failed to remove existing directory %s: %w", filename, err) + } + } } - _, err = f.Seek(0, 0) + f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return nil, err } @@ -762,6 +800,117 @@ func prepareObserverServices(dockerServices Services, flowNodeContainerConfigs [ return dockerServices } +func prepareLedgerService(dockerServices Services, flowNodeContainerConfigs []testnet.ContainerConfig) Services { + // Find the first execution node that uses remote ledger (index 0) + // The ledger service will reuse its trie directory + var firstExecutionNode *testnet.ContainerConfig + executionIndex := 0 + for _, container := range flowNodeContainerConfigs { + if container.Role == flow.RoleExecution { + if executionIndex < ledgerExecutionCount { + firstExecutionNode = &container + break + } + executionIndex++ + } + } + + if firstExecutionNode == nil { + panic("failed to find first execution node for ledger service") + } + + // Use the same trie directory as the first execution node + trieDir := "./" + filepath.Join(TrieDir, firstExecutionNode.Role.String(), firstExecutionNode.NodeID.String()) + + // Ensure trie directory exists for the ledger service + err := os.MkdirAll(trieDir, 0755) + if err != nil && !errors.Is(err, fs.ErrExist) { + panic(err) + } + + // Copy root checkpoint from bootstrap directory to trie directory on the host + // The symlinks will work inside containers because: + // 1. Execution node has both /bootstrap and /trie mounted + // 2. Ledger service has /trie mounted and can follow symlinks to /bootstrap (via execution node's mount) + // 3. We create symlinks using relative paths that work in both host and container contexts + bootstrapExecutionStateDir := filepath.Join(BootstrapDir, bootstrapFilenames.DirnameExecutionState) + checkpointSource := filepath.Join(bootstrapExecutionStateDir, bootstrapFilenames.FilenameWALRootCheckpoint) + if _, err := os.Stat(checkpointSource); err == nil { + // Checkpoint exists, create symlinks on host + // The symlinks will use relative paths that resolve correctly inside containers + // because both /bootstrap and /trie are mounted in the containers + _, err = wal.SoftlinkCheckpointFile(bootstrapFilenames.FilenameWALRootCheckpoint, bootstrapExecutionStateDir, trieDir) + if err != nil { + panic(fmt.Errorf("failed to create checkpoint symlinks: %w", err)) + } + fmt.Printf("created checkpoint symlinks in trie directory: %s\n", trieDir) + } else { + // Checkpoint doesn't exist, this is expected for fresh bootstrap + // The execution node will create it when it initializes + fmt.Printf("root checkpoint not found in %s, ledger service will start with empty state\n", checkpointSource) + } + + // Allocate ports for ledger service + ledgerServiceName := "ledger_service_1" + err = ports.AllocatePorts(ledgerServiceName, "ledger") + if err != nil { + panic(err) + } + + // Shared socket directory: use absolute path so Docker mounts the same host dir in all containers + absSocketDir, err := filepath.Abs(SocketDir) + if err != nil { + panic(fmt.Errorf("socket dir absolute path: %w", err)) + } + + // Create ledger service + // Use Unix domain socket; ledger and execution nodes share absSocketDir mounted at /sockets + service := Service{ + name: ledgerServiceName, + Image: "localnet-ledger", + Command: []string{ + "--triedir=/trie", + "--ledger-service-socket=/sockets/ledger.sock", + "--mtrie-cache-size=100", + "--checkpoint-distance=100", + "--checkpoints-to-keep=3", + fmt.Sprintf("--loglevel=%s", logLevel), + }, + Volumes: []string{ + fmt.Sprintf("%s:/trie:z", trieDir), + fmt.Sprintf("%s:/bootstrap:z", BootstrapDir), + fmt.Sprintf("%s:/sockets:z", absSocketDir), + }, + Environment: []string{ + fmt.Sprintf("GOMAXPROCS=%d", DefaultGOMAXPROCS), + }, + Labels: map[string]string{ + "org.flowfoundation.role": "ledger", + "org.flowfoundation.num": "001", + }, + } + + // Build configuration for ledger service + service.Build = Build{ + Context: "../../", + Dockerfile: "cmd/Dockerfile", + Args: map[string]string{ + "TARGET": "./cmd/ledger", + "VERSION": build.Version(), + "COMMIT": build.Commit(), + "GOARCH": runtime.GOARCH, + }, + Target: "production", + } + + dockerServices[ledgerServiceName] = service + + fmt.Println() + fmt.Println("Ledger service bootstrapping data generated...") + + return dockerServices +} + func prepareTestExecutionService(dockerServices Services, flowNodeContainerConfigs []testnet.ContainerConfig) Services { if testExecutionCount == 0 { return dockerServices diff --git a/integration/localnet/builder/ports.go b/integration/localnet/builder/ports.go index f3b8b581004..1f5f2fc02be 100644 --- a/integration/localnet/builder/ports.go +++ b/integration/localnet/builder/ports.go @@ -53,6 +53,11 @@ var config = map[string]*portConfig{ end: 8000, portCount: 2, }, + "ledger": { + start: 8000, // 8000-8100 => 50 ledger services + end: 8100, + portCount: 2, + }, } // PortAllocator is responsible for allocating and tracking container-to-host port mappings for each node diff --git a/integration/testnet/client.go b/integration/testnet/client.go index f12330dfc6a..e5129b43579 100644 --- a/integration/testnet/client.go +++ b/integration/testnet/client.go @@ -487,11 +487,11 @@ func (c *Client) CreateAccount( ctx context.Context, accountKey *sdk.AccountKey, latestBlockID sdk.Identifier, -) (sdk.Address, error) { +) (sdk.Address, *sdk.TransactionResult, error) { payer := c.SDKServiceAddress() tx, err := templates.CreateAccount([]*sdk.AccountKey{accountKey}, nil, payer) if err != nil { - return sdk.Address{}, fmt.Errorf("failed cusnctruct create account transaction %w", err) + return sdk.Address{}, nil, fmt.Errorf("failed to construct create account transaction: %w", err) } tx.SetComputeLimit(1000). SetReferenceBlockID(latestBlockID). @@ -500,23 +500,23 @@ func (c *Client) CreateAccount( err = c.SignAndSendTransaction(ctx, tx) if err != nil { - return sdk.Address{}, fmt.Errorf("failed to sign and send create account transaction %w", err) + return sdk.Address{}, nil, fmt.Errorf("failed to sign and send create account transaction %w", err) } result, err := c.WaitForSealed(ctx, tx.ID()) if err != nil { - return sdk.Address{}, fmt.Errorf("failed to wait for create account transaction to seal %w", err) + return sdk.Address{}, nil, fmt.Errorf("failed to wait for create account transaction to seal %w", err) } if result.Error != nil { - return sdk.Address{}, fmt.Errorf("failed to create new account %w", result.Error) + return sdk.Address{}, nil, fmt.Errorf("failed to create new account %w", result.Error) } if address, ok := c.UserAddress(result); ok { - return address, nil + return address, result, nil } - return sdk.Address{}, fmt.Errorf("failed to get account address of the created flow account") + return sdk.Address{}, nil, fmt.Errorf("failed to get account address of the created flow account") } func (c *Client) GetEventsForBlockIDs( diff --git a/integration/testnet/container.go b/integration/testnet/container.go index b32af817506..f2e2c27de8a 100644 --- a/integration/testnet/container.go +++ b/integration/testnet/container.go @@ -9,8 +9,6 @@ import ( "time" "github.com/cockroachdb/pebble/v2" - "github.com/dapperlabs/testingdock" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/go-connections/nat" "github.com/onflow/crypto" @@ -21,6 +19,7 @@ import ( sdk "github.com/onflow/flow-go-sdk" sdkclient "github.com/onflow/flow-go-sdk/access/grpc" + "github.com/onflow/testingdock" "github.com/onflow/flow-go/cmd/bootstrap/utils" ghostclient "github.com/onflow/flow-go/engine/ghost/client" @@ -146,11 +145,12 @@ func (c *ContainerConfig) ImageName() string { // Container represents a test Docker container for a generic Flow node. type Container struct { *testingdock.Container - Config ContainerConfig - Ports map[string]string // port mapping - datadir string // host directory bound to container's database - net *FlowNetwork // reference to the network we are a part of - opts *testingdock.ContainerOpts + Config ContainerConfig + Ports map[string]string // port mapping + portsResolved bool // true after host ports have been resolved from the running container + datadir string // host directory bound to container's database + net *FlowNetwork // reference to the network we are a part of + opts *testingdock.ContainerOpts } // Addr returns the host-accessible listening address of the container for the given container port. @@ -166,16 +166,67 @@ func (c *Container) ContainerAddr(containerPort string) string { } // Port returns the container's host port for the given container port. -// Panics if the port was not exposed. +// If the host port was auto-allocated by Docker (i.e. not pre-assigned), the actual +// port is resolved lazily by inspecting the running container. +// Panics if the port was not exposed or if resolution fails. func (c *Container) Port(containerPort string) string { port, ok := c.Ports[containerPort] if !ok { panic(fmt.Sprintf("port %s is not registered for %s", containerPort, c.Config.ContainerName)) } + if port == "" { + c.resolveHostPorts() + port = c.Ports[containerPort] + if port == "" { + panic(fmt.Sprintf("could not resolve host port for container port %s on %s", containerPort, c.Config.ContainerName)) + } + } return port } +// resolveHostPorts inspects the running Docker container to discover the actual +// host ports assigned by Docker for auto-allocated port bindings. +func (c *Container) resolveHostPorts() { + if c.portsResolved { + return + } + + ctx, cancel := context.WithTimeout(context.Background(), checkContainerTimeout) + defer cancel() + + info, err := c.net.cli.ContainerInspect(ctx, c.Container.ID) + if err != nil { + panic(fmt.Sprintf("could not inspect container %s to resolve ports: %v", c.Config.ContainerName, err)) + } + + for containerPort := range c.Ports { + if c.Ports[containerPort] != "" { + continue // already resolved or pre-assigned + } + natPort := nat.Port(fmt.Sprintf("%s/tcp", containerPort)) + bindings, ok := info.NetworkSettings.Ports[natPort] + if !ok || len(bindings) == 0 { + continue + } + c.Ports[containerPort] = bindings[0].HostPort + } + c.portsResolved = true +} + +// resetHostPorts clears cached host port values so they will be re-resolved +// on the next call to Port(). This must be called before restarting a container +// because Docker may assign different host ports for auto-allocated bindings. +func (c *Container) resetHostPorts() { + c.portsResolved = false + for k := range c.Ports { + c.Ports[k] = "" + } +} + // exposePort exposes the given container port and binds it to the given host port. +// If hostPort is empty, Docker will auto-allocate an available host port when the +// container starts. The actual port can be retrieved via Port() after the container +// is running. // If no protocol is specified, assumes TCP. func (c *Container) exposePort(containerPort, hostPort string) { // keep track of port mapping for easy lookups @@ -312,7 +363,11 @@ func (c *Container) Start() error { ctx, cancel := context.WithTimeout(context.Background(), checkContainerTimeout) defer cancel() - err := c.net.cli.ContainerStart(ctx, c.ID, types.ContainerStartOptions{}) + // Reset cached port resolution state. Docker may assign different host ports + // when restarting a container with auto-allocated ports. + c.resetHostPorts() + + err := c.net.cli.ContainerStart(ctx, c.ID, container.StartOptions{}) if err != nil { return fmt.Errorf("could not start container: %w", err) } @@ -419,30 +474,30 @@ func (c *Container) OpenState() (*state.State, error) { } // containerStopped returns true if the container is not running. -func containerStopped(state *types.ContainerJSON) bool { +func containerStopped(state *container.InspectResponse) bool { return !state.State.Running } // containerRunning returns true if the container is running. -func containerRunning(state *types.ContainerJSON) bool { +func containerRunning(state *container.InspectResponse) bool { return state.State.Running } // containerDisconnected returns true if the container is not connected to a // network. -func containerDisconnected(state *types.ContainerJSON) bool { +func containerDisconnected(state *container.InspectResponse) bool { return len(state.NetworkSettings.Networks) == 0 } // containerConnected returns true if the container is connected to a network. -func containerConnected(state *types.ContainerJSON) bool { +func containerConnected(state *container.InspectResponse) bool { return len(state.NetworkSettings.Networks) == 1 } // waitForCondition waits for the given condition to be true, checking the // condition with an exponential backoff. Returns an error if inspecting fails // or when the context expires. Returns nil when the condition is true. -func (c *Container) waitForCondition(ctx context.Context, condition func(*types.ContainerJSON) bool) error { +func (c *Container) waitForCondition(ctx context.Context, condition func(*container.InspectResponse) bool) error { retryAfter := checkContainerPeriod for { diff --git a/integration/testnet/experimental_client.go b/integration/testnet/experimental_client.go new file mode 100644 index 00000000000..53e5b836fbe --- /dev/null +++ b/integration/testnet/experimental_client.go @@ -0,0 +1,344 @@ +package testnet + +import ( + "context" + "fmt" + + "github.com/antihax/optional" + + swagger "github.com/onflow/flow/openapi/experimental/go-client-generated" +) + +// ExperimentalAPIClient wraps the generated OpenAPI client for the experimental REST API, +// providing higher-level methods for common operations. +type ExperimentalAPIClient struct { + client *swagger.APIClient +} + +// NewExperimentalAPIClient creates a new [ExperimentalAPIClient] targeting the given base URL. +// +// No error returns are expected during normal operation. +func NewExperimentalAPIClient(baseURL string) (*ExperimentalAPIClient, error) { + cfg := swagger.NewConfiguration() + cfg.BasePath = baseURL + client := swagger.NewAPIClient(cfg) + return &ExperimentalAPIClient{client: client}, nil +} + +// GetAccountTransactions fetches a single page of account transactions for the given address. +// +// Expected error returns during normal operation: +// - Returns an error with the HTTP status code and response body for non-200 responses. +func (c *ExperimentalAPIClient) GetAccountTransactions( + ctx context.Context, + address string, + opts *swagger.AccountsApiGetAccountTransactionsOpts, +) (*swagger.AccountTransactionsResponse, error) { + resp, _, err := c.client.AccountsApi.GetAccountTransactions(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("API request failed for account %s: %w", address, err) + } + return &resp, nil +} + +// GetAllAccountTransactions paginates through all account transactions for the given address +// and returns the accumulated results. The `pageSize` controls how many transactions are +// fetched per request. An optional `roles` filter restricts results to transactions where +// the account had the specified role. An optional `expand` parameter controls which nested +// fields (e.g. "transaction", "result") are included in each response entry. +// +// No error returns are expected during normal operation. +func (c *ExperimentalAPIClient) GetAllAccountTransactions( + ctx context.Context, + address string, + pageSize int, + roles *swagger.Role, + expand *[]string, +) ([]swagger.AccountTransaction, error) { + var all []swagger.AccountTransaction + + opts := buildOpts(int32(pageSize), nil, roles, expand) + + for { + resp, err := c.GetAccountTransactions(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("failed to get account transactions page: %w", err) + } + + all = append(all, resp.Transactions...) + if resp.NextCursor == "" { + break + } + cursor := resp.NextCursor + opts = buildOpts(int32(pageSize), &cursor, roles, expand) + } + return all, nil +} + +// GetAccountFungibleTransfers fetches a single page of fungible token transfers for the given address. +// +// Expected error returns during normal operation: +// - Returns an error with the HTTP status code and response body for non-200 responses. +func (c *ExperimentalAPIClient) GetAccountFungibleTransfers( + ctx context.Context, + address string, + opts *swagger.AccountsApiGetAccountFungibleTransfersOpts, +) (*swagger.AccountFungibleTransfersResponse, error) { + resp, _, err := c.client.AccountsApi.GetAccountFungibleTransfers(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("FT transfers API request failed for account %s: %w", address, err) + } + return &resp, nil +} + +// GetAllAccountFungibleTransfers paginates through all fungible token transfers for the given address. +// +// No error returns are expected during normal operation. +func (c *ExperimentalAPIClient) GetAllAccountFungibleTransfers( + ctx context.Context, + address string, + pageSize int, + opts *swagger.AccountsApiGetAccountFungibleTransfersOpts, +) ([]swagger.FungibleTokenTransfer, error) { + var all []swagger.FungibleTokenTransfer + + if opts == nil { + opts = &swagger.AccountsApiGetAccountFungibleTransfersOpts{} + } + opts.Limit = optional.NewInt32(int32(pageSize)) + + for { + resp, err := c.GetAccountFungibleTransfers(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("failed to get FT transfers page: %w", err) + } + + all = append(all, resp.Transfers...) + if resp.NextCursor == "" { + break + } + opts.Cursor = optional.NewInterface(resp.NextCursor) + } + return all, nil +} + +// GetAccountNonFungibleTransfers fetches a single page of non-fungible token transfers for the given address. +// +// Expected error returns during normal operation: +// - Returns an error with the HTTP status code and response body for non-200 responses. +func (c *ExperimentalAPIClient) GetAccountNonFungibleTransfers( + ctx context.Context, + address string, + opts *swagger.AccountsApiGetAccountNonFungibleTransfersOpts, +) (*swagger.AccountNonFungibleTransfersResponse, error) { + resp, _, err := c.client.AccountsApi.GetAccountNonFungibleTransfers(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("NFT transfers API request failed for account %s: %w", address, err) + } + return &resp, nil +} + +// GetAllAccountNonFungibleTransfers paginates through all non-fungible token transfers for the given address. +// +// No error returns are expected during normal operation. +func (c *ExperimentalAPIClient) GetAllAccountNonFungibleTransfers( + ctx context.Context, + address string, + pageSize int, + opts *swagger.AccountsApiGetAccountNonFungibleTransfersOpts, +) ([]swagger.NonFungibleTokenTransfer, error) { + var all []swagger.NonFungibleTokenTransfer + + if opts == nil { + opts = &swagger.AccountsApiGetAccountNonFungibleTransfersOpts{} + } + opts.Limit = optional.NewInt32(int32(pageSize)) + + for { + resp, err := c.GetAccountNonFungibleTransfers(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("failed to get NFT transfers page: %w", err) + } + + all = append(all, resp.Transfers...) + if resp.NextCursor == "" { + break + } + opts.Cursor = optional.NewInterface(resp.NextCursor) + } + return all, nil +} + +// GetContractByIdentifier fetches the latest deployment of the contract with the given identifier. +// +// Expected error returns during normal operation: +// - Returns an error with the HTTP status code and response body for non-200 responses. +func (c *ExperimentalAPIClient) GetContractByIdentifier( + ctx context.Context, + identifier string, + opts *swagger.ContractsApiGetContractByIdentifierOpts, +) (*swagger.ContractDeployment, error) { + resp, _, err := c.client.ContractsApi.GetContractByIdentifier(ctx, identifier, opts) + if err != nil { + return nil, fmt.Errorf("contracts API request failed for %s: %w", identifier, err) + } + return &resp, nil +} + +// GetContractDeployments fetches a single page of deployment history for the given contract. +// +// Expected error returns during normal operation: +// - Returns an error with the HTTP status code and response body for non-200 responses. +func (c *ExperimentalAPIClient) GetContractDeployments( + ctx context.Context, + identifier string, + opts *swagger.ContractsApiGetContractDeploymentsOpts, +) (*swagger.ContractDeploymentsResponse, error) { + resp, _, err := c.client.ContractsApi.GetContractDeployments(ctx, identifier, opts) + if err != nil { + return nil, fmt.Errorf("contract deployments API request failed for %s: %w", identifier, err) + } + return &resp, nil +} + +// GetAllContractDeployments paginates through all deployment history pages for the given contract +// and returns the accumulated results. +// +// No error returns are expected during normal operation. +func (c *ExperimentalAPIClient) GetAllContractDeployments( + ctx context.Context, + identifier string, + pageSize int, +) ([]swagger.ContractDeployment, error) { + var all []swagger.ContractDeployment + opts := &swagger.ContractsApiGetContractDeploymentsOpts{ + Limit: optional.NewInt32(int32(pageSize)), + } + for { + resp, err := c.GetContractDeployments(ctx, identifier, opts) + if err != nil { + return nil, fmt.Errorf("failed to get contract deployments page: %w", err) + } + all = append(all, resp.Deployments...) + if resp.NextCursor == "" { + break + } + opts.Cursor = optional.NewInterface(resp.NextCursor) + } + return all, nil +} + +// GetContracts fetches a single page of contracts (latest deployment per contract). +// +// Expected error returns during normal operation: +// - Returns an error with the HTTP status code and response body for non-200 responses. +func (c *ExperimentalAPIClient) GetContracts( + ctx context.Context, + opts *swagger.ContractsApiGetContractsOpts, +) (*swagger.ContractsResponse, error) { + resp, _, err := c.client.ContractsApi.GetContracts(ctx, opts) + if err != nil { + return nil, fmt.Errorf("contracts list API request failed: %w", err) + } + return &resp, nil +} + +// GetAllContracts paginates through all contracts pages and returns the accumulated results. +// expand optionally specifies fields to expand inline (e.g. []string{"code"}). +// +// No error returns are expected during normal operation. +func (c *ExperimentalAPIClient) GetAllContracts( + ctx context.Context, + pageSize int, + expand []string, +) ([]swagger.ContractDeployment, error) { + var all []swagger.ContractDeployment + opts := &swagger.ContractsApiGetContractsOpts{ + Limit: optional.NewInt32(int32(pageSize)), + } + if len(expand) > 0 { + opts.Expand = optional.NewInterface(expand) + } + for { + resp, err := c.GetContracts(ctx, opts) + if err != nil { + return nil, fmt.Errorf("failed to get contracts page: %w", err) + } + all = append(all, resp.Contracts...) + if resp.NextCursor == "" { + break + } + opts.Cursor = optional.NewInterface(resp.NextCursor) + } + return all, nil +} + +// GetContractsByAccount fetches a single page of contracts deployed to the given account. +// +// Expected error returns during normal operation: +// - Returns an error with the HTTP status code and response body for non-200 responses. +func (c *ExperimentalAPIClient) GetContractsByAccount( + ctx context.Context, + address string, + opts *swagger.ContractsApiGetContractsByAccountOpts, +) (*swagger.ContractsResponse, error) { + resp, _, err := c.client.ContractsApi.GetContractsByAccount(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("contracts by account API request failed for %s: %w", address, err) + } + return &resp, nil +} + +// GetAllContractsByAccount paginates through all contract pages for the given account and +// returns the accumulated results. +// expand optionally specifies fields to expand inline (e.g. []string{"code"}). +// +// No error returns are expected during normal operation. +func (c *ExperimentalAPIClient) GetAllContractsByAccount( + ctx context.Context, + address string, + pageSize int, + expand []string, +) ([]swagger.ContractDeployment, error) { + var all []swagger.ContractDeployment + opts := &swagger.ContractsApiGetContractsByAccountOpts{ + Limit: optional.NewInt32(int32(pageSize)), + } + if len(expand) > 0 { + opts.Expand = optional.NewInterface(expand) + } + for { + resp, err := c.GetContractsByAccount(ctx, address, opts) + if err != nil { + return nil, fmt.Errorf("failed to get contracts by account page: %w", err) + } + all = append(all, resp.Contracts...) + if resp.NextCursor == "" { + break + } + opts.Cursor = optional.NewInterface(resp.NextCursor) + } + return all, nil +} + +// buildOpts constructs [swagger.AccountsApiGetAccountTransactionsOpts] from the given parameters. +func buildOpts( + limit int32, + cursor *string, + roles *swagger.Role, + expand *[]string, +) *swagger.AccountsApiGetAccountTransactionsOpts { + opts := &swagger.AccountsApiGetAccountTransactionsOpts{ + Limit: optional.NewInt32(limit), + } + if cursor != nil { + opts.Cursor = optional.NewInterface(*cursor) + } + if roles != nil { + opts.Roles = optional.NewInterface(*roles) + } + if expand != nil { + opts.Expand = optional.NewInterface(*expand) + } + return opts +} diff --git a/integration/testnet/network.go b/integration/testnet/network.go index eb04c114a08..b56f2c8450a 100644 --- a/integration/testnet/network.go +++ b/integration/testnet/network.go @@ -15,15 +15,7 @@ import ( "testing" "time" - "github.com/onflow/flow-go/follower/database" - "github.com/onflow/flow-go/state/protocol/datastore" - "github.com/onflow/flow-go/state/protocol/protocol_state" - "github.com/onflow/flow-go/storage/operation/pebbleimpl" - - "github.com/dapperlabs/testingdock" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" - dockercontainer "github.com/docker/docker/api/types/container" dockerclient "github.com/docker/docker/client" io_prometheus_client "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" @@ -32,13 +24,14 @@ import ( "github.com/stretchr/testify/require" "github.com/onflow/cadence" - "github.com/onflow/flow-go-sdk/crypto" + "github.com/onflow/testingdock" "github.com/onflow/flow-go/cmd/bootstrap/dkg" "github.com/onflow/flow-go/cmd/bootstrap/run" "github.com/onflow/flow-go/cmd/bootstrap/utils" consensus_follower "github.com/onflow/flow-go/follower" + "github.com/onflow/flow-go/follower/database" "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/insecure/cmd" "github.com/onflow/flow-go/model/bootstrap" @@ -53,9 +46,12 @@ import ( "github.com/onflow/flow-go/network/p2p/keyutils" "github.com/onflow/flow-go/network/p2p/translator" clusterstate "github.com/onflow/flow-go/state/cluster" + "github.com/onflow/flow-go/state/protocol/datastore" "github.com/onflow/flow-go/state/protocol/inmem" + "github.com/onflow/flow-go/state/protocol/protocol_state" "github.com/onflow/flow-go/state/protocol/protocol_state/kvstore" "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" "github.com/onflow/flow-go/utils/io" "github.com/onflow/flow-go/utils/unittest" ) @@ -86,6 +82,8 @@ const ( DefaultExecutionDataServiceDir = "/data/execution_data" // DefaultExecutionStateDir for the execution data service blobstore. DefaultExecutionStateDir = "/data/execution_state" + // DefaultExtendedIndexingDir for the extended indexing database. + DefaultExtendedIndexingDir = "/data/extended_index" // DefaultChunkDataPackDir for the chunk data packs DefaultChunkDataPackDir = "/data/chunk_data_pack" // DefaultProfilerDir is the default directory for the profiler @@ -160,6 +158,19 @@ type FlowNetwork struct { BootstrapDir string BootstrapSnapshot *inmem.Snapshot BootstrapData *BootstrapData + + // deferredFollowerConfigs holds consensus follower configurations that must be + // initialized after the network starts. Initialization is deferred because the + // follower setup requires resolving Docker-allocated host ports, which are only + // available after containers are running. + deferredFollowerConfigs []deferredFollowerConfig +} + +// deferredFollowerConfig stores the data needed to initialize a consensus follower +// after the network has started and container ports are available. +type deferredFollowerConfig struct { + rootProtocolSnapshotPath string + followerConf ConsensusFollowerConfig } // CorruptedIdentities returns the identities of corrupted nodes in testnet (for BFT testing). @@ -229,7 +240,7 @@ func (net *FlowNetwork) Start(ctx context.Context) { cli, err := dockerclient.NewClientWithOpts(dockerclient.FromEnv, dockerclient.WithAPIVersionNegotiation()) require.NoError(net.t, err) - containers, err := cli.ContainerList(ctx, types.ContainerListOptions{}) + containers, err := cli.ContainerList(ctx, container.ListOptions{}) require.NoError(net.t, err) t := net.t @@ -242,7 +253,22 @@ func (net *FlowNetwork) Start(ctx context.Context) { t.Log("starting flow network") net.suite.Start(ctx) - containers, err = cli.ContainerList(ctx, types.ContainerListOptions{}) + // populate corrupted port mapping after containers have started and Docker has + // auto-allocated the host ports + for _, c := range net.Containers { + if c.Config.Corrupted { + net.CorruptedPortMapping[c.Config.NodeID] = c.Port(cmd.CorruptNetworkPort) + } + } + + // initialize consensus followers now that containers are running and host ports + // can be resolved + for _, dc := range net.deferredFollowerConfigs { + net.addConsensusFollower(t, dc.rootProtocolSnapshotPath, dc.followerConf) + } + net.deferredFollowerConfigs = nil + + containers, err = cli.ContainerList(ctx, container.ListOptions{}) require.NoError(net.t, err) t.Logf("%v (%v) after starting flow network, found %d docker containers", time.Now().UTC(), t.Name(), len(containers)) @@ -657,10 +683,14 @@ func PrepareFlowNetwork(t *testing.T, networkConf NetworkConfig, chainID flow.Ch rootProtocolSnapshotPath := filepath.Join(bootstrapDir, bootstrap.PathRootProtocolStateSnapshot) - // add each follower to the network + // defer consensus follower initialization until Start(), because followers need + // to resolve Docker-allocated host ports which are only available after containers start. for _, followerConf := range networkConf.ConsensusFollowers { t.Logf("add consensus follower %v", followerConf.NodeID) - flowNetwork.addConsensusFollower(t, rootProtocolSnapshotPath, followerConf, confs) + flowNetwork.deferredFollowerConfigs = append(flowNetwork.deferredFollowerConfigs, deferredFollowerConfig{ + rootProtocolSnapshotPath: rootProtocolSnapshotPath, + followerConf: followerConf, + }) } t.Logf("%v finish preparing flow network for %v", time.Now().UTC(), t.Name()) @@ -668,7 +698,7 @@ func PrepareFlowNetwork(t *testing.T, networkConf NetworkConfig, chainID flow.Ch return flowNetwork } -func (net *FlowNetwork) addConsensusFollower(t *testing.T, rootProtocolSnapshotPath string, followerConf ConsensusFollowerConfig, _ []ContainerConfig) { +func (net *FlowNetwork) addConsensusFollower(t *testing.T, rootProtocolSnapshotPath string, followerConf ConsensusFollowerConfig) { tmpdir := makeTempSubDir(t, net.baseTempdir, "flow-consensus-follower") // create a directory for the follower database @@ -723,11 +753,11 @@ func (net *FlowNetwork) addConsensusFollower(t *testing.T, rootProtocolSnapshotP } func (net *FlowNetwork) StopContainerByName(ctx context.Context, containerName string) error { - container := net.ContainerByName(containerName) - if container == nil { + c := net.ContainerByName(containerName) + if c == nil { return fmt.Errorf("%s container not found", containerName) } - return net.cli.ContainerStop(ctx, container.ID, dockercontainer.StopOptions{}) + return net.cli.ContainerStop(ctx, c.ID, container.StopOptions{}) } type ObserverConfig struct { @@ -802,20 +832,20 @@ func (net *FlowNetwork) AddObserver(t *testing.T, conf ObserverConfig) *Containe opts: &containerOpts, } - nodeContainer.exposePort(GRPCPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCPort, "") nodeContainer.AddFlag("rpc-addr", nodeContainer.ContainerAddr(GRPCPort)) nodeContainer.AddFlag("state-stream-addr", nodeContainer.ContainerAddr(GRPCPort)) - nodeContainer.exposePort(GRPCSecurePort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCSecurePort, "") nodeContainer.AddFlag("secure-rpc-addr", nodeContainer.ContainerAddr(GRPCSecurePort)) - nodeContainer.exposePort(GRPCWebPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCWebPort, "") nodeContainer.AddFlag("http-addr", nodeContainer.ContainerAddr(GRPCWebPort)) - nodeContainer.exposePort(AdminPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(AdminPort, "") nodeContainer.AddFlag("admin-addr", nodeContainer.ContainerAddr(AdminPort)) - nodeContainer.exposePort(RESTPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(RESTPort, "") nodeContainer.AddFlag("rest-addr", nodeContainer.ContainerAddr(RESTPort)) nodeContainer.opts.HealthCheck = testingdock.HealthCheckCustom(nodeContainer.HealthcheckCallback()) @@ -895,7 +925,7 @@ func (net *FlowNetwork) AddNode(t *testing.T, bootstrapDir string, nodeConf Cont if !nodeConf.Ghost { switch nodeConf.Role { case flow.RoleCollection: - nodeContainer.exposePort(GRPCPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCPort, "") nodeContainer.AddFlag("ingress-addr", nodeContainer.ContainerAddr(GRPCPort)) // set a low timeout so that all nodes agree on the current view more quickly @@ -904,7 +934,7 @@ func (net *FlowNetwork) AddNode(t *testing.T, bootstrapDir string, nodeConf Cont t.Logf("%v hotstuff startup time will be in 8 seconds: %v", time.Now().UTC(), hotstuffStartupTime) case flow.RoleExecution: - nodeContainer.exposePort(GRPCPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCPort, "") nodeContainer.AddFlag("rpc-addr", nodeContainer.ContainerAddr(GRPCPort)) nodeContainer.AddFlag("triedir", DefaultExecutionRootDir) @@ -913,17 +943,17 @@ func (net *FlowNetwork) AddNode(t *testing.T, bootstrapDir string, nodeConf Cont nodeContainer.AddFlag("register-dir", DefaultRegisterDir) case flow.RoleAccess: - nodeContainer.exposePort(GRPCPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCPort, "") nodeContainer.AddFlag("rpc-addr", nodeContainer.ContainerAddr(GRPCPort)) nodeContainer.AddFlag("state-stream-addr", nodeContainer.ContainerAddr(GRPCPort)) - nodeContainer.exposePort(GRPCSecurePort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCSecurePort, "") nodeContainer.AddFlag("secure-rpc-addr", nodeContainer.ContainerAddr(GRPCSecurePort)) - nodeContainer.exposePort(GRPCWebPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCWebPort, "") nodeContainer.AddFlag("http-addr", nodeContainer.ContainerAddr(GRPCWebPort)) - nodeContainer.exposePort(RESTPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(RESTPort, "") nodeContainer.AddFlag("rest-addr", nodeContainer.ContainerAddr(RESTPort)) // uncomment line below to point the access node exclusively to a single collection node @@ -931,7 +961,7 @@ func (net *FlowNetwork) AddNode(t *testing.T, bootstrapDir string, nodeConf Cont nodeContainer.AddFlag("collection-ingress-port", GRPCPort) if nodeContainer.IsFlagSet("supports-observer") { - nodeContainer.exposePort(PublicNetworkPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(PublicNetworkPort, "") nodeContainer.AddFlag("public-network-address", nodeContainer.ContainerAddr(PublicNetworkPort)) } @@ -961,17 +991,17 @@ func (net *FlowNetwork) AddNode(t *testing.T, bootstrapDir string, nodeConf Cont } // enable Admin server for all real nodes - nodeContainer.exposePort(AdminPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(AdminPort, "") nodeContainer.AddFlag("admin-addr", nodeContainer.ContainerAddr(AdminPort)) // enable healthchecks for all nodes (via admin server) nodeContainer.opts.HealthCheck = testingdock.HealthCheckCustom(nodeContainer.HealthcheckCallback()) if nodeConf.EnableMetricsServer { - nodeContainer.exposePort(MetricsPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(MetricsPort, "") } } else { - nodeContainer.exposePort(GRPCPort, testingdock.RandomPort(t)) + nodeContainer.exposePort(GRPCPort, "") nodeContainer.AddFlag("rpc-addr", nodeContainer.ContainerAddr(GRPCPort)) if nodeContainer.IsFlagSet("supports-observer") { @@ -991,9 +1021,8 @@ func (net *FlowNetwork) AddNode(t *testing.T, bootstrapDir string, nodeConf Cont if nodeConf.Corrupted { // corrupted nodes are running with a Corrupted Conduit Factory (CCF), hence need to bind their // CCF port to local host, so they can be accessible by the orchestrator network. - hostPort := testingdock.RandomPort(t) - nodeContainer.exposePort(cmd.CorruptNetworkPort, hostPort) - net.CorruptedPortMapping[nodeConf.NodeID] = hostPort + // The host port is auto-allocated by Docker and resolved after the network starts. + nodeContainer.exposePort(cmd.CorruptNetworkPort, "") } suiteContainer := net.suite.Container(*opts) diff --git a/integration/tests/access/cohort1/access_api_test.go b/integration/tests/access/cohort1/access_api_test.go index e2b04df8024..633193d3fac 100644 --- a/integration/tests/access/cohort1/access_api_test.go +++ b/integration/tests/access/cohort1/access_api_test.go @@ -1383,6 +1383,106 @@ func (s *AccessAPISuite) TestSystemTransactions() { s.testSystemTransactionsRest(systemCollection, blockID, txResults) } +// TestExecutionReceiptsAndResultsConsistency verifies the consistency of the execution receipt and +// result endpoints using a real sealed block. The test chains the following queries and asserts +// cross-API consistency: +// +// 1. GetExecutionResultForBlockID — the sealed execution result for a known block. +// 2. GetExecutionReceiptsByBlockID — all execution receipts stored for the block; the result ID +// is taken directly from a receipt's Meta field (avoiding proto round-trip hash issues). +// 3. GetExecutionResultByID — fetch the result by the ID obtained from the receipt; must reference +// the same block as in step 1. +// 4. GetExecutionReceiptsByResultID — all receipts committing to that result ID. +// +// Invariants checked: +// - GetExecutionResultForBlockID succeeds and the result references the queried block. +// - GetExecutionReceiptsByBlockID returns at least one receipt for the sealed block. +// - GetExecutionResultByID(receipt.Meta.ResultId) returns a result whose BlockId matches blockID. +// - Every receipt from GetExecutionReceiptsByResultID commits to the expected result ID. +// - Receipts from GetExecutionReceiptsByResultID are a subset of those from GetExecutionReceiptsByBlockID. +func (s *AccessAPISuite) TestExecutionReceiptsAndResultsConsistency() { + rpcClient := s.an2Client.RPCClient() + + // Wait until block 5 is both available and sealed (GetExecutionResultForBlockID requires + // the finalized seal to be indexed, which happens after the block is finalized and sealed). + var blockID flow.Identifier + var sealedResultResp *accessproto.ExecutionResultForBlockIDResponse + require.Eventually(s.T(), func() bool { + resp, err := rpcClient.GetBlockHeaderByHeight(s.ctx, &accessproto.GetBlockHeaderByHeightRequest{Height: 5}) + if err != nil { + return false + } + id := convert.MessageToIdentifier(resp.GetBlock().GetId()) + resultResp, err := rpcClient.GetExecutionResultForBlockID(s.ctx, &accessproto.GetExecutionResultForBlockIDRequest{ + BlockId: id[:], + }) + if err != nil { + return false + } + blockID = id + sealedResultResp = resultResp + return true + }, 60*time.Second, 500*time.Millisecond) + + // GetExecutionResultForBlockID — verify the sealed result references this block. + s.Require().NotNil(sealedResultResp.ExecutionResult) + s.Require().Equal(blockID, convert.MessageToIdentifier(sealedResultResp.ExecutionResult.BlockId), + "sealed result's BlockId must match the queried block") + + // GetExecutionReceiptsByBlockID — fetch all receipts stored for this block. + // Use the result ID directly from a receipt's Meta field to avoid proto round-trip + // hash recomputation, which is unreliable due to nil-vs-empty-slice differences. + receiptsByBlock, err := rpcClient.GetExecutionReceiptsByBlockID(s.ctx, &accessproto.GetExecutionReceiptsByBlockIDRequest{ + BlockId: blockID[:], + }) + s.Require().NoError(err) + s.Require().NotEmpty(receiptsByBlock.Receipts, "must have at least one receipt for the sealed block") + + for _, receipt := range receiptsByBlock.Receipts { + s.Require().NotNil(receipt.Meta, "all receipts must have meta set") + } + + // Take the result ID from the first receipt's Meta — this is the as-stored ID with no recomputation. + resultID := convert.MessageToIdentifier(receiptsByBlock.Receipts[0].Meta.ResultId) + + // GetExecutionResultByID — must return a result whose BlockId matches our block. + resultByID, err := rpcClient.GetExecutionResultByID(s.ctx, &accessproto.GetExecutionResultByIDRequest{ + Id: convert.IdentifierToMessage(resultID), + }) + s.Require().NoError(err) + s.Require().NotNil(resultByID.ExecutionResult) + s.Require().Equal(blockID, convert.MessageToIdentifier(resultByID.ExecutionResult.BlockId), + "result fetched by ID must reference the same block") + + // GetExecutionReceiptsByResultID — all receipts committing to this result ID. + receiptsByResult, err := rpcClient.GetExecutionReceiptsByResultID(s.ctx, &accessproto.GetExecutionReceiptsByResultIDRequest{ + ResultId: convert.IdentifierToMessage(resultID), + }) + s.Require().NoError(err) + s.Require().NotEmpty(receiptsByResult.Receipts, "must have at least one receipt for the result") + + // Every receipt from GetExecutionReceiptsByResultID must commit to the requested result ID. + for _, receipt := range receiptsByResult.Receipts { + s.Require().NotNil(receipt.Meta) + s.Require().Equal(resultID, convert.MessageToIdentifier(receipt.Meta.ResultId), + "all receipts returned by result ID must commit to the requested result") + } + + // Receipts from GetExecutionReceiptsByResultID must be a subset of those from GetExecutionReceiptsByBlockID. + byBlockSet := make(map[string]struct{}, len(receiptsByBlock.Receipts)) + for _, receipt := range receiptsByBlock.Receipts { + key := convert.MessageToIdentifier(receipt.Meta.ExecutorId).String() + + convert.MessageToIdentifier(receipt.Meta.ResultId).String() + byBlockSet[key] = struct{}{} + } + for _, receipt := range receiptsByResult.Receipts { + key := convert.MessageToIdentifier(receipt.Meta.ExecutorId).String() + + convert.MessageToIdentifier(receipt.Meta.ResultId).String() + s.Require().Contains(byBlockSet, key, + "every receipt returned by result ID must also appear in the receipts for the block") + } +} + func (s *AccessAPISuite) testSystemTransactionsGrpc(systemCollection *flow.Collection, blockID flow.Identifier) []*accessmodel.TransactionResult { rpcClient := s.an2Client.RPCClient() diff --git a/integration/tests/access/cohort2/observer_indexer_enabled_test.go b/integration/tests/access/cohort2/observer_indexer_enabled_test.go index 1149ad65acf..1aa464d416b 100644 --- a/integration/tests/access/cohort2/observer_indexer_enabled_test.go +++ b/integration/tests/access/cohort2/observer_indexer_enabled_test.go @@ -67,14 +67,18 @@ func (s *ObserverIndexerEnabledSuite) SetupTest() { "GetAccount": {}, "GetAccountAtLatestBlock": {}, "GetAccountAtBlockHeight": {}, + "GetExecutionReceiptsByBlockID": {}, + "GetExecutionReceiptsByResultID": {}, } s.localRest = map[string]struct{}{ - "getBlocksByIDs": {}, - "getBlocksByHeight": {}, - "getBlockPayloadByID": {}, - "getNetworkParameters": {}, - "getNodeVersionInfo": {}, + "getBlocksByIDs": {}, + "getBlocksByHeight": {}, + "getBlockPayloadByID": {}, + "getNetworkParameters": {}, + "getNodeVersionInfo": {}, + "getExecutionReceiptsByBlockID": {}, + "getExecutionReceiptsByResultID": {}, } s.testedRPCs = s.getRPCs @@ -457,6 +461,32 @@ func (s *ObserverIndexerEnabledSuite) TestAllObserverIndexedRPCsHappyPath() { return res.ExecutionResult, err }) + // GetExecutionReceiptsByBlockID + checkRPC(func(client accessproto.AccessAPIClient) (any, error) { + res, err := client.GetExecutionReceiptsByBlockID(ctx, &accessproto.GetExecutionReceiptsByBlockIDRequest{ + BlockId: blockWithAccount.Block.Id, + }) + if err != nil { + return nil, err + } + return res.Receipts, nil + }) + + // GetExecutionReceiptsByResultID + checkRPC(func(client accessproto.AccessAPIClient) (any, error) { + converted, err := convert.MessageToBlock(blockWithAccount.Block) + require.NoError(t, err) + + resultId := converted.Payload.Results[0].ID() + res, err := client.GetExecutionReceiptsByResultID(ctx, &accessproto.GetExecutionReceiptsByResultIDRequest{ + ResultId: convert.IdentifierToMessage(resultId), + }) + if err != nil { + return nil, err + } + return res.Receipts, nil + }) + // GetTransaction checkRPC(func(client accessproto.AccessAPIClient) (any, error) { res, err := client.GetTransaction(ctx, &accessproto.GetTransactionRequest{ @@ -656,6 +686,18 @@ func (s *ObserverIndexerEnabledSuite) getRPCs() []RPCTest { _, err := client.GetExecutionResultForBlockID(ctx, &accessproto.GetExecutionResultForBlockIDRequest{}) return err }}, + {name: "GetExecutionReceiptsByBlockID", call: func(ctx context.Context, client accessproto.AccessAPIClient) error { + _, err := client.GetExecutionReceiptsByBlockID(ctx, &accessproto.GetExecutionReceiptsByBlockIDRequest{ + BlockId: make([]byte, 32), + }) + return err + }}, + {name: "GetExecutionReceiptsByResultID", call: func(ctx context.Context, client accessproto.AccessAPIClient) error { + _, err := client.GetExecutionReceiptsByResultID(ctx, &accessproto.GetExecutionReceiptsByResultIDRequest{ + ResultId: make([]byte, 32), + }) + return err + }}, } } @@ -740,5 +782,15 @@ func (s *ObserverIndexerEnabledSuite) getRestEndpoints() []RestEndpointTest { method: http.MethodGet, path: "/node_version_info", }, + { + name: "getExecutionReceiptsByBlockID", + method: http.MethodGet, + path: "/execution_receipts?block_id=" + block.ID().String(), + }, + { + name: "getExecutionReceiptsByResultID", + method: http.MethodGet, + path: "/execution_receipts/results/" + executionResult.ID().String(), + }, } } diff --git a/integration/tests/access/cohort2/observer_test.go b/integration/tests/access/cohort2/observer_test.go index 797ed6b8045..5bbcd093c47 100644 --- a/integration/tests/access/cohort2/observer_test.go +++ b/integration/tests/access/cohort2/observer_test.go @@ -71,11 +71,13 @@ func (s *ObserverSuite) SetupTest() { } s.localRest = map[string]struct{}{ - "getBlocksByIDs": {}, - "getBlocksByHeight": {}, - "getBlockPayloadByID": {}, - "getNetworkParameters": {}, - "getNodeVersionInfo": {}, + "getBlocksByIDs": {}, + "getBlocksByHeight": {}, + "getBlockPayloadByID": {}, + "getNetworkParameters": {}, + "getNodeVersionInfo": {}, + "getExecutionReceiptsByBlockID": {}, + "getExecutionReceiptsByResultID": {}, } s.testedRPCs = s.getRPCs @@ -395,6 +397,18 @@ func (s *ObserverSuite) getRPCs() []RPCTest { _, err := client.GetExecutionResultForBlockID(ctx, &accessproto.GetExecutionResultForBlockIDRequest{}) return err }}, + {name: "GetExecutionReceiptsByBlockID", call: func(ctx context.Context, client accessproto.AccessAPIClient) error { + _, err := client.GetExecutionReceiptsByBlockID(ctx, &accessproto.GetExecutionReceiptsByBlockIDRequest{ + BlockId: make([]byte, 32), + }) + return err + }}, + {name: "GetExecutionReceiptsByResultID", call: func(ctx context.Context, client accessproto.AccessAPIClient) error { + _, err := client.GetExecutionReceiptsByResultID(ctx, &accessproto.GetExecutionReceiptsByResultIDRequest{ + ResultId: make([]byte, 32), + }) + return err + }}, } } @@ -419,6 +433,11 @@ func (s *ObserverSuite) getRestEndpoints() []RestEndpointTest { method: http.MethodGet, path: "/transactions/" + transactionId, }, + { + name: "getTransactionsByBlockID", + method: http.MethodGet, + path: "/transactions?block_id=" + block.ID().String(), + }, { name: "createTransaction", method: http.MethodPost, @@ -430,6 +449,11 @@ func (s *ObserverSuite) getRestEndpoints() []RestEndpointTest { method: http.MethodGet, path: fmt.Sprintf("/transaction_results/%s?block_id=%s&collection_id=%s", transactionId, block.ID().String(), collection.ID().String()), }, + { + name: "getTransactionResultsByBlock", + method: http.MethodGet, + path: "/transaction_results?block_id=" + block.ID().String(), + }, { name: "getBlocksByIDs", method: http.MethodGet, @@ -486,6 +510,16 @@ func (s *ObserverSuite) getRestEndpoints() []RestEndpointTest { method: http.MethodGet, path: "/node_version_info", }, + { + name: "getExecutionReceiptsByBlockID", + method: http.MethodGet, + path: "/execution_receipts?block_id=" + block.ID().String(), + }, + { + name: "getExecutionReceiptsByResultID", + method: http.MethodGet, + path: "/execution_receipts/results/" + executionResult.ID().String(), + }, } } diff --git a/integration/tests/access/cohort3/consensus_follower_test.go b/integration/tests/access/cohort3/consensus_follower_test.go index 26817eeef69..492f1d696ce 100644 --- a/integration/tests/access/cohort3/consensus_follower_test.go +++ b/integration/tests/access/cohort3/consensus_follower_test.go @@ -53,9 +53,20 @@ func (s *ConsensusFollowerSuite) SetupTest() { s.log = unittest.LoggerForTest(s.Suite.T(), zerolog.InfoLevel) s.log.Info().Msg("================> SetupTest") s.ctx, s.cancel = context.WithCancel(context.Background()) - s.buildNetworkConfig() - // start the network + followerNodeIDs := s.buildNetworkConfig() + // start the network (consensus followers are initialized during Start) s.net.Start(s.ctx) + + // set up follower managers after Start, since consensus followers are created + // during Start() when container ports are available + var err error + follower1 := s.net.ConsensusFollowerByID(followerNodeIDs[0]) + s.followerMgr1, err = newFollowerManager(s.T(), follower1) + require.NoError(s.T(), err) + + follower2 := s.net.ConsensusFollowerByID(followerNodeIDs[1]) + s.followerMgr2, err = newFollowerManager(s.T(), follower2) + require.NoError(s.T(), err) } // TestReceiveBlocks tests the following @@ -115,7 +126,10 @@ func (s *ConsensusFollowerSuite) TestReceiveBlocks() { }) } -func (s *ConsensusFollowerSuite) buildNetworkConfig() { +// buildNetworkConfig prepares the network configuration and returns the follower node IDs. +// The consensus followers themselves are initialized later during Start() when container +// ports become available. +func (s *ConsensusFollowerSuite) buildNetworkConfig() []flow.Identifier { // staked access node s.stakedID = unittest.IdentifierFixture() @@ -165,13 +179,7 @@ func (s *ConsensusFollowerSuite) buildNetworkConfig() { conf := testnet.NewNetworkConfig("consensus follower test", net, testnet.WithConsensusFollowers(followerConfigs...)) s.net = testnet.PrepareFlowNetwork(s.T(), conf, flow.Localnet) - follower1 := s.net.ConsensusFollowerByID(followerConfigs[0].NodeID) - s.followerMgr1, err = newFollowerManager(s.T(), follower1) - require.NoError(s.T(), err) - - follower2 := s.net.ConsensusFollowerByID(followerConfigs[1].NodeID) - s.followerMgr2, err = newFollowerManager(s.T(), follower2) - require.NoError(s.T(), err) + return []flow.Identifier{followerConfigs[0].NodeID, followerConfigs[1].NodeID} } // TODO: Move this to unittest and resolve the circular dependency issue diff --git a/integration/tests/access/cohort3/extended_indexing_contracts_test.go b/integration/tests/access/cohort3/extended_indexing_contracts_test.go new file mode 100644 index 00000000000..e98f3c5ffc2 --- /dev/null +++ b/integration/tests/access/cohort3/extended_indexing_contracts_test.go @@ -0,0 +1,285 @@ +package cohort3 + +import ( + "context" + "encoding/base64" + "encoding/hex" + "fmt" + "strconv" + "time" + + "github.com/antihax/optional" + sdk "github.com/onflow/flow-go-sdk" + "github.com/stretchr/testify/require" + + swagger "github.com/onflow/flow/openapi/experimental/go-client-generated" + + "github.com/onflow/flow-go/integration/testnet" + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/dsl" +) + +// testContractName is the name used for the contract deployed during contract indexing tests. +const testContractName = "IndexingTestContract" + +// contractV1 is the initial version of the test contract deployed to the service account. +var contractV1 = dsl.Contract{ + Name: testContractName, + Members: []dsl.CadenceCode{ + dsl.Code(` + access(all) let version: String + init() { self.version = "1.0" } + `), + }, +} + +// contractV2 is the updated version of the test contract, used to exercise the update path. +var contractV2 = dsl.Contract{ + Name: testContractName, + Members: []dsl.CadenceCode{ + dsl.Code(` + access(all) let version: String + init() { self.version = "2.0" } + `), + }, +} + +// TestContractLifecycle verifies the full contract deployment lifecycle through the extended indexer: +// 1. Deploy a contract (AccountContractAdded → deployment indexed at the deploy block) +// 2. Update the contract (AccountContractUpdated → second deployment indexed) +// 3. Verify all REST endpoints: +// - GET /experimental/v1/contracts/{identifier} returns the latest deployment +// - GET /experimental/v1/contracts/{identifier}/deployments returns both in newest-first order +// - GET /experimental/v1/contracts lists the contract +// - GET /experimental/v1/accounts/{address}/contracts scopes to the service account +// - Pagination via next_cursor works for both /contracts and /deployments +func (s *ExtendedIndexingSuite) TestContractLifecycle() { + t := s.T() + ctx := context.Background() + + t.Logf("%v ================> START TESTING %v", time.Now().UTC(), t.Name()) + defer t.Logf("%v ================> FINISH TESTING %v", time.Now().UTC(), t.Name()) + + accessClient, err := s.net.ContainerByName(testnet.PrimaryAN).TestnetClient() + s.Require().NoError(err) + + // ---- Step 1: Deploy contractV1 ---- + refBlockID, err := accessClient.GetLatestBlockID(ctx) + s.Require().NoError(err) + + deployTx, err := accessClient.DeployContract(ctx, sdk.Identifier(refBlockID), contractV1) + s.Require().NoError(err) + + deployResult, err := accessClient.WaitForSealed(ctx, deployTx.ID()) + s.Require().NoError(err) + s.Require().NoError(deployResult.Error, "contract deploy transaction should succeed") + t.Logf("contract v1 deployed at block %d, tx %s", deployResult.BlockHeight, deployTx.ID()) + + // ---- Step 2: Update to contractV2 ---- + refBlockID, err = accessClient.GetLatestBlockID(ctx) + s.Require().NoError(err) + + updateTx, err := accessClient.UpdateContract(ctx, sdk.Identifier(refBlockID), contractV2) + s.Require().NoError(err) + + updateResult, err := accessClient.WaitForSealed(ctx, updateTx.ID()) + s.Require().NoError(err) + s.Require().NoError(updateResult.Error, "contract update transaction should succeed") + t.Logf("contract v2 deployed at block %d, tx %s", updateResult.BlockHeight, updateTx.ID()) + + // ---- Step 3: Wait for the extended indexer to process both blocks ---- + waitCtx, waitCancel := context.WithTimeout(ctx, 120*time.Second) + defer waitCancel() + + err = accessClient.WaitUntilIndexed(waitCtx, updateResult.BlockHeight+5) + s.Require().NoError(err, "extended indexer did not catch up in time") + t.Log("extended indexer caught up") + + // Derive identifiers for assertions. + serviceAddr := flow.Address(accessClient.SDKServiceAddress()) + contractID := fmt.Sprintf("A.%s.%s", serviceAddr.Hex(), testContractName) + t.Logf("contract identifier: %s", contractID) + + deploy1Code := []byte(contractV1.ToCadence()) + deploy1CodeHash := accessmodel.CadenceCodeHash(deploy1Code) + deploy1 := accessmodel.ContractDeployment{ + ContractName: testContractName, + Address: serviceAddr, + BlockHeight: deployResult.BlockHeight, + TransactionID: flow.Identifier(deployTx.ID()), + Code: deploy1Code, + CodeHash: deploy1CodeHash, + } + + deploy2Code := []byte(contractV2.ToCadence()) + deploy2CodeHash := accessmodel.CadenceCodeHash(deploy2Code) + deploy2 := accessmodel.ContractDeployment{ + ContractName: testContractName, + Address: serviceAddr, + BlockHeight: updateResult.BlockHeight, + TransactionID: flow.Identifier(updateTx.ID()), + Code: deploy2Code, + CodeHash: deploy2CodeHash, + } + + // ---- Step 4: Verify GET /experimental/v1/contracts/{identifier} ---- + s.verifyContractLatestDeployment(contractID, deploy2) + + // ---- Step 5: Verify GET /experimental/v1/contracts/{identifier}/deployments ---- + // The API returns deployments newest-first (descending block height). + s.verifyContractDeploymentHistory(contractID, []accessmodel.ContractDeployment{deploy2, deploy1}) + + // ---- Step 6: Verify GET /experimental/v1/contracts lists the contract ---- + s.verifyContractInList(contractID, deploy2) + + // ---- Step 7: Verify GET /experimental/v1/accounts/{address}/contracts scopes correctly ---- + s.verifyContractsByAddress(serviceAddr.Hex(), deploy2) + + // ---- Step 8: Verify pagination for deployments ---- + s.verifyContractDeploymentPagination(contractID) +} + +// verifyContractLatestDeployment polls GET /experimental/v1/contracts/{identifier} until it +// returns the most recent deployment, then asserts all key fields. +func (s *ExtendedIndexingSuite) verifyContractLatestDeployment(contractID string, expected accessmodel.ContractDeployment) { + ctx := context.Background() + + var d *swagger.ContractDeployment + require.Eventually(s.T(), func() bool { + resp, err := s.apiClient.GetContractByIdentifier(ctx, contractID, &swagger.ContractsApiGetContractByIdentifierOpts{ + Expand: optional.NewInterface([]string{"code"}), + }) + if err != nil { + s.T().Logf("GET contract %s failed: %v", contractID, err) + return false + } + d = resp + return true + }, 30*time.Second, 1*time.Second, "GET contract %s should succeed", contractID) + + s.Equal(contractID, d.ContractId, "contract_id should match") + s.Equal(strconv.FormatUint(expected.BlockHeight, 10), d.BlockHeight, "block_height should match") + s.Equal(expected.TransactionID.String(), d.TransactionId, "transaction_id should match") + s.Equal(base64.StdEncoding.EncodeToString(expected.Code), d.Code, "code should match") + s.Equal(hex.EncodeToString(expected.CodeHash), d.CodeHash, "code_hash should match") + + s.T().Logf("verified latest deployment for %s at height %s", contractID, d.BlockHeight) +} + +// verifyContractDeploymentHistory polls GET /experimental/v1/contracts/{identifier}/deployments +// until two deployments are present, then asserts correct ordering (newest first). +func (s *ExtendedIndexingSuite) verifyContractDeploymentHistory(contractID string, expected []accessmodel.ContractDeployment) { + ctx := context.Background() + + var deployments []swagger.ContractDeployment + require.Eventually(s.T(), func() bool { + resp, err := s.apiClient.GetContractDeployments(ctx, contractID, &swagger.ContractsApiGetContractDeploymentsOpts{ + Expand: optional.NewInterface([]string{"code"}), + }) + if err != nil { + s.T().Logf("GET contract deployments %s failed: %v", contractID, err) + return false + } + deployments = resp.Deployments + return true + }, 30*time.Second, 1*time.Second, "GET contract deployments %s should succeed", contractID) + + s.Require().Len(deployments, 2, "should have exactly 2 deployments") + + for i, exp := range expected { + d := deployments[i] + s.Equal(accessmodel.ContractID(exp.Address, exp.ContractName), d.ContractId, "deployment at index %d should have matching contract_id", i) + s.Equal(strconv.FormatUint(exp.BlockHeight, 10), d.BlockHeight, "deployment at index %d should have matching block_height", i) + s.Equal(exp.TransactionID.String(), d.TransactionId, "deployment at index %d should have matching transaction_id", i) + s.Equal(base64.StdEncoding.EncodeToString(exp.Code), d.Code, "deployment at index %d should have matching code", i) + s.Equal(hex.EncodeToString(exp.CodeHash), d.CodeHash, "deployment at index %d should have matching code_hash", i) + } + + s.T().Logf("verified deployment history for %s: %d deployments", contractID, len(expected)) +} + +// verifyContractInList paginates GET /experimental/v1/contracts until the expected contract +// appears with its latest deployment, then asserts all key fields. +func (s *ExtendedIndexingSuite) verifyContractInList(contractID string, expected accessmodel.ContractDeployment) { + ctx := context.Background() + + var all []swagger.ContractDeployment + require.Eventually(s.T(), func() bool { + contracts, err := s.apiClient.GetAllContracts(ctx, 20, []string{"code"}) + if err != nil { + s.T().Logf("GET /contracts failed: %v", err) + return false + } + all = contracts + return true + }, 30*time.Second, 1*time.Second, "GET /contracts should succeed") + + for _, d := range all { + if d.ContractId == contractID { + s.Equal(accessmodel.ContractID(expected.Address, expected.ContractName), d.ContractId, "contract_id should match") + s.Equal(strconv.FormatUint(expected.BlockHeight, 10), d.BlockHeight, "block_height should match") + s.Equal(expected.TransactionID.String(), d.TransactionId, "transaction_id should match") + s.Equal(base64.StdEncoding.EncodeToString(expected.Code), d.Code, "code should match") + s.Equal(hex.EncodeToString(expected.CodeHash), d.CodeHash, "code_hash should match") + s.T().Logf("verified %s appears in /contracts list at height %s", contractID, d.BlockHeight) + return + } + } + s.Require().Fail("contract should appear in /contracts list", "contract %s not found in /contracts list", contractID) +} + +// verifyContractsByAddress paginates GET /experimental/v1/accounts/{address}/contracts and +// verifies the expected contract is present at its latest deployment. +func (s *ExtendedIndexingSuite) verifyContractsByAddress(address string, expected accessmodel.ContractDeployment) { + ctx := context.Background() + + var all []swagger.ContractDeployment + require.Eventually(s.T(), func() bool { + contracts, err := s.apiClient.GetAllContractsByAccount(ctx, address, 20, []string{"code"}) + if err != nil { + s.T().Logf("GET /accounts/%s/contracts failed: %v", address, err) + return false + } + all = contracts + return true + }, 30*time.Second, 1*time.Second, "GET /accounts/%s/contracts should succeed", address) + + for _, d := range all { + expectedContractID := accessmodel.ContractID(expected.Address, expected.ContractName) + if d.ContractId == expectedContractID { + s.Equal(expectedContractID, d.ContractId, "contract_id should match") + s.Equal(strconv.FormatUint(expected.BlockHeight, 10), d.BlockHeight, "block_height should match") + s.Equal(expected.TransactionID.String(), d.TransactionId, "transaction_id should match") + s.Equal(base64.StdEncoding.EncodeToString(expected.Code), d.Code, "code should match") + s.Equal(hex.EncodeToString(expected.CodeHash), d.CodeHash, "code_hash should match") + s.T().Logf("verified %s appears under address %s", expectedContractID, address) + return + } + } + s.Require().Fail("contract should appear in /accounts/%s/contracts list", + "contract %s not found in /accounts/%s/contracts list", address, accessmodel.ContractID(expected.Address, expected.ContractName), address) +} + +// verifyContractDeploymentPagination verifies that paginating through +// GET /experimental/v1/contracts/{identifier}/deployments with limit=1 returns the same entries +// as a single large-page request. +func (s *ExtendedIndexingSuite) verifyContractDeploymentPagination(contractID string) { + ctx := context.Background() + + allAtOnce, err := s.apiClient.GetAllContractDeployments(ctx, contractID, 100) + s.Require().NoError(err, "bulk fetch of contract deployments should succeed") + + allPaged, err := s.apiClient.GetAllContractDeployments(ctx, contractID, 1) + s.Require().NoError(err, "paginated fetch of contract deployments should succeed") + + s.Require().Equal(len(allAtOnce), len(allPaged), + "paginated deployments should equal bulk-fetched deployments") + + for i := range allAtOnce { + s.Equal(allAtOnce[i].BlockHeight, allPaged[i].BlockHeight, + "deployment at index %d should have matching block_height", i) + } + + s.T().Logf("pagination verified for %s: %d deployments", contractID, len(allAtOnce)) +} diff --git a/integration/tests/access/cohort3/extended_indexing_scheduled_txs_test.go b/integration/tests/access/cohort3/extended_indexing_scheduled_txs_test.go new file mode 100644 index 00000000000..8ec68cc8e57 --- /dev/null +++ b/integration/tests/access/cohort3/extended_indexing_scheduled_txs_test.go @@ -0,0 +1,243 @@ +package cohort3 + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "time" + + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/integration/testnet" + "github.com/onflow/flow-go/integration/tests/lib" + "github.com/onflow/flow-go/model/flow" +) + +// TestScheduledTransactionLifecycle tests the full lifecycle: +// 1. Schedule a transaction (Scheduled event → status "scheduled") +// 2. Wait for execution (Executed event → status "executed") +// 3. Schedule and cancel another (Canceled event → status "cancelled") +// 4. Verify all data via the REST endpoints and pagination. +func (s *ExtendedIndexingSuite) TestScheduledTransactionLifecycle() { + accessClient, err := s.net.ContainerByName(testnet.PrimaryAN).TestnetClient() + s.Require().NoError(err) + + sc := systemcontracts.SystemContractsForChain(s.net.Root().HeaderBody.ChainID) + + // Deploy the test handler contract. + deployTxID, err := lib.DeployScheduledTransactionsTestContract(accessClient, sc) + s.Require().NoError(err, "could not deploy test handler contract") + + _, err = accessClient.WaitForSealed(context.Background(), deployTxID) + s.Require().NoError(err) + s.T().Log("test handler contract deployed") + + // ---- Schedule tx1 with a near-future timestamp so it executes quickly ---- + nearFutureTimestamp := time.Now().Unix() + 5 + scheduledID1, err := lib.ScheduleTransactionAtTimestamp(nearFutureTimestamp, accessClient, sc) + s.Require().NoError(err) + s.Require().NotZero(scheduledID1) + s.T().Logf("scheduled tx1 with scheduler ID: %d", scheduledID1) + + // ---- Schedule tx2 far in the future, then cancel it ---- + futureTimestamp := time.Now().Unix() + 3600 + scheduledID2, err := lib.ScheduleTransactionAtTimestamp(futureTimestamp, accessClient, sc) + s.Require().NoError(err) + s.Require().NotZero(scheduledID2) + s.T().Logf("scheduled tx2 with scheduler ID: %d", scheduledID2) + + cancelledID, err := lib.CancelTransactionByID(scheduledID2, accessClient, sc) + s.Require().NoError(err) + s.T().Logf("cancelled tx2 (scheduler ID: %d, cancel event ID: %d)", scheduledID2, cancelledID) + + // ---- Wait for the extended indexer to process enough blocks ---- + latestHeader, err := accessClient.GetLatestFinalizedBlockHeader(context.Background()) + s.Require().NoError(err) + + waitCtx, waitCancel := context.WithTimeout(context.Background(), 120*time.Second) + defer waitCancel() + err = accessClient.WaitUntilIndexed(waitCtx, uint64(latestHeader.Height)+5) + s.Require().NoError(err, "extended indexer did not catch up in time") + s.T().Log("extended indexer caught up") + + // ---- Verify tx1 is executed ---- + s.verifyScheduledTxStatus(scheduledID1, "executed") + + // ---- Verify tx2 is cancelled ---- + s.verifyScheduledTxStatus(scheduledID2, "cancelled") + + // ---- Verify the /scheduled endpoint lists both ---- + allTxs := s.fetchAllScheduledTxs(20) + s.T().Logf("found %d scheduled transactions in /scheduled", len(allTxs)) + + var foundID1, foundID2 bool + for _, tx := range allTxs { + idStr := fmt.Sprintf("%v", tx["id"]) + if idStr == fmt.Sprintf("%d", scheduledID1) { + foundID1 = true + s.Equal("executed", tx["status"], "tx1 should be executed") + } + if idStr == fmt.Sprintf("%d", scheduledID2) { + foundID2 = true + s.Equal("cancelled", tx["status"], "tx2 should be cancelled") + } + } + s.True(foundID1, "tx1 (executed) should appear in /scheduled") + s.True(foundID2, "tx2 (cancelled) should appear in /scheduled") + + // ---- Verify /accounts/{address}/scheduled scopes to owner ---- + ownerAddr := flow.Address(accessClient.SDKServiceAddress()).String() + addrTxs := s.fetchAllScheduledTxsByAddress(ownerAddr, 20) + s.T().Logf("found %d scheduled transactions in /accounts/{address}/scheduled", len(addrTxs)) + + var addrFoundID1, addrFoundID2 bool + for _, tx := range addrTxs { + idStr := fmt.Sprintf("%v", tx["id"]) + if idStr == fmt.Sprintf("%d", scheduledID1) { + addrFoundID1 = true + } + if idStr == fmt.Sprintf("%d", scheduledID2) { + addrFoundID2 = true + } + } + s.True(addrFoundID1, "tx1 should appear in /accounts/{address}/scheduled") + s.True(addrFoundID2, "tx2 should appear in /accounts/{address}/scheduled") + + // ---- Verify pagination works via /scheduled with limit=1 ---- + s.verifyScheduledTxPagination() + + // ---- Verify status filter ---- + executedTxs := s.fetchScheduledTxsWithFilter("status=executed") + for _, tx := range executedTxs { + s.Equal("executed", tx["status"], "status filter should only return executed txs") + } + + cancelledTxs := s.fetchScheduledTxsWithFilter("status=cancelled") + for _, tx := range cancelledTxs { + s.Equal("cancelled", tx["status"], "status filter should only return cancelled txs") + } +} + +// verifyScheduledTxStatus polls GET /experimental/v1/scheduled/transaction/{id} until the +// expected status is returned. +func (s *ExtendedIndexingSuite) verifyScheduledTxStatus(id uint64, expectedStatus string) { + url := fmt.Sprintf("%s/experimental/v1/scheduled/transaction/%d", s.restBaseURL, id) + require.Eventually(s.T(), func() bool { + tx := s.fetchScheduledTxJSON(url) + if tx == nil { + return false + } + actual, _ := tx["status"].(string) + if actual != expectedStatus { + s.T().Logf("waiting for tx %d status %q, got %q", id, expectedStatus, actual) + return false + } + return true + }, 60*time.Second, 2*time.Second, "tx %d did not reach status %q", id, expectedStatus) +} + +// fetchAllScheduledTxs paginates through GET /experimental/v1/scheduled and returns all results. +func (s *ExtendedIndexingSuite) fetchAllScheduledTxs(pageSize int) []map[string]any { + return s.collectScheduledPages(fmt.Sprintf("%s/experimental/v1/scheduled?limit=%d", s.restBaseURL, pageSize)) +} + +// fetchAllScheduledTxsByAddress paginates through GET /experimental/v1/accounts/{address}/scheduled. +func (s *ExtendedIndexingSuite) fetchAllScheduledTxsByAddress(address string, pageSize int) []map[string]any { + return s.collectScheduledPages(fmt.Sprintf("%s/experimental/v1/accounts/%s/scheduled?limit=%d", s.restBaseURL, address, pageSize)) +} + +// fetchScheduledTxsWithFilter fetches /experimental/v1/scheduled with the given query string filter. +func (s *ExtendedIndexingSuite) fetchScheduledTxsWithFilter(filter string) []map[string]any { + url := fmt.Sprintf("%s/experimental/v1/scheduled?limit=100&%s", s.restBaseURL, filter) + body := s.fetchScheduledTxJSONBody(url) + if body == nil { + return nil + } + txs, _ := body["scheduled_transactions"].([]any) + return toMapSlice(txs) +} + +// verifyScheduledTxPagination verifies that paginating through results one at a time yields the +// same total as fetching all at once. +func (s *ExtendedIndexingSuite) verifyScheduledTxPagination() { + allAtOnce := s.fetchAllScheduledTxs(100) + allPaged := s.collectScheduledPages(fmt.Sprintf("%s/experimental/v1/scheduled?limit=1", s.restBaseURL)) + + s.Require().Equal(len(allAtOnce), len(allPaged), + "paginated results should equal unpaginated results") + + for i := range allAtOnce { + s.Equal(allAtOnce[i]["id"], allPaged[i]["id"], + "tx at index %d should have the same ID", i) + } +} + +// collectScheduledPages follows next_cursor links to collect all transactions across all pages. +func (s *ExtendedIndexingSuite) collectScheduledPages(firstURL string) []map[string]any { + var all []map[string]any + url := firstURL + for { + body := s.fetchScheduledTxJSONBody(url) + if body == nil { + break + } + txs, _ := body["scheduled_transactions"].([]any) + all = append(all, toMapSlice(txs)...) + + nextCursor, _ := body["next_cursor"].(string) + if nextCursor == "" { + break + } + url = fmt.Sprintf("%s&cursor=%s", firstURL, nextCursor) + } + return all +} + +// fetchScheduledTxJSON fetches JSON from the given URL. Returns nil on non-200 or error. +func (s *ExtendedIndexingSuite) fetchScheduledTxJSON(url string) map[string]any { + resp, err := http.Get(url) //nolint:gosec + if err != nil { + return nil + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil + } + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil + } + var result map[string]any + if err := json.Unmarshal(body, &result); err != nil { + return nil + } + return result +} + +// fetchScheduledTxJSONBody fetches JSON from the given URL with require.Eventually retry logic. +func (s *ExtendedIndexingSuite) fetchScheduledTxJSONBody(url string) map[string]any { + var result map[string]any + require.Eventually(s.T(), func() bool { + r := s.fetchScheduledTxJSON(url) + if r == nil { + return false + } + result = r + return true + }, 30*time.Second, 1*time.Second, "REST GET %s should succeed", url) + return result +} + +// toMapSlice converts a []any (from JSON unmarshaling) to []map[string]any. +func toMapSlice(in []any) []map[string]any { + out := make([]map[string]any, 0, len(in)) + for _, item := range in { + if m, ok := item.(map[string]any); ok { + out = append(out, m) + } + } + return out +} diff --git a/integration/tests/access/cohort3/extended_indexing_test.go b/integration/tests/access/cohort3/extended_indexing_test.go new file mode 100644 index 00000000000..c84415ae372 --- /dev/null +++ b/integration/tests/access/cohort3/extended_indexing_test.go @@ -0,0 +1,504 @@ +package cohort3 + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "slices" + "strings" + "testing" + "time" + + "github.com/antihax/optional" + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + + "github.com/onflow/cadence" + sdk "github.com/onflow/flow-go-sdk" + sdkcrypto "github.com/onflow/flow-go-sdk/crypto" + swagger "github.com/onflow/flow/openapi/experimental/go-client-generated" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/integration/testnet" + "github.com/onflow/flow-go/integration/tests/lib" + "github.com/onflow/flow-go/model/flow" +) + +const ( + // sendFlowTokensScript is a Cadence script that transfers Flow tokens to the given address. + sendFlowTokensScript = ` +import FungibleToken from 0x%s +import FlowToken from 0x%s + +transaction(amount: UFix64, to: Address) { + let sentVault: @{FungibleToken.Vault} + + prepare(signer: auth(BorrowValue) &Account) { + let vaultRef = signer.storage.borrow(from: /storage/flowTokenVault) + ?? panic("Could not borrow reference to the owner's Vault!") + self.sentVault <- vaultRef.withdraw(amount: amount) + } + + execute { + let receiverRef = getAccount(to) + .capabilities.borrow<&{FungibleToken.Receiver}>(/public/flowTokenReceiver) + ?? panic("Could not borrow receiver reference to the recipient's Vault") + receiverRef.deposit(from: <-self.sentVault) + } +} +` +) + +type transactionExpectation struct { + txID flow.Identifier + address flow.Address + expectedRoles []string + unexpectedRoles []string +} + +func TestExtendedIndexing(t *testing.T) { + suite.Run(t, new(ExtendedIndexingSuite)) +} + +// ExtendedIndexingSuite verifies that the extended indexer (account_transactions) correctly indexes +// data when enabled on an access node. It uses the gRPC API to confirm that block heights are +// being processed through the full pipeline: +// +// block production → execution data sync → execution state indexing → extended indexing +type ExtendedIndexingSuite struct { + suite.Suite + net *testnet.FlowNetwork + cancel context.CancelFunc + apiClient *testnet.ExperimentalAPIClient + restBaseURL string +} + +func (s *ExtendedIndexingSuite) SetupSuite() { + consensusConfigs := []func(config *testnet.NodeConfig){ + testnet.WithAdditionalFlag("--cruise-ctl-fallback-proposal-duration=250ms"), + testnet.WithAdditionalFlagf("--required-verification-seal-approvals=%d", 1), + testnet.WithAdditionalFlagf("--required-construction-seal-approvals=%d", 1), + testnet.WithLogLevel(zerolog.FatalLevel), + } + + executionConfigs := []func(config *testnet.NodeConfig){ + testnet.WithLogLevel(zerolog.FatalLevel), + // Enable scheduled transaction execution so PendingExecution/Executed events are emitted. + testnet.WithAdditionalFlag("--scheduled-callbacks-enabled=true"), + } + + // Access node with execution data sync, execution data indexing, and extended indexing enabled. + accessNodeOpts := []func(config *testnet.NodeConfig){ + testnet.WithLogLevel(zerolog.InfoLevel), + testnet.WithAdditionalFlag("--execution-data-sync-enabled=true"), + testnet.WithAdditionalFlag("--execution-data-indexing-enabled=true"), + testnet.WithAdditionalFlagf("--execution-data-dir=%s", testnet.DefaultExecutionDataServiceDir), + testnet.WithAdditionalFlagf("--execution-state-dir=%s", testnet.DefaultExecutionStateDir), + testnet.WithAdditionalFlag("--extended-indexing-enabled=true"), + testnet.WithAdditionalFlagf("--extended-indexing-db-dir=%s", testnet.DefaultExtendedIndexingDir), + } + + nodeConfigs := []testnet.NodeConfig{ + testnet.NewNodeConfig(flow.RoleCollection, testnet.WithLogLevel(zerolog.FatalLevel)), + testnet.NewNodeConfig(flow.RoleCollection, testnet.WithLogLevel(zerolog.FatalLevel)), + testnet.NewNodeConfig(flow.RoleExecution, executionConfigs...), + testnet.NewNodeConfig(flow.RoleExecution, executionConfigs...), + testnet.NewNodeConfig(flow.RoleConsensus, consensusConfigs...), + testnet.NewNodeConfig(flow.RoleConsensus, consensusConfigs...), + testnet.NewNodeConfig(flow.RoleConsensus, consensusConfigs...), + testnet.NewNodeConfig(flow.RoleVerification, testnet.WithLogLevel(zerolog.FatalLevel)), + testnet.NewNodeConfig(flow.RoleAccess, accessNodeOpts...), + } + + conf := testnet.NewNetworkConfig("access_extended_indexing_test", nodeConfigs) + s.net = testnet.PrepareFlowNetwork(s.T(), conf, flow.Localnet) + + ctx, cancel := context.WithCancel(context.Background()) + s.cancel = cancel + s.net.Start(ctx) + + restPort := s.net.ContainerByName(testnet.PrimaryAN).Port(testnet.RESTPort) + s.restBaseURL = fmt.Sprintf("http://localhost:%s", restPort) + + apiClient, err := testnet.NewExperimentalAPIClient(s.restBaseURL) + s.Require().NoError(err) + s.apiClient = apiClient +} + +func (s *ExtendedIndexingSuite) TearDownSuite() { + if s.net != nil { + s.net.Remove() + s.net = nil + } + if s.cancel != nil { + s.cancel() + s.cancel = nil + } +} + +// TestExtendedIndexing verifies the REST API endpoint for querying account transactions. +// It exercises the full pipeline: transaction submission → indexing → REST API response, including +// pagination and role filtering. +func (s *ExtendedIndexingSuite) TestExtendedIndexing() { + expectations := s.runTransactions() + for _, expectation := range expectations { + s.verifyAccountTransactionRoles(expectation.address.String(), expectation.txID.String(), expectation.expectedRoles, expectation.unexpectedRoles) + } + + // Verify that transaction bodies and results are populated and match the standard REST API + s.verifyTransactionDetailsFromAPI(expectations) + + serviceClient, err := s.net.ContainerByName(testnet.PrimaryAN).TestnetClient() + s.Require().NoError(err) + serviceAddr := flow.Address(serviceClient.SDKServiceAddress()) + + // Verify API pagination + s.verifyPagination(serviceAddr.String()) + + // Verify API role filtering + s.verifyRoleFiltering(serviceAddr.String()) +} + +func (s *ExtendedIndexingSuite) runTransactions() []transactionExpectation { + ctx := context.Background() + + // Step 1: Get a testnet client for the service account + serviceClient, err := s.net.ContainerByName(testnet.PrimaryAN).TestnetClient() + s.Require().NoError(err) + + latestBlockID, err := serviceClient.GetLatestBlockID(ctx) + s.Require().NoError(err) + + // Step 2: Create a new account + accountPrivateKey := lib.RandomPrivateKey() + accountKey := sdk.NewAccountKey(). + FromPrivateKey(accountPrivateKey). + SetHashAlgo(sdkcrypto.SHA3_256). + SetWeight(sdk.AccountKeyWeightThreshold) + + newAccountAddress, createTxResult, err := serviceClient.CreateAccount(ctx, accountKey, sdk.Identifier(latestBlockID)) + s.Require().NoError(err) + createAccountTxID := flow.Identifier(createTxResult.TransactionID) + s.T().Logf("created new account: %s", newAccountAddress) + + // Step 3: Transfer Flow tokens to the new account + latestBlockID, err = serviceClient.GetLatestBlockID(ctx) + s.Require().NoError(err) + + transferTx := buildFlowTransferTx(s.T(), newAccountAddress, "1.0") + transferTx. + SetReferenceBlockID(sdk.Identifier(latestBlockID)). + SetProposalKey(serviceClient.SDKServiceAddress(), 0, serviceClient.GetAndIncrementSeqNumber()). + SetPayer(serviceClient.SDKServiceAddress()). + SetComputeLimit(9999) + + err = serviceClient.SignAndSendTransaction(ctx, transferTx) + s.Require().NoError(err) + + transferTxResult, err := serviceClient.WaitForSealed(ctx, transferTx.ID()) + s.Require().NoError(err) + s.Require().NoError(transferTxResult.Error) + s.T().Logf("transfer tx sealed at height %d, tx ID: %s", transferTxResult.BlockHeight, transferTx.ID()) + + // Step 4: Wait for the extended indexer to process these blocks + waitCtx, waitCancel := context.WithTimeout(ctx, 120*time.Second) + defer waitCancel() + + err = serviceClient.WaitUntilIndexed(waitCtx, transferTxResult.BlockHeight+10) + s.Require().NoError(err) + + serviceAddr := flow.Address(serviceClient.SDKServiceAddress()) + newAddr := flow.Address(newAccountAddress) + transferTxID := flow.Identifier(transferTx.ID()) + + return []transactionExpectation{ + { + txID: createAccountTxID, + address: serviceAddr, + expectedRoles: []string{"authorizer", "payer", "proposer", "interacted"}, + unexpectedRoles: nil, + }, + { + txID: createAccountTxID, + address: newAddr, + expectedRoles: []string{"interacted"}, + unexpectedRoles: []string{"authorizer", "payer", "proposer"}, + }, + { + txID: transferTxID, + address: serviceAddr, + expectedRoles: []string{"authorizer", "payer", "proposer", "interacted"}, + unexpectedRoles: nil, + }, + { + txID: transferTxID, + address: newAddr, + expectedRoles: []string{"interacted"}, + unexpectedRoles: []string{"authorizer", "payer", "proposer"}, + }, + } +} + +// verifyAccountTransactionRoles fetches account transactions from the REST API and verifies that +// the given transaction has the expected roles and does not have the unexpected roles. +func (s *ExtendedIndexingSuite) verifyAccountTransactionRoles( + address string, + txID string, + expectedRoles []string, + unexpectedRoles []string, +) { + allTxs := s.collectAllPages(address, 50, nil, nil) + s.T().Logf("account %s has %d transactions via REST API", address, len(allTxs)) + + var foundTx *swagger.AccountTransaction + for i, tx := range allTxs { + if tx.TransactionId == txID { + foundTx = &allTxs[i] + break + } + } + s.Require().NotNil(foundTx, "tx %s not found in account %s REST API response", txID, address) + + for _, role := range expectedRoles { + s.Contains(foundTx.Roles, role, "account %s should have role %s for tx %s", address, role, txID) + } + for _, role := range unexpectedRoles { + s.NotContains(foundTx.Roles, role, "account %s should not have role %s for tx %s", address, role, txID) + } +} + +// verifyPagination verifies the REST API pagination behavior for the given account. It checks that +// limit=1 returns exactly 1 result with a next_cursor, that the second page contains a different +// transaction, and that paginating through all results yields the same total count as an unpaginated request. +func (s *ExtendedIndexingSuite) verifyPagination(address string) { + // Paginating through all results should yield the same count as a single unpaginated request + allUnpaginated := s.fetchAccountTransactions(address, nil) + allPaginated := s.collectAllPages(address, 1, nil, nil) + s.Require().Len(allUnpaginated.Transactions, len(allPaginated), "unpaginated and paginated transactions should have the same length") + + for i, unpagedTx := range allUnpaginated.Transactions { + pagedTx := allPaginated[i] + s.Equal(unpagedTx, pagedTx, "paged transaction should be the same as the unpaged transaction") + if i > 0 { + s.NotEqual(unpagedTx.TransactionId, allUnpaginated.Transactions[i-1].TransactionId, "paged transaction should have a different transaction ID than the previous unpaged transaction") + s.NotEqual(pagedTx.TransactionId, allPaginated[i-1].TransactionId, "paged transaction should have a different transaction ID than the previous paged transaction") + } + } + +} + +// verifyRoleFiltering verifies that the REST API role filter returns only transactions with the +// requested role and that the filtered set is a subset of the unfiltered set. +func (s *ExtendedIndexingSuite) verifyRoleFiltering(address string) { + unfilteredResp := s.fetchAccountTransactions(address, nil) + + role := swagger.AUTHORIZER_Role + authResp := s.fetchAccountTransactions(address, &swagger.AccountsApiGetAccountTransactionsOpts{ + Roles: optional.NewInterface(role), + }) + + expectedCount := 0 + for _, tx := range unfilteredResp.Transactions { + if slices.Contains(tx.Roles, string(role)) { + s.Contains(tx.Roles, "authorizer", "expected transaction should have authorizer role") + expectedCount++ + } + } + s.Len(authResp.Transactions, expectedCount, "filtered results should be the same length as the expected results") +} + +// fetchAccountTransactions calls the experimental API client to fetch account transactions. +// It retries on errors to account for extended indexer lag. +func (s *ExtendedIndexingSuite) fetchAccountTransactions( + address string, + opts *swagger.AccountsApiGetAccountTransactionsOpts, +) *swagger.AccountTransactionsResponse { + t := s.T() + ctx := context.Background() + + var result *swagger.AccountTransactionsResponse + require.Eventually(t, func() bool { + resp, err := s.apiClient.GetAccountTransactions(ctx, address, opts) + if err != nil { + t.Logf("API request failed: %v", err) + return false + } + result = resp + return true + }, 30*time.Second, 1*time.Second, "REST API request should succeed for account %s", address) + + return result +} + +// collectAllPages paginates through all results for an account and returns all transaction entries. +func (s *ExtendedIndexingSuite) collectAllPages( + address string, + pageSize int, + roles *swagger.Role, + expand *[]string, +) []swagger.AccountTransaction { + ctx := context.Background() + all, err := s.apiClient.GetAllAccountTransactions(ctx, address, pageSize, roles, expand) + s.Require().NoError(err) + return all +} + +// verifyTransactionDetailsFromAPI verifies that the account transactions API returns populated +// transaction bodies and results, and that these match the data returned by the standard REST API +// endpoints (/v1/transactions/{id} and /v1/transaction_results/{id}). +func (s *ExtendedIndexingSuite) verifyTransactionDetailsFromAPI(expectations []transactionExpectation) { + // Collect unique transaction IDs from expectations to avoid verifying the same tx twice + // (a tx can appear in multiple expectations for different addresses). + verified := make(map[string]bool) + + for _, exp := range expectations { + txID := exp.txID.String() + if verified[txID] { + continue + } + verified[txID] = true + + // Fetch the account transactions for this address and find the specific tx + expand := []string{"transaction", "result"} + allTxs := s.collectAllPages(exp.address.String(), 50, nil, &expand) + var acctTx *swagger.AccountTransaction + for i, tx := range allTxs { + if tx.TransactionId == txID { + acctTx = &allTxs[i] + break + } + } + s.Require().NotNil(acctTx, "tx %s not found in account %s transactions", txID, exp.address.String()) + + s.verifyTransactionDetails(*acctTx) + } +} + +// verifyTransactionDetails asserts that the Transaction and Result fields within an AccountTransaction +// are populated and that their key fields match the data from the standard REST API endpoints. +// Field-by-field comparison is used because: +// - The standard REST API returns raw JSON (map[string]any) while the experimental API returns typed structs. +// - Event payloads are encoded differently (standard API uses base64 JSON, experimental API uses CCF/CBOR). +func (s *ExtendedIndexingSuite) verifyTransactionDetails(acctTx swagger.AccountTransaction) { + txID := acctTx.TransactionId + + s.Require().NotNil(acctTx.Transaction, "Transaction body should be populated for tx %s", txID) + s.Require().NotNil(acctTx.Result, "Transaction result should be populated for tx %s", txID) + + // Fetch from standard REST API + restTx := s.fetchRESTTransaction(txID) + restResult := s.fetchRESTTransactionResult(txID) + + // Compare transaction body fields + s.Equal(restTx["id"], acctTx.Transaction.Id, "transaction ID should match") + s.Equal(restTx["script"], acctTx.Transaction.Script, "script should match") + s.Equal(restTx["payer"], acctTx.Transaction.Payer, "payer should match") + s.Equal(restTx["gas_limit"], acctTx.Transaction.GasLimit, "gas_limit should match") + s.Equal(restTx["reference_block_id"], acctTx.Transaction.ReferenceBlockId, "reference_block_id should match") + + restAuthorizers, ok := restTx["authorizers"].([]any) + s.Require().True(ok, "authorizers should be an array") + s.Require().Equal(len(restAuthorizers), len(acctTx.Transaction.Authorizers), "authorizer count should match") + for i, a := range restAuthorizers { + s.Equal(a, acctTx.Transaction.Authorizers[i], "authorizer %d should match", i) + } + + // Compare result fields + s.Equal(restResult["block_id"], acctTx.Result.BlockId, "block_id should match") + s.Equal(restResult["status"], string(*acctTx.Result.Status), "status should match") + s.Equal(restResult["error_message"], acctTx.Result.ErrorMessage, "error_message should match") + s.Equal(restResult["collection_id"], acctTx.Result.CollectionId, "collection_id should match") + + // JSON numbers decode to float64 in map[string]any, so convert before comparing. + restStatusCode, ok := restResult["status_code"].(float64) + s.Require().True(ok, "status_code should be a number") + s.Equal(int32(restStatusCode), acctTx.Result.StatusCode, "status_code should match") + + // Compare events by count and type/index (skip payload since encodings differ). + restEvents, ok := restResult["events"].([]any) + s.Require().True(ok, "events should be an array") + s.Require().Equal(len(restEvents), len(acctTx.Result.Events), "event count should match") + for i, restEvt := range restEvents { + evtMap, ok := restEvt.(map[string]any) + s.Require().True(ok, "event should be an object") + s.Equal(evtMap["type"], acctTx.Result.Events[i].Type_, "event type should match for event %d", i) + s.Equal(evtMap["event_index"], acctTx.Result.Events[i].EventIndex, "event_index should match for event %d", i) + } + + s.T().Logf("verified transaction details for tx %s: body and result match standard REST API", txID) +} + +// fetchRESTTransaction fetches a transaction from the standard REST API endpoint /v1/transactions/{id}. +func (s *ExtendedIndexingSuite) fetchRESTTransaction(txID string) map[string]any { + url := fmt.Sprintf("%s/v1/transactions/%s", s.restBaseURL, txID) + return s.fetchRESTJSON(url, "transaction "+txID) +} + +// fetchRESTTransactionResult fetches a transaction result from the standard REST API endpoint +// /v1/transaction_results/{id}. +func (s *ExtendedIndexingSuite) fetchRESTTransactionResult(txID string) map[string]any { + url := fmt.Sprintf("%s/v1/transaction_results/%s", s.restBaseURL, txID) + return s.fetchRESTJSON(url, "transaction result "+txID) +} + +// fetchRESTJSON performs an HTTP GET to the given URL and returns the decoded JSON body as a map. +// It retries with require.Eventually to handle timing issues. +func (s *ExtendedIndexingSuite) fetchRESTJSON(url string, desc string) map[string]any { + var result map[string]any + require.Eventually(s.T(), func() bool { + resp, err := http.Get(url) //nolint:gosec + if err != nil { + s.T().Logf("GET %s failed: %v", desc, err) + return false + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + s.T().Logf("GET %s returned status %d: %s", desc, resp.StatusCode, string(body)) + return false + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + s.T().Logf("GET %s read body failed: %v", desc, err) + return false + } + + if err := json.Unmarshal(body, &result); err != nil { + s.T().Logf("GET %s JSON decode failed: %v", desc, err) + return false + } + return true + }, 30*time.Second, 1*time.Second, "REST API request should succeed for %s", desc) + + return result +} + +// buildFlowTransferTx constructs a Cadence transaction that transfers Flow tokens to the given address. +func buildFlowTransferTx(t *testing.T, to sdk.Address, amount string) *sdk.Transaction { + contracts := systemcontracts.SystemContractsForChain(flow.Localnet) + ftAddr := contracts.FungibleToken.Address.Hex() + flowTokenAddr := contracts.FlowToken.Address.Hex() + + script := fmt.Sprintf(sendFlowTokensScript, ftAddr, flowTokenAddr) + + amountArg, err := cadence.NewUFix64(amount) + require.NoError(t, err) + toArg := cadence.NewAddress(cadence.BytesToAddress(to.Bytes())) + + tx := sdk.NewTransaction(). + SetScript([]byte(strings.TrimSpace(script))). + AddAuthorizer(sdk.Address(flow.Localnet.Chain().ServiceAddress())) + + err = tx.AddArgument(amountArg) + require.NoError(t, err) + + err = tx.AddArgument(toArg) + require.NoError(t, err) + + return tx +} diff --git a/integration/tests/access/cohort3/extended_indexing_transfers_test.go b/integration/tests/access/cohort3/extended_indexing_transfers_test.go new file mode 100644 index 00000000000..1b90b1f6697 --- /dev/null +++ b/integration/tests/access/cohort3/extended_indexing_transfers_test.go @@ -0,0 +1,513 @@ +package cohort3 + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/antihax/optional" + + "github.com/onflow/cadence" + ftcontracts "github.com/onflow/flow-ft/lib/go/contracts" + sdk "github.com/onflow/flow-go-sdk" + sdkcrypto "github.com/onflow/flow-go-sdk/crypto" + "github.com/onflow/flow-go-sdk/templates" + nftcontracts "github.com/onflow/flow-nft/lib/go/contracts" + swagger "github.com/onflow/flow/openapi/experimental/go-client-generated" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/integration/testnet" + "github.com/onflow/flow-go/integration/tests/lib" + "github.com/onflow/flow-go/model/flow" +) + +const ( + // setupExampleTokenVaultScript creates an ExampleToken vault on the signer's account. + setupExampleTokenVaultScript = ` +import FungibleToken from 0x%[1]s +import ExampleToken from 0x%[2]s + +transaction { + prepare(signer: auth(BorrowValue, SaveValue, Capabilities) &Account) { + if signer.storage.borrow<&ExampleToken.Vault>(from: ExampleToken.VaultStoragePath) != nil { + return + } + signer.storage.save( + <-ExampleToken.createEmptyVault(vaultType: Type<@ExampleToken.Vault>()), + to: ExampleToken.VaultStoragePath + ) + signer.capabilities.publish( + signer.capabilities.storage.issue<&{FungibleToken.Receiver}>(ExampleToken.VaultStoragePath), + at: ExampleToken.ReceiverPublicPath + ) + signer.capabilities.publish( + signer.capabilities.storage.issue<&{FungibleToken.Balance}>(ExampleToken.VaultStoragePath), + at: ExampleToken.VaultPublicPath + ) + } +} +` + + // setupExampleNFTCollectionScript creates an ExampleNFT collection on the signer's account. + setupExampleNFTCollectionScript = ` +import NonFungibleToken from 0x%[1]s +import ExampleNFT from 0x%[2]s + +transaction { + prepare(signer: auth(BorrowValue, SaveValue, Capabilities) &Account) { + if signer.storage.borrow<&ExampleNFT.Collection>(from: ExampleNFT.CollectionStoragePath) != nil { + return + } + signer.storage.save( + <-ExampleNFT.createEmptyCollection(nftType: Type<@ExampleNFT.NFT>()), + to: ExampleNFT.CollectionStoragePath + ) + signer.capabilities.publish( + signer.capabilities.storage.issue<&{NonFungibleToken.Collection}>(ExampleNFT.CollectionStoragePath), + at: ExampleNFT.CollectionPublicPath + ) + } +} +` + + // sendExampleTokensScript transfers ExampleToken from the signer to the recipient. + sendExampleTokensScript = ` +import FungibleToken from 0x%[1]s +import ExampleToken from 0x%[2]s + +transaction(amount: UFix64, to: Address) { + let sentVault: @{FungibleToken.Vault} + + prepare(signer: auth(BorrowValue) &Account) { + let vaultRef = signer.storage.borrow(from: ExampleToken.VaultStoragePath) + ?? panic("Could not borrow reference to the owner's Vault!") + self.sentVault <- vaultRef.withdraw(amount: amount) + } + + execute { + let receiverRef = getAccount(to) + .capabilities.borrow<&{FungibleToken.Receiver}>(ExampleToken.ReceiverPublicPath) + ?? panic("Could not borrow receiver reference to the recipient's Vault") + receiverRef.deposit(from: <-self.sentVault) + } +} +` + + // mintAndSendExampleNFTScript mints an ExampleNFT and deposits it to the recipient's collection. + mintAndSendExampleNFTScript = ` +import NonFungibleToken from 0x%[1]s +import ExampleNFT from 0x%[2]s +import MetadataViews from 0x%[3]s + +transaction(recipient: Address) { + let minter: &ExampleNFT.NFTMinter + + prepare(signer: auth(BorrowValue) &Account) { + self.minter = signer.storage.borrow<&ExampleNFT.NFTMinter>(from: ExampleNFT.MinterStoragePath) + ?? panic("Could not borrow a reference to the NFT minter") + } + + execute { + let receiverRef = getAccount(recipient) + .capabilities.borrow<&{NonFungibleToken.Receiver}>(ExampleNFT.CollectionPublicPath) + ?? panic("Could not get receiver reference to the recipient's NFT Collection") + + let nft <- self.minter.mintNFT( + name: "Test NFT", + description: "A test NFT for integration testing", + thumbnail: "https://example.com/nft.png", + royalties: [] + ) + receiverRef.deposit(token: <-nft) + } +} +` +) + +// TestAccountTransfers verifies the REST API endpoints for querying FT and NFT token transfers. +// It deploys custom FT (ExampleToken) and NFT (ExampleNFT) contracts, executes various transfers +// using both FlowToken and the custom tokens, and validates the transfer indexing via the REST API. +func (s *ExtendedIndexingSuite) TestAccountTransfers() { + ctx := context.Background() + + serviceClient, err := s.net.ContainerByName(testnet.PrimaryAN).TestnetClient() + s.Require().NoError(err) + + contracts := systemcontracts.SystemContractsForChain(flow.Localnet) + serviceAddr := serviceClient.SDKServiceAddress() + + // Step 1: Deploy ExampleToken (custom FT) and ExampleNFT contracts on the service account. + s.T().Log("deploying ExampleToken contract") + exampleTokenCode := ftcontracts.ExampleToken( + contracts.FungibleToken.Address.Hex(), + contracts.MetadataViews.Address.Hex(), + contracts.FungibleTokenMetadataViews.Address.Hex(), + ) + s.deployContract(ctx, serviceClient, "ExampleToken", exampleTokenCode) + + s.T().Log("deploying ExampleNFT contract") + exampleNFTCode := nftcontracts.ExampleNFT( + sdk.Address(contracts.NonFungibleToken.Address), + sdk.Address(contracts.MetadataViews.Address), + sdk.Address(contracts.ViewResolver.Address), + ) + s.deployContract(ctx, serviceClient, "ExampleNFT", exampleNFTCode) + + // Step 2: Create a new account. + latestBlockID, err := serviceClient.GetLatestBlockID(ctx) + s.Require().NoError(err) + + accountPrivateKey := lib.RandomPrivateKey() + accountKey := sdk.NewAccountKey(). + FromPrivateKey(accountPrivateKey). + SetHashAlgo(sdkcrypto.SHA3_256). + SetWeight(sdk.AccountKeyWeightThreshold) + + newAccountAddress, _, err := serviceClient.CreateAccount(ctx, accountKey, sdk.Identifier(latestBlockID)) + s.Require().NoError(err) + s.T().Logf("created new account: %s", newAccountAddress) + + newAddr := flow.Address(newAccountAddress) + + // Step 3: Create a client for the new account to sign setup transactions. + grpcAddr := s.net.ContainerByName(testnet.PrimaryAN).Addr(testnet.GRPCPort) + accountClient, err := testnet.NewClientWithKey(grpcAddr, newAccountAddress, accountPrivateKey, flow.Localnet.Chain()) + s.Require().NoError(err) + + // Step 4: Setup ExampleToken vault and ExampleNFT collection on the new account. + s.T().Log("setting up ExampleToken vault on new account") + s.sendTransaction(ctx, accountClient, fmt.Sprintf( + setupExampleTokenVaultScript, + contracts.FungibleToken.Address.Hex(), + serviceAddr.Hex(), + )) + + s.T().Log("setting up ExampleNFT collection on new account") + s.sendTransaction(ctx, accountClient, fmt.Sprintf( + setupExampleNFTCollectionScript, + contracts.NonFungibleToken.Address.Hex(), + serviceAddr.Hex(), + )) + + // Step 5: Execute token transfers. + // 5a. FlowToken transfer: service → new account + s.T().Log("transferring FlowTokens to new account") + flowTransferResult := s.sendTransferTx(ctx, serviceClient, newAccountAddress, "10.0", buildFlowTransferTx) + + // 5b. ExampleToken transfer: service → new account + s.T().Log("transferring ExampleTokens to new account") + exampleTokenTransferResult := s.sendExampleTokenTransferTx(ctx, serviceClient, newAccountAddress, "50.0", contracts) + + // 5c. ExampleNFT: mint on service and deposit to new account + s.T().Log("minting ExampleNFT and sending to new account") + nftMintResult := s.sendMintNFTTx(ctx, serviceClient, newAccountAddress, contracts) + + // Step 6: Wait for the extended indexer to catch up. + maxHeight := max(nftMintResult.BlockHeight, flowTransferResult.BlockHeight, exampleTokenTransferResult.BlockHeight) + + waitCtx, waitCancel := context.WithTimeout(ctx, 120*time.Second) + defer waitCancel() + err = serviceClient.WaitUntilIndexed(waitCtx, maxHeight+10) + s.Require().NoError(err) + s.T().Logf("indexer caught up to height %d", maxHeight+10) + + // Step 7: Verify FT transfers via the REST API. + s.verifyFTTransfers(newAddr, flow.Address(serviceAddr)) + + // Step 8: Verify NFT transfers via the REST API. + s.verifyNFTTransfers(newAddr) +} + +// deployContract deploys a contract with the given name and code on the service account. +func (s *ExtendedIndexingSuite) deployContract( + ctx context.Context, + client *testnet.Client, + name string, + code []byte, +) { + latestBlockID, err := client.GetLatestBlockID(ctx) + s.Require().NoError(err) + + addr := client.Account().Address + tx := templates.AddAccountContract(addr, templates.Contract{ + Name: name, + Source: string(code), + }) + tx.SetReferenceBlockID(sdk.Identifier(latestBlockID)). + SetProposalKey(addr, 0, client.GetAndIncrementSeqNumber()). + SetPayer(addr). + SetComputeLimit(9999) + + err = client.SignAndSendTransaction(ctx, tx) + s.Require().NoError(err) + + result, err := client.WaitForSealed(ctx, tx.ID()) + s.Require().NoError(err) + s.Require().NoError(result.Error, "deploy %s failed", name) + s.T().Logf("deployed %s at height %d", name, result.BlockHeight) +} + +// sendTransaction builds, signs, sends, and waits for a transaction using the provided script. +// It uses the client's account address as the authorizer, proposer, and payer. +func (s *ExtendedIndexingSuite) sendTransaction( + ctx context.Context, + client *testnet.Client, + script string, + args ...cadence.Value, +) *sdk.TransactionResult { + latestBlockID, err := client.GetLatestBlockID(ctx) + s.Require().NoError(err) + + addr := client.Account().Address + + tx := sdk.NewTransaction(). + SetScript([]byte(strings.TrimSpace(script))). + AddAuthorizer(addr) + + for _, arg := range args { + err = tx.AddArgument(arg) + s.Require().NoError(err) + } + + tx.SetReferenceBlockID(sdk.Identifier(latestBlockID)). + SetProposalKey(addr, 0, client.GetAndIncrementSeqNumber()). + SetPayer(addr). + SetComputeLimit(9999) + + err = client.SignAndSendTransaction(ctx, tx) + s.Require().NoError(err) + + result, err := client.WaitForSealed(ctx, tx.ID()) + s.Require().NoError(err) + s.Require().NoError(result.Error, "transaction failed: %s", result.Error) + return result +} + +// sendTransferTx builds and sends a FlowToken transfer transaction. +func (s *ExtendedIndexingSuite) sendTransferTx( + ctx context.Context, + client *testnet.Client, + to sdk.Address, + amount string, + buildTx func(*testing.T, sdk.Address, string) *sdk.Transaction, +) *sdk.TransactionResult { + latestBlockID, err := client.GetLatestBlockID(ctx) + s.Require().NoError(err) + + tx := buildTx(s.T(), to, amount) + tx.SetReferenceBlockID(sdk.Identifier(latestBlockID)). + SetProposalKey(client.SDKServiceAddress(), 0, client.GetAndIncrementSeqNumber()). + SetPayer(client.SDKServiceAddress()). + SetComputeLimit(9999) + + err = client.SignAndSendTransaction(ctx, tx) + s.Require().NoError(err) + + result, err := client.WaitForSealed(ctx, tx.ID()) + s.Require().NoError(err) + s.Require().NoError(result.Error, "FlowToken transfer failed") + s.T().Logf("FlowToken transfer sealed at height %d, tx: %s", result.BlockHeight, tx.ID()) + return result +} + +// sendExampleTokenTransferTx transfers ExampleToken from the service account to the recipient. +func (s *ExtendedIndexingSuite) sendExampleTokenTransferTx( + ctx context.Context, + client *testnet.Client, + to sdk.Address, + amount string, + contracts *systemcontracts.SystemContracts, +) *sdk.TransactionResult { + script := fmt.Sprintf(sendExampleTokensScript, + contracts.FungibleToken.Address.Hex(), + client.SDKServiceAddress().Hex(), + ) + + amountArg, err := cadence.NewUFix64(amount) + s.Require().NoError(err) + toArg := cadence.NewAddress(cadence.BytesToAddress(to.Bytes())) + + result := s.sendTransaction(ctx, client, script, amountArg, toArg) + s.T().Logf("ExampleToken transfer sealed at height %d", result.BlockHeight) + return result +} + +// sendMintNFTTx mints an ExampleNFT and deposits it into the recipient's collection. +func (s *ExtendedIndexingSuite) sendMintNFTTx( + ctx context.Context, + client *testnet.Client, + to sdk.Address, + contracts *systemcontracts.SystemContracts, +) *sdk.TransactionResult { + script := fmt.Sprintf(mintAndSendExampleNFTScript, + contracts.NonFungibleToken.Address.Hex(), + client.SDKServiceAddress().Hex(), + contracts.MetadataViews.Address.Hex(), + ) + + toArg := cadence.NewAddress(cadence.BytesToAddress(to.Bytes())) + result := s.sendTransaction(ctx, client, script, toArg) + s.T().Logf("ExampleNFT mint sealed at height %d", result.BlockHeight) + return result +} + +// verifyFTTransfers validates FT transfer indexing via the REST API. +func (s *ExtendedIndexingSuite) verifyFTTransfers( + recipientAddr flow.Address, + senderAddr flow.Address, +) { + ctx := context.Background() + + // Verify the recipient received both FlowToken and ExampleToken transfers. + s.T().Log("verifying FT transfers for recipient") + recipientTransfers := s.fetchFTTransfersEventually(recipientAddr.String(), nil, 2) + s.T().Logf("recipient %s has %d FT transfers", recipientAddr, len(recipientTransfers)) + s.GreaterOrEqual(len(recipientTransfers), 2, "recipient should have at least 2 FT transfers (FlowToken + ExampleToken)") + + // Check that we see both token types. + tokenTypes := make(map[string]bool) + for _, transfer := range recipientTransfers { + tokenTypes[transfer.TokenType] = true + s.T().Logf(" FT transfer: token_type=%s amount=%s source=%s recipient=%s", + transfer.TokenType, transfer.Amount, transfer.SourceAddress, transfer.RecipientAddress) + } + s.True(len(tokenTypes) >= 2, "should have transfers for at least 2 different token types, got: %v", tokenTypes) + + // Verify token_type filter returns only transfers of that type. + for tokenType := range tokenTypes { + filtered, err := s.apiClient.GetAllAccountFungibleTransfers(ctx, recipientAddr.String(), 50, + &swagger.AccountsApiGetAccountFungibleTransfersOpts{ + TokenType: optional.NewString(tokenType), + }) + s.Require().NoError(err) + s.NotEmpty(filtered, "filtered results for token_type=%s should not be empty", tokenType) + for _, t := range filtered { + s.Equal(tokenType, t.TokenType, "filtered transfer should match requested token_type") + } + } + + // Verify recipient_address filter: recipient-only transfers for the recipient address. + recipientOnly, err := s.apiClient.GetAllAccountFungibleTransfers(ctx, recipientAddr.String(), 50, + &swagger.AccountsApiGetAccountFungibleTransfersOpts{ + RecipientAddress: optional.NewInterface(recipientAddr.String()), + }) + s.Require().NoError(err) + for _, t := range recipientOnly { + s.Equal(recipientAddr.Hex(), t.RecipientAddress, + "recipient_address filter should only return transfers where this account is the recipient") + } + + // Verify the sender sent both FlowToken and ExampleToken. + s.T().Log("verifying FT transfers for sender") + senderTransfers := s.fetchFTTransfersEventually(senderAddr.String(), nil, 2) + s.T().Logf("sender %s has %d FT transfers", senderAddr, len(senderTransfers)) + s.GreaterOrEqual(len(senderTransfers), 2, "sender should have at least 2 FT transfers") + + // Verify source_address filter: sender-only transfers for the sender address. + senderOnly, err := s.apiClient.GetAllAccountFungibleTransfers(ctx, senderAddr.String(), 50, + &swagger.AccountsApiGetAccountFungibleTransfersOpts{ + SourceAddress: optional.NewInterface(senderAddr.String()), + }) + s.Require().NoError(err) + for _, t := range senderOnly { + s.Equal(senderAddr.Hex(), t.SourceAddress, + "source_address filter should only return transfers where this account is the sender") + } + + // Verify FT pagination: page through with limit=1, compare to unpaginated. + s.T().Log("verifying FT pagination") + allPaged, err := s.apiClient.GetAllAccountFungibleTransfers(ctx, recipientAddr.String(), 1, nil) + s.Require().NoError(err) + allUnpaged, err := s.apiClient.GetAllAccountFungibleTransfers(ctx, recipientAddr.String(), 50, nil) + s.Require().NoError(err) + s.Equal(len(allUnpaged), len(allPaged), "paginated and unpaginated FT transfer counts should match") + for i := range allUnpaged { + s.Equal(allUnpaged[i].TransactionId, allPaged[i].TransactionId, + "FT transfer %d should have the same transaction ID in both paginated and unpaginated results", i) + } +} + +// verifyNFTTransfers validates NFT transfer indexing via the REST API. +func (s *ExtendedIndexingSuite) verifyNFTTransfers( + recipientAddr flow.Address, +) { + ctx := context.Background() + + // Verify the recipient received at least one NFT transfer. + s.T().Log("verifying NFT transfers for recipient") + recipientTransfers := s.fetchNFTTransfersEventually(recipientAddr.String(), nil, 1) + s.T().Logf("recipient %s has %d NFT transfers", recipientAddr, len(recipientTransfers)) + s.GreaterOrEqual(len(recipientTransfers), 1, "recipient should have at least 1 NFT transfer") + + for _, transfer := range recipientTransfers { + s.T().Logf(" NFT transfer: token_type=%s nft_id=%s source=%s recipient=%s", + transfer.TokenType, transfer.NftId, transfer.SourceAddress, transfer.RecipientAddress) + s.NotEmpty(transfer.TokenType, "NFT transfer should have a token_type") + s.Equal(recipientAddr.Hex(), transfer.RecipientAddress, "recipient address should match") + } + + // Verify recipient_address filter: recipient-only. + recipientOnly, err := s.apiClient.GetAllAccountNonFungibleTransfers(ctx, recipientAddr.String(), 50, + &swagger.AccountsApiGetAccountNonFungibleTransfersOpts{ + RecipientAddress: optional.NewInterface(recipientAddr.String()), + }) + s.Require().NoError(err) + for _, t := range recipientOnly { + s.Equal(recipientAddr.Hex(), t.RecipientAddress, + "recipient_address filter should only return transfers where this account is the recipient") + } + + // Verify NFT pagination. + s.T().Log("verifying NFT pagination") + allPaged, err := s.apiClient.GetAllAccountNonFungibleTransfers(ctx, recipientAddr.String(), 1, nil) + s.Require().NoError(err) + allUnpaged, err := s.apiClient.GetAllAccountNonFungibleTransfers(ctx, recipientAddr.String(), 50, nil) + s.Require().NoError(err) + s.Equal(len(allUnpaged), len(allPaged), "paginated and unpaginated NFT transfer counts should match") +} + +// fetchFTTransfersEventually retries fetching FT transfers until at least minCount results are returned. +func (s *ExtendedIndexingSuite) fetchFTTransfersEventually( + address string, + opts *swagger.AccountsApiGetAccountFungibleTransfersOpts, + minCount int, +) []swagger.FungibleTokenTransfer { + ctx := context.Background() + + var result []swagger.FungibleTokenTransfer + s.Require().Eventually(func() bool { + transfers, err := s.apiClient.GetAllAccountFungibleTransfers(ctx, address, 50, opts) + if err != nil { + s.T().Logf("FT transfers API request failed for %s: %v", address, err) + return false + } + result = transfers + return len(transfers) >= minCount + }, 30*time.Second, 1*time.Second, "should get at least %d FT transfers for %s", minCount, address) + + return result +} + +// fetchNFTTransfersEventually retries fetching NFT transfers until at least minCount results are returned. +func (s *ExtendedIndexingSuite) fetchNFTTransfersEventually( + address string, + opts *swagger.AccountsApiGetAccountNonFungibleTransfersOpts, + minCount int, +) []swagger.NonFungibleTokenTransfer { + ctx := context.Background() + + var result []swagger.NonFungibleTokenTransfer + s.Require().Eventually(func() bool { + transfers, err := s.apiClient.GetAllAccountNonFungibleTransfers(ctx, address, 50, opts) + if err != nil { + s.T().Logf("NFT transfers API request failed for %s: %v", address, err) + return false + } + result = transfers + return len(transfers) >= minCount + }, 30*time.Second, 1*time.Second, "should get at least %d NFT transfers for %s", minCount, address) + + return result +} diff --git a/integration/tests/access/cohort4/grpc_state_stream_test.go b/integration/tests/access/cohort4/grpc_state_stream_test.go index 6c414b4d5e1..36bcd923e4d 100644 --- a/integration/tests/access/cohort4/grpc_state_stream_test.go +++ b/integration/tests/access/cohort4/grpc_state_stream_test.go @@ -285,7 +285,7 @@ func (s *GrpcStateStreamSuite) generateEvents(client *testnet.Client, txCount in for i := 0; i < txCount; i++ { accountKey := test.AccountKeyGenerator().New() - address, err := client.CreateAccount(s.ctx, accountKey, sdk.HexToID(refBlockID.String())) + address, _, err := client.CreateAccount(s.ctx, accountKey, sdk.HexToID(refBlockID.String())) if err != nil { i-- continue diff --git a/integration/tests/admin/command_runner_test.go b/integration/tests/admin/command_runner_test.go index 8166bcd01cf..e39409cfe5f 100644 --- a/integration/tests/admin/command_runner_test.go +++ b/integration/tests/admin/command_runner_test.go @@ -19,7 +19,7 @@ import ( "testing" "time" - "github.com/dapperlabs/testingdock" + "github.com/onflow/testingdock" "github.com/rs/zerolog" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" diff --git a/integration/tests/collection/suite.go b/integration/tests/collection/suite.go index a8b5420d170..3bef30f433c 100644 --- a/integration/tests/collection/suite.go +++ b/integration/tests/collection/suite.go @@ -178,11 +178,10 @@ func (suite *CollectorSuite) TxForCluster(target flow.IdentitySkeletonList) *sdk // hash-grind the script until the transaction will be routed to target cluster for { - serviceAccountAddr, err := suite.net.Root().ChainID.Chain().AddressAtIndex(suite.serviceAccountIdx) - suite.Require().NoError(err) - suite.serviceAccountIdx++ + // update the script for each loop tx.SetScript(append(tx.Script, '/', '/')) - err = tx.SignEnvelope(sdk.Address(serviceAccountAddr), acct.key.Index, acct.signer) + tx.EnvelopeSignatures = nil // clear the envelope signatures before adding a fresh one + err := tx.SignEnvelope(acct.addr, acct.key.Index, acct.signer) require.NoError(suite.T(), err) routed, ok := clusters.ByTxID(convert.IDFromSDK(tx.ID())) require.True(suite.T(), ok) diff --git a/integration/tests/epochs/base_suite.go b/integration/tests/epochs/base_suite.go index 7fcae7a2a7b..842d8590df8 100644 --- a/integration/tests/epochs/base_suite.go +++ b/integration/tests/epochs/base_suite.go @@ -4,7 +4,7 @@ // and resource-heavy, we split them into several cohorts, which can be run in parallel. // // If a new cohort is added in the future, it must be added to: -// - ci.yml, flaky-test-monitor.yml, bors.toml (ensure new cohort of tests is run) +// - ci.yml, flaky-test-monitor.yml (ensure new cohort of tests is run) // - Makefile (include new cohort in integration-test directive, etc.) package epochs diff --git a/integration/tests/epochs/cohort1/epoch_dynamic_bootstrap_in_efm_test.go b/integration/tests/epochs/cohort1/epoch_dynamic_bootstrap_in_efm_test.go index 5f9927cd5ea..6a307e46e45 100644 --- a/integration/tests/epochs/cohort1/epoch_dynamic_bootstrap_in_efm_test.go +++ b/integration/tests/epochs/cohort1/epoch_dynamic_bootstrap_in_efm_test.go @@ -55,7 +55,7 @@ func (s *DynamicBootstrapInEFMSuite) TestDynamicBootstrapInEFM() { } testContainer := s.Net.AddObserver(s.T(), observerConf) testContainer.WriteRootSnapshot(snapshot) - testContainer.Container.Start(s.Ctx) + require.NoError(s.T(), testContainer.Container.Start(s.Ctx)) s.TimedLogf("successfully started observer") observerClient, err := testContainer.TestnetClient() diff --git a/integration/tests/epochs/dynamic_epoch_transition_suite.go b/integration/tests/epochs/dynamic_epoch_transition_suite.go index 4791ca51bd8..68b48bf17d5 100644 --- a/integration/tests/epochs/dynamic_epoch_transition_suite.go +++ b/integration/tests/epochs/dynamic_epoch_transition_suite.go @@ -4,7 +4,7 @@ // and resource-heavy, we split them into several cohorts, which can be run in parallel. // // If a new cohort is added in the future, it must be added to: -// - ci.yml, flaky-test-monitor.yml, bors.toml (ensure new cohort of tests is run) +// - ci.yml, flaky-test-monitor.yml (ensure new cohort of tests is run) // - Makefile (include new cohort in integration-test directive, etc.) package epochs @@ -51,9 +51,9 @@ func (s *DynamicEpochTransitionSuite) SetupTest() { // NOTE: this value is set fairly aggressively to ensure shorter test times. // If flakiness due to failure to complete staking operations in time is observed, // try increasing (by 10-20 views). - s.StakingAuctionLen = 50 + s.StakingAuctionLen = 70 s.DKGPhaseLen = 50 - s.EpochLen = 250 + s.EpochLen = 270 s.FinalizationSafetyThreshold = 20 // run the generic setup, which starts up the network @@ -528,7 +528,7 @@ func (s *DynamicEpochTransitionSuite) RunTestEpochJoinAndLeave(role flow.Role, c segment.Sealed().View, segment.Highest().View) testContainer.WriteRootSnapshot(rootSnapshot) - testContainer.Container.Start(s.Ctx) + require.NoError(s.T(), testContainer.Container.Start(s.Ctx)) epoch1, err := rootSnapshot.Epochs().Current() require.NoError(s.T(), err) diff --git a/integration/tests/execution/failing_tx_reverted_test.go b/integration/tests/execution/failing_tx_reverted_test.go index 1d3818c2b00..fe5f74014f3 100644 --- a/integration/tests/execution/failing_tx_reverted_test.go +++ b/integration/tests/execution/failing_tx_reverted_test.go @@ -11,6 +11,7 @@ import ( "github.com/onflow/flow-go/integration/tests/lib" "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" ) func TestExecutionFailingTxReverted(t *testing.T) { @@ -68,7 +69,12 @@ func (s *FailingTxRevertedSuite) TestExecutionFailingTxReverted() { lib.WithChainID(chainID), ) failingTx.PayloadSignatures = nil - failingTx.EnvelopeSignatures = nil + failingTx.EnvelopeSignatures = []sdk.TransactionSignature{ + sdk.TransactionSignature{ + Address: failingTx.Payer, + Signature: unittest.SignatureFixtureForTransactions(), + }, + } err = s.AccessClient().SendTransaction(context.Background(), &failingTx) require.NoError(s.T(), err, "could not send tx to create counter with wrong sig") diff --git a/integration/tests/lib/util.go b/integration/tests/lib/util.go index 32b857d546e..db9da99c791 100644 --- a/integration/tests/lib/util.go +++ b/integration/tests/lib/util.go @@ -125,6 +125,7 @@ func CreateCounterTx(counterAddress sdk.Address) dsl.Transaction { return dsl.Transaction{ Imports: dsl.Imports{ dsl.Import{ + Names: []string{"Testing"}, Address: counterAddress, }, }, @@ -176,6 +177,7 @@ func CreateCounterPanicTx(chain flow.Chain) dsl.Transaction { return dsl.Transaction{ Imports: dsl.Imports{ dsl.Import{ + Names: []string{"Testing"}, Address: sdk.Address(chain.ServiceAddress()), }, }, diff --git a/integration/tests/mvp/mvp_test.go b/integration/tests/mvp/mvp_test.go index 68eceae79d4..6eada8e66fa 100644 --- a/integration/tests/mvp/mvp_test.go +++ b/integration/tests/mvp/mvp_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - "github.com/dapperlabs/testingdock" + "github.com/onflow/testingdock" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/integration/utils/transactions.go b/integration/utils/transactions.go index ec83807e3e5..74bdaf30405 100644 --- a/integration/utils/transactions.go +++ b/integration/utils/transactions.go @@ -241,7 +241,7 @@ func CreateFlowAccount(ctx context.Context, client *testnet.Client) (sdk.Address } // createAccount will submit a create account transaction and wait for it to be sealed - addr, err := client.CreateAccount(ctx, fullAccountKey, sdk.Identifier(latestBlockID)) + addr, _, err := client.CreateAccount(ctx, fullAccountKey, sdk.Identifier(latestBlockID)) if err != nil { return sdk.EmptyAddress, fmt.Errorf("failed to create account: %w", err) } diff --git a/k8s/local/flow-collection-node-deployment.yml b/k8s/local/flow-collection-node-deployment.yml deleted file mode 100644 index 40715c783f6..00000000000 --- a/k8s/local/flow-collection-node-deployment.yml +++ /dev/null @@ -1,286 +0,0 @@ -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-ingress-service - namespace: flow - - labels: - app: flow-test-net - node: collection - env: local - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: local - version: v1 - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - ---- -# To pre-emptively prepare for the case where we'd want to connect to a specific collection cluster, we can have sub services per cluster - -# Service for accessing the first collection cluster -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-v1-0 - namespace: flow - - labels: - app: flow-test-net - node: collection - env: local - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: local - version: v1 - statefulset.kubernetes.io/pod-name: flow-collection-node-v1-0 - - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc - ---- - -# Service for accessing the second collection cluster -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-v1-1 - namespace: flow - - labels: - app: flow-test-net - node: collection - env: local - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: local - version: v1 - statefulset.kubernetes.io/pod-name: flow-collection-node-v1-1 - - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc - ---- - -# Service for accessing the third collection cluster -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-v1-2 - namespace: flow - - labels: - app: flow-test-net - node: collection - env: local - owner: Kan - version: v1 - statefulset.kubernetes.io/pod-name: flow-collection-node-v1-2 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: local - version: v1 - - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc - ---- - -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-collection-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: collection - env: local - owner: Kan - version: v1 - -spec: - replicas: 3 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: collection - env: local - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: collection - env: local - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - terminationGracePeriodSeconds: 30 - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/collection - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - '--ingress-addr' - - ':9000' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - - name: ingress - containerPort: 9000 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - # Cannot get ordinal index yet from metadata at this time: https://github.com/kubernetes/kubernetes/pull/83101/files - # Have to parse out from pod name - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - - name: JAEGER_SERVICE_NAME - value: collection - - name: JAEGER_AGENT_HOST - value: jaeger-agent - - name: JAEGER_SAMPLER_TYPE - value: const - - name: JAEGER_SAMPLER_PARAM - value: "1" - - name: JAEGER_REPORTER_LOG_SPANS - value: "true" - # Resource requests and contraints - resources: - requests: - cpu: '125m' - memory: '128Mi' - limits: - cpu: '250m' - memory: '256Mi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 10Gi - storageClassName: standard diff --git a/k8s/local/flow-consensus-node-deployment.yml b/k8s/local/flow-consensus-node-deployment.yml deleted file mode 100644 index 6e607ef15e6..00000000000 --- a/k8s/local/flow-consensus-node-deployment.yml +++ /dev/null @@ -1,132 +0,0 @@ -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-consensus-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: consensus - env: local - owner: Kan - version: v1 - -spec: - replicas: 1 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: consensus - env: local - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: consensus - env: local - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/consensus - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - - # Resource requests and constraints - resources: - requests: - cpu: '250m' - memory: '512Mi' - limits: - cpu: '500m' - memory: '2Gi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 10Gi - storageClassName: standard \ No newline at end of file diff --git a/k8s/local/flow-execution-node-deployment.yml b/k8s/local/flow-execution-node-deployment.yml deleted file mode 100644 index 21936b56f0a..00000000000 --- a/k8s/local/flow-execution-node-deployment.yml +++ /dev/null @@ -1,132 +0,0 @@ -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-execution-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: execution - env: local - owner: Kan - version: v1 - -spec: - replicas: 1 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: execution - env: local - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: execution - env: local - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/execution - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - - # Resource requests and constraints - resources: - requests: - cpu: '125m' - memory: '128Mi' - limits: - cpu: '250m' - memory: '256Mi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 20Gi - storageClassName: standard \ No newline at end of file diff --git a/k8s/local/flow-network-service.yml b/k8s/local/flow-network-service.yml deleted file mode 100644 index 2b6f77bbdff..00000000000 --- a/k8s/local/flow-network-service.yml +++ /dev/null @@ -1,30 +0,0 @@ -# Headless Service, for internal cluster access by other pods -apiVersion: v1 -kind: Service - -metadata: - name: flow-test-network-v1 - namespace: flow - - labels: - app: flow-test-net - env: local - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - env: local - version: v1 - clusterIP: None - ports: - - name: http - protocol: TCP - port: 8080 - targetPort: http # reference to the name of the port in your container config - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc # reference to the name of the port in your container config \ No newline at end of file diff --git a/k8s/local/flow-node-config-map.yml b/k8s/local/flow-node-config-map.yml deleted file mode 100644 index b3cd40cb51b..00000000000 --- a/k8s/local/flow-node-config-map.yml +++ /dev/null @@ -1,7 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: flow-node-config-map - namespace: flow -data: - entries: 'collection-8a9a01361b8a1e048a17acbd0deb18473e335389667b3e491edf030948335487@flow-collection-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000,collection-a1f922ed445ea61dd50d97d0fa69a69aa22e998530a0b976aae679ebf4756ade@flow-collection-node-v1-1.flow-test-network-v1.flow.svc.cluster.local:3569=1000,collection-b6beaa7f7d45c74192029b9261b703b208d76d054505e77758659c48c1f6f4eb@flow-collection-node-v1-2.flow-test-network-v1.flow.svc.cluster.local:3569=1000,consensus-87aa9e83d59111f912fe785d32e361ff917bb0b452a736dc8de0ca0bdd577b3b@flow-consensus-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000,execution-8806fa187214d53bb1d2ed7fc67d7c3bfc0e1518fa28319c9b9598e89b2cd2ee@flow-execution-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000,verification-fbdb6deafcecaf3b318d271af56156ff99bc9d40152cd93920173fe4027e6d7f@flow-verification-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000' diff --git a/k8s/local/flow-persistent-volumes.yml b/k8s/local/flow-persistent-volumes.yml deleted file mode 100644 index 15dc7ebd9fd..00000000000 --- a/k8s/local/flow-persistent-volumes.yml +++ /dev/null @@ -1,105 +0,0 @@ -apiVersion: v1 -kind: PersistentVolume -metadata: - name: badger-pv-0 - labels: - type: local - app: flow-test-net -spec: - storageClassName: standard - capacity: - storage: 10Gi - accessModes: - - ReadWriteOnce - - ReadOnlyMany - hostPath: - path: "/tmp/k8s/badger-pv-0" - ---- -apiVersion: v1 -kind: PersistentVolume -metadata: - name: badger-pv-1 - labels: - type: local - app: flow-test-net -spec: - storageClassName: standard - capacity: - storage: 20Gi - accessModes: - - ReadWriteOnce - - ReadOnlyMany - hostPath: - path: "/tmp/k8s/badger-pv-1" ---- -apiVersion: v1 -kind: PersistentVolume -metadata: - name: badger-pv-2 - labels: - type: local - app: flow-test-net -spec: - storageClassName: standard - capacity: - storage: 20Gi - accessModes: - - ReadWriteOnce - - ReadOnlyMany - hostPath: - path: "/tmp/k8s/badger-pv-2" - ---- -apiVersion: v1 -kind: PersistentVolume -metadata: - name: badger-pv-3 - labels: - type: local - app: flow-test-net -spec: - storageClassName: standard - capacity: - storage: 20Gi - accessModes: - - ReadWriteOnce - - ReadOnlyMany - hostPath: - path: "/tmp/k8s/badger-pv-3" - ---- -apiVersion: v1 -kind: PersistentVolume -metadata: - name: badger-pv-4 - labels: - type: local - app: flow-test-net -spec: - storageClassName: standard - capacity: - storage: 20Gi - accessModes: - - ReadWriteOnce - - ReadOnlyMany - hostPath: - path: "/tmp/k8s/badger-pv-4" - ---- -apiVersion: v1 -kind: PersistentVolume -metadata: - name: badger-pv-5 - labels: - type: local - app: flow-test-net -spec: - storageClassName: standard - capacity: - storage: 20Gi - accessModes: - - ReadWriteOnce - - ReadOnlyMany - hostPath: - path: "/tmp/k8s/badger-pv-5" diff --git a/k8s/local/flow-verification-node-deployment.yml b/k8s/local/flow-verification-node-deployment.yml deleted file mode 100644 index c53fad7ea7e..00000000000 --- a/k8s/local/flow-verification-node-deployment.yml +++ /dev/null @@ -1,132 +0,0 @@ -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-verification-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: verification - env: local - owner: Kan - version: v1 - -spec: - replicas: 1 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: verification - env: local - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: verification - env: local - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/verification - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - - # Resource requests and constraints - resources: - requests: - cpu: '125m' - memory: '256Mi' - limits: - cpu: '250m' - memory: '512Mi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 20Gi - storageClassName: standard \ No newline at end of file diff --git a/k8s/local/jaeger-all-in-one.yml b/k8s/local/jaeger-all-in-one.yml deleted file mode 100644 index 743e6e753e9..00000000000 --- a/k8s/local/jaeger-all-in-one.yml +++ /dev/null @@ -1,157 +0,0 @@ -# -# Copyright 2017-2019 The Jaeger Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software distributed under the License -# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express -# or implied. See the License for the specific language governing permissions and limitations under -# the License. -# - -# Taken from: https://github.com/jaegertracing/jaeger-kubernetes - -apiVersion: v1 -kind: List -items: -- apiVersion: extensions/v1beta1 - kind: Deployment - metadata: - name: jaeger - labels: - app: jaeger - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: all-in-one - spec: - replicas: 1 - strategy: - type: Recreate - template: - metadata: - labels: - app: jaeger - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: all-in-one - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "16686" - spec: - containers: - - env: - - name: COLLECTOR_ZIPKIN_HTTP_PORT - value: "9411" - image: jaegertracing/all-in-one - name: jaeger - ports: - - containerPort: 5775 - protocol: UDP - - containerPort: 6831 - protocol: UDP - - containerPort: 6832 - protocol: UDP - - containerPort: 5778 - protocol: TCP - - containerPort: 16686 - protocol: TCP - - containerPort: 9411 - protocol: TCP - readinessProbe: - httpGet: - path: "/" - port: 14269 - initialDelaySeconds: 5 -- apiVersion: v1 - kind: Service - metadata: - name: jaeger-query - labels: - app: jaeger - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: query - spec: - ports: - - name: query-http - port: 80 - protocol: TCP - targetPort: 16686 - selector: - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: all-in-one - type: LoadBalancer -- apiVersion: v1 - kind: Service - metadata: - name: jaeger-collector - labels: - app: jaeger - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: collector - spec: - ports: - - name: jaeger-collector-tchannel - port: 14267 - protocol: TCP - targetPort: 14267 - - name: jaeger-collector-http - port: 14268 - protocol: TCP - targetPort: 14268 - - name: jaeger-collector-zipkin - port: 9411 - protocol: TCP - targetPort: 9411 - selector: - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: all-in-one - type: ClusterIP -- apiVersion: v1 - kind: Service - metadata: - name: jaeger-agent - labels: - app: jaeger - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: agent - spec: - ports: - - name: agent-zipkin-thrift - port: 5775 - protocol: UDP - targetPort: 5775 - - name: agent-compact - port: 6831 - protocol: UDP - targetPort: 6831 - - name: agent-binary - port: 6832 - protocol: UDP - targetPort: 6832 - - name: agent-configs - port: 5778 - protocol: TCP - targetPort: 5778 - clusterIP: None - selector: - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: all-in-one -- apiVersion: v1 - kind: Service - metadata: - name: zipkin - labels: - app: jaeger - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: zipkin - spec: - ports: - - name: jaeger-collector-zipkin - port: 9411 - protocol: TCP - targetPort: 9411 - clusterIP: None - selector: - app.kubernetes.io/name: jaeger - app.kubernetes.io/component: all-in-one diff --git a/k8s/staging/flow-collection-node-deployment.yml b/k8s/staging/flow-collection-node-deployment.yml deleted file mode 100644 index 7211babe90c..00000000000 --- a/k8s/staging/flow-collection-node-deployment.yml +++ /dev/null @@ -1,291 +0,0 @@ -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-ingress-service - namespace: flow - - labels: - app: flow-test-net - node: collection - env: staging - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: staging - version: v1 - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - ---- -# To pre-emptively prepare for the case where we'd want to connect to a specific collection cluster, we can have sub services per cluster - -# Service for accessing the first collection cluster -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-v1-0 - namespace: flow - - labels: - app: flow-test-net - node: collection - env: staging - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: staging - version: v1 - statefulset.kubernetes.io/pod-name: flow-collection-node-v1-0 - - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc - ---- - -# Service for accessing the second collection cluster -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-v1-1 - namespace: flow - - labels: - app: flow-test-net - node: collection - env: staging - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: staging - version: v1 - statefulset.kubernetes.io/pod-name: flow-collection-node-v1-1 - - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc - ---- - -# Service for accessing the third collection cluster -apiVersion: v1 -kind: Service - -metadata: - name: flow-collection-node-v1-2 - namespace: flow - - labels: - app: flow-test-net - node: collection - env: staging - owner: Kan - version: v1 - statefulset.kubernetes.io/pod-name: flow-collection-node-v1-2 - -spec: - type: ClusterIP - selector: - app: flow-test-net - node: collection - env: staging - version: v1 - - ports: - - name: ingress - protocol: TCP - port: 9000 - targetPort: ingress - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc - ---- - -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-collection-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: collection - env: staging - owner: Kan - version: v1 - -spec: - replicas: 3 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: collection - env: staging - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: collection - env: staging - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - terminationGracePeriodSeconds: 30 - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/collection - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - '--ingress-addr' - - ':9000' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - - name: ingress - containerPort: 9000 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - # Cannot get ordinal index yet from metadata at this time: https://github.com/kubernetes/kubernetes/pull/83101/files - # Have to parse out from pod name - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - - name: JAEGER_SERVICE_NAME - value: collection - - name: JAEGER_AGENT_HOST - value: jaeger-agent - - name: JAEGER_SAMPLER_TYPE - value: const - - name: JAEGER_SAMPLER_PARAM - value: "1" - - name: JAEGER_REPORTER_LOG_SPANS - value: "true" - # Due to the fact that we're using a headless service, we cannot use the cgo version of net, - # which causes an error, instead, force using the pure go version now - - name: GODEBUG - value: "netdns=go" - - # Resource requests and contraints - resources: - requests: - cpu: '125m' - memory: '128Mi' - limits: - cpu: '250m' - memory: '256Mi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 10Gi - storageClassName: standard diff --git a/k8s/staging/flow-consensus-node-deployment.yml b/k8s/staging/flow-consensus-node-deployment.yml deleted file mode 100644 index 1bb39a9ece7..00000000000 --- a/k8s/staging/flow-consensus-node-deployment.yml +++ /dev/null @@ -1,136 +0,0 @@ -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-consensus-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: consensus - env: staging - owner: Kan - version: v1 - -spec: - replicas: 1 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: consensus - env: staging - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: consensus - env: staging - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/consensus - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - # Due to the fact that we're using a headless service, we cannot use the cgo version of net, - # which causes an error, instead, force using the pure go version now - - name: GODEBUG - value: "netdns=go" - - # Resource requests and constraints - resources: - requests: - cpu: '250m' - memory: '512Mi' - limits: - cpu: '500m' - memory: '2Gi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 10Gi - storageClassName: standard \ No newline at end of file diff --git a/k8s/staging/flow-execution-node-deployment.yml b/k8s/staging/flow-execution-node-deployment.yml deleted file mode 100644 index 06fc8aa8785..00000000000 --- a/k8s/staging/flow-execution-node-deployment.yml +++ /dev/null @@ -1,136 +0,0 @@ -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-execution-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: execution - env: staging - owner: Kan - version: v1 - -spec: - replicas: 1 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: execution - env: staging - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: execution - env: staging - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/execution - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - # Due to the fact that we're using a headless service, we cannot use the cgo version of net, - # which causes an error, instead, force using the pure go version now - - name: GODEBUG - value: "netdns=go" - - # Resource requests and constraints - resources: - requests: - cpu: '125m' - memory: '128Mi' - limits: - cpu: '250m' - memory: '256Mi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 100Gi - storageClassName: standard \ No newline at end of file diff --git a/k8s/staging/flow-network-service.yml b/k8s/staging/flow-network-service.yml deleted file mode 100644 index ecf1735ffd8..00000000000 --- a/k8s/staging/flow-network-service.yml +++ /dev/null @@ -1,33 +0,0 @@ -# Headless Service, for internal cluster access by other pods -apiVersion: v1 -kind: Service - -metadata: - name: flow-test-network-v1 - namespace: flow - - labels: - app: flow-test-net - env: staging - owner: Kan - version: v1 - -spec: - type: ClusterIP - selector: - app: flow-test-net - env: staging - version: v1 - # Headless Service, gives each pod a DNS address only. - # Did not play well with cgo addrinfo lookup, which is used due to the DNS names ending in .local - # best to use pure go implementation - clusterIP: None - ports: - - name: http - protocol: TCP - port: 8080 - targetPort: http # reference to the name of the port in your container config - - name: grpc - protocol: TCP - port: 3569 - targetPort: grpc # reference to the name of the port in your container config \ No newline at end of file diff --git a/k8s/staging/flow-node-config-map.yml b/k8s/staging/flow-node-config-map.yml deleted file mode 100644 index b3cd40cb51b..00000000000 --- a/k8s/staging/flow-node-config-map.yml +++ /dev/null @@ -1,7 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: flow-node-config-map - namespace: flow -data: - entries: 'collection-8a9a01361b8a1e048a17acbd0deb18473e335389667b3e491edf030948335487@flow-collection-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000,collection-a1f922ed445ea61dd50d97d0fa69a69aa22e998530a0b976aae679ebf4756ade@flow-collection-node-v1-1.flow-test-network-v1.flow.svc.cluster.local:3569=1000,collection-b6beaa7f7d45c74192029b9261b703b208d76d054505e77758659c48c1f6f4eb@flow-collection-node-v1-2.flow-test-network-v1.flow.svc.cluster.local:3569=1000,consensus-87aa9e83d59111f912fe785d32e361ff917bb0b452a736dc8de0ca0bdd577b3b@flow-consensus-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000,execution-8806fa187214d53bb1d2ed7fc67d7c3bfc0e1518fa28319c9b9598e89b2cd2ee@flow-execution-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000,verification-fbdb6deafcecaf3b318d271af56156ff99bc9d40152cd93920173fe4027e6d7f@flow-verification-node-v1-0.flow-test-network-v1.flow.svc.cluster.local:3569=1000' diff --git a/k8s/staging/flow-verification-node-deployment.yml b/k8s/staging/flow-verification-node-deployment.yml deleted file mode 100644 index 2bae3231889..00000000000 --- a/k8s/staging/flow-verification-node-deployment.yml +++ /dev/null @@ -1,135 +0,0 @@ -apiVersion: apps/v1 -kind: StatefulSet -metadata: - # This is the full name of your deployment. It must be unique - name: flow-verification-node-v1 - namespace: flow - - # Best practice labels: - # app: (the non-unique version of metadata.name) - # kind: [web|worker] - # env: [staging|production|test|dev] - # owner: who to ask about this service - # version: the major version of this service (v1/v2/v1beta1) - labels: - app: flow-test-net - node: verification - env: staging - owner: Kan - version: v1 - -spec: - replicas: 1 - serviceName: flow-test-network-v1 - selector: - matchLabels: - app: flow-test-net - node: verification - env: staging - version: v1 - podManagementPolicy: Parallel - template: - metadata: - annotations: - # Set to "false" to opt out of prometheus scrapes - # Prometheus still needs a port called "metrics" (below) to scrape properly - prometheus.io/scrape: 'true' - - # Set the path to the API endpoint that exposes prometheus metrics, or leave blank for `/metrics` - # prometheus.io/path: "/metrics" - - labels: - app: flow-test-net - node: verification - env: staging - owner: Kan - version: v1 - kind: web - - spec: - imagePullSecrets: - - name: gcr - containers: - - name: flow-test-net - # No tag, will be attached by teamcity - image: gcr.io/dl-flow/verification - args: - - '--nodename' - - '$(POD_NAME)' - - '--entries' - - '$(NODE_ENTRIES)' - - '--datadir' - - '/flowdb' - - # Ports exposed can be named so other resources can reference - # them by name and not have to hard code numbers - ports: - - name: grpc - containerPort: 3569 - - name: http - containerPort: 8080 - # Prometheus is looking specifically for a port named 'metrics' - # This may be the same as the above port, or different - - name: metrics - containerPort: 8080 - - # Environment variables - env: - - name: ENV - value: STAGING - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: NODE_ENTRIES - valueFrom: - configMapKeyRef: - name: flow-node-config-map - key: entries - # Due to the fact that we're using a headless service, we cannot use the cgo version of net, - # which causes an error, instead, force using the pure go version now - - name: GODEBUG - value: "netdns=go" - # Resource requests and constraints - resources: - requests: - cpu: '125m' - memory: '256Mi' - limits: - cpu: '250m' - memory: '512Mi' - volumeMounts: - - name: badger-volume - mountPath: /flowdb - - # The current liveness and readiness probes use the /metrics endpoint, which is non-ideal and MVP only - # These probes should eventually make use of the gRPC server's Ping function, or should at least - # be moved over to a /live endpoint that has some introspection into the gRPC's liveness/readiness - - # Readiness Probe - readinessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 5 - successThreshold: 1 - - # Liveness Probe - livenessProbe: - httpGet: - path: /metrics - port: http - initialDelaySeconds: 30 - periodSeconds: 30 - successThreshold: 1 - - volumeClaimTemplates: - - metadata: - name: badger-volume - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 20Gi - storageClassName: standard \ No newline at end of file diff --git a/ledger/common/bitutils/utils_test.go b/ledger/common/bitutils/utils_test.go index f168c058ffa..d149cdf766c 100644 --- a/ledger/common/bitutils/utils_test.go +++ b/ledger/common/bitutils/utils_test.go @@ -58,11 +58,11 @@ func TestBitTools(t *testing.T) { for j := 0; j < len(bytes)/2; j++ { bytes[j], bytes[len(bytes)-j-1] = bytes[len(bytes)-j-1], bytes[j] } - for j := 0; j < len(bytes); j++ { + for j := range bytes { bytes[j] = bits.Reverse8(bytes[j]) } // test bit reads are equal for all indices - for i := 0; i < maxBits; i++ { + for i := range maxBits { bit := int(b.Bit(i)) assert.Equal(t, bit, ReadBit(bytes, i)) } @@ -75,7 +75,7 @@ func TestBitTools(t *testing.T) { require.NoError(t, err) // build a random big bit by bit - for idx := 0; idx < maxBits; idx++ { + for idx := range maxBits { bit := rand.Intn(2) // b = 2*b + bit b.Lsh(&b, 1) @@ -96,7 +96,7 @@ func TestBitTools(t *testing.T) { require.NoError(t, err) // build a random big bit by bit - for idx := 0; idx < maxBits; idx++ { + for idx := range maxBits { bit := rand.Intn(2) // b = 2*b + bit b.Lsh(&b, 1) diff --git a/ledger/common/hash/copy_generic.go b/ledger/common/hash/copy_generic.go index 9e35d981519..46462eb0c56 100644 --- a/ledger/common/hash/copy_generic.go +++ b/ledger/common/hash/copy_generic.go @@ -29,7 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //go:build (!amd64 && !386 && !ppc64le) || purego -// +build !amd64,!386,!ppc64le purego package hash @@ -40,7 +39,7 @@ import ( // copyOut copies 32 bytes to a hash array. func copyOut(d *state) Hash { var out Hash - for i := 0; i < 4; i++ { + for i := range 4 { binary.LittleEndian.PutUint64(out[i<<3:], d.a[i]) } return out @@ -74,7 +73,7 @@ func copyIn512(d *state, buf1, buf2 Hash) { func copyIn256(d *state, buf Hash) { sliceBuf := buf[:] - for i := 0; i < 4; i++ { + for i := range 4 { d.a[i] = binary.LittleEndian.Uint64(sliceBuf) sliceBuf = sliceBuf[8:] } diff --git a/ledger/common/hash/copy_unaligned.go b/ledger/common/hash/copy_unaligned.go index c04b9958509..a37cdf45eed 100644 --- a/ledger/common/hash/copy_unaligned.go +++ b/ledger/common/hash/copy_unaligned.go @@ -29,8 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //go:build (amd64 || 386 || ppc64le) && !purego -// +build amd64 386 ppc64le -// +build !purego package hash diff --git a/ledger/common/hash/hash_test.go b/ledger/common/hash/hash_test.go index 1b49293761c..b5b8227208a 100644 --- a/ledger/common/hash/hash_test.go +++ b/ledger/common/hash/hash_test.go @@ -22,7 +22,7 @@ func TestHash(t *testing.T) { t.Run("HashLeaf", func(t *testing.T) { var path hash.Hash - for i := 0; i < 5000; i++ { + for i := range 5000 { value := make([]byte, i) _, err := rand.Read(path[:]) require.NoError(t, err) @@ -41,7 +41,7 @@ func TestHash(t *testing.T) { t.Run("HashInterNode", func(t *testing.T) { var h1, h2 hash.Hash - for i := 0; i < 5000; i++ { + for range 5000 { _, err := rand.Read(h1[:]) require.NoError(t, err) _, err = rand.Read(h2[:]) diff --git a/ledger/common/hash/keccak.go b/ledger/common/hash/keccak.go index 847afb726a5..8ebf2ab6730 100644 --- a/ledger/common/hash/keccak.go +++ b/ledger/common/hash/keccak.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && !purego && gc -// +build amd64,!purego,gc package hash diff --git a/ledger/common/hash/keccakf.go b/ledger/common/hash/keccakf.go index 76d0b9a1a5d..51f7dad8e52 100644 --- a/ledger/common/hash/keccakf.go +++ b/ledger/common/hash/keccakf.go @@ -29,7 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //go:build !amd64 || purego || !gc -// +build !amd64 purego !gc package hash diff --git a/ledger/common/hash/sha3.go b/ledger/common/hash/sha3.go index 9dde092cca3..4e67d2aa48d 100644 --- a/ledger/common/hash/sha3.go +++ b/ledger/common/hash/sha3.go @@ -68,7 +68,7 @@ func xorInAtIndex(d *state, buf []byte, index int) { n := len(buf) >> 3 aAtIndex := d.a[index:] - for i := 0; i < n; i++ { + for i := range n { a := binary.LittleEndian.Uint64(buf) aAtIndex[i] ^= a buf = buf[8:] diff --git a/ledger/common/pathfinder/pathfinder.go b/ledger/common/pathfinder/pathfinder.go index 7849cf28256..9bcae15a1d7 100644 --- a/ledger/common/pathfinder/pathfinder.go +++ b/ledger/common/pathfinder/pathfinder.go @@ -114,7 +114,7 @@ func PathsFromPayloads(payloads []*ledger.Payload, version uint8) ([]ledger.Path return paths, nil } -// UpdateToPayloads constructs an slice of payloads given ledger update +// UpdateToPayloads constructs an slice of payloads given ledger update. func UpdateToPayloads(update *ledger.Update) ([]*ledger.Payload, error) { keys := update.Keys() values := update.Values() diff --git a/ledger/common/testutils/testutils.go b/ledger/common/testutils/testutils.go index e0e100ee46c..c2560e95451 100644 --- a/ledger/common/testutils/testutils.go +++ b/ledger/common/testutils/testutils.go @@ -188,7 +188,7 @@ func RandomPayload(minByteSize int, maxByteSize int) *l.Payload { // RandomPayloads returns n random payloads func RandomPayloads(n int, minByteSize int, maxByteSize int) []*l.Payload { res := make([]*l.Payload, 0) - for i := 0; i < n; i++ { + for range n { res = append(res, RandomPayload(minByteSize, maxByteSize)) } return res @@ -200,7 +200,7 @@ func RandomValues(n int, minByteSize, maxByteSize int) []l.Value { panic("minByteSize cannot be smaller then maxByteSize") } values := make([]l.Value, 0) - for i := 0; i < n; i++ { + for range n { var byteSize = maxByteSize if minByteSize < maxByteSize { byteSize = minByteSize + rand.Intn(maxByteSize-minByteSize) @@ -225,7 +225,7 @@ func RandomUniqueKeys(n, m, minByteSize, maxByteSize int) []l.Key { i := 0 for i < n { keyParts := make([]l.KeyPart, 0) - for j := 0; j < m; j++ { + for j := range m { byteSize := maxByteSize if minByteSize < maxByteSize { byteSize = minByteSize + rand.Intn(maxByteSize-minByteSize) diff --git a/ledger/complete/compactor.go b/ledger/complete/compactor.go index a08a36d2232..0db6dbef7c0 100644 --- a/ledger/complete/compactor.go +++ b/ledger/complete/compactor.go @@ -282,7 +282,14 @@ Loop: } c.logger.Info().Msg("Finished draining trie update channel in compactor on shutdown") - // Don't wait for checkpointing to finish because it might take too long. + // Don't wait for checkpointing to finish if it takes more than 10ms because it might take too long. + // We wait at least a little bit to make the tests a lot more stable. + if !checkpointSem.TryAcquire(1) { + select { + case <-checkpointResultCh: + case <-time.After(10 * time.Millisecond): + } + } } // checkpoint creates checkpoint of tries snapshot, diff --git a/ledger/complete/factory.go b/ledger/complete/factory.go new file mode 100644 index 00000000000..2152a1143f2 --- /dev/null +++ b/ledger/complete/factory.go @@ -0,0 +1,59 @@ +package complete + +import ( + "github.com/rs/zerolog" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger/complete/wal" + "github.com/onflow/flow-go/module" +) + +// LocalLedgerFactory creates in-process ledger instances with compactor. +type LocalLedgerFactory struct { + wal wal.LedgerWAL + capacity int + compactorConfig *ledger.CompactorConfig + triggerCheckpoint *atomic.Bool + metrics module.LedgerMetrics + logger zerolog.Logger + pathFinderVersion uint8 +} + +// NewLocalLedgerFactory creates a new factory for local ledger instances. +// triggerCheckpoint is a runtime control signal to trigger checkpoint on next segment finish. +func NewLocalLedgerFactory( + ledgerWAL wal.LedgerWAL, + capacity int, + compactorConfig *ledger.CompactorConfig, + triggerCheckpoint *atomic.Bool, + metrics module.LedgerMetrics, + logger zerolog.Logger, + pathFinderVersion uint8, +) ledger.Factory { + return &LocalLedgerFactory{ + wal: ledgerWAL, + capacity: capacity, + compactorConfig: compactorConfig, + triggerCheckpoint: triggerCheckpoint, + metrics: metrics, + logger: logger, + pathFinderVersion: pathFinderVersion, + } +} + +func (f *LocalLedgerFactory) NewLedger() (ledger.Ledger, error) { + ledgerWithCompactor, err := NewLedgerWithCompactor( + f.wal, + f.capacity, + f.compactorConfig, + f.triggerCheckpoint, + f.metrics, + f.logger, + f.pathFinderVersion, + ) + if err != nil { + return nil, err + } + return ledgerWithCompactor, nil +} diff --git a/ledger/complete/ledger.go b/ledger/complete/ledger.go index 82ff8e7f477..6ceb65c7dd5 100644 --- a/ledger/complete/ledger.go +++ b/ledger/complete/ledger.go @@ -3,6 +3,7 @@ package complete import ( "fmt" "io" + "sync" "time" "github.com/rs/zerolog" @@ -40,6 +41,7 @@ type Ledger struct { metrics module.LedgerMetrics logger zerolog.Logger trieUpdateCh chan *WALTrieUpdate + closeTrieUpdateCh sync.Once pathFinderVersion uint8 } @@ -110,7 +112,9 @@ func (l *Ledger) Done() <-chan struct{} { // Ledger is responsible for closing trieUpdateCh channel, // so Compactor can drain and process remaining updates. - close(l.trieUpdateCh) + l.closeTrieUpdateCh.Do(func() { + close(l.trieUpdateCh) + }) }() return done } @@ -457,3 +461,36 @@ func (l *Ledger) FindTrieByStateCommit(commitment flow.StateCommitment) (*trie.M return nil, nil } + +// StateCount returns the number of states (tries) stored in the forest +func (l *Ledger) StateCount() int { + return l.ForestSize() +} + +// StateByIndex returns the state at the given index +// -1 is the last index +func (l *Ledger) StateByIndex(index int) (ledger.State, error) { + tries, err := l.Tries() + if err != nil { + return ledger.DummyState, fmt.Errorf("failed to get tries: %w", err) + } + + count := len(tries) + if count == 0 { + return ledger.DummyState, fmt.Errorf("no states available") + } + + // Handle negative index (-1 means last index) + if index < 0 { + index = count + index + if index < 0 { + return ledger.DummyState, fmt.Errorf("index %d is out of range (count: %d)", index-count, count) + } + } + + if index >= count { + return ledger.DummyState, fmt.Errorf("index %d is out of range (count: %d)", index, count) + } + + return ledger.State(tries[index].RootHash()), nil +} diff --git a/ledger/complete/ledger_test.go b/ledger/complete/ledger_test.go index d7021516440..cbe0be529d6 100644 --- a/ledger/complete/ledger_test.go +++ b/ledger/complete/ledger_test.go @@ -813,3 +813,171 @@ func migrationByKey(p []ledger.Payload) ([]ledger.Payload, error) { return ret, nil } + +func TestLedger_StateCount(t *testing.T) { + wal := &fixtures.NoopWAL{} + l, err := complete.NewLedger(wal, 100, &metrics.NoopCollector{}, zerolog.Logger{}, complete.DefaultPathFinderVersion) + require.NoError(t, err) + + compactor := fixtures.NewNoopCompactor(l) + <-compactor.Ready() + defer func() { + <-l.Done() + <-compactor.Done() + }() + + // Initially should have at least the empty trie + initialCount := l.StateCount() + assert.GreaterOrEqual(t, initialCount, 1, "should have at least one state (empty trie)") + + // Create some updates to add more states + state := l.InitialState() + keys := testutils.RandomUniqueKeys(3, 2, 2, 4) + values := testutils.RandomValues(3, 1, 32) + + // First update + update1, err := ledger.NewUpdate(state, keys[0:1], values[0:1]) + require.NoError(t, err) + newState1, _, err := l.Set(update1) + require.NoError(t, err) + + // Second update from the first new state + update2, err := ledger.NewUpdate(newState1, keys[1:2], values[1:2]) + require.NoError(t, err) + newState2, _, err := l.Set(update2) + require.NoError(t, err) + + // State count should have increased + finalCount := l.StateCount() + assert.Greater(t, finalCount, initialCount, "state count should increase after updates") + _ = newState2 // avoid unused variable +} + +func TestLedger_StateByIndex(t *testing.T) { + wal := &fixtures.NoopWAL{} + l, err := complete.NewLedger(wal, 100, &metrics.NoopCollector{}, zerolog.Logger{}, complete.DefaultPathFinderVersion) + require.NoError(t, err) + + compactor := fixtures.NewNoopCompactor(l) + <-compactor.Ready() + defer func() { + <-l.Done() + <-compactor.Done() + }() + + // Get initial state + initialState := l.InitialState() + stateCount := l.StateCount() + require.Greater(t, stateCount, 0, "should have at least one state") + + // Test getting state at index 0 + state0, err := l.StateByIndex(0) + require.NoError(t, err) + assert.NotEqual(t, ledger.DummyState, state0, "state at index 0 should not be dummy state") + + // Test getting last state using -1 + lastState, err := l.StateByIndex(-1) + require.NoError(t, err) + assert.NotEqual(t, ledger.DummyState, lastState, "last state should not be dummy state") + + // Create some updates to add more states + state := initialState + keys := testutils.RandomUniqueKeys(3, 2, 2, 4) + values := testutils.RandomValues(3, 1, 32) + + // Create multiple updates + for i := 0; i < 3; i++ { + update, err := ledger.NewUpdate(state, keys[i:i+1], values[i:i+1]) + require.NoError(t, err) + newState, _, err := l.Set(update) + require.NoError(t, err) + state = newState + } + + // Verify we can get states by index + finalCount := l.StateCount() + require.GreaterOrEqual(t, finalCount, 1, "should have at least one state") + + // Test getting first state + firstState, err := l.StateByIndex(0) + require.NoError(t, err) + assert.NotEqual(t, ledger.DummyState, firstState) + + // Test getting last state with -1 + lastStateAfterUpdates, err := l.StateByIndex(-1) + require.NoError(t, err) + assert.NotEqual(t, ledger.DummyState, lastStateAfterUpdates) + + // Test getting last state with positive index + if finalCount > 0 { + lastStateByIndex, err := l.StateByIndex(finalCount - 1) + require.NoError(t, err) + assert.NotEqual(t, ledger.DummyState, lastStateByIndex) + // Last state by index should match last state by -1 + assert.Equal(t, lastStateAfterUpdates, lastStateByIndex, "last state by -1 should match last state by positive index") + } + + // Test out of range indices + _, err = l.StateByIndex(finalCount) + require.Error(t, err, "should error for index out of range") + + _, err = l.StateByIndex(-finalCount - 1) + require.Error(t, err, "should error for negative index out of range") +} + +func TestLedgerWithCompactor_StateCountAndStateByIndex(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + metricsCollector := &metrics.NoopCollector{} + diskWal, err := wal.NewDiskWAL(zerolog.Nop(), nil, metricsCollector, dir, 100, pathfinder.PathByteSize, wal.SegmentSize) + require.NoError(t, err) + + compactorConfig := ledger.DefaultCompactorConfig(metricsCollector) + lwc, err := complete.NewLedgerWithCompactor( + diskWal, + 100, + compactorConfig, + atomic.NewBool(false), + metricsCollector, + zerolog.Nop(), + complete.DefaultPathFinderVersion, + ) + require.NoError(t, err) + + <-lwc.Ready() + defer func() { + <-lwc.Done() + }() + + // Test StateCount + initialCount := lwc.StateCount() + assert.GreaterOrEqual(t, initialCount, 1, "should have at least one state") + + // Test StateByIndex + state0, err := lwc.StateByIndex(0) + require.NoError(t, err) + assert.NotEqual(t, ledger.DummyState, state0) + + lastState, err := lwc.StateByIndex(-1) + require.NoError(t, err) + assert.NotEqual(t, ledger.DummyState, lastState) + + // Create some updates + state := lwc.InitialState() + keys := testutils.RandomUniqueKeys(2, 2, 2, 4) + values := testutils.RandomValues(2, 1, 32) + + update, err := ledger.NewUpdate(state, keys, values) + require.NoError(t, err) + newState, _, err := lwc.Set(update) + require.NoError(t, err) + + // Verify StateCount increased + finalCount := lwc.StateCount() + assert.Greater(t, finalCount, initialCount, "state count should increase after update") + + // Verify we can get the new state + lastStateAfterUpdate, err := lwc.StateByIndex(-1) + require.NoError(t, err) + assert.Equal(t, ledger.State(newState), lastStateAfterUpdate, "last state should match the new state") + }) +} diff --git a/ledger/complete/ledger_with_compactor.go b/ledger/complete/ledger_with_compactor.go new file mode 100644 index 00000000000..7a07d65c8e1 --- /dev/null +++ b/ledger/complete/ledger_with_compactor.go @@ -0,0 +1,116 @@ +package complete + +import ( + "fmt" + + "github.com/rs/zerolog" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/ledger" + realWAL "github.com/onflow/flow-go/ledger/complete/wal" + "github.com/onflow/flow-go/module" +) + +// LedgerWithCompactor wraps a Ledger and its internal Compactor, +// managing both as a single component. This hides the compactor +// as an implementation detail. +// Embedding *Ledger allows automatic delegation of Ledger methods. +type LedgerWithCompactor struct { + *Ledger + compactor *Compactor + logger zerolog.Logger +} + +// NewLedgerWithCompactor creates a new ledger with an internal compactor. +// The compactor lifecycle is managed by this wrapper. +// Use Ready() to wait for the ledger and compactor to be ready. +// triggerCheckpoint is a runtime control signal to trigger checkpoint on next segment finish. +func NewLedgerWithCompactor( + diskWAL realWAL.LedgerWAL, + ledgerCapacity int, + compactorConfig *ledger.CompactorConfig, + triggerCheckpoint *atomic.Bool, + metrics module.LedgerMetrics, + logger zerolog.Logger, + pathFinderVersion uint8, +) (*LedgerWithCompactor, error) { + logger = logger.With().Str("ledger_mod", "complete").Logger() + + // Create the ledger + l, err := NewLedger(diskWAL, ledgerCapacity, metrics, logger, pathFinderVersion) + if err != nil { + return nil, fmt.Errorf("failed to create ledger: %w", err) + } + + // Create the compactor (internal to ledger) + compactor, err := NewCompactor( + l, + diskWAL, + logger.With().Str("subcomponent", "compactor").Logger(), + compactorConfig.CheckpointCapacity, + compactorConfig.CheckpointDistance, + compactorConfig.CheckpointsToKeep, + triggerCheckpoint, + compactorConfig.Metrics, + ) + if err != nil { + return nil, fmt.Errorf("failed to create compactor: %w", err) + } + + return &LedgerWithCompactor{ + Ledger: l, + compactor: compactor, + logger: logger, + }, nil +} + +// Note: Ledger methods (InitialState, HasState, GetSingleValue, Get, Set, Prove, +// StateCount, StateByIndex) are automatically delegated via embedding. + +// Ready manages lifecycle of both ledger and compactor. +// Signals when initialization (WAL replay) is complete and compactor is ready. +// Overrides the embedded Ledger.Ready() to coordinate with the compactor. +func (lwc *LedgerWithCompactor) Ready() <-chan struct{} { + ready := make(chan struct{}) + go func() { + defer close(ready) + + // Wait for ledger initialization (WAL replay) to complete + <-lwc.Ledger.Ready() + + // Start compactor + <-lwc.compactor.Ready() + + lwc.logger.Info().Msg("ledger with compactor ready") + }() + return ready +} + +// Done manages shutdown of both ledger and compactor. +// Overrides the embedded Ledger.Done() to coordinate with the compactor. +func (lwc *LedgerWithCompactor) Done() <-chan struct{} { + done := make(chan struct{}) + go func() { + defer close(done) + + lwc.logger.Info().Msg("stopping ledger with compactor...") + + // Close the trie update channel first so the compactor can drain it + // The compactor's drain loop blocks until the channel is closed. + // Use sync.Once to ensure it's only closed once (ledger.Done() also closes it). + lwc.closeTrieUpdateCh.Do(func() { + close(lwc.trieUpdateCh) + }) + + // Stop compactor first (it needs to finish WAL writes) + <-lwc.compactor.Done() + + lwc.logger.Info().Msg("stopping ledger ...") + + // Then stop ledger + <-lwc.Ledger.Done() + + lwc.logger.Info().Msg("ledger with compactor stopped") + }() + return done +} diff --git a/ledger/complete/mtrie/flattener/encoding_test.go b/ledger/complete/mtrie/flattener/encoding_test.go index 8b157a1e9d7..bf1b341ca76 100644 --- a/ledger/complete/mtrie/flattener/encoding_test.go +++ b/ledger/complete/mtrie/flattener/encoding_test.go @@ -157,7 +157,7 @@ func TestRandomLeafNodeEncodingDecoding(t *testing.T) { writeScratch := make([]byte, scratchBufferSize) readScratch := make([]byte, scratchBufferSize) - for i := 0; i < count; i++ { + for i := range count { height := rand.Intn(257) var hashValue hash.Hash diff --git a/ledger/complete/mtrie/trie/trie.go b/ledger/complete/mtrie/trie/trie.go index 064e7f157e3..2c65584045f 100644 --- a/ledger/complete/mtrie/trie/trie.go +++ b/ledger/complete/mtrie/trie/trie.go @@ -188,11 +188,9 @@ func valueSizes(sizes []int, paths []ledger.Path, head *node.Node) { } else { // concurrent read of left and right subtree wg := sync.WaitGroup{} - wg.Add(1) - go func() { + wg.Go(func() { valueSizes(lsizes, lpaths, head.LeftChild()) - wg.Done() - }() + }) valueSizes(rsizes, rpaths, head.RightChild()) wg.Wait() // wait for all threads } @@ -301,11 +299,9 @@ func read(payloads []*ledger.Payload, paths []ledger.Path, head *node.Node) { } else { // concurrent read of left and right subtree wg := sync.WaitGroup{} - wg.Add(1) - go func() { + wg.Go(func() { read(lpayloads, lpaths, head.LeftChild()) - wg.Done() - }() + }) read(rpayloads, rpaths, head.RightChild()) wg.Wait() // wait for all threads } @@ -647,12 +643,10 @@ func prove(head *node.Node, paths []ledger.Path, proofs []*ledger.TrieProof) { prove(head.RightChild(), rpaths, rproofs) } else { wg := sync.WaitGroup{} - wg.Add(1) - go func() { + wg.Go(func() { addSiblingTrieHashToProofs(head.RightChild(), depth, lproofs) prove(head.LeftChild(), lpaths, lproofs) - wg.Done() - }() + }) addSiblingTrieHashToProofs(head.LeftChild(), depth, rproofs) prove(head.RightChild(), rpaths, rproofs) diff --git a/ledger/complete/wal/checkpoint_v5_test.go b/ledger/complete/wal/checkpoint_v5_test.go index 4422d3376c0..0cd61adf481 100644 --- a/ledger/complete/wal/checkpoint_v5_test.go +++ b/ledger/complete/wal/checkpoint_v5_test.go @@ -4,6 +4,7 @@ import ( "path/filepath" "testing" + "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" @@ -14,7 +15,7 @@ func TestCopyCheckpointFileV5(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createSimpleTrie(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV5(dir, fileName, logger, tries...), "fail to store checkpoint") to := filepath.Join(dir, "newfolder") newPaths, err := CopyCheckpointFile(fileName, dir, to) diff --git a/ledger/complete/wal/checkpoint_v6_test.go b/ledger/complete/wal/checkpoint_v6_test.go index 83bbcb2a4c7..1e036d3adf6 100644 --- a/ledger/complete/wal/checkpoint_v6_test.go +++ b/ledger/complete/wal/checkpoint_v6_test.go @@ -188,7 +188,7 @@ func createMultipleRandomTriesMini(t *testing.T) ([]*trie.MTrie, *trie.MTrie) { func TestEncodeSubTrie(t *testing.T) { file := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() tries := createMultipleRandomTries(t) estimatedSubtrieNodeCount := estimateSubtrieNodeCount(tries[0]) subtrieRoots := createSubTrieRoots(tries) @@ -287,7 +287,7 @@ func TestWriteAndReadCheckpointV6EmptyTrie(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := []*trie.MTrie{trie.NewEmptyMTrie()} fileName := "checkpoint-empty-trie" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") decoded, err := OpenAndReadCheckpointV6(dir, fileName, logger) require.NoErrorf(t, err, "fail to read checkpoint %v/%v", dir, fileName) @@ -299,7 +299,7 @@ func TestWriteAndReadCheckpointV6SimpleTrie(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createSimpleTrie(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") decoded, err := OpenAndReadCheckpointV6(dir, fileName, logger) require.NoErrorf(t, err, "fail to read checkpoint %v/%v", dir, fileName) @@ -311,7 +311,7 @@ func TestWriteAndReadCheckpointV6MultipleTries(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createMultipleRandomTries(t) fileName := "checkpoint-multi-file" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") decoded, err := OpenAndReadCheckpointV6(dir, fileName, logger) require.NoErrorf(t, err, "fail to read checkpoint %v/%v", dir, fileName) @@ -323,7 +323,7 @@ func TestWriteAndReadCheckpointV6MultipleTries(t *testing.T) { func TestCheckpointV6IsDeterminstic(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createMultipleRandomTries(t) - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, "checkpoint1", logger), "fail to store checkpoint") require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, "checkpoint2", logger), "fail to store checkpoint") partFiles1 := filePaths(dir, "checkpoint1", subtrieLevel) @@ -342,7 +342,7 @@ func TestWriteAndReadCheckpointV6LeafEmptyTrie(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := []*trie.MTrie{trie.NewEmptyMTrie()} fileName := "checkpoint-empty-trie" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") bufSize := 10 @@ -361,7 +361,7 @@ func TestWriteAndReadCheckpointV6LeafSimpleTrie(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createSimpleTrie(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") bufSize := 1 leafNodesCh := make(chan *LeafNode, bufSize) @@ -385,7 +385,7 @@ func TestWriteAndReadCheckpointV6LeafMultipleTriesFail(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { fileName := "checkpoint-multi-leaf-file" tries, _ := createMultipleRandomTriesMini(t) - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") bufSize := 5 leafNodesCh := make(chan *LeafNode, bufSize) @@ -402,7 +402,7 @@ func TestWriteAndReadCheckpointV6LeafMultipleTriesOK(t *testing.T) { tries := []*trie.MTrie{last} - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") bufSize := 5 leafNodesCh := make(chan *LeafNode, bufSize) @@ -491,7 +491,7 @@ func TestWriteAndReadCheckpointV5(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createMultipleRandomTries(t) fileName := "checkpoint1" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, storeCheckpointV5(tries, dir, fileName, logger), "fail to store checkpoint") decoded, err := LoadCheckpoint(filepath.Join(dir, fileName), logger) @@ -505,7 +505,7 @@ func TestWriteAndReadCheckpointV5(t *testing.T) { func TestWriteAndReadCheckpointV6ThenBackToV5(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createMultipleRandomTries(t) - logger := unittest.Logger() + logger := zerolog.Nop() // store tries into v6 then read back, then store into v5 require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, "checkpoint-v6", logger), "fail to store checkpoint") @@ -534,7 +534,7 @@ func TestCleanupOnErrorIfNotExist(t *testing.T) { t.Run("clean up after finish storing files", func(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createMultipleRandomTries(t) - logger := unittest.Logger() + logger := zerolog.Nop() // store tries into v6 then read back, then store into v5 require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, "checkpoint-v6", logger), "fail to store checkpoint") @@ -565,7 +565,7 @@ func TestAllPartFileExist(t *testing.T) { } require.NoErrorf(t, err, "fail to find sub trie file path") - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") // delete i-th part file, then the error should mention i-th file missing @@ -593,7 +593,7 @@ func TestAllPartFileExistLeafReader(t *testing.T) { } require.NoErrorf(t, err, "fail to find sub trie file path") - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") // delete i-th part file, then the error should mention i-th file missing @@ -613,7 +613,7 @@ func TestCannotStoreTwice(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createSimpleTrie(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") // checkpoint already exist, can't store again require.Error(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger)) @@ -640,7 +640,7 @@ func TestCopyCheckpointFileV6(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createSimpleTrie(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") to := filepath.Join(dir, "newfolder") newPaths, err := CopyCheckpointFile(fileName, dir, to) @@ -656,7 +656,7 @@ func TestReadCheckpointRootHash(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createSimpleTrie(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") trieRoots, err := ReadTriesRootHash(logger, dir, fileName) @@ -673,7 +673,7 @@ func TestReadCheckpointRootHashValidateChecksum(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createSimpleTrie(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") // add a wrong checksum to top trie file @@ -700,7 +700,7 @@ func TestReadCheckpointRootHashMulti(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createMultipleRandomTries(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") trieRoots, err := ReadTriesRootHash(logger, dir, fileName) @@ -717,7 +717,7 @@ func TestCheckpointHasRootHash(t *testing.T) { unittest.RunWithTempDir(t, func(dir string) { tries := createMultipleRandomTries(t) fileName := "checkpoint" - logger := unittest.Logger() + logger := zerolog.Nop() require.NoErrorf(t, StoreCheckpointV6Concurrently(tries, dir, fileName, logger), "fail to store checkpoint") trieRoots, err := ReadTriesRootHash(logger, dir, fileName) diff --git a/ledger/complete/wal/checkpointer.go b/ledger/complete/wal/checkpointer.go index b67f2385440..2c1aeead713 100644 --- a/ledger/complete/wal/checkpointer.go +++ b/ledger/complete/wal/checkpointer.go @@ -15,7 +15,6 @@ import ( "github.com/docker/go-units" "github.com/rs/zerolog" - "github.com/rs/zerolog/log" "golang.org/x/sync/errgroup" "github.com/onflow/flow-go/ledger" @@ -439,7 +438,7 @@ func StoreCheckpointV5(dir string, fileName string, logger zerolog.Logger, tries // Index 0 is a special case with nil node. traversedSubtrieNodes[nil] = 0 - logging := logProgress(fmt.Sprintf("storing %v-th sub trie roots", i), estimatedSubtrieNodeCount, log.Logger) + logging := logProgress(fmt.Sprintf("storing %v-th sub trie roots", i), estimatedSubtrieNodeCount, logger) for _, root := range subTrieRoot { // Empty trie is always added to forest as starting point and // empty trie's root is nil. It remains in the forest until evicted @@ -1110,7 +1109,37 @@ func SoftlinkCheckpointFile(filename string, from string, to string) ([]string, newPath := filepath.Join(to, partfile) newPaths[i] = newPath - err := os.Symlink(match, newPath) + // Check if symlink already exists and points to the correct target + if fi, err := os.Lstat(newPath); err == nil { + if fi.Mode()&os.ModeSymlink != 0 { + // Symlink exists, check if it points to the correct target + target, err := os.Readlink(newPath) + if err != nil { + return nil, fmt.Errorf("cannot read existing symlink %v: %w", newPath, err) + } + // Calculate expected relative target for comparison + symlinkDir := filepath.Dir(newPath) + expectedRelTarget, _ := filepath.Rel(symlinkDir, match) + if target == expectedRelTarget || target == match { + // Symlink already exists and points to correct target, skip creation + continue + } + // Symlink exists but points to different target, this is an error + return nil, fmt.Errorf("symlink %v already exists but points to %v instead of %v", newPath, target, match) + } + // Path exists but is not a symlink, this is an error + return nil, fmt.Errorf("path %v already exists but is not a symlink", newPath) + } + + // Create symlink with relative path from newPath to match + // This ensures the symlink works in both host and container contexts + symlinkDir := filepath.Dir(newPath) + relTarget, err := filepath.Rel(symlinkDir, match) + if err != nil { + // If relative path calculation fails, use match as-is + relTarget = match + } + err = os.Symlink(relTarget, newPath) if err != nil { return nil, fmt.Errorf("cannot link file from %v to %v: %w", match, newPath, err) } diff --git a/ledger/complete/wal/checkpointer_test.go b/ledger/complete/wal/checkpointer_test.go index dd46ffdb85e..f69faeb3269 100644 --- a/ledger/complete/wal/checkpointer_test.go +++ b/ledger/complete/wal/checkpointer_test.go @@ -485,16 +485,25 @@ func randomlyModifyFile(t *testing.T, filename string) { file, err := os.OpenFile(filename, os.O_RDWR, 0644) require.NoError(t, err) + defer file.Close() fileInfo, err := file.Stat() require.NoError(t, err) fileSize := fileInfo.Size() + if fileSize == 0 { + // Empty file, nothing to modify - this shouldn't happen in normal test scenarios + // but handle gracefully by returning early + return + } + buf := make([]byte, 1) // get some random offset - offset := int64(rand.Int()) % (fileSize + int64(len(buf))) + // Use fileSize (not fileSize + len(buf)) to ensure offset is always < fileSize + // Valid file positions are 0 to fileSize-1 + offset := int64(rand.Int()) % fileSize _, err = file.ReadAt(buf, offset) require.NoError(t, err) diff --git a/ledger/complete/wal/fadvise.go b/ledger/complete/wal/fadvise.go index a949b098e6d..ea4a5ce8ad2 100644 --- a/ledger/complete/wal/fadvise.go +++ b/ledger/complete/wal/fadvise.go @@ -1,5 +1,4 @@ //go:build !linux -// +build !linux package wal diff --git a/ledger/complete/wal/fadvise_linux.go b/ledger/complete/wal/fadvise_linux.go index 71d951d8af8..0cfebacc103 100644 --- a/ledger/complete/wal/fadvise_linux.go +++ b/ledger/complete/wal/fadvise_linux.go @@ -1,5 +1,4 @@ //go:build linux -// +build linux package wal diff --git a/ledger/complete/wal/wal.go b/ledger/complete/wal/wal.go index 4f8d04082c2..cbfe9ba6780 100644 --- a/ledger/complete/wal/wal.go +++ b/ledger/complete/wal/wal.go @@ -4,6 +4,7 @@ import ( "fmt" "sort" + "github.com/hashicorp/go-multierror" prometheusWAL "github.com/onflow/wal/wal" "github.com/prometheus/client_golang/prometheus" "github.com/rs/zerolog" @@ -12,6 +13,7 @@ import ( "github.com/onflow/flow-go/ledger/complete/mtrie" "github.com/onflow/flow-go/ledger/complete/mtrie/trie" "github.com/onflow/flow-go/module" + utilsio "github.com/onflow/flow-go/utils/io" ) const SegmentSize = 32 * 1024 * 1024 // 32 MB @@ -23,21 +25,43 @@ type DiskWAL struct { pathByteSize int log zerolog.Logger dir string + fileLock *utilsio.FileLock } // TODO use real logger and metrics, but that would require passing them to Trie storage func NewDiskWAL(logger zerolog.Logger, reg prometheus.Registerer, metrics module.WALMetrics, dir string, forestCapacity int, pathByteSize int, segmentSize int) (*DiskWAL, error) { + // Acquire exclusive file lock to ensure only one process can write to this WAL directory + fileLock, err := utilsio.NewFileLock(dir) + if err != nil { + panic(fmt.Sprintf("failed to create file lock for WAL directory %s: %v", dir, err)) + } + if err := fileLock.Lock(); err != nil { + // The Lock() method returns a complete error message that distinguishes between + // permission denied and lock conflicts. This is a fatal error - the process should crash. + panic(err.Error()) + } + w, err := prometheusWAL.NewSize(logger, reg, dir, segmentSize, false) if err != nil { - return nil, fmt.Errorf("could not create disk wal from dir %v, segmentSize %v: %w", dir, segmentSize, err) + // Release the lock if WAL creation fails + err = fmt.Errorf("could not create disk wal from dir %v, segmentSize %v: %w", dir, segmentSize, err) + if unlockErr := fileLock.Unlock(); unlockErr != nil { + err = multierror.Append(err, fmt.Errorf("failed to release file lock: %w", unlockErr)) + } + return nil, err } + + log := logger.With().Str("ledger_mod", "diskwal").Logger() + log.Info().Str("lock_path", fileLock.Path()).Msg("acquired exclusive lock on WAL directory") + return &DiskWAL{ wal: w, paused: false, forestCapacity: forestCapacity, pathByteSize: pathByteSize, - log: logger.With().Str("ledger_mod", "diskwal").Logger(), + log: log, dir: dir, + fileLock: fileLock, }, nil } @@ -341,12 +365,22 @@ func (w *DiskWAL) Ready() <-chan struct{} { } // Done implements interface module.ReadyDoneAware -// it closes all the open write-ahead log files. +// it closes all the open write-ahead log files and releases the file lock. func (w *DiskWAL) Done() <-chan struct{} { err := w.wal.Close() if err != nil { w.log.Err(err).Msg("error while closing WAL") } + + // Release the file lock + if w.fileLock != nil { + if err := w.fileLock.Unlock(); err != nil { + w.log.Err(err).Msg("error while releasing file lock") + } else { + w.log.Info().Str("lock_path", w.fileLock.Path()).Msg("released exclusive lock on WAL directory") + } + } + done := make(chan struct{}) close(done) return done diff --git a/ledger/config.go b/ledger/config.go new file mode 100644 index 00000000000..4b6f9dcd6ae --- /dev/null +++ b/ledger/config.go @@ -0,0 +1,30 @@ +package ledger + +import ( + "github.com/onflow/flow-go/module" +) + +// Default values for ledger configuration. +const ( + DefaultMTrieCacheSize = 500 + DefaultCheckpointDistance = 20 + DefaultCheckpointsToKeep = 5 +) + +// CompactorConfig holds configuration for ledger compaction. +type CompactorConfig struct { + CheckpointCapacity uint + CheckpointDistance uint + CheckpointsToKeep uint + Metrics module.WALMetrics +} + +// DefaultCompactorConfig returns default compactor configuration. +func DefaultCompactorConfig(metrics module.WALMetrics) *CompactorConfig { + return &CompactorConfig{ + CheckpointCapacity: DefaultMTrieCacheSize, + CheckpointDistance: DefaultCheckpointDistance, + CheckpointsToKeep: DefaultCheckpointsToKeep, + Metrics: metrics, + } +} diff --git a/ledger/factory.go b/ledger/factory.go new file mode 100644 index 00000000000..29d656a6d4e --- /dev/null +++ b/ledger/factory.go @@ -0,0 +1,9 @@ +package ledger + +// Factory creates ledger instances with internal compaction management. +// The compactor lifecycle is managed internally by the ledger. +type Factory interface { + // NewLedger creates a new ledger instance with internal compactor. + // The ledger's Ready() method will signal when initialization (WAL replay) is complete. + NewLedger() (Ledger, error) +} diff --git a/ledger/factory/factory.go b/ledger/factory/factory.go new file mode 100644 index 00000000000..a5120f0fb47 --- /dev/null +++ b/ledger/factory/factory.go @@ -0,0 +1,117 @@ +package factory + +import ( + "fmt" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/zerolog" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger/common/pathfinder" + "github.com/onflow/flow-go/ledger/complete" + "github.com/onflow/flow-go/ledger/complete/wal" + "github.com/onflow/flow-go/ledger/remote" + "github.com/onflow/flow-go/module" +) + +// Config holds configuration for creating a ledger instance. +type Config struct { + // Remote ledger service configuration + LedgerServiceAddr string // gRPC address for remote ledger service (empty means use local ledger) + LedgerMaxRequestSize uint // Maximum request message size in bytes for remote ledger client (0 = default 1 GiB) + LedgerMaxResponseSize uint // Maximum response message size in bytes for remote ledger client (0 = default 1 GiB) + + // Local ledger configuration + Triedir string + MTrieCacheSize uint32 + CheckpointDistance uint + CheckpointsToKeep uint + MetricsRegisterer prometheus.Registerer + WALMetrics module.WALMetrics + LedgerMetrics module.LedgerMetrics + Logger zerolog.Logger +} + +// NewLedger creates a ledger instance based on the configuration. +// If LedgerServiceAddr is set, it creates a remote ledger client. +// Otherwise, it creates a local ledger with WAL and compactor. +// triggerCheckpoint is a runtime control signal to trigger checkpoint on next segment finish (can be nil for remote ledger). +func NewLedger(config Config, triggerCheckpoint *atomic.Bool) (ledger.Ledger, error) { + if config.LedgerServiceAddr != "" { + return newRemoteLedger(config) + } + return newLocalLedger(config, triggerCheckpoint) +} + +// newRemoteLedger creates a remote ledger client that connects to a ledger service. +func newRemoteLedger(config Config) (ledger.Ledger, error) { + config.Logger.Info(). + Str("ledger_service_addr", config.LedgerServiceAddr). + Msg("using remote ledger service") + + factory := remote.NewRemoteLedgerFactory( + config.LedgerServiceAddr, + config.Logger.With().Str("subcomponent", "ledger").Logger(), + config.LedgerMaxRequestSize, + config.LedgerMaxResponseSize, + ) + + ledgerStorage, err := factory.NewLedger() + if err != nil { + return nil, fmt.Errorf("failed to create remote ledger: %w", err) + } + + return ledgerStorage, nil +} + +// newLocalLedger creates a local ledger with WAL and compactor. +func newLocalLedger(config Config, triggerCheckpoint *atomic.Bool) (ledger.Ledger, error) { + // the local ledger service is used when: + // 1. execution node is running ledger in local + // 2. the standalone ledger service is running it in local + + config.Logger.Info(). + Str("triedir", config.Triedir). + Msg("using local ledger") + + // Create WAL + diskWal, err := wal.NewDiskWAL( + config.Logger.With().Str("subcomponent", "wal").Logger(), + config.MetricsRegisterer, + config.WALMetrics, + config.Triedir, + int(config.MTrieCacheSize), + pathfinder.PathByteSize, + wal.SegmentSize, + ) + if err != nil { + return nil, fmt.Errorf("failed to initialize wal: %w", err) + } + + // Create compactor config + compactorConfig := &ledger.CompactorConfig{ + CheckpointCapacity: uint(config.MTrieCacheSize), + CheckpointDistance: config.CheckpointDistance, + CheckpointsToKeep: config.CheckpointsToKeep, + Metrics: config.WALMetrics, + } + + // Use factory to create ledger with internal compactor + factory := complete.NewLocalLedgerFactory( + diskWal, + int(config.MTrieCacheSize), + compactorConfig, + triggerCheckpoint, + config.LedgerMetrics, + config.Logger.With().Str("subcomponent", "ledger").Logger(), + complete.DefaultPathFinderVersion, + ) + + ledgerStorage, err := factory.NewLedger() + if err != nil { + return nil, fmt.Errorf("failed to create local ledger: %w", err) + } + + return ledgerStorage, nil +} diff --git a/ledger/factory/factory_test.go b/ledger/factory/factory_test.go new file mode 100644 index 00000000000..d42b50dd09d --- /dev/null +++ b/ledger/factory/factory_test.go @@ -0,0 +1,500 @@ +package factory + +import ( + "context" + "fmt" + "net" + "os" + "path/filepath" + "testing" + "time" + + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/atomic" + "google.golang.org/grpc" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/utils/unittest" + + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger/common/pathfinder" + "github.com/onflow/flow-go/ledger/complete" + "github.com/onflow/flow-go/ledger/complete/wal" + ledgerpb "github.com/onflow/flow-go/ledger/protobuf" + "github.com/onflow/flow-go/ledger/remote" + "github.com/onflow/flow-go/module/metrics" +) + +// TestRemoteLedgerClient creates a local ledger and a remote ledger client, +// and tests that they behave identically for various operations. +func TestRemoteLedgerClient(t *testing.T) { + withLedgerPair(t, func(localLedger, remoteLedger ledger.Ledger) { + + t.Run("InitialState", func(t *testing.T) { + localState := localLedger.InitialState() + remoteState := remoteLedger.InitialState() + + // Both should return the same initial state + assert.Equal(t, localState, remoteState, "InitialState should be the same for local and remote ledger") + assert.NotEqual(t, ledger.DummyState, localState) + assert.NotEqual(t, ledger.DummyState, remoteState) + }) + + t.Run("HasState", func(t *testing.T) { + localInitialState := localLedger.InitialState() + remoteInitialState := remoteLedger.InitialState() + + // Both should have the same initial state + assert.Equal(t, localInitialState, remoteInitialState) + + localHasState := localLedger.HasState(localInitialState) + remoteHasState := remoteLedger.HasState(remoteInitialState) + assert.Equal(t, localHasState, remoteHasState, "HasState should return the same result for local and remote ledger") + assert.True(t, localHasState) + + // Test with non-existent state + dummyState := ledger.DummyState + localHasState = localLedger.HasState(dummyState) + remoteHasState = remoteLedger.HasState(dummyState) + assert.Equal(t, localHasState, remoteHasState, "HasState for non-existent state should return the same result") + assert.False(t, localHasState) + }) + + t.Run("GetSingleValue", func(t *testing.T) { + localInitialState := localLedger.InitialState() + remoteInitialState := remoteLedger.InitialState() + assert.Equal(t, localInitialState, remoteInitialState) + + // Create a test key + key := ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key")), + }) + + localQuery, err := ledger.NewQuerySingleValue(localInitialState, key) + require.NoError(t, err) + remoteQuery, err := ledger.NewQuerySingleValue(remoteInitialState, key) + require.NoError(t, err) + + localValue, err := localLedger.GetSingleValue(localQuery) + require.NoError(t, err) + remoteValue, err := remoteLedger.GetSingleValue(remoteQuery) + require.NoError(t, err) + + // Both should return the same value + assert.Equal(t, localValue, remoteValue, "GetSingleValue should return the same value for local and remote ledger") + assert.Equal(t, ledger.Value([]byte{}), localValue) + assert.Equal(t, 0, len(localValue)) + }) + + t.Run("Get", func(t *testing.T) { + localInitialState := localLedger.InitialState() + remoteInitialState := remoteLedger.InitialState() + assert.Equal(t, localInitialState, remoteInitialState) + + // Create test keys + keys := []ledger.Key{ + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner1")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key1")), + }), + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner2")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key2")), + }), + } + + localQuery, err := ledger.NewQuery(localInitialState, keys) + require.NoError(t, err) + remoteQuery, err := ledger.NewQuery(remoteInitialState, keys) + require.NoError(t, err) + + localValues, err := localLedger.Get(localQuery) + require.NoError(t, err) + remoteValues, err := remoteLedger.Get(remoteQuery) + require.NoError(t, err) + + // Both should return the same values + require.Len(t, localValues, 2) + require.Len(t, remoteValues, 2) + assert.Equal(t, localValues, remoteValues, "Get should return the same values for local and remote ledger") + assert.Equal(t, ledger.Value([]byte{}), localValues[0]) + assert.Equal(t, 0, len(localValues[0])) + }) + + t.Run("Set", func(t *testing.T) { + localInitialState := localLedger.InitialState() + remoteInitialState := remoteLedger.InitialState() + assert.Equal(t, localInitialState, remoteInitialState) + + // Create test keys and values + keys := []ledger.Key{ + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key-non-empty")), + }), + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner-1")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key-empty-slice")), + }), + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner-2")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key-nil")), + }), + } + values := []ledger.Value{ + ledger.Value("test-value"), + ledger.Value([]byte{}), + ledger.Value(nil), + } + + localUpdate, err := ledger.NewUpdate(localInitialState, keys, values) + require.NoError(t, err) + remoteUpdate, err := ledger.NewUpdate(remoteInitialState, keys, values) + require.NoError(t, err) + + localNewState, localTrieUpdate, err := localLedger.Set(localUpdate) + require.NoError(t, err) + remoteNewState, remoteTrieUpdate, err := remoteLedger.Set(remoteUpdate) + require.NoError(t, err) + + // Both should return the same new state + assert.Equal(t, localNewState, remoteNewState, "Set should return the same new state for local and remote ledger") + assert.NotEqual(t, ledger.DummyState, localNewState) + assert.NotEqual(t, localInitialState, localNewState) + + // Both should return non-nil trie updates + assert.NotNil(t, localTrieUpdate) + assert.NotNil(t, remoteTrieUpdate) + + // Verify that both trie updates produce identical CBOR encodings + // This ensures that nil vs empty slice distinction is preserved correctly + // through the remote ledger's protobuf encoding/decoding cycle + localTrieUpdateCBOR := ledger.EncodeTrieUpdateCBOR(localTrieUpdate) + remoteTrieUpdateCBOR := ledger.EncodeTrieUpdateCBOR(remoteTrieUpdate) + assert.Equal(t, localTrieUpdateCBOR, remoteTrieUpdateCBOR, + "Trie updates must produce identical CBOR encodings. "+ + "Local CBOR length: %d, Remote CBOR length: %d", + len(localTrieUpdateCBOR), len(remoteTrieUpdateCBOR)) + + // Verify we can read back the value from both + localQuery, err := ledger.NewQuerySingleValue(localNewState, keys[0]) + require.NoError(t, err) + remoteQuery, err := ledger.NewQuerySingleValue(remoteNewState, keys[0]) + require.NoError(t, err) + + localValue, err := localLedger.GetSingleValue(localQuery) + require.NoError(t, err) + remoteValue, err := remoteLedger.GetSingleValue(remoteQuery) + require.NoError(t, err) + + // Both should return the same value + assert.Equal(t, localValue, remoteValue, "GetSingleValue after Set should return the same value") + assert.Equal(t, ledger.Value("test-value"), localValue) + }) + + t.Run("Prove", func(t *testing.T) { + localInitialState := localLedger.InitialState() + remoteInitialState := remoteLedger.InitialState() + assert.Equal(t, localInitialState, remoteInitialState) + + // Create test key + key := ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key")), + }) + + localQuery, err := ledger.NewQuery(localInitialState, []ledger.Key{key}) + require.NoError(t, err) + remoteQuery, err := ledger.NewQuery(remoteInitialState, []ledger.Key{key}) + require.NoError(t, err) + + localProof, err := localLedger.Prove(localQuery) + require.NoError(t, err) + remoteProof, err := remoteLedger.Prove(remoteQuery) + require.NoError(t, err) + + // Both should return proofs of the same length + assert.NotNil(t, localProof) + assert.NotNil(t, remoteProof) + assert.Equal(t, len(localProof), len(remoteProof), "Prove should return proofs of the same length") + assert.Greater(t, len(localProof), 0) + }) + }) +} + +// TestTrieUpdatePayloadValueEquivalence verifies that trie updates with three different +// payload value representations (non-empty, empty slice, nil) produce the same result ID +// for both remote ledger and local ledger. +// +// This test ensures that: +// 1. State commitments match between local and remote ledgers for all three value types +// 2. Execution data IDs are identical across all three scenarios +// 3. The nil vs empty slice distinction is properly preserved through protobuf encoding +func TestTrieUpdatePayloadValueEquivalence(t *testing.T) { + withLedgerPair(t, func(localLedger, remoteLedger ledger.Ledger) { + + // Get initial state (should be the same for both) + localInitialState := localLedger.InitialState() + remoteInitialState := remoteLedger.InitialState() + require.Equal(t, localInitialState, remoteInitialState, "Initial states must match") + + // Create three test keys for the three different payload value types + keys := []ledger.Key{ + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key-non-empty")), + }), + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key-empty-slice")), + }), + ledger.NewKey([]ledger.KeyPart{ + ledger.NewKeyPart(ledger.KeyPartOwner, []byte("test-owner")), + ledger.NewKeyPart(ledger.KeyPartKey, []byte("test-key-nil")), + }), + } + + // Create a single update with three different payload value representations: + // 1. Non-empty payload value + // 2. Empty slice payload value + // 3. Nil payload value + values := []ledger.Value{ + ledger.Value([]byte{1, 2, 3}), // non-empty + ledger.Value([]byte{}), // empty slice + ledger.Value(nil), // nil + } + + t.Logf("Creating single trie update with three payloads: non-empty, empty slice, and nil") + + // Create updates for both ledgers with all three values in a single update + localUpdate, err := ledger.NewUpdate(localInitialState, keys, values) + require.NoError(t, err, "Failed to create local update") + + remoteUpdate, err := ledger.NewUpdate(remoteInitialState, keys, values) + require.NoError(t, err, "Failed to create remote update") + + // Apply the single update to both ledgers + localNewState, localTrieUpdate, err := localLedger.Set(localUpdate) + require.NoError(t, err, "Failed to apply local update") + + remoteNewState, remoteTrieUpdate, err := remoteLedger.Set(remoteUpdate) + require.NoError(t, err, "Failed to apply remote update") + + // Verify state commitments match + assert.Equal(t, localNewState, remoteNewState, + "State commitments must match between local and remote ledger") + assert.NotEqual(t, ledger.DummyState, localNewState, + "State should not be dummy state") + + // Verify trie updates are not nil + require.NotNil(t, localTrieUpdate, "Local trie update should not be nil") + require.NotNil(t, remoteTrieUpdate, "Remote trie update should not be nil") + + // Verify both trie updates have the same number of payloads + require.Equal(t, len(localTrieUpdate.Payloads), len(remoteTrieUpdate.Payloads), + "Local and remote trie updates should have the same number of payloads") + require.Equal(t, 3, len(localTrieUpdate.Payloads), + "Trie update should contain exactly 3 payloads") + + t.Logf("Trie update contains %d payloads", len(localTrieUpdate.Payloads)) + t.Logf("Payload 0 (non-empty) value length: %d", len(localTrieUpdate.Payloads[0].Value())) + t.Logf("Payload 1 (empty slice) value length: %d, is nil: %v", len(localTrieUpdate.Payloads[1].Value()), localTrieUpdate.Payloads[1].Value() == nil) + t.Logf("Payload 2 (nil) value length: %d, is nil: %v", len(localTrieUpdate.Payloads[2].Value()), localTrieUpdate.Payloads[2].Value() == nil) + + // Create ChunkExecutionData from the local trie update + collection := unittest.CollectionFixture(1) + localChunkExecutionData := &execution_data.ChunkExecutionData{ + Collection: &collection, + Events: flow.EventsList{}, + TrieUpdate: localTrieUpdate, + TransactionResults: []flow.LightTransactionResult{}, + } + + // Create ChunkExecutionData from the remote trie update + remoteChunkExecutionData := &execution_data.ChunkExecutionData{ + Collection: &collection, + Events: flow.EventsList{}, + TrieUpdate: remoteTrieUpdate, + TransactionResults: []flow.LightTransactionResult{}, + } + + // Create BlockExecutionData for both + blockID := unittest.IdentifierFixture() + localBlockExecutionData := &execution_data.BlockExecutionData{ + BlockID: blockID, + ChunkExecutionDatas: []*execution_data.ChunkExecutionData{localChunkExecutionData}, + } + + remoteBlockExecutionData := &execution_data.BlockExecutionData{ + BlockID: blockID, + ChunkExecutionDatas: []*execution_data.ChunkExecutionData{remoteChunkExecutionData}, + } + + // Calculate execution data IDs using the default serializer + serializer := execution_data.DefaultSerializer + ctx := context.Background() + + localExecutionDataID, err := execution_data.CalculateID(ctx, localBlockExecutionData, serializer) + require.NoError(t, err, "Failed to calculate local execution data ID") + + remoteExecutionDataID, err := execution_data.CalculateID(ctx, remoteBlockExecutionData, serializer) + require.NoError(t, err, "Failed to calculate remote execution data ID") + + // The key assertion: local and remote execution data IDs must match + // This verifies that the remote ledger properly preserves the nil vs empty slice + // distinction through protobuf encoding, ensuring deterministic CBOR serialization + assert.Equal(t, localExecutionDataID, remoteExecutionDataID, + "Execution data IDs must match between local and remote ledger. "+ + "Local ID: %s, Remote ID: %s", + localExecutionDataID, remoteExecutionDataID) + + t.Logf("Test completed successfully.") + t.Logf("State commitment: %s", localNewState) + t.Logf("Execution data ID (local and remote match): %s", localExecutionDataID) + }) +} + +// startLedgerServer starts a ledger server on a random port and returns the address and cleanup function. +func startLedgerServer(t *testing.T, walDir string) (string, func()) { + // Find an available port + listener, err := net.Listen("tcp", ":0") + require.NoError(t, err) + addr := listener.Addr().String() + listener.Close() + + logger := unittest.Logger() + + // Create WAL + metricsCollector := &metrics.NoopCollector{} + diskWal, err := wal.NewDiskWAL( + logger, + nil, + metricsCollector, + walDir, + 100, + pathfinder.PathByteSize, + wal.SegmentSize, + ) + require.NoError(t, err) + + // Create compactor config + compactorConfig := ledger.DefaultCompactorConfig(metricsCollector) + + // Create ledger factory + factory := complete.NewLocalLedgerFactory( + diskWal, + 100, + compactorConfig, + atomic.NewBool(false), // trigger checkpoint signal + metricsCollector, + logger, + complete.DefaultPathFinderVersion, + ) + + // Create ledger instance + ledgerStorage, err := factory.NewLedger() + require.NoError(t, err) + + // Wait for ledger to be ready (WAL replay) + <-ledgerStorage.Ready() + + // Create gRPC server with max message size configuration + // Use large limits to match production defaults (1 GiB for both) + grpcServer := grpc.NewServer( + grpc.MaxRecvMsgSize(1<<30), // 1 GiB for requests + grpc.MaxSendMsgSize(1<<30), // 1 GiB for responses + ) + + // Create and register ledger service + ledgerService := remote.NewService(ledgerStorage, logger) + ledgerpb.RegisterLedgerServiceServer(grpcServer, ledgerService) + + // Start gRPC server + lis, err := net.Listen("tcp", addr) + require.NoError(t, err) + + // Start server in goroutine + serverErr := make(chan error, 1) + go func() { + if err := grpcServer.Serve(lis); err != nil { + serverErr <- fmt.Errorf("gRPC server error: %w", err) + } + }() + + // Wait a bit for server to start + time.Sleep(100 * time.Millisecond) + + // Cleanup function + cleanup := func() { + grpcServer.GracefulStop() + <-ledgerStorage.Done() + } + + return addr, cleanup +} + +// withLedgerPair creates both a local and remote ledger instance, handles Ready/Done, +// and automatically cleans up resources after the test function completes. +// The temp directory is automatically cleaned up by t.TempDir(). +func withLedgerPair(t *testing.T, fn func(localLedger, remoteLedger ledger.Ledger)) { + // Create temporary directories for WALs + tempDir := t.TempDir() + remoteWalDir := filepath.Join(tempDir, "remote_wal") + localWalDir := filepath.Join(tempDir, "local_wal") + + err := os.MkdirAll(remoteWalDir, 0755) + require.NoError(t, err) + err = os.MkdirAll(localWalDir, 0755) + require.NoError(t, err) + + // Start ledger server + serverAddr, serverCleanup := startLedgerServer(t, remoteWalDir) + + logger := zerolog.Nop() + metricsCollector := &metrics.NoopCollector{} + + // Create local ledger using factory + localLedger, err := NewLedger(Config{ + Triedir: localWalDir, + MTrieCacheSize: 100, + CheckpointDistance: 1000, + CheckpointsToKeep: 10, + MetricsRegisterer: nil, + WALMetrics: metricsCollector, + LedgerMetrics: metricsCollector, + Logger: logger, + }, atomic.NewBool(false)) + require.NoError(t, err) + require.NotNil(t, localLedger) + + // Create remote client using factory + remoteLedger, err := NewLedger(Config{ + LedgerServiceAddr: serverAddr, + Logger: logger, + }, nil) + require.NoError(t, err) + require.NotNil(t, remoteLedger) + + // Wait for both to be ready + <-localLedger.Ready() + <-remoteLedger.Ready() + + // Ensure cleanup happens even if the test function panics + defer func() { + // Stop remote ledger + <-remoteLedger.Done() + + // Stop local ledger (WAL cleanup is handled internally by the ledger) + <-localLedger.Done() + + // Stop server + serverCleanup() + }() + + // Execute the test function with the ledgers + fn(localLedger, remoteLedger) +} diff --git a/ledger/ledger.go b/ledger/ledger.go index 3e5b8c2a906..c7255648b31 100644 --- a/ledger/ledger.go +++ b/ledger/ledger.go @@ -39,6 +39,13 @@ type Ledger interface { // Prove returns proofs for the given keys at specific state Prove(query *Query) (proof Proof, err error) + + // StateCount returns the count + StateCount() int + + // StateByIndex returns the state at the given index + // -1 is the last index + StateByIndex(index int) (State, error) } // Query holds all data needed for a ledger read or ledger proof diff --git a/ledger/ledger_test.go b/ledger/ledger_test.go index 69dfedad9c4..76bc7920be9 100644 --- a/ledger/ledger_test.go +++ b/ledger/ledger_test.go @@ -18,7 +18,7 @@ func BenchmarkCanonicalForm(b *testing.B) { keyParts := make([]KeyPart, 0, 200) - for i := 0; i < 16; i++ { + for i := range 16 { keyParts = append(keyParts, KeyPart{}) keyParts[i].Value = []byte("somedomain1") keyParts[i].Type = 1234 @@ -44,7 +44,7 @@ func BenchmarkCanonicalForm(b *testing.B) { func BenchmarkOriginalCanonicalForm(b *testing.B) { keyParts := make([]KeyPart, 0, 200) - for i := 0; i < 16; i++ { + for i := range 16 { keyParts = append(keyParts, KeyPart{}) keyParts[i].Value = []byte("somedomain1") keyParts[i].Type = 1234 diff --git a/ledger/mock/factory.go b/ledger/mock/factory.go new file mode 100644 index 00000000000..4c26a640169 --- /dev/null +++ b/ledger/mock/factory.go @@ -0,0 +1,92 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/ledger" + mock "github.com/stretchr/testify/mock" +) + +// NewFactory creates a new instance of Factory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *Factory { + mock := &Factory{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// Factory is an autogenerated mock type for the Factory type +type Factory struct { + mock.Mock +} + +type Factory_Expecter struct { + mock *mock.Mock +} + +func (_m *Factory) EXPECT() *Factory_Expecter { + return &Factory_Expecter{mock: &_m.Mock} +} + +// NewLedger provides a mock function for the type Factory +func (_mock *Factory) NewLedger() (ledger.Ledger, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for NewLedger") + } + + var r0 ledger.Ledger + var r1 error + if returnFunc, ok := ret.Get(0).(func() (ledger.Ledger, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() ledger.Ledger); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(ledger.Ledger) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Factory_NewLedger_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewLedger' +type Factory_NewLedger_Call struct { + *mock.Call +} + +// NewLedger is a helper method to define mock.On call +func (_e *Factory_Expecter) NewLedger() *Factory_NewLedger_Call { + return &Factory_NewLedger_Call{Call: _e.mock.On("NewLedger")} +} + +func (_c *Factory_NewLedger_Call) Run(run func()) *Factory_NewLedger_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Factory_NewLedger_Call) Return(ledger1 ledger.Ledger, err error) *Factory_NewLedger_Call { + _c.Call.Return(ledger1, err) + return _c +} + +func (_c *Factory_NewLedger_Call) RunAndReturn(run func() (ledger.Ledger, error)) *Factory_NewLedger_Call { + _c.Call.Return(run) + return _c +} diff --git a/ledger/mock/ledger.go b/ledger/mock/ledger.go index 82a9de94e63..8bad7e84dcd 100644 --- a/ledger/mock/ledger.go +++ b/ledger/mock/ledger.go @@ -1,40 +1,90 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - ledger "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger" mock "github.com/stretchr/testify/mock" ) +// NewLedger creates a new instance of Ledger. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLedger(t interface { + mock.TestingT + Cleanup(func()) +}) *Ledger { + mock := &Ledger{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Ledger is an autogenerated mock type for the Ledger type type Ledger struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *Ledger) Done() <-chan struct{} { - ret := _m.Called() +type Ledger_Expecter struct { + mock *mock.Mock +} + +func (_m *Ledger) EXPECT() *Ledger_Expecter { + return &Ledger_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type Ledger +func (_mock *Ledger) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Get provides a mock function with given fields: query -func (_m *Ledger) Get(query *ledger.Query) ([]ledger.Value, error) { - ret := _m.Called(query) +// Ledger_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Ledger_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Ledger_Expecter) Done() *Ledger_Done_Call { + return &Ledger_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Ledger_Done_Call) Run(run func()) *Ledger_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Ledger_Done_Call) Return(valCh <-chan struct{}) *Ledger_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Ledger_Done_Call) RunAndReturn(run func() <-chan struct{}) *Ledger_Done_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type Ledger +func (_mock *Ledger) Get(query *ledger.Query) ([]ledger.Value, error) { + ret := _mock.Called(query) if len(ret) == 0 { panic("no return value specified for Get") @@ -42,29 +92,61 @@ func (_m *Ledger) Get(query *ledger.Query) ([]ledger.Value, error) { var r0 []ledger.Value var r1 error - if rf, ok := ret.Get(0).(func(*ledger.Query) ([]ledger.Value, error)); ok { - return rf(query) + if returnFunc, ok := ret.Get(0).(func(*ledger.Query) ([]ledger.Value, error)); ok { + return returnFunc(query) } - if rf, ok := ret.Get(0).(func(*ledger.Query) []ledger.Value); ok { - r0 = rf(query) + if returnFunc, ok := ret.Get(0).(func(*ledger.Query) []ledger.Value); ok { + r0 = returnFunc(query) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]ledger.Value) } } - - if rf, ok := ret.Get(1).(func(*ledger.Query) error); ok { - r1 = rf(query) + if returnFunc, ok := ret.Get(1).(func(*ledger.Query) error); ok { + r1 = returnFunc(query) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetSingleValue provides a mock function with given fields: query -func (_m *Ledger) GetSingleValue(query *ledger.QuerySingleValue) (ledger.Value, error) { - ret := _m.Called(query) +// Ledger_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Ledger_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - query *ledger.Query +func (_e *Ledger_Expecter) Get(query interface{}) *Ledger_Get_Call { + return &Ledger_Get_Call{Call: _e.mock.On("Get", query)} +} + +func (_c *Ledger_Get_Call) Run(run func(query *ledger.Query)) *Ledger_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *ledger.Query + if args[0] != nil { + arg0 = args[0].(*ledger.Query) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Ledger_Get_Call) Return(values []ledger.Value, err error) *Ledger_Get_Call { + _c.Call.Return(values, err) + return _c +} + +func (_c *Ledger_Get_Call) RunAndReturn(run func(query *ledger.Query) ([]ledger.Value, error)) *Ledger_Get_Call { + _c.Call.Return(run) + return _c +} + +// GetSingleValue provides a mock function for the type Ledger +func (_mock *Ledger) GetSingleValue(query *ledger.QuerySingleValue) (ledger.Value, error) { + ret := _mock.Called(query) if len(ret) == 0 { panic("no return value specified for GetSingleValue") @@ -72,67 +154,158 @@ func (_m *Ledger) GetSingleValue(query *ledger.QuerySingleValue) (ledger.Value, var r0 ledger.Value var r1 error - if rf, ok := ret.Get(0).(func(*ledger.QuerySingleValue) (ledger.Value, error)); ok { - return rf(query) + if returnFunc, ok := ret.Get(0).(func(*ledger.QuerySingleValue) (ledger.Value, error)); ok { + return returnFunc(query) } - if rf, ok := ret.Get(0).(func(*ledger.QuerySingleValue) ledger.Value); ok { - r0 = rf(query) + if returnFunc, ok := ret.Get(0).(func(*ledger.QuerySingleValue) ledger.Value); ok { + r0 = returnFunc(query) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(ledger.Value) } } - - if rf, ok := ret.Get(1).(func(*ledger.QuerySingleValue) error); ok { - r1 = rf(query) + if returnFunc, ok := ret.Get(1).(func(*ledger.QuerySingleValue) error); ok { + r1 = returnFunc(query) } else { r1 = ret.Error(1) } - return r0, r1 } -// HasState provides a mock function with given fields: state -func (_m *Ledger) HasState(state ledger.State) bool { - ret := _m.Called(state) +// Ledger_GetSingleValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSingleValue' +type Ledger_GetSingleValue_Call struct { + *mock.Call +} + +// GetSingleValue is a helper method to define mock.On call +// - query *ledger.QuerySingleValue +func (_e *Ledger_Expecter) GetSingleValue(query interface{}) *Ledger_GetSingleValue_Call { + return &Ledger_GetSingleValue_Call{Call: _e.mock.On("GetSingleValue", query)} +} + +func (_c *Ledger_GetSingleValue_Call) Run(run func(query *ledger.QuerySingleValue)) *Ledger_GetSingleValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *ledger.QuerySingleValue + if args[0] != nil { + arg0 = args[0].(*ledger.QuerySingleValue) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Ledger_GetSingleValue_Call) Return(value ledger.Value, err error) *Ledger_GetSingleValue_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *Ledger_GetSingleValue_Call) RunAndReturn(run func(query *ledger.QuerySingleValue) (ledger.Value, error)) *Ledger_GetSingleValue_Call { + _c.Call.Return(run) + return _c +} + +// HasState provides a mock function for the type Ledger +func (_mock *Ledger) HasState(state ledger.State) bool { + ret := _mock.Called(state) if len(ret) == 0 { panic("no return value specified for HasState") } var r0 bool - if rf, ok := ret.Get(0).(func(ledger.State) bool); ok { - r0 = rf(state) + if returnFunc, ok := ret.Get(0).(func(ledger.State) bool); ok { + r0 = returnFunc(state) } else { r0 = ret.Get(0).(bool) } - return r0 } -// InitialState provides a mock function with no fields -func (_m *Ledger) InitialState() ledger.State { - ret := _m.Called() +// Ledger_HasState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasState' +type Ledger_HasState_Call struct { + *mock.Call +} + +// HasState is a helper method to define mock.On call +// - state ledger.State +func (_e *Ledger_Expecter) HasState(state interface{}) *Ledger_HasState_Call { + return &Ledger_HasState_Call{Call: _e.mock.On("HasState", state)} +} + +func (_c *Ledger_HasState_Call) Run(run func(state ledger.State)) *Ledger_HasState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 ledger.State + if args[0] != nil { + arg0 = args[0].(ledger.State) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Ledger_HasState_Call) Return(b bool) *Ledger_HasState_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Ledger_HasState_Call) RunAndReturn(run func(state ledger.State) bool) *Ledger_HasState_Call { + _c.Call.Return(run) + return _c +} + +// InitialState provides a mock function for the type Ledger +func (_mock *Ledger) InitialState() ledger.State { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for InitialState") } var r0 ledger.State - if rf, ok := ret.Get(0).(func() ledger.State); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() ledger.State); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(ledger.State) } } - return r0 } -// Prove provides a mock function with given fields: query -func (_m *Ledger) Prove(query *ledger.Query) (ledger.Proof, error) { - ret := _m.Called(query) +// Ledger_InitialState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InitialState' +type Ledger_InitialState_Call struct { + *mock.Call +} + +// InitialState is a helper method to define mock.On call +func (_e *Ledger_Expecter) InitialState() *Ledger_InitialState_Call { + return &Ledger_InitialState_Call{Call: _e.mock.On("InitialState")} +} + +func (_c *Ledger_InitialState_Call) Run(run func()) *Ledger_InitialState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Ledger_InitialState_Call) Return(state ledger.State) *Ledger_InitialState_Call { + _c.Call.Return(state) + return _c +} + +func (_c *Ledger_InitialState_Call) RunAndReturn(run func() ledger.State) *Ledger_InitialState_Call { + _c.Call.Return(run) + return _c +} + +// Prove provides a mock function for the type Ledger +func (_mock *Ledger) Prove(query *ledger.Query) (ledger.Proof, error) { + ret := _mock.Called(query) if len(ret) == 0 { panic("no return value specified for Prove") @@ -140,49 +313,107 @@ func (_m *Ledger) Prove(query *ledger.Query) (ledger.Proof, error) { var r0 ledger.Proof var r1 error - if rf, ok := ret.Get(0).(func(*ledger.Query) (ledger.Proof, error)); ok { - return rf(query) + if returnFunc, ok := ret.Get(0).(func(*ledger.Query) (ledger.Proof, error)); ok { + return returnFunc(query) } - if rf, ok := ret.Get(0).(func(*ledger.Query) ledger.Proof); ok { - r0 = rf(query) + if returnFunc, ok := ret.Get(0).(func(*ledger.Query) ledger.Proof); ok { + r0 = returnFunc(query) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(ledger.Proof) } } - - if rf, ok := ret.Get(1).(func(*ledger.Query) error); ok { - r1 = rf(query) + if returnFunc, ok := ret.Get(1).(func(*ledger.Query) error); ok { + r1 = returnFunc(query) } else { r1 = ret.Error(1) } - return r0, r1 } -// Ready provides a mock function with no fields -func (_m *Ledger) Ready() <-chan struct{} { - ret := _m.Called() +// Ledger_Prove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Prove' +type Ledger_Prove_Call struct { + *mock.Call +} + +// Prove is a helper method to define mock.On call +// - query *ledger.Query +func (_e *Ledger_Expecter) Prove(query interface{}) *Ledger_Prove_Call { + return &Ledger_Prove_Call{Call: _e.mock.On("Prove", query)} +} + +func (_c *Ledger_Prove_Call) Run(run func(query *ledger.Query)) *Ledger_Prove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *ledger.Query + if args[0] != nil { + arg0 = args[0].(*ledger.Query) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Ledger_Prove_Call) Return(proof ledger.Proof, err error) *Ledger_Prove_Call { + _c.Call.Return(proof, err) + return _c +} + +func (_c *Ledger_Prove_Call) RunAndReturn(run func(query *ledger.Query) (ledger.Proof, error)) *Ledger_Prove_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type Ledger +func (_mock *Ledger) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Set provides a mock function with given fields: update -func (_m *Ledger) Set(update *ledger.Update) (ledger.State, *ledger.TrieUpdate, error) { - ret := _m.Called(update) +// Ledger_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Ledger_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *Ledger_Expecter) Ready() *Ledger_Ready_Call { + return &Ledger_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *Ledger_Ready_Call) Run(run func()) *Ledger_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Ledger_Ready_Call) Return(valCh <-chan struct{}) *Ledger_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Ledger_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Ledger_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Set provides a mock function for the type Ledger +func (_mock *Ledger) Set(update *ledger.Update) (ledger.State, *ledger.TrieUpdate, error) { + ret := _mock.Called(update) if len(ret) == 0 { panic("no return value specified for Set") @@ -191,44 +422,167 @@ func (_m *Ledger) Set(update *ledger.Update) (ledger.State, *ledger.TrieUpdate, var r0 ledger.State var r1 *ledger.TrieUpdate var r2 error - if rf, ok := ret.Get(0).(func(*ledger.Update) (ledger.State, *ledger.TrieUpdate, error)); ok { - return rf(update) + if returnFunc, ok := ret.Get(0).(func(*ledger.Update) (ledger.State, *ledger.TrieUpdate, error)); ok { + return returnFunc(update) } - if rf, ok := ret.Get(0).(func(*ledger.Update) ledger.State); ok { - r0 = rf(update) + if returnFunc, ok := ret.Get(0).(func(*ledger.Update) ledger.State); ok { + r0 = returnFunc(update) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(ledger.State) } } - - if rf, ok := ret.Get(1).(func(*ledger.Update) *ledger.TrieUpdate); ok { - r1 = rf(update) + if returnFunc, ok := ret.Get(1).(func(*ledger.Update) *ledger.TrieUpdate); ok { + r1 = returnFunc(update) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*ledger.TrieUpdate) } } - - if rf, ok := ret.Get(2).(func(*ledger.Update) error); ok { - r2 = rf(update) + if returnFunc, ok := ret.Get(2).(func(*ledger.Update) error); ok { + r2 = returnFunc(update) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewLedger creates a new instance of Ledger. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLedger(t interface { - mock.TestingT - Cleanup(func()) -}) *Ledger { - mock := &Ledger{} - mock.Mock.Test(t) +// Ledger_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set' +type Ledger_Set_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Set is a helper method to define mock.On call +// - update *ledger.Update +func (_e *Ledger_Expecter) Set(update interface{}) *Ledger_Set_Call { + return &Ledger_Set_Call{Call: _e.mock.On("Set", update)} +} - return mock +func (_c *Ledger_Set_Call) Run(run func(update *ledger.Update)) *Ledger_Set_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *ledger.Update + if args[0] != nil { + arg0 = args[0].(*ledger.Update) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Ledger_Set_Call) Return(newState ledger.State, trieUpdate *ledger.TrieUpdate, err error) *Ledger_Set_Call { + _c.Call.Return(newState, trieUpdate, err) + return _c +} + +func (_c *Ledger_Set_Call) RunAndReturn(run func(update *ledger.Update) (ledger.State, *ledger.TrieUpdate, error)) *Ledger_Set_Call { + _c.Call.Return(run) + return _c +} + +// StateByIndex provides a mock function for the type Ledger +func (_mock *Ledger) StateByIndex(index int) (ledger.State, error) { + ret := _mock.Called(index) + + if len(ret) == 0 { + panic("no return value specified for StateByIndex") + } + + var r0 ledger.State + var r1 error + if returnFunc, ok := ret.Get(0).(func(int) (ledger.State, error)); ok { + return returnFunc(index) + } + if returnFunc, ok := ret.Get(0).(func(int) ledger.State); ok { + r0 = returnFunc(index) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(ledger.State) + } + } + if returnFunc, ok := ret.Get(1).(func(int) error); ok { + r1 = returnFunc(index) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Ledger_StateByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StateByIndex' +type Ledger_StateByIndex_Call struct { + *mock.Call +} + +// StateByIndex is a helper method to define mock.On call +// - index int +func (_e *Ledger_Expecter) StateByIndex(index interface{}) *Ledger_StateByIndex_Call { + return &Ledger_StateByIndex_Call{Call: _e.mock.On("StateByIndex", index)} +} + +func (_c *Ledger_StateByIndex_Call) Run(run func(index int)) *Ledger_StateByIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Ledger_StateByIndex_Call) Return(state ledger.State, err error) *Ledger_StateByIndex_Call { + _c.Call.Return(state, err) + return _c +} + +func (_c *Ledger_StateByIndex_Call) RunAndReturn(run func(index int) (ledger.State, error)) *Ledger_StateByIndex_Call { + _c.Call.Return(run) + return _c +} + +// StateCount provides a mock function for the type Ledger +func (_mock *Ledger) StateCount() int { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for StateCount") + } + + var r0 int + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(int) + } + return r0 +} + +// Ledger_StateCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StateCount' +type Ledger_StateCount_Call struct { + *mock.Call +} + +// StateCount is a helper method to define mock.On call +func (_e *Ledger_Expecter) StateCount() *Ledger_StateCount_Call { + return &Ledger_StateCount_Call{Call: _e.mock.On("StateCount")} +} + +func (_c *Ledger_StateCount_Call) Run(run func()) *Ledger_StateCount_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Ledger_StateCount_Call) Return(n int) *Ledger_StateCount_Call { + _c.Call.Return(n) + return _c +} + +func (_c *Ledger_StateCount_Call) RunAndReturn(run func() int) *Ledger_StateCount_Call { + _c.Call.Return(run) + return _c } diff --git a/ledger/mock/reporter.go b/ledger/mock/reporter.go index fdd5e3e8a0b..0a034b4b357 100644 --- a/ledger/mock/reporter.go +++ b/ledger/mock/reporter.go @@ -1,63 +1,138 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - ledger "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/ledger" mock "github.com/stretchr/testify/mock" ) +// NewReporter creates a new instance of Reporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReporter(t interface { + mock.TestingT + Cleanup(func()) +}) *Reporter { + mock := &Reporter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Reporter is an autogenerated mock type for the Reporter type type Reporter struct { mock.Mock } -// Name provides a mock function with no fields -func (_m *Reporter) Name() string { - ret := _m.Called() +type Reporter_Expecter struct { + mock *mock.Mock +} + +func (_m *Reporter) EXPECT() *Reporter_Expecter { + return &Reporter_Expecter{mock: &_m.Mock} +} + +// Name provides a mock function for the type Reporter +func (_mock *Reporter) Name() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Name") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// Report provides a mock function with given fields: payloads, statecommitment -func (_m *Reporter) Report(payloads []ledger.Payload, statecommitment ledger.State) error { - ret := _m.Called(payloads, statecommitment) +// Reporter_Name_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Name' +type Reporter_Name_Call struct { + *mock.Call +} + +// Name is a helper method to define mock.On call +func (_e *Reporter_Expecter) Name() *Reporter_Name_Call { + return &Reporter_Name_Call{Call: _e.mock.On("Name")} +} + +func (_c *Reporter_Name_Call) Run(run func()) *Reporter_Name_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Reporter_Name_Call) Return(s string) *Reporter_Name_Call { + _c.Call.Return(s) + return _c +} + +func (_c *Reporter_Name_Call) RunAndReturn(run func() string) *Reporter_Name_Call { + _c.Call.Return(run) + return _c +} + +// Report provides a mock function for the type Reporter +func (_mock *Reporter) Report(payloads []ledger.Payload, statecommitment ledger.State) error { + ret := _mock.Called(payloads, statecommitment) if len(ret) == 0 { panic("no return value specified for Report") } var r0 error - if rf, ok := ret.Get(0).(func([]ledger.Payload, ledger.State) error); ok { - r0 = rf(payloads, statecommitment) + if returnFunc, ok := ret.Get(0).(func([]ledger.Payload, ledger.State) error); ok { + r0 = returnFunc(payloads, statecommitment) } else { r0 = ret.Error(0) } - return r0 } -// NewReporter creates a new instance of Reporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReporter(t interface { - mock.TestingT - Cleanup(func()) -}) *Reporter { - mock := &Reporter{} - mock.Mock.Test(t) +// Reporter_Report_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Report' +type Reporter_Report_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Report is a helper method to define mock.On call +// - payloads []ledger.Payload +// - statecommitment ledger.State +func (_e *Reporter_Expecter) Report(payloads interface{}, statecommitment interface{}) *Reporter_Report_Call { + return &Reporter_Report_Call{Call: _e.mock.On("Report", payloads, statecommitment)} +} - return mock +func (_c *Reporter_Report_Call) Run(run func(payloads []ledger.Payload, statecommitment ledger.State)) *Reporter_Report_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []ledger.Payload + if args[0] != nil { + arg0 = args[0].([]ledger.Payload) + } + var arg1 ledger.State + if args[1] != nil { + arg1 = args[1].(ledger.State) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Reporter_Report_Call) Return(err error) *Reporter_Report_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Reporter_Report_Call) RunAndReturn(run func(payloads []ledger.Payload, statecommitment ledger.State) error) *Reporter_Report_Call { + _c.Call.Return(run) + return _c } diff --git a/ledger/partial/ledger.go b/ledger/partial/ledger.go index 33b3d141935..a807556af5d 100644 --- a/ledger/partial/ledger.go +++ b/ledger/partial/ledger.go @@ -164,3 +164,18 @@ func (l *Ledger) Set(update *ledger.Update) (newState ledger.State, trieUpdate * func (l *Ledger) Prove(query *ledger.Query) (proof ledger.Proof, err error) { return nil, err } + +// StateCount returns the number of states in the partial ledger +// Partial ledger only has one state +func (l *Ledger) StateCount() int { + return 1 +} + +// StateByIndex returns the state at the given index +// Partial ledger only has one state +func (l *Ledger) StateByIndex(index int) (ledger.State, error) { + if index == 0 || index == -1 { + return l.state, nil + } + return ledger.DummyState, fmt.Errorf("index %d is out of range (partial ledger has 1 state)", index) +} diff --git a/ledger/partial/ledger_test.go b/ledger/partial/ledger_test.go index 209bf707ed0..dd51343918e 100644 --- a/ledger/partial/ledger_test.go +++ b/ledger/partial/ledger_test.go @@ -169,3 +169,89 @@ func TestEmptyLedger(t *testing.T) { require.True(t, trieUpdate.IsEmpty()) require.Equal(t, u.State(), newState) } + +func TestPartialLedger_StateCount(t *testing.T) { + w := &fixtures.NoopWAL{} + + l, err := complete.NewLedger(w, 100, &metrics.NoopCollector{}, zerolog.Logger{}, complete.DefaultPathFinderVersion) + require.NoError(t, err) + + compactor := fixtures.NewNoopCompactor(l) + <-compactor.Ready() + + defer func() { + <-l.Done() + <-compactor.Done() + }() + + // create update and get proof + state := l.InitialState() + keys := testutils.RandomUniqueKeys(2, 2, 2, 4) + values := testutils.RandomValues(2, 1, 32) + update, err := ledger.NewUpdate(state, keys, values) + require.NoError(t, err) + + newState, _, err := l.Set(update) + require.NoError(t, err) + + query, err := ledger.NewQuery(newState, keys) + require.NoError(t, err) + proof, err := l.Prove(query) + require.NoError(t, err) + + pled, err := partial.NewLedger(proof, newState, partial.DefaultPathFinderVersion) + require.NoError(t, err) + + // Partial ledger should always have exactly one state + stateCount := pled.StateCount() + assert.Equal(t, 1, stateCount, "partial ledger should have exactly one state") +} + +func TestPartialLedger_StateByIndex(t *testing.T) { + w := &fixtures.NoopWAL{} + + l, err := complete.NewLedger(w, 100, &metrics.NoopCollector{}, zerolog.Logger{}, complete.DefaultPathFinderVersion) + require.NoError(t, err) + + compactor := fixtures.NewNoopCompactor(l) + <-compactor.Ready() + + defer func() { + <-l.Done() + <-compactor.Done() + }() + + // create update and get proof + state := l.InitialState() + keys := testutils.RandomUniqueKeys(2, 2, 2, 4) + values := testutils.RandomValues(2, 1, 32) + update, err := ledger.NewUpdate(state, keys, values) + require.NoError(t, err) + + newState, _, err := l.Set(update) + require.NoError(t, err) + + query, err := ledger.NewQuery(newState, keys) + require.NoError(t, err) + proof, err := l.Prove(query) + require.NoError(t, err) + + pled, err := partial.NewLedger(proof, newState, partial.DefaultPathFinderVersion) + require.NoError(t, err) + + // Test getting state at index 0 (only valid index for partial ledger) + state0, err := pled.StateByIndex(0) + require.NoError(t, err) + assert.Equal(t, newState, state0, "state at index 0 should match the ledger state") + + // Test that other indices fail + _, err = pled.StateByIndex(1) + require.Error(t, err, "should error for index out of range") + + state_1, err := pled.StateByIndex(-1) + require.NoError(t, err) + assert.Equal(t, newState, state_1, "state at index -1 should match the ledger state") + + _, err = pled.StateByIndex(-2) + require.Error(t, err, "should error for negative index out of range") +} diff --git a/ledger/partial/ptrie/partialTrie_test.go b/ledger/partial/ptrie/partialTrie_test.go index 1f0a522323a..46405245398 100644 --- a/ledger/partial/ptrie/partialTrie_test.go +++ b/ledger/partial/ptrie/partialTrie_test.go @@ -370,7 +370,7 @@ func TestRandomProofs(t *testing.T) { minPayloadSize := 2 maxPayloadSize := 10 experimentRep := 20 - for e := 0; e < experimentRep; e++ { + for range experimentRep { withForest(t, pathByteSize, experimentRep+1, func(t *testing.T, f *mtrie.Forest) { // generate some random paths and payloads diff --git a/ledger/protobuf/buf.gen.yaml b/ledger/protobuf/buf.gen.yaml new file mode 100644 index 00000000000..05f96e382fd --- /dev/null +++ b/ledger/protobuf/buf.gen.yaml @@ -0,0 +1,11 @@ +version: v1beta1 +plugins: + - name: go + out: . + opt: + - paths=source_relative + - name: go-grpc + out: . + opt: + - paths=source_relative + diff --git a/ledger/protobuf/buf.yaml b/ledger/protobuf/buf.yaml new file mode 100644 index 00000000000..25204840201 --- /dev/null +++ b/ledger/protobuf/buf.yaml @@ -0,0 +1,8 @@ +version: v1 +breaking: + use: + - FILE +lint: + use: + - DEFAULT + diff --git a/ledger/protobuf/ledger.pb.go b/ledger/protobuf/ledger.pb.go new file mode 100644 index 00000000000..602d79a9ba9 --- /dev/null +++ b/ledger/protobuf/ledger.pb.go @@ -0,0 +1,753 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: ledger.proto + +package protobuf + +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + _ "google.golang.org/protobuf/types/known/emptypb" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package + +// State represents a ledger state (32-byte hash) +type State struct { + Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *State) Reset() { *m = State{} } +func (m *State) String() string { return proto.CompactTextString(m) } +func (*State) ProtoMessage() {} +func (*State) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{0} +} + +func (m *State) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_State.Unmarshal(m, b) +} +func (m *State) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_State.Marshal(b, m, deterministic) +} +func (m *State) XXX_Merge(src proto.Message) { + xxx_messageInfo_State.Merge(m, src) +} +func (m *State) XXX_Size() int { + return xxx_messageInfo_State.Size(m) +} +func (m *State) XXX_DiscardUnknown() { + xxx_messageInfo_State.DiscardUnknown(m) +} + +var xxx_messageInfo_State proto.InternalMessageInfo + +func (m *State) GetHash() []byte { + if m != nil { + return m.Hash + } + return nil +} + +// KeyPart represents a part of a hierarchical key +type KeyPart struct { + // type is actually uint16 but uint16 is not available in proto3 + Type uint32 `protobuf:"varint,1,opt,name=type,proto3" json:"type,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *KeyPart) Reset() { *m = KeyPart{} } +func (m *KeyPart) String() string { return proto.CompactTextString(m) } +func (*KeyPart) ProtoMessage() {} +func (*KeyPart) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{1} +} + +func (m *KeyPart) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_KeyPart.Unmarshal(m, b) +} +func (m *KeyPart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_KeyPart.Marshal(b, m, deterministic) +} +func (m *KeyPart) XXX_Merge(src proto.Message) { + xxx_messageInfo_KeyPart.Merge(m, src) +} +func (m *KeyPart) XXX_Size() int { + return xxx_messageInfo_KeyPart.Size(m) +} +func (m *KeyPart) XXX_DiscardUnknown() { + xxx_messageInfo_KeyPart.DiscardUnknown(m) +} + +var xxx_messageInfo_KeyPart proto.InternalMessageInfo + +func (m *KeyPart) GetType() uint32 { + if m != nil { + return m.Type + } + return 0 +} + +func (m *KeyPart) GetValue() []byte { + if m != nil { + return m.Value + } + return nil +} + +// Key represents a hierarchical ledger key +type Key struct { + Parts []*KeyPart `protobuf:"bytes,1,rep,name=parts,proto3" json:"parts,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Key) Reset() { *m = Key{} } +func (m *Key) String() string { return proto.CompactTextString(m) } +func (*Key) ProtoMessage() {} +func (*Key) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{2} +} + +func (m *Key) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Key.Unmarshal(m, b) +} +func (m *Key) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Key.Marshal(b, m, deterministic) +} +func (m *Key) XXX_Merge(src proto.Message) { + xxx_messageInfo_Key.Merge(m, src) +} +func (m *Key) XXX_Size() int { + return xxx_messageInfo_Key.Size(m) +} +func (m *Key) XXX_DiscardUnknown() { + xxx_messageInfo_Key.DiscardUnknown(m) +} + +var xxx_messageInfo_Key proto.InternalMessageInfo + +func (m *Key) GetParts() []*KeyPart { + if m != nil { + return m.Parts + } + return nil +} + +// Value represents a ledger value +type Value struct { + Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` + // is_nil distinguishes between nil and []byte{} (empty slice). + // When data is nil or empty: + // - is_nil=true means the original value was nil + // - is_nil=false means the original value was []byte{} (empty slice) + // + // When data is non-empty, is_nil is ignored (should be false). + IsNil bool `protobuf:"varint,2,opt,name=is_nil,json=isNil,proto3" json:"is_nil,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Value) Reset() { *m = Value{} } +func (m *Value) String() string { return proto.CompactTextString(m) } +func (*Value) ProtoMessage() {} +func (*Value) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{3} +} + +func (m *Value) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Value.Unmarshal(m, b) +} +func (m *Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Value.Marshal(b, m, deterministic) +} +func (m *Value) XXX_Merge(src proto.Message) { + xxx_messageInfo_Value.Merge(m, src) +} +func (m *Value) XXX_Size() int { + return xxx_messageInfo_Value.Size(m) +} +func (m *Value) XXX_DiscardUnknown() { + xxx_messageInfo_Value.DiscardUnknown(m) +} + +var xxx_messageInfo_Value proto.InternalMessageInfo + +func (m *Value) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (m *Value) GetIsNil() bool { + if m != nil { + return m.IsNil + } + return false +} + +// StateRequest contains a state to query +type StateRequest struct { + State *State `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StateRequest) Reset() { *m = StateRequest{} } +func (m *StateRequest) String() string { return proto.CompactTextString(m) } +func (*StateRequest) ProtoMessage() {} +func (*StateRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{4} +} + +func (m *StateRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StateRequest.Unmarshal(m, b) +} +func (m *StateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StateRequest.Marshal(b, m, deterministic) +} +func (m *StateRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_StateRequest.Merge(m, src) +} +func (m *StateRequest) XXX_Size() int { + return xxx_messageInfo_StateRequest.Size(m) +} +func (m *StateRequest) XXX_DiscardUnknown() { + xxx_messageInfo_StateRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_StateRequest proto.InternalMessageInfo + +func (m *StateRequest) GetState() *State { + if m != nil { + return m.State + } + return nil +} + +// StateResponse contains a state +type StateResponse struct { + State *State `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StateResponse) Reset() { *m = StateResponse{} } +func (m *StateResponse) String() string { return proto.CompactTextString(m) } +func (*StateResponse) ProtoMessage() {} +func (*StateResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{5} +} + +func (m *StateResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StateResponse.Unmarshal(m, b) +} +func (m *StateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StateResponse.Marshal(b, m, deterministic) +} +func (m *StateResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_StateResponse.Merge(m, src) +} +func (m *StateResponse) XXX_Size() int { + return xxx_messageInfo_StateResponse.Size(m) +} +func (m *StateResponse) XXX_DiscardUnknown() { + xxx_messageInfo_StateResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_StateResponse proto.InternalMessageInfo + +func (m *StateResponse) GetState() *State { + if m != nil { + return m.State + } + return nil +} + +// HasStateResponse indicates if a state exists +type HasStateResponse struct { + HasState bool `protobuf:"varint,1,opt,name=has_state,json=hasState,proto3" json:"has_state,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *HasStateResponse) Reset() { *m = HasStateResponse{} } +func (m *HasStateResponse) String() string { return proto.CompactTextString(m) } +func (*HasStateResponse) ProtoMessage() {} +func (*HasStateResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{6} +} + +func (m *HasStateResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_HasStateResponse.Unmarshal(m, b) +} +func (m *HasStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_HasStateResponse.Marshal(b, m, deterministic) +} +func (m *HasStateResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_HasStateResponse.Merge(m, src) +} +func (m *HasStateResponse) XXX_Size() int { + return xxx_messageInfo_HasStateResponse.Size(m) +} +func (m *HasStateResponse) XXX_DiscardUnknown() { + xxx_messageInfo_HasStateResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_HasStateResponse proto.InternalMessageInfo + +func (m *HasStateResponse) GetHasState() bool { + if m != nil { + return m.HasState + } + return false +} + +// GetSingleValueRequest contains a query for a single value +type GetSingleValueRequest struct { + State *State `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` + Key *Key `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetSingleValueRequest) Reset() { *m = GetSingleValueRequest{} } +func (m *GetSingleValueRequest) String() string { return proto.CompactTextString(m) } +func (*GetSingleValueRequest) ProtoMessage() {} +func (*GetSingleValueRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{7} +} + +func (m *GetSingleValueRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetSingleValueRequest.Unmarshal(m, b) +} +func (m *GetSingleValueRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetSingleValueRequest.Marshal(b, m, deterministic) +} +func (m *GetSingleValueRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetSingleValueRequest.Merge(m, src) +} +func (m *GetSingleValueRequest) XXX_Size() int { + return xxx_messageInfo_GetSingleValueRequest.Size(m) +} +func (m *GetSingleValueRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetSingleValueRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetSingleValueRequest proto.InternalMessageInfo + +func (m *GetSingleValueRequest) GetState() *State { + if m != nil { + return m.State + } + return nil +} + +func (m *GetSingleValueRequest) GetKey() *Key { + if m != nil { + return m.Key + } + return nil +} + +// ValueResponse contains a single value +type ValueResponse struct { + Value *Value `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ValueResponse) Reset() { *m = ValueResponse{} } +func (m *ValueResponse) String() string { return proto.CompactTextString(m) } +func (*ValueResponse) ProtoMessage() {} +func (*ValueResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{8} +} + +func (m *ValueResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ValueResponse.Unmarshal(m, b) +} +func (m *ValueResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ValueResponse.Marshal(b, m, deterministic) +} +func (m *ValueResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ValueResponse.Merge(m, src) +} +func (m *ValueResponse) XXX_Size() int { + return xxx_messageInfo_ValueResponse.Size(m) +} +func (m *ValueResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ValueResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ValueResponse proto.InternalMessageInfo + +func (m *ValueResponse) GetValue() *Value { + if m != nil { + return m.Value + } + return nil +} + +// GetRequest contains a query for multiple values +type GetRequest struct { + State *State `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` + Keys []*Key `protobuf:"bytes,2,rep,name=keys,proto3" json:"keys,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetRequest) Reset() { *m = GetRequest{} } +func (m *GetRequest) String() string { return proto.CompactTextString(m) } +func (*GetRequest) ProtoMessage() {} +func (*GetRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{9} +} + +func (m *GetRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetRequest.Unmarshal(m, b) +} +func (m *GetRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetRequest.Marshal(b, m, deterministic) +} +func (m *GetRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetRequest.Merge(m, src) +} +func (m *GetRequest) XXX_Size() int { + return xxx_messageInfo_GetRequest.Size(m) +} +func (m *GetRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetRequest proto.InternalMessageInfo + +func (m *GetRequest) GetState() *State { + if m != nil { + return m.State + } + return nil +} + +func (m *GetRequest) GetKeys() []*Key { + if m != nil { + return m.Keys + } + return nil +} + +// GetResponse contains multiple values +type GetResponse struct { + Values []*Value `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetResponse) Reset() { *m = GetResponse{} } +func (m *GetResponse) String() string { return proto.CompactTextString(m) } +func (*GetResponse) ProtoMessage() {} +func (*GetResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{10} +} + +func (m *GetResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetResponse.Unmarshal(m, b) +} +func (m *GetResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetResponse.Marshal(b, m, deterministic) +} +func (m *GetResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetResponse.Merge(m, src) +} +func (m *GetResponse) XXX_Size() int { + return xxx_messageInfo_GetResponse.Size(m) +} +func (m *GetResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetResponse proto.InternalMessageInfo + +func (m *GetResponse) GetValues() []*Value { + if m != nil { + return m.Values + } + return nil +} + +// SetRequest contains an update operation +type SetRequest struct { + State *State `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` + Keys []*Key `protobuf:"bytes,2,rep,name=keys,proto3" json:"keys,omitempty"` + Values []*Value `protobuf:"bytes,3,rep,name=values,proto3" json:"values,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SetRequest) Reset() { *m = SetRequest{} } +func (m *SetRequest) String() string { return proto.CompactTextString(m) } +func (*SetRequest) ProtoMessage() {} +func (*SetRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{11} +} + +func (m *SetRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SetRequest.Unmarshal(m, b) +} +func (m *SetRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SetRequest.Marshal(b, m, deterministic) +} +func (m *SetRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_SetRequest.Merge(m, src) +} +func (m *SetRequest) XXX_Size() int { + return xxx_messageInfo_SetRequest.Size(m) +} +func (m *SetRequest) XXX_DiscardUnknown() { + xxx_messageInfo_SetRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_SetRequest proto.InternalMessageInfo + +func (m *SetRequest) GetState() *State { + if m != nil { + return m.State + } + return nil +} + +func (m *SetRequest) GetKeys() []*Key { + if m != nil { + return m.Keys + } + return nil +} + +func (m *SetRequest) GetValues() []*Value { + if m != nil { + return m.Values + } + return nil +} + +// SetResponse contains the new state after an update +type SetResponse struct { + NewState *State `protobuf:"bytes,1,opt,name=new_state,json=newState,proto3" json:"new_state,omitempty"` + TrieUpdate []byte `protobuf:"bytes,2,opt,name=trie_update,json=trieUpdate,proto3" json:"trie_update,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SetResponse) Reset() { *m = SetResponse{} } +func (m *SetResponse) String() string { return proto.CompactTextString(m) } +func (*SetResponse) ProtoMessage() {} +func (*SetResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{12} +} + +func (m *SetResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SetResponse.Unmarshal(m, b) +} +func (m *SetResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SetResponse.Marshal(b, m, deterministic) +} +func (m *SetResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_SetResponse.Merge(m, src) +} +func (m *SetResponse) XXX_Size() int { + return xxx_messageInfo_SetResponse.Size(m) +} +func (m *SetResponse) XXX_DiscardUnknown() { + xxx_messageInfo_SetResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_SetResponse proto.InternalMessageInfo + +func (m *SetResponse) GetNewState() *State { + if m != nil { + return m.NewState + } + return nil +} + +func (m *SetResponse) GetTrieUpdate() []byte { + if m != nil { + return m.TrieUpdate + } + return nil +} + +// ProveRequest contains a proof query +type ProveRequest struct { + State *State `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` + Keys []*Key `protobuf:"bytes,2,rep,name=keys,proto3" json:"keys,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ProveRequest) Reset() { *m = ProveRequest{} } +func (m *ProveRequest) String() string { return proto.CompactTextString(m) } +func (*ProveRequest) ProtoMessage() {} +func (*ProveRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{13} +} + +func (m *ProveRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ProveRequest.Unmarshal(m, b) +} +func (m *ProveRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ProveRequest.Marshal(b, m, deterministic) +} +func (m *ProveRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_ProveRequest.Merge(m, src) +} +func (m *ProveRequest) XXX_Size() int { + return xxx_messageInfo_ProveRequest.Size(m) +} +func (m *ProveRequest) XXX_DiscardUnknown() { + xxx_messageInfo_ProveRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_ProveRequest proto.InternalMessageInfo + +func (m *ProveRequest) GetState() *State { + if m != nil { + return m.State + } + return nil +} + +func (m *ProveRequest) GetKeys() []*Key { + if m != nil { + return m.Keys + } + return nil +} + +// ProofResponse contains a proof +type ProofResponse struct { + Proof []byte `protobuf:"bytes,1,opt,name=proof,proto3" json:"proof,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ProofResponse) Reset() { *m = ProofResponse{} } +func (m *ProofResponse) String() string { return proto.CompactTextString(m) } +func (*ProofResponse) ProtoMessage() {} +func (*ProofResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_63585974d4c6a2c4, []int{14} +} + +func (m *ProofResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ProofResponse.Unmarshal(m, b) +} +func (m *ProofResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ProofResponse.Marshal(b, m, deterministic) +} +func (m *ProofResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ProofResponse.Merge(m, src) +} +func (m *ProofResponse) XXX_Size() int { + return xxx_messageInfo_ProofResponse.Size(m) +} +func (m *ProofResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ProofResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ProofResponse proto.InternalMessageInfo + +func (m *ProofResponse) GetProof() []byte { + if m != nil { + return m.Proof + } + return nil +} + +func init() { + proto.RegisterType((*State)(nil), "ledger.State") + proto.RegisterType((*KeyPart)(nil), "ledger.KeyPart") + proto.RegisterType((*Key)(nil), "ledger.Key") + proto.RegisterType((*Value)(nil), "ledger.Value") + proto.RegisterType((*StateRequest)(nil), "ledger.StateRequest") + proto.RegisterType((*StateResponse)(nil), "ledger.StateResponse") + proto.RegisterType((*HasStateResponse)(nil), "ledger.HasStateResponse") + proto.RegisterType((*GetSingleValueRequest)(nil), "ledger.GetSingleValueRequest") + proto.RegisterType((*ValueResponse)(nil), "ledger.ValueResponse") + proto.RegisterType((*GetRequest)(nil), "ledger.GetRequest") + proto.RegisterType((*GetResponse)(nil), "ledger.GetResponse") + proto.RegisterType((*SetRequest)(nil), "ledger.SetRequest") + proto.RegisterType((*SetResponse)(nil), "ledger.SetResponse") + proto.RegisterType((*ProveRequest)(nil), "ledger.ProveRequest") + proto.RegisterType((*ProofResponse)(nil), "ledger.ProofResponse") +} + +func init() { proto.RegisterFile("ledger.proto", fileDescriptor_63585974d4c6a2c4) } + +var fileDescriptor_63585974d4c6a2c4 = []byte{ + // 563 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xdd, 0x6a, 0xdb, 0x4c, + 0x10, 0xc5, 0x76, 0xe4, 0xcf, 0x19, 0xd9, 0x5f, 0xcb, 0xd6, 0x2e, 0xc6, 0x26, 0x34, 0xa8, 0x18, + 0xd2, 0x3f, 0x09, 0x6c, 0x5f, 0x15, 0x7a, 0x53, 0x68, 0xdd, 0x92, 0x52, 0x8c, 0xd4, 0xf6, 0x22, + 0xbd, 0x30, 0x72, 0x3c, 0x96, 0x45, 0x14, 0xad, 0xaa, 0x5d, 0xdb, 0xe8, 0x8d, 0xfb, 0x18, 0x65, + 0x7f, 0x14, 0x49, 0x6e, 0x08, 0x0d, 0xe4, 0x46, 0xec, 0xce, 0x9c, 0xb3, 0xe7, 0x8c, 0x66, 0x77, + 0xa0, 0x1d, 0xe1, 0x2a, 0xc0, 0xd4, 0x4e, 0x52, 0xca, 0x29, 0x69, 0xaa, 0xdd, 0x60, 0x18, 0x50, + 0x1a, 0x44, 0xe8, 0xc8, 0xe8, 0x72, 0xbb, 0x76, 0xf0, 0x3a, 0xe1, 0x99, 0x02, 0x59, 0x43, 0x30, + 0x3c, 0xee, 0x73, 0x24, 0x04, 0x8e, 0x36, 0x3e, 0xdb, 0xf4, 0x6b, 0xa7, 0xb5, 0xb3, 0xb6, 0x2b, + 0xd7, 0xd6, 0x04, 0xfe, 0x3b, 0xc7, 0x6c, 0xee, 0xa7, 0x5c, 0xa4, 0x79, 0x96, 0xa0, 0x4c, 0x77, + 0x5c, 0xb9, 0x26, 0x5d, 0x30, 0x76, 0x7e, 0xb4, 0xc5, 0x7e, 0x5d, 0x72, 0xd4, 0xc6, 0x7a, 0x0d, + 0x8d, 0x73, 0xcc, 0xc8, 0x08, 0x8c, 0xc4, 0x4f, 0x39, 0xeb, 0xd7, 0x4e, 0x1b, 0x67, 0xe6, 0xf8, + 0x91, 0xad, 0xbd, 0xe9, 0x03, 0x5d, 0x95, 0xb5, 0xc6, 0x60, 0xfc, 0x10, 0x34, 0x21, 0xb0, 0xf2, + 0xb9, 0x9f, 0xeb, 0x8b, 0x35, 0xe9, 0x41, 0x33, 0x64, 0x8b, 0x38, 0x8c, 0xa4, 0x42, 0xcb, 0x35, + 0x42, 0xf6, 0x35, 0x8c, 0xac, 0x09, 0xb4, 0xa5, 0x67, 0x17, 0x7f, 0x6d, 0x91, 0x71, 0xf2, 0x1c, + 0x0c, 0x26, 0xf6, 0x92, 0x6b, 0x8e, 0x3b, 0xb9, 0x94, 0x02, 0xa9, 0x9c, 0x35, 0x85, 0x8e, 0x26, + 0xb1, 0x84, 0xc6, 0x0c, 0xff, 0x8d, 0xe5, 0xc0, 0xe3, 0x4f, 0x3e, 0xab, 0x12, 0x87, 0x70, 0xbc, + 0xf1, 0xd9, 0xa2, 0x20, 0xb7, 0xdc, 0xd6, 0x46, 0x83, 0xac, 0x9f, 0xd0, 0x9b, 0x21, 0xf7, 0xc2, + 0x38, 0x88, 0x50, 0x16, 0x76, 0x1f, 0x93, 0xe4, 0x04, 0x1a, 0x57, 0x98, 0xc9, 0x6a, 0xcd, 0xb1, + 0x59, 0xfa, 0x65, 0xae, 0x88, 0x8b, 0x1a, 0xf4, 0x99, 0x45, 0x0d, 0xaa, 0x03, 0x07, 0x87, 0x2a, + 0x94, 0x6e, 0x88, 0x0b, 0x30, 0x43, 0x7e, 0x2f, 0x1f, 0xcf, 0xe0, 0xe8, 0x0a, 0x33, 0xd6, 0xaf, + 0xcb, 0xde, 0x55, 0x8c, 0xc8, 0x84, 0x35, 0x05, 0x53, 0x9e, 0xa9, 0x7d, 0x8c, 0xa0, 0x29, 0xb5, + 0xf2, 0x6e, 0x1f, 0x18, 0xd1, 0x49, 0x2b, 0x03, 0xf0, 0x1e, 0xd8, 0x49, 0x49, 0xba, 0x71, 0x97, + 0xf4, 0x05, 0x98, 0x5e, 0xc9, 0xf0, 0x4b, 0x38, 0x8e, 0x71, 0xbf, 0xb8, 0x43, 0xbf, 0x15, 0xe3, + 0xde, 0xd3, 0x16, 0x4c, 0x9e, 0x86, 0xb8, 0xd8, 0x26, 0x2b, 0x81, 0x56, 0x97, 0x1d, 0x44, 0xe8, + 0xbb, 0x8c, 0x58, 0xdf, 0xa0, 0x3d, 0x4f, 0xe9, 0x0e, 0x1f, 0xf6, 0x17, 0x8f, 0xa0, 0x33, 0x4f, + 0x29, 0x5d, 0xdf, 0x78, 0xee, 0x82, 0x91, 0x88, 0x80, 0x7e, 0x22, 0x6a, 0x33, 0xfe, 0x5d, 0x87, + 0xce, 0x17, 0xc9, 0xf5, 0x30, 0xdd, 0x85, 0x97, 0x48, 0xde, 0x41, 0xfb, 0x73, 0x1c, 0xf2, 0xd0, + 0x8f, 0x94, 0xff, 0xa7, 0xb6, 0x1a, 0x00, 0x76, 0x3e, 0x00, 0xec, 0x0f, 0x62, 0x00, 0x0c, 0x7a, + 0x55, 0x5f, 0xb9, 0xcc, 0x5b, 0x68, 0xe5, 0x57, 0x9e, 0x74, 0x0f, 0x20, 0xb2, 0xbe, 0x41, 0x3f, + 0x8f, 0xfe, 0xf5, 0x34, 0x3e, 0xc2, 0xff, 0xd5, 0xdb, 0x4f, 0x4e, 0x72, 0xec, 0xad, 0xaf, 0xa2, + 0xf0, 0x50, 0xbd, 0xd7, 0x36, 0x34, 0x66, 0xc8, 0x09, 0x29, 0x91, 0x73, 0xc6, 0x93, 0x4a, 0xac, + 0xc0, 0x7b, 0x65, 0xbc, 0x77, 0x0b, 0xbe, 0xdc, 0xfe, 0x29, 0x18, 0xb2, 0x63, 0x45, 0x81, 0xe5, + 0x06, 0x16, 0xae, 0x2a, 0x0d, 0x78, 0xff, 0xea, 0xe2, 0x45, 0x10, 0xf2, 0xcd, 0x76, 0x69, 0x5f, + 0xd2, 0x6b, 0x87, 0xc6, 0xeb, 0x88, 0xee, 0x1d, 0xf1, 0x79, 0x13, 0x50, 0x47, 0x31, 0x6e, 0x86, + 0xec, 0xb2, 0x29, 0x57, 0x93, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x7f, 0xcc, 0x9c, 0x5b, 0x94, + 0x05, 0x00, 0x00, +} diff --git a/ledger/protobuf/ledger.proto b/ledger/protobuf/ledger.proto new file mode 100644 index 00000000000..de24e694b65 --- /dev/null +++ b/ledger/protobuf/ledger.proto @@ -0,0 +1,118 @@ +syntax = "proto3"; + +package ledger; + +option go_package = "github.com/onflow/flow-go/ledger/protobuf"; + +import "google/protobuf/empty.proto"; + +// LedgerService provides remote access to ledger operations +service LedgerService { + // InitialState returns the initial state of the ledger + rpc InitialState(google.protobuf.Empty) returns (StateResponse); + + // HasState checks if the given state exists in the ledger + rpc HasState(StateRequest) returns (HasStateResponse); + + // GetSingleValue returns a single value for a given key at a specific state + rpc GetSingleValue(GetSingleValueRequest) returns (ValueResponse); + + // Get returns values for multiple keys at a specific state + rpc Get(GetRequest) returns (GetResponse); + + // Set updates keys with new values at a specific state and returns the new state + rpc Set(SetRequest) returns (SetResponse); + + // Prove returns proofs for the given keys at a specific state + rpc Prove(ProveRequest) returns (ProofResponse); +} + +// State represents a ledger state (32-byte hash) +message State { + bytes hash = 1; // 32 bytes +} + +// KeyPart represents a part of a hierarchical key +message KeyPart { + // type is actually uint16 but uint16 is not available in proto3 + uint32 type = 1; + bytes value = 2; +} + +// Key represents a hierarchical ledger key +message Key { + repeated KeyPart parts = 1; +} + +// Value represents a ledger value +message Value { + bytes data = 1; + // is_nil distinguishes between nil and []byte{} (empty slice). + // When data is nil or empty: + // - is_nil=true means the original value was nil + // - is_nil=false means the original value was []byte{} (empty slice) + // When data is non-empty, is_nil is ignored (should be false). + bool is_nil = 2; +} + +// StateRequest contains a state to query +message StateRequest { + State state = 1; +} + +// StateResponse contains a state +message StateResponse { + State state = 1; +} + +// HasStateResponse indicates if a state exists +message HasStateResponse { + bool has_state = 1; +} + +// GetSingleValueRequest contains a query for a single value +message GetSingleValueRequest { + State state = 1; + Key key = 2; +} + +// ValueResponse contains a single value +message ValueResponse { + Value value = 1; +} + +// GetRequest contains a query for multiple values +message GetRequest { + State state = 1; + repeated Key keys = 2; +} + +// GetResponse contains multiple values +message GetResponse { + repeated Value values = 1; +} + +// SetRequest contains an update operation +message SetRequest { + State state = 1; + repeated Key keys = 2; + repeated Value values = 3; +} + +// SetResponse contains the new state after an update +message SetResponse { + State new_state = 1; + bytes trie_update = 2; // Encoded TrieUpdate (opaque to gRPC) +} + +// ProveRequest contains a proof query +message ProveRequest { + State state = 1; + repeated Key keys = 2; +} + +// ProofResponse contains a proof +message ProofResponse { + bytes proof = 1; // Encoded Proof (opaque to gRPC) +} + diff --git a/ledger/protobuf/ledger_grpc.pb.go b/ledger/protobuf/ledger_grpc.pb.go new file mode 100644 index 00000000000..9563796331c --- /dev/null +++ b/ledger/protobuf/ledger_grpc.pb.go @@ -0,0 +1,307 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.3.0 +// - protoc (unknown) +// source: ledger.proto + +package protobuf + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + emptypb "google.golang.org/protobuf/types/known/emptypb" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +const ( + LedgerService_InitialState_FullMethodName = "/ledger.LedgerService/InitialState" + LedgerService_HasState_FullMethodName = "/ledger.LedgerService/HasState" + LedgerService_GetSingleValue_FullMethodName = "/ledger.LedgerService/GetSingleValue" + LedgerService_Get_FullMethodName = "/ledger.LedgerService/Get" + LedgerService_Set_FullMethodName = "/ledger.LedgerService/Set" + LedgerService_Prove_FullMethodName = "/ledger.LedgerService/Prove" +) + +// LedgerServiceClient is the client API for LedgerService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type LedgerServiceClient interface { + // InitialState returns the initial state of the ledger + InitialState(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*StateResponse, error) + // HasState checks if the given state exists in the ledger + HasState(ctx context.Context, in *StateRequest, opts ...grpc.CallOption) (*HasStateResponse, error) + // GetSingleValue returns a single value for a given key at a specific state + GetSingleValue(ctx context.Context, in *GetSingleValueRequest, opts ...grpc.CallOption) (*ValueResponse, error) + // Get returns values for multiple keys at a specific state + Get(ctx context.Context, in *GetRequest, opts ...grpc.CallOption) (*GetResponse, error) + // Set updates keys with new values at a specific state and returns the new state + Set(ctx context.Context, in *SetRequest, opts ...grpc.CallOption) (*SetResponse, error) + // Prove returns proofs for the given keys at a specific state + Prove(ctx context.Context, in *ProveRequest, opts ...grpc.CallOption) (*ProofResponse, error) +} + +type ledgerServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewLedgerServiceClient(cc grpc.ClientConnInterface) LedgerServiceClient { + return &ledgerServiceClient{cc} +} + +func (c *ledgerServiceClient) InitialState(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*StateResponse, error) { + out := new(StateResponse) + err := c.cc.Invoke(ctx, LedgerService_InitialState_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *ledgerServiceClient) HasState(ctx context.Context, in *StateRequest, opts ...grpc.CallOption) (*HasStateResponse, error) { + out := new(HasStateResponse) + err := c.cc.Invoke(ctx, LedgerService_HasState_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *ledgerServiceClient) GetSingleValue(ctx context.Context, in *GetSingleValueRequest, opts ...grpc.CallOption) (*ValueResponse, error) { + out := new(ValueResponse) + err := c.cc.Invoke(ctx, LedgerService_GetSingleValue_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *ledgerServiceClient) Get(ctx context.Context, in *GetRequest, opts ...grpc.CallOption) (*GetResponse, error) { + out := new(GetResponse) + err := c.cc.Invoke(ctx, LedgerService_Get_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *ledgerServiceClient) Set(ctx context.Context, in *SetRequest, opts ...grpc.CallOption) (*SetResponse, error) { + out := new(SetResponse) + err := c.cc.Invoke(ctx, LedgerService_Set_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *ledgerServiceClient) Prove(ctx context.Context, in *ProveRequest, opts ...grpc.CallOption) (*ProofResponse, error) { + out := new(ProofResponse) + err := c.cc.Invoke(ctx, LedgerService_Prove_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// LedgerServiceServer is the server API for LedgerService service. +// All implementations must embed UnimplementedLedgerServiceServer +// for forward compatibility +type LedgerServiceServer interface { + // InitialState returns the initial state of the ledger + InitialState(context.Context, *emptypb.Empty) (*StateResponse, error) + // HasState checks if the given state exists in the ledger + HasState(context.Context, *StateRequest) (*HasStateResponse, error) + // GetSingleValue returns a single value for a given key at a specific state + GetSingleValue(context.Context, *GetSingleValueRequest) (*ValueResponse, error) + // Get returns values for multiple keys at a specific state + Get(context.Context, *GetRequest) (*GetResponse, error) + // Set updates keys with new values at a specific state and returns the new state + Set(context.Context, *SetRequest) (*SetResponse, error) + // Prove returns proofs for the given keys at a specific state + Prove(context.Context, *ProveRequest) (*ProofResponse, error) + mustEmbedUnimplementedLedgerServiceServer() +} + +// UnimplementedLedgerServiceServer must be embedded to have forward compatible implementations. +type UnimplementedLedgerServiceServer struct { +} + +func (UnimplementedLedgerServiceServer) InitialState(context.Context, *emptypb.Empty) (*StateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method InitialState not implemented") +} +func (UnimplementedLedgerServiceServer) HasState(context.Context, *StateRequest) (*HasStateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method HasState not implemented") +} +func (UnimplementedLedgerServiceServer) GetSingleValue(context.Context, *GetSingleValueRequest) (*ValueResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetSingleValue not implemented") +} +func (UnimplementedLedgerServiceServer) Get(context.Context, *GetRequest) (*GetResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Get not implemented") +} +func (UnimplementedLedgerServiceServer) Set(context.Context, *SetRequest) (*SetResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Set not implemented") +} +func (UnimplementedLedgerServiceServer) Prove(context.Context, *ProveRequest) (*ProofResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Prove not implemented") +} +func (UnimplementedLedgerServiceServer) mustEmbedUnimplementedLedgerServiceServer() {} + +// UnsafeLedgerServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to LedgerServiceServer will +// result in compilation errors. +type UnsafeLedgerServiceServer interface { + mustEmbedUnimplementedLedgerServiceServer() +} + +func RegisterLedgerServiceServer(s grpc.ServiceRegistrar, srv LedgerServiceServer) { + s.RegisterService(&LedgerService_ServiceDesc, srv) +} + +func _LedgerService_InitialState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(emptypb.Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LedgerServiceServer).InitialState(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LedgerService_InitialState_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LedgerServiceServer).InitialState(ctx, req.(*emptypb.Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _LedgerService_HasState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LedgerServiceServer).HasState(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LedgerService_HasState_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LedgerServiceServer).HasState(ctx, req.(*StateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _LedgerService_GetSingleValue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetSingleValueRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LedgerServiceServer).GetSingleValue(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LedgerService_GetSingleValue_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LedgerServiceServer).GetSingleValue(ctx, req.(*GetSingleValueRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _LedgerService_Get_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LedgerServiceServer).Get(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LedgerService_Get_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LedgerServiceServer).Get(ctx, req.(*GetRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _LedgerService_Set_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SetRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LedgerServiceServer).Set(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LedgerService_Set_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LedgerServiceServer).Set(ctx, req.(*SetRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _LedgerService_Prove_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ProveRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LedgerServiceServer).Prove(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LedgerService_Prove_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LedgerServiceServer).Prove(ctx, req.(*ProveRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// LedgerService_ServiceDesc is the grpc.ServiceDesc for LedgerService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var LedgerService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "ledger.LedgerService", + HandlerType: (*LedgerServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "InitialState", + Handler: _LedgerService_InitialState_Handler, + }, + { + MethodName: "HasState", + Handler: _LedgerService_HasState_Handler, + }, + { + MethodName: "GetSingleValue", + Handler: _LedgerService_GetSingleValue_Handler, + }, + { + MethodName: "Get", + Handler: _LedgerService_Get_Handler, + }, + { + MethodName: "Set", + Handler: _LedgerService_Set_Handler, + }, + { + MethodName: "Prove", + Handler: _LedgerService_Prove_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "ledger.proto", +} diff --git a/ledger/remote/client.go b/ledger/remote/client.go new file mode 100644 index 00000000000..9f2119bf677 --- /dev/null +++ b/ledger/remote/client.go @@ -0,0 +1,467 @@ +package remote + +import ( + "context" + "fmt" + "strings" + "sync" + "time" + + "github.com/rs/zerolog" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/emptypb" + + "github.com/onflow/flow-go/ledger" + ledgerpb "github.com/onflow/flow-go/ledger/protobuf" +) + +// Client implements ledger.Ledger interface using gRPC calls to a remote ledger service. +type Client struct { + conn *grpc.ClientConn + client ledgerpb.LedgerServiceClient + logger zerolog.Logger + done chan struct{} + once sync.Once + ctx context.Context + cancel context.CancelFunc + callTimeout time.Duration +} + +// clientConfig holds configuration options for the Client. +type clientConfig struct { + maxRequestSize uint + maxResponseSize uint + callTimeout time.Duration +} + +// defaultClientConfig returns the default configuration. +func defaultClientConfig() *clientConfig { + return &clientConfig{ + maxRequestSize: 1 << 30, // 1 GiB + maxResponseSize: 1 << 30, // 1 GiB + callTimeout: time.Minute, + } +} + +// ClientOption is a function that configures a Client. +type ClientOption func(*clientConfig) + +// WithMaxRequestSize sets the maximum request message size in bytes. +func WithMaxRequestSize(size uint) ClientOption { + return func(cfg *clientConfig) { + cfg.maxRequestSize = size + } +} + +// WithMaxResponseSize sets the maximum response message size in bytes. +func WithMaxResponseSize(size uint) ClientOption { + return func(cfg *clientConfig) { + cfg.maxResponseSize = size + } +} + +// WithCallTimeout sets the timeout for individual gRPC calls. +func WithCallTimeout(timeout time.Duration) ClientOption { + return func(cfg *clientConfig) { + cfg.callTimeout = timeout + } +} + +// NewClient creates a new remote ledger client. +// grpcAddr can be either a TCP address (e.g., "localhost:9000") or a Unix domain socket. +// For Unix sockets, you can use either the full gRPC format (e.g., "unix:///tmp/ledger.sock") +// or just the absolute path (e.g., "/tmp/ledger.sock") - the unix:// prefix will be added automatically. +// Options can be provided to customize the client configuration. +// By default, max request and response sizes are 1 GiB. +func NewClient(grpcAddr string, logger zerolog.Logger, opts ...ClientOption) (*Client, error) { + logger = logger.With().Str("component", "remote_ledger_client").Logger() + + cfg := defaultClientConfig() + for _, opt := range opts { + opt(cfg) + } + + // Handle Unix domain socket addresses + // gRPC client accepts "unix:///absolute/path" or "unix://relative/path" format + // For convenience, if an absolute path is provided (starts with /), automatically add the unix:// prefix + if strings.HasPrefix(grpcAddr, "/") { + grpcAddr = "unix://" + grpcAddr + logger.Debug().Str("address", grpcAddr).Msg("using Unix domain socket (auto-prefixed)") + } else if strings.HasPrefix(grpcAddr, "unix://") { + logger.Debug().Str("address", grpcAddr).Msg("using Unix domain socket") + } + + // Create gRPC connection with max message size configuration. + // Default to 1 GiB (instead of standard 4 MiB) to handle large proofs that can exceed 4MB. + // This was increased to fix "grpc: received message larger than max" errors when generating + // proofs for blocks with many state changes. + // Retry connection with exponential backoff until the service becomes available. + // After approximately 40 minutes of retrying (90 attempts), the client will give up and crash. + var conn *grpc.ClientConn + retryDelay := 100 * time.Millisecond + maxRetryDelay := 30 * time.Second + maxRetries := 90 // ~40 minutes total wait time with exponential backoff capped at 30s + + for attempt := 0; ; attempt++ { + var err error + conn, err = grpc.NewClient( + grpcAddr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithDefaultCallOptions( + grpc.MaxCallRecvMsgSize(int(cfg.maxResponseSize)), + grpc.MaxCallSendMsgSize(int(cfg.maxRequestSize)), + ), + ) + if err == nil { + logger.Info().Str("address", grpcAddr).Msg("successfully connected to ledger service") + break + } + + if attempt >= maxRetries { + logger.Fatal(). + Err(err). + Int("attempts", attempt). + Str("address", grpcAddr). + Msg("failed to connect to ledger service after maximum retries, crashing node") + } + + logger.Warn(). + Err(err). + Int("attempt", attempt+1). + Int("max_attempts", maxRetries). + Dur("retry_delay", retryDelay). + Time("retry_at", time.Now().Add(retryDelay)). + Str("address", grpcAddr). + Msg("failed to connect to ledger service, retrying...") + + time.Sleep(retryDelay) + // Exponential backoff with max cap + retryDelay = min(maxRetryDelay, time.Duration(float64(retryDelay)*1.5)) + } + + client := ledgerpb.NewLedgerServiceClient(conn) + + ctx, cancel := context.WithCancel(context.Background()) + + return &Client{ + conn: conn, + client: client, + logger: logger, + done: make(chan struct{}), + ctx: ctx, + cancel: cancel, + callTimeout: cfg.callTimeout, + }, nil +} + +// Close closes the gRPC connection. +func (c *Client) Close() error { + if c.conn != nil { + err := c.conn.Close() + c.conn = nil + return err + } + return nil +} + +// callCtx returns a context for gRPC calls with the configured timeout. +// The context is also cancelled when the client is shut down via Done(). +func (c *Client) callCtx() (context.Context, context.CancelFunc) { + return context.WithTimeout(c.ctx, c.callTimeout) +} + +// InitialState returns the initial state of the ledger. +func (c *Client) InitialState() ledger.State { + ctx, cancel := c.callCtx() + defer cancel() + resp, err := c.client.InitialState(ctx, &emptypb.Empty{}) + if err != nil { + c.logger.Fatal().Err(err).Msg("failed to get initial state") + return ledger.DummyState + } + + var state ledger.State + if len(resp.State.Hash) != len(state) { + c.logger.Fatal(). + Int("expected", len(state)). + Int("got", len(resp.State.Hash)). + Msg("invalid state hash length") + return ledger.DummyState + } + copy(state[:], resp.State.Hash) + return state +} + +// HasState returns true if the given state exists in the ledger. +func (c *Client) HasState(state ledger.State) bool { + ctx, cancel := c.callCtx() + defer cancel() + req := &ledgerpb.StateRequest{ + State: &ledgerpb.State{ + Hash: state[:], + }, + } + + resp, err := c.client.HasState(ctx, req) + if err != nil { + c.logger.Error().Err(err).Msg("failed to check state") + return false + } + + return resp.HasState +} + +// GetSingleValue returns a single value for a given key at a specific state. +func (c *Client) GetSingleValue(query *ledger.QuerySingleValue) (ledger.Value, error) { + ctx, cancel := c.callCtx() + defer cancel() + state := query.State() + req := &ledgerpb.GetSingleValueRequest{ + State: &ledgerpb.State{ + Hash: state[:], + }, + Key: ledgerKeyToProtoKey(query.Key()), + } + + resp, err := c.client.GetSingleValue(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to get single value: %w", err) + } + + // Reconstruct the original value type using is_nil flag + // This preserves the distinction between nil and []byte{} that protobuf loses + if len(resp.Value.Data) == 0 { + if resp.Value.IsNil { + return nil, nil + } + return ledger.Value([]byte{}), nil + } + // Copy the data to avoid holding reference to the gRPC response buffer + return ledger.Value(append([]byte{}, resp.Value.Data...)), nil +} + +// Get returns values for multiple keys at a specific state. +func (c *Client) Get(query *ledger.Query) ([]ledger.Value, error) { + ctx, cancel := c.callCtx() + defer cancel() + state := query.State() + req := &ledgerpb.GetRequest{ + State: &ledgerpb.State{ + Hash: state[:], + }, + Keys: make([]*ledgerpb.Key, len(query.Keys())), + } + + for i, key := range query.Keys() { + req.Keys[i] = ledgerKeyToProtoKey(key) + } + + resp, err := c.client.Get(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to get values: %w", err) + } + + values := make([]ledger.Value, len(resp.Values)) + for i, protoValue := range resp.Values { + // Reconstruct the original value type using is_nil flag + // This preserves the distinction between nil and []byte{} that protobuf loses + if len(protoValue.Data) == 0 { + if protoValue.IsNil { + values[i] = nil + } else { + values[i] = ledger.Value([]byte{}) + } + } else { + // Copy the data to avoid holding reference to the gRPC response buffer + values[i] = ledger.Value(append([]byte{}, protoValue.Data...)) + } + } + + return values, nil +} + +// Set updates keys with new values at a specific state and returns the new state. +func (c *Client) Set(update *ledger.Update) (ledger.State, *ledger.TrieUpdate, error) { + // Handle empty updates locally without RPC call. + // This matches the behavior of the local ledger implementations which return + // the same state when there are no keys to update. + if update.Size() == 0 { + return update.State(), + &ledger.TrieUpdate{ + RootHash: ledger.RootHash(update.State()), + Paths: []ledger.Path{}, + Payloads: []*ledger.Payload{}, + }, + nil + } + + ctx, cancel := c.callCtx() + defer cancel() + state := update.State() + req := &ledgerpb.SetRequest{ + State: &ledgerpb.State{ + Hash: state[:], + }, + Keys: make([]*ledgerpb.Key, len(update.Keys())), + Values: make([]*ledgerpb.Value, len(update.Values())), + } + + for i, key := range update.Keys() { + req.Keys[i] = ledgerKeyToProtoKey(key) + } + + for i, value := range update.Values() { + // Distinguish between nil and []byte{} for protobuf encoding + // Protobuf cannot distinguish them, so we use is_nil flag + isNil := value == nil + req.Values[i] = &ledgerpb.Value{ + Data: value, + IsNil: isNil, + } + } + + resp, err := c.client.Set(ctx, req) + if err != nil { + return ledger.DummyState, nil, fmt.Errorf("failed to set values: %w", err) + } + + if resp == nil || resp.NewState == nil { + return ledger.DummyState, nil, fmt.Errorf("invalid response: missing new state") + } + + var newState ledger.State + if len(resp.NewState.Hash) != len(newState) { + return ledger.DummyState, nil, fmt.Errorf("invalid new state hash length") + } + copy(newState[:], resp.NewState.Hash) + + // Decode trie update using centralized decoding function to ensure + // client and server use the same encoding method + trieUpdate, err := decodeTrieUpdateFromTransport(resp.TrieUpdate) + if err != nil { + return ledger.DummyState, nil, fmt.Errorf("failed to decode trie update: %w", err) + } + + return newState, trieUpdate, nil +} + +// Prove returns proofs for the given keys at a specific state. +func (c *Client) Prove(query *ledger.Query) (ledger.Proof, error) { + ctx, cancel := c.callCtx() + defer cancel() + state := query.State() + req := &ledgerpb.ProveRequest{ + State: &ledgerpb.State{ + Hash: state[:], + }, + Keys: make([]*ledgerpb.Key, len(query.Keys())), + } + + for i, key := range query.Keys() { + req.Keys[i] = ledgerKeyToProtoKey(key) + } + + resp, err := c.client.Prove(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to generate proof: %w", err) + } + + // Copy the proof to avoid holding reference to the gRPC response buffer + return ledger.Proof(append([]byte{}, resp.Proof...)), nil +} + +// Ready returns a channel that is closed when the client is ready. +// For a remote client, this waits for the ledger service to be ready by +// calling InitialState() with retries to ensure the service has finished initialization. +func (c *Client) Ready() <-chan struct{} { + ready := make(chan struct{}) + go func() { + defer close(ready) + // Wait for the ledger service to be ready by calling InitialState() + // This ensures the service has finished WAL replay and is ready to serve requests + // Retry with exponential backoff (delay capped at 30s) + maxRetries := 30 + retryDelay := 100 * time.Millisecond + maxRetryDelay := 30 * time.Second + + for i := 0; i < maxRetries; i++ { + ctx, cancel := c.callCtx() + _, err := c.client.InitialState(ctx, &emptypb.Empty{}) + cancel() + if err == nil { + c.logger.Info().Msg("ledger service ready") + return + } + + // Check if the client context was cancelled (shutdown in progress) + if c.ctx.Err() != nil { + c.logger.Info().Msg("client shutdown during ready check") + return + } + + if i < maxRetries-1 { + c.logger.Warn(). + Err(err). + Int("attempt", i+1). + Dur("retry_delay", retryDelay). + Time("retry_at", time.Now().Add(retryDelay)). + Msg("ledger service not ready, retrying...") + time.Sleep(retryDelay) + retryDelay = min(time.Duration(float64(retryDelay)*1.5), maxRetryDelay) + } else { + c.logger.Warn().Err(err).Msg("ledger service not ready after retries, proceeding anyway") + // Still close the channel to avoid blocking forever + // The execution node will fail later with a more specific error if the service is truly not ready + } + } + }() + return ready +} + +// Done returns a channel that is closed when the client is done. +// This cancels any in-flight gRPC calls and closes the connection. +// The method is idempotent - multiple calls return the same channel. +func (c *Client) Done() <-chan struct{} { + c.once.Do(func() { + go func() { + defer close(c.done) + // Cancel context first to abort any in-flight calls + c.cancel() + if err := c.Close(); err != nil { + c.logger.Error().Err(err).Msg("error closing gRPC connection") + } + }() + }) + return c.done +} + +// StateCount returns the number of states in the ledger. +// This is not supported for remote clients as it requires gRPC methods that are not yet implemented. +func (c *Client) StateCount() int { + // Remote client doesn't have access to state count without additional gRPC methods + // Return 0 to indicate no states are available (or unknown) + // This will cause the health check to fail, which is appropriate + return 0 +} + +// StateByIndex returns the state at the given index. +// -1 is the last index. +// This is not supported for remote clients as it requires gRPC methods that are not yet implemented. +func (c *Client) StateByIndex(index int) (ledger.State, error) { + return ledger.DummyState, fmt.Errorf("StateByIndex is not supported for remote ledger clients") +} + +// ledgerKeyToProtoKey converts a ledger.Key to a protobuf Key. +func ledgerKeyToProtoKey(key ledger.Key) *ledgerpb.Key { + parts := make([]*ledgerpb.KeyPart, len(key.KeyParts)) + for i, part := range key.KeyParts { + parts[i] = &ledgerpb.KeyPart{ + Type: uint32(part.Type), + Value: part.Value, + } + } + return &ledgerpb.Key{ + Parts: parts, + } +} diff --git a/ledger/remote/client_test.go b/ledger/remote/client_test.go new file mode 100644 index 00000000000..1401de77151 --- /dev/null +++ b/ledger/remote/client_test.go @@ -0,0 +1,74 @@ +package remote + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/ledger" + "github.com/onflow/flow-go/utils/unittest" +) + +// TestClientSetEmptyUpdate verifies that the Client.Set method handles empty updates +// correctly without making an RPC call. This matches the behavior of the local ledger +// implementations (ledger/complete/ledger.go and ledger/partial/ledger.go). +// +// When a transaction/collection doesn't modify any registers (read-only), the update +// will have zero keys. The client should return the same state without making an RPC +// call, avoiding the "keys cannot be empty" error from the server. +func TestClientSetEmptyUpdate(t *testing.T) { + // Create an empty update (no keys, no values) + state := ledger.State(unittest.StateCommitmentFixture()) + update, err := ledger.NewUpdate(state, []ledger.Key{}, []ledger.Value{}) + require.NoError(t, err) + require.Equal(t, 0, update.Size(), "update should have zero keys") + + // Create a client with no actual connection (we shouldn't need it for empty updates) + // The client will panic if it tries to make an RPC call, which verifies we don't call the server + client := &Client{ + // All fields are nil/zero - any RPC call would panic + } + + // Call Set with empty update + newState, trieUpdate, err := client.Set(update) + + // Verify no error + require.NoError(t, err, "Set with empty update should not return error") + + // Verify the state is unchanged + assert.Equal(t, state, newState, "new state should equal original state for empty update") + + // Verify the trie update is valid but empty + require.NotNil(t, trieUpdate, "trie update should not be nil") + assert.Equal(t, ledger.RootHash(state), trieUpdate.RootHash, "trie update root hash should match state") + assert.Empty(t, trieUpdate.Paths, "trie update should have no paths for empty update") + assert.Empty(t, trieUpdate.Payloads, "trie update should have no payloads for empty update") +} + +// TestClientSetEmptyUpdateMatchesLocalLedger verifies that the remote client's +// empty update handling produces the same result as the local ledger implementations. +func TestClientSetEmptyUpdateMatchesLocalLedger(t *testing.T) { + state := ledger.State(unittest.StateCommitmentFixture()) + update, err := ledger.NewUpdate(state, []ledger.Key{}, []ledger.Value{}) + require.NoError(t, err) + + // Get result from remote client (without actual connection) + client := &Client{} + remoteState, remoteTrieUpdate, err := client.Set(update) + require.NoError(t, err) + + // The expected result matches what local ledger implementations return: + // - State unchanged + // - TrieUpdate with RootHash equal to state, empty Paths and Payloads + expectedTrieUpdate := &ledger.TrieUpdate{ + RootHash: ledger.RootHash(state), + Paths: []ledger.Path{}, + Payloads: []*ledger.Payload{}, + } + + assert.Equal(t, state, remoteState, "state should be unchanged") + assert.Equal(t, expectedTrieUpdate.RootHash, remoteTrieUpdate.RootHash) + assert.Equal(t, len(expectedTrieUpdate.Paths), len(remoteTrieUpdate.Paths)) + assert.Equal(t, len(expectedTrieUpdate.Payloads), len(remoteTrieUpdate.Payloads)) +} diff --git a/ledger/remote/encoding.go b/ledger/remote/encoding.go new file mode 100644 index 00000000000..8a09a30e523 --- /dev/null +++ b/ledger/remote/encoding.go @@ -0,0 +1,33 @@ +package remote + +import ( + "github.com/onflow/flow-go/ledger" +) + +// encodeTrieUpdateForTransport encodes a trie update for transmission over gRPC. +// This function MUST be used by the server when encoding trie updates. +// The client MUST use decodeTrieUpdateFromTransport to decode. +// +// This centralized function ensures that both client and server use the same +// encoding method, preventing encoding/decoding mismatches. +// +// Currently uses CBOR encoding to preserve the distinction between nil and []byte{} +// values in payloads. If the encoding method needs to change, update this function +// and ensure decodeTrieUpdateFromTransport uses the matching decoder. +func encodeTrieUpdateForTransport(trieUpdate *ledger.TrieUpdate) []byte { + return ledger.EncodeTrieUpdateCBOR(trieUpdate) +} + +// decodeTrieUpdateFromTransport decodes a trie update received over gRPC. +// This function MUST be used by the client when decoding trie updates. +// The server MUST use encodeTrieUpdateForTransport to encode. +// +// This centralized function ensures that both client and server use the same +// encoding method, preventing encoding/decoding mismatches. +// +// Currently uses CBOR decoding to preserve the distinction between nil and []byte{} +// values in payloads. If the encoding method needs to change, update this function +// and ensure encodeTrieUpdateForTransport uses the matching encoder. +func decodeTrieUpdateFromTransport(encodedTrieUpdate []byte) (*ledger.TrieUpdate, error) { + return ledger.DecodeTrieUpdateCBOR(encodedTrieUpdate) +} diff --git a/ledger/remote/factory.go b/ledger/remote/factory.go new file mode 100644 index 00000000000..d7e5ad89b98 --- /dev/null +++ b/ledger/remote/factory.go @@ -0,0 +1,46 @@ +package remote + +import ( + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/ledger" +) + +// RemoteLedgerFactory creates remote ledger instances via gRPC. +type RemoteLedgerFactory struct { + grpcAddr string + logger zerolog.Logger + maxRequestSize uint + maxResponseSize uint +} + +// NewRemoteLedgerFactory creates a new factory for remote ledger instances. +// maxRequestSize and maxResponseSize specify the maximum message sizes in bytes. +// If both are 0, defaults to 1 GiB for both requests and responses. +func NewRemoteLedgerFactory( + grpcAddr string, + logger zerolog.Logger, + maxRequestSize, maxResponseSize uint, +) ledger.Factory { + return &RemoteLedgerFactory{ + grpcAddr: grpcAddr, + logger: logger, + maxRequestSize: maxRequestSize, + maxResponseSize: maxResponseSize, + } +} + +func (f *RemoteLedgerFactory) NewLedger() (ledger.Ledger, error) { + var opts []ClientOption + if f.maxRequestSize > 0 { + opts = append(opts, WithMaxRequestSize(f.maxRequestSize)) + } + if f.maxResponseSize > 0 { + opts = append(opts, WithMaxResponseSize(f.maxResponseSize)) + } + client, err := NewClient(f.grpcAddr, f.logger, opts...) + if err != nil { + return nil, err + } + return client, nil +} diff --git a/ledger/remote/protobuf_encoding_test.go b/ledger/remote/protobuf_encoding_test.go new file mode 100644 index 00000000000..2b519777b92 --- /dev/null +++ b/ledger/remote/protobuf_encoding_test.go @@ -0,0 +1,257 @@ +package remote + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + ledgerpb "github.com/onflow/flow-go/ledger/protobuf" +) + +// TestProtobufNilVsEmptySlice demonstrates that protobuf cannot distinguish +// between nil and []byte{} after encoding/decoding. +// +// This test shows the root cause of the execution_data_id mismatch: +// - When a client sends []byte{} (empty slice), protobuf encodes it +// - When the server decodes it, it becomes nil +// - The server cannot distinguish between originally nil vs originally []byte{} +// - This causes different CBOR encodings (f6 for nil vs 40 for []byte{}) +// - Leading to different execution_data_id values +// +// Note: In practice, gRPC handles protobuf encoding/decoding automatically. +// This test simulates what happens by directly checking protobuf message behavior. +func TestProtobufNilVsEmptySlice(t *testing.T) { + // Create three different values that should be distinguishable + values := []struct { + name string + input []byte + }{ + {"nil_value", nil}, + {"empty_slice", []byte{}}, + {"non_empty_slice", []byte{1, 2, 3}}, + } + + // Create protobuf messages with these values (what the client does) + protoValues := make([]*ledgerpb.Value, len(values)) + for i, v := range values { + protoValues[i] = &ledgerpb.Value{ + Data: v.input, + } + } + + // Verify the original distinction on the client side + t.Log("Client side - Original values before protobuf encoding:") + for i, v := range values { + if v.input == nil { + t.Logf(" [%d] %s: nil (len=%d, isNil=%v)", i, v.name, 0, true) + } else { + t.Logf(" [%d] %s: []byte{} (len=%d, isNil=%v)", i, v.name, len(v.input), false) + } + } + + // Simulate what happens: when protobuf encodes []byte{}, it becomes + // indistinguishable from nil on the wire. When decoded, both become nil. + // This is what the server sees after gRPC decodes the protobuf message. + t.Log("\nServer side - What server receives after protobuf encoding/decoding:") + t.Log(" (In real gRPC, this happens automatically during transmission)") + + // The key insight: protobuf treats empty bytes fields as optional + // When []byte{} is encoded and decoded, it becomes nil + // We can simulate this by checking what happens when we set Data to []byte{} + serverSeesTypes := make(map[string]int) + for i, protoValue := range protoValues { + // In protobuf, when Data is []byte{}, after encoding/decoding it becomes nil + // This is the behavior we're testing + var typeStr string + var serverSees []byte + + // Simulate protobuf behavior: empty slice becomes nil after round-trip + if protoValue.Data == nil { + serverSees = nil + typeStr = "NIL" + } else if len(protoValue.Data) == 0 { + // This is the problem: []byte{} becomes nil after protobuf round-trip + serverSees = nil + typeStr = "NIL" // Lost distinction! + } else { + serverSees = protoValue.Data + typeStr = "NON_EMPTY" + } + + serverSeesTypes[typeStr]++ + t.Logf(" [%d] %s: server sees %s (len=%d, isNil=%v)", + i, values[i].name, typeStr, len(serverSees), serverSees == nil) + } + + // The critical assertion: we expected 3 distinct types, but protobuf only gives us 2 + // - nil and []byte{} both become nil (indistinguishable) + // - Only non-empty slices remain distinct + t.Logf("\nDistinct types server can distinguish: %d (expected 2, not 3)", len(serverSeesTypes)) + for k, v := range serverSeesTypes { + t.Logf(" %s: %d occurrences", k, v) + } + + // Verify that nil and empty slice both become nil after protobuf round-trip + // This is the core issue: the server cannot distinguish them + assert.Equal(t, 2, len(serverSeesTypes), + "Expected 2 distinct types after protobuf round-trip (NIL and NON_EMPTY), "+ + "but got %d. This proves protobuf loses the nil vs []byte{} distinction.", + len(serverSeesTypes)) + + assert.Equal(t, 2, serverSeesTypes["NIL"], + "Both nil and []byte{} become NIL on the server (lost distinction)") + assert.Equal(t, 1, serverSeesTypes["NON_EMPTY"], + "Only non-empty slice remains distinguishable") +} + +// TestProtobufEncodingDemonstratesIssue demonstrates the issue in the context +// of how it affects the ledger service. +func TestProtobufEncodingDemonstratesIssue(t *testing.T) { + // Simulate what happens when CommitDelta sends values to remote ledger + originalValues := []struct { + name string + value []byte + }{ + {"nil_from_local_ledger", nil}, + {"empty_slice_from_local_ledger", []byte{}}, + {"non_empty_value", []byte{1, 2, 3}}, + } + + // Step 1: Client creates protobuf messages (what LedgerClient does in client.go:172-174) + protoValues := make([]*ledgerpb.Value, len(originalValues)) + for i, v := range originalValues { + protoValues[i] = &ledgerpb.Value{ + Data: v.value, + } + } + + t.Log("Step 1 - Client creates protobuf messages:") + for i, v := range originalValues { + t.Logf(" [%d] %s: Data=%v (len=%d, isNil=%v)", + i, v.name, protoValues[i].Data, len(protoValues[i].Data), protoValues[i].Data == nil) + } + + // Step 2: gRPC automatically encodes protobuf (happens over the wire) + // In protobuf, empty bytes fields are optional and can be represented as nil + // When []byte{} is encoded, it becomes an empty bytes field + // When decoded, empty bytes fields become nil + + // Step 3: Server receives and decodes (what LedgerService does) + // After gRPC decodes, both nil and []byte{} become nil + t.Log("\nStep 2-3 - After gRPC encoding/decoding (what server sees):") + serverSeesTypes := make(map[string]int) + for i, protoValue := range protoValues { + // Simulate what gRPC/protobuf does: []byte{} becomes nil after round-trip + var serverSees []byte + var typeStr string + + if protoValue.Data == nil { + serverSees = nil + typeStr = "NIL" + } else if len(protoValue.Data) == 0 { + // This is the problem: []byte{} becomes nil after protobuf round-trip + serverSees = nil + typeStr = "NIL" // Lost distinction! + } else { + serverSees = protoValue.Data + typeStr = "NON_EMPTY" + } + + serverSeesTypes[typeStr]++ + t.Logf(" [%d] %s: server sees %s (len=%d, isNil=%v)", + i, originalValues[i].name, typeStr, len(serverSees), serverSees == nil) + } + + // The problem: server can only distinguish 2 types, not 3 + assert.Equal(t, 2, len(serverSeesTypes), + "Server can only distinguish 2 types (NIL and NON_EMPTY), "+ + "not 3 (nil, []byte{}, non-empty). The nil vs []byte{} distinction is lost.") + + // This is why normalization won't work - the server can't tell which was which + t.Log("\nConclusion:") + t.Log(" - Client sends: nil, []byte{}, [1,2,3]") + t.Log(" - Server receives: nil, nil, [1,2,3]") + t.Log(" - Server cannot distinguish between originally nil vs originally []byte{}") + t.Log(" - This causes different TrieUpdate structures and different execution_data_id") + t.Log(" - The fix must happen at CBOR encoding level, not at protobuf level") +} + +// TestProtobufIsNilFieldPreservesDistinction verifies that the IsNil field +// allows the server to distinguish between nil and []byte{} after protobuf round-trip. +func TestProtobufIsNilFieldPreservesDistinction(t *testing.T) { + // Create three different values that should be distinguishable + originalValues := []struct { + name string + value []byte + }{ + {"nil_value", nil}, + {"empty_slice", []byte{}}, + {"non_empty_slice", []byte{1, 2, 3}}, + } + + // Step 1: Client creates protobuf messages with IsNil field (what LedgerClient does) + protoValues := make([]*ledgerpb.Value, len(originalValues)) + for i, v := range originalValues { + isNil := v.value == nil + protoValues[i] = &ledgerpb.Value{ + Data: v.value, + IsNil: isNil, + } + } + + t.Log("Step 1 - Client creates protobuf messages with IsNil field:") + for i, v := range originalValues { + t.Logf(" [%d] %s: Data=%v (len=%d, isNil=%v, IsNil=%v)", + i, v.name, protoValues[i].Data, len(protoValues[i].Data), + protoValues[i].Data == nil, protoValues[i].IsNil) + } + + // Step 2-3: Simulate protobuf encoding/decoding (gRPC does this automatically) + // After protobuf round-trip, Data becomes nil for both nil and []byte{} + // But IsNil field is preserved! + t.Log("\nStep 2-3 - After protobuf encoding/decoding:") + serverReconstructsTypes := make(map[string]int) + for i, protoValue := range protoValues { + // Simulate what happens: Data becomes nil, but IsNil is preserved + var serverSees []byte + var typeStr string + + // Simulate protobuf behavior: empty Data becomes nil after round-trip + if len(protoValue.Data) == 0 { + // Use IsNil to reconstruct original value type + if protoValue.IsNil { + serverSees = nil + typeStr = "NIL" + } else { + serverSees = []byte{} // Reconstruct empty slice + typeStr = "EMPTY_SLICE" + } + } else { + serverSees = protoValue.Data + typeStr = "NON_EMPTY" + } + + serverReconstructsTypes[typeStr]++ + t.Logf(" [%d] %s: server reconstructs %s (len=%d, isNil=%v, IsNil=%v)", + i, originalValues[i].name, typeStr, len(serverSees), serverSees == nil, protoValue.IsNil) + } + + // The fix: server can now distinguish all 3 types! + assert.Equal(t, 3, len(serverReconstructsTypes), + "With IsNil field, server can distinguish 3 types (NIL, EMPTY_SLICE, NON_EMPTY), "+ + "not just 2. The nil vs []byte{} distinction is preserved!") + + assert.Equal(t, 1, serverReconstructsTypes["NIL"], + "nil value is correctly identified as NIL") + assert.Equal(t, 1, serverReconstructsTypes["EMPTY_SLICE"], + "empty slice []byte{} is correctly identified as EMPTY_SLICE (distinction preserved!)") + assert.Equal(t, 1, serverReconstructsTypes["NON_EMPTY"], + "non-empty slice remains distinguishable") + + t.Log("\nConclusion:") + t.Log(" - Client sends: nil (IsNil=true), []byte{} (IsNil=false), [1,2,3] (IsNil=false)") + t.Log(" - After protobuf: Data becomes nil for both nil and []byte{}") + t.Log(" - Server uses IsNil to reconstruct: nil, []byte{}, [1,2,3]") + t.Log(" - All 3 types are now distinguishable!") + t.Log(" - This preserves the distinction needed for deterministic CBOR encoding") +} diff --git a/ledger/remote/service.go b/ledger/remote/service.go new file mode 100644 index 00000000000..b98bdb245a4 --- /dev/null +++ b/ledger/remote/service.go @@ -0,0 +1,252 @@ +package remote + +import ( + "context" + + "github.com/rs/zerolog" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" + + "github.com/onflow/flow-go/ledger" + ledgerpb "github.com/onflow/flow-go/ledger/protobuf" +) + +// Service implements the gRPC LedgerService interface +type Service struct { + ledgerpb.UnimplementedLedgerServiceServer + ledger ledger.Ledger + logger zerolog.Logger +} + +// NewService creates a new ledger service +func NewService(l ledger.Ledger, logger zerolog.Logger) *Service { + return &Service{ + ledger: l, + logger: logger, + } +} + +// InitialState returns the initial state of the ledger +func (s *Service) InitialState(ctx context.Context, req *emptypb.Empty) (*ledgerpb.StateResponse, error) { + state := s.ledger.InitialState() + return &ledgerpb.StateResponse{ + State: &ledgerpb.State{ + Hash: state[:], + }, + }, nil +} + +// HasState checks if the given state exists in the ledger +func (s *Service) HasState(ctx context.Context, req *ledgerpb.StateRequest) (*ledgerpb.HasStateResponse, error) { + if req.State == nil || len(req.State.Hash) != len(ledger.State{}) { + return nil, status.Error(codes.InvalidArgument, "invalid state") + } + + var state ledger.State + copy(state[:], req.State.Hash) + + hasState := s.ledger.HasState(state) + return &ledgerpb.HasStateResponse{ + HasState: hasState, + }, nil +} + +// GetSingleValue returns a single value for a given key at a specific state +func (s *Service) GetSingleValue(ctx context.Context, req *ledgerpb.GetSingleValueRequest) (*ledgerpb.ValueResponse, error) { + if req.State == nil || len(req.State.Hash) != len(ledger.State{}) { + return nil, status.Error(codes.InvalidArgument, "invalid state") + } + + var state ledger.State + copy(state[:], req.State.Hash) + + key, err := protoKeyToLedgerKey(req.Key) + if err != nil { + return nil, err // protoKeyToLedgerKey already returns status.Error + } + + query, err := ledger.NewQuerySingleValue(state, key) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + value, err := s.ledger.GetSingleValue(query) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &ledgerpb.ValueResponse{ + Value: &ledgerpb.Value{ + Data: value, + IsNil: value == nil, + }, + }, nil +} + +// Get returns values for multiple keys at a specific state +func (s *Service) Get(ctx context.Context, req *ledgerpb.GetRequest) (*ledgerpb.GetResponse, error) { + if req.State == nil || len(req.State.Hash) != len(ledger.State{}) { + return nil, status.Error(codes.InvalidArgument, "invalid state") + } + + if len(req.Keys) == 0 { + return nil, status.Error(codes.InvalidArgument, "keys cannot be empty") + } + + var state ledger.State + copy(state[:], req.State.Hash) + + keys := make([]ledger.Key, len(req.Keys)) + for i, protoKey := range req.Keys { + key, err := protoKeyToLedgerKey(protoKey) + if err != nil { + return nil, err // protoKeyToLedgerKey already returns status.Error + } + keys[i] = key + } + + query, err := ledger.NewQuery(state, keys) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + values, err := s.ledger.Get(query) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + protoValues := make([]*ledgerpb.Value, len(values)) + for i, v := range values { + protoValues[i] = &ledgerpb.Value{ + Data: v, + IsNil: v == nil, + } + } + + return &ledgerpb.GetResponse{ + Values: protoValues, + }, nil +} + +// Set updates keys with new values at a specific state and returns the new state +func (s *Service) Set(ctx context.Context, req *ledgerpb.SetRequest) (*ledgerpb.SetResponse, error) { + if req.State == nil || len(req.State.Hash) != len(ledger.State{}) { + return nil, status.Error(codes.InvalidArgument, "invalid state") + } + + if len(req.Keys) == 0 { + return nil, status.Error(codes.InvalidArgument, "keys cannot be empty") + } + + if len(req.Keys) != len(req.Values) { + return nil, status.Error(codes.InvalidArgument, "keys and values length mismatch") + } + + var state ledger.State + copy(state[:], req.State.Hash) + + keys := make([]ledger.Key, len(req.Keys)) + for i, protoKey := range req.Keys { + key, err := protoKeyToLedgerKey(protoKey) + if err != nil { + return nil, err // protoKeyToLedgerKey already returns status.Error + } + keys[i] = key + } + + values := make([]ledger.Value, len(req.Values)) + for i, protoValue := range req.Values { + var value ledger.Value + // Reconstruct the original value type using is_nil flag + // This preserves the distinction between nil and []byte{} that protobuf loses + if len(protoValue.Data) == 0 { + if protoValue.IsNil { + // Original value was nil + value = nil + } else { + // Original value was []byte{} (empty slice) + value = ledger.Value([]byte{}) + } + } else { + // Non-empty value, use data as-is + value = ledger.Value(protoValue.Data) + } + values[i] = value + } + + update, err := ledger.NewUpdate(state, keys, values) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + newState, trieUpdate, err := s.ledger.Set(update) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + // Encode trie update using centralized encoding function to ensure + // client and server use the same encoding method + trieUpdateBytes := encodeTrieUpdateForTransport(trieUpdate) + + return &ledgerpb.SetResponse{ + NewState: &ledgerpb.State{ + Hash: newState[:], + }, + TrieUpdate: trieUpdateBytes, + }, nil +} + +// Prove returns proofs for the given keys at a specific state +func (s *Service) Prove(ctx context.Context, req *ledgerpb.ProveRequest) (*ledgerpb.ProofResponse, error) { + if req.State == nil || len(req.State.Hash) != len(ledger.State{}) { + return nil, status.Error(codes.InvalidArgument, "invalid state") + } + + if len(req.Keys) == 0 { + return nil, status.Error(codes.InvalidArgument, "keys cannot be empty") + } + + var state ledger.State + copy(state[:], req.State.Hash) + + keys := make([]ledger.Key, len(req.Keys)) + for i, protoKey := range req.Keys { + key, err := protoKeyToLedgerKey(protoKey) + if err != nil { + return nil, err // protoKeyToLedgerKey already returns status.Error + } + keys[i] = key + } + + query, err := ledger.NewQuery(state, keys) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + proof, err := s.ledger.Prove(query) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &ledgerpb.ProofResponse{ + Proof: proof, + }, nil +} + +// protoKeyToLedgerKey converts a protobuf Key to a ledger.Key +func protoKeyToLedgerKey(protoKey *ledgerpb.Key) (ledger.Key, error) { + if protoKey == nil { + return ledger.Key{}, status.Error(codes.InvalidArgument, "key is nil") + } + + keyParts := make([]ledger.KeyPart, len(protoKey.Parts)) + for i, part := range protoKey.Parts { + if part.Type > 65535 { + return ledger.Key{}, status.Error(codes.InvalidArgument, "key part type exceeds uint16") + } + keyParts[i] = ledger.NewKeyPart(uint16(part.Type), part.Value) + } + + return ledger.NewKey(keyParts), nil +} diff --git a/ledger/trie.go b/ledger/trie.go index 94224dc7185..386095a2923 100644 --- a/ledger/trie.go +++ b/ledger/trie.go @@ -266,13 +266,32 @@ type serializablePayload struct { Value Value } +func (p Payload) seralizable() (serializablePayload, error) { + k, err := p.Key() + if err != nil { + return serializablePayload{}, err + } + + v := p.value + if v == nil { + // Normalize nil payload values to empty slice (Value{}) to ensure consistency + // across all serialization formats (checkpoint files, WAL files, and execution data). + // This eliminates the distinction between nil and empty slice values, as both represent + // the removal of a register from the execution state. When an execution node loads a trie, + // it first reads checkpoint files and then WAL files, during which nil values are normalized + // to []byte{}. By normalizing at payload encoding time, we ensure all code paths produce + // consistent encoded data regardless of whether the original value was nil or []byte{}. + v = Value{} + } + return serializablePayload{Key: k, Value: v}, nil +} + // MarshalJSON returns JSON encoding of p. func (p Payload) MarshalJSON() ([]byte, error) { - k, err := p.Key() + sp, err := p.seralizable() if err != nil { return nil, err } - sp := serializablePayload{Key: k, Value: p.value} return json.Marshal(sp) } @@ -292,11 +311,10 @@ func (p *Payload) UnmarshalJSON(b []byte) error { // MarshalCBOR returns CBOR encoding of p. func (p Payload) MarshalCBOR() ([]byte, error) { - k, err := p.Key() + sp, err := p.seralizable() if err != nil { return nil, err } - sp := serializablePayload{Key: k, Value: p.value} return cbor.Marshal(sp) } @@ -363,6 +381,8 @@ func (p *Payload) Address() (flow.Address, error) { // Value returns payload value. // CAUTION: do not modify returned value because it shares underlying data with payload value. +// CAUTION: to check wheather the payload value is empty, use len(payload.Value()) == 0, +// due to normalization of nil and empty slice values in payloads during serialization. func (p *Payload) Value() Value { if p == nil { return Value{} @@ -539,7 +559,7 @@ func NewTrieBatchProof() *TrieBatchProof { func NewTrieBatchProofWithEmptyProofs(numberOfProofs int) *TrieBatchProof { bp := new(TrieBatchProof) bp.Proofs = make([]*TrieProof, numberOfProofs) - for i := 0; i < numberOfProofs; i++ { + for i := range numberOfProofs { bp.Proofs[i] = NewTrieProof() } return bp diff --git a/ledger/trie_encoder.go b/ledger/trie_encoder.go index 442bb46e28a..d7bc6f98438 100644 --- a/ledger/trie_encoder.go +++ b/ledger/trie_encoder.go @@ -3,6 +3,8 @@ package ledger import ( "fmt" + "github.com/fxamacker/cbor/v2" + "github.com/onflow/flow-go/ledger/common/bitutils" "github.com/onflow/flow-go/ledger/common/hash" "github.com/onflow/flow-go/ledger/common/utils" @@ -540,6 +542,12 @@ func decodePayload(inp []byte, zeroCopy bool, version uint16) (*Payload, error) return nil, fmt.Errorf("error decoding payload: %w", err) } + // Normalize nil to empty slice for deterministic CBOR serialization + // ReadSlice returns nil when size is 0, but we need []byte{} for consistency + if encValue == nil { + encValue = []byte{} + } + if zeroCopy { return &Payload{encKey, encValue}, nil } @@ -688,6 +696,39 @@ func decodeTrieUpdate(inp []byte, version uint16) (*TrieUpdate, error) { return &TrieUpdate{RootHash: rh, Paths: paths, Payloads: payloads}, nil } +// EncodeTrieUpdateCBOR encodes a trie update struct using CBOR encoding. +// CBOR encoding preserves the distinction between nil and []byte{} values in payloads +// because Payload has MarshalCBOR/UnmarshalCBOR methods that handle this correctly. +func EncodeTrieUpdateCBOR(t *TrieUpdate) []byte { + if t == nil { + return []byte{} + } + + encoded, err := cbor.Marshal(t) + if err != nil { + // This should not happen in normal operation + panic(fmt.Errorf("failed to encode trie update with CBOR: %w", err)) + } + + return encoded +} + +// DecodeTrieUpdateCBOR constructs a trie update from a CBOR-encoded byte slice. +// CBOR encoding preserves the distinction between nil and []byte{} values in payloads +// because Payload has MarshalCBOR/UnmarshalCBOR methods that handle this correctly. +func DecodeTrieUpdateCBOR(encodedTrieUpdate []byte) (*TrieUpdate, error) { + if len(encodedTrieUpdate) == 0 { + return nil, nil + } + + var tu TrieUpdate + if err := cbor.Unmarshal(encodedTrieUpdate, &tu); err != nil { + return nil, fmt.Errorf("error decoding trie update with CBOR: %w", err) + } + + return &tu, nil +} + // EncodeTrieProof encodes the content of a proof into a byte slice func EncodeTrieProof(p *TrieProof) []byte { if p == nil { diff --git a/ledger/trie_encoder_test.go b/ledger/trie_encoder_test.go index 60298cf4fe3..f1094ffb383 100644 --- a/ledger/trie_encoder_test.go +++ b/ledger/trie_encoder_test.go @@ -5,11 +5,13 @@ import ( "encoding/hex" "testing" + "github.com/golang/protobuf/proto" "github.com/stretchr/testify/require" "github.com/onflow/flow-go/ledger" "github.com/onflow/flow-go/ledger/common/hash" "github.com/onflow/flow-go/ledger/common/testutils" + ledgerpb "github.com/onflow/flow-go/ledger/protobuf" ) // TestKeyPartSerialization tests encoding and decoding functionality of a ledger key part @@ -368,7 +370,7 @@ func TestPayloadWithoutPrefixSerialization(t *testing.T) { require.Equal(t, p, decodedp) // Reset encoded payload - for i := 0; i < len(encoded); i++ { + for i := range encoded { encoded[i] = 0 } @@ -616,3 +618,266 @@ func TestTrieUpdateSerialization(t *testing.T) { require.True(t, decodedtu.Equals(tu)) }) } + +// TestTrieUpdateNilVsEmptySlice verifies that EncodeTrieUpdate/DecodeTrieUpdate +// does not distinguish between nil and []byte{} values in payloads. +func TestTrieUpdateNilVsEmptySlice(t *testing.T) { + p1 := testutils.PathByUint16(1) + kp1 := ledger.NewKeyPart(uint16(1), []byte("key 1")) + k1 := ledger.NewKey([]ledger.KeyPart{kp1}) + // Original value is nil, but will be normalized to []byte{} + pl1 := ledger.NewPayload(k1, nil) + + p2 := testutils.PathByUint16(2) + kp2 := ledger.NewKeyPart(uint16(1), []byte("key 2")) + k2 := ledger.NewKey([]ledger.KeyPart{kp2}) + // Original value is []byte{} + pl2 := ledger.NewPayload(k2, []byte{}) + + tu := &ledger.TrieUpdate{ + RootHash: testutils.RootHashFixture(), + Paths: []ledger.Path{p1, p2}, + Payloads: []*ledger.Payload{pl1, pl2}, + } + + // Step 1: Verify original distinction + require.Nil(t, tu.Payloads[0].Value(), "Payload 0 should have nil value") + require.NotNil(t, tu.Payloads[1].Value(), "Payload 1 should have non-nil value") + require.Equal(t, 0, len(tu.Payloads[1].Value()), "Payload 1 should have 0 length") + + // Step 2: Encode and Decode + encoded := ledger.EncodeTrieUpdate(tu) + decoded, err := ledger.DecodeTrieUpdate(encoded) + require.NoError(t, err) + + // Step 3: Verify distinction is lost + // Both will be []byte{} after decode due to normalization in decodePayload. + // Even if we removed the normalization, both would be nil because ReadSlice(0) returns nil. + // This proves EncodeTrieUpdate/DecodeTrieUpdate does not distinguish between nil and []byte{}. + t.Logf("Decoded Payload 0 value: %v (isNil=%v)", decoded.Payloads[0].Value(), decoded.Payloads[0].Value() == nil) + t.Logf("Decoded Payload 1 value: %v (isNil=%v)", decoded.Payloads[1].Value(), decoded.Payloads[1].Value() == nil) + + require.Equal(t, 0, len(decoded.Payloads[0].Value()), "Decoded Payload 0 should have 0 length") + require.Equal(t, 0, len(decoded.Payloads[1].Value()), "Decoded Payload 1 should have 0 length") + + // The key assertion: they are now identical despite starting differently + require.Equal(t, decoded.Payloads[0].Value(), decoded.Payloads[1].Value(), + "Decoded nil and []byte{} are now identical (loss of distinction)") +} + +// TestTrieUpdateCBORNilVsEmptySlice verifies that EncodeTrieUpdateCBOR/DecodeTrieUpdateCBOR +// does not distinction between nil and []byte{} values in payloads after normalization +func TestTrieUpdateCBORNilVsEmptySlice(t *testing.T) { + t.Parallel() + p1 := testutils.PathByUint16(1) + kp1 := ledger.NewKeyPart(uint16(1), []byte("key 1")) + k1 := ledger.NewKey([]ledger.KeyPart{kp1}) + // Original value is nil + pl1 := ledger.NewPayload(k1, nil) + + p2 := testutils.PathByUint16(2) + kp2 := ledger.NewKeyPart(uint16(1), []byte("key 2")) + k2 := ledger.NewKey([]ledger.KeyPart{kp2}) + // Original value is []byte{} + pl2 := ledger.NewPayload(k2, []byte{}) + + tu := &ledger.TrieUpdate{ + RootHash: testutils.RootHashFixture(), + Paths: []ledger.Path{p1, p2}, + Payloads: []*ledger.Payload{pl1, pl2}, + } + + // Step 1: Verify original distinction + require.Nil(t, tu.Payloads[0].Value(), "Payload 0 should have nil value") + require.NotNil(t, tu.Payloads[1].Value(), "Payload 1 should have non-nil value") + require.Equal(t, 0, len(tu.Payloads[1].Value()), "Payload 1 should have 0 length") + + // Step 2: Encode and Decode using CBOR + encoded := ledger.EncodeTrieUpdateCBOR(tu) + decoded, err := ledger.DecodeTrieUpdateCBOR(encoded) + require.NoError(t, err) + + // Step 3: Verify distinction is preserved with CBOR encoding + t.Logf("Decoded Payload 0 value: %v (isNil=%v)", decoded.Payloads[0].Value(), decoded.Payloads[0].Value() == nil) + t.Logf("Decoded Payload 1 value: %v (isNil=%v)", decoded.Payloads[1].Value(), decoded.Payloads[1].Value() == nil) + + // Verify that []byte{} is preserved as []byte{} + require.NotNil(t, decoded.Payloads[0].Value(), "Decoded Payload 0 should have nil value") + require.Equal(t, 0, len(decoded.Payloads[0].Value()), "Decoded Payload 0 should have 0 length") + require.NotNil(t, decoded.Payloads[1].Value(), "Decoded Payload 1 should have non-nil value") + require.Equal(t, 0, len(decoded.Payloads[1].Value()), "Decoded Payload 1 should have 0 length") + + // The key assertion: they should be the same after encoding/decoding due to normalization in encoding + require.Equal(t, decoded.Payloads[0].Value(), decoded.Payloads[1].Value(), + "Decoded nil and []byte{} should remain distinct with CBOR encoding") +} + +// TestTrieUpdateCBORRoundTrip tests that EncodeTrieUpdateCBOR and DecodeTrieUpdateCBOR +// correctly round-trip various TrieUpdate configurations. +func TestTrieUpdateCBORRoundTrip(t *testing.T) { + t.Parallel() + t.Run("empty trie update", func(t *testing.T) { + t.Parallel() + tu := &ledger.TrieUpdate{ + RootHash: testutils.RootHashFixture(), + Paths: []ledger.Path{}, + Payloads: []*ledger.Payload{}, + } + + encoded := ledger.EncodeTrieUpdateCBOR(tu) + decoded, err := ledger.DecodeTrieUpdateCBOR(encoded) + require.NoError(t, err) + require.True(t, tu.Equals(decoded)) + }) + + t.Run("single payload with nil value", func(t *testing.T) { + t.Parallel() + p1 := testutils.PathByUint16(1) + kp1 := ledger.NewKeyPart(uint16(1), []byte("key 1")) + k1 := ledger.NewKey([]ledger.KeyPart{kp1}) + pl1 := ledger.NewPayload(k1, nil) + + tu := &ledger.TrieUpdate{ + RootHash: testutils.RootHashFixture(), + Paths: []ledger.Path{p1}, + Payloads: []*ledger.Payload{pl1}, + } + + encoded := ledger.EncodeTrieUpdateCBOR(tu) + decoded, err := ledger.DecodeTrieUpdateCBOR(encoded) + require.NoError(t, err) + require.True(t, tu.Equals(decoded)) + require.NotNil(t, decoded.Payloads[0].Value(), "Nil value should be normalized to empty slice") + }) + + t.Run("single payload with empty slice value", func(t *testing.T) { + t.Parallel() + p1 := testutils.PathByUint16(1) + kp1 := ledger.NewKeyPart(uint16(1), []byte("key 1")) + k1 := ledger.NewKey([]ledger.KeyPart{kp1}) + pl1 := ledger.NewPayload(k1, []byte{}) + + tu := &ledger.TrieUpdate{ + RootHash: testutils.RootHashFixture(), + Paths: []ledger.Path{p1}, + Payloads: []*ledger.Payload{pl1}, + } + + encoded := ledger.EncodeTrieUpdateCBOR(tu) + decoded, err := ledger.DecodeTrieUpdateCBOR(encoded) + require.NoError(t, err) + require.True(t, tu.Equals(decoded)) + require.NotNil(t, decoded.Payloads[0].Value(), "Empty slice value should be preserved as non-nil") + require.Equal(t, 0, len(decoded.Payloads[0].Value()), "Empty slice should have 0 length") + }) + + t.Run("multiple payloads with mixed nil and non-nil values", func(t *testing.T) { + t.Parallel() + p1 := testutils.PathByUint16(1) + kp1 := ledger.NewKeyPart(uint16(1), []byte("key 1")) + k1 := ledger.NewKey([]ledger.KeyPart{kp1}) + pl1 := ledger.NewPayload(k1, nil) + + p2 := testutils.PathByUint16(2) + kp2 := ledger.NewKeyPart(uint16(1), []byte("key 2")) + k2 := ledger.NewKey([]ledger.KeyPart{kp2}) + pl2 := ledger.NewPayload(k2, []byte{}) + + p3 := testutils.PathByUint16(3) + kp3 := ledger.NewKeyPart(uint16(1), []byte("key 3")) + k3 := ledger.NewKey([]ledger.KeyPart{kp3}) + pl3 := ledger.NewPayload(k3, []byte{1, 2, 3}) + + tu := &ledger.TrieUpdate{ + RootHash: testutils.RootHashFixture(), + Paths: []ledger.Path{p1, p2, p3}, + Payloads: []*ledger.Payload{pl1, pl2, pl3}, + } + + encoded := ledger.EncodeTrieUpdateCBOR(tu) + decoded, err := ledger.DecodeTrieUpdateCBOR(encoded) + require.NoError(t, err) + require.True(t, tu.Equals(decoded)) + + // Verify each value type is preserved + require.NotNil(t, decoded.Payloads[0].Value(), "First payload should have no-nil empty slice after normalization") + require.Equal(t, 0, len(decoded.Payloads[0].Value()), "First payload should have 0 length") + require.NotNil(t, decoded.Payloads[1].Value(), "Second payload should have non-nil empty slice") + require.Equal(t, 0, len(decoded.Payloads[1].Value()), "Second payload should have 0 length") + require.NotNil(t, decoded.Payloads[2].Value(), "Third payload should have non-nil value") + require.Equal(t, ledger.Value([]byte{1, 2, 3}), decoded.Payloads[2].Value(), "Third payload should have correct value") + }) + + t.Run("nil trie update", func(t *testing.T) { + t.Parallel() + encoded := ledger.EncodeTrieUpdateCBOR(nil) + require.Equal(t, []byte{}, encoded) + + decoded, err := ledger.DecodeTrieUpdateCBOR([]byte{}) + require.NoError(t, err) + require.Nil(t, decoded) + }) +} + +// TestTrieUpdateEncodingMethodsPreservesValueTypes tests that all three encoding methods +// (EncodeTrieUpdate/DecodeTrieUpdate, EncodeTrieUpdateCBOR/DecodeTrieUpdateCBOR, and protobuf) +// correctly preserve nil, empty slice, and non-empty slice values in payloads after round-trip encoding/decoding. +func TestTrieUpdateEncodingMethodsPreservesValueTypes(t *testing.T) { + t.Parallel() + + // Create a TrieUpdate with three payloads: nil, empty slice, and non-empty slice + p1 := testutils.PathByUint16(1) + kp1 := ledger.NewKeyPart(uint16(1), []byte("key 1")) + k1 := ledger.NewKey([]ledger.KeyPart{kp1}) + pl1 := ledger.NewPayload(k1, nil) // nil value + + p2 := testutils.PathByUint16(2) + kp2 := ledger.NewKeyPart(uint16(1), []byte("key 2")) + k2 := ledger.NewKey([]ledger.KeyPart{kp2}) + pl2 := ledger.NewPayload(k2, []byte{}) // empty slice value + + p3 := testutils.PathByUint16(3) + kp3 := ledger.NewKeyPart(uint16(1), []byte("key 3")) + k3 := ledger.NewKey([]ledger.KeyPart{kp3}) + pl3 := ledger.NewPayload(k3, []byte{1, 2, 3}) // non-empty slice value + + originalTU := &ledger.TrieUpdate{ + RootHash: testutils.RootHashFixture(), + Paths: []ledger.Path{p1, p2, p3}, + Payloads: []*ledger.Payload{pl1, pl2, pl3}, + } + + // Verify all three methods produce equivalent results for the non-empty value + t.Run("all methods produce equivalent results", func(t *testing.T) { + t.Parallel() + + // Encode using all three methods + encoded1 := ledger.EncodeTrieUpdate(originalTU) + encoded2 := ledger.EncodeTrieUpdateCBOR(originalTU) + trieUpdateBytes := ledger.EncodeTrieUpdateCBOR(originalTU) + setResponse := &ledgerpb.SetResponse{ + TrieUpdate: trieUpdateBytes, + } + encoded3, err := proto.Marshal(setResponse) + require.NoError(t, err) + + // Decode all three + decoded1, err := ledger.DecodeTrieUpdate(encoded1) + require.NoError(t, err) + + decoded2, err := ledger.DecodeTrieUpdateCBOR(encoded2) + require.NoError(t, err) + + var protoDecoded ledgerpb.SetResponse + err = proto.Unmarshal(encoded3, &protoDecoded) + require.NoError(t, err) + decoded3, err := ledger.DecodeTrieUpdateCBOR(protoDecoded.TrieUpdate) + require.NoError(t, err) + + // All three should produce the same non-empty value + require.Equal(t, decoded1.Payloads[2].Value(), decoded2.Payloads[2].Value(), "Method 1 and 2 should produce same non-empty value") + require.Equal(t, decoded2.Payloads[2].Value(), decoded3.Payloads[2].Value(), "Method 2 and 3 should produce same non-empty value") + require.Equal(t, decoded1, decoded2, "EncodeTrieUpdate and EncodeTrieUpdateCBOR should produce same TrieUpdate") + require.Equal(t, decoded2, decoded3, "EncodeTrieUpdateCBOR and EncodeTrieUpdateProtoBuf should produce same TrieUpdate") + }) +} diff --git a/ledger/trie_test.go b/ledger/trie_test.go index 3b5e6031da4..78b3dbe39ce 100644 --- a/ledger/trie_test.go +++ b/ledger/trie_test.go @@ -409,7 +409,7 @@ func TestPayloadJSONSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with JSON-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } @@ -421,6 +421,11 @@ func TestPayloadJSONSerialization(t *testing.T) { v2 := p2.Value() require.True(t, v2.Equals(Value{})) + + // after decoding, the value will be normalized to []byte{} + // which will be different from the original format + require.True(t, p.value == nil) + require.True(t, p2.value != nil) }) t.Run("empty key", func(t *testing.T) { @@ -438,7 +443,7 @@ func TestPayloadJSONSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with JSON-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } @@ -467,7 +472,7 @@ func TestPayloadJSONSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with JSON-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } @@ -496,7 +501,7 @@ func TestPayloadJSONSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with JSON-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } @@ -537,12 +542,13 @@ func TestPayloadCBORSerialization(t *testing.T) { 0xf6, // null 0x65, // text(5) 0x56, 0x61, 0x6c, 0x75, 0x65, // "Value" - 0xf6, // null + 0x40, // null will be normalized to []byte{} } var p Payload b, err := cbor.Marshal(p) require.NoError(t, err) + require.True(t, p.value == nil) require.Equal(t, encoded, b) var p2 Payload @@ -550,7 +556,7 @@ func TestPayloadCBORSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with CBOR-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } @@ -562,6 +568,11 @@ func TestPayloadCBORSerialization(t *testing.T) { v2 := p2.Value() require.True(t, v2.Equals(Value{})) + + // after decoding, the value will be normalized to []byte{} + // which will be different from the original format + require.True(t, p.value == nil) + require.True(t, p2.value != nil) }) t.Run("empty key", func(t *testing.T) { @@ -591,7 +602,7 @@ func TestPayloadCBORSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with CBOR-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } @@ -624,7 +635,7 @@ func TestPayloadCBORSerialization(t *testing.T) { 0x01, 0x02, // "\u0001\u0002" 0x65, // text(5) 0x56, 0x61, 0x6c, 0x75, 0x65, // "Value" - 0xf6, // null + 0x40, // null will be normalized to []byte{} } k := Key{KeyParts: []KeyPart{{1, []byte{1, 2}}}} @@ -639,7 +650,7 @@ func TestPayloadCBORSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with CBOR-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } @@ -688,7 +699,7 @@ func TestPayloadCBORSerialization(t *testing.T) { require.NoError(t, err) // Reset b to make sure that p2 doesn't share underlying data with CBOR-encoded data. - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } diff --git a/model/access/account_transaction.go b/model/access/account_transaction.go new file mode 100644 index 00000000000..24819d0922c --- /dev/null +++ b/model/access/account_transaction.go @@ -0,0 +1,88 @@ +package access + +import ( + "fmt" + + "github.com/onflow/flow-go/model/flow" +) + +type TransactionRole int + +const ( + // CAUTION: these values are stored in the database. Do not change the values. + TransactionRoleAuthorizer TransactionRole = 0 // Account is an authorizer for the transaction + TransactionRolePayer TransactionRole = 1 // Account is the payer for the transaction + TransactionRoleProposer TransactionRole = 2 // Account is the proposer for the transaction + TransactionRoleInteracted TransactionRole = 3 // Account is referenced by an event in the transaction +) + +var ( + transactionRoles = map[TransactionRole]string{ + TransactionRoleAuthorizer: "authorizer", + TransactionRolePayer: "payer", + TransactionRoleProposer: "proposer", + TransactionRoleInteracted: "interacted", + } +) + +// String returns the string representation of a [TransactionRole] matching the OpenAPI spec +// enum values: "authorizer", "payer", "proposer", "interacted". +// +// Panics on unknown values since roles are stored in the database and unknown values indicate +// data corruption. +func (r TransactionRole) String() string { + role, ok := transactionRoles[r] + if !ok { + panic(fmt.Sprintf("unknown TransactionRole: %d", int(r))) + } + return role +} + +// ParseTransactionRole parses a string into a [TransactionRole]. Accepted values match the +// OpenAPI spec enum: "authorizer", "payer", "proposer", "interacted". +// +// Returns an error when the input string does not match any known role name. +func ParseTransactionRole(s string) (TransactionRole, error) { + switch s { + case transactionRoles[TransactionRoleAuthorizer]: + return TransactionRoleAuthorizer, nil + case transactionRoles[TransactionRolePayer]: + return TransactionRolePayer, nil + case transactionRoles[TransactionRoleProposer]: + return TransactionRoleProposer, nil + case transactionRoles[TransactionRoleInteracted]: + return TransactionRoleInteracted, nil + default: + return 0, fmt.Errorf("unknown transaction role: %q", s) + } +} + +// AccountTransaction represents a transaction entry from the account transaction index. +// It contains the essential fields needed to identify and locate a transaction, +// plus metadata about the account's participation. +type AccountTransaction struct { + Address flow.Address // Account address + BlockHeight uint64 // Block height where transaction was included + BlockTimestamp uint64 // Block timestamp where transaction was included, in Unix milliseconds + TransactionID flow.Identifier // Transaction identifier + TransactionIndex uint32 // Index of transaction within the block + Roles []TransactionRole // Roles of the account in the transaction + + // Expansion fields populated when expandResults is true. + Transaction *flow.TransactionBody `msgpack:"-"` // Transaction body (nil unless expanded) + Result *TransactionResult `msgpack:"-"` // Transaction result (nil unless expanded) +} + +// AccountTransactionCursor identifies a position in the account transaction index for +// cursor-based pagination. It corresponds to the last entry returned in a previous page. +type AccountTransactionCursor struct { + Address flow.Address // Account address + BlockHeight uint64 // Block height of the last returned entry + TransactionIndex uint32 // Transaction index within the block of the last returned entry +} + +// AccountTransactionsPage represents a single page of account transaction results. +type AccountTransactionsPage struct { + Transactions []AccountTransaction // Transactions in this page (descending order by height) + NextCursor *AccountTransactionCursor // Cursor to fetch the next page, nil when no more results +} diff --git a/model/access/account_transfer.go b/model/access/account_transfer.go new file mode 100644 index 00000000000..958277223e2 --- /dev/null +++ b/model/access/account_transfer.go @@ -0,0 +1,64 @@ +package access + +import ( + "math/big" + + "github.com/onflow/flow-go/model/flow" +) + +// FungibleTokenTransfer represents a fungible token transfer event extracted from block execution data. +// Each transfer is identified by its position within the block (TransactionIndex, EventIndex). +type FungibleTokenTransfer struct { + TransactionID flow.Identifier // Transaction that produced the transfer event + BlockHeight uint64 // Block height where the transaction was included + BlockTimestamp uint64 // Block timestamp where the transaction was included + TransactionIndex uint32 // Index of the transaction within the block + EventIndices []uint32 // Index of the event within the transaction + TokenType string // Fully qualified token type identifier (e.g., "A.0x1654653399040a61.FlowToken") + Amount *big.Int // Amount of tokens transferred + SourceAddress flow.Address // Account that sent the tokens + RecipientAddress flow.Address // Account that received the tokens + + // Expansion fields populated when expandResults is true. + Transaction *flow.TransactionBody `msgpack:"-"` // Transaction body (nil unless expanded) + Result *TransactionResult `msgpack:"-"` // Transaction result (nil unless expanded) +} + +// NonFungibleTokenTransfer represents a non-fungible token transfer event extracted from block execution data. +// Each transfer is identified by its position within the block (TransactionIndex, EventIndex). +type NonFungibleTokenTransfer struct { + TransactionID flow.Identifier // Transaction that produced the transfer event + BlockHeight uint64 // Block height where the transaction was included + BlockTimestamp uint64 // Block timestamp where the transaction was included + TransactionIndex uint32 // Index of the transaction within the block + EventIndices []uint32 // Index of the event within the transaction + TokenType string // Fully qualified type of NFT collection (e.g., "A.0x1654653399040a61.MyNFT") + ID uint64 // Unique identifier of the NFT within its collection + SourceAddress flow.Address // Account that sent the token + RecipientAddress flow.Address // Account that received the token + + // Expansion fields populated when expandResults is true. + Transaction *flow.TransactionBody `msgpack:"-"` // Transaction body (nil unless expanded) + Result *TransactionResult `msgpack:"-"` // Transaction result (nil unless expanded) +} + +// TransferCursor identifies a position in the token transfer index for cursor-based pagination. +// It corresponds to the last entry returned in a previous page. +type TransferCursor struct { + Address flow.Address // Account address + BlockHeight uint64 // Block height of the last returned entry + TransactionIndex uint32 // Transaction index within the block of the last returned entry + EventIndex uint32 // Event index within the transaction of the last returned entry +} + +// FungibleTokenTransfersPage represents a single page of fungible token transfer results. +type FungibleTokenTransfersPage struct { + Transfers []FungibleTokenTransfer // Transfers in this page (descending order by height) + NextCursor *TransferCursor // Cursor to fetch the next page, nil when no more results +} + +// NonFungibleTokenTransfersPage represents a single page of non-fungible token transfer results. +type NonFungibleTokenTransfersPage struct { + Transfers []NonFungibleTokenTransfer // Transfers in this page (descending order by height) + NextCursor *TransferCursor // Cursor to fetch the next page, nil when no more results +} diff --git a/model/access/contract_deployment.go b/model/access/contract_deployment.go new file mode 100644 index 00000000000..b9fdd69f98b --- /dev/null +++ b/model/access/contract_deployment.go @@ -0,0 +1,109 @@ +package access + +import ( + "crypto/sha3" + "fmt" + "strings" + + "github.com/onflow/flow-go/model/flow" +) + +const ( + // MinContractIDLength is the minimum length of a valid contract ID. + // The format is "A.{address_hex}.{name}". + MinContractIDLength = 4 + 2*flow.AddressLength +) + +// ContractDeployment is a point-in-time snapshot of a contract on-chain. +// Each deployment (add or update) produces a distinct ContractDeployment record. +type ContractDeployment struct { + // Address is the account that owns the contract. + Address flow.Address + // ContractName is the unqualified contract name, derived from ContractID. + ContractName string + // BlockHeight is the block height at which this deployment was applied. + BlockHeight uint64 + // TransactionID is the ID of the transaction that applied this deployment. + TransactionID flow.Identifier + // TransactionIndex is the position of the deploying transaction within its block. + TransactionIndex uint32 + // EventIndex is the position of the contract event within its transaction. + // Needed to uniquely identify a deployment when a single transaction deploys multiple contracts. + EventIndex uint32 + // Code is the Cadence source code of the contract at the time of deployment. + // May be nil if code could not be extracted from the transaction body. + Code []byte + // CodeHash is the SHA3-256 hash of the contract code, as reported in the protocol event. + CodeHash []byte + + // IsDeleted is true if the contract was deleted. + // Deleting contracts is not currently supported by the protocol, however there are contracts on + // mainnet that are deleted. + IsDeleted bool + + // IsPlaceholder is true if the deployment was created during bootstrapping based on the current + // chain state, and not based on a protocol event. + // When true, the BlockHeight, TransactionID, TxIndex, and EventIndex fields are undefined. + IsPlaceholder bool + + // Expansion fields populated when expandResults is true. Never persisted. + Transaction *flow.TransactionBody `msgpack:"-"` // Transaction body (nil unless expanded) + Result *TransactionResult `msgpack:"-"` // Transaction result (nil unless expanded) +} + +// ContractID constructs the canonical contract ID string from an address and contract name. +// Format: "A.{address_hex}.{name}" +func ContractID(address flow.Address, name string) string { + return "A." + address.Hex() + "." + name +} + +// ParseContractID extracts the address and contract name from a contract identifier of the form +// "A.{address_hex}.{name}". +// +// Any error indicates the contractID is not in the expected format. +func ParseContractID(id string) (flow.Address, string, error) { + if len(id) < MinContractIDLength || id[:2] != "A." { + return flow.Address{}, "", fmt.Errorf("unexpected contract ID format: %q", id) + } + addr, name, ok := strings.Cut(id[2:], ".") // strip "A." then split on "." + if !ok { + return flow.Address{}, "", fmt.Errorf("unexpected contract ID format (no second dot): %q", id) + } + address, err := flow.StringToAddress(addr) + if err != nil { + return flow.Address{}, "", fmt.Errorf("invalid address in contract ID %q: %w", id, err) + } + if strings.Contains(name, ".") { + return flow.Address{}, "", fmt.Errorf("contract name is invalid: %q", name) + } + return address, name, nil +} + +// CadenceCodeHash calculates the SHA3-256 hash of the provided code using the same algorithm as Cadence. +func CadenceCodeHash(code []byte) []byte { + hash := sha3.Sum256(code) + return hash[:] +} + +// ContractDeploymentsCursor is the single pagination cursor type for all contract index iterators. +type ContractDeploymentsCursor struct { + // Address is the account that owns the contract. + Address flow.Address + // ContractName is the unqualified contract name. + ContractName string + // BlockHeight is the block height of the last returned deployment. + BlockHeight uint64 + // TransactionIndex is the position of the deploying transaction within its block. + TransactionIndex uint32 + // EventIndex is the position of the contract event within its transaction. + EventIndex uint32 +} + +// ContractDeploymentPage is a page of deployment history for a single contract. +// Returned by GetContractDeployments. +type ContractDeploymentPage struct { + // Deployments is the ordered list of deployments for this page. + Deployments []ContractDeployment + // NextCursor is nil when no more results exist. + NextCursor *ContractDeploymentsCursor +} diff --git a/model/access/contract_deployment_test.go b/model/access/contract_deployment_test.go new file mode 100644 index 00000000000..8347b6127f3 --- /dev/null +++ b/model/access/contract_deployment_test.go @@ -0,0 +1,67 @@ +package access_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +func TestContractID(t *testing.T) { + addr := flow.HexToAddress("0000000000000001") + id := access.ContractID(addr, "Foo") + assert.Equal(t, "A.0000000000000001.Foo", id) +} + +func TestParseContractID(t *testing.T) { + addr := flow.HexToAddress("0000000000000001") + + t.Run("valid ID", func(t *testing.T) { + gotAddr, gotName, err := access.ParseContractID("A.0000000000000001.Foo") + require.NoError(t, err) + assert.Equal(t, addr, gotAddr) + assert.Equal(t, "Foo", gotName) + }) + + t.Run("name with dots is invalid", func(t *testing.T) { + _, _, err := access.ParseContractID("A.0000000000000001.Foo.Bar") + require.Error(t, err) + }) + + t.Run("roundtrip with ContractID", func(t *testing.T) { + id := access.ContractID(addr, "MyContract") + gotAddr, gotName, err := access.ParseContractID(id) + require.NoError(t, err) + assert.Equal(t, addr, gotAddr) + assert.Equal(t, "MyContract", gotName) + }) + + t.Run("empty string", func(t *testing.T) { + _, _, err := access.ParseContractID("") + require.Error(t, err) + }) + + t.Run("too short", func(t *testing.T) { + _, _, err := access.ParseContractID("A.0000000000000001") // no name segment + require.Error(t, err) + }) + + t.Run("wrong prefix", func(t *testing.T) { + _, _, err := access.ParseContractID("B.0000000000000001.Foo") + require.Error(t, err) + }) + + t.Run("no second dot", func(t *testing.T) { + // "A." + 18 chars (no second dot) = 20 chars, passes length check + _, _, err := access.ParseContractID("A.0000000000000001x") + require.Error(t, err) + }) + + t.Run("invalid hex address", func(t *testing.T) { + _, _, err := access.ParseContractID("A.zzzzzzzzzzzzzzzz.Foo") + require.Error(t, err) + }) +} diff --git a/model/access/scheduled_transaction.go b/model/access/scheduled_transaction.go new file mode 100644 index 00000000000..31297b5ae4d --- /dev/null +++ b/model/access/scheduled_transaction.go @@ -0,0 +1,160 @@ +package access + +import ( + "fmt" + "strings" + + "github.com/onflow/flow-go/model/flow" +) + +// ScheduledTransactionStatus represents the lifecycle state of a scheduled transaction. +type ScheduledTransactionStatus int8 + +const ( + ScheduledTxStatusScheduled ScheduledTransactionStatus = iota + ScheduledTxStatusExecuted + ScheduledTxStatusCancelled + ScheduledTxStatusFailed +) + +var scheduledTransactionStatusStrings = map[ScheduledTransactionStatus]string{ + ScheduledTxStatusScheduled: "scheduled", + ScheduledTxStatusExecuted: "executed", + ScheduledTxStatusCancelled: "cancelled", + ScheduledTxStatusFailed: "failed", +} + +// String returns the string representation of the status. +func (s ScheduledTransactionStatus) String() string { + if str, ok := scheduledTransactionStatusStrings[s]; ok { + return str + } + panic(fmt.Sprintf("unknown scheduled transaction status: %d", s)) +} + +// ParseScheduledTransactionStatus parses a string into a ScheduledTransactionStatus. +// +// Any error indicates the string is not a valid status. +func ParseScheduledTransactionStatus(s string) (ScheduledTransactionStatus, error) { + switch strings.ToLower(s) { + case scheduledTransactionStatusStrings[ScheduledTxStatusScheduled]: + return ScheduledTxStatusScheduled, nil + case scheduledTransactionStatusStrings[ScheduledTxStatusExecuted]: + return ScheduledTxStatusExecuted, nil + case scheduledTransactionStatusStrings[ScheduledTxStatusCancelled]: + return ScheduledTxStatusCancelled, nil + case scheduledTransactionStatusStrings[ScheduledTxStatusFailed]: + return ScheduledTxStatusFailed, nil + default: + return 0, fmt.Errorf("unknown scheduled transaction status: %s", s) + } +} + +// ScheduledTransactionPriority represents the execution priority of a scheduled transaction. +type ScheduledTransactionPriority uint8 + +const ( + ScheduledTxPriorityHigh ScheduledTransactionPriority = 0 + ScheduledTxPriorityMedium ScheduledTransactionPriority = 1 + ScheduledTxPriorityLow ScheduledTransactionPriority = 2 +) + +var scheduledTransactionPriorityStrings = map[ScheduledTransactionPriority]string{ + ScheduledTxPriorityHigh: "high", + ScheduledTxPriorityMedium: "medium", + ScheduledTxPriorityLow: "low", +} + +// String returns the string representation of the priority. +func (p ScheduledTransactionPriority) String() string { + if str, ok := scheduledTransactionPriorityStrings[p]; ok { + return str + } + panic(fmt.Sprintf("unknown scheduled transaction priority: %d", p)) +} + +// ParseScheduledTransactionPriority parses a string into a ScheduledTransactionPriority. +// +// Any error indicates the string is not a valid priority. +func ParseScheduledTransactionPriority(s string) (ScheduledTransactionPriority, error) { + switch strings.ToLower(s) { + case scheduledTransactionPriorityStrings[ScheduledTxPriorityHigh]: + return ScheduledTxPriorityHigh, nil + case scheduledTransactionPriorityStrings[ScheduledTxPriorityMedium]: + return ScheduledTxPriorityMedium, nil + case scheduledTransactionPriorityStrings[ScheduledTxPriorityLow]: + return ScheduledTxPriorityLow, nil + default: + return 0, fmt.Errorf("unknown scheduled transaction priority: %s", s) + } +} + +// ScheduledTransaction represents a scheduled transaction as indexed by the access node. +type ScheduledTransaction struct { + ID uint64 + Priority ScheduledTransactionPriority + Timestamp uint64 // stored by the contract as a UFix64 with the fractional zeroed out + ExecutionEffort uint64 + Fees uint64 + + TransactionHandlerOwner flow.Address + TransactionHandlerTypeIdentifier string + TransactionHandlerUUID uint64 + TransactionHandlerPublicPath string + + Status ScheduledTransactionStatus + + // CreatedTransactionID is the transaction ID of the transaction in which the scheduled transaction was created + // It is always set unless the scheduled transaction is a placeholder, in which case IsPlaceholder is true. + CreatedTransactionID flow.Identifier + + // ExecutedTransactionID is the transaction ID of the transaction in which the scheduled transaction was executed + // If set, status is set to [ScheduledTxStatusExecuted]. + ExecutedTransactionID flow.Identifier + + // CancelledTransactionID is the transaction ID of the transaction in which the scheduled transaction was cancelled + // If set, status is set to [ScheduledTxStatusCancelled]. + CancelledTransactionID flow.Identifier + + // FeesReturned is the amount of fees returned to the scheduled transaction's owner when the scheduled transaction was cancelled + FeesReturned uint64 + + // FeesDeducted is the amount of fees deducted from the scheduled transaction's owner when the scheduled transaction was cancelled + FeesDeducted uint64 + + // IsPlaceholder is true if the scheduled transaction was created based on the current chain state, + // and not based on a protocol event. This happens when the index is bootstrapped after the original + // transaction where the scheduled transaction was first created. + // When true, the `CreatedTransactionID`, `TransactionHandlerUUID`, and `TransactionHandlerPublicPath` + // fields are undefined. + IsPlaceholder bool + + // Expansion fields populated when expandResults is true. Never persisted. + Transaction *flow.TransactionBody `msgpack:"-"` // Transaction body (nil unless expanded) + Result *TransactionResult `msgpack:"-"` // Transaction result (nil unless expanded) + HandlerContract *ContractDeployment `msgpack:"-"` // Handler contract (nil unless expanded) + + // Timestamp fields are populated by the backend. Never persisted. Zero when not applicable. + CreatedAt uint64 `msgpack:"-"` // Unix ms timestamp of block in which the scheduled transaction was created + CompletedAt uint64 `msgpack:"-"` // Unix ms timestamp of block in which the scheduled transaction was executed or cancelled +} + +func (tx *ScheduledTransaction) HandlerContractID() (string, error) { + parts := strings.Split(tx.TransactionHandlerTypeIdentifier, ".") + if len(parts) < 3 { + return "", fmt.Errorf("invalid handler type identifier: %s", tx.TransactionHandlerTypeIdentifier) + } + return strings.Join(parts[:3], "."), nil +} + +// ScheduledTransactionCursor identifies a position in the scheduled transaction index for +// cursor-based pagination. It corresponds to the last entry returned in a previous page. +type ScheduledTransactionCursor struct { + ID uint64 // Scheduled transaction ID of the last returned entry +} + +// ScheduledTransactionsPage represents a single page of scheduled transaction results. +type ScheduledTransactionsPage struct { + Transactions []ScheduledTransaction // Results in this page (descending order by ID) + NextCursor *ScheduledTransactionCursor // Cursor to fetch the next page, nil when no more results +} diff --git a/model/access/system_collection.go b/model/access/system_collection.go index a485941468c..e182dbcf2c5 100644 --- a/model/access/system_collection.go +++ b/model/access/system_collection.go @@ -20,6 +20,11 @@ type SystemCollectionBuilder interface { // No error returns are expected during normal operation. ExecuteCallbacksTransactions(chain flow.Chain, processEvents flow.EventsList) ([]*flow.TransactionBody, error) + // ExecuteCallbacksTransaction constructs a transaction to execute a callback, for the given chain. + // + // No error returns are expected during normal operation. + ExecuteCallbacksTransaction(chain flow.Chain, id uint64, effort uint64) (*flow.TransactionBody, error) + // SystemChunkTransaction creates and returns the transaction corresponding to the // system chunk for the given chain. // diff --git a/model/access/systemcollection/system_collection.go b/model/access/systemcollection/system_collection.go index 341d6e82b70..1c6d5c50ec2 100644 --- a/model/access/systemcollection/system_collection.go +++ b/model/access/systemcollection/system_collection.go @@ -17,6 +17,10 @@ var ChainHeightVersions = map[flow.ChainID]access.HeightVersionMapper{ 0: Version0, 290050888: Version1, }), + flow.Mainnet: access.NewStaticHeightVersionMapper(map[uint64]access.Version{ + 0: Version0, + 133408444: Version1, // Mainnet27 HCU 1, 20th Nov 2025, 8:15am + }), } // versionBuilder is a map of all versions of the system collection. diff --git a/model/access/systemcollection/system_collection_test.go b/model/access/systemcollection/system_collection_test.go index 52b79c83ea2..4c6776c7381 100644 --- a/model/access/systemcollection/system_collection_test.go +++ b/model/access/systemcollection/system_collection_test.go @@ -20,6 +20,9 @@ const ( // testTestnetV1Height is the height at which Testnet transitions to Version1. testTestnetV1Height = 290050888 + + // testTestnetV1Height is the height at which Testnet transitions to Version1. + testMainnetV1Height = 133408444 ) func TestDefault(t *testing.T) { @@ -123,19 +126,17 @@ func TestVersioned_ByHeight(t *testing.T) { testTestnetV1Height + 100: Version1, }, }, - // Uncomment and configure when Mainnet boundaries are defined: - // { - // chainID: flow.Mainnet, - // heightTests: map[uint64]access.Version{ - // 0: Version0, - // testMainnetV1Height - 100: Version0, - // testMainnetV1Height: Version1, - // testMainnetV1Height + 100: Version1, - // }, - // }, + { + chainID: flow.Mainnet, + heightTests: map[uint64]access.Version{ + 0: Version0, + testMainnetV1Height - 100: Version0, + testMainnetV1Height: Version1, + testMainnetV1Height + 100: Version1, + }, + }, // Networks that always use the latest version (nil heightTests = always latest) - {chainID: flow.Mainnet}, {chainID: flow.Emulator}, {chainID: flow.Sandboxnet}, {chainID: flow.Previewnet}, @@ -206,11 +207,20 @@ func TestChainHeightVersions(t *testing.T) { assert.Equal(t, Version1, testnetMapper.GetVersion(testTestnetV1Height)) }) + t.Run("Mainnet uses explicit version boundaries", func(t *testing.T) { + mainnetMapper := ChainHeightVersions[flow.Mainnet] + + // Mainnet should use V0 at height 0 + assert.Equal(t, Version0, mainnetMapper.GetVersion(0)) + + // Mainnet should use V1 at testMainnetV1Height + assert.Equal(t, Version1, mainnetMapper.GetVersion(testMainnetV1Height)) + }) + t.Run("chains without explicit mappings use LatestBoundary via Default", func(t *testing.T) { // These chains don't have explicit entries in ChainHeightVersions, // so Default() will give them LatestBoundary testNetworks := []flow.ChainID{ - flow.Mainnet, flow.Sandboxnet, flow.Previewnet, flow.Benchnet, diff --git a/model/access/systemcollection/system_collection_v0.go b/model/access/systemcollection/system_collection_v0.go index 5c3cfe942e0..5966c447d3a 100644 --- a/model/access/systemcollection/system_collection_v0.go +++ b/model/access/systemcollection/system_collection_v0.go @@ -8,6 +8,7 @@ import ( "github.com/rs/zerolog/log" + "github.com/onflow/cadence" jsoncdc "github.com/onflow/cadence/encoding/json" "github.com/onflow/flow-core-contracts/lib/go/templates" @@ -88,6 +89,32 @@ func (b *builderV0) ExecuteCallbacksTransactions(chain flow.Chain, processEvents return txs, nil } +// ExecuteCallbacksTransaction constructs a list of transaction to execute callbacks, for the given chain. +// +// No error returns are expected during normal operation. +func (b *builderV0) ExecuteCallbacksTransaction(chain flow.Chain, id uint64, effort uint64) (*flow.TransactionBody, error) { + sc := systemcontracts.SystemContractsForChain(chain.ChainID()) + env := sc.AsTemplateEnv() + script := templates.GenerateSchedulerExecutorTransactionScript(env) + + encID, err := jsoncdc.Encode(cadence.NewUInt64(id)) + if err != nil { + return nil, fmt.Errorf("failed to encode id: %w", err) + } + + tx, err := flow.NewTransactionBodyBuilder(). + AddAuthorizer(sc.FlowServiceAccount.Address). + SetScript(script). + AddArgument(encID). + SetComputeLimit(effort). + Build() + if err != nil { + return nil, fmt.Errorf("failed to construct execute callback transactions: %w", err) + } + + return tx, nil +} + // callbackArgsFromEventV1 decodes the event payload and returns the callback ID and effort. // // No error returns are expected during normal operation. diff --git a/model/access/systemcollection/system_collection_v0_test.go b/model/access/systemcollection/system_collection_v0_test.go index 5a813fcafca..be47c2491c1 100644 --- a/model/access/systemcollection/system_collection_v0_test.go +++ b/model/access/systemcollection/system_collection_v0_test.go @@ -84,6 +84,14 @@ func (s *builderV0Suite) TestExecuteCallbacksTransactions() { } } +func (s *builderV0Suite) TestExecuteCallbacksTransaction() { + expectedID := flow.MustHexStringToIdentifier("3b16467513ee196aa369bafab83786dcd0aa0ae09059369df13cf45b13b7de26") + + tx, err := s.builder.ExecuteCallbacksTransaction(s.g.ChainID().Chain(), 42, 1000) + s.Require().NoError(err) + s.Require().True(expectedID == tx.ID(), "invalid change made in the v0 versioned system collection") +} + func (s *builderV0Suite) TestSystemChunkTransaction() { expectedID := flow.MustHexStringToIdentifier("3408f8b1aa1b33cfc3f78c3f15217272807b14cec4ef64168bcf313bc4174621") diff --git a/model/access/systemcollection/system_collection_v1.go b/model/access/systemcollection/system_collection_v1.go index 0a847ec4e52..a5b0322191e 100644 --- a/model/access/systemcollection/system_collection_v1.go +++ b/model/access/systemcollection/system_collection_v1.go @@ -34,6 +34,13 @@ func (b *builderV1) ExecuteCallbacksTransactions(chain flow.Chain, processEvents return blueprints.ExecuteCallbacksTransactions(chain, processEvents) } +// ExecuteCallbacksTransaction constructs a transaction to execute a callback, for the given chain. +// +// No error returns are expected during normal operation. +func (b *builderV1) ExecuteCallbacksTransaction(chain flow.Chain, id uint64, effort uint64) (*flow.TransactionBody, error) { + return blueprints.ExecuteCallbacksTransaction(chain, id, effort) +} + // SystemChunkTransaction creates and returns the transaction corresponding to the // system chunk for the given chain. // diff --git a/model/access/systemcollection/system_collection_v1_test.go b/model/access/systemcollection/system_collection_v1_test.go index 90db7f2a6b4..00f3d2239cf 100644 --- a/model/access/systemcollection/system_collection_v1_test.go +++ b/model/access/systemcollection/system_collection_v1_test.go @@ -84,6 +84,14 @@ func (s *builderV1Suite) TestExecuteCallbacksTransactions() { } } +func (s *builderV1Suite) TestExecuteCallbacksTransaction() { + expectedID := flow.MustHexStringToIdentifier("cae4adc3eb92ee67a47754e3e7095e4402249aa482be19b800de601ce4cd0d32") + + tx, err := s.builder.ExecuteCallbacksTransaction(s.g.ChainID().Chain(), 42, 1000) + s.Require().NoError(err) + s.Require().True(expectedID == tx.ID(), "invalid change made in the v1 versioned system collection") +} + func (s *builderV1Suite) TestSystemChunkTransaction() { expectedID := flow.MustHexStringToIdentifier("3408f8b1aa1b33cfc3f78c3f15217272807b14cec4ef64168bcf313bc4174621") diff --git a/model/access/transaction_result.go b/model/access/transaction_result.go index ef6f53707bf..acf6433b79d 100644 --- a/model/access/transaction_result.go +++ b/model/access/transaction_result.go @@ -6,14 +6,15 @@ import ( // TransactionResult represents a flow.TransactionResult with additional fields required for the Access API type TransactionResult struct { - Status flow.TransactionStatus - StatusCode uint - Events []flow.Event - ErrorMessage string - BlockID flow.Identifier - TransactionID flow.Identifier - CollectionID flow.Identifier - BlockHeight uint64 + Status flow.TransactionStatus + StatusCode uint + Events []flow.Event + ErrorMessage string + BlockID flow.Identifier + TransactionID flow.Identifier + CollectionID flow.Identifier + BlockHeight uint64 + ComputationUsed uint64 } func (r *TransactionResult) IsExecuted() bool { diff --git a/model/encoding/cbor/codec.go b/model/encoding/cbor/codec.go index 20737549c15..e50bcd17ae8 100644 --- a/model/encoding/cbor/codec.go +++ b/model/encoding/cbor/codec.go @@ -46,15 +46,15 @@ var UnsafeDecMode, _ = cbor.DecOptions{}.DecMode() // target (struct we are unmarshalling into), which prevents some classes of resource exhaustion attacks. var DefaultDecMode, _ = cbor.DecOptions{ExtraReturnErrors: cbor.ExtraDecErrorUnknownField}.DecMode() -func (m *Marshaler) Marshal(val interface{}) ([]byte, error) { +func (m *Marshaler) Marshal(val any) ([]byte, error) { return EncMode.Marshal(val) } -func (m *Marshaler) Unmarshal(b []byte, val interface{}) error { +func (m *Marshaler) Unmarshal(b []byte, val any) error { return cbor.Unmarshal(b, val) } -func (m *Marshaler) MustMarshal(val interface{}) []byte { +func (m *Marshaler) MustMarshal(val any) []byte { b, err := m.Marshal(val) if err != nil { panic(err) @@ -63,7 +63,7 @@ func (m *Marshaler) MustMarshal(val interface{}) []byte { return b } -func (m *Marshaler) MustUnmarshal(b []byte, val interface{}) { +func (m *Marshaler) MustUnmarshal(b []byte, val any) { err := m.Unmarshal(b, val) if err != nil { panic(err) diff --git a/model/encoding/codec.go b/model/encoding/codec.go index 7ae24d10277..0fefd2af8b5 100644 --- a/model/encoding/codec.go +++ b/model/encoding/codec.go @@ -14,30 +14,30 @@ type Marshaler interface { // Marshaler marshals a value to bytes. // // This function returns an error if the value type is not supported by this marshaler. - Marshal(interface{}) ([]byte, error) + Marshal(any) ([]byte, error) // Unmarshal unmarshals bytes to a value. // // This functions returns an error if the bytes do not fit the provided value type. - Unmarshal([]byte, interface{}) error + Unmarshal([]byte, any) error // MustMarshal marshals a value to bytes. // // This function panics if marshaling fails. - MustMarshal(interface{}) []byte + MustMarshal(any) []byte // MustUnmarshal unmarshals bytes to a value. // // This function panics if decoding fails. - MustUnmarshal([]byte, interface{}) + MustUnmarshal([]byte, any) } type Encoder interface { - Encode(interface{}) error + Encode(any) error } type Decoder interface { - Decode(interface{}) error + Decode(any) error } type Codec interface { diff --git a/model/encoding/json/codec.go b/model/encoding/json/codec.go index f81eb0291af..0e5c1d3b884 100644 --- a/model/encoding/json/codec.go +++ b/model/encoding/json/codec.go @@ -15,15 +15,15 @@ func NewMarshaler() *Marshaler { return &Marshaler{} } -func (m *Marshaler) Marshal(val interface{}) ([]byte, error) { +func (m *Marshaler) Marshal(val any) ([]byte, error) { return json.Marshal(val) } -func (m *Marshaler) Unmarshal(b []byte, val interface{}) error { +func (m *Marshaler) Unmarshal(b []byte, val any) error { return json.Unmarshal(b, val) } -func (m *Marshaler) MustMarshal(val interface{}) []byte { +func (m *Marshaler) MustMarshal(val any) []byte { b, err := m.Marshal(val) if err != nil { panic(err) @@ -32,7 +32,7 @@ func (m *Marshaler) MustMarshal(val interface{}) []byte { return b } -func (m *Marshaler) MustUnmarshal(b []byte, val interface{}) { +func (m *Marshaler) MustUnmarshal(b []byte, val any) { err := m.Unmarshal(b, val) if err != nil { panic(err) diff --git a/model/encoding/rlp/codec.go b/model/encoding/rlp/codec.go index 2b6bf8f72cb..84e4e7bef12 100644 --- a/model/encoding/rlp/codec.go +++ b/model/encoding/rlp/codec.go @@ -16,15 +16,15 @@ func NewMarshaler() *Marshaler { return &Marshaler{} } -func (m *Marshaler) Marshal(val interface{}) ([]byte, error) { +func (m *Marshaler) Marshal(val any) ([]byte, error) { return rlp.EncodeToBytes(val) } -func (m *Marshaler) Unmarshal(b []byte, val interface{}) error { +func (m *Marshaler) Unmarshal(b []byte, val any) error { return rlp.DecodeBytes(b, val) } -func (m *Marshaler) MustMarshal(val interface{}) []byte { +func (m *Marshaler) MustMarshal(val any) []byte { b, err := m.Marshal(val) if err != nil { panic(err) @@ -33,7 +33,7 @@ func (m *Marshaler) MustMarshal(val interface{}) []byte { return b } -func (m *Marshaler) MustUnmarshal(b []byte, val interface{}) { +func (m *Marshaler) MustUnmarshal(b []byte, val any) { err := m.Unmarshal(b, val) if err != nil { panic(err) @@ -56,7 +56,7 @@ type Encoder struct { w io.Writer } -func (e *Encoder) Encode(v interface{}) error { +func (e *Encoder) Encode(v any) error { return rlp.Encode(e.w, v) } @@ -64,6 +64,6 @@ type Decoder struct { r io.Reader } -func (e *Decoder) Decode(v interface{}) error { +func (e *Decoder) Decode(v any) error { return rlp.Decode(e.r, v) } diff --git a/model/fingerprint/fingerprint.go b/model/fingerprint/fingerprint.go index 323b5249745..771cc18ddf5 100644 --- a/model/fingerprint/fingerprint.go +++ b/model/fingerprint/fingerprint.go @@ -18,7 +18,7 @@ type Fingerprinter interface { // hashes of the same entity depending on the JSON implementation and b) the Fingerprinter interface allows to exclude // fields not needed in the pre-image of the hash that comprises the Identifier, which could be different from the // encoding for sending entities in messages or for storing them. -func Fingerprint(entity interface{}) []byte { +func Fingerprint(entity any) []byte { if fingerprinter, ok := entity.(Fingerprinter); ok { return fingerprinter.Fingerprint() } diff --git a/model/fingerprint/fingerprint_test.go b/model/fingerprint/fingerprint_test.go index 2bce0ef8fb7..cf9c1df1321 100644 --- a/model/fingerprint/fingerprint_test.go +++ b/model/fingerprint/fingerprint_test.go @@ -11,7 +11,7 @@ import ( func TestFingerprint(t *testing.T) { tests := []struct { - input interface{} + input any output string }{ {"abc", "0x83616263"}, diff --git a/model/fingerprint/mock/fingerprinter.go b/model/fingerprint/mock/fingerprinter.go index 3b55c5a3048..9469693f571 100644 --- a/model/fingerprint/mock/fingerprinter.go +++ b/model/fingerprint/mock/fingerprinter.go @@ -1,44 +1,82 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewFingerprinter creates a new instance of Fingerprinter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFingerprinter(t interface { + mock.TestingT + Cleanup(func()) +}) *Fingerprinter { + mock := &Fingerprinter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Fingerprinter is an autogenerated mock type for the Fingerprinter type type Fingerprinter struct { mock.Mock } -// Fingerprint provides a mock function with no fields -func (_m *Fingerprinter) Fingerprint() []byte { - ret := _m.Called() +type Fingerprinter_Expecter struct { + mock *mock.Mock +} + +func (_m *Fingerprinter) EXPECT() *Fingerprinter_Expecter { + return &Fingerprinter_Expecter{mock: &_m.Mock} +} + +// Fingerprint provides a mock function for the type Fingerprinter +func (_mock *Fingerprinter) Fingerprint() []byte { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Fingerprint") } var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - return r0 } -// NewFingerprinter creates a new instance of Fingerprinter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewFingerprinter(t interface { - mock.TestingT - Cleanup(func()) -}) *Fingerprinter { - mock := &Fingerprinter{} - mock.Mock.Test(t) +// Fingerprinter_Fingerprint_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Fingerprint' +type Fingerprinter_Fingerprint_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Fingerprint is a helper method to define mock.On call +func (_e *Fingerprinter_Expecter) Fingerprint() *Fingerprinter_Fingerprint_Call { + return &Fingerprinter_Fingerprint_Call{Call: _e.mock.On("Fingerprint")} +} - return mock +func (_c *Fingerprinter_Fingerprint_Call) Run(run func()) *Fingerprinter_Fingerprint_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Fingerprinter_Fingerprint_Call) Return(bytes []byte) *Fingerprinter_Fingerprint_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *Fingerprinter_Fingerprint_Call) RunAndReturn(run func() []byte) *Fingerprinter_Fingerprint_Call { + _c.Call.Return(run) + return _c } diff --git a/model/flow/address.go b/model/flow/address.go index 941531cd850..c41a7a5a553 100644 --- a/model/flow/address.go +++ b/model/flow/address.go @@ -17,10 +17,6 @@ type Address [AddressLength]byte // EmptyAddress is the default value of a variable of type Address var EmptyAddress = BytesToAddress(nil) -func ConvertAddress(b [AddressLength]byte) Address { - return Address(b) -} - // HexToAddress converts a hex string to an Address. func HexToAddress(h string) Address { addr, _ := StringToAddress(h) @@ -289,7 +285,7 @@ const invalidCodePreviewNetwork = uint64(0x5211829E88528817) func encodeWord(word uint64) uint64 { // Multiply the index GF(2) vector by the code generator matrix codeWord := uint64(0) - for i := 0; i < linearCodeK; i++ { + for i := range linearCodeK { if word&1 == 1 { codeWord ^= generatorMatrixRows[i] } @@ -302,7 +298,7 @@ func encodeWord(word uint64) uint64 { func isValidCodeWord(codeWord uint64) bool { // Multiply the code word GF(2)-vector by the parity-check matrix parity := uint(0) - for i := 0; i < linearCodeN; i++ { + for i := range linearCodeN { if codeWord&1 == 1 { parity ^= parityCheckMatrixColumns[i] } @@ -318,7 +314,7 @@ func decodeCodeWord(codeWord uint64) uint64 { // the partial code generator. word := uint64(0) codeWord >>= (linearCodeN - linearCodeK) - for i := 0; i < linearCodeK; i++ { + for i := range linearCodeK { if codeWord&1 == 1 { word ^= inverseMatrixRows[i] } diff --git a/model/flow/address_test.go b/model/flow/address_test.go index 527dce77bef..da62462d83f 100644 --- a/model/flow/address_test.go +++ b/model/flow/address_test.go @@ -23,8 +23,8 @@ func TestConvertAddress(t *testing.T) { assert.NotEqual(t, cadenceAddress, runtimeAddress) - assert.Equal(t, expected, ConvertAddress(cadenceAddress)) - assert.Equal(t, expected, ConvertAddress(runtimeAddress)) + assert.Equal(t, expected, Address(cadenceAddress)) + assert.Equal(t, expected, Address(runtimeAddress)) } func TestBytesToAddress(t *testing.T) { @@ -185,7 +185,7 @@ func testAddressGeneration(t *testing.T) { // sanity check of NextAddress function consistency state := chain.NewAddressGenerator() expectedIndex := uint64(0) - for i := 0; i < loop; i++ { + for range loop { expectedIndex++ address, err := state.NextAddress() require.NoError(t, err) @@ -201,7 +201,7 @@ func testAddressGeneration(t *testing.T) { if chainID == Mainnet { r := uint64(rand.Intn(maxIndex - loop)) state = chain.NewAddressGeneratorAtIndex(r) - for i := 0; i < loop; i++ { + for range loop { address, err := state.NextAddress() require.NoError(t, err) weight := bits.OnesCount64(address.uint64()) @@ -216,7 +216,7 @@ func testAddressGeneration(t *testing.T) { state = chain.NewAddressGeneratorAtIndex(r) refAddress, err := state.NextAddress() require.NoError(t, err) - for i := 0; i < loop; i++ { + for range loop { address, err := state.NextAddress() require.NoError(t, err) distance := bits.OnesCount64(address.uint64() ^ refAddress.uint64()) @@ -227,7 +227,7 @@ func testAddressGeneration(t *testing.T) { // All valid addresses must pass IsValid. r = uint64(rand.Intn(maxIndex - loop)) state = chain.NewAddressGeneratorAtIndex(r) - for i := 0; i < loop; i++ { + for range loop { address, err := state.NextAddress() require.NoError(t, err) check := chain.IsValid(address) @@ -242,7 +242,7 @@ func testAddressGeneration(t *testing.T) { r = uint64(rand.Intn(maxIndex - loop)) state = chain.NewAddressGeneratorAtIndex(r) - for i := 0; i < loop; i++ { + for range loop { address, err := state.NextAddress() require.NoError(t, err) invalidAddress = uint64ToAddress(address.uint64() ^ invalidCodeWord) @@ -272,7 +272,7 @@ func testAddressesIntersection(t *testing.T) { // a valid address in one network must be invalid in all other networks r := uint64(rand.Intn(maxIndex - loop)) state := chain.NewAddressGeneratorAtIndex(r) - for k := 0; k < loop; k++ { + for range loop { address, err := state.NextAddress() require.NoError(t, err) for _, otherChain := range chainIDs { @@ -298,7 +298,7 @@ func testAddressesIntersection(t *testing.T) { // fail the check for all networks r = uint64(rand.Intn(maxIndex - loop)) state = chain.NewAddressGeneratorAtIndex(r) - for k := 0; k < loop; k++ { + for range loop { address, err := state.NextAddress() require.NoError(t, err) invalidAddress = uint64ToAddress(address.uint64() ^ invalidCodeWord) @@ -322,7 +322,7 @@ func testIndexFromAddress(t *testing.T) { } for _, chain := range chains { - for i := 0; i < loop; i++ { + for range loop { // check the correctness of IndexFromAddress // random valid index @@ -350,7 +350,7 @@ func testIndexFromAddress(t *testing.T) { func TestUint48(t *testing.T) { const loop = 50 // test consistensy of putUint48 and uint48 - for i := 0; i < loop; i++ { + for range loop { r := uint64(rand.Intn(1 << linearCodeK)) b := make([]byte, addressIndexLength) putUint48(b, r) diff --git a/model/flow/aggregated_signature.go b/model/flow/aggregated_signature.go index fe53c57a5a4..9571d33a768 100644 --- a/model/flow/aggregated_signature.go +++ b/model/flow/aggregated_signature.go @@ -1,6 +1,8 @@ package flow import ( + "slices" + "github.com/onflow/crypto" ) @@ -22,10 +24,5 @@ func (a *AggregatedSignature) CardinalitySignerSet() int { // HasSigner returns true if and only if signer's signature is part of this aggregated signature func (a *AggregatedSignature) HasSigner(signerID Identifier) bool { - for _, id := range a.SignerIDs { - if id == signerID { - return true - } - } - return false + return slices.Contains(a.SignerIDs, signerID) } diff --git a/model/flow/chain.go b/model/flow/chain.go index 7cc4df23244..2ac2b219c1b 100644 --- a/model/flow/chain.go +++ b/model/flow/chain.go @@ -10,7 +10,7 @@ import ( // A ChainID is a unique identifier for a specific Flow network instance. // -// Chain IDs are used used to prevent replay attacks and to support network-specific address generation. +// Chain IDs are used to prevent replay attacks and to support network-specific address generation. type ChainID string type ChainIDList []ChainID diff --git a/model/flow/execution_result.go b/model/flow/execution_result.go index fbcf00e6e22..7317a55e554 100644 --- a/model/flow/execution_result.go +++ b/model/flow/execution_result.go @@ -136,7 +136,7 @@ func (er ExecutionResult) ServiceEventsByChunk(chunkIndex uint64) ServiceEventLi } startIndex := 0 - for i := uint64(0); i < chunkIndex; i++ { + for i := range chunkIndex { startIndex += int(er.Chunks[i].ServiceEventCount) } return er.ServiceEvents[startIndex : startIndex+int(serviceEventCount)] diff --git a/model/flow/header_body_builder.go b/model/flow/header_body_builder.go index 1b01297e68e..60a71511cce 100644 --- a/model/flow/header_body_builder.go +++ b/model/flow/header_body_builder.go @@ -68,7 +68,7 @@ func NewHeaderBodyBuilder() *HeaderBodyBuilder { // All errors indicate that a valid HeaderBody cannot be created from the current builder state. func (b *HeaderBodyBuilder) Build() (*HeaderBody, error) { // make sure every required field was initialized - for bit := 0; bit < int(numHeaderBodyFields); bit++ { + for bit := range int(numHeaderBodyFields) { if bitutils.ReadBit(b.present, bit) == 0 { return nil, fmt.Errorf("HeaderBodyBuilder: missing field %s", headerBodyFieldBitIndex(bit)) } diff --git a/model/flow/identifier.go b/model/flow/identifier.go index e9c7861bc94..977a2e34565 100644 --- a/model/flow/identifier.go +++ b/model/flow/identifier.go @@ -127,7 +127,7 @@ func HashToID(hash []byte) Identifier { // different hashes depending on the JSON implementation and b) the Fingerprinter interface allows to exclude fields not // needed in the pre-image of the hash that comprises the Identifier, which could be different from the encoding for // sending entities in messages or for storing them. -func MakeID(entity interface{}) Identifier { +func MakeID(entity any) Identifier { // collect fingerprint of the entity data := fingerprint.Fingerprint(entity) // make ID from fingerprint @@ -248,7 +248,7 @@ func ByteSlicesToIds(b [][]byte) (IdentifierList, error) { total := len(b) ids := make(IdentifierList, total) - for i := 0; i < total; i++ { + for i := range total { id, err := ByteSliceToId(b[i]) if err != nil { return nil, err diff --git a/model/flow/identifierList.go b/model/flow/identifierList.go index afbeadc7a09..58dd7cd248c 100644 --- a/model/flow/identifierList.go +++ b/model/flow/identifierList.go @@ -2,8 +2,7 @@ package flow import ( "fmt" - - "golang.org/x/exp/slices" + "slices" ) // IdentifierList defines a sortable list of identifiers @@ -59,12 +58,7 @@ func (il IdentifierList) Copy() IdentifierList { // Contains returns whether this identifier list contains the target identifier. func (il IdentifierList) Contains(target Identifier) bool { - for _, id := range il { - if target == id { - return true - } - } - return false + return slices.Contains(il, target) } // Union returns a new identifier list containing the union of `il` and `other`. diff --git a/model/flow/identifier_test.go b/model/flow/identifier_test.go index 2e75b27b421..62ca2e317df 100644 --- a/model/flow/identifier_test.go +++ b/model/flow/identifier_test.go @@ -27,7 +27,7 @@ func TestIdentifierFormat(t *testing.T) { // should print hex representation with %s formatting verb t.Run("%s", func(t *testing.T) { - formatted := fmt.Sprintf("%s", id) //nolint:gosimple + formatted := fmt.Sprintf("%s", id) //nolint:staticcheck assert.Equal(t, id.String(), formatted) }) diff --git a/model/flow/identity_list.go b/model/flow/identity_list.go index efe042f2f53..824ed86c108 100644 --- a/model/flow/identity_list.go +++ b/model/flow/identity_list.go @@ -109,7 +109,7 @@ func (il GenericIdentityList[T]) Map(f IdentityMapFunc[T]) GenericIdentityList[T func (il GenericIdentityList[T]) Copy() GenericIdentityList[T] { dup := make(GenericIdentityList[T], 0, len(il)) lenList := len(il) - for i := 0; i < lenList; i++ { // performance tests show this is faster than 'range' + for i := range lenList { // performance tests show this is faster than 'range' next := *(il[i]) // copy the object dup = append(dup, &next) } diff --git a/model/flow/protocol_state.go b/model/flow/protocol_state.go index 420d77f543b..fc4f2c4bd97 100644 --- a/model/flow/protocol_state.go +++ b/model/flow/protocol_state.go @@ -578,7 +578,7 @@ func (ll DynamicIdentityEntryList) ByNodeID(nodeID Identifier) (*DynamicIdentity func (ll DynamicIdentityEntryList) Copy() DynamicIdentityEntryList { lenList := len(ll) dup := make(DynamicIdentityEntryList, 0, lenList) - for i := 0; i < lenList; i++ { + for i := range lenList { // copy the object next := *(ll[i]) dup = append(dup, &next) diff --git a/model/flow/role.go b/model/flow/role.go index 7ea3d26cda8..3945249e468 100644 --- a/model/flow/role.go +++ b/model/flow/role.go @@ -2,6 +2,7 @@ package flow import ( "fmt" + "slices" "sort" "github.com/pkg/errors" @@ -78,12 +79,7 @@ type RoleList []Role // Contains returns true if RoleList contains the role, otherwise false. func (r RoleList) Contains(role Role) bool { - for _, each := range r { - if each == role { - return true - } - } - return false + return slices.Contains(r, role) } // Union returns a new role list containing every role that occurs in diff --git a/model/flow/service_event.go b/model/flow/service_event.go index 325665c7cd7..414833defbe 100644 --- a/model/flow/service_event.go +++ b/model/flow/service_event.go @@ -37,7 +37,7 @@ const ( // encoding and decoding. type ServiceEvent struct { Type ServiceEventType - Event interface{} + Event any } // ServiceEventList is a handy container to enable comparisons @@ -78,8 +78,8 @@ type ServiceEventMarshaller interface { } type marshallerImpl struct { - marshalFunc func(v interface{}) ([]byte, error) - unmarshalFunc func(data []byte, v interface{}) error + marshalFunc func(v any) ([]byte, error) + unmarshalFunc func(data []byte, v any) error } var _ ServiceEventMarshaller = (*marshallerImpl)(nil) @@ -162,7 +162,7 @@ func unmarshalWrapped[E any](b []byte, marshaller marshallerImpl) (*E, error) { // The input bytes must be encoded as a specific event type (for example, EpochSetup). // Forwards errors from the underlying marshaller (treat errors as you would from eg. json.Unmarshal) func (marshaller marshallerImpl) UnmarshalWithType(b []byte, eventType ServiceEventType) (ServiceEvent, error) { - var event interface{} + var event any switch eventType { case ServiceEventSetup: event = new(EpochSetup) diff --git a/model/flow/service_event_test.go b/model/flow/service_event_test.go index 02877d068a7..c0776fba1fd 100644 --- a/model/flow/service_event_test.go +++ b/model/flow/service_event_test.go @@ -6,7 +6,6 @@ import ( "testing" "github.com/fxamacker/cbor/v2" - "github.com/google/go-cmp/cmp" gocmp "github.com/google/go-cmp/cmp" "github.com/onflow/crypto" "github.com/stretchr/testify/require" @@ -26,9 +25,9 @@ func TestEncodeDecode(t *testing.T) { setEpochExtensionViewCount := &flow.SetEpochExtensionViewCount{Value: uint64(rand.Uint32())} ejectionEvent := &flow.EjectNode{NodeID: unittest.IdentifierFixture()} - comparePubKey := cmp.FilterValues(func(a, b crypto.PublicKey) bool { + comparePubKey := gocmp.FilterValues(func(a, b crypto.PublicKey) bool { return true - }, cmp.Comparer(func(a, b crypto.PublicKey) bool { + }, gocmp.Comparer(func(a, b crypto.PublicKey) bool { if a == nil { return b == nil } diff --git a/model/flow/transaction.go b/model/flow/transaction.go index b87e3154d6a..d2c765e08b1 100644 --- a/model/flow/transaction.go +++ b/model/flow/transaction.go @@ -96,9 +96,9 @@ func (tb TransactionBody) Fingerprint() []byte { // EncodeRLP defines RLP encoding behaviour for TransactionBody. func (tb TransactionBody) EncodeRLP(w io.Writer) error { encodingCanonicalForm := struct { - Payload interface{} - PayloadSignatures interface{} - EnvelopeSignatures interface{} + Payload any + PayloadSignatures any + EnvelopeSignatures any }{ Payload: tb.PayloadCanonicalForm(), PayloadSignatures: signaturesList(tb.PayloadSignatures).canonicalForm(), @@ -163,7 +163,7 @@ func (tb *TransactionBody) PayloadMessage() []byte { return fingerprint.Fingerprint(tb.PayloadCanonicalForm()) } -func (tb *TransactionBody) PayloadCanonicalForm() interface{} { +func (tb *TransactionBody) PayloadCanonicalForm() any { authorizers := make([][]byte, len(tb.Authorizers)) for i, auth := range tb.Authorizers { authorizers[i] = auth.Bytes() @@ -199,10 +199,10 @@ func (tb *TransactionBody) EnvelopeMessage() []byte { return fingerprint.Fingerprint(tb.envelopeCanonicalForm()) } -func (tb *TransactionBody) envelopeCanonicalForm() interface{} { +func (tb *TransactionBody) envelopeCanonicalForm() any { return struct { - Payload interface{} - PayloadSignatures interface{} + Payload any + PayloadSignatures any }{ tb.PayloadCanonicalForm(), signaturesList(tb.PayloadSignatures).canonicalForm(), @@ -333,7 +333,7 @@ func (s TransactionSignature) shouldUseLegacyCanonicalForm() bool { return len(s.ExtensionData) == 0 || (len(s.ExtensionData) == 1 && s.ExtensionData[0] == byte(PlainScheme)) } -func (s TransactionSignature) canonicalForm() interface{} { +func (s TransactionSignature) canonicalForm() any { // int is not RLP-serializable, therefore s.SignerIndex and s.KeyIndex are converted to uint if s.shouldUseLegacyCanonicalForm() { // This is the legacy cononical form, mainly here for backward compatibility @@ -370,8 +370,8 @@ func compareSignatures(sigA, sigB TransactionSignature) int { type signaturesList []TransactionSignature -func (s signaturesList) canonicalForm() interface{} { - signatures := make([]interface{}, len(s)) +func (s signaturesList) canonicalForm() any { + signatures := make([]any, len(s)) for i, signature := range s { signatures[i] = signature.canonicalForm() diff --git a/model/flow/transaction_body_builder.go b/model/flow/transaction_body_builder.go index 6ae7f177739..638d8679ff7 100644 --- a/model/flow/transaction_body_builder.go +++ b/model/flow/transaction_body_builder.go @@ -118,7 +118,7 @@ func (tb *TransactionBodyBuilder) payloadMessage() []byte { return fingerprint.Fingerprint(tb.payloadCanonicalForm()) } -func (tb *TransactionBodyBuilder) payloadCanonicalForm() interface{} { +func (tb *TransactionBodyBuilder) payloadCanonicalForm() any { authorizers := make([][]byte, len(tb.u.Authorizers)) for i, auth := range tb.u.Authorizers { authorizers[i] = auth.Bytes() @@ -154,10 +154,10 @@ func (tb *TransactionBodyBuilder) EnvelopeMessage() []byte { return fingerprint.Fingerprint(tb.envelopeCanonicalForm()) } -func (tb *TransactionBodyBuilder) envelopeCanonicalForm() interface{} { +func (tb *TransactionBodyBuilder) envelopeCanonicalForm() any { return struct { - Payload interface{} - PayloadSignatures interface{} + Payload any + PayloadSignatures any }{ tb.payloadCanonicalForm(), signaturesList(tb.u.PayloadSignatures).canonicalForm(), diff --git a/model/flow/version_beacon.go b/model/flow/version_beacon.go index adbedd41c91..89202de7f7a 100644 --- a/model/flow/version_beacon.go +++ b/model/flow/version_beacon.go @@ -94,8 +94,8 @@ func (v *VersionBeacon) EqualTo(other *VersionBeacon) bool { // An error with an appropriate message is returned // if any validation fails. func (v *VersionBeacon) Validate() error { - eventError := func(format string, args ...interface{}) error { - args = append([]interface{}{v.Sequence}, args...) + eventError := func(format string, args ...any) error { + args = append([]any{v.Sequence}, args...) return fmt.Errorf( "version beacon (sequence=%d) error: "+format, args..., diff --git a/model/messages/untrusted_message.go b/model/messages/untrusted_message.go index 334ff6aeff9..a83179c94d0 100644 --- a/model/messages/untrusted_message.go +++ b/model/messages/untrusted_message.go @@ -35,7 +35,7 @@ type UntrustedMessage interface { // // No errors are expected during normal operation. // TODO: investigate how to eliminate this workaround in both ghost/rpc.go and corruptnet/message_processor.go -func InternalToMessage(event interface{}) (UntrustedMessage, error) { +func InternalToMessage(event any) (UntrustedMessage, error) { switch internal := event.(type) { case *flow.Proposal: return (*Proposal)(internal), nil diff --git a/module/chunks/chunkVerifier.go b/module/chunks/chunkVerifier.go index aebf4ca80dc..47493c3321b 100644 --- a/module/chunks/chunkVerifier.go +++ b/module/chunks/chunkVerifier.go @@ -308,7 +308,7 @@ func (fcv *ChunkVerifier) verifyTransactionsInContext( Str("event_tx_id", event.TransactionID.String()). Uint32("event_tx_index", event.TransactionIndex). Uint32("event_index", event.EventIndex). - Bytes("event_payload", event.Payload). + Hex("event_payload", event.Payload). Str("block_id", chunk.BlockID.String()). Str("collection_id", collectionID). Str("result_id", result.ID().String()). diff --git a/module/chunks/chunkVerifier_test.go b/module/chunks/chunkVerifier_test.go index c108c95eca8..4dfea123dae 100644 --- a/module/chunks/chunkVerifier_test.go +++ b/module/chunks/chunkVerifier_test.go @@ -60,9 +60,9 @@ var id0 = flow.NewRegisterID(unittest.RandomAddressFixture(), "") var id5 = flow.NewRegisterID(unittest.RandomAddressFixture(), "") // the chain we use for this test suite -var testChain = flow.Emulator -var epochSetupEvent, _ = unittest.EpochSetupFixtureByChainID(testChain) -var epochCommitEvent, _ = unittest.EpochCommitFixtureByChainID(testChain) +var testChainID = flow.Emulator +var epochSetupEvent, _ = unittest.EpochSetupFixtureByChainID(testChainID) +var epochCommitEvent, _ = unittest.EpochCommitFixtureByChainID(testChainID) // serviceEventsList is the list of service events emitted by default. var serviceEventsList = []flow.Event{ @@ -92,7 +92,7 @@ type ChunkVerifierTestSuite struct { // SetupTest is executed prior to each individual test in this test suite func (s *ChunkVerifierTestSuite) SetupSuite() { vmCtx := fvm.NewContext( - fvm.WithChain(testChain.Chain()), + testChainID.Chain(), fvm.WithScheduledTransactionsEnabled(true), ) vmMock := fvmmock.NewVM(s.T()) @@ -135,11 +135,11 @@ func (s *ChunkVerifierTestSuite) SetupSuite() { s.verifier = chunks.NewChunkVerifier(vmMock, vmCtx, zerolog.Nop()) - txBody, err := blueprints.SystemChunkTransaction(testChain.Chain()) + txBody, err := blueprints.SystemChunkTransaction(testChainID.Chain()) require.NoError(s.T(), err) serviceTxBody = txBody - processTxBody, err = blueprints.ProcessCallbacksTransaction(testChain.Chain()) + processTxBody, err = blueprints.ProcessCallbacksTransaction(testChainID.Chain()) require.NoError(s.T(), err) } @@ -276,7 +276,7 @@ func (s *ChunkVerifierTestSuite) TestServiceEventsMismatch_SystemChunk() { // modify the list of service events produced by FVM // EpochSetup event is expected, but we emit EpochCommit here resulting in a chunk fault - epochCommitServiceEvent, err := convert.ServiceEvent(testChain, epochCommitEvent) + epochCommitServiceEvent, err := convert.ServiceEvent(testChainID, epochCommitEvent) require.NoError(s.T(), err) s.snapshots[string(serviceTxBody.Script)] = &snapshot.ExecutionSnapshot{} @@ -287,7 +287,7 @@ func (s *ChunkVerifierTestSuite) TestServiceEventsMismatch_SystemChunk() { Events: meta.ChunkEvents, } - processTxBody, err := blueprints.ProcessCallbacksTransaction(testChain.Chain()) + processTxBody, err := blueprints.ProcessCallbacksTransaction(testChainID.Chain()) require.NoError(s.T(), err) s.snapshots[string(processTxBody.Script)] = &snapshot.ExecutionSnapshot{} @@ -326,7 +326,7 @@ func (s *ChunkVerifierTestSuite) TestServiceEventsMismatch_NonSystemChunk() { // modify the list of service events produced by FVM // EpochSetup event is expected, but we emit EpochCommit here resulting in a chunk fault - epochCommitServiceEvent, err := convert.ServiceEvent(testChain, epochCommitEvent) + epochCommitServiceEvent, err := convert.ServiceEvent(testChainID, epochCommitEvent) require.NoError(s.T(), err) s.snapshots[script] = &snapshot.ExecutionSnapshot{} @@ -457,7 +457,7 @@ func (s *ChunkVerifierTestSuite) TestExecutionDataIdMismatch() { } func (s *ChunkVerifierTestSuite) TestSystemChunkWithScheduledTransactionsReturningEvent() { - systemContracts := systemcontracts.SystemContractsForChain(testChain) + systemContracts := systemcontracts.SystemContractsForChain(testChainID) // create the event returned for processed callback processedEventName := fmt.Sprintf( @@ -495,7 +495,7 @@ func (s *ChunkVerifierTestSuite) TestSystemChunkWithScheduledTransactionsReturni } // Create execute callback transaction body - executeCallbackTxs, err := blueprints.ExecuteCallbacksTransactions(testChain.Chain(), flow.EventsList{processEvent}) + executeCallbackTxs, err := blueprints.ExecuteCallbacksTransactions(testChainID.Chain(), flow.EventsList{processEvent}) require.NoError(s.T(), err) require.Len(s.T(), executeCallbackTxs, 1) @@ -507,7 +507,7 @@ func (s *ChunkVerifierTestSuite) TestSystemChunkWithScheduledTransactionsReturni } // Setup system transaction output - epochSetupServiceEvent, err := convert.ServiceEvent(testChain, epochSetupEvent) + epochSetupServiceEvent, err := convert.ServiceEvent(testChainID, epochSetupEvent) require.NoError(s.T(), err) s.outputs[string(serviceTxBody.Script)] = fvm.ProcedureOutput{ @@ -555,7 +555,7 @@ func (s *ChunkVerifierTestSuite) TestSystemChunkWithNoScheduledTransactions() { } // Setup system transaction output - epochSetupServiceEvent, err := convert.ServiceEvent(testChain, epochSetupEvent) + epochSetupServiceEvent, err := convert.ServiceEvent(testChainID, epochSetupEvent) require.NoError(s.T(), err) s.outputs[string(serviceTxBody.Script)] = fvm.ProcedureOutput{ @@ -672,7 +672,7 @@ func generateEvents(t *testing.T, collection *flow.Collection, includeServiceEve if includeServiceEvent { for _, e := range serviceEventsList { e := e - event, err := convert.ServiceEvent(testChain, e) + event, err := convert.ServiceEvent(testChainID, e) require.NoError(t, err) serviceEvents = append(serviceEvents, *event) diff --git a/module/component/component.go b/module/component/component.go index 11b543f239f..a798a5aae92 100644 --- a/module/component/component.go +++ b/module/component/component.go @@ -264,7 +264,6 @@ func (c *ComponentManager) Start(parent irrecoverable.SignalerContext) { // launch workers for _, worker := range c.workers { - worker := worker go func() { defer workersDone.Done() var readyOnce sync.Once diff --git a/module/component/mock/component.go b/module/component/mock/component.go index 55ba98226d6..ef3686f6d0e 100644 --- a/module/component/mock/component.go +++ b/module/component/mock/component.go @@ -1,72 +1,169 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewComponent creates a new instance of Component. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewComponent(t interface { + mock.TestingT + Cleanup(func()) +}) *Component { + mock := &Component{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Component is an autogenerated mock type for the Component type type Component struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *Component) Done() <-chan struct{} { - ret := _m.Called() +type Component_Expecter struct { + mock *mock.Mock +} + +func (_m *Component) EXPECT() *Component_Expecter { + return &Component_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type Component +func (_mock *Component) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *Component) Ready() <-chan struct{} { - ret := _m.Called() +// Component_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Component_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Component_Expecter) Done() *Component_Done_Call { + return &Component_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Component_Done_Call) Run(run func()) *Component_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Component_Done_Call) Return(valCh <-chan struct{}) *Component_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Component_Done_Call) RunAndReturn(run func() <-chan struct{}) *Component_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type Component +func (_mock *Component) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *Component) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// Component_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Component_Ready_Call struct { + *mock.Call } -// NewComponent creates a new instance of Component. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewComponent(t interface { - mock.TestingT - Cleanup(func()) -}) *Component { - mock := &Component{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *Component_Expecter) Ready() *Component_Ready_Call { + return &Component_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *Component_Ready_Call) Run(run func()) *Component_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *Component_Ready_Call) Return(valCh <-chan struct{}) *Component_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Component_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Component_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type Component +func (_mock *Component) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// Component_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type Component_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *Component_Expecter) Start(signalerContext interface{}) *Component_Start_Call { + return &Component_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *Component_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *Component_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Component_Start_Call) Return() *Component_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *Component_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *Component_Start_Call { + _c.Run(run) + return _c } diff --git a/module/component/mock/component_manager_builder.go b/module/component/mock/component_manager_builder.go index 1d0e0f14615..65a92190b77 100644 --- a/module/component/mock/component_manager_builder.go +++ b/module/component/mock/component_manager_builder.go @@ -1,67 +1,136 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - component "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/module/component" mock "github.com/stretchr/testify/mock" ) +// NewComponentManagerBuilder creates a new instance of ComponentManagerBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewComponentManagerBuilder(t interface { + mock.TestingT + Cleanup(func()) +}) *ComponentManagerBuilder { + mock := &ComponentManagerBuilder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ComponentManagerBuilder is an autogenerated mock type for the ComponentManagerBuilder type type ComponentManagerBuilder struct { mock.Mock } -// AddWorker provides a mock function with given fields: _a0 -func (_m *ComponentManagerBuilder) AddWorker(_a0 component.ComponentWorker) component.ComponentManagerBuilder { - ret := _m.Called(_a0) +type ComponentManagerBuilder_Expecter struct { + mock *mock.Mock +} + +func (_m *ComponentManagerBuilder) EXPECT() *ComponentManagerBuilder_Expecter { + return &ComponentManagerBuilder_Expecter{mock: &_m.Mock} +} + +// AddWorker provides a mock function for the type ComponentManagerBuilder +func (_mock *ComponentManagerBuilder) AddWorker(componentWorker component.ComponentWorker) component.ComponentManagerBuilder { + ret := _mock.Called(componentWorker) if len(ret) == 0 { panic("no return value specified for AddWorker") } var r0 component.ComponentManagerBuilder - if rf, ok := ret.Get(0).(func(component.ComponentWorker) component.ComponentManagerBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(component.ComponentWorker) component.ComponentManagerBuilder); ok { + r0 = returnFunc(componentWorker) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(component.ComponentManagerBuilder) } } - return r0 } -// Build provides a mock function with no fields -func (_m *ComponentManagerBuilder) Build() *component.ComponentManager { - ret := _m.Called() +// ComponentManagerBuilder_AddWorker_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddWorker' +type ComponentManagerBuilder_AddWorker_Call struct { + *mock.Call +} + +// AddWorker is a helper method to define mock.On call +// - componentWorker component.ComponentWorker +func (_e *ComponentManagerBuilder_Expecter) AddWorker(componentWorker interface{}) *ComponentManagerBuilder_AddWorker_Call { + return &ComponentManagerBuilder_AddWorker_Call{Call: _e.mock.On("AddWorker", componentWorker)} +} + +func (_c *ComponentManagerBuilder_AddWorker_Call) Run(run func(componentWorker component.ComponentWorker)) *ComponentManagerBuilder_AddWorker_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 component.ComponentWorker + if args[0] != nil { + arg0 = args[0].(component.ComponentWorker) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComponentManagerBuilder_AddWorker_Call) Return(componentManagerBuilder component.ComponentManagerBuilder) *ComponentManagerBuilder_AddWorker_Call { + _c.Call.Return(componentManagerBuilder) + return _c +} + +func (_c *ComponentManagerBuilder_AddWorker_Call) RunAndReturn(run func(componentWorker component.ComponentWorker) component.ComponentManagerBuilder) *ComponentManagerBuilder_AddWorker_Call { + _c.Call.Return(run) + return _c +} + +// Build provides a mock function for the type ComponentManagerBuilder +func (_mock *ComponentManagerBuilder) Build() *component.ComponentManager { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Build") } var r0 *component.ComponentManager - if rf, ok := ret.Get(0).(func() *component.ComponentManager); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *component.ComponentManager); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*component.ComponentManager) } } - return r0 } -// NewComponentManagerBuilder creates a new instance of ComponentManagerBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewComponentManagerBuilder(t interface { - mock.TestingT - Cleanup(func()) -}) *ComponentManagerBuilder { - mock := &ComponentManagerBuilder{} - mock.Mock.Test(t) +// ComponentManagerBuilder_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build' +type ComponentManagerBuilder_Build_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Build is a helper method to define mock.On call +func (_e *ComponentManagerBuilder_Expecter) Build() *ComponentManagerBuilder_Build_Call { + return &ComponentManagerBuilder_Build_Call{Call: _e.mock.On("Build")} +} - return mock +func (_c *ComponentManagerBuilder_Build_Call) Run(run func()) *ComponentManagerBuilder_Build_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ComponentManagerBuilder_Build_Call) Return(componentManager *component.ComponentManager) *ComponentManagerBuilder_Build_Call { + _c.Call.Return(componentManager) + return _c +} + +func (_c *ComponentManagerBuilder_Build_Call) RunAndReturn(run func() *component.ComponentManager) *ComponentManagerBuilder_Build_Call { + _c.Call.Return(run) + return _c } diff --git a/module/dkg/verification.go b/module/dkg/verification.go new file mode 100644 index 00000000000..1e887dded3b --- /dev/null +++ b/module/dkg/verification.go @@ -0,0 +1,108 @@ +package dkg + +import ( + "errors" + "fmt" + + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" +) + +// VerifyBeaconKeyForEpoch verifies that the beacon private key for the current epoch exists, +// is safe to use, and matches the expected public key from the protocol state. +// This function is intended to be called at node startup. When the --require-beacon-key flag is set, +// this function returns an error (and should crash the node). Otherwise, logs a warning and returns nil. +// +// Parameters: +// - log: logger for outputting verification status +// - nodeID: the node's identifier +// - protocolState: the protocol state to query epoch and DKG information +// - beaconKeys: storage for retrieving the beacon private key +// - requireKeyPresent: if false, verification failures are logged as warnings and the function returns nil instead of an error +// +// Returns nil if: +// - requireKeyPresent is false and a verification failure occurs (logged as warning), OR +// - the beacon key exists, is safe, and matches the expected public key, OR +// - the node is not a DKG participant for the current epoch (nothing to verify) +// +// This is a binary validation function and all errors indicate that validation failed, which should be interpreted by the upper layer as an exception. +// Returns an error if: +// - the beacon key is missing from storage +// - the beacon key exists but is marked unsafe +// - the beacon key does not match the expected public key +// - any unexpected error occurs while querying state +func VerifyBeaconKeyForEpoch( + log zerolog.Logger, + nodeID flow.Identifier, + protocolState protocol.State, + beaconKeys storage.SafeBeaconKeys, + requireKeyPresent bool, +) error { + log = log.With().Str("component", "startup_beacon_key_verifier").Logger() + // Get current epoch + currentEpoch, err := protocolState.Final().Epochs().Current() + if err != nil { + return fmt.Errorf("could not get current epoch for beacon key verification: %w", err) + } + epochCounter := currentEpoch.Counter() + + // Check if we're in the DKG committee for this epoch + dkg, err := currentEpoch.DKG() + if err != nil { + return fmt.Errorf("could not get DKG info for epoch %d: %w", epochCounter, err) + } + + // Check if this node is a DKG participant + expectedPubKey, err := dkg.KeyShare(nodeID) + if protocol.IsIdentityNotFound(err) { + log.Info().Uint64("epoch", epochCounter). + Msg("node is not a DKG participant for current epoch, skipping beacon key verification") + return nil + } + if err != nil { + return fmt.Errorf("could not get DKG key share for node %s in epoch %d: %w", nodeID, epochCounter, err) + } + + // Verify beacon key exists and is safe + key, safe, err := beaconKeys.RetrieveMyBeaconPrivateKey(epochCounter) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + if !requireKeyPresent { + log.Warn().Uint64("epoch", epochCounter). + Msg("beacon key not found for current epoch, but --require-beacon-key flag is not set, skipping verification failure") + return nil + } + } + return fmt.Errorf("could not retrieve beacon key for epoch %d from secrets database - cannot participate in consensus: %w", epochCounter, err) + } + + if !requireKeyPresent { + log.Warn().Uint64("epoch", epochCounter). + Msg("beacon key verification failed for current epoch, but --require-beacon-key flag is not set, skipping verification failure") + return nil + } + + if !safe { + return fmt.Errorf("beacon key for epoch %d exists but is marked unsafe - cannot participate in consensus", epochCounter) + } + + if key == nil { + return fmt.Errorf("beacon key for epoch %d is nil - cannot participate in consensus", epochCounter) + } + + // Verify key matches expected public key from protocol state + if !expectedPubKey.Equals(key.PublicKey()) { + return fmt.Errorf("beacon private key does not match expected public key for epoch %d (expected=%s, got=%s)", + epochCounter, expectedPubKey, key.PublicKey()) + } + + log.Info(). + Uint64("epoch", epochCounter). + Str("public_key", expectedPubKey.String()). + Msg("beacon key verified successfully") + + return nil +} diff --git a/module/dkg/verification_test.go b/module/dkg/verification_test.go new file mode 100644 index 00000000000..e4bba9521b6 --- /dev/null +++ b/module/dkg/verification_test.go @@ -0,0 +1,226 @@ +package dkg + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + + "github.com/onflow/crypto" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + mockprotocol "github.com/onflow/flow-go/state/protocol/mock" + "github.com/onflow/flow-go/storage" + mockstorage "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/utils/unittest" +) + +func TestVerifyBeaconKeyForEpoch(t *testing.T) { + suite.Run(t, new(VerifyBeaconKeyForEpochSuite)) +} + +type VerifyBeaconKeyForEpochSuite struct { + suite.Suite + + nodeID flow.Identifier + epochCounter uint64 + state *mockprotocol.State + finalSnapshot *mockprotocol.Snapshot + epochs *mockprotocol.EpochQuery + currentEpoch *mockprotocol.CommittedEpoch + dkg *mockprotocol.DKG + beaconKeys *mockstorage.SafeBeaconKeys +} + +func (s *VerifyBeaconKeyForEpochSuite) SetupTest() { + s.nodeID = unittest.IdentifierFixture() + s.epochCounter = uint64(1) + + s.state = mockprotocol.NewState(s.T()) + s.finalSnapshot = mockprotocol.NewSnapshot(s.T()) + s.epochs = mockprotocol.NewEpochQuery(s.T()) + s.currentEpoch = mockprotocol.NewCommittedEpoch(s.T()) + s.dkg = mockprotocol.NewDKG(s.T()) + s.beaconKeys = mockstorage.NewSafeBeaconKeys(s.T()) + + s.state.On("Final").Return(s.finalSnapshot).Maybe() + s.finalSnapshot.On("Epochs").Return(s.epochs).Maybe() + s.epochs.On("Current").Return(s.currentEpoch, nil).Maybe() + s.currentEpoch.On("Counter").Return(s.epochCounter).Maybe() + s.currentEpoch.On("DKG").Return(s.dkg, nil).Maybe() +} + +// TestHappyPath tests a scenario where: +// - node is a DKG participant +// - beacon key exists and is safe +// - beacon key matches expected public key +// Should return nil (success). +func (s *VerifyBeaconKeyForEpochSuite) TestHappyPath() { + myBeaconKey := unittest.PrivateKeyFixture(crypto.BLSBLS12381) + expectedPubKey := myBeaconKey.PublicKey() + + s.dkg.On("KeyShare", s.nodeID).Return(expectedPubKey, nil).Once() + s.beaconKeys.On("RetrieveMyBeaconPrivateKey", s.epochCounter).Return(myBeaconKey, true, nil).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.NoError(s.T(), err) +} + +// TestRequireKeyPresentFalse tests a scenario where: +// - requireKeyPresent is false +// - node is a DKG participant +// - beacon key is not found in storage +// Should return nil (not fail) because requireKeyPresent is false. +func (s *VerifyBeaconKeyForEpochSuite) TestRequireKeyPresentFalse() { + myBeaconKey := unittest.PrivateKeyFixture(crypto.BLSBLS12381) + expectedPubKey := myBeaconKey.PublicKey() + + s.dkg.On("KeyShare", s.nodeID).Return(expectedPubKey, nil).Once() + s.beaconKeys.On("RetrieveMyBeaconPrivateKey", s.epochCounter).Return(nil, false, storage.ErrNotFound).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, false) + require.NoError(s.T(), err) +} + +// TestNodeNotDKGParticipant tests a scenario where: +// - node is not a DKG participant for the current epoch +// Should return nil (skip verification). +func (s *VerifyBeaconKeyForEpochSuite) TestNodeNotDKGParticipant() { + s.dkg.On("KeyShare", s.nodeID).Return(nil, protocol.IdentityNotFoundError{NodeID: s.nodeID}).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.NoError(s.T(), err) +} + +// TestBeaconKeyNotFound tests a scenario where: +// - node is a DKG participant +// - beacon key is not found in storage +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestBeaconKeyNotFound() { + myBeaconKey := unittest.PrivateKeyFixture(crypto.BLSBLS12381) + expectedPubKey := myBeaconKey.PublicKey() + + s.dkg.On("KeyShare", s.nodeID).Return(expectedPubKey, nil).Once() + s.beaconKeys.On("RetrieveMyBeaconPrivateKey", s.epochCounter).Return(nil, false, storage.ErrNotFound).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.Error(s.T(), err) + require.ErrorIs(s.T(), err, storage.ErrNotFound) + require.Contains(s.T(), err.Error(), "could not retrieve beacon key") +} + +// TestBeaconKeyUnsafe tests a scenario where: +// - node is a DKG participant +// - beacon key exists but is marked as unsafe +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestBeaconKeyUnsafe() { + myBeaconKey := unittest.PrivateKeyFixture(crypto.BLSBLS12381) + expectedPubKey := myBeaconKey.PublicKey() + + s.dkg.On("KeyShare", s.nodeID).Return(expectedPubKey, nil).Once() + s.beaconKeys.On("RetrieveMyBeaconPrivateKey", s.epochCounter).Return(myBeaconKey, false, nil).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.Error(s.T(), err) + require.Contains(s.T(), err.Error(), "marked unsafe") +} + +// TestBeaconKeyNil tests a scenario where: +// - node is a DKG participant +// - beacon key is safe but nil +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestBeaconKeyNil() { + myBeaconKey := unittest.PrivateKeyFixture(crypto.BLSBLS12381) + expectedPubKey := myBeaconKey.PublicKey() + + s.dkg.On("KeyShare", s.nodeID).Return(expectedPubKey, nil).Once() + s.beaconKeys.On("RetrieveMyBeaconPrivateKey", s.epochCounter).Return(nil, true, nil).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.Error(s.T(), err) + require.Contains(s.T(), err.Error(), "is nil") +} + +// TestPublicKeyMismatch tests a scenario where: +// - node is a DKG participant +// - beacon key exists and is safe +// - beacon key does NOT match expected public key +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestPublicKeyMismatch() { + myBeaconKey := unittest.PrivateKeyFixture(crypto.BLSBLS12381) + differentPubKey := unittest.PublicKeysFixture(1, crypto.BLSBLS12381)[0] + + s.dkg.On("KeyShare", s.nodeID).Return(differentPubKey, nil).Once() + s.beaconKeys.On("RetrieveMyBeaconPrivateKey", s.epochCounter).Return(myBeaconKey, true, nil).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.Error(s.T(), err) + require.Contains(s.T(), err.Error(), "does not match expected public key") +} + +// TestGetCurrentEpochError tests a scenario where: +// - error getting current epoch from protocol state +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestGetCurrentEpochError() { + exception := errors.New("exception") + + // Create fresh mocks for this test to avoid conflicts with SetupTest + state := mockprotocol.NewState(s.T()) + finalSnapshot := mockprotocol.NewSnapshot(s.T()) + epochs := mockprotocol.NewEpochQuery(s.T()) + beaconKeys := mockstorage.NewSafeBeaconKeys(s.T()) + + state.On("Final").Return(finalSnapshot) + finalSnapshot.On("Epochs").Return(epochs) + epochs.On("Current").Return(nil, exception).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, state, beaconKeys, true) + require.Error(s.T(), err) + require.ErrorIs(s.T(), err, exception) +} + +// TestGetDKGError tests a scenario where: +// - error getting DKG info from current epoch +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestGetDKGError() { + exception := errors.New("exception") + + s.currentEpoch.On("DKG").Unset() + s.currentEpoch.On("DKG").Return(nil, exception).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.Error(s.T(), err) + require.ErrorIs(s.T(), err, exception) +} + +// TestGetKeyShareException tests a scenario where: +// - unexpected error getting key share (not IdentityNotFoundError) +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestGetKeyShareException() { + exception := errors.New("exception") + + s.dkg.On("KeyShare", s.nodeID).Return(nil, exception).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.Error(s.T(), err) + require.ErrorIs(s.T(), err, exception) +} + +// TestRetrieveKeyException tests a scenario where: +// - node is a DKG participant +// - unexpected error retrieving beacon key (not ErrNotFound) +// Should return error. +func (s *VerifyBeaconKeyForEpochSuite) TestRetrieveKeyException() { + exception := errors.New("exception") + myBeaconKey := unittest.PrivateKeyFixture(crypto.BLSBLS12381) + expectedPubKey := myBeaconKey.PublicKey() + + s.dkg.On("KeyShare", s.nodeID).Return(expectedPubKey, nil).Once() + s.beaconKeys.On("RetrieveMyBeaconPrivateKey", s.epochCounter).Return(nil, false, exception).Once() + + err := VerifyBeaconKeyForEpoch(unittest.Logger(), s.nodeID, s.state, s.beaconKeys, true) + require.Error(s.T(), err) + require.ErrorIs(s.T(), err, exception) +} diff --git a/module/epochs/epoch_lookup_test.go b/module/epochs/epoch_lookup_test.go index 41e7efc079b..7feeaa32171 100644 --- a/module/epochs/epoch_lookup_test.go +++ b/module/epochs/epoch_lookup_test.go @@ -268,17 +268,24 @@ func (suite *EpochLookupSuite) TestProtocolEvents_EpochExtended_SanityChecks() { FinalView: suite.currEpoch.finalView + 100, } + throwCalled := make(chan struct{}) ctx.On("Throw", mock.AnythingOfType("*errors.errorString")).Run(func(args mock.Arguments) { err, ok := args.Get(0).(error) assert.True(suite.T(), ok) assert.Contains(suite.T(), err.Error(), fmt.Sprintf(invalidEpochViewSequence, extension.FirstView, suite.currEpoch.finalView)) + close(throwCalled) }) suite.lookup.EpochExtended(suite.currEpoch.epochCounter, nil, extension) // wait for the protocol event to be processed (async) assert.Eventually(suite.T(), func() bool { - return len(suite.lookup.epochEvents) == 0 + select { + case <-throwCalled: + return len(suite.lookup.epochEvents) == 0 + default: + return false + } }, 2*time.Second, 50*time.Millisecond) }) } diff --git a/module/epochs/machine_account.go b/module/epochs/machine_account.go index 08451e1273e..df696e1e428 100644 --- a/module/epochs/machine_account.go +++ b/module/epochs/machine_account.go @@ -23,49 +23,39 @@ import ( ) var ( - // Hard and soft balance limits for collection and consensus nodes. - // We will log a warning once for a soft limit, and will log an error - // in perpetuity for a hard limit. + // Balance limits for collection and consensus nodes. // Taken from https://www.notion.so/dapperlabs/Machine-Account-f3c293593ea442a39614fcebf705a132 - // TODO update these for FLIP74 - defaultSoftMinBalanceLN cadence.UFix64 - defaultHardMinBalanceLN cadence.UFix64 - defaultSoftMinBalanceSN cadence.UFix64 - defaultHardMinBalanceSN cadence.UFix64 + cdcRecommendedMinBalanceLN cadence.UFix64 + cdcRecommendedMinBalanceSN cadence.UFix64 ) const ( - recommendedMinBalanceLN = 0.002 - recommendedMinBalanceSN = 0.05 + // We recommend node operators refill once they reach this threshold + recommendedMinBalanceLN = 0.25 + recommendedMinBalanceSN = 2.0 + recommendedRefillToBalanceLN = 0.75 + recommendedRefillToBalanceSN = 6.0 ) func init() { var err error - defaultSoftMinBalanceLN, err = cadence.NewUFix64("0.0025") - if err != nil { - panic(fmt.Errorf("could not convert soft min balance for LN: %w", err)) - } - defaultHardMinBalanceLN, err = cadence.NewUFix64("0.002") + cdcRecommendedMinBalanceLN, err = cadence.NewUFix64("0.25") if err != nil { panic(fmt.Errorf("could not convert hard min balance for LN: %w", err)) } - defaultSoftMinBalanceSN, err = cadence.NewUFix64("0.125") - if err != nil { - panic(fmt.Errorf("could not convert soft min balance for SN: %w", err)) - } - defaultHardMinBalanceSN, err = cadence.NewUFix64("0.05") + cdcRecommendedMinBalanceSN, err = cadence.NewUFix64("2.0") if err != nil { panic(fmt.Errorf("could not convert hard min balance for SN: %w", err)) } // sanity checks - if asFloat, err := ufix64Tofloat64(defaultHardMinBalanceLN); err != nil { + if asFloat, err := ufix64Tofloat64(cdcRecommendedMinBalanceLN); err != nil { panic(err) } else if asFloat != recommendedMinBalanceLN { panic(fmt.Errorf("failed sanity check: %f!=%f", asFloat, recommendedMinBalanceLN)) } - if asFloat, err := ufix64Tofloat64(defaultHardMinBalanceSN); err != nil { + if asFloat, err := ufix64Tofloat64(cdcRecommendedMinBalanceSN); err != nil { panic(err) } else if asFloat != recommendedMinBalanceSN { panic(fmt.Errorf("failed sanity check: %f!=%f", asFloat, recommendedMinBalanceSN)) @@ -91,18 +81,14 @@ func checkMachineAccountRetryBackoff() retry.Backoff { // MachineAccountValidatorConfig defines configuration options for MachineAccountConfigValidator. type MachineAccountValidatorConfig struct { - SoftMinBalanceLN cadence.UFix64 HardMinBalanceLN cadence.UFix64 - SoftMinBalanceSN cadence.UFix64 HardMinBalanceSN cadence.UFix64 } func DefaultMachineAccountValidatorConfig() MachineAccountValidatorConfig { return MachineAccountValidatorConfig{ - SoftMinBalanceLN: defaultSoftMinBalanceLN, - HardMinBalanceLN: defaultHardMinBalanceLN, - SoftMinBalanceSN: defaultSoftMinBalanceSN, - HardMinBalanceSN: defaultHardMinBalanceSN, + HardMinBalanceLN: cdcRecommendedMinBalanceLN, + HardMinBalanceSN: cdcRecommendedMinBalanceSN, } } @@ -110,9 +96,7 @@ func DefaultMachineAccountValidatorConfig() MachineAccountValidatorConfig { // balance checks. This is useful for test networks where transaction fees are // disabled. func WithoutBalanceChecks(conf *MachineAccountValidatorConfig) { - conf.SoftMinBalanceLN = 0 conf.HardMinBalanceLN = 0 - conf.SoftMinBalanceSN = 0 conf.HardMinBalanceSN = 0 } @@ -323,17 +307,11 @@ func CheckMachineAccountInfo( switch role { case flow.RoleCollection: if balance < conf.HardMinBalanceLN { - return fmt.Errorf("machine account balance is below hard minimum (%s < %s)", balance, conf.HardMinBalanceLN) - } - if balance < conf.SoftMinBalanceLN { - log.Warn().Msgf("machine account balance is below recommended balance (%s < %s)", balance, conf.SoftMinBalanceLN) + return fmt.Errorf("machine account balance is below minimum (%s < %s). Please refill to %f FLOW", balance, conf.HardMinBalanceLN, recommendedRefillToBalanceLN) } case flow.RoleConsensus: if balance < conf.HardMinBalanceSN { - return fmt.Errorf("machine account balance is below hard minimum (%s < %s)", balance, conf.HardMinBalanceSN) - } - if balance < conf.SoftMinBalanceSN { - log.Warn().Msgf("machine account balance is below recommended balance (%s < %s)", balance, conf.SoftMinBalanceSN) + return fmt.Errorf("machine account balance is below minimum (%s < %s). Please refill to %f FLOW", balance, conf.HardMinBalanceSN, recommendedRefillToBalanceSN) } default: // sanity check - should be caught earlier in this function diff --git a/module/epochs/machine_account_test.go b/module/epochs/machine_account_test.go index e80af3e31ce..2c6bbec9c3c 100644 --- a/module/epochs/machine_account_test.go +++ b/module/epochs/machine_account_test.go @@ -82,13 +82,13 @@ func TestMachineAccountChecking(t *testing.T) { t.Run("account with < hard minimum balance", func(t *testing.T) { t.Run("collection", func(t *testing.T) { local, remote := unittest.MachineAccountFixture(t) - remote.Balance = uint64(defaultHardMinBalanceLN) - 1 + remote.Balance = uint64(cdcRecommendedMinBalanceLN) - 1 err := CheckMachineAccountInfo(zerolog.Nop(), conf, flow.RoleCollection, local, remote) require.Error(t, err) }) t.Run("consensus", func(t *testing.T) { local, remote := unittest.MachineAccountFixture(t) - remote.Balance = uint64(defaultHardMinBalanceSN) - 1 + remote.Balance = uint64(cdcRecommendedMinBalanceSN) - 1 err := CheckMachineAccountInfo(zerolog.Nop(), conf, flow.RoleConsensus, local, remote) require.Error(t, err) }) @@ -115,29 +115,6 @@ func TestMachineAccountChecking(t *testing.T) { }) }) - // should log a warning when balance below soft minimum balance (but not - // below hard minimum balance) - t.Run("account with < soft minimum balance", func(t *testing.T) { - t.Run("collection", func(t *testing.T) { - local, remote := unittest.MachineAccountFixture(t) - remote.Balance = uint64(defaultSoftMinBalanceLN) - 1 - log, hook := unittest.HookedLogger() - - err := CheckMachineAccountInfo(log, conf, flow.RoleCollection, local, remote) - assert.NoError(t, err) - assert.Regexp(t, "machine account balance is below recommended balance", hook.Logs()) - }) - t.Run("consensus", func(t *testing.T) { - local, remote := unittest.MachineAccountFixture(t) - remote.Balance = uint64(defaultSoftMinBalanceSN) - 1 - log, hook := unittest.HookedLogger() - - err := CheckMachineAccountInfo(log, conf, flow.RoleConsensus, local, remote) - assert.NoError(t, err) - assert.Regexp(t, "machine account balance is below recommended balance", hook.Logs()) - }) - }) - // should log a warning when the local file deviates from defaults t.Run("local file deviates from defaults", func(t *testing.T) { t.Run("hash algo", func(t *testing.T) { @@ -187,8 +164,8 @@ func TestMachineAccountValidatorBackoff_Overflow(t *testing.T) { backoff := checkMachineAccountRetryBackoff() // once the backoff reaches the maximum, it should remain in [(1-jitter)*max,(1+jitter*max)] - max := checkMachineAccountRetryMax + checkMachineAccountRetryMax*(checkMachineAccountRetryJitterPct+1)/100 - min := checkMachineAccountRetryMax - checkMachineAccountRetryMax*(checkMachineAccountRetryJitterPct+1)/100 + maxBackoff := checkMachineAccountRetryMax + checkMachineAccountRetryMax*(checkMachineAccountRetryJitterPct+1)/100 + minBackoff := checkMachineAccountRetryMax - checkMachineAccountRetryMax*(checkMachineAccountRetryJitterPct+1)/100 lastWait, stop := backoff.Next() assert.False(t, stop) @@ -199,8 +176,8 @@ func TestMachineAccountValidatorBackoff_Overflow(t *testing.T) { // * strictly increase, or // * be within range of max duration + jitter if wait < lastWait { - assert.Less(t, min, wait) - assert.Less(t, wait, max) + assert.Less(t, minBackoff, wait) + assert.Less(t, wait, maxBackoff) } lastWait = wait } diff --git a/module/errors.go b/module/errors.go index 5d91dafa8f6..60ae9bf72c7 100644 --- a/module/errors.go +++ b/module/errors.go @@ -10,7 +10,7 @@ type UnknownBlockError struct { err error } -func NewUnknownBlockError(msg string, args ...interface{}) error { +func NewUnknownBlockError(msg string, args ...any) error { return UnknownBlockError{ err: fmt.Errorf(msg, args...), } @@ -34,7 +34,7 @@ type UnknownResultError struct { err error } -func NewUnknownResultError(msg string, args ...interface{}) error { +func NewUnknownResultError(msg string, args ...any) error { return UnknownResultError{ err: fmt.Errorf(msg, args...), } diff --git a/module/execution/mock/script_executor.go b/module/execution/mock/script_executor.go index b33420f17f1..1f9a45e78be 100644 --- a/module/execution/mock/script_executor.go +++ b/module/execution/mock/script_executor.go @@ -1,23 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" + "context" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewScriptExecutor creates a new instance of ScriptExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScriptExecutor(t interface { + mock.TestingT + Cleanup(func()) +}) *ScriptExecutor { + mock := &ScriptExecutor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ScriptExecutor is an autogenerated mock type for the ScriptExecutor type type ScriptExecutor struct { mock.Mock } -// ExecuteAtBlockHeight provides a mock function with given fields: ctx, script, arguments, height -func (_m *ScriptExecutor) ExecuteAtBlockHeight(ctx context.Context, script []byte, arguments [][]byte, height uint64) ([]byte, error) { - ret := _m.Called(ctx, script, arguments, height) +type ScriptExecutor_Expecter struct { + mock *mock.Mock +} + +func (_m *ScriptExecutor) EXPECT() *ScriptExecutor_Expecter { + return &ScriptExecutor_Expecter{mock: &_m.Mock} +} + +// ExecuteAtBlockHeight provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) ExecuteAtBlockHeight(ctx context.Context, script []byte, arguments [][]byte, height uint64) ([]byte, error) { + ret := _mock.Called(ctx, script, arguments, height) if len(ret) == 0 { panic("no return value specified for ExecuteAtBlockHeight") @@ -25,29 +49,79 @@ func (_m *ScriptExecutor) ExecuteAtBlockHeight(ctx context.Context, script []byt var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, uint64) ([]byte, error)); ok { - return rf(ctx, script, arguments, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, uint64) ([]byte, error)); ok { + return returnFunc(ctx, script, arguments, height) } - if rf, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, uint64) []byte); ok { - r0 = rf(ctx, script, arguments, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, uint64) []byte); ok { + r0 = returnFunc(ctx, script, arguments, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, [][]byte, uint64) error); ok { - r1 = rf(ctx, script, arguments, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, [][]byte, uint64) error); ok { + r1 = returnFunc(ctx, script, arguments, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtBlockHeight provides a mock function with given fields: ctx, address, height -func (_m *ScriptExecutor) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { - ret := _m.Called(ctx, address, height) +// ScriptExecutor_ExecuteAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteAtBlockHeight' +type ScriptExecutor_ExecuteAtBlockHeight_Call struct { + *mock.Call +} + +// ExecuteAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - script []byte +// - arguments [][]byte +// - height uint64 +func (_e *ScriptExecutor_Expecter) ExecuteAtBlockHeight(ctx interface{}, script interface{}, arguments interface{}, height interface{}) *ScriptExecutor_ExecuteAtBlockHeight_Call { + return &ScriptExecutor_ExecuteAtBlockHeight_Call{Call: _e.mock.On("ExecuteAtBlockHeight", ctx, script, arguments, height)} +} + +func (_c *ScriptExecutor_ExecuteAtBlockHeight_Call) Run(run func(ctx context.Context, script []byte, arguments [][]byte, height uint64)) *ScriptExecutor_ExecuteAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 [][]byte + if args[2] != nil { + arg2 = args[2].([][]byte) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScriptExecutor_ExecuteAtBlockHeight_Call) Return(bytes []byte, err error) *ScriptExecutor_ExecuteAtBlockHeight_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ScriptExecutor_ExecuteAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, script []byte, arguments [][]byte, height uint64) ([]byte, error)) *ScriptExecutor_ExecuteAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtBlockHeight provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountAtBlockHeight") @@ -55,29 +129,73 @@ func (_m *ScriptExecutor) GetAccountAtBlockHeight(ctx context.Context, address f var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { + r0 = returnFunc(ctx, address, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAvailableBalance provides a mock function with given fields: ctx, address, height -func (_m *ScriptExecutor) GetAccountAvailableBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { - ret := _m.Called(ctx, address, height) +// ScriptExecutor_GetAccountAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockHeight' +type ScriptExecutor_GetAccountAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *ScriptExecutor_Expecter) GetAccountAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *ScriptExecutor_GetAccountAtBlockHeight_Call { + return &ScriptExecutor_GetAccountAtBlockHeight_Call{Call: _e.mock.On("GetAccountAtBlockHeight", ctx, address, height)} +} + +func (_c *ScriptExecutor_GetAccountAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *ScriptExecutor_GetAccountAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetAccountAtBlockHeight_Call) Return(account *flow.Account, err error) *ScriptExecutor_GetAccountAtBlockHeight_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *ScriptExecutor_GetAccountAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error)) *ScriptExecutor_GetAccountAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAvailableBalance provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetAccountAvailableBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountAvailableBalance") @@ -85,27 +203,71 @@ func (_m *ScriptExecutor) GetAccountAvailableBalance(ctx context.Context, addres var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { + r0 = returnFunc(ctx, address, height) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountBalance provides a mock function with given fields: ctx, address, height -func (_m *ScriptExecutor) GetAccountBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { - ret := _m.Called(ctx, address, height) +// ScriptExecutor_GetAccountAvailableBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAvailableBalance' +type ScriptExecutor_GetAccountAvailableBalance_Call struct { + *mock.Call +} + +// GetAccountAvailableBalance is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *ScriptExecutor_Expecter) GetAccountAvailableBalance(ctx interface{}, address interface{}, height interface{}) *ScriptExecutor_GetAccountAvailableBalance_Call { + return &ScriptExecutor_GetAccountAvailableBalance_Call{Call: _e.mock.On("GetAccountAvailableBalance", ctx, address, height)} +} + +func (_c *ScriptExecutor_GetAccountAvailableBalance_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *ScriptExecutor_GetAccountAvailableBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetAccountAvailableBalance_Call) Return(v uint64, err error) *ScriptExecutor_GetAccountAvailableBalance_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScriptExecutor_GetAccountAvailableBalance_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (uint64, error)) *ScriptExecutor_GetAccountAvailableBalance_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountBalance provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetAccountBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountBalance") @@ -113,27 +275,151 @@ func (_m *ScriptExecutor) GetAccountBalance(ctx context.Context, address flow.Ad var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (uint64, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) uint64); ok { + r0 = returnFunc(ctx, address, height) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) } else { r1 = ret.Error(1) } + return r0, r1 +} + +// ScriptExecutor_GetAccountBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountBalance' +type ScriptExecutor_GetAccountBalance_Call struct { + *mock.Call +} + +// GetAccountBalance is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *ScriptExecutor_Expecter) GetAccountBalance(ctx interface{}, address interface{}, height interface{}) *ScriptExecutor_GetAccountBalance_Call { + return &ScriptExecutor_GetAccountBalance_Call{Call: _e.mock.On("GetAccountBalance", ctx, address, height)} +} +func (_c *ScriptExecutor_GetAccountBalance_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *ScriptExecutor_GetAccountBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetAccountBalance_Call) Return(v uint64, err error) *ScriptExecutor_GetAccountBalance_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScriptExecutor_GetAccountBalance_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (uint64, error)) *ScriptExecutor_GetAccountBalance_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountCode provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetAccountCode(ctx context.Context, address flow.Address, contractName string, height uint64) ([]byte, error) { + ret := _mock.Called(ctx, address, contractName, height) + + if len(ret) == 0 { + panic("no return value specified for GetAccountCode") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, string, uint64) ([]byte, error)); ok { + return returnFunc(ctx, address, contractName, height) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, string, uint64) []byte); ok { + r0 = returnFunc(ctx, address, contractName, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, string, uint64) error); ok { + r1 = returnFunc(ctx, address, contractName, height) + } else { + r1 = ret.Error(1) + } return r0, r1 } -// GetAccountKey provides a mock function with given fields: ctx, address, keyIndex, height -func (_m *ScriptExecutor) GetAccountKey(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, keyIndex, height) +// ScriptExecutor_GetAccountCode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountCode' +type ScriptExecutor_GetAccountCode_Call struct { + *mock.Call +} + +// GetAccountCode is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - contractName string +// - height uint64 +func (_e *ScriptExecutor_Expecter) GetAccountCode(ctx interface{}, address interface{}, contractName interface{}, height interface{}) *ScriptExecutor_GetAccountCode_Call { + return &ScriptExecutor_GetAccountCode_Call{Call: _e.mock.On("GetAccountCode", ctx, address, contractName, height)} +} + +func (_c *ScriptExecutor_GetAccountCode_Call) Run(run func(ctx context.Context, address flow.Address, contractName string, height uint64)) *ScriptExecutor_GetAccountCode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetAccountCode_Call) Return(bytes []byte, err error) *ScriptExecutor_GetAccountCode_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ScriptExecutor_GetAccountCode_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, contractName string, height uint64) ([]byte, error)) *ScriptExecutor_GetAccountCode_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKey provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetAccountKey(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, keyIndex, height) if len(ret) == 0 { panic("no return value specified for GetAccountKey") @@ -141,29 +427,79 @@ func (_m *ScriptExecutor) GetAccountKey(ctx context.Context, address flow.Addres var r0 *flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountPublicKey, error)); ok { - return rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) (*flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, keyIndex, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountPublicKey); ok { - r0 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint32, uint64) *flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, keyIndex, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.AccountPublicKey) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { - r1 = rf(ctx, address, keyIndex, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint32, uint64) error); ok { + r1 = returnFunc(ctx, address, keyIndex, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountKeys provides a mock function with given fields: ctx, address, height -func (_m *ScriptExecutor) GetAccountKeys(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { - ret := _m.Called(ctx, address, height) +// ScriptExecutor_GetAccountKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKey' +type ScriptExecutor_GetAccountKey_Call struct { + *mock.Call +} + +// GetAccountKey is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - keyIndex uint32 +// - height uint64 +func (_e *ScriptExecutor_Expecter) GetAccountKey(ctx interface{}, address interface{}, keyIndex interface{}, height interface{}) *ScriptExecutor_GetAccountKey_Call { + return &ScriptExecutor_GetAccountKey_Call{Call: _e.mock.On("GetAccountKey", ctx, address, keyIndex, height)} +} + +func (_c *ScriptExecutor_GetAccountKey_Call) Run(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64)) *ScriptExecutor_GetAccountKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint32 + if args[2] != nil { + arg2 = args[2].(uint32) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetAccountKey_Call) Return(accountPublicKey *flow.AccountPublicKey, err error) *ScriptExecutor_GetAccountKey_Call { + _c.Call.Return(accountPublicKey, err) + return _c +} + +func (_c *ScriptExecutor_GetAccountKey_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error)) *ScriptExecutor_GetAccountKey_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountKeys provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetAccountKeys(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { + ret := _mock.Called(ctx, address, height) if len(ret) == 0 { panic("no return value specified for GetAccountKeys") @@ -171,36 +507,196 @@ func (_m *ScriptExecutor) GetAccountKeys(ctx context.Context, address flow.Addre var r0 []flow.AccountPublicKey var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]flow.AccountPublicKey, error)); ok { - return rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) ([]flow.AccountPublicKey, error)); ok { + return returnFunc(ctx, address, height) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []flow.AccountPublicKey); ok { - r0 = rf(ctx, address, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) []flow.AccountPublicKey); ok { + r0 = returnFunc(ctx, address, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.AccountPublicKey) } } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} - if rf, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { - r1 = rf(ctx, address, height) +// ScriptExecutor_GetAccountKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountKeys' +type ScriptExecutor_GetAccountKeys_Call struct { + *mock.Call +} + +// GetAccountKeys is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *ScriptExecutor_Expecter) GetAccountKeys(ctx interface{}, address interface{}, height interface{}) *ScriptExecutor_GetAccountKeys_Call { + return &ScriptExecutor_GetAccountKeys_Call{Call: _e.mock.On("GetAccountKeys", ctx, address, height)} +} + +func (_c *ScriptExecutor_GetAccountKeys_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *ScriptExecutor_GetAccountKeys_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetAccountKeys_Call) Return(accountPublicKeys []flow.AccountPublicKey, err error) *ScriptExecutor_GetAccountKeys_Call { + _c.Call.Return(accountPublicKeys, err) + return _c +} + +func (_c *ScriptExecutor_GetAccountKeys_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error)) *ScriptExecutor_GetAccountKeys_Call { + _c.Call.Return(run) + return _c +} + +// GetStorageSnapshot provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) GetStorageSnapshot(height uint64) (snapshot.StorageSnapshot, error) { + ret := _mock.Called(height) + + if len(ret) == 0 { + panic("no return value specified for GetStorageSnapshot") + } + + var r0 snapshot.StorageSnapshot + var r1 error + if returnFunc, ok := ret.Get(0).(func(uint64) (snapshot.StorageSnapshot, error)); ok { + return returnFunc(height) + } + if returnFunc, ok := ret.Get(0).(func(uint64) snapshot.StorageSnapshot); ok { + r0 = returnFunc(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(snapshot.StorageSnapshot) + } + } + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } + return r0, r1 +} +// ScriptExecutor_GetStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStorageSnapshot' +type ScriptExecutor_GetStorageSnapshot_Call struct { + *mock.Call +} + +// GetStorageSnapshot is a helper method to define mock.On call +// - height uint64 +func (_e *ScriptExecutor_Expecter) GetStorageSnapshot(height interface{}) *ScriptExecutor_GetStorageSnapshot_Call { + return &ScriptExecutor_GetStorageSnapshot_Call{Call: _e.mock.On("GetStorageSnapshot", height)} +} + +func (_c *ScriptExecutor_GetStorageSnapshot_Call) Run(run func(height uint64)) *ScriptExecutor_GetStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScriptExecutor_GetStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot, err error) *ScriptExecutor_GetStorageSnapshot_Call { + _c.Call.Return(storageSnapshot, err) + return _c +} + +func (_c *ScriptExecutor_GetStorageSnapshot_Call) RunAndReturn(run func(height uint64) (snapshot.StorageSnapshot, error)) *ScriptExecutor_GetStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// RegisterValue provides a mock function for the type ScriptExecutor +func (_mock *ScriptExecutor) RegisterValue(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { + ret := _mock.Called(ID, height) + + if len(ret) == 0 { + panic("no return value specified for RegisterValue") + } + + var r0 flow.RegisterValue + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { + return returnFunc(ID, height) + } + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { + r0 = returnFunc(ID, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(flow.RegisterValue) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { + r1 = returnFunc(ID, height) + } else { + r1 = ret.Error(1) + } return r0, r1 } -// NewScriptExecutor creates a new instance of ScriptExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewScriptExecutor(t interface { - mock.TestingT - Cleanup(func()) -}) *ScriptExecutor { - mock := &ScriptExecutor{} - mock.Mock.Test(t) +// ScriptExecutor_RegisterValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterValue' +type ScriptExecutor_RegisterValue_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RegisterValue is a helper method to define mock.On call +// - ID flow.RegisterID +// - height uint64 +func (_e *ScriptExecutor_Expecter) RegisterValue(ID interface{}, height interface{}) *ScriptExecutor_RegisterValue_Call { + return &ScriptExecutor_RegisterValue_Call{Call: _e.mock.On("RegisterValue", ID, height)} +} - return mock +func (_c *ScriptExecutor_RegisterValue_Call) Run(run func(ID flow.RegisterID, height uint64)) *ScriptExecutor_RegisterValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ScriptExecutor_RegisterValue_Call) Return(v flow.RegisterValue, err error) *ScriptExecutor_RegisterValue_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScriptExecutor_RegisterValue_Call) RunAndReturn(run func(ID flow.RegisterID, height uint64) (flow.RegisterValue, error)) *ScriptExecutor_RegisterValue_Call { + _c.Call.Return(run) + return _c } diff --git a/module/execution/scripts.go b/module/execution/scripts.go index 50a3b93c7da..6eba3db28cf 100644 --- a/module/execution/scripts.go +++ b/module/execution/scripts.go @@ -2,6 +2,7 @@ package execution import ( "context" + "errors" "github.com/rs/zerolog" @@ -20,17 +21,20 @@ import ( // RegisterAtHeight returns register value for provided register ID at the block height. // Even if the register wasn't indexed at the provided height, returns the highest height the register was indexed at. // If the register with the ID was not indexed at all return nil value and no error. -// Expected errors: -// - storage.ErrHeightNotIndexed if the given height was not indexed yet or lower than the first indexed height. +// +// Expected error returns during normal operation +// - [storage.ErrNotFound] if the register is not found at the given height. +// - [storage.ErrHeightNotIndexed] if the given height was not indexed yet or lower than the first indexed height. type RegisterAtHeight func(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) type ScriptExecutor interface { // ExecuteAtBlockHeight executes provided script against the block height. // A result value is returned encoded as byte array. An error will be returned if script // doesn't successfully execute. - // Expected errors: - // - storage.ErrNotFound if block or register value at height was not found. - // - storage.ErrHeightNotIndexed if the data for the block height is not available + // + // Expected error returns during normal operation + // - [storage.ErrNotFound] if block or register value at height was not found. + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available ExecuteAtBlockHeight( ctx context.Context, script []byte, @@ -39,29 +43,52 @@ type ScriptExecutor interface { ) ([]byte, error) // GetAccountAtBlockHeight returns a Flow account by the provided address and block height. - // Expected errors: - // - storage.ErrHeightNotIndexed if the data for the block height is not available + // + // Expected error returns during normal operation + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) // GetAccountBalance returns a Flow account balance by the provided address and block height. - // Expected errors: - // - storage.ErrHeightNotIndexed if the data for the block height is not available + // + // Expected error returns during normal operation + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available GetAccountBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) // GetAccountAvailableBalance returns a Flow account available balance by the provided address and block height. - // Expected errors: - // - storage.ErrHeightNotIndexed if the data for the block height is not available + // + // Expected error returns during normal operation + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available GetAccountAvailableBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) // GetAccountKeys returns a Flow account public keys by the provided address and block height. - // Expected errors: - // - storage.ErrHeightNotIndexed if the data for the block height is not available + // + // Expected error returns during normal operation + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available GetAccountKeys(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) // GetAccountKey returns a Flow account public key by the provided address, block height and index. - // Expected errors: - // - storage.ErrHeightNotIndexed if the data for the block height is not available + // + // Expected error returns during normal operation + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available GetAccountKey(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) + + // GetAccountCode returns a Flow account code by the provided address, contract name and block height. + // + // Expected error returns during normal operation: + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available + GetAccountCode(ctx context.Context, address flow.Address, contractName string, height uint64) ([]byte, error) + + // RegisterValue retrieves register values by the register IDs at the provided block height. + // + // Expected error returns during normal operation + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available + RegisterValue(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) + + // GetStorageSnapshot returns a storage snapshot at the provided block height. + // + // Expected error returns during normal operation + // - [storage.ErrHeightNotIndexed] if the data for the block height is not available + GetStorageSnapshot(height uint64) (snapshot.StorageSnapshot, error) } var _ ScriptExecutor = (*Scripts)(nil) @@ -89,12 +116,13 @@ func NewScripts( chainID, false, true, + false, ) blocks := environment.NewBlockFinder(header) options = append(options, fvm.WithBlocks(blocks)) // add blocks for getBlocks calls in scripts options = append(options, fvm.WithMetricsReporter(metrics)) options = append(options, fvm.WithAllowProgramCacheWritesInScriptsEnabled(enableProgramCacheWrites)) - vmCtx := fvm.NewContext(options...) + vmCtx := fvm.NewContext(chainID.Chain(), options...) queryExecutor := query.NewQueryExecutor( queryConf, @@ -116,9 +144,10 @@ func NewScripts( // ExecuteAtBlockHeight executes provided script against the block height. // A result value is returned encoded as byte array. An error will be returned if script // doesn't successfully execute. -// Expected errors: -// - Script execution related errors -// - storage.ErrHeightNotIndexed if the data for the block height is not available +// +// Expected error returns during normal operation +// - Script execution related errors +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available func (s *Scripts) ExecuteAtBlockHeight( ctx context.Context, script []byte, @@ -138,9 +167,10 @@ func (s *Scripts) ExecuteAtBlockHeight( } // GetAccountAtBlockHeight returns a Flow account by the provided address and block height. -// Expected errors: -// - Script execution related errors -// - storage.ErrHeightNotIndexed if the data for the block height is not available +// +// Expected error returns during normal operation +// - Script execution related errors +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available func (s *Scripts) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { snap, header, err := s.snapshotWithBlock(height) if err != nil { @@ -151,9 +181,10 @@ func (s *Scripts) GetAccountAtBlockHeight(ctx context.Context, address flow.Addr } // GetAccountBalance returns a balance of Flow account by the provided address and block height. -// Expected errors: -// - Script execution related errors -// - storage.ErrHeightNotIndexed if the data for the block height is not available +// +// Expected error returns during normal operation +// - Script execution related errors +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available func (s *Scripts) GetAccountBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { snap, header, err := s.snapshotWithBlock(height) if err != nil { @@ -164,9 +195,10 @@ func (s *Scripts) GetAccountBalance(ctx context.Context, address flow.Address, h } // GetAccountAvailableBalance returns an available balance of Flow account by the provided address and block height. -// Expected errors: -// - Script execution related errors -// - storage.ErrHeightNotIndexed if the data for the block height is not available +// +// Expected error returns during normal operation +// - Script execution related errors +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available func (s *Scripts) GetAccountAvailableBalance(ctx context.Context, address flow.Address, height uint64) (uint64, error) { snap, header, err := s.snapshotWithBlock(height) if err != nil { @@ -177,9 +209,10 @@ func (s *Scripts) GetAccountAvailableBalance(ctx context.Context, address flow.A } // GetAccountKeys returns a public keys of Flow account by the provided address and block height. -// Expected errors: -// - Script execution related errors -// - storage.ErrHeightNotIndexed if the data for the block height is not available +// +// Expected error returns during normal operation +// - Script execution related errors +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available func (s *Scripts) GetAccountKeys(ctx context.Context, address flow.Address, height uint64) ([]flow.AccountPublicKey, error) { snap, header, err := s.snapshotWithBlock(height) if err != nil { @@ -190,9 +223,10 @@ func (s *Scripts) GetAccountKeys(ctx context.Context, address flow.Address, heig } // GetAccountKey returns a public key of Flow account by the provided address, block height and index. -// Expected errors: -// - Script execution related errors -// - storage.ErrHeightNotIndexed if the data for the block height is not available +// +// Expected error returns during normal operation +// - Script execution related errors +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available func (s *Scripts) GetAccountKey(ctx context.Context, address flow.Address, keyIndex uint32, height uint64) (*flow.AccountPublicKey, error) { snap, header, err := s.snapshotWithBlock(height) if err != nil { @@ -202,8 +236,41 @@ func (s *Scripts) GetAccountKey(ctx context.Context, address flow.Address, keyIn return s.executor.GetAccountKey(ctx, address, keyIndex, header, snap) } +// GetAccountCode returns a Flow account code by the provided address, contract name and block height. +// +// Expected error returns during normal operation: +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available +func (s *Scripts) GetAccountCode(ctx context.Context, address flow.Address, contractName string, height uint64) ([]byte, error) { + snap, header, err := s.snapshotWithBlock(height) + if err != nil { + return nil, err + } + + return s.executor.GetAccountCode(ctx, address, contractName, header, snap) +} + +// GetStorageSnapshot returns a storage snapshot at the given height. +// +// Expected error returns during normal operation: +// - [storage.ErrHeightNotIndexed] if the data for the block height is not available +func (s *Scripts) GetStorageSnapshot(height uint64) (snapshot.StorageSnapshot, error) { + snapshot, _, err := s.snapshotWithBlock(height) + return snapshot, err +} + +// RegisterValue retrieves register values by the register IDs at the provided block height. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if the register is not found at the given height. +// - [storage.ErrHeightNotIndexed]: if the given height was not indexed yet or lower than the first indexed height. +func (s *Scripts) RegisterValue(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { + return s.registerAtHeight(ID, height) +} + // snapshotWithBlock is a common function for executing scripts and get account functionality. // It creates a storage snapshot that is needed by the FVM to execute scripts. +// +// No error returns during normal operation. func (s *Scripts) snapshotWithBlock(height uint64) (snapshot.StorageSnapshot, *flow.Header, error) { header, err := s.headers.ByHeight(height) if err != nil { @@ -211,7 +278,16 @@ func (s *Scripts) snapshotWithBlock(height uint64) (snapshot.StorageSnapshot, *f } storageSnapshot := snapshot.NewReadFuncStorageSnapshot(func(ID flow.RegisterID) (flow.RegisterValue, error) { - return s.registerAtHeight(ID, height) + value, err := s.registerAtHeight(ID, height) + if err != nil { + // the storage snapshot consumer expects the snapshot to return nil if the register is not found + // instead of an error. + if errors.Is(err, storage.ErrNotFound) { + return nil, nil + } + return nil, err + } + return value, nil }) return storageSnapshot, header, nil diff --git a/module/execution/scripts_test.go b/module/execution/scripts_test.go index af0b3749642..3cb832e119d 100644 --- a/module/execution/scripts_test.go +++ b/module/execution/scripts_test.go @@ -6,13 +6,14 @@ import ( "os" "testing" + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + "github.com/onflow/cadence" "github.com/onflow/cadence/encoding/ccf" jsoncdc "github.com/onflow/cadence/encoding/json" "github.com/onflow/cadence/stdlib" - "github.com/rs/zerolog" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" "github.com/onflow/flow-go/engine/execution/computation/query" "github.com/onflow/flow-go/engine/execution/testutil" @@ -23,7 +24,6 @@ import ( "github.com/onflow/flow-go/fvm/systemcontracts" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/metrics" - "github.com/onflow/flow-go/module/state_synchronization/indexer" synctest "github.com/onflow/flow-go/module/state_synchronization/requester/unittest" "github.com/onflow/flow-go/storage" pebbleStorage "github.com/onflow/flow-go/storage/pebble" @@ -152,8 +152,65 @@ func (s *scriptTestSuite) TestGetAccountKeys() { } +func (s *scriptTestSuite) TestRegisterValue() { + regAddress := unittest.RandomAddressFixture() + registerID := flow.NewRegisterID(regAddress, "test_key") + value := flow.RegisterValue([]byte("test_value")) + + s.Run("returns stored register value", func() { + s.height++ + err := s.registerIndex.Store(flow.RegisterEntries{{Key: registerID, Value: value}}, s.height) + s.Require().NoError(err) + + result, err := s.scripts.RegisterValue(registerID, s.height) + s.Require().NoError(err) + s.Assert().Equal(value, result) + }) + + s.Run("returns ErrNotFound for missing register at indexed height", func() { + missingID := flow.NewRegisterID(unittest.RandomAddressFixture(), "missing_key") + result, err := s.scripts.RegisterValue(missingID, s.height) + s.Assert().ErrorIs(err, storage.ErrNotFound) + s.Assert().Nil(result) + }) + + s.Run("returns most recently indexed value when queried at later height", func() { + lateRegID := flow.NewRegisterID(unittest.RandomAddressFixture(), "late_key") + v1 := flow.RegisterValue([]byte("v1")) + v2 := flow.RegisterValue([]byte("v2")) + + h1 := s.height + 1 + err := s.registerIndex.Store(flow.RegisterEntries{{Key: lateRegID, Value: v1}}, h1) + s.Require().NoError(err) + + // advance height without storing lateRegID + h2 := h1 + 1 + err = s.registerIndex.Store(flow.RegisterEntries{}, h2) + s.Require().NoError(err) + + // querying at h2 returns v1 (stored at h1) + result, err := s.scripts.RegisterValue(lateRegID, h2) + s.Require().NoError(err) + s.Assert().Equal(v1, result) + + // store v2 at h3 + h3 := h2 + 1 + err = s.registerIndex.Store(flow.RegisterEntries{{Key: lateRegID, Value: v2}}, h3) + s.Require().NoError(err) + s.height = h3 + + result, err = s.scripts.RegisterValue(lateRegID, h3) + s.Require().NoError(err) + s.Assert().Equal(v2, result) + + // querying at h2 still returns v1 + result, err = s.scripts.RegisterValue(lateRegID, h2) + s.Require().NoError(err) + s.Assert().Equal(v1, result) + }) +} + func (s *scriptTestSuite) SetupTest() { - lockManager := storage.NewTestingLockManager() logger := unittest.LoggerForTest(s.Suite.T(), zerolog.InfoLevel) entropyProvider := testutil.ProtocolStateWithSourceFixture(nil) blockchain := unittest.BlockchainFixture(10) @@ -163,7 +220,7 @@ func (s *scriptTestSuite) SetupTest() { s.snapshot = snapshot.NewSnapshotTree(nil) s.vm = fvm.NewVirtualMachine() s.vmCtx = fvm.NewContext( - fvm.WithChain(s.chain), + s.chain, fvm.WithAuthorizationChecksEnabled(false), fvm.WithSequenceNumberCheckAndIncrementEnabled(false), ) @@ -178,31 +235,13 @@ func (s *scriptTestSuite) SetupTest() { derivedChainData, err := derived.NewDerivedChainData(derived.DefaultDerivedDataCacheSize) s.Require().NoError(err) - index := indexer.New( - logger, - metrics.NewNoopCollector(), - nil, - s.registerIndex, - headers, - nil, - nil, - nil, - nil, - nil, - flow.Testnet, - derivedChainData, - nil, - nil, - lockManager, - ) - s.scripts = NewScripts( logger, metrics.NewNoopCollector(), s.chain.ChainID(), entropyProvider, headers, - index.RegisterValue, + s.registerIndex.Get, query.NewDefaultConfig(), derivedChainData, true, @@ -277,7 +316,7 @@ func (s *scriptTestSuite) createAccount() flow.Address { data, err := ccf.Decode(nil, accountCreatedEvents[0].Payload) s.Require().NoError(err) - return flow.ConvertAddress( + return flow.Address( cadence.SearchFieldByName( data.(cadence.Event), stdlib.AccountEventAddressParameter.Identifier, diff --git a/module/executiondatasync/execution_data/downloader.go b/module/executiondatasync/execution_data/downloader.go index b0eae050519..99e0ad481a3 100644 --- a/module/executiondatasync/execution_data/downloader.go +++ b/module/executiondatasync/execution_data/downloader.go @@ -105,8 +105,6 @@ func (d *downloader) Get(ctx context.Context, executionDataID flow.Identifier) ( var mu sync.Mutex for i, chunkDataID := range edRoot.ChunkExecutionDataIDs { - i := i - chunkDataID := chunkDataID g.Go(func() error { ced, cids, err := d.getChunkExecutionData( @@ -262,7 +260,7 @@ func (d *downloader) trackBlobs(blockID flow.Identifier, cids []cid.Cid) error { // - BlobNotFoundError if the root blob could not be found from the blob service // - MalformedDataError if the root blob cannot be properly deserialized // - BlobSizeLimitExceededError if the root blob exceeds the maximum allowed size -func (d *downloader) getBlobs(ctx context.Context, blobGetter network.BlobGetter, cids []cid.Cid) (interface{}, error) { +func (d *downloader) getBlobs(ctx context.Context, blobGetter network.BlobGetter, cids []cid.Cid) (any, error) { // this uses an optimization to deserialize the data in a streaming fashion as it is received // from the network, reducing the amount of memory required to deserialize large objects. blobCh, errCh := d.retrieveBlobs(ctx, blobGetter, cids) diff --git a/module/executiondatasync/execution_data/mock/downloader.go b/module/executiondatasync/execution_data/mock/downloader.go index e64250a84cf..60cff1da5be 100644 --- a/module/executiondatasync/execution_data/mock/downloader.go +++ b/module/executiondatasync/execution_data/mock/downloader.go @@ -1,44 +1,93 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "context" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewDownloader creates a new instance of Downloader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDownloader(t interface { + mock.TestingT + Cleanup(func()) +}) *Downloader { + mock := &Downloader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Downloader is an autogenerated mock type for the Downloader type type Downloader struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *Downloader) Done() <-chan struct{} { - ret := _m.Called() +type Downloader_Expecter struct { + mock *mock.Mock +} + +func (_m *Downloader) EXPECT() *Downloader_Expecter { + return &Downloader_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type Downloader +func (_mock *Downloader) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Get provides a mock function with given fields: ctx, rootID -func (_m *Downloader) Get(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error) { - ret := _m.Called(ctx, rootID) +// Downloader_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Downloader_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Downloader_Expecter) Done() *Downloader_Done_Call { + return &Downloader_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Downloader_Done_Call) Run(run func()) *Downloader_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Downloader_Done_Call) Return(valCh <-chan struct{}) *Downloader_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Downloader_Done_Call) RunAndReturn(run func() <-chan struct{}) *Downloader_Done_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type Downloader +func (_mock *Downloader) Get(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error) { + ret := _mock.Called(ctx, rootID) if len(ret) == 0 { panic("no return value specified for Get") @@ -46,84 +95,230 @@ func (_m *Downloader) Get(ctx context.Context, rootID flow.Identifier) (*executi var r0 *execution_data.BlockExecutionData var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { - return rf(ctx, rootID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { + return returnFunc(ctx, rootID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { - r0 = rf(ctx, rootID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { + r0 = returnFunc(ctx, rootID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionData) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, rootID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, rootID) } else { r1 = ret.Error(1) } - return r0, r1 } -// HighestCompleteHeight provides a mock function with no fields -func (_m *Downloader) HighestCompleteHeight() uint64 { - ret := _m.Called() +// Downloader_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Downloader_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - ctx context.Context +// - rootID flow.Identifier +func (_e *Downloader_Expecter) Get(ctx interface{}, rootID interface{}) *Downloader_Get_Call { + return &Downloader_Get_Call{Call: _e.mock.On("Get", ctx, rootID)} +} + +func (_c *Downloader_Get_Call) Run(run func(ctx context.Context, rootID flow.Identifier)) *Downloader_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Downloader_Get_Call) Return(blockExecutionData *execution_data.BlockExecutionData, err error) *Downloader_Get_Call { + _c.Call.Return(blockExecutionData, err) + return _c +} + +func (_c *Downloader_Get_Call) RunAndReturn(run func(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error)) *Downloader_Get_Call { + _c.Call.Return(run) + return _c +} + +// HighestCompleteHeight provides a mock function for the type Downloader +func (_mock *Downloader) HighestCompleteHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HighestCompleteHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// OnBlockProcessed provides a mock function with given fields: _a0 -func (_m *Downloader) OnBlockProcessed(_a0 uint64) { - _m.Called(_a0) +// Downloader_HighestCompleteHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HighestCompleteHeight' +type Downloader_HighestCompleteHeight_Call struct { + *mock.Call +} + +// HighestCompleteHeight is a helper method to define mock.On call +func (_e *Downloader_Expecter) HighestCompleteHeight() *Downloader_HighestCompleteHeight_Call { + return &Downloader_HighestCompleteHeight_Call{Call: _e.mock.On("HighestCompleteHeight")} } -// Ready provides a mock function with no fields -func (_m *Downloader) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *Downloader_HighestCompleteHeight_Call) Run(run func()) *Downloader_HighestCompleteHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Downloader_HighestCompleteHeight_Call) Return(v uint64) *Downloader_HighestCompleteHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Downloader_HighestCompleteHeight_Call) RunAndReturn(run func() uint64) *Downloader_HighestCompleteHeight_Call { + _c.Call.Return(run) + return _c +} + +// OnBlockProcessed provides a mock function for the type Downloader +func (_mock *Downloader) OnBlockProcessed(v uint64) { + _mock.Called(v) + return +} + +// Downloader_OnBlockProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockProcessed' +type Downloader_OnBlockProcessed_Call struct { + *mock.Call +} + +// OnBlockProcessed is a helper method to define mock.On call +// - v uint64 +func (_e *Downloader_Expecter) OnBlockProcessed(v interface{}) *Downloader_OnBlockProcessed_Call { + return &Downloader_OnBlockProcessed_Call{Call: _e.mock.On("OnBlockProcessed", v)} +} + +func (_c *Downloader_OnBlockProcessed_Call) Run(run func(v uint64)) *Downloader_OnBlockProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Downloader_OnBlockProcessed_Call) Return() *Downloader_OnBlockProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *Downloader_OnBlockProcessed_Call) RunAndReturn(run func(v uint64)) *Downloader_OnBlockProcessed_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type Downloader +func (_mock *Downloader) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// SetHeightUpdatesConsumer provides a mock function with given fields: _a0 -func (_m *Downloader) SetHeightUpdatesConsumer(_a0 execution_data.HeightUpdatesConsumer) { - _m.Called(_a0) +// Downloader_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Downloader_Ready_Call struct { + *mock.Call } -// NewDownloader creates a new instance of Downloader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDownloader(t interface { - mock.TestingT - Cleanup(func()) -}) *Downloader { - mock := &Downloader{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *Downloader_Expecter) Ready() *Downloader_Ready_Call { + return &Downloader_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *Downloader_Ready_Call) Run(run func()) *Downloader_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *Downloader_Ready_Call) Return(valCh <-chan struct{}) *Downloader_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Downloader_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Downloader_Ready_Call { + _c.Call.Return(run) + return _c +} + +// SetHeightUpdatesConsumer provides a mock function for the type Downloader +func (_mock *Downloader) SetHeightUpdatesConsumer(heightUpdatesConsumer execution_data.HeightUpdatesConsumer) { + _mock.Called(heightUpdatesConsumer) + return +} + +// Downloader_SetHeightUpdatesConsumer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetHeightUpdatesConsumer' +type Downloader_SetHeightUpdatesConsumer_Call struct { + *mock.Call +} + +// SetHeightUpdatesConsumer is a helper method to define mock.On call +// - heightUpdatesConsumer execution_data.HeightUpdatesConsumer +func (_e *Downloader_Expecter) SetHeightUpdatesConsumer(heightUpdatesConsumer interface{}) *Downloader_SetHeightUpdatesConsumer_Call { + return &Downloader_SetHeightUpdatesConsumer_Call{Call: _e.mock.On("SetHeightUpdatesConsumer", heightUpdatesConsumer)} +} + +func (_c *Downloader_SetHeightUpdatesConsumer_Call) Run(run func(heightUpdatesConsumer execution_data.HeightUpdatesConsumer)) *Downloader_SetHeightUpdatesConsumer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 execution_data.HeightUpdatesConsumer + if args[0] != nil { + arg0 = args[0].(execution_data.HeightUpdatesConsumer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Downloader_SetHeightUpdatesConsumer_Call) Return() *Downloader_SetHeightUpdatesConsumer_Call { + _c.Call.Return() + return _c +} + +func (_c *Downloader_SetHeightUpdatesConsumer_Call) RunAndReturn(run func(heightUpdatesConsumer execution_data.HeightUpdatesConsumer)) *Downloader_SetHeightUpdatesConsumer_Call { + _c.Run(run) + return _c } diff --git a/module/executiondatasync/execution_data/mock/execution_data_cache.go b/module/executiondatasync/execution_data/mock/execution_data_cache.go index 3475518f986..15dac0d6a7e 100644 --- a/module/executiondatasync/execution_data/mock/execution_data_cache.go +++ b/module/executiondatasync/execution_data/mock/execution_data_cache.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "context" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataCache creates a new instance of ExecutionDataCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataCache(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataCache { + mock := &ExecutionDataCache{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataCache is an autogenerated mock type for the ExecutionDataCache type type ExecutionDataCache struct { mock.Mock } -// ByBlockID provides a mock function with given fields: ctx, blockID -func (_m *ExecutionDataCache) ByBlockID(ctx context.Context, blockID flow.Identifier) (*execution_data.BlockExecutionDataEntity, error) { - ret := _m.Called(ctx, blockID) +type ExecutionDataCache_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionDataCache) EXPECT() *ExecutionDataCache_Expecter { + return &ExecutionDataCache_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type ExecutionDataCache +func (_mock *ExecutionDataCache) ByBlockID(ctx context.Context, blockID flow.Identifier) (*execution_data.BlockExecutionDataEntity, error) { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -26,29 +49,67 @@ func (_m *ExecutionDataCache) ByBlockID(ctx context.Context, blockID flow.Identi var r0 *execution_data.BlockExecutionDataEntity var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionDataEntity, error)); ok { - return rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionDataEntity, error)); ok { + return returnFunc(ctx, blockID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionDataEntity); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionDataEntity); ok { + r0 = returnFunc(ctx, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionDataEntity) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByHeight provides a mock function with given fields: ctx, height -func (_m *ExecutionDataCache) ByHeight(ctx context.Context, height uint64) (*execution_data.BlockExecutionDataEntity, error) { - ret := _m.Called(ctx, height) +// ExecutionDataCache_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ExecutionDataCache_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *ExecutionDataCache_Expecter) ByBlockID(ctx interface{}, blockID interface{}) *ExecutionDataCache_ByBlockID_Call { + return &ExecutionDataCache_ByBlockID_Call{Call: _e.mock.On("ByBlockID", ctx, blockID)} +} + +func (_c *ExecutionDataCache_ByBlockID_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *ExecutionDataCache_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataCache_ByBlockID_Call) Return(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity, err error) *ExecutionDataCache_ByBlockID_Call { + _c.Call.Return(blockExecutionDataEntity, err) + return _c +} + +func (_c *ExecutionDataCache_ByBlockID_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) (*execution_data.BlockExecutionDataEntity, error)) *ExecutionDataCache_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByHeight provides a mock function for the type ExecutionDataCache +func (_mock *ExecutionDataCache) ByHeight(ctx context.Context, height uint64) (*execution_data.BlockExecutionDataEntity, error) { + ret := _mock.Called(ctx, height) if len(ret) == 0 { panic("no return value specified for ByHeight") @@ -56,29 +117,67 @@ func (_m *ExecutionDataCache) ByHeight(ctx context.Context, height uint64) (*exe var r0 *execution_data.BlockExecutionDataEntity var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) (*execution_data.BlockExecutionDataEntity, error)); ok { - return rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) (*execution_data.BlockExecutionDataEntity, error)); ok { + return returnFunc(ctx, height) } - if rf, ok := ret.Get(0).(func(context.Context, uint64) *execution_data.BlockExecutionDataEntity); ok { - r0 = rf(ctx, height) + if returnFunc, ok := ret.Get(0).(func(context.Context, uint64) *execution_data.BlockExecutionDataEntity); ok { + r0 = returnFunc(ctx, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionDataEntity) } } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) error); ok { - r1 = rf(ctx, height) + if returnFunc, ok := ret.Get(1).(func(context.Context, uint64) error); ok { + r1 = returnFunc(ctx, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: ctx, executionDataID -func (_m *ExecutionDataCache) ByID(ctx context.Context, executionDataID flow.Identifier) (*execution_data.BlockExecutionDataEntity, error) { - ret := _m.Called(ctx, executionDataID) +// ExecutionDataCache_ByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByHeight' +type ExecutionDataCache_ByHeight_Call struct { + *mock.Call +} + +// ByHeight is a helper method to define mock.On call +// - ctx context.Context +// - height uint64 +func (_e *ExecutionDataCache_Expecter) ByHeight(ctx interface{}, height interface{}) *ExecutionDataCache_ByHeight_Call { + return &ExecutionDataCache_ByHeight_Call{Call: _e.mock.On("ByHeight", ctx, height)} +} + +func (_c *ExecutionDataCache_ByHeight_Call) Run(run func(ctx context.Context, height uint64)) *ExecutionDataCache_ByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataCache_ByHeight_Call) Return(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity, err error) *ExecutionDataCache_ByHeight_Call { + _c.Call.Return(blockExecutionDataEntity, err) + return _c +} + +func (_c *ExecutionDataCache_ByHeight_Call) RunAndReturn(run func(ctx context.Context, height uint64) (*execution_data.BlockExecutionDataEntity, error)) *ExecutionDataCache_ByHeight_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ExecutionDataCache +func (_mock *ExecutionDataCache) ByID(ctx context.Context, executionDataID flow.Identifier) (*execution_data.BlockExecutionDataEntity, error) { + ret := _mock.Called(ctx, executionDataID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -86,29 +185,67 @@ func (_m *ExecutionDataCache) ByID(ctx context.Context, executionDataID flow.Ide var r0 *execution_data.BlockExecutionDataEntity var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionDataEntity, error)); ok { - return rf(ctx, executionDataID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionDataEntity, error)); ok { + return returnFunc(ctx, executionDataID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionDataEntity); ok { - r0 = rf(ctx, executionDataID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionDataEntity); ok { + r0 = returnFunc(ctx, executionDataID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionDataEntity) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, executionDataID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, executionDataID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LookupID provides a mock function with given fields: blockID -func (_m *ExecutionDataCache) LookupID(blockID flow.Identifier) (flow.Identifier, error) { - ret := _m.Called(blockID) +// ExecutionDataCache_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ExecutionDataCache_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - ctx context.Context +// - executionDataID flow.Identifier +func (_e *ExecutionDataCache_Expecter) ByID(ctx interface{}, executionDataID interface{}) *ExecutionDataCache_ByID_Call { + return &ExecutionDataCache_ByID_Call{Call: _e.mock.On("ByID", ctx, executionDataID)} +} + +func (_c *ExecutionDataCache_ByID_Call) Run(run func(ctx context.Context, executionDataID flow.Identifier)) *ExecutionDataCache_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataCache_ByID_Call) Return(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity, err error) *ExecutionDataCache_ByID_Call { + _c.Call.Return(blockExecutionDataEntity, err) + return _c +} + +func (_c *ExecutionDataCache_ByID_Call) RunAndReturn(run func(ctx context.Context, executionDataID flow.Identifier) (*execution_data.BlockExecutionDataEntity, error)) *ExecutionDataCache_ByID_Call { + _c.Call.Return(run) + return _c +} + +// LookupID provides a mock function for the type ExecutionDataCache +func (_mock *ExecutionDataCache) LookupID(blockID flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for LookupID") @@ -116,36 +253,54 @@ func (_m *ExecutionDataCache) LookupID(blockID flow.Identifier) (flow.Identifier var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionDataCache creates a new instance of ExecutionDataCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataCache(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataCache { - mock := &ExecutionDataCache{} - mock.Mock.Test(t) +// ExecutionDataCache_LookupID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LookupID' +type ExecutionDataCache_LookupID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// LookupID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionDataCache_Expecter) LookupID(blockID interface{}) *ExecutionDataCache_LookupID_Call { + return &ExecutionDataCache_LookupID_Call{Call: _e.mock.On("LookupID", blockID)} +} - return mock +func (_c *ExecutionDataCache_LookupID_Call) Run(run func(blockID flow.Identifier)) *ExecutionDataCache_LookupID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionDataCache_LookupID_Call) Return(identifier flow.Identifier, err error) *ExecutionDataCache_LookupID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ExecutionDataCache_LookupID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.Identifier, error)) *ExecutionDataCache_LookupID_Call { + _c.Call.Return(run) + return _c } diff --git a/module/executiondatasync/execution_data/mock/execution_data_getter.go b/module/executiondatasync/execution_data/mock/execution_data_getter.go index ee19f20831d..8d62538eab5 100644 --- a/module/executiondatasync/execution_data/mock/execution_data_getter.go +++ b/module/executiondatasync/execution_data/mock/execution_data_getter.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "context" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataGetter creates a new instance of ExecutionDataGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataGetter(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataGetter { + mock := &ExecutionDataGetter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataGetter is an autogenerated mock type for the ExecutionDataGetter type type ExecutionDataGetter struct { mock.Mock } -// Get provides a mock function with given fields: ctx, rootID -func (_m *ExecutionDataGetter) Get(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error) { - ret := _m.Called(ctx, rootID) +type ExecutionDataGetter_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionDataGetter) EXPECT() *ExecutionDataGetter_Expecter { + return &ExecutionDataGetter_Expecter{mock: &_m.Mock} +} + +// Get provides a mock function for the type ExecutionDataGetter +func (_mock *ExecutionDataGetter) Get(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error) { + ret := _mock.Called(ctx, rootID) if len(ret) == 0 { panic("no return value specified for Get") @@ -26,36 +49,60 @@ func (_m *ExecutionDataGetter) Get(ctx context.Context, rootID flow.Identifier) var r0 *execution_data.BlockExecutionData var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { - return rf(ctx, rootID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { + return returnFunc(ctx, rootID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { - r0 = rf(ctx, rootID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { + r0 = returnFunc(ctx, rootID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionData) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, rootID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, rootID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionDataGetter creates a new instance of ExecutionDataGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataGetter(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataGetter { - mock := &ExecutionDataGetter{} - mock.Mock.Test(t) +// ExecutionDataGetter_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type ExecutionDataGetter_Get_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Get is a helper method to define mock.On call +// - ctx context.Context +// - rootID flow.Identifier +func (_e *ExecutionDataGetter_Expecter) Get(ctx interface{}, rootID interface{}) *ExecutionDataGetter_Get_Call { + return &ExecutionDataGetter_Get_Call{Call: _e.mock.On("Get", ctx, rootID)} +} - return mock +func (_c *ExecutionDataGetter_Get_Call) Run(run func(ctx context.Context, rootID flow.Identifier)) *ExecutionDataGetter_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataGetter_Get_Call) Return(blockExecutionData *execution_data.BlockExecutionData, err error) *ExecutionDataGetter_Get_Call { + _c.Call.Return(blockExecutionData, err) + return _c +} + +func (_c *ExecutionDataGetter_Get_Call) RunAndReturn(run func(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error)) *ExecutionDataGetter_Get_Call { + _c.Call.Return(run) + return _c } diff --git a/module/executiondatasync/execution_data/mock/execution_data_store.go b/module/executiondatasync/execution_data/mock/execution_data_store.go index 42fd911fb57..56fd21d9afe 100644 --- a/module/executiondatasync/execution_data/mock/execution_data_store.go +++ b/module/executiondatasync/execution_data/mock/execution_data_store.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "context" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataStore creates a new instance of ExecutionDataStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataStore(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataStore { + mock := &ExecutionDataStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataStore is an autogenerated mock type for the ExecutionDataStore type type ExecutionDataStore struct { mock.Mock } -// Add provides a mock function with given fields: ctx, executionData -func (_m *ExecutionDataStore) Add(ctx context.Context, executionData *execution_data.BlockExecutionData) (flow.Identifier, error) { - ret := _m.Called(ctx, executionData) +type ExecutionDataStore_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionDataStore) EXPECT() *ExecutionDataStore_Expecter { + return &ExecutionDataStore_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type ExecutionDataStore +func (_mock *ExecutionDataStore) Add(ctx context.Context, executionData *execution_data.BlockExecutionData) (flow.Identifier, error) { + ret := _mock.Called(ctx, executionData) if len(ret) == 0 { panic("no return value specified for Add") @@ -26,29 +49,67 @@ func (_m *ExecutionDataStore) Add(ctx context.Context, executionData *execution_ var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *execution_data.BlockExecutionData) (flow.Identifier, error)); ok { - return rf(ctx, executionData) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution_data.BlockExecutionData) (flow.Identifier, error)); ok { + return returnFunc(ctx, executionData) } - if rf, ok := ret.Get(0).(func(context.Context, *execution_data.BlockExecutionData) flow.Identifier); ok { - r0 = rf(ctx, executionData) + if returnFunc, ok := ret.Get(0).(func(context.Context, *execution_data.BlockExecutionData) flow.Identifier); ok { + r0 = returnFunc(ctx, executionData) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(context.Context, *execution_data.BlockExecutionData) error); ok { - r1 = rf(ctx, executionData) + if returnFunc, ok := ret.Get(1).(func(context.Context, *execution_data.BlockExecutionData) error); ok { + r1 = returnFunc(ctx, executionData) } else { r1 = ret.Error(1) } - return r0, r1 } -// Get provides a mock function with given fields: ctx, rootID -func (_m *ExecutionDataStore) Get(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error) { - ret := _m.Called(ctx, rootID) +// ExecutionDataStore_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type ExecutionDataStore_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - ctx context.Context +// - executionData *execution_data.BlockExecutionData +func (_e *ExecutionDataStore_Expecter) Add(ctx interface{}, executionData interface{}) *ExecutionDataStore_Add_Call { + return &ExecutionDataStore_Add_Call{Call: _e.mock.On("Add", ctx, executionData)} +} + +func (_c *ExecutionDataStore_Add_Call) Run(run func(ctx context.Context, executionData *execution_data.BlockExecutionData)) *ExecutionDataStore_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *execution_data.BlockExecutionData + if args[1] != nil { + arg1 = args[1].(*execution_data.BlockExecutionData) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataStore_Add_Call) Return(identifier flow.Identifier, err error) *ExecutionDataStore_Add_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ExecutionDataStore_Add_Call) RunAndReturn(run func(ctx context.Context, executionData *execution_data.BlockExecutionData) (flow.Identifier, error)) *ExecutionDataStore_Add_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type ExecutionDataStore +func (_mock *ExecutionDataStore) Get(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error) { + ret := _mock.Called(ctx, rootID) if len(ret) == 0 { panic("no return value specified for Get") @@ -56,36 +117,60 @@ func (_m *ExecutionDataStore) Get(ctx context.Context, rootID flow.Identifier) ( var r0 *execution_data.BlockExecutionData var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { - return rf(ctx, rootID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*execution_data.BlockExecutionData, error)); ok { + return returnFunc(ctx, rootID) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { - r0 = rf(ctx, rootID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *execution_data.BlockExecutionData); ok { + r0 = returnFunc(ctx, rootID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionData) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(ctx, rootID) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(ctx, rootID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionDataStore creates a new instance of ExecutionDataStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataStore(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataStore { - mock := &ExecutionDataStore{} - mock.Mock.Test(t) +// ExecutionDataStore_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type ExecutionDataStore_Get_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Get is a helper method to define mock.On call +// - ctx context.Context +// - rootID flow.Identifier +func (_e *ExecutionDataStore_Expecter) Get(ctx interface{}, rootID interface{}) *ExecutionDataStore_Get_Call { + return &ExecutionDataStore_Get_Call{Call: _e.mock.On("Get", ctx, rootID)} +} - return mock +func (_c *ExecutionDataStore_Get_Call) Run(run func(ctx context.Context, rootID flow.Identifier)) *ExecutionDataStore_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataStore_Get_Call) Return(blockExecutionData *execution_data.BlockExecutionData, err error) *ExecutionDataStore_Get_Call { + _c.Call.Return(blockExecutionData, err) + return _c +} + +func (_c *ExecutionDataStore_Get_Call) RunAndReturn(run func(ctx context.Context, rootID flow.Identifier) (*execution_data.BlockExecutionData, error)) *ExecutionDataStore_Get_Call { + _c.Call.Return(run) + return _c } diff --git a/module/executiondatasync/execution_data/mock/processed_height_recorder.go b/module/executiondatasync/execution_data/mock/processed_height_recorder.go index 6b5afade686..47484bbc4e4 100644 --- a/module/executiondatasync/execution_data/mock/processed_height_recorder.go +++ b/module/executiondatasync/execution_data/mock/processed_height_recorder.go @@ -1,55 +1,161 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewProcessedHeightRecorder creates a new instance of ProcessedHeightRecorder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProcessedHeightRecorder(t interface { + mock.TestingT + Cleanup(func()) +}) *ProcessedHeightRecorder { + mock := &ProcessedHeightRecorder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ProcessedHeightRecorder is an autogenerated mock type for the ProcessedHeightRecorder type type ProcessedHeightRecorder struct { mock.Mock } -// HighestCompleteHeight provides a mock function with no fields -func (_m *ProcessedHeightRecorder) HighestCompleteHeight() uint64 { - ret := _m.Called() +type ProcessedHeightRecorder_Expecter struct { + mock *mock.Mock +} + +func (_m *ProcessedHeightRecorder) EXPECT() *ProcessedHeightRecorder_Expecter { + return &ProcessedHeightRecorder_Expecter{mock: &_m.Mock} +} + +// HighestCompleteHeight provides a mock function for the type ProcessedHeightRecorder +func (_mock *ProcessedHeightRecorder) HighestCompleteHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HighestCompleteHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// OnBlockProcessed provides a mock function with given fields: _a0 -func (_m *ProcessedHeightRecorder) OnBlockProcessed(_a0 uint64) { - _m.Called(_a0) +// ProcessedHeightRecorder_HighestCompleteHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HighestCompleteHeight' +type ProcessedHeightRecorder_HighestCompleteHeight_Call struct { + *mock.Call } -// SetHeightUpdatesConsumer provides a mock function with given fields: _a0 -func (_m *ProcessedHeightRecorder) SetHeightUpdatesConsumer(_a0 execution_data.HeightUpdatesConsumer) { - _m.Called(_a0) +// HighestCompleteHeight is a helper method to define mock.On call +func (_e *ProcessedHeightRecorder_Expecter) HighestCompleteHeight() *ProcessedHeightRecorder_HighestCompleteHeight_Call { + return &ProcessedHeightRecorder_HighestCompleteHeight_Call{Call: _e.mock.On("HighestCompleteHeight")} } -// NewProcessedHeightRecorder creates a new instance of ProcessedHeightRecorder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProcessedHeightRecorder(t interface { - mock.TestingT - Cleanup(func()) -}) *ProcessedHeightRecorder { - mock := &ProcessedHeightRecorder{} - mock.Mock.Test(t) +func (_c *ProcessedHeightRecorder_HighestCompleteHeight_Call) Run(run func()) *ProcessedHeightRecorder_HighestCompleteHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ProcessedHeightRecorder_HighestCompleteHeight_Call) Return(v uint64) *ProcessedHeightRecorder_HighestCompleteHeight_Call { + _c.Call.Return(v) + return _c +} - return mock +func (_c *ProcessedHeightRecorder_HighestCompleteHeight_Call) RunAndReturn(run func() uint64) *ProcessedHeightRecorder_HighestCompleteHeight_Call { + _c.Call.Return(run) + return _c +} + +// OnBlockProcessed provides a mock function for the type ProcessedHeightRecorder +func (_mock *ProcessedHeightRecorder) OnBlockProcessed(v uint64) { + _mock.Called(v) + return +} + +// ProcessedHeightRecorder_OnBlockProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockProcessed' +type ProcessedHeightRecorder_OnBlockProcessed_Call struct { + *mock.Call +} + +// OnBlockProcessed is a helper method to define mock.On call +// - v uint64 +func (_e *ProcessedHeightRecorder_Expecter) OnBlockProcessed(v interface{}) *ProcessedHeightRecorder_OnBlockProcessed_Call { + return &ProcessedHeightRecorder_OnBlockProcessed_Call{Call: _e.mock.On("OnBlockProcessed", v)} +} + +func (_c *ProcessedHeightRecorder_OnBlockProcessed_Call) Run(run func(v uint64)) *ProcessedHeightRecorder_OnBlockProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProcessedHeightRecorder_OnBlockProcessed_Call) Return() *ProcessedHeightRecorder_OnBlockProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *ProcessedHeightRecorder_OnBlockProcessed_Call) RunAndReturn(run func(v uint64)) *ProcessedHeightRecorder_OnBlockProcessed_Call { + _c.Run(run) + return _c +} + +// SetHeightUpdatesConsumer provides a mock function for the type ProcessedHeightRecorder +func (_mock *ProcessedHeightRecorder) SetHeightUpdatesConsumer(heightUpdatesConsumer execution_data.HeightUpdatesConsumer) { + _mock.Called(heightUpdatesConsumer) + return +} + +// ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetHeightUpdatesConsumer' +type ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call struct { + *mock.Call +} + +// SetHeightUpdatesConsumer is a helper method to define mock.On call +// - heightUpdatesConsumer execution_data.HeightUpdatesConsumer +func (_e *ProcessedHeightRecorder_Expecter) SetHeightUpdatesConsumer(heightUpdatesConsumer interface{}) *ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call { + return &ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call{Call: _e.mock.On("SetHeightUpdatesConsumer", heightUpdatesConsumer)} +} + +func (_c *ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call) Run(run func(heightUpdatesConsumer execution_data.HeightUpdatesConsumer)) *ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 execution_data.HeightUpdatesConsumer + if args[0] != nil { + arg0 = args[0].(execution_data.HeightUpdatesConsumer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call) Return() *ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call { + _c.Call.Return() + return _c +} + +func (_c *ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call) RunAndReturn(run func(heightUpdatesConsumer execution_data.HeightUpdatesConsumer)) *ProcessedHeightRecorder_SetHeightUpdatesConsumer_Call { + _c.Run(run) + return _c } diff --git a/module/executiondatasync/execution_data/mock/serializer.go b/module/executiondatasync/execution_data/mock/serializer.go index cecae509493..91476d46b24 100644 --- a/module/executiondatasync/execution_data/mock/serializer.go +++ b/module/executiondatasync/execution_data/mock/serializer.go @@ -1,76 +1,157 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - io "io" + "io" mock "github.com/stretchr/testify/mock" ) +// NewSerializer creates a new instance of Serializer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSerializer(t interface { + mock.TestingT + Cleanup(func()) +}) *Serializer { + mock := &Serializer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Serializer is an autogenerated mock type for the Serializer type type Serializer struct { mock.Mock } -// Deserialize provides a mock function with given fields: _a0 -func (_m *Serializer) Deserialize(_a0 io.Reader) (interface{}, error) { - ret := _m.Called(_a0) +type Serializer_Expecter struct { + mock *mock.Mock +} + +func (_m *Serializer) EXPECT() *Serializer_Expecter { + return &Serializer_Expecter{mock: &_m.Mock} +} + +// Deserialize provides a mock function for the type Serializer +func (_mock *Serializer) Deserialize(reader io.Reader) (any, error) { + ret := _mock.Called(reader) if len(ret) == 0 { panic("no return value specified for Deserialize") } - var r0 interface{} + var r0 any var r1 error - if rf, ok := ret.Get(0).(func(io.Reader) (interface{}, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(io.Reader) (any, error)); ok { + return returnFunc(reader) } - if rf, ok := ret.Get(0).(func(io.Reader) interface{}); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(io.Reader) any); ok { + r0 = returnFunc(reader) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(interface{}) + r0 = ret.Get(0).(any) } } - - if rf, ok := ret.Get(1).(func(io.Reader) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(io.Reader) error); ok { + r1 = returnFunc(reader) } else { r1 = ret.Error(1) } - return r0, r1 } -// Serialize provides a mock function with given fields: _a0, _a1 -func (_m *Serializer) Serialize(_a0 io.Writer, _a1 interface{}) error { - ret := _m.Called(_a0, _a1) +// Serializer_Deserialize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Deserialize' +type Serializer_Deserialize_Call struct { + *mock.Call +} + +// Deserialize is a helper method to define mock.On call +// - reader io.Reader +func (_e *Serializer_Expecter) Deserialize(reader interface{}) *Serializer_Deserialize_Call { + return &Serializer_Deserialize_Call{Call: _e.mock.On("Deserialize", reader)} +} + +func (_c *Serializer_Deserialize_Call) Run(run func(reader io.Reader)) *Serializer_Deserialize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 io.Reader + if args[0] != nil { + arg0 = args[0].(io.Reader) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Serializer_Deserialize_Call) Return(v any, err error) *Serializer_Deserialize_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Serializer_Deserialize_Call) RunAndReturn(run func(reader io.Reader) (any, error)) *Serializer_Deserialize_Call { + _c.Call.Return(run) + return _c +} + +// Serialize provides a mock function for the type Serializer +func (_mock *Serializer) Serialize(writer io.Writer, v any) error { + ret := _mock.Called(writer, v) if len(ret) == 0 { panic("no return value specified for Serialize") } var r0 error - if rf, ok := ret.Get(0).(func(io.Writer, interface{}) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(io.Writer, any) error); ok { + r0 = returnFunc(writer, v) } else { r0 = ret.Error(0) } - return r0 } -// NewSerializer creates a new instance of Serializer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSerializer(t interface { - mock.TestingT - Cleanup(func()) -}) *Serializer { - mock := &Serializer{} - mock.Mock.Test(t) +// Serializer_Serialize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Serialize' +type Serializer_Serialize_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Serialize is a helper method to define mock.On call +// - writer io.Writer +// - v any +func (_e *Serializer_Expecter) Serialize(writer interface{}, v interface{}) *Serializer_Serialize_Call { + return &Serializer_Serialize_Call{Call: _e.mock.On("Serialize", writer, v)} +} - return mock +func (_c *Serializer_Serialize_Call) Run(run func(writer io.Writer, v any)) *Serializer_Serialize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 io.Writer + if args[0] != nil { + arg0 = args[0].(io.Writer) + } + var arg1 any + if args[1] != nil { + arg1 = args[1].(any) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Serializer_Serialize_Call) Return(err error) *Serializer_Serialize_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Serializer_Serialize_Call) RunAndReturn(run func(writer io.Writer, v any) error) *Serializer_Serialize_Call { + _c.Call.Return(run) + return _c } diff --git a/module/executiondatasync/execution_data/serializer.go b/module/executiondatasync/execution_data/serializer.go index 942bb02a4e8..e94715a1a51 100644 --- a/module/executiondatasync/execution_data/serializer.go +++ b/module/executiondatasync/execution_data/serializer.go @@ -57,7 +57,7 @@ const ( // getCode returns the header code for the given value's type. // It returns an error if the type is not supported. -func getCode(v interface{}) (byte, error) { +func getCode(v any) (byte, error) { switch v.(type) { case *flow.BlockExecutionDataRoot: return codeExecutionDataRoot, nil @@ -74,7 +74,7 @@ func getCode(v interface{}) (byte, error) { // getPrototype returns a new instance of the type that corresponds to the given header code. // It returns an error if the code is not supported. -func getPrototype(code byte) (interface{}, error) { +func getPrototype(code byte) (any, error) { switch code { case codeExecutionDataRoot: return &flow.BlockExecutionDataRoot{}, nil @@ -92,11 +92,11 @@ func getPrototype(code byte) (interface{}, error) { type Serializer interface { // Serialize encodes and compresses the given value to the given writer. // No errors are expected during normal operation. - Serialize(io.Writer, interface{}) error + Serialize(io.Writer, any) error // Deserialize decompresses and decodes the data from the given reader. // No errors are expected during normal operation. - Deserialize(io.Reader) (interface{}, error) + Deserialize(io.Reader) (any, error) } // serializer implements the Serializer interface. Object are serialized by encoding and @@ -118,7 +118,7 @@ func NewSerializer(codec encoding.Codec, compressor network.Compressor) *seriali } // writePrototype writes the header code for the given value to the given writer -func (s *serializer) writePrototype(w io.Writer, v interface{}) error { +func (s *serializer) writePrototype(w io.Writer, v any) error { var code byte var err error @@ -141,7 +141,7 @@ func (s *serializer) writePrototype(w io.Writer, v interface{}) error { // Serialize encodes and compresses the given value to the given writer. // No errors are expected during normal operation. -func (s *serializer) Serialize(w io.Writer, v interface{}) error { +func (s *serializer) Serialize(w io.Writer, v any) error { if err := s.writePrototype(w, v); err != nil { return fmt.Errorf("failed to write prototype: %w", err) } @@ -167,7 +167,7 @@ func (s *serializer) Serialize(w io.Writer, v interface{}) error { } // readPrototype reads a header code from the given reader and returns a prototype value -func (s *serializer) readPrototype(r io.Reader) (interface{}, error) { +func (s *serializer) readPrototype(r io.Reader) (any, error) { var code byte var err error @@ -188,7 +188,7 @@ func (s *serializer) readPrototype(r io.Reader) (interface{}, error) { // Deserialize decompresses and decodes the data from the given reader. // No errors are expected during normal operation. -func (s *serializer) Deserialize(r io.Reader) (interface{}, error) { +func (s *serializer) Deserialize(r io.Reader) (any, error) { v, err := s.readPrototype(r) if err != nil { diff --git a/module/executiondatasync/execution_data/store.go b/module/executiondatasync/execution_data/store.go index 8d31a8a0c4f..e9ca87d4b54 100644 --- a/module/executiondatasync/execution_data/store.go +++ b/module/executiondatasync/execution_data/store.go @@ -115,7 +115,7 @@ func (s *store) Add(ctx context.Context, executionData *BlockExecutionData) (flo // blobstore, and returns the root CID. // No errors are expected during normal operation. func (s *store) addChunkExecutionData(ctx context.Context, chunkExecutionData *ChunkExecutionData) (cid.Cid, error) { - var v interface{} = chunkExecutionData + var v any = chunkExecutionData // given an arbitrarily large v, split it into blobs of size up to maxBlobSize, adding them to // the blobstore. Then, combine the list of CIDs added into a second level of blobs, and repeat. @@ -141,7 +141,7 @@ func (s *store) addChunkExecutionData(ctx context.Context, chunkExecutionData *C // addBlobs splits the given value into blobs of size up to maxBlobSize, adds them to the blobstore, // then returns the CIDs for each blob added. // No errors are expected during normal operation. -func (s *store) addBlobs(ctx context.Context, v interface{}) ([]cid.Cid, error) { +func (s *store) addBlobs(ctx context.Context, v any) ([]cid.Cid, error) { // first, serialize the data into a large byte slice buf := new(bytes.Buffer) if err := s.serializer.Serialize(buf, v); err != nil { @@ -247,7 +247,7 @@ func (s *store) getChunkExecutionData(ctx context.Context, chunkExecutionDataID // the deserialized value. // - BlobNotFoundError if any of the CIDs could not be found from the blobstore // - MalformedDataError if any of the blobs cannot be properly deserialized -func (s *store) getBlobs(ctx context.Context, cids []cid.Cid) (interface{}, error) { +func (s *store) getBlobs(ctx context.Context, cids []cid.Cid) (any, error) { buf := new(bytes.Buffer) // get each blob and append the raw data to the buffer diff --git a/module/executiondatasync/optimistic_sync/core.go b/module/executiondatasync/optimistic_sync/core.go index 044485a7ad5..8d98c4eae84 100644 --- a/module/executiondatasync/optimistic_sync/core.go +++ b/module/executiondatasync/optimistic_sync/core.go @@ -2,31 +2,12 @@ package optimistic_sync import ( "context" - "errors" "fmt" - "sync" - "time" - - "github.com/rs/zerolog" - "golang.org/x/sync/errgroup" - - "github.com/onflow/flow-go/engine/access/ingestion/tx_error_messages" - "github.com/onflow/flow-go/model/flow" - "github.com/onflow/flow-go/module/executiondatasync/execution_data" - "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync/persisters" - "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync/persisters/stores" - "github.com/onflow/flow-go/module/state_synchronization/indexer" - "github.com/onflow/flow-go/module/state_synchronization/requester" - "github.com/onflow/flow-go/storage" - "github.com/onflow/flow-go/storage/inmemory" ) -// DefaultTxResultErrMsgsRequestTimeout is the default timeout for requesting transaction result error messages. -const DefaultTxResultErrMsgsRequestTimeout = 5 * time.Second - -// errResultAbandoned is returned when calling one of the methods after the result has been abandoned. +// ErrResultAbandoned is returned when calling one of the methods after the result has been abandoned. // Not exported because this is not an expected error condition. -var errResultAbandoned = fmt.Errorf("result abandoned") +var ErrResultAbandoned = fmt.Errorf("result abandoned") // // Core defines the interface for pipelined execution result processing. There are 3 main steps which @@ -69,302 +50,3 @@ type Core interface { // the caller should cancel its context to ensure the operation completes in a timely manner. Abandon() } - -// workingData encapsulates all components and temporary storage -// involved in processing a single block's execution data. When processing -// is complete or abandoned, the entire workingData can be discarded. -type workingData struct { - protocolDB storage.DB - lockManager storage.LockManager - - persistentRegisters storage.RegisterIndex - persistentEvents storage.Events - persistentCollections storage.Collections - persistentResults storage.LightTransactionResults - persistentTxResultErrMsgs storage.TransactionResultErrorMessages - latestPersistedSealedResult storage.LatestPersistedSealedResult - - inmemRegisters *inmemory.RegistersReader - inmemEvents *inmemory.EventsReader - inmemCollections *inmemory.CollectionsReader - inmemTransactions *inmemory.TransactionsReader - inmemResults *inmemory.LightTransactionResultsReader - inmemTxResultErrMsgs *inmemory.TransactionResultErrorMessagesReader - - // Active processing components - execDataRequester requester.ExecutionDataRequester - txResultErrMsgsRequester tx_error_messages.Requester - txResultErrMsgsRequestTimeout time.Duration - - // Working data - executionData *execution_data.BlockExecutionData - txResultErrMsgsData []flow.TransactionResultErrorMessage - indexerData *indexer.IndexerData - persisted bool -} - -var _ Core = (*CoreImpl)(nil) - -// CoreImpl implements the Core interface for processing execution data. -// It coordinates the download, indexing, and persisting of execution data. -// -// Safe for concurrent use. -type CoreImpl struct { - log zerolog.Logger - mu sync.Mutex - - workingData *workingData - - executionResult *flow.ExecutionResult - block *flow.Block -} - -// NewCoreImpl creates a new CoreImpl with all necessary dependencies -// Safe for concurrent use. -// -// No error returns are expected during normal operations -func NewCoreImpl( - logger zerolog.Logger, - executionResult *flow.ExecutionResult, - block *flow.Block, - execDataRequester requester.ExecutionDataRequester, - txResultErrMsgsRequester tx_error_messages.Requester, - txResultErrMsgsRequestTimeout time.Duration, - persistentRegisters storage.RegisterIndex, - persistentEvents storage.Events, - persistentCollections storage.Collections, - persistentResults storage.LightTransactionResults, - persistentTxResultErrMsg storage.TransactionResultErrorMessages, - latestPersistedSealedResult storage.LatestPersistedSealedResult, - protocolDB storage.DB, - lockManager storage.LockManager, -) (*CoreImpl, error) { - if block.ID() != executionResult.BlockID { - return nil, fmt.Errorf("header ID and execution result block ID must match") - } - - coreLogger := logger.With(). - Str("component", "execution_data_core"). - Str("execution_result_id", executionResult.ID().String()). - Str("block_id", executionResult.BlockID.String()). - Uint64("height", block.Height). - Logger() - - return &CoreImpl{ - log: coreLogger, - block: block, - executionResult: executionResult, - workingData: &workingData{ - protocolDB: protocolDB, - lockManager: lockManager, - - execDataRequester: execDataRequester, - txResultErrMsgsRequester: txResultErrMsgsRequester, - txResultErrMsgsRequestTimeout: txResultErrMsgsRequestTimeout, - - persistentRegisters: persistentRegisters, - persistentEvents: persistentEvents, - persistentCollections: persistentCollections, - persistentResults: persistentResults, - persistentTxResultErrMsgs: persistentTxResultErrMsg, - latestPersistedSealedResult: latestPersistedSealedResult, - }, - }, nil -} - -// Download retrieves all necessary data for processing from the network. -// Download will block until the data is successfully downloaded, and has not internal timeout. -// When Aboandon is called, the caller must cancel the context passed in to shutdown the operation -// otherwise it may block indefinitely. -// -// The method may only be called once. Calling it multiple times will return an error. -// Calling Download after Abandon is called will return an error. -// -// Expected error returns during normal operation: -// - [context.Canceled]: if the provided context was canceled before completion -func (c *CoreImpl) Download(ctx context.Context) error { - c.mu.Lock() - defer c.mu.Unlock() - if c.workingData == nil { - return errResultAbandoned - } - if c.workingData.executionData != nil { - return fmt.Errorf("already downloaded") - } - - c.log.Debug().Msg("downloading execution data") - - g, gCtx := errgroup.WithContext(ctx) - - var executionData *execution_data.BlockExecutionData - g.Go(func() error { - var err error - executionData, err = c.workingData.execDataRequester.RequestExecutionData(gCtx) - if err != nil { - return fmt.Errorf("failed to request execution data: %w", err) - } - - return nil - }) - - var txResultErrMsgsData []flow.TransactionResultErrorMessage - g.Go(func() error { - timeoutCtx, cancel := context.WithTimeout(gCtx, c.workingData.txResultErrMsgsRequestTimeout) - defer cancel() - - var err error - txResultErrMsgsData, err = c.workingData.txResultErrMsgsRequester.Request(timeoutCtx) - if err != nil { - // transaction error messages are downloaded from execution nodes over grpc and have no - // protocol guarantees for delivery or correctness. Therefore, we attempt to download them - // on a best-effort basis, and give up after a reasonable timeout to avoid blocking the - // main indexing process. Missing error messages are handled gracefully by the rest of - // the system, and can be retried or backfilled as needed later. - if errors.Is(err, context.DeadlineExceeded) { - c.log.Debug(). - Dur("timeout", c.workingData.txResultErrMsgsRequestTimeout). - Msg("transaction result error messages request timed out") - return nil - } - - return fmt.Errorf("failed to request transaction result error messages data: %w", err) - } - return nil - }) - - if err := g.Wait(); err != nil { - return err - } - - c.workingData.executionData = executionData - c.workingData.txResultErrMsgsData = txResultErrMsgsData - - c.log.Debug().Msg("successfully downloaded execution data") - - return nil -} - -// Index processes the downloaded data and stores it into in-memory indexes. -// Must be called after Download. -// -// The method may only be called once. Calling it multiple times will return an error. -// Calling Index after Abandon is called will return an error. -// -// No error returns are expected during normal operations -func (c *CoreImpl) Index() error { - c.mu.Lock() - defer c.mu.Unlock() - if c.workingData == nil { - return errResultAbandoned - } - if c.workingData.executionData == nil { - return fmt.Errorf("downloading is not complete") - } - if c.workingData.indexerData != nil { - return fmt.Errorf("already indexed") - } - - c.log.Debug().Msg("indexing execution data") - - indexerComponent, err := indexer.NewInMemoryIndexer(c.log, c.block, c.executionResult) - if err != nil { - return fmt.Errorf("failed to create indexer: %w", err) - } - - indexerData, err := indexerComponent.IndexBlockData(c.workingData.executionData) - if err != nil { - return fmt.Errorf("failed to index execution data: %w", err) - } - - if c.workingData.txResultErrMsgsData != nil { - err = indexer.ValidateTxErrors(indexerData.Results, c.workingData.txResultErrMsgsData) - if err != nil { - return fmt.Errorf("failed to validate transaction result error messages: %w", err) - } - } - - blockID := c.executionResult.BlockID - - c.workingData.indexerData = indexerData - c.workingData.inmemCollections = inmemory.NewCollections(indexerData.Collections) - c.workingData.inmemTransactions = inmemory.NewTransactions(indexerData.Transactions) - c.workingData.inmemTxResultErrMsgs = inmemory.NewTransactionResultErrorMessages(blockID, c.workingData.txResultErrMsgsData) - c.workingData.inmemEvents = inmemory.NewEvents(blockID, indexerData.Events) - c.workingData.inmemResults = inmemory.NewLightTransactionResults(blockID, indexerData.Results) - c.workingData.inmemRegisters = inmemory.NewRegisters(c.block.Height, indexerData.Registers) - - c.log.Debug().Msg("successfully indexed execution data") - - return nil -} - -// Persist stores the indexed data in permanent storage. -// Must be called after Index. -// -// The method may only be called once. Calling it multiple times will return an error. -// Calling Persist after Abandon is called will return an error. -// -// No error returns are expected during normal operations -func (c *CoreImpl) Persist() error { - c.mu.Lock() - defer c.mu.Unlock() - if c.workingData == nil { - return errResultAbandoned - } - if c.workingData.persisted { - return fmt.Errorf("already persisted") - } - if c.workingData.indexerData == nil { - return fmt.Errorf("indexing is not complete") - } - - c.log.Debug().Msg("persisting execution data") - - indexerData := c.workingData.indexerData - - // the BlockPersister updates the latest persisted sealed result within the batch operation, so - // all other updates must be done before the batch is committed to ensure the state remains - // consistent. The registers db allows repeated indexing of the most recent block's registers, - // so it is safe to persist them before the block persister. - registerPersister := persisters.NewRegistersPersister(indexerData.Registers, c.workingData.persistentRegisters, c.block.Height) - if err := registerPersister.Persist(); err != nil { - return fmt.Errorf("failed to persist registers: %w", err) - } - - persisterStores := []stores.PersisterStore{ - stores.NewEventsStore(indexerData.Events, c.workingData.persistentEvents, c.executionResult.BlockID), - stores.NewResultsStore(indexerData.Results, c.workingData.persistentResults, c.executionResult.BlockID), - stores.NewCollectionsStore(indexerData.Collections, c.workingData.persistentCollections), - stores.NewTxResultErrMsgStore(c.workingData.txResultErrMsgsData, c.workingData.persistentTxResultErrMsgs, c.executionResult.BlockID, c.workingData.lockManager), - stores.NewLatestSealedResultStore(c.workingData.latestPersistedSealedResult, c.executionResult.ID(), c.block.Height), - } - blockPersister := persisters.NewBlockPersister( - c.log, - c.workingData.protocolDB, - c.workingData.lockManager, - c.executionResult, - persisterStores, - ) - if err := blockPersister.Persist(); err != nil { - return fmt.Errorf("failed to persist block data: %w", err) - } - - // reset the indexer data to prevent multiple calls to Persist - c.workingData.indexerData = nil - c.workingData.persisted = true - - return nil -} - -// Abandon indicates that the protocol has abandoned this state. Hence processing will be aborted -// and any data dropped. -// This method will block until other in-progress operations are complete. If Download is in progress, -// the caller should cancel its context to ensure the operation completes in a timely manner. -// -// The method is idempotent. Calling it multiple times has no effect. -func (c *CoreImpl) Abandon() { - c.mu.Lock() - defer c.mu.Unlock() - - c.workingData = nil -} diff --git a/module/executiondatasync/optimistic_sync/mock/core.go b/module/executiondatasync/optimistic_sync/mock/core.go index f2e9fb62b80..7be980f935b 100644 --- a/module/executiondatasync/optimistic_sync/mock/core.go +++ b/module/executiondatasync/optimistic_sync/mock/core.go @@ -1,87 +1,210 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" mock "github.com/stretchr/testify/mock" ) +// NewCore creates a new instance of Core. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCore(t interface { + mock.TestingT + Cleanup(func()) +}) *Core { + mock := &Core{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Core is an autogenerated mock type for the Core type type Core struct { mock.Mock } -// Abandon provides a mock function with no fields -func (_m *Core) Abandon() { - _m.Called() +type Core_Expecter struct { + mock *mock.Mock +} + +func (_m *Core) EXPECT() *Core_Expecter { + return &Core_Expecter{mock: &_m.Mock} +} + +// Abandon provides a mock function for the type Core +func (_mock *Core) Abandon() { + _mock.Called() + return } -// Download provides a mock function with given fields: ctx -func (_m *Core) Download(ctx context.Context) error { - ret := _m.Called(ctx) +// Core_Abandon_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Abandon' +type Core_Abandon_Call struct { + *mock.Call +} + +// Abandon is a helper method to define mock.On call +func (_e *Core_Expecter) Abandon() *Core_Abandon_Call { + return &Core_Abandon_Call{Call: _e.mock.On("Abandon")} +} + +func (_c *Core_Abandon_Call) Run(run func()) *Core_Abandon_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Core_Abandon_Call) Return() *Core_Abandon_Call { + _c.Call.Return() + return _c +} + +func (_c *Core_Abandon_Call) RunAndReturn(run func()) *Core_Abandon_Call { + _c.Run(run) + return _c +} + +// Download provides a mock function for the type Core +func (_mock *Core) Download(ctx context.Context) error { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for Download") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Error(0) } - return r0 } -// Index provides a mock function with no fields -func (_m *Core) Index() error { - ret := _m.Called() +// Core_Download_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Download' +type Core_Download_Call struct { + *mock.Call +} + +// Download is a helper method to define mock.On call +// - ctx context.Context +func (_e *Core_Expecter) Download(ctx interface{}) *Core_Download_Call { + return &Core_Download_Call{Call: _e.mock.On("Download", ctx)} +} + +func (_c *Core_Download_Call) Run(run func(ctx context.Context)) *Core_Download_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Core_Download_Call) Return(err error) *Core_Download_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Core_Download_Call) RunAndReturn(run func(ctx context.Context) error) *Core_Download_Call { + _c.Call.Return(run) + return _c +} + +// Index provides a mock function for the type Core +func (_mock *Core) Index() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Index") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Persist provides a mock function with no fields -func (_m *Core) Persist() error { - ret := _m.Called() +// Core_Index_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Index' +type Core_Index_Call struct { + *mock.Call +} + +// Index is a helper method to define mock.On call +func (_e *Core_Expecter) Index() *Core_Index_Call { + return &Core_Index_Call{Call: _e.mock.On("Index")} +} + +func (_c *Core_Index_Call) Run(run func()) *Core_Index_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Core_Index_Call) Return(err error) *Core_Index_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Core_Index_Call) RunAndReturn(run func() error) *Core_Index_Call { + _c.Call.Return(run) + return _c +} + +// Persist provides a mock function for the type Core +func (_mock *Core) Persist() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Persist") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// NewCore creates a new instance of Core. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCore(t interface { - mock.TestingT - Cleanup(func()) -}) *Core { - mock := &Core{} - mock.Mock.Test(t) +// Core_Persist_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Persist' +type Core_Persist_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Persist is a helper method to define mock.On call +func (_e *Core_Expecter) Persist() *Core_Persist_Call { + return &Core_Persist_Call{Call: _e.mock.On("Persist")} +} - return mock +func (_c *Core_Persist_Call) Run(run func()) *Core_Persist_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Core_Persist_Call) Return(err error) *Core_Persist_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Core_Persist_Call) RunAndReturn(run func() error) *Core_Persist_Call { + _c.Call.Return(run) + return _c } diff --git a/module/executiondatasync/optimistic_sync/pipeline.go b/module/executiondatasync/optimistic_sync/pipeline.go index d95a658f978..49ee9349576 100644 --- a/module/executiondatasync/optimistic_sync/pipeline.go +++ b/module/executiondatasync/optimistic_sync/pipeline.go @@ -3,21 +3,10 @@ package optimistic_sync import ( "context" "errors" - "fmt" - - "github.com/gammazero/workerpool" - "github.com/rs/zerolog" - "go.uber.org/atomic" - - "github.com/onflow/flow-go/engine" - "github.com/onflow/flow-go/model/flow" - "github.com/onflow/flow-go/module/irrecoverable" ) -var ( - // ErrInvalidTransition is returned when a state transition is invalid. - ErrInvalidTransition = errors.New("invalid state transition") -) +// ErrInvalidTransition is returned when a state transition is invalid. +var ErrInvalidTransition = errors.New("invalid state transition") // PipelineStateProvider is an interface that provides a pipeline's state. type PipelineStateProvider interface { @@ -58,391 +47,3 @@ type Pipeline interface { // Abandon marks the pipeline as abandoned. Abandon() } - -var _ Pipeline = (*PipelineImpl)(nil) - -// worker implements a single worker goroutine that processes tasks submitted to it. -// It supports submission of context-based tasks that return an error. -// Each error that occurs during task execution is sent to a dedicated error channel. -// The primary purpose of the worker is to handle tasks in a non-blocking manner, while still allowing the parent thread -// to observe and handle errors that occur during task execution. -type worker struct { - ctx context.Context - cancel context.CancelFunc - pool *workerpool.WorkerPool - errChan chan error -} - -// newWorker creates a single worker. -func newWorker() *worker { - ctx, cancel := context.WithCancel(context.Background()) - return &worker{ - ctx: ctx, - cancel: cancel, - pool: workerpool.New(1), - errChan: make(chan error, 1), - } -} - -// Submit submits a new task for processing, each error will be propagated in a specific channel. -// Might block the worker if there is no one reading from the error channel and errors are happening. -func (w *worker) Submit(task func(ctx context.Context) error) { - w.pool.Submit(func() { - err := task(w.ctx) - if err != nil && !errors.Is(err, context.Canceled) { - w.errChan <- err - } - }) -} - -// ErrChan returns the channel where errors are delivered from executed tasks. -func (w *worker) ErrChan() <-chan error { - return w.errChan -} - -// StopWait stops the worker pool and waits for all queued tasks to complete. -// No additional tasks may be submitted, but all pending tasks are executed by workers before this function returns. -// This function is blocking and guarantees that any error that occurred during the execution of tasks will be delivered -// to the caller as a return value of this function. -// Any error that was delivered during execution will be delivered to the caller. -func (w *worker) StopWait() error { - w.cancel() - w.pool.StopWait() - - defer close(w.errChan) - select { - case err := <-w.errChan: - return err - default: - return nil - } -} - -// PipelineImpl implements the Pipeline interface -type PipelineImpl struct { - log zerolog.Logger - stateConsumer PipelineStateConsumer - stateChangedNotifier engine.Notifier - core Core - worker *worker - - // The following fields are accessed externally. they are stored using atomics to avoid - // blocking the caller. - state *atomic.Int32 - parentStateCache *atomic.Int32 - isSealed *atomic.Bool - isAbandoned *atomic.Bool - isIndexed *atomic.Bool -} - -// NewPipeline creates a new processing pipeline. -// The pipeline is initialized in the Pending state. -func NewPipeline( - log zerolog.Logger, - executionResult *flow.ExecutionResult, - isSealed bool, - stateReceiver PipelineStateConsumer, -) *PipelineImpl { - log = log.With(). - Str("component", "pipeline"). - Str("execution_result_id", executionResult.ExecutionDataID.String()). - Str("block_id", executionResult.BlockID.String()). - Logger() - - return &PipelineImpl{ - log: log, - stateConsumer: stateReceiver, - worker: newWorker(), - state: atomic.NewInt32(int32(StatePending)), - parentStateCache: atomic.NewInt32(int32(StatePending)), - isSealed: atomic.NewBool(isSealed), - isAbandoned: atomic.NewBool(false), - isIndexed: atomic.NewBool(false), - stateChangedNotifier: engine.NewNotifier(), - } -} - -// Run starts the pipeline processing and blocks until completion or context cancellation. -// CAUTION: not concurrency safe! Run must only be called once. -// -// Expected Errors: -// - context.Canceled: when the context is canceled -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) -func (p *PipelineImpl) Run(ctx context.Context, core Core, parentState State) error { - if p.core != nil { - return irrecoverable.NewExceptionf("pipeline has been already started, it is not designed to be run again") - } - p.core = core - p.parentStateCache.Store(int32(parentState)) - // run the main event loop by calling p.loop. any error returned from it needs to be propagated to the caller. - // IMPORTANT: after the main loop has exited we need to ensure that worker goroutine has also finished - // because we need to ensure that it can report any error that has happened during the execution of detached operation. - // By calling StopWait we ensure that worker has stopped which also guarantees that any error has been delivered to the - // error channel and returned as result of StopWait. Without waiting for the worker to stop, we might skip some errors - // since the worker didn't have a chance to report them yet, and we have already returned from the Run method. - return errors.Join(p.loop(ctx), p.worker.StopWait()) -} - -// loop implements the main event loop for state machine. It reacts on different events and performs operations upon -// entering or leaving some state. -// loop will perform a blocking operation until one of next things happens, whatever happens first: -// 1. parent context signals that it is no longer valid. -// 2. the worker thread has received an error. It's not safe to continue execution anymore, so this error needs to be propagated -// to the caller. -// 3. Pipeline has successfully entered terminal state. -// Pipeline won't and shouldn't perform any state transitions after returning from this function. -// Expected Errors: -// - context.Canceled: when the context is canceled -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) -func (p *PipelineImpl) loop(ctx context.Context) error { - // try to start processing in case we are able to. - p.stateChangedNotifier.Notify() - - for { - select { - case <-ctx.Done(): - return ctx.Err() - case err := <-p.worker.ErrChan(): - return err - case <-p.stateChangedNotifier.Channel(): - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - // if parent got abandoned no point to continue, and we just go to the abandoned state and perform cleanup logic. - if p.checkAbandoned() { - if err := p.transitionTo(StateAbandoned); err != nil { - return fmt.Errorf("could not transition to abandoned state: %w", err) - } - } - - currentState := p.GetState() - switch currentState { - case StatePending: - if err := p.onStartProcessing(); err != nil { - return fmt.Errorf("could not process pending state: %w", err) - } - case StateProcessing: - if err := p.onProcessing(); err != nil { - return fmt.Errorf("could not process processing state: %w", err) - } - case StateWaitingPersist: - if err := p.onPersistChanges(); err != nil { - return fmt.Errorf("could not process waiting persist state: %w", err) - } - case StateAbandoned: - p.core.Abandon() - return nil - case StateComplete: - return nil // terminate - default: - return fmt.Errorf("invalid pipeline state: %s", currentState) - } - } - } -} - -// onStartProcessing performs the initial state transitions depending on the parent state: -// - Pending -> Processing -// - Pending -> Abandoned -// No errors are expected during normal operations. -func (p *PipelineImpl) onStartProcessing() error { - switch p.parentState() { - case StateProcessing, StateWaitingPersist, StateComplete: - err := p.transitionTo(StateProcessing) - if err != nil { - return err - } - p.worker.Submit(p.performDownload) - case StatePending: - return nil - case StateAbandoned: - return p.transitionTo(StateAbandoned) - default: - // it's unexpected for the parent to be in any other state. this most likely indicates there's a bug - return fmt.Errorf("unexpected parent state: %s", p.parentState()) - } - return nil -} - -// onProcessing performs the state transitions when the pipeline is in the Processing state. -// When data has been successfully indexed, we can transition to StateWaitingPersist. -// No errors are expected during normal operations. -func (p *PipelineImpl) onProcessing() error { - if p.isIndexed.Load() { - return p.transitionTo(StateWaitingPersist) - } - return nil -} - -// onPersistChanges performs the state transitions when the pipeline is in the WaitingPersist state. -// When the execution result has been sealed and the parent has already transitioned to StateComplete then -// we can persist the data and transition to StateComplete. -// No errors are expected during normal operations. -func (p *PipelineImpl) onPersistChanges() error { - if p.isSealed.Load() && p.parentState() == StateComplete { - if err := p.core.Persist(); err != nil { - return fmt.Errorf("could not persist pending changes: %w", err) - } - return p.transitionTo(StateComplete) - } else { - return nil - } -} - -// checkAbandoned returns true if the pipeline or its parent are abandoned. -func (p *PipelineImpl) checkAbandoned() bool { - if p.isAbandoned.Load() { - return true - } - if p.parentState() == StateAbandoned { - return true - } - return p.GetState() == StateAbandoned -} - -// GetState returns the current state of the pipeline. -func (p *PipelineImpl) GetState() State { - return State(p.state.Load()) -} - -// parentState returns the last cached parent state of the pipeline. -func (p *PipelineImpl) parentState() State { - return State(p.parentStateCache.Load()) -} - -// SetSealed marks the execution result as sealed. -// This will cause the pipeline to eventually transition to the StateComplete state when the parent finishes processing. -func (p *PipelineImpl) SetSealed() { - // Note: do not use a mutex here to avoid blocking the results forest. - if p.isSealed.CompareAndSwap(false, true) { - p.stateChangedNotifier.Notify() - } -} - -// OnParentStateUpdated updates the pipeline's state based on the provided parent state. -// If the parent state has changed, it will notify the state consumer and trigger a state change notification. -func (p *PipelineImpl) OnParentStateUpdated(parentState State) { - oldState := p.parentStateCache.Load() - if p.parentStateCache.CompareAndSwap(oldState, int32(parentState)) { - p.stateChangedNotifier.Notify() - } -} - -// Abandon marks the pipeline as abandoned -// This will cause the pipeline to eventually transition to the Abandoned state and halt processing -func (p *PipelineImpl) Abandon() { - if p.isAbandoned.CompareAndSwap(false, true) { - p.stateChangedNotifier.Notify() - } -} - -// performDownload performs the processing step of the pipeline by downloading and indexing data. -// It uses an atomic flag to indicate whether the operation has been completed successfully which -// informs the state machine that eventually it can transition to the next state. -// Expected Errors: -// - context.Canceled: when the context is canceled -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) -func (p *PipelineImpl) performDownload(ctx context.Context) error { - if err := p.core.Download(ctx); err != nil { - return fmt.Errorf("could not perform download: %w", err) - } - if err := p.core.Index(); err != nil { - return fmt.Errorf("could not perform indexing: %w", err) - } - if p.isIndexed.CompareAndSwap(false, true) { - p.stateChangedNotifier.Notify() - } - return nil -} - -// transitionTo transitions the pipeline to the given state and broadcasts -// the state change to children pipelines. -// -// Expected Errors: -// - ErrInvalidTransition: when the transition is invalid -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) -func (p *PipelineImpl) transitionTo(newState State) error { - hasChange, err := p.setState(newState) - if err != nil { - return err - } - - if hasChange { - // send notification for all state changes. we require that implementations of [PipelineStateConsumer] - // are non-blocking and consume the state updates without noteworthy delay. - p.stateConsumer.OnStateUpdated(newState) - p.stateChangedNotifier.Notify() - } - - return nil -} - -// setState sets the state of the pipeline and logs the transition. -// Returns true if the state was changed, false otherwise. -// -// Expected Errors: -// - ErrInvalidTransition: when the state transition is invalid -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) -func (p *PipelineImpl) setState(newState State) (bool, error) { - currentState := p.GetState() - - // transitioning to the same state is a no-op - if currentState == newState { - return false, nil - } - - if err := p.validateTransition(currentState, newState); err != nil { - return false, fmt.Errorf("failed to transition from %s to %s: %w", currentState, newState, err) - } - - if !p.state.CompareAndSwap(int32(currentState), int32(newState)) { - // Note: this should never happen since state is only updated within the Run goroutine. - return false, fmt.Errorf("failed to transition from %s to %s", currentState, newState) - } - - p.log.Debug(). - Str("old_state", currentState.String()). - Str("new_state", newState.String()). - Msg("pipeline state transition") - - return true, nil -} - -// validateTransition validates the transition from the current state to the new state. -// -// Expected Errors: -// - ErrInvalidTransition: when the transition is invalid -// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) -func (p *PipelineImpl) validateTransition(currentState State, newState State) error { - switch newState { - case StateProcessing: - if currentState == StatePending { - return nil - } - case StateWaitingPersist: - if currentState == StateProcessing { - return nil - } - case StateComplete: - if currentState == StateWaitingPersist { - return nil - } - case StateAbandoned: - // Note: it does not make sense to transition to abandoned from persisting or completed since to be in either state: - // 1. the parent must be completed - // 2. the pipeline's result must be sealed - // At that point, there are no conditions that would cause the pipeline be abandoned - switch currentState { - case StatePending, StateProcessing, StateWaitingPersist: - return nil - } - - default: - return fmt.Errorf("invalid transition to state: %s", newState) - } - - return ErrInvalidTransition -} diff --git a/module/executiondatasync/optimistic_sync/pipeline/core.go b/module/executiondatasync/optimistic_sync/pipeline/core.go new file mode 100644 index 00000000000..67af0ba7a41 --- /dev/null +++ b/module/executiondatasync/optimistic_sync/pipeline/core.go @@ -0,0 +1,325 @@ +package pipeline + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "github.com/rs/zerolog" + "golang.org/x/sync/errgroup" + + "github.com/onflow/flow-go/engine/access/ingestion/tx_error_messages" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync/persisters" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync/persisters/stores" + "github.com/onflow/flow-go/module/state_synchronization/indexer" + "github.com/onflow/flow-go/module/state_synchronization/requester" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/inmemory" +) + +// DefaultTxResultErrMsgsRequestTimeout is the default timeout for requesting transaction result error messages. +const DefaultTxResultErrMsgsRequestTimeout = 5 * time.Second + +// workingData encapsulates all components and temporary storage +// involved in processing a single block's execution data. When processing +// is complete or abandoned, the entire workingData can be discarded. +type workingData struct { + protocolDB storage.DB + lockManager storage.LockManager + + persistentRegisters storage.RegisterIndex + persistentEvents storage.Events + persistentCollections storage.Collections + persistentResults storage.LightTransactionResults + persistentTxResultErrMsgs storage.TransactionResultErrorMessages + latestPersistedSealedResult storage.LatestPersistedSealedResult + + inmemRegisters *inmemory.RegistersReader + inmemEvents *inmemory.EventsReader + inmemCollections *inmemory.CollectionsReader + inmemTransactions *inmemory.TransactionsReader + inmemResults *inmemory.LightTransactionResultsReader + inmemTxResultErrMsgs *inmemory.TransactionResultErrorMessagesReader + + // Active processing components + execDataRequester requester.ExecutionDataRequester + txResultErrMsgsRequester tx_error_messages.Requester + txResultErrMsgsRequestTimeout time.Duration + + // Working data + executionData *execution_data.BlockExecutionData + txResultErrMsgsData []flow.TransactionResultErrorMessage + indexerData *indexer.IndexerData + persisted bool +} + +var _ optimistic_sync.Core = (*Core)(nil) + +// Core implements the Core interface for processing execution data. +// It coordinates the download, indexing, and persisting of execution data. +// +// Safe for concurrent use. +type Core struct { + log zerolog.Logger + mu sync.Mutex + + workingData *workingData + + executionResult *flow.ExecutionResult + block *flow.Block +} + +// NewCore creates a new Core with all necessary dependencies +// Safe for concurrent use. +// +// No error returns are expected during normal operations +func NewCore( + logger zerolog.Logger, + executionResult *flow.ExecutionResult, + block *flow.Block, + execDataRequester requester.ExecutionDataRequester, + txResultErrMsgsRequester tx_error_messages.Requester, + txResultErrMsgsRequestTimeout time.Duration, + persistentRegisters storage.RegisterIndex, + persistentEvents storage.Events, + persistentCollections storage.Collections, + persistentResults storage.LightTransactionResults, + persistentTxResultErrMsg storage.TransactionResultErrorMessages, + latestPersistedSealedResult storage.LatestPersistedSealedResult, + protocolDB storage.DB, + lockManager storage.LockManager, +) (*Core, error) { + if block.ID() != executionResult.BlockID { + return nil, fmt.Errorf("header ID and execution result block ID must match") + } + + coreLogger := logger.With(). + Str("component", "execution_data_core"). + Str("execution_result_id", executionResult.ID().String()). + Str("block_id", executionResult.BlockID.String()). + Uint64("height", block.Height). + Logger() + + return &Core{ + log: coreLogger, + block: block, + executionResult: executionResult, + workingData: &workingData{ + protocolDB: protocolDB, + lockManager: lockManager, + + execDataRequester: execDataRequester, + txResultErrMsgsRequester: txResultErrMsgsRequester, + txResultErrMsgsRequestTimeout: txResultErrMsgsRequestTimeout, + + persistentRegisters: persistentRegisters, + persistentEvents: persistentEvents, + persistentCollections: persistentCollections, + persistentResults: persistentResults, + persistentTxResultErrMsgs: persistentTxResultErrMsg, + latestPersistedSealedResult: latestPersistedSealedResult, + }, + }, nil +} + +// Download retrieves all necessary data for processing from the network. +// Download will block until the data is successfully downloaded, and has not internal timeout. +// When Aboandon is called, the caller must cancel the context passed in to shutdown the operation +// otherwise it may block indefinitely. +// +// The method may only be called once. Calling it multiple times will return an error. +// Calling Download after Abandon is called will return an error. +// +// Expected error returns during normal operation: +// - [context.Canceled]: if the provided context was canceled before completion +func (c *Core) Download(ctx context.Context) error { + c.mu.Lock() + defer c.mu.Unlock() + if c.workingData == nil { + return optimistic_sync.ErrResultAbandoned + } + if c.workingData.executionData != nil { + return fmt.Errorf("already downloaded") + } + + c.log.Debug().Msg("downloading execution data") + + g, gCtx := errgroup.WithContext(ctx) + + var executionData *execution_data.BlockExecutionData + g.Go(func() error { + var err error + executionData, err = c.workingData.execDataRequester.RequestExecutionData(gCtx) + if err != nil { + return fmt.Errorf("failed to request execution data: %w", err) + } + + return nil + }) + + var txResultErrMsgsData []flow.TransactionResultErrorMessage + g.Go(func() error { + timeoutCtx, cancel := context.WithTimeout(gCtx, c.workingData.txResultErrMsgsRequestTimeout) + defer cancel() + + var err error + txResultErrMsgsData, err = c.workingData.txResultErrMsgsRequester.Request(timeoutCtx) + if err != nil { + // transaction error messages are downloaded from execution nodes over grpc and have no + // protocol guarantees for delivery or correctness. Therefore, we attempt to download them + // on a best-effort basis, and give up after a reasonable timeout to avoid blocking the + // main indexing process. Missing error messages are handled gracefully by the rest of + // the system, and can be retried or backfilled as needed later. + if errors.Is(err, context.DeadlineExceeded) { + c.log.Debug(). + Dur("timeout", c.workingData.txResultErrMsgsRequestTimeout). + Msg("transaction result error messages request timed out") + return nil + } + + return fmt.Errorf("failed to request transaction result error messages data: %w", err) + } + return nil + }) + + if err := g.Wait(); err != nil { + return err + } + + c.workingData.executionData = executionData + c.workingData.txResultErrMsgsData = txResultErrMsgsData + + c.log.Debug().Msg("successfully downloaded execution data") + + return nil +} + +// Index processes the downloaded data and stores it into in-memory indexes. +// Must be called after Download. +// +// The method may only be called once. Calling it multiple times will return an error. +// Calling Index after Abandon is called will return an error. +// +// No error returns are expected during normal operations +func (c *Core) Index() error { + c.mu.Lock() + defer c.mu.Unlock() + if c.workingData == nil { + return optimistic_sync.ErrResultAbandoned + } + if c.workingData.executionData == nil { + return fmt.Errorf("downloading is not complete") + } + if c.workingData.indexerData != nil { + return fmt.Errorf("already indexed") + } + + c.log.Debug().Msg("indexing execution data") + + indexerComponent, err := indexer.NewInMemoryIndexer(c.log, c.block, c.executionResult) + if err != nil { + return fmt.Errorf("failed to create indexer: %w", err) + } + + indexerData, err := indexerComponent.IndexBlockData(c.workingData.executionData) + if err != nil { + return fmt.Errorf("failed to index execution data: %w", err) + } + + if c.workingData.txResultErrMsgsData != nil { + err = indexer.ValidateTxErrors(indexerData.Results, c.workingData.txResultErrMsgsData) + if err != nil { + return fmt.Errorf("failed to validate transaction result error messages: %w", err) + } + } + + blockID := c.executionResult.BlockID + + c.workingData.indexerData = indexerData + c.workingData.inmemCollections = inmemory.NewCollections(indexerData.Collections) + c.workingData.inmemTransactions = inmemory.NewTransactions(indexerData.Transactions) + c.workingData.inmemTxResultErrMsgs = inmemory.NewTransactionResultErrorMessages(blockID, c.workingData.txResultErrMsgsData) + c.workingData.inmemEvents = inmemory.NewEvents(blockID, indexerData.Events) + c.workingData.inmemResults = inmemory.NewLightTransactionResults(blockID, indexerData.Results) + c.workingData.inmemRegisters = inmemory.NewRegisters(c.block.Height, indexerData.Registers) + + c.log.Debug().Msg("successfully indexed execution data") + + return nil +} + +// Persist stores the indexed data in permanent storage. +// Must be called after Index. +// +// The method may only be called once. Calling it multiple times will return an error. +// Calling Persist after Abandon is called will return an error. +// +// No error returns are expected during normal operations +func (c *Core) Persist() error { + c.mu.Lock() + defer c.mu.Unlock() + if c.workingData == nil { + return optimistic_sync.ErrResultAbandoned + } + if c.workingData.persisted { + return fmt.Errorf("already persisted") + } + if c.workingData.indexerData == nil { + return fmt.Errorf("indexing is not complete") + } + + c.log.Debug().Msg("persisting execution data") + + indexerData := c.workingData.indexerData + + // the BlockPersister updates the latest persisted sealed result within the batch operation, so + // all other updates must be done before the batch is committed to ensure the state remains + // consistent. The registers db allows repeated indexing of the most recent block's registers, + // so it is safe to persist them before the block persister. + registerPersister := persisters.NewRegistersPersister(indexerData.Registers, c.workingData.persistentRegisters, c.block.Height) + if err := registerPersister.Persist(); err != nil { + return fmt.Errorf("failed to persist registers: %w", err) + } + + persisterStores := []stores.PersisterStore{ + stores.NewEventsStore(indexerData.Events, c.workingData.persistentEvents, c.executionResult.BlockID), + stores.NewResultsStore(indexerData.Results, c.workingData.persistentResults, c.executionResult.BlockID), + stores.NewCollectionsStore(indexerData.Collections, c.workingData.persistentCollections), + stores.NewTxResultErrMsgStore(c.workingData.txResultErrMsgsData, c.workingData.persistentTxResultErrMsgs, c.executionResult.BlockID, c.workingData.lockManager), + stores.NewLatestSealedResultStore(c.workingData.latestPersistedSealedResult, c.executionResult.ID(), c.block.Height), + } + blockPersister := persisters.NewBlockPersister( + c.log, + c.workingData.protocolDB, + c.workingData.lockManager, + c.executionResult, + persisterStores, + ) + if err := blockPersister.Persist(); err != nil { + return fmt.Errorf("failed to persist block data: %w", err) + } + + // reset the indexer data to prevent multiple calls to Persist + c.workingData.indexerData = nil + c.workingData.persisted = true + + return nil +} + +// Abandon indicates that the protocol has abandoned this state. Hence processing will be aborted +// and any data dropped. +// This method will block until other in-progress operations are complete. If Download is in progress, +// the caller should cancel its context to ensure the operation completes in a timely manner. +// +// The method is idempotent. Calling it multiple times has no effect. +func (c *Core) Abandon() { + c.mu.Lock() + defer c.mu.Unlock() + + c.workingData = nil +} diff --git a/module/executiondatasync/optimistic_sync/core_impl_test.go b/module/executiondatasync/optimistic_sync/pipeline/core_test.go similarity index 90% rename from module/executiondatasync/optimistic_sync/core_impl_test.go rename to module/executiondatasync/optimistic_sync/pipeline/core_test.go index 048a80fb521..e9118d323c2 100644 --- a/module/executiondatasync/optimistic_sync/core_impl_test.go +++ b/module/executiondatasync/optimistic_sync/pipeline/core_test.go @@ -1,4 +1,4 @@ -package optimistic_sync +package pipeline import ( "context" @@ -13,6 +13,7 @@ import ( txerrmsgsmock "github.com/onflow/flow-go/engine/access/ingestion/tx_error_messages/mock" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync" reqestermock "github.com/onflow/flow-go/module/state_synchronization/requester/mock" "github.com/onflow/flow-go/storage" storagemock "github.com/onflow/flow-go/storage/mock" @@ -20,8 +21,8 @@ import ( "github.com/onflow/flow-go/utils/unittest/fixtures" ) -// CoreImplSuite is a test suite for testing the CoreImpl. -type CoreImplSuite struct { +// CoreSuite is a test suite for testing the Core. +type CoreSuite struct { suite.Suite execDataRequester *reqestermock.ExecutionDataRequester txResultErrMsgsRequester *txerrmsgsmock.Requester @@ -36,12 +37,12 @@ type CoreImplSuite struct { latestPersistedSealedResult *storagemock.LatestPersistedSealedResult } -func TestCoreImplSuiteSuite(t *testing.T) { +func TestCoreSuiteSuite(t *testing.T) { t.Parallel() - suite.Run(t, new(CoreImplSuite)) + suite.Run(t, new(CoreSuite)) } -func (c *CoreImplSuite) SetupTest() { +func (c *CoreSuite) SetupTest() { t := c.T() c.execDataRequester = reqestermock.NewExecutionDataRequester(t) @@ -49,11 +50,11 @@ func (c *CoreImplSuite) SetupTest() { c.txResultErrMsgsRequestTimeout = 100 * time.Millisecond } -// createTestCoreImpl creates a CoreImpl instance with mocked dependencies for testing. +// createTestCore creates a Core instance with mocked dependencies for testing. // -// Returns a configured CoreImpl ready for testing. -func (c *CoreImplSuite) createTestCoreImpl(tf *testFixture) *CoreImpl { - core, err := NewCoreImpl( +// Returns a configured Core ready for testing. +func (c *CoreSuite) createTestCore(tf *testFixture) *Core { + core, err := NewCore( unittest.Logger(), tf.exeResult, tf.block, @@ -129,12 +130,12 @@ func generateFixture(g *fixtures.GeneratorSuite) *testFixture { } } -func (c *CoreImplSuite) TestCoreImpl_Constructor() { +func (c *CoreSuite) TestCore_Constructor() { block := unittest.BlockFixture() executionResult := unittest.ExecutionResultFixture(unittest.WithBlock(block)) c.Run("happy path", func() { - core, err := NewCoreImpl( + core, err := NewCore( unittest.Logger(), executionResult, block, @@ -155,7 +156,7 @@ func (c *CoreImplSuite) TestCoreImpl_Constructor() { }) c.Run("block ID mismatch", func() { - core, err := NewCoreImpl( + core, err := NewCore( unittest.Logger(), executionResult, unittest.BlockFixture(), @@ -176,9 +177,9 @@ func (c *CoreImplSuite) TestCoreImpl_Constructor() { }) } -// TestCoreImpl_Download tests the Download method retrieves execution data and transaction error +// TestCore_Download tests the Download method retrieves execution data and transaction error // messages. -func (c *CoreImplSuite) TestCoreImpl_Download() { +func (c *CoreSuite) TestCore_Download() { ctx := context.Background() g := fixtures.NewGeneratorSuite() @@ -192,7 +193,7 @@ func (c *CoreImplSuite) TestCoreImpl_Download() { c.Run("successful download", func() { tf := generateFixture(g) - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) c.execDataRequester.On("RequestExecutionData", mock.Anything).Return(tf.execData, nil).Once() c.txResultErrMsgsRequester.On("Request", mock.Anything).Return(tf.txErrMsgs, nil).Once() @@ -210,7 +211,7 @@ func (c *CoreImplSuite) TestCoreImpl_Download() { c.Run("execution data request error", func() { tf := generateFixture(g) - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) expectedErr := fmt.Errorf("test execution data request error") @@ -230,7 +231,7 @@ func (c *CoreImplSuite) TestCoreImpl_Download() { c.Run("transaction result error messages request error", func() { tf := generateFixture(g) - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) expectedErr := fmt.Errorf("test tx error messages request error") @@ -250,7 +251,7 @@ func (c *CoreImplSuite) TestCoreImpl_Download() { c.Run("context cancellation", func() { tf := generateFixture(g) - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -276,7 +277,7 @@ func (c *CoreImplSuite) TestCoreImpl_Download() { c.Run("txResultErrMsgsRequestTimeout expiration", func() { tf := generateFixture(g) - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) c.execDataRequester.On("RequestExecutionData", mock.Anything).Return(tf.execData, nil).Once() @@ -303,18 +304,18 @@ func (c *CoreImplSuite) TestCoreImpl_Download() { c.Run("Download after Abandon returns an error", func() { tf := generateFixture(g) - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) core.Abandon() c.Nil(core.workingData) err := core.Download(ctx) - c.ErrorIs(err, errResultAbandoned) + c.ErrorIs(err, optimistic_sync.ErrResultAbandoned) }) } -// TestCoreImpl_Index tests the Index method which processes downloaded data. -func (c *CoreImplSuite) TestCoreImpl_Index() { +// TestCore_Index tests the Index method which processes downloaded data. +func (c *CoreSuite) TestCore_Index() { ctx := context.Background() g := fixtures.NewGeneratorSuite() @@ -323,7 +324,7 @@ func (c *CoreImplSuite) TestCoreImpl_Index() { c.txResultErrMsgsRequester.On("Request", mock.Anything).Return(tf.txErrMsgs, nil) c.Run("successful indexing", func() { - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Download(ctx) c.Require().NoError(err) @@ -346,7 +347,7 @@ func (c *CoreImplSuite) TestCoreImpl_Index() { }) c.Run("indexer constructor error", func() { - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) core.block = g.Blocks().Fixture() err := core.Download(ctx) @@ -358,7 +359,7 @@ func (c *CoreImplSuite) TestCoreImpl_Index() { }) c.Run("failed to index block", func() { - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Download(ctx) c.Require().NoError(err) @@ -371,7 +372,7 @@ func (c *CoreImplSuite) TestCoreImpl_Index() { }) c.Run("failed to validate transaction result error messages", func() { - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Download(ctx) c.Require().NoError(err) @@ -387,17 +388,17 @@ func (c *CoreImplSuite) TestCoreImpl_Index() { }) c.Run("Index after Abandon returns an error", func() { - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) core.Abandon() c.Nil(core.workingData) err := core.Index() - c.ErrorIs(err, errResultAbandoned) + c.ErrorIs(err, optimistic_sync.ErrResultAbandoned) }) c.Run("Index before Download returns an error", func() { - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Index() c.ErrorContains(err, "downloading is not complete") @@ -405,8 +406,8 @@ func (c *CoreImplSuite) TestCoreImpl_Index() { }) } -// TestCoreImpl_Persist tests the Persist method which persists indexed data to storages and database. -func (c *CoreImplSuite) TestCoreImpl_Persist() { +// TestCore_Persist tests the Persist method which persists indexed data to storages and database. +func (c *CoreSuite) TestCore_Persist() { t := c.T() ctx := context.Background() g := fixtures.NewGeneratorSuite() @@ -429,7 +430,7 @@ func (c *CoreImplSuite) TestCoreImpl_Persist() { c.Run("successful persistence of empty data", func() { resetMocks() - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Download(ctx) c.Require().NoError(err) @@ -483,7 +484,7 @@ func (c *CoreImplSuite) TestCoreImpl_Persist() { expectedErr := fmt.Errorf("test persisting registers failure") resetMocks() - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Download(ctx) c.Require().NoError(err) @@ -502,7 +503,7 @@ func (c *CoreImplSuite) TestCoreImpl_Persist() { expectedErr := fmt.Errorf("test persisting events failure") resetMocks() - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Download(ctx) c.Require().NoError(err) @@ -529,18 +530,18 @@ func (c *CoreImplSuite) TestCoreImpl_Persist() { c.Run("Persist after Abandon returns an error", func() { resetMocks() - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) core.Abandon() c.Nil(core.workingData) err := core.Persist() - c.ErrorIs(err, errResultAbandoned) + c.ErrorIs(err, optimistic_sync.ErrResultAbandoned) }) c.Run("Persist before Index returns an error", func() { resetMocks() - core := c.createTestCoreImpl(tf) + core := c.createTestCore(tf) err := core.Persist() c.ErrorContains(err, "indexing is not complete") }) diff --git a/module/executiondatasync/optimistic_sync/pipeline/pipeline.go b/module/executiondatasync/optimistic_sync/pipeline/pipeline.go new file mode 100644 index 00000000000..c44e6f44b15 --- /dev/null +++ b/module/executiondatasync/optimistic_sync/pipeline/pipeline.go @@ -0,0 +1,404 @@ +package pipeline + +import ( + "context" + "errors" + "fmt" + + "github.com/gammazero/workerpool" + "github.com/rs/zerolog" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/engine" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync" + "github.com/onflow/flow-go/module/irrecoverable" +) + +var _ optimistic_sync.Pipeline = (*Pipeline)(nil) + +// worker implements a single worker goroutine that processes tasks submitted to it. +// It supports submission of context-based tasks that return an error. +// Each error that occurs during task execution is sent to a dedicated error channel. +// The primary purpose of the worker is to handle tasks in a non-blocking manner, while still allowing the parent thread +// to observe and handle errors that occur during task execution. +type worker struct { + ctx context.Context + cancel context.CancelFunc + pool *workerpool.WorkerPool + errChan chan error +} + +// newWorker creates a single worker. +func newWorker() *worker { + ctx, cancel := context.WithCancel(context.Background()) + return &worker{ + ctx: ctx, + cancel: cancel, + pool: workerpool.New(1), + errChan: make(chan error, 1), + } +} + +// Submit submits a new task for processing, each error will be propagated in a specific channel. +// Might block the worker if there is no one reading from the error channel and errors are happening. +func (w *worker) Submit(task func(ctx context.Context) error) { + w.pool.Submit(func() { + err := task(w.ctx) + if err != nil && !errors.Is(err, context.Canceled) { + w.errChan <- err + } + }) +} + +// ErrChan returns the channel where errors are delivered from executed tasks. +func (w *worker) ErrChan() <-chan error { + return w.errChan +} + +// StopWait stops the worker pool and waits for all queued tasks to complete. +// No additional tasks may be submitted, but all pending tasks are executed by workers before this function returns. +// This function is blocking and guarantees that any error that occurred during the execution of tasks will be delivered +// to the caller as a return value of this function. +// Any error that was delivered during execution will be delivered to the caller. +func (w *worker) StopWait() error { + w.cancel() + w.pool.StopWait() + + defer close(w.errChan) + select { + case err := <-w.errChan: + return err + default: + return nil + } +} + +// Pipeline implements the Pipeline interface +type Pipeline struct { + log zerolog.Logger + stateConsumer optimistic_sync.PipelineStateConsumer + stateChangedNotifier engine.Notifier + core optimistic_sync.Core + worker *worker + + // The following fields are accessed externally. they are stored using atomics to avoid + // blocking the caller. + state *atomic.Int32 + parentStateCache *atomic.Int32 + isSealed *atomic.Bool + isAbandoned *atomic.Bool + isIndexed *atomic.Bool +} + +// NewPipeline creates a new processing pipeline. +// The pipeline is initialized in the Pending state. +func NewPipeline( + log zerolog.Logger, + executionResult *flow.ExecutionResult, + isSealed bool, + stateReceiver optimistic_sync.PipelineStateConsumer, +) *Pipeline { + log = log.With(). + Str("component", "pipeline"). + Str("execution_result_id", executionResult.ExecutionDataID.String()). + Str("block_id", executionResult.BlockID.String()). + Logger() + + return &Pipeline{ + log: log, + stateConsumer: stateReceiver, + worker: newWorker(), + state: atomic.NewInt32(int32(optimistic_sync.StatePending)), + parentStateCache: atomic.NewInt32(int32(optimistic_sync.StatePending)), + isSealed: atomic.NewBool(isSealed), + isAbandoned: atomic.NewBool(false), + isIndexed: atomic.NewBool(false), + stateChangedNotifier: engine.NewNotifier(), + } +} + +// Run starts the pipeline processing and blocks until completion or context cancellation. +// CAUTION: not concurrency safe! Run must only be called once. +// +// Expected Errors: +// - context.Canceled: when the context is canceled +// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +func (p *Pipeline) Run(ctx context.Context, core optimistic_sync.Core, parentState optimistic_sync.State) error { + if p.core != nil { + return irrecoverable.NewExceptionf("pipeline has been already started, it is not designed to be run again") + } + p.core = core + p.parentStateCache.Store(int32(parentState)) + // run the main event loop by calling p.loop. any error returned from it needs to be propagated to the caller. + // IMPORTANT: after the main loop has exited we need to ensure that worker goroutine has also finished + // because we need to ensure that it can report any error that has happened during the execution of detached operation. + // By calling StopWait we ensure that worker has stopped which also guarantees that any error has been delivered to the + // error channel and returned as result of StopWait. Without waiting for the worker to stop, we might skip some errors + // since the worker didn't have a chance to report them yet, and we have already returned from the Run method. + return errors.Join(p.loop(ctx), p.worker.StopWait()) +} + +// loop implements the main event loop for state machine. It reacts on different events and performs operations upon +// entering or leaving some state. +// loop will perform a blocking operation until one of next things happens, whatever happens first: +// 1. parent context signals that it is no longer valid. +// 2. the worker thread has received an error. It's not safe to continue execution anymore, so this error needs to be propagated +// to the caller. +// 3. Pipeline has successfully entered terminal state. +// Pipeline won't and shouldn't perform any state transitions after returning from this function. +// Expected Errors: +// - context.Canceled: when the context is canceled +// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +func (p *Pipeline) loop(ctx context.Context) error { + // try to start processing in case we are able to. + p.stateChangedNotifier.Notify() + + for { + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-p.worker.ErrChan(): + return err + case <-p.stateChangedNotifier.Channel(): + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + // if parent got abandoned no point to continue, and we just go to the abandoned state and perform cleanup logic. + if p.checkAbandoned() { + if err := p.transitionTo(optimistic_sync.StateAbandoned); err != nil { + return fmt.Errorf("could not transition to abandoned state: %w", err) + } + } + + currentState := p.GetState() + switch currentState { + case optimistic_sync.StatePending: + if err := p.onStartProcessing(); err != nil { + return fmt.Errorf("could not process pending state: %w", err) + } + case optimistic_sync.StateProcessing: + if err := p.onProcessing(); err != nil { + return fmt.Errorf("could not process processing state: %w", err) + } + case optimistic_sync.StateWaitingPersist: + if err := p.onPersistChanges(); err != nil { + return fmt.Errorf("could not process waiting persist state: %w", err) + } + case optimistic_sync.StateAbandoned: + p.core.Abandon() + return nil + case optimistic_sync.StateComplete: + return nil // terminate + default: + return fmt.Errorf("invalid pipeline state: %s", currentState) + } + } + } +} + +// onStartProcessing performs the initial state transitions depending on the parent state: +// - Pending -> Processing +// - Pending -> Abandoned +// No errors are expected during normal operations. +func (p *Pipeline) onStartProcessing() error { + switch p.parentState() { + case optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist, optimistic_sync.StateComplete: + err := p.transitionTo(optimistic_sync.StateProcessing) + if err != nil { + return err + } + p.worker.Submit(p.performDownload) + case optimistic_sync.StatePending: + return nil + case optimistic_sync.StateAbandoned: + return p.transitionTo(optimistic_sync.StateAbandoned) + default: + // it's unexpected for the parent to be in any other state. this most likely indicates there's a bug + return fmt.Errorf("unexpected parent state: %s", p.parentState()) + } + return nil +} + +// onProcessing performs the state transitions when the pipeline is in the Processing state. +// When data has been successfully indexed, we can transition to StateWaitingPersist. +// No errors are expected during normal operations. +func (p *Pipeline) onProcessing() error { + if p.isIndexed.Load() { + return p.transitionTo(optimistic_sync.StateWaitingPersist) + } + return nil +} + +// onPersistChanges performs the state transitions when the pipeline is in the WaitingPersist state. +// When the execution result has been sealed and the parent has already transitioned to StateComplete then +// we can persist the data and transition to StateComplete. +// No errors are expected during normal operations. +func (p *Pipeline) onPersistChanges() error { + if p.isSealed.Load() && p.parentState() == optimistic_sync.StateComplete { + if err := p.core.Persist(); err != nil { + return fmt.Errorf("could not persist pending changes: %w", err) + } + return p.transitionTo(optimistic_sync.StateComplete) + } else { + return nil + } +} + +// checkAbandoned returns true if the pipeline or its parent are abandoned. +func (p *Pipeline) checkAbandoned() bool { + if p.isAbandoned.Load() { + return true + } + if p.parentState() == optimistic_sync.StateAbandoned { + return true + } + return p.GetState() == optimistic_sync.StateAbandoned +} + +// GetState returns the current state of the pipeline. +func (p *Pipeline) GetState() optimistic_sync.State { + return optimistic_sync.State(p.state.Load()) +} + +// parentState returns the last cached parent state of the pipeline. +func (p *Pipeline) parentState() optimistic_sync.State { + return optimistic_sync.State(p.parentStateCache.Load()) +} + +// SetSealed marks the execution result as sealed. +// This will cause the pipeline to eventually transition to the StateComplete state when the parent finishes processing. +func (p *Pipeline) SetSealed() { + // Note: do not use a mutex here to avoid blocking the results forest. + if p.isSealed.CompareAndSwap(false, true) { + p.stateChangedNotifier.Notify() + } +} + +// OnParentStateUpdated updates the pipeline's state based on the provided parent state. +// If the parent state has changed, it will notify the state consumer and trigger a state change notification. +func (p *Pipeline) OnParentStateUpdated(parentState optimistic_sync.State) { + oldState := p.parentStateCache.Load() + if p.parentStateCache.CompareAndSwap(oldState, int32(parentState)) { + p.stateChangedNotifier.Notify() + } +} + +// Abandon marks the pipeline as abandoned +// This will cause the pipeline to eventually transition to the Abandoned state and halt processing +func (p *Pipeline) Abandon() { + if p.isAbandoned.CompareAndSwap(false, true) { + p.stateChangedNotifier.Notify() + } +} + +// performDownload performs the processing step of the pipeline by downloading and indexing data. +// It uses an atomic flag to indicate whether the operation has been completed successfully which +// informs the state machine that eventually it can transition to the next state. +// Expected Errors: +// - context.Canceled: when the context is canceled +// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +func (p *Pipeline) performDownload(ctx context.Context) error { + if err := p.core.Download(ctx); err != nil { + return fmt.Errorf("could not perform download: %w", err) + } + if err := p.core.Index(); err != nil { + return fmt.Errorf("could not perform indexing: %w", err) + } + if p.isIndexed.CompareAndSwap(false, true) { + p.stateChangedNotifier.Notify() + } + return nil +} + +// transitionTo transitions the pipeline to the given state and broadcasts +// the state change to children pipelines. +// +// Expected Errors: +// - ErrInvalidTransition: when the transition is invalid +// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +func (p *Pipeline) transitionTo(newState optimistic_sync.State) error { + hasChange, err := p.setState(newState) + if err != nil { + return err + } + + if hasChange { + // send notification for all state changes. we require that implementations of [PipelineStateConsumer] + // are non-blocking and consume the state updates without noteworthy delay. + p.stateConsumer.OnStateUpdated(newState) + p.stateChangedNotifier.Notify() + } + + return nil +} + +// setState sets the state of the pipeline and logs the transition. +// Returns true if the state was changed, false otherwise. +// +// Expected Errors: +// - ErrInvalidTransition: when the state transition is invalid +// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +func (p *Pipeline) setState(newState optimistic_sync.State) (bool, error) { + currentState := p.GetState() + + // transitioning to the same state is a no-op + if currentState == newState { + return false, nil + } + + if err := p.validateTransition(currentState, newState); err != nil { + return false, fmt.Errorf("failed to transition from %s to %s: %w", currentState, newState, err) + } + + if !p.state.CompareAndSwap(int32(currentState), int32(newState)) { + // Note: this should never happen since state is only updated within the Run goroutine. + return false, fmt.Errorf("failed to transition from %s to %s", currentState, newState) + } + + p.log.Debug(). + Str("old_state", currentState.String()). + Str("new_state", newState.String()). + Msg("pipeline state transition") + + return true, nil +} + +// validateTransition validates the transition from the current state to the new state. +// +// Expected Errors: +// - ErrInvalidTransition: when the transition is invalid +// - All other errors are potential indicators of bugs or corrupted internal state (continuation impossible) +func (p *Pipeline) validateTransition(currentState optimistic_sync.State, newState optimistic_sync.State) error { + switch newState { + case optimistic_sync.StateProcessing: + if currentState == optimistic_sync.StatePending { + return nil + } + case optimistic_sync.StateWaitingPersist: + if currentState == optimistic_sync.StateProcessing { + return nil + } + case optimistic_sync.StateComplete: + if currentState == optimistic_sync.StateWaitingPersist { + return nil + } + case optimistic_sync.StateAbandoned: + // Note: it does not make sense to transition to abandoned from persisting or completed since to be in either state: + // 1. the parent must be completed + // 2. the pipeline's result must be sealed + // At that point, there are no conditions that would cause the pipeline be abandoned + switch currentState { + case optimistic_sync.StatePending, optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist: + return nil + } + + default: + return fmt.Errorf("invalid transition to state: %s", newState) + } + + return optimistic_sync.ErrInvalidTransition +} diff --git a/module/executiondatasync/optimistic_sync/pipeline_functional_test.go b/module/executiondatasync/optimistic_sync/pipeline/pipeline_functional_test.go similarity index 82% rename from module/executiondatasync/optimistic_sync/pipeline_functional_test.go rename to module/executiondatasync/optimistic_sync/pipeline/pipeline_functional_test.go index be23d5b99c3..c7da63bec2f 100644 --- a/module/executiondatasync/optimistic_sync/pipeline_functional_test.go +++ b/module/executiondatasync/optimistic_sync/pipeline/pipeline_functional_test.go @@ -1,4 +1,4 @@ -package optimistic_sync +package pipeline import ( "context" @@ -19,6 +19,7 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync" "github.com/onflow/flow-go/module/metrics" reqestermock "github.com/onflow/flow-go/module/state_synchronization/requester/mock" "github.com/onflow/flow-go/storage" @@ -53,7 +54,7 @@ type PipelineFunctionalSuite struct { headers *store.Headers results *store.ExecutionResults persistentLatestSealedResult *store.LatestPersistedSealedResult - core *CoreImpl + core *Core block *flow.Block executionResult *flow.ExecutionResult metrics module.CacheMetrics @@ -175,7 +176,7 @@ func (p *PipelineFunctionalSuite) SetupTest() { p.txResultErrMsgsRequestTimeout = DefaultTxResultErrMsgsRequestTimeout p.config = PipelineConfig{ - parentState: StateWaitingPersist, + parentState: optimistic_sync.StateWaitingPersist, } // generate expected data based on the fixtures @@ -237,7 +238,7 @@ func (p *PipelineFunctionalSuite) TestPipelineCompletesSuccessfully() { p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(p.expectedExecutionData, nil).Once() p.txResultErrMsgsRequester.On("Request", mock.Anything).Return(p.expectedTxResultErrMsgs, nil).Once() - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { // Check for errors in a separate goroutine go func() { err := <-errChan @@ -246,13 +247,13 @@ func (p *PipelineFunctionalSuite) TestPipelineCompletesSuccessfully() { } }() - pipeline.OnParentStateUpdated(StateComplete) + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) - waitForStateUpdates(p.T(), updateChan, errChan, StateProcessing, StateWaitingPersist) + waitForStateUpdates(p.T(), updateChan, errChan, optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist) pipeline.SetSealed() - waitForStateUpdates(p.T(), updateChan, errChan, StateComplete) + waitForStateUpdates(p.T(), updateChan, errChan, optimistic_sync.StateComplete) actualEvents, err := p.persistentEvents.ByBlockID(p.block.ID()) p.Require().NoError(err) @@ -301,11 +302,11 @@ func (p *PipelineFunctionalSuite) TestPipelineDownloadError() { p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(nil, expectedErr).Once() p.txResultErrMsgsRequester.On("Request", mock.Anything).Return(p.expectedTxResultErrMsgs, nil).Once() - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { - pipeline.OnParentStateUpdated(StateComplete) + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) waitForError(p.T(), errChan, expectedErr) - p.Assert().Equal(StateProcessing, pipeline.GetState()) + p.Assert().Equal(optimistic_sync.StateProcessing, pipeline.GetState()) }, p.config) }) @@ -315,11 +316,11 @@ func (p *PipelineFunctionalSuite) TestPipelineDownloadError() { p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(p.expectedExecutionData, nil).Once() p.txResultErrMsgsRequester.On("Request", mock.Anything).Return(nil, expectedErr).Once() - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { - pipeline.OnParentStateUpdated(StateComplete) + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) waitForError(p.T(), errChan, expectedErr) - p.Assert().Equal(StateProcessing, pipeline.GetState()) + p.Assert().Equal(optimistic_sync.StateProcessing, pipeline.GetState()) }, p.config) }) } @@ -341,14 +342,14 @@ func (p *PipelineFunctionalSuite) TestPipelineIndexingError() { expectedIndexingError := fmt.Errorf("could not perform indexing: failed to index execution data: unexpected block execution data: expected block_id=%s, actual block_id=%s", p.block.ID().String(), invalidBlockID.String()) - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { - pipeline.OnParentStateUpdated(StateComplete) + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) waitForErrorWithCustomCheckers(p.T(), errChan, func(err error) { p.Require().Error(err) p.Assert().Equal(expectedIndexingError.Error(), err.Error()) }) - p.Assert().Equal(StateProcessing, pipeline.GetState()) + p.Assert().Equal(optimistic_sync.StateProcessing, pipeline.GetState()) }, p.config) } @@ -366,15 +367,15 @@ func (p *PipelineFunctionalSuite) TestPipelinePersistingError() { p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(p.expectedExecutionData, nil).Once() p.txResultErrMsgsRequester.On("Request", mock.Anything).Return(p.expectedTxResultErrMsgs, nil).Once() - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { - pipeline.OnParentStateUpdated(StateComplete) + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) - waitForStateUpdates(p.T(), updateChan, errChan, StateProcessing, StateWaitingPersist) + waitForStateUpdates(p.T(), updateChan, errChan, optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist) pipeline.SetSealed() waitForError(p.T(), errChan, expectedError) - p.Assert().Equal(StateWaitingPersist, pipeline.GetState()) + p.Assert().Equal(optimistic_sync.StateWaitingPersist, pipeline.GetState()) }, p.config) } @@ -382,7 +383,7 @@ func (p *PipelineFunctionalSuite) TestPipelinePersistingError() { // request of execution data. It ensures that cancellation is handled properly when triggered // while execution data is being downloaded. func (p *PipelineFunctionalSuite) TestMainCtxCancellationDuringRequestingExecutionData() { - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { p.execDataRequester. On("RequestExecutionData", mock.Anything). Return(func(ctx context.Context) (*execution_data.BlockExecutionData, error) { @@ -395,13 +396,13 @@ func (p *PipelineFunctionalSuite) TestMainCtxCancellationDuringRequestingExecuti // This call marked as `Maybe()` because it may not be called depending on timing. p.txResultErrMsgsRequester.On("Request", mock.Anything).Return([]flow.TransactionResultErrorMessage{}, nil).Maybe() - pipeline.OnParentStateUpdated(StateComplete) + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) - waitForStateUpdates(p.T(), updateChan, errChan, StateProcessing) + waitForStateUpdates(p.T(), updateChan, errChan, optimistic_sync.StateProcessing) waitForError(p.T(), errChan, context.Canceled) - p.Assert().Equal(StateProcessing, pipeline.GetState()) - }, PipelineConfig{parentState: StatePending}) + p.Assert().Equal(optimistic_sync.StateProcessing, pipeline.GetState()) + }, PipelineConfig{parentState: optimistic_sync.StatePending}) } // TestMainCtxCancellationDuringRequestingTxResultErrMsgs tests context cancellation during @@ -409,7 +410,7 @@ func (p *PipelineFunctionalSuite) TestMainCtxCancellationDuringRequestingExecuti // is cancelled during this phase, the pipeline handles the cancellation gracefully // and transitions to the correct state. func (p *PipelineFunctionalSuite) TestMainCtxCancellationDuringRequestingTxResultErrMsgs() { - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { // This call marked as `Maybe()` because it may not be called depending on timing. p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(nil, nil).Maybe() @@ -422,13 +423,13 @@ func (p *PipelineFunctionalSuite) TestMainCtxCancellationDuringRequestingTxResul }). Once() - pipeline.OnParentStateUpdated(StateComplete) + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) - waitForStateUpdates(p.T(), updateChan, errChan, StateProcessing) + waitForStateUpdates(p.T(), updateChan, errChan, optimistic_sync.StateProcessing) waitForError(p.T(), errChan, context.Canceled) - p.Assert().Equal(StateProcessing, pipeline.GetState()) - }, PipelineConfig{parentState: StatePending}) + p.Assert().Equal(optimistic_sync.StateProcessing, pipeline.GetState()) + }, PipelineConfig{parentState: optimistic_sync.StatePending}) } // TestMainCtxCancellationDuringWaitingPersist tests the pipeline's behavior when the main context is canceled during StateWaitingPersist. @@ -436,10 +437,10 @@ func (p *PipelineFunctionalSuite) TestMainCtxCancellationDuringWaitingPersist() p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(p.expectedExecutionData, nil).Once() p.txResultErrMsgsRequester.On("Request", mock.Anything).Return(p.expectedTxResultErrMsgs, nil).Once() - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { - pipeline.OnParentStateUpdated(StateComplete) + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { + pipeline.OnParentStateUpdated(optimistic_sync.StateComplete) - waitForStateUpdates(p.T(), updateChan, errChan, StateProcessing, StateWaitingPersist) + waitForStateUpdates(p.T(), updateChan, errChan, optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist) cancel() @@ -447,7 +448,7 @@ func (p *PipelineFunctionalSuite) TestMainCtxCancellationDuringWaitingPersist() waitForError(p.T(), errChan, context.Canceled) - p.Assert().Equal(StateWaitingPersist, pipeline.GetState()) + p.Assert().Equal(optimistic_sync.StateWaitingPersist, pipeline.GetState()) }, p.config) } @@ -461,32 +462,32 @@ func (p *PipelineFunctionalSuite) TestPipelineShutdownOnParentAbandon() { name string config PipelineConfig checkError func(err error) - customSetup func(pipeline Pipeline, updateChan chan State, errChan chan error) + customSetup func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error) }{ { name: "from StatePending", config: PipelineConfig{ - beforePipelineRun: func(pipeline *PipelineImpl) { - pipeline.OnParentStateUpdated(StateAbandoned) + beforePipelineRun: func(pipeline *Pipeline) { + pipeline.OnParentStateUpdated(optimistic_sync.StateAbandoned) }, - parentState: StateAbandoned, + parentState: optimistic_sync.StateAbandoned, }, checkError: assertNoError, - customSetup: func(pipeline Pipeline, updateChan chan State, errChan chan error) {}, + customSetup: func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error) {}, }, { name: "from StateProcessing", config: PipelineConfig{ - beforePipelineRun: func(pipeline *PipelineImpl) { + beforePipelineRun: func(pipeline *Pipeline) { p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(func(ctx context.Context) (*execution_data.BlockExecutionData, error) { - pipeline.OnParentStateUpdated(StateAbandoned) // abandon during processing step + pipeline.OnParentStateUpdated(optimistic_sync.StateAbandoned) // abandon during processing step return p.expectedExecutionData, nil }).Once() // this method may not be called depending on how quickly the RequestExecutionData // mock returns. p.txResultErrMsgsRequester.On("Request", mock.Anything).Return(p.expectedTxResultErrMsgs, nil).Maybe() }, - parentState: StateWaitingPersist, + parentState: optimistic_sync.StateWaitingPersist, }, checkError: func(err error) { // depending on the timing, the error may be during or after the indexing step. @@ -496,23 +497,23 @@ func (p *PipelineFunctionalSuite) TestPipelineShutdownOnParentAbandon() { p.Require().NoError(err) } }, - customSetup: func(pipeline Pipeline, updateChan chan State, errChan chan error) { - synctestWaitForStateUpdates(p.T(), updateChan, StateProcessing) + customSetup: func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error) { + synctestWaitForStateUpdates(p.T(), updateChan, optimistic_sync.StateProcessing) }, }, { name: "from StateWaitingPersist", config: PipelineConfig{ - beforePipelineRun: func(pipeline *PipelineImpl) { + beforePipelineRun: func(pipeline *Pipeline) { p.execDataRequester.On("RequestExecutionData", mock.Anything).Return(p.expectedExecutionData, nil).Once() p.txResultErrMsgsRequester.On("Request", mock.Anything).Return(p.expectedTxResultErrMsgs, nil).Once() }, - parentState: StateWaitingPersist, + parentState: optimistic_sync.StateWaitingPersist, }, checkError: assertNoError, - customSetup: func(pipeline Pipeline, updateChan chan State, errChan chan error) { - synctestWaitForStateUpdates(p.T(), updateChan, StateProcessing, StateWaitingPersist) - pipeline.OnParentStateUpdated(StateAbandoned) + customSetup: func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error) { + synctestWaitForStateUpdates(p.T(), updateChan, optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist) + pipeline.OnParentStateUpdated(optimistic_sync.StateAbandoned) }, }, } @@ -523,13 +524,13 @@ func (p *PipelineFunctionalSuite) TestPipelineShutdownOnParentAbandon() { p.txResultErrMsgsRequester.On("Request", mock.Anything).Unset() synctest.Test(p.T(), func(t *testing.T) { - p.WithRunningPipeline(func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc) { + p.WithRunningPipeline(func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc) { test.customSetup(pipeline, updateChan, errChan) - synctestWaitForStateUpdates(p.T(), updateChan, StateAbandoned) + synctestWaitForStateUpdates(p.T(), updateChan, optimistic_sync.StateAbandoned) test.checkError(<-errChan) - p.Assert().Equal(StateAbandoned, pipeline.GetState()) + p.Assert().Equal(optimistic_sync.StateAbandoned, pipeline.GetState()) p.Assert().Nil(p.core.workingData) }, test.config) }) @@ -538,20 +539,20 @@ func (p *PipelineFunctionalSuite) TestPipelineShutdownOnParentAbandon() { } type PipelineConfig struct { - beforePipelineRun func(pipeline *PipelineImpl) - parentState State + beforePipelineRun func(pipeline *Pipeline) + parentState optimistic_sync.State } // WithRunningPipeline is a test helper that initializes and starts a pipeline instance. // It manages the context and channels needed to run the pipeline and invokes the testFunc // with access to the pipeline, update channel, error channel, and cancel function. func (p *PipelineFunctionalSuite) WithRunningPipeline( - testFunc func(pipeline Pipeline, updateChan chan State, errChan chan error, cancel context.CancelFunc), + testFunc func(pipeline optimistic_sync.Pipeline, updateChan chan optimistic_sync.State, errChan chan error, cancel context.CancelFunc), pipelineConfig PipelineConfig, ) { var err error - p.core, err = NewCoreImpl( + p.core, err = NewCore( p.logger, p.executionResult, p.block, diff --git a/module/executiondatasync/optimistic_sync/pipeline_test.go b/module/executiondatasync/optimistic_sync/pipeline/pipeline_test.go similarity index 63% rename from module/executiondatasync/optimistic_sync/pipeline_test.go rename to module/executiondatasync/optimistic_sync/pipeline/pipeline_test.go index 123ff2e4498..7d14877d9a1 100644 --- a/module/executiondatasync/optimistic_sync/pipeline_test.go +++ b/module/executiondatasync/optimistic_sync/pipeline/pipeline_test.go @@ -1,4 +1,4 @@ -package optimistic_sync +package pipeline import ( "context" @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync" osmock "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync/mock" "github.com/onflow/flow-go/utils/unittest" ) @@ -22,27 +23,27 @@ func TestPipelineStateTransitions(t *testing.T) { pipeline, mockCore, updateChan, parent := createPipeline(t) pipeline.SetSealed() - parent.UpdateState(StateComplete, pipeline) + parent.UpdateState(optimistic_sync.StateComplete, pipeline) mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Return(nil) mockCore.On("Persist").Return(nil) - assert.Equal(t, StatePending, pipeline.GetState(), "Pipeline should start in Pending state") + assert.Equal(t, optimistic_sync.StatePending, pipeline.GetState(), "Pipeline should start in Pending state") go func() { err := pipeline.Run(context.Background(), mockCore, parent.GetState()) require.NoError(t, err) }() - for _, expected := range []State{StateProcessing, StateWaitingPersist, StateComplete} { + for _, expected := range []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist, optimistic_sync.StateComplete} { synctest.Wait() assertUpdate(t, updateChan, expected) } // wait for Run goroutine to finish synctest.Wait() - assertNoUpdate(t, pipeline, updateChan, StateComplete) + assertNoUpdate(t, pipeline, updateChan, optimistic_sync.StateComplete) }) } @@ -52,7 +53,7 @@ func TestPipelineParentDependentTransitions(t *testing.T) { synctest.Test(t, func(t *testing.T) { pipeline, mockCore, updateChan, parent := createPipeline(t) - assert.Equal(t, StatePending, pipeline.GetState(), "Pipeline should start in Pending state") + assert.Equal(t, optimistic_sync.StatePending, pipeline.GetState(), "Pipeline should start in Pending state") go func() { err := pipeline.Run(context.Background(), mockCore, parent.GetState()) @@ -60,35 +61,35 @@ func TestPipelineParentDependentTransitions(t *testing.T) { }() // 1. Initial update - parent in Ready state - parent.UpdateState(StatePending, pipeline) + parent.UpdateState(optimistic_sync.StatePending, pipeline) // Check that pipeline remains in Ready state synctest.Wait() - assertNoUpdate(t, pipeline, updateChan, StatePending) + assertNoUpdate(t, pipeline, updateChan, optimistic_sync.StatePending) // 2. Update parent to downloading - parent.UpdateState(StateProcessing, pipeline) + parent.UpdateState(optimistic_sync.StateProcessing, pipeline) // Pipeline should now call Download and Index within the processing state, then progress to // WaitingPersist and stop mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Return(nil) - for _, expected := range []State{StateProcessing, StateWaitingPersist} { + for _, expected := range []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist} { synctest.Wait() assertUpdate(t, updateChan, expected) } - assert.Equal(t, StateWaitingPersist, pipeline.GetState(), "Pipeline should be in StateWaitingPersist state") + assert.Equal(t, optimistic_sync.StateWaitingPersist, pipeline.GetState(), "Pipeline should be in StateWaitingPersist state") // pipeline should remain in WaitingPersist state synctest.Wait() - assertNoUpdate(t, pipeline, updateChan, StateWaitingPersist) + assertNoUpdate(t, pipeline, updateChan, optimistic_sync.StateWaitingPersist) // 3. Update parent to complete - should allow persisting when sealed - parent.UpdateState(StateComplete, pipeline) + parent.UpdateState(optimistic_sync.StateComplete, pipeline) // this alone should not allow the pipeline to progress to any other state synctest.Wait() - assertNoUpdate(t, pipeline, updateChan, StateWaitingPersist) + assertNoUpdate(t, pipeline, updateChan, optimistic_sync.StateWaitingPersist) // 4. Mark the execution result as sealed, this should allow the pipeline to progress to Complete state pipeline.SetSealed() @@ -96,11 +97,11 @@ func TestPipelineParentDependentTransitions(t *testing.T) { // Wait for pipeline to complete synctest.Wait() - assertUpdate(t, updateChan, StateComplete) + assertUpdate(t, updateChan, optimistic_sync.StateComplete) // Run should complete without error synctest.Wait() - assertNoUpdate(t, pipeline, updateChan, StateComplete) + assertNoUpdate(t, pipeline, updateChan, optimistic_sync.StateComplete) }) } @@ -122,24 +123,24 @@ func TestAbandoned(t *testing.T) { // first state must be abandoned synctest.Wait() - assertUpdate(t, updateChan, StateAbandoned) + assertUpdate(t, updateChan, optimistic_sync.StateAbandoned) // wait for Run goroutine to finish synctest.Wait() - assertNoUpdate(t, pipeline, updateChan, StateAbandoned) + assertNoUpdate(t, pipeline, updateChan, optimistic_sync.StateAbandoned) }) }) // Test cases abandoning during different stages of processing testCases := []struct { name string - setupMock func(*PipelineImpl, *mockStateProvider, *osmock.Core) - onStateFns map[State]func(*PipelineImpl, *mockStateProvider) - expectedStates []State + setupMock func(*Pipeline, *mockStateProvider, *osmock.Core) + onStateFns map[optimistic_sync.State]func(*Pipeline, *mockStateProvider) + expectedStates []optimistic_sync.State }{ { name: "Abandon during download", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) { mockCore. On("Download", mock.Anything). Return(func(ctx context.Context) error { @@ -148,68 +149,68 @@ func TestAbandoned(t *testing.T) { return ctx.Err() }) }, - expectedStates: []State{StateProcessing, StateAbandoned}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateAbandoned}, }, { name: "Parent abandoned during download", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) { mockCore. On("Download", mock.Anything). Return(func(ctx context.Context) error { - parent.UpdateState(StateAbandoned, pipeline) + parent.UpdateState(optimistic_sync.StateAbandoned, pipeline) <-ctx.Done() // abandon should cause context to be canceled return ctx.Err() }) }, - expectedStates: []State{StateProcessing, StateAbandoned}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateAbandoned}, }, { name: "Abandon during index", // Note: indexing will complete, and the pipeline will transition to waiting persist - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) { mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Run(func(args mock.Arguments) { pipeline.Abandon() }).Return(nil) }, - expectedStates: []State{StateProcessing, StateAbandoned}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateAbandoned}, }, { name: "Parent abandoned during index", // Note: indexing will complete, and the pipeline will transition to waiting persist - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) { mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Run(func(args mock.Arguments) { - parent.UpdateState(StateAbandoned, pipeline) + parent.UpdateState(optimistic_sync.StateAbandoned, pipeline) }).Return(nil) }, - expectedStates: []State{StateProcessing, StateAbandoned}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateAbandoned}, }, { name: "Abandon during waiting to persist", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) { mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Return(nil) }, - onStateFns: map[State]func(*PipelineImpl, *mockStateProvider){ - StateWaitingPersist: func(pipeline *PipelineImpl, parent *mockStateProvider) { + onStateFns: map[optimistic_sync.State]func(*Pipeline, *mockStateProvider){ + optimistic_sync.StateWaitingPersist: func(pipeline *Pipeline, parent *mockStateProvider) { pipeline.Abandon() }, }, - expectedStates: []State{StateProcessing, StateWaitingPersist, StateAbandoned}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist, optimistic_sync.StateAbandoned}, }, { name: "Parent abandoned during waiting to persist", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) { mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Return(nil) }, - onStateFns: map[State]func(*PipelineImpl, *mockStateProvider){ - StateWaitingPersist: func(pipeline *PipelineImpl, parent *mockStateProvider) { - parent.UpdateState(StateAbandoned, pipeline) + onStateFns: map[optimistic_sync.State]func(*Pipeline, *mockStateProvider){ + optimistic_sync.StateWaitingPersist: func(pipeline *Pipeline, parent *mockStateProvider) { + parent.UpdateState(optimistic_sync.StateAbandoned, pipeline) }, }, - expectedStates: []State{StateProcessing, StateWaitingPersist, StateAbandoned}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist, optimistic_sync.StateAbandoned}, }, // Note: it does not make sense to abandon during persist, since it will only be run when: // 1. the parent is already complete @@ -231,7 +232,7 @@ func TestAbandoned(t *testing.T) { }() // Send parent update to start processing - parent.UpdateState(StateProcessing, pipeline) + parent.UpdateState(optimistic_sync.StateProcessing, pipeline) for _, expected := range tc.expectedStates { synctest.Wait() @@ -244,7 +245,7 @@ func TestAbandoned(t *testing.T) { // wait for Run goroutine to finish synctest.Wait() - assertNoUpdate(t, pipeline, updateChan, StateAbandoned) + assertNoUpdate(t, pipeline, updateChan, optimistic_sync.StateAbandoned) }) }) } @@ -255,11 +256,11 @@ func TestPipelineContextCancellation(t *testing.T) { // Test cases for different stages of processing testCases := []struct { name string - setupMock func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) context.Context + setupMock func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) context.Context }{ { name: "Cancel before download starts", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) context.Context { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) context.Context { ctx, cancel := context.WithCancel(context.Background()) cancel() // no Core methods called @@ -268,7 +269,7 @@ func TestPipelineContextCancellation(t *testing.T) { }, { name: "Cancel during download", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) context.Context { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) context.Context { ctx, cancel := context.WithCancel(context.Background()) mockCore.On("Download", mock.Anything).Run(func(args mock.Arguments) { cancel() @@ -282,7 +283,7 @@ func TestPipelineContextCancellation(t *testing.T) { }, { name: "Cancel between steps", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core) context.Context { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core) context.Context { ctx, cancel := context.WithCancel(context.Background()) mockCore.On("Download", mock.Anything).Return(nil) @@ -300,7 +301,7 @@ func TestPipelineContextCancellation(t *testing.T) { synctest.Test(t, func(t *testing.T) { pipeline, mockCore, _, parent := createPipeline(t) - parent.UpdateState(StateComplete, pipeline) + parent.UpdateState(optimistic_sync.StateComplete, pipeline) pipeline.SetSealed() ctx := tc.setupMock(pipeline, parent, mockCore) @@ -323,39 +324,39 @@ func TestPipelineErrorHandling(t *testing.T) { // Test cases for different stages of processing testCases := []struct { name string - setupMock func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core, expectedErr error) + setupMock func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core, expectedErr error) expectedErr error - expectedStates []State + expectedStates []optimistic_sync.State }{ { name: "Download Error", - setupMock: func(pipeline *PipelineImpl, _ *mockStateProvider, mockCore *osmock.Core, expectedErr error) { + setupMock: func(pipeline *Pipeline, _ *mockStateProvider, mockCore *osmock.Core, expectedErr error) { mockCore.On("Download", mock.Anything).Return(expectedErr) }, expectedErr: errors.New("download error"), - expectedStates: []State{StateProcessing}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing}, }, { name: "Index Error", - setupMock: func(pipeline *PipelineImpl, _ *mockStateProvider, mockCore *osmock.Core, expectedErr error) { + setupMock: func(pipeline *Pipeline, _ *mockStateProvider, mockCore *osmock.Core, expectedErr error) { mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Return(expectedErr) }, expectedErr: errors.New("index error"), - expectedStates: []State{StateProcessing}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing}, }, { name: "Persist Error", - setupMock: func(pipeline *PipelineImpl, parent *mockStateProvider, mockCore *osmock.Core, expectedErr error) { + setupMock: func(pipeline *Pipeline, parent *mockStateProvider, mockCore *osmock.Core, expectedErr error) { mockCore.On("Download", mock.Anything).Return(nil) mockCore.On("Index").Run(func(args mock.Arguments) { - parent.UpdateState(StateComplete, pipeline) + parent.UpdateState(optimistic_sync.StateComplete, pipeline) pipeline.SetSealed() }).Return(nil) mockCore.On("Persist").Return(expectedErr) }, expectedErr: errors.New("persist error"), - expectedStates: []State{StateProcessing, StateWaitingPersist}, + expectedStates: []optimistic_sync.State{optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist}, }, } @@ -372,7 +373,7 @@ func TestPipelineErrorHandling(t *testing.T) { }() // Send parent update to trigger processing - parent.UpdateState(StateProcessing, pipeline) + parent.UpdateState(optimistic_sync.StateProcessing, pipeline) for _, expected := range tc.expectedStates { synctest.Wait() @@ -399,15 +400,15 @@ func TestSetSealed(t *testing.T) { // TestValidateTransition verifies that the pipeline correctly validates state transitions. func TestValidateTransition(t *testing.T) { - allStates := []State{StatePending, StateProcessing, StateWaitingPersist, StateComplete, StateAbandoned} + allStates := []optimistic_sync.State{optimistic_sync.StatePending, optimistic_sync.StateProcessing, optimistic_sync.StateWaitingPersist, optimistic_sync.StateComplete, optimistic_sync.StateAbandoned} // these are all of the valid transitions from a state to another state - validTransitions := map[State]map[State]bool{ - StatePending: {StateProcessing: true, StateAbandoned: true}, - StateProcessing: {StateWaitingPersist: true, StateAbandoned: true}, - StateWaitingPersist: {StateComplete: true, StateAbandoned: true}, - StateComplete: {}, - StateAbandoned: {}, + validTransitions := map[optimistic_sync.State]map[optimistic_sync.State]bool{ + optimistic_sync.StatePending: {optimistic_sync.StateProcessing: true, optimistic_sync.StateAbandoned: true}, + optimistic_sync.StateProcessing: {optimistic_sync.StateWaitingPersist: true, optimistic_sync.StateAbandoned: true}, + optimistic_sync.StateWaitingPersist: {optimistic_sync.StateComplete: true, optimistic_sync.StateAbandoned: true}, + optimistic_sync.StateComplete: {}, + optimistic_sync.StateAbandoned: {}, } // iterate through all possible transitions, and validate that the valid transitions succeed, and the invalid transitions fail @@ -425,12 +426,12 @@ func TestValidateTransition(t *testing.T) { continue } - assert.ErrorIs(t, err, ErrInvalidTransition) + assert.ErrorIs(t, err, optimistic_sync.ErrInvalidTransition) } } } -func assertNoUpdate(t *testing.T, pipeline Pipeline, updateChan <-chan State, existingState State) { +func assertNoUpdate(t *testing.T, pipeline *Pipeline, updateChan <-chan optimistic_sync.State, existingState optimistic_sync.State) { select { case update := <-updateChan: t.Errorf("Pipeline should remain in %s state, but transitioned to %s", existingState, update) @@ -439,7 +440,7 @@ func assertNoUpdate(t *testing.T, pipeline Pipeline, updateChan <-chan State, ex } } -func assertUpdate(t *testing.T, updateChan <-chan State, expected State) { +func assertUpdate(t *testing.T, updateChan <-chan optimistic_sync.State, expected optimistic_sync.State) { select { case update := <-updateChan: assert.Equal(t, expected, update, "Pipeline should transition to %s state", expected) diff --git a/module/executiondatasync/optimistic_sync/pipeline_test_utils.go b/module/executiondatasync/optimistic_sync/pipeline/pipeline_test_utils.go similarity index 81% rename from module/executiondatasync/optimistic_sync/pipeline_test_utils.go rename to module/executiondatasync/optimistic_sync/pipeline/pipeline_test_utils.go index 31084099361..95f68283742 100644 --- a/module/executiondatasync/optimistic_sync/pipeline_test_utils.go +++ b/module/executiondatasync/optimistic_sync/pipeline/pipeline_test_utils.go @@ -1,4 +1,4 @@ -package optimistic_sync +package pipeline import ( "testing" @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync" osmock "github.com/onflow/flow-go/module/executiondatasync/optimistic_sync/mock" "github.com/onflow/flow-go/utils/unittest" ) @@ -16,52 +17,52 @@ import ( // mockStateProvider is a mock implementation of a parent state provider. // It tracks the current state and notifies the pipeline when the state changes. type mockStateProvider struct { - state State + state optimistic_sync.State } -var _ PipelineStateProvider = (*mockStateProvider)(nil) +var _ optimistic_sync.PipelineStateProvider = (*mockStateProvider)(nil) // NewMockStateProvider initializes a mockStateProvider with the default state StatePending. func NewMockStateProvider() *mockStateProvider { return &mockStateProvider{ - state: StatePending, + state: optimistic_sync.StatePending, } } // UpdateState sets the internal state and triggers a pipeline update. -func (m *mockStateProvider) UpdateState(state State, pipeline *PipelineImpl) { +func (m *mockStateProvider) UpdateState(state optimistic_sync.State, pipeline *Pipeline) { m.state = state pipeline.OnParentStateUpdated(state) } // GetState returns the current internal state. -func (m *mockStateProvider) GetState() State { +func (m *mockStateProvider) GetState() optimistic_sync.State { return m.state } // mockStateConsumer is a mock implementation used in tests to receive state updates from the pipeline. // It exposes a buffered channel to capture the state transitions. type mockStateConsumer struct { - updateChan chan State + updateChan chan optimistic_sync.State } -var _ PipelineStateConsumer = (*mockStateConsumer)(nil) +var _ optimistic_sync.PipelineStateConsumer = (*mockStateConsumer)(nil) // NewMockStateConsumer creates a new instance of mockStateConsumer with a buffered channel. func NewMockStateConsumer() *mockStateConsumer { return &mockStateConsumer{ - updateChan: make(chan State, 10), + updateChan: make(chan optimistic_sync.State, 10), } } -func (m *mockStateConsumer) OnStateUpdated(state State) { +func (m *mockStateConsumer) OnStateUpdated(state optimistic_sync.State) { m.updateChan <- state } // waitForStateUpdates waits for a sequence of state updates to occur or timeout after 500ms. // updates must be received in the correct order or the test will fail. -func waitForStateUpdates(t *testing.T, updateChan <-chan State, errChan <-chan error, expectedStates ...State) { +func waitForStateUpdates(t *testing.T, updateChan <-chan optimistic_sync.State, errChan <-chan error, expectedStates ...optimistic_sync.State) { done := make(chan struct{}) unittest.RequireReturnsBefore(t, func() { for _, expected := range expectedStates { @@ -108,7 +109,7 @@ func waitForError(t *testing.T, errChan <-chan error, expectedErr error) { // createPipeline initializes and returns a pipeline instance with its mock dependencies. // It returns the pipeline, the mocked core, a state update channel, and the parent state provider. -func createPipeline(t *testing.T) (*PipelineImpl, *osmock.Core, <-chan State, *mockStateProvider) { +func createPipeline(t *testing.T) (*Pipeline, *osmock.Core, <-chan optimistic_sync.State, *mockStateProvider) { mockCore := osmock.NewCore(t) parent := NewMockStateProvider() stateReceiver := NewMockStateConsumer() @@ -121,7 +122,7 @@ func createPipeline(t *testing.T) (*PipelineImpl, *osmock.Core, <-chan State, *m // synctestWaitForStateUpdates waits for a sequence of state updates to occur using synctest.Wait. // updates must be received in the correct order or the test will fail. // TODO: refactor all tests to use the synctest approach. -func synctestWaitForStateUpdates(t *testing.T, updateChan <-chan State, expectedStates ...State) { +func synctestWaitForStateUpdates(t *testing.T, updateChan <-chan optimistic_sync.State, expectedStates ...optimistic_sync.State) { for _, expected := range expectedStates { synctest.Wait() update, ok := <-updateChan diff --git a/module/executiondatasync/provider/provider.go b/module/executiondatasync/provider/provider.go index 72551826634..9ceeac83c6e 100644 --- a/module/executiondatasync/provider/provider.go +++ b/module/executiondatasync/provider/provider.go @@ -160,8 +160,6 @@ func (p *ExecutionDataProvider) provide(ctx context.Context, blockHeight uint64, chunkDataIDs := make([]cid.Cid, len(executionData.ChunkExecutionDatas)) for i, chunkExecutionData := range executionData.ChunkExecutionDatas { - i := i - chunkExecutionData := chunkExecutionData g.Go(func() error { logger.Debug().Int("chunk_index", i).Msg("adding chunk execution data") @@ -305,7 +303,7 @@ func (p *ExecutionDataCIDProvider) addChunkExecutionData( } // addBlobs serializes the given object, splits the serialized data into blobs, and sends them to the given channel. -func (p *ExecutionDataCIDProvider) addBlobs(v interface{}, blobCh chan<- blobs.Blob) ([]cid.Cid, error) { +func (p *ExecutionDataCIDProvider) addBlobs(v any, blobCh chan<- blobs.Blob) ([]cid.Cid, error) { bcw := blobs.NewBlobChannelWriter(blobCh, p.maxBlobSize) defer bcw.Close() diff --git a/module/executiondatasync/provider/provider_test.go b/module/executiondatasync/provider/provider_test.go index 32b0944c6c3..7dea1a20772 100644 --- a/module/executiondatasync/provider/provider_test.go +++ b/module/executiondatasync/provider/provider_test.go @@ -37,7 +37,7 @@ const ( var ( // canonicalExecutionDataID is the execution data ID of the canonical execution data. - canonicalExecutionDataID = flow.MustHexStringToIdentifier("6796622b06907cc0894260c175fdec8960fe99c167084f901d238db22a676de3") + canonicalExecutionDataID = flow.MustHexStringToIdentifier("15fb366a043645f201587047a52a965f42013e202fb686cbe1d595554b1d2126") ) func getDatastore() datastore.Batching { diff --git a/module/executiondatasync/testutil/fixtures.go b/module/executiondatasync/testutil/fixtures.go index 88ff99a0f2c..05e955a07f1 100644 --- a/module/executiondatasync/testutil/fixtures.go +++ b/module/executiondatasync/testutil/fixtures.go @@ -24,6 +24,8 @@ type TestFixture struct { ExecutionResult *flow.ExecutionResult ExecutionData *execution_data.BlockExecutionData TxErrorMessages []flow.TransactionResultErrorMessage + Guarantees []*flow.CollectionGuarantee + Index *flow.Index ExpectedEvents []flow.Event ExpectedResults []flow.LightTransactionResult @@ -39,12 +41,16 @@ func newTestFixture( execData *execution_data.BlockExecutionData, txErrMsgs []flow.TransactionResultErrorMessage, scheduledTransactionIDs []uint64, + guarantees []*flow.CollectionGuarantee, + index *flow.Index, ) *TestFixture { tf := &TestFixture{ Block: block, ExecutionResult: exeResult, ExecutionData: execData, TxErrorMessages: txErrMsgs, + Guarantees: guarantees, + Index: index, ExpectedScheduledTransactions: make(map[flow.Identifier]uint64), } @@ -118,6 +124,7 @@ func CompleteFixture(t *testing.T, g *fixtures.GeneratorSuite, parentBlock *flow guarantees := make([]*flow.CollectionGuarantee, collectionCount) path := g.LedgerPaths().Fixture() var txErrMsgs []flow.TransactionResultErrorMessage + index := new(flow.Index) txCount := 0 for i, collection := range collections { @@ -131,6 +138,8 @@ func CompleteFixture(t *testing.T, g *fixtures.GeneratorSuite, parentBlock *flow chunkExecutionDatas = append(chunkExecutionDatas, chunkData) guarantees[i] = g.Guarantees().Fixture(fixtures.Guarantee.WithCollectionID(collection.ID())) + index.GuaranteeIDs = append(index.GuaranteeIDs, guarantees[i].ID()) + for txIndex := range chunkExecutionDatas[i].TransactionResults { if txIndex%3 == 0 { chunkExecutionDatas[i].TransactionResults[txIndex].Failed = true @@ -182,6 +191,17 @@ func CompleteFixture(t *testing.T, g *fixtures.GeneratorSuite, parentBlock *flow fixtures.Block.WithPayload(payload), ) + for _, seal := range payload.Seals { + index.SealIDs = append(index.SealIDs, seal.ID()) + } + for _, receipt := range payload.Receipts { + index.ReceiptIDs = append(index.ReceiptIDs, receipt.ID()) + } + for _, result := range payload.Results { + index.ResultIDs = append(index.ResultIDs, result.ID()) + } + index.ProtocolStateID = payload.ProtocolStateID + // generate the block execution data with all data execData := g.BlockExecutionDatas().Fixture( fixtures.BlockExecutionData.WithBlockID(block.ID()), @@ -196,5 +216,5 @@ func CompleteFixture(t *testing.T, g *fixtures.GeneratorSuite, parentBlock *flow fixtures.ExecutionResult.WithExecutionDataID(executionDataID), ) - return newTestFixture(t, block, exeResult, execData, txErrMsgs, scheduledTransactionIDs) + return newTestFixture(t, block, exeResult, execData, txErrMsgs, scheduledTransactionIDs, guarantees, index) } diff --git a/module/executiondatasync/tracker/mock/storage.go b/module/executiondatasync/tracker/mock/storage.go index 5a56946c0d1..811631f20af 100644 --- a/module/executiondatasync/tracker/mock/storage.go +++ b/module/executiondatasync/tracker/mock/storage.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - tracker "github.com/onflow/flow-go/module/executiondatasync/tracker" + "github.com/onflow/flow-go/module/executiondatasync/tracker" mock "github.com/stretchr/testify/mock" ) +// NewStorage creates a new instance of Storage. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStorage(t interface { + mock.TestingT + Cleanup(func()) +}) *Storage { + mock := &Storage{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Storage is an autogenerated mock type for the Storage type type Storage struct { mock.Mock } -// GetFulfilledHeight provides a mock function with no fields -func (_m *Storage) GetFulfilledHeight() (uint64, error) { - ret := _m.Called() +type Storage_Expecter struct { + mock *mock.Mock +} + +func (_m *Storage) EXPECT() *Storage_Expecter { + return &Storage_Expecter{mock: &_m.Mock} +} + +// GetFulfilledHeight provides a mock function for the type Storage +func (_mock *Storage) GetFulfilledHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetFulfilledHeight") @@ -22,27 +46,52 @@ func (_m *Storage) GetFulfilledHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetPrunedHeight provides a mock function with no fields -func (_m *Storage) GetPrunedHeight() (uint64, error) { - ret := _m.Called() +// Storage_GetFulfilledHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFulfilledHeight' +type Storage_GetFulfilledHeight_Call struct { + *mock.Call +} + +// GetFulfilledHeight is a helper method to define mock.On call +func (_e *Storage_Expecter) GetFulfilledHeight() *Storage_GetFulfilledHeight_Call { + return &Storage_GetFulfilledHeight_Call{Call: _e.mock.On("GetFulfilledHeight")} +} + +func (_c *Storage_GetFulfilledHeight_Call) Run(run func()) *Storage_GetFulfilledHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Storage_GetFulfilledHeight_Call) Return(v uint64, err error) *Storage_GetFulfilledHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Storage_GetFulfilledHeight_Call) RunAndReturn(run func() (uint64, error)) *Storage_GetFulfilledHeight_Call { + _c.Call.Return(run) + return _c +} + +// GetPrunedHeight provides a mock function for the type Storage +func (_mock *Storage) GetPrunedHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetPrunedHeight") @@ -50,88 +99,198 @@ func (_m *Storage) GetPrunedHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// PruneUpToHeight provides a mock function with given fields: height -func (_m *Storage) PruneUpToHeight(height uint64) error { - ret := _m.Called(height) +// Storage_GetPrunedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPrunedHeight' +type Storage_GetPrunedHeight_Call struct { + *mock.Call +} + +// GetPrunedHeight is a helper method to define mock.On call +func (_e *Storage_Expecter) GetPrunedHeight() *Storage_GetPrunedHeight_Call { + return &Storage_GetPrunedHeight_Call{Call: _e.mock.On("GetPrunedHeight")} +} + +func (_c *Storage_GetPrunedHeight_Call) Run(run func()) *Storage_GetPrunedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Storage_GetPrunedHeight_Call) Return(v uint64, err error) *Storage_GetPrunedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Storage_GetPrunedHeight_Call) RunAndReturn(run func() (uint64, error)) *Storage_GetPrunedHeight_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToHeight provides a mock function for the type Storage +func (_mock *Storage) PruneUpToHeight(height uint64) error { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for PruneUpToHeight") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(height) } else { r0 = ret.Error(0) } - return r0 } -// SetFulfilledHeight provides a mock function with given fields: height -func (_m *Storage) SetFulfilledHeight(height uint64) error { - ret := _m.Called(height) +// Storage_PruneUpToHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToHeight' +type Storage_PruneUpToHeight_Call struct { + *mock.Call +} + +// PruneUpToHeight is a helper method to define mock.On call +// - height uint64 +func (_e *Storage_Expecter) PruneUpToHeight(height interface{}) *Storage_PruneUpToHeight_Call { + return &Storage_PruneUpToHeight_Call{Call: _e.mock.On("PruneUpToHeight", height)} +} + +func (_c *Storage_PruneUpToHeight_Call) Run(run func(height uint64)) *Storage_PruneUpToHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Storage_PruneUpToHeight_Call) Return(err error) *Storage_PruneUpToHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Storage_PruneUpToHeight_Call) RunAndReturn(run func(height uint64) error) *Storage_PruneUpToHeight_Call { + _c.Call.Return(run) + return _c +} + +// SetFulfilledHeight provides a mock function for the type Storage +func (_mock *Storage) SetFulfilledHeight(height uint64) error { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for SetFulfilledHeight") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(height) } else { r0 = ret.Error(0) } - return r0 } -// Update provides a mock function with given fields: _a0 -func (_m *Storage) Update(_a0 tracker.UpdateFn) error { - ret := _m.Called(_a0) +// Storage_SetFulfilledHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetFulfilledHeight' +type Storage_SetFulfilledHeight_Call struct { + *mock.Call +} + +// SetFulfilledHeight is a helper method to define mock.On call +// - height uint64 +func (_e *Storage_Expecter) SetFulfilledHeight(height interface{}) *Storage_SetFulfilledHeight_Call { + return &Storage_SetFulfilledHeight_Call{Call: _e.mock.On("SetFulfilledHeight", height)} +} + +func (_c *Storage_SetFulfilledHeight_Call) Run(run func(height uint64)) *Storage_SetFulfilledHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Storage_SetFulfilledHeight_Call) Return(err error) *Storage_SetFulfilledHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Storage_SetFulfilledHeight_Call) RunAndReturn(run func(height uint64) error) *Storage_SetFulfilledHeight_Call { + _c.Call.Return(run) + return _c +} + +// Update provides a mock function for the type Storage +func (_mock *Storage) Update(updateFn tracker.UpdateFn) error { + ret := _mock.Called(updateFn) if len(ret) == 0 { panic("no return value specified for Update") } var r0 error - if rf, ok := ret.Get(0).(func(tracker.UpdateFn) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(tracker.UpdateFn) error); ok { + r0 = returnFunc(updateFn) } else { r0 = ret.Error(0) } - return r0 } -// NewStorage creates a new instance of Storage. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStorage(t interface { - mock.TestingT - Cleanup(func()) -}) *Storage { - mock := &Storage{} - mock.Mock.Test(t) +// Storage_Update_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Update' +type Storage_Update_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Update is a helper method to define mock.On call +// - updateFn tracker.UpdateFn +func (_e *Storage_Expecter) Update(updateFn interface{}) *Storage_Update_Call { + return &Storage_Update_Call{Call: _e.mock.On("Update", updateFn)} +} - return mock +func (_c *Storage_Update_Call) Run(run func(updateFn tracker.UpdateFn)) *Storage_Update_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 tracker.UpdateFn + if args[0] != nil { + arg0 = args[0].(tracker.UpdateFn) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Storage_Update_Call) Return(err error) *Storage_Update_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Storage_Update_Call) RunAndReturn(run func(updateFn tracker.UpdateFn) error) *Storage_Update_Call { + _c.Call.Return(run) + return _c } diff --git a/module/forest/concurrency_helpers.go b/module/forest/concurrency_helpers.go new file mode 100644 index 00000000000..ef091f6a445 --- /dev/null +++ b/module/forest/concurrency_helpers.go @@ -0,0 +1,44 @@ +package forest + +import ( + "sync" +) + +/* ATTENTION: LevelledForest and its derived objects, such as the VertexIterator, are NOT Concurrency Safe. The + * LevelledForest is a low-level library geared for performance. As locking is not needed in some application + * scenarios (most notably the consensus EventHandler, which by design is single-threaded), concurrency handling + * is delegated to the higher-level business logic using the LevelledForest. + * + * Here, we provide helper structs for higher-level business logic, to simplify their concurrency handling. + */ + +// VertexIteratorConcurrencySafe wraps the Vertex Iterator to make it concurrency safe. Effectively, +// the behaviour is like iterating on a SNAPSHOT at the time of iterator construction. +// Under concurrent recalls, the iterator delivers each item once across all concurrent callers. +// Items are delivered in order and `NextVertex` establishes a 'synchronized before' relation as +// defined in the go memory model https://go.dev/ref/mem. +type VertexIteratorConcurrencySafe struct { + unsafeIter VertexIterator + mu sync.RWMutex +} + +func NewVertexIteratorConcurrencySafe(iter VertexIterator) *VertexIteratorConcurrencySafe { + return &VertexIteratorConcurrencySafe{unsafeIter: iter} +} + +// NextVertex returns the next Vertex or nil if there is none. A caller receiving a non-nil value +// are 'synchronized before' (see https://go.dev/ref/mem) the receiver of the subsequent non-nil +// value. NextVertex() delivers each item once, following a fully sequential deterministic order, +// with results being distributed in order across all competing threads. +func (i *VertexIteratorConcurrencySafe) NextVertex() Vertex { + i.mu.Lock() // must acquire write lock here, as wrapped `VertexIterator` changes its internal state + defer i.mu.Unlock() + return i.unsafeIter.NextVertex() +} + +// HasNext returns true if and only if there is a next Vertex +func (i *VertexIteratorConcurrencySafe) HasNext() bool { + i.mu.RLock() + defer i.mu.RUnlock() + return i.unsafeIter.HasNext() +} diff --git a/module/forest/concurrency_helpers_test.go b/module/forest/concurrency_helpers_test.go new file mode 100644 index 00000000000..fb73b7ac1d0 --- /dev/null +++ b/module/forest/concurrency_helpers_test.go @@ -0,0 +1,258 @@ +package forest + +import ( + "fmt" + "math/rand" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" +) + +// Test_SlicePrimitives demonstrates that we can use slices, including `VertexList` +// as concurrency-safe snapshots. +func Test_SlicePrimitives(t *testing.T) { + // Conceptually, we always proceed along the following pattern: + // • We assume there is a LevelledForest instance, protected for concurrent access by higher-level + // business logic (not represented in this test). + // • The higher-level business logic instantiates a `VertexIterator` (not represented in this test) by calling + // `GetChildren` or `GetVerticesAtLevel` for example. Under the hood, the `VertexIterator` receives a `VertexList` + // as it's sole input. The slice `VertexList` golang internally represents as the tripel + // [pointer to array, slice length, slice capacity] (see https://go.dev/blog/slices-intro for details). The slice + // is passed by value, i.e. `VertexIterator` maintains its own copy of these values. + // • Here, we emulate interleaving writes by the forest to the shared slice `VertexList`. + + v := NewVertexMock("v", 3, "C", 2) + vContainer := &vertexContainer{id: unittest.IdentifierFixture(), level: 3, vertex: v} + + t.Run("nil slice", func(t *testing.T) { + // Prepare vertex list that, representing the slice of children held by the + var vertexList VertexList // nil zero value + + // vertex iterator maintains a snapshot of a nil slice + iterator := newVertexIterator(vertexList) + + // Emulating concurrent access, where new data is added by the forest: + // we expect that vertexList was expanded, but the iterator's notion should be unchanged + vertexList = append(vertexList, vContainer) + assert.Nil(t, iterator.data) + assert.Equal(t, len(vertexList), len(iterator.data)+1) + }) + + t.Run("empty slice of zero capacity", func(t *testing.T) { + // Prepare vertex list that, representing the slice of children held by the + var vertexList VertexList = []*vertexContainer{} + + // vertex iterator maintains a snapshot of the non-nil slice, with zero capacity + iterator := newVertexIterator(vertexList) + + // Emulating concurrent access, where new data is added by the forest: + // we expect that vertexList was expanded, but the iterator's notion should be unchanged + vertexList = append(vertexList, vContainer) + assert.NotNil(t, iterator.data) + assert.Zero(t, len(iterator.data)) + assert.Equal(t, len(vertexList), len(iterator.data)+1) + }) + + t.Run("empty slice of with capacity 2 (len = 0, cap = 2)", func(t *testing.T) { + // Prepare vertex list that, representing the slice of children held by the + var vertexList VertexList = make(VertexList, 0, 2) + + // vertex iterator maintains a snapshot of a slice with length zero but capacity 2 + iterator := newVertexIterator(vertexList) + + // Emulating concurrent access, where new data is added by the forest: + // we expect that vertexList was expanded, but the iterator's notion should be unchanged + vertexList = append(vertexList, vContainer) + assert.NotNil(t, iterator.data) + assert.Zero(t, len(iterator.data)) + assert.Equal(t, 2, cap(iterator.data)) + assert.Equal(t, len(vertexList), len(iterator.data)+1) + }) + + t.Run("non-empty slice with larger capacity (len = 1, cap = 2)", func(t *testing.T) { + // Prepare vertex list that, representing the slice of children held by the + var vertexList VertexList = make(VertexList, 1, 2) + _v := NewVertexMock("v", 3, "C", 2) + vertexList[0] = &vertexContainer{id: unittest.IdentifierFixture(), level: 3, vertex: _v} + + // vertex iterator maintains a snapshot of a slice with length 1 but capacity 2 + iterator := newVertexIterator(vertexList) + + // Emulating concurrent access, where new data is added by the forest: + // we expect that vertexList was expanded, but the iterator's notion should be unchanged + vertexList = append(vertexList, vContainer) + assert.NotNil(t, iterator.data) + assert.Equal(t, 1, len(iterator.data)) + assert.Equal(t, 2, cap(iterator.data)) + assert.Equal(t, len(vertexList), len(iterator.data)+1) + }) + + t.Run("fully filled non-empty slice (len = 10, cap = 10)", func(t *testing.T) { + // Prepare vertex list that, representing the slice of children held by the + var vertexList VertexList = make(VertexList, 10) + for i := 0; i < cap(vertexList); i++ { + _v := NewVertexMock(fmt.Sprintf("v%d", i), 3, "C", 2) + vertexList[i] = &vertexContainer{id: unittest.IdentifierFixture(), level: 3, vertex: _v} + } + + // vertex iterator maintains a snapshot of the slice, where it is filled with 10 elements + iterator := newVertexIterator(vertexList) + + // Emulating concurrent access, where new data is added by the forest + vertexList = append(vertexList, vContainer) + + // we expect that vertexList was expanded, but the iterator's notion should be unchanged + assert.NotNil(t, iterator.data) + assert.Equal(t, 10, len(iterator.data)) + assert.Equal(t, 10, cap(iterator.data)) + assert.Equal(t, len(vertexList), len(iterator.data)+1) + }) +} + +// Test_VertexIteratorConcurrencySafe verifies concurrent iteration +// We start with a forest (populated by `populateNewForest`) containing the following vertices: +// +// ↙-- [A] +// ··-[C] ←-- [D] +// +// Then vertices v0, v1, v2, etc are added concurrently here in the test +// +// ↙-- [A] +// ··-[C] ←-- [D] +// ↖-- [v0] +// ↖-- [v1] +// ⋮ +// +// Before each addition, we create a vertex operator. Wile more and more vertices are added +// the constructed VertexIterators are checked to confirm they are unaffected, like they +// are operating on a snapshot taken at the time of their construction. +func Test_VertexIteratorConcurrencySafe(t *testing.T) { + forest := newConcurrencySafeForestWrapper(populateNewForest(t)) + + start := make(chan struct{}) + done1, done2 := make(chan struct{}), make(chan struct{}) + + go func() { // Go Routine 1 + <-start + for i := 0; i < 1000; i++ { + // add additional child vertex of [C] + var v Vertex = NewVertexMock(fmt.Sprintf("v%03d", i), 3, "C", 2) + err := forest.VerifyAndAddVertex(&v) + assert.NoError(t, err) + time.Sleep(500 * time.Microsecond) // sleep 0.5ms -> in total 0.5s + } + close(done1) + }() + + go func() { // Go Routine 2 + <-start + var vertexIteratorCheckers []*vertexIteratorChecker + + for { + select { + case <-done1: + close(done2) + return + default: // fallthrough + } + + // the other thread is concurrently adding [C]. At all times, there should be at least + iteratorChecker := forest.GetChildren(TestVertices["C"].VertexID()) + vertexIteratorCheckers = append(vertexIteratorCheckers, iteratorChecker) + for _, checker := range vertexIteratorCheckers { + checker.Check(t) + } + // sleep randomly up to 2ms, average 1ms, so we create only about half as much + // iterators as new vertices are added. + time.Sleep(time.Duration(rand.Intn(2000)) * time.Microsecond) + } + }() + + // start, and then wait for all go routines to finish. Routine 1 finishes after it added 1000 + // new vertices [v000], [v001], [v999] to the forest. Routine 2 will run until routine 1 has + // finished. While routine 2 is running, it verifies that vertex additions to the forests + // leve the iterators unchanged. + close(start) + + // Wait up to 2 seconds, checking every 100 milliseconds + bothDone := func() bool { + select { + case <-done1: + select { + case <-done2: + return true + default: + return false + } + default: + return false + } + } + assert.Eventually(t, bothDone, 2*time.Second, 100*time.Millisecond, "Condition never became true") + +} + +// For testing only! +type concurrencySafeForestWrapper struct { + forest *LevelledForest + mu sync.RWMutex +} + +func newConcurrencySafeForestWrapper(f *LevelledForest) *concurrencySafeForestWrapper { + return &concurrencySafeForestWrapper{forest: f} +} + +func (w *concurrencySafeForestWrapper) VerifyAndAddVertex(vertex *Vertex) error { + w.mu.Lock() + defer w.mu.Unlock() + err := w.forest.VerifyVertex(*vertex) + if err != nil { + return err + } + w.forest.AddVertex(*vertex) + return nil +} + +// GetChildren returns an iterator the children of the specified vertex. +func (w *concurrencySafeForestWrapper) GetChildren(id flow.Identifier) *vertexIteratorChecker { + w.mu.RLock() + defer w.mu.RUnlock() + + // creating non-concurrency safe iterator and memorizing its snapshot information for later testing + unsafeIter := w.forest.GetChildren(id) + numberChildren := w.forest.GetNumberOfChildren(id) + sliceCapacity := cap(unsafeIter.data) + + // create wapper `VertexIteratorConcurrencySafe` and a check for verifying it + safeIter := NewVertexIteratorConcurrencySafe(unsafeIter) + return newVertexIteratorChecker(safeIter, numberChildren, sliceCapacity) +} + +// For testing only! +type vertexIteratorChecker struct { + safeIterator *VertexIteratorConcurrencySafe + expectedLength int + expectedCapacity int +} + +func newVertexIteratorChecker(iter *VertexIteratorConcurrencySafe, expectedLength int, expectedCapacity int) *vertexIteratorChecker { + return &vertexIteratorChecker{ + safeIterator: iter, + expectedLength: expectedLength, + expectedCapacity: expectedCapacity, + } +} + +func (c *vertexIteratorChecker) Check(t *testing.T) { + // We are directly accessing the slice here backing the unsafe iterator without any concurrency + // protection. This is expected to be fine, because the `data` slice is append only. + unsafeIter := c.safeIterator.unsafeIter + assert.NotNil(t, unsafeIter.data) + assert.Equal(t, c.expectedLength, len(unsafeIter.data)) + assert.Equal(t, c.expectedCapacity, cap(unsafeIter.data)) +} diff --git a/module/forest/leveled_forest.go b/module/forest/leveled_forest.go index e0967f052f5..e988f84872f 100644 --- a/module/forest/leveled_forest.go +++ b/module/forest/leveled_forest.go @@ -23,7 +23,7 @@ import ( // LevelledForest is NOT safe for concurrent use by multiple goroutines. type LevelledForest struct { vertices VertexSet - verticesAtLevel map[uint64]VertexList + verticesAtLevel map[uint64]VertexList // by convention, `VertexList`s are append-only (and eventually garbage collected, upon pruning) size uint64 LowestLevel uint64 } @@ -41,7 +41,7 @@ type VertexSet map[flow.Identifier]*vertexContainer type vertexContainer struct { id flow.Identifier level uint64 - children VertexList + children VertexList // by convention, append only // the following are only set if the block is actually known vertex Vertex @@ -136,6 +136,7 @@ func (f *LevelledForest) GetSize() uint64 { func (f *LevelledForest) GetChildren(id flow.Identifier) VertexIterator { // if vertex does not exist, container will be nil if container, ok := f.vertices[id]; ok { + // by design, the list of children is append-only. return newVertexIterator(container.children) } return newVertexIterator(nil) // VertexIterator gracefully handles nil slices diff --git a/module/forest/leveled_forest_test.go b/module/forest/leveled_forest_test.go index e63b2aba5ed..7da7cad1ba3 100644 --- a/module/forest/leveled_forest_test.go +++ b/module/forest/leveled_forest_test.go @@ -35,19 +35,18 @@ func NewVertexMock(vertexId string, vertexLevel uint64, parentId string, parentL // FOREST: // -// ↙-- [A] -// (Genesis) ← [B] ← [C] ←-- [D] -// ⋮ ⋮ ⋮ ⋮ -// ⋮ ⋮ ⋮ (Missing1) ←---- [W] -// ⋮ ⋮ ⋮ ⋮ (Missing2) ← [X] ← [Y] -// ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ↖ [Z] -// ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ +// ↙-- [A] +// (Genesis) ← [B] ← [C] ←-- [D] +// ⋮ ⋮ ⋮ ⋮ +// ⋮ ⋮ ⋮ (Missing1) ←---- [W] +// ⋮ ⋮ ⋮ ⋮ (Missing2) ← [X] ← [Y] +// ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ↖ [Z] +// ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ +// 0 1 2 3 4 5 6 Level // -// LEVEL: 0 1 2 3 4 5 6 // Nomenclature: -// -// [B] Vertex B (internally represented as a full vertex container) -// (M) referenced vertex that has not been added (internally represented as empty vertex container) +// [B] Vertex B (internally represented as a full vertex container) +// (M) referenced vertex that has not been added (internally represented as empty vertex container) var TestVertices = map[string]*mock.Vertex{ "A": NewVertexMock("A", 3, "Genesis", 0), "B": NewVertexMock("B", 1, "Genesis", 0), diff --git a/module/forest/mock/vertex.go b/module/forest/mock/vertex.go index a24678376ed..482c80a969b 100644 --- a/module/forest/mock/vertex.go +++ b/module/forest/mock/vertex.go @@ -1,39 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewVertex creates a new instance of Vertex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVertex(t interface { + mock.TestingT + Cleanup(func()) +}) *Vertex { + mock := &Vertex{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Vertex is an autogenerated mock type for the Vertex type type Vertex struct { mock.Mock } -// Level provides a mock function with no fields -func (_m *Vertex) Level() uint64 { - ret := _m.Called() +type Vertex_Expecter struct { + mock *mock.Mock +} + +func (_m *Vertex) EXPECT() *Vertex_Expecter { + return &Vertex_Expecter{mock: &_m.Mock} +} + +// Level provides a mock function for the type Vertex +func (_mock *Vertex) Level() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Level") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Parent provides a mock function with no fields -func (_m *Vertex) Parent() (flow.Identifier, uint64) { - ret := _m.Called() +// Vertex_Level_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Level' +type Vertex_Level_Call struct { + *mock.Call +} + +// Level is a helper method to define mock.On call +func (_e *Vertex_Expecter) Level() *Vertex_Level_Call { + return &Vertex_Level_Call{Call: _e.mock.On("Level")} +} + +func (_c *Vertex_Level_Call) Run(run func()) *Vertex_Level_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Vertex_Level_Call) Return(v uint64) *Vertex_Level_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Vertex_Level_Call) RunAndReturn(run func() uint64) *Vertex_Level_Call { + _c.Call.Return(run) + return _c +} + +// Parent provides a mock function for the type Vertex +func (_mock *Vertex) Parent() (flow.Identifier, uint64) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Parent") @@ -41,56 +90,93 @@ func (_m *Vertex) Parent() (flow.Identifier, uint64) { var r0 flow.Identifier var r1 uint64 - if rf, ok := ret.Get(0).(func() (flow.Identifier, uint64)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.Identifier, uint64)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func() uint64); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() uint64); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(uint64) } - return r0, r1 } -// VertexID provides a mock function with no fields -func (_m *Vertex) VertexID() flow.Identifier { - ret := _m.Called() +// Vertex_Parent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Parent' +type Vertex_Parent_Call struct { + *mock.Call +} + +// Parent is a helper method to define mock.On call +func (_e *Vertex_Expecter) Parent() *Vertex_Parent_Call { + return &Vertex_Parent_Call{Call: _e.mock.On("Parent")} +} + +func (_c *Vertex_Parent_Call) Run(run func()) *Vertex_Parent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Vertex_Parent_Call) Return(identifier flow.Identifier, v uint64) *Vertex_Parent_Call { + _c.Call.Return(identifier, v) + return _c +} + +func (_c *Vertex_Parent_Call) RunAndReturn(run func() (flow.Identifier, uint64)) *Vertex_Parent_Call { + _c.Call.Return(run) + return _c +} + +// VertexID provides a mock function for the type Vertex +func (_mock *Vertex) VertexID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for VertexID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// NewVertex creates a new instance of Vertex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVertex(t interface { - mock.TestingT - Cleanup(func()) -}) *Vertex { - mock := &Vertex{} - mock.Mock.Test(t) +// Vertex_VertexID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VertexID' +type Vertex_VertexID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VertexID is a helper method to define mock.On call +func (_e *Vertex_Expecter) VertexID() *Vertex_VertexID_Call { + return &Vertex_VertexID_Call{Call: _e.mock.On("VertexID")} +} - return mock +func (_c *Vertex_VertexID_Call) Run(run func()) *Vertex_VertexID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Vertex_VertexID_Call) Return(identifier flow.Identifier) *Vertex_VertexID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *Vertex_VertexID_Call) RunAndReturn(run func() flow.Identifier) *Vertex_VertexID_Call { + _c.Call.Return(run) + return _c } diff --git a/module/forest/vertex.go b/module/forest/vertex.go index bcb090516c4..8f5d5e94a42 100644 --- a/module/forest/vertex.go +++ b/module/forest/vertex.go @@ -23,10 +23,36 @@ func VertexToString(v Vertex) string { } // VertexIterator is a stateful iterator for VertexList. -// Internally operates directly on the Vertex Containers +// Internally, it operates directly on the Vertex Containers. // It has one-element look ahead for skipping empty vertex containers. +// +// ATTENTION: Not Concurrency Safe! +// +// This vertex iterator does NOT COPY the provided list of vertices for +// efficiency reasons. For APPEND_ONLY `VertexList`s, the `VertexIterator` +// can be wrapped into a VertexIteratorConcurrencySafe to make it concurrency +// safe. By design, the LevelledForest guarantees this. Hence, construction +// of these vertex iterators is private to the `forest` package. type VertexIterator struct { - data VertexList + // CAUTION: to support concurrency-safe iterators, the `VertexIterator` *must* maintain its own slice descriptor. + // This is the default in Golang, as slices are typically passed by value, since only the slice descriptor (see + // https://go.dev/blog/slices-intro for details) is copied, but not the backing array. While very uncommon in go, + // we emphasize that a hypothetical change to `data *VertexList` (using pointer to slice) would break our wrapper + // `VertexIteratorConcurrencySafe`. + // Context: + // • `VertexIterator`s are instantiated by calling LevelledForest.GetChildren or .GetVerticesAtLevel` for + // example. In both cases, the provided `VertexList` is append-only in the levelled forest. So we assume a + // LevelledForest instance which is synchronized for concurrent access by higher-level business logic. Then, + // a `VertexIterator` many be iterated on, while concurrently elements are added to the forest. + // • Note that `data` is intrinsically safe for concurrent access, as long as no elements are modified inplace. + // In other words, append-only usage patterns are intrinsically safe for concurrent access. Eventually, the forest + // may exceed the current slice's capacity, at which point a new array is allocated by forest, while we maintain + // a reference to the older array here. Essentially, we maintain a snapshot of the slice at the point we received + // it, since our `data` field below also contains a local copy of the slice's length at the point we received it. + data VertexList // tldr; assumed safe for concurrent access, as forest operates append-only + + // not protected for concurrent access: + idx int next Vertex } @@ -55,6 +81,17 @@ func (it *VertexIterator) HasNext() bool { return it.next != nil } +// newVertexIterator instantiates an iterator. Essentially it operates on a snapshot of the slice. +// Even if the Levelled Forest makes additions to the input slice, we maintain our own notion of +// length and backing slice. +// CAUTION: +// - we do NOT COPY the list's containers for efficiency. +// - Package-private, as usage must be limited to APPEND-ONLY `VertexList` +// Without append-only guarantees, we would break the `VertexIteratorConcurrencySafe` +// and generally a lot of conceptual challenges arise for iteration in concurrent +// environments. We easily avoid the complexity by restricting the usage to the +// levelled forest, which by design operates append-only (and eventually garbage collected +// on pruning. func newVertexIterator(vertexList VertexList) VertexIterator { it := VertexIterator{ data: vertexList, @@ -75,11 +112,14 @@ func (err InvalidVertexError) Error() string { return fmt.Sprintf("invalid vertex %s: %s", VertexToString(err.Vertex), err.msg) } +// IsInvalidVertexError returns true if and only if the input error is a (wrapped) InvalidVertexError. func IsInvalidVertexError(err error) bool { var target InvalidVertexError return errors.As(err, &target) } +// NewInvalidVertexErrorf instantiates an [InvalidVertexError]. The +// inputs `msg` and `args` follow the pattern of [fmt.Errorf]. func NewInvalidVertexErrorf(vertex Vertex, msg string, args ...interface{}) InvalidVertexError { return InvalidVertexError{ Vertex: vertex, diff --git a/module/grpcserver/interceptor_logging.go b/module/grpcserver/interceptor_logging.go index c665ce0867d..6a24ebed17f 100644 --- a/module/grpcserver/interceptor_logging.go +++ b/module/grpcserver/interceptor_logging.go @@ -8,16 +8,52 @@ import ( "github.com/rs/zerolog" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/peer" ) -// LoggingInterceptor returns a grpc.UnaryServerInterceptor that logs incoming GRPC request and response +// LoggingInterceptor returns a grpc.UnaryServerInterceptor that logs incoming GRPC request and response. +// It extracts the requester's peer address from the gRPC context and includes it in log entries. +// Logs are emitted at the start and finish of each call for debugging and tracing purposes. +// Both start and finish logs are at debug level. +// +// Example log messages for searching: +// - Start: DBG "started call" grpc.method=Ping grpc.service=flow.access.AccessAPI peer.address=... +// - Finish: DBG "finished call" grpc.method=Ping grpc.service=flow.access.AccessAPI peer.address=... grpc.code=OK grpc.time_ms=... func LoggingInterceptor(log zerolog.Logger) grpc.UnaryServerInterceptor { return logging.UnaryServerInterceptor( InterceptorLogger(log), logging.WithLevels(statusCodeToLogLevel), + logging.WithFieldsFromContext(extractPeerFields), + logging.WithLogOnEvents(logging.StartCall, logging.FinishCall), ) } +// StreamLoggingInterceptor returns a grpc.StreamServerInterceptor that logs incoming streaming GRPC requests. +// It extracts the requester's peer address from the gRPC context and includes it in log entries. +// Logs are emitted at the start and finish of each streaming call for debugging and tracing purposes. +// Both start and finish logs are at debug level. +// +// Example log messages for searching: +// - Start: DBG "started call" grpc.method=SubscribeEvents grpc.service=flow.executiondata.ExecutionDataAPI peer.address=... +// - Finish: DBG "finished call" grpc.method=SubscribeEvents grpc.service=flow.executiondata.ExecutionDataAPI peer.address=... grpc.code=OK grpc.time_ms=... +func StreamLoggingInterceptor(log zerolog.Logger) grpc.StreamServerInterceptor { + return logging.StreamServerInterceptor( + InterceptorLogger(log), + logging.WithLevels(statusCodeToLogLevel), + logging.WithFieldsFromContext(extractPeerFields), + logging.WithLogOnEvents(logging.StartCall, logging.FinishCall), + ) +} + +// extractPeerFields extracts peer information from the gRPC context and returns it as logging fields. +// This includes the client's remote address for request tracing and debugging. +func extractPeerFields(ctx context.Context) logging.Fields { + if p, ok := peer.FromContext(ctx); ok { + return logging.Fields{"peer.address", p.Addr.String()} + } + return nil +} + // InterceptorLogger adapts a zerolog.Logger to interceptor's logging.Logger // This code is simple enough to be copied and not imported. func InterceptorLogger(l zerolog.Logger) logging.Logger { @@ -39,16 +75,8 @@ func InterceptorLogger(l zerolog.Logger) logging.Logger { }) } -// statusCodeToLogLevel converts a grpc status.Code to the appropriate logging.Level -func statusCodeToLogLevel(c codes.Code) logging.Level { - switch c { - case codes.OK: - // log successful returns as Debug to avoid excessive logging in info mode - return logging.LevelDebug - case codes.DeadlineExceeded, codes.ResourceExhausted, codes.OutOfRange: - // these are common, map to info - return logging.LevelInfo - default: - return logging.DefaultServerCodeToLevel(c) - } +// statusCodeToLogLevel converts a grpc status.Code to the appropriate logging.Level. +// All status codes are logged at debug level to avoid excessive logging. +func statusCodeToLogLevel(_ codes.Code) logging.Level { + return logging.LevelDebug } diff --git a/module/grpcserver/interceptor_ratelimit.go b/module/grpcserver/interceptor_ratelimit.go index 30b8a1e4c99..00988d535ec 100644 --- a/module/grpcserver/interceptor_ratelimit.go +++ b/module/grpcserver/interceptor_ratelimit.go @@ -56,10 +56,10 @@ func NewRateLimiterInterceptor(log zerolog.Logger, apiRateLimits map[string]int, // based on the limits defined when creating the RateLimiterInterceptor func (interceptor *RateLimiterInterceptor) UnaryServerInterceptor( ctx context.Context, - req interface{}, + req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, -) (resp interface{}, err error) { +) (resp any, err error) { // remove the package name (e.g. "/flow.access.AccessAPI/Ping" to "Ping") methodName := filepath.Base(info.FullMethod) diff --git a/module/grpcserver/server_builder.go b/module/grpcserver/server_builder.go index fbbfe16403a..f5fb47941f8 100644 --- a/module/grpcserver/server_builder.go +++ b/module/grpcserver/server_builder.go @@ -102,6 +102,7 @@ func NewGrpcServerBuilder( // Note: make sure logging interceptor is innermost wrapper to capture all messages unaryInterceptors = append(unaryInterceptors, LoggingInterceptor(log)) + streamInterceptors = append(streamInterceptors, StreamLoggingInterceptor(log)) grpcOpts = append(grpcOpts, grpc.ChainUnaryInterceptor(unaryInterceptors...)) if len(streamInterceptors) > 0 { diff --git a/module/irrecoverable/exception_test.go b/module/irrecoverable/exception_test.go index eb3fcf8e5e6..e847575d781 100644 --- a/module/irrecoverable/exception_test.go +++ b/module/irrecoverable/exception_test.go @@ -8,6 +8,27 @@ import ( "github.com/stretchr/testify/assert" ) +// IsIrrecoverableException returns true if and only of the provided error is +// (a wrapped) irrecoverable exception. By protocol convention, irrecoverable +// errors conceptually handled the same way as other unexpected errors: any +// occurrence means that the software has left the pre-defined path of _safe_ +// operations. Continuing despite an unexpected error or irrecoverable exception +// is impossible, because protocol-compliant operation of a node can no longer +// be expected. In the worst case the node might be slashed or the protocol as a +// hole compromised. +// For the reason mentioned above, protocol business logic should generally only +// check for sentinel errors expected exactly in the situation the business logic +// is in. Any error that does not match the sentinels known to be benign in that +// situation should be treated as a critical failure and the node must crash. +// Hence, PROTOCOL BUSINESS LOGIC should NEVER CHECK whether an error is an +// IRRECOVERABLE EXCEPTION. This function is for TESTING ONLY. +func IsIrrecoverableException(err error) bool { + // The Go build system specifically handles `_test.go` files, treating them as part of + // the test suite and not including them in the final production binary using go build. + var e = new(exception) + return errors.As(err, &e) +} + var sentinelVar = errors.New("sentinelVar") type sentinelType struct{} diff --git a/module/jobqueue/component_consumer.go b/module/jobqueue/component_consumer.go index 457aed3f804..8656f59c945 100644 --- a/module/jobqueue/component_consumer.go +++ b/module/jobqueue/component_consumer.go @@ -27,14 +27,12 @@ type ComponentConsumer struct { func NewComponentConsumer( log zerolog.Logger, workSignal <-chan struct{}, - progressInitializer storage.ConsumerProgressInitializer, + progress storage.ConsumerProgress, jobs module.Jobs, - defaultIndex uint64, processor JobProcessor, // method used to process jobs maxProcessing uint64, maxSearchAhead uint64, ) (*ComponentConsumer, error) { - c := &ComponentConsumer{ workSignal: workSignal, jobs: jobs, @@ -48,7 +46,7 @@ func NewComponentConsumer( maxProcessing, ) - consumer, err := NewConsumer(log, jobs, progressInitializer, worker, maxProcessing, maxSearchAhead, defaultIndex) + consumer, err := NewConsumer(log, jobs, progress, worker, maxProcessing, maxSearchAhead) if err != nil { return nil, err } diff --git a/module/jobqueue/component_consumer_test.go b/module/jobqueue/component_consumer_test.go index 8f4ec576580..dc121f0d96c 100644 --- a/module/jobqueue/component_consumer_test.go +++ b/module/jobqueue/component_consumer_test.go @@ -87,15 +87,11 @@ func (suite *ComponentConsumerSuite) prepareTest( progress.On("ProcessedIndex").Return(suite.defaultIndex, nil) progress.On("SetProcessedIndex", mock.AnythingOfType("uint64")).Return(nil) - progressInitializer := new(storagemock.ConsumerProgressInitializer) - progressInitializer.On("Initialize", mock.AnythingOfType("uint64")).Return(progress, nil) - consumer, err := NewComponentConsumer( unittest.Logger(), workSignal, - progressInitializer, + progress, jobs, - suite.defaultIndex, processor, suite.maxProcessing, suite.maxSearchAhead, diff --git a/module/jobqueue/consumer.go b/module/jobqueue/consumer.go index 035f625dfaf..4ffb4998184 100644 --- a/module/jobqueue/consumer.go +++ b/module/jobqueue/consumer.go @@ -50,18 +50,11 @@ type Consumer struct { func NewConsumer( log zerolog.Logger, jobs module.Jobs, - progressInitializer storage.ConsumerProgressInitializer, + progress storage.ConsumerProgress, worker Worker, maxProcessing uint64, maxSearchAhead uint64, - defaultIndex uint64, ) (*Consumer, error) { - - progress, err := progressInitializer.Initialize(defaultIndex) - if err != nil { - return nil, fmt.Errorf("could not initialize processed index: %w", err) - } - processedIndex, err := progress.ProcessedIndex() if err != nil { return nil, fmt.Errorf("could not read processed index: %w", err) diff --git a/module/jobqueue/consumer_behavior_test.go b/module/jobqueue/consumer_behavior_test.go index b26f1249720..8e6cfe7eed8 100644 --- a/module/jobqueue/consumer_behavior_test.go +++ b/module/jobqueue/consumer_behavior_test.go @@ -580,8 +580,12 @@ func assertProcessed(t testing.TB, cp storage.ConsumerProgress, expectProcessed func newTestConsumer(t testing.TB, cp storage.ConsumerProgressInitializer, jobs module.Jobs, worker jobqueue.Worker, maxSearchAhead uint64, defaultIndex uint64) module.JobConsumer { log := unittest.Logger().With().Str("module", "consumer").Logger() + + progress, err := cp.Initialize(defaultIndex) + require.NoError(t, err) + maxProcessing := uint64(3) - c, err := jobqueue.NewConsumer(log, jobs, cp, worker, maxProcessing, maxSearchAhead, defaultIndex) + c, err := jobqueue.NewConsumer(log, jobs, progress, worker, maxProcessing, maxSearchAhead) require.NoError(t, err) return c } diff --git a/module/jobqueue/consumer_test.go b/module/jobqueue/consumer_test.go index 4c672d73876..70810f758f2 100644 --- a/module/jobqueue/consumer_test.go +++ b/module/jobqueue/consumer_test.go @@ -160,10 +160,11 @@ func TestProcessedIndexDeletion(t *testing.T) { dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { log := unittest.Logger().With().Str("module", "consumer").Logger() jobs := NewMockJobs() - progressInitializer := store.NewConsumerProgress(db, "consumer") + progress, err := store.NewConsumerProgress(db, "consumer").Initialize(0) + require.NoError(t, err) worker := newMockWorker() maxProcessing := uint64(3) - c, err := NewConsumer(log, jobs, progressInitializer, worker, maxProcessing, 0, 0) + c, err := NewConsumer(log, jobs, progress, worker, maxProcessing, 0) require.NoError(t, err) worker.WithConsumer(c) @@ -200,11 +201,10 @@ func TestCheckBeforeStartIsNoop(t *testing.T) { c, err := NewConsumer( unittest.Logger(), NewMockJobs(), - progressInitializer, + progress, worker, uint64(3), 0, - 10, // default index is before the stored processedIndex ) require.NoError(t, err) worker.WithConsumer(c) diff --git a/module/limiters/concurrency_limiter.go b/module/limiters/concurrency_limiter.go new file mode 100644 index 00000000000..539647a1a89 --- /dev/null +++ b/module/limiters/concurrency_limiter.go @@ -0,0 +1,71 @@ +package limiters + +import ( + "errors" + + "go.uber.org/atomic" +) + +// ConcurrencyLimiter is a limiter that allows a maximum number of concurrent operations to be executed. +// +// Safe for concurrent use. +type ConcurrencyLimiter struct { + maxConcurrent uint32 + totalConcurrent *atomic.Uint32 +} + +// NewConcurrencyLimiter creates a new ConcurrencyLimiter with the given maximum number of concurrent operations. +func NewConcurrencyLimiter(maxConcurrent uint32) (*ConcurrencyLimiter, error) { + if maxConcurrent == 0 { + return nil, errors.New("maxConcurrent must be greater than 0") + } + + return &ConcurrencyLimiter{ + maxConcurrent: maxConcurrent, + totalConcurrent: atomic.NewUint32(0), + }, nil +} + +// Acquire atomically increments the concurrency counter if it is below the configured limit. +// Returns true if the slot was acquired, false if the limit was reached. +// The caller MUST call [Release] exactly once after a successful Acquire. +func (h *ConcurrencyLimiter) Acquire() bool { + for { + current := h.totalConcurrent.Load() + if current >= h.maxConcurrent { + return false + } + if h.totalConcurrent.CompareAndSwap(current, current+1) { + return true + } + } +} + +// Release decrements the concurrency counter, freeing a slot previously obtained via [Acquire]. +// Must be called exactly once for every successful [Acquire] call. +// Panics if called without a matching [Acquire] (counter underflow). +func (h *ConcurrencyLimiter) Release() { + for { + current := h.totalConcurrent.Load() + if current == 0 { + panic("concurrency limiter release without matching acquire") + } + if h.totalConcurrent.CompareAndSwap(current, current-1) { + return + } + } +} + +// Allow executes fn if the number of concurrent operations is below the configured limit. +// Returns true if fn was executed, false if the limit was reached and fn was not called. +// The concurrency counter is decremented when fn returns, including on panic. +func (h *ConcurrencyLimiter) Allow(fn func()) bool { + if !h.Acquire() { + return false + } + // decrement within a defer to support usecases where panics are handled gracefully by the caller + defer h.Release() + + fn() + return true +} diff --git a/module/limiters/concurrency_limiter_test.go b/module/limiters/concurrency_limiter_test.go new file mode 100644 index 00000000000..4af4f29208b --- /dev/null +++ b/module/limiters/concurrency_limiter_test.go @@ -0,0 +1,219 @@ +package limiters + +import ( + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestConcurrencyLimiter_Allow_WithinLimit verifies that Allow executes the function +// and returns true when below the concurrency limit. +func TestConcurrencyLimiter_Allow_WithinLimit(t *testing.T) { + limiter, err := NewConcurrencyLimiter(2) + require.NoError(t, err) + executed := false + allowed := limiter.Allow(func() { executed = true }) + require.True(t, allowed) + assert.True(t, executed) +} + +// TestConcurrencyLimiter_Allow_AtLimit verifies that Allow returns false without +// executing the function when the concurrency limit is reached. +func TestConcurrencyLimiter_Allow_AtLimit(t *testing.T) { + limiter, err := NewConcurrencyLimiter(1) + require.NoError(t, err) + + // Block the first call inside Allow so the counter stays at 1. + started := make(chan struct{}) + unblock := make(chan struct{}) + + var wg sync.WaitGroup + wg.Go(func() { + limiter.Allow(func() { + close(started) + <-unblock + }) + }) + + // Wait until the goroutine is inside fn (counter == 1). + <-started + + // A second call must be rejected. + executed := false + allowed := limiter.Allow(func() { executed = true }) + assert.False(t, allowed) + assert.False(t, executed) + + close(unblock) + wg.Wait() +} + +// TestConcurrencyLimiter_Allow_CounterDecrement verifies that the internal counter +// returns to zero after Allow completes so subsequent calls are accepted again. +func TestConcurrencyLimiter_Allow_CounterDecrement(t *testing.T) { + limiter, err := NewConcurrencyLimiter(1) + require.NoError(t, err) + + allowed := limiter.Allow(func() {}) + require.True(t, allowed) + + // Counter must be decremented; second call should succeed. + allowed = limiter.Allow(func() {}) + assert.True(t, allowed) +} + +// TestConcurrencyLimiter_Allow_CounterDecrementOnPanic verifies that the internal +// counter is decremented even when the supplied function panics. +func TestConcurrencyLimiter_Allow_CounterDecrementOnPanic(t *testing.T) { + limiter, err := NewConcurrencyLimiter(1) + require.NoError(t, err) + + require.Panics(t, func() { + limiter.Allow(func() { panic("boom") }) + }) + + // Counter must have been decremented via defer; next call must succeed. + executed := false + allowed := limiter.Allow(func() { executed = true }) + assert.True(t, allowed) + assert.True(t, executed) +} + +// TestConcurrencyLimiter_NewZeroLimit verifies that the constructor returns an error +// when the limit is zero. +func TestConcurrencyLimiter_NewZeroLimit(t *testing.T) { + _, err := NewConcurrencyLimiter(0) + assert.Error(t, err) +} + +// TestConcurrencyLimiter_Acquire_WithinLimit verifies that Acquire returns true +// when below the concurrency limit. +func TestConcurrencyLimiter_Acquire_WithinLimit(t *testing.T) { + limiter, err := NewConcurrencyLimiter(2) + require.NoError(t, err) + + assert.True(t, limiter.Acquire()) + assert.True(t, limiter.Acquire()) + + limiter.Release() + limiter.Release() +} + +// TestConcurrencyLimiter_Acquire_AtLimit verifies that Acquire returns false +// when the concurrency limit is reached, and succeeds again after Release. +func TestConcurrencyLimiter_Acquire_AtLimit(t *testing.T) { + limiter, err := NewConcurrencyLimiter(1) + require.NoError(t, err) + + assert.True(t, limiter.Acquire()) + assert.False(t, limiter.Acquire(), "second Acquire must fail at limit") + + limiter.Release() + assert.True(t, limiter.Acquire(), "Acquire must succeed after Release") + + limiter.Release() +} + +// TestConcurrencyLimiter_Acquire_ConcurrentCalls verifies that at most maxConcurrent +// slots can be acquired simultaneously across concurrent goroutines. +func TestConcurrencyLimiter_Acquire_ConcurrentCalls(t *testing.T) { + const maxConcurrent = 5 + const totalGoroutines = 50 + + limiter, err := NewConcurrencyLimiter(maxConcurrent) + require.NoError(t, err) + + var ( + peak atomic.Int32 + current atomic.Int32 + wg sync.WaitGroup + ) + + start := make(chan struct{}) + + for i := 0; i < totalGoroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + if limiter.Acquire() { + n := current.Add(1) + for { + old := peak.Load() + if n <= old || peak.CompareAndSwap(old, n) { + break + } + } + time.Sleep(time.Millisecond) + current.Add(-1) + limiter.Release() + } + }() + } + + close(start) + wg.Wait() + + assert.LessOrEqual(t, peak.Load(), int32(maxConcurrent), + "peak concurrent acquisitions must not exceed maxConcurrent") +} + +// TestConcurrencyLimiter_Release_Underflow verifies that Release panics when called +// without a matching Acquire (counter at zero). +func TestConcurrencyLimiter_Release_Underflow(t *testing.T) { + limiter, err := NewConcurrencyLimiter(1) + require.NoError(t, err) + + assert.PanicsWithValue(t, "concurrency limiter release without matching acquire", func() { + limiter.Release() + }) +} + +// TestConcurrencyLimiter_Allow_ConcurrentCalls verifies that at most maxConcurrent +// goroutines execute fn simultaneously across a burst of concurrent callers. +func TestConcurrencyLimiter_Allow_ConcurrentCalls(t *testing.T) { + const maxConcurrent = 5 + const totalGoroutines = 50 + + limiter, err := NewConcurrencyLimiter(maxConcurrent) + require.NoError(t, err) + + var ( + peak atomic.Int32 // highest observed concurrent executions + current atomic.Int32 + wg sync.WaitGroup + ) + + start := make(chan struct{}) + + for i := 0; i < totalGoroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + limiter.Allow(func() { + n := current.Add(1) + // Record peak without locking; a slightly stale read is acceptable + // because we only care about the maximum ever observed. + for { + old := peak.Load() + if n <= old || peak.CompareAndSwap(old, n) { + break + } + } + time.Sleep(time.Millisecond) // hold the slot briefly + current.Add(-1) + }) + }() + } + + close(start) + wg.Wait() + + assert.LessOrEqual(t, peak.Load(), int32(maxConcurrent), + "peak concurrent executions must not exceed maxConcurrent") +} diff --git a/module/local.go b/module/local.go index cb7ec0b8f2e..0ae1db06ab5 100644 --- a/module/local.go +++ b/module/local.go @@ -16,6 +16,9 @@ type Local interface { // Address returns the (listen) address of the local node. Address() string + // Role returns the role of the local node. + Role() flow.Role + // Sign provides a signature oracle that given a message and hasher, it // generates and returns a signature over the message using the node's private key // as well as the input hasher diff --git a/module/local/me.go b/module/local/me.go index 5cdb4275a6f..ff3b546a045 100644 --- a/module/local/me.go +++ b/module/local/me.go @@ -8,6 +8,7 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/flow/filter" + "github.com/onflow/flow-go/module" ) type Local struct { @@ -15,6 +16,8 @@ type Local struct { sk crypto.PrivateKey // instance of the node's private staking key } +var _ module.Local = (*Local)(nil) + func New(id flow.IdentitySkeleton, sk crypto.PrivateKey) (*Local, error) { if !sk.PublicKey().Equals(id.StakingPubKey) { return nil, fmt.Errorf("cannot initialize with mismatching keys, expect %v, but got %v", @@ -32,6 +35,10 @@ func (l *Local) NodeID() flow.Identifier { return l.me.NodeID } +func (l *Local) Role() flow.Role { + return l.me.Role +} + func (l *Local) Address() string { return l.me.Address } diff --git a/module/local/me_nokey.go b/module/local/me_nokey.go index 7f697aec1ae..b5df97482b1 100644 --- a/module/local/me_nokey.go +++ b/module/local/me_nokey.go @@ -8,12 +8,15 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/flow/filter" + "github.com/onflow/flow-go/module" ) type LocalNoKey struct { me flow.IdentitySkeleton } +var _ module.Local = (*LocalNoKey)(nil) + func NewNoKey(id flow.IdentitySkeleton) (*LocalNoKey, error) { l := &LocalNoKey{ me: id, @@ -25,6 +28,10 @@ func (l *LocalNoKey) NodeID() flow.Identifier { return l.me.NodeID } +func (l *LocalNoKey) Role() flow.Role { + return l.me.Role +} + func (l *LocalNoKey) Address() string { return l.me.Address } diff --git a/module/mempool/consensus/exec_fork_suppressor.go b/module/mempool/consensus/exec_fork_suppressor.go index 209b0337c3a..0b9007fdc67 100644 --- a/module/mempool/consensus/exec_fork_suppressor.go +++ b/module/mempool/consensus/exec_fork_suppressor.go @@ -17,44 +17,80 @@ import ( "github.com/onflow/flow-go/storage/store" ) -// ExecForkSuppressor is a wrapper around a conventional mempool.IncorporatedResultSeals -// mempool. It implements the following mitigation strategy for execution forks: -// - In case two conflicting results are considered sealable for the same block, -// sealing should halt. Specifically, two results are considered conflicting, -// if they differ in their start or end state. -// - Even after a restart, the sealing should not resume. +// ExecForkSuppressor is a wrapper around a conventional [mempool.IncorporatedResultSeals] mempool. +// It implements the following mitigation strategy for execution forks: +// - In case two conflicting results are considered sealable for the same block, sealing should halt. +// Specifically, two results are considered conflicting, if they differ in their start or end state +// (simplified heuristic, assuming different events or metadata necessitate different end states). +// - Even after a restart, the sealing should not resume if an execution fork as been detected before. // - We rely on human intervention to resolve the conflict. // // The ExecForkSuppressor implements this mitigation strategy as follows: -// - For each candidate seal inserted into the mempool, indexes seal -// by respective blockID, storing all seals in the internal map `sealsForBlock`. -// - Whenever client perform any query, we check if there are conflicting seals. -// - We pick first seal available for a block and check whether -// the seal has the same state transition as other seals included for same block. +// - Let 𝓈 be a seal in the mempool. With 𝓈.BlockID we denote the ID of the block whose result +// would be sealed by 𝓈. The ID of the incorporated result the seal would commit is denoted by +// 𝓈.IncorporatedResultID. For each seal 𝓈 successfully added to the underlying mempool, we +// store the following entries in our internal maps: +// `sealsForBlock[𝓈.BlockID][𝓈.IncorporatedResultID] = struct{}{}` +// `byHeight[𝓈.Header.Height][𝓈.BlockID] = struct{}{}` +// `sealsForBlock` records, for each executed block ID, all distinct incorporated results +// whose seals have been forwarded downstream. An execution fork is present if two entries +// for the same block commit to inconsistent state transitions. +// `byHeight` mirrors the same information keyed by block height, enabling efficient height-based pruning. +// - Whenever a client performs a query, we check if there are conflicting seals. +// - We pick the first seal available for a block and check whether +// the seal has the same state transition as other seals available for the same block. // - If conflicting state transitions for the same block are detected, // ExecForkSuppressor sets an internal flag and thereafter // reports the mempool as empty, which will lead to the respective // consensus node not including any more seals. -// - Evidence for an execution fork stored in a database (persisted across restarts). +// - Evidence for an execution fork is stored in a database (persisted across restarts). +// +// In the mature protocol, there will be mechanisms that prevent some seals from being created in the first place, +// but some of those mechanisms are not yet implemented. In place of the mature solution (seals for results with +// insufficient reliability never being added to the mempool), we work with heuristic filters preventing some of +// the seals in the mempool from being retrieved. This is fine for now, because all ENs are operated by vetted +// partners. We make a deliberate design choice: the wrappers around the core mempool contain all the algorithmic +// shortcuts necessary to ensure correctness, until we have the mature solution in place. +// Unfortunately, this design choice induces the following subtlety: +// +// IMPORTANT: For each block, `sealsForBlock` tracks all IncorporatedResult IDs for which seals have been +// forwarded to the underlying pool (see [potentiallySealableResults] for further context). This is a SUPERSET of +// IncorporatedResults whose seals the underlying pool considers 'includable': the lower-level wrappers may hold back +// seals that don't meet their inclusion criteria (e.g., requiring at least 2 execution receipts from different ENs). +// Hence, the ExecForkSuppressor must NOT use `sealsForBlock` directly to determine conflicting seals. Instead, +// at query time, it verifies each candidate through the underlying pool, so that only actually-includable seals +// are compared for fork detection. // // Implementation is concurrency safe. type ExecForkSuppressor struct { mutex sync.RWMutex seals mempool.IncorporatedResultSeals - sealsForBlock map[flow.Identifier]sealSet // map BlockID -> set of IncorporatedResultSeal - byHeight map[uint64]map[flow.Identifier]struct{} // map height -> set of executed block IDs at height - lowestHeight uint64 execForkDetected atomic.Bool onExecFork ExecForkActor execForkEvidenceStore storage.ExecutionForkEvidence lockManager storage.LockManager log zerolog.Logger + + // sealsForBlock is a set of sets. Formally, it maps: BlockID -> set of IncorporatedResult IDs. Intuitively, + // `sealsForBlock` records, for each executed block ID, all distinct incorporated results whose seals have + // been forwarded downstream. + // `byHeight` and `lowestHeight` are used to prune `sealsForBlock` by height. + sealsForBlock map[flow.Identifier]potentiallySealableResults // BlockID -> set of IncorporatedResult IDs (superset of wrapped pool, see struct docs) + byHeight map[uint64]map[flow.Identifier]struct{} // map height -> set of executed block IDs at height + lowestHeight uint64 } var _ mempool.IncorporatedResultSeals = (*ExecForkSuppressor)(nil) -// sealSet is a set of seals; internally represented as a map from incorporated result ID -> to seal -type sealSet map[flow.Identifier]*flow.IncorporatedResultSeal +// potentiallySealableResults is a set of IDs of IncorporatedResults that are potentially sealable. +// It is a SUPERSET of the IncorporatedResults that the wrapped pool considers sealable (see struct-level documentation). +// CAUTION: some of these seals might be held back from inclusion by the lower-level disaster prevention heuristics +// but they are still stored in the ExecForkSuppressor because the seals have passed through the ExecForkSuppressor before +// being added to the underlying mempool. +// +// We intentionally store only the Incorporated Result IDs (not seals pertaining to them) to structurally enforce that all +// seals compared for conflicts have been retrieved from the wrapped mempool first. +type potentiallySealableResults map[flow.Identifier]struct{} // sealsList is a list of seals type sealsList []*flow.IncorporatedResultSeal @@ -81,7 +117,7 @@ func NewExecStateForkSuppressor( wrapper := ExecForkSuppressor{ mutex: sync.RWMutex{}, seals: seals, - sealsForBlock: make(map[flow.Identifier]sealSet), + sealsForBlock: make(map[flow.Identifier]potentiallySealableResults), byHeight: make(map[uint64]map[flow.Identifier]struct{}), execForkDetected: *atomic.NewBool(execForkDetectedFlag), onExecFork: onExecFork, @@ -93,8 +129,13 @@ func NewExecStateForkSuppressor( return &wrapper, nil } -// Add adds the given seal to the mempool. Return value indicates whether seal was added to the mempool. -// Internally indexes every added seal by blockID. Expects that underlying mempool never eject items. +// Add forwards the given seal to the underlying mempool, with the return value indicating whether seal was accepted +// by the underlying mempool. For every `newSeal` that is accepted, we record: +// - for block `newSeal.Seal.BlockID` add ` newSeal.IncorporatedResult.ID()` to the set of incorporated results +// for that block, which we have seen seals for. +// IMPORTANT: this set is a SUPERSET of the seals that the wrapped pool considers includable (see struct-level documentation). +// - cache the block height in `byHeight` index, to enable later pruning of `sealsForBlock` by height. +// // Error returns: // - engine.InvalidInputError (sentinel error) // In case a seal fails one of the required consistency checks; @@ -121,11 +162,6 @@ func (s *ExecForkSuppressor) Add(newSeal *flow.IncorporatedResultSeal) (bool, er } blockID := newSeal.Seal.BlockID - // This mempool allows adding multiple seals for same blockID even if they have different state transition. - // When builder logic tries to query such seals we will check whenever we have an execution fork. The main reason for - // detecting forks at query time(not at adding time) is ability to add extra logic in underlying mempools. For instance - // we could filter seals comming from underlying mempool by some criteria. - // STEP 2: add newSeal to the wrapped mempool added, err := s.seals.Add(newSeal) // internally de-duplicates if err != nil { @@ -135,15 +171,23 @@ func (s *ExecForkSuppressor) Add(newSeal *flow.IncorporatedResultSeal) (bool, er return false, nil } - // STEP 3: add newSeal to secondary index of this wrapper - // CAUTION: We expect that underlying mempool NEVER ejects seals because it breaks liveness. - blockSeals, found := s.sealsForBlock[blockID] + // STEP 3: record `newSeal.IncorporatedResultID()` in sealsForBlock. + // + // IMPORTANT: Formally, seals pertain to *Incorporated Results*, not blocks. Typically, we have a block B and all ENs publishing the + // same result r[B] for block B. Consensus nodes then record r[B] in the child blocks of B - exactly once in each fork (simplified). + // So just by the main chain forking, there can be multiple valid incorporated results for the same block. Note that we treat all seals + // for the same block as equivalent (they may differ in which verifiers signed). We have the following one-to-many relationships: + // block (one) <--> (many) incorporated results + // and incorporated result (one) <--> single seal as representative of equivalence class (mempool drops duplicates) + // + // CAUTION: sealsForBlock is a SUPERSET of IncorporatedResults the wrapped pool considers includable (see struct-level documentation). + irIDs, found := s.sealsForBlock[blockID] if !found { // no other seal for this block was in mempool before => create a set for the seals for this block - blockSeals = make(sealSet) - s.sealsForBlock[blockID] = blockSeals + irIDs = make(potentiallySealableResults) + s.sealsForBlock[blockID] = irIDs } - blockSeals[newSeal.IncorporatedResultID()] = newSeal + irIDs[newSeal.IncorporatedResultID()] = struct{}{} // cache block height to prune additional index by height blocksAtHeight, found := s.byHeight[newSeal.Header.Height] @@ -164,8 +208,7 @@ func (s *ExecForkSuppressor) All() []*flow.IncorporatedResultSeal { seals := s.seals.All() s.mutex.RUnlock() - // index seals retrieved from underlying mepool by blockID to check - // for conflicting seals + // index seals retrieved from underlying mempool by blockID to check for conflicting seals sealsByBlockID := make(map[flow.Identifier]sealsList, 0) for _, seal := range seals { sealsPerBlock := sealsByBlockID[seal.Seal.BlockID] @@ -177,10 +220,12 @@ func (s *ExecForkSuppressor) All() []*flow.IncorporatedResultSeal { } // Get returns an IncorporatedResultSeal by IncorporatedResult's ID. -// This call essentially is to find the seal for the incorporated result in the mempool. -// Note: This call might crash if the block of the seal has multiple seals in mempool for conflicting -// incorporated results. Usually the builder will call this method to find a seal for an incorporated -// result, so the builder might crash if multiple conflicting seals exist. +// The wrapped pool's Get is used as the source of truth: it only returns seals satisfying +// the pool's inclusion conditions (e.g., sufficient execution receipts). +// For fork detection, we retrieve candidate seal IDs for the same block from sealsForBlock, +// then filter each through the wrapped pool to obtain only includable seals for conflict checking. +// Note: This call might crash if the block of the seal has multiple includable seals in +// mempool for conflicting incorporated results. func (s *ExecForkSuppressor) Get(identifier flow.Identifier) (*flow.IncorporatedResultSeal, bool) { s.mutex.RLock() seal, found := s.seals.Get(identifier) @@ -189,16 +234,21 @@ func (s *ExecForkSuppressor) Get(identifier flow.Identifier) (*flow.Incorporated s.mutex.RUnlock() return seal, found } - sealsForBlock := s.sealsForBlock[seal.Seal.BlockID] - // if there are no other seals for this block previously seen - then no possible execution forks - if len(sealsForBlock) == 1 { + irIDs := s.sealsForBlock[seal.Seal.BlockID] + if len(irIDs) == 1 { + // only one IncorporatedResult known for this block => no possible execution fork s.mutex.RUnlock() return seal, true } - // convert map into list + // Multiple IncorporatedResults recorded for this block, the seals for some of which might not qualify yet for + // inclusion and may be withheld by the lower-level wrappers. We limit our fork detection to incorporated results + // whose seals actually qualify for inclusion ; we don't want to trigger on forks, whose sealing is suppressed + // by lower-level wrappers. var sealsPerBlock sealsList - for _, otherSeal := range sealsForBlock { - sealsPerBlock = append(sealsPerBlock, otherSeal) + for id := range irIDs { + if candidateSeal, ok := s.seals.Get(id); ok { + sealsPerBlock = append(sealsPerBlock, candidateSeal) + } } s.mutex.RUnlock() @@ -252,7 +302,7 @@ func (s *ExecForkSuppressor) Limit() uint { func (s *ExecForkSuppressor) Clear() { s.mutex.Lock() defer s.mutex.Unlock() - s.sealsForBlock = make(map[flow.Identifier]sealSet) + s.sealsForBlock = make(map[flow.Identifier]potentiallySealableResults) s.seals.Clear() } @@ -316,14 +366,9 @@ func (s *ExecForkSuppressor) enforceValidChunks(irSeal *flow.IncorporatedResultS return nil } -// enforceConsistentStateTransitions checks whether the execution results in the seals -// have matching state transitions. If a fork in the execution state is detected: -// - wrapped mempool is cleared -// - internal execForkDetected flag is ste to true -// - the new value of execForkDetected is persisted to data base -// -// and executionForkErr (sentinel error) is returned -// The function assumes the execution results in the seals have a non-zero number of chunks. +// hasConsistentStateTransitions checks whether the state transitions of the two seals are consistent. +// Two seals have consistent state transitions iff they reference the same initial and final state. +// Pre-requisite: execution results in both seals have a non-zero number of chunks. func hasConsistentStateTransitions(irSeal, irSeal2 *flow.IncorporatedResultSeal) bool { if irSeal.IncorporatedResult.Result.ID() == irSeal2.IncorporatedResult.Result.ID() { // happy case: candidate seals are for the same result @@ -346,17 +391,32 @@ func hasConsistentStateTransitions(irSeal, irSeal2 *flow.IncorporatedResultSeal) return true } -// filterConflictingSeals performs filtering of provided seals by checking if there are conflicting seals for same block. -// For every block we check if first seal has same state transitions as others. Multiple seals for same block are allowed -// but their state transitions should be the same. Upon detecting seal with inconsistent state transition we will clear our mempool, -// stop accepting new seals and querying old seals and store execution fork evidence into DB. Creator of mempool will be notified -// by callback. +// filterConflictingSeals checks the provided seals for conflicting state transitions per block. +// +// CAUTION: All input seals must be eligible for including (i.e. not held back by lower-level mempool wrappers). +// Multiple seals for the same block are allowed as long as their state transitions are consistent. +// Upon detecting an inconsistent state transition, the mempool is cleared, the execForkDetected flag is set, +// evidence is persisted to the DB, and the onExecFork callback is invoked. +// +// CONTEXT: By necessity of the mature protocol, the core mempool allows adding multiple seals for the same blockID but is oblivious to +// whether they have different state transitions. This is because: +// In the mature protocol, during severe network partitions, chunks may get temporarily lost and execution nodes may become temporarily +// unreachable. At first, this can be indistinguishable from a byzantine attack where a collector cluster withholds a collection. The +// network will proceed and attempt to restore liveness of execution by declaring the collection as lost, allowing the remaining ENs to +// continue without it. If the network partition resolves at this point, two valid seals might temporarily co-exist. Choosing either at +// random would be valid for the mature protocol, but *not* for now, where forks are likely still just code bugs in the ENs. +// +// On the happy path, incorporated results for the same block all commit to the same final state. In contrast, accidental +// execution forks (due to bugs) typically differ in the final state. Hence we use this as a simplified heuristic, assuming +// different events or metadata necessitate different end states. Fork detection is deferred to query time +// (not add time) because the wrapped mempool may apply additional inclusion conditions that change over time. +// For instance, the wrapped pool might only consider a seal includable once sufficient execution receipts exist. +// Fork detection should only trigger for seals that are actually includable. func (s *ExecForkSuppressor) filterConflictingSeals(sealsByBlockID map[flow.Identifier]sealsList) sealsList { var result sealsList for _, sealsInBlock := range sealsByBlockID { if len(sealsInBlock) > 1 { - // enforce that newSeal's state transition does not conflict with other stored seals for the same block - // already other seal for this block in mempool => compare consistency of results' state transitions + // check whether sealed results all commit to the same state transition: var conflictingSeals sealsList candidateSeal := sealsInBlock[0] for _, otherSeal := range sealsInBlock[1:] { diff --git a/module/mempool/consensus/exec_fork_suppressor_test.go b/module/mempool/consensus/exec_fork_suppressor_test.go index 546867b5c7a..a4d565402a1 100644 --- a/module/mempool/consensus/exec_fork_suppressor_test.go +++ b/module/mempool/consensus/exec_fork_suppressor_test.go @@ -234,7 +234,11 @@ func Test_ConflictingResults(t *testing.T) { }) t.Run("by-id-query", func(t *testing.T) { assertConflictingResult(t, func(irSeals []*flow.IncorporatedResultSeal, conflictingSeal *flow.IncorporatedResultSeal, wrapper *ExecForkSuppressor, wrappedMempool *poolmock.IncorporatedResultSeals) { - wrappedMempool.On("Get", conflictingSeal.IncorporatedResultID()).Return(conflictingSeal, true).Once() + // Get is called once for the initial lookup plus once per seal in sealsForBlock + // (to filter inclusion candidates). conflictingSeal is looked up twice total. + wrappedMempool.On("Get", conflictingSeal.IncorporatedResultID()).Return(conflictingSeal, true).Twice() + // irSeals[1] shares the same block as conflictingSeal + wrappedMempool.On("Get", irSeals[1].IncorporatedResultID()).Return(irSeals[1], true).Once() byID, found := wrapper.Get(conflictingSeal.IncorporatedResultID()) require.False(t, found) require.Nil(t, byID) @@ -271,7 +275,10 @@ func Test_ForkDetectionPersisted(t *testing.T) { added, _ := wrapper.Add(sealB) // should be rejected because it is conflicting with sealA require.True(t, added) - wrappedMempool.On("Get", sealA.IncorporatedResultID()).Return(sealA, true).Once() + // Get is called once for the initial lookup, plus once per seal in sealsForBlock + // (to filter inclusion candidates). sealA is looked up twice total. + wrappedMempool.On("Get", sealA.IncorporatedResultID()).Return(sealA, true).Twice() + wrappedMempool.On("Get", sealB.IncorporatedResultID()).Return(sealB, true).Once() execForkActor.On("OnExecFork", mock.Anything).Run(func(args mock.Arguments) { conflictingSeals := args.Get(0).([]*flow.IncorporatedResultSeal) require.ElementsMatch(t, []*flow.IncorporatedResultSeal{sealA, sealB}, conflictingSeals) diff --git a/module/mempool/consensus/incorporated_result_seals.go b/module/mempool/consensus/incorporated_result_seals.go index 575405116cd..220c6ee890f 100644 --- a/module/mempool/consensus/incorporated_result_seals.go +++ b/module/mempool/consensus/incorporated_result_seals.go @@ -46,7 +46,7 @@ func (ir *IncorporatedResultSeals) All() []*flow.IncorporatedResultSeal { } // resultHasMultipleReceipts implements an additional _temporary_ safety measure: -// only consider incorporatedResult sealable if there are at AT LEAST 2 RECEIPTS +// only consider incorporatedResult sealable if there are AT LEAST 2 RECEIPTS // from _different_ ENs committing to the result. func (ir *IncorporatedResultSeals) resultHasMultipleReceipts(incorporatedResult *flow.IncorporatedResult) bool { blockID := incorporatedResult.Result.BlockID // block that was computed diff --git a/module/mempool/consensus/mock/exec_fork_actor.go b/module/mempool/consensus/mock/exec_fork_actor.go index 5f18410cfc7..602e7cdd66c 100644 --- a/module/mempool/consensus/mock/exec_fork_actor.go +++ b/module/mempool/consensus/mock/exec_fork_actor.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) -// ExecForkActor is an autogenerated mock type for the ExecForkActor type -type ExecForkActor struct { - mock.Mock -} - -// OnExecFork provides a mock function with given fields: _a0 -func (_m *ExecForkActor) OnExecFork(_a0 []*flow.IncorporatedResultSeal) { - _m.Called(_a0) -} - // NewExecForkActor creates a new instance of ExecForkActor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewExecForkActor(t interface { @@ -30,3 +22,56 @@ func NewExecForkActor(t interface { return mock } + +// ExecForkActor is an autogenerated mock type for the ExecForkActor type +type ExecForkActor struct { + mock.Mock +} + +type ExecForkActor_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecForkActor) EXPECT() *ExecForkActor_Expecter { + return &ExecForkActor_Expecter{mock: &_m.Mock} +} + +// OnExecFork provides a mock function for the type ExecForkActor +func (_mock *ExecForkActor) OnExecFork(incorporatedResultSeals []*flow.IncorporatedResultSeal) { + _mock.Called(incorporatedResultSeals) + return +} + +// ExecForkActor_OnExecFork_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnExecFork' +type ExecForkActor_OnExecFork_Call struct { + *mock.Call +} + +// OnExecFork is a helper method to define mock.On call +// - incorporatedResultSeals []*flow.IncorporatedResultSeal +func (_e *ExecForkActor_Expecter) OnExecFork(incorporatedResultSeals interface{}) *ExecForkActor_OnExecFork_Call { + return &ExecForkActor_OnExecFork_Call{Call: _e.mock.On("OnExecFork", incorporatedResultSeals)} +} + +func (_c *ExecForkActor_OnExecFork_Call) Run(run func(incorporatedResultSeals []*flow.IncorporatedResultSeal)) *ExecForkActor_OnExecFork_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []*flow.IncorporatedResultSeal + if args[0] != nil { + arg0 = args[0].([]*flow.IncorporatedResultSeal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecForkActor_OnExecFork_Call) Return() *ExecForkActor_OnExecFork_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecForkActor_OnExecFork_Call) RunAndReturn(run func(incorporatedResultSeals []*flow.IncorporatedResultSeal)) *ExecForkActor_OnExecFork_Call { + _c.Run(run) + return _c +} diff --git a/module/mempool/errors.go b/module/mempool/errors.go index 1dec04c84f8..addd2152e45 100644 --- a/module/mempool/errors.go +++ b/module/mempool/errors.go @@ -10,7 +10,7 @@ type UnknownExecutionResultError struct { err error } -func NewUnknownExecutionResultErrorf(msg string, args ...interface{}) error { +func NewUnknownExecutionResultErrorf(msg string, args ...any) error { return UnknownExecutionResultError{ err: fmt.Errorf(msg, args...), } @@ -37,7 +37,7 @@ type BelowPrunedThresholdError struct { err error } -func NewBelowPrunedThresholdErrorf(msg string, args ...interface{}) error { +func NewBelowPrunedThresholdErrorf(msg string, args ...any) error { return BelowPrunedThresholdError{ err: fmt.Errorf(msg, args...), } diff --git a/module/mempool/incorporated_result_seals.go b/module/mempool/incorporated_result_seals.go index 50711b63b5a..44b73f4ecc5 100644 --- a/module/mempool/incorporated_result_seals.go +++ b/module/mempool/incorporated_result_seals.go @@ -7,7 +7,9 @@ import ( // IncorporatedResultSeals represents a concurrency safe memory pool for // incorporated result seals. type IncorporatedResultSeals interface { - // Add adds an IncorporatedResultSeal to the mempool. + // Add adds an IncorporatedResultSeal to the mempool. The method returns true if the seal was added to the mempool, + // and false if it was a duplicate (dropped). The seal is considered a duplicate if and only if a seal for the same + // IncorporatedResult ID is already present in the mempool. Add(irSeal *flow.IncorporatedResultSeal) (bool, error) // All returns all the IncorporatedResultSeals in the mempool. diff --git a/module/mempool/mock/assignments.go b/module/mempool/mock/assignments.go index cb30939359f..e0ff26b1386 100644 --- a/module/mempool/mock/assignments.go +++ b/module/mempool/mock/assignments.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - chunks "github.com/onflow/flow-go/model/chunks" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/chunks" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewAssignments creates a new instance of Assignments. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAssignments(t interface { + mock.TestingT + Cleanup(func()) +}) *Assignments { + mock := &Assignments{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Assignments is an autogenerated mock type for the Assignments type type Assignments struct { mock.Mock } -// Add provides a mock function with given fields: _a0, _a1 -func (_m *Assignments) Add(_a0 flow.Identifier, _a1 *chunks.Assignment) bool { - ret := _m.Called(_a0, _a1) +type Assignments_Expecter struct { + mock *mock.Mock +} + +func (_m *Assignments) EXPECT() *Assignments_Expecter { + return &Assignments_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type Assignments +func (_mock *Assignments) Add(identifier flow.Identifier, assignment *chunks.Assignment) bool { + ret := _mock.Called(identifier, assignment) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, *chunks.Assignment) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, *chunks.Assignment) bool); ok { + r0 = returnFunc(identifier, assignment) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *Assignments) Adjust(key flow.Identifier, f func(*chunks.Assignment) *chunks.Assignment) (*chunks.Assignment, bool) { - ret := _m.Called(key, f) +// Assignments_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type Assignments_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - identifier flow.Identifier +// - assignment *chunks.Assignment +func (_e *Assignments_Expecter) Add(identifier interface{}, assignment interface{}) *Assignments_Add_Call { + return &Assignments_Add_Call{Call: _e.mock.On("Add", identifier, assignment)} +} + +func (_c *Assignments_Add_Call) Run(run func(identifier flow.Identifier, assignment *chunks.Assignment)) *Assignments_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 *chunks.Assignment + if args[1] != nil { + arg1 = args[1].(*chunks.Assignment) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Assignments_Add_Call) Return(b bool) *Assignments_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Assignments_Add_Call) RunAndReturn(run func(identifier flow.Identifier, assignment *chunks.Assignment) bool) *Assignments_Add_Call { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type Assignments +func (_mock *Assignments) Adjust(key flow.Identifier, f func(*chunks.Assignment) *chunks.Assignment) (*chunks.Assignment, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -42,54 +104,146 @@ func (_m *Assignments) Adjust(key flow.Identifier, f func(*chunks.Assignment) *c var r0 *chunks.Assignment var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*chunks.Assignment) *chunks.Assignment) (*chunks.Assignment, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*chunks.Assignment) *chunks.Assignment) (*chunks.Assignment, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*chunks.Assignment) *chunks.Assignment) *chunks.Assignment); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*chunks.Assignment) *chunks.Assignment) *chunks.Assignment); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*chunks.Assignment) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, func(*chunks.Assignment) *chunks.Assignment) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, func(*chunks.Assignment) *chunks.Assignment) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *Assignments) All() map[flow.Identifier]*chunks.Assignment { - ret := _m.Called() +// Assignments_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type Assignments_Adjust_Call struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key flow.Identifier +// - f func(*chunks.Assignment) *chunks.Assignment +func (_e *Assignments_Expecter) Adjust(key interface{}, f interface{}) *Assignments_Adjust_Call { + return &Assignments_Adjust_Call{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *Assignments_Adjust_Call) Run(run func(key flow.Identifier, f func(*chunks.Assignment) *chunks.Assignment)) *Assignments_Adjust_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 func(*chunks.Assignment) *chunks.Assignment + if args[1] != nil { + arg1 = args[1].(func(*chunks.Assignment) *chunks.Assignment) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Assignments_Adjust_Call) Return(assignment *chunks.Assignment, b bool) *Assignments_Adjust_Call { + _c.Call.Return(assignment, b) + return _c +} + +func (_c *Assignments_Adjust_Call) RunAndReturn(run func(key flow.Identifier, f func(*chunks.Assignment) *chunks.Assignment) (*chunks.Assignment, bool)) *Assignments_Adjust_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type Assignments +func (_mock *Assignments) All() map[flow.Identifier]*chunks.Assignment { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[flow.Identifier]*chunks.Assignment - if rf, ok := ret.Get(0).(func() map[flow.Identifier]*chunks.Assignment); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[flow.Identifier]*chunks.Assignment); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[flow.Identifier]*chunks.Assignment) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *Assignments) Clear() { - _m.Called() +// Assignments_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type Assignments_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *Assignments_Expecter) All() *Assignments_All_Call { + return &Assignments_All_Call{Call: _e.mock.On("All")} +} + +func (_c *Assignments_All_Call) Run(run func()) *Assignments_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Assignments_All_Call) Return(identifierToAssignment map[flow.Identifier]*chunks.Assignment) *Assignments_All_Call { + _c.Call.Return(identifierToAssignment) + return _c +} + +func (_c *Assignments_All_Call) RunAndReturn(run func() map[flow.Identifier]*chunks.Assignment) *Assignments_All_Call { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type Assignments +func (_mock *Assignments) Clear() { + _mock.Called() + return +} + +// Assignments_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type Assignments_Clear_Call struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *Assignments_Expecter) Clear() *Assignments_Clear_Call { + return &Assignments_Clear_Call{Call: _e.mock.On("Clear")} +} + +func (_c *Assignments_Clear_Call) Run(run func()) *Assignments_Clear_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Assignments_Clear_Call) Return() *Assignments_Clear_Call { + _c.Call.Return() + return _c +} + +func (_c *Assignments_Clear_Call) RunAndReturn(run func()) *Assignments_Clear_Call { + _c.Run(run) + return _c } -// Get provides a mock function with given fields: _a0 -func (_m *Assignments) Get(_a0 flow.Identifier) (*chunks.Assignment, bool) { - ret := _m.Called(_a0) +// Get provides a mock function for the type Assignments +func (_mock *Assignments) Get(identifier flow.Identifier) (*chunks.Assignment, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Get") @@ -97,110 +251,246 @@ func (_m *Assignments) Get(_a0 flow.Identifier) (*chunks.Assignment, bool) { var r0 *chunks.Assignment var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*chunks.Assignment, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*chunks.Assignment, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *chunks.Assignment); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *chunks.Assignment); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*chunks.Assignment) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: _a0 -func (_m *Assignments) Has(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// Assignments_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Assignments_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Assignments_Expecter) Get(identifier interface{}) *Assignments_Get_Call { + return &Assignments_Get_Call{Call: _e.mock.On("Get", identifier)} +} + +func (_c *Assignments_Get_Call) Run(run func(identifier flow.Identifier)) *Assignments_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Assignments_Get_Call) Return(assignment *chunks.Assignment, b bool) *Assignments_Get_Call { + _c.Call.Return(assignment, b) + return _c +} + +func (_c *Assignments_Get_Call) RunAndReturn(run func(identifier flow.Identifier) (*chunks.Assignment, bool)) *Assignments_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type Assignments +func (_mock *Assignments) Has(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Remove provides a mock function with given fields: _a0 -func (_m *Assignments) Remove(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// Assignments_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type Assignments_Has_Call struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Assignments_Expecter) Has(identifier interface{}) *Assignments_Has_Call { + return &Assignments_Has_Call{Call: _e.mock.On("Has", identifier)} +} + +func (_c *Assignments_Has_Call) Run(run func(identifier flow.Identifier)) *Assignments_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Assignments_Has_Call) Return(b bool) *Assignments_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Assignments_Has_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *Assignments_Has_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type Assignments +func (_mock *Assignments) Remove(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *Assignments) Size() uint { - ret := _m.Called() +// Assignments_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type Assignments_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Assignments_Expecter) Remove(identifier interface{}) *Assignments_Remove_Call { + return &Assignments_Remove_Call{Call: _e.mock.On("Remove", identifier)} +} + +func (_c *Assignments_Remove_Call) Run(run func(identifier flow.Identifier)) *Assignments_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Assignments_Remove_Call) Return(b bool) *Assignments_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Assignments_Remove_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *Assignments_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type Assignments +func (_mock *Assignments) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *Assignments) Values() []*chunks.Assignment { - ret := _m.Called() +// Assignments_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type Assignments_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *Assignments_Expecter) Size() *Assignments_Size_Call { + return &Assignments_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *Assignments_Size_Call) Run(run func()) *Assignments_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Assignments_Size_Call) Return(v uint) *Assignments_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Assignments_Size_Call) RunAndReturn(run func() uint) *Assignments_Size_Call { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type Assignments +func (_mock *Assignments) Values() []*chunks.Assignment { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []*chunks.Assignment - if rf, ok := ret.Get(0).(func() []*chunks.Assignment); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*chunks.Assignment); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*chunks.Assignment) } } - return r0 } -// NewAssignments creates a new instance of Assignments. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAssignments(t interface { - mock.TestingT - Cleanup(func()) -}) *Assignments { - mock := &Assignments{} - mock.Mock.Test(t) +// Assignments_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type Assignments_Values_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *Assignments_Expecter) Values() *Assignments_Values_Call { + return &Assignments_Values_Call{Call: _e.mock.On("Values")} +} - return mock +func (_c *Assignments_Values_Call) Run(run func()) *Assignments_Values_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Assignments_Values_Call) Return(assignments []*chunks.Assignment) *Assignments_Values_Call { + _c.Call.Return(assignments) + return _c +} + +func (_c *Assignments_Values_Call) RunAndReturn(run func() []*chunks.Assignment) *Assignments_Values_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/back_data.go b/module/mempool/mock/back_data.go index 2f1a3b8c3a2..1c1ce3a5e0f 100644 --- a/module/mempool/mock/back_data.go +++ b/module/mempool/mock/back_data.go @@ -1,60 +1,179 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewBackData creates a new instance of BackData. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBackData[K comparable, V any](t interface { + mock.TestingT + Cleanup(func()) +}) *BackData[K, V] { + mock := &BackData[K, V]{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // BackData is an autogenerated mock type for the BackData type type BackData[K comparable, V any] struct { mock.Mock } -// Add provides a mock function with given fields: key, value -func (_m *BackData[K, V]) Add(key K, value V) bool { - ret := _m.Called(key, value) +type BackData_Expecter[K comparable, V any] struct { + mock *mock.Mock +} + +func (_m *BackData[K, V]) EXPECT() *BackData_Expecter[K, V] { + return &BackData_Expecter[K, V]{mock: &_m.Mock} +} + +// Add provides a mock function for the type BackData +func (_mock *BackData[K, V]) Add(key K, value V) bool { + ret := _mock.Called(key, value) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(K, V) bool); ok { - r0 = rf(key, value) + if returnFunc, ok := ret.Get(0).(func(K, V) bool); ok { + r0 = returnFunc(key, value) } else { r0 = ret.Get(0).(bool) } - return r0 } -// All provides a mock function with no fields -func (_m *BackData[K, V]) All() map[K]V { - ret := _m.Called() +// BackData_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type BackData_Add_Call[K comparable, V any] struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - key K +// - value V +func (_e *BackData_Expecter[K, V]) Add(key interface{}, value interface{}) *BackData_Add_Call[K, V] { + return &BackData_Add_Call[K, V]{Call: _e.mock.On("Add", key, value)} +} + +func (_c *BackData_Add_Call[K, V]) Run(run func(key K, value V)) *BackData_Add_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + var arg1 V + if args[1] != nil { + arg1 = args[1].(V) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BackData_Add_Call[K, V]) Return(b bool) *BackData_Add_Call[K, V] { + _c.Call.Return(b) + return _c +} + +func (_c *BackData_Add_Call[K, V]) RunAndReturn(run func(key K, value V) bool) *BackData_Add_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type BackData +func (_mock *BackData[K, V]) All() map[K]V { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[K]V - if rf, ok := ret.Get(0).(func() map[K]V); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[K]V); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[K]V) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *BackData[K, V]) Clear() { - _m.Called() +// BackData_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type BackData_All_Call[K comparable, V any] struct { + *mock.Call } -// Get provides a mock function with given fields: key -func (_m *BackData[K, V]) Get(key K) (V, bool) { - ret := _m.Called(key) +// All is a helper method to define mock.On call +func (_e *BackData_Expecter[K, V]) All() *BackData_All_Call[K, V] { + return &BackData_All_Call[K, V]{Call: _e.mock.On("All")} +} + +func (_c *BackData_All_Call[K, V]) Run(run func()) *BackData_All_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackData_All_Call[K, V]) Return(vToV map[K]V) *BackData_All_Call[K, V] { + _c.Call.Return(vToV) + return _c +} + +func (_c *BackData_All_Call[K, V]) RunAndReturn(run func() map[K]V) *BackData_All_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type BackData +func (_mock *BackData[K, V]) Clear() { + _mock.Called() + return +} + +// BackData_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type BackData_Clear_Call[K comparable, V any] struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *BackData_Expecter[K, V]) Clear() *BackData_Clear_Call[K, V] { + return &BackData_Clear_Call[K, V]{Call: _e.mock.On("Clear")} +} + +func (_c *BackData_Clear_Call[K, V]) Run(run func()) *BackData_Clear_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackData_Clear_Call[K, V]) Return() *BackData_Clear_Call[K, V] { + _c.Call.Return() + return _c +} + +func (_c *BackData_Clear_Call[K, V]) RunAndReturn(run func()) *BackData_Clear_Call[K, V] { + _c.Run(run) + return _c +} + +// Get provides a mock function for the type BackData +func (_mock *BackData[K, V]) Get(key K) (V, bool) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Get") @@ -62,67 +181,158 @@ func (_m *BackData[K, V]) Get(key K) (V, bool) { var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K) (V, bool)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func(K) (V, bool)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func(K) V); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(K) V); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K) bool); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func(K) bool); ok { + r1 = returnFunc(key) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: key -func (_m *BackData[K, V]) Has(key K) bool { - ret := _m.Called(key) +// BackData_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type BackData_Get_Call[K comparable, V any] struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - key K +func (_e *BackData_Expecter[K, V]) Get(key interface{}) *BackData_Get_Call[K, V] { + return &BackData_Get_Call[K, V]{Call: _e.mock.On("Get", key)} +} + +func (_c *BackData_Get_Call[K, V]) Run(run func(key K)) *BackData_Get_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BackData_Get_Call[K, V]) Return(v V, b bool) *BackData_Get_Call[K, V] { + _c.Call.Return(v, b) + return _c +} + +func (_c *BackData_Get_Call[K, V]) RunAndReturn(run func(key K) (V, bool)) *BackData_Get_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type BackData +func (_mock *BackData[K, V]) Has(key K) bool { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(K) bool); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(K) bool); ok { + r0 = returnFunc(key) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Keys provides a mock function with no fields -func (_m *BackData[K, V]) Keys() []K { - ret := _m.Called() +// BackData_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type BackData_Has_Call[K comparable, V any] struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - key K +func (_e *BackData_Expecter[K, V]) Has(key interface{}) *BackData_Has_Call[K, V] { + return &BackData_Has_Call[K, V]{Call: _e.mock.On("Has", key)} +} + +func (_c *BackData_Has_Call[K, V]) Run(run func(key K)) *BackData_Has_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BackData_Has_Call[K, V]) Return(b bool) *BackData_Has_Call[K, V] { + _c.Call.Return(b) + return _c +} + +func (_c *BackData_Has_Call[K, V]) RunAndReturn(run func(key K) bool) *BackData_Has_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Keys provides a mock function for the type BackData +func (_mock *BackData[K, V]) Keys() []K { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Keys") } var r0 []K - if rf, ok := ret.Get(0).(func() []K); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []K); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]K) } } - return r0 } -// Remove provides a mock function with given fields: key -func (_m *BackData[K, V]) Remove(key K) (V, bool) { - ret := _m.Called(key) +// BackData_Keys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Keys' +type BackData_Keys_Call[K comparable, V any] struct { + *mock.Call +} + +// Keys is a helper method to define mock.On call +func (_e *BackData_Expecter[K, V]) Keys() *BackData_Keys_Call[K, V] { + return &BackData_Keys_Call[K, V]{Call: _e.mock.On("Keys")} +} + +func (_c *BackData_Keys_Call[K, V]) Run(run func()) *BackData_Keys_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackData_Keys_Call[K, V]) Return(vs []K) *BackData_Keys_Call[K, V] { + _c.Call.Return(vs) + return _c +} + +func (_c *BackData_Keys_Call[K, V]) RunAndReturn(run func() []K) *BackData_Keys_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type BackData +func (_mock *BackData[K, V]) Remove(key K) (V, bool) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Remove") @@ -130,74 +340,144 @@ func (_m *BackData[K, V]) Remove(key K) (V, bool) { var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K) (V, bool)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func(K) (V, bool)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func(K) V); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(K) V); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K) bool); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func(K) bool); ok { + r1 = returnFunc(key) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Size provides a mock function with no fields -func (_m *BackData[K, V]) Size() uint { - ret := _m.Called() +// BackData_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type BackData_Remove_Call[K comparable, V any] struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - key K +func (_e *BackData_Expecter[K, V]) Remove(key interface{}) *BackData_Remove_Call[K, V] { + return &BackData_Remove_Call[K, V]{Call: _e.mock.On("Remove", key)} +} + +func (_c *BackData_Remove_Call[K, V]) Run(run func(key K)) *BackData_Remove_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BackData_Remove_Call[K, V]) Return(v V, b bool) *BackData_Remove_Call[K, V] { + _c.Call.Return(v, b) + return _c +} + +func (_c *BackData_Remove_Call[K, V]) RunAndReturn(run func(key K) (V, bool)) *BackData_Remove_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type BackData +func (_mock *BackData[K, V]) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *BackData[K, V]) Values() []V { - ret := _m.Called() +// BackData_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type BackData_Size_Call[K comparable, V any] struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *BackData_Expecter[K, V]) Size() *BackData_Size_Call[K, V] { + return &BackData_Size_Call[K, V]{Call: _e.mock.On("Size")} +} + +func (_c *BackData_Size_Call[K, V]) Run(run func()) *BackData_Size_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackData_Size_Call[K, V]) Return(v uint) *BackData_Size_Call[K, V] { + _c.Call.Return(v) + return _c +} + +func (_c *BackData_Size_Call[K, V]) RunAndReturn(run func() uint) *BackData_Size_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type BackData +func (_mock *BackData[K, V]) Values() []V { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []V - if rf, ok := ret.Get(0).(func() []V); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []V); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]V) } } - return r0 } -// NewBackData creates a new instance of BackData. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBackData[K comparable, V any](t interface { - mock.TestingT - Cleanup(func()) -}) *BackData[K, V] { - mock := &BackData[K, V]{} - mock.Mock.Test(t) +// BackData_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type BackData_Values_Call[K comparable, V any] struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *BackData_Expecter[K, V]) Values() *BackData_Values_Call[K, V] { + return &BackData_Values_Call[K, V]{Call: _e.mock.On("Values")} +} - return mock +func (_c *BackData_Values_Call[K, V]) Run(run func()) *BackData_Values_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackData_Values_Call[K, V]) Return(vs []V) *BackData_Values_Call[K, V] { + _c.Call.Return(vs) + return _c +} + +func (_c *BackData_Values_Call[K, V]) RunAndReturn(run func() []V) *BackData_Values_Call[K, V] { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/chunk_requests.go b/module/mempool/mock/chunk_requests.go index b98ed91e624..404e3977586 100644 --- a/module/mempool/mock/chunk_requests.go +++ b/module/mempool/mock/chunk_requests.go @@ -1,84 +1,197 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - chunks "github.com/onflow/flow-go/model/chunks" - flow "github.com/onflow/flow-go/model/flow" - - mempool "github.com/onflow/flow-go/module/mempool" + "time" + "github.com/onflow/flow-go/model/chunks" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/verification" + "github.com/onflow/flow-go/module/mempool" mock "github.com/stretchr/testify/mock" +) + +// NewChunkRequests creates a new instance of ChunkRequests. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChunkRequests(t interface { + mock.TestingT + Cleanup(func()) +}) *ChunkRequests { + mock := &ChunkRequests{} + mock.Mock.Test(t) - time "time" + t.Cleanup(func() { mock.AssertExpectations(t) }) - verification "github.com/onflow/flow-go/model/verification" -) + return mock +} // ChunkRequests is an autogenerated mock type for the ChunkRequests type type ChunkRequests struct { mock.Mock } -// Add provides a mock function with given fields: request -func (_m *ChunkRequests) Add(request *verification.ChunkDataPackRequest) bool { - ret := _m.Called(request) +type ChunkRequests_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunkRequests) EXPECT() *ChunkRequests_Expecter { + return &ChunkRequests_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) Add(request *verification.ChunkDataPackRequest) bool { + ret := _mock.Called(request) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(*verification.ChunkDataPackRequest) bool); ok { - r0 = rf(request) + if returnFunc, ok := ret.Get(0).(func(*verification.ChunkDataPackRequest) bool); ok { + r0 = returnFunc(request) } else { r0 = ret.Get(0).(bool) } - return r0 } -// All provides a mock function with no fields -func (_m *ChunkRequests) All() verification.ChunkDataPackRequestInfoList { - ret := _m.Called() +// ChunkRequests_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type ChunkRequests_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - request *verification.ChunkDataPackRequest +func (_e *ChunkRequests_Expecter) Add(request interface{}) *ChunkRequests_Add_Call { + return &ChunkRequests_Add_Call{Call: _e.mock.On("Add", request)} +} + +func (_c *ChunkRequests_Add_Call) Run(run func(request *verification.ChunkDataPackRequest)) *ChunkRequests_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *verification.ChunkDataPackRequest + if args[0] != nil { + arg0 = args[0].(*verification.ChunkDataPackRequest) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkRequests_Add_Call) Return(b bool) *ChunkRequests_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ChunkRequests_Add_Call) RunAndReturn(run func(request *verification.ChunkDataPackRequest) bool) *ChunkRequests_Add_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) All() verification.ChunkDataPackRequestInfoList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 verification.ChunkDataPackRequestInfoList - if rf, ok := ret.Get(0).(func() verification.ChunkDataPackRequestInfoList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() verification.ChunkDataPackRequestInfoList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(verification.ChunkDataPackRequestInfoList) } } - return r0 } -// IncrementAttempt provides a mock function with given fields: chunkID -func (_m *ChunkRequests) IncrementAttempt(chunkID flow.Identifier) bool { - ret := _m.Called(chunkID) +// ChunkRequests_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ChunkRequests_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *ChunkRequests_Expecter) All() *ChunkRequests_All_Call { + return &ChunkRequests_All_Call{Call: _e.mock.On("All")} +} + +func (_c *ChunkRequests_All_Call) Run(run func()) *ChunkRequests_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunkRequests_All_Call) Return(chunkDataPackRequestInfoList verification.ChunkDataPackRequestInfoList) *ChunkRequests_All_Call { + _c.Call.Return(chunkDataPackRequestInfoList) + return _c +} + +func (_c *ChunkRequests_All_Call) RunAndReturn(run func() verification.ChunkDataPackRequestInfoList) *ChunkRequests_All_Call { + _c.Call.Return(run) + return _c +} + +// IncrementAttempt provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) IncrementAttempt(chunkID flow.Identifier) bool { + ret := _mock.Called(chunkID) if len(ret) == 0 { panic("no return value specified for IncrementAttempt") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(chunkID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// PopAll provides a mock function with given fields: chunkID -func (_m *ChunkRequests) PopAll(chunkID flow.Identifier) (chunks.LocatorMap, bool) { - ret := _m.Called(chunkID) +// ChunkRequests_IncrementAttempt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IncrementAttempt' +type ChunkRequests_IncrementAttempt_Call struct { + *mock.Call +} + +// IncrementAttempt is a helper method to define mock.On call +// - chunkID flow.Identifier +func (_e *ChunkRequests_Expecter) IncrementAttempt(chunkID interface{}) *ChunkRequests_IncrementAttempt_Call { + return &ChunkRequests_IncrementAttempt_Call{Call: _e.mock.On("IncrementAttempt", chunkID)} +} + +func (_c *ChunkRequests_IncrementAttempt_Call) Run(run func(chunkID flow.Identifier)) *ChunkRequests_IncrementAttempt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkRequests_IncrementAttempt_Call) Return(b bool) *ChunkRequests_IncrementAttempt_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ChunkRequests_IncrementAttempt_Call) RunAndReturn(run func(chunkID flow.Identifier) bool) *ChunkRequests_IncrementAttempt_Call { + _c.Call.Return(run) + return _c +} + +// PopAll provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) PopAll(chunkID flow.Identifier) (chunks.LocatorMap, bool) { + ret := _mock.Called(chunkID) if len(ret) == 0 { panic("no return value specified for PopAll") @@ -86,47 +199,112 @@ func (_m *ChunkRequests) PopAll(chunkID flow.Identifier) (chunks.LocatorMap, boo var r0 chunks.LocatorMap var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (chunks.LocatorMap, bool)); ok { - return rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (chunks.LocatorMap, bool)); ok { + return returnFunc(chunkID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) chunks.LocatorMap); ok { - r0 = rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) chunks.LocatorMap); ok { + r0 = returnFunc(chunkID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(chunks.LocatorMap) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(chunkID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(chunkID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Remove provides a mock function with given fields: chunkID -func (_m *ChunkRequests) Remove(chunkID flow.Identifier) bool { - ret := _m.Called(chunkID) +// ChunkRequests_PopAll_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PopAll' +type ChunkRequests_PopAll_Call struct { + *mock.Call +} + +// PopAll is a helper method to define mock.On call +// - chunkID flow.Identifier +func (_e *ChunkRequests_Expecter) PopAll(chunkID interface{}) *ChunkRequests_PopAll_Call { + return &ChunkRequests_PopAll_Call{Call: _e.mock.On("PopAll", chunkID)} +} + +func (_c *ChunkRequests_PopAll_Call) Run(run func(chunkID flow.Identifier)) *ChunkRequests_PopAll_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkRequests_PopAll_Call) Return(locatorMap chunks.LocatorMap, b bool) *ChunkRequests_PopAll_Call { + _c.Call.Return(locatorMap, b) + return _c +} + +func (_c *ChunkRequests_PopAll_Call) RunAndReturn(run func(chunkID flow.Identifier) (chunks.LocatorMap, bool)) *ChunkRequests_PopAll_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) Remove(chunkID flow.Identifier) bool { + ret := _mock.Called(chunkID) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(chunkID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// RequestHistory provides a mock function with given fields: chunkID -func (_m *ChunkRequests) RequestHistory(chunkID flow.Identifier) (uint64, time.Time, time.Duration, bool) { - ret := _m.Called(chunkID) +// ChunkRequests_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type ChunkRequests_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - chunkID flow.Identifier +func (_e *ChunkRequests_Expecter) Remove(chunkID interface{}) *ChunkRequests_Remove_Call { + return &ChunkRequests_Remove_Call{Call: _e.mock.On("Remove", chunkID)} +} + +func (_c *ChunkRequests_Remove_Call) Run(run func(chunkID flow.Identifier)) *ChunkRequests_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkRequests_Remove_Call) Return(b bool) *ChunkRequests_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ChunkRequests_Remove_Call) RunAndReturn(run func(chunkID flow.Identifier) bool) *ChunkRequests_Remove_Call { + _c.Call.Return(run) + return _c +} + +// RequestHistory provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) RequestHistory(chunkID flow.Identifier) (uint64, time.Time, time.Duration, bool) { + ret := _mock.Called(chunkID) if len(ret) == 0 { panic("no return value specified for RequestHistory") @@ -136,57 +314,113 @@ func (_m *ChunkRequests) RequestHistory(chunkID flow.Identifier) (uint64, time.T var r1 time.Time var r2 time.Duration var r3 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (uint64, time.Time, time.Duration, bool)); ok { - return rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (uint64, time.Time, time.Duration, bool)); ok { + return returnFunc(chunkID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { - r0 = rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) uint64); ok { + r0 = returnFunc(chunkID) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) time.Time); ok { - r1 = rf(chunkID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) time.Time); ok { + r1 = returnFunc(chunkID) } else { r1 = ret.Get(1).(time.Time) } - - if rf, ok := ret.Get(2).(func(flow.Identifier) time.Duration); ok { - r2 = rf(chunkID) + if returnFunc, ok := ret.Get(2).(func(flow.Identifier) time.Duration); ok { + r2 = returnFunc(chunkID) } else { r2 = ret.Get(2).(time.Duration) } - - if rf, ok := ret.Get(3).(func(flow.Identifier) bool); ok { - r3 = rf(chunkID) + if returnFunc, ok := ret.Get(3).(func(flow.Identifier) bool); ok { + r3 = returnFunc(chunkID) } else { r3 = ret.Get(3).(bool) } - return r0, r1, r2, r3 } -// Size provides a mock function with no fields -func (_m *ChunkRequests) Size() uint { - ret := _m.Called() +// ChunkRequests_RequestHistory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestHistory' +type ChunkRequests_RequestHistory_Call struct { + *mock.Call +} + +// RequestHistory is a helper method to define mock.On call +// - chunkID flow.Identifier +func (_e *ChunkRequests_Expecter) RequestHistory(chunkID interface{}) *ChunkRequests_RequestHistory_Call { + return &ChunkRequests_RequestHistory_Call{Call: _e.mock.On("RequestHistory", chunkID)} +} + +func (_c *ChunkRequests_RequestHistory_Call) Run(run func(chunkID flow.Identifier)) *ChunkRequests_RequestHistory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkRequests_RequestHistory_Call) Return(v uint64, time1 time.Time, duration time.Duration, b bool) *ChunkRequests_RequestHistory_Call { + _c.Call.Return(v, time1, duration, b) + return _c +} + +func (_c *ChunkRequests_RequestHistory_Call) RunAndReturn(run func(chunkID flow.Identifier) (uint64, time.Time, time.Duration, bool)) *ChunkRequests_RequestHistory_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// UpdateRequestHistory provides a mock function with given fields: chunkID, updater -func (_m *ChunkRequests) UpdateRequestHistory(chunkID flow.Identifier, updater mempool.ChunkRequestHistoryUpdaterFunc) (uint64, time.Time, time.Duration, bool) { - ret := _m.Called(chunkID, updater) +// ChunkRequests_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type ChunkRequests_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *ChunkRequests_Expecter) Size() *ChunkRequests_Size_Call { + return &ChunkRequests_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *ChunkRequests_Size_Call) Run(run func()) *ChunkRequests_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunkRequests_Size_Call) Return(v uint) *ChunkRequests_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ChunkRequests_Size_Call) RunAndReturn(run func() uint) *ChunkRequests_Size_Call { + _c.Call.Return(run) + return _c +} + +// UpdateRequestHistory provides a mock function for the type ChunkRequests +func (_mock *ChunkRequests) UpdateRequestHistory(chunkID flow.Identifier, updater mempool.ChunkRequestHistoryUpdaterFunc) (uint64, time.Time, time.Duration, bool) { + ret := _mock.Called(chunkID, updater) if len(ret) == 0 { panic("no return value specified for UpdateRequestHistory") @@ -196,46 +430,68 @@ func (_m *ChunkRequests) UpdateRequestHistory(chunkID flow.Identifier, updater m var r1 time.Time var r2 time.Duration var r3 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) (uint64, time.Time, time.Duration, bool)); ok { - return rf(chunkID, updater) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) (uint64, time.Time, time.Duration, bool)); ok { + return returnFunc(chunkID, updater) } - if rf, ok := ret.Get(0).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) uint64); ok { - r0 = rf(chunkID, updater) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) uint64); ok { + r0 = returnFunc(chunkID, updater) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) time.Time); ok { - r1 = rf(chunkID, updater) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) time.Time); ok { + r1 = returnFunc(chunkID, updater) } else { r1 = ret.Get(1).(time.Time) } - - if rf, ok := ret.Get(2).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) time.Duration); ok { - r2 = rf(chunkID, updater) + if returnFunc, ok := ret.Get(2).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) time.Duration); ok { + r2 = returnFunc(chunkID, updater) } else { r2 = ret.Get(2).(time.Duration) } - - if rf, ok := ret.Get(3).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) bool); ok { - r3 = rf(chunkID, updater) + if returnFunc, ok := ret.Get(3).(func(flow.Identifier, mempool.ChunkRequestHistoryUpdaterFunc) bool); ok { + r3 = returnFunc(chunkID, updater) } else { r3 = ret.Get(3).(bool) } - return r0, r1, r2, r3 } -// NewChunkRequests creates a new instance of ChunkRequests. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChunkRequests(t interface { - mock.TestingT - Cleanup(func()) -}) *ChunkRequests { - mock := &ChunkRequests{} - mock.Mock.Test(t) +// ChunkRequests_UpdateRequestHistory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateRequestHistory' +type ChunkRequests_UpdateRequestHistory_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UpdateRequestHistory is a helper method to define mock.On call +// - chunkID flow.Identifier +// - updater mempool.ChunkRequestHistoryUpdaterFunc +func (_e *ChunkRequests_Expecter) UpdateRequestHistory(chunkID interface{}, updater interface{}) *ChunkRequests_UpdateRequestHistory_Call { + return &ChunkRequests_UpdateRequestHistory_Call{Call: _e.mock.On("UpdateRequestHistory", chunkID, updater)} +} - return mock +func (_c *ChunkRequests_UpdateRequestHistory_Call) Run(run func(chunkID flow.Identifier, updater mempool.ChunkRequestHistoryUpdaterFunc)) *ChunkRequests_UpdateRequestHistory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 mempool.ChunkRequestHistoryUpdaterFunc + if args[1] != nil { + arg1 = args[1].(mempool.ChunkRequestHistoryUpdaterFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkRequests_UpdateRequestHistory_Call) Return(v uint64, time1 time.Time, duration time.Duration, b bool) *ChunkRequests_UpdateRequestHistory_Call { + _c.Call.Return(v, time1, duration, b) + return _c +} + +func (_c *ChunkRequests_UpdateRequestHistory_Call) RunAndReturn(run func(chunkID flow.Identifier, updater mempool.ChunkRequestHistoryUpdaterFunc) (uint64, time.Time, time.Duration, bool)) *ChunkRequests_UpdateRequestHistory_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/chunk_statuses.go b/module/mempool/mock/chunk_statuses.go index 7834ed92fae..8a8b995dee5 100644 --- a/module/mempool/mock/chunk_statuses.go +++ b/module/mempool/mock/chunk_statuses.go @@ -1,41 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/verification" mock "github.com/stretchr/testify/mock" - - verification "github.com/onflow/flow-go/model/verification" ) +// NewChunkStatuses creates a new instance of ChunkStatuses. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChunkStatuses(t interface { + mock.TestingT + Cleanup(func()) +}) *ChunkStatuses { + mock := &ChunkStatuses{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ChunkStatuses is an autogenerated mock type for the ChunkStatuses type type ChunkStatuses struct { mock.Mock } -// Add provides a mock function with given fields: _a0, _a1 -func (_m *ChunkStatuses) Add(_a0 flow.Identifier, _a1 *verification.ChunkStatus) bool { - ret := _m.Called(_a0, _a1) +type ChunkStatuses_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunkStatuses) EXPECT() *ChunkStatuses_Expecter { + return &ChunkStatuses_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Add(identifier flow.Identifier, chunkStatus *verification.ChunkStatus) bool { + ret := _mock.Called(identifier, chunkStatus) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, *verification.ChunkStatus) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, *verification.ChunkStatus) bool); ok { + r0 = returnFunc(identifier, chunkStatus) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *ChunkStatuses) Adjust(key flow.Identifier, f func(*verification.ChunkStatus) *verification.ChunkStatus) (*verification.ChunkStatus, bool) { - ret := _m.Called(key, f) +// ChunkStatuses_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type ChunkStatuses_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - identifier flow.Identifier +// - chunkStatus *verification.ChunkStatus +func (_e *ChunkStatuses_Expecter) Add(identifier interface{}, chunkStatus interface{}) *ChunkStatuses_Add_Call { + return &ChunkStatuses_Add_Call{Call: _e.mock.On("Add", identifier, chunkStatus)} +} + +func (_c *ChunkStatuses_Add_Call) Run(run func(identifier flow.Identifier, chunkStatus *verification.ChunkStatus)) *ChunkStatuses_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 *verification.ChunkStatus + if args[1] != nil { + arg1 = args[1].(*verification.ChunkStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkStatuses_Add_Call) Return(b bool) *ChunkStatuses_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ChunkStatuses_Add_Call) RunAndReturn(run func(identifier flow.Identifier, chunkStatus *verification.ChunkStatus) bool) *ChunkStatuses_Add_Call { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Adjust(key flow.Identifier, f func(*verification.ChunkStatus) *verification.ChunkStatus) (*verification.ChunkStatus, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -43,54 +104,146 @@ func (_m *ChunkStatuses) Adjust(key flow.Identifier, f func(*verification.ChunkS var r0 *verification.ChunkStatus var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*verification.ChunkStatus) *verification.ChunkStatus) (*verification.ChunkStatus, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*verification.ChunkStatus) *verification.ChunkStatus) (*verification.ChunkStatus, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*verification.ChunkStatus) *verification.ChunkStatus) *verification.ChunkStatus); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*verification.ChunkStatus) *verification.ChunkStatus) *verification.ChunkStatus); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*verification.ChunkStatus) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, func(*verification.ChunkStatus) *verification.ChunkStatus) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, func(*verification.ChunkStatus) *verification.ChunkStatus) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *ChunkStatuses) All() map[flow.Identifier]*verification.ChunkStatus { - ret := _m.Called() +// ChunkStatuses_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type ChunkStatuses_Adjust_Call struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key flow.Identifier +// - f func(*verification.ChunkStatus) *verification.ChunkStatus +func (_e *ChunkStatuses_Expecter) Adjust(key interface{}, f interface{}) *ChunkStatuses_Adjust_Call { + return &ChunkStatuses_Adjust_Call{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *ChunkStatuses_Adjust_Call) Run(run func(key flow.Identifier, f func(*verification.ChunkStatus) *verification.ChunkStatus)) *ChunkStatuses_Adjust_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 func(*verification.ChunkStatus) *verification.ChunkStatus + if args[1] != nil { + arg1 = args[1].(func(*verification.ChunkStatus) *verification.ChunkStatus) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkStatuses_Adjust_Call) Return(chunkStatus *verification.ChunkStatus, b bool) *ChunkStatuses_Adjust_Call { + _c.Call.Return(chunkStatus, b) + return _c +} + +func (_c *ChunkStatuses_Adjust_Call) RunAndReturn(run func(key flow.Identifier, f func(*verification.ChunkStatus) *verification.ChunkStatus) (*verification.ChunkStatus, bool)) *ChunkStatuses_Adjust_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) All() map[flow.Identifier]*verification.ChunkStatus { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[flow.Identifier]*verification.ChunkStatus - if rf, ok := ret.Get(0).(func() map[flow.Identifier]*verification.ChunkStatus); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[flow.Identifier]*verification.ChunkStatus); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[flow.Identifier]*verification.ChunkStatus) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *ChunkStatuses) Clear() { - _m.Called() +// ChunkStatuses_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ChunkStatuses_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *ChunkStatuses_Expecter) All() *ChunkStatuses_All_Call { + return &ChunkStatuses_All_Call{Call: _e.mock.On("All")} } -// Get provides a mock function with given fields: _a0 -func (_m *ChunkStatuses) Get(_a0 flow.Identifier) (*verification.ChunkStatus, bool) { - ret := _m.Called(_a0) +func (_c *ChunkStatuses_All_Call) Run(run func()) *ChunkStatuses_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunkStatuses_All_Call) Return(identifierToChunkStatus map[flow.Identifier]*verification.ChunkStatus) *ChunkStatuses_All_Call { + _c.Call.Return(identifierToChunkStatus) + return _c +} + +func (_c *ChunkStatuses_All_Call) RunAndReturn(run func() map[flow.Identifier]*verification.ChunkStatus) *ChunkStatuses_All_Call { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Clear() { + _mock.Called() + return +} + +// ChunkStatuses_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type ChunkStatuses_Clear_Call struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *ChunkStatuses_Expecter) Clear() *ChunkStatuses_Clear_Call { + return &ChunkStatuses_Clear_Call{Call: _e.mock.On("Clear")} +} + +func (_c *ChunkStatuses_Clear_Call) Run(run func()) *ChunkStatuses_Clear_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunkStatuses_Clear_Call) Return() *ChunkStatuses_Clear_Call { + _c.Call.Return() + return _c +} + +func (_c *ChunkStatuses_Clear_Call) RunAndReturn(run func()) *ChunkStatuses_Clear_Call { + _c.Run(run) + return _c +} + +// Get provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Get(identifier flow.Identifier) (*verification.ChunkStatus, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Get") @@ -98,110 +251,246 @@ func (_m *ChunkStatuses) Get(_a0 flow.Identifier) (*verification.ChunkStatus, bo var r0 *verification.ChunkStatus var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*verification.ChunkStatus, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*verification.ChunkStatus, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *verification.ChunkStatus); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *verification.ChunkStatus); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*verification.ChunkStatus) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: _a0 -func (_m *ChunkStatuses) Has(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// ChunkStatuses_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type ChunkStatuses_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ChunkStatuses_Expecter) Get(identifier interface{}) *ChunkStatuses_Get_Call { + return &ChunkStatuses_Get_Call{Call: _e.mock.On("Get", identifier)} +} + +func (_c *ChunkStatuses_Get_Call) Run(run func(identifier flow.Identifier)) *ChunkStatuses_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkStatuses_Get_Call) Return(chunkStatus *verification.ChunkStatus, b bool) *ChunkStatuses_Get_Call { + _c.Call.Return(chunkStatus, b) + return _c +} + +func (_c *ChunkStatuses_Get_Call) RunAndReturn(run func(identifier flow.Identifier) (*verification.ChunkStatus, bool)) *ChunkStatuses_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Has(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Remove provides a mock function with given fields: _a0 -func (_m *ChunkStatuses) Remove(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// ChunkStatuses_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type ChunkStatuses_Has_Call struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ChunkStatuses_Expecter) Has(identifier interface{}) *ChunkStatuses_Has_Call { + return &ChunkStatuses_Has_Call{Call: _e.mock.On("Has", identifier)} +} + +func (_c *ChunkStatuses_Has_Call) Run(run func(identifier flow.Identifier)) *ChunkStatuses_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkStatuses_Has_Call) Return(b bool) *ChunkStatuses_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ChunkStatuses_Has_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *ChunkStatuses_Has_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Remove(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *ChunkStatuses) Size() uint { - ret := _m.Called() +// ChunkStatuses_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type ChunkStatuses_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ChunkStatuses_Expecter) Remove(identifier interface{}) *ChunkStatuses_Remove_Call { + return &ChunkStatuses_Remove_Call{Call: _e.mock.On("Remove", identifier)} +} + +func (_c *ChunkStatuses_Remove_Call) Run(run func(identifier flow.Identifier)) *ChunkStatuses_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkStatuses_Remove_Call) Return(b bool) *ChunkStatuses_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ChunkStatuses_Remove_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *ChunkStatuses_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *ChunkStatuses) Values() []*verification.ChunkStatus { - ret := _m.Called() +// ChunkStatuses_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type ChunkStatuses_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *ChunkStatuses_Expecter) Size() *ChunkStatuses_Size_Call { + return &ChunkStatuses_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *ChunkStatuses_Size_Call) Run(run func()) *ChunkStatuses_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunkStatuses_Size_Call) Return(v uint) *ChunkStatuses_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ChunkStatuses_Size_Call) RunAndReturn(run func() uint) *ChunkStatuses_Size_Call { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type ChunkStatuses +func (_mock *ChunkStatuses) Values() []*verification.ChunkStatus { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []*verification.ChunkStatus - if rf, ok := ret.Get(0).(func() []*verification.ChunkStatus); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*verification.ChunkStatus); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*verification.ChunkStatus) } } - return r0 } -// NewChunkStatuses creates a new instance of ChunkStatuses. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChunkStatuses(t interface { - mock.TestingT - Cleanup(func()) -}) *ChunkStatuses { - mock := &ChunkStatuses{} - mock.Mock.Test(t) +// ChunkStatuses_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type ChunkStatuses_Values_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *ChunkStatuses_Expecter) Values() *ChunkStatuses_Values_Call { + return &ChunkStatuses_Values_Call{Call: _e.mock.On("Values")} +} - return mock +func (_c *ChunkStatuses_Values_Call) Run(run func()) *ChunkStatuses_Values_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunkStatuses_Values_Call) Return(chunkStatuss []*verification.ChunkStatus) *ChunkStatuses_Values_Call { + _c.Call.Return(chunkStatuss) + return _c +} + +func (_c *ChunkStatuses_Values_Call) RunAndReturn(run func() []*verification.ChunkStatus) *ChunkStatuses_Values_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/dns_cache.go b/module/mempool/mock/dns_cache.go index 17873f92406..dc8510d9e94 100644 --- a/module/mempool/mock/dns_cache.go +++ b/module/mempool/mock/dns_cache.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mempool "github.com/onflow/flow-go/module/mempool" - mock "github.com/stretchr/testify/mock" + "net" - net "net" + "github.com/onflow/flow-go/module/mempool" + mock "github.com/stretchr/testify/mock" ) +// NewDNSCache creates a new instance of DNSCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDNSCache(t interface { + mock.TestingT + Cleanup(func()) +}) *DNSCache { + mock := &DNSCache{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DNSCache is an autogenerated mock type for the DNSCache type type DNSCache struct { mock.Mock } -// GetDomainIp provides a mock function with given fields: _a0 -func (_m *DNSCache) GetDomainIp(_a0 string) (*mempool.IpRecord, bool) { - ret := _m.Called(_a0) +type DNSCache_Expecter struct { + mock *mock.Mock +} + +func (_m *DNSCache) EXPECT() *DNSCache_Expecter { + return &DNSCache_Expecter{mock: &_m.Mock} +} + +// GetDomainIp provides a mock function for the type DNSCache +func (_mock *DNSCache) GetDomainIp(s string) (*mempool.IpRecord, bool) { + ret := _mock.Called(s) if len(ret) == 0 { panic("no return value specified for GetDomainIp") @@ -24,29 +48,61 @@ func (_m *DNSCache) GetDomainIp(_a0 string) (*mempool.IpRecord, bool) { var r0 *mempool.IpRecord var r1 bool - if rf, ok := ret.Get(0).(func(string) (*mempool.IpRecord, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) (*mempool.IpRecord, bool)); ok { + return returnFunc(s) } - if rf, ok := ret.Get(0).(func(string) *mempool.IpRecord); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) *mempool.IpRecord); ok { + r0 = returnFunc(s) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*mempool.IpRecord) } } - - if rf, ok := ret.Get(1).(func(string) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(string) bool); ok { + r1 = returnFunc(s) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetTxtRecord provides a mock function with given fields: _a0 -func (_m *DNSCache) GetTxtRecord(_a0 string) (*mempool.TxtRecord, bool) { - ret := _m.Called(_a0) +// DNSCache_GetDomainIp_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetDomainIp' +type DNSCache_GetDomainIp_Call struct { + *mock.Call +} + +// GetDomainIp is a helper method to define mock.On call +// - s string +func (_e *DNSCache_Expecter) GetDomainIp(s interface{}) *DNSCache_GetDomainIp_Call { + return &DNSCache_GetDomainIp_Call{Call: _e.mock.On("GetDomainIp", s)} +} + +func (_c *DNSCache_GetDomainIp_Call) Run(run func(s string)) *DNSCache_GetDomainIp_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DNSCache_GetDomainIp_Call) Return(ipRecord *mempool.IpRecord, b bool) *DNSCache_GetDomainIp_Call { + _c.Call.Return(ipRecord, b) + return _c +} + +func (_c *DNSCache_GetDomainIp_Call) RunAndReturn(run func(s string) (*mempool.IpRecord, bool)) *DNSCache_GetDomainIp_Call { + _c.Call.Return(run) + return _c +} + +// GetTxtRecord provides a mock function for the type DNSCache +func (_mock *DNSCache) GetTxtRecord(s string) (*mempool.TxtRecord, bool) { + ret := _mock.Called(s) if len(ret) == 0 { panic("no return value specified for GetTxtRecord") @@ -54,29 +110,61 @@ func (_m *DNSCache) GetTxtRecord(_a0 string) (*mempool.TxtRecord, bool) { var r0 *mempool.TxtRecord var r1 bool - if rf, ok := ret.Get(0).(func(string) (*mempool.TxtRecord, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) (*mempool.TxtRecord, bool)); ok { + return returnFunc(s) } - if rf, ok := ret.Get(0).(func(string) *mempool.TxtRecord); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) *mempool.TxtRecord); ok { + r0 = returnFunc(s) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*mempool.TxtRecord) } } - - if rf, ok := ret.Get(1).(func(string) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(string) bool); ok { + r1 = returnFunc(s) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// LockIPDomain provides a mock function with given fields: _a0 -func (_m *DNSCache) LockIPDomain(_a0 string) (bool, error) { - ret := _m.Called(_a0) +// DNSCache_GetTxtRecord_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTxtRecord' +type DNSCache_GetTxtRecord_Call struct { + *mock.Call +} + +// GetTxtRecord is a helper method to define mock.On call +// - s string +func (_e *DNSCache_Expecter) GetTxtRecord(s interface{}) *DNSCache_GetTxtRecord_Call { + return &DNSCache_GetTxtRecord_Call{Call: _e.mock.On("GetTxtRecord", s)} +} + +func (_c *DNSCache_GetTxtRecord_Call) Run(run func(s string)) *DNSCache_GetTxtRecord_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DNSCache_GetTxtRecord_Call) Return(txtRecord *mempool.TxtRecord, b bool) *DNSCache_GetTxtRecord_Call { + _c.Call.Return(txtRecord, b) + return _c +} + +func (_c *DNSCache_GetTxtRecord_Call) RunAndReturn(run func(s string) (*mempool.TxtRecord, bool)) *DNSCache_GetTxtRecord_Call { + _c.Call.Return(run) + return _c +} + +// LockIPDomain provides a mock function for the type DNSCache +func (_mock *DNSCache) LockIPDomain(s string) (bool, error) { + ret := _mock.Called(s) if len(ret) == 0 { panic("no return value specified for LockIPDomain") @@ -84,27 +172,59 @@ func (_m *DNSCache) LockIPDomain(_a0 string) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(string) (bool, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) (bool, error)); ok { + return returnFunc(s) } - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) bool); ok { + r0 = returnFunc(s) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(string) error); ok { + r1 = returnFunc(s) } else { r1 = ret.Error(1) } - return r0, r1 } -// LockTxtRecord provides a mock function with given fields: _a0 -func (_m *DNSCache) LockTxtRecord(_a0 string) (bool, error) { - ret := _m.Called(_a0) +// DNSCache_LockIPDomain_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LockIPDomain' +type DNSCache_LockIPDomain_Call struct { + *mock.Call +} + +// LockIPDomain is a helper method to define mock.On call +// - s string +func (_e *DNSCache_Expecter) LockIPDomain(s interface{}) *DNSCache_LockIPDomain_Call { + return &DNSCache_LockIPDomain_Call{Call: _e.mock.On("LockIPDomain", s)} +} + +func (_c *DNSCache_LockIPDomain_Call) Run(run func(s string)) *DNSCache_LockIPDomain_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DNSCache_LockIPDomain_Call) Return(b bool, err error) *DNSCache_LockIPDomain_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *DNSCache_LockIPDomain_Call) RunAndReturn(run func(s string) (bool, error)) *DNSCache_LockIPDomain_Call { + _c.Call.Return(run) + return _c +} + +// LockTxtRecord provides a mock function for the type DNSCache +func (_mock *DNSCache) LockTxtRecord(s string) (bool, error) { + ret := _mock.Called(s) if len(ret) == 0 { panic("no return value specified for LockTxtRecord") @@ -112,99 +232,287 @@ func (_m *DNSCache) LockTxtRecord(_a0 string) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(string) (bool, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) (bool, error)); ok { + return returnFunc(s) } - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) bool); ok { + r0 = returnFunc(s) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(string) error); ok { + r1 = returnFunc(s) } else { r1 = ret.Error(1) } - return r0, r1 } -// PutIpDomain provides a mock function with given fields: _a0, _a1, _a2 -func (_m *DNSCache) PutIpDomain(_a0 string, _a1 []net.IPAddr, _a2 int64) bool { - ret := _m.Called(_a0, _a1, _a2) +// DNSCache_LockTxtRecord_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LockTxtRecord' +type DNSCache_LockTxtRecord_Call struct { + *mock.Call +} + +// LockTxtRecord is a helper method to define mock.On call +// - s string +func (_e *DNSCache_Expecter) LockTxtRecord(s interface{}) *DNSCache_LockTxtRecord_Call { + return &DNSCache_LockTxtRecord_Call{Call: _e.mock.On("LockTxtRecord", s)} +} + +func (_c *DNSCache_LockTxtRecord_Call) Run(run func(s string)) *DNSCache_LockTxtRecord_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DNSCache_LockTxtRecord_Call) Return(b bool, err error) *DNSCache_LockTxtRecord_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *DNSCache_LockTxtRecord_Call) RunAndReturn(run func(s string) (bool, error)) *DNSCache_LockTxtRecord_Call { + _c.Call.Return(run) + return _c +} + +// PutIpDomain provides a mock function for the type DNSCache +func (_mock *DNSCache) PutIpDomain(s string, iPAddrs []net.IPAddr, n int64) bool { + ret := _mock.Called(s, iPAddrs, n) if len(ret) == 0 { panic("no return value specified for PutIpDomain") } var r0 bool - if rf, ok := ret.Get(0).(func(string, []net.IPAddr, int64) bool); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(string, []net.IPAddr, int64) bool); ok { + r0 = returnFunc(s, iPAddrs, n) } else { r0 = ret.Get(0).(bool) } - return r0 } -// PutTxtRecord provides a mock function with given fields: _a0, _a1, _a2 -func (_m *DNSCache) PutTxtRecord(_a0 string, _a1 []string, _a2 int64) bool { - ret := _m.Called(_a0, _a1, _a2) +// DNSCache_PutIpDomain_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PutIpDomain' +type DNSCache_PutIpDomain_Call struct { + *mock.Call +} + +// PutIpDomain is a helper method to define mock.On call +// - s string +// - iPAddrs []net.IPAddr +// - n int64 +func (_e *DNSCache_Expecter) PutIpDomain(s interface{}, iPAddrs interface{}, n interface{}) *DNSCache_PutIpDomain_Call { + return &DNSCache_PutIpDomain_Call{Call: _e.mock.On("PutIpDomain", s, iPAddrs, n)} +} + +func (_c *DNSCache_PutIpDomain_Call) Run(run func(s string, iPAddrs []net.IPAddr, n int64)) *DNSCache_PutIpDomain_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 []net.IPAddr + if args[1] != nil { + arg1 = args[1].([]net.IPAddr) + } + var arg2 int64 + if args[2] != nil { + arg2 = args[2].(int64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DNSCache_PutIpDomain_Call) Return(b bool) *DNSCache_PutIpDomain_Call { + _c.Call.Return(b) + return _c +} + +func (_c *DNSCache_PutIpDomain_Call) RunAndReturn(run func(s string, iPAddrs []net.IPAddr, n int64) bool) *DNSCache_PutIpDomain_Call { + _c.Call.Return(run) + return _c +} + +// PutTxtRecord provides a mock function for the type DNSCache +func (_mock *DNSCache) PutTxtRecord(s string, strings []string, n int64) bool { + ret := _mock.Called(s, strings, n) if len(ret) == 0 { panic("no return value specified for PutTxtRecord") } var r0 bool - if rf, ok := ret.Get(0).(func(string, []string, int64) bool); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(string, []string, int64) bool); ok { + r0 = returnFunc(s, strings, n) } else { r0 = ret.Get(0).(bool) } - return r0 } -// RemoveIp provides a mock function with given fields: _a0 -func (_m *DNSCache) RemoveIp(_a0 string) bool { - ret := _m.Called(_a0) +// DNSCache_PutTxtRecord_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PutTxtRecord' +type DNSCache_PutTxtRecord_Call struct { + *mock.Call +} + +// PutTxtRecord is a helper method to define mock.On call +// - s string +// - strings []string +// - n int64 +func (_e *DNSCache_Expecter) PutTxtRecord(s interface{}, strings interface{}, n interface{}) *DNSCache_PutTxtRecord_Call { + return &DNSCache_PutTxtRecord_Call{Call: _e.mock.On("PutTxtRecord", s, strings, n)} +} + +func (_c *DNSCache_PutTxtRecord_Call) Run(run func(s string, strings []string, n int64)) *DNSCache_PutTxtRecord_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 []string + if args[1] != nil { + arg1 = args[1].([]string) + } + var arg2 int64 + if args[2] != nil { + arg2 = args[2].(int64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DNSCache_PutTxtRecord_Call) Return(b bool) *DNSCache_PutTxtRecord_Call { + _c.Call.Return(b) + return _c +} + +func (_c *DNSCache_PutTxtRecord_Call) RunAndReturn(run func(s string, strings []string, n int64) bool) *DNSCache_PutTxtRecord_Call { + _c.Call.Return(run) + return _c +} + +// RemoveIp provides a mock function for the type DNSCache +func (_mock *DNSCache) RemoveIp(s string) bool { + ret := _mock.Called(s) if len(ret) == 0 { panic("no return value specified for RemoveIp") } var r0 bool - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) bool); ok { + r0 = returnFunc(s) } else { r0 = ret.Get(0).(bool) } - return r0 } -// RemoveTxt provides a mock function with given fields: _a0 -func (_m *DNSCache) RemoveTxt(_a0 string) bool { - ret := _m.Called(_a0) +// DNSCache_RemoveIp_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemoveIp' +type DNSCache_RemoveIp_Call struct { + *mock.Call +} + +// RemoveIp is a helper method to define mock.On call +// - s string +func (_e *DNSCache_Expecter) RemoveIp(s interface{}) *DNSCache_RemoveIp_Call { + return &DNSCache_RemoveIp_Call{Call: _e.mock.On("RemoveIp", s)} +} + +func (_c *DNSCache_RemoveIp_Call) Run(run func(s string)) *DNSCache_RemoveIp_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DNSCache_RemoveIp_Call) Return(b bool) *DNSCache_RemoveIp_Call { + _c.Call.Return(b) + return _c +} + +func (_c *DNSCache_RemoveIp_Call) RunAndReturn(run func(s string) bool) *DNSCache_RemoveIp_Call { + _c.Call.Return(run) + return _c +} + +// RemoveTxt provides a mock function for the type DNSCache +func (_mock *DNSCache) RemoveTxt(s string) bool { + ret := _mock.Called(s) if len(ret) == 0 { panic("no return value specified for RemoveTxt") } var r0 bool - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) bool); ok { + r0 = returnFunc(s) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *DNSCache) Size() (uint, uint) { - ret := _m.Called() +// DNSCache_RemoveTxt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemoveTxt' +type DNSCache_RemoveTxt_Call struct { + *mock.Call +} + +// RemoveTxt is a helper method to define mock.On call +// - s string +func (_e *DNSCache_Expecter) RemoveTxt(s interface{}) *DNSCache_RemoveTxt_Call { + return &DNSCache_RemoveTxt_Call{Call: _e.mock.On("RemoveTxt", s)} +} + +func (_c *DNSCache_RemoveTxt_Call) Run(run func(s string)) *DNSCache_RemoveTxt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DNSCache_RemoveTxt_Call) Return(b bool) *DNSCache_RemoveTxt_Call { + _c.Call.Return(b) + return _c +} + +func (_c *DNSCache_RemoveTxt_Call) RunAndReturn(run func(s string) bool) *DNSCache_RemoveTxt_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type DNSCache +func (_mock *DNSCache) Size() (uint, uint) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") @@ -212,70 +520,171 @@ func (_m *DNSCache) Size() (uint, uint) { var r0 uint var r1 uint - if rf, ok := ret.Get(0).(func() (uint, uint)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint, uint)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - - if rf, ok := ret.Get(1).(func() uint); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() uint); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(uint) } - return r0, r1 } -// UpdateIPDomain provides a mock function with given fields: _a0, _a1, _a2 -func (_m *DNSCache) UpdateIPDomain(_a0 string, _a1 []net.IPAddr, _a2 int64) error { - ret := _m.Called(_a0, _a1, _a2) +// DNSCache_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type DNSCache_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *DNSCache_Expecter) Size() *DNSCache_Size_Call { + return &DNSCache_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *DNSCache_Size_Call) Run(run func()) *DNSCache_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DNSCache_Size_Call) Return(v uint, v1 uint) *DNSCache_Size_Call { + _c.Call.Return(v, v1) + return _c +} + +func (_c *DNSCache_Size_Call) RunAndReturn(run func() (uint, uint)) *DNSCache_Size_Call { + _c.Call.Return(run) + return _c +} + +// UpdateIPDomain provides a mock function for the type DNSCache +func (_mock *DNSCache) UpdateIPDomain(s string, iPAddrs []net.IPAddr, n int64) error { + ret := _mock.Called(s, iPAddrs, n) if len(ret) == 0 { panic("no return value specified for UpdateIPDomain") } var r0 error - if rf, ok := ret.Get(0).(func(string, []net.IPAddr, int64) error); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(string, []net.IPAddr, int64) error); ok { + r0 = returnFunc(s, iPAddrs, n) } else { r0 = ret.Error(0) } - return r0 } -// UpdateTxtRecord provides a mock function with given fields: _a0, _a1, _a2 -func (_m *DNSCache) UpdateTxtRecord(_a0 string, _a1 []string, _a2 int64) error { - ret := _m.Called(_a0, _a1, _a2) +// DNSCache_UpdateIPDomain_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateIPDomain' +type DNSCache_UpdateIPDomain_Call struct { + *mock.Call +} + +// UpdateIPDomain is a helper method to define mock.On call +// - s string +// - iPAddrs []net.IPAddr +// - n int64 +func (_e *DNSCache_Expecter) UpdateIPDomain(s interface{}, iPAddrs interface{}, n interface{}) *DNSCache_UpdateIPDomain_Call { + return &DNSCache_UpdateIPDomain_Call{Call: _e.mock.On("UpdateIPDomain", s, iPAddrs, n)} +} + +func (_c *DNSCache_UpdateIPDomain_Call) Run(run func(s string, iPAddrs []net.IPAddr, n int64)) *DNSCache_UpdateIPDomain_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 []net.IPAddr + if args[1] != nil { + arg1 = args[1].([]net.IPAddr) + } + var arg2 int64 + if args[2] != nil { + arg2 = args[2].(int64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DNSCache_UpdateIPDomain_Call) Return(err error) *DNSCache_UpdateIPDomain_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DNSCache_UpdateIPDomain_Call) RunAndReturn(run func(s string, iPAddrs []net.IPAddr, n int64) error) *DNSCache_UpdateIPDomain_Call { + _c.Call.Return(run) + return _c +} + +// UpdateTxtRecord provides a mock function for the type DNSCache +func (_mock *DNSCache) UpdateTxtRecord(s string, strings []string, n int64) error { + ret := _mock.Called(s, strings, n) if len(ret) == 0 { panic("no return value specified for UpdateTxtRecord") } var r0 error - if rf, ok := ret.Get(0).(func(string, []string, int64) error); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(string, []string, int64) error); ok { + r0 = returnFunc(s, strings, n) } else { r0 = ret.Error(0) } - return r0 } -// NewDNSCache creates a new instance of DNSCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDNSCache(t interface { - mock.TestingT - Cleanup(func()) -}) *DNSCache { - mock := &DNSCache{} - mock.Mock.Test(t) +// DNSCache_UpdateTxtRecord_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateTxtRecord' +type DNSCache_UpdateTxtRecord_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UpdateTxtRecord is a helper method to define mock.On call +// - s string +// - strings []string +// - n int64 +func (_e *DNSCache_Expecter) UpdateTxtRecord(s interface{}, strings interface{}, n interface{}) *DNSCache_UpdateTxtRecord_Call { + return &DNSCache_UpdateTxtRecord_Call{Call: _e.mock.On("UpdateTxtRecord", s, strings, n)} +} - return mock +func (_c *DNSCache_UpdateTxtRecord_Call) Run(run func(s string, strings []string, n int64)) *DNSCache_UpdateTxtRecord_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 []string + if args[1] != nil { + arg1 = args[1].([]string) + } + var arg2 int64 + if args[2] != nil { + arg2 = args[2].(int64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DNSCache_UpdateTxtRecord_Call) Return(err error) *DNSCache_UpdateTxtRecord_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DNSCache_UpdateTxtRecord_Call) RunAndReturn(run func(s string, strings []string, n int64) error) *DNSCache_UpdateTxtRecord_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/execution_data.go b/module/mempool/mock/execution_data.go index 1bd80b8ed58..0158b2f9c68 100644 --- a/module/mempool/mock/execution_data.go +++ b/module/mempool/mock/execution_data.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewExecutionData creates a new instance of ExecutionData. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionData(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionData { + mock := &ExecutionData{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionData is an autogenerated mock type for the ExecutionData type type ExecutionData struct { mock.Mock } -// Add provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionData) Add(_a0 flow.Identifier, _a1 *execution_data.BlockExecutionDataEntity) bool { - ret := _m.Called(_a0, _a1) +type ExecutionData_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionData) EXPECT() *ExecutionData_Expecter { + return &ExecutionData_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Add(identifier flow.Identifier, blockExecutionDataEntity *execution_data.BlockExecutionDataEntity) bool { + ret := _mock.Called(identifier, blockExecutionDataEntity) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, *execution_data.BlockExecutionDataEntity) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, *execution_data.BlockExecutionDataEntity) bool); ok { + r0 = returnFunc(identifier, blockExecutionDataEntity) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *ExecutionData) Adjust(key flow.Identifier, f func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) (*execution_data.BlockExecutionDataEntity, bool) { - ret := _m.Called(key, f) +// ExecutionData_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type ExecutionData_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - identifier flow.Identifier +// - blockExecutionDataEntity *execution_data.BlockExecutionDataEntity +func (_e *ExecutionData_Expecter) Add(identifier interface{}, blockExecutionDataEntity interface{}) *ExecutionData_Add_Call { + return &ExecutionData_Add_Call{Call: _e.mock.On("Add", identifier, blockExecutionDataEntity)} +} + +func (_c *ExecutionData_Add_Call) Run(run func(identifier flow.Identifier, blockExecutionDataEntity *execution_data.BlockExecutionDataEntity)) *ExecutionData_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 *execution_data.BlockExecutionDataEntity + if args[1] != nil { + arg1 = args[1].(*execution_data.BlockExecutionDataEntity) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionData_Add_Call) Return(b bool) *ExecutionData_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ExecutionData_Add_Call) RunAndReturn(run func(identifier flow.Identifier, blockExecutionDataEntity *execution_data.BlockExecutionDataEntity) bool) *ExecutionData_Add_Call { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Adjust(key flow.Identifier, f func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) (*execution_data.BlockExecutionDataEntity, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -42,54 +104,146 @@ func (_m *ExecutionData) Adjust(key flow.Identifier, f func(*execution_data.Bloc var r0 *execution_data.BlockExecutionDataEntity var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) (*execution_data.BlockExecutionDataEntity, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) (*execution_data.BlockExecutionDataEntity, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionDataEntity) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *ExecutionData) All() map[flow.Identifier]*execution_data.BlockExecutionDataEntity { - ret := _m.Called() +// ExecutionData_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type ExecutionData_Adjust_Call struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key flow.Identifier +// - f func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity +func (_e *ExecutionData_Expecter) Adjust(key interface{}, f interface{}) *ExecutionData_Adjust_Call { + return &ExecutionData_Adjust_Call{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *ExecutionData_Adjust_Call) Run(run func(key flow.Identifier, f func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity)) *ExecutionData_Adjust_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity + if args[1] != nil { + arg1 = args[1].(func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionData_Adjust_Call) Return(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity, b bool) *ExecutionData_Adjust_Call { + _c.Call.Return(blockExecutionDataEntity, b) + return _c +} + +func (_c *ExecutionData_Adjust_Call) RunAndReturn(run func(key flow.Identifier, f func(*execution_data.BlockExecutionDataEntity) *execution_data.BlockExecutionDataEntity) (*execution_data.BlockExecutionDataEntity, bool)) *ExecutionData_Adjust_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type ExecutionData +func (_mock *ExecutionData) All() map[flow.Identifier]*execution_data.BlockExecutionDataEntity { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[flow.Identifier]*execution_data.BlockExecutionDataEntity - if rf, ok := ret.Get(0).(func() map[flow.Identifier]*execution_data.BlockExecutionDataEntity); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[flow.Identifier]*execution_data.BlockExecutionDataEntity); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[flow.Identifier]*execution_data.BlockExecutionDataEntity) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *ExecutionData) Clear() { - _m.Called() +// ExecutionData_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ExecutionData_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *ExecutionData_Expecter) All() *ExecutionData_All_Call { + return &ExecutionData_All_Call{Call: _e.mock.On("All")} +} + +func (_c *ExecutionData_All_Call) Run(run func()) *ExecutionData_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionData_All_Call) Return(identifierToBlockExecutionDataEntity map[flow.Identifier]*execution_data.BlockExecutionDataEntity) *ExecutionData_All_Call { + _c.Call.Return(identifierToBlockExecutionDataEntity) + return _c +} + +func (_c *ExecutionData_All_Call) RunAndReturn(run func() map[flow.Identifier]*execution_data.BlockExecutionDataEntity) *ExecutionData_All_Call { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Clear() { + _mock.Called() + return +} + +// ExecutionData_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type ExecutionData_Clear_Call struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *ExecutionData_Expecter) Clear() *ExecutionData_Clear_Call { + return &ExecutionData_Clear_Call{Call: _e.mock.On("Clear")} +} + +func (_c *ExecutionData_Clear_Call) Run(run func()) *ExecutionData_Clear_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionData_Clear_Call) Return() *ExecutionData_Clear_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionData_Clear_Call) RunAndReturn(run func()) *ExecutionData_Clear_Call { + _c.Run(run) + return _c } -// Get provides a mock function with given fields: _a0 -func (_m *ExecutionData) Get(_a0 flow.Identifier) (*execution_data.BlockExecutionDataEntity, bool) { - ret := _m.Called(_a0) +// Get provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Get(identifier flow.Identifier) (*execution_data.BlockExecutionDataEntity, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Get") @@ -97,110 +251,246 @@ func (_m *ExecutionData) Get(_a0 flow.Identifier) (*execution_data.BlockExecutio var r0 *execution_data.BlockExecutionDataEntity var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*execution_data.BlockExecutionDataEntity, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*execution_data.BlockExecutionDataEntity, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *execution_data.BlockExecutionDataEntity); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *execution_data.BlockExecutionDataEntity); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionDataEntity) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: _a0 -func (_m *ExecutionData) Has(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// ExecutionData_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type ExecutionData_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ExecutionData_Expecter) Get(identifier interface{}) *ExecutionData_Get_Call { + return &ExecutionData_Get_Call{Call: _e.mock.On("Get", identifier)} +} + +func (_c *ExecutionData_Get_Call) Run(run func(identifier flow.Identifier)) *ExecutionData_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionData_Get_Call) Return(blockExecutionDataEntity *execution_data.BlockExecutionDataEntity, b bool) *ExecutionData_Get_Call { + _c.Call.Return(blockExecutionDataEntity, b) + return _c +} + +func (_c *ExecutionData_Get_Call) RunAndReturn(run func(identifier flow.Identifier) (*execution_data.BlockExecutionDataEntity, bool)) *ExecutionData_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Has(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Remove provides a mock function with given fields: _a0 -func (_m *ExecutionData) Remove(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// ExecutionData_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type ExecutionData_Has_Call struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ExecutionData_Expecter) Has(identifier interface{}) *ExecutionData_Has_Call { + return &ExecutionData_Has_Call{Call: _e.mock.On("Has", identifier)} +} + +func (_c *ExecutionData_Has_Call) Run(run func(identifier flow.Identifier)) *ExecutionData_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionData_Has_Call) Return(b bool) *ExecutionData_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ExecutionData_Has_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *ExecutionData_Has_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Remove(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *ExecutionData) Size() uint { - ret := _m.Called() +// ExecutionData_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type ExecutionData_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *ExecutionData_Expecter) Remove(identifier interface{}) *ExecutionData_Remove_Call { + return &ExecutionData_Remove_Call{Call: _e.mock.On("Remove", identifier)} +} + +func (_c *ExecutionData_Remove_Call) Run(run func(identifier flow.Identifier)) *ExecutionData_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionData_Remove_Call) Return(b bool) *ExecutionData_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ExecutionData_Remove_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *ExecutionData_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *ExecutionData) Values() []*execution_data.BlockExecutionDataEntity { - ret := _m.Called() +// ExecutionData_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type ExecutionData_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *ExecutionData_Expecter) Size() *ExecutionData_Size_Call { + return &ExecutionData_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *ExecutionData_Size_Call) Run(run func()) *ExecutionData_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionData_Size_Call) Return(v uint) *ExecutionData_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ExecutionData_Size_Call) RunAndReturn(run func() uint) *ExecutionData_Size_Call { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type ExecutionData +func (_mock *ExecutionData) Values() []*execution_data.BlockExecutionDataEntity { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []*execution_data.BlockExecutionDataEntity - if rf, ok := ret.Get(0).(func() []*execution_data.BlockExecutionDataEntity); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*execution_data.BlockExecutionDataEntity); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*execution_data.BlockExecutionDataEntity) } } - return r0 } -// NewExecutionData creates a new instance of ExecutionData. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionData(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionData { - mock := &ExecutionData{} - mock.Mock.Test(t) +// ExecutionData_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type ExecutionData_Values_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *ExecutionData_Expecter) Values() *ExecutionData_Values_Call { + return &ExecutionData_Values_Call{Call: _e.mock.On("Values")} +} - return mock +func (_c *ExecutionData_Values_Call) Run(run func()) *ExecutionData_Values_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionData_Values_Call) Return(blockExecutionDataEntitys []*execution_data.BlockExecutionDataEntity) *ExecutionData_Values_Call { + _c.Call.Return(blockExecutionDataEntitys) + return _c +} + +func (_c *ExecutionData_Values_Call) RunAndReturn(run func() []*execution_data.BlockExecutionDataEntity) *ExecutionData_Values_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/execution_tree.go b/module/mempool/mock/execution_tree.go index 493f111c129..ef6118c9201 100644 --- a/module/mempool/mock/execution_tree.go +++ b/module/mempool/mock/execution_tree.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - mempool "github.com/onflow/flow-go/module/mempool" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/mempool" mock "github.com/stretchr/testify/mock" ) +// NewExecutionTree creates a new instance of ExecutionTree. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionTree(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionTree { + mock := &ExecutionTree{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionTree is an autogenerated mock type for the ExecutionTree type type ExecutionTree struct { mock.Mock } -// AddReceipt provides a mock function with given fields: receipt, block -func (_m *ExecutionTree) AddReceipt(receipt *flow.ExecutionReceipt, block *flow.Header) (bool, error) { - ret := _m.Called(receipt, block) +type ExecutionTree_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionTree) EXPECT() *ExecutionTree_Expecter { + return &ExecutionTree_Expecter{mock: &_m.Mock} +} + +// AddReceipt provides a mock function for the type ExecutionTree +func (_mock *ExecutionTree) AddReceipt(receipt *flow.ExecutionReceipt, block *flow.Header) (bool, error) { + ret := _mock.Called(receipt, block) if len(ret) == 0 { panic("no return value specified for AddReceipt") @@ -24,99 +47,268 @@ func (_m *ExecutionTree) AddReceipt(receipt *flow.ExecutionReceipt, block *flow. var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt, *flow.Header) (bool, error)); ok { - return rf(receipt, block) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt, *flow.Header) (bool, error)); ok { + return returnFunc(receipt, block) } - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt, *flow.Header) bool); ok { - r0 = rf(receipt, block) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt, *flow.Header) bool); ok { + r0 = returnFunc(receipt, block) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*flow.ExecutionReceipt, *flow.Header) error); ok { - r1 = rf(receipt, block) + if returnFunc, ok := ret.Get(1).(func(*flow.ExecutionReceipt, *flow.Header) error); ok { + r1 = returnFunc(receipt, block) } else { r1 = ret.Error(1) } - return r0, r1 } -// AddResult provides a mock function with given fields: result, block -func (_m *ExecutionTree) AddResult(result *flow.ExecutionResult, block *flow.Header) error { - ret := _m.Called(result, block) +// ExecutionTree_AddReceipt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddReceipt' +type ExecutionTree_AddReceipt_Call struct { + *mock.Call +} + +// AddReceipt is a helper method to define mock.On call +// - receipt *flow.ExecutionReceipt +// - block *flow.Header +func (_e *ExecutionTree_Expecter) AddReceipt(receipt interface{}, block interface{}) *ExecutionTree_AddReceipt_Call { + return &ExecutionTree_AddReceipt_Call{Call: _e.mock.On("AddReceipt", receipt, block)} +} + +func (_c *ExecutionTree_AddReceipt_Call) Run(run func(receipt *flow.ExecutionReceipt, block *flow.Header)) *ExecutionTree_AddReceipt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionTree_AddReceipt_Call) Return(b bool, err error) *ExecutionTree_AddReceipt_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ExecutionTree_AddReceipt_Call) RunAndReturn(run func(receipt *flow.ExecutionReceipt, block *flow.Header) (bool, error)) *ExecutionTree_AddReceipt_Call { + _c.Call.Return(run) + return _c +} + +// AddResult provides a mock function for the type ExecutionTree +func (_mock *ExecutionTree) AddResult(result *flow.ExecutionResult, block *flow.Header) error { + ret := _mock.Called(result, block) if len(ret) == 0 { panic("no return value specified for AddResult") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionResult, *flow.Header) error); ok { - r0 = rf(result, block) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionResult, *flow.Header) error); ok { + r0 = returnFunc(result, block) } else { r0 = ret.Error(0) } - return r0 } -// HasReceipt provides a mock function with given fields: receipt -func (_m *ExecutionTree) HasReceipt(receipt *flow.ExecutionReceipt) bool { - ret := _m.Called(receipt) +// ExecutionTree_AddResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddResult' +type ExecutionTree_AddResult_Call struct { + *mock.Call +} + +// AddResult is a helper method to define mock.On call +// - result *flow.ExecutionResult +// - block *flow.Header +func (_e *ExecutionTree_Expecter) AddResult(result interface{}, block interface{}) *ExecutionTree_AddResult_Call { + return &ExecutionTree_AddResult_Call{Call: _e.mock.On("AddResult", result, block)} +} + +func (_c *ExecutionTree_AddResult_Call) Run(run func(result *flow.ExecutionResult, block *flow.Header)) *ExecutionTree_AddResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionResult + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionResult) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionTree_AddResult_Call) Return(err error) *ExecutionTree_AddResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionTree_AddResult_Call) RunAndReturn(run func(result *flow.ExecutionResult, block *flow.Header) error) *ExecutionTree_AddResult_Call { + _c.Call.Return(run) + return _c +} + +// HasReceipt provides a mock function for the type ExecutionTree +func (_mock *ExecutionTree) HasReceipt(receipt *flow.ExecutionReceipt) bool { + ret := _mock.Called(receipt) if len(ret) == 0 { panic("no return value specified for HasReceipt") } var r0 bool - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt) bool); ok { - r0 = rf(receipt) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt) bool); ok { + r0 = returnFunc(receipt) } else { r0 = ret.Get(0).(bool) } - return r0 } -// LowestHeight provides a mock function with no fields -func (_m *ExecutionTree) LowestHeight() uint64 { - ret := _m.Called() +// ExecutionTree_HasReceipt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasReceipt' +type ExecutionTree_HasReceipt_Call struct { + *mock.Call +} + +// HasReceipt is a helper method to define mock.On call +// - receipt *flow.ExecutionReceipt +func (_e *ExecutionTree_Expecter) HasReceipt(receipt interface{}) *ExecutionTree_HasReceipt_Call { + return &ExecutionTree_HasReceipt_Call{Call: _e.mock.On("HasReceipt", receipt)} +} + +func (_c *ExecutionTree_HasReceipt_Call) Run(run func(receipt *flow.ExecutionReceipt)) *ExecutionTree_HasReceipt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionTree_HasReceipt_Call) Return(b bool) *ExecutionTree_HasReceipt_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ExecutionTree_HasReceipt_Call) RunAndReturn(run func(receipt *flow.ExecutionReceipt) bool) *ExecutionTree_HasReceipt_Call { + _c.Call.Return(run) + return _c +} + +// LowestHeight provides a mock function for the type ExecutionTree +func (_mock *ExecutionTree) LowestHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LowestHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// PruneUpToHeight provides a mock function with given fields: newLowestHeight -func (_m *ExecutionTree) PruneUpToHeight(newLowestHeight uint64) error { - ret := _m.Called(newLowestHeight) +// ExecutionTree_LowestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LowestHeight' +type ExecutionTree_LowestHeight_Call struct { + *mock.Call +} + +// LowestHeight is a helper method to define mock.On call +func (_e *ExecutionTree_Expecter) LowestHeight() *ExecutionTree_LowestHeight_Call { + return &ExecutionTree_LowestHeight_Call{Call: _e.mock.On("LowestHeight")} +} + +func (_c *ExecutionTree_LowestHeight_Call) Run(run func()) *ExecutionTree_LowestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionTree_LowestHeight_Call) Return(v uint64) *ExecutionTree_LowestHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ExecutionTree_LowestHeight_Call) RunAndReturn(run func() uint64) *ExecutionTree_LowestHeight_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToHeight provides a mock function for the type ExecutionTree +func (_mock *ExecutionTree) PruneUpToHeight(newLowestHeight uint64) error { + ret := _mock.Called(newLowestHeight) if len(ret) == 0 { panic("no return value specified for PruneUpToHeight") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(newLowestHeight) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(newLowestHeight) } else { r0 = ret.Error(0) } - return r0 } -// ReachableReceipts provides a mock function with given fields: resultID, blockFilter, receiptFilter -func (_m *ExecutionTree) ReachableReceipts(resultID flow.Identifier, blockFilter mempool.BlockFilter, receiptFilter mempool.ReceiptFilter) ([]*flow.ExecutionReceipt, error) { - ret := _m.Called(resultID, blockFilter, receiptFilter) +// ExecutionTree_PruneUpToHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToHeight' +type ExecutionTree_PruneUpToHeight_Call struct { + *mock.Call +} + +// PruneUpToHeight is a helper method to define mock.On call +// - newLowestHeight uint64 +func (_e *ExecutionTree_Expecter) PruneUpToHeight(newLowestHeight interface{}) *ExecutionTree_PruneUpToHeight_Call { + return &ExecutionTree_PruneUpToHeight_Call{Call: _e.mock.On("PruneUpToHeight", newLowestHeight)} +} + +func (_c *ExecutionTree_PruneUpToHeight_Call) Run(run func(newLowestHeight uint64)) *ExecutionTree_PruneUpToHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionTree_PruneUpToHeight_Call) Return(err error) *ExecutionTree_PruneUpToHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionTree_PruneUpToHeight_Call) RunAndReturn(run func(newLowestHeight uint64) error) *ExecutionTree_PruneUpToHeight_Call { + _c.Call.Return(run) + return _c +} + +// ReachableReceipts provides a mock function for the type ExecutionTree +func (_mock *ExecutionTree) ReachableReceipts(resultID flow.Identifier, blockFilter mempool.BlockFilter, receiptFilter mempool.ReceiptFilter) ([]*flow.ExecutionReceipt, error) { + ret := _mock.Called(resultID, blockFilter, receiptFilter) if len(ret) == 0 { panic("no return value specified for ReachableReceipts") @@ -124,54 +316,110 @@ func (_m *ExecutionTree) ReachableReceipts(resultID flow.Identifier, blockFilter var r0 []*flow.ExecutionReceipt var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, mempool.BlockFilter, mempool.ReceiptFilter) ([]*flow.ExecutionReceipt, error)); ok { - return rf(resultID, blockFilter, receiptFilter) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, mempool.BlockFilter, mempool.ReceiptFilter) ([]*flow.ExecutionReceipt, error)); ok { + return returnFunc(resultID, blockFilter, receiptFilter) } - if rf, ok := ret.Get(0).(func(flow.Identifier, mempool.BlockFilter, mempool.ReceiptFilter) []*flow.ExecutionReceipt); ok { - r0 = rf(resultID, blockFilter, receiptFilter) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, mempool.BlockFilter, mempool.ReceiptFilter) []*flow.ExecutionReceipt); ok { + r0 = returnFunc(resultID, blockFilter, receiptFilter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.ExecutionReceipt) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, mempool.BlockFilter, mempool.ReceiptFilter) error); ok { - r1 = rf(resultID, blockFilter, receiptFilter) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, mempool.BlockFilter, mempool.ReceiptFilter) error); ok { + r1 = returnFunc(resultID, blockFilter, receiptFilter) } else { r1 = ret.Error(1) } - return r0, r1 } -// Size provides a mock function with no fields -func (_m *ExecutionTree) Size() uint { - ret := _m.Called() +// ExecutionTree_ReachableReceipts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReachableReceipts' +type ExecutionTree_ReachableReceipts_Call struct { + *mock.Call +} + +// ReachableReceipts is a helper method to define mock.On call +// - resultID flow.Identifier +// - blockFilter mempool.BlockFilter +// - receiptFilter mempool.ReceiptFilter +func (_e *ExecutionTree_Expecter) ReachableReceipts(resultID interface{}, blockFilter interface{}, receiptFilter interface{}) *ExecutionTree_ReachableReceipts_Call { + return &ExecutionTree_ReachableReceipts_Call{Call: _e.mock.On("ReachableReceipts", resultID, blockFilter, receiptFilter)} +} + +func (_c *ExecutionTree_ReachableReceipts_Call) Run(run func(resultID flow.Identifier, blockFilter mempool.BlockFilter, receiptFilter mempool.ReceiptFilter)) *ExecutionTree_ReachableReceipts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 mempool.BlockFilter + if args[1] != nil { + arg1 = args[1].(mempool.BlockFilter) + } + var arg2 mempool.ReceiptFilter + if args[2] != nil { + arg2 = args[2].(mempool.ReceiptFilter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ExecutionTree_ReachableReceipts_Call) Return(executionReceipts []*flow.ExecutionReceipt, err error) *ExecutionTree_ReachableReceipts_Call { + _c.Call.Return(executionReceipts, err) + return _c +} + +func (_c *ExecutionTree_ReachableReceipts_Call) RunAndReturn(run func(resultID flow.Identifier, blockFilter mempool.BlockFilter, receiptFilter mempool.ReceiptFilter) ([]*flow.ExecutionReceipt, error)) *ExecutionTree_ReachableReceipts_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type ExecutionTree +func (_mock *ExecutionTree) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewExecutionTree creates a new instance of ExecutionTree. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionTree(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionTree { - mock := &ExecutionTree{} - mock.Mock.Test(t) +// ExecutionTree_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type ExecutionTree_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *ExecutionTree_Expecter) Size() *ExecutionTree_Size_Call { + return &ExecutionTree_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *ExecutionTree_Size_Call) Run(run func()) *ExecutionTree_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionTree_Size_Call) Return(v uint) *ExecutionTree_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ExecutionTree_Size_Call) RunAndReturn(run func() uint) *ExecutionTree_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/guarantees.go b/module/mempool/mock/guarantees.go index cd7d2fbf316..21cf1dc1f80 100644 --- a/module/mempool/mock/guarantees.go +++ b/module/mempool/mock/guarantees.go @@ -1,39 +1,101 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewGuarantees creates a new instance of Guarantees. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGuarantees(t interface { + mock.TestingT + Cleanup(func()) +}) *Guarantees { + mock := &Guarantees{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Guarantees is an autogenerated mock type for the Guarantees type type Guarantees struct { mock.Mock } -// Add provides a mock function with given fields: _a0, _a1 -func (_m *Guarantees) Add(_a0 flow.Identifier, _a1 *flow.CollectionGuarantee) bool { - ret := _m.Called(_a0, _a1) +type Guarantees_Expecter struct { + mock *mock.Mock +} + +func (_m *Guarantees) EXPECT() *Guarantees_Expecter { + return &Guarantees_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type Guarantees +func (_mock *Guarantees) Add(identifier flow.Identifier, collectionGuarantee *flow.CollectionGuarantee) bool { + ret := _mock.Called(identifier, collectionGuarantee) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, *flow.CollectionGuarantee) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, *flow.CollectionGuarantee) bool); ok { + r0 = returnFunc(identifier, collectionGuarantee) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *Guarantees) Adjust(key flow.Identifier, f func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) (*flow.CollectionGuarantee, bool) { - ret := _m.Called(key, f) +// Guarantees_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type Guarantees_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - identifier flow.Identifier +// - collectionGuarantee *flow.CollectionGuarantee +func (_e *Guarantees_Expecter) Add(identifier interface{}, collectionGuarantee interface{}) *Guarantees_Add_Call { + return &Guarantees_Add_Call{Call: _e.mock.On("Add", identifier, collectionGuarantee)} +} + +func (_c *Guarantees_Add_Call) Run(run func(identifier flow.Identifier, collectionGuarantee *flow.CollectionGuarantee)) *Guarantees_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 *flow.CollectionGuarantee + if args[1] != nil { + arg1 = args[1].(*flow.CollectionGuarantee) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Guarantees_Add_Call) Return(b bool) *Guarantees_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Guarantees_Add_Call) RunAndReturn(run func(identifier flow.Identifier, collectionGuarantee *flow.CollectionGuarantee) bool) *Guarantees_Add_Call { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type Guarantees +func (_mock *Guarantees) Adjust(key flow.Identifier, f func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) (*flow.CollectionGuarantee, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -41,54 +103,146 @@ func (_m *Guarantees) Adjust(key flow.Identifier, f func(*flow.CollectionGuarant var r0 *flow.CollectionGuarantee var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) (*flow.CollectionGuarantee, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) (*flow.CollectionGuarantee, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) *flow.CollectionGuarantee); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) *flow.CollectionGuarantee); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.CollectionGuarantee) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *Guarantees) All() map[flow.Identifier]*flow.CollectionGuarantee { - ret := _m.Called() +// Guarantees_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type Guarantees_Adjust_Call struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key flow.Identifier +// - f func(*flow.CollectionGuarantee) *flow.CollectionGuarantee +func (_e *Guarantees_Expecter) Adjust(key interface{}, f interface{}) *Guarantees_Adjust_Call { + return &Guarantees_Adjust_Call{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *Guarantees_Adjust_Call) Run(run func(key flow.Identifier, f func(*flow.CollectionGuarantee) *flow.CollectionGuarantee)) *Guarantees_Adjust_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 func(*flow.CollectionGuarantee) *flow.CollectionGuarantee + if args[1] != nil { + arg1 = args[1].(func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Guarantees_Adjust_Call) Return(collectionGuarantee *flow.CollectionGuarantee, b bool) *Guarantees_Adjust_Call { + _c.Call.Return(collectionGuarantee, b) + return _c +} + +func (_c *Guarantees_Adjust_Call) RunAndReturn(run func(key flow.Identifier, f func(*flow.CollectionGuarantee) *flow.CollectionGuarantee) (*flow.CollectionGuarantee, bool)) *Guarantees_Adjust_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type Guarantees +func (_mock *Guarantees) All() map[flow.Identifier]*flow.CollectionGuarantee { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[flow.Identifier]*flow.CollectionGuarantee - if rf, ok := ret.Get(0).(func() map[flow.Identifier]*flow.CollectionGuarantee); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[flow.Identifier]*flow.CollectionGuarantee); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[flow.Identifier]*flow.CollectionGuarantee) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *Guarantees) Clear() { - _m.Called() +// Guarantees_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type Guarantees_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *Guarantees_Expecter) All() *Guarantees_All_Call { + return &Guarantees_All_Call{Call: _e.mock.On("All")} +} + +func (_c *Guarantees_All_Call) Run(run func()) *Guarantees_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Guarantees_All_Call) Return(identifierToCollectionGuarantee map[flow.Identifier]*flow.CollectionGuarantee) *Guarantees_All_Call { + _c.Call.Return(identifierToCollectionGuarantee) + return _c +} + +func (_c *Guarantees_All_Call) RunAndReturn(run func() map[flow.Identifier]*flow.CollectionGuarantee) *Guarantees_All_Call { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type Guarantees +func (_mock *Guarantees) Clear() { + _mock.Called() + return +} + +// Guarantees_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type Guarantees_Clear_Call struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *Guarantees_Expecter) Clear() *Guarantees_Clear_Call { + return &Guarantees_Clear_Call{Call: _e.mock.On("Clear")} +} + +func (_c *Guarantees_Clear_Call) Run(run func()) *Guarantees_Clear_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Guarantees_Clear_Call) Return() *Guarantees_Clear_Call { + _c.Call.Return() + return _c +} + +func (_c *Guarantees_Clear_Call) RunAndReturn(run func()) *Guarantees_Clear_Call { + _c.Run(run) + return _c } -// Get provides a mock function with given fields: _a0 -func (_m *Guarantees) Get(_a0 flow.Identifier) (*flow.CollectionGuarantee, bool) { - ret := _m.Called(_a0) +// Get provides a mock function for the type Guarantees +func (_mock *Guarantees) Get(identifier flow.Identifier) (*flow.CollectionGuarantee, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Get") @@ -96,110 +250,246 @@ func (_m *Guarantees) Get(_a0 flow.Identifier) (*flow.CollectionGuarantee, bool) var r0 *flow.CollectionGuarantee var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.CollectionGuarantee, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.CollectionGuarantee, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.CollectionGuarantee); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.CollectionGuarantee); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.CollectionGuarantee) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: _a0 -func (_m *Guarantees) Has(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// Guarantees_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Guarantees_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Guarantees_Expecter) Get(identifier interface{}) *Guarantees_Get_Call { + return &Guarantees_Get_Call{Call: _e.mock.On("Get", identifier)} +} + +func (_c *Guarantees_Get_Call) Run(run func(identifier flow.Identifier)) *Guarantees_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Guarantees_Get_Call) Return(collectionGuarantee *flow.CollectionGuarantee, b bool) *Guarantees_Get_Call { + _c.Call.Return(collectionGuarantee, b) + return _c +} + +func (_c *Guarantees_Get_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.CollectionGuarantee, bool)) *Guarantees_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type Guarantees +func (_mock *Guarantees) Has(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Remove provides a mock function with given fields: _a0 -func (_m *Guarantees) Remove(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// Guarantees_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type Guarantees_Has_Call struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Guarantees_Expecter) Has(identifier interface{}) *Guarantees_Has_Call { + return &Guarantees_Has_Call{Call: _e.mock.On("Has", identifier)} +} + +func (_c *Guarantees_Has_Call) Run(run func(identifier flow.Identifier)) *Guarantees_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Guarantees_Has_Call) Return(b bool) *Guarantees_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Guarantees_Has_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *Guarantees_Has_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type Guarantees +func (_mock *Guarantees) Remove(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *Guarantees) Size() uint { - ret := _m.Called() +// Guarantees_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type Guarantees_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Guarantees_Expecter) Remove(identifier interface{}) *Guarantees_Remove_Call { + return &Guarantees_Remove_Call{Call: _e.mock.On("Remove", identifier)} +} + +func (_c *Guarantees_Remove_Call) Run(run func(identifier flow.Identifier)) *Guarantees_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Guarantees_Remove_Call) Return(b bool) *Guarantees_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Guarantees_Remove_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *Guarantees_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type Guarantees +func (_mock *Guarantees) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *Guarantees) Values() []*flow.CollectionGuarantee { - ret := _m.Called() +// Guarantees_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type Guarantees_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *Guarantees_Expecter) Size() *Guarantees_Size_Call { + return &Guarantees_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *Guarantees_Size_Call) Run(run func()) *Guarantees_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Guarantees_Size_Call) Return(v uint) *Guarantees_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Guarantees_Size_Call) RunAndReturn(run func() uint) *Guarantees_Size_Call { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type Guarantees +func (_mock *Guarantees) Values() []*flow.CollectionGuarantee { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []*flow.CollectionGuarantee - if rf, ok := ret.Get(0).(func() []*flow.CollectionGuarantee); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*flow.CollectionGuarantee); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.CollectionGuarantee) } } - return r0 } -// NewGuarantees creates a new instance of Guarantees. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGuarantees(t interface { - mock.TestingT - Cleanup(func()) -}) *Guarantees { - mock := &Guarantees{} - mock.Mock.Test(t) +// Guarantees_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type Guarantees_Values_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *Guarantees_Expecter) Values() *Guarantees_Values_Call { + return &Guarantees_Values_Call{Call: _e.mock.On("Values")} +} - return mock +func (_c *Guarantees_Values_Call) Run(run func()) *Guarantees_Values_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Guarantees_Values_Call) Return(collectionGuarantees []*flow.CollectionGuarantee) *Guarantees_Values_Call { + _c.Call.Return(collectionGuarantees) + return _c +} + +func (_c *Guarantees_Values_Call) RunAndReturn(run func() []*flow.CollectionGuarantee) *Guarantees_Values_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/identifier_map.go b/module/mempool/mock/identifier_map.go index 7e52e2fbce1..c4b364b264a 100644 --- a/module/mempool/mock/identifier_map.go +++ b/module/mempool/mock/identifier_map.go @@ -1,26 +1,90 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewIdentifierMap creates a new instance of IdentifierMap. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIdentifierMap(t interface { + mock.TestingT + Cleanup(func()) +}) *IdentifierMap { + mock := &IdentifierMap{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IdentifierMap is an autogenerated mock type for the IdentifierMap type type IdentifierMap struct { mock.Mock } -// Append provides a mock function with given fields: key, id -func (_m *IdentifierMap) Append(key flow.Identifier, id flow.Identifier) { - _m.Called(key, id) +type IdentifierMap_Expecter struct { + mock *mock.Mock +} + +func (_m *IdentifierMap) EXPECT() *IdentifierMap_Expecter { + return &IdentifierMap_Expecter{mock: &_m.Mock} +} + +// Append provides a mock function for the type IdentifierMap +func (_mock *IdentifierMap) Append(key flow.Identifier, id flow.Identifier) { + _mock.Called(key, id) + return +} + +// IdentifierMap_Append_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Append' +type IdentifierMap_Append_Call struct { + *mock.Call } -// Get provides a mock function with given fields: key -func (_m *IdentifierMap) Get(key flow.Identifier) (flow.IdentifierList, bool) { - ret := _m.Called(key) +// Append is a helper method to define mock.On call +// - key flow.Identifier +// - id flow.Identifier +func (_e *IdentifierMap_Expecter) Append(key interface{}, id interface{}) *IdentifierMap_Append_Call { + return &IdentifierMap_Append_Call{Call: _e.mock.On("Append", key, id)} +} + +func (_c *IdentifierMap_Append_Call) Run(run func(key flow.Identifier, id flow.Identifier)) *IdentifierMap_Append_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *IdentifierMap_Append_Call) Return() *IdentifierMap_Append_Call { + _c.Call.Return() + return _c +} + +func (_c *IdentifierMap_Append_Call) RunAndReturn(run func(key flow.Identifier, id flow.Identifier)) *IdentifierMap_Append_Call { + _c.Run(run) + return _c +} + +// Get provides a mock function for the type IdentifierMap +func (_mock *IdentifierMap) Get(key flow.Identifier) (flow.IdentifierList, bool) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Get") @@ -28,47 +92,112 @@ func (_m *IdentifierMap) Get(key flow.Identifier) (flow.IdentifierList, bool) { var r0 flow.IdentifierList var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.IdentifierList, bool)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.IdentifierList, bool)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.IdentifierList); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.IdentifierList); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentifierList) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(key) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: key -func (_m *IdentifierMap) Has(key flow.Identifier) bool { - ret := _m.Called(key) +// IdentifierMap_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type IdentifierMap_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - key flow.Identifier +func (_e *IdentifierMap_Expecter) Get(key interface{}) *IdentifierMap_Get_Call { + return &IdentifierMap_Get_Call{Call: _e.mock.On("Get", key)} +} + +func (_c *IdentifierMap_Get_Call) Run(run func(key flow.Identifier)) *IdentifierMap_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IdentifierMap_Get_Call) Return(identifierList flow.IdentifierList, b bool) *IdentifierMap_Get_Call { + _c.Call.Return(identifierList, b) + return _c +} + +func (_c *IdentifierMap_Get_Call) RunAndReturn(run func(key flow.Identifier) (flow.IdentifierList, bool)) *IdentifierMap_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type IdentifierMap +func (_mock *IdentifierMap) Has(key flow.Identifier) bool { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(key) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Keys provides a mock function with no fields -func (_m *IdentifierMap) Keys() (flow.IdentifierList, bool) { - ret := _m.Called() +// IdentifierMap_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type IdentifierMap_Has_Call struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - key flow.Identifier +func (_e *IdentifierMap_Expecter) Has(key interface{}) *IdentifierMap_Has_Call { + return &IdentifierMap_Has_Call{Call: _e.mock.On("Has", key)} +} + +func (_c *IdentifierMap_Has_Call) Run(run func(key flow.Identifier)) *IdentifierMap_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IdentifierMap_Has_Call) Return(b bool) *IdentifierMap_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *IdentifierMap_Has_Call) RunAndReturn(run func(key flow.Identifier) bool) *IdentifierMap_Has_Call { + _c.Call.Return(run) + return _c +} + +// Keys provides a mock function for the type IdentifierMap +func (_mock *IdentifierMap) Keys() (flow.IdentifierList, bool) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Keys") @@ -76,90 +205,199 @@ func (_m *IdentifierMap) Keys() (flow.IdentifierList, bool) { var r0 flow.IdentifierList var r1 bool - if rf, ok := ret.Get(0).(func() (flow.IdentifierList, bool)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.IdentifierList, bool)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.IdentifierList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentifierList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentifierList) } } - - if rf, ok := ret.Get(1).(func() bool); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Remove provides a mock function with given fields: key -func (_m *IdentifierMap) Remove(key flow.Identifier) bool { - ret := _m.Called(key) +// IdentifierMap_Keys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Keys' +type IdentifierMap_Keys_Call struct { + *mock.Call +} + +// Keys is a helper method to define mock.On call +func (_e *IdentifierMap_Expecter) Keys() *IdentifierMap_Keys_Call { + return &IdentifierMap_Keys_Call{Call: _e.mock.On("Keys")} +} + +func (_c *IdentifierMap_Keys_Call) Run(run func()) *IdentifierMap_Keys_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IdentifierMap_Keys_Call) Return(identifierList flow.IdentifierList, b bool) *IdentifierMap_Keys_Call { + _c.Call.Return(identifierList, b) + return _c +} + +func (_c *IdentifierMap_Keys_Call) RunAndReturn(run func() (flow.IdentifierList, bool)) *IdentifierMap_Keys_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type IdentifierMap +func (_mock *IdentifierMap) Remove(key flow.Identifier) bool { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(key) } else { r0 = ret.Get(0).(bool) } - return r0 } -// RemoveIdFromKey provides a mock function with given fields: key, id -func (_m *IdentifierMap) RemoveIdFromKey(key flow.Identifier, id flow.Identifier) error { - ret := _m.Called(key, id) +// IdentifierMap_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type IdentifierMap_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - key flow.Identifier +func (_e *IdentifierMap_Expecter) Remove(key interface{}) *IdentifierMap_Remove_Call { + return &IdentifierMap_Remove_Call{Call: _e.mock.On("Remove", key)} +} + +func (_c *IdentifierMap_Remove_Call) Run(run func(key flow.Identifier)) *IdentifierMap_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IdentifierMap_Remove_Call) Return(b bool) *IdentifierMap_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *IdentifierMap_Remove_Call) RunAndReturn(run func(key flow.Identifier) bool) *IdentifierMap_Remove_Call { + _c.Call.Return(run) + return _c +} + +// RemoveIdFromKey provides a mock function for the type IdentifierMap +func (_mock *IdentifierMap) RemoveIdFromKey(key flow.Identifier, id flow.Identifier) error { + ret := _mock.Called(key, id) if len(ret) == 0 { panic("no return value specified for RemoveIdFromKey") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) error); ok { - r0 = rf(key, id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) error); ok { + r0 = returnFunc(key, id) } else { r0 = ret.Error(0) } - return r0 } -// Size provides a mock function with no fields -func (_m *IdentifierMap) Size() uint { - ret := _m.Called() +// IdentifierMap_RemoveIdFromKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemoveIdFromKey' +type IdentifierMap_RemoveIdFromKey_Call struct { + *mock.Call +} + +// RemoveIdFromKey is a helper method to define mock.On call +// - key flow.Identifier +// - id flow.Identifier +func (_e *IdentifierMap_Expecter) RemoveIdFromKey(key interface{}, id interface{}) *IdentifierMap_RemoveIdFromKey_Call { + return &IdentifierMap_RemoveIdFromKey_Call{Call: _e.mock.On("RemoveIdFromKey", key, id)} +} + +func (_c *IdentifierMap_RemoveIdFromKey_Call) Run(run func(key flow.Identifier, id flow.Identifier)) *IdentifierMap_RemoveIdFromKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *IdentifierMap_RemoveIdFromKey_Call) Return(err error) *IdentifierMap_RemoveIdFromKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *IdentifierMap_RemoveIdFromKey_Call) RunAndReturn(run func(key flow.Identifier, id flow.Identifier) error) *IdentifierMap_RemoveIdFromKey_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type IdentifierMap +func (_mock *IdentifierMap) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewIdentifierMap creates a new instance of IdentifierMap. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIdentifierMap(t interface { - mock.TestingT - Cleanup(func()) -}) *IdentifierMap { - mock := &IdentifierMap{} - mock.Mock.Test(t) +// IdentifierMap_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type IdentifierMap_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *IdentifierMap_Expecter) Size() *IdentifierMap_Size_Call { + return &IdentifierMap_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *IdentifierMap_Size_Call) Run(run func()) *IdentifierMap_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IdentifierMap_Size_Call) Return(v uint) *IdentifierMap_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *IdentifierMap_Size_Call) RunAndReturn(run func() uint) *IdentifierMap_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/incorporated_result_seals.go b/module/mempool/mock/incorporated_result_seals.go index afb3e1426da..a354743128c 100644 --- a/module/mempool/mock/incorporated_result_seals.go +++ b/module/mempool/mock/incorporated_result_seals.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewIncorporatedResultSeals creates a new instance of IncorporatedResultSeals. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIncorporatedResultSeals(t interface { + mock.TestingT + Cleanup(func()) +}) *IncorporatedResultSeals { + mock := &IncorporatedResultSeals{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IncorporatedResultSeals is an autogenerated mock type for the IncorporatedResultSeals type type IncorporatedResultSeals struct { mock.Mock } -// Add provides a mock function with given fields: irSeal -func (_m *IncorporatedResultSeals) Add(irSeal *flow.IncorporatedResultSeal) (bool, error) { - ret := _m.Called(irSeal) +type IncorporatedResultSeals_Expecter struct { + mock *mock.Mock +} + +func (_m *IncorporatedResultSeals) EXPECT() *IncorporatedResultSeals_Expecter { + return &IncorporatedResultSeals_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) Add(irSeal *flow.IncorporatedResultSeal) (bool, error) { + ret := _mock.Called(irSeal) if len(ret) == 0 { panic("no return value specified for Add") @@ -23,52 +46,138 @@ func (_m *IncorporatedResultSeals) Add(irSeal *flow.IncorporatedResultSeal) (boo var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*flow.IncorporatedResultSeal) (bool, error)); ok { - return rf(irSeal) + if returnFunc, ok := ret.Get(0).(func(*flow.IncorporatedResultSeal) (bool, error)); ok { + return returnFunc(irSeal) } - if rf, ok := ret.Get(0).(func(*flow.IncorporatedResultSeal) bool); ok { - r0 = rf(irSeal) + if returnFunc, ok := ret.Get(0).(func(*flow.IncorporatedResultSeal) bool); ok { + r0 = returnFunc(irSeal) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*flow.IncorporatedResultSeal) error); ok { - r1 = rf(irSeal) + if returnFunc, ok := ret.Get(1).(func(*flow.IncorporatedResultSeal) error); ok { + r1 = returnFunc(irSeal) } else { r1 = ret.Error(1) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *IncorporatedResultSeals) All() []*flow.IncorporatedResultSeal { - ret := _m.Called() +// IncorporatedResultSeals_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type IncorporatedResultSeals_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - irSeal *flow.IncorporatedResultSeal +func (_e *IncorporatedResultSeals_Expecter) Add(irSeal interface{}) *IncorporatedResultSeals_Add_Call { + return &IncorporatedResultSeals_Add_Call{Call: _e.mock.On("Add", irSeal)} +} + +func (_c *IncorporatedResultSeals_Add_Call) Run(run func(irSeal *flow.IncorporatedResultSeal)) *IncorporatedResultSeals_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.IncorporatedResultSeal + if args[0] != nil { + arg0 = args[0].(*flow.IncorporatedResultSeal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IncorporatedResultSeals_Add_Call) Return(b bool, err error) *IncorporatedResultSeals_Add_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *IncorporatedResultSeals_Add_Call) RunAndReturn(run func(irSeal *flow.IncorporatedResultSeal) (bool, error)) *IncorporatedResultSeals_Add_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) All() []*flow.IncorporatedResultSeal { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 []*flow.IncorporatedResultSeal - if rf, ok := ret.Get(0).(func() []*flow.IncorporatedResultSeal); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*flow.IncorporatedResultSeal); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.IncorporatedResultSeal) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *IncorporatedResultSeals) Clear() { - _m.Called() +// IncorporatedResultSeals_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type IncorporatedResultSeals_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *IncorporatedResultSeals_Expecter) All() *IncorporatedResultSeals_All_Call { + return &IncorporatedResultSeals_All_Call{Call: _e.mock.On("All")} +} + +func (_c *IncorporatedResultSeals_All_Call) Run(run func()) *IncorporatedResultSeals_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// Get provides a mock function with given fields: _a0 -func (_m *IncorporatedResultSeals) Get(_a0 flow.Identifier) (*flow.IncorporatedResultSeal, bool) { - ret := _m.Called(_a0) +func (_c *IncorporatedResultSeals_All_Call) Return(incorporatedResultSeals []*flow.IncorporatedResultSeal) *IncorporatedResultSeals_All_Call { + _c.Call.Return(incorporatedResultSeals) + return _c +} + +func (_c *IncorporatedResultSeals_All_Call) RunAndReturn(run func() []*flow.IncorporatedResultSeal) *IncorporatedResultSeals_All_Call { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) Clear() { + _mock.Called() + return +} + +// IncorporatedResultSeals_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type IncorporatedResultSeals_Clear_Call struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *IncorporatedResultSeals_Expecter) Clear() *IncorporatedResultSeals_Clear_Call { + return &IncorporatedResultSeals_Clear_Call{Call: _e.mock.On("Clear")} +} + +func (_c *IncorporatedResultSeals_Clear_Call) Run(run func()) *IncorporatedResultSeals_Clear_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncorporatedResultSeals_Clear_Call) Return() *IncorporatedResultSeals_Clear_Call { + _c.Call.Return() + return _c +} + +func (_c *IncorporatedResultSeals_Clear_Call) RunAndReturn(run func()) *IncorporatedResultSeals_Clear_Call { + _c.Run(run) + return _c +} + +// Get provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) Get(identifier flow.Identifier) (*flow.IncorporatedResultSeal, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Get") @@ -76,108 +185,244 @@ func (_m *IncorporatedResultSeals) Get(_a0 flow.Identifier) (*flow.IncorporatedR var r0 *flow.IncorporatedResultSeal var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.IncorporatedResultSeal, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.IncorporatedResultSeal, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.IncorporatedResultSeal); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.IncorporatedResultSeal); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.IncorporatedResultSeal) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Limit provides a mock function with no fields -func (_m *IncorporatedResultSeals) Limit() uint { - ret := _m.Called() +// IncorporatedResultSeals_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type IncorporatedResultSeals_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *IncorporatedResultSeals_Expecter) Get(identifier interface{}) *IncorporatedResultSeals_Get_Call { + return &IncorporatedResultSeals_Get_Call{Call: _e.mock.On("Get", identifier)} +} + +func (_c *IncorporatedResultSeals_Get_Call) Run(run func(identifier flow.Identifier)) *IncorporatedResultSeals_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IncorporatedResultSeals_Get_Call) Return(incorporatedResultSeal *flow.IncorporatedResultSeal, b bool) *IncorporatedResultSeals_Get_Call { + _c.Call.Return(incorporatedResultSeal, b) + return _c +} + +func (_c *IncorporatedResultSeals_Get_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.IncorporatedResultSeal, bool)) *IncorporatedResultSeals_Get_Call { + _c.Call.Return(run) + return _c +} + +// Limit provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) Limit() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Limit") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// PruneUpToHeight provides a mock function with given fields: height -func (_m *IncorporatedResultSeals) PruneUpToHeight(height uint64) error { - ret := _m.Called(height) +// IncorporatedResultSeals_Limit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Limit' +type IncorporatedResultSeals_Limit_Call struct { + *mock.Call +} + +// Limit is a helper method to define mock.On call +func (_e *IncorporatedResultSeals_Expecter) Limit() *IncorporatedResultSeals_Limit_Call { + return &IncorporatedResultSeals_Limit_Call{Call: _e.mock.On("Limit")} +} + +func (_c *IncorporatedResultSeals_Limit_Call) Run(run func()) *IncorporatedResultSeals_Limit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncorporatedResultSeals_Limit_Call) Return(v uint) *IncorporatedResultSeals_Limit_Call { + _c.Call.Return(v) + return _c +} + +func (_c *IncorporatedResultSeals_Limit_Call) RunAndReturn(run func() uint) *IncorporatedResultSeals_Limit_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToHeight provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) PruneUpToHeight(height uint64) error { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for PruneUpToHeight") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(height) } else { r0 = ret.Error(0) } - return r0 } -// Remove provides a mock function with given fields: incorporatedResultID -func (_m *IncorporatedResultSeals) Remove(incorporatedResultID flow.Identifier) bool { - ret := _m.Called(incorporatedResultID) +// IncorporatedResultSeals_PruneUpToHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToHeight' +type IncorporatedResultSeals_PruneUpToHeight_Call struct { + *mock.Call +} + +// PruneUpToHeight is a helper method to define mock.On call +// - height uint64 +func (_e *IncorporatedResultSeals_Expecter) PruneUpToHeight(height interface{}) *IncorporatedResultSeals_PruneUpToHeight_Call { + return &IncorporatedResultSeals_PruneUpToHeight_Call{Call: _e.mock.On("PruneUpToHeight", height)} +} + +func (_c *IncorporatedResultSeals_PruneUpToHeight_Call) Run(run func(height uint64)) *IncorporatedResultSeals_PruneUpToHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IncorporatedResultSeals_PruneUpToHeight_Call) Return(err error) *IncorporatedResultSeals_PruneUpToHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *IncorporatedResultSeals_PruneUpToHeight_Call) RunAndReturn(run func(height uint64) error) *IncorporatedResultSeals_PruneUpToHeight_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) Remove(incorporatedResultID flow.Identifier) bool { + ret := _mock.Called(incorporatedResultID) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(incorporatedResultID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(incorporatedResultID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *IncorporatedResultSeals) Size() uint { - ret := _m.Called() +// IncorporatedResultSeals_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type IncorporatedResultSeals_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - incorporatedResultID flow.Identifier +func (_e *IncorporatedResultSeals_Expecter) Remove(incorporatedResultID interface{}) *IncorporatedResultSeals_Remove_Call { + return &IncorporatedResultSeals_Remove_Call{Call: _e.mock.On("Remove", incorporatedResultID)} +} + +func (_c *IncorporatedResultSeals_Remove_Call) Run(run func(incorporatedResultID flow.Identifier)) *IncorporatedResultSeals_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IncorporatedResultSeals_Remove_Call) Return(b bool) *IncorporatedResultSeals_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *IncorporatedResultSeals_Remove_Call) RunAndReturn(run func(incorporatedResultID flow.Identifier) bool) *IncorporatedResultSeals_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type IncorporatedResultSeals +func (_mock *IncorporatedResultSeals) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewIncorporatedResultSeals creates a new instance of IncorporatedResultSeals. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIncorporatedResultSeals(t interface { - mock.TestingT - Cleanup(func()) -}) *IncorporatedResultSeals { - mock := &IncorporatedResultSeals{} - mock.Mock.Test(t) +// IncorporatedResultSeals_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type IncorporatedResultSeals_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *IncorporatedResultSeals_Expecter) Size() *IncorporatedResultSeals_Size_Call { + return &IncorporatedResultSeals_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *IncorporatedResultSeals_Size_Call) Run(run func()) *IncorporatedResultSeals_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncorporatedResultSeals_Size_Call) Return(v uint) *IncorporatedResultSeals_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *IncorporatedResultSeals_Size_Call) RunAndReturn(run func() uint) *IncorporatedResultSeals_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/mempool.go b/module/mempool/mock/mempool.go index b1b555994ea..caf3259bf57 100644 --- a/module/mempool/mock/mempool.go +++ b/module/mempool/mock/mempool.go @@ -1,35 +1,100 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewMempool creates a new instance of Mempool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMempool[K comparable, V any](t interface { + mock.TestingT + Cleanup(func()) +}) *Mempool[K, V] { + mock := &Mempool[K, V]{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Mempool is an autogenerated mock type for the Mempool type type Mempool[K comparable, V any] struct { mock.Mock } -// Add provides a mock function with given fields: _a0, _a1 -func (_m *Mempool[K, V]) Add(_a0 K, _a1 V) bool { - ret := _m.Called(_a0, _a1) +type Mempool_Expecter[K comparable, V any] struct { + mock *mock.Mock +} + +func (_m *Mempool[K, V]) EXPECT() *Mempool_Expecter[K, V] { + return &Mempool_Expecter[K, V]{mock: &_m.Mock} +} + +// Add provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Add(v K, v1 V) bool { + ret := _mock.Called(v, v1) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(K, V) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(K, V) bool); ok { + r0 = returnFunc(v, v1) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *Mempool[K, V]) Adjust(key K, f func(V) V) (V, bool) { - ret := _m.Called(key, f) +// Mempool_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type Mempool_Add_Call[K comparable, V any] struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - v K +// - v1 V +func (_e *Mempool_Expecter[K, V]) Add(v interface{}, v1 interface{}) *Mempool_Add_Call[K, V] { + return &Mempool_Add_Call[K, V]{Call: _e.mock.On("Add", v, v1)} +} + +func (_c *Mempool_Add_Call[K, V]) Run(run func(v K, v1 V)) *Mempool_Add_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + var arg1 V + if args[1] != nil { + arg1 = args[1].(V) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Mempool_Add_Call[K, V]) Return(b bool) *Mempool_Add_Call[K, V] { + _c.Call.Return(b) + return _c +} + +func (_c *Mempool_Add_Call[K, V]) RunAndReturn(run func(v K, v1 V) bool) *Mempool_Add_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Adjust(key K, f func(V) V) (V, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -37,54 +102,146 @@ func (_m *Mempool[K, V]) Adjust(key K, f func(V) V) (V, bool) { var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K, func(V) V) (V, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(K, func(V) V) (V, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(K, func(V) V) V); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(K, func(V) V) V); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K, func(V) V) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(K, func(V) V) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *Mempool[K, V]) All() map[K]V { - ret := _m.Called() +// Mempool_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type Mempool_Adjust_Call[K comparable, V any] struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key K +// - f func(V) V +func (_e *Mempool_Expecter[K, V]) Adjust(key interface{}, f interface{}) *Mempool_Adjust_Call[K, V] { + return &Mempool_Adjust_Call[K, V]{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *Mempool_Adjust_Call[K, V]) Run(run func(key K, f func(V) V)) *Mempool_Adjust_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + var arg1 func(V) V + if args[1] != nil { + arg1 = args[1].(func(V) V) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Mempool_Adjust_Call[K, V]) Return(v V, b bool) *Mempool_Adjust_Call[K, V] { + _c.Call.Return(v, b) + return _c +} + +func (_c *Mempool_Adjust_Call[K, V]) RunAndReturn(run func(key K, f func(V) V) (V, bool)) *Mempool_Adjust_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) All() map[K]V { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[K]V - if rf, ok := ret.Get(0).(func() map[K]V); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[K]V); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[K]V) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *Mempool[K, V]) Clear() { - _m.Called() +// Mempool_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type Mempool_All_Call[K comparable, V any] struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *Mempool_Expecter[K, V]) All() *Mempool_All_Call[K, V] { + return &Mempool_All_Call[K, V]{Call: _e.mock.On("All")} +} + +func (_c *Mempool_All_Call[K, V]) Run(run func()) *Mempool_All_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Mempool_All_Call[K, V]) Return(vToV map[K]V) *Mempool_All_Call[K, V] { + _c.Call.Return(vToV) + return _c +} + +func (_c *Mempool_All_Call[K, V]) RunAndReturn(run func() map[K]V) *Mempool_All_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Clear() { + _mock.Called() + return +} + +// Mempool_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type Mempool_Clear_Call[K comparable, V any] struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *Mempool_Expecter[K, V]) Clear() *Mempool_Clear_Call[K, V] { + return &Mempool_Clear_Call[K, V]{Call: _e.mock.On("Clear")} +} + +func (_c *Mempool_Clear_Call[K, V]) Run(run func()) *Mempool_Clear_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Mempool_Clear_Call[K, V]) Return() *Mempool_Clear_Call[K, V] { + _c.Call.Return() + return _c +} + +func (_c *Mempool_Clear_Call[K, V]) RunAndReturn(run func()) *Mempool_Clear_Call[K, V] { + _c.Run(run) + return _c } -// Get provides a mock function with given fields: _a0 -func (_m *Mempool[K, V]) Get(_a0 K) (V, bool) { - ret := _m.Called(_a0) +// Get provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Get(v K) (V, bool) { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for Get") @@ -92,110 +249,246 @@ func (_m *Mempool[K, V]) Get(_a0 K) (V, bool) { var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K) (V, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(K) (V, bool)); ok { + return returnFunc(v) } - if rf, ok := ret.Get(0).(func(K) V); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(K) V); ok { + r0 = returnFunc(v) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(K) bool); ok { + r1 = returnFunc(v) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: _a0 -func (_m *Mempool[K, V]) Has(_a0 K) bool { - ret := _m.Called(_a0) +// Mempool_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Mempool_Get_Call[K comparable, V any] struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - v K +func (_e *Mempool_Expecter[K, V]) Get(v interface{}) *Mempool_Get_Call[K, V] { + return &Mempool_Get_Call[K, V]{Call: _e.mock.On("Get", v)} +} + +func (_c *Mempool_Get_Call[K, V]) Run(run func(v K)) *Mempool_Get_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Mempool_Get_Call[K, V]) Return(v1 V, b bool) *Mempool_Get_Call[K, V] { + _c.Call.Return(v1, b) + return _c +} + +func (_c *Mempool_Get_Call[K, V]) RunAndReturn(run func(v K) (V, bool)) *Mempool_Get_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Has(v K) bool { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(K) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(K) bool); ok { + r0 = returnFunc(v) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Remove provides a mock function with given fields: _a0 -func (_m *Mempool[K, V]) Remove(_a0 K) bool { - ret := _m.Called(_a0) +// Mempool_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type Mempool_Has_Call[K comparable, V any] struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - v K +func (_e *Mempool_Expecter[K, V]) Has(v interface{}) *Mempool_Has_Call[K, V] { + return &Mempool_Has_Call[K, V]{Call: _e.mock.On("Has", v)} +} + +func (_c *Mempool_Has_Call[K, V]) Run(run func(v K)) *Mempool_Has_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Mempool_Has_Call[K, V]) Return(b bool) *Mempool_Has_Call[K, V] { + _c.Call.Return(b) + return _c +} + +func (_c *Mempool_Has_Call[K, V]) RunAndReturn(run func(v K) bool) *Mempool_Has_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Remove(v K) bool { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(K) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(K) bool); ok { + r0 = returnFunc(v) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *Mempool[K, V]) Size() uint { - ret := _m.Called() +// Mempool_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type Mempool_Remove_Call[K comparable, V any] struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - v K +func (_e *Mempool_Expecter[K, V]) Remove(v interface{}) *Mempool_Remove_Call[K, V] { + return &Mempool_Remove_Call[K, V]{Call: _e.mock.On("Remove", v)} +} + +func (_c *Mempool_Remove_Call[K, V]) Run(run func(v K)) *Mempool_Remove_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Mempool_Remove_Call[K, V]) Return(b bool) *Mempool_Remove_Call[K, V] { + _c.Call.Return(b) + return _c +} + +func (_c *Mempool_Remove_Call[K, V]) RunAndReturn(run func(v K) bool) *Mempool_Remove_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *Mempool[K, V]) Values() []V { - ret := _m.Called() +// Mempool_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type Mempool_Size_Call[K comparable, V any] struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *Mempool_Expecter[K, V]) Size() *Mempool_Size_Call[K, V] { + return &Mempool_Size_Call[K, V]{Call: _e.mock.On("Size")} +} + +func (_c *Mempool_Size_Call[K, V]) Run(run func()) *Mempool_Size_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Mempool_Size_Call[K, V]) Return(v uint) *Mempool_Size_Call[K, V] { + _c.Call.Return(v) + return _c +} + +func (_c *Mempool_Size_Call[K, V]) RunAndReturn(run func() uint) *Mempool_Size_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type Mempool +func (_mock *Mempool[K, V]) Values() []V { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []V - if rf, ok := ret.Get(0).(func() []V); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []V); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]V) } } - return r0 } -// NewMempool creates a new instance of Mempool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMempool[K comparable, V any](t interface { - mock.TestingT - Cleanup(func()) -}) *Mempool[K, V] { - mock := &Mempool[K, V]{} - mock.Mock.Test(t) +// Mempool_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type Mempool_Values_Call[K comparable, V any] struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *Mempool_Expecter[K, V]) Values() *Mempool_Values_Call[K, V] { + return &Mempool_Values_Call[K, V]{Call: _e.mock.On("Values")} +} - return mock +func (_c *Mempool_Values_Call[K, V]) Run(run func()) *Mempool_Values_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Mempool_Values_Call[K, V]) Return(vs []V) *Mempool_Values_Call[K, V] { + _c.Call.Return(vs) + return _c +} + +func (_c *Mempool_Values_Call[K, V]) RunAndReturn(run func() []V) *Mempool_Values_Call[K, V] { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/mutable_back_data.go b/module/mempool/mock/mutable_back_data.go index bc330255a7f..def6d6cee8f 100644 --- a/module/mempool/mock/mutable_back_data.go +++ b/module/mempool/mock/mutable_back_data.go @@ -1,35 +1,100 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewMutableBackData creates a new instance of MutableBackData. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMutableBackData[K comparable, V any](t interface { + mock.TestingT + Cleanup(func()) +}) *MutableBackData[K, V] { + mock := &MutableBackData[K, V]{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // MutableBackData is an autogenerated mock type for the MutableBackData type type MutableBackData[K comparable, V any] struct { mock.Mock } -// Add provides a mock function with given fields: key, value -func (_m *MutableBackData[K, V]) Add(key K, value V) bool { - ret := _m.Called(key, value) +type MutableBackData_Expecter[K comparable, V any] struct { + mock *mock.Mock +} + +func (_m *MutableBackData[K, V]) EXPECT() *MutableBackData_Expecter[K, V] { + return &MutableBackData_Expecter[K, V]{mock: &_m.Mock} +} + +// Add provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Add(key K, value V) bool { + ret := _mock.Called(key, value) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(K, V) bool); ok { - r0 = rf(key, value) + if returnFunc, ok := ret.Get(0).(func(K, V) bool); ok { + r0 = returnFunc(key, value) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *MutableBackData[K, V]) Adjust(key K, f func(V) V) (V, bool) { - ret := _m.Called(key, f) +// MutableBackData_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type MutableBackData_Add_Call[K comparable, V any] struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - key K +// - value V +func (_e *MutableBackData_Expecter[K, V]) Add(key interface{}, value interface{}) *MutableBackData_Add_Call[K, V] { + return &MutableBackData_Add_Call[K, V]{Call: _e.mock.On("Add", key, value)} +} + +func (_c *MutableBackData_Add_Call[K, V]) Run(run func(key K, value V)) *MutableBackData_Add_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + var arg1 V + if args[1] != nil { + arg1 = args[1].(V) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MutableBackData_Add_Call[K, V]) Return(b bool) *MutableBackData_Add_Call[K, V] { + _c.Call.Return(b) + return _c +} + +func (_c *MutableBackData_Add_Call[K, V]) RunAndReturn(run func(key K, value V) bool) *MutableBackData_Add_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Adjust(key K, f func(value V) V) (V, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -37,29 +102,67 @@ func (_m *MutableBackData[K, V]) Adjust(key K, f func(V) V) (V, bool) { var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K, func(V) V) (V, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(K, func(value V) V) (V, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(K, func(V) V) V); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(K, func(value V) V) V); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K, func(V) V) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(K, func(value V) V) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// AdjustWithInit provides a mock function with given fields: key, adjust, init -func (_m *MutableBackData[K, V]) AdjustWithInit(key K, adjust func(V) V, init func() V) (V, bool) { - ret := _m.Called(key, adjust, init) +// MutableBackData_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type MutableBackData_Adjust_Call[K comparable, V any] struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key K +// - f func(value V) V +func (_e *MutableBackData_Expecter[K, V]) Adjust(key interface{}, f interface{}) *MutableBackData_Adjust_Call[K, V] { + return &MutableBackData_Adjust_Call[K, V]{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *MutableBackData_Adjust_Call[K, V]) Run(run func(key K, f func(value V) V)) *MutableBackData_Adjust_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + var arg1 func(value V) V + if args[1] != nil { + arg1 = args[1].(func(value V) V) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MutableBackData_Adjust_Call[K, V]) Return(v V, b bool) *MutableBackData_Adjust_Call[K, V] { + _c.Call.Return(v, b) + return _c +} + +func (_c *MutableBackData_Adjust_Call[K, V]) RunAndReturn(run func(key K, f func(value V) V) (V, bool)) *MutableBackData_Adjust_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// AdjustWithInit provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) AdjustWithInit(key K, adjust func(value V) V, init func() V) (V, bool) { + ret := _mock.Called(key, adjust, init) if len(ret) == 0 { panic("no return value specified for AdjustWithInit") @@ -67,54 +170,152 @@ func (_m *MutableBackData[K, V]) AdjustWithInit(key K, adjust func(V) V, init fu var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K, func(V) V, func() V) (V, bool)); ok { - return rf(key, adjust, init) + if returnFunc, ok := ret.Get(0).(func(K, func(value V) V, func() V) (V, bool)); ok { + return returnFunc(key, adjust, init) } - if rf, ok := ret.Get(0).(func(K, func(V) V, func() V) V); ok { - r0 = rf(key, adjust, init) + if returnFunc, ok := ret.Get(0).(func(K, func(value V) V, func() V) V); ok { + r0 = returnFunc(key, adjust, init) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K, func(V) V, func() V) bool); ok { - r1 = rf(key, adjust, init) + if returnFunc, ok := ret.Get(1).(func(K, func(value V) V, func() V) bool); ok { + r1 = returnFunc(key, adjust, init) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *MutableBackData[K, V]) All() map[K]V { - ret := _m.Called() +// MutableBackData_AdjustWithInit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AdjustWithInit' +type MutableBackData_AdjustWithInit_Call[K comparable, V any] struct { + *mock.Call +} + +// AdjustWithInit is a helper method to define mock.On call +// - key K +// - adjust func(value V) V +// - init func() V +func (_e *MutableBackData_Expecter[K, V]) AdjustWithInit(key interface{}, adjust interface{}, init interface{}) *MutableBackData_AdjustWithInit_Call[K, V] { + return &MutableBackData_AdjustWithInit_Call[K, V]{Call: _e.mock.On("AdjustWithInit", key, adjust, init)} +} + +func (_c *MutableBackData_AdjustWithInit_Call[K, V]) Run(run func(key K, adjust func(value V) V, init func() V)) *MutableBackData_AdjustWithInit_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + var arg1 func(value V) V + if args[1] != nil { + arg1 = args[1].(func(value V) V) + } + var arg2 func() V + if args[2] != nil { + arg2 = args[2].(func() V) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *MutableBackData_AdjustWithInit_Call[K, V]) Return(v V, b bool) *MutableBackData_AdjustWithInit_Call[K, V] { + _c.Call.Return(v, b) + return _c +} + +func (_c *MutableBackData_AdjustWithInit_Call[K, V]) RunAndReturn(run func(key K, adjust func(value V) V, init func() V) (V, bool)) *MutableBackData_AdjustWithInit_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) All() map[K]V { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[K]V - if rf, ok := ret.Get(0).(func() map[K]V); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[K]V); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[K]V) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *MutableBackData[K, V]) Clear() { - _m.Called() +// MutableBackData_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type MutableBackData_All_Call[K comparable, V any] struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *MutableBackData_Expecter[K, V]) All() *MutableBackData_All_Call[K, V] { + return &MutableBackData_All_Call[K, V]{Call: _e.mock.On("All")} +} + +func (_c *MutableBackData_All_Call[K, V]) Run(run func()) *MutableBackData_All_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableBackData_All_Call[K, V]) Return(vToV map[K]V) *MutableBackData_All_Call[K, V] { + _c.Call.Return(vToV) + return _c +} + +func (_c *MutableBackData_All_Call[K, V]) RunAndReturn(run func() map[K]V) *MutableBackData_All_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Clear() { + _mock.Called() + return +} + +// MutableBackData_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type MutableBackData_Clear_Call[K comparable, V any] struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *MutableBackData_Expecter[K, V]) Clear() *MutableBackData_Clear_Call[K, V] { + return &MutableBackData_Clear_Call[K, V]{Call: _e.mock.On("Clear")} +} + +func (_c *MutableBackData_Clear_Call[K, V]) Run(run func()) *MutableBackData_Clear_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableBackData_Clear_Call[K, V]) Return() *MutableBackData_Clear_Call[K, V] { + _c.Call.Return() + return _c } -// Get provides a mock function with given fields: key -func (_m *MutableBackData[K, V]) Get(key K) (V, bool) { - ret := _m.Called(key) +func (_c *MutableBackData_Clear_Call[K, V]) RunAndReturn(run func()) *MutableBackData_Clear_Call[K, V] { + _c.Run(run) + return _c +} + +// Get provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Get(key K) (V, bool) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Get") @@ -122,67 +323,158 @@ func (_m *MutableBackData[K, V]) Get(key K) (V, bool) { var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K) (V, bool)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func(K) (V, bool)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func(K) V); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(K) V); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K) bool); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func(K) bool); ok { + r1 = returnFunc(key) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: key -func (_m *MutableBackData[K, V]) Has(key K) bool { - ret := _m.Called(key) +// MutableBackData_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type MutableBackData_Get_Call[K comparable, V any] struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - key K +func (_e *MutableBackData_Expecter[K, V]) Get(key interface{}) *MutableBackData_Get_Call[K, V] { + return &MutableBackData_Get_Call[K, V]{Call: _e.mock.On("Get", key)} +} + +func (_c *MutableBackData_Get_Call[K, V]) Run(run func(key K)) *MutableBackData_Get_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MutableBackData_Get_Call[K, V]) Return(v V, b bool) *MutableBackData_Get_Call[K, V] { + _c.Call.Return(v, b) + return _c +} + +func (_c *MutableBackData_Get_Call[K, V]) RunAndReturn(run func(key K) (V, bool)) *MutableBackData_Get_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Has(key K) bool { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(K) bool); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(K) bool); ok { + r0 = returnFunc(key) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Keys provides a mock function with no fields -func (_m *MutableBackData[K, V]) Keys() []K { - ret := _m.Called() +// MutableBackData_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type MutableBackData_Has_Call[K comparable, V any] struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - key K +func (_e *MutableBackData_Expecter[K, V]) Has(key interface{}) *MutableBackData_Has_Call[K, V] { + return &MutableBackData_Has_Call[K, V]{Call: _e.mock.On("Has", key)} +} + +func (_c *MutableBackData_Has_Call[K, V]) Run(run func(key K)) *MutableBackData_Has_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MutableBackData_Has_Call[K, V]) Return(b bool) *MutableBackData_Has_Call[K, V] { + _c.Call.Return(b) + return _c +} + +func (_c *MutableBackData_Has_Call[K, V]) RunAndReturn(run func(key K) bool) *MutableBackData_Has_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Keys provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Keys() []K { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Keys") } var r0 []K - if rf, ok := ret.Get(0).(func() []K); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []K); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]K) } } - return r0 } -// Remove provides a mock function with given fields: key -func (_m *MutableBackData[K, V]) Remove(key K) (V, bool) { - ret := _m.Called(key) +// MutableBackData_Keys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Keys' +type MutableBackData_Keys_Call[K comparable, V any] struct { + *mock.Call +} + +// Keys is a helper method to define mock.On call +func (_e *MutableBackData_Expecter[K, V]) Keys() *MutableBackData_Keys_Call[K, V] { + return &MutableBackData_Keys_Call[K, V]{Call: _e.mock.On("Keys")} +} + +func (_c *MutableBackData_Keys_Call[K, V]) Run(run func()) *MutableBackData_Keys_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableBackData_Keys_Call[K, V]) Return(vs []K) *MutableBackData_Keys_Call[K, V] { + _c.Call.Return(vs) + return _c +} + +func (_c *MutableBackData_Keys_Call[K, V]) RunAndReturn(run func() []K) *MutableBackData_Keys_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Remove(key K) (V, bool) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Remove") @@ -190,74 +482,144 @@ func (_m *MutableBackData[K, V]) Remove(key K) (V, bool) { var r0 V var r1 bool - if rf, ok := ret.Get(0).(func(K) (V, bool)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func(K) (V, bool)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func(K) V); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(K) V); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(V) } } - - if rf, ok := ret.Get(1).(func(K) bool); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func(K) bool); ok { + r1 = returnFunc(key) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Size provides a mock function with no fields -func (_m *MutableBackData[K, V]) Size() uint { - ret := _m.Called() +// MutableBackData_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type MutableBackData_Remove_Call[K comparable, V any] struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - key K +func (_e *MutableBackData_Expecter[K, V]) Remove(key interface{}) *MutableBackData_Remove_Call[K, V] { + return &MutableBackData_Remove_Call[K, V]{Call: _e.mock.On("Remove", key)} +} + +func (_c *MutableBackData_Remove_Call[K, V]) Run(run func(key K)) *MutableBackData_Remove_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 K + if args[0] != nil { + arg0 = args[0].(K) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MutableBackData_Remove_Call[K, V]) Return(v V, b bool) *MutableBackData_Remove_Call[K, V] { + _c.Call.Return(v, b) + return _c +} + +func (_c *MutableBackData_Remove_Call[K, V]) RunAndReturn(run func(key K) (V, bool)) *MutableBackData_Remove_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *MutableBackData[K, V]) Values() []V { - ret := _m.Called() +// MutableBackData_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type MutableBackData_Size_Call[K comparable, V any] struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *MutableBackData_Expecter[K, V]) Size() *MutableBackData_Size_Call[K, V] { + return &MutableBackData_Size_Call[K, V]{Call: _e.mock.On("Size")} +} + +func (_c *MutableBackData_Size_Call[K, V]) Run(run func()) *MutableBackData_Size_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableBackData_Size_Call[K, V]) Return(v uint) *MutableBackData_Size_Call[K, V] { + _c.Call.Return(v) + return _c +} + +func (_c *MutableBackData_Size_Call[K, V]) RunAndReturn(run func() uint) *MutableBackData_Size_Call[K, V] { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type MutableBackData +func (_mock *MutableBackData[K, V]) Values() []V { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []V - if rf, ok := ret.Get(0).(func() []V); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []V); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]V) } } - return r0 } -// NewMutableBackData creates a new instance of MutableBackData. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMutableBackData[K comparable, V any](t interface { - mock.TestingT - Cleanup(func()) -}) *MutableBackData[K, V] { - mock := &MutableBackData[K, V]{} - mock.Mock.Test(t) +// MutableBackData_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type MutableBackData_Values_Call[K comparable, V any] struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *MutableBackData_Expecter[K, V]) Values() *MutableBackData_Values_Call[K, V] { + return &MutableBackData_Values_Call[K, V]{Call: _e.mock.On("Values")} +} - return mock +func (_c *MutableBackData_Values_Call[K, V]) Run(run func()) *MutableBackData_Values_Call[K, V] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableBackData_Values_Call[K, V]) Return(vs []V) *MutableBackData_Values_Call[K, V] { + _c.Call.Return(vs) + return _c +} + +func (_c *MutableBackData_Values_Call[K, V]) RunAndReturn(run func() []V) *MutableBackData_Values_Call[K, V] { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/pending_receipts.go b/module/mempool/mock/pending_receipts.go index 5ae9dcd8778..67c6d5b9a90 100644 --- a/module/mempool/mock/pending_receipts.go +++ b/module/mempool/mock/pending_receipts.go @@ -1,102 +1,243 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewPendingReceipts creates a new instance of PendingReceipts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPendingReceipts(t interface { + mock.TestingT + Cleanup(func()) +}) *PendingReceipts { + mock := &PendingReceipts{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // PendingReceipts is an autogenerated mock type for the PendingReceipts type type PendingReceipts struct { mock.Mock } -// Add provides a mock function with given fields: receipt -func (_m *PendingReceipts) Add(receipt *flow.ExecutionReceipt) bool { - ret := _m.Called(receipt) +type PendingReceipts_Expecter struct { + mock *mock.Mock +} + +func (_m *PendingReceipts) EXPECT() *PendingReceipts_Expecter { + return &PendingReceipts_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type PendingReceipts +func (_mock *PendingReceipts) Add(receipt *flow.ExecutionReceipt) bool { + ret := _mock.Called(receipt) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt) bool); ok { - r0 = rf(receipt) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt) bool); ok { + r0 = returnFunc(receipt) } else { r0 = ret.Get(0).(bool) } - return r0 } -// ByPreviousResultID provides a mock function with given fields: previousResultID -func (_m *PendingReceipts) ByPreviousResultID(previousResultID flow.Identifier) []*flow.ExecutionReceipt { - ret := _m.Called(previousResultID) +// PendingReceipts_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type PendingReceipts_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - receipt *flow.ExecutionReceipt +func (_e *PendingReceipts_Expecter) Add(receipt interface{}) *PendingReceipts_Add_Call { + return &PendingReceipts_Add_Call{Call: _e.mock.On("Add", receipt)} +} + +func (_c *PendingReceipts_Add_Call) Run(run func(receipt *flow.ExecutionReceipt)) *PendingReceipts_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingReceipts_Add_Call) Return(b bool) *PendingReceipts_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *PendingReceipts_Add_Call) RunAndReturn(run func(receipt *flow.ExecutionReceipt) bool) *PendingReceipts_Add_Call { + _c.Call.Return(run) + return _c +} + +// ByPreviousResultID provides a mock function for the type PendingReceipts +func (_mock *PendingReceipts) ByPreviousResultID(previousResultID flow.Identifier) []*flow.ExecutionReceipt { + ret := _mock.Called(previousResultID) if len(ret) == 0 { panic("no return value specified for ByPreviousResultID") } var r0 []*flow.ExecutionReceipt - if rf, ok := ret.Get(0).(func(flow.Identifier) []*flow.ExecutionReceipt); ok { - r0 = rf(previousResultID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []*flow.ExecutionReceipt); ok { + r0 = returnFunc(previousResultID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.ExecutionReceipt) } } - return r0 } -// PruneUpToHeight provides a mock function with given fields: height -func (_m *PendingReceipts) PruneUpToHeight(height uint64) error { - ret := _m.Called(height) +// PendingReceipts_ByPreviousResultID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByPreviousResultID' +type PendingReceipts_ByPreviousResultID_Call struct { + *mock.Call +} + +// ByPreviousResultID is a helper method to define mock.On call +// - previousResultID flow.Identifier +func (_e *PendingReceipts_Expecter) ByPreviousResultID(previousResultID interface{}) *PendingReceipts_ByPreviousResultID_Call { + return &PendingReceipts_ByPreviousResultID_Call{Call: _e.mock.On("ByPreviousResultID", previousResultID)} +} + +func (_c *PendingReceipts_ByPreviousResultID_Call) Run(run func(previousResultID flow.Identifier)) *PendingReceipts_ByPreviousResultID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingReceipts_ByPreviousResultID_Call) Return(executionReceipts []*flow.ExecutionReceipt) *PendingReceipts_ByPreviousResultID_Call { + _c.Call.Return(executionReceipts) + return _c +} + +func (_c *PendingReceipts_ByPreviousResultID_Call) RunAndReturn(run func(previousResultID flow.Identifier) []*flow.ExecutionReceipt) *PendingReceipts_ByPreviousResultID_Call { + _c.Call.Return(run) + return _c +} + +// PruneUpToHeight provides a mock function for the type PendingReceipts +func (_mock *PendingReceipts) PruneUpToHeight(height uint64) error { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for PruneUpToHeight") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(height) } else { r0 = ret.Error(0) } - return r0 } -// Remove provides a mock function with given fields: receiptID -func (_m *PendingReceipts) Remove(receiptID flow.Identifier) bool { - ret := _m.Called(receiptID) +// PendingReceipts_PruneUpToHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneUpToHeight' +type PendingReceipts_PruneUpToHeight_Call struct { + *mock.Call +} + +// PruneUpToHeight is a helper method to define mock.On call +// - height uint64 +func (_e *PendingReceipts_Expecter) PruneUpToHeight(height interface{}) *PendingReceipts_PruneUpToHeight_Call { + return &PendingReceipts_PruneUpToHeight_Call{Call: _e.mock.On("PruneUpToHeight", height)} +} + +func (_c *PendingReceipts_PruneUpToHeight_Call) Run(run func(height uint64)) *PendingReceipts_PruneUpToHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingReceipts_PruneUpToHeight_Call) Return(err error) *PendingReceipts_PruneUpToHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PendingReceipts_PruneUpToHeight_Call) RunAndReturn(run func(height uint64) error) *PendingReceipts_PruneUpToHeight_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type PendingReceipts +func (_mock *PendingReceipts) Remove(receiptID flow.Identifier) bool { + ret := _mock.Called(receiptID) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(receiptID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(receiptID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewPendingReceipts creates a new instance of PendingReceipts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPendingReceipts(t interface { - mock.TestingT - Cleanup(func()) -}) *PendingReceipts { - mock := &PendingReceipts{} - mock.Mock.Test(t) +// PendingReceipts_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type PendingReceipts_Remove_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Remove is a helper method to define mock.On call +// - receiptID flow.Identifier +func (_e *PendingReceipts_Expecter) Remove(receiptID interface{}) *PendingReceipts_Remove_Call { + return &PendingReceipts_Remove_Call{Call: _e.mock.On("Remove", receiptID)} +} - return mock +func (_c *PendingReceipts_Remove_Call) Run(run func(receiptID flow.Identifier)) *PendingReceipts_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingReceipts_Remove_Call) Return(b bool) *PendingReceipts_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *PendingReceipts_Remove_Call) RunAndReturn(run func(receiptID flow.Identifier) bool) *PendingReceipts_Remove_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/transaction_timings.go b/module/mempool/mock/transaction_timings.go index 568336d94c0..9e0b964188e 100644 --- a/module/mempool/mock/transaction_timings.go +++ b/module/mempool/mock/transaction_timings.go @@ -1,39 +1,101 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTransactionTimings creates a new instance of TransactionTimings. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionTimings(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionTimings { + mock := &TransactionTimings{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionTimings is an autogenerated mock type for the TransactionTimings type type TransactionTimings struct { mock.Mock } -// Add provides a mock function with given fields: _a0, _a1 -func (_m *TransactionTimings) Add(_a0 flow.Identifier, _a1 *flow.TransactionTiming) bool { - ret := _m.Called(_a0, _a1) +type TransactionTimings_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionTimings) EXPECT() *TransactionTimings_Expecter { + return &TransactionTimings_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Add(identifier flow.Identifier, transactionTiming *flow.TransactionTiming) bool { + ret := _mock.Called(identifier, transactionTiming) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, *flow.TransactionTiming) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, *flow.TransactionTiming) bool); ok { + r0 = returnFunc(identifier, transactionTiming) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *TransactionTimings) Adjust(key flow.Identifier, f func(*flow.TransactionTiming) *flow.TransactionTiming) (*flow.TransactionTiming, bool) { - ret := _m.Called(key, f) +// TransactionTimings_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type TransactionTimings_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - identifier flow.Identifier +// - transactionTiming *flow.TransactionTiming +func (_e *TransactionTimings_Expecter) Add(identifier interface{}, transactionTiming interface{}) *TransactionTimings_Add_Call { + return &TransactionTimings_Add_Call{Call: _e.mock.On("Add", identifier, transactionTiming)} +} + +func (_c *TransactionTimings_Add_Call) Run(run func(identifier flow.Identifier, transactionTiming *flow.TransactionTiming)) *TransactionTimings_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 *flow.TransactionTiming + if args[1] != nil { + arg1 = args[1].(*flow.TransactionTiming) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionTimings_Add_Call) Return(b bool) *TransactionTimings_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *TransactionTimings_Add_Call) RunAndReturn(run func(identifier flow.Identifier, transactionTiming *flow.TransactionTiming) bool) *TransactionTimings_Add_Call { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Adjust(key flow.Identifier, f func(*flow.TransactionTiming) *flow.TransactionTiming) (*flow.TransactionTiming, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -41,54 +103,146 @@ func (_m *TransactionTimings) Adjust(key flow.Identifier, f func(*flow.Transacti var r0 *flow.TransactionTiming var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionTiming) *flow.TransactionTiming) (*flow.TransactionTiming, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionTiming) *flow.TransactionTiming) (*flow.TransactionTiming, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionTiming) *flow.TransactionTiming) *flow.TransactionTiming); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionTiming) *flow.TransactionTiming) *flow.TransactionTiming); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionTiming) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, func(*flow.TransactionTiming) *flow.TransactionTiming) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, func(*flow.TransactionTiming) *flow.TransactionTiming) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *TransactionTimings) All() map[flow.Identifier]*flow.TransactionTiming { - ret := _m.Called() +// TransactionTimings_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type TransactionTimings_Adjust_Call struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key flow.Identifier +// - f func(*flow.TransactionTiming) *flow.TransactionTiming +func (_e *TransactionTimings_Expecter) Adjust(key interface{}, f interface{}) *TransactionTimings_Adjust_Call { + return &TransactionTimings_Adjust_Call{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *TransactionTimings_Adjust_Call) Run(run func(key flow.Identifier, f func(*flow.TransactionTiming) *flow.TransactionTiming)) *TransactionTimings_Adjust_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 func(*flow.TransactionTiming) *flow.TransactionTiming + if args[1] != nil { + arg1 = args[1].(func(*flow.TransactionTiming) *flow.TransactionTiming) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionTimings_Adjust_Call) Return(transactionTiming *flow.TransactionTiming, b bool) *TransactionTimings_Adjust_Call { + _c.Call.Return(transactionTiming, b) + return _c +} + +func (_c *TransactionTimings_Adjust_Call) RunAndReturn(run func(key flow.Identifier, f func(*flow.TransactionTiming) *flow.TransactionTiming) (*flow.TransactionTiming, bool)) *TransactionTimings_Adjust_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) All() map[flow.Identifier]*flow.TransactionTiming { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[flow.Identifier]*flow.TransactionTiming - if rf, ok := ret.Get(0).(func() map[flow.Identifier]*flow.TransactionTiming); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[flow.Identifier]*flow.TransactionTiming); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[flow.Identifier]*flow.TransactionTiming) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *TransactionTimings) Clear() { - _m.Called() +// TransactionTimings_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type TransactionTimings_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *TransactionTimings_Expecter) All() *TransactionTimings_All_Call { + return &TransactionTimings_All_Call{Call: _e.mock.On("All")} +} + +func (_c *TransactionTimings_All_Call) Run(run func()) *TransactionTimings_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionTimings_All_Call) Return(identifierToTransactionTiming map[flow.Identifier]*flow.TransactionTiming) *TransactionTimings_All_Call { + _c.Call.Return(identifierToTransactionTiming) + return _c +} + +func (_c *TransactionTimings_All_Call) RunAndReturn(run func() map[flow.Identifier]*flow.TransactionTiming) *TransactionTimings_All_Call { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Clear() { + _mock.Called() + return +} + +// TransactionTimings_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type TransactionTimings_Clear_Call struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *TransactionTimings_Expecter) Clear() *TransactionTimings_Clear_Call { + return &TransactionTimings_Clear_Call{Call: _e.mock.On("Clear")} +} + +func (_c *TransactionTimings_Clear_Call) Run(run func()) *TransactionTimings_Clear_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionTimings_Clear_Call) Return() *TransactionTimings_Clear_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionTimings_Clear_Call) RunAndReturn(run func()) *TransactionTimings_Clear_Call { + _c.Run(run) + return _c } -// Get provides a mock function with given fields: _a0 -func (_m *TransactionTimings) Get(_a0 flow.Identifier) (*flow.TransactionTiming, bool) { - ret := _m.Called(_a0) +// Get provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Get(identifier flow.Identifier) (*flow.TransactionTiming, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Get") @@ -96,110 +250,246 @@ func (_m *TransactionTimings) Get(_a0 flow.Identifier) (*flow.TransactionTiming, var r0 *flow.TransactionTiming var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionTiming, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionTiming, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionTiming); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionTiming); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionTiming) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: _a0 -func (_m *TransactionTimings) Has(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// TransactionTimings_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type TransactionTimings_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *TransactionTimings_Expecter) Get(identifier interface{}) *TransactionTimings_Get_Call { + return &TransactionTimings_Get_Call{Call: _e.mock.On("Get", identifier)} +} + +func (_c *TransactionTimings_Get_Call) Run(run func(identifier flow.Identifier)) *TransactionTimings_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionTimings_Get_Call) Return(transactionTiming *flow.TransactionTiming, b bool) *TransactionTimings_Get_Call { + _c.Call.Return(transactionTiming, b) + return _c +} + +func (_c *TransactionTimings_Get_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.TransactionTiming, bool)) *TransactionTimings_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Has(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Remove provides a mock function with given fields: _a0 -func (_m *TransactionTimings) Remove(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// TransactionTimings_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type TransactionTimings_Has_Call struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *TransactionTimings_Expecter) Has(identifier interface{}) *TransactionTimings_Has_Call { + return &TransactionTimings_Has_Call{Call: _e.mock.On("Has", identifier)} +} + +func (_c *TransactionTimings_Has_Call) Run(run func(identifier flow.Identifier)) *TransactionTimings_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionTimings_Has_Call) Return(b bool) *TransactionTimings_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *TransactionTimings_Has_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *TransactionTimings_Has_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Remove(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *TransactionTimings) Size() uint { - ret := _m.Called() +// TransactionTimings_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type TransactionTimings_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *TransactionTimings_Expecter) Remove(identifier interface{}) *TransactionTimings_Remove_Call { + return &TransactionTimings_Remove_Call{Call: _e.mock.On("Remove", identifier)} +} + +func (_c *TransactionTimings_Remove_Call) Run(run func(identifier flow.Identifier)) *TransactionTimings_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionTimings_Remove_Call) Return(b bool) *TransactionTimings_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *TransactionTimings_Remove_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *TransactionTimings_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *TransactionTimings) Values() []*flow.TransactionTiming { - ret := _m.Called() +// TransactionTimings_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type TransactionTimings_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *TransactionTimings_Expecter) Size() *TransactionTimings_Size_Call { + return &TransactionTimings_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *TransactionTimings_Size_Call) Run(run func()) *TransactionTimings_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionTimings_Size_Call) Return(v uint) *TransactionTimings_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *TransactionTimings_Size_Call) RunAndReturn(run func() uint) *TransactionTimings_Size_Call { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type TransactionTimings +func (_mock *TransactionTimings) Values() []*flow.TransactionTiming { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []*flow.TransactionTiming - if rf, ok := ret.Get(0).(func() []*flow.TransactionTiming); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*flow.TransactionTiming); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionTiming) } } - return r0 } -// NewTransactionTimings creates a new instance of TransactionTimings. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionTimings(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionTimings { - mock := &TransactionTimings{} - mock.Mock.Test(t) +// TransactionTimings_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type TransactionTimings_Values_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *TransactionTimings_Expecter) Values() *TransactionTimings_Values_Call { + return &TransactionTimings_Values_Call{Call: _e.mock.On("Values")} +} - return mock +func (_c *TransactionTimings_Values_Call) Run(run func()) *TransactionTimings_Values_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionTimings_Values_Call) Return(transactionTimings []*flow.TransactionTiming) *TransactionTimings_Values_Call { + _c.Call.Return(transactionTimings) + return _c +} + +func (_c *TransactionTimings_Values_Call) RunAndReturn(run func() []*flow.TransactionTiming) *TransactionTimings_Values_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/mock/transactions.go b/module/mempool/mock/transactions.go index 5d986705688..d65ab0377b4 100644 --- a/module/mempool/mock/transactions.go +++ b/module/mempool/mock/transactions.go @@ -1,39 +1,101 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTransactions creates a new instance of Transactions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactions(t interface { + mock.TestingT + Cleanup(func()) +}) *Transactions { + mock := &Transactions{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Transactions is an autogenerated mock type for the Transactions type type Transactions struct { mock.Mock } -// Add provides a mock function with given fields: _a0, _a1 -func (_m *Transactions) Add(_a0 flow.Identifier, _a1 *flow.TransactionBody) bool { - ret := _m.Called(_a0, _a1) +type Transactions_Expecter struct { + mock *mock.Mock +} + +func (_m *Transactions) EXPECT() *Transactions_Expecter { + return &Transactions_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type Transactions +func (_mock *Transactions) Add(identifier flow.Identifier, transactionBody *flow.TransactionBody) bool { + ret := _mock.Called(identifier, transactionBody) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, *flow.TransactionBody) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, *flow.TransactionBody) bool); ok { + r0 = returnFunc(identifier, transactionBody) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Adjust provides a mock function with given fields: key, f -func (_m *Transactions) Adjust(key flow.Identifier, f func(*flow.TransactionBody) *flow.TransactionBody) (*flow.TransactionBody, bool) { - ret := _m.Called(key, f) +// Transactions_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type Transactions_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - identifier flow.Identifier +// - transactionBody *flow.TransactionBody +func (_e *Transactions_Expecter) Add(identifier interface{}, transactionBody interface{}) *Transactions_Add_Call { + return &Transactions_Add_Call{Call: _e.mock.On("Add", identifier, transactionBody)} +} + +func (_c *Transactions_Add_Call) Run(run func(identifier flow.Identifier, transactionBody *flow.TransactionBody)) *Transactions_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 *flow.TransactionBody + if args[1] != nil { + arg1 = args[1].(*flow.TransactionBody) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Transactions_Add_Call) Return(b bool) *Transactions_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Transactions_Add_Call) RunAndReturn(run func(identifier flow.Identifier, transactionBody *flow.TransactionBody) bool) *Transactions_Add_Call { + _c.Call.Return(run) + return _c +} + +// Adjust provides a mock function for the type Transactions +func (_mock *Transactions) Adjust(key flow.Identifier, f func(*flow.TransactionBody) *flow.TransactionBody) (*flow.TransactionBody, bool) { + ret := _mock.Called(key, f) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -41,74 +103,199 @@ func (_m *Transactions) Adjust(key flow.Identifier, f func(*flow.TransactionBody var r0 *flow.TransactionBody var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionBody) *flow.TransactionBody) (*flow.TransactionBody, bool)); ok { - return rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionBody) *flow.TransactionBody) (*flow.TransactionBody, bool)); ok { + return returnFunc(key, f) } - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionBody) *flow.TransactionBody) *flow.TransactionBody); ok { - r0 = rf(key, f) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.TransactionBody) *flow.TransactionBody) *flow.TransactionBody); ok { + r0 = returnFunc(key, f) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, func(*flow.TransactionBody) *flow.TransactionBody) bool); ok { - r1 = rf(key, f) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, func(*flow.TransactionBody) *flow.TransactionBody) bool); ok { + r1 = returnFunc(key, f) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// All provides a mock function with no fields -func (_m *Transactions) All() map[flow.Identifier]*flow.TransactionBody { - ret := _m.Called() +// Transactions_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type Transactions_Adjust_Call struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - key flow.Identifier +// - f func(*flow.TransactionBody) *flow.TransactionBody +func (_e *Transactions_Expecter) Adjust(key interface{}, f interface{}) *Transactions_Adjust_Call { + return &Transactions_Adjust_Call{Call: _e.mock.On("Adjust", key, f)} +} + +func (_c *Transactions_Adjust_Call) Run(run func(key flow.Identifier, f func(*flow.TransactionBody) *flow.TransactionBody)) *Transactions_Adjust_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 func(*flow.TransactionBody) *flow.TransactionBody + if args[1] != nil { + arg1 = args[1].(func(*flow.TransactionBody) *flow.TransactionBody) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Transactions_Adjust_Call) Return(transactionBody *flow.TransactionBody, b bool) *Transactions_Adjust_Call { + _c.Call.Return(transactionBody, b) + return _c +} + +func (_c *Transactions_Adjust_Call) RunAndReturn(run func(key flow.Identifier, f func(*flow.TransactionBody) *flow.TransactionBody) (*flow.TransactionBody, bool)) *Transactions_Adjust_Call { + _c.Call.Return(run) + return _c +} + +// All provides a mock function for the type Transactions +func (_mock *Transactions) All() map[flow.Identifier]*flow.TransactionBody { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for All") } var r0 map[flow.Identifier]*flow.TransactionBody - if rf, ok := ret.Get(0).(func() map[flow.Identifier]*flow.TransactionBody); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() map[flow.Identifier]*flow.TransactionBody); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[flow.Identifier]*flow.TransactionBody) } } - return r0 } -// ByPayer provides a mock function with given fields: payer -func (_m *Transactions) ByPayer(payer flow.Address) []*flow.TransactionBody { - ret := _m.Called(payer) +// Transactions_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type Transactions_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +func (_e *Transactions_Expecter) All() *Transactions_All_Call { + return &Transactions_All_Call{Call: _e.mock.On("All")} +} + +func (_c *Transactions_All_Call) Run(run func()) *Transactions_All_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Transactions_All_Call) Return(identifierToTransactionBody map[flow.Identifier]*flow.TransactionBody) *Transactions_All_Call { + _c.Call.Return(identifierToTransactionBody) + return _c +} + +func (_c *Transactions_All_Call) RunAndReturn(run func() map[flow.Identifier]*flow.TransactionBody) *Transactions_All_Call { + _c.Call.Return(run) + return _c +} + +// ByPayer provides a mock function for the type Transactions +func (_mock *Transactions) ByPayer(payer flow.Address) []*flow.TransactionBody { + ret := _mock.Called(payer) if len(ret) == 0 { panic("no return value specified for ByPayer") } var r0 []*flow.TransactionBody - if rf, ok := ret.Get(0).(func(flow.Address) []*flow.TransactionBody); ok { - r0 = rf(payer) + if returnFunc, ok := ret.Get(0).(func(flow.Address) []*flow.TransactionBody); ok { + r0 = returnFunc(payer) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionBody) } } - return r0 } -// Clear provides a mock function with no fields -func (_m *Transactions) Clear() { - _m.Called() +// Transactions_ByPayer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByPayer' +type Transactions_ByPayer_Call struct { + *mock.Call +} + +// ByPayer is a helper method to define mock.On call +// - payer flow.Address +func (_e *Transactions_Expecter) ByPayer(payer interface{}) *Transactions_ByPayer_Call { + return &Transactions_ByPayer_Call{Call: _e.mock.On("ByPayer", payer)} +} + +func (_c *Transactions_ByPayer_Call) Run(run func(payer flow.Address)) *Transactions_ByPayer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Transactions_ByPayer_Call) Return(transactionBodys []*flow.TransactionBody) *Transactions_ByPayer_Call { + _c.Call.Return(transactionBodys) + return _c +} + +func (_c *Transactions_ByPayer_Call) RunAndReturn(run func(payer flow.Address) []*flow.TransactionBody) *Transactions_ByPayer_Call { + _c.Call.Return(run) + return _c +} + +// Clear provides a mock function for the type Transactions +func (_mock *Transactions) Clear() { + _mock.Called() + return +} + +// Transactions_Clear_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clear' +type Transactions_Clear_Call struct { + *mock.Call +} + +// Clear is a helper method to define mock.On call +func (_e *Transactions_Expecter) Clear() *Transactions_Clear_Call { + return &Transactions_Clear_Call{Call: _e.mock.On("Clear")} } -// Get provides a mock function with given fields: _a0 -func (_m *Transactions) Get(_a0 flow.Identifier) (*flow.TransactionBody, bool) { - ret := _m.Called(_a0) +func (_c *Transactions_Clear_Call) Run(run func()) *Transactions_Clear_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Transactions_Clear_Call) Return() *Transactions_Clear_Call { + _c.Call.Return() + return _c +} + +func (_c *Transactions_Clear_Call) RunAndReturn(run func()) *Transactions_Clear_Call { + _c.Run(run) + return _c +} + +// Get provides a mock function for the type Transactions +func (_mock *Transactions) Get(identifier flow.Identifier) (*flow.TransactionBody, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Get") @@ -116,110 +303,246 @@ func (_m *Transactions) Get(_a0 flow.Identifier) (*flow.TransactionBody, bool) { var r0 *flow.TransactionBody var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionBody, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionBody, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionBody); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionBody); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Has provides a mock function with given fields: _a0 -func (_m *Transactions) Has(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// Transactions_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Transactions_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Transactions_Expecter) Get(identifier interface{}) *Transactions_Get_Call { + return &Transactions_Get_Call{Call: _e.mock.On("Get", identifier)} +} + +func (_c *Transactions_Get_Call) Run(run func(identifier flow.Identifier)) *Transactions_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Transactions_Get_Call) Return(transactionBody *flow.TransactionBody, b bool) *Transactions_Get_Call { + _c.Call.Return(transactionBody, b) + return _c +} + +func (_c *Transactions_Get_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.TransactionBody, bool)) *Transactions_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type Transactions +func (_mock *Transactions) Has(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Remove provides a mock function with given fields: _a0 -func (_m *Transactions) Remove(_a0 flow.Identifier) bool { - ret := _m.Called(_a0) +// Transactions_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type Transactions_Has_Call struct { + *mock.Call +} + +// Has is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Transactions_Expecter) Has(identifier interface{}) *Transactions_Has_Call { + return &Transactions_Has_Call{Call: _e.mock.On("Has", identifier)} +} + +func (_c *Transactions_Has_Call) Run(run func(identifier flow.Identifier)) *Transactions_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Transactions_Has_Call) Return(b bool) *Transactions_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Transactions_Has_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *Transactions_Has_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type Transactions +func (_mock *Transactions) Remove(identifier flow.Identifier) bool { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *Transactions) Size() uint { - ret := _m.Called() +// Transactions_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type Transactions_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *Transactions_Expecter) Remove(identifier interface{}) *Transactions_Remove_Call { + return &Transactions_Remove_Call{Call: _e.mock.On("Remove", identifier)} +} + +func (_c *Transactions_Remove_Call) Run(run func(identifier flow.Identifier)) *Transactions_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Transactions_Remove_Call) Return(b bool) *Transactions_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Transactions_Remove_Call) RunAndReturn(run func(identifier flow.Identifier) bool) *Transactions_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type Transactions +func (_mock *Transactions) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Values provides a mock function with no fields -func (_m *Transactions) Values() []*flow.TransactionBody { - ret := _m.Called() +// Transactions_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type Transactions_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *Transactions_Expecter) Size() *Transactions_Size_Call { + return &Transactions_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *Transactions_Size_Call) Run(run func()) *Transactions_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Transactions_Size_Call) Return(v uint) *Transactions_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Transactions_Size_Call) RunAndReturn(run func() uint) *Transactions_Size_Call { + _c.Call.Return(run) + return _c +} + +// Values provides a mock function for the type Transactions +func (_mock *Transactions) Values() []*flow.TransactionBody { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Values") } var r0 []*flow.TransactionBody - if rf, ok := ret.Get(0).(func() []*flow.TransactionBody); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*flow.TransactionBody); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.TransactionBody) } } - return r0 } -// NewTransactions creates a new instance of Transactions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactions(t interface { - mock.TestingT - Cleanup(func()) -}) *Transactions { - mock := &Transactions{} - mock.Mock.Test(t) +// Transactions_Values_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Values' +type Transactions_Values_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Values is a helper method to define mock.On call +func (_e *Transactions_Expecter) Values() *Transactions_Values_Call { + return &Transactions_Values_Call{Call: _e.mock.On("Values")} +} - return mock +func (_c *Transactions_Values_Call) Run(run func()) *Transactions_Values_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Transactions_Values_Call) Return(transactionBodys []*flow.TransactionBody) *Transactions_Values_Call { + _c.Call.Return(transactionBodys) + return _c +} + +func (_c *Transactions_Values_Call) RunAndReturn(run func() []*flow.TransactionBody) *Transactions_Values_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mempool/stdmap/incorporated_result_seals.go b/module/mempool/stdmap/incorporated_result_seals.go index 321a7861443..15d5cfabc38 100644 --- a/module/mempool/stdmap/incorporated_result_seals.go +++ b/module/mempool/stdmap/incorporated_result_seals.go @@ -60,7 +60,9 @@ func (ir *IncorporatedResultSeals) removeByHeight(height uint64) { delete(ir.byHeight, height) } -// Add adds an IncorporatedResultSeal to the mempool +// Add adds an IncorporatedResultSeal to the mempool. The method returns true if the seal was added to the mempool, +// and false if it was a duplicate (dropped). The seal is considered a duplicate if and only if a seal for the same +// IncorporatedResult ID is already present in the mempool. func (ir *IncorporatedResultSeals) Add(seal *flow.IncorporatedResultSeal) (bool, error) { added := false resultID := seal.IncorporatedResult.ID() diff --git a/module/metrics.go b/module/metrics.go index 6c6385019d3..c67059f7966 100644 --- a/module/metrics.go +++ b/module/metrics.go @@ -826,6 +826,29 @@ type ExecutionStateIndexerMetrics interface { InitializeLatestHeight(height uint64) } +type ExtendedIndexingMetrics interface { + // BlockIndexedExtended records the latest processed height for a given extended indexer. + BlockIndexedExtended(indexer string, height uint64) + + // ScheduledTransactionIndexed records counts of scheduled transactions processed in a single block. + // scheduled is the number of newly created scheduled transactions. + // executed is the number marked as executed. + // failed is the number marked as failed. + // canceled is the number marked as canceled. + // backfilled is the number fetched from state because they were unknown to the local index. + ScheduledTransactionIndexed(scheduled, executed, failed, canceled, backfilled int) + + // FTTransferIndexed records the number of fungible token transfers indexed for a single block. + FTTransferIndexed(count int) + + // NFTTransferIndexed records the number of non-fungible token transfers indexed for a single block. + NFTTransferIndexed(count int) + + // ContractDeploymentIndexed records the number of contract deployments indexed for a single block, + // broken down by action (create vs update). + ContractDeploymentIndexed(created, updated int) +} + type TransactionErrorMessagesMetrics interface { // TxErrorsInitialHeight records the initial height of the transaction error messages. TxErrorsInitialHeight(height uint64) @@ -940,6 +963,9 @@ type AccessMetrics interface { // UpdateLastFullBlockHeight tracks the height of the last block for which all collections were received UpdateLastFullBlockHeight(height uint64) + + // UpdateIngestionFinalizedBlockHeight tracks the latest finalized block height processed by ingestion + UpdateIngestionFinalizedBlockHeight(height uint64) } type ExecutionResultStats struct { diff --git a/module/metrics/access.go b/module/metrics/access.go index 577e8c34405..5ebdfbf4596 100644 --- a/module/metrics/access.go +++ b/module/metrics/access.go @@ -40,15 +40,16 @@ type AccessCollector struct { module.TransactionValidationMetrics module.BackendScriptsMetrics - connectionReused prometheus.Counter - connectionsInPool *prometheus.GaugeVec - connectionAdded prometheus.Counter - connectionEstablished prometheus.Counter - connectionInvalidated prometheus.Counter - connectionUpdated prometheus.Counter - connectionEvicted prometheus.Counter - lastFullBlockHeight prometheus.Gauge - maxReceiptHeight prometheus.Gauge + connectionReused prometheus.Counter + connectionsInPool *prometheus.GaugeVec + connectionAdded prometheus.Counter + connectionEstablished prometheus.Counter + connectionInvalidated prometheus.Counter + connectionUpdated prometheus.Counter + connectionEvicted prometheus.Counter + lastFullBlockHeight prometheus.Gauge + ingestionFinalizedBlockHeight prometheus.Gauge + maxReceiptHeight prometheus.Gauge // used to skip heights that are lower than the current max height maxReceiptHeightValue counters.StrictMonotonicCounter @@ -106,6 +107,12 @@ func NewAccessCollector(opts ...AccessCollectorOpts) *AccessCollector { Subsystem: subsystemIngestion, Help: "gauge to track the highest consecutive finalized block height with all collections indexed", }), + ingestionFinalizedBlockHeight: promauto.NewGauge(prometheus.GaugeOpts{ + Name: "ingestion_finalized_block_height", + Namespace: namespaceAccess, + Subsystem: subsystemIngestion, + Help: "gauge to track the latest finalized block height processed by ingestion", + }), maxReceiptHeight: promauto.NewGauge(prometheus.GaugeOpts{ Name: "max_receipt_height", Namespace: namespaceAccess, @@ -155,6 +162,10 @@ func (ac *AccessCollector) UpdateLastFullBlockHeight(height uint64) { ac.lastFullBlockHeight.Set(float64(height)) } +func (ac *AccessCollector) UpdateIngestionFinalizedBlockHeight(height uint64) { + ac.ingestionFinalizedBlockHeight.Set(float64(height)) +} + func (ac *AccessCollector) UpdateExecutionReceiptMaxHeight(height uint64) { if ac.maxReceiptHeightValue.Set(height) { ac.maxReceiptHeight.Set(float64(height)) diff --git a/module/metrics/alsp.go b/module/metrics/alsp.go index 3d5dc2bc510..33edf997cc9 100644 --- a/module/metrics/alsp.go +++ b/module/metrics/alsp.go @@ -4,6 +4,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/network/channels" ) // AlspMetrics is a struct that contains all the metrics related to the ALSP module. @@ -38,12 +39,13 @@ func NewAlspMetrics() *AlspMetrics { // OnMisbehaviorReported is called when a misbehavior is reported by the application layer to ALSP. // An engine detecting a spamming-related misbehavior reports it to the ALSP module. It increases // the counter vector of reported misbehavior. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. // Args: // - channel: the channel on which the misbehavior was reported // - misbehaviorType: the type of misbehavior reported func (a *AlspMetrics) OnMisbehaviorReported(channel string, misbehaviorType string) { a.reportedMisbehaviorCount.With(prometheus.Labels{ - LabelChannel: channel, + LabelChannel: channels.NormalizeTopicForMetrics(channel), LabelMisbehavior: misbehaviorType, }).Inc() } diff --git a/module/metrics/execution.go b/module/metrics/execution.go index f11543a6d5d..16ef95bf835 100644 --- a/module/metrics/execution.go +++ b/module/metrics/execution.go @@ -12,6 +12,7 @@ import ( ) type ExecutionCollector struct { + *LedgerCollector tracer module.Tracer totalExecutedBlocksCounter prometheus.Counter totalExecutedCollectionsCounter prometheus.Counter @@ -24,24 +25,6 @@ type ExecutionCollector struct { targetChunkDataPackPrunedHeightGauge prometheus.Gauge stateStorageDiskTotal prometheus.Gauge storageStateCommitment prometheus.Gauge - checkpointSize prometheus.Gauge - forestApproxMemorySize prometheus.Gauge - forestNumberOfTrees prometheus.Gauge - latestTrieRegCount prometheus.Gauge - latestTrieRegCountDiff prometheus.Gauge - latestTrieRegSize prometheus.Gauge - latestTrieRegSizeDiff prometheus.Gauge - latestTrieMaxDepthTouched prometheus.Gauge - updated prometheus.Counter - proofSize prometheus.Gauge - updatedValuesNumber prometheus.Counter - updatedValuesSize prometheus.Gauge - updatedDuration prometheus.Histogram - updatedDurationPerValue prometheus.Histogram - readValuesNumber prometheus.Counter - readValuesSize prometheus.Gauge - readDuration prometheus.Histogram - readDurationPerValue prometheus.Histogram blockComputationUsed prometheus.Histogram blockComputationVector *prometheus.GaugeVec blockCachedPrograms prometheus.Gauge @@ -104,129 +87,8 @@ type ExecutionCollector struct { } func NewExecutionCollector(tracer module.Tracer) *ExecutionCollector { - - forestApproxMemorySize := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "forest_approx_memory_size", - Help: "an approximate size of in-memory forest in bytes", - }) - - forestNumberOfTrees := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "forest_number_of_trees", - Help: "the number of trees in memory", - }) - - latestTrieRegCount := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "latest_trie_reg_count", - Help: "the number of allocated registers (latest created trie)", - }) - - latestTrieRegCountDiff := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "latest_trie_reg_count_diff", - Help: "the difference between number of unique register allocated of the latest created trie and parent trie", - }) - - latestTrieRegSize := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "latest_trie_reg_size", - Help: "the size of allocated registers (latest created trie)", - }) - - latestTrieRegSizeDiff := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "latest_trie_reg_size_diff", - Help: "the difference between size of unique register allocated of the latest created trie and parent trie", - }) - - latestTrieMaxDepthTouched := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "latest_trie_max_depth_touched", - Help: "the maximum depth touched of the latest created trie", - }) - - updatedCount := promauto.NewCounter(prometheus.CounterOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "updates_counted", - Help: "the number of updates", - }) - - proofSize := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "average_proof_size", - Help: "the average size of a single generated proof in bytes", - }) - - updatedValuesNumber := promauto.NewCounter(prometheus.CounterOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "update_values_number", - Help: "the total number of values updated", - }) - - updatedValuesSize := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "update_values_size", - Help: "the total size of values for single update in bytes", - }) - - updatedDuration := promauto.NewHistogram(prometheus.HistogramOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "update_duration", - Help: "the duration of update operation", - Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, - }) - - updatedDurationPerValue := promauto.NewHistogram(prometheus.HistogramOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "update_duration_per_value", - Help: "the duration of update operation per value", - Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, - }) - - readValuesNumber := promauto.NewCounter(prometheus.CounterOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "read_values_number", - Help: "the total number of values read", - }) - - readValuesSize := promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "read_values_size", - Help: "the total size of values for single read in bytes", - }) - - readDuration := promauto.NewHistogram(prometheus.HistogramOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "read_duration", - Help: "the duration of read operation", - Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, - }) - - readDurationPerValue := promauto.NewHistogram(prometheus.HistogramOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemMTrie, - Name: "read_duration_per_value", - Help: "the duration of read operation per value", - Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, - }) + // Create LedgerCollector with execution namespace and state_storage subsystem for checkpoint + ledgerCollector := NewLedgerCollector(namespaceExecution, subsystemStateStorage) blockExecutionTime := promauto.NewHistogram(prometheus.HistogramOpts{ Namespace: namespaceExecution, @@ -549,25 +411,8 @@ func NewExecutionCollector(tracer module.Tracer) *ExecutionCollector { }) ec := &ExecutionCollector{ - tracer: tracer, - - forestApproxMemorySize: forestApproxMemorySize, - forestNumberOfTrees: forestNumberOfTrees, - latestTrieRegCount: latestTrieRegCount, - latestTrieRegCountDiff: latestTrieRegCountDiff, - latestTrieRegSize: latestTrieRegSize, - latestTrieRegSizeDiff: latestTrieRegSizeDiff, - latestTrieMaxDepthTouched: latestTrieMaxDepthTouched, - updated: updatedCount, - proofSize: proofSize, - updatedValuesNumber: updatedValuesNumber, - updatedValuesSize: updatedValuesSize, - updatedDuration: updatedDuration, - updatedDurationPerValue: updatedDurationPerValue, - readValuesNumber: readValuesNumber, - readValuesSize: readValuesSize, - readDuration: readDuration, - readDurationPerValue: readDurationPerValue, + LedgerCollector: ledgerCollector, + tracer: tracer, blockExecutionTime: blockExecutionTime, blockComputationUsed: blockComputationUsed, blockComputationVector: blockComputationVector, @@ -687,13 +532,6 @@ func NewExecutionCollector(tracer module.Tracer) *ExecutionCollector { Help: "the storage size of a state commitment in bytes", }), - checkpointSize: promauto.NewGauge(prometheus.GaugeOpts{ - Namespace: namespaceExecution, - Subsystem: subsystemStateStorage, - Name: "checkpoint_size_bytes", - Help: "the size of a checkpoint in bytes", - }), - stateSyncActive: promauto.NewGauge(prometheus.GaugeOpts{ Namespace: namespaceExecution, Subsystem: subsystemIngestion, @@ -929,11 +767,6 @@ func (ec *ExecutionCollector) ExecutionStorageStateCommitment(bytes int64) { ec.storageStateCommitment.Set(float64(bytes)) } -// ExecutionCheckpointSize reports the size of a checkpoint in bytes -func (ec *ExecutionCollector) ExecutionCheckpointSize(bytes uint64) { - ec.checkpointSize.Set(float64(bytes)) -} - // ExecutionLastExecutedBlockHeight reports last executed block height func (ec *ExecutionCollector) ExecutionLastExecutedBlockHeight(height uint64) { ec.lastExecutedBlockHeightGauge.Set(float64(height)) @@ -953,91 +786,6 @@ func (ec *ExecutionCollector) ExecutionTargetChunkDataPackPrunedHeight(height ui ec.targetChunkDataPackPrunedHeightGauge.Set(float64(height)) } -// ForestApproxMemorySize records approximate memory usage of forest (all in-memory trees) -func (ec *ExecutionCollector) ForestApproxMemorySize(bytes uint64) { - ec.forestApproxMemorySize.Set(float64(bytes)) -} - -// ForestNumberOfTrees current number of trees in a forest (in memory) -func (ec *ExecutionCollector) ForestNumberOfTrees(number uint64) { - ec.forestNumberOfTrees.Set(float64(number)) -} - -// LatestTrieRegCount records the number of unique register allocated (the lastest created trie) -func (ec *ExecutionCollector) LatestTrieRegCount(number uint64) { - ec.latestTrieRegCount.Set(float64(number)) -} - -// LatestTrieRegCountDiff records the difference between the number of unique register allocated of the latest created trie and parent trie -func (ec *ExecutionCollector) LatestTrieRegCountDiff(number int64) { - ec.latestTrieRegCountDiff.Set(float64(number)) -} - -// LatestTrieRegSize records the size of unique register allocated (the lastest created trie) -func (ec *ExecutionCollector) LatestTrieRegSize(size uint64) { - ec.latestTrieRegSize.Set(float64(size)) -} - -// LatestTrieRegSizeDiff records the difference between the size of unique register allocated of the latest created trie and parent trie -func (ec *ExecutionCollector) LatestTrieRegSizeDiff(size int64) { - ec.latestTrieRegSizeDiff.Set(float64(size)) -} - -// LatestTrieMaxDepthTouched records the maximum depth touched of the last created trie -func (ec *ExecutionCollector) LatestTrieMaxDepthTouched(maxDepth uint16) { - ec.latestTrieMaxDepthTouched.Set(float64(maxDepth)) -} - -// UpdateCount increase a counter of performed updates -func (ec *ExecutionCollector) UpdateCount() { - ec.updated.Inc() -} - -// ProofSize records a proof size -func (ec *ExecutionCollector) ProofSize(bytes uint32) { - ec.proofSize.Set(float64(bytes)) -} - -// UpdateValuesNumber accumulates number of updated values -func (ec *ExecutionCollector) UpdateValuesNumber(number uint64) { - ec.updatedValuesNumber.Add(float64(number)) -} - -// UpdateValuesSize total size (in bytes) of updates values -func (ec *ExecutionCollector) UpdateValuesSize(bytes uint64) { - ec.updatedValuesSize.Set(float64(bytes)) -} - -// UpdateDuration records absolute time for the update of a trie -func (ec *ExecutionCollector) UpdateDuration(duration time.Duration) { - ec.updatedDuration.Observe(duration.Seconds()) -} - -// UpdateDurationPerItem records update time for single value (total duration / number of updated values) -func (ec *ExecutionCollector) UpdateDurationPerItem(duration time.Duration) { - ec.updatedDurationPerValue.Observe(duration.Seconds()) -} - -// ReadValuesNumber accumulates number of read values -func (ec *ExecutionCollector) ReadValuesNumber(number uint64) { - ec.readValuesNumber.Add(float64(number)) -} - -// ReadValuesSize total size (in bytes) of read values -func (ec *ExecutionCollector) ReadValuesSize(bytes uint64) { - ec.readValuesSize.Set(float64(bytes)) -} - -// ReadDuration records absolute time for the read from a trie -func (ec *ExecutionCollector) ReadDuration(duration time.Duration) { - ec.readDuration.Observe(duration.Seconds()) -} - -// ReadDurationPerItem records read time for single value (total duration / number of read values) -func (ec *ExecutionCollector) ReadDurationPerItem(duration time.Duration) { - ec.readDurationPerValue.Observe(duration.Seconds()) -} - func (ec *ExecutionCollector) ExecutionCollectionRequestSent() { ec.collectionRequestSent.Inc() } diff --git a/module/metrics/extended_indexing.go b/module/metrics/extended_indexing.go new file mode 100644 index 00000000000..e8de8a6748d --- /dev/null +++ b/module/metrics/extended_indexing.go @@ -0,0 +1,103 @@ +package metrics + +import ( + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/onflow/flow-go/module" +) + +var _ module.ExtendedIndexingMetrics = (*ExtendedIndexingCollector)(nil) + +type ExtendedIndexingCollector struct { + indexedHeight *prometheus.GaugeVec + scheduledTxCount *prometheus.CounterVec + scheduledTxBackfillCount prometheus.Counter + ftTransferCount prometheus.Counter + nftTransferCount prometheus.Counter + contractDeploymentCount *prometheus.CounterVec +} + +func NewExtendedIndexingCollector() module.ExtendedIndexingMetrics { + indexedHeight := promauto.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: namespaceAccess, + Subsystem: subsystemExtendedIndexing, + Name: "latest_height", + Help: "latest processed height for extended indexers", + }, []string{"indexer"}) + + scheduledTxCount := promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: namespaceAccess, + Subsystem: subsystemExtendedIndexing, + Name: "scheduledtx_total", + Help: "total number of scheduled transactions processed, by status", + }, []string{"status"}) + + scheduledTxBackfillCount := promauto.NewCounter(prometheus.CounterOpts{ + Namespace: namespaceAccess, + Subsystem: subsystemExtendedIndexing, + Name: "scheduledtx_backfilled_total", + Help: "total number of scheduled transactions backfilled from state", + }) + + ftTransferCount := promauto.NewCounter(prometheus.CounterOpts{ + Namespace: namespaceAccess, + Subsystem: subsystemExtendedIndexing, + Name: "ft_transfers_total", + Help: "total number of fungible token transfers indexed", + }) + + nftTransferCount := promauto.NewCounter(prometheus.CounterOpts{ + Namespace: namespaceAccess, + Subsystem: subsystemExtendedIndexing, + Name: "nft_transfers_total", + Help: "total number of non-fungible token transfers indexed", + }) + + contractDeploymentCount := promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: namespaceAccess, + Subsystem: subsystemExtendedIndexing, + Name: "contract_deployments_total", + Help: "total number of contract deployments indexed, by action", + }, []string{"action"}) + + return &ExtendedIndexingCollector{ + indexedHeight: indexedHeight, + scheduledTxCount: scheduledTxCount, + scheduledTxBackfillCount: scheduledTxBackfillCount, + ftTransferCount: ftTransferCount, + nftTransferCount: nftTransferCount, + contractDeploymentCount: contractDeploymentCount, + } +} + +// BlockIndexedExtended records the latest processed height for a given extended indexer. +func (c *ExtendedIndexingCollector) BlockIndexedExtended(indexer string, height uint64) { + c.indexedHeight.WithLabelValues(indexer).Set(float64(height)) +} + +// ScheduledTransactionIndexed records counts of scheduled transactions processed in a single block. +func (c *ExtendedIndexingCollector) ScheduledTransactionIndexed(scheduled, executed, failed, canceled, backfilled int) { + c.scheduledTxCount.WithLabelValues("scheduled").Add(float64(scheduled)) + c.scheduledTxCount.WithLabelValues("executed").Add(float64(executed)) + c.scheduledTxCount.WithLabelValues("failed").Add(float64(failed)) + c.scheduledTxCount.WithLabelValues("canceled").Add(float64(canceled)) + c.scheduledTxBackfillCount.Add(float64(backfilled)) +} + +// FTTransferIndexed records the number of fungible token transfers indexed for a single block. +func (c *ExtendedIndexingCollector) FTTransferIndexed(count int) { + c.ftTransferCount.Add(float64(count)) +} + +// NFTTransferIndexed records the number of non-fungible token transfers indexed for a single block. +func (c *ExtendedIndexingCollector) NFTTransferIndexed(count int) { + c.nftTransferCount.Add(float64(count)) +} + +// ContractDeploymentIndexed records the number of contract deployments indexed for a single block, +// broken down by action (create vs update). +func (c *ExtendedIndexingCollector) ContractDeploymentIndexed(created, updated int) { + c.contractDeploymentCount.WithLabelValues("create").Add(float64(created)) + c.contractDeploymentCount.WithLabelValues("update").Add(float64(updated)) +} diff --git a/module/metrics/gossipsub.go b/module/metrics/gossipsub.go index 39dfd1f1e36..2379582ef89 100644 --- a/module/metrics/gossipsub.go +++ b/module/metrics/gossipsub.go @@ -5,6 +5,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/network/channels" ) // LocalGossipSubRouterMetrics encapsulates the metrics collectors for GossipSub router of the local node. @@ -261,8 +262,10 @@ func NewGossipSubLocalMeshMetrics(prefix string) *LocalGossipSubRouterMetrics { var _ module.LocalGossipSubRouterMetrics = (*LocalGossipSubRouterMetrics)(nil) // OnLocalMeshSizeUpdated updates the local mesh size metric. +// Cluster topics are normalized to their prefix (e.g., "sync-cluster", "consensus-cluster") +// to prevent unbounded cardinality growth during epoch transitions. func (g *LocalGossipSubRouterMetrics) OnLocalMeshSizeUpdated(topic string, size int) { - g.localMeshSize.WithLabelValues(topic).Set(float64(size)) + g.localMeshSize.WithLabelValues(channels.NormalizeTopicForMetrics(topic)).Set(float64(size)) } // OnPeerAddedToProtocol is called when the local node receives a stream from a peer on a gossipsub-related protocol. @@ -296,14 +299,16 @@ func (g *LocalGossipSubRouterMetrics) OnLocalPeerLeftTopic() { // OnPeerGraftTopic is called when the local node receives a GRAFT message from a remote peer on a topic. // Note: the received GRAFT at this point is considered passed the RPC inspection, and is accepted by the local node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (g *LocalGossipSubRouterMetrics) OnPeerGraftTopic(topic string) { - g.peerGraftTopicCount.WithLabelValues(topic).Inc() + g.peerGraftTopicCount.WithLabelValues(channels.NormalizeTopicForMetrics(topic)).Inc() } // OnPeerPruneTopic is called when the local node receives a PRUNE message from a remote peer on a topic. // Note: the received PRUNE at this point is considered passed the RPC inspection, and is accepted by the local node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (g *LocalGossipSubRouterMetrics) OnPeerPruneTopic(topic string) { - g.peerPruneTopicCount.WithLabelValues(topic).Inc() + g.peerPruneTopicCount.WithLabelValues(channels.NormalizeTopicForMetrics(topic)).Inc() } // OnMessageEnteredValidation is called when a received pubsub message enters the validation pipeline. It is the diff --git a/module/metrics/gossipsub_rpc_validation_inspector.go b/module/metrics/gossipsub_rpc_validation_inspector.go index d8c20fccc81..4611b3241d3 100644 --- a/module/metrics/gossipsub_rpc_validation_inspector.go +++ b/module/metrics/gossipsub_rpc_validation_inspector.go @@ -7,6 +7,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/network/channels" p2pmsg "github.com/onflow/flow-go/network/p2p/message" ) @@ -421,11 +422,12 @@ func (c *GossipSubRpcValidationInspectorMetrics) OnIWantMessageIDsReceived(msgId // OnIHaveMessageIDsReceived tracks the number of message ids received by the node from other nodes on an iHave message. // This function is called on each iHave message received by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. // Args: // - channel: the channel on which the iHave message was received. // - msgIdCount: the number of message ids received on the iHave message. func (c *GossipSubRpcValidationInspectorMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { - c.receivedIHaveMsgIDsHistogram.WithLabelValues(channel).Observe(float64(msgIdCount)) + c.receivedIHaveMsgIDsHistogram.WithLabelValues(channels.NormalizeTopicForMetrics(channel)).Observe(float64(msgIdCount)) } // OnIncomingRpcReceived tracks the number of incoming RPC messages received by the node. diff --git a/module/metrics/gossipsub_score.go b/module/metrics/gossipsub_score.go index 15e3628469c..8e13f40e352 100644 --- a/module/metrics/gossipsub_score.go +++ b/module/metrics/gossipsub_score.go @@ -143,19 +143,19 @@ func (g *GossipSubScoreMetrics) OnBehaviourPenaltyUpdated(penalty float64) { } func (g *GossipSubScoreMetrics) OnTimeInMeshUpdated(topic channels.Topic, duration time.Duration) { - g.timeInMesh.WithLabelValues(string(topic)).Observe(duration.Seconds()) + g.timeInMesh.WithLabelValues(channels.NormalizeTopicForMetrics(string(topic))).Observe(duration.Seconds()) } func (g *GossipSubScoreMetrics) OnFirstMessageDeliveredUpdated(topic channels.Topic, f float64) { - g.firstMessageDelivery.WithLabelValues(string(topic)).Observe(f) + g.firstMessageDelivery.WithLabelValues(channels.NormalizeTopicForMetrics(string(topic))).Observe(f) } func (g *GossipSubScoreMetrics) OnMeshMessageDeliveredUpdated(topic channels.Topic, f float64) { - g.meshMessageDelivery.WithLabelValues(string(topic)).Observe(f) + g.meshMessageDelivery.WithLabelValues(channels.NormalizeTopicForMetrics(string(topic))).Observe(f) } func (g *GossipSubScoreMetrics) OnInvalidMessageDeliveredUpdated(topic channels.Topic, f float64) { - g.invalidMessageDelivery.WithLabelValues(string(topic)).Observe(f) + g.invalidMessageDelivery.WithLabelValues(channels.NormalizeTopicForMetrics(string(topic))).Observe(f) } func (g *GossipSubScoreMetrics) SetWarningStateCount(u uint) { diff --git a/module/metrics/ledger.go b/module/metrics/ledger.go new file mode 100644 index 00000000000..0bae9e6ffe6 --- /dev/null +++ b/module/metrics/ledger.go @@ -0,0 +1,252 @@ +package metrics + +import ( + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/onflow/flow-go/module" +) + +const ( + namespaceLedger = "ledger" + subsystemWAL = "wal" +) + +// LedgerCollector implements both module.LedgerMetrics and module.WALMetrics. +// It can be reused by both the standalone ledger service and execution nodes. +type LedgerCollector struct { + namespace string + walSubsystem string + // LedgerMetrics + forestApproxMemorySize prometheus.Gauge + forestNumberOfTrees prometheus.Gauge + latestTrieRegCount prometheus.Gauge + latestTrieRegCountDiff prometheus.Gauge + latestTrieRegSize prometheus.Gauge + latestTrieRegSizeDiff prometheus.Gauge + latestTrieMaxDepthTouched prometheus.Gauge + updateCount prometheus.Counter + proofSize prometheus.Gauge + updateValuesNumber prometheus.Counter + updateValuesSize prometheus.Gauge + updateDuration prometheus.Histogram + updateDurationPerItem prometheus.Histogram + readValuesNumber prometheus.Counter + readValuesSize prometheus.Gauge + readDuration prometheus.Histogram + readDurationPerItem prometheus.Histogram + + // WALMetrics + checkpointSize prometheus.Gauge +} + +// NewLedgerCollector creates a new LedgerCollector that implements both +// module.LedgerMetrics and module.WALMetrics interfaces. +// If namespace is empty, it defaults to "ledger". +// If walSubsystem is empty, it defaults to "wal". +func NewLedgerCollector(namespace, walSubsystem string) *LedgerCollector { + if namespace == "" { + namespace = namespaceLedger + } + if walSubsystem == "" { + walSubsystem = subsystemWAL + } + return &LedgerCollector{ + namespace: namespace, + walSubsystem: walSubsystem, + forestApproxMemorySize: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "forest_approx_memory_size", + Help: "an approximate size of in-memory forest in bytes", + }), + forestNumberOfTrees: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "forest_number_of_trees", + Help: "the number of trees in memory", + }), + latestTrieRegCount: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "latest_trie_reg_count", + Help: "the number of allocated registers (latest created trie)", + }), + latestTrieRegCountDiff: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "latest_trie_reg_count_diff", + Help: "the difference between number of unique register allocated of the latest created trie and parent trie", + }), + latestTrieRegSize: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "latest_trie_reg_size", + Help: "the size of allocated registers (latest created trie)", + }), + latestTrieRegSizeDiff: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "latest_trie_reg_size_diff", + Help: "the difference between size of unique register allocated of the latest created trie and parent trie", + }), + latestTrieMaxDepthTouched: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "latest_trie_max_depth_touched", + Help: "the maximum depth touched of the latest created trie", + }), + updateCount: promauto.NewCounter(prometheus.CounterOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "updates_counted", + Help: "the number of updates", + }), + proofSize: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "average_proof_size", + Help: "the average size of a single generated proof in bytes", + }), + updateValuesNumber: promauto.NewCounter(prometheus.CounterOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "update_values_number", + Help: "the total number of values updated", + }), + updateValuesSize: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "update_values_size", + Help: "the total size of values for single update in bytes", + }), + updateDuration: promauto.NewHistogram(prometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "update_duration", + Help: "the duration of update operation", + Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, + }), + updateDurationPerItem: promauto.NewHistogram(prometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "update_duration_per_value", + Help: "the duration of update operation per value", + Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, + }), + readValuesNumber: promauto.NewCounter(prometheus.CounterOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "read_values_number", + Help: "the total number of values read", + }), + readValuesSize: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "read_values_size", + Help: "the total size of values for single read in bytes", + }), + readDuration: promauto.NewHistogram(prometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "read_duration", + Help: "the duration of read operation", + Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, + }), + readDurationPerItem: promauto.NewHistogram(prometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: subsystemMTrie, + Name: "read_duration_per_value", + Help: "the duration of read operation per value", + Buckets: []float64{0.05, 0.2, 0.5, 1, 2, 5}, + }), + checkpointSize: promauto.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: walSubsystem, + Name: "checkpoint_size_bytes", + Help: "the size of a checkpoint in bytes", + }), + } +} + +// Ensure LedgerCollector implements both interfaces +var _ module.LedgerMetrics = (*LedgerCollector)(nil) +var _ module.WALMetrics = (*LedgerCollector)(nil) + +// LedgerMetrics implementation + +func (lc *LedgerCollector) ForestApproxMemorySize(bytes uint64) { + lc.forestApproxMemorySize.Set(float64(bytes)) +} + +func (lc *LedgerCollector) ForestNumberOfTrees(number uint64) { + lc.forestNumberOfTrees.Set(float64(number)) +} + +func (lc *LedgerCollector) LatestTrieRegCount(number uint64) { + lc.latestTrieRegCount.Set(float64(number)) +} + +func (lc *LedgerCollector) LatestTrieRegCountDiff(number int64) { + lc.latestTrieRegCountDiff.Set(float64(number)) +} + +func (lc *LedgerCollector) LatestTrieRegSize(size uint64) { + lc.latestTrieRegSize.Set(float64(size)) +} + +func (lc *LedgerCollector) LatestTrieRegSizeDiff(size int64) { + lc.latestTrieRegSizeDiff.Set(float64(size)) +} + +func (lc *LedgerCollector) LatestTrieMaxDepthTouched(maxDepth uint16) { + lc.latestTrieMaxDepthTouched.Set(float64(maxDepth)) +} + +func (lc *LedgerCollector) UpdateCount() { + lc.updateCount.Inc() +} + +func (lc *LedgerCollector) ProofSize(bytes uint32) { + lc.proofSize.Set(float64(bytes)) +} + +func (lc *LedgerCollector) UpdateValuesNumber(number uint64) { + lc.updateValuesNumber.Add(float64(number)) +} + +func (lc *LedgerCollector) UpdateValuesSize(bytes uint64) { + lc.updateValuesSize.Set(float64(bytes)) +} + +func (lc *LedgerCollector) UpdateDuration(duration time.Duration) { + lc.updateDuration.Observe(duration.Seconds()) +} + +func (lc *LedgerCollector) UpdateDurationPerItem(duration time.Duration) { + lc.updateDurationPerItem.Observe(duration.Seconds()) +} + +func (lc *LedgerCollector) ReadValuesNumber(number uint64) { + lc.readValuesNumber.Add(float64(number)) +} + +func (lc *LedgerCollector) ReadValuesSize(bytes uint64) { + lc.readValuesSize.Set(float64(bytes)) +} + +func (lc *LedgerCollector) ReadDuration(duration time.Duration) { + lc.readDuration.Observe(duration.Seconds()) +} + +func (lc *LedgerCollector) ReadDurationPerItem(duration time.Duration) { + lc.readDurationPerItem.Observe(duration.Seconds()) +} + +// WALMetrics implementation + +func (lc *LedgerCollector) ExecutionCheckpointSize(bytes uint64) { + lc.checkpointSize.Set(float64(bytes)) +} diff --git a/module/metrics/namespaces.go b/module/metrics/namespaces.go index b72b524850f..d3c9fef1c34 100644 --- a/module/metrics/namespaces.go +++ b/module/metrics/namespaces.go @@ -95,6 +95,7 @@ const ( subsystemExeDataPruner = "pruner" subsystemExecutionDataRequester = "execution_data_requester" subsystemExecutionStateIndexer = "execution_state_indexer" + subsystemExtendedIndexing = "extended" subsystemExeDataBlobstore = "blobstore" subsystemTxErrorFetcher = "tx_errors" ) diff --git a/module/metrics/network.go b/module/metrics/network.go index a6eead52e48..a7073eb0dcf 100644 --- a/module/metrics/network.go +++ b/module/metrics/network.go @@ -10,6 +10,7 @@ import ( "github.com/rs/zerolog" "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/network/channels" logging2 "github.com/onflow/flow-go/network/p2p/logging" "github.com/onflow/flow-go/utils/logging" ) @@ -260,18 +261,21 @@ func NewNetworkCollector(logger zerolog.Logger, opts ...NetworkCollectorOpt) *Ne } // OutboundMessageSent collects metrics related to a message sent by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) OutboundMessageSent(sizeBytes int, topic, protocol, messageType string) { - nc.outboundMessageSize.WithLabelValues(topic, protocol, messageType).Observe(float64(sizeBytes)) + nc.outboundMessageSize.WithLabelValues(channels.NormalizeTopicForMetrics(topic), protocol, messageType).Observe(float64(sizeBytes)) } // InboundMessageReceived collects metrics related to a message received by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) InboundMessageReceived(sizeBytes int, topic, protocol, messageType string) { - nc.inboundMessageSize.WithLabelValues(topic, protocol, messageType).Observe(float64(sizeBytes)) + nc.inboundMessageSize.WithLabelValues(channels.NormalizeTopicForMetrics(topic), protocol, messageType).Observe(float64(sizeBytes)) } // DuplicateInboundMessagesDropped increments the metric tracking the number of duplicate messages dropped by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) DuplicateInboundMessagesDropped(topic, protocol, messageType string) { - nc.duplicateMessagesDropped.WithLabelValues(topic, protocol, messageType).Add(1) + nc.duplicateMessagesDropped.WithLabelValues(channels.NormalizeTopicForMetrics(topic), protocol, messageType).Add(1) } func (nc *NetworkCollector) MessageAdded(priority int) { @@ -287,18 +291,21 @@ func (nc *NetworkCollector) QueueDuration(duration time.Duration, priority int) } // MessageProcessingStarted increments the metric tracking the number of messages being processed by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) MessageProcessingStarted(topic string) { - nc.numMessagesProcessing.WithLabelValues(topic).Inc() + nc.numMessagesProcessing.WithLabelValues(channels.NormalizeTopicForMetrics(topic)).Inc() } // UnicastMessageSendingStarted increments the metric tracking the number of unicast messages sent by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) UnicastMessageSendingStarted(topic string) { - nc.numDirectMessagesSending.WithLabelValues(topic).Inc() + nc.numDirectMessagesSending.WithLabelValues(channels.NormalizeTopicForMetrics(topic)).Inc() } // UnicastMessageSendingCompleted decrements the metric tracking the number of unicast messages sent by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) UnicastMessageSendingCompleted(topic string) { - nc.numDirectMessagesSending.WithLabelValues(topic).Dec() + nc.numDirectMessagesSending.WithLabelValues(channels.NormalizeTopicForMetrics(topic)).Dec() } func (nc *NetworkCollector) RoutingTablePeerAdded() { @@ -311,9 +318,11 @@ func (nc *NetworkCollector) RoutingTablePeerRemoved() { // MessageProcessingFinished tracks the time spent by the node to process a message and decrements the metric tracking // the number of messages being processed by the node. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) MessageProcessingFinished(topic string, duration time.Duration) { - nc.numMessagesProcessing.WithLabelValues(topic).Dec() - nc.inboundProcessTime.WithLabelValues(topic).Add(duration.Seconds()) + normalizedTopic := channels.NormalizeTopicForMetrics(topic) + nc.numMessagesProcessing.WithLabelValues(normalizedTopic).Dec() + nc.inboundProcessTime.WithLabelValues(normalizedTopic).Add(duration.Seconds()) } // OutboundConnections updates the metric tracking the number of outbound connections of this node @@ -353,11 +362,13 @@ func (nc *NetworkCollector) OnDNSLookupRequestDropped() { } // OnUnauthorizedMessage tracks the number of unauthorized messages seen on the network. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) OnUnauthorizedMessage(role, msgType, topic, offense string) { - nc.unAuthorizedMessagesCount.WithLabelValues(role, msgType, topic, offense).Inc() + nc.unAuthorizedMessagesCount.WithLabelValues(role, msgType, channels.NormalizeTopicForMetrics(topic), offense).Inc() } // OnRateLimitedPeer tracks the number of rate limited messages seen on the network. +// Cluster topics are normalized to their prefix to prevent unbounded cardinality growth. func (nc *NetworkCollector) OnRateLimitedPeer(peerID peer.ID, role, msgType, topic, reason string) { nc.logger.Warn(). Str("peer_id", logging2.PeerId(peerID)). @@ -367,7 +378,7 @@ func (nc *NetworkCollector) OnRateLimitedPeer(peerID peer.ID, role, msgType, top Str("reason", reason). Bool(logging.KeySuspicious, true). Msg("unicast peer rate limited") - nc.rateLimitedUnicastMessagesCount.WithLabelValues(role, msgType, topic, reason).Inc() + nc.rateLimitedUnicastMessagesCount.WithLabelValues(role, msgType, channels.NormalizeTopicForMetrics(topic), reason).Inc() } // OnViolationReportSkipped tracks the number of slashing violations consumer violations that were not diff --git a/module/metrics/network_test.go b/module/metrics/network_test.go new file mode 100644 index 00000000000..ea4c24946c7 --- /dev/null +++ b/module/metrics/network_test.go @@ -0,0 +1,172 @@ +package metrics + +import ( + "fmt" + "testing" + + "github.com/prometheus/client_golang/prometheus" + io_prometheus_client "github.com/prometheus/client_model/go" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestNetworkCollector_ClusterTopicNormalization verifies that cluster topics are normalized +// to their prefix (e.g., "sync-cluster-*" -> "sync-cluster") to prevent unbounded metric +// cardinality growth during epoch transitions. +func TestNetworkCollector_ClusterTopicNormalization(t *testing.T) { + prefix := fmt.Sprintf("test_%s_", t.Name()) + logger := zerolog.Nop() + nc := NewNetworkCollector(logger, WithNetworkPrefix(prefix)) + + // These cluster topics should be normalized to their prefix + clusterTopic1 := "sync-cluster-test-cluster-id-1" + clusterTopic2 := "sync-cluster-test-cluster-id-2" + consensusClusterTopic := "consensus-cluster-test-cluster-id" + nonClusterTopic := "blocks" + protocol := "pubsub" + msgType := "BlockProposal" + + // Record metrics for multiple cluster topics and a non-cluster topic + nc.InboundMessageReceived(100, clusterTopic1, protocol, msgType) + nc.InboundMessageReceived(200, clusterTopic2, protocol, msgType) + nc.InboundMessageReceived(300, consensusClusterTopic, protocol, msgType) + nc.InboundMessageReceived(400, nonClusterTopic, protocol, msgType) + + nc.OutboundMessageSent(150, clusterTopic1, protocol, msgType) + nc.OutboundMessageSent(250, clusterTopic2, protocol, msgType) + nc.OutboundMessageSent(350, consensusClusterTopic, protocol, msgType) + nc.OutboundMessageSent(450, nonClusterTopic, protocol, msgType) + + nc.DuplicateInboundMessagesDropped(clusterTopic1, protocol, msgType) + nc.DuplicateInboundMessagesDropped(clusterTopic2, protocol, msgType) + nc.DuplicateInboundMessagesDropped(consensusClusterTopic, protocol, msgType) + nc.DuplicateInboundMessagesDropped(nonClusterTopic, protocol, msgType) + + // Verify cluster topics are normalized to their prefix + // Both sync-cluster topics should be recorded under "sync-cluster" + assertHistogramVecHasLabel(t, nc.inboundMessageSize, LabelChannel, "sync-cluster", "sync-cluster topics should be normalized to 'sync-cluster'") + assertHistogramVecHasLabel(t, nc.inboundMessageSize, LabelChannel, "consensus-cluster", "consensus-cluster topics should be normalized to 'consensus-cluster'") + + // Verify the original cluster topic names are NOT present (they should be normalized) + assertHistogramVecNotHasLabel(t, nc.inboundMessageSize, LabelChannel, clusterTopic1, "original cluster topic name should not be present") + assertHistogramVecNotHasLabel(t, nc.inboundMessageSize, LabelChannel, clusterTopic2, "original cluster topic name should not be present") + assertHistogramVecNotHasLabel(t, nc.inboundMessageSize, LabelChannel, consensusClusterTopic, "original consensus-cluster topic name should not be present") + + // Verify non-cluster topics are NOT normalized (they should keep their original name) + assertHistogramVecHasLabel(t, nc.inboundMessageSize, LabelChannel, nonClusterTopic, "non-cluster topics should keep their original name") +} + +// TestLocalGossipSubRouterMetrics_ClusterTopicNormalization verifies that LocalGossipSubRouterMetrics +// normalizes cluster topics to their prefix. +func TestLocalGossipSubRouterMetrics_ClusterTopicNormalization(t *testing.T) { + prefix := fmt.Sprintf("test_%s_", t.Name()) + m := NewGossipSubLocalMeshMetrics(prefix) + + clusterTopic1 := "sync-cluster-cluster-1" + clusterTopic2 := "sync-cluster-cluster-2" + consensusClusterTopic := "consensus-cluster-cluster-1" + nonClusterTopic := "blocks" + + // Record metrics for cluster and non-cluster topics + m.OnLocalMeshSizeUpdated(clusterTopic1, 5) + m.OnLocalMeshSizeUpdated(clusterTopic2, 3) + m.OnLocalMeshSizeUpdated(consensusClusterTopic, 4) + m.OnLocalMeshSizeUpdated(nonClusterTopic, 2) + + m.OnPeerGraftTopic(clusterTopic1) + m.OnPeerGraftTopic(clusterTopic2) + m.OnPeerGraftTopic(consensusClusterTopic) + m.OnPeerGraftTopic(nonClusterTopic) + + m.OnPeerPruneTopic(clusterTopic1) + m.OnPeerPruneTopic(clusterTopic2) + m.OnPeerPruneTopic(consensusClusterTopic) + m.OnPeerPruneTopic(nonClusterTopic) + + // Verify cluster topics are normalized to their prefix + assertGaugeVecHasLabel(t, &m.localMeshSize, LabelChannel, "sync-cluster", "sync-cluster topics should be normalized") + assertGaugeVecHasLabel(t, &m.localMeshSize, LabelChannel, "consensus-cluster", "consensus-cluster topics should be normalized") + + // Verify original cluster topic names are NOT present + assertGaugeVecNotHasLabel(t, &m.localMeshSize, LabelChannel, clusterTopic1, "original cluster topic should not be present") + assertGaugeVecNotHasLabel(t, &m.localMeshSize, LabelChannel, clusterTopic2, "original cluster topic should not be present") + assertGaugeVecNotHasLabel(t, &m.localMeshSize, LabelChannel, consensusClusterTopic, "original consensus-cluster topic should not be present") + + // Verify non-cluster topics are NOT normalized + assertGaugeVecHasLabel(t, &m.localMeshSize, LabelChannel, nonClusterTopic, "non-cluster topics should keep their original name") +} + +// assertHistogramVecHasLabel checks that the histogram vec has at least one metric with the given label value. +func assertHistogramVecHasLabel(t *testing.T, hv *prometheus.HistogramVec, labelName, labelValue, msg string) { + t.Helper() + found := histogramVecHasLabelValue(t, hv, labelName, labelValue) + assert.True(t, found, msg) +} + +// assertHistogramVecNotHasLabel checks that the histogram vec has no metrics with the given label value. +func assertHistogramVecNotHasLabel(t *testing.T, hv *prometheus.HistogramVec, labelName, labelValue, msg string) { + t.Helper() + found := histogramVecHasLabelValue(t, hv, labelName, labelValue) + assert.False(t, found, msg) +} + +// assertGaugeVecHasLabel checks that the gauge vec has at least one metric with the given label value. +func assertGaugeVecHasLabel(t *testing.T, gv *prometheus.GaugeVec, labelName, labelValue, msg string) { + t.Helper() + found := gaugeVecHasLabelValue(t, gv, labelName, labelValue) + assert.True(t, found, msg) +} + +// assertGaugeVecNotHasLabel checks that the gauge vec has no metrics with the given label value. +func assertGaugeVecNotHasLabel(t *testing.T, gv *prometheus.GaugeVec, labelName, labelValue, msg string) { + t.Helper() + found := gaugeVecHasLabelValue(t, gv, labelName, labelValue) + assert.False(t, found, msg) +} + +// histogramVecHasLabelValue collects metrics from the histogram vec and checks if any have the given label value. +func histogramVecHasLabelValue(t *testing.T, hv *prometheus.HistogramVec, labelName, labelValue string) bool { + t.Helper() + ch := make(chan prometheus.Metric, 100) + go func() { + hv.Collect(ch) + close(ch) + }() + + for metric := range ch { + var m io_prometheus_client.Metric + err := metric.Write(&m) + require.NoError(t, err) + + for _, label := range m.GetLabel() { + if label.GetName() == labelName && label.GetValue() == labelValue { + return true + } + } + } + return false +} + +// gaugeVecHasLabelValue collects metrics from the gauge vec and checks if any have the given label value. +func gaugeVecHasLabelValue(t *testing.T, gv *prometheus.GaugeVec, labelName, labelValue string) bool { + t.Helper() + ch := make(chan prometheus.Metric, 100) + go func() { + gv.Collect(ch) + close(ch) + }() + + for metric := range ch { + var m io_prometheus_client.Metric + err := metric.Write(&m) + require.NoError(t, err) + + for _, label := range m.GetLabel() { + if label.GetName() == labelName && label.GetValue() == labelValue { + return true + } + } + } + return false +} diff --git a/module/metrics/noop.go b/module/metrics/noop.go index b1565826f40..4a4b69a2264 100644 --- a/module/metrics/noop.go +++ b/module/metrics/noop.go @@ -4,12 +4,11 @@ import ( "context" "time" - "google.golang.org/grpc/codes" - "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/protocol" httpmetrics "github.com/slok/go-http-metrics/metrics" + "google.golang.org/grpc/codes" "github.com/onflow/flow-go/model/chainsync" "github.com/onflow/flow-go/model/cluster" @@ -229,6 +228,7 @@ func (nc *NoopCollector) TransactionValidationSkipped() func (nc *NoopCollector) TransactionSubmissionFailed() {} func (nc *NoopCollector) UpdateExecutionReceiptMaxHeight(height uint64) {} func (nc *NoopCollector) UpdateLastFullBlockHeight(height uint64) {} +func (nc *NoopCollector) UpdateIngestionFinalizedBlockHeight(height uint64) {} func (nc *NoopCollector) ChunkDataPackRequestProcessed() {} func (nc *NoopCollector) ExecutionSync(syncing bool) {} func (nc *NoopCollector) ExecutionBlockDataUploadStarted() {} @@ -377,6 +377,14 @@ func (nc *NoopCollector) BlockIndexed(uint64, time.Duration, int, int, int) {} func (nc *NoopCollector) BlockReindexed() {} func (nc *NoopCollector) InitializeLatestHeight(height uint64) {} +var _ module.ExtendedIndexingMetrics = (*NoopCollector)(nil) + +func (nc *NoopCollector) BlockIndexedExtended(string, uint64) {} +func (nc *NoopCollector) ScheduledTransactionIndexed(int, int, int, int, int) {} +func (nc *NoopCollector) FTTransferIndexed(int) {} +func (nc *NoopCollector) NFTTransferIndexed(int) {} +func (nc *NoopCollector) ContractDeploymentIndexed(int, int) {} + var _ module.TransactionErrorMessagesMetrics = (*NoopCollector)(nil) func (nc *NoopCollector) TxErrorsInitialHeight(uint64) {} diff --git a/module/metrics/rest_api.go b/module/metrics/rest_api.go index e9132f243c6..dab51dcd518 100644 --- a/module/metrics/rest_api.go +++ b/module/metrics/rest_api.go @@ -17,15 +17,16 @@ type RestCollector struct { httpRequestsInflight *prometheus.GaugeVec httpRequestsTotal *prometheus.GaugeVec - // urlToRouteMapper is a callback that converts a URL to a route name - urlToRouteMapper func(string) (string, error) + urlToRouteMapper func(string, string) (string, error) // converts (method, url) to a route name } var _ module.RestMetrics = (*RestCollector)(nil) // NewRestCollector returns a new metrics RestCollector that implements the RestCollector // using Prometheus as the backend. -func NewRestCollector(urlToRouteMapper func(string) (string, error), registerer prometheus.Registerer) (*RestCollector, error) { +func NewRestCollector(urlToRouteMapper func(string, string) (string, error), + registerer prometheus.Registerer, +) (*RestCollector, error) { if urlToRouteMapper == nil { return nil, fmt.Errorf("urlToRouteMapper cannot be nil") } @@ -76,35 +77,35 @@ func NewRestCollector(urlToRouteMapper func(string) (string, error), registerer // ObserveHTTPRequestDuration records the duration of the REST request. // This method is called automatically by go-http-metrics/middleware func (r *RestCollector) ObserveHTTPRequestDuration(_ context.Context, p httpmetrics.HTTPReqProperties, duration time.Duration) { - handler := r.mapURLToRoute(p.ID) + handler := r.mapURLToRoute(p.Method, p.ID) r.httpRequestDurHistogram.WithLabelValues(p.Service, handler, p.Method, p.Code).Observe(duration.Seconds()) } // ObserveHTTPResponseSize records the response size of the REST request. // This method is called automatically by go-http-metrics/middleware func (r *RestCollector) ObserveHTTPResponseSize(_ context.Context, p httpmetrics.HTTPReqProperties, sizeBytes int64) { - handler := r.mapURLToRoute(p.ID) + handler := r.mapURLToRoute(p.Method, p.ID) r.httpResponseSizeHistogram.WithLabelValues(p.Service, handler, p.Method, p.Code).Observe(float64(sizeBytes)) } // AddInflightRequests increments and decrements the number of inflight request being processed. // This method is called automatically by go-http-metrics/middleware func (r *RestCollector) AddInflightRequests(_ context.Context, p httpmetrics.HTTPProperties, quantity int) { - handler := r.mapURLToRoute(p.ID) + handler := r.mapURLToRoute("", p.ID) r.httpRequestsInflight.WithLabelValues(p.Service, handler).Add(float64(quantity)) } // AddTotalRequests records all REST requests // This is a custom method called by the REST handler func (r *RestCollector) AddTotalRequests(_ context.Context, method, path string) { - handler := r.mapURLToRoute(path) + handler := r.mapURLToRoute(method, path) r.httpRequestsTotal.WithLabelValues(method, handler).Inc() } // mapURLToRoute uses the urlToRouteMapper callback to convert a URL to a route name // This normalizes the URL, removing dynamic information converting it to a static string -func (r *RestCollector) mapURLToRoute(url string) string { - route, err := r.urlToRouteMapper(url) +func (r *RestCollector) mapURLToRoute(method, url string) string { + route, err := r.urlToRouteMapper(method, url) if err != nil { return "unknown" } diff --git a/module/mock/access_metrics.go b/module/mock/access_metrics.go index 47145fd21b4..40a59509cba 100644 --- a/module/mock/access_metrics.go +++ b/module/mock/access_metrics.go @@ -1,188 +1,1299 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - flow "github.com/onflow/flow-go/model/flow" - metrics "github.com/slok/go-http-metrics/metrics" + "context" + "time" + "github.com/onflow/flow-go/model/flow" + "github.com/slok/go-http-metrics/metrics" mock "github.com/stretchr/testify/mock" - - time "time" ) +// NewAccessMetrics creates a new instance of AccessMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccessMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *AccessMetrics { + mock := &AccessMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // AccessMetrics is an autogenerated mock type for the AccessMetrics type type AccessMetrics struct { mock.Mock } -// AddInflightRequests provides a mock function with given fields: ctx, props, quantity -func (_m *AccessMetrics) AddInflightRequests(ctx context.Context, props metrics.HTTPProperties, quantity int) { - _m.Called(ctx, props, quantity) +type AccessMetrics_Expecter struct { + mock *mock.Mock } -// AddTotalRequests provides a mock function with given fields: ctx, method, routeName -func (_m *AccessMetrics) AddTotalRequests(ctx context.Context, method string, routeName string) { - _m.Called(ctx, method, routeName) +func (_m *AccessMetrics) EXPECT() *AccessMetrics_Expecter { + return &AccessMetrics_Expecter{mock: &_m.Mock} } -// ConnectionAddedToPool provides a mock function with no fields -func (_m *AccessMetrics) ConnectionAddedToPool() { - _m.Called() +// AddInflightRequests provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) AddInflightRequests(ctx context.Context, props metrics.HTTPProperties, quantity int) { + _mock.Called(ctx, props, quantity) + return } -// ConnectionFromPoolEvicted provides a mock function with no fields -func (_m *AccessMetrics) ConnectionFromPoolEvicted() { - _m.Called() +// AccessMetrics_AddInflightRequests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddInflightRequests' +type AccessMetrics_AddInflightRequests_Call struct { + *mock.Call } -// ConnectionFromPoolInvalidated provides a mock function with no fields -func (_m *AccessMetrics) ConnectionFromPoolInvalidated() { - _m.Called() +// AddInflightRequests is a helper method to define mock.On call +// - ctx context.Context +// - props metrics.HTTPProperties +// - quantity int +func (_e *AccessMetrics_Expecter) AddInflightRequests(ctx interface{}, props interface{}, quantity interface{}) *AccessMetrics_AddInflightRequests_Call { + return &AccessMetrics_AddInflightRequests_Call{Call: _e.mock.On("AddInflightRequests", ctx, props, quantity)} } -// ConnectionFromPoolReused provides a mock function with no fields -func (_m *AccessMetrics) ConnectionFromPoolReused() { - _m.Called() +func (_c *AccessMetrics_AddInflightRequests_Call) Run(run func(ctx context.Context, props metrics.HTTPProperties, quantity int)) *AccessMetrics_AddInflightRequests_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 metrics.HTTPProperties + if args[1] != nil { + arg1 = args[1].(metrics.HTTPProperties) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// ConnectionFromPoolUpdated provides a mock function with no fields -func (_m *AccessMetrics) ConnectionFromPoolUpdated() { - _m.Called() +func (_c *AccessMetrics_AddInflightRequests_Call) Return() *AccessMetrics_AddInflightRequests_Call { + _c.Call.Return() + return _c } -// NewConnectionEstablished provides a mock function with no fields -func (_m *AccessMetrics) NewConnectionEstablished() { - _m.Called() +func (_c *AccessMetrics_AddInflightRequests_Call) RunAndReturn(run func(ctx context.Context, props metrics.HTTPProperties, quantity int)) *AccessMetrics_AddInflightRequests_Call { + _c.Run(run) + return _c } -// ObserveHTTPRequestDuration provides a mock function with given fields: ctx, props, duration -func (_m *AccessMetrics) ObserveHTTPRequestDuration(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration) { - _m.Called(ctx, props, duration) +// AddTotalRequests provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) AddTotalRequests(ctx context.Context, method string, routeName string) { + _mock.Called(ctx, method, routeName) + return } -// ObserveHTTPResponseSize provides a mock function with given fields: ctx, props, sizeBytes -func (_m *AccessMetrics) ObserveHTTPResponseSize(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64) { - _m.Called(ctx, props, sizeBytes) +// AccessMetrics_AddTotalRequests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddTotalRequests' +type AccessMetrics_AddTotalRequests_Call struct { + *mock.Call } -// ScriptExecuted provides a mock function with given fields: dur, size -func (_m *AccessMetrics) ScriptExecuted(dur time.Duration, size int) { - _m.Called(dur, size) +// AddTotalRequests is a helper method to define mock.On call +// - ctx context.Context +// - method string +// - routeName string +func (_e *AccessMetrics_Expecter) AddTotalRequests(ctx interface{}, method interface{}, routeName interface{}) *AccessMetrics_AddTotalRequests_Call { + return &AccessMetrics_AddTotalRequests_Call{Call: _e.mock.On("AddTotalRequests", ctx, method, routeName)} } -// ScriptExecutionErrorLocal provides a mock function with no fields -func (_m *AccessMetrics) ScriptExecutionErrorLocal() { - _m.Called() +func (_c *AccessMetrics_AddTotalRequests_Call) Run(run func(ctx context.Context, method string, routeName string)) *AccessMetrics_AddTotalRequests_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// ScriptExecutionErrorMatch provides a mock function with no fields -func (_m *AccessMetrics) ScriptExecutionErrorMatch() { - _m.Called() +func (_c *AccessMetrics_AddTotalRequests_Call) Return() *AccessMetrics_AddTotalRequests_Call { + _c.Call.Return() + return _c } -// ScriptExecutionErrorMismatch provides a mock function with no fields -func (_m *AccessMetrics) ScriptExecutionErrorMismatch() { - _m.Called() +func (_c *AccessMetrics_AddTotalRequests_Call) RunAndReturn(run func(ctx context.Context, method string, routeName string)) *AccessMetrics_AddTotalRequests_Call { + _c.Run(run) + return _c } -// ScriptExecutionErrorOnExecutionNode provides a mock function with no fields -func (_m *AccessMetrics) ScriptExecutionErrorOnExecutionNode() { - _m.Called() +// ConnectionAddedToPool provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ConnectionAddedToPool() { + _mock.Called() + return } -// ScriptExecutionNotIndexed provides a mock function with no fields -func (_m *AccessMetrics) ScriptExecutionNotIndexed() { - _m.Called() +// AccessMetrics_ConnectionAddedToPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionAddedToPool' +type AccessMetrics_ConnectionAddedToPool_Call struct { + *mock.Call } -// ScriptExecutionResultMatch provides a mock function with no fields -func (_m *AccessMetrics) ScriptExecutionResultMatch() { - _m.Called() +// ConnectionAddedToPool is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ConnectionAddedToPool() *AccessMetrics_ConnectionAddedToPool_Call { + return &AccessMetrics_ConnectionAddedToPool_Call{Call: _e.mock.On("ConnectionAddedToPool")} } -// ScriptExecutionResultMismatch provides a mock function with no fields -func (_m *AccessMetrics) ScriptExecutionResultMismatch() { - _m.Called() +func (_c *AccessMetrics_ConnectionAddedToPool_Call) Run(run func()) *AccessMetrics_ConnectionAddedToPool_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// TotalConnectionsInPool provides a mock function with given fields: connectionCount, connectionPoolSize -func (_m *AccessMetrics) TotalConnectionsInPool(connectionCount uint, connectionPoolSize uint) { - _m.Called(connectionCount, connectionPoolSize) +func (_c *AccessMetrics_ConnectionAddedToPool_Call) Return() *AccessMetrics_ConnectionAddedToPool_Call { + _c.Call.Return() + return _c } -// TransactionExecuted provides a mock function with given fields: txID, when -func (_m *AccessMetrics) TransactionExecuted(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +func (_c *AccessMetrics_ConnectionAddedToPool_Call) RunAndReturn(run func()) *AccessMetrics_ConnectionAddedToPool_Call { + _c.Run(run) + return _c } -// TransactionExpired provides a mock function with given fields: txID -func (_m *AccessMetrics) TransactionExpired(txID flow.Identifier) { - _m.Called(txID) +// ConnectionFromPoolEvicted provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ConnectionFromPoolEvicted() { + _mock.Called() + return } -// TransactionFinalized provides a mock function with given fields: txID, when -func (_m *AccessMetrics) TransactionFinalized(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +// AccessMetrics_ConnectionFromPoolEvicted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolEvicted' +type AccessMetrics_ConnectionFromPoolEvicted_Call struct { + *mock.Call } -// TransactionReceived provides a mock function with given fields: txID, when -func (_m *AccessMetrics) TransactionReceived(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +// ConnectionFromPoolEvicted is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ConnectionFromPoolEvicted() *AccessMetrics_ConnectionFromPoolEvicted_Call { + return &AccessMetrics_ConnectionFromPoolEvicted_Call{Call: _e.mock.On("ConnectionFromPoolEvicted")} } -// TransactionResultFetched provides a mock function with given fields: dur, size -func (_m *AccessMetrics) TransactionResultFetched(dur time.Duration, size int) { - _m.Called(dur, size) +func (_c *AccessMetrics_ConnectionFromPoolEvicted_Call) Run(run func()) *AccessMetrics_ConnectionFromPoolEvicted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// TransactionSealed provides a mock function with given fields: txID, when -func (_m *AccessMetrics) TransactionSealed(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +func (_c *AccessMetrics_ConnectionFromPoolEvicted_Call) Return() *AccessMetrics_ConnectionFromPoolEvicted_Call { + _c.Call.Return() + return _c } -// TransactionSubmissionFailed provides a mock function with no fields -func (_m *AccessMetrics) TransactionSubmissionFailed() { - _m.Called() +func (_c *AccessMetrics_ConnectionFromPoolEvicted_Call) RunAndReturn(run func()) *AccessMetrics_ConnectionFromPoolEvicted_Call { + _c.Run(run) + return _c } -// TransactionValidated provides a mock function with no fields -func (_m *AccessMetrics) TransactionValidated() { - _m.Called() +// ConnectionFromPoolInvalidated provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ConnectionFromPoolInvalidated() { + _mock.Called() + return } -// TransactionValidationFailed provides a mock function with given fields: reason -func (_m *AccessMetrics) TransactionValidationFailed(reason string) { - _m.Called(reason) +// AccessMetrics_ConnectionFromPoolInvalidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolInvalidated' +type AccessMetrics_ConnectionFromPoolInvalidated_Call struct { + *mock.Call } -// TransactionValidationSkipped provides a mock function with no fields -func (_m *AccessMetrics) TransactionValidationSkipped() { - _m.Called() +// ConnectionFromPoolInvalidated is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ConnectionFromPoolInvalidated() *AccessMetrics_ConnectionFromPoolInvalidated_Call { + return &AccessMetrics_ConnectionFromPoolInvalidated_Call{Call: _e.mock.On("ConnectionFromPoolInvalidated")} } -// UpdateExecutionReceiptMaxHeight provides a mock function with given fields: height -func (_m *AccessMetrics) UpdateExecutionReceiptMaxHeight(height uint64) { - _m.Called(height) +func (_c *AccessMetrics_ConnectionFromPoolInvalidated_Call) Run(run func()) *AccessMetrics_ConnectionFromPoolInvalidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// UpdateLastFullBlockHeight provides a mock function with given fields: height -func (_m *AccessMetrics) UpdateLastFullBlockHeight(height uint64) { - _m.Called(height) +func (_c *AccessMetrics_ConnectionFromPoolInvalidated_Call) Return() *AccessMetrics_ConnectionFromPoolInvalidated_Call { + _c.Call.Return() + return _c } -// NewAccessMetrics creates a new instance of AccessMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewAccessMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *AccessMetrics { - mock := &AccessMetrics{} - mock.Mock.Test(t) +func (_c *AccessMetrics_ConnectionFromPoolInvalidated_Call) RunAndReturn(run func()) *AccessMetrics_ConnectionFromPoolInvalidated_Call { + _c.Run(run) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ConnectionFromPoolReused provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ConnectionFromPoolReused() { + _mock.Called() + return +} - return mock +// AccessMetrics_ConnectionFromPoolReused_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolReused' +type AccessMetrics_ConnectionFromPoolReused_Call struct { + *mock.Call +} + +// ConnectionFromPoolReused is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ConnectionFromPoolReused() *AccessMetrics_ConnectionFromPoolReused_Call { + return &AccessMetrics_ConnectionFromPoolReused_Call{Call: _e.mock.On("ConnectionFromPoolReused")} +} + +func (_c *AccessMetrics_ConnectionFromPoolReused_Call) Run(run func()) *AccessMetrics_ConnectionFromPoolReused_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ConnectionFromPoolReused_Call) Return() *AccessMetrics_ConnectionFromPoolReused_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ConnectionFromPoolReused_Call) RunAndReturn(run func()) *AccessMetrics_ConnectionFromPoolReused_Call { + _c.Run(run) + return _c +} + +// ConnectionFromPoolUpdated provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ConnectionFromPoolUpdated() { + _mock.Called() + return +} + +// AccessMetrics_ConnectionFromPoolUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolUpdated' +type AccessMetrics_ConnectionFromPoolUpdated_Call struct { + *mock.Call +} + +// ConnectionFromPoolUpdated is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ConnectionFromPoolUpdated() *AccessMetrics_ConnectionFromPoolUpdated_Call { + return &AccessMetrics_ConnectionFromPoolUpdated_Call{Call: _e.mock.On("ConnectionFromPoolUpdated")} +} + +func (_c *AccessMetrics_ConnectionFromPoolUpdated_Call) Run(run func()) *AccessMetrics_ConnectionFromPoolUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ConnectionFromPoolUpdated_Call) Return() *AccessMetrics_ConnectionFromPoolUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ConnectionFromPoolUpdated_Call) RunAndReturn(run func()) *AccessMetrics_ConnectionFromPoolUpdated_Call { + _c.Run(run) + return _c +} + +// NewConnectionEstablished provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) NewConnectionEstablished() { + _mock.Called() + return +} + +// AccessMetrics_NewConnectionEstablished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewConnectionEstablished' +type AccessMetrics_NewConnectionEstablished_Call struct { + *mock.Call +} + +// NewConnectionEstablished is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) NewConnectionEstablished() *AccessMetrics_NewConnectionEstablished_Call { + return &AccessMetrics_NewConnectionEstablished_Call{Call: _e.mock.On("NewConnectionEstablished")} +} + +func (_c *AccessMetrics_NewConnectionEstablished_Call) Run(run func()) *AccessMetrics_NewConnectionEstablished_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_NewConnectionEstablished_Call) Return() *AccessMetrics_NewConnectionEstablished_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_NewConnectionEstablished_Call) RunAndReturn(run func()) *AccessMetrics_NewConnectionEstablished_Call { + _c.Run(run) + return _c +} + +// ObserveHTTPRequestDuration provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ObserveHTTPRequestDuration(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration) { + _mock.Called(ctx, props, duration) + return +} + +// AccessMetrics_ObserveHTTPRequestDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ObserveHTTPRequestDuration' +type AccessMetrics_ObserveHTTPRequestDuration_Call struct { + *mock.Call +} + +// ObserveHTTPRequestDuration is a helper method to define mock.On call +// - ctx context.Context +// - props metrics.HTTPReqProperties +// - duration time.Duration +func (_e *AccessMetrics_Expecter) ObserveHTTPRequestDuration(ctx interface{}, props interface{}, duration interface{}) *AccessMetrics_ObserveHTTPRequestDuration_Call { + return &AccessMetrics_ObserveHTTPRequestDuration_Call{Call: _e.mock.On("ObserveHTTPRequestDuration", ctx, props, duration)} +} + +func (_c *AccessMetrics_ObserveHTTPRequestDuration_Call) Run(run func(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration)) *AccessMetrics_ObserveHTTPRequestDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 metrics.HTTPReqProperties + if args[1] != nil { + arg1 = args[1].(metrics.HTTPReqProperties) + } + var arg2 time.Duration + if args[2] != nil { + arg2 = args[2].(time.Duration) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *AccessMetrics_ObserveHTTPRequestDuration_Call) Return() *AccessMetrics_ObserveHTTPRequestDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ObserveHTTPRequestDuration_Call) RunAndReturn(run func(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration)) *AccessMetrics_ObserveHTTPRequestDuration_Call { + _c.Run(run) + return _c +} + +// ObserveHTTPResponseSize provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ObserveHTTPResponseSize(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64) { + _mock.Called(ctx, props, sizeBytes) + return +} + +// AccessMetrics_ObserveHTTPResponseSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ObserveHTTPResponseSize' +type AccessMetrics_ObserveHTTPResponseSize_Call struct { + *mock.Call +} + +// ObserveHTTPResponseSize is a helper method to define mock.On call +// - ctx context.Context +// - props metrics.HTTPReqProperties +// - sizeBytes int64 +func (_e *AccessMetrics_Expecter) ObserveHTTPResponseSize(ctx interface{}, props interface{}, sizeBytes interface{}) *AccessMetrics_ObserveHTTPResponseSize_Call { + return &AccessMetrics_ObserveHTTPResponseSize_Call{Call: _e.mock.On("ObserveHTTPResponseSize", ctx, props, sizeBytes)} +} + +func (_c *AccessMetrics_ObserveHTTPResponseSize_Call) Run(run func(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64)) *AccessMetrics_ObserveHTTPResponseSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 metrics.HTTPReqProperties + if args[1] != nil { + arg1 = args[1].(metrics.HTTPReqProperties) + } + var arg2 int64 + if args[2] != nil { + arg2 = args[2].(int64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *AccessMetrics_ObserveHTTPResponseSize_Call) Return() *AccessMetrics_ObserveHTTPResponseSize_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ObserveHTTPResponseSize_Call) RunAndReturn(run func(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64)) *AccessMetrics_ObserveHTTPResponseSize_Call { + _c.Run(run) + return _c +} + +// ScriptExecuted provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecuted(dur time.Duration, size int) { + _mock.Called(dur, size) + return +} + +// AccessMetrics_ScriptExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecuted' +type AccessMetrics_ScriptExecuted_Call struct { + *mock.Call +} + +// ScriptExecuted is a helper method to define mock.On call +// - dur time.Duration +// - size int +func (_e *AccessMetrics_Expecter) ScriptExecuted(dur interface{}, size interface{}) *AccessMetrics_ScriptExecuted_Call { + return &AccessMetrics_ScriptExecuted_Call{Call: _e.mock.On("ScriptExecuted", dur, size)} +} + +func (_c *AccessMetrics_ScriptExecuted_Call) Run(run func(dur time.Duration, size int)) *AccessMetrics_ScriptExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecuted_Call) Return() *AccessMetrics_ScriptExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecuted_Call) RunAndReturn(run func(dur time.Duration, size int)) *AccessMetrics_ScriptExecuted_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionErrorLocal provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecutionErrorLocal() { + _mock.Called() + return +} + +// AccessMetrics_ScriptExecutionErrorLocal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorLocal' +type AccessMetrics_ScriptExecutionErrorLocal_Call struct { + *mock.Call +} + +// ScriptExecutionErrorLocal is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ScriptExecutionErrorLocal() *AccessMetrics_ScriptExecutionErrorLocal_Call { + return &AccessMetrics_ScriptExecutionErrorLocal_Call{Call: _e.mock.On("ScriptExecutionErrorLocal")} +} + +func (_c *AccessMetrics_ScriptExecutionErrorLocal_Call) Run(run func()) *AccessMetrics_ScriptExecutionErrorLocal_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorLocal_Call) Return() *AccessMetrics_ScriptExecutionErrorLocal_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorLocal_Call) RunAndReturn(run func()) *AccessMetrics_ScriptExecutionErrorLocal_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionErrorMatch provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecutionErrorMatch() { + _mock.Called() + return +} + +// AccessMetrics_ScriptExecutionErrorMatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorMatch' +type AccessMetrics_ScriptExecutionErrorMatch_Call struct { + *mock.Call +} + +// ScriptExecutionErrorMatch is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ScriptExecutionErrorMatch() *AccessMetrics_ScriptExecutionErrorMatch_Call { + return &AccessMetrics_ScriptExecutionErrorMatch_Call{Call: _e.mock.On("ScriptExecutionErrorMatch")} +} + +func (_c *AccessMetrics_ScriptExecutionErrorMatch_Call) Run(run func()) *AccessMetrics_ScriptExecutionErrorMatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorMatch_Call) Return() *AccessMetrics_ScriptExecutionErrorMatch_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorMatch_Call) RunAndReturn(run func()) *AccessMetrics_ScriptExecutionErrorMatch_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionErrorMismatch provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecutionErrorMismatch() { + _mock.Called() + return +} + +// AccessMetrics_ScriptExecutionErrorMismatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorMismatch' +type AccessMetrics_ScriptExecutionErrorMismatch_Call struct { + *mock.Call +} + +// ScriptExecutionErrorMismatch is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ScriptExecutionErrorMismatch() *AccessMetrics_ScriptExecutionErrorMismatch_Call { + return &AccessMetrics_ScriptExecutionErrorMismatch_Call{Call: _e.mock.On("ScriptExecutionErrorMismatch")} +} + +func (_c *AccessMetrics_ScriptExecutionErrorMismatch_Call) Run(run func()) *AccessMetrics_ScriptExecutionErrorMismatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorMismatch_Call) Return() *AccessMetrics_ScriptExecutionErrorMismatch_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorMismatch_Call) RunAndReturn(run func()) *AccessMetrics_ScriptExecutionErrorMismatch_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionErrorOnExecutionNode provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecutionErrorOnExecutionNode() { + _mock.Called() + return +} + +// AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorOnExecutionNode' +type AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call struct { + *mock.Call +} + +// ScriptExecutionErrorOnExecutionNode is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ScriptExecutionErrorOnExecutionNode() *AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call { + return &AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call{Call: _e.mock.On("ScriptExecutionErrorOnExecutionNode")} +} + +func (_c *AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call) Run(run func()) *AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call) Return() *AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call) RunAndReturn(run func()) *AccessMetrics_ScriptExecutionErrorOnExecutionNode_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionNotIndexed provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecutionNotIndexed() { + _mock.Called() + return +} + +// AccessMetrics_ScriptExecutionNotIndexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionNotIndexed' +type AccessMetrics_ScriptExecutionNotIndexed_Call struct { + *mock.Call +} + +// ScriptExecutionNotIndexed is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ScriptExecutionNotIndexed() *AccessMetrics_ScriptExecutionNotIndexed_Call { + return &AccessMetrics_ScriptExecutionNotIndexed_Call{Call: _e.mock.On("ScriptExecutionNotIndexed")} +} + +func (_c *AccessMetrics_ScriptExecutionNotIndexed_Call) Run(run func()) *AccessMetrics_ScriptExecutionNotIndexed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecutionNotIndexed_Call) Return() *AccessMetrics_ScriptExecutionNotIndexed_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecutionNotIndexed_Call) RunAndReturn(run func()) *AccessMetrics_ScriptExecutionNotIndexed_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionResultMatch provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecutionResultMatch() { + _mock.Called() + return +} + +// AccessMetrics_ScriptExecutionResultMatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionResultMatch' +type AccessMetrics_ScriptExecutionResultMatch_Call struct { + *mock.Call +} + +// ScriptExecutionResultMatch is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ScriptExecutionResultMatch() *AccessMetrics_ScriptExecutionResultMatch_Call { + return &AccessMetrics_ScriptExecutionResultMatch_Call{Call: _e.mock.On("ScriptExecutionResultMatch")} +} + +func (_c *AccessMetrics_ScriptExecutionResultMatch_Call) Run(run func()) *AccessMetrics_ScriptExecutionResultMatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecutionResultMatch_Call) Return() *AccessMetrics_ScriptExecutionResultMatch_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecutionResultMatch_Call) RunAndReturn(run func()) *AccessMetrics_ScriptExecutionResultMatch_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionResultMismatch provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) ScriptExecutionResultMismatch() { + _mock.Called() + return +} + +// AccessMetrics_ScriptExecutionResultMismatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionResultMismatch' +type AccessMetrics_ScriptExecutionResultMismatch_Call struct { + *mock.Call +} + +// ScriptExecutionResultMismatch is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) ScriptExecutionResultMismatch() *AccessMetrics_ScriptExecutionResultMismatch_Call { + return &AccessMetrics_ScriptExecutionResultMismatch_Call{Call: _e.mock.On("ScriptExecutionResultMismatch")} +} + +func (_c *AccessMetrics_ScriptExecutionResultMismatch_Call) Run(run func()) *AccessMetrics_ScriptExecutionResultMismatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_ScriptExecutionResultMismatch_Call) Return() *AccessMetrics_ScriptExecutionResultMismatch_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_ScriptExecutionResultMismatch_Call) RunAndReturn(run func()) *AccessMetrics_ScriptExecutionResultMismatch_Call { + _c.Run(run) + return _c +} + +// TotalConnectionsInPool provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TotalConnectionsInPool(connectionCount uint, connectionPoolSize uint) { + _mock.Called(connectionCount, connectionPoolSize) + return +} + +// AccessMetrics_TotalConnectionsInPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TotalConnectionsInPool' +type AccessMetrics_TotalConnectionsInPool_Call struct { + *mock.Call +} + +// TotalConnectionsInPool is a helper method to define mock.On call +// - connectionCount uint +// - connectionPoolSize uint +func (_e *AccessMetrics_Expecter) TotalConnectionsInPool(connectionCount interface{}, connectionPoolSize interface{}) *AccessMetrics_TotalConnectionsInPool_Call { + return &AccessMetrics_TotalConnectionsInPool_Call{Call: _e.mock.On("TotalConnectionsInPool", connectionCount, connectionPoolSize)} +} + +func (_c *AccessMetrics_TotalConnectionsInPool_Call) Run(run func(connectionCount uint, connectionPoolSize uint)) *AccessMetrics_TotalConnectionsInPool_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + var arg1 uint + if args[1] != nil { + arg1 = args[1].(uint) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessMetrics_TotalConnectionsInPool_Call) Return() *AccessMetrics_TotalConnectionsInPool_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TotalConnectionsInPool_Call) RunAndReturn(run func(connectionCount uint, connectionPoolSize uint)) *AccessMetrics_TotalConnectionsInPool_Call { + _c.Run(run) + return _c +} + +// TransactionExecuted provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionExecuted(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return +} + +// AccessMetrics_TransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionExecuted' +type AccessMetrics_TransactionExecuted_Call struct { + *mock.Call +} + +// TransactionExecuted is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *AccessMetrics_Expecter) TransactionExecuted(txID interface{}, when interface{}) *AccessMetrics_TransactionExecuted_Call { + return &AccessMetrics_TransactionExecuted_Call{Call: _e.mock.On("TransactionExecuted", txID, when)} +} + +func (_c *AccessMetrics_TransactionExecuted_Call) Run(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessMetrics_TransactionExecuted_Call) Return() *AccessMetrics_TransactionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionExecuted_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionExecuted_Call { + _c.Run(run) + return _c +} + +// TransactionExpired provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionExpired(txID flow.Identifier) { + _mock.Called(txID) + return +} + +// AccessMetrics_TransactionExpired_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionExpired' +type AccessMetrics_TransactionExpired_Call struct { + *mock.Call +} + +// TransactionExpired is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *AccessMetrics_Expecter) TransactionExpired(txID interface{}) *AccessMetrics_TransactionExpired_Call { + return &AccessMetrics_TransactionExpired_Call{Call: _e.mock.On("TransactionExpired", txID)} +} + +func (_c *AccessMetrics_TransactionExpired_Call) Run(run func(txID flow.Identifier)) *AccessMetrics_TransactionExpired_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccessMetrics_TransactionExpired_Call) Return() *AccessMetrics_TransactionExpired_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionExpired_Call) RunAndReturn(run func(txID flow.Identifier)) *AccessMetrics_TransactionExpired_Call { + _c.Run(run) + return _c +} + +// TransactionFinalized provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionFinalized(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return +} + +// AccessMetrics_TransactionFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionFinalized' +type AccessMetrics_TransactionFinalized_Call struct { + *mock.Call +} + +// TransactionFinalized is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *AccessMetrics_Expecter) TransactionFinalized(txID interface{}, when interface{}) *AccessMetrics_TransactionFinalized_Call { + return &AccessMetrics_TransactionFinalized_Call{Call: _e.mock.On("TransactionFinalized", txID, when)} +} + +func (_c *AccessMetrics_TransactionFinalized_Call) Run(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessMetrics_TransactionFinalized_Call) Return() *AccessMetrics_TransactionFinalized_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionFinalized_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionFinalized_Call { + _c.Run(run) + return _c +} + +// TransactionReceived provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionReceived(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return +} + +// AccessMetrics_TransactionReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionReceived' +type AccessMetrics_TransactionReceived_Call struct { + *mock.Call +} + +// TransactionReceived is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *AccessMetrics_Expecter) TransactionReceived(txID interface{}, when interface{}) *AccessMetrics_TransactionReceived_Call { + return &AccessMetrics_TransactionReceived_Call{Call: _e.mock.On("TransactionReceived", txID, when)} +} + +func (_c *AccessMetrics_TransactionReceived_Call) Run(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessMetrics_TransactionReceived_Call) Return() *AccessMetrics_TransactionReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionReceived_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionReceived_Call { + _c.Run(run) + return _c +} + +// TransactionResultFetched provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionResultFetched(dur time.Duration, size int) { + _mock.Called(dur, size) + return +} + +// AccessMetrics_TransactionResultFetched_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionResultFetched' +type AccessMetrics_TransactionResultFetched_Call struct { + *mock.Call +} + +// TransactionResultFetched is a helper method to define mock.On call +// - dur time.Duration +// - size int +func (_e *AccessMetrics_Expecter) TransactionResultFetched(dur interface{}, size interface{}) *AccessMetrics_TransactionResultFetched_Call { + return &AccessMetrics_TransactionResultFetched_Call{Call: _e.mock.On("TransactionResultFetched", dur, size)} +} + +func (_c *AccessMetrics_TransactionResultFetched_Call) Run(run func(dur time.Duration, size int)) *AccessMetrics_TransactionResultFetched_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessMetrics_TransactionResultFetched_Call) Return() *AccessMetrics_TransactionResultFetched_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionResultFetched_Call) RunAndReturn(run func(dur time.Duration, size int)) *AccessMetrics_TransactionResultFetched_Call { + _c.Run(run) + return _c +} + +// TransactionSealed provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionSealed(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return +} + +// AccessMetrics_TransactionSealed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionSealed' +type AccessMetrics_TransactionSealed_Call struct { + *mock.Call +} + +// TransactionSealed is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *AccessMetrics_Expecter) TransactionSealed(txID interface{}, when interface{}) *AccessMetrics_TransactionSealed_Call { + return &AccessMetrics_TransactionSealed_Call{Call: _e.mock.On("TransactionSealed", txID, when)} +} + +func (_c *AccessMetrics_TransactionSealed_Call) Run(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionSealed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccessMetrics_TransactionSealed_Call) Return() *AccessMetrics_TransactionSealed_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionSealed_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *AccessMetrics_TransactionSealed_Call { + _c.Run(run) + return _c +} + +// TransactionSubmissionFailed provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionSubmissionFailed() { + _mock.Called() + return +} + +// AccessMetrics_TransactionSubmissionFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionSubmissionFailed' +type AccessMetrics_TransactionSubmissionFailed_Call struct { + *mock.Call +} + +// TransactionSubmissionFailed is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) TransactionSubmissionFailed() *AccessMetrics_TransactionSubmissionFailed_Call { + return &AccessMetrics_TransactionSubmissionFailed_Call{Call: _e.mock.On("TransactionSubmissionFailed")} +} + +func (_c *AccessMetrics_TransactionSubmissionFailed_Call) Run(run func()) *AccessMetrics_TransactionSubmissionFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_TransactionSubmissionFailed_Call) Return() *AccessMetrics_TransactionSubmissionFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionSubmissionFailed_Call) RunAndReturn(run func()) *AccessMetrics_TransactionSubmissionFailed_Call { + _c.Run(run) + return _c +} + +// TransactionValidated provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionValidated() { + _mock.Called() + return +} + +// AccessMetrics_TransactionValidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidated' +type AccessMetrics_TransactionValidated_Call struct { + *mock.Call +} + +// TransactionValidated is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) TransactionValidated() *AccessMetrics_TransactionValidated_Call { + return &AccessMetrics_TransactionValidated_Call{Call: _e.mock.On("TransactionValidated")} +} + +func (_c *AccessMetrics_TransactionValidated_Call) Run(run func()) *AccessMetrics_TransactionValidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_TransactionValidated_Call) Return() *AccessMetrics_TransactionValidated_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionValidated_Call) RunAndReturn(run func()) *AccessMetrics_TransactionValidated_Call { + _c.Run(run) + return _c +} + +// TransactionValidationFailed provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionValidationFailed(reason string) { + _mock.Called(reason) + return +} + +// AccessMetrics_TransactionValidationFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidationFailed' +type AccessMetrics_TransactionValidationFailed_Call struct { + *mock.Call +} + +// TransactionValidationFailed is a helper method to define mock.On call +// - reason string +func (_e *AccessMetrics_Expecter) TransactionValidationFailed(reason interface{}) *AccessMetrics_TransactionValidationFailed_Call { + return &AccessMetrics_TransactionValidationFailed_Call{Call: _e.mock.On("TransactionValidationFailed", reason)} +} + +func (_c *AccessMetrics_TransactionValidationFailed_Call) Run(run func(reason string)) *AccessMetrics_TransactionValidationFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccessMetrics_TransactionValidationFailed_Call) Return() *AccessMetrics_TransactionValidationFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionValidationFailed_Call) RunAndReturn(run func(reason string)) *AccessMetrics_TransactionValidationFailed_Call { + _c.Run(run) + return _c +} + +// TransactionValidationSkipped provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) TransactionValidationSkipped() { + _mock.Called() + return +} + +// AccessMetrics_TransactionValidationSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidationSkipped' +type AccessMetrics_TransactionValidationSkipped_Call struct { + *mock.Call +} + +// TransactionValidationSkipped is a helper method to define mock.On call +func (_e *AccessMetrics_Expecter) TransactionValidationSkipped() *AccessMetrics_TransactionValidationSkipped_Call { + return &AccessMetrics_TransactionValidationSkipped_Call{Call: _e.mock.On("TransactionValidationSkipped")} +} + +func (_c *AccessMetrics_TransactionValidationSkipped_Call) Run(run func()) *AccessMetrics_TransactionValidationSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccessMetrics_TransactionValidationSkipped_Call) Return() *AccessMetrics_TransactionValidationSkipped_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_TransactionValidationSkipped_Call) RunAndReturn(run func()) *AccessMetrics_TransactionValidationSkipped_Call { + _c.Run(run) + return _c +} + +// UpdateExecutionReceiptMaxHeight provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) UpdateExecutionReceiptMaxHeight(height uint64) { + _mock.Called(height) + return +} + +// AccessMetrics_UpdateExecutionReceiptMaxHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateExecutionReceiptMaxHeight' +type AccessMetrics_UpdateExecutionReceiptMaxHeight_Call struct { + *mock.Call +} + +// UpdateExecutionReceiptMaxHeight is a helper method to define mock.On call +// - height uint64 +func (_e *AccessMetrics_Expecter) UpdateExecutionReceiptMaxHeight(height interface{}) *AccessMetrics_UpdateExecutionReceiptMaxHeight_Call { + return &AccessMetrics_UpdateExecutionReceiptMaxHeight_Call{Call: _e.mock.On("UpdateExecutionReceiptMaxHeight", height)} +} + +func (_c *AccessMetrics_UpdateExecutionReceiptMaxHeight_Call) Run(run func(height uint64)) *AccessMetrics_UpdateExecutionReceiptMaxHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccessMetrics_UpdateExecutionReceiptMaxHeight_Call) Return() *AccessMetrics_UpdateExecutionReceiptMaxHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_UpdateExecutionReceiptMaxHeight_Call) RunAndReturn(run func(height uint64)) *AccessMetrics_UpdateExecutionReceiptMaxHeight_Call { + _c.Run(run) + return _c +} + +// UpdateIngestionFinalizedBlockHeight provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) UpdateIngestionFinalizedBlockHeight(height uint64) { + _mock.Called(height) + return +} + +// AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateIngestionFinalizedBlockHeight' +type AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call struct { + *mock.Call +} + +// UpdateIngestionFinalizedBlockHeight is a helper method to define mock.On call +// - height uint64 +func (_e *AccessMetrics_Expecter) UpdateIngestionFinalizedBlockHeight(height interface{}) *AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call { + return &AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call{Call: _e.mock.On("UpdateIngestionFinalizedBlockHeight", height)} +} + +func (_c *AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call) Run(run func(height uint64)) *AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call) Return() *AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call) RunAndReturn(run func(height uint64)) *AccessMetrics_UpdateIngestionFinalizedBlockHeight_Call { + _c.Run(run) + return _c +} + +// UpdateLastFullBlockHeight provides a mock function for the type AccessMetrics +func (_mock *AccessMetrics) UpdateLastFullBlockHeight(height uint64) { + _mock.Called(height) + return +} + +// AccessMetrics_UpdateLastFullBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateLastFullBlockHeight' +type AccessMetrics_UpdateLastFullBlockHeight_Call struct { + *mock.Call +} + +// UpdateLastFullBlockHeight is a helper method to define mock.On call +// - height uint64 +func (_e *AccessMetrics_Expecter) UpdateLastFullBlockHeight(height interface{}) *AccessMetrics_UpdateLastFullBlockHeight_Call { + return &AccessMetrics_UpdateLastFullBlockHeight_Call{Call: _e.mock.On("UpdateLastFullBlockHeight", height)} +} + +func (_c *AccessMetrics_UpdateLastFullBlockHeight_Call) Run(run func(height uint64)) *AccessMetrics_UpdateLastFullBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *AccessMetrics_UpdateLastFullBlockHeight_Call) Return() *AccessMetrics_UpdateLastFullBlockHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *AccessMetrics_UpdateLastFullBlockHeight_Call) RunAndReturn(run func(height uint64)) *AccessMetrics_UpdateLastFullBlockHeight_Call { + _c.Run(run) + return _c } diff --git a/module/mock/alsp_metrics.go b/module/mock/alsp_metrics.go index 0c202466bed..dd973358dd9 100644 --- a/module/mock/alsp_metrics.go +++ b/module/mock/alsp_metrics.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// AlspMetrics is an autogenerated mock type for the AlspMetrics type -type AlspMetrics struct { - mock.Mock -} - -// OnMisbehaviorReported provides a mock function with given fields: channel, misbehaviorType -func (_m *AlspMetrics) OnMisbehaviorReported(channel string, misbehaviorType string) { - _m.Called(channel, misbehaviorType) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewAlspMetrics creates a new instance of AlspMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,62 @@ func NewAlspMetrics(t interface { return mock } + +// AlspMetrics is an autogenerated mock type for the AlspMetrics type +type AlspMetrics struct { + mock.Mock +} + +type AlspMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *AlspMetrics) EXPECT() *AlspMetrics_Expecter { + return &AlspMetrics_Expecter{mock: &_m.Mock} +} + +// OnMisbehaviorReported provides a mock function for the type AlspMetrics +func (_mock *AlspMetrics) OnMisbehaviorReported(channel string, misbehaviorType string) { + _mock.Called(channel, misbehaviorType) + return +} + +// AlspMetrics_OnMisbehaviorReported_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMisbehaviorReported' +type AlspMetrics_OnMisbehaviorReported_Call struct { + *mock.Call +} + +// OnMisbehaviorReported is a helper method to define mock.On call +// - channel string +// - misbehaviorType string +func (_e *AlspMetrics_Expecter) OnMisbehaviorReported(channel interface{}, misbehaviorType interface{}) *AlspMetrics_OnMisbehaviorReported_Call { + return &AlspMetrics_OnMisbehaviorReported_Call{Call: _e.mock.On("OnMisbehaviorReported", channel, misbehaviorType)} +} + +func (_c *AlspMetrics_OnMisbehaviorReported_Call) Run(run func(channel string, misbehaviorType string)) *AlspMetrics_OnMisbehaviorReported_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AlspMetrics_OnMisbehaviorReported_Call) Return() *AlspMetrics_OnMisbehaviorReported_Call { + _c.Call.Return() + return _c +} + +func (_c *AlspMetrics_OnMisbehaviorReported_Call) RunAndReturn(run func(channel string, misbehaviorType string)) *AlspMetrics_OnMisbehaviorReported_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/backend_scripts_metrics.go b/module/mock/backend_scripts_metrics.go index 0b981dd282e..8c5ee62fe05 100644 --- a/module/mock/backend_scripts_metrics.go +++ b/module/mock/backend_scripts_metrics.go @@ -1,68 +1,315 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewBackendScriptsMetrics creates a new instance of BackendScriptsMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBackendScriptsMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *BackendScriptsMetrics { + mock := &BackendScriptsMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BackendScriptsMetrics is an autogenerated mock type for the BackendScriptsMetrics type type BackendScriptsMetrics struct { mock.Mock } -// ScriptExecuted provides a mock function with given fields: dur, size -func (_m *BackendScriptsMetrics) ScriptExecuted(dur time.Duration, size int) { - _m.Called(dur, size) +type BackendScriptsMetrics_Expecter struct { + mock *mock.Mock } -// ScriptExecutionErrorLocal provides a mock function with no fields -func (_m *BackendScriptsMetrics) ScriptExecutionErrorLocal() { - _m.Called() +func (_m *BackendScriptsMetrics) EXPECT() *BackendScriptsMetrics_Expecter { + return &BackendScriptsMetrics_Expecter{mock: &_m.Mock} } -// ScriptExecutionErrorMatch provides a mock function with no fields -func (_m *BackendScriptsMetrics) ScriptExecutionErrorMatch() { - _m.Called() +// ScriptExecuted provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecuted(dur time.Duration, size int) { + _mock.Called(dur, size) + return } -// ScriptExecutionErrorMismatch provides a mock function with no fields -func (_m *BackendScriptsMetrics) ScriptExecutionErrorMismatch() { - _m.Called() +// BackendScriptsMetrics_ScriptExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecuted' +type BackendScriptsMetrics_ScriptExecuted_Call struct { + *mock.Call } -// ScriptExecutionErrorOnExecutionNode provides a mock function with no fields -func (_m *BackendScriptsMetrics) ScriptExecutionErrorOnExecutionNode() { - _m.Called() +// ScriptExecuted is a helper method to define mock.On call +// - dur time.Duration +// - size int +func (_e *BackendScriptsMetrics_Expecter) ScriptExecuted(dur interface{}, size interface{}) *BackendScriptsMetrics_ScriptExecuted_Call { + return &BackendScriptsMetrics_ScriptExecuted_Call{Call: _e.mock.On("ScriptExecuted", dur, size)} } -// ScriptExecutionNotIndexed provides a mock function with no fields -func (_m *BackendScriptsMetrics) ScriptExecutionNotIndexed() { - _m.Called() +func (_c *BackendScriptsMetrics_ScriptExecuted_Call) Run(run func(dur time.Duration, size int)) *BackendScriptsMetrics_ScriptExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c } -// ScriptExecutionResultMatch provides a mock function with no fields -func (_m *BackendScriptsMetrics) ScriptExecutionResultMatch() { - _m.Called() +func (_c *BackendScriptsMetrics_ScriptExecuted_Call) Return() *BackendScriptsMetrics_ScriptExecuted_Call { + _c.Call.Return() + return _c } -// ScriptExecutionResultMismatch provides a mock function with no fields -func (_m *BackendScriptsMetrics) ScriptExecutionResultMismatch() { - _m.Called() +func (_c *BackendScriptsMetrics_ScriptExecuted_Call) RunAndReturn(run func(dur time.Duration, size int)) *BackendScriptsMetrics_ScriptExecuted_Call { + _c.Run(run) + return _c } -// NewBackendScriptsMetrics creates a new instance of BackendScriptsMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBackendScriptsMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *BackendScriptsMetrics { - mock := &BackendScriptsMetrics{} - mock.Mock.Test(t) +// ScriptExecutionErrorLocal provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecutionErrorLocal() { + _mock.Called() + return +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// BackendScriptsMetrics_ScriptExecutionErrorLocal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorLocal' +type BackendScriptsMetrics_ScriptExecutionErrorLocal_Call struct { + *mock.Call +} - return mock +// ScriptExecutionErrorLocal is a helper method to define mock.On call +func (_e *BackendScriptsMetrics_Expecter) ScriptExecutionErrorLocal() *BackendScriptsMetrics_ScriptExecutionErrorLocal_Call { + return &BackendScriptsMetrics_ScriptExecutionErrorLocal_Call{Call: _e.mock.On("ScriptExecutionErrorLocal")} +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorLocal_Call) Run(run func()) *BackendScriptsMetrics_ScriptExecutionErrorLocal_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorLocal_Call) Return() *BackendScriptsMetrics_ScriptExecutionErrorLocal_Call { + _c.Call.Return() + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorLocal_Call) RunAndReturn(run func()) *BackendScriptsMetrics_ScriptExecutionErrorLocal_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionErrorMatch provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecutionErrorMatch() { + _mock.Called() + return +} + +// BackendScriptsMetrics_ScriptExecutionErrorMatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorMatch' +type BackendScriptsMetrics_ScriptExecutionErrorMatch_Call struct { + *mock.Call +} + +// ScriptExecutionErrorMatch is a helper method to define mock.On call +func (_e *BackendScriptsMetrics_Expecter) ScriptExecutionErrorMatch() *BackendScriptsMetrics_ScriptExecutionErrorMatch_Call { + return &BackendScriptsMetrics_ScriptExecutionErrorMatch_Call{Call: _e.mock.On("ScriptExecutionErrorMatch")} +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorMatch_Call) Run(run func()) *BackendScriptsMetrics_ScriptExecutionErrorMatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorMatch_Call) Return() *BackendScriptsMetrics_ScriptExecutionErrorMatch_Call { + _c.Call.Return() + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorMatch_Call) RunAndReturn(run func()) *BackendScriptsMetrics_ScriptExecutionErrorMatch_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionErrorMismatch provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecutionErrorMismatch() { + _mock.Called() + return +} + +// BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorMismatch' +type BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call struct { + *mock.Call +} + +// ScriptExecutionErrorMismatch is a helper method to define mock.On call +func (_e *BackendScriptsMetrics_Expecter) ScriptExecutionErrorMismatch() *BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call { + return &BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call{Call: _e.mock.On("ScriptExecutionErrorMismatch")} +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call) Run(run func()) *BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call) Return() *BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call { + _c.Call.Return() + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call) RunAndReturn(run func()) *BackendScriptsMetrics_ScriptExecutionErrorMismatch_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionErrorOnExecutionNode provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecutionErrorOnExecutionNode() { + _mock.Called() + return +} + +// BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionErrorOnExecutionNode' +type BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call struct { + *mock.Call +} + +// ScriptExecutionErrorOnExecutionNode is a helper method to define mock.On call +func (_e *BackendScriptsMetrics_Expecter) ScriptExecutionErrorOnExecutionNode() *BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call { + return &BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call{Call: _e.mock.On("ScriptExecutionErrorOnExecutionNode")} +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call) Run(run func()) *BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call) Return() *BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call { + _c.Call.Return() + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call) RunAndReturn(run func()) *BackendScriptsMetrics_ScriptExecutionErrorOnExecutionNode_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionNotIndexed provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecutionNotIndexed() { + _mock.Called() + return +} + +// BackendScriptsMetrics_ScriptExecutionNotIndexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionNotIndexed' +type BackendScriptsMetrics_ScriptExecutionNotIndexed_Call struct { + *mock.Call +} + +// ScriptExecutionNotIndexed is a helper method to define mock.On call +func (_e *BackendScriptsMetrics_Expecter) ScriptExecutionNotIndexed() *BackendScriptsMetrics_ScriptExecutionNotIndexed_Call { + return &BackendScriptsMetrics_ScriptExecutionNotIndexed_Call{Call: _e.mock.On("ScriptExecutionNotIndexed")} +} + +func (_c *BackendScriptsMetrics_ScriptExecutionNotIndexed_Call) Run(run func()) *BackendScriptsMetrics_ScriptExecutionNotIndexed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionNotIndexed_Call) Return() *BackendScriptsMetrics_ScriptExecutionNotIndexed_Call { + _c.Call.Return() + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionNotIndexed_Call) RunAndReturn(run func()) *BackendScriptsMetrics_ScriptExecutionNotIndexed_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionResultMatch provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecutionResultMatch() { + _mock.Called() + return +} + +// BackendScriptsMetrics_ScriptExecutionResultMatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionResultMatch' +type BackendScriptsMetrics_ScriptExecutionResultMatch_Call struct { + *mock.Call +} + +// ScriptExecutionResultMatch is a helper method to define mock.On call +func (_e *BackendScriptsMetrics_Expecter) ScriptExecutionResultMatch() *BackendScriptsMetrics_ScriptExecutionResultMatch_Call { + return &BackendScriptsMetrics_ScriptExecutionResultMatch_Call{Call: _e.mock.On("ScriptExecutionResultMatch")} +} + +func (_c *BackendScriptsMetrics_ScriptExecutionResultMatch_Call) Run(run func()) *BackendScriptsMetrics_ScriptExecutionResultMatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionResultMatch_Call) Return() *BackendScriptsMetrics_ScriptExecutionResultMatch_Call { + _c.Call.Return() + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionResultMatch_Call) RunAndReturn(run func()) *BackendScriptsMetrics_ScriptExecutionResultMatch_Call { + _c.Run(run) + return _c +} + +// ScriptExecutionResultMismatch provides a mock function for the type BackendScriptsMetrics +func (_mock *BackendScriptsMetrics) ScriptExecutionResultMismatch() { + _mock.Called() + return +} + +// BackendScriptsMetrics_ScriptExecutionResultMismatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScriptExecutionResultMismatch' +type BackendScriptsMetrics_ScriptExecutionResultMismatch_Call struct { + *mock.Call +} + +// ScriptExecutionResultMismatch is a helper method to define mock.On call +func (_e *BackendScriptsMetrics_Expecter) ScriptExecutionResultMismatch() *BackendScriptsMetrics_ScriptExecutionResultMismatch_Call { + return &BackendScriptsMetrics_ScriptExecutionResultMismatch_Call{Call: _e.mock.On("ScriptExecutionResultMismatch")} +} + +func (_c *BackendScriptsMetrics_ScriptExecutionResultMismatch_Call) Run(run func()) *BackendScriptsMetrics_ScriptExecutionResultMismatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionResultMismatch_Call) Return() *BackendScriptsMetrics_ScriptExecutionResultMismatch_Call { + _c.Call.Return() + return _c +} + +func (_c *BackendScriptsMetrics_ScriptExecutionResultMismatch_Call) RunAndReturn(run func()) *BackendScriptsMetrics_ScriptExecutionResultMismatch_Call { + _c.Run(run) + return _c } diff --git a/module/mock/bitswap_metrics.go b/module/mock/bitswap_metrics.go index acaaefc1362..bfe704e6667 100644 --- a/module/mock/bitswap_metrics.go +++ b/module/mock/bitswap_metrics.go @@ -1,69 +1,450 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewBitswapMetrics creates a new instance of BitswapMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBitswapMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *BitswapMetrics { + mock := &BitswapMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // BitswapMetrics is an autogenerated mock type for the BitswapMetrics type type BitswapMetrics struct { mock.Mock } -// BlobsReceived provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) BlobsReceived(prefix string, n uint64) { - _m.Called(prefix, n) +type BitswapMetrics_Expecter struct { + mock *mock.Mock } -// BlobsSent provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) BlobsSent(prefix string, n uint64) { - _m.Called(prefix, n) +func (_m *BitswapMetrics) EXPECT() *BitswapMetrics_Expecter { + return &BitswapMetrics_Expecter{mock: &_m.Mock} } -// DataReceived provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) DataReceived(prefix string, n uint64) { - _m.Called(prefix, n) +// BlobsReceived provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) BlobsReceived(prefix string, n uint64) { + _mock.Called(prefix, n) + return } -// DataSent provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) DataSent(prefix string, n uint64) { - _m.Called(prefix, n) +// BitswapMetrics_BlobsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlobsReceived' +type BitswapMetrics_BlobsReceived_Call struct { + *mock.Call } -// DupBlobsReceived provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) DupBlobsReceived(prefix string, n uint64) { - _m.Called(prefix, n) +// BlobsReceived is a helper method to define mock.On call +// - prefix string +// - n uint64 +func (_e *BitswapMetrics_Expecter) BlobsReceived(prefix interface{}, n interface{}) *BitswapMetrics_BlobsReceived_Call { + return &BitswapMetrics_BlobsReceived_Call{Call: _e.mock.On("BlobsReceived", prefix, n)} } -// DupDataReceived provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) DupDataReceived(prefix string, n uint64) { - _m.Called(prefix, n) +func (_c *BitswapMetrics_BlobsReceived_Call) Run(run func(prefix string, n uint64)) *BitswapMetrics_BlobsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c } -// MessagesReceived provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) MessagesReceived(prefix string, n uint64) { - _m.Called(prefix, n) +func (_c *BitswapMetrics_BlobsReceived_Call) Return() *BitswapMetrics_BlobsReceived_Call { + _c.Call.Return() + return _c } -// Peers provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) Peers(prefix string, n int) { - _m.Called(prefix, n) +func (_c *BitswapMetrics_BlobsReceived_Call) RunAndReturn(run func(prefix string, n uint64)) *BitswapMetrics_BlobsReceived_Call { + _c.Run(run) + return _c } -// Wantlist provides a mock function with given fields: prefix, n -func (_m *BitswapMetrics) Wantlist(prefix string, n int) { - _m.Called(prefix, n) +// BlobsSent provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) BlobsSent(prefix string, n uint64) { + _mock.Called(prefix, n) + return } -// NewBitswapMetrics creates a new instance of BitswapMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBitswapMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *BitswapMetrics { - mock := &BitswapMetrics{} - mock.Mock.Test(t) +// BitswapMetrics_BlobsSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlobsSent' +type BitswapMetrics_BlobsSent_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// BlobsSent is a helper method to define mock.On call +// - prefix string +// - n uint64 +func (_e *BitswapMetrics_Expecter) BlobsSent(prefix interface{}, n interface{}) *BitswapMetrics_BlobsSent_Call { + return &BitswapMetrics_BlobsSent_Call{Call: _e.mock.On("BlobsSent", prefix, n)} +} - return mock +func (_c *BitswapMetrics_BlobsSent_Call) Run(run func(prefix string, n uint64)) *BitswapMetrics_BlobsSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_BlobsSent_Call) Return() *BitswapMetrics_BlobsSent_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_BlobsSent_Call) RunAndReturn(run func(prefix string, n uint64)) *BitswapMetrics_BlobsSent_Call { + _c.Run(run) + return _c +} + +// DataReceived provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) DataReceived(prefix string, n uint64) { + _mock.Called(prefix, n) + return +} + +// BitswapMetrics_DataReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DataReceived' +type BitswapMetrics_DataReceived_Call struct { + *mock.Call +} + +// DataReceived is a helper method to define mock.On call +// - prefix string +// - n uint64 +func (_e *BitswapMetrics_Expecter) DataReceived(prefix interface{}, n interface{}) *BitswapMetrics_DataReceived_Call { + return &BitswapMetrics_DataReceived_Call{Call: _e.mock.On("DataReceived", prefix, n)} +} + +func (_c *BitswapMetrics_DataReceived_Call) Run(run func(prefix string, n uint64)) *BitswapMetrics_DataReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_DataReceived_Call) Return() *BitswapMetrics_DataReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_DataReceived_Call) RunAndReturn(run func(prefix string, n uint64)) *BitswapMetrics_DataReceived_Call { + _c.Run(run) + return _c +} + +// DataSent provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) DataSent(prefix string, n uint64) { + _mock.Called(prefix, n) + return +} + +// BitswapMetrics_DataSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DataSent' +type BitswapMetrics_DataSent_Call struct { + *mock.Call +} + +// DataSent is a helper method to define mock.On call +// - prefix string +// - n uint64 +func (_e *BitswapMetrics_Expecter) DataSent(prefix interface{}, n interface{}) *BitswapMetrics_DataSent_Call { + return &BitswapMetrics_DataSent_Call{Call: _e.mock.On("DataSent", prefix, n)} +} + +func (_c *BitswapMetrics_DataSent_Call) Run(run func(prefix string, n uint64)) *BitswapMetrics_DataSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_DataSent_Call) Return() *BitswapMetrics_DataSent_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_DataSent_Call) RunAndReturn(run func(prefix string, n uint64)) *BitswapMetrics_DataSent_Call { + _c.Run(run) + return _c +} + +// DupBlobsReceived provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) DupBlobsReceived(prefix string, n uint64) { + _mock.Called(prefix, n) + return +} + +// BitswapMetrics_DupBlobsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DupBlobsReceived' +type BitswapMetrics_DupBlobsReceived_Call struct { + *mock.Call +} + +// DupBlobsReceived is a helper method to define mock.On call +// - prefix string +// - n uint64 +func (_e *BitswapMetrics_Expecter) DupBlobsReceived(prefix interface{}, n interface{}) *BitswapMetrics_DupBlobsReceived_Call { + return &BitswapMetrics_DupBlobsReceived_Call{Call: _e.mock.On("DupBlobsReceived", prefix, n)} +} + +func (_c *BitswapMetrics_DupBlobsReceived_Call) Run(run func(prefix string, n uint64)) *BitswapMetrics_DupBlobsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_DupBlobsReceived_Call) Return() *BitswapMetrics_DupBlobsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_DupBlobsReceived_Call) RunAndReturn(run func(prefix string, n uint64)) *BitswapMetrics_DupBlobsReceived_Call { + _c.Run(run) + return _c +} + +// DupDataReceived provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) DupDataReceived(prefix string, n uint64) { + _mock.Called(prefix, n) + return +} + +// BitswapMetrics_DupDataReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DupDataReceived' +type BitswapMetrics_DupDataReceived_Call struct { + *mock.Call +} + +// DupDataReceived is a helper method to define mock.On call +// - prefix string +// - n uint64 +func (_e *BitswapMetrics_Expecter) DupDataReceived(prefix interface{}, n interface{}) *BitswapMetrics_DupDataReceived_Call { + return &BitswapMetrics_DupDataReceived_Call{Call: _e.mock.On("DupDataReceived", prefix, n)} +} + +func (_c *BitswapMetrics_DupDataReceived_Call) Run(run func(prefix string, n uint64)) *BitswapMetrics_DupDataReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_DupDataReceived_Call) Return() *BitswapMetrics_DupDataReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_DupDataReceived_Call) RunAndReturn(run func(prefix string, n uint64)) *BitswapMetrics_DupDataReceived_Call { + _c.Run(run) + return _c +} + +// MessagesReceived provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) MessagesReceived(prefix string, n uint64) { + _mock.Called(prefix, n) + return +} + +// BitswapMetrics_MessagesReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessagesReceived' +type BitswapMetrics_MessagesReceived_Call struct { + *mock.Call +} + +// MessagesReceived is a helper method to define mock.On call +// - prefix string +// - n uint64 +func (_e *BitswapMetrics_Expecter) MessagesReceived(prefix interface{}, n interface{}) *BitswapMetrics_MessagesReceived_Call { + return &BitswapMetrics_MessagesReceived_Call{Call: _e.mock.On("MessagesReceived", prefix, n)} +} + +func (_c *BitswapMetrics_MessagesReceived_Call) Run(run func(prefix string, n uint64)) *BitswapMetrics_MessagesReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_MessagesReceived_Call) Return() *BitswapMetrics_MessagesReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_MessagesReceived_Call) RunAndReturn(run func(prefix string, n uint64)) *BitswapMetrics_MessagesReceived_Call { + _c.Run(run) + return _c +} + +// Peers provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) Peers(prefix string, n int) { + _mock.Called(prefix, n) + return +} + +// BitswapMetrics_Peers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Peers' +type BitswapMetrics_Peers_Call struct { + *mock.Call +} + +// Peers is a helper method to define mock.On call +// - prefix string +// - n int +func (_e *BitswapMetrics_Expecter) Peers(prefix interface{}, n interface{}) *BitswapMetrics_Peers_Call { + return &BitswapMetrics_Peers_Call{Call: _e.mock.On("Peers", prefix, n)} +} + +func (_c *BitswapMetrics_Peers_Call) Run(run func(prefix string, n int)) *BitswapMetrics_Peers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_Peers_Call) Return() *BitswapMetrics_Peers_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_Peers_Call) RunAndReturn(run func(prefix string, n int)) *BitswapMetrics_Peers_Call { + _c.Run(run) + return _c +} + +// Wantlist provides a mock function for the type BitswapMetrics +func (_mock *BitswapMetrics) Wantlist(prefix string, n int) { + _mock.Called(prefix, n) + return +} + +// BitswapMetrics_Wantlist_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Wantlist' +type BitswapMetrics_Wantlist_Call struct { + *mock.Call +} + +// Wantlist is a helper method to define mock.On call +// - prefix string +// - n int +func (_e *BitswapMetrics_Expecter) Wantlist(prefix interface{}, n interface{}) *BitswapMetrics_Wantlist_Call { + return &BitswapMetrics_Wantlist_Call{Call: _e.mock.On("Wantlist", prefix, n)} +} + +func (_c *BitswapMetrics_Wantlist_Call) Run(run func(prefix string, n int)) *BitswapMetrics_Wantlist_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BitswapMetrics_Wantlist_Call) Return() *BitswapMetrics_Wantlist_Call { + _c.Call.Return() + return _c +} + +func (_c *BitswapMetrics_Wantlist_Call) RunAndReturn(run func(prefix string, n int)) *BitswapMetrics_Wantlist_Call { + _c.Run(run) + return _c } diff --git a/module/mock/block_iterator.go b/module/mock/block_iterator.go index 1efa21af3c7..0244663c2f2 100644 --- a/module/mock/block_iterator.go +++ b/module/mock/block_iterator.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBlockIterator creates a new instance of BlockIterator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockIterator(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockIterator { + mock := &BlockIterator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BlockIterator is an autogenerated mock type for the BlockIterator type type BlockIterator struct { mock.Mock } -// Checkpoint provides a mock function with no fields -func (_m *BlockIterator) Checkpoint() (uint64, error) { - ret := _m.Called() +type BlockIterator_Expecter struct { + mock *mock.Mock +} + +func (_m *BlockIterator) EXPECT() *BlockIterator_Expecter { + return &BlockIterator_Expecter{mock: &_m.Mock} +} + +// Checkpoint provides a mock function for the type BlockIterator +func (_mock *BlockIterator) Checkpoint() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Checkpoint") @@ -22,27 +46,52 @@ func (_m *BlockIterator) Checkpoint() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Next provides a mock function with no fields -func (_m *BlockIterator) Next() (flow.Identifier, bool, error) { - ret := _m.Called() +// BlockIterator_Checkpoint_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Checkpoint' +type BlockIterator_Checkpoint_Call struct { + *mock.Call +} + +// Checkpoint is a helper method to define mock.On call +func (_e *BlockIterator_Expecter) Checkpoint() *BlockIterator_Checkpoint_Call { + return &BlockIterator_Checkpoint_Call{Call: _e.mock.On("Checkpoint")} +} + +func (_c *BlockIterator_Checkpoint_Call) Run(run func()) *BlockIterator_Checkpoint_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BlockIterator_Checkpoint_Call) Return(savedIndex uint64, exception error) *BlockIterator_Checkpoint_Call { + _c.Call.Return(savedIndex, exception) + return _c +} + +func (_c *BlockIterator_Checkpoint_Call) RunAndReturn(run func() (uint64, error)) *BlockIterator_Checkpoint_Call { + _c.Call.Return(run) + return _c +} + +// Next provides a mock function for the type BlockIterator +func (_mock *BlockIterator) Next() (flow.Identifier, bool, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Next") @@ -51,35 +100,59 @@ func (_m *BlockIterator) Next() (flow.Identifier, bool, error) { var r0 flow.Identifier var r1 bool var r2 error - if rf, ok := ret.Get(0).(func() (flow.Identifier, bool, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.Identifier, bool, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func() bool); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// Progress provides a mock function with no fields -func (_m *BlockIterator) Progress() (uint64, uint64, uint64) { - ret := _m.Called() +// BlockIterator_Next_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Next' +type BlockIterator_Next_Call struct { + *mock.Call +} + +// Next is a helper method to define mock.On call +func (_e *BlockIterator_Expecter) Next() *BlockIterator_Next_Call { + return &BlockIterator_Next_Call{Call: _e.mock.On("Next")} +} + +func (_c *BlockIterator_Next_Call) Run(run func()) *BlockIterator_Next_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BlockIterator_Next_Call) Return(blockID flow.Identifier, hasNext bool, exception error) *BlockIterator_Next_Call { + _c.Call.Return(blockID, hasNext, exception) + return _c +} + +func (_c *BlockIterator_Next_Call) RunAndReturn(run func() (flow.Identifier, bool, error)) *BlockIterator_Next_Call { + _c.Call.Return(run) + return _c +} + +// Progress provides a mock function for the type BlockIterator +func (_mock *BlockIterator) Progress() (uint64, uint64, uint64) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Progress") @@ -88,40 +161,50 @@ func (_m *BlockIterator) Progress() (uint64, uint64, uint64) { var r0 uint64 var r1 uint64 var r2 uint64 - if rf, ok := ret.Get(0).(func() (uint64, uint64, uint64)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, uint64, uint64)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() uint64); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() uint64); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(uint64) } - - if rf, ok := ret.Get(2).(func() uint64); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() uint64); ok { + r2 = returnFunc() } else { r2 = ret.Get(2).(uint64) } - return r0, r1, r2 } -// NewBlockIterator creates a new instance of BlockIterator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockIterator(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockIterator { - mock := &BlockIterator{} - mock.Mock.Test(t) +// BlockIterator_Progress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Progress' +type BlockIterator_Progress_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Progress is a helper method to define mock.On call +func (_e *BlockIterator_Expecter) Progress() *BlockIterator_Progress_Call { + return &BlockIterator_Progress_Call{Call: _e.mock.On("Progress")} +} - return mock +func (_c *BlockIterator_Progress_Call) Run(run func()) *BlockIterator_Progress_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BlockIterator_Progress_Call) Return(start uint64, end uint64, next uint64) *BlockIterator_Progress_Call { + _c.Call.Return(start, end, next) + return _c +} + +func (_c *BlockIterator_Progress_Call) RunAndReturn(run func() (uint64, uint64, uint64)) *BlockIterator_Progress_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/block_requester.go b/module/mock/block_requester.go index 32adf7b6093..bd29271306b 100644 --- a/module/mock/block_requester.go +++ b/module/mock/block_requester.go @@ -1,42 +1,163 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBlockRequester creates a new instance of BlockRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockRequester(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockRequester { + mock := &BlockRequester{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BlockRequester is an autogenerated mock type for the BlockRequester type type BlockRequester struct { mock.Mock } -// Prune provides a mock function with given fields: final -func (_m *BlockRequester) Prune(final *flow.Header) { - _m.Called(final) +type BlockRequester_Expecter struct { + mock *mock.Mock } -// RequestBlock provides a mock function with given fields: blockID, height -func (_m *BlockRequester) RequestBlock(blockID flow.Identifier, height uint64) { - _m.Called(blockID, height) +func (_m *BlockRequester) EXPECT() *BlockRequester_Expecter { + return &BlockRequester_Expecter{mock: &_m.Mock} } -// RequestHeight provides a mock function with given fields: height -func (_m *BlockRequester) RequestHeight(height uint64) { - _m.Called(height) +// Prune provides a mock function for the type BlockRequester +func (_mock *BlockRequester) Prune(final *flow.Header) { + _mock.Called(final) + return } -// NewBlockRequester creates a new instance of BlockRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockRequester(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockRequester { - mock := &BlockRequester{} - mock.Mock.Test(t) +// BlockRequester_Prune_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Prune' +type BlockRequester_Prune_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Prune is a helper method to define mock.On call +// - final *flow.Header +func (_e *BlockRequester_Expecter) Prune(final interface{}) *BlockRequester_Prune_Call { + return &BlockRequester_Prune_Call{Call: _e.mock.On("Prune", final)} +} - return mock +func (_c *BlockRequester_Prune_Call) Run(run func(final *flow.Header)) *BlockRequester_Prune_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockRequester_Prune_Call) Return() *BlockRequester_Prune_Call { + _c.Call.Return() + return _c +} + +func (_c *BlockRequester_Prune_Call) RunAndReturn(run func(final *flow.Header)) *BlockRequester_Prune_Call { + _c.Run(run) + return _c +} + +// RequestBlock provides a mock function for the type BlockRequester +func (_mock *BlockRequester) RequestBlock(blockID flow.Identifier, height uint64) { + _mock.Called(blockID, height) + return +} + +// BlockRequester_RequestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestBlock' +type BlockRequester_RequestBlock_Call struct { + *mock.Call +} + +// RequestBlock is a helper method to define mock.On call +// - blockID flow.Identifier +// - height uint64 +func (_e *BlockRequester_Expecter) RequestBlock(blockID interface{}, height interface{}) *BlockRequester_RequestBlock_Call { + return &BlockRequester_RequestBlock_Call{Call: _e.mock.On("RequestBlock", blockID, height)} +} + +func (_c *BlockRequester_RequestBlock_Call) Run(run func(blockID flow.Identifier, height uint64)) *BlockRequester_RequestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlockRequester_RequestBlock_Call) Return() *BlockRequester_RequestBlock_Call { + _c.Call.Return() + return _c +} + +func (_c *BlockRequester_RequestBlock_Call) RunAndReturn(run func(blockID flow.Identifier, height uint64)) *BlockRequester_RequestBlock_Call { + _c.Run(run) + return _c +} + +// RequestHeight provides a mock function for the type BlockRequester +func (_mock *BlockRequester) RequestHeight(height uint64) { + _mock.Called(height) + return +} + +// BlockRequester_RequestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestHeight' +type BlockRequester_RequestHeight_Call struct { + *mock.Call +} + +// RequestHeight is a helper method to define mock.On call +// - height uint64 +func (_e *BlockRequester_Expecter) RequestHeight(height interface{}) *BlockRequester_RequestHeight_Call { + return &BlockRequester_RequestHeight_Call{Call: _e.mock.On("RequestHeight", height)} +} + +func (_c *BlockRequester_RequestHeight_Call) Run(run func(height uint64)) *BlockRequester_RequestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockRequester_RequestHeight_Call) Return() *BlockRequester_RequestHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *BlockRequester_RequestHeight_Call) RunAndReturn(run func(height uint64)) *BlockRequester_RequestHeight_Call { + _c.Run(run) + return _c } diff --git a/module/mock/builder.go b/module/mock/builder.go index 3e79501103d..438b7b6724d 100644 --- a/module/mock/builder.go +++ b/module/mock/builder.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewBuilder creates a new instance of Builder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBuilder(t interface { + mock.TestingT + Cleanup(func()) +}) *Builder { + mock := &Builder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Builder is an autogenerated mock type for the Builder type type Builder struct { mock.Mock } -// BuildOn provides a mock function with given fields: parentID, setter, sign -func (_m *Builder) BuildOn(parentID flow.Identifier, setter func(*flow.HeaderBodyBuilder) error, sign func(*flow.Header) ([]byte, error)) (*flow.ProposalHeader, error) { - ret := _m.Called(parentID, setter, sign) +type Builder_Expecter struct { + mock *mock.Mock +} + +func (_m *Builder) EXPECT() *Builder_Expecter { + return &Builder_Expecter{mock: &_m.Mock} +} + +// BuildOn provides a mock function for the type Builder +func (_mock *Builder) BuildOn(parentID flow.Identifier, setter func(*flow.HeaderBodyBuilder) error, sign func(*flow.Header) ([]byte, error)) (*flow.ProposalHeader, error) { + ret := _mock.Called(parentID, setter, sign) if len(ret) == 0 { panic("no return value specified for BuildOn") @@ -22,36 +46,66 @@ func (_m *Builder) BuildOn(parentID flow.Identifier, setter func(*flow.HeaderBod var r0 *flow.ProposalHeader var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.HeaderBodyBuilder) error, func(*flow.Header) ([]byte, error)) (*flow.ProposalHeader, error)); ok { - return rf(parentID, setter, sign) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.HeaderBodyBuilder) error, func(*flow.Header) ([]byte, error)) (*flow.ProposalHeader, error)); ok { + return returnFunc(parentID, setter, sign) } - if rf, ok := ret.Get(0).(func(flow.Identifier, func(*flow.HeaderBodyBuilder) error, func(*flow.Header) ([]byte, error)) *flow.ProposalHeader); ok { - r0 = rf(parentID, setter, sign) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, func(*flow.HeaderBodyBuilder) error, func(*flow.Header) ([]byte, error)) *flow.ProposalHeader); ok { + r0 = returnFunc(parentID, setter, sign) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ProposalHeader) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, func(*flow.HeaderBodyBuilder) error, func(*flow.Header) ([]byte, error)) error); ok { - r1 = rf(parentID, setter, sign) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, func(*flow.HeaderBodyBuilder) error, func(*flow.Header) ([]byte, error)) error); ok { + r1 = returnFunc(parentID, setter, sign) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBuilder creates a new instance of Builder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBuilder(t interface { - mock.TestingT - Cleanup(func()) -}) *Builder { - mock := &Builder{} - mock.Mock.Test(t) +// Builder_BuildOn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BuildOn' +type Builder_BuildOn_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// BuildOn is a helper method to define mock.On call +// - parentID flow.Identifier +// - setter func(*flow.HeaderBodyBuilder) error +// - sign func(*flow.Header) ([]byte, error) +func (_e *Builder_Expecter) BuildOn(parentID interface{}, setter interface{}, sign interface{}) *Builder_BuildOn_Call { + return &Builder_BuildOn_Call{Call: _e.mock.On("BuildOn", parentID, setter, sign)} +} - return mock +func (_c *Builder_BuildOn_Call) Run(run func(parentID flow.Identifier, setter func(*flow.HeaderBodyBuilder) error, sign func(*flow.Header) ([]byte, error))) *Builder_BuildOn_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 func(*flow.HeaderBodyBuilder) error + if args[1] != nil { + arg1 = args[1].(func(*flow.HeaderBodyBuilder) error) + } + var arg2 func(*flow.Header) ([]byte, error) + if args[2] != nil { + arg2 = args[2].(func(*flow.Header) ([]byte, error)) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Builder_BuildOn_Call) Return(proposalHeader *flow.ProposalHeader, err error) *Builder_BuildOn_Call { + _c.Call.Return(proposalHeader, err) + return _c +} + +func (_c *Builder_BuildOn_Call) RunAndReturn(run func(parentID flow.Identifier, setter func(*flow.HeaderBodyBuilder) error, sign func(*flow.Header) ([]byte, error)) (*flow.ProposalHeader, error)) *Builder_BuildOn_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/cache_metrics.go b/module/mock/cache_metrics.go index 4c14a03f9f7..b0eb88e9cfc 100644 --- a/module/mock/cache_metrics.go +++ b/module/mock/cache_metrics.go @@ -1,44 +1,202 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewCacheMetrics creates a new instance of CacheMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCacheMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *CacheMetrics { + mock := &CacheMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // CacheMetrics is an autogenerated mock type for the CacheMetrics type type CacheMetrics struct { mock.Mock } -// CacheEntries provides a mock function with given fields: resource, entries -func (_m *CacheMetrics) CacheEntries(resource string, entries uint) { - _m.Called(resource, entries) +type CacheMetrics_Expecter struct { + mock *mock.Mock } -// CacheHit provides a mock function with given fields: resource -func (_m *CacheMetrics) CacheHit(resource string) { - _m.Called(resource) +func (_m *CacheMetrics) EXPECT() *CacheMetrics_Expecter { + return &CacheMetrics_Expecter{mock: &_m.Mock} } -// CacheMiss provides a mock function with given fields: resource -func (_m *CacheMetrics) CacheMiss(resource string) { - _m.Called(resource) +// CacheEntries provides a mock function for the type CacheMetrics +func (_mock *CacheMetrics) CacheEntries(resource string, entries uint) { + _mock.Called(resource, entries) + return } -// CacheNotFound provides a mock function with given fields: resource -func (_m *CacheMetrics) CacheNotFound(resource string) { - _m.Called(resource) +// CacheMetrics_CacheEntries_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CacheEntries' +type CacheMetrics_CacheEntries_Call struct { + *mock.Call } -// NewCacheMetrics creates a new instance of CacheMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCacheMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *CacheMetrics { - mock := &CacheMetrics{} - mock.Mock.Test(t) +// CacheEntries is a helper method to define mock.On call +// - resource string +// - entries uint +func (_e *CacheMetrics_Expecter) CacheEntries(resource interface{}, entries interface{}) *CacheMetrics_CacheEntries_Call { + return &CacheMetrics_CacheEntries_Call{Call: _e.mock.On("CacheEntries", resource, entries)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *CacheMetrics_CacheEntries_Call) Run(run func(resource string, entries uint)) *CacheMetrics_CacheEntries_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint + if args[1] != nil { + arg1 = args[1].(uint) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return mock +func (_c *CacheMetrics_CacheEntries_Call) Return() *CacheMetrics_CacheEntries_Call { + _c.Call.Return() + return _c +} + +func (_c *CacheMetrics_CacheEntries_Call) RunAndReturn(run func(resource string, entries uint)) *CacheMetrics_CacheEntries_Call { + _c.Run(run) + return _c +} + +// CacheHit provides a mock function for the type CacheMetrics +func (_mock *CacheMetrics) CacheHit(resource string) { + _mock.Called(resource) + return +} + +// CacheMetrics_CacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CacheHit' +type CacheMetrics_CacheHit_Call struct { + *mock.Call +} + +// CacheHit is a helper method to define mock.On call +// - resource string +func (_e *CacheMetrics_Expecter) CacheHit(resource interface{}) *CacheMetrics_CacheHit_Call { + return &CacheMetrics_CacheHit_Call{Call: _e.mock.On("CacheHit", resource)} +} + +func (_c *CacheMetrics_CacheHit_Call) Run(run func(resource string)) *CacheMetrics_CacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CacheMetrics_CacheHit_Call) Return() *CacheMetrics_CacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *CacheMetrics_CacheHit_Call) RunAndReturn(run func(resource string)) *CacheMetrics_CacheHit_Call { + _c.Run(run) + return _c +} + +// CacheMiss provides a mock function for the type CacheMetrics +func (_mock *CacheMetrics) CacheMiss(resource string) { + _mock.Called(resource) + return +} + +// CacheMetrics_CacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CacheMiss' +type CacheMetrics_CacheMiss_Call struct { + *mock.Call +} + +// CacheMiss is a helper method to define mock.On call +// - resource string +func (_e *CacheMetrics_Expecter) CacheMiss(resource interface{}) *CacheMetrics_CacheMiss_Call { + return &CacheMetrics_CacheMiss_Call{Call: _e.mock.On("CacheMiss", resource)} +} + +func (_c *CacheMetrics_CacheMiss_Call) Run(run func(resource string)) *CacheMetrics_CacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CacheMetrics_CacheMiss_Call) Return() *CacheMetrics_CacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *CacheMetrics_CacheMiss_Call) RunAndReturn(run func(resource string)) *CacheMetrics_CacheMiss_Call { + _c.Run(run) + return _c +} + +// CacheNotFound provides a mock function for the type CacheMetrics +func (_mock *CacheMetrics) CacheNotFound(resource string) { + _mock.Called(resource) + return +} + +// CacheMetrics_CacheNotFound_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CacheNotFound' +type CacheMetrics_CacheNotFound_Call struct { + *mock.Call +} + +// CacheNotFound is a helper method to define mock.On call +// - resource string +func (_e *CacheMetrics_Expecter) CacheNotFound(resource interface{}) *CacheMetrics_CacheNotFound_Call { + return &CacheMetrics_CacheNotFound_Call{Call: _e.mock.On("CacheNotFound", resource)} +} + +func (_c *CacheMetrics_CacheNotFound_Call) Run(run func(resource string)) *CacheMetrics_CacheNotFound_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CacheMetrics_CacheNotFound_Call) Return() *CacheMetrics_CacheNotFound_Call { + _c.Call.Return() + return _c +} + +func (_c *CacheMetrics_CacheNotFound_Call) RunAndReturn(run func(resource string)) *CacheMetrics_CacheNotFound_Call { + _c.Run(run) + return _c } diff --git a/module/mock/chain_sync_metrics.go b/module/mock/chain_sync_metrics.go index 8f57a1ffe71..f45508d5dc0 100644 --- a/module/mock/chain_sync_metrics.go +++ b/module/mock/chain_sync_metrics.go @@ -1,52 +1,255 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - chainsync "github.com/onflow/flow-go/model/chainsync" + "github.com/onflow/flow-go/model/chainsync" mock "github.com/stretchr/testify/mock" ) +// NewChainSyncMetrics creates a new instance of ChainSyncMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChainSyncMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ChainSyncMetrics { + mock := &ChainSyncMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ChainSyncMetrics is an autogenerated mock type for the ChainSyncMetrics type type ChainSyncMetrics struct { mock.Mock } -// BatchRequested provides a mock function with given fields: batch -func (_m *ChainSyncMetrics) BatchRequested(batch chainsync.Batch) { - _m.Called(batch) +type ChainSyncMetrics_Expecter struct { + mock *mock.Mock } -// PrunedBlockByHeight provides a mock function with given fields: status -func (_m *ChainSyncMetrics) PrunedBlockByHeight(status *chainsync.Status) { - _m.Called(status) +func (_m *ChainSyncMetrics) EXPECT() *ChainSyncMetrics_Expecter { + return &ChainSyncMetrics_Expecter{mock: &_m.Mock} } -// PrunedBlockById provides a mock function with given fields: status -func (_m *ChainSyncMetrics) PrunedBlockById(status *chainsync.Status) { - _m.Called(status) +// BatchRequested provides a mock function for the type ChainSyncMetrics +func (_mock *ChainSyncMetrics) BatchRequested(batch chainsync.Batch) { + _mock.Called(batch) + return } -// PrunedBlocks provides a mock function with given fields: totalByHeight, totalById, storedByHeight, storedById -func (_m *ChainSyncMetrics) PrunedBlocks(totalByHeight int, totalById int, storedByHeight int, storedById int) { - _m.Called(totalByHeight, totalById, storedByHeight, storedById) +// ChainSyncMetrics_BatchRequested_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRequested' +type ChainSyncMetrics_BatchRequested_Call struct { + *mock.Call } -// RangeRequested provides a mock function with given fields: ran -func (_m *ChainSyncMetrics) RangeRequested(ran chainsync.Range) { - _m.Called(ran) +// BatchRequested is a helper method to define mock.On call +// - batch chainsync.Batch +func (_e *ChainSyncMetrics_Expecter) BatchRequested(batch interface{}) *ChainSyncMetrics_BatchRequested_Call { + return &ChainSyncMetrics_BatchRequested_Call{Call: _e.mock.On("BatchRequested", batch)} } -// NewChainSyncMetrics creates a new instance of ChainSyncMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChainSyncMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ChainSyncMetrics { - mock := &ChainSyncMetrics{} - mock.Mock.Test(t) +func (_c *ChainSyncMetrics_BatchRequested_Call) Run(run func(batch chainsync.Batch)) *ChainSyncMetrics_BatchRequested_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 chainsync.Batch + if args[0] != nil { + arg0 = args[0].(chainsync.Batch) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ChainSyncMetrics_BatchRequested_Call) Return() *ChainSyncMetrics_BatchRequested_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *ChainSyncMetrics_BatchRequested_Call) RunAndReturn(run func(batch chainsync.Batch)) *ChainSyncMetrics_BatchRequested_Call { + _c.Run(run) + return _c +} + +// PrunedBlockByHeight provides a mock function for the type ChainSyncMetrics +func (_mock *ChainSyncMetrics) PrunedBlockByHeight(status *chainsync.Status) { + _mock.Called(status) + return +} + +// ChainSyncMetrics_PrunedBlockByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PrunedBlockByHeight' +type ChainSyncMetrics_PrunedBlockByHeight_Call struct { + *mock.Call +} + +// PrunedBlockByHeight is a helper method to define mock.On call +// - status *chainsync.Status +func (_e *ChainSyncMetrics_Expecter) PrunedBlockByHeight(status interface{}) *ChainSyncMetrics_PrunedBlockByHeight_Call { + return &ChainSyncMetrics_PrunedBlockByHeight_Call{Call: _e.mock.On("PrunedBlockByHeight", status)} +} + +func (_c *ChainSyncMetrics_PrunedBlockByHeight_Call) Run(run func(status *chainsync.Status)) *ChainSyncMetrics_PrunedBlockByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *chainsync.Status + if args[0] != nil { + arg0 = args[0].(*chainsync.Status) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChainSyncMetrics_PrunedBlockByHeight_Call) Return() *ChainSyncMetrics_PrunedBlockByHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ChainSyncMetrics_PrunedBlockByHeight_Call) RunAndReturn(run func(status *chainsync.Status)) *ChainSyncMetrics_PrunedBlockByHeight_Call { + _c.Run(run) + return _c +} + +// PrunedBlockById provides a mock function for the type ChainSyncMetrics +func (_mock *ChainSyncMetrics) PrunedBlockById(status *chainsync.Status) { + _mock.Called(status) + return +} + +// ChainSyncMetrics_PrunedBlockById_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PrunedBlockById' +type ChainSyncMetrics_PrunedBlockById_Call struct { + *mock.Call +} + +// PrunedBlockById is a helper method to define mock.On call +// - status *chainsync.Status +func (_e *ChainSyncMetrics_Expecter) PrunedBlockById(status interface{}) *ChainSyncMetrics_PrunedBlockById_Call { + return &ChainSyncMetrics_PrunedBlockById_Call{Call: _e.mock.On("PrunedBlockById", status)} +} + +func (_c *ChainSyncMetrics_PrunedBlockById_Call) Run(run func(status *chainsync.Status)) *ChainSyncMetrics_PrunedBlockById_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *chainsync.Status + if args[0] != nil { + arg0 = args[0].(*chainsync.Status) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChainSyncMetrics_PrunedBlockById_Call) Return() *ChainSyncMetrics_PrunedBlockById_Call { + _c.Call.Return() + return _c +} + +func (_c *ChainSyncMetrics_PrunedBlockById_Call) RunAndReturn(run func(status *chainsync.Status)) *ChainSyncMetrics_PrunedBlockById_Call { + _c.Run(run) + return _c +} + +// PrunedBlocks provides a mock function for the type ChainSyncMetrics +func (_mock *ChainSyncMetrics) PrunedBlocks(totalByHeight int, totalById int, storedByHeight int, storedById int) { + _mock.Called(totalByHeight, totalById, storedByHeight, storedById) + return +} + +// ChainSyncMetrics_PrunedBlocks_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PrunedBlocks' +type ChainSyncMetrics_PrunedBlocks_Call struct { + *mock.Call +} + +// PrunedBlocks is a helper method to define mock.On call +// - totalByHeight int +// - totalById int +// - storedByHeight int +// - storedById int +func (_e *ChainSyncMetrics_Expecter) PrunedBlocks(totalByHeight interface{}, totalById interface{}, storedByHeight interface{}, storedById interface{}) *ChainSyncMetrics_PrunedBlocks_Call { + return &ChainSyncMetrics_PrunedBlocks_Call{Call: _e.mock.On("PrunedBlocks", totalByHeight, totalById, storedByHeight, storedById)} +} + +func (_c *ChainSyncMetrics_PrunedBlocks_Call) Run(run func(totalByHeight int, totalById int, storedByHeight int, storedById int)) *ChainSyncMetrics_PrunedBlocks_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ChainSyncMetrics_PrunedBlocks_Call) Return() *ChainSyncMetrics_PrunedBlocks_Call { + _c.Call.Return() + return _c +} + +func (_c *ChainSyncMetrics_PrunedBlocks_Call) RunAndReturn(run func(totalByHeight int, totalById int, storedByHeight int, storedById int)) *ChainSyncMetrics_PrunedBlocks_Call { + _c.Run(run) + return _c +} + +// RangeRequested provides a mock function for the type ChainSyncMetrics +func (_mock *ChainSyncMetrics) RangeRequested(ran chainsync.Range) { + _mock.Called(ran) + return +} + +// ChainSyncMetrics_RangeRequested_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RangeRequested' +type ChainSyncMetrics_RangeRequested_Call struct { + *mock.Call +} + +// RangeRequested is a helper method to define mock.On call +// - ran chainsync.Range +func (_e *ChainSyncMetrics_Expecter) RangeRequested(ran interface{}) *ChainSyncMetrics_RangeRequested_Call { + return &ChainSyncMetrics_RangeRequested_Call{Call: _e.mock.On("RangeRequested", ran)} +} + +func (_c *ChainSyncMetrics_RangeRequested_Call) Run(run func(ran chainsync.Range)) *ChainSyncMetrics_RangeRequested_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 chainsync.Range + if args[0] != nil { + arg0 = args[0].(chainsync.Range) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChainSyncMetrics_RangeRequested_Call) Return() *ChainSyncMetrics_RangeRequested_Call { + _c.Call.Return() + return _c +} + +func (_c *ChainSyncMetrics_RangeRequested_Call) RunAndReturn(run func(ran chainsync.Range)) *ChainSyncMetrics_RangeRequested_Call { + _c.Run(run) + return _c } diff --git a/module/mock/chunk_assigner.go b/module/mock/chunk_assigner.go index 91fd50d04cd..180d1721004 100644 --- a/module/mock/chunk_assigner.go +++ b/module/mock/chunk_assigner.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - chunks "github.com/onflow/flow-go/model/chunks" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/chunks" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewChunkAssigner creates a new instance of ChunkAssigner. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChunkAssigner(t interface { + mock.TestingT + Cleanup(func()) +}) *ChunkAssigner { + mock := &ChunkAssigner{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ChunkAssigner is an autogenerated mock type for the ChunkAssigner type type ChunkAssigner struct { mock.Mock } -// Assign provides a mock function with given fields: result, blockID -func (_m *ChunkAssigner) Assign(result *flow.ExecutionResult, blockID flow.Identifier) (*chunks.Assignment, error) { - ret := _m.Called(result, blockID) +type ChunkAssigner_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunkAssigner) EXPECT() *ChunkAssigner_Expecter { + return &ChunkAssigner_Expecter{mock: &_m.Mock} +} + +// Assign provides a mock function for the type ChunkAssigner +func (_mock *ChunkAssigner) Assign(result *flow.ExecutionResult, blockID flow.Identifier) (*chunks.Assignment, error) { + ret := _mock.Called(result, blockID) if len(ret) == 0 { panic("no return value specified for Assign") @@ -24,36 +47,60 @@ func (_m *ChunkAssigner) Assign(result *flow.ExecutionResult, blockID flow.Ident var r0 *chunks.Assignment var r1 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionResult, flow.Identifier) (*chunks.Assignment, error)); ok { - return rf(result, blockID) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionResult, flow.Identifier) (*chunks.Assignment, error)); ok { + return returnFunc(result, blockID) } - if rf, ok := ret.Get(0).(func(*flow.ExecutionResult, flow.Identifier) *chunks.Assignment); ok { - r0 = rf(result, blockID) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionResult, flow.Identifier) *chunks.Assignment); ok { + r0 = returnFunc(result, blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*chunks.Assignment) } } - - if rf, ok := ret.Get(1).(func(*flow.ExecutionResult, flow.Identifier) error); ok { - r1 = rf(result, blockID) + if returnFunc, ok := ret.Get(1).(func(*flow.ExecutionResult, flow.Identifier) error); ok { + r1 = returnFunc(result, blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewChunkAssigner creates a new instance of ChunkAssigner. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChunkAssigner(t interface { - mock.TestingT - Cleanup(func()) -}) *ChunkAssigner { - mock := &ChunkAssigner{} - mock.Mock.Test(t) +// ChunkAssigner_Assign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Assign' +type ChunkAssigner_Assign_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Assign is a helper method to define mock.On call +// - result *flow.ExecutionResult +// - blockID flow.Identifier +func (_e *ChunkAssigner_Expecter) Assign(result interface{}, blockID interface{}) *ChunkAssigner_Assign_Call { + return &ChunkAssigner_Assign_Call{Call: _e.mock.On("Assign", result, blockID)} +} - return mock +func (_c *ChunkAssigner_Assign_Call) Run(run func(result *flow.ExecutionResult, blockID flow.Identifier)) *ChunkAssigner_Assign_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionResult + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionResult) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkAssigner_Assign_Call) Return(assignment *chunks.Assignment, err error) *ChunkAssigner_Assign_Call { + _c.Call.Return(assignment, err) + return _c +} + +func (_c *ChunkAssigner_Assign_Call) RunAndReturn(run func(result *flow.ExecutionResult, blockID flow.Identifier) (*chunks.Assignment, error)) *ChunkAssigner_Assign_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/chunk_verifier.go b/module/mock/chunk_verifier.go index 7eb3eef557d..c6c76939dea 100644 --- a/module/mock/chunk_verifier.go +++ b/module/mock/chunk_verifier.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/onflow/flow-go/model/verification" mock "github.com/stretchr/testify/mock" - - verification "github.com/onflow/flow-go/model/verification" ) +// NewChunkVerifier creates a new instance of ChunkVerifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChunkVerifier(t interface { + mock.TestingT + Cleanup(func()) +}) *ChunkVerifier { + mock := &ChunkVerifier{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ChunkVerifier is an autogenerated mock type for the ChunkVerifier type type ChunkVerifier struct { mock.Mock } -// Verify provides a mock function with given fields: ch -func (_m *ChunkVerifier) Verify(ch *verification.VerifiableChunkData) ([]byte, error) { - ret := _m.Called(ch) +type ChunkVerifier_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunkVerifier) EXPECT() *ChunkVerifier_Expecter { + return &ChunkVerifier_Expecter{mock: &_m.Mock} +} + +// Verify provides a mock function for the type ChunkVerifier +func (_mock *ChunkVerifier) Verify(ch *verification.VerifiableChunkData) ([]byte, error) { + ret := _mock.Called(ch) if len(ret) == 0 { panic("no return value specified for Verify") @@ -23,36 +46,54 @@ func (_m *ChunkVerifier) Verify(ch *verification.VerifiableChunkData) ([]byte, e var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(*verification.VerifiableChunkData) ([]byte, error)); ok { - return rf(ch) + if returnFunc, ok := ret.Get(0).(func(*verification.VerifiableChunkData) ([]byte, error)); ok { + return returnFunc(ch) } - if rf, ok := ret.Get(0).(func(*verification.VerifiableChunkData) []byte); ok { - r0 = rf(ch) + if returnFunc, ok := ret.Get(0).(func(*verification.VerifiableChunkData) []byte); ok { + r0 = returnFunc(ch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(*verification.VerifiableChunkData) error); ok { - r1 = rf(ch) + if returnFunc, ok := ret.Get(1).(func(*verification.VerifiableChunkData) error); ok { + r1 = returnFunc(ch) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewChunkVerifier creates a new instance of ChunkVerifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChunkVerifier(t interface { - mock.TestingT - Cleanup(func()) -}) *ChunkVerifier { - mock := &ChunkVerifier{} - mock.Mock.Test(t) +// ChunkVerifier_Verify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Verify' +type ChunkVerifier_Verify_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Verify is a helper method to define mock.On call +// - ch *verification.VerifiableChunkData +func (_e *ChunkVerifier_Expecter) Verify(ch interface{}) *ChunkVerifier_Verify_Call { + return &ChunkVerifier_Verify_Call{Call: _e.mock.On("Verify", ch)} +} - return mock +func (_c *ChunkVerifier_Verify_Call) Run(run func(ch *verification.VerifiableChunkData)) *ChunkVerifier_Verify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *verification.VerifiableChunkData + if args[0] != nil { + arg0 = args[0].(*verification.VerifiableChunkData) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkVerifier_Verify_Call) Return(bytes []byte, err error) *ChunkVerifier_Verify_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *ChunkVerifier_Verify_Call) RunAndReturn(run func(ch *verification.VerifiableChunkData) ([]byte, error)) *ChunkVerifier_Verify_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/cleaner_metrics.go b/module/mock/cleaner_metrics.go index ad8b75c392f..39b916bb7c5 100644 --- a/module/mock/cleaner_metrics.go +++ b/module/mock/cleaner_metrics.go @@ -1,23 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) -// CleanerMetrics is an autogenerated mock type for the CleanerMetrics type -type CleanerMetrics struct { - mock.Mock -} - -// RanGC provides a mock function with given fields: took -func (_m *CleanerMetrics) RanGC(took time.Duration) { - _m.Called(took) -} - // NewCleanerMetrics creates a new instance of CleanerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewCleanerMetrics(t interface { @@ -31,3 +23,56 @@ func NewCleanerMetrics(t interface { return mock } + +// CleanerMetrics is an autogenerated mock type for the CleanerMetrics type +type CleanerMetrics struct { + mock.Mock +} + +type CleanerMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *CleanerMetrics) EXPECT() *CleanerMetrics_Expecter { + return &CleanerMetrics_Expecter{mock: &_m.Mock} +} + +// RanGC provides a mock function for the type CleanerMetrics +func (_mock *CleanerMetrics) RanGC(took time.Duration) { + _mock.Called(took) + return +} + +// CleanerMetrics_RanGC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RanGC' +type CleanerMetrics_RanGC_Call struct { + *mock.Call +} + +// RanGC is a helper method to define mock.On call +// - took time.Duration +func (_e *CleanerMetrics_Expecter) RanGC(took interface{}) *CleanerMetrics_RanGC_Call { + return &CleanerMetrics_RanGC_Call{Call: _e.mock.On("RanGC", took)} +} + +func (_c *CleanerMetrics_RanGC_Call) Run(run func(took time.Duration)) *CleanerMetrics_RanGC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CleanerMetrics_RanGC_Call) Return() *CleanerMetrics_RanGC_Call { + _c.Call.Return() + return _c +} + +func (_c *CleanerMetrics_RanGC_Call) RunAndReturn(run func(took time.Duration)) *CleanerMetrics_RanGC_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/cluster_root_qc_voter.go b/module/mock/cluster_root_qc_voter.go index 6a4292094a9..63321c5347b 100644 --- a/module/mock/cluster_root_qc_voter.go +++ b/module/mock/cluster_root_qc_voter.go @@ -1,48 +1,96 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewClusterRootQCVoter creates a new instance of ClusterRootQCVoter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewClusterRootQCVoter(t interface { + mock.TestingT + Cleanup(func()) +}) *ClusterRootQCVoter { + mock := &ClusterRootQCVoter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ClusterRootQCVoter is an autogenerated mock type for the ClusterRootQCVoter type type ClusterRootQCVoter struct { mock.Mock } -// Vote provides a mock function with given fields: _a0, _a1 -func (_m *ClusterRootQCVoter) Vote(_a0 context.Context, _a1 protocol.TentativeEpoch) error { - ret := _m.Called(_a0, _a1) +type ClusterRootQCVoter_Expecter struct { + mock *mock.Mock +} + +func (_m *ClusterRootQCVoter) EXPECT() *ClusterRootQCVoter_Expecter { + return &ClusterRootQCVoter_Expecter{mock: &_m.Mock} +} + +// Vote provides a mock function for the type ClusterRootQCVoter +func (_mock *ClusterRootQCVoter) Vote(context1 context.Context, tentativeEpoch protocol.TentativeEpoch) error { + ret := _mock.Called(context1, tentativeEpoch) if len(ret) == 0 { panic("no return value specified for Vote") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, protocol.TentativeEpoch) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, protocol.TentativeEpoch) error); ok { + r0 = returnFunc(context1, tentativeEpoch) } else { r0 = ret.Error(0) } - return r0 } -// NewClusterRootQCVoter creates a new instance of ClusterRootQCVoter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClusterRootQCVoter(t interface { - mock.TestingT - Cleanup(func()) -}) *ClusterRootQCVoter { - mock := &ClusterRootQCVoter{} - mock.Mock.Test(t) +// ClusterRootQCVoter_Vote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Vote' +type ClusterRootQCVoter_Vote_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Vote is a helper method to define mock.On call +// - context1 context.Context +// - tentativeEpoch protocol.TentativeEpoch +func (_e *ClusterRootQCVoter_Expecter) Vote(context1 interface{}, tentativeEpoch interface{}) *ClusterRootQCVoter_Vote_Call { + return &ClusterRootQCVoter_Vote_Call{Call: _e.mock.On("Vote", context1, tentativeEpoch)} +} - return mock +func (_c *ClusterRootQCVoter_Vote_Call) Run(run func(context1 context.Context, tentativeEpoch protocol.TentativeEpoch)) *ClusterRootQCVoter_Vote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 protocol.TentativeEpoch + if args[1] != nil { + arg1 = args[1].(protocol.TentativeEpoch) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ClusterRootQCVoter_Vote_Call) Return(err error) *ClusterRootQCVoter_Vote_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ClusterRootQCVoter_Vote_Call) RunAndReturn(run func(context1 context.Context, tentativeEpoch protocol.TentativeEpoch) error) *ClusterRootQCVoter_Vote_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/collection_executed_metric.go b/module/mock/collection_executed_metric.go index aedfc4f4300..ca13d34b55d 100644 --- a/module/mock/collection_executed_metric.go +++ b/module/mock/collection_executed_metric.go @@ -1,52 +1,237 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewCollectionExecutedMetric creates a new instance of CollectionExecutedMetric. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCollectionExecutedMetric(t interface { + mock.TestingT + Cleanup(func()) +}) *CollectionExecutedMetric { + mock := &CollectionExecutedMetric{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CollectionExecutedMetric is an autogenerated mock type for the CollectionExecutedMetric type type CollectionExecutedMetric struct { mock.Mock } -// BlockFinalized provides a mock function with given fields: block -func (_m *CollectionExecutedMetric) BlockFinalized(block *flow.Block) { - _m.Called(block) +type CollectionExecutedMetric_Expecter struct { + mock *mock.Mock } -// CollectionExecuted provides a mock function with given fields: light -func (_m *CollectionExecutedMetric) CollectionExecuted(light *flow.LightCollection) { - _m.Called(light) +func (_m *CollectionExecutedMetric) EXPECT() *CollectionExecutedMetric_Expecter { + return &CollectionExecutedMetric_Expecter{mock: &_m.Mock} } -// CollectionFinalized provides a mock function with given fields: light -func (_m *CollectionExecutedMetric) CollectionFinalized(light *flow.LightCollection) { - _m.Called(light) +// BlockFinalized provides a mock function for the type CollectionExecutedMetric +func (_mock *CollectionExecutedMetric) BlockFinalized(block *flow.Block) { + _mock.Called(block) + return } -// ExecutionReceiptReceived provides a mock function with given fields: r -func (_m *CollectionExecutedMetric) ExecutionReceiptReceived(r *flow.ExecutionReceipt) { - _m.Called(r) +// CollectionExecutedMetric_BlockFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockFinalized' +type CollectionExecutedMetric_BlockFinalized_Call struct { + *mock.Call } -// UpdateLastFullBlockHeight provides a mock function with given fields: height -func (_m *CollectionExecutedMetric) UpdateLastFullBlockHeight(height uint64) { - _m.Called(height) +// BlockFinalized is a helper method to define mock.On call +// - block *flow.Block +func (_e *CollectionExecutedMetric_Expecter) BlockFinalized(block interface{}) *CollectionExecutedMetric_BlockFinalized_Call { + return &CollectionExecutedMetric_BlockFinalized_Call{Call: _e.mock.On("BlockFinalized", block)} } -// NewCollectionExecutedMetric creates a new instance of CollectionExecutedMetric. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCollectionExecutedMetric(t interface { - mock.TestingT - Cleanup(func()) -}) *CollectionExecutedMetric { - mock := &CollectionExecutedMetric{} - mock.Mock.Test(t) +func (_c *CollectionExecutedMetric_BlockFinalized_Call) Run(run func(block *flow.Block)) *CollectionExecutedMetric_BlockFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Block + if args[0] != nil { + arg0 = args[0].(*flow.Block) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *CollectionExecutedMetric_BlockFinalized_Call) Return() *CollectionExecutedMetric_BlockFinalized_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *CollectionExecutedMetric_BlockFinalized_Call) RunAndReturn(run func(block *flow.Block)) *CollectionExecutedMetric_BlockFinalized_Call { + _c.Run(run) + return _c +} + +// CollectionExecuted provides a mock function for the type CollectionExecutedMetric +func (_mock *CollectionExecutedMetric) CollectionExecuted(light *flow.LightCollection) { + _mock.Called(light) + return +} + +// CollectionExecutedMetric_CollectionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CollectionExecuted' +type CollectionExecutedMetric_CollectionExecuted_Call struct { + *mock.Call +} + +// CollectionExecuted is a helper method to define mock.On call +// - light *flow.LightCollection +func (_e *CollectionExecutedMetric_Expecter) CollectionExecuted(light interface{}) *CollectionExecutedMetric_CollectionExecuted_Call { + return &CollectionExecutedMetric_CollectionExecuted_Call{Call: _e.mock.On("CollectionExecuted", light)} +} + +func (_c *CollectionExecutedMetric_CollectionExecuted_Call) Run(run func(light *flow.LightCollection)) *CollectionExecutedMetric_CollectionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.LightCollection + if args[0] != nil { + arg0 = args[0].(*flow.LightCollection) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionExecutedMetric_CollectionExecuted_Call) Return() *CollectionExecutedMetric_CollectionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionExecutedMetric_CollectionExecuted_Call) RunAndReturn(run func(light *flow.LightCollection)) *CollectionExecutedMetric_CollectionExecuted_Call { + _c.Run(run) + return _c +} + +// CollectionFinalized provides a mock function for the type CollectionExecutedMetric +func (_mock *CollectionExecutedMetric) CollectionFinalized(light *flow.LightCollection) { + _mock.Called(light) + return +} + +// CollectionExecutedMetric_CollectionFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CollectionFinalized' +type CollectionExecutedMetric_CollectionFinalized_Call struct { + *mock.Call +} + +// CollectionFinalized is a helper method to define mock.On call +// - light *flow.LightCollection +func (_e *CollectionExecutedMetric_Expecter) CollectionFinalized(light interface{}) *CollectionExecutedMetric_CollectionFinalized_Call { + return &CollectionExecutedMetric_CollectionFinalized_Call{Call: _e.mock.On("CollectionFinalized", light)} +} + +func (_c *CollectionExecutedMetric_CollectionFinalized_Call) Run(run func(light *flow.LightCollection)) *CollectionExecutedMetric_CollectionFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.LightCollection + if args[0] != nil { + arg0 = args[0].(*flow.LightCollection) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionExecutedMetric_CollectionFinalized_Call) Return() *CollectionExecutedMetric_CollectionFinalized_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionExecutedMetric_CollectionFinalized_Call) RunAndReturn(run func(light *flow.LightCollection)) *CollectionExecutedMetric_CollectionFinalized_Call { + _c.Run(run) + return _c +} + +// ExecutionReceiptReceived provides a mock function for the type CollectionExecutedMetric +func (_mock *CollectionExecutedMetric) ExecutionReceiptReceived(r *flow.ExecutionReceipt) { + _mock.Called(r) + return +} + +// CollectionExecutedMetric_ExecutionReceiptReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionReceiptReceived' +type CollectionExecutedMetric_ExecutionReceiptReceived_Call struct { + *mock.Call +} + +// ExecutionReceiptReceived is a helper method to define mock.On call +// - r *flow.ExecutionReceipt +func (_e *CollectionExecutedMetric_Expecter) ExecutionReceiptReceived(r interface{}) *CollectionExecutedMetric_ExecutionReceiptReceived_Call { + return &CollectionExecutedMetric_ExecutionReceiptReceived_Call{Call: _e.mock.On("ExecutionReceiptReceived", r)} +} + +func (_c *CollectionExecutedMetric_ExecutionReceiptReceived_Call) Run(run func(r *flow.ExecutionReceipt)) *CollectionExecutedMetric_ExecutionReceiptReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionExecutedMetric_ExecutionReceiptReceived_Call) Return() *CollectionExecutedMetric_ExecutionReceiptReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionExecutedMetric_ExecutionReceiptReceived_Call) RunAndReturn(run func(r *flow.ExecutionReceipt)) *CollectionExecutedMetric_ExecutionReceiptReceived_Call { + _c.Run(run) + return _c +} + +// UpdateLastFullBlockHeight provides a mock function for the type CollectionExecutedMetric +func (_mock *CollectionExecutedMetric) UpdateLastFullBlockHeight(height uint64) { + _mock.Called(height) + return +} + +// CollectionExecutedMetric_UpdateLastFullBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateLastFullBlockHeight' +type CollectionExecutedMetric_UpdateLastFullBlockHeight_Call struct { + *mock.Call +} + +// UpdateLastFullBlockHeight is a helper method to define mock.On call +// - height uint64 +func (_e *CollectionExecutedMetric_Expecter) UpdateLastFullBlockHeight(height interface{}) *CollectionExecutedMetric_UpdateLastFullBlockHeight_Call { + return &CollectionExecutedMetric_UpdateLastFullBlockHeight_Call{Call: _e.mock.On("UpdateLastFullBlockHeight", height)} +} + +func (_c *CollectionExecutedMetric_UpdateLastFullBlockHeight_Call) Run(run func(height uint64)) *CollectionExecutedMetric_UpdateLastFullBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionExecutedMetric_UpdateLastFullBlockHeight_Call) Return() *CollectionExecutedMetric_UpdateLastFullBlockHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionExecutedMetric_UpdateLastFullBlockHeight_Call) RunAndReturn(run func(height uint64)) *CollectionExecutedMetric_UpdateLastFullBlockHeight_Call { + _c.Run(run) + return _c } diff --git a/module/mock/collection_metrics.go b/module/mock/collection_metrics.go index 78fc2c5908e..56b280b95da 100644 --- a/module/mock/collection_metrics.go +++ b/module/mock/collection_metrics.go @@ -1,64 +1,310 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cluster "github.com/onflow/flow-go/model/cluster" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewCollectionMetrics creates a new instance of CollectionMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCollectionMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *CollectionMetrics { + mock := &CollectionMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CollectionMetrics is an autogenerated mock type for the CollectionMetrics type type CollectionMetrics struct { mock.Mock } -// ClusterBlockCreated provides a mock function with given fields: block, priorityTxnsCount -func (_m *CollectionMetrics) ClusterBlockCreated(block *cluster.Block, priorityTxnsCount uint) { - _m.Called(block, priorityTxnsCount) +type CollectionMetrics_Expecter struct { + mock *mock.Mock } -// ClusterBlockFinalized provides a mock function with given fields: block -func (_m *CollectionMetrics) ClusterBlockFinalized(block *cluster.Block) { - _m.Called(block) +func (_m *CollectionMetrics) EXPECT() *CollectionMetrics_Expecter { + return &CollectionMetrics_Expecter{mock: &_m.Mock} } -// CollectionMaxSize provides a mock function with given fields: size -func (_m *CollectionMetrics) CollectionMaxSize(size uint) { - _m.Called(size) +// ClusterBlockCreated provides a mock function for the type CollectionMetrics +func (_mock *CollectionMetrics) ClusterBlockCreated(block *cluster.Block, priorityTxnsCount uint) { + _mock.Called(block, priorityTxnsCount) + return } -// TransactionIngested provides a mock function with given fields: txID -func (_m *CollectionMetrics) TransactionIngested(txID flow.Identifier) { - _m.Called(txID) +// CollectionMetrics_ClusterBlockCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClusterBlockCreated' +type CollectionMetrics_ClusterBlockCreated_Call struct { + *mock.Call } -// TransactionValidated provides a mock function with no fields -func (_m *CollectionMetrics) TransactionValidated() { - _m.Called() +// ClusterBlockCreated is a helper method to define mock.On call +// - block *cluster.Block +// - priorityTxnsCount uint +func (_e *CollectionMetrics_Expecter) ClusterBlockCreated(block interface{}, priorityTxnsCount interface{}) *CollectionMetrics_ClusterBlockCreated_Call { + return &CollectionMetrics_ClusterBlockCreated_Call{Call: _e.mock.On("ClusterBlockCreated", block, priorityTxnsCount)} } -// TransactionValidationFailed provides a mock function with given fields: reason -func (_m *CollectionMetrics) TransactionValidationFailed(reason string) { - _m.Called(reason) +func (_c *CollectionMetrics_ClusterBlockCreated_Call) Run(run func(block *cluster.Block, priorityTxnsCount uint)) *CollectionMetrics_ClusterBlockCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *cluster.Block + if args[0] != nil { + arg0 = args[0].(*cluster.Block) + } + var arg1 uint + if args[1] != nil { + arg1 = args[1].(uint) + } + run( + arg0, + arg1, + ) + }) + return _c } -// TransactionValidationSkipped provides a mock function with no fields -func (_m *CollectionMetrics) TransactionValidationSkipped() { - _m.Called() +func (_c *CollectionMetrics_ClusterBlockCreated_Call) Return() *CollectionMetrics_ClusterBlockCreated_Call { + _c.Call.Return() + return _c } -// NewCollectionMetrics creates a new instance of CollectionMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCollectionMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *CollectionMetrics { - mock := &CollectionMetrics{} - mock.Mock.Test(t) +func (_c *CollectionMetrics_ClusterBlockCreated_Call) RunAndReturn(run func(block *cluster.Block, priorityTxnsCount uint)) *CollectionMetrics_ClusterBlockCreated_Call { + _c.Run(run) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ClusterBlockFinalized provides a mock function for the type CollectionMetrics +func (_mock *CollectionMetrics) ClusterBlockFinalized(block *cluster.Block) { + _mock.Called(block) + return +} - return mock +// CollectionMetrics_ClusterBlockFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClusterBlockFinalized' +type CollectionMetrics_ClusterBlockFinalized_Call struct { + *mock.Call +} + +// ClusterBlockFinalized is a helper method to define mock.On call +// - block *cluster.Block +func (_e *CollectionMetrics_Expecter) ClusterBlockFinalized(block interface{}) *CollectionMetrics_ClusterBlockFinalized_Call { + return &CollectionMetrics_ClusterBlockFinalized_Call{Call: _e.mock.On("ClusterBlockFinalized", block)} +} + +func (_c *CollectionMetrics_ClusterBlockFinalized_Call) Run(run func(block *cluster.Block)) *CollectionMetrics_ClusterBlockFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *cluster.Block + if args[0] != nil { + arg0 = args[0].(*cluster.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionMetrics_ClusterBlockFinalized_Call) Return() *CollectionMetrics_ClusterBlockFinalized_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionMetrics_ClusterBlockFinalized_Call) RunAndReturn(run func(block *cluster.Block)) *CollectionMetrics_ClusterBlockFinalized_Call { + _c.Run(run) + return _c +} + +// CollectionMaxSize provides a mock function for the type CollectionMetrics +func (_mock *CollectionMetrics) CollectionMaxSize(size uint) { + _mock.Called(size) + return +} + +// CollectionMetrics_CollectionMaxSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CollectionMaxSize' +type CollectionMetrics_CollectionMaxSize_Call struct { + *mock.Call +} + +// CollectionMaxSize is a helper method to define mock.On call +// - size uint +func (_e *CollectionMetrics_Expecter) CollectionMaxSize(size interface{}) *CollectionMetrics_CollectionMaxSize_Call { + return &CollectionMetrics_CollectionMaxSize_Call{Call: _e.mock.On("CollectionMaxSize", size)} +} + +func (_c *CollectionMetrics_CollectionMaxSize_Call) Run(run func(size uint)) *CollectionMetrics_CollectionMaxSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionMetrics_CollectionMaxSize_Call) Return() *CollectionMetrics_CollectionMaxSize_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionMetrics_CollectionMaxSize_Call) RunAndReturn(run func(size uint)) *CollectionMetrics_CollectionMaxSize_Call { + _c.Run(run) + return _c +} + +// TransactionIngested provides a mock function for the type CollectionMetrics +func (_mock *CollectionMetrics) TransactionIngested(txID flow.Identifier) { + _mock.Called(txID) + return +} + +// CollectionMetrics_TransactionIngested_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionIngested' +type CollectionMetrics_TransactionIngested_Call struct { + *mock.Call +} + +// TransactionIngested is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *CollectionMetrics_Expecter) TransactionIngested(txID interface{}) *CollectionMetrics_TransactionIngested_Call { + return &CollectionMetrics_TransactionIngested_Call{Call: _e.mock.On("TransactionIngested", txID)} +} + +func (_c *CollectionMetrics_TransactionIngested_Call) Run(run func(txID flow.Identifier)) *CollectionMetrics_TransactionIngested_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionMetrics_TransactionIngested_Call) Return() *CollectionMetrics_TransactionIngested_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionMetrics_TransactionIngested_Call) RunAndReturn(run func(txID flow.Identifier)) *CollectionMetrics_TransactionIngested_Call { + _c.Run(run) + return _c +} + +// TransactionValidated provides a mock function for the type CollectionMetrics +func (_mock *CollectionMetrics) TransactionValidated() { + _mock.Called() + return +} + +// CollectionMetrics_TransactionValidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidated' +type CollectionMetrics_TransactionValidated_Call struct { + *mock.Call +} + +// TransactionValidated is a helper method to define mock.On call +func (_e *CollectionMetrics_Expecter) TransactionValidated() *CollectionMetrics_TransactionValidated_Call { + return &CollectionMetrics_TransactionValidated_Call{Call: _e.mock.On("TransactionValidated")} +} + +func (_c *CollectionMetrics_TransactionValidated_Call) Run(run func()) *CollectionMetrics_TransactionValidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CollectionMetrics_TransactionValidated_Call) Return() *CollectionMetrics_TransactionValidated_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionMetrics_TransactionValidated_Call) RunAndReturn(run func()) *CollectionMetrics_TransactionValidated_Call { + _c.Run(run) + return _c +} + +// TransactionValidationFailed provides a mock function for the type CollectionMetrics +func (_mock *CollectionMetrics) TransactionValidationFailed(reason string) { + _mock.Called(reason) + return +} + +// CollectionMetrics_TransactionValidationFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidationFailed' +type CollectionMetrics_TransactionValidationFailed_Call struct { + *mock.Call +} + +// TransactionValidationFailed is a helper method to define mock.On call +// - reason string +func (_e *CollectionMetrics_Expecter) TransactionValidationFailed(reason interface{}) *CollectionMetrics_TransactionValidationFailed_Call { + return &CollectionMetrics_TransactionValidationFailed_Call{Call: _e.mock.On("TransactionValidationFailed", reason)} +} + +func (_c *CollectionMetrics_TransactionValidationFailed_Call) Run(run func(reason string)) *CollectionMetrics_TransactionValidationFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionMetrics_TransactionValidationFailed_Call) Return() *CollectionMetrics_TransactionValidationFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionMetrics_TransactionValidationFailed_Call) RunAndReturn(run func(reason string)) *CollectionMetrics_TransactionValidationFailed_Call { + _c.Run(run) + return _c +} + +// TransactionValidationSkipped provides a mock function for the type CollectionMetrics +func (_mock *CollectionMetrics) TransactionValidationSkipped() { + _mock.Called() + return +} + +// CollectionMetrics_TransactionValidationSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidationSkipped' +type CollectionMetrics_TransactionValidationSkipped_Call struct { + *mock.Call +} + +// TransactionValidationSkipped is a helper method to define mock.On call +func (_e *CollectionMetrics_Expecter) TransactionValidationSkipped() *CollectionMetrics_TransactionValidationSkipped_Call { + return &CollectionMetrics_TransactionValidationSkipped_Call{Call: _e.mock.On("TransactionValidationSkipped")} +} + +func (_c *CollectionMetrics_TransactionValidationSkipped_Call) Run(run func()) *CollectionMetrics_TransactionValidationSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CollectionMetrics_TransactionValidationSkipped_Call) Return() *CollectionMetrics_TransactionValidationSkipped_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionMetrics_TransactionValidationSkipped_Call) RunAndReturn(run func()) *CollectionMetrics_TransactionValidationSkipped_Call { + _c.Run(run) + return _c } diff --git a/module/mock/compliance_metrics.go b/module/mock/compliance_metrics.go index 86bcf0a0676..1372007ef28 100644 --- a/module/mock/compliance_metrics.go +++ b/module/mock/compliance_metrics.go @@ -1,87 +1,515 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewComplianceMetrics creates a new instance of ComplianceMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewComplianceMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ComplianceMetrics { + mock := &ComplianceMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ComplianceMetrics is an autogenerated mock type for the ComplianceMetrics type type ComplianceMetrics struct { mock.Mock } -// BlockFinalized provides a mock function with given fields: _a0 -func (_m *ComplianceMetrics) BlockFinalized(_a0 *flow.Block) { - _m.Called(_a0) +type ComplianceMetrics_Expecter struct { + mock *mock.Mock } -// BlockSealed provides a mock function with given fields: _a0 -func (_m *ComplianceMetrics) BlockSealed(_a0 *flow.Block) { - _m.Called(_a0) +func (_m *ComplianceMetrics) EXPECT() *ComplianceMetrics_Expecter { + return &ComplianceMetrics_Expecter{mock: &_m.Mock} } -// CurrentDKGPhaseViews provides a mock function with given fields: phase1FinalView, phase2FinalView, phase3FinalView -func (_m *ComplianceMetrics) CurrentDKGPhaseViews(phase1FinalView uint64, phase2FinalView uint64, phase3FinalView uint64) { - _m.Called(phase1FinalView, phase2FinalView, phase3FinalView) +// BlockFinalized provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) BlockFinalized(v *flow.Block) { + _mock.Called(v) + return } -// CurrentEpochCounter provides a mock function with given fields: counter -func (_m *ComplianceMetrics) CurrentEpochCounter(counter uint64) { - _m.Called(counter) +// ComplianceMetrics_BlockFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockFinalized' +type ComplianceMetrics_BlockFinalized_Call struct { + *mock.Call } -// CurrentEpochFinalView provides a mock function with given fields: view -func (_m *ComplianceMetrics) CurrentEpochFinalView(view uint64) { - _m.Called(view) +// BlockFinalized is a helper method to define mock.On call +// - v *flow.Block +func (_e *ComplianceMetrics_Expecter) BlockFinalized(v interface{}) *ComplianceMetrics_BlockFinalized_Call { + return &ComplianceMetrics_BlockFinalized_Call{Call: _e.mock.On("BlockFinalized", v)} } -// CurrentEpochPhase provides a mock function with given fields: phase -func (_m *ComplianceMetrics) CurrentEpochPhase(phase flow.EpochPhase) { - _m.Called(phase) +func (_c *ComplianceMetrics_BlockFinalized_Call) Run(run func(v *flow.Block)) *ComplianceMetrics_BlockFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Block + if args[0] != nil { + arg0 = args[0].(*flow.Block) + } + run( + arg0, + ) + }) + return _c } -// EpochFallbackModeExited provides a mock function with no fields -func (_m *ComplianceMetrics) EpochFallbackModeExited() { - _m.Called() +func (_c *ComplianceMetrics_BlockFinalized_Call) Return() *ComplianceMetrics_BlockFinalized_Call { + _c.Call.Return() + return _c } -// EpochFallbackModeTriggered provides a mock function with no fields -func (_m *ComplianceMetrics) EpochFallbackModeTriggered() { - _m.Called() +func (_c *ComplianceMetrics_BlockFinalized_Call) RunAndReturn(run func(v *flow.Block)) *ComplianceMetrics_BlockFinalized_Call { + _c.Run(run) + return _c } -// EpochTransitionHeight provides a mock function with given fields: height -func (_m *ComplianceMetrics) EpochTransitionHeight(height uint64) { - _m.Called(height) +// BlockSealed provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) BlockSealed(v *flow.Block) { + _mock.Called(v) + return } -// FinalizedHeight provides a mock function with given fields: height -func (_m *ComplianceMetrics) FinalizedHeight(height uint64) { - _m.Called(height) +// ComplianceMetrics_BlockSealed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockSealed' +type ComplianceMetrics_BlockSealed_Call struct { + *mock.Call } -// ProtocolStateVersion provides a mock function with given fields: version -func (_m *ComplianceMetrics) ProtocolStateVersion(version uint64) { - _m.Called(version) +// BlockSealed is a helper method to define mock.On call +// - v *flow.Block +func (_e *ComplianceMetrics_Expecter) BlockSealed(v interface{}) *ComplianceMetrics_BlockSealed_Call { + return &ComplianceMetrics_BlockSealed_Call{Call: _e.mock.On("BlockSealed", v)} } -// SealedHeight provides a mock function with given fields: height -func (_m *ComplianceMetrics) SealedHeight(height uint64) { - _m.Called(height) +func (_c *ComplianceMetrics_BlockSealed_Call) Run(run func(v *flow.Block)) *ComplianceMetrics_BlockSealed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Block + if args[0] != nil { + arg0 = args[0].(*flow.Block) + } + run( + arg0, + ) + }) + return _c } -// NewComplianceMetrics creates a new instance of ComplianceMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewComplianceMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ComplianceMetrics { - mock := &ComplianceMetrics{} - mock.Mock.Test(t) +func (_c *ComplianceMetrics_BlockSealed_Call) Return() *ComplianceMetrics_BlockSealed_Call { + _c.Call.Return() + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ComplianceMetrics_BlockSealed_Call) RunAndReturn(run func(v *flow.Block)) *ComplianceMetrics_BlockSealed_Call { + _c.Run(run) + return _c +} - return mock +// CurrentDKGPhaseViews provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) CurrentDKGPhaseViews(phase1FinalView uint64, phase2FinalView uint64, phase3FinalView uint64) { + _mock.Called(phase1FinalView, phase2FinalView, phase3FinalView) + return +} + +// ComplianceMetrics_CurrentDKGPhaseViews_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CurrentDKGPhaseViews' +type ComplianceMetrics_CurrentDKGPhaseViews_Call struct { + *mock.Call +} + +// CurrentDKGPhaseViews is a helper method to define mock.On call +// - phase1FinalView uint64 +// - phase2FinalView uint64 +// - phase3FinalView uint64 +func (_e *ComplianceMetrics_Expecter) CurrentDKGPhaseViews(phase1FinalView interface{}, phase2FinalView interface{}, phase3FinalView interface{}) *ComplianceMetrics_CurrentDKGPhaseViews_Call { + return &ComplianceMetrics_CurrentDKGPhaseViews_Call{Call: _e.mock.On("CurrentDKGPhaseViews", phase1FinalView, phase2FinalView, phase3FinalView)} +} + +func (_c *ComplianceMetrics_CurrentDKGPhaseViews_Call) Run(run func(phase1FinalView uint64, phase2FinalView uint64, phase3FinalView uint64)) *ComplianceMetrics_CurrentDKGPhaseViews_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_CurrentDKGPhaseViews_Call) Return() *ComplianceMetrics_CurrentDKGPhaseViews_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_CurrentDKGPhaseViews_Call) RunAndReturn(run func(phase1FinalView uint64, phase2FinalView uint64, phase3FinalView uint64)) *ComplianceMetrics_CurrentDKGPhaseViews_Call { + _c.Run(run) + return _c +} + +// CurrentEpochCounter provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) CurrentEpochCounter(counter uint64) { + _mock.Called(counter) + return +} + +// ComplianceMetrics_CurrentEpochCounter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CurrentEpochCounter' +type ComplianceMetrics_CurrentEpochCounter_Call struct { + *mock.Call +} + +// CurrentEpochCounter is a helper method to define mock.On call +// - counter uint64 +func (_e *ComplianceMetrics_Expecter) CurrentEpochCounter(counter interface{}) *ComplianceMetrics_CurrentEpochCounter_Call { + return &ComplianceMetrics_CurrentEpochCounter_Call{Call: _e.mock.On("CurrentEpochCounter", counter)} +} + +func (_c *ComplianceMetrics_CurrentEpochCounter_Call) Run(run func(counter uint64)) *ComplianceMetrics_CurrentEpochCounter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_CurrentEpochCounter_Call) Return() *ComplianceMetrics_CurrentEpochCounter_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_CurrentEpochCounter_Call) RunAndReturn(run func(counter uint64)) *ComplianceMetrics_CurrentEpochCounter_Call { + _c.Run(run) + return _c +} + +// CurrentEpochFinalView provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) CurrentEpochFinalView(view uint64) { + _mock.Called(view) + return +} + +// ComplianceMetrics_CurrentEpochFinalView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CurrentEpochFinalView' +type ComplianceMetrics_CurrentEpochFinalView_Call struct { + *mock.Call +} + +// CurrentEpochFinalView is a helper method to define mock.On call +// - view uint64 +func (_e *ComplianceMetrics_Expecter) CurrentEpochFinalView(view interface{}) *ComplianceMetrics_CurrentEpochFinalView_Call { + return &ComplianceMetrics_CurrentEpochFinalView_Call{Call: _e.mock.On("CurrentEpochFinalView", view)} +} + +func (_c *ComplianceMetrics_CurrentEpochFinalView_Call) Run(run func(view uint64)) *ComplianceMetrics_CurrentEpochFinalView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_CurrentEpochFinalView_Call) Return() *ComplianceMetrics_CurrentEpochFinalView_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_CurrentEpochFinalView_Call) RunAndReturn(run func(view uint64)) *ComplianceMetrics_CurrentEpochFinalView_Call { + _c.Run(run) + return _c +} + +// CurrentEpochPhase provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) CurrentEpochPhase(phase flow.EpochPhase) { + _mock.Called(phase) + return +} + +// ComplianceMetrics_CurrentEpochPhase_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CurrentEpochPhase' +type ComplianceMetrics_CurrentEpochPhase_Call struct { + *mock.Call +} + +// CurrentEpochPhase is a helper method to define mock.On call +// - phase flow.EpochPhase +func (_e *ComplianceMetrics_Expecter) CurrentEpochPhase(phase interface{}) *ComplianceMetrics_CurrentEpochPhase_Call { + return &ComplianceMetrics_CurrentEpochPhase_Call{Call: _e.mock.On("CurrentEpochPhase", phase)} +} + +func (_c *ComplianceMetrics_CurrentEpochPhase_Call) Run(run func(phase flow.EpochPhase)) *ComplianceMetrics_CurrentEpochPhase_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.EpochPhase + if args[0] != nil { + arg0 = args[0].(flow.EpochPhase) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_CurrentEpochPhase_Call) Return() *ComplianceMetrics_CurrentEpochPhase_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_CurrentEpochPhase_Call) RunAndReturn(run func(phase flow.EpochPhase)) *ComplianceMetrics_CurrentEpochPhase_Call { + _c.Run(run) + return _c +} + +// EpochFallbackModeExited provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) EpochFallbackModeExited() { + _mock.Called() + return +} + +// ComplianceMetrics_EpochFallbackModeExited_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochFallbackModeExited' +type ComplianceMetrics_EpochFallbackModeExited_Call struct { + *mock.Call +} + +// EpochFallbackModeExited is a helper method to define mock.On call +func (_e *ComplianceMetrics_Expecter) EpochFallbackModeExited() *ComplianceMetrics_EpochFallbackModeExited_Call { + return &ComplianceMetrics_EpochFallbackModeExited_Call{Call: _e.mock.On("EpochFallbackModeExited")} +} + +func (_c *ComplianceMetrics_EpochFallbackModeExited_Call) Run(run func()) *ComplianceMetrics_EpochFallbackModeExited_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ComplianceMetrics_EpochFallbackModeExited_Call) Return() *ComplianceMetrics_EpochFallbackModeExited_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_EpochFallbackModeExited_Call) RunAndReturn(run func()) *ComplianceMetrics_EpochFallbackModeExited_Call { + _c.Run(run) + return _c +} + +// EpochFallbackModeTriggered provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) EpochFallbackModeTriggered() { + _mock.Called() + return +} + +// ComplianceMetrics_EpochFallbackModeTriggered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochFallbackModeTriggered' +type ComplianceMetrics_EpochFallbackModeTriggered_Call struct { + *mock.Call +} + +// EpochFallbackModeTriggered is a helper method to define mock.On call +func (_e *ComplianceMetrics_Expecter) EpochFallbackModeTriggered() *ComplianceMetrics_EpochFallbackModeTriggered_Call { + return &ComplianceMetrics_EpochFallbackModeTriggered_Call{Call: _e.mock.On("EpochFallbackModeTriggered")} +} + +func (_c *ComplianceMetrics_EpochFallbackModeTriggered_Call) Run(run func()) *ComplianceMetrics_EpochFallbackModeTriggered_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ComplianceMetrics_EpochFallbackModeTriggered_Call) Return() *ComplianceMetrics_EpochFallbackModeTriggered_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_EpochFallbackModeTriggered_Call) RunAndReturn(run func()) *ComplianceMetrics_EpochFallbackModeTriggered_Call { + _c.Run(run) + return _c +} + +// EpochTransitionHeight provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) EpochTransitionHeight(height uint64) { + _mock.Called(height) + return +} + +// ComplianceMetrics_EpochTransitionHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochTransitionHeight' +type ComplianceMetrics_EpochTransitionHeight_Call struct { + *mock.Call +} + +// EpochTransitionHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ComplianceMetrics_Expecter) EpochTransitionHeight(height interface{}) *ComplianceMetrics_EpochTransitionHeight_Call { + return &ComplianceMetrics_EpochTransitionHeight_Call{Call: _e.mock.On("EpochTransitionHeight", height)} +} + +func (_c *ComplianceMetrics_EpochTransitionHeight_Call) Run(run func(height uint64)) *ComplianceMetrics_EpochTransitionHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_EpochTransitionHeight_Call) Return() *ComplianceMetrics_EpochTransitionHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_EpochTransitionHeight_Call) RunAndReturn(run func(height uint64)) *ComplianceMetrics_EpochTransitionHeight_Call { + _c.Run(run) + return _c +} + +// FinalizedHeight provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) FinalizedHeight(height uint64) { + _mock.Called(height) + return +} + +// ComplianceMetrics_FinalizedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedHeight' +type ComplianceMetrics_FinalizedHeight_Call struct { + *mock.Call +} + +// FinalizedHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ComplianceMetrics_Expecter) FinalizedHeight(height interface{}) *ComplianceMetrics_FinalizedHeight_Call { + return &ComplianceMetrics_FinalizedHeight_Call{Call: _e.mock.On("FinalizedHeight", height)} +} + +func (_c *ComplianceMetrics_FinalizedHeight_Call) Run(run func(height uint64)) *ComplianceMetrics_FinalizedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_FinalizedHeight_Call) Return() *ComplianceMetrics_FinalizedHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_FinalizedHeight_Call) RunAndReturn(run func(height uint64)) *ComplianceMetrics_FinalizedHeight_Call { + _c.Run(run) + return _c +} + +// ProtocolStateVersion provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) ProtocolStateVersion(version uint64) { + _mock.Called(version) + return +} + +// ComplianceMetrics_ProtocolStateVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProtocolStateVersion' +type ComplianceMetrics_ProtocolStateVersion_Call struct { + *mock.Call +} + +// ProtocolStateVersion is a helper method to define mock.On call +// - version uint64 +func (_e *ComplianceMetrics_Expecter) ProtocolStateVersion(version interface{}) *ComplianceMetrics_ProtocolStateVersion_Call { + return &ComplianceMetrics_ProtocolStateVersion_Call{Call: _e.mock.On("ProtocolStateVersion", version)} +} + +func (_c *ComplianceMetrics_ProtocolStateVersion_Call) Run(run func(version uint64)) *ComplianceMetrics_ProtocolStateVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_ProtocolStateVersion_Call) Return() *ComplianceMetrics_ProtocolStateVersion_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_ProtocolStateVersion_Call) RunAndReturn(run func(version uint64)) *ComplianceMetrics_ProtocolStateVersion_Call { + _c.Run(run) + return _c +} + +// SealedHeight provides a mock function for the type ComplianceMetrics +func (_mock *ComplianceMetrics) SealedHeight(height uint64) { + _mock.Called(height) + return +} + +// ComplianceMetrics_SealedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SealedHeight' +type ComplianceMetrics_SealedHeight_Call struct { + *mock.Call +} + +// SealedHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ComplianceMetrics_Expecter) SealedHeight(height interface{}) *ComplianceMetrics_SealedHeight_Call { + return &ComplianceMetrics_SealedHeight_Call{Call: _e.mock.On("SealedHeight", height)} +} + +func (_c *ComplianceMetrics_SealedHeight_Call) Run(run func(height uint64)) *ComplianceMetrics_SealedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComplianceMetrics_SealedHeight_Call) Return() *ComplianceMetrics_SealedHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ComplianceMetrics_SealedHeight_Call) RunAndReturn(run func(height uint64)) *ComplianceMetrics_SealedHeight_Call { + _c.Run(run) + return _c } diff --git a/module/mock/consensus_metrics.go b/module/mock/consensus_metrics.go index a6588cbdf28..bc0db6df7e2 100644 --- a/module/mock/consensus_metrics.go +++ b/module/mock/consensus_metrics.go @@ -1,69 +1,352 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - mock "github.com/stretchr/testify/mock" + "time" - time "time" + "github.com/onflow/flow-go/model/flow" + mock "github.com/stretchr/testify/mock" ) +// NewConsensusMetrics creates a new instance of ConsensusMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConsensusMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ConsensusMetrics { + mock := &ConsensusMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ConsensusMetrics is an autogenerated mock type for the ConsensusMetrics type type ConsensusMetrics struct { mock.Mock } -// CheckSealingDuration provides a mock function with given fields: duration -func (_m *ConsensusMetrics) CheckSealingDuration(duration time.Duration) { - _m.Called(duration) +type ConsensusMetrics_Expecter struct { + mock *mock.Mock } -// EmergencySeal provides a mock function with no fields -func (_m *ConsensusMetrics) EmergencySeal() { - _m.Called() +func (_m *ConsensusMetrics) EXPECT() *ConsensusMetrics_Expecter { + return &ConsensusMetrics_Expecter{mock: &_m.Mock} } -// FinishBlockToSeal provides a mock function with given fields: blockID -func (_m *ConsensusMetrics) FinishBlockToSeal(blockID flow.Identifier) { - _m.Called(blockID) +// CheckSealingDuration provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) CheckSealingDuration(duration time.Duration) { + _mock.Called(duration) + return } -// FinishCollectionToFinalized provides a mock function with given fields: collectionID -func (_m *ConsensusMetrics) FinishCollectionToFinalized(collectionID flow.Identifier) { - _m.Called(collectionID) +// ConsensusMetrics_CheckSealingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckSealingDuration' +type ConsensusMetrics_CheckSealingDuration_Call struct { + *mock.Call } -// OnApprovalProcessingDuration provides a mock function with given fields: duration -func (_m *ConsensusMetrics) OnApprovalProcessingDuration(duration time.Duration) { - _m.Called(duration) +// CheckSealingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *ConsensusMetrics_Expecter) CheckSealingDuration(duration interface{}) *ConsensusMetrics_CheckSealingDuration_Call { + return &ConsensusMetrics_CheckSealingDuration_Call{Call: _e.mock.On("CheckSealingDuration", duration)} } -// OnReceiptProcessingDuration provides a mock function with given fields: duration -func (_m *ConsensusMetrics) OnReceiptProcessingDuration(duration time.Duration) { - _m.Called(duration) +func (_c *ConsensusMetrics_CheckSealingDuration_Call) Run(run func(duration time.Duration)) *ConsensusMetrics_CheckSealingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// StartBlockToSeal provides a mock function with given fields: blockID -func (_m *ConsensusMetrics) StartBlockToSeal(blockID flow.Identifier) { - _m.Called(blockID) +func (_c *ConsensusMetrics_CheckSealingDuration_Call) Return() *ConsensusMetrics_CheckSealingDuration_Call { + _c.Call.Return() + return _c } -// StartCollectionToFinalized provides a mock function with given fields: collectionID -func (_m *ConsensusMetrics) StartCollectionToFinalized(collectionID flow.Identifier) { - _m.Called(collectionID) +func (_c *ConsensusMetrics_CheckSealingDuration_Call) RunAndReturn(run func(duration time.Duration)) *ConsensusMetrics_CheckSealingDuration_Call { + _c.Run(run) + return _c } -// NewConsensusMetrics creates a new instance of ConsensusMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConsensusMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ConsensusMetrics { - mock := &ConsensusMetrics{} - mock.Mock.Test(t) +// EmergencySeal provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) EmergencySeal() { + _mock.Called() + return +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ConsensusMetrics_EmergencySeal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EmergencySeal' +type ConsensusMetrics_EmergencySeal_Call struct { + *mock.Call +} - return mock +// EmergencySeal is a helper method to define mock.On call +func (_e *ConsensusMetrics_Expecter) EmergencySeal() *ConsensusMetrics_EmergencySeal_Call { + return &ConsensusMetrics_EmergencySeal_Call{Call: _e.mock.On("EmergencySeal")} +} + +func (_c *ConsensusMetrics_EmergencySeal_Call) Run(run func()) *ConsensusMetrics_EmergencySeal_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ConsensusMetrics_EmergencySeal_Call) Return() *ConsensusMetrics_EmergencySeal_Call { + _c.Call.Return() + return _c +} + +func (_c *ConsensusMetrics_EmergencySeal_Call) RunAndReturn(run func()) *ConsensusMetrics_EmergencySeal_Call { + _c.Run(run) + return _c +} + +// FinishBlockToSeal provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) FinishBlockToSeal(blockID flow.Identifier) { + _mock.Called(blockID) + return +} + +// ConsensusMetrics_FinishBlockToSeal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinishBlockToSeal' +type ConsensusMetrics_FinishBlockToSeal_Call struct { + *mock.Call +} + +// FinishBlockToSeal is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ConsensusMetrics_Expecter) FinishBlockToSeal(blockID interface{}) *ConsensusMetrics_FinishBlockToSeal_Call { + return &ConsensusMetrics_FinishBlockToSeal_Call{Call: _e.mock.On("FinishBlockToSeal", blockID)} +} + +func (_c *ConsensusMetrics_FinishBlockToSeal_Call) Run(run func(blockID flow.Identifier)) *ConsensusMetrics_FinishBlockToSeal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsensusMetrics_FinishBlockToSeal_Call) Return() *ConsensusMetrics_FinishBlockToSeal_Call { + _c.Call.Return() + return _c +} + +func (_c *ConsensusMetrics_FinishBlockToSeal_Call) RunAndReturn(run func(blockID flow.Identifier)) *ConsensusMetrics_FinishBlockToSeal_Call { + _c.Run(run) + return _c +} + +// FinishCollectionToFinalized provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) FinishCollectionToFinalized(collectionID flow.Identifier) { + _mock.Called(collectionID) + return +} + +// ConsensusMetrics_FinishCollectionToFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinishCollectionToFinalized' +type ConsensusMetrics_FinishCollectionToFinalized_Call struct { + *mock.Call +} + +// FinishCollectionToFinalized is a helper method to define mock.On call +// - collectionID flow.Identifier +func (_e *ConsensusMetrics_Expecter) FinishCollectionToFinalized(collectionID interface{}) *ConsensusMetrics_FinishCollectionToFinalized_Call { + return &ConsensusMetrics_FinishCollectionToFinalized_Call{Call: _e.mock.On("FinishCollectionToFinalized", collectionID)} +} + +func (_c *ConsensusMetrics_FinishCollectionToFinalized_Call) Run(run func(collectionID flow.Identifier)) *ConsensusMetrics_FinishCollectionToFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsensusMetrics_FinishCollectionToFinalized_Call) Return() *ConsensusMetrics_FinishCollectionToFinalized_Call { + _c.Call.Return() + return _c +} + +func (_c *ConsensusMetrics_FinishCollectionToFinalized_Call) RunAndReturn(run func(collectionID flow.Identifier)) *ConsensusMetrics_FinishCollectionToFinalized_Call { + _c.Run(run) + return _c +} + +// OnApprovalProcessingDuration provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) OnApprovalProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// ConsensusMetrics_OnApprovalProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnApprovalProcessingDuration' +type ConsensusMetrics_OnApprovalProcessingDuration_Call struct { + *mock.Call +} + +// OnApprovalProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *ConsensusMetrics_Expecter) OnApprovalProcessingDuration(duration interface{}) *ConsensusMetrics_OnApprovalProcessingDuration_Call { + return &ConsensusMetrics_OnApprovalProcessingDuration_Call{Call: _e.mock.On("OnApprovalProcessingDuration", duration)} +} + +func (_c *ConsensusMetrics_OnApprovalProcessingDuration_Call) Run(run func(duration time.Duration)) *ConsensusMetrics_OnApprovalProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsensusMetrics_OnApprovalProcessingDuration_Call) Return() *ConsensusMetrics_OnApprovalProcessingDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *ConsensusMetrics_OnApprovalProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *ConsensusMetrics_OnApprovalProcessingDuration_Call { + _c.Run(run) + return _c +} + +// OnReceiptProcessingDuration provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) OnReceiptProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// ConsensusMetrics_OnReceiptProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnReceiptProcessingDuration' +type ConsensusMetrics_OnReceiptProcessingDuration_Call struct { + *mock.Call +} + +// OnReceiptProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *ConsensusMetrics_Expecter) OnReceiptProcessingDuration(duration interface{}) *ConsensusMetrics_OnReceiptProcessingDuration_Call { + return &ConsensusMetrics_OnReceiptProcessingDuration_Call{Call: _e.mock.On("OnReceiptProcessingDuration", duration)} +} + +func (_c *ConsensusMetrics_OnReceiptProcessingDuration_Call) Run(run func(duration time.Duration)) *ConsensusMetrics_OnReceiptProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsensusMetrics_OnReceiptProcessingDuration_Call) Return() *ConsensusMetrics_OnReceiptProcessingDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *ConsensusMetrics_OnReceiptProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *ConsensusMetrics_OnReceiptProcessingDuration_Call { + _c.Run(run) + return _c +} + +// StartBlockToSeal provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) StartBlockToSeal(blockID flow.Identifier) { + _mock.Called(blockID) + return +} + +// ConsensusMetrics_StartBlockToSeal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartBlockToSeal' +type ConsensusMetrics_StartBlockToSeal_Call struct { + *mock.Call +} + +// StartBlockToSeal is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ConsensusMetrics_Expecter) StartBlockToSeal(blockID interface{}) *ConsensusMetrics_StartBlockToSeal_Call { + return &ConsensusMetrics_StartBlockToSeal_Call{Call: _e.mock.On("StartBlockToSeal", blockID)} +} + +func (_c *ConsensusMetrics_StartBlockToSeal_Call) Run(run func(blockID flow.Identifier)) *ConsensusMetrics_StartBlockToSeal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsensusMetrics_StartBlockToSeal_Call) Return() *ConsensusMetrics_StartBlockToSeal_Call { + _c.Call.Return() + return _c +} + +func (_c *ConsensusMetrics_StartBlockToSeal_Call) RunAndReturn(run func(blockID flow.Identifier)) *ConsensusMetrics_StartBlockToSeal_Call { + _c.Run(run) + return _c +} + +// StartCollectionToFinalized provides a mock function for the type ConsensusMetrics +func (_mock *ConsensusMetrics) StartCollectionToFinalized(collectionID flow.Identifier) { + _mock.Called(collectionID) + return +} + +// ConsensusMetrics_StartCollectionToFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartCollectionToFinalized' +type ConsensusMetrics_StartCollectionToFinalized_Call struct { + *mock.Call +} + +// StartCollectionToFinalized is a helper method to define mock.On call +// - collectionID flow.Identifier +func (_e *ConsensusMetrics_Expecter) StartCollectionToFinalized(collectionID interface{}) *ConsensusMetrics_StartCollectionToFinalized_Call { + return &ConsensusMetrics_StartCollectionToFinalized_Call{Call: _e.mock.On("StartCollectionToFinalized", collectionID)} +} + +func (_c *ConsensusMetrics_StartCollectionToFinalized_Call) Run(run func(collectionID flow.Identifier)) *ConsensusMetrics_StartCollectionToFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsensusMetrics_StartCollectionToFinalized_Call) Return() *ConsensusMetrics_StartCollectionToFinalized_Call { + _c.Call.Return() + return _c +} + +func (_c *ConsensusMetrics_StartCollectionToFinalized_Call) RunAndReturn(run func(collectionID flow.Identifier)) *ConsensusMetrics_StartCollectionToFinalized_Call { + _c.Run(run) + return _c } diff --git a/module/mock/cruise_ctl_metrics.go b/module/mock/cruise_ctl_metrics.go index e6e0541cede..a482331b72d 100644 --- a/module/mock/cruise_ctl_metrics.go +++ b/module/mock/cruise_ctl_metrics.go @@ -1,48 +1,210 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewCruiseCtlMetrics creates a new instance of CruiseCtlMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCruiseCtlMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *CruiseCtlMetrics { + mock := &CruiseCtlMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CruiseCtlMetrics is an autogenerated mock type for the CruiseCtlMetrics type type CruiseCtlMetrics struct { mock.Mock } -// ControllerOutput provides a mock function with given fields: duration -func (_m *CruiseCtlMetrics) ControllerOutput(duration time.Duration) { - _m.Called(duration) +type CruiseCtlMetrics_Expecter struct { + mock *mock.Mock } -// PIDError provides a mock function with given fields: p, i, d -func (_m *CruiseCtlMetrics) PIDError(p float64, i float64, d float64) { - _m.Called(p, i, d) +func (_m *CruiseCtlMetrics) EXPECT() *CruiseCtlMetrics_Expecter { + return &CruiseCtlMetrics_Expecter{mock: &_m.Mock} } -// ProposalPublicationDelay provides a mock function with given fields: duration -func (_m *CruiseCtlMetrics) ProposalPublicationDelay(duration time.Duration) { - _m.Called(duration) +// ControllerOutput provides a mock function for the type CruiseCtlMetrics +func (_mock *CruiseCtlMetrics) ControllerOutput(duration time.Duration) { + _mock.Called(duration) + return } -// TargetProposalDuration provides a mock function with given fields: duration -func (_m *CruiseCtlMetrics) TargetProposalDuration(duration time.Duration) { - _m.Called(duration) +// CruiseCtlMetrics_ControllerOutput_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ControllerOutput' +type CruiseCtlMetrics_ControllerOutput_Call struct { + *mock.Call } -// NewCruiseCtlMetrics creates a new instance of CruiseCtlMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCruiseCtlMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *CruiseCtlMetrics { - mock := &CruiseCtlMetrics{} - mock.Mock.Test(t) +// ControllerOutput is a helper method to define mock.On call +// - duration time.Duration +func (_e *CruiseCtlMetrics_Expecter) ControllerOutput(duration interface{}) *CruiseCtlMetrics_ControllerOutput_Call { + return &CruiseCtlMetrics_ControllerOutput_Call{Call: _e.mock.On("ControllerOutput", duration)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *CruiseCtlMetrics_ControllerOutput_Call) Run(run func(duration time.Duration)) *CruiseCtlMetrics_ControllerOutput_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *CruiseCtlMetrics_ControllerOutput_Call) Return() *CruiseCtlMetrics_ControllerOutput_Call { + _c.Call.Return() + return _c +} + +func (_c *CruiseCtlMetrics_ControllerOutput_Call) RunAndReturn(run func(duration time.Duration)) *CruiseCtlMetrics_ControllerOutput_Call { + _c.Run(run) + return _c +} + +// PIDError provides a mock function for the type CruiseCtlMetrics +func (_mock *CruiseCtlMetrics) PIDError(p float64, i float64, d float64) { + _mock.Called(p, i, d) + return +} + +// CruiseCtlMetrics_PIDError_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PIDError' +type CruiseCtlMetrics_PIDError_Call struct { + *mock.Call +} + +// PIDError is a helper method to define mock.On call +// - p float64 +// - i float64 +// - d float64 +func (_e *CruiseCtlMetrics_Expecter) PIDError(p interface{}, i interface{}, d interface{}) *CruiseCtlMetrics_PIDError_Call { + return &CruiseCtlMetrics_PIDError_Call{Call: _e.mock.On("PIDError", p, i, d)} +} + +func (_c *CruiseCtlMetrics_PIDError_Call) Run(run func(p float64, i float64, d float64)) *CruiseCtlMetrics_PIDError_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + var arg2 float64 + if args[2] != nil { + arg2 = args[2].(float64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *CruiseCtlMetrics_PIDError_Call) Return() *CruiseCtlMetrics_PIDError_Call { + _c.Call.Return() + return _c +} + +func (_c *CruiseCtlMetrics_PIDError_Call) RunAndReturn(run func(p float64, i float64, d float64)) *CruiseCtlMetrics_PIDError_Call { + _c.Run(run) + return _c +} + +// ProposalPublicationDelay provides a mock function for the type CruiseCtlMetrics +func (_mock *CruiseCtlMetrics) ProposalPublicationDelay(duration time.Duration) { + _mock.Called(duration) + return +} + +// CruiseCtlMetrics_ProposalPublicationDelay_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProposalPublicationDelay' +type CruiseCtlMetrics_ProposalPublicationDelay_Call struct { + *mock.Call +} + +// ProposalPublicationDelay is a helper method to define mock.On call +// - duration time.Duration +func (_e *CruiseCtlMetrics_Expecter) ProposalPublicationDelay(duration interface{}) *CruiseCtlMetrics_ProposalPublicationDelay_Call { + return &CruiseCtlMetrics_ProposalPublicationDelay_Call{Call: _e.mock.On("ProposalPublicationDelay", duration)} +} + +func (_c *CruiseCtlMetrics_ProposalPublicationDelay_Call) Run(run func(duration time.Duration)) *CruiseCtlMetrics_ProposalPublicationDelay_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CruiseCtlMetrics_ProposalPublicationDelay_Call) Return() *CruiseCtlMetrics_ProposalPublicationDelay_Call { + _c.Call.Return() + return _c +} + +func (_c *CruiseCtlMetrics_ProposalPublicationDelay_Call) RunAndReturn(run func(duration time.Duration)) *CruiseCtlMetrics_ProposalPublicationDelay_Call { + _c.Run(run) + return _c +} + +// TargetProposalDuration provides a mock function for the type CruiseCtlMetrics +func (_mock *CruiseCtlMetrics) TargetProposalDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// CruiseCtlMetrics_TargetProposalDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TargetProposalDuration' +type CruiseCtlMetrics_TargetProposalDuration_Call struct { + *mock.Call +} + +// TargetProposalDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *CruiseCtlMetrics_Expecter) TargetProposalDuration(duration interface{}) *CruiseCtlMetrics_TargetProposalDuration_Call { + return &CruiseCtlMetrics_TargetProposalDuration_Call{Call: _e.mock.On("TargetProposalDuration", duration)} +} + +func (_c *CruiseCtlMetrics_TargetProposalDuration_Call) Run(run func(duration time.Duration)) *CruiseCtlMetrics_TargetProposalDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CruiseCtlMetrics_TargetProposalDuration_Call) Return() *CruiseCtlMetrics_TargetProposalDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *CruiseCtlMetrics_TargetProposalDuration_Call) RunAndReturn(run func(duration time.Duration)) *CruiseCtlMetrics_TargetProposalDuration_Call { + _c.Run(run) + return _c } diff --git a/module/mock/crypto_mocks.go b/module/mock/crypto_mocks.go new file mode 100644 index 00000000000..2c5319f0df6 --- /dev/null +++ b/module/mock/crypto_mocks.go @@ -0,0 +1,2680 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/crypto" + "github.com/onflow/crypto/hash" + mock "github.com/stretchr/testify/mock" +) + +// NewDKGState creates a new instance of DKGState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGState(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGState { + mock := &DKGState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// DKGState is an autogenerated mock type for the DKGState type +type DKGState struct { + mock.Mock +} + +type DKGState_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGState) EXPECT() *DKGState_Expecter { + return &DKGState_Expecter{mock: &_m.Mock} +} + +// End provides a mock function for the type DKGState +func (_mock *DKGState) End() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for End") + } + + var r0 crypto.PrivateKey + var r1 crypto.PublicKey + var r2 []crypto.PublicKey + var r3 error + if returnFunc, ok := ret.Get(0).(func() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() crypto.PrivateKey); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.PrivateKey) + } + } + if returnFunc, ok := ret.Get(1).(func() crypto.PublicKey); ok { + r1 = returnFunc() + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(crypto.PublicKey) + } + } + if returnFunc, ok := ret.Get(2).(func() []crypto.PublicKey); ok { + r2 = returnFunc() + } else { + if ret.Get(2) != nil { + r2 = ret.Get(2).([]crypto.PublicKey) + } + } + if returnFunc, ok := ret.Get(3).(func() error); ok { + r3 = returnFunc() + } else { + r3 = ret.Error(3) + } + return r0, r1, r2, r3 +} + +// DKGState_End_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'End' +type DKGState_End_Call struct { + *mock.Call +} + +// End is a helper method to define mock.On call +func (_e *DKGState_Expecter) End() *DKGState_End_Call { + return &DKGState_End_Call{Call: _e.mock.On("End")} +} + +func (_c *DKGState_End_Call) Run(run func()) *DKGState_End_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGState_End_Call) Return(privateKey crypto.PrivateKey, publicKey crypto.PublicKey, publicKeys []crypto.PublicKey, err error) *DKGState_End_Call { + _c.Call.Return(privateKey, publicKey, publicKeys, err) + return _c +} + +func (_c *DKGState_End_Call) RunAndReturn(run func() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey, error)) *DKGState_End_Call { + _c.Call.Return(run) + return _c +} + +// ForceDisqualify provides a mock function for the type DKGState +func (_mock *DKGState) ForceDisqualify(participant int) error { + ret := _mock.Called(participant) + + if len(ret) == 0 { + panic("no return value specified for ForceDisqualify") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(int) error); ok { + r0 = returnFunc(participant) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// DKGState_ForceDisqualify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ForceDisqualify' +type DKGState_ForceDisqualify_Call struct { + *mock.Call +} + +// ForceDisqualify is a helper method to define mock.On call +// - participant int +func (_e *DKGState_Expecter) ForceDisqualify(participant interface{}) *DKGState_ForceDisqualify_Call { + return &DKGState_ForceDisqualify_Call{Call: _e.mock.On("ForceDisqualify", participant)} +} + +func (_c *DKGState_ForceDisqualify_Call) Run(run func(participant int)) *DKGState_ForceDisqualify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGState_ForceDisqualify_Call) Return(err error) *DKGState_ForceDisqualify_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_ForceDisqualify_Call) RunAndReturn(run func(participant int) error) *DKGState_ForceDisqualify_Call { + _c.Call.Return(run) + return _c +} + +// HandleBroadcastMsg provides a mock function for the type DKGState +func (_mock *DKGState) HandleBroadcastMsg(orig int, msg []byte) error { + ret := _mock.Called(orig, msg) + + if len(ret) == 0 { + panic("no return value specified for HandleBroadcastMsg") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(int, []byte) error); ok { + r0 = returnFunc(orig, msg) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// DKGState_HandleBroadcastMsg_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleBroadcastMsg' +type DKGState_HandleBroadcastMsg_Call struct { + *mock.Call +} + +// HandleBroadcastMsg is a helper method to define mock.On call +// - orig int +// - msg []byte +func (_e *DKGState_Expecter) HandleBroadcastMsg(orig interface{}, msg interface{}) *DKGState_HandleBroadcastMsg_Call { + return &DKGState_HandleBroadcastMsg_Call{Call: _e.mock.On("HandleBroadcastMsg", orig, msg)} +} + +func (_c *DKGState_HandleBroadcastMsg_Call) Run(run func(orig int, msg []byte)) *DKGState_HandleBroadcastMsg_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGState_HandleBroadcastMsg_Call) Return(err error) *DKGState_HandleBroadcastMsg_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_HandleBroadcastMsg_Call) RunAndReturn(run func(orig int, msg []byte) error) *DKGState_HandleBroadcastMsg_Call { + _c.Call.Return(run) + return _c +} + +// HandlePrivateMsg provides a mock function for the type DKGState +func (_mock *DKGState) HandlePrivateMsg(orig int, msg []byte) error { + ret := _mock.Called(orig, msg) + + if len(ret) == 0 { + panic("no return value specified for HandlePrivateMsg") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(int, []byte) error); ok { + r0 = returnFunc(orig, msg) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// DKGState_HandlePrivateMsg_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandlePrivateMsg' +type DKGState_HandlePrivateMsg_Call struct { + *mock.Call +} + +// HandlePrivateMsg is a helper method to define mock.On call +// - orig int +// - msg []byte +func (_e *DKGState_Expecter) HandlePrivateMsg(orig interface{}, msg interface{}) *DKGState_HandlePrivateMsg_Call { + return &DKGState_HandlePrivateMsg_Call{Call: _e.mock.On("HandlePrivateMsg", orig, msg)} +} + +func (_c *DKGState_HandlePrivateMsg_Call) Run(run func(orig int, msg []byte)) *DKGState_HandlePrivateMsg_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGState_HandlePrivateMsg_Call) Return(err error) *DKGState_HandlePrivateMsg_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_HandlePrivateMsg_Call) RunAndReturn(run func(orig int, msg []byte) error) *DKGState_HandlePrivateMsg_Call { + _c.Call.Return(run) + return _c +} + +// NextTimeout provides a mock function for the type DKGState +func (_mock *DKGState) NextTimeout() error { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for NextTimeout") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() + } else { + r0 = ret.Error(0) + } + return r0 +} + +// DKGState_NextTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NextTimeout' +type DKGState_NextTimeout_Call struct { + *mock.Call +} + +// NextTimeout is a helper method to define mock.On call +func (_e *DKGState_Expecter) NextTimeout() *DKGState_NextTimeout_Call { + return &DKGState_NextTimeout_Call{Call: _e.mock.On("NextTimeout")} +} + +func (_c *DKGState_NextTimeout_Call) Run(run func()) *DKGState_NextTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGState_NextTimeout_Call) Return(err error) *DKGState_NextTimeout_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_NextTimeout_Call) RunAndReturn(run func() error) *DKGState_NextTimeout_Call { + _c.Call.Return(run) + return _c +} + +// Running provides a mock function for the type DKGState +func (_mock *DKGState) Running() bool { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Running") + } + + var r0 bool + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(bool) + } + return r0 +} + +// DKGState_Running_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Running' +type DKGState_Running_Call struct { + *mock.Call +} + +// Running is a helper method to define mock.On call +func (_e *DKGState_Expecter) Running() *DKGState_Running_Call { + return &DKGState_Running_Call{Call: _e.mock.On("Running")} +} + +func (_c *DKGState_Running_Call) Run(run func()) *DKGState_Running_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGState_Running_Call) Return(b bool) *DKGState_Running_Call { + _c.Call.Return(b) + return _c +} + +func (_c *DKGState_Running_Call) RunAndReturn(run func() bool) *DKGState_Running_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type DKGState +func (_mock *DKGState) Size() int { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Size") + } + + var r0 int + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(int) + } + return r0 +} + +// DKGState_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type DKGState_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *DKGState_Expecter) Size() *DKGState_Size_Call { + return &DKGState_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *DKGState_Size_Call) Run(run func()) *DKGState_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGState_Size_Call) Return(n int) *DKGState_Size_Call { + _c.Call.Return(n) + return _c +} + +func (_c *DKGState_Size_Call) RunAndReturn(run func() int) *DKGState_Size_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type DKGState +func (_mock *DKGState) Start(seed []byte) error { + ret := _mock.Called(seed) + + if len(ret) == 0 { + panic("no return value specified for Start") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func([]byte) error); ok { + r0 = returnFunc(seed) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// DKGState_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type DKGState_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - seed []byte +func (_e *DKGState_Expecter) Start(seed interface{}) *DKGState_Start_Call { + return &DKGState_Start_Call{Call: _e.mock.On("Start", seed)} +} + +func (_c *DKGState_Start_Call) Run(run func(seed []byte)) *DKGState_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGState_Start_Call) Return(err error) *DKGState_Start_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_Start_Call) RunAndReturn(run func(seed []byte) error) *DKGState_Start_Call { + _c.Call.Return(run) + return _c +} + +// Threshold provides a mock function for the type DKGState +func (_mock *DKGState) Threshold() int { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Threshold") + } + + var r0 int + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(int) + } + return r0 +} + +// DKGState_Threshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Threshold' +type DKGState_Threshold_Call struct { + *mock.Call +} + +// Threshold is a helper method to define mock.On call +func (_e *DKGState_Expecter) Threshold() *DKGState_Threshold_Call { + return &DKGState_Threshold_Call{Call: _e.mock.On("Threshold")} +} + +func (_c *DKGState_Threshold_Call) Run(run func()) *DKGState_Threshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGState_Threshold_Call) Return(n int) *DKGState_Threshold_Call { + _c.Call.Return(n) + return _c +} + +func (_c *DKGState_Threshold_Call) RunAndReturn(run func() int) *DKGState_Threshold_Call { + _c.Call.Return(run) + return _c +} + +// NewDKGProcessor creates a new instance of DKGProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGProcessor(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGProcessor { + mock := &DKGProcessor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// DKGProcessor is an autogenerated mock type for the DKGProcessor type +type DKGProcessor struct { + mock.Mock +} + +type DKGProcessor_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGProcessor) EXPECT() *DKGProcessor_Expecter { + return &DKGProcessor_Expecter{mock: &_m.Mock} +} + +// Broadcast provides a mock function for the type DKGProcessor +func (_mock *DKGProcessor) Broadcast(data []byte) { + _mock.Called(data) + return +} + +// DKGProcessor_Broadcast_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Broadcast' +type DKGProcessor_Broadcast_Call struct { + *mock.Call +} + +// Broadcast is a helper method to define mock.On call +// - data []byte +func (_e *DKGProcessor_Expecter) Broadcast(data interface{}) *DKGProcessor_Broadcast_Call { + return &DKGProcessor_Broadcast_Call{Call: _e.mock.On("Broadcast", data)} +} + +func (_c *DKGProcessor_Broadcast_Call) Run(run func(data []byte)) *DKGProcessor_Broadcast_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGProcessor_Broadcast_Call) Return() *DKGProcessor_Broadcast_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGProcessor_Broadcast_Call) RunAndReturn(run func(data []byte)) *DKGProcessor_Broadcast_Call { + _c.Run(run) + return _c +} + +// Disqualify provides a mock function for the type DKGProcessor +func (_mock *DKGProcessor) Disqualify(index int, log string) { + _mock.Called(index, log) + return +} + +// DKGProcessor_Disqualify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Disqualify' +type DKGProcessor_Disqualify_Call struct { + *mock.Call +} + +// Disqualify is a helper method to define mock.On call +// - index int +// - log string +func (_e *DKGProcessor_Expecter) Disqualify(index interface{}, log interface{}) *DKGProcessor_Disqualify_Call { + return &DKGProcessor_Disqualify_Call{Call: _e.mock.On("Disqualify", index, log)} +} + +func (_c *DKGProcessor_Disqualify_Call) Run(run func(index int, log string)) *DKGProcessor_Disqualify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGProcessor_Disqualify_Call) Return() *DKGProcessor_Disqualify_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGProcessor_Disqualify_Call) RunAndReturn(run func(index int, log string)) *DKGProcessor_Disqualify_Call { + _c.Run(run) + return _c +} + +// FlagMisbehavior provides a mock function for the type DKGProcessor +func (_mock *DKGProcessor) FlagMisbehavior(index int, log string) { + _mock.Called(index, log) + return +} + +// DKGProcessor_FlagMisbehavior_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FlagMisbehavior' +type DKGProcessor_FlagMisbehavior_Call struct { + *mock.Call +} + +// FlagMisbehavior is a helper method to define mock.On call +// - index int +// - log string +func (_e *DKGProcessor_Expecter) FlagMisbehavior(index interface{}, log interface{}) *DKGProcessor_FlagMisbehavior_Call { + return &DKGProcessor_FlagMisbehavior_Call{Call: _e.mock.On("FlagMisbehavior", index, log)} +} + +func (_c *DKGProcessor_FlagMisbehavior_Call) Run(run func(index int, log string)) *DKGProcessor_FlagMisbehavior_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGProcessor_FlagMisbehavior_Call) Return() *DKGProcessor_FlagMisbehavior_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGProcessor_FlagMisbehavior_Call) RunAndReturn(run func(index int, log string)) *DKGProcessor_FlagMisbehavior_Call { + _c.Run(run) + return _c +} + +// PrivateSend provides a mock function for the type DKGProcessor +func (_mock *DKGProcessor) PrivateSend(dest int, data []byte) { + _mock.Called(dest, data) + return +} + +// DKGProcessor_PrivateSend_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PrivateSend' +type DKGProcessor_PrivateSend_Call struct { + *mock.Call +} + +// PrivateSend is a helper method to define mock.On call +// - dest int +// - data []byte +func (_e *DKGProcessor_Expecter) PrivateSend(dest interface{}, data interface{}) *DKGProcessor_PrivateSend_Call { + return &DKGProcessor_PrivateSend_Call{Call: _e.mock.On("PrivateSend", dest, data)} +} + +func (_c *DKGProcessor_PrivateSend_Call) Run(run func(dest int, data []byte)) *DKGProcessor_PrivateSend_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGProcessor_PrivateSend_Call) Return() *DKGProcessor_PrivateSend_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGProcessor_PrivateSend_Call) RunAndReturn(run func(dest int, data []byte)) *DKGProcessor_PrivateSend_Call { + _c.Run(run) + return _c +} + +// newSigner creates a new instance of signer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newSigner(t interface { + mock.TestingT + Cleanup(func()) +}) *signer { + mock := &signer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// signer is an autogenerated mock type for the signer type +type signer struct { + mock.Mock +} + +type signer_Expecter struct { + mock *mock.Mock +} + +func (_m *signer) EXPECT() *signer_Expecter { + return &signer_Expecter{mock: &_m.Mock} +} + +// decodePrivateKey provides a mock function for the type signer +func (_mock *signer) decodePrivateKey(bytes []byte) (crypto.PrivateKey, error) { + ret := _mock.Called(bytes) + + if len(ret) == 0 { + panic("no return value specified for decodePrivateKey") + } + + var r0 crypto.PrivateKey + var r1 error + if returnFunc, ok := ret.Get(0).(func([]byte) (crypto.PrivateKey, error)); ok { + return returnFunc(bytes) + } + if returnFunc, ok := ret.Get(0).(func([]byte) crypto.PrivateKey); ok { + r0 = returnFunc(bytes) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.PrivateKey) + } + } + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(bytes) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// signer_decodePrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'decodePrivateKey' +type signer_decodePrivateKey_Call struct { + *mock.Call +} + +// decodePrivateKey is a helper method to define mock.On call +// - bytes []byte +func (_e *signer_Expecter) decodePrivateKey(bytes interface{}) *signer_decodePrivateKey_Call { + return &signer_decodePrivateKey_Call{Call: _e.mock.On("decodePrivateKey", bytes)} +} + +func (_c *signer_decodePrivateKey_Call) Run(run func(bytes []byte)) *signer_decodePrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *signer_decodePrivateKey_Call) Return(privateKey crypto.PrivateKey, err error) *signer_decodePrivateKey_Call { + _c.Call.Return(privateKey, err) + return _c +} + +func (_c *signer_decodePrivateKey_Call) RunAndReturn(run func(bytes []byte) (crypto.PrivateKey, error)) *signer_decodePrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// decodePublicKey provides a mock function for the type signer +func (_mock *signer) decodePublicKey(bytes []byte) (crypto.PublicKey, error) { + ret := _mock.Called(bytes) + + if len(ret) == 0 { + panic("no return value specified for decodePublicKey") + } + + var r0 crypto.PublicKey + var r1 error + if returnFunc, ok := ret.Get(0).(func([]byte) (crypto.PublicKey, error)); ok { + return returnFunc(bytes) + } + if returnFunc, ok := ret.Get(0).(func([]byte) crypto.PublicKey); ok { + r0 = returnFunc(bytes) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.PublicKey) + } + } + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(bytes) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// signer_decodePublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'decodePublicKey' +type signer_decodePublicKey_Call struct { + *mock.Call +} + +// decodePublicKey is a helper method to define mock.On call +// - bytes []byte +func (_e *signer_Expecter) decodePublicKey(bytes interface{}) *signer_decodePublicKey_Call { + return &signer_decodePublicKey_Call{Call: _e.mock.On("decodePublicKey", bytes)} +} + +func (_c *signer_decodePublicKey_Call) Run(run func(bytes []byte)) *signer_decodePublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *signer_decodePublicKey_Call) Return(publicKey crypto.PublicKey, err error) *signer_decodePublicKey_Call { + _c.Call.Return(publicKey, err) + return _c +} + +func (_c *signer_decodePublicKey_Call) RunAndReturn(run func(bytes []byte) (crypto.PublicKey, error)) *signer_decodePublicKey_Call { + _c.Call.Return(run) + return _c +} + +// decodePublicKeyCompressed provides a mock function for the type signer +func (_mock *signer) decodePublicKeyCompressed(bytes []byte) (crypto.PublicKey, error) { + ret := _mock.Called(bytes) + + if len(ret) == 0 { + panic("no return value specified for decodePublicKeyCompressed") + } + + var r0 crypto.PublicKey + var r1 error + if returnFunc, ok := ret.Get(0).(func([]byte) (crypto.PublicKey, error)); ok { + return returnFunc(bytes) + } + if returnFunc, ok := ret.Get(0).(func([]byte) crypto.PublicKey); ok { + r0 = returnFunc(bytes) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.PublicKey) + } + } + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(bytes) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// signer_decodePublicKeyCompressed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'decodePublicKeyCompressed' +type signer_decodePublicKeyCompressed_Call struct { + *mock.Call +} + +// decodePublicKeyCompressed is a helper method to define mock.On call +// - bytes []byte +func (_e *signer_Expecter) decodePublicKeyCompressed(bytes interface{}) *signer_decodePublicKeyCompressed_Call { + return &signer_decodePublicKeyCompressed_Call{Call: _e.mock.On("decodePublicKeyCompressed", bytes)} +} + +func (_c *signer_decodePublicKeyCompressed_Call) Run(run func(bytes []byte)) *signer_decodePublicKeyCompressed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *signer_decodePublicKeyCompressed_Call) Return(publicKey crypto.PublicKey, err error) *signer_decodePublicKeyCompressed_Call { + _c.Call.Return(publicKey, err) + return _c +} + +func (_c *signer_decodePublicKeyCompressed_Call) RunAndReturn(run func(bytes []byte) (crypto.PublicKey, error)) *signer_decodePublicKeyCompressed_Call { + _c.Call.Return(run) + return _c +} + +// generatePrivateKey provides a mock function for the type signer +func (_mock *signer) generatePrivateKey(bytes []byte) (crypto.PrivateKey, error) { + ret := _mock.Called(bytes) + + if len(ret) == 0 { + panic("no return value specified for generatePrivateKey") + } + + var r0 crypto.PrivateKey + var r1 error + if returnFunc, ok := ret.Get(0).(func([]byte) (crypto.PrivateKey, error)); ok { + return returnFunc(bytes) + } + if returnFunc, ok := ret.Get(0).(func([]byte) crypto.PrivateKey); ok { + r0 = returnFunc(bytes) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.PrivateKey) + } + } + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(bytes) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// signer_generatePrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'generatePrivateKey' +type signer_generatePrivateKey_Call struct { + *mock.Call +} + +// generatePrivateKey is a helper method to define mock.On call +// - bytes []byte +func (_e *signer_Expecter) generatePrivateKey(bytes interface{}) *signer_generatePrivateKey_Call { + return &signer_generatePrivateKey_Call{Call: _e.mock.On("generatePrivateKey", bytes)} +} + +func (_c *signer_generatePrivateKey_Call) Run(run func(bytes []byte)) *signer_generatePrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *signer_generatePrivateKey_Call) Return(privateKey crypto.PrivateKey, err error) *signer_generatePrivateKey_Call { + _c.Call.Return(privateKey, err) + return _c +} + +func (_c *signer_generatePrivateKey_Call) RunAndReturn(run func(bytes []byte) (crypto.PrivateKey, error)) *signer_generatePrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// NewPrivateKey creates a new instance of PrivateKey. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPrivateKey(t interface { + mock.TestingT + Cleanup(func()) +}) *PrivateKey { + mock := &PrivateKey{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// PrivateKey is an autogenerated mock type for the PrivateKey type +type PrivateKey struct { + mock.Mock +} + +type PrivateKey_Expecter struct { + mock *mock.Mock +} + +func (_m *PrivateKey) EXPECT() *PrivateKey_Expecter { + return &PrivateKey_Expecter{mock: &_m.Mock} +} + +// Algorithm provides a mock function for the type PrivateKey +func (_mock *PrivateKey) Algorithm() crypto.SigningAlgorithm { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Algorithm") + } + + var r0 crypto.SigningAlgorithm + if returnFunc, ok := ret.Get(0).(func() crypto.SigningAlgorithm); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(crypto.SigningAlgorithm) + } + return r0 +} + +// PrivateKey_Algorithm_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Algorithm' +type PrivateKey_Algorithm_Call struct { + *mock.Call +} + +// Algorithm is a helper method to define mock.On call +func (_e *PrivateKey_Expecter) Algorithm() *PrivateKey_Algorithm_Call { + return &PrivateKey_Algorithm_Call{Call: _e.mock.On("Algorithm")} +} + +func (_c *PrivateKey_Algorithm_Call) Run(run func()) *PrivateKey_Algorithm_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PrivateKey_Algorithm_Call) Return(signingAlgorithm crypto.SigningAlgorithm) *PrivateKey_Algorithm_Call { + _c.Call.Return(signingAlgorithm) + return _c +} + +func (_c *PrivateKey_Algorithm_Call) RunAndReturn(run func() crypto.SigningAlgorithm) *PrivateKey_Algorithm_Call { + _c.Call.Return(run) + return _c +} + +// Encode provides a mock function for the type PrivateKey +func (_mock *PrivateKey) Encode() []byte { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Encode") + } + + var r0 []byte + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + return r0 +} + +// PrivateKey_Encode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Encode' +type PrivateKey_Encode_Call struct { + *mock.Call +} + +// Encode is a helper method to define mock.On call +func (_e *PrivateKey_Expecter) Encode() *PrivateKey_Encode_Call { + return &PrivateKey_Encode_Call{Call: _e.mock.On("Encode")} +} + +func (_c *PrivateKey_Encode_Call) Run(run func()) *PrivateKey_Encode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PrivateKey_Encode_Call) Return(bytes []byte) *PrivateKey_Encode_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *PrivateKey_Encode_Call) RunAndReturn(run func() []byte) *PrivateKey_Encode_Call { + _c.Call.Return(run) + return _c +} + +// Equals provides a mock function for the type PrivateKey +func (_mock *PrivateKey) Equals(privateKey crypto.PrivateKey) bool { + ret := _mock.Called(privateKey) + + if len(ret) == 0 { + panic("no return value specified for Equals") + } + + var r0 bool + if returnFunc, ok := ret.Get(0).(func(crypto.PrivateKey) bool); ok { + r0 = returnFunc(privateKey) + } else { + r0 = ret.Get(0).(bool) + } + return r0 +} + +// PrivateKey_Equals_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Equals' +type PrivateKey_Equals_Call struct { + *mock.Call +} + +// Equals is a helper method to define mock.On call +// - privateKey crypto.PrivateKey +func (_e *PrivateKey_Expecter) Equals(privateKey interface{}) *PrivateKey_Equals_Call { + return &PrivateKey_Equals_Call{Call: _e.mock.On("Equals", privateKey)} +} + +func (_c *PrivateKey_Equals_Call) Run(run func(privateKey crypto.PrivateKey)) *PrivateKey_Equals_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 crypto.PrivateKey + if args[0] != nil { + arg0 = args[0].(crypto.PrivateKey) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PrivateKey_Equals_Call) Return(b bool) *PrivateKey_Equals_Call { + _c.Call.Return(b) + return _c +} + +func (_c *PrivateKey_Equals_Call) RunAndReturn(run func(privateKey crypto.PrivateKey) bool) *PrivateKey_Equals_Call { + _c.Call.Return(run) + return _c +} + +// PublicKey provides a mock function for the type PrivateKey +func (_mock *PrivateKey) PublicKey() crypto.PublicKey { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for PublicKey") + } + + var r0 crypto.PublicKey + if returnFunc, ok := ret.Get(0).(func() crypto.PublicKey); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.PublicKey) + } + } + return r0 +} + +// PrivateKey_PublicKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PublicKey' +type PrivateKey_PublicKey_Call struct { + *mock.Call +} + +// PublicKey is a helper method to define mock.On call +func (_e *PrivateKey_Expecter) PublicKey() *PrivateKey_PublicKey_Call { + return &PrivateKey_PublicKey_Call{Call: _e.mock.On("PublicKey")} +} + +func (_c *PrivateKey_PublicKey_Call) Run(run func()) *PrivateKey_PublicKey_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PrivateKey_PublicKey_Call) Return(publicKey crypto.PublicKey) *PrivateKey_PublicKey_Call { + _c.Call.Return(publicKey) + return _c +} + +func (_c *PrivateKey_PublicKey_Call) RunAndReturn(run func() crypto.PublicKey) *PrivateKey_PublicKey_Call { + _c.Call.Return(run) + return _c +} + +// Sign provides a mock function for the type PrivateKey +func (_mock *PrivateKey) Sign(bytes []byte, hasher hash.Hasher) (crypto.Signature, error) { + ret := _mock.Called(bytes, hasher) + + if len(ret) == 0 { + panic("no return value specified for Sign") + } + + var r0 crypto.Signature + var r1 error + if returnFunc, ok := ret.Get(0).(func([]byte, hash.Hasher) (crypto.Signature, error)); ok { + return returnFunc(bytes, hasher) + } + if returnFunc, ok := ret.Get(0).(func([]byte, hash.Hasher) crypto.Signature); ok { + r0 = returnFunc(bytes, hasher) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.Signature) + } + } + if returnFunc, ok := ret.Get(1).(func([]byte, hash.Hasher) error); ok { + r1 = returnFunc(bytes, hasher) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PrivateKey_Sign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sign' +type PrivateKey_Sign_Call struct { + *mock.Call +} + +// Sign is a helper method to define mock.On call +// - bytes []byte +// - hasher hash.Hasher +func (_e *PrivateKey_Expecter) Sign(bytes interface{}, hasher interface{}) *PrivateKey_Sign_Call { + return &PrivateKey_Sign_Call{Call: _e.mock.On("Sign", bytes, hasher)} +} + +func (_c *PrivateKey_Sign_Call) Run(run func(bytes []byte, hasher hash.Hasher)) *PrivateKey_Sign_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 hash.Hasher + if args[1] != nil { + arg1 = args[1].(hash.Hasher) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PrivateKey_Sign_Call) Return(signature crypto.Signature, err error) *PrivateKey_Sign_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *PrivateKey_Sign_Call) RunAndReturn(run func(bytes []byte, hasher hash.Hasher) (crypto.Signature, error)) *PrivateKey_Sign_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type PrivateKey +func (_mock *PrivateKey) Size() int { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Size") + } + + var r0 int + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(int) + } + return r0 +} + +// PrivateKey_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type PrivateKey_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *PrivateKey_Expecter) Size() *PrivateKey_Size_Call { + return &PrivateKey_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *PrivateKey_Size_Call) Run(run func()) *PrivateKey_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PrivateKey_Size_Call) Return(n int) *PrivateKey_Size_Call { + _c.Call.Return(n) + return _c +} + +func (_c *PrivateKey_Size_Call) RunAndReturn(run func() int) *PrivateKey_Size_Call { + _c.Call.Return(run) + return _c +} + +// String provides a mock function for the type PrivateKey +func (_mock *PrivateKey) String() string { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for String") + } + + var r0 string + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(string) + } + return r0 +} + +// PrivateKey_String_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'String' +type PrivateKey_String_Call struct { + *mock.Call +} + +// String is a helper method to define mock.On call +func (_e *PrivateKey_Expecter) String() *PrivateKey_String_Call { + return &PrivateKey_String_Call{Call: _e.mock.On("String")} +} + +func (_c *PrivateKey_String_Call) Run(run func()) *PrivateKey_String_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PrivateKey_String_Call) Return(s string) *PrivateKey_String_Call { + _c.Call.Return(s) + return _c +} + +func (_c *PrivateKey_String_Call) RunAndReturn(run func() string) *PrivateKey_String_Call { + _c.Call.Return(run) + return _c +} + +// NewPublicKey creates a new instance of PublicKey. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPublicKey(t interface { + mock.TestingT + Cleanup(func()) +}) *PublicKey { + mock := &PublicKey{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// PublicKey is an autogenerated mock type for the PublicKey type +type PublicKey struct { + mock.Mock +} + +type PublicKey_Expecter struct { + mock *mock.Mock +} + +func (_m *PublicKey) EXPECT() *PublicKey_Expecter { + return &PublicKey_Expecter{mock: &_m.Mock} +} + +// Algorithm provides a mock function for the type PublicKey +func (_mock *PublicKey) Algorithm() crypto.SigningAlgorithm { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Algorithm") + } + + var r0 crypto.SigningAlgorithm + if returnFunc, ok := ret.Get(0).(func() crypto.SigningAlgorithm); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(crypto.SigningAlgorithm) + } + return r0 +} + +// PublicKey_Algorithm_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Algorithm' +type PublicKey_Algorithm_Call struct { + *mock.Call +} + +// Algorithm is a helper method to define mock.On call +func (_e *PublicKey_Expecter) Algorithm() *PublicKey_Algorithm_Call { + return &PublicKey_Algorithm_Call{Call: _e.mock.On("Algorithm")} +} + +func (_c *PublicKey_Algorithm_Call) Run(run func()) *PublicKey_Algorithm_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PublicKey_Algorithm_Call) Return(signingAlgorithm crypto.SigningAlgorithm) *PublicKey_Algorithm_Call { + _c.Call.Return(signingAlgorithm) + return _c +} + +func (_c *PublicKey_Algorithm_Call) RunAndReturn(run func() crypto.SigningAlgorithm) *PublicKey_Algorithm_Call { + _c.Call.Return(run) + return _c +} + +// Encode provides a mock function for the type PublicKey +func (_mock *PublicKey) Encode() []byte { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Encode") + } + + var r0 []byte + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + return r0 +} + +// PublicKey_Encode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Encode' +type PublicKey_Encode_Call struct { + *mock.Call +} + +// Encode is a helper method to define mock.On call +func (_e *PublicKey_Expecter) Encode() *PublicKey_Encode_Call { + return &PublicKey_Encode_Call{Call: _e.mock.On("Encode")} +} + +func (_c *PublicKey_Encode_Call) Run(run func()) *PublicKey_Encode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PublicKey_Encode_Call) Return(bytes []byte) *PublicKey_Encode_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *PublicKey_Encode_Call) RunAndReturn(run func() []byte) *PublicKey_Encode_Call { + _c.Call.Return(run) + return _c +} + +// EncodeCompressed provides a mock function for the type PublicKey +func (_mock *PublicKey) EncodeCompressed() []byte { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for EncodeCompressed") + } + + var r0 []byte + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + return r0 +} + +// PublicKey_EncodeCompressed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EncodeCompressed' +type PublicKey_EncodeCompressed_Call struct { + *mock.Call +} + +// EncodeCompressed is a helper method to define mock.On call +func (_e *PublicKey_Expecter) EncodeCompressed() *PublicKey_EncodeCompressed_Call { + return &PublicKey_EncodeCompressed_Call{Call: _e.mock.On("EncodeCompressed")} +} + +func (_c *PublicKey_EncodeCompressed_Call) Run(run func()) *PublicKey_EncodeCompressed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PublicKey_EncodeCompressed_Call) Return(bytes []byte) *PublicKey_EncodeCompressed_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *PublicKey_EncodeCompressed_Call) RunAndReturn(run func() []byte) *PublicKey_EncodeCompressed_Call { + _c.Call.Return(run) + return _c +} + +// Equals provides a mock function for the type PublicKey +func (_mock *PublicKey) Equals(publicKey crypto.PublicKey) bool { + ret := _mock.Called(publicKey) + + if len(ret) == 0 { + panic("no return value specified for Equals") + } + + var r0 bool + if returnFunc, ok := ret.Get(0).(func(crypto.PublicKey) bool); ok { + r0 = returnFunc(publicKey) + } else { + r0 = ret.Get(0).(bool) + } + return r0 +} + +// PublicKey_Equals_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Equals' +type PublicKey_Equals_Call struct { + *mock.Call +} + +// Equals is a helper method to define mock.On call +// - publicKey crypto.PublicKey +func (_e *PublicKey_Expecter) Equals(publicKey interface{}) *PublicKey_Equals_Call { + return &PublicKey_Equals_Call{Call: _e.mock.On("Equals", publicKey)} +} + +func (_c *PublicKey_Equals_Call) Run(run func(publicKey crypto.PublicKey)) *PublicKey_Equals_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 crypto.PublicKey + if args[0] != nil { + arg0 = args[0].(crypto.PublicKey) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PublicKey_Equals_Call) Return(b bool) *PublicKey_Equals_Call { + _c.Call.Return(b) + return _c +} + +func (_c *PublicKey_Equals_Call) RunAndReturn(run func(publicKey crypto.PublicKey) bool) *PublicKey_Equals_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type PublicKey +func (_mock *PublicKey) Size() int { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Size") + } + + var r0 int + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(int) + } + return r0 +} + +// PublicKey_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type PublicKey_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *PublicKey_Expecter) Size() *PublicKey_Size_Call { + return &PublicKey_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *PublicKey_Size_Call) Run(run func()) *PublicKey_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PublicKey_Size_Call) Return(n int) *PublicKey_Size_Call { + _c.Call.Return(n) + return _c +} + +func (_c *PublicKey_Size_Call) RunAndReturn(run func() int) *PublicKey_Size_Call { + _c.Call.Return(run) + return _c +} + +// String provides a mock function for the type PublicKey +func (_mock *PublicKey) String() string { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for String") + } + + var r0 string + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(string) + } + return r0 +} + +// PublicKey_String_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'String' +type PublicKey_String_Call struct { + *mock.Call +} + +// String is a helper method to define mock.On call +func (_e *PublicKey_Expecter) String() *PublicKey_String_Call { + return &PublicKey_String_Call{Call: _e.mock.On("String")} +} + +func (_c *PublicKey_String_Call) Run(run func()) *PublicKey_String_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PublicKey_String_Call) Return(s string) *PublicKey_String_Call { + _c.Call.Return(s) + return _c +} + +func (_c *PublicKey_String_Call) RunAndReturn(run func() string) *PublicKey_String_Call { + _c.Call.Return(run) + return _c +} + +// Verify provides a mock function for the type PublicKey +func (_mock *PublicKey) Verify(signature crypto.Signature, bytes []byte, hasher hash.Hasher) (bool, error) { + ret := _mock.Called(signature, bytes, hasher) + + if len(ret) == 0 { + panic("no return value specified for Verify") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(crypto.Signature, []byte, hash.Hasher) (bool, error)); ok { + return returnFunc(signature, bytes, hasher) + } + if returnFunc, ok := ret.Get(0).(func(crypto.Signature, []byte, hash.Hasher) bool); ok { + r0 = returnFunc(signature, bytes, hasher) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(crypto.Signature, []byte, hash.Hasher) error); ok { + r1 = returnFunc(signature, bytes, hasher) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// PublicKey_Verify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Verify' +type PublicKey_Verify_Call struct { + *mock.Call +} + +// Verify is a helper method to define mock.On call +// - signature crypto.Signature +// - bytes []byte +// - hasher hash.Hasher +func (_e *PublicKey_Expecter) Verify(signature interface{}, bytes interface{}, hasher interface{}) *PublicKey_Verify_Call { + return &PublicKey_Verify_Call{Call: _e.mock.On("Verify", signature, bytes, hasher)} +} + +func (_c *PublicKey_Verify_Call) Run(run func(signature crypto.Signature, bytes []byte, hasher hash.Hasher)) *PublicKey_Verify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 crypto.Signature + if args[0] != nil { + arg0 = args[0].(crypto.Signature) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 hash.Hasher + if args[2] != nil { + arg2 = args[2].(hash.Hasher) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *PublicKey_Verify_Call) Return(b bool, err error) *PublicKey_Verify_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *PublicKey_Verify_Call) RunAndReturn(run func(signature crypto.Signature, bytes []byte, hasher hash.Hasher) (bool, error)) *PublicKey_Verify_Call { + _c.Call.Return(run) + return _c +} + +// NewThresholdSignatureInspector creates a new instance of ThresholdSignatureInspector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewThresholdSignatureInspector(t interface { + mock.TestingT + Cleanup(func()) +}) *ThresholdSignatureInspector { + mock := &ThresholdSignatureInspector{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ThresholdSignatureInspector is an autogenerated mock type for the ThresholdSignatureInspector type +type ThresholdSignatureInspector struct { + mock.Mock +} + +type ThresholdSignatureInspector_Expecter struct { + mock *mock.Mock +} + +func (_m *ThresholdSignatureInspector) EXPECT() *ThresholdSignatureInspector_Expecter { + return &ThresholdSignatureInspector_Expecter{mock: &_m.Mock} +} + +// EnoughShares provides a mock function for the type ThresholdSignatureInspector +func (_mock *ThresholdSignatureInspector) EnoughShares() bool { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for EnoughShares") + } + + var r0 bool + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(bool) + } + return r0 +} + +// ThresholdSignatureInspector_EnoughShares_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EnoughShares' +type ThresholdSignatureInspector_EnoughShares_Call struct { + *mock.Call +} + +// EnoughShares is a helper method to define mock.On call +func (_e *ThresholdSignatureInspector_Expecter) EnoughShares() *ThresholdSignatureInspector_EnoughShares_Call { + return &ThresholdSignatureInspector_EnoughShares_Call{Call: _e.mock.On("EnoughShares")} +} + +func (_c *ThresholdSignatureInspector_EnoughShares_Call) Run(run func()) *ThresholdSignatureInspector_EnoughShares_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ThresholdSignatureInspector_EnoughShares_Call) Return(b bool) *ThresholdSignatureInspector_EnoughShares_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ThresholdSignatureInspector_EnoughShares_Call) RunAndReturn(run func() bool) *ThresholdSignatureInspector_EnoughShares_Call { + _c.Call.Return(run) + return _c +} + +// HasShare provides a mock function for the type ThresholdSignatureInspector +func (_mock *ThresholdSignatureInspector) HasShare(index int) (bool, error) { + ret := _mock.Called(index) + + if len(ret) == 0 { + panic("no return value specified for HasShare") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(int) (bool, error)); ok { + return returnFunc(index) + } + if returnFunc, ok := ret.Get(0).(func(int) bool); ok { + r0 = returnFunc(index) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int) error); ok { + r1 = returnFunc(index) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureInspector_HasShare_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasShare' +type ThresholdSignatureInspector_HasShare_Call struct { + *mock.Call +} + +// HasShare is a helper method to define mock.On call +// - index int +func (_e *ThresholdSignatureInspector_Expecter) HasShare(index interface{}) *ThresholdSignatureInspector_HasShare_Call { + return &ThresholdSignatureInspector_HasShare_Call{Call: _e.mock.On("HasShare", index)} +} + +func (_c *ThresholdSignatureInspector_HasShare_Call) Run(run func(index int)) *ThresholdSignatureInspector_HasShare_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ThresholdSignatureInspector_HasShare_Call) Return(b bool, err error) *ThresholdSignatureInspector_HasShare_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureInspector_HasShare_Call) RunAndReturn(run func(index int) (bool, error)) *ThresholdSignatureInspector_HasShare_Call { + _c.Call.Return(run) + return _c +} + +// ThresholdSignature provides a mock function for the type ThresholdSignatureInspector +func (_mock *ThresholdSignatureInspector) ThresholdSignature() (crypto.Signature, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for ThresholdSignature") + } + + var r0 crypto.Signature + var r1 error + if returnFunc, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() crypto.Signature); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.Signature) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureInspector_ThresholdSignature_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ThresholdSignature' +type ThresholdSignatureInspector_ThresholdSignature_Call struct { + *mock.Call +} + +// ThresholdSignature is a helper method to define mock.On call +func (_e *ThresholdSignatureInspector_Expecter) ThresholdSignature() *ThresholdSignatureInspector_ThresholdSignature_Call { + return &ThresholdSignatureInspector_ThresholdSignature_Call{Call: _e.mock.On("ThresholdSignature")} +} + +func (_c *ThresholdSignatureInspector_ThresholdSignature_Call) Run(run func()) *ThresholdSignatureInspector_ThresholdSignature_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ThresholdSignatureInspector_ThresholdSignature_Call) Return(signature crypto.Signature, err error) *ThresholdSignatureInspector_ThresholdSignature_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *ThresholdSignatureInspector_ThresholdSignature_Call) RunAndReturn(run func() (crypto.Signature, error)) *ThresholdSignatureInspector_ThresholdSignature_Call { + _c.Call.Return(run) + return _c +} + +// TrustedAdd provides a mock function for the type ThresholdSignatureInspector +func (_mock *ThresholdSignatureInspector) TrustedAdd(index int, share crypto.Signature) (bool, error) { + ret := _mock.Called(index, share) + + if len(ret) == 0 { + panic("no return value specified for TrustedAdd") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { + return returnFunc(index, share) + } + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { + r0 = returnFunc(index, share) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { + r1 = returnFunc(index, share) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureInspector_TrustedAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TrustedAdd' +type ThresholdSignatureInspector_TrustedAdd_Call struct { + *mock.Call +} + +// TrustedAdd is a helper method to define mock.On call +// - index int +// - share crypto.Signature +func (_e *ThresholdSignatureInspector_Expecter) TrustedAdd(index interface{}, share interface{}) *ThresholdSignatureInspector_TrustedAdd_Call { + return &ThresholdSignatureInspector_TrustedAdd_Call{Call: _e.mock.On("TrustedAdd", index, share)} +} + +func (_c *ThresholdSignatureInspector_TrustedAdd_Call) Run(run func(index int, share crypto.Signature)) *ThresholdSignatureInspector_TrustedAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ThresholdSignatureInspector_TrustedAdd_Call) Return(b bool, err error) *ThresholdSignatureInspector_TrustedAdd_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureInspector_TrustedAdd_Call) RunAndReturn(run func(index int, share crypto.Signature) (bool, error)) *ThresholdSignatureInspector_TrustedAdd_Call { + _c.Call.Return(run) + return _c +} + +// VerifyAndAdd provides a mock function for the type ThresholdSignatureInspector +func (_mock *ThresholdSignatureInspector) VerifyAndAdd(index int, share crypto.Signature) (bool, bool, error) { + ret := _mock.Called(index, share) + + if len(ret) == 0 { + panic("no return value specified for VerifyAndAdd") + } + + var r0 bool + var r1 bool + var r2 error + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) (bool, bool, error)); ok { + return returnFunc(index, share) + } + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { + r0 = returnFunc(index, share) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int, crypto.Signature) bool); ok { + r1 = returnFunc(index, share) + } else { + r1 = ret.Get(1).(bool) + } + if returnFunc, ok := ret.Get(2).(func(int, crypto.Signature) error); ok { + r2 = returnFunc(index, share) + } else { + r2 = ret.Error(2) + } + return r0, r1, r2 +} + +// ThresholdSignatureInspector_VerifyAndAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyAndAdd' +type ThresholdSignatureInspector_VerifyAndAdd_Call struct { + *mock.Call +} + +// VerifyAndAdd is a helper method to define mock.On call +// - index int +// - share crypto.Signature +func (_e *ThresholdSignatureInspector_Expecter) VerifyAndAdd(index interface{}, share interface{}) *ThresholdSignatureInspector_VerifyAndAdd_Call { + return &ThresholdSignatureInspector_VerifyAndAdd_Call{Call: _e.mock.On("VerifyAndAdd", index, share)} +} + +func (_c *ThresholdSignatureInspector_VerifyAndAdd_Call) Run(run func(index int, share crypto.Signature)) *ThresholdSignatureInspector_VerifyAndAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ThresholdSignatureInspector_VerifyAndAdd_Call) Return(b bool, b1 bool, err error) *ThresholdSignatureInspector_VerifyAndAdd_Call { + _c.Call.Return(b, b1, err) + return _c +} + +func (_c *ThresholdSignatureInspector_VerifyAndAdd_Call) RunAndReturn(run func(index int, share crypto.Signature) (bool, bool, error)) *ThresholdSignatureInspector_VerifyAndAdd_Call { + _c.Call.Return(run) + return _c +} + +// VerifyShare provides a mock function for the type ThresholdSignatureInspector +func (_mock *ThresholdSignatureInspector) VerifyShare(index int, share crypto.Signature) (bool, error) { + ret := _mock.Called(index, share) + + if len(ret) == 0 { + panic("no return value specified for VerifyShare") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { + return returnFunc(index, share) + } + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { + r0 = returnFunc(index, share) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { + r1 = returnFunc(index, share) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureInspector_VerifyShare_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyShare' +type ThresholdSignatureInspector_VerifyShare_Call struct { + *mock.Call +} + +// VerifyShare is a helper method to define mock.On call +// - index int +// - share crypto.Signature +func (_e *ThresholdSignatureInspector_Expecter) VerifyShare(index interface{}, share interface{}) *ThresholdSignatureInspector_VerifyShare_Call { + return &ThresholdSignatureInspector_VerifyShare_Call{Call: _e.mock.On("VerifyShare", index, share)} +} + +func (_c *ThresholdSignatureInspector_VerifyShare_Call) Run(run func(index int, share crypto.Signature)) *ThresholdSignatureInspector_VerifyShare_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ThresholdSignatureInspector_VerifyShare_Call) Return(b bool, err error) *ThresholdSignatureInspector_VerifyShare_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureInspector_VerifyShare_Call) RunAndReturn(run func(index int, share crypto.Signature) (bool, error)) *ThresholdSignatureInspector_VerifyShare_Call { + _c.Call.Return(run) + return _c +} + +// VerifyThresholdSignature provides a mock function for the type ThresholdSignatureInspector +func (_mock *ThresholdSignatureInspector) VerifyThresholdSignature(thresholdSignature crypto.Signature) (bool, error) { + ret := _mock.Called(thresholdSignature) + + if len(ret) == 0 { + panic("no return value specified for VerifyThresholdSignature") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(crypto.Signature) (bool, error)); ok { + return returnFunc(thresholdSignature) + } + if returnFunc, ok := ret.Get(0).(func(crypto.Signature) bool); ok { + r0 = returnFunc(thresholdSignature) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(crypto.Signature) error); ok { + r1 = returnFunc(thresholdSignature) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureInspector_VerifyThresholdSignature_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyThresholdSignature' +type ThresholdSignatureInspector_VerifyThresholdSignature_Call struct { + *mock.Call +} + +// VerifyThresholdSignature is a helper method to define mock.On call +// - thresholdSignature crypto.Signature +func (_e *ThresholdSignatureInspector_Expecter) VerifyThresholdSignature(thresholdSignature interface{}) *ThresholdSignatureInspector_VerifyThresholdSignature_Call { + return &ThresholdSignatureInspector_VerifyThresholdSignature_Call{Call: _e.mock.On("VerifyThresholdSignature", thresholdSignature)} +} + +func (_c *ThresholdSignatureInspector_VerifyThresholdSignature_Call) Run(run func(thresholdSignature crypto.Signature)) *ThresholdSignatureInspector_VerifyThresholdSignature_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 crypto.Signature + if args[0] != nil { + arg0 = args[0].(crypto.Signature) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ThresholdSignatureInspector_VerifyThresholdSignature_Call) Return(b bool, err error) *ThresholdSignatureInspector_VerifyThresholdSignature_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureInspector_VerifyThresholdSignature_Call) RunAndReturn(run func(thresholdSignature crypto.Signature) (bool, error)) *ThresholdSignatureInspector_VerifyThresholdSignature_Call { + _c.Call.Return(run) + return _c +} + +// NewThresholdSignatureParticipant creates a new instance of ThresholdSignatureParticipant. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewThresholdSignatureParticipant(t interface { + mock.TestingT + Cleanup(func()) +}) *ThresholdSignatureParticipant { + mock := &ThresholdSignatureParticipant{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ThresholdSignatureParticipant is an autogenerated mock type for the ThresholdSignatureParticipant type +type ThresholdSignatureParticipant struct { + mock.Mock +} + +type ThresholdSignatureParticipant_Expecter struct { + mock *mock.Mock +} + +func (_m *ThresholdSignatureParticipant) EXPECT() *ThresholdSignatureParticipant_Expecter { + return &ThresholdSignatureParticipant_Expecter{mock: &_m.Mock} +} + +// EnoughShares provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) EnoughShares() bool { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for EnoughShares") + } + + var r0 bool + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(bool) + } + return r0 +} + +// ThresholdSignatureParticipant_EnoughShares_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EnoughShares' +type ThresholdSignatureParticipant_EnoughShares_Call struct { + *mock.Call +} + +// EnoughShares is a helper method to define mock.On call +func (_e *ThresholdSignatureParticipant_Expecter) EnoughShares() *ThresholdSignatureParticipant_EnoughShares_Call { + return &ThresholdSignatureParticipant_EnoughShares_Call{Call: _e.mock.On("EnoughShares")} +} + +func (_c *ThresholdSignatureParticipant_EnoughShares_Call) Run(run func()) *ThresholdSignatureParticipant_EnoughShares_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_EnoughShares_Call) Return(b bool) *ThresholdSignatureParticipant_EnoughShares_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ThresholdSignatureParticipant_EnoughShares_Call) RunAndReturn(run func() bool) *ThresholdSignatureParticipant_EnoughShares_Call { + _c.Call.Return(run) + return _c +} + +// HasShare provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) HasShare(index int) (bool, error) { + ret := _mock.Called(index) + + if len(ret) == 0 { + panic("no return value specified for HasShare") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(int) (bool, error)); ok { + return returnFunc(index) + } + if returnFunc, ok := ret.Get(0).(func(int) bool); ok { + r0 = returnFunc(index) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int) error); ok { + r1 = returnFunc(index) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureParticipant_HasShare_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasShare' +type ThresholdSignatureParticipant_HasShare_Call struct { + *mock.Call +} + +// HasShare is a helper method to define mock.On call +// - index int +func (_e *ThresholdSignatureParticipant_Expecter) HasShare(index interface{}) *ThresholdSignatureParticipant_HasShare_Call { + return &ThresholdSignatureParticipant_HasShare_Call{Call: _e.mock.On("HasShare", index)} +} + +func (_c *ThresholdSignatureParticipant_HasShare_Call) Run(run func(index int)) *ThresholdSignatureParticipant_HasShare_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_HasShare_Call) Return(b bool, err error) *ThresholdSignatureParticipant_HasShare_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureParticipant_HasShare_Call) RunAndReturn(run func(index int) (bool, error)) *ThresholdSignatureParticipant_HasShare_Call { + _c.Call.Return(run) + return _c +} + +// SignShare provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) SignShare() (crypto.Signature, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for SignShare") + } + + var r0 crypto.Signature + var r1 error + if returnFunc, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() crypto.Signature); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.Signature) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureParticipant_SignShare_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SignShare' +type ThresholdSignatureParticipant_SignShare_Call struct { + *mock.Call +} + +// SignShare is a helper method to define mock.On call +func (_e *ThresholdSignatureParticipant_Expecter) SignShare() *ThresholdSignatureParticipant_SignShare_Call { + return &ThresholdSignatureParticipant_SignShare_Call{Call: _e.mock.On("SignShare")} +} + +func (_c *ThresholdSignatureParticipant_SignShare_Call) Run(run func()) *ThresholdSignatureParticipant_SignShare_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_SignShare_Call) Return(signature crypto.Signature, err error) *ThresholdSignatureParticipant_SignShare_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *ThresholdSignatureParticipant_SignShare_Call) RunAndReturn(run func() (crypto.Signature, error)) *ThresholdSignatureParticipant_SignShare_Call { + _c.Call.Return(run) + return _c +} + +// ThresholdSignature provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) ThresholdSignature() (crypto.Signature, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for ThresholdSignature") + } + + var r0 crypto.Signature + var r1 error + if returnFunc, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() crypto.Signature); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(crypto.Signature) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureParticipant_ThresholdSignature_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ThresholdSignature' +type ThresholdSignatureParticipant_ThresholdSignature_Call struct { + *mock.Call +} + +// ThresholdSignature is a helper method to define mock.On call +func (_e *ThresholdSignatureParticipant_Expecter) ThresholdSignature() *ThresholdSignatureParticipant_ThresholdSignature_Call { + return &ThresholdSignatureParticipant_ThresholdSignature_Call{Call: _e.mock.On("ThresholdSignature")} +} + +func (_c *ThresholdSignatureParticipant_ThresholdSignature_Call) Run(run func()) *ThresholdSignatureParticipant_ThresholdSignature_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_ThresholdSignature_Call) Return(signature crypto.Signature, err error) *ThresholdSignatureParticipant_ThresholdSignature_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *ThresholdSignatureParticipant_ThresholdSignature_Call) RunAndReturn(run func() (crypto.Signature, error)) *ThresholdSignatureParticipant_ThresholdSignature_Call { + _c.Call.Return(run) + return _c +} + +// TrustedAdd provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) TrustedAdd(index int, share crypto.Signature) (bool, error) { + ret := _mock.Called(index, share) + + if len(ret) == 0 { + panic("no return value specified for TrustedAdd") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { + return returnFunc(index, share) + } + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { + r0 = returnFunc(index, share) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { + r1 = returnFunc(index, share) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureParticipant_TrustedAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TrustedAdd' +type ThresholdSignatureParticipant_TrustedAdd_Call struct { + *mock.Call +} + +// TrustedAdd is a helper method to define mock.On call +// - index int +// - share crypto.Signature +func (_e *ThresholdSignatureParticipant_Expecter) TrustedAdd(index interface{}, share interface{}) *ThresholdSignatureParticipant_TrustedAdd_Call { + return &ThresholdSignatureParticipant_TrustedAdd_Call{Call: _e.mock.On("TrustedAdd", index, share)} +} + +func (_c *ThresholdSignatureParticipant_TrustedAdd_Call) Run(run func(index int, share crypto.Signature)) *ThresholdSignatureParticipant_TrustedAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_TrustedAdd_Call) Return(b bool, err error) *ThresholdSignatureParticipant_TrustedAdd_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureParticipant_TrustedAdd_Call) RunAndReturn(run func(index int, share crypto.Signature) (bool, error)) *ThresholdSignatureParticipant_TrustedAdd_Call { + _c.Call.Return(run) + return _c +} + +// VerifyAndAdd provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) VerifyAndAdd(index int, share crypto.Signature) (bool, bool, error) { + ret := _mock.Called(index, share) + + if len(ret) == 0 { + panic("no return value specified for VerifyAndAdd") + } + + var r0 bool + var r1 bool + var r2 error + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) (bool, bool, error)); ok { + return returnFunc(index, share) + } + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { + r0 = returnFunc(index, share) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int, crypto.Signature) bool); ok { + r1 = returnFunc(index, share) + } else { + r1 = ret.Get(1).(bool) + } + if returnFunc, ok := ret.Get(2).(func(int, crypto.Signature) error); ok { + r2 = returnFunc(index, share) + } else { + r2 = ret.Error(2) + } + return r0, r1, r2 +} + +// ThresholdSignatureParticipant_VerifyAndAdd_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyAndAdd' +type ThresholdSignatureParticipant_VerifyAndAdd_Call struct { + *mock.Call +} + +// VerifyAndAdd is a helper method to define mock.On call +// - index int +// - share crypto.Signature +func (_e *ThresholdSignatureParticipant_Expecter) VerifyAndAdd(index interface{}, share interface{}) *ThresholdSignatureParticipant_VerifyAndAdd_Call { + return &ThresholdSignatureParticipant_VerifyAndAdd_Call{Call: _e.mock.On("VerifyAndAdd", index, share)} +} + +func (_c *ThresholdSignatureParticipant_VerifyAndAdd_Call) Run(run func(index int, share crypto.Signature)) *ThresholdSignatureParticipant_VerifyAndAdd_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_VerifyAndAdd_Call) Return(b bool, b1 bool, err error) *ThresholdSignatureParticipant_VerifyAndAdd_Call { + _c.Call.Return(b, b1, err) + return _c +} + +func (_c *ThresholdSignatureParticipant_VerifyAndAdd_Call) RunAndReturn(run func(index int, share crypto.Signature) (bool, bool, error)) *ThresholdSignatureParticipant_VerifyAndAdd_Call { + _c.Call.Return(run) + return _c +} + +// VerifyShare provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) VerifyShare(index int, share crypto.Signature) (bool, error) { + ret := _mock.Called(index, share) + + if len(ret) == 0 { + panic("no return value specified for VerifyShare") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { + return returnFunc(index, share) + } + if returnFunc, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { + r0 = returnFunc(index, share) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { + r1 = returnFunc(index, share) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureParticipant_VerifyShare_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyShare' +type ThresholdSignatureParticipant_VerifyShare_Call struct { + *mock.Call +} + +// VerifyShare is a helper method to define mock.On call +// - index int +// - share crypto.Signature +func (_e *ThresholdSignatureParticipant_Expecter) VerifyShare(index interface{}, share interface{}) *ThresholdSignatureParticipant_VerifyShare_Call { + return &ThresholdSignatureParticipant_VerifyShare_Call{Call: _e.mock.On("VerifyShare", index, share)} +} + +func (_c *ThresholdSignatureParticipant_VerifyShare_Call) Run(run func(index int, share crypto.Signature)) *ThresholdSignatureParticipant_VerifyShare_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 crypto.Signature + if args[1] != nil { + arg1 = args[1].(crypto.Signature) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_VerifyShare_Call) Return(b bool, err error) *ThresholdSignatureParticipant_VerifyShare_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureParticipant_VerifyShare_Call) RunAndReturn(run func(index int, share crypto.Signature) (bool, error)) *ThresholdSignatureParticipant_VerifyShare_Call { + _c.Call.Return(run) + return _c +} + +// VerifyThresholdSignature provides a mock function for the type ThresholdSignatureParticipant +func (_mock *ThresholdSignatureParticipant) VerifyThresholdSignature(thresholdSignature crypto.Signature) (bool, error) { + ret := _mock.Called(thresholdSignature) + + if len(ret) == 0 { + panic("no return value specified for VerifyThresholdSignature") + } + + var r0 bool + var r1 error + if returnFunc, ok := ret.Get(0).(func(crypto.Signature) (bool, error)); ok { + return returnFunc(thresholdSignature) + } + if returnFunc, ok := ret.Get(0).(func(crypto.Signature) bool); ok { + r0 = returnFunc(thresholdSignature) + } else { + r0 = ret.Get(0).(bool) + } + if returnFunc, ok := ret.Get(1).(func(crypto.Signature) error); ok { + r1 = returnFunc(thresholdSignature) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ThresholdSignatureParticipant_VerifyThresholdSignature_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyThresholdSignature' +type ThresholdSignatureParticipant_VerifyThresholdSignature_Call struct { + *mock.Call +} + +// VerifyThresholdSignature is a helper method to define mock.On call +// - thresholdSignature crypto.Signature +func (_e *ThresholdSignatureParticipant_Expecter) VerifyThresholdSignature(thresholdSignature interface{}) *ThresholdSignatureParticipant_VerifyThresholdSignature_Call { + return &ThresholdSignatureParticipant_VerifyThresholdSignature_Call{Call: _e.mock.On("VerifyThresholdSignature", thresholdSignature)} +} + +func (_c *ThresholdSignatureParticipant_VerifyThresholdSignature_Call) Run(run func(thresholdSignature crypto.Signature)) *ThresholdSignatureParticipant_VerifyThresholdSignature_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 crypto.Signature + if args[0] != nil { + arg0 = args[0].(crypto.Signature) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ThresholdSignatureParticipant_VerifyThresholdSignature_Call) Return(b bool, err error) *ThresholdSignatureParticipant_VerifyThresholdSignature_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ThresholdSignatureParticipant_VerifyThresholdSignature_Call) RunAndReturn(run func(thresholdSignature crypto.Signature) (bool, error)) *ThresholdSignatureParticipant_VerifyThresholdSignature_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/mock/dht_metrics.go b/module/mock/dht_metrics.go index 7fa90934124..c74f871f6ff 100644 --- a/module/mock/dht_metrics.go +++ b/module/mock/dht_metrics.go @@ -1,23 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// DHTMetrics is an autogenerated mock type for the DHTMetrics type -type DHTMetrics struct { - mock.Mock -} - -// RoutingTablePeerAdded provides a mock function with no fields -func (_m *DHTMetrics) RoutingTablePeerAdded() { - _m.Called() -} - -// RoutingTablePeerRemoved provides a mock function with no fields -func (_m *DHTMetrics) RoutingTablePeerRemoved() { - _m.Called() -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewDHTMetrics creates a new instance of DHTMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -32,3 +21,82 @@ func NewDHTMetrics(t interface { return mock } + +// DHTMetrics is an autogenerated mock type for the DHTMetrics type +type DHTMetrics struct { + mock.Mock +} + +type DHTMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *DHTMetrics) EXPECT() *DHTMetrics_Expecter { + return &DHTMetrics_Expecter{mock: &_m.Mock} +} + +// RoutingTablePeerAdded provides a mock function for the type DHTMetrics +func (_mock *DHTMetrics) RoutingTablePeerAdded() { + _mock.Called() + return +} + +// DHTMetrics_RoutingTablePeerAdded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTablePeerAdded' +type DHTMetrics_RoutingTablePeerAdded_Call struct { + *mock.Call +} + +// RoutingTablePeerAdded is a helper method to define mock.On call +func (_e *DHTMetrics_Expecter) RoutingTablePeerAdded() *DHTMetrics_RoutingTablePeerAdded_Call { + return &DHTMetrics_RoutingTablePeerAdded_Call{Call: _e.mock.On("RoutingTablePeerAdded")} +} + +func (_c *DHTMetrics_RoutingTablePeerAdded_Call) Run(run func()) *DHTMetrics_RoutingTablePeerAdded_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DHTMetrics_RoutingTablePeerAdded_Call) Return() *DHTMetrics_RoutingTablePeerAdded_Call { + _c.Call.Return() + return _c +} + +func (_c *DHTMetrics_RoutingTablePeerAdded_Call) RunAndReturn(run func()) *DHTMetrics_RoutingTablePeerAdded_Call { + _c.Run(run) + return _c +} + +// RoutingTablePeerRemoved provides a mock function for the type DHTMetrics +func (_mock *DHTMetrics) RoutingTablePeerRemoved() { + _mock.Called() + return +} + +// DHTMetrics_RoutingTablePeerRemoved_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTablePeerRemoved' +type DHTMetrics_RoutingTablePeerRemoved_Call struct { + *mock.Call +} + +// RoutingTablePeerRemoved is a helper method to define mock.On call +func (_e *DHTMetrics_Expecter) RoutingTablePeerRemoved() *DHTMetrics_RoutingTablePeerRemoved_Call { + return &DHTMetrics_RoutingTablePeerRemoved_Call{Call: _e.mock.On("RoutingTablePeerRemoved")} +} + +func (_c *DHTMetrics_RoutingTablePeerRemoved_Call) Run(run func()) *DHTMetrics_RoutingTablePeerRemoved_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DHTMetrics_RoutingTablePeerRemoved_Call) Return() *DHTMetrics_RoutingTablePeerRemoved_Call { + _c.Call.Return() + return _c +} + +func (_c *DHTMetrics_RoutingTablePeerRemoved_Call) RunAndReturn(run func()) *DHTMetrics_RoutingTablePeerRemoved_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/dkg_broker.go b/module/mock/dkg_broker.go index 4169ca53452..a00f5f5b45e 100644 --- a/module/mock/dkg_broker.go +++ b/module/mock/dkg_broker.go @@ -1,150 +1,494 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - - messages "github.com/onflow/flow-go/model/messages" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/messages" mock "github.com/stretchr/testify/mock" ) +// NewDKGBroker creates a new instance of DKGBroker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGBroker(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGBroker { + mock := &DKGBroker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKGBroker is an autogenerated mock type for the DKGBroker type type DKGBroker struct { mock.Mock } -// Broadcast provides a mock function with given fields: data -func (_m *DKGBroker) Broadcast(data []byte) { - _m.Called(data) +type DKGBroker_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGBroker) EXPECT() *DKGBroker_Expecter { + return &DKGBroker_Expecter{mock: &_m.Mock} } -// Disqualify provides a mock function with given fields: index, log -func (_m *DKGBroker) Disqualify(index int, log string) { - _m.Called(index, log) +// Broadcast provides a mock function for the type DKGBroker +func (_mock *DKGBroker) Broadcast(data []byte) { + _mock.Called(data) + return } -// FlagMisbehavior provides a mock function with given fields: index, log -func (_m *DKGBroker) FlagMisbehavior(index int, log string) { - _m.Called(index, log) +// DKGBroker_Broadcast_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Broadcast' +type DKGBroker_Broadcast_Call struct { + *mock.Call } -// GetBroadcastMsgCh provides a mock function with no fields -func (_m *DKGBroker) GetBroadcastMsgCh() <-chan messages.BroadcastDKGMessage { - ret := _m.Called() +// Broadcast is a helper method to define mock.On call +// - data []byte +func (_e *DKGBroker_Expecter) Broadcast(data interface{}) *DKGBroker_Broadcast_Call { + return &DKGBroker_Broadcast_Call{Call: _e.mock.On("Broadcast", data)} +} + +func (_c *DKGBroker_Broadcast_Call) Run(run func(data []byte)) *DKGBroker_Broadcast_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGBroker_Broadcast_Call) Return() *DKGBroker_Broadcast_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGBroker_Broadcast_Call) RunAndReturn(run func(data []byte)) *DKGBroker_Broadcast_Call { + _c.Run(run) + return _c +} + +// Disqualify provides a mock function for the type DKGBroker +func (_mock *DKGBroker) Disqualify(index int, log string) { + _mock.Called(index, log) + return +} + +// DKGBroker_Disqualify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Disqualify' +type DKGBroker_Disqualify_Call struct { + *mock.Call +} + +// Disqualify is a helper method to define mock.On call +// - index int +// - log string +func (_e *DKGBroker_Expecter) Disqualify(index interface{}, log interface{}) *DKGBroker_Disqualify_Call { + return &DKGBroker_Disqualify_Call{Call: _e.mock.On("Disqualify", index, log)} +} + +func (_c *DKGBroker_Disqualify_Call) Run(run func(index int, log string)) *DKGBroker_Disqualify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGBroker_Disqualify_Call) Return() *DKGBroker_Disqualify_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGBroker_Disqualify_Call) RunAndReturn(run func(index int, log string)) *DKGBroker_Disqualify_Call { + _c.Run(run) + return _c +} + +// FlagMisbehavior provides a mock function for the type DKGBroker +func (_mock *DKGBroker) FlagMisbehavior(index int, log string) { + _mock.Called(index, log) + return +} + +// DKGBroker_FlagMisbehavior_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FlagMisbehavior' +type DKGBroker_FlagMisbehavior_Call struct { + *mock.Call +} + +// FlagMisbehavior is a helper method to define mock.On call +// - index int +// - log string +func (_e *DKGBroker_Expecter) FlagMisbehavior(index interface{}, log interface{}) *DKGBroker_FlagMisbehavior_Call { + return &DKGBroker_FlagMisbehavior_Call{Call: _e.mock.On("FlagMisbehavior", index, log)} +} + +func (_c *DKGBroker_FlagMisbehavior_Call) Run(run func(index int, log string)) *DKGBroker_FlagMisbehavior_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGBroker_FlagMisbehavior_Call) Return() *DKGBroker_FlagMisbehavior_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGBroker_FlagMisbehavior_Call) RunAndReturn(run func(index int, log string)) *DKGBroker_FlagMisbehavior_Call { + _c.Run(run) + return _c +} + +// GetBroadcastMsgCh provides a mock function for the type DKGBroker +func (_mock *DKGBroker) GetBroadcastMsgCh() <-chan messages.BroadcastDKGMessage { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetBroadcastMsgCh") } var r0 <-chan messages.BroadcastDKGMessage - if rf, ok := ret.Get(0).(func() <-chan messages.BroadcastDKGMessage); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan messages.BroadcastDKGMessage); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan messages.BroadcastDKGMessage) } } - return r0 } -// GetIndex provides a mock function with no fields -func (_m *DKGBroker) GetIndex() int { - ret := _m.Called() +// DKGBroker_GetBroadcastMsgCh_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBroadcastMsgCh' +type DKGBroker_GetBroadcastMsgCh_Call struct { + *mock.Call +} + +// GetBroadcastMsgCh is a helper method to define mock.On call +func (_e *DKGBroker_Expecter) GetBroadcastMsgCh() *DKGBroker_GetBroadcastMsgCh_Call { + return &DKGBroker_GetBroadcastMsgCh_Call{Call: _e.mock.On("GetBroadcastMsgCh")} +} + +func (_c *DKGBroker_GetBroadcastMsgCh_Call) Run(run func()) *DKGBroker_GetBroadcastMsgCh_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGBroker_GetBroadcastMsgCh_Call) Return(broadcastDKGMessageCh <-chan messages.BroadcastDKGMessage) *DKGBroker_GetBroadcastMsgCh_Call { + _c.Call.Return(broadcastDKGMessageCh) + return _c +} + +func (_c *DKGBroker_GetBroadcastMsgCh_Call) RunAndReturn(run func() <-chan messages.BroadcastDKGMessage) *DKGBroker_GetBroadcastMsgCh_Call { + _c.Call.Return(run) + return _c +} + +// GetIndex provides a mock function for the type DKGBroker +func (_mock *DKGBroker) GetIndex() int { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetIndex") } var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(int) } - return r0 } -// GetPrivateMsgCh provides a mock function with no fields -func (_m *DKGBroker) GetPrivateMsgCh() <-chan messages.PrivDKGMessageIn { - ret := _m.Called() +// DKGBroker_GetIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIndex' +type DKGBroker_GetIndex_Call struct { + *mock.Call +} + +// GetIndex is a helper method to define mock.On call +func (_e *DKGBroker_Expecter) GetIndex() *DKGBroker_GetIndex_Call { + return &DKGBroker_GetIndex_Call{Call: _e.mock.On("GetIndex")} +} + +func (_c *DKGBroker_GetIndex_Call) Run(run func()) *DKGBroker_GetIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGBroker_GetIndex_Call) Return(n int) *DKGBroker_GetIndex_Call { + _c.Call.Return(n) + return _c +} + +func (_c *DKGBroker_GetIndex_Call) RunAndReturn(run func() int) *DKGBroker_GetIndex_Call { + _c.Call.Return(run) + return _c +} + +// GetPrivateMsgCh provides a mock function for the type DKGBroker +func (_mock *DKGBroker) GetPrivateMsgCh() <-chan messages.PrivDKGMessageIn { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetPrivateMsgCh") } var r0 <-chan messages.PrivDKGMessageIn - if rf, ok := ret.Get(0).(func() <-chan messages.PrivDKGMessageIn); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan messages.PrivDKGMessageIn); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan messages.PrivDKGMessageIn) } } - return r0 } -// Poll provides a mock function with given fields: referenceBlock -func (_m *DKGBroker) Poll(referenceBlock flow.Identifier) error { - ret := _m.Called(referenceBlock) +// DKGBroker_GetPrivateMsgCh_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPrivateMsgCh' +type DKGBroker_GetPrivateMsgCh_Call struct { + *mock.Call +} + +// GetPrivateMsgCh is a helper method to define mock.On call +func (_e *DKGBroker_Expecter) GetPrivateMsgCh() *DKGBroker_GetPrivateMsgCh_Call { + return &DKGBroker_GetPrivateMsgCh_Call{Call: _e.mock.On("GetPrivateMsgCh")} +} + +func (_c *DKGBroker_GetPrivateMsgCh_Call) Run(run func()) *DKGBroker_GetPrivateMsgCh_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGBroker_GetPrivateMsgCh_Call) Return(privDKGMessageInCh <-chan messages.PrivDKGMessageIn) *DKGBroker_GetPrivateMsgCh_Call { + _c.Call.Return(privDKGMessageInCh) + return _c +} + +func (_c *DKGBroker_GetPrivateMsgCh_Call) RunAndReturn(run func() <-chan messages.PrivDKGMessageIn) *DKGBroker_GetPrivateMsgCh_Call { + _c.Call.Return(run) + return _c +} + +// Poll provides a mock function for the type DKGBroker +func (_mock *DKGBroker) Poll(referenceBlock flow.Identifier) error { + ret := _mock.Called(referenceBlock) if len(ret) == 0 { panic("no return value specified for Poll") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier) error); ok { - r0 = rf(referenceBlock) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) error); ok { + r0 = returnFunc(referenceBlock) } else { r0 = ret.Error(0) } - return r0 } -// PrivateSend provides a mock function with given fields: dest, data -func (_m *DKGBroker) PrivateSend(dest int, data []byte) { - _m.Called(dest, data) +// DKGBroker_Poll_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Poll' +type DKGBroker_Poll_Call struct { + *mock.Call +} + +// Poll is a helper method to define mock.On call +// - referenceBlock flow.Identifier +func (_e *DKGBroker_Expecter) Poll(referenceBlock interface{}) *DKGBroker_Poll_Call { + return &DKGBroker_Poll_Call{Call: _e.mock.On("Poll", referenceBlock)} +} + +func (_c *DKGBroker_Poll_Call) Run(run func(referenceBlock flow.Identifier)) *DKGBroker_Poll_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGBroker_Poll_Call) Return(err error) *DKGBroker_Poll_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGBroker_Poll_Call) RunAndReturn(run func(referenceBlock flow.Identifier) error) *DKGBroker_Poll_Call { + _c.Call.Return(run) + return _c +} + +// PrivateSend provides a mock function for the type DKGBroker +func (_mock *DKGBroker) PrivateSend(dest int, data []byte) { + _mock.Called(dest, data) + return +} + +// DKGBroker_PrivateSend_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PrivateSend' +type DKGBroker_PrivateSend_Call struct { + *mock.Call +} + +// PrivateSend is a helper method to define mock.On call +// - dest int +// - data []byte +func (_e *DKGBroker_Expecter) PrivateSend(dest interface{}, data interface{}) *DKGBroker_PrivateSend_Call { + return &DKGBroker_PrivateSend_Call{Call: _e.mock.On("PrivateSend", dest, data)} +} + +func (_c *DKGBroker_PrivateSend_Call) Run(run func(dest int, data []byte)) *DKGBroker_PrivateSend_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGBroker_PrivateSend_Call) Return() *DKGBroker_PrivateSend_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGBroker_PrivateSend_Call) RunAndReturn(run func(dest int, data []byte)) *DKGBroker_PrivateSend_Call { + _c.Run(run) + return _c +} + +// Shutdown provides a mock function for the type DKGBroker +func (_mock *DKGBroker) Shutdown() { + _mock.Called() + return +} + +// DKGBroker_Shutdown_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Shutdown' +type DKGBroker_Shutdown_Call struct { + *mock.Call } -// Shutdown provides a mock function with no fields -func (_m *DKGBroker) Shutdown() { - _m.Called() +// Shutdown is a helper method to define mock.On call +func (_e *DKGBroker_Expecter) Shutdown() *DKGBroker_Shutdown_Call { + return &DKGBroker_Shutdown_Call{Call: _e.mock.On("Shutdown")} } -// SubmitResult provides a mock function with given fields: _a0, _a1 -func (_m *DKGBroker) SubmitResult(_a0 crypto.PublicKey, _a1 []crypto.PublicKey) error { - ret := _m.Called(_a0, _a1) +func (_c *DKGBroker_Shutdown_Call) Run(run func()) *DKGBroker_Shutdown_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGBroker_Shutdown_Call) Return() *DKGBroker_Shutdown_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGBroker_Shutdown_Call) RunAndReturn(run func()) *DKGBroker_Shutdown_Call { + _c.Run(run) + return _c +} + +// SubmitResult provides a mock function for the type DKGBroker +func (_mock *DKGBroker) SubmitResult(publicKey crypto.PublicKey, publicKeys []crypto.PublicKey) error { + ret := _mock.Called(publicKey, publicKeys) if len(ret) == 0 { panic("no return value specified for SubmitResult") } var r0 error - if rf, ok := ret.Get(0).(func(crypto.PublicKey, []crypto.PublicKey) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(crypto.PublicKey, []crypto.PublicKey) error); ok { + r0 = returnFunc(publicKey, publicKeys) } else { r0 = ret.Error(0) } - return r0 } -// NewDKGBroker creates a new instance of DKGBroker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGBroker(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGBroker { - mock := &DKGBroker{} - mock.Mock.Test(t) +// DKGBroker_SubmitResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitResult' +type DKGBroker_SubmitResult_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubmitResult is a helper method to define mock.On call +// - publicKey crypto.PublicKey +// - publicKeys []crypto.PublicKey +func (_e *DKGBroker_Expecter) SubmitResult(publicKey interface{}, publicKeys interface{}) *DKGBroker_SubmitResult_Call { + return &DKGBroker_SubmitResult_Call{Call: _e.mock.On("SubmitResult", publicKey, publicKeys)} +} - return mock +func (_c *DKGBroker_SubmitResult_Call) Run(run func(publicKey crypto.PublicKey, publicKeys []crypto.PublicKey)) *DKGBroker_SubmitResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 crypto.PublicKey + if args[0] != nil { + arg0 = args[0].(crypto.PublicKey) + } + var arg1 []crypto.PublicKey + if args[1] != nil { + arg1 = args[1].([]crypto.PublicKey) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGBroker_SubmitResult_Call) Return(err error) *DKGBroker_SubmitResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGBroker_SubmitResult_Call) RunAndReturn(run func(publicKey crypto.PublicKey, publicKeys []crypto.PublicKey) error) *DKGBroker_SubmitResult_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/dkg_contract_client.go b/module/mock/dkg_contract_client.go index c6d316476d0..1b1e1db994a 100644 --- a/module/mock/dkg_contract_client.go +++ b/module/mock/dkg_contract_client.go @@ -1,42 +1,97 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - - messages "github.com/onflow/flow-go/model/messages" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/messages" mock "github.com/stretchr/testify/mock" ) +// NewDKGContractClient creates a new instance of DKGContractClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGContractClient(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGContractClient { + mock := &DKGContractClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKGContractClient is an autogenerated mock type for the DKGContractClient type type DKGContractClient struct { mock.Mock } -// Broadcast provides a mock function with given fields: msg -func (_m *DKGContractClient) Broadcast(msg messages.BroadcastDKGMessage) error { - ret := _m.Called(msg) +type DKGContractClient_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGContractClient) EXPECT() *DKGContractClient_Expecter { + return &DKGContractClient_Expecter{mock: &_m.Mock} +} + +// Broadcast provides a mock function for the type DKGContractClient +func (_mock *DKGContractClient) Broadcast(msg messages.BroadcastDKGMessage) error { + ret := _mock.Called(msg) if len(ret) == 0 { panic("no return value specified for Broadcast") } var r0 error - if rf, ok := ret.Get(0).(func(messages.BroadcastDKGMessage) error); ok { - r0 = rf(msg) + if returnFunc, ok := ret.Get(0).(func(messages.BroadcastDKGMessage) error); ok { + r0 = returnFunc(msg) } else { r0 = ret.Error(0) } - return r0 } -// ReadBroadcast provides a mock function with given fields: fromIndex, referenceBlock -func (_m *DKGContractClient) ReadBroadcast(fromIndex uint, referenceBlock flow.Identifier) ([]messages.BroadcastDKGMessage, error) { - ret := _m.Called(fromIndex, referenceBlock) +// DKGContractClient_Broadcast_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Broadcast' +type DKGContractClient_Broadcast_Call struct { + *mock.Call +} + +// Broadcast is a helper method to define mock.On call +// - msg messages.BroadcastDKGMessage +func (_e *DKGContractClient_Expecter) Broadcast(msg interface{}) *DKGContractClient_Broadcast_Call { + return &DKGContractClient_Broadcast_Call{Call: _e.mock.On("Broadcast", msg)} +} + +func (_c *DKGContractClient_Broadcast_Call) Run(run func(msg messages.BroadcastDKGMessage)) *DKGContractClient_Broadcast_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 messages.BroadcastDKGMessage + if args[0] != nil { + arg0 = args[0].(messages.BroadcastDKGMessage) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGContractClient_Broadcast_Call) Return(err error) *DKGContractClient_Broadcast_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGContractClient_Broadcast_Call) RunAndReturn(run func(msg messages.BroadcastDKGMessage) error) *DKGContractClient_Broadcast_Call { + _c.Call.Return(run) + return _c +} + +// ReadBroadcast provides a mock function for the type DKGContractClient +func (_mock *DKGContractClient) ReadBroadcast(fromIndex uint, referenceBlock flow.Identifier) ([]messages.BroadcastDKGMessage, error) { + ret := _mock.Called(fromIndex, referenceBlock) if len(ret) == 0 { panic("no return value specified for ReadBroadcast") @@ -44,72 +99,167 @@ func (_m *DKGContractClient) ReadBroadcast(fromIndex uint, referenceBlock flow.I var r0 []messages.BroadcastDKGMessage var r1 error - if rf, ok := ret.Get(0).(func(uint, flow.Identifier) ([]messages.BroadcastDKGMessage, error)); ok { - return rf(fromIndex, referenceBlock) + if returnFunc, ok := ret.Get(0).(func(uint, flow.Identifier) ([]messages.BroadcastDKGMessage, error)); ok { + return returnFunc(fromIndex, referenceBlock) } - if rf, ok := ret.Get(0).(func(uint, flow.Identifier) []messages.BroadcastDKGMessage); ok { - r0 = rf(fromIndex, referenceBlock) + if returnFunc, ok := ret.Get(0).(func(uint, flow.Identifier) []messages.BroadcastDKGMessage); ok { + r0 = returnFunc(fromIndex, referenceBlock) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]messages.BroadcastDKGMessage) } } - - if rf, ok := ret.Get(1).(func(uint, flow.Identifier) error); ok { - r1 = rf(fromIndex, referenceBlock) + if returnFunc, ok := ret.Get(1).(func(uint, flow.Identifier) error); ok { + r1 = returnFunc(fromIndex, referenceBlock) } else { r1 = ret.Error(1) } - return r0, r1 } -// SubmitEmptyResult provides a mock function with no fields -func (_m *DKGContractClient) SubmitEmptyResult() error { - ret := _m.Called() +// DKGContractClient_ReadBroadcast_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadBroadcast' +type DKGContractClient_ReadBroadcast_Call struct { + *mock.Call +} + +// ReadBroadcast is a helper method to define mock.On call +// - fromIndex uint +// - referenceBlock flow.Identifier +func (_e *DKGContractClient_Expecter) ReadBroadcast(fromIndex interface{}, referenceBlock interface{}) *DKGContractClient_ReadBroadcast_Call { + return &DKGContractClient_ReadBroadcast_Call{Call: _e.mock.On("ReadBroadcast", fromIndex, referenceBlock)} +} + +func (_c *DKGContractClient_ReadBroadcast_Call) Run(run func(fromIndex uint, referenceBlock flow.Identifier)) *DKGContractClient_ReadBroadcast_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGContractClient_ReadBroadcast_Call) Return(broadcastDKGMessages []messages.BroadcastDKGMessage, err error) *DKGContractClient_ReadBroadcast_Call { + _c.Call.Return(broadcastDKGMessages, err) + return _c +} + +func (_c *DKGContractClient_ReadBroadcast_Call) RunAndReturn(run func(fromIndex uint, referenceBlock flow.Identifier) ([]messages.BroadcastDKGMessage, error)) *DKGContractClient_ReadBroadcast_Call { + _c.Call.Return(run) + return _c +} + +// SubmitEmptyResult provides a mock function for the type DKGContractClient +func (_mock *DKGContractClient) SubmitEmptyResult() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SubmitEmptyResult") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// SubmitParametersAndResult provides a mock function with given fields: indexMap, groupPublicKey, publicKeys -func (_m *DKGContractClient) SubmitParametersAndResult(indexMap flow.DKGIndexMap, groupPublicKey crypto.PublicKey, publicKeys []crypto.PublicKey) error { - ret := _m.Called(indexMap, groupPublicKey, publicKeys) +// DKGContractClient_SubmitEmptyResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitEmptyResult' +type DKGContractClient_SubmitEmptyResult_Call struct { + *mock.Call +} + +// SubmitEmptyResult is a helper method to define mock.On call +func (_e *DKGContractClient_Expecter) SubmitEmptyResult() *DKGContractClient_SubmitEmptyResult_Call { + return &DKGContractClient_SubmitEmptyResult_Call{Call: _e.mock.On("SubmitEmptyResult")} +} + +func (_c *DKGContractClient_SubmitEmptyResult_Call) Run(run func()) *DKGContractClient_SubmitEmptyResult_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGContractClient_SubmitEmptyResult_Call) Return(err error) *DKGContractClient_SubmitEmptyResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGContractClient_SubmitEmptyResult_Call) RunAndReturn(run func() error) *DKGContractClient_SubmitEmptyResult_Call { + _c.Call.Return(run) + return _c +} + +// SubmitParametersAndResult provides a mock function for the type DKGContractClient +func (_mock *DKGContractClient) SubmitParametersAndResult(indexMap flow.DKGIndexMap, groupPublicKey crypto.PublicKey, publicKeys []crypto.PublicKey) error { + ret := _mock.Called(indexMap, groupPublicKey, publicKeys) if len(ret) == 0 { panic("no return value specified for SubmitParametersAndResult") } var r0 error - if rf, ok := ret.Get(0).(func(flow.DKGIndexMap, crypto.PublicKey, []crypto.PublicKey) error); ok { - r0 = rf(indexMap, groupPublicKey, publicKeys) + if returnFunc, ok := ret.Get(0).(func(flow.DKGIndexMap, crypto.PublicKey, []crypto.PublicKey) error); ok { + r0 = returnFunc(indexMap, groupPublicKey, publicKeys) } else { r0 = ret.Error(0) } - return r0 } -// NewDKGContractClient creates a new instance of DKGContractClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGContractClient(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGContractClient { - mock := &DKGContractClient{} - mock.Mock.Test(t) +// DKGContractClient_SubmitParametersAndResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitParametersAndResult' +type DKGContractClient_SubmitParametersAndResult_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubmitParametersAndResult is a helper method to define mock.On call +// - indexMap flow.DKGIndexMap +// - groupPublicKey crypto.PublicKey +// - publicKeys []crypto.PublicKey +func (_e *DKGContractClient_Expecter) SubmitParametersAndResult(indexMap interface{}, groupPublicKey interface{}, publicKeys interface{}) *DKGContractClient_SubmitParametersAndResult_Call { + return &DKGContractClient_SubmitParametersAndResult_Call{Call: _e.mock.On("SubmitParametersAndResult", indexMap, groupPublicKey, publicKeys)} +} - return mock +func (_c *DKGContractClient_SubmitParametersAndResult_Call) Run(run func(indexMap flow.DKGIndexMap, groupPublicKey crypto.PublicKey, publicKeys []crypto.PublicKey)) *DKGContractClient_SubmitParametersAndResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.DKGIndexMap + if args[0] != nil { + arg0 = args[0].(flow.DKGIndexMap) + } + var arg1 crypto.PublicKey + if args[1] != nil { + arg1 = args[1].(crypto.PublicKey) + } + var arg2 []crypto.PublicKey + if args[2] != nil { + arg2 = args[2].([]crypto.PublicKey) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DKGContractClient_SubmitParametersAndResult_Call) Return(err error) *DKGContractClient_SubmitParametersAndResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGContractClient_SubmitParametersAndResult_Call) RunAndReturn(run func(indexMap flow.DKGIndexMap, groupPublicKey crypto.PublicKey, publicKeys []crypto.PublicKey) error) *DKGContractClient_SubmitParametersAndResult_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/dkg_controller.go b/module/mock/dkg_controller.go index 1637c7536c7..cae392f998c 100644 --- a/module/mock/dkg_controller.go +++ b/module/mock/dkg_controller.go @@ -1,76 +1,177 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewDKGController creates a new instance of DKGController. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGController(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGController { + mock := &DKGController{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKGController is an autogenerated mock type for the DKGController type type DKGController struct { mock.Mock } -// End provides a mock function with no fields -func (_m *DKGController) End() error { - ret := _m.Called() +type DKGController_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGController) EXPECT() *DKGController_Expecter { + return &DKGController_Expecter{mock: &_m.Mock} +} + +// End provides a mock function for the type DKGController +func (_mock *DKGController) End() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for End") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// EndPhase1 provides a mock function with no fields -func (_m *DKGController) EndPhase1() error { - ret := _m.Called() +// DKGController_End_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'End' +type DKGController_End_Call struct { + *mock.Call +} + +// End is a helper method to define mock.On call +func (_e *DKGController_Expecter) End() *DKGController_End_Call { + return &DKGController_End_Call{Call: _e.mock.On("End")} +} + +func (_c *DKGController_End_Call) Run(run func()) *DKGController_End_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_End_Call) Return(err error) *DKGController_End_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGController_End_Call) RunAndReturn(run func() error) *DKGController_End_Call { + _c.Call.Return(run) + return _c +} + +// EndPhase1 provides a mock function for the type DKGController +func (_mock *DKGController) EndPhase1() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EndPhase1") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// EndPhase2 provides a mock function with no fields -func (_m *DKGController) EndPhase2() error { - ret := _m.Called() +// DKGController_EndPhase1_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EndPhase1' +type DKGController_EndPhase1_Call struct { + *mock.Call +} + +// EndPhase1 is a helper method to define mock.On call +func (_e *DKGController_Expecter) EndPhase1() *DKGController_EndPhase1_Call { + return &DKGController_EndPhase1_Call{Call: _e.mock.On("EndPhase1")} +} + +func (_c *DKGController_EndPhase1_Call) Run(run func()) *DKGController_EndPhase1_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_EndPhase1_Call) Return(err error) *DKGController_EndPhase1_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGController_EndPhase1_Call) RunAndReturn(run func() error) *DKGController_EndPhase1_Call { + _c.Call.Return(run) + return _c +} + +// EndPhase2 provides a mock function for the type DKGController +func (_mock *DKGController) EndPhase2() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EndPhase2") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// GetArtifacts provides a mock function with no fields -func (_m *DKGController) GetArtifacts() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey) { - ret := _m.Called() +// DKGController_EndPhase2_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EndPhase2' +type DKGController_EndPhase2_Call struct { + *mock.Call +} + +// EndPhase2 is a helper method to define mock.On call +func (_e *DKGController_Expecter) EndPhase2() *DKGController_EndPhase2_Call { + return &DKGController_EndPhase2_Call{Call: _e.mock.On("EndPhase2")} +} + +func (_c *DKGController_EndPhase2_Call) Run(run func()) *DKGController_EndPhase2_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_EndPhase2_Call) Return(err error) *DKGController_EndPhase2_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGController_EndPhase2_Call) RunAndReturn(run func() error) *DKGController_EndPhase2_Call { + _c.Call.Return(run) + return _c +} + +// GetArtifacts provides a mock function for the type DKGController +func (_mock *DKGController) GetArtifacts() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetArtifacts") @@ -79,123 +180,272 @@ func (_m *DKGController) GetArtifacts() (crypto.PrivateKey, crypto.PublicKey, [] var r0 crypto.PrivateKey var r1 crypto.PublicKey var r2 []crypto.PublicKey - if rf, ok := ret.Get(0).(func() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() crypto.PrivateKey); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() crypto.PrivateKey); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func() crypto.PublicKey); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() crypto.PublicKey); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).(crypto.PublicKey) } } - - if rf, ok := ret.Get(2).(func() []crypto.PublicKey); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() []crypto.PublicKey); ok { + r2 = returnFunc() } else { if ret.Get(2) != nil { r2 = ret.Get(2).([]crypto.PublicKey) } } - return r0, r1, r2 } -// GetIndex provides a mock function with no fields -func (_m *DKGController) GetIndex() int { - ret := _m.Called() +// DKGController_GetArtifacts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetArtifacts' +type DKGController_GetArtifacts_Call struct { + *mock.Call +} + +// GetArtifacts is a helper method to define mock.On call +func (_e *DKGController_Expecter) GetArtifacts() *DKGController_GetArtifacts_Call { + return &DKGController_GetArtifacts_Call{Call: _e.mock.On("GetArtifacts")} +} + +func (_c *DKGController_GetArtifacts_Call) Run(run func()) *DKGController_GetArtifacts_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_GetArtifacts_Call) Return(privateKey crypto.PrivateKey, publicKey crypto.PublicKey, publicKeys []crypto.PublicKey) *DKGController_GetArtifacts_Call { + _c.Call.Return(privateKey, publicKey, publicKeys) + return _c +} + +func (_c *DKGController_GetArtifacts_Call) RunAndReturn(run func() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey)) *DKGController_GetArtifacts_Call { + _c.Call.Return(run) + return _c +} + +// GetIndex provides a mock function for the type DKGController +func (_mock *DKGController) GetIndex() int { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetIndex") } var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(int) } - return r0 } -// Poll provides a mock function with given fields: blockReference -func (_m *DKGController) Poll(blockReference flow.Identifier) error { - ret := _m.Called(blockReference) +// DKGController_GetIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIndex' +type DKGController_GetIndex_Call struct { + *mock.Call +} + +// GetIndex is a helper method to define mock.On call +func (_e *DKGController_Expecter) GetIndex() *DKGController_GetIndex_Call { + return &DKGController_GetIndex_Call{Call: _e.mock.On("GetIndex")} +} + +func (_c *DKGController_GetIndex_Call) Run(run func()) *DKGController_GetIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_GetIndex_Call) Return(n int) *DKGController_GetIndex_Call { + _c.Call.Return(n) + return _c +} + +func (_c *DKGController_GetIndex_Call) RunAndReturn(run func() int) *DKGController_GetIndex_Call { + _c.Call.Return(run) + return _c +} + +// Poll provides a mock function for the type DKGController +func (_mock *DKGController) Poll(blockReference flow.Identifier) error { + ret := _mock.Called(blockReference) if len(ret) == 0 { panic("no return value specified for Poll") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier) error); ok { - r0 = rf(blockReference) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) error); ok { + r0 = returnFunc(blockReference) } else { r0 = ret.Error(0) } - return r0 } -// Run provides a mock function with no fields -func (_m *DKGController) Run() error { - ret := _m.Called() +// DKGController_Poll_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Poll' +type DKGController_Poll_Call struct { + *mock.Call +} + +// Poll is a helper method to define mock.On call +// - blockReference flow.Identifier +func (_e *DKGController_Expecter) Poll(blockReference interface{}) *DKGController_Poll_Call { + return &DKGController_Poll_Call{Call: _e.mock.On("Poll", blockReference)} +} + +func (_c *DKGController_Poll_Call) Run(run func(blockReference flow.Identifier)) *DKGController_Poll_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGController_Poll_Call) Return(err error) *DKGController_Poll_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGController_Poll_Call) RunAndReturn(run func(blockReference flow.Identifier) error) *DKGController_Poll_Call { + _c.Call.Return(run) + return _c +} + +// Run provides a mock function for the type DKGController +func (_mock *DKGController) Run() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Run") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Shutdown provides a mock function with no fields -func (_m *DKGController) Shutdown() { - _m.Called() +// DKGController_Run_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Run' +type DKGController_Run_Call struct { + *mock.Call +} + +// Run is a helper method to define mock.On call +func (_e *DKGController_Expecter) Run() *DKGController_Run_Call { + return &DKGController_Run_Call{Call: _e.mock.On("Run")} } -// SubmitResult provides a mock function with no fields -func (_m *DKGController) SubmitResult() error { - ret := _m.Called() +func (_c *DKGController_Run_Call) Run(run func()) *DKGController_Run_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_Run_Call) Return(err error) *DKGController_Run_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGController_Run_Call) RunAndReturn(run func() error) *DKGController_Run_Call { + _c.Call.Return(run) + return _c +} + +// Shutdown provides a mock function for the type DKGController +func (_mock *DKGController) Shutdown() { + _mock.Called() + return +} + +// DKGController_Shutdown_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Shutdown' +type DKGController_Shutdown_Call struct { + *mock.Call +} + +// Shutdown is a helper method to define mock.On call +func (_e *DKGController_Expecter) Shutdown() *DKGController_Shutdown_Call { + return &DKGController_Shutdown_Call{Call: _e.mock.On("Shutdown")} +} + +func (_c *DKGController_Shutdown_Call) Run(run func()) *DKGController_Shutdown_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_Shutdown_Call) Return() *DKGController_Shutdown_Call { + _c.Call.Return() + return _c +} + +func (_c *DKGController_Shutdown_Call) RunAndReturn(run func()) *DKGController_Shutdown_Call { + _c.Run(run) + return _c +} + +// SubmitResult provides a mock function for the type DKGController +func (_mock *DKGController) SubmitResult() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SubmitResult") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// NewDKGController creates a new instance of DKGController. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGController(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGController { - mock := &DKGController{} - mock.Mock.Test(t) +// DKGController_SubmitResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitResult' +type DKGController_SubmitResult_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SubmitResult is a helper method to define mock.On call +func (_e *DKGController_Expecter) SubmitResult() *DKGController_SubmitResult_Call { + return &DKGController_SubmitResult_Call{Call: _e.mock.On("SubmitResult")} +} - return mock +func (_c *DKGController_SubmitResult_Call) Run(run func()) *DKGController_SubmitResult_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKGController_SubmitResult_Call) Return(err error) *DKGController_SubmitResult_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGController_SubmitResult_Call) RunAndReturn(run func() error) *DKGController_SubmitResult_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/dkg_controller_factory.go b/module/mock/dkg_controller_factory.go index d37798a7771..608a895e26b 100644 --- a/module/mock/dkg_controller_factory.go +++ b/module/mock/dkg_controller_factory.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" - - module "github.com/onflow/flow-go/module" ) +// NewDKGControllerFactory creates a new instance of DKGControllerFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGControllerFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGControllerFactory { + mock := &DKGControllerFactory{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKGControllerFactory is an autogenerated mock type for the DKGControllerFactory type type DKGControllerFactory struct { mock.Mock } -// Create provides a mock function with given fields: dkgInstanceID, participants, seed -func (_m *DKGControllerFactory) Create(dkgInstanceID string, participants flow.IdentitySkeletonList, seed []byte) (module.DKGController, error) { - ret := _m.Called(dkgInstanceID, participants, seed) +type DKGControllerFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGControllerFactory) EXPECT() *DKGControllerFactory_Expecter { + return &DKGControllerFactory_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type DKGControllerFactory +func (_mock *DKGControllerFactory) Create(dkgInstanceID string, participants flow.IdentitySkeletonList, seed []byte) (module.DKGController, error) { + ret := _mock.Called(dkgInstanceID, participants, seed) if len(ret) == 0 { panic("no return value specified for Create") @@ -24,36 +47,66 @@ func (_m *DKGControllerFactory) Create(dkgInstanceID string, participants flow.I var r0 module.DKGController var r1 error - if rf, ok := ret.Get(0).(func(string, flow.IdentitySkeletonList, []byte) (module.DKGController, error)); ok { - return rf(dkgInstanceID, participants, seed) + if returnFunc, ok := ret.Get(0).(func(string, flow.IdentitySkeletonList, []byte) (module.DKGController, error)); ok { + return returnFunc(dkgInstanceID, participants, seed) } - if rf, ok := ret.Get(0).(func(string, flow.IdentitySkeletonList, []byte) module.DKGController); ok { - r0 = rf(dkgInstanceID, participants, seed) + if returnFunc, ok := ret.Get(0).(func(string, flow.IdentitySkeletonList, []byte) module.DKGController); ok { + r0 = returnFunc(dkgInstanceID, participants, seed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(module.DKGController) } } - - if rf, ok := ret.Get(1).(func(string, flow.IdentitySkeletonList, []byte) error); ok { - r1 = rf(dkgInstanceID, participants, seed) + if returnFunc, ok := ret.Get(1).(func(string, flow.IdentitySkeletonList, []byte) error); ok { + r1 = returnFunc(dkgInstanceID, participants, seed) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewDKGControllerFactory creates a new instance of DKGControllerFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGControllerFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGControllerFactory { - mock := &DKGControllerFactory{} - mock.Mock.Test(t) +// DKGControllerFactory_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type DKGControllerFactory_Create_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Create is a helper method to define mock.On call +// - dkgInstanceID string +// - participants flow.IdentitySkeletonList +// - seed []byte +func (_e *DKGControllerFactory_Expecter) Create(dkgInstanceID interface{}, participants interface{}, seed interface{}) *DKGControllerFactory_Create_Call { + return &DKGControllerFactory_Create_Call{Call: _e.mock.On("Create", dkgInstanceID, participants, seed)} +} - return mock +func (_c *DKGControllerFactory_Create_Call) Run(run func(dkgInstanceID string, participants flow.IdentitySkeletonList, seed []byte)) *DKGControllerFactory_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 flow.IdentitySkeletonList + if args[1] != nil { + arg1 = args[1].(flow.IdentitySkeletonList) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DKGControllerFactory_Create_Call) Return(dKGController module.DKGController, err error) *DKGControllerFactory_Create_Call { + _c.Call.Return(dKGController, err) + return _c +} + +func (_c *DKGControllerFactory_Create_Call) RunAndReturn(run func(dkgInstanceID string, participants flow.IdentitySkeletonList, seed []byte) (module.DKGController, error)) *DKGControllerFactory_Create_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/dkg_processor.go b/module/mock/dkg_processor.go deleted file mode 100644 index e519c5dca25..00000000000 --- a/module/mock/dkg_processor.go +++ /dev/null @@ -1,44 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import mock "github.com/stretchr/testify/mock" - -// DKGProcessor is an autogenerated mock type for the DKGProcessor type -type DKGProcessor struct { - mock.Mock -} - -// Broadcast provides a mock function with given fields: data -func (_m *DKGProcessor) Broadcast(data []byte) { - _m.Called(data) -} - -// Disqualify provides a mock function with given fields: index, log -func (_m *DKGProcessor) Disqualify(index int, log string) { - _m.Called(index, log) -} - -// FlagMisbehavior provides a mock function with given fields: index, log -func (_m *DKGProcessor) FlagMisbehavior(index int, log string) { - _m.Called(index, log) -} - -// PrivateSend provides a mock function with given fields: dest, data -func (_m *DKGProcessor) PrivateSend(dest int, data []byte) { - _m.Called(dest, data) -} - -// NewDKGProcessor creates a new instance of DKGProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGProcessor(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGProcessor { - mock := &DKGProcessor{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/module/mock/dkg_state.go b/module/mock/dkg_state.go deleted file mode 100644 index 023b1f462e8..00000000000 --- a/module/mock/dkg_state.go +++ /dev/null @@ -1,219 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - crypto "github.com/onflow/crypto" - mock "github.com/stretchr/testify/mock" -) - -// DKGState is an autogenerated mock type for the DKGState type -type DKGState struct { - mock.Mock -} - -// End provides a mock function with no fields -func (_m *DKGState) End() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey, error) { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for End") - } - - var r0 crypto.PrivateKey - var r1 crypto.PublicKey - var r2 []crypto.PublicKey - var r3 error - if rf, ok := ret.Get(0).(func() (crypto.PrivateKey, crypto.PublicKey, []crypto.PublicKey, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() crypto.PrivateKey); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.PrivateKey) - } - } - - if rf, ok := ret.Get(1).(func() crypto.PublicKey); ok { - r1 = rf() - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(crypto.PublicKey) - } - } - - if rf, ok := ret.Get(2).(func() []crypto.PublicKey); ok { - r2 = rf() - } else { - if ret.Get(2) != nil { - r2 = ret.Get(2).([]crypto.PublicKey) - } - } - - if rf, ok := ret.Get(3).(func() error); ok { - r3 = rf() - } else { - r3 = ret.Error(3) - } - - return r0, r1, r2, r3 -} - -// ForceDisqualify provides a mock function with given fields: participant -func (_m *DKGState) ForceDisqualify(participant int) error { - ret := _m.Called(participant) - - if len(ret) == 0 { - panic("no return value specified for ForceDisqualify") - } - - var r0 error - if rf, ok := ret.Get(0).(func(int) error); ok { - r0 = rf(participant) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// HandleBroadcastMsg provides a mock function with given fields: orig, msg -func (_m *DKGState) HandleBroadcastMsg(orig int, msg []byte) error { - ret := _m.Called(orig, msg) - - if len(ret) == 0 { - panic("no return value specified for HandleBroadcastMsg") - } - - var r0 error - if rf, ok := ret.Get(0).(func(int, []byte) error); ok { - r0 = rf(orig, msg) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// HandlePrivateMsg provides a mock function with given fields: orig, msg -func (_m *DKGState) HandlePrivateMsg(orig int, msg []byte) error { - ret := _m.Called(orig, msg) - - if len(ret) == 0 { - panic("no return value specified for HandlePrivateMsg") - } - - var r0 error - if rf, ok := ret.Get(0).(func(int, []byte) error); ok { - r0 = rf(orig, msg) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// NextTimeout provides a mock function with no fields -func (_m *DKGState) NextTimeout() error { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for NextTimeout") - } - - var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Running provides a mock function with no fields -func (_m *DKGState) Running() bool { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Running") - } - - var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -// Size provides a mock function with no fields -func (_m *DKGState) Size() int { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Size") - } - - var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(int) - } - - return r0 -} - -// Start provides a mock function with given fields: seed -func (_m *DKGState) Start(seed []byte) error { - ret := _m.Called(seed) - - if len(ret) == 0 { - panic("no return value specified for Start") - } - - var r0 error - if rf, ok := ret.Get(0).(func([]byte) error); ok { - r0 = rf(seed) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// Threshold provides a mock function with no fields -func (_m *DKGState) Threshold() int { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Threshold") - } - - var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(int) - } - - return r0 -} - -// NewDKGState creates a new instance of DKGState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGState(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGState { - mock := &DKGState{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/module/mock/engine_metrics.go b/module/mock/engine_metrics.go index b2838e776ec..99cd4e2b677 100644 --- a/module/mock/engine_metrics.go +++ b/module/mock/engine_metrics.go @@ -1,49 +1,266 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewEngineMetrics creates a new instance of EngineMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEngineMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *EngineMetrics { + mock := &EngineMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EngineMetrics is an autogenerated mock type for the EngineMetrics type type EngineMetrics struct { mock.Mock } -// InboundMessageDropped provides a mock function with given fields: engine, messages -func (_m *EngineMetrics) InboundMessageDropped(engine string, messages string) { - _m.Called(engine, messages) +type EngineMetrics_Expecter struct { + mock *mock.Mock } -// MessageHandled provides a mock function with given fields: engine, messages -func (_m *EngineMetrics) MessageHandled(engine string, messages string) { - _m.Called(engine, messages) +func (_m *EngineMetrics) EXPECT() *EngineMetrics_Expecter { + return &EngineMetrics_Expecter{mock: &_m.Mock} } -// MessageReceived provides a mock function with given fields: engine, message -func (_m *EngineMetrics) MessageReceived(engine string, message string) { - _m.Called(engine, message) +// InboundMessageDropped provides a mock function for the type EngineMetrics +func (_mock *EngineMetrics) InboundMessageDropped(engine string, messages string) { + _mock.Called(engine, messages) + return } -// MessageSent provides a mock function with given fields: engine, message -func (_m *EngineMetrics) MessageSent(engine string, message string) { - _m.Called(engine, message) +// EngineMetrics_InboundMessageDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InboundMessageDropped' +type EngineMetrics_InboundMessageDropped_Call struct { + *mock.Call } -// OutboundMessageDropped provides a mock function with given fields: engine, messages -func (_m *EngineMetrics) OutboundMessageDropped(engine string, messages string) { - _m.Called(engine, messages) +// InboundMessageDropped is a helper method to define mock.On call +// - engine string +// - messages string +func (_e *EngineMetrics_Expecter) InboundMessageDropped(engine interface{}, messages interface{}) *EngineMetrics_InboundMessageDropped_Call { + return &EngineMetrics_InboundMessageDropped_Call{Call: _e.mock.On("InboundMessageDropped", engine, messages)} } -// NewEngineMetrics creates a new instance of EngineMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEngineMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *EngineMetrics { - mock := &EngineMetrics{} - mock.Mock.Test(t) +func (_c *EngineMetrics_InboundMessageDropped_Call) Run(run func(engine string, messages string)) *EngineMetrics_InboundMessageDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *EngineMetrics_InboundMessageDropped_Call) Return() *EngineMetrics_InboundMessageDropped_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *EngineMetrics_InboundMessageDropped_Call) RunAndReturn(run func(engine string, messages string)) *EngineMetrics_InboundMessageDropped_Call { + _c.Run(run) + return _c +} + +// MessageHandled provides a mock function for the type EngineMetrics +func (_mock *EngineMetrics) MessageHandled(engine string, messages string) { + _mock.Called(engine, messages) + return +} + +// EngineMetrics_MessageHandled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageHandled' +type EngineMetrics_MessageHandled_Call struct { + *mock.Call +} + +// MessageHandled is a helper method to define mock.On call +// - engine string +// - messages string +func (_e *EngineMetrics_Expecter) MessageHandled(engine interface{}, messages interface{}) *EngineMetrics_MessageHandled_Call { + return &EngineMetrics_MessageHandled_Call{Call: _e.mock.On("MessageHandled", engine, messages)} +} + +func (_c *EngineMetrics_MessageHandled_Call) Run(run func(engine string, messages string)) *EngineMetrics_MessageHandled_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EngineMetrics_MessageHandled_Call) Return() *EngineMetrics_MessageHandled_Call { + _c.Call.Return() + return _c +} + +func (_c *EngineMetrics_MessageHandled_Call) RunAndReturn(run func(engine string, messages string)) *EngineMetrics_MessageHandled_Call { + _c.Run(run) + return _c +} + +// MessageReceived provides a mock function for the type EngineMetrics +func (_mock *EngineMetrics) MessageReceived(engine string, message string) { + _mock.Called(engine, message) + return +} + +// EngineMetrics_MessageReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageReceived' +type EngineMetrics_MessageReceived_Call struct { + *mock.Call +} + +// MessageReceived is a helper method to define mock.On call +// - engine string +// - message string +func (_e *EngineMetrics_Expecter) MessageReceived(engine interface{}, message interface{}) *EngineMetrics_MessageReceived_Call { + return &EngineMetrics_MessageReceived_Call{Call: _e.mock.On("MessageReceived", engine, message)} +} + +func (_c *EngineMetrics_MessageReceived_Call) Run(run func(engine string, message string)) *EngineMetrics_MessageReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EngineMetrics_MessageReceived_Call) Return() *EngineMetrics_MessageReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *EngineMetrics_MessageReceived_Call) RunAndReturn(run func(engine string, message string)) *EngineMetrics_MessageReceived_Call { + _c.Run(run) + return _c +} + +// MessageSent provides a mock function for the type EngineMetrics +func (_mock *EngineMetrics) MessageSent(engine string, message string) { + _mock.Called(engine, message) + return +} + +// EngineMetrics_MessageSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageSent' +type EngineMetrics_MessageSent_Call struct { + *mock.Call +} + +// MessageSent is a helper method to define mock.On call +// - engine string +// - message string +func (_e *EngineMetrics_Expecter) MessageSent(engine interface{}, message interface{}) *EngineMetrics_MessageSent_Call { + return &EngineMetrics_MessageSent_Call{Call: _e.mock.On("MessageSent", engine, message)} +} + +func (_c *EngineMetrics_MessageSent_Call) Run(run func(engine string, message string)) *EngineMetrics_MessageSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EngineMetrics_MessageSent_Call) Return() *EngineMetrics_MessageSent_Call { + _c.Call.Return() + return _c +} + +func (_c *EngineMetrics_MessageSent_Call) RunAndReturn(run func(engine string, message string)) *EngineMetrics_MessageSent_Call { + _c.Run(run) + return _c +} + +// OutboundMessageDropped provides a mock function for the type EngineMetrics +func (_mock *EngineMetrics) OutboundMessageDropped(engine string, messages string) { + _mock.Called(engine, messages) + return +} + +// EngineMetrics_OutboundMessageDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OutboundMessageDropped' +type EngineMetrics_OutboundMessageDropped_Call struct { + *mock.Call +} + +// OutboundMessageDropped is a helper method to define mock.On call +// - engine string +// - messages string +func (_e *EngineMetrics_Expecter) OutboundMessageDropped(engine interface{}, messages interface{}) *EngineMetrics_OutboundMessageDropped_Call { + return &EngineMetrics_OutboundMessageDropped_Call{Call: _e.mock.On("OutboundMessageDropped", engine, messages)} +} + +func (_c *EngineMetrics_OutboundMessageDropped_Call) Run(run func(engine string, messages string)) *EngineMetrics_OutboundMessageDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EngineMetrics_OutboundMessageDropped_Call) Return() *EngineMetrics_OutboundMessageDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *EngineMetrics_OutboundMessageDropped_Call) RunAndReturn(run func(engine string, messages string)) *EngineMetrics_OutboundMessageDropped_Call { + _c.Run(run) + return _c } diff --git a/module/mock/epoch_lookup.go b/module/mock/epoch_lookup.go index 72648ea24cc..a79636fbf56 100644 --- a/module/mock/epoch_lookup.go +++ b/module/mock/epoch_lookup.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewEpochLookup creates a new instance of EpochLookup. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochLookup(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochLookup { + mock := &EpochLookup{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EpochLookup is an autogenerated mock type for the EpochLookup type type EpochLookup struct { mock.Mock } -// EpochForView provides a mock function with given fields: view -func (_m *EpochLookup) EpochForView(view uint64) (uint64, error) { - ret := _m.Called(view) +type EpochLookup_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochLookup) EXPECT() *EpochLookup_Expecter { + return &EpochLookup_Expecter{mock: &_m.Mock} +} + +// EpochForView provides a mock function for the type EpochLookup +func (_mock *EpochLookup) EpochForView(view uint64) (uint64, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for EpochForView") @@ -19,34 +45,52 @@ func (_m *EpochLookup) EpochForView(view uint64) (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (uint64, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(view) } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEpochLookup creates a new instance of EpochLookup. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochLookup(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochLookup { - mock := &EpochLookup{} - mock.Mock.Test(t) +// EpochLookup_EpochForView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochForView' +type EpochLookup_EpochForView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// EpochForView is a helper method to define mock.On call +// - view uint64 +func (_e *EpochLookup_Expecter) EpochForView(view interface{}) *EpochLookup_EpochForView_Call { + return &EpochLookup_EpochForView_Call{Call: _e.mock.On("EpochForView", view)} +} - return mock +func (_c *EpochLookup_EpochForView_Call) Run(run func(view uint64)) *EpochLookup_EpochForView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochLookup_EpochForView_Call) Return(epochCounter uint64, err error) *EpochLookup_EpochForView_Call { + _c.Call.Return(epochCounter, err) + return _c +} + +func (_c *EpochLookup_EpochForView_Call) RunAndReturn(run func(view uint64) (uint64, error)) *EpochLookup_EpochForView_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/evm_metrics.go b/module/mock/evm_metrics.go index 04e90149f75..00c789969fe 100644 --- a/module/mock/evm_metrics.go +++ b/module/mock/evm_metrics.go @@ -1,39 +1,180 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewEVMMetrics creates a new instance of EVMMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEVMMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *EVMMetrics { + mock := &EVMMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EVMMetrics is an autogenerated mock type for the EVMMetrics type type EVMMetrics struct { mock.Mock } -// EVMBlockExecuted provides a mock function with given fields: txCount, totalGasUsed, totalSupplyInFlow -func (_m *EVMMetrics) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { - _m.Called(txCount, totalGasUsed, totalSupplyInFlow) +type EVMMetrics_Expecter struct { + mock *mock.Mock } -// EVMTransactionExecuted provides a mock function with given fields: gasUsed, isDirectCall, failed -func (_m *EVMMetrics) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { - _m.Called(gasUsed, isDirectCall, failed) +func (_m *EVMMetrics) EXPECT() *EVMMetrics_Expecter { + return &EVMMetrics_Expecter{mock: &_m.Mock} } -// SetNumberOfDeployedCOAs provides a mock function with given fields: count -func (_m *EVMMetrics) SetNumberOfDeployedCOAs(count uint64) { - _m.Called(count) +// EVMBlockExecuted provides a mock function for the type EVMMetrics +func (_mock *EVMMetrics) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { + _mock.Called(txCount, totalGasUsed, totalSupplyInFlow) + return } -// NewEVMMetrics creates a new instance of EVMMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEVMMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *EVMMetrics { - mock := &EVMMetrics{} - mock.Mock.Test(t) +// EVMMetrics_EVMBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMBlockExecuted' +type EVMMetrics_EVMBlockExecuted_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// EVMBlockExecuted is a helper method to define mock.On call +// - txCount int +// - totalGasUsed uint64 +// - totalSupplyInFlow float64 +func (_e *EVMMetrics_Expecter) EVMBlockExecuted(txCount interface{}, totalGasUsed interface{}, totalSupplyInFlow interface{}) *EVMMetrics_EVMBlockExecuted_Call { + return &EVMMetrics_EVMBlockExecuted_Call{Call: _e.mock.On("EVMBlockExecuted", txCount, totalGasUsed, totalSupplyInFlow)} +} - return mock +func (_c *EVMMetrics_EVMBlockExecuted_Call) Run(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *EVMMetrics_EVMBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 float64 + if args[2] != nil { + arg2 = args[2].(float64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *EVMMetrics_EVMBlockExecuted_Call) Return() *EVMMetrics_EVMBlockExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *EVMMetrics_EVMBlockExecuted_Call) RunAndReturn(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *EVMMetrics_EVMBlockExecuted_Call { + _c.Run(run) + return _c +} + +// EVMTransactionExecuted provides a mock function for the type EVMMetrics +func (_mock *EVMMetrics) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { + _mock.Called(gasUsed, isDirectCall, failed) + return +} + +// EVMMetrics_EVMTransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMTransactionExecuted' +type EVMMetrics_EVMTransactionExecuted_Call struct { + *mock.Call +} + +// EVMTransactionExecuted is a helper method to define mock.On call +// - gasUsed uint64 +// - isDirectCall bool +// - failed bool +func (_e *EVMMetrics_Expecter) EVMTransactionExecuted(gasUsed interface{}, isDirectCall interface{}, failed interface{}) *EVMMetrics_EVMTransactionExecuted_Call { + return &EVMMetrics_EVMTransactionExecuted_Call{Call: _e.mock.On("EVMTransactionExecuted", gasUsed, isDirectCall, failed)} +} + +func (_c *EVMMetrics_EVMTransactionExecuted_Call) Run(run func(gasUsed uint64, isDirectCall bool, failed bool)) *EVMMetrics_EVMTransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + var arg2 bool + if args[2] != nil { + arg2 = args[2].(bool) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *EVMMetrics_EVMTransactionExecuted_Call) Return() *EVMMetrics_EVMTransactionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *EVMMetrics_EVMTransactionExecuted_Call) RunAndReturn(run func(gasUsed uint64, isDirectCall bool, failed bool)) *EVMMetrics_EVMTransactionExecuted_Call { + _c.Run(run) + return _c +} + +// SetNumberOfDeployedCOAs provides a mock function for the type EVMMetrics +func (_mock *EVMMetrics) SetNumberOfDeployedCOAs(count uint64) { + _mock.Called(count) + return +} + +// EVMMetrics_SetNumberOfDeployedCOAs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetNumberOfDeployedCOAs' +type EVMMetrics_SetNumberOfDeployedCOAs_Call struct { + *mock.Call +} + +// SetNumberOfDeployedCOAs is a helper method to define mock.On call +// - count uint64 +func (_e *EVMMetrics_Expecter) SetNumberOfDeployedCOAs(count interface{}) *EVMMetrics_SetNumberOfDeployedCOAs_Call { + return &EVMMetrics_SetNumberOfDeployedCOAs_Call{Call: _e.mock.On("SetNumberOfDeployedCOAs", count)} +} + +func (_c *EVMMetrics_SetNumberOfDeployedCOAs_Call) Run(run func(count uint64)) *EVMMetrics_SetNumberOfDeployedCOAs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EVMMetrics_SetNumberOfDeployedCOAs_Call) Return() *EVMMetrics_SetNumberOfDeployedCOAs_Call { + _c.Call.Return() + return _c +} + +func (_c *EVMMetrics_SetNumberOfDeployedCOAs_Call) RunAndReturn(run func(count uint64)) *EVMMetrics_SetNumberOfDeployedCOAs_Call { + _c.Run(run) + return _c } diff --git a/module/mock/execution_data_provider_metrics.go b/module/mock/execution_data_provider_metrics.go index 6869e83c99e..f79f4348ed6 100644 --- a/module/mock/execution_data_provider_metrics.go +++ b/module/mock/execution_data_provider_metrics.go @@ -1,43 +1,163 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataProviderMetrics creates a new instance of ExecutionDataProviderMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataProviderMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataProviderMetrics { + mock := &ExecutionDataProviderMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataProviderMetrics is an autogenerated mock type for the ExecutionDataProviderMetrics type type ExecutionDataProviderMetrics struct { mock.Mock } -// AddBlobsFailed provides a mock function with no fields -func (_m *ExecutionDataProviderMetrics) AddBlobsFailed() { - _m.Called() +type ExecutionDataProviderMetrics_Expecter struct { + mock *mock.Mock } -// AddBlobsSucceeded provides a mock function with given fields: duration, totalSize -func (_m *ExecutionDataProviderMetrics) AddBlobsSucceeded(duration time.Duration, totalSize uint64) { - _m.Called(duration, totalSize) +func (_m *ExecutionDataProviderMetrics) EXPECT() *ExecutionDataProviderMetrics_Expecter { + return &ExecutionDataProviderMetrics_Expecter{mock: &_m.Mock} } -// RootIDComputed provides a mock function with given fields: duration, numberOfChunks -func (_m *ExecutionDataProviderMetrics) RootIDComputed(duration time.Duration, numberOfChunks int) { - _m.Called(duration, numberOfChunks) +// AddBlobsFailed provides a mock function for the type ExecutionDataProviderMetrics +func (_mock *ExecutionDataProviderMetrics) AddBlobsFailed() { + _mock.Called() + return } -// NewExecutionDataProviderMetrics creates a new instance of ExecutionDataProviderMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataProviderMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataProviderMetrics { - mock := &ExecutionDataProviderMetrics{} - mock.Mock.Test(t) +// ExecutionDataProviderMetrics_AddBlobsFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlobsFailed' +type ExecutionDataProviderMetrics_AddBlobsFailed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// AddBlobsFailed is a helper method to define mock.On call +func (_e *ExecutionDataProviderMetrics_Expecter) AddBlobsFailed() *ExecutionDataProviderMetrics_AddBlobsFailed_Call { + return &ExecutionDataProviderMetrics_AddBlobsFailed_Call{Call: _e.mock.On("AddBlobsFailed")} +} - return mock +func (_c *ExecutionDataProviderMetrics_AddBlobsFailed_Call) Run(run func()) *ExecutionDataProviderMetrics_AddBlobsFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataProviderMetrics_AddBlobsFailed_Call) Return() *ExecutionDataProviderMetrics_AddBlobsFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataProviderMetrics_AddBlobsFailed_Call) RunAndReturn(run func()) *ExecutionDataProviderMetrics_AddBlobsFailed_Call { + _c.Run(run) + return _c +} + +// AddBlobsSucceeded provides a mock function for the type ExecutionDataProviderMetrics +func (_mock *ExecutionDataProviderMetrics) AddBlobsSucceeded(duration time.Duration, totalSize uint64) { + _mock.Called(duration, totalSize) + return +} + +// ExecutionDataProviderMetrics_AddBlobsSucceeded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlobsSucceeded' +type ExecutionDataProviderMetrics_AddBlobsSucceeded_Call struct { + *mock.Call +} + +// AddBlobsSucceeded is a helper method to define mock.On call +// - duration time.Duration +// - totalSize uint64 +func (_e *ExecutionDataProviderMetrics_Expecter) AddBlobsSucceeded(duration interface{}, totalSize interface{}) *ExecutionDataProviderMetrics_AddBlobsSucceeded_Call { + return &ExecutionDataProviderMetrics_AddBlobsSucceeded_Call{Call: _e.mock.On("AddBlobsSucceeded", duration, totalSize)} +} + +func (_c *ExecutionDataProviderMetrics_AddBlobsSucceeded_Call) Run(run func(duration time.Duration, totalSize uint64)) *ExecutionDataProviderMetrics_AddBlobsSucceeded_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataProviderMetrics_AddBlobsSucceeded_Call) Return() *ExecutionDataProviderMetrics_AddBlobsSucceeded_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataProviderMetrics_AddBlobsSucceeded_Call) RunAndReturn(run func(duration time.Duration, totalSize uint64)) *ExecutionDataProviderMetrics_AddBlobsSucceeded_Call { + _c.Run(run) + return _c +} + +// RootIDComputed provides a mock function for the type ExecutionDataProviderMetrics +func (_mock *ExecutionDataProviderMetrics) RootIDComputed(duration time.Duration, numberOfChunks int) { + _mock.Called(duration, numberOfChunks) + return +} + +// ExecutionDataProviderMetrics_RootIDComputed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RootIDComputed' +type ExecutionDataProviderMetrics_RootIDComputed_Call struct { + *mock.Call +} + +// RootIDComputed is a helper method to define mock.On call +// - duration time.Duration +// - numberOfChunks int +func (_e *ExecutionDataProviderMetrics_Expecter) RootIDComputed(duration interface{}, numberOfChunks interface{}) *ExecutionDataProviderMetrics_RootIDComputed_Call { + return &ExecutionDataProviderMetrics_RootIDComputed_Call{Call: _e.mock.On("RootIDComputed", duration, numberOfChunks)} +} + +func (_c *ExecutionDataProviderMetrics_RootIDComputed_Call) Run(run func(duration time.Duration, numberOfChunks int)) *ExecutionDataProviderMetrics_RootIDComputed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataProviderMetrics_RootIDComputed_Call) Return() *ExecutionDataProviderMetrics_RootIDComputed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataProviderMetrics_RootIDComputed_Call) RunAndReturn(run func(duration time.Duration, numberOfChunks int)) *ExecutionDataProviderMetrics_RootIDComputed_Call { + _c.Run(run) + return _c } diff --git a/module/mock/execution_data_pruner_metrics.go b/module/mock/execution_data_pruner_metrics.go index a5cfcc60338..cb5fcc6da08 100644 --- a/module/mock/execution_data_pruner_metrics.go +++ b/module/mock/execution_data_pruner_metrics.go @@ -1,23 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) -// ExecutionDataPrunerMetrics is an autogenerated mock type for the ExecutionDataPrunerMetrics type -type ExecutionDataPrunerMetrics struct { - mock.Mock -} - -// Pruned provides a mock function with given fields: height, duration -func (_m *ExecutionDataPrunerMetrics) Pruned(height uint64, duration time.Duration) { - _m.Called(height, duration) -} - // NewExecutionDataPrunerMetrics creates a new instance of ExecutionDataPrunerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewExecutionDataPrunerMetrics(t interface { @@ -31,3 +23,62 @@ func NewExecutionDataPrunerMetrics(t interface { return mock } + +// ExecutionDataPrunerMetrics is an autogenerated mock type for the ExecutionDataPrunerMetrics type +type ExecutionDataPrunerMetrics struct { + mock.Mock +} + +type ExecutionDataPrunerMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionDataPrunerMetrics) EXPECT() *ExecutionDataPrunerMetrics_Expecter { + return &ExecutionDataPrunerMetrics_Expecter{mock: &_m.Mock} +} + +// Pruned provides a mock function for the type ExecutionDataPrunerMetrics +func (_mock *ExecutionDataPrunerMetrics) Pruned(height uint64, duration time.Duration) { + _mock.Called(height, duration) + return +} + +// ExecutionDataPrunerMetrics_Pruned_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Pruned' +type ExecutionDataPrunerMetrics_Pruned_Call struct { + *mock.Call +} + +// Pruned is a helper method to define mock.On call +// - height uint64 +// - duration time.Duration +func (_e *ExecutionDataPrunerMetrics_Expecter) Pruned(height interface{}, duration interface{}) *ExecutionDataPrunerMetrics_Pruned_Call { + return &ExecutionDataPrunerMetrics_Pruned_Call{Call: _e.mock.On("Pruned", height, duration)} +} + +func (_c *ExecutionDataPrunerMetrics_Pruned_Call) Run(run func(height uint64, duration time.Duration)) *ExecutionDataPrunerMetrics_Pruned_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataPrunerMetrics_Pruned_Call) Return() *ExecutionDataPrunerMetrics_Pruned_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataPrunerMetrics_Pruned_Call) RunAndReturn(run func(height uint64, duration time.Duration)) *ExecutionDataPrunerMetrics_Pruned_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/execution_data_requester_metrics.go b/module/mock/execution_data_requester_metrics.go index 3a1cdc1b253..5f9529191a3 100644 --- a/module/mock/execution_data_requester_metrics.go +++ b/module/mock/execution_data_requester_metrics.go @@ -1,48 +1,196 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataRequesterMetrics creates a new instance of ExecutionDataRequesterMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataRequesterMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataRequesterMetrics { + mock := &ExecutionDataRequesterMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataRequesterMetrics is an autogenerated mock type for the ExecutionDataRequesterMetrics type type ExecutionDataRequesterMetrics struct { mock.Mock } -// ExecutionDataFetchFinished provides a mock function with given fields: duration, success, height -func (_m *ExecutionDataRequesterMetrics) ExecutionDataFetchFinished(duration time.Duration, success bool, height uint64) { - _m.Called(duration, success, height) +type ExecutionDataRequesterMetrics_Expecter struct { + mock *mock.Mock } -// ExecutionDataFetchStarted provides a mock function with no fields -func (_m *ExecutionDataRequesterMetrics) ExecutionDataFetchStarted() { - _m.Called() +func (_m *ExecutionDataRequesterMetrics) EXPECT() *ExecutionDataRequesterMetrics_Expecter { + return &ExecutionDataRequesterMetrics_Expecter{mock: &_m.Mock} } -// FetchRetried provides a mock function with no fields -func (_m *ExecutionDataRequesterMetrics) FetchRetried() { - _m.Called() +// ExecutionDataFetchFinished provides a mock function for the type ExecutionDataRequesterMetrics +func (_mock *ExecutionDataRequesterMetrics) ExecutionDataFetchFinished(duration time.Duration, success bool, height uint64) { + _mock.Called(duration, success, height) + return } -// NotificationSent provides a mock function with given fields: height -func (_m *ExecutionDataRequesterMetrics) NotificationSent(height uint64) { - _m.Called(height) +// ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionDataFetchFinished' +type ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call struct { + *mock.Call } -// NewExecutionDataRequesterMetrics creates a new instance of ExecutionDataRequesterMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataRequesterMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataRequesterMetrics { - mock := &ExecutionDataRequesterMetrics{} - mock.Mock.Test(t) +// ExecutionDataFetchFinished is a helper method to define mock.On call +// - duration time.Duration +// - success bool +// - height uint64 +func (_e *ExecutionDataRequesterMetrics_Expecter) ExecutionDataFetchFinished(duration interface{}, success interface{}, height interface{}) *ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call { + return &ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call{Call: _e.mock.On("ExecutionDataFetchFinished", duration, success, height)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call) Run(run func(duration time.Duration, success bool, height uint64)) *ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} - return mock +func (_c *ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call) Return() *ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call) RunAndReturn(run func(duration time.Duration, success bool, height uint64)) *ExecutionDataRequesterMetrics_ExecutionDataFetchFinished_Call { + _c.Run(run) + return _c +} + +// ExecutionDataFetchStarted provides a mock function for the type ExecutionDataRequesterMetrics +func (_mock *ExecutionDataRequesterMetrics) ExecutionDataFetchStarted() { + _mock.Called() + return +} + +// ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionDataFetchStarted' +type ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call struct { + *mock.Call +} + +// ExecutionDataFetchStarted is a helper method to define mock.On call +func (_e *ExecutionDataRequesterMetrics_Expecter) ExecutionDataFetchStarted() *ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call { + return &ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call{Call: _e.mock.On("ExecutionDataFetchStarted")} +} + +func (_c *ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call) Run(run func()) *ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call) Return() *ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call) RunAndReturn(run func()) *ExecutionDataRequesterMetrics_ExecutionDataFetchStarted_Call { + _c.Run(run) + return _c +} + +// FetchRetried provides a mock function for the type ExecutionDataRequesterMetrics +func (_mock *ExecutionDataRequesterMetrics) FetchRetried() { + _mock.Called() + return +} + +// ExecutionDataRequesterMetrics_FetchRetried_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FetchRetried' +type ExecutionDataRequesterMetrics_FetchRetried_Call struct { + *mock.Call +} + +// FetchRetried is a helper method to define mock.On call +func (_e *ExecutionDataRequesterMetrics_Expecter) FetchRetried() *ExecutionDataRequesterMetrics_FetchRetried_Call { + return &ExecutionDataRequesterMetrics_FetchRetried_Call{Call: _e.mock.On("FetchRetried")} +} + +func (_c *ExecutionDataRequesterMetrics_FetchRetried_Call) Run(run func()) *ExecutionDataRequesterMetrics_FetchRetried_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataRequesterMetrics_FetchRetried_Call) Return() *ExecutionDataRequesterMetrics_FetchRetried_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterMetrics_FetchRetried_Call) RunAndReturn(run func()) *ExecutionDataRequesterMetrics_FetchRetried_Call { + _c.Run(run) + return _c +} + +// NotificationSent provides a mock function for the type ExecutionDataRequesterMetrics +func (_mock *ExecutionDataRequesterMetrics) NotificationSent(height uint64) { + _mock.Called(height) + return +} + +// ExecutionDataRequesterMetrics_NotificationSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NotificationSent' +type ExecutionDataRequesterMetrics_NotificationSent_Call struct { + *mock.Call +} + +// NotificationSent is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutionDataRequesterMetrics_Expecter) NotificationSent(height interface{}) *ExecutionDataRequesterMetrics_NotificationSent_Call { + return &ExecutionDataRequesterMetrics_NotificationSent_Call{Call: _e.mock.On("NotificationSent", height)} +} + +func (_c *ExecutionDataRequesterMetrics_NotificationSent_Call) Run(run func(height uint64)) *ExecutionDataRequesterMetrics_NotificationSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionDataRequesterMetrics_NotificationSent_Call) Return() *ExecutionDataRequesterMetrics_NotificationSent_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterMetrics_NotificationSent_Call) RunAndReturn(run func(height uint64)) *ExecutionDataRequesterMetrics_NotificationSent_Call { + _c.Run(run) + return _c } diff --git a/module/mock/execution_data_requester_v2_metrics.go b/module/mock/execution_data_requester_v2_metrics.go index 76162a30605..0d5858eaa8a 100644 --- a/module/mock/execution_data_requester_v2_metrics.go +++ b/module/mock/execution_data_requester_v2_metrics.go @@ -1,58 +1,281 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataRequesterV2Metrics creates a new instance of ExecutionDataRequesterV2Metrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataRequesterV2Metrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataRequesterV2Metrics { + mock := &ExecutionDataRequesterV2Metrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataRequesterV2Metrics is an autogenerated mock type for the ExecutionDataRequesterV2Metrics type type ExecutionDataRequesterV2Metrics struct { mock.Mock } -// FulfilledHeight provides a mock function with given fields: blockHeight -func (_m *ExecutionDataRequesterV2Metrics) FulfilledHeight(blockHeight uint64) { - _m.Called(blockHeight) +type ExecutionDataRequesterV2Metrics_Expecter struct { + mock *mock.Mock } -// ReceiptSkipped provides a mock function with no fields -func (_m *ExecutionDataRequesterV2Metrics) ReceiptSkipped() { - _m.Called() +func (_m *ExecutionDataRequesterV2Metrics) EXPECT() *ExecutionDataRequesterV2Metrics_Expecter { + return &ExecutionDataRequesterV2Metrics_Expecter{mock: &_m.Mock} } -// RequestCanceled provides a mock function with no fields -func (_m *ExecutionDataRequesterV2Metrics) RequestCanceled() { - _m.Called() +// FulfilledHeight provides a mock function for the type ExecutionDataRequesterV2Metrics +func (_mock *ExecutionDataRequesterV2Metrics) FulfilledHeight(blockHeight uint64) { + _mock.Called(blockHeight) + return } -// RequestFailed provides a mock function with given fields: duration, retryable -func (_m *ExecutionDataRequesterV2Metrics) RequestFailed(duration time.Duration, retryable bool) { - _m.Called(duration, retryable) +// ExecutionDataRequesterV2Metrics_FulfilledHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FulfilledHeight' +type ExecutionDataRequesterV2Metrics_FulfilledHeight_Call struct { + *mock.Call } -// RequestSucceeded provides a mock function with given fields: blockHeight, duration, totalSize, numberOfAttempts -func (_m *ExecutionDataRequesterV2Metrics) RequestSucceeded(blockHeight uint64, duration time.Duration, totalSize uint64, numberOfAttempts int) { - _m.Called(blockHeight, duration, totalSize, numberOfAttempts) +// FulfilledHeight is a helper method to define mock.On call +// - blockHeight uint64 +func (_e *ExecutionDataRequesterV2Metrics_Expecter) FulfilledHeight(blockHeight interface{}) *ExecutionDataRequesterV2Metrics_FulfilledHeight_Call { + return &ExecutionDataRequesterV2Metrics_FulfilledHeight_Call{Call: _e.mock.On("FulfilledHeight", blockHeight)} } -// ResponseDropped provides a mock function with no fields -func (_m *ExecutionDataRequesterV2Metrics) ResponseDropped() { - _m.Called() +func (_c *ExecutionDataRequesterV2Metrics_FulfilledHeight_Call) Run(run func(blockHeight uint64)) *ExecutionDataRequesterV2Metrics_FulfilledHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c } -// NewExecutionDataRequesterV2Metrics creates a new instance of ExecutionDataRequesterV2Metrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataRequesterV2Metrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataRequesterV2Metrics { - mock := &ExecutionDataRequesterV2Metrics{} - mock.Mock.Test(t) +func (_c *ExecutionDataRequesterV2Metrics_FulfilledHeight_Call) Return() *ExecutionDataRequesterV2Metrics_FulfilledHeight_Call { + _c.Call.Return() + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ExecutionDataRequesterV2Metrics_FulfilledHeight_Call) RunAndReturn(run func(blockHeight uint64)) *ExecutionDataRequesterV2Metrics_FulfilledHeight_Call { + _c.Run(run) + return _c +} - return mock +// ReceiptSkipped provides a mock function for the type ExecutionDataRequesterV2Metrics +func (_mock *ExecutionDataRequesterV2Metrics) ReceiptSkipped() { + _mock.Called() + return +} + +// ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReceiptSkipped' +type ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call struct { + *mock.Call +} + +// ReceiptSkipped is a helper method to define mock.On call +func (_e *ExecutionDataRequesterV2Metrics_Expecter) ReceiptSkipped() *ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call { + return &ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call{Call: _e.mock.On("ReceiptSkipped")} +} + +func (_c *ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call) Run(run func()) *ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call) Return() *ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call) RunAndReturn(run func()) *ExecutionDataRequesterV2Metrics_ReceiptSkipped_Call { + _c.Run(run) + return _c +} + +// RequestCanceled provides a mock function for the type ExecutionDataRequesterV2Metrics +func (_mock *ExecutionDataRequesterV2Metrics) RequestCanceled() { + _mock.Called() + return +} + +// ExecutionDataRequesterV2Metrics_RequestCanceled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestCanceled' +type ExecutionDataRequesterV2Metrics_RequestCanceled_Call struct { + *mock.Call +} + +// RequestCanceled is a helper method to define mock.On call +func (_e *ExecutionDataRequesterV2Metrics_Expecter) RequestCanceled() *ExecutionDataRequesterV2Metrics_RequestCanceled_Call { + return &ExecutionDataRequesterV2Metrics_RequestCanceled_Call{Call: _e.mock.On("RequestCanceled")} +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestCanceled_Call) Run(run func()) *ExecutionDataRequesterV2Metrics_RequestCanceled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestCanceled_Call) Return() *ExecutionDataRequesterV2Metrics_RequestCanceled_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestCanceled_Call) RunAndReturn(run func()) *ExecutionDataRequesterV2Metrics_RequestCanceled_Call { + _c.Run(run) + return _c +} + +// RequestFailed provides a mock function for the type ExecutionDataRequesterV2Metrics +func (_mock *ExecutionDataRequesterV2Metrics) RequestFailed(duration time.Duration, retryable bool) { + _mock.Called(duration, retryable) + return +} + +// ExecutionDataRequesterV2Metrics_RequestFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestFailed' +type ExecutionDataRequesterV2Metrics_RequestFailed_Call struct { + *mock.Call +} + +// RequestFailed is a helper method to define mock.On call +// - duration time.Duration +// - retryable bool +func (_e *ExecutionDataRequesterV2Metrics_Expecter) RequestFailed(duration interface{}, retryable interface{}) *ExecutionDataRequesterV2Metrics_RequestFailed_Call { + return &ExecutionDataRequesterV2Metrics_RequestFailed_Call{Call: _e.mock.On("RequestFailed", duration, retryable)} +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestFailed_Call) Run(run func(duration time.Duration, retryable bool)) *ExecutionDataRequesterV2Metrics_RequestFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestFailed_Call) Return() *ExecutionDataRequesterV2Metrics_RequestFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestFailed_Call) RunAndReturn(run func(duration time.Duration, retryable bool)) *ExecutionDataRequesterV2Metrics_RequestFailed_Call { + _c.Run(run) + return _c +} + +// RequestSucceeded provides a mock function for the type ExecutionDataRequesterV2Metrics +func (_mock *ExecutionDataRequesterV2Metrics) RequestSucceeded(blockHeight uint64, duration time.Duration, totalSize uint64, numberOfAttempts int) { + _mock.Called(blockHeight, duration, totalSize, numberOfAttempts) + return +} + +// ExecutionDataRequesterV2Metrics_RequestSucceeded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestSucceeded' +type ExecutionDataRequesterV2Metrics_RequestSucceeded_Call struct { + *mock.Call +} + +// RequestSucceeded is a helper method to define mock.On call +// - blockHeight uint64 +// - duration time.Duration +// - totalSize uint64 +// - numberOfAttempts int +func (_e *ExecutionDataRequesterV2Metrics_Expecter) RequestSucceeded(blockHeight interface{}, duration interface{}, totalSize interface{}, numberOfAttempts interface{}) *ExecutionDataRequesterV2Metrics_RequestSucceeded_Call { + return &ExecutionDataRequesterV2Metrics_RequestSucceeded_Call{Call: _e.mock.On("RequestSucceeded", blockHeight, duration, totalSize, numberOfAttempts)} +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestSucceeded_Call) Run(run func(blockHeight uint64, duration time.Duration, totalSize uint64, numberOfAttempts int)) *ExecutionDataRequesterV2Metrics_RequestSucceeded_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestSucceeded_Call) Return() *ExecutionDataRequesterV2Metrics_RequestSucceeded_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_RequestSucceeded_Call) RunAndReturn(run func(blockHeight uint64, duration time.Duration, totalSize uint64, numberOfAttempts int)) *ExecutionDataRequesterV2Metrics_RequestSucceeded_Call { + _c.Run(run) + return _c +} + +// ResponseDropped provides a mock function for the type ExecutionDataRequesterV2Metrics +func (_mock *ExecutionDataRequesterV2Metrics) ResponseDropped() { + _mock.Called() + return +} + +// ExecutionDataRequesterV2Metrics_ResponseDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ResponseDropped' +type ExecutionDataRequesterV2Metrics_ResponseDropped_Call struct { + *mock.Call +} + +// ResponseDropped is a helper method to define mock.On call +func (_e *ExecutionDataRequesterV2Metrics_Expecter) ResponseDropped() *ExecutionDataRequesterV2Metrics_ResponseDropped_Call { + return &ExecutionDataRequesterV2Metrics_ResponseDropped_Call{Call: _e.mock.On("ResponseDropped")} +} + +func (_c *ExecutionDataRequesterV2Metrics_ResponseDropped_Call) Run(run func()) *ExecutionDataRequesterV2Metrics_ResponseDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_ResponseDropped_Call) Return() *ExecutionDataRequesterV2Metrics_ResponseDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequesterV2Metrics_ResponseDropped_Call) RunAndReturn(run func()) *ExecutionDataRequesterV2Metrics_ResponseDropped_Call { + _c.Run(run) + return _c } diff --git a/module/mock/execution_metrics.go b/module/mock/execution_metrics.go index 61cfa617b9d..373fa3d72cc 100644 --- a/module/mock/execution_metrics.go +++ b/module/mock/execution_metrics.go @@ -1,281 +1,2074 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "time" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" +) + +// NewExecutionMetrics creates a new instance of ExecutionMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionMetrics { + mock := &ExecutionMetrics{} + mock.Mock.Test(t) - module "github.com/onflow/flow-go/module" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // ExecutionMetrics is an autogenerated mock type for the ExecutionMetrics type type ExecutionMetrics struct { mock.Mock } -// ChunkDataPackRequestProcessed provides a mock function with no fields -func (_m *ExecutionMetrics) ChunkDataPackRequestProcessed() { - _m.Called() +type ExecutionMetrics_Expecter struct { + mock *mock.Mock } -// EVMBlockExecuted provides a mock function with given fields: txCount, totalGasUsed, totalSupplyInFlow -func (_m *ExecutionMetrics) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { - _m.Called(txCount, totalGasUsed, totalSupplyInFlow) +func (_m *ExecutionMetrics) EXPECT() *ExecutionMetrics_Expecter { + return &ExecutionMetrics_Expecter{mock: &_m.Mock} } -// EVMTransactionExecuted provides a mock function with given fields: gasUsed, isDirectCall, failed -func (_m *ExecutionMetrics) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { - _m.Called(gasUsed, isDirectCall, failed) +// ChunkDataPackRequestProcessed provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ChunkDataPackRequestProcessed() { + _mock.Called() + return } -// ExecutionBlockCachedPrograms provides a mock function with given fields: programs -func (_m *ExecutionMetrics) ExecutionBlockCachedPrograms(programs int) { - _m.Called(programs) +// ExecutionMetrics_ChunkDataPackRequestProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChunkDataPackRequestProcessed' +type ExecutionMetrics_ChunkDataPackRequestProcessed_Call struct { + *mock.Call } -// ExecutionBlockDataUploadFinished provides a mock function with given fields: dur -func (_m *ExecutionMetrics) ExecutionBlockDataUploadFinished(dur time.Duration) { - _m.Called(dur) +// ChunkDataPackRequestProcessed is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) ChunkDataPackRequestProcessed() *ExecutionMetrics_ChunkDataPackRequestProcessed_Call { + return &ExecutionMetrics_ChunkDataPackRequestProcessed_Call{Call: _e.mock.On("ChunkDataPackRequestProcessed")} } -// ExecutionBlockDataUploadStarted provides a mock function with no fields -func (_m *ExecutionMetrics) ExecutionBlockDataUploadStarted() { - _m.Called() +func (_c *ExecutionMetrics_ChunkDataPackRequestProcessed_Call) Run(run func()) *ExecutionMetrics_ChunkDataPackRequestProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// ExecutionBlockExecuted provides a mock function with given fields: dur, stats -func (_m *ExecutionMetrics) ExecutionBlockExecuted(dur time.Duration, stats module.BlockExecutionResultStats) { - _m.Called(dur, stats) +func (_c *ExecutionMetrics_ChunkDataPackRequestProcessed_Call) Return() *ExecutionMetrics_ChunkDataPackRequestProcessed_Call { + _c.Call.Return() + return _c } -// ExecutionBlockExecutionEffortVectorComponent provides a mock function with given fields: _a0, _a1 -func (_m *ExecutionMetrics) ExecutionBlockExecutionEffortVectorComponent(_a0 string, _a1 uint64) { - _m.Called(_a0, _a1) +func (_c *ExecutionMetrics_ChunkDataPackRequestProcessed_Call) RunAndReturn(run func()) *ExecutionMetrics_ChunkDataPackRequestProcessed_Call { + _c.Run(run) + return _c } -// ExecutionCheckpointSize provides a mock function with given fields: bytes -func (_m *ExecutionMetrics) ExecutionCheckpointSize(bytes uint64) { - _m.Called(bytes) +// EVMBlockExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) EVMBlockExecuted(txCount int, totalGasUsed uint64, totalSupplyInFlow float64) { + _mock.Called(txCount, totalGasUsed, totalSupplyInFlow) + return } -// ExecutionChunkDataPackGenerated provides a mock function with given fields: proofSize, numberOfTransactions -func (_m *ExecutionMetrics) ExecutionChunkDataPackGenerated(proofSize int, numberOfTransactions int) { - _m.Called(proofSize, numberOfTransactions) +// ExecutionMetrics_EVMBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMBlockExecuted' +type ExecutionMetrics_EVMBlockExecuted_Call struct { + *mock.Call } -// ExecutionCollectionExecuted provides a mock function with given fields: dur, stats -func (_m *ExecutionMetrics) ExecutionCollectionExecuted(dur time.Duration, stats module.CollectionExecutionResultStats) { - _m.Called(dur, stats) +// EVMBlockExecuted is a helper method to define mock.On call +// - txCount int +// - totalGasUsed uint64 +// - totalSupplyInFlow float64 +func (_e *ExecutionMetrics_Expecter) EVMBlockExecuted(txCount interface{}, totalGasUsed interface{}, totalSupplyInFlow interface{}) *ExecutionMetrics_EVMBlockExecuted_Call { + return &ExecutionMetrics_EVMBlockExecuted_Call{Call: _e.mock.On("EVMBlockExecuted", txCount, totalGasUsed, totalSupplyInFlow)} } -// ExecutionCollectionRequestSent provides a mock function with no fields -func (_m *ExecutionMetrics) ExecutionCollectionRequestSent() { - _m.Called() +func (_c *ExecutionMetrics_EVMBlockExecuted_Call) Run(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *ExecutionMetrics_EVMBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 float64 + if args[2] != nil { + arg2 = args[2].(float64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// ExecutionComputationResultUploadRetried provides a mock function with no fields -func (_m *ExecutionMetrics) ExecutionComputationResultUploadRetried() { - _m.Called() +func (_c *ExecutionMetrics_EVMBlockExecuted_Call) Return() *ExecutionMetrics_EVMBlockExecuted_Call { + _c.Call.Return() + return _c } -// ExecutionComputationResultUploaded provides a mock function with no fields -func (_m *ExecutionMetrics) ExecutionComputationResultUploaded() { - _m.Called() +func (_c *ExecutionMetrics_EVMBlockExecuted_Call) RunAndReturn(run func(txCount int, totalGasUsed uint64, totalSupplyInFlow float64)) *ExecutionMetrics_EVMBlockExecuted_Call { + _c.Run(run) + return _c } -// ExecutionLastChunkDataPackPrunedHeight provides a mock function with given fields: height -func (_m *ExecutionMetrics) ExecutionLastChunkDataPackPrunedHeight(height uint64) { - _m.Called(height) +// EVMTransactionExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) EVMTransactionExecuted(gasUsed uint64, isDirectCall bool, failed bool) { + _mock.Called(gasUsed, isDirectCall, failed) + return } -// ExecutionLastExecutedBlockHeight provides a mock function with given fields: height -func (_m *ExecutionMetrics) ExecutionLastExecutedBlockHeight(height uint64) { - _m.Called(height) +// ExecutionMetrics_EVMTransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EVMTransactionExecuted' +type ExecutionMetrics_EVMTransactionExecuted_Call struct { + *mock.Call } -// ExecutionLastFinalizedExecutedBlockHeight provides a mock function with given fields: height -func (_m *ExecutionMetrics) ExecutionLastFinalizedExecutedBlockHeight(height uint64) { - _m.Called(height) +// EVMTransactionExecuted is a helper method to define mock.On call +// - gasUsed uint64 +// - isDirectCall bool +// - failed bool +func (_e *ExecutionMetrics_Expecter) EVMTransactionExecuted(gasUsed interface{}, isDirectCall interface{}, failed interface{}) *ExecutionMetrics_EVMTransactionExecuted_Call { + return &ExecutionMetrics_EVMTransactionExecuted_Call{Call: _e.mock.On("EVMTransactionExecuted", gasUsed, isDirectCall, failed)} } -// ExecutionScheduledTransactionsExecuted provides a mock function with given fields: scheduledTransactionCount, processComputationUsed, executeComputationLimits -func (_m *ExecutionMetrics) ExecutionScheduledTransactionsExecuted(scheduledTransactionCount int, processComputationUsed uint64, executeComputationLimits uint64) { - _m.Called(scheduledTransactionCount, processComputationUsed, executeComputationLimits) +func (_c *ExecutionMetrics_EVMTransactionExecuted_Call) Run(run func(gasUsed uint64, isDirectCall bool, failed bool)) *ExecutionMetrics_EVMTransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + var arg2 bool + if args[2] != nil { + arg2 = args[2].(bool) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// ExecutionScriptExecuted provides a mock function with given fields: dur, compUsed, memoryUsed, memoryEstimate -func (_m *ExecutionMetrics) ExecutionScriptExecuted(dur time.Duration, compUsed uint64, memoryUsed uint64, memoryEstimate uint64) { - _m.Called(dur, compUsed, memoryUsed, memoryEstimate) +func (_c *ExecutionMetrics_EVMTransactionExecuted_Call) Return() *ExecutionMetrics_EVMTransactionExecuted_Call { + _c.Call.Return() + return _c } -// ExecutionStorageStateCommitment provides a mock function with given fields: bytes -func (_m *ExecutionMetrics) ExecutionStorageStateCommitment(bytes int64) { - _m.Called(bytes) +func (_c *ExecutionMetrics_EVMTransactionExecuted_Call) RunAndReturn(run func(gasUsed uint64, isDirectCall bool, failed bool)) *ExecutionMetrics_EVMTransactionExecuted_Call { + _c.Run(run) + return _c } -// ExecutionSync provides a mock function with given fields: syncing -func (_m *ExecutionMetrics) ExecutionSync(syncing bool) { - _m.Called(syncing) +// ExecutionBlockCachedPrograms provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionBlockCachedPrograms(programs int) { + _mock.Called(programs) + return } -// ExecutionTargetChunkDataPackPrunedHeight provides a mock function with given fields: height -func (_m *ExecutionMetrics) ExecutionTargetChunkDataPackPrunedHeight(height uint64) { - _m.Called(height) +// ExecutionMetrics_ExecutionBlockCachedPrograms_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionBlockCachedPrograms' +type ExecutionMetrics_ExecutionBlockCachedPrograms_Call struct { + *mock.Call } -// ExecutionTransactionExecuted provides a mock function with given fields: dur, stats, info -func (_m *ExecutionMetrics) ExecutionTransactionExecuted(dur time.Duration, stats module.TransactionExecutionResultStats, info module.TransactionExecutionResultInfo) { - _m.Called(dur, stats, info) +// ExecutionBlockCachedPrograms is a helper method to define mock.On call +// - programs int +func (_e *ExecutionMetrics_Expecter) ExecutionBlockCachedPrograms(programs interface{}) *ExecutionMetrics_ExecutionBlockCachedPrograms_Call { + return &ExecutionMetrics_ExecutionBlockCachedPrograms_Call{Call: _e.mock.On("ExecutionBlockCachedPrograms", programs)} } -// FinishBlockReceivedToExecuted provides a mock function with given fields: blockID -func (_m *ExecutionMetrics) FinishBlockReceivedToExecuted(blockID flow.Identifier) { - _m.Called(blockID) +func (_c *ExecutionMetrics_ExecutionBlockCachedPrograms_Call) Run(run func(programs int)) *ExecutionMetrics_ExecutionBlockCachedPrograms_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c } -// ForestApproxMemorySize provides a mock function with given fields: bytes -func (_m *ExecutionMetrics) ForestApproxMemorySize(bytes uint64) { - _m.Called(bytes) +func (_c *ExecutionMetrics_ExecutionBlockCachedPrograms_Call) Return() *ExecutionMetrics_ExecutionBlockCachedPrograms_Call { + _c.Call.Return() + return _c } -// ForestNumberOfTrees provides a mock function with given fields: number -func (_m *ExecutionMetrics) ForestNumberOfTrees(number uint64) { - _m.Called(number) +func (_c *ExecutionMetrics_ExecutionBlockCachedPrograms_Call) RunAndReturn(run func(programs int)) *ExecutionMetrics_ExecutionBlockCachedPrograms_Call { + _c.Run(run) + return _c } -// LatestTrieMaxDepthTouched provides a mock function with given fields: maxDepth -func (_m *ExecutionMetrics) LatestTrieMaxDepthTouched(maxDepth uint16) { - _m.Called(maxDepth) +// ExecutionBlockDataUploadFinished provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionBlockDataUploadFinished(dur time.Duration) { + _mock.Called(dur) + return } -// LatestTrieRegCount provides a mock function with given fields: number -func (_m *ExecutionMetrics) LatestTrieRegCount(number uint64) { - _m.Called(number) +// ExecutionMetrics_ExecutionBlockDataUploadFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionBlockDataUploadFinished' +type ExecutionMetrics_ExecutionBlockDataUploadFinished_Call struct { + *mock.Call } -// LatestTrieRegCountDiff provides a mock function with given fields: number -func (_m *ExecutionMetrics) LatestTrieRegCountDiff(number int64) { - _m.Called(number) +// ExecutionBlockDataUploadFinished is a helper method to define mock.On call +// - dur time.Duration +func (_e *ExecutionMetrics_Expecter) ExecutionBlockDataUploadFinished(dur interface{}) *ExecutionMetrics_ExecutionBlockDataUploadFinished_Call { + return &ExecutionMetrics_ExecutionBlockDataUploadFinished_Call{Call: _e.mock.On("ExecutionBlockDataUploadFinished", dur)} } -// LatestTrieRegSize provides a mock function with given fields: size -func (_m *ExecutionMetrics) LatestTrieRegSize(size uint64) { - _m.Called(size) +func (_c *ExecutionMetrics_ExecutionBlockDataUploadFinished_Call) Run(run func(dur time.Duration)) *ExecutionMetrics_ExecutionBlockDataUploadFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// LatestTrieRegSizeDiff provides a mock function with given fields: size -func (_m *ExecutionMetrics) LatestTrieRegSizeDiff(size int64) { - _m.Called(size) +func (_c *ExecutionMetrics_ExecutionBlockDataUploadFinished_Call) Return() *ExecutionMetrics_ExecutionBlockDataUploadFinished_Call { + _c.Call.Return() + return _c } -// ProofSize provides a mock function with given fields: bytes -func (_m *ExecutionMetrics) ProofSize(bytes uint32) { - _m.Called(bytes) +func (_c *ExecutionMetrics_ExecutionBlockDataUploadFinished_Call) RunAndReturn(run func(dur time.Duration)) *ExecutionMetrics_ExecutionBlockDataUploadFinished_Call { + _c.Run(run) + return _c } -// ReadDuration provides a mock function with given fields: duration -func (_m *ExecutionMetrics) ReadDuration(duration time.Duration) { - _m.Called(duration) +// ExecutionBlockDataUploadStarted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionBlockDataUploadStarted() { + _mock.Called() + return } -// ReadDurationPerItem provides a mock function with given fields: duration -func (_m *ExecutionMetrics) ReadDurationPerItem(duration time.Duration) { - _m.Called(duration) +// ExecutionMetrics_ExecutionBlockDataUploadStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionBlockDataUploadStarted' +type ExecutionMetrics_ExecutionBlockDataUploadStarted_Call struct { + *mock.Call } -// ReadValuesNumber provides a mock function with given fields: number -func (_m *ExecutionMetrics) ReadValuesNumber(number uint64) { - _m.Called(number) +// ExecutionBlockDataUploadStarted is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) ExecutionBlockDataUploadStarted() *ExecutionMetrics_ExecutionBlockDataUploadStarted_Call { + return &ExecutionMetrics_ExecutionBlockDataUploadStarted_Call{Call: _e.mock.On("ExecutionBlockDataUploadStarted")} } -// ReadValuesSize provides a mock function with given fields: byte -func (_m *ExecutionMetrics) ReadValuesSize(byte uint64) { - _m.Called(byte) +func (_c *ExecutionMetrics_ExecutionBlockDataUploadStarted_Call) Run(run func()) *ExecutionMetrics_ExecutionBlockDataUploadStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// RuntimeSetNumberOfAccounts provides a mock function with given fields: count -func (_m *ExecutionMetrics) RuntimeSetNumberOfAccounts(count uint64) { - _m.Called(count) +func (_c *ExecutionMetrics_ExecutionBlockDataUploadStarted_Call) Return() *ExecutionMetrics_ExecutionBlockDataUploadStarted_Call { + _c.Call.Return() + return _c } -// RuntimeTransactionChecked provides a mock function with given fields: dur -func (_m *ExecutionMetrics) RuntimeTransactionChecked(dur time.Duration) { - _m.Called(dur) +func (_c *ExecutionMetrics_ExecutionBlockDataUploadStarted_Call) RunAndReturn(run func()) *ExecutionMetrics_ExecutionBlockDataUploadStarted_Call { + _c.Run(run) + return _c } -// RuntimeTransactionInterpreted provides a mock function with given fields: dur -func (_m *ExecutionMetrics) RuntimeTransactionInterpreted(dur time.Duration) { - _m.Called(dur) +// ExecutionBlockExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionBlockExecuted(dur time.Duration, stats module.BlockExecutionResultStats) { + _mock.Called(dur, stats) + return } -// RuntimeTransactionParsed provides a mock function with given fields: dur -func (_m *ExecutionMetrics) RuntimeTransactionParsed(dur time.Duration) { - _m.Called(dur) +// ExecutionMetrics_ExecutionBlockExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionBlockExecuted' +type ExecutionMetrics_ExecutionBlockExecuted_Call struct { + *mock.Call } -// RuntimeTransactionProgramsCacheHit provides a mock function with no fields -func (_m *ExecutionMetrics) RuntimeTransactionProgramsCacheHit() { - _m.Called() +// ExecutionBlockExecuted is a helper method to define mock.On call +// - dur time.Duration +// - stats module.BlockExecutionResultStats +func (_e *ExecutionMetrics_Expecter) ExecutionBlockExecuted(dur interface{}, stats interface{}) *ExecutionMetrics_ExecutionBlockExecuted_Call { + return &ExecutionMetrics_ExecutionBlockExecuted_Call{Call: _e.mock.On("ExecutionBlockExecuted", dur, stats)} } -// RuntimeTransactionProgramsCacheMiss provides a mock function with no fields -func (_m *ExecutionMetrics) RuntimeTransactionProgramsCacheMiss() { - _m.Called() +func (_c *ExecutionMetrics_ExecutionBlockExecuted_Call) Run(run func(dur time.Duration, stats module.BlockExecutionResultStats)) *ExecutionMetrics_ExecutionBlockExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 module.BlockExecutionResultStats + if args[1] != nil { + arg1 = args[1].(module.BlockExecutionResultStats) + } + run( + arg0, + arg1, + ) + }) + return _c } -// SetNumberOfDeployedCOAs provides a mock function with given fields: count -func (_m *ExecutionMetrics) SetNumberOfDeployedCOAs(count uint64) { - _m.Called(count) +func (_c *ExecutionMetrics_ExecutionBlockExecuted_Call) Return() *ExecutionMetrics_ExecutionBlockExecuted_Call { + _c.Call.Return() + return _c } -// StartBlockReceivedToExecuted provides a mock function with given fields: blockID -func (_m *ExecutionMetrics) StartBlockReceivedToExecuted(blockID flow.Identifier) { - _m.Called(blockID) +func (_c *ExecutionMetrics_ExecutionBlockExecuted_Call) RunAndReturn(run func(dur time.Duration, stats module.BlockExecutionResultStats)) *ExecutionMetrics_ExecutionBlockExecuted_Call { + _c.Run(run) + return _c } -// UpdateCollectionMaxHeight provides a mock function with given fields: height -func (_m *ExecutionMetrics) UpdateCollectionMaxHeight(height uint64) { - _m.Called(height) +// ExecutionBlockExecutionEffortVectorComponent provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionBlockExecutionEffortVectorComponent(s string, v uint64) { + _mock.Called(s, v) + return } -// UpdateCount provides a mock function with no fields -func (_m *ExecutionMetrics) UpdateCount() { - _m.Called() +// ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionBlockExecutionEffortVectorComponent' +type ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call struct { + *mock.Call } -// UpdateDuration provides a mock function with given fields: duration -func (_m *ExecutionMetrics) UpdateDuration(duration time.Duration) { - _m.Called(duration) +// ExecutionBlockExecutionEffortVectorComponent is a helper method to define mock.On call +// - s string +// - v uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionBlockExecutionEffortVectorComponent(s interface{}, v interface{}) *ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call { + return &ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call{Call: _e.mock.On("ExecutionBlockExecutionEffortVectorComponent", s, v)} } -// UpdateDurationPerItem provides a mock function with given fields: duration -func (_m *ExecutionMetrics) UpdateDurationPerItem(duration time.Duration) { - _m.Called(duration) +func (_c *ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call) Run(run func(s string, v uint64)) *ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c } -// UpdateValuesNumber provides a mock function with given fields: number -func (_m *ExecutionMetrics) UpdateValuesNumber(number uint64) { - _m.Called(number) +func (_c *ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call) Return() *ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call { + _c.Call.Return() + return _c } -// UpdateValuesSize provides a mock function with given fields: byte -func (_m *ExecutionMetrics) UpdateValuesSize(byte uint64) { - _m.Called(byte) +func (_c *ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call) RunAndReturn(run func(s string, v uint64)) *ExecutionMetrics_ExecutionBlockExecutionEffortVectorComponent_Call { + _c.Run(run) + return _c } -// NewExecutionMetrics creates a new instance of ExecutionMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionMetrics { - mock := &ExecutionMetrics{} - mock.Mock.Test(t) +// ExecutionCheckpointSize provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionCheckpointSize(bytes uint64) { + _mock.Called(bytes) + return +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ExecutionMetrics_ExecutionCheckpointSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionCheckpointSize' +type ExecutionMetrics_ExecutionCheckpointSize_Call struct { + *mock.Call +} - return mock +// ExecutionCheckpointSize is a helper method to define mock.On call +// - bytes uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionCheckpointSize(bytes interface{}) *ExecutionMetrics_ExecutionCheckpointSize_Call { + return &ExecutionMetrics_ExecutionCheckpointSize_Call{Call: _e.mock.On("ExecutionCheckpointSize", bytes)} +} + +func (_c *ExecutionMetrics_ExecutionCheckpointSize_Call) Run(run func(bytes uint64)) *ExecutionMetrics_ExecutionCheckpointSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionCheckpointSize_Call) Return() *ExecutionMetrics_ExecutionCheckpointSize_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionCheckpointSize_Call) RunAndReturn(run func(bytes uint64)) *ExecutionMetrics_ExecutionCheckpointSize_Call { + _c.Run(run) + return _c +} + +// ExecutionChunkDataPackGenerated provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionChunkDataPackGenerated(proofSize int, numberOfTransactions int) { + _mock.Called(proofSize, numberOfTransactions) + return +} + +// ExecutionMetrics_ExecutionChunkDataPackGenerated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionChunkDataPackGenerated' +type ExecutionMetrics_ExecutionChunkDataPackGenerated_Call struct { + *mock.Call +} + +// ExecutionChunkDataPackGenerated is a helper method to define mock.On call +// - proofSize int +// - numberOfTransactions int +func (_e *ExecutionMetrics_Expecter) ExecutionChunkDataPackGenerated(proofSize interface{}, numberOfTransactions interface{}) *ExecutionMetrics_ExecutionChunkDataPackGenerated_Call { + return &ExecutionMetrics_ExecutionChunkDataPackGenerated_Call{Call: _e.mock.On("ExecutionChunkDataPackGenerated", proofSize, numberOfTransactions)} +} + +func (_c *ExecutionMetrics_ExecutionChunkDataPackGenerated_Call) Run(run func(proofSize int, numberOfTransactions int)) *ExecutionMetrics_ExecutionChunkDataPackGenerated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionChunkDataPackGenerated_Call) Return() *ExecutionMetrics_ExecutionChunkDataPackGenerated_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionChunkDataPackGenerated_Call) RunAndReturn(run func(proofSize int, numberOfTransactions int)) *ExecutionMetrics_ExecutionChunkDataPackGenerated_Call { + _c.Run(run) + return _c +} + +// ExecutionCollectionExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionCollectionExecuted(dur time.Duration, stats module.CollectionExecutionResultStats) { + _mock.Called(dur, stats) + return +} + +// ExecutionMetrics_ExecutionCollectionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionCollectionExecuted' +type ExecutionMetrics_ExecutionCollectionExecuted_Call struct { + *mock.Call +} + +// ExecutionCollectionExecuted is a helper method to define mock.On call +// - dur time.Duration +// - stats module.CollectionExecutionResultStats +func (_e *ExecutionMetrics_Expecter) ExecutionCollectionExecuted(dur interface{}, stats interface{}) *ExecutionMetrics_ExecutionCollectionExecuted_Call { + return &ExecutionMetrics_ExecutionCollectionExecuted_Call{Call: _e.mock.On("ExecutionCollectionExecuted", dur, stats)} +} + +func (_c *ExecutionMetrics_ExecutionCollectionExecuted_Call) Run(run func(dur time.Duration, stats module.CollectionExecutionResultStats)) *ExecutionMetrics_ExecutionCollectionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 module.CollectionExecutionResultStats + if args[1] != nil { + arg1 = args[1].(module.CollectionExecutionResultStats) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionCollectionExecuted_Call) Return() *ExecutionMetrics_ExecutionCollectionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionCollectionExecuted_Call) RunAndReturn(run func(dur time.Duration, stats module.CollectionExecutionResultStats)) *ExecutionMetrics_ExecutionCollectionExecuted_Call { + _c.Run(run) + return _c +} + +// ExecutionCollectionRequestSent provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionCollectionRequestSent() { + _mock.Called() + return +} + +// ExecutionMetrics_ExecutionCollectionRequestSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionCollectionRequestSent' +type ExecutionMetrics_ExecutionCollectionRequestSent_Call struct { + *mock.Call +} + +// ExecutionCollectionRequestSent is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) ExecutionCollectionRequestSent() *ExecutionMetrics_ExecutionCollectionRequestSent_Call { + return &ExecutionMetrics_ExecutionCollectionRequestSent_Call{Call: _e.mock.On("ExecutionCollectionRequestSent")} +} + +func (_c *ExecutionMetrics_ExecutionCollectionRequestSent_Call) Run(run func()) *ExecutionMetrics_ExecutionCollectionRequestSent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionCollectionRequestSent_Call) Return() *ExecutionMetrics_ExecutionCollectionRequestSent_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionCollectionRequestSent_Call) RunAndReturn(run func()) *ExecutionMetrics_ExecutionCollectionRequestSent_Call { + _c.Run(run) + return _c +} + +// ExecutionComputationResultUploadRetried provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionComputationResultUploadRetried() { + _mock.Called() + return +} + +// ExecutionMetrics_ExecutionComputationResultUploadRetried_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionComputationResultUploadRetried' +type ExecutionMetrics_ExecutionComputationResultUploadRetried_Call struct { + *mock.Call +} + +// ExecutionComputationResultUploadRetried is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) ExecutionComputationResultUploadRetried() *ExecutionMetrics_ExecutionComputationResultUploadRetried_Call { + return &ExecutionMetrics_ExecutionComputationResultUploadRetried_Call{Call: _e.mock.On("ExecutionComputationResultUploadRetried")} +} + +func (_c *ExecutionMetrics_ExecutionComputationResultUploadRetried_Call) Run(run func()) *ExecutionMetrics_ExecutionComputationResultUploadRetried_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionComputationResultUploadRetried_Call) Return() *ExecutionMetrics_ExecutionComputationResultUploadRetried_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionComputationResultUploadRetried_Call) RunAndReturn(run func()) *ExecutionMetrics_ExecutionComputationResultUploadRetried_Call { + _c.Run(run) + return _c +} + +// ExecutionComputationResultUploaded provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionComputationResultUploaded() { + _mock.Called() + return +} + +// ExecutionMetrics_ExecutionComputationResultUploaded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionComputationResultUploaded' +type ExecutionMetrics_ExecutionComputationResultUploaded_Call struct { + *mock.Call +} + +// ExecutionComputationResultUploaded is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) ExecutionComputationResultUploaded() *ExecutionMetrics_ExecutionComputationResultUploaded_Call { + return &ExecutionMetrics_ExecutionComputationResultUploaded_Call{Call: _e.mock.On("ExecutionComputationResultUploaded")} +} + +func (_c *ExecutionMetrics_ExecutionComputationResultUploaded_Call) Run(run func()) *ExecutionMetrics_ExecutionComputationResultUploaded_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionComputationResultUploaded_Call) Return() *ExecutionMetrics_ExecutionComputationResultUploaded_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionComputationResultUploaded_Call) RunAndReturn(run func()) *ExecutionMetrics_ExecutionComputationResultUploaded_Call { + _c.Run(run) + return _c +} + +// ExecutionLastChunkDataPackPrunedHeight provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionLastChunkDataPackPrunedHeight(height uint64) { + _mock.Called(height) + return +} + +// ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionLastChunkDataPackPrunedHeight' +type ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call struct { + *mock.Call +} + +// ExecutionLastChunkDataPackPrunedHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionLastChunkDataPackPrunedHeight(height interface{}) *ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call { + return &ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call{Call: _e.mock.On("ExecutionLastChunkDataPackPrunedHeight", height)} +} + +func (_c *ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call) Run(run func(height uint64)) *ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call) Return() *ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call) RunAndReturn(run func(height uint64)) *ExecutionMetrics_ExecutionLastChunkDataPackPrunedHeight_Call { + _c.Run(run) + return _c +} + +// ExecutionLastExecutedBlockHeight provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionLastExecutedBlockHeight(height uint64) { + _mock.Called(height) + return +} + +// ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionLastExecutedBlockHeight' +type ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call struct { + *mock.Call +} + +// ExecutionLastExecutedBlockHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionLastExecutedBlockHeight(height interface{}) *ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call { + return &ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call{Call: _e.mock.On("ExecutionLastExecutedBlockHeight", height)} +} + +func (_c *ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call) Run(run func(height uint64)) *ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call) Return() *ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call) RunAndReturn(run func(height uint64)) *ExecutionMetrics_ExecutionLastExecutedBlockHeight_Call { + _c.Run(run) + return _c +} + +// ExecutionLastFinalizedExecutedBlockHeight provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionLastFinalizedExecutedBlockHeight(height uint64) { + _mock.Called(height) + return +} + +// ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionLastFinalizedExecutedBlockHeight' +type ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call struct { + *mock.Call +} + +// ExecutionLastFinalizedExecutedBlockHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionLastFinalizedExecutedBlockHeight(height interface{}) *ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call { + return &ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call{Call: _e.mock.On("ExecutionLastFinalizedExecutedBlockHeight", height)} +} + +func (_c *ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call) Run(run func(height uint64)) *ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call) Return() *ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call) RunAndReturn(run func(height uint64)) *ExecutionMetrics_ExecutionLastFinalizedExecutedBlockHeight_Call { + _c.Run(run) + return _c +} + +// ExecutionScheduledTransactionsExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionScheduledTransactionsExecuted(scheduledTransactionCount int, processComputationUsed uint64, executeComputationLimits uint64) { + _mock.Called(scheduledTransactionCount, processComputationUsed, executeComputationLimits) + return +} + +// ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionScheduledTransactionsExecuted' +type ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call struct { + *mock.Call +} + +// ExecutionScheduledTransactionsExecuted is a helper method to define mock.On call +// - scheduledTransactionCount int +// - processComputationUsed uint64 +// - executeComputationLimits uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionScheduledTransactionsExecuted(scheduledTransactionCount interface{}, processComputationUsed interface{}, executeComputationLimits interface{}) *ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call { + return &ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call{Call: _e.mock.On("ExecutionScheduledTransactionsExecuted", scheduledTransactionCount, processComputationUsed, executeComputationLimits)} +} + +func (_c *ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call) Run(run func(scheduledTransactionCount int, processComputationUsed uint64, executeComputationLimits uint64)) *ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call) Return() *ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call) RunAndReturn(run func(scheduledTransactionCount int, processComputationUsed uint64, executeComputationLimits uint64)) *ExecutionMetrics_ExecutionScheduledTransactionsExecuted_Call { + _c.Run(run) + return _c +} + +// ExecutionScriptExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionScriptExecuted(dur time.Duration, compUsed uint64, memoryUsed uint64, memoryEstimate uint64) { + _mock.Called(dur, compUsed, memoryUsed, memoryEstimate) + return +} + +// ExecutionMetrics_ExecutionScriptExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionScriptExecuted' +type ExecutionMetrics_ExecutionScriptExecuted_Call struct { + *mock.Call +} + +// ExecutionScriptExecuted is a helper method to define mock.On call +// - dur time.Duration +// - compUsed uint64 +// - memoryUsed uint64 +// - memoryEstimate uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionScriptExecuted(dur interface{}, compUsed interface{}, memoryUsed interface{}, memoryEstimate interface{}) *ExecutionMetrics_ExecutionScriptExecuted_Call { + return &ExecutionMetrics_ExecutionScriptExecuted_Call{Call: _e.mock.On("ExecutionScriptExecuted", dur, compUsed, memoryUsed, memoryEstimate)} +} + +func (_c *ExecutionMetrics_ExecutionScriptExecuted_Call) Run(run func(dur time.Duration, compUsed uint64, memoryUsed uint64, memoryEstimate uint64)) *ExecutionMetrics_ExecutionScriptExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionScriptExecuted_Call) Return() *ExecutionMetrics_ExecutionScriptExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionScriptExecuted_Call) RunAndReturn(run func(dur time.Duration, compUsed uint64, memoryUsed uint64, memoryEstimate uint64)) *ExecutionMetrics_ExecutionScriptExecuted_Call { + _c.Run(run) + return _c +} + +// ExecutionStorageStateCommitment provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionStorageStateCommitment(bytes int64) { + _mock.Called(bytes) + return +} + +// ExecutionMetrics_ExecutionStorageStateCommitment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionStorageStateCommitment' +type ExecutionMetrics_ExecutionStorageStateCommitment_Call struct { + *mock.Call +} + +// ExecutionStorageStateCommitment is a helper method to define mock.On call +// - bytes int64 +func (_e *ExecutionMetrics_Expecter) ExecutionStorageStateCommitment(bytes interface{}) *ExecutionMetrics_ExecutionStorageStateCommitment_Call { + return &ExecutionMetrics_ExecutionStorageStateCommitment_Call{Call: _e.mock.On("ExecutionStorageStateCommitment", bytes)} +} + +func (_c *ExecutionMetrics_ExecutionStorageStateCommitment_Call) Run(run func(bytes int64)) *ExecutionMetrics_ExecutionStorageStateCommitment_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int64 + if args[0] != nil { + arg0 = args[0].(int64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionStorageStateCommitment_Call) Return() *ExecutionMetrics_ExecutionStorageStateCommitment_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionStorageStateCommitment_Call) RunAndReturn(run func(bytes int64)) *ExecutionMetrics_ExecutionStorageStateCommitment_Call { + _c.Run(run) + return _c +} + +// ExecutionSync provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionSync(syncing bool) { + _mock.Called(syncing) + return +} + +// ExecutionMetrics_ExecutionSync_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionSync' +type ExecutionMetrics_ExecutionSync_Call struct { + *mock.Call +} + +// ExecutionSync is a helper method to define mock.On call +// - syncing bool +func (_e *ExecutionMetrics_Expecter) ExecutionSync(syncing interface{}) *ExecutionMetrics_ExecutionSync_Call { + return &ExecutionMetrics_ExecutionSync_Call{Call: _e.mock.On("ExecutionSync", syncing)} +} + +func (_c *ExecutionMetrics_ExecutionSync_Call) Run(run func(syncing bool)) *ExecutionMetrics_ExecutionSync_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 bool + if args[0] != nil { + arg0 = args[0].(bool) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionSync_Call) Return() *ExecutionMetrics_ExecutionSync_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionSync_Call) RunAndReturn(run func(syncing bool)) *ExecutionMetrics_ExecutionSync_Call { + _c.Run(run) + return _c +} + +// ExecutionTargetChunkDataPackPrunedHeight provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionTargetChunkDataPackPrunedHeight(height uint64) { + _mock.Called(height) + return +} + +// ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionTargetChunkDataPackPrunedHeight' +type ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call struct { + *mock.Call +} + +// ExecutionTargetChunkDataPackPrunedHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutionMetrics_Expecter) ExecutionTargetChunkDataPackPrunedHeight(height interface{}) *ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call { + return &ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call{Call: _e.mock.On("ExecutionTargetChunkDataPackPrunedHeight", height)} +} + +func (_c *ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call) Run(run func(height uint64)) *ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call) Return() *ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call) RunAndReturn(run func(height uint64)) *ExecutionMetrics_ExecutionTargetChunkDataPackPrunedHeight_Call { + _c.Run(run) + return _c +} + +// ExecutionTransactionExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ExecutionTransactionExecuted(dur time.Duration, stats module.TransactionExecutionResultStats, info module.TransactionExecutionResultInfo) { + _mock.Called(dur, stats, info) + return +} + +// ExecutionMetrics_ExecutionTransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionTransactionExecuted' +type ExecutionMetrics_ExecutionTransactionExecuted_Call struct { + *mock.Call +} + +// ExecutionTransactionExecuted is a helper method to define mock.On call +// - dur time.Duration +// - stats module.TransactionExecutionResultStats +// - info module.TransactionExecutionResultInfo +func (_e *ExecutionMetrics_Expecter) ExecutionTransactionExecuted(dur interface{}, stats interface{}, info interface{}) *ExecutionMetrics_ExecutionTransactionExecuted_Call { + return &ExecutionMetrics_ExecutionTransactionExecuted_Call{Call: _e.mock.On("ExecutionTransactionExecuted", dur, stats, info)} +} + +func (_c *ExecutionMetrics_ExecutionTransactionExecuted_Call) Run(run func(dur time.Duration, stats module.TransactionExecutionResultStats, info module.TransactionExecutionResultInfo)) *ExecutionMetrics_ExecutionTransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 module.TransactionExecutionResultStats + if args[1] != nil { + arg1 = args[1].(module.TransactionExecutionResultStats) + } + var arg2 module.TransactionExecutionResultInfo + if args[2] != nil { + arg2 = args[2].(module.TransactionExecutionResultInfo) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ExecutionTransactionExecuted_Call) Return() *ExecutionMetrics_ExecutionTransactionExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ExecutionTransactionExecuted_Call) RunAndReturn(run func(dur time.Duration, stats module.TransactionExecutionResultStats, info module.TransactionExecutionResultInfo)) *ExecutionMetrics_ExecutionTransactionExecuted_Call { + _c.Run(run) + return _c +} + +// FinishBlockReceivedToExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) FinishBlockReceivedToExecuted(blockID flow.Identifier) { + _mock.Called(blockID) + return +} + +// ExecutionMetrics_FinishBlockReceivedToExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinishBlockReceivedToExecuted' +type ExecutionMetrics_FinishBlockReceivedToExecuted_Call struct { + *mock.Call +} + +// FinishBlockReceivedToExecuted is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionMetrics_Expecter) FinishBlockReceivedToExecuted(blockID interface{}) *ExecutionMetrics_FinishBlockReceivedToExecuted_Call { + return &ExecutionMetrics_FinishBlockReceivedToExecuted_Call{Call: _e.mock.On("FinishBlockReceivedToExecuted", blockID)} +} + +func (_c *ExecutionMetrics_FinishBlockReceivedToExecuted_Call) Run(run func(blockID flow.Identifier)) *ExecutionMetrics_FinishBlockReceivedToExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_FinishBlockReceivedToExecuted_Call) Return() *ExecutionMetrics_FinishBlockReceivedToExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_FinishBlockReceivedToExecuted_Call) RunAndReturn(run func(blockID flow.Identifier)) *ExecutionMetrics_FinishBlockReceivedToExecuted_Call { + _c.Run(run) + return _c +} + +// ForestApproxMemorySize provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ForestApproxMemorySize(bytes uint64) { + _mock.Called(bytes) + return +} + +// ExecutionMetrics_ForestApproxMemorySize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ForestApproxMemorySize' +type ExecutionMetrics_ForestApproxMemorySize_Call struct { + *mock.Call +} + +// ForestApproxMemorySize is a helper method to define mock.On call +// - bytes uint64 +func (_e *ExecutionMetrics_Expecter) ForestApproxMemorySize(bytes interface{}) *ExecutionMetrics_ForestApproxMemorySize_Call { + return &ExecutionMetrics_ForestApproxMemorySize_Call{Call: _e.mock.On("ForestApproxMemorySize", bytes)} +} + +func (_c *ExecutionMetrics_ForestApproxMemorySize_Call) Run(run func(bytes uint64)) *ExecutionMetrics_ForestApproxMemorySize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ForestApproxMemorySize_Call) Return() *ExecutionMetrics_ForestApproxMemorySize_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ForestApproxMemorySize_Call) RunAndReturn(run func(bytes uint64)) *ExecutionMetrics_ForestApproxMemorySize_Call { + _c.Run(run) + return _c +} + +// ForestNumberOfTrees provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ForestNumberOfTrees(number uint64) { + _mock.Called(number) + return +} + +// ExecutionMetrics_ForestNumberOfTrees_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ForestNumberOfTrees' +type ExecutionMetrics_ForestNumberOfTrees_Call struct { + *mock.Call +} + +// ForestNumberOfTrees is a helper method to define mock.On call +// - number uint64 +func (_e *ExecutionMetrics_Expecter) ForestNumberOfTrees(number interface{}) *ExecutionMetrics_ForestNumberOfTrees_Call { + return &ExecutionMetrics_ForestNumberOfTrees_Call{Call: _e.mock.On("ForestNumberOfTrees", number)} +} + +func (_c *ExecutionMetrics_ForestNumberOfTrees_Call) Run(run func(number uint64)) *ExecutionMetrics_ForestNumberOfTrees_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ForestNumberOfTrees_Call) Return() *ExecutionMetrics_ForestNumberOfTrees_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ForestNumberOfTrees_Call) RunAndReturn(run func(number uint64)) *ExecutionMetrics_ForestNumberOfTrees_Call { + _c.Run(run) + return _c +} + +// LatestTrieMaxDepthTouched provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) LatestTrieMaxDepthTouched(maxDepth uint16) { + _mock.Called(maxDepth) + return +} + +// ExecutionMetrics_LatestTrieMaxDepthTouched_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieMaxDepthTouched' +type ExecutionMetrics_LatestTrieMaxDepthTouched_Call struct { + *mock.Call +} + +// LatestTrieMaxDepthTouched is a helper method to define mock.On call +// - maxDepth uint16 +func (_e *ExecutionMetrics_Expecter) LatestTrieMaxDepthTouched(maxDepth interface{}) *ExecutionMetrics_LatestTrieMaxDepthTouched_Call { + return &ExecutionMetrics_LatestTrieMaxDepthTouched_Call{Call: _e.mock.On("LatestTrieMaxDepthTouched", maxDepth)} +} + +func (_c *ExecutionMetrics_LatestTrieMaxDepthTouched_Call) Run(run func(maxDepth uint16)) *ExecutionMetrics_LatestTrieMaxDepthTouched_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint16 + if args[0] != nil { + arg0 = args[0].(uint16) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_LatestTrieMaxDepthTouched_Call) Return() *ExecutionMetrics_LatestTrieMaxDepthTouched_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_LatestTrieMaxDepthTouched_Call) RunAndReturn(run func(maxDepth uint16)) *ExecutionMetrics_LatestTrieMaxDepthTouched_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegCount provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) LatestTrieRegCount(number uint64) { + _mock.Called(number) + return +} + +// ExecutionMetrics_LatestTrieRegCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegCount' +type ExecutionMetrics_LatestTrieRegCount_Call struct { + *mock.Call +} + +// LatestTrieRegCount is a helper method to define mock.On call +// - number uint64 +func (_e *ExecutionMetrics_Expecter) LatestTrieRegCount(number interface{}) *ExecutionMetrics_LatestTrieRegCount_Call { + return &ExecutionMetrics_LatestTrieRegCount_Call{Call: _e.mock.On("LatestTrieRegCount", number)} +} + +func (_c *ExecutionMetrics_LatestTrieRegCount_Call) Run(run func(number uint64)) *ExecutionMetrics_LatestTrieRegCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegCount_Call) Return() *ExecutionMetrics_LatestTrieRegCount_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegCount_Call) RunAndReturn(run func(number uint64)) *ExecutionMetrics_LatestTrieRegCount_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegCountDiff provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) LatestTrieRegCountDiff(number int64) { + _mock.Called(number) + return +} + +// ExecutionMetrics_LatestTrieRegCountDiff_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegCountDiff' +type ExecutionMetrics_LatestTrieRegCountDiff_Call struct { + *mock.Call +} + +// LatestTrieRegCountDiff is a helper method to define mock.On call +// - number int64 +func (_e *ExecutionMetrics_Expecter) LatestTrieRegCountDiff(number interface{}) *ExecutionMetrics_LatestTrieRegCountDiff_Call { + return &ExecutionMetrics_LatestTrieRegCountDiff_Call{Call: _e.mock.On("LatestTrieRegCountDiff", number)} +} + +func (_c *ExecutionMetrics_LatestTrieRegCountDiff_Call) Run(run func(number int64)) *ExecutionMetrics_LatestTrieRegCountDiff_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int64 + if args[0] != nil { + arg0 = args[0].(int64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegCountDiff_Call) Return() *ExecutionMetrics_LatestTrieRegCountDiff_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegCountDiff_Call) RunAndReturn(run func(number int64)) *ExecutionMetrics_LatestTrieRegCountDiff_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegSize provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) LatestTrieRegSize(size uint64) { + _mock.Called(size) + return +} + +// ExecutionMetrics_LatestTrieRegSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegSize' +type ExecutionMetrics_LatestTrieRegSize_Call struct { + *mock.Call +} + +// LatestTrieRegSize is a helper method to define mock.On call +// - size uint64 +func (_e *ExecutionMetrics_Expecter) LatestTrieRegSize(size interface{}) *ExecutionMetrics_LatestTrieRegSize_Call { + return &ExecutionMetrics_LatestTrieRegSize_Call{Call: _e.mock.On("LatestTrieRegSize", size)} +} + +func (_c *ExecutionMetrics_LatestTrieRegSize_Call) Run(run func(size uint64)) *ExecutionMetrics_LatestTrieRegSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegSize_Call) Return() *ExecutionMetrics_LatestTrieRegSize_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegSize_Call) RunAndReturn(run func(size uint64)) *ExecutionMetrics_LatestTrieRegSize_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegSizeDiff provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) LatestTrieRegSizeDiff(size int64) { + _mock.Called(size) + return +} + +// ExecutionMetrics_LatestTrieRegSizeDiff_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegSizeDiff' +type ExecutionMetrics_LatestTrieRegSizeDiff_Call struct { + *mock.Call +} + +// LatestTrieRegSizeDiff is a helper method to define mock.On call +// - size int64 +func (_e *ExecutionMetrics_Expecter) LatestTrieRegSizeDiff(size interface{}) *ExecutionMetrics_LatestTrieRegSizeDiff_Call { + return &ExecutionMetrics_LatestTrieRegSizeDiff_Call{Call: _e.mock.On("LatestTrieRegSizeDiff", size)} +} + +func (_c *ExecutionMetrics_LatestTrieRegSizeDiff_Call) Run(run func(size int64)) *ExecutionMetrics_LatestTrieRegSizeDiff_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int64 + if args[0] != nil { + arg0 = args[0].(int64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegSizeDiff_Call) Return() *ExecutionMetrics_LatestTrieRegSizeDiff_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_LatestTrieRegSizeDiff_Call) RunAndReturn(run func(size int64)) *ExecutionMetrics_LatestTrieRegSizeDiff_Call { + _c.Run(run) + return _c +} + +// ProofSize provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ProofSize(bytes uint32) { + _mock.Called(bytes) + return +} + +// ExecutionMetrics_ProofSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProofSize' +type ExecutionMetrics_ProofSize_Call struct { + *mock.Call +} + +// ProofSize is a helper method to define mock.On call +// - bytes uint32 +func (_e *ExecutionMetrics_Expecter) ProofSize(bytes interface{}) *ExecutionMetrics_ProofSize_Call { + return &ExecutionMetrics_ProofSize_Call{Call: _e.mock.On("ProofSize", bytes)} +} + +func (_c *ExecutionMetrics_ProofSize_Call) Run(run func(bytes uint32)) *ExecutionMetrics_ProofSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint32 + if args[0] != nil { + arg0 = args[0].(uint32) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ProofSize_Call) Return() *ExecutionMetrics_ProofSize_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ProofSize_Call) RunAndReturn(run func(bytes uint32)) *ExecutionMetrics_ProofSize_Call { + _c.Run(run) + return _c +} + +// ReadDuration provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ReadDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// ExecutionMetrics_ReadDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadDuration' +type ExecutionMetrics_ReadDuration_Call struct { + *mock.Call +} + +// ReadDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *ExecutionMetrics_Expecter) ReadDuration(duration interface{}) *ExecutionMetrics_ReadDuration_Call { + return &ExecutionMetrics_ReadDuration_Call{Call: _e.mock.On("ReadDuration", duration)} +} + +func (_c *ExecutionMetrics_ReadDuration_Call) Run(run func(duration time.Duration)) *ExecutionMetrics_ReadDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ReadDuration_Call) Return() *ExecutionMetrics_ReadDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ReadDuration_Call) RunAndReturn(run func(duration time.Duration)) *ExecutionMetrics_ReadDuration_Call { + _c.Run(run) + return _c +} + +// ReadDurationPerItem provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ReadDurationPerItem(duration time.Duration) { + _mock.Called(duration) + return +} + +// ExecutionMetrics_ReadDurationPerItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadDurationPerItem' +type ExecutionMetrics_ReadDurationPerItem_Call struct { + *mock.Call +} + +// ReadDurationPerItem is a helper method to define mock.On call +// - duration time.Duration +func (_e *ExecutionMetrics_Expecter) ReadDurationPerItem(duration interface{}) *ExecutionMetrics_ReadDurationPerItem_Call { + return &ExecutionMetrics_ReadDurationPerItem_Call{Call: _e.mock.On("ReadDurationPerItem", duration)} +} + +func (_c *ExecutionMetrics_ReadDurationPerItem_Call) Run(run func(duration time.Duration)) *ExecutionMetrics_ReadDurationPerItem_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ReadDurationPerItem_Call) Return() *ExecutionMetrics_ReadDurationPerItem_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ReadDurationPerItem_Call) RunAndReturn(run func(duration time.Duration)) *ExecutionMetrics_ReadDurationPerItem_Call { + _c.Run(run) + return _c +} + +// ReadValuesNumber provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ReadValuesNumber(number uint64) { + _mock.Called(number) + return +} + +// ExecutionMetrics_ReadValuesNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadValuesNumber' +type ExecutionMetrics_ReadValuesNumber_Call struct { + *mock.Call +} + +// ReadValuesNumber is a helper method to define mock.On call +// - number uint64 +func (_e *ExecutionMetrics_Expecter) ReadValuesNumber(number interface{}) *ExecutionMetrics_ReadValuesNumber_Call { + return &ExecutionMetrics_ReadValuesNumber_Call{Call: _e.mock.On("ReadValuesNumber", number)} +} + +func (_c *ExecutionMetrics_ReadValuesNumber_Call) Run(run func(number uint64)) *ExecutionMetrics_ReadValuesNumber_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ReadValuesNumber_Call) Return() *ExecutionMetrics_ReadValuesNumber_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ReadValuesNumber_Call) RunAndReturn(run func(number uint64)) *ExecutionMetrics_ReadValuesNumber_Call { + _c.Run(run) + return _c +} + +// ReadValuesSize provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) ReadValuesSize(byte uint64) { + _mock.Called(byte) + return +} + +// ExecutionMetrics_ReadValuesSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadValuesSize' +type ExecutionMetrics_ReadValuesSize_Call struct { + *mock.Call +} + +// ReadValuesSize is a helper method to define mock.On call +// - byte uint64 +func (_e *ExecutionMetrics_Expecter) ReadValuesSize(byte interface{}) *ExecutionMetrics_ReadValuesSize_Call { + return &ExecutionMetrics_ReadValuesSize_Call{Call: _e.mock.On("ReadValuesSize", byte)} +} + +func (_c *ExecutionMetrics_ReadValuesSize_Call) Run(run func(byte uint64)) *ExecutionMetrics_ReadValuesSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_ReadValuesSize_Call) Return() *ExecutionMetrics_ReadValuesSize_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_ReadValuesSize_Call) RunAndReturn(run func(byte uint64)) *ExecutionMetrics_ReadValuesSize_Call { + _c.Run(run) + return _c +} + +// RuntimeSetNumberOfAccounts provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) RuntimeSetNumberOfAccounts(count uint64) { + _mock.Called(count) + return +} + +// ExecutionMetrics_RuntimeSetNumberOfAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeSetNumberOfAccounts' +type ExecutionMetrics_RuntimeSetNumberOfAccounts_Call struct { + *mock.Call +} + +// RuntimeSetNumberOfAccounts is a helper method to define mock.On call +// - count uint64 +func (_e *ExecutionMetrics_Expecter) RuntimeSetNumberOfAccounts(count interface{}) *ExecutionMetrics_RuntimeSetNumberOfAccounts_Call { + return &ExecutionMetrics_RuntimeSetNumberOfAccounts_Call{Call: _e.mock.On("RuntimeSetNumberOfAccounts", count)} +} + +func (_c *ExecutionMetrics_RuntimeSetNumberOfAccounts_Call) Run(run func(count uint64)) *ExecutionMetrics_RuntimeSetNumberOfAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_RuntimeSetNumberOfAccounts_Call) Return() *ExecutionMetrics_RuntimeSetNumberOfAccounts_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_RuntimeSetNumberOfAccounts_Call) RunAndReturn(run func(count uint64)) *ExecutionMetrics_RuntimeSetNumberOfAccounts_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionChecked provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) RuntimeTransactionChecked(dur time.Duration) { + _mock.Called(dur) + return +} + +// ExecutionMetrics_RuntimeTransactionChecked_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionChecked' +type ExecutionMetrics_RuntimeTransactionChecked_Call struct { + *mock.Call +} + +// RuntimeTransactionChecked is a helper method to define mock.On call +// - dur time.Duration +func (_e *ExecutionMetrics_Expecter) RuntimeTransactionChecked(dur interface{}) *ExecutionMetrics_RuntimeTransactionChecked_Call { + return &ExecutionMetrics_RuntimeTransactionChecked_Call{Call: _e.mock.On("RuntimeTransactionChecked", dur)} +} + +func (_c *ExecutionMetrics_RuntimeTransactionChecked_Call) Run(run func(dur time.Duration)) *ExecutionMetrics_RuntimeTransactionChecked_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionChecked_Call) Return() *ExecutionMetrics_RuntimeTransactionChecked_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionChecked_Call) RunAndReturn(run func(dur time.Duration)) *ExecutionMetrics_RuntimeTransactionChecked_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionInterpreted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) RuntimeTransactionInterpreted(dur time.Duration) { + _mock.Called(dur) + return +} + +// ExecutionMetrics_RuntimeTransactionInterpreted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionInterpreted' +type ExecutionMetrics_RuntimeTransactionInterpreted_Call struct { + *mock.Call +} + +// RuntimeTransactionInterpreted is a helper method to define mock.On call +// - dur time.Duration +func (_e *ExecutionMetrics_Expecter) RuntimeTransactionInterpreted(dur interface{}) *ExecutionMetrics_RuntimeTransactionInterpreted_Call { + return &ExecutionMetrics_RuntimeTransactionInterpreted_Call{Call: _e.mock.On("RuntimeTransactionInterpreted", dur)} +} + +func (_c *ExecutionMetrics_RuntimeTransactionInterpreted_Call) Run(run func(dur time.Duration)) *ExecutionMetrics_RuntimeTransactionInterpreted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionInterpreted_Call) Return() *ExecutionMetrics_RuntimeTransactionInterpreted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionInterpreted_Call) RunAndReturn(run func(dur time.Duration)) *ExecutionMetrics_RuntimeTransactionInterpreted_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionParsed provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) RuntimeTransactionParsed(dur time.Duration) { + _mock.Called(dur) + return +} + +// ExecutionMetrics_RuntimeTransactionParsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionParsed' +type ExecutionMetrics_RuntimeTransactionParsed_Call struct { + *mock.Call +} + +// RuntimeTransactionParsed is a helper method to define mock.On call +// - dur time.Duration +func (_e *ExecutionMetrics_Expecter) RuntimeTransactionParsed(dur interface{}) *ExecutionMetrics_RuntimeTransactionParsed_Call { + return &ExecutionMetrics_RuntimeTransactionParsed_Call{Call: _e.mock.On("RuntimeTransactionParsed", dur)} +} + +func (_c *ExecutionMetrics_RuntimeTransactionParsed_Call) Run(run func(dur time.Duration)) *ExecutionMetrics_RuntimeTransactionParsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionParsed_Call) Return() *ExecutionMetrics_RuntimeTransactionParsed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionParsed_Call) RunAndReturn(run func(dur time.Duration)) *ExecutionMetrics_RuntimeTransactionParsed_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheHit provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) RuntimeTransactionProgramsCacheHit() { + _mock.Called() + return +} + +// ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheHit' +type ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheHit is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) RuntimeTransactionProgramsCacheHit() *ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call { + return &ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheHit")} +} + +func (_c *ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call) Run(run func()) *ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call) Return() *ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call) RunAndReturn(run func()) *ExecutionMetrics_RuntimeTransactionProgramsCacheHit_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheMiss provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) RuntimeTransactionProgramsCacheMiss() { + _mock.Called() + return +} + +// ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheMiss' +type ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheMiss is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) RuntimeTransactionProgramsCacheMiss() *ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call { + return &ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheMiss")} +} + +func (_c *ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call) Run(run func()) *ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call) Return() *ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call) RunAndReturn(run func()) *ExecutionMetrics_RuntimeTransactionProgramsCacheMiss_Call { + _c.Run(run) + return _c +} + +// SetNumberOfDeployedCOAs provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) SetNumberOfDeployedCOAs(count uint64) { + _mock.Called(count) + return +} + +// ExecutionMetrics_SetNumberOfDeployedCOAs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetNumberOfDeployedCOAs' +type ExecutionMetrics_SetNumberOfDeployedCOAs_Call struct { + *mock.Call +} + +// SetNumberOfDeployedCOAs is a helper method to define mock.On call +// - count uint64 +func (_e *ExecutionMetrics_Expecter) SetNumberOfDeployedCOAs(count interface{}) *ExecutionMetrics_SetNumberOfDeployedCOAs_Call { + return &ExecutionMetrics_SetNumberOfDeployedCOAs_Call{Call: _e.mock.On("SetNumberOfDeployedCOAs", count)} +} + +func (_c *ExecutionMetrics_SetNumberOfDeployedCOAs_Call) Run(run func(count uint64)) *ExecutionMetrics_SetNumberOfDeployedCOAs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_SetNumberOfDeployedCOAs_Call) Return() *ExecutionMetrics_SetNumberOfDeployedCOAs_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_SetNumberOfDeployedCOAs_Call) RunAndReturn(run func(count uint64)) *ExecutionMetrics_SetNumberOfDeployedCOAs_Call { + _c.Run(run) + return _c +} + +// StartBlockReceivedToExecuted provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) StartBlockReceivedToExecuted(blockID flow.Identifier) { + _mock.Called(blockID) + return +} + +// ExecutionMetrics_StartBlockReceivedToExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartBlockReceivedToExecuted' +type ExecutionMetrics_StartBlockReceivedToExecuted_Call struct { + *mock.Call +} + +// StartBlockReceivedToExecuted is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionMetrics_Expecter) StartBlockReceivedToExecuted(blockID interface{}) *ExecutionMetrics_StartBlockReceivedToExecuted_Call { + return &ExecutionMetrics_StartBlockReceivedToExecuted_Call{Call: _e.mock.On("StartBlockReceivedToExecuted", blockID)} +} + +func (_c *ExecutionMetrics_StartBlockReceivedToExecuted_Call) Run(run func(blockID flow.Identifier)) *ExecutionMetrics_StartBlockReceivedToExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_StartBlockReceivedToExecuted_Call) Return() *ExecutionMetrics_StartBlockReceivedToExecuted_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_StartBlockReceivedToExecuted_Call) RunAndReturn(run func(blockID flow.Identifier)) *ExecutionMetrics_StartBlockReceivedToExecuted_Call { + _c.Run(run) + return _c +} + +// UpdateCollectionMaxHeight provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) UpdateCollectionMaxHeight(height uint64) { + _mock.Called(height) + return +} + +// ExecutionMetrics_UpdateCollectionMaxHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateCollectionMaxHeight' +type ExecutionMetrics_UpdateCollectionMaxHeight_Call struct { + *mock.Call +} + +// UpdateCollectionMaxHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutionMetrics_Expecter) UpdateCollectionMaxHeight(height interface{}) *ExecutionMetrics_UpdateCollectionMaxHeight_Call { + return &ExecutionMetrics_UpdateCollectionMaxHeight_Call{Call: _e.mock.On("UpdateCollectionMaxHeight", height)} +} + +func (_c *ExecutionMetrics_UpdateCollectionMaxHeight_Call) Run(run func(height uint64)) *ExecutionMetrics_UpdateCollectionMaxHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_UpdateCollectionMaxHeight_Call) Return() *ExecutionMetrics_UpdateCollectionMaxHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_UpdateCollectionMaxHeight_Call) RunAndReturn(run func(height uint64)) *ExecutionMetrics_UpdateCollectionMaxHeight_Call { + _c.Run(run) + return _c +} + +// UpdateCount provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) UpdateCount() { + _mock.Called() + return +} + +// ExecutionMetrics_UpdateCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateCount' +type ExecutionMetrics_UpdateCount_Call struct { + *mock.Call +} + +// UpdateCount is a helper method to define mock.On call +func (_e *ExecutionMetrics_Expecter) UpdateCount() *ExecutionMetrics_UpdateCount_Call { + return &ExecutionMetrics_UpdateCount_Call{Call: _e.mock.On("UpdateCount")} +} + +func (_c *ExecutionMetrics_UpdateCount_Call) Run(run func()) *ExecutionMetrics_UpdateCount_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionMetrics_UpdateCount_Call) Return() *ExecutionMetrics_UpdateCount_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_UpdateCount_Call) RunAndReturn(run func()) *ExecutionMetrics_UpdateCount_Call { + _c.Run(run) + return _c +} + +// UpdateDuration provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) UpdateDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// ExecutionMetrics_UpdateDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateDuration' +type ExecutionMetrics_UpdateDuration_Call struct { + *mock.Call +} + +// UpdateDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *ExecutionMetrics_Expecter) UpdateDuration(duration interface{}) *ExecutionMetrics_UpdateDuration_Call { + return &ExecutionMetrics_UpdateDuration_Call{Call: _e.mock.On("UpdateDuration", duration)} +} + +func (_c *ExecutionMetrics_UpdateDuration_Call) Run(run func(duration time.Duration)) *ExecutionMetrics_UpdateDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_UpdateDuration_Call) Return() *ExecutionMetrics_UpdateDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_UpdateDuration_Call) RunAndReturn(run func(duration time.Duration)) *ExecutionMetrics_UpdateDuration_Call { + _c.Run(run) + return _c +} + +// UpdateDurationPerItem provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) UpdateDurationPerItem(duration time.Duration) { + _mock.Called(duration) + return +} + +// ExecutionMetrics_UpdateDurationPerItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateDurationPerItem' +type ExecutionMetrics_UpdateDurationPerItem_Call struct { + *mock.Call +} + +// UpdateDurationPerItem is a helper method to define mock.On call +// - duration time.Duration +func (_e *ExecutionMetrics_Expecter) UpdateDurationPerItem(duration interface{}) *ExecutionMetrics_UpdateDurationPerItem_Call { + return &ExecutionMetrics_UpdateDurationPerItem_Call{Call: _e.mock.On("UpdateDurationPerItem", duration)} +} + +func (_c *ExecutionMetrics_UpdateDurationPerItem_Call) Run(run func(duration time.Duration)) *ExecutionMetrics_UpdateDurationPerItem_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_UpdateDurationPerItem_Call) Return() *ExecutionMetrics_UpdateDurationPerItem_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_UpdateDurationPerItem_Call) RunAndReturn(run func(duration time.Duration)) *ExecutionMetrics_UpdateDurationPerItem_Call { + _c.Run(run) + return _c +} + +// UpdateValuesNumber provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) UpdateValuesNumber(number uint64) { + _mock.Called(number) + return +} + +// ExecutionMetrics_UpdateValuesNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateValuesNumber' +type ExecutionMetrics_UpdateValuesNumber_Call struct { + *mock.Call +} + +// UpdateValuesNumber is a helper method to define mock.On call +// - number uint64 +func (_e *ExecutionMetrics_Expecter) UpdateValuesNumber(number interface{}) *ExecutionMetrics_UpdateValuesNumber_Call { + return &ExecutionMetrics_UpdateValuesNumber_Call{Call: _e.mock.On("UpdateValuesNumber", number)} +} + +func (_c *ExecutionMetrics_UpdateValuesNumber_Call) Run(run func(number uint64)) *ExecutionMetrics_UpdateValuesNumber_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_UpdateValuesNumber_Call) Return() *ExecutionMetrics_UpdateValuesNumber_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_UpdateValuesNumber_Call) RunAndReturn(run func(number uint64)) *ExecutionMetrics_UpdateValuesNumber_Call { + _c.Run(run) + return _c +} + +// UpdateValuesSize provides a mock function for the type ExecutionMetrics +func (_mock *ExecutionMetrics) UpdateValuesSize(byte uint64) { + _mock.Called(byte) + return +} + +// ExecutionMetrics_UpdateValuesSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateValuesSize' +type ExecutionMetrics_UpdateValuesSize_Call struct { + *mock.Call +} + +// UpdateValuesSize is a helper method to define mock.On call +// - byte uint64 +func (_e *ExecutionMetrics_Expecter) UpdateValuesSize(byte interface{}) *ExecutionMetrics_UpdateValuesSize_Call { + return &ExecutionMetrics_UpdateValuesSize_Call{Call: _e.mock.On("UpdateValuesSize", byte)} +} + +func (_c *ExecutionMetrics_UpdateValuesSize_Call) Run(run func(byte uint64)) *ExecutionMetrics_UpdateValuesSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionMetrics_UpdateValuesSize_Call) Return() *ExecutionMetrics_UpdateValuesSize_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionMetrics_UpdateValuesSize_Call) RunAndReturn(run func(byte uint64)) *ExecutionMetrics_UpdateValuesSize_Call { + _c.Run(run) + return _c } diff --git a/module/mock/execution_state_indexer_metrics.go b/module/mock/execution_state_indexer_metrics.go index e278c84d79a..362beb5dec6 100644 --- a/module/mock/execution_state_indexer_metrics.go +++ b/module/mock/execution_state_indexer_metrics.go @@ -1,43 +1,175 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewExecutionStateIndexerMetrics creates a new instance of ExecutionStateIndexerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionStateIndexerMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionStateIndexerMetrics { + mock := &ExecutionStateIndexerMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionStateIndexerMetrics is an autogenerated mock type for the ExecutionStateIndexerMetrics type type ExecutionStateIndexerMetrics struct { mock.Mock } -// BlockIndexed provides a mock function with given fields: height, duration, events, registers, transactionResults -func (_m *ExecutionStateIndexerMetrics) BlockIndexed(height uint64, duration time.Duration, events int, registers int, transactionResults int) { - _m.Called(height, duration, events, registers, transactionResults) +type ExecutionStateIndexerMetrics_Expecter struct { + mock *mock.Mock } -// BlockReindexed provides a mock function with no fields -func (_m *ExecutionStateIndexerMetrics) BlockReindexed() { - _m.Called() +func (_m *ExecutionStateIndexerMetrics) EXPECT() *ExecutionStateIndexerMetrics_Expecter { + return &ExecutionStateIndexerMetrics_Expecter{mock: &_m.Mock} } -// InitializeLatestHeight provides a mock function with given fields: height -func (_m *ExecutionStateIndexerMetrics) InitializeLatestHeight(height uint64) { - _m.Called(height) +// BlockIndexed provides a mock function for the type ExecutionStateIndexerMetrics +func (_mock *ExecutionStateIndexerMetrics) BlockIndexed(height uint64, duration time.Duration, events int, registers int, transactionResults int) { + _mock.Called(height, duration, events, registers, transactionResults) + return } -// NewExecutionStateIndexerMetrics creates a new instance of ExecutionStateIndexerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionStateIndexerMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionStateIndexerMetrics { - mock := &ExecutionStateIndexerMetrics{} - mock.Mock.Test(t) +// ExecutionStateIndexerMetrics_BlockIndexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockIndexed' +type ExecutionStateIndexerMetrics_BlockIndexed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// BlockIndexed is a helper method to define mock.On call +// - height uint64 +// - duration time.Duration +// - events int +// - registers int +// - transactionResults int +func (_e *ExecutionStateIndexerMetrics_Expecter) BlockIndexed(height interface{}, duration interface{}, events interface{}, registers interface{}, transactionResults interface{}) *ExecutionStateIndexerMetrics_BlockIndexed_Call { + return &ExecutionStateIndexerMetrics_BlockIndexed_Call{Call: _e.mock.On("BlockIndexed", height, duration, events, registers, transactionResults)} +} - return mock +func (_c *ExecutionStateIndexerMetrics_BlockIndexed_Call) Run(run func(height uint64, duration time.Duration, events int, registers int, transactionResults int)) *ExecutionStateIndexerMetrics_BlockIndexed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *ExecutionStateIndexerMetrics_BlockIndexed_Call) Return() *ExecutionStateIndexerMetrics_BlockIndexed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionStateIndexerMetrics_BlockIndexed_Call) RunAndReturn(run func(height uint64, duration time.Duration, events int, registers int, transactionResults int)) *ExecutionStateIndexerMetrics_BlockIndexed_Call { + _c.Run(run) + return _c +} + +// BlockReindexed provides a mock function for the type ExecutionStateIndexerMetrics +func (_mock *ExecutionStateIndexerMetrics) BlockReindexed() { + _mock.Called() + return +} + +// ExecutionStateIndexerMetrics_BlockReindexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockReindexed' +type ExecutionStateIndexerMetrics_BlockReindexed_Call struct { + *mock.Call +} + +// BlockReindexed is a helper method to define mock.On call +func (_e *ExecutionStateIndexerMetrics_Expecter) BlockReindexed() *ExecutionStateIndexerMetrics_BlockReindexed_Call { + return &ExecutionStateIndexerMetrics_BlockReindexed_Call{Call: _e.mock.On("BlockReindexed")} +} + +func (_c *ExecutionStateIndexerMetrics_BlockReindexed_Call) Run(run func()) *ExecutionStateIndexerMetrics_BlockReindexed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionStateIndexerMetrics_BlockReindexed_Call) Return() *ExecutionStateIndexerMetrics_BlockReindexed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionStateIndexerMetrics_BlockReindexed_Call) RunAndReturn(run func()) *ExecutionStateIndexerMetrics_BlockReindexed_Call { + _c.Run(run) + return _c +} + +// InitializeLatestHeight provides a mock function for the type ExecutionStateIndexerMetrics +func (_mock *ExecutionStateIndexerMetrics) InitializeLatestHeight(height uint64) { + _mock.Called(height) + return +} + +// ExecutionStateIndexerMetrics_InitializeLatestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InitializeLatestHeight' +type ExecutionStateIndexerMetrics_InitializeLatestHeight_Call struct { + *mock.Call +} + +// InitializeLatestHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ExecutionStateIndexerMetrics_Expecter) InitializeLatestHeight(height interface{}) *ExecutionStateIndexerMetrics_InitializeLatestHeight_Call { + return &ExecutionStateIndexerMetrics_InitializeLatestHeight_Call{Call: _e.mock.On("InitializeLatestHeight", height)} +} + +func (_c *ExecutionStateIndexerMetrics_InitializeLatestHeight_Call) Run(run func(height uint64)) *ExecutionStateIndexerMetrics_InitializeLatestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionStateIndexerMetrics_InitializeLatestHeight_Call) Return() *ExecutionStateIndexerMetrics_InitializeLatestHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionStateIndexerMetrics_InitializeLatestHeight_Call) RunAndReturn(run func(height uint64)) *ExecutionStateIndexerMetrics_InitializeLatestHeight_Call { + _c.Run(run) + return _c } diff --git a/module/mock/extended_indexing_metrics.go b/module/mock/extended_indexing_metrics.go new file mode 100644 index 00000000000..762fc1f3b90 --- /dev/null +++ b/module/mock/extended_indexing_metrics.go @@ -0,0 +1,272 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewExtendedIndexingMetrics creates a new instance of ExtendedIndexingMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExtendedIndexingMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ExtendedIndexingMetrics { + mock := &ExtendedIndexingMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ExtendedIndexingMetrics is an autogenerated mock type for the ExtendedIndexingMetrics type +type ExtendedIndexingMetrics struct { + mock.Mock +} + +type ExtendedIndexingMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *ExtendedIndexingMetrics) EXPECT() *ExtendedIndexingMetrics_Expecter { + return &ExtendedIndexingMetrics_Expecter{mock: &_m.Mock} +} + +// BlockIndexedExtended provides a mock function for the type ExtendedIndexingMetrics +func (_mock *ExtendedIndexingMetrics) BlockIndexedExtended(indexer string, height uint64) { + _mock.Called(indexer, height) + return +} + +// ExtendedIndexingMetrics_BlockIndexedExtended_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockIndexedExtended' +type ExtendedIndexingMetrics_BlockIndexedExtended_Call struct { + *mock.Call +} + +// BlockIndexedExtended is a helper method to define mock.On call +// - indexer string +// - height uint64 +func (_e *ExtendedIndexingMetrics_Expecter) BlockIndexedExtended(indexer interface{}, height interface{}) *ExtendedIndexingMetrics_BlockIndexedExtended_Call { + return &ExtendedIndexingMetrics_BlockIndexedExtended_Call{Call: _e.mock.On("BlockIndexedExtended", indexer, height)} +} + +func (_c *ExtendedIndexingMetrics_BlockIndexedExtended_Call) Run(run func(indexer string, height uint64)) *ExtendedIndexingMetrics_BlockIndexedExtended_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExtendedIndexingMetrics_BlockIndexedExtended_Call) Return() *ExtendedIndexingMetrics_BlockIndexedExtended_Call { + _c.Call.Return() + return _c +} + +func (_c *ExtendedIndexingMetrics_BlockIndexedExtended_Call) RunAndReturn(run func(indexer string, height uint64)) *ExtendedIndexingMetrics_BlockIndexedExtended_Call { + _c.Run(run) + return _c +} + +// ContractDeploymentIndexed provides a mock function for the type ExtendedIndexingMetrics +func (_mock *ExtendedIndexingMetrics) ContractDeploymentIndexed(created int, updated int) { + _mock.Called(created, updated) + return +} + +// ExtendedIndexingMetrics_ContractDeploymentIndexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ContractDeploymentIndexed' +type ExtendedIndexingMetrics_ContractDeploymentIndexed_Call struct { + *mock.Call +} + +// ContractDeploymentIndexed is a helper method to define mock.On call +// - created int +// - updated int +func (_e *ExtendedIndexingMetrics_Expecter) ContractDeploymentIndexed(created interface{}, updated interface{}) *ExtendedIndexingMetrics_ContractDeploymentIndexed_Call { + return &ExtendedIndexingMetrics_ContractDeploymentIndexed_Call{Call: _e.mock.On("ContractDeploymentIndexed", created, updated)} +} + +func (_c *ExtendedIndexingMetrics_ContractDeploymentIndexed_Call) Run(run func(created int, updated int)) *ExtendedIndexingMetrics_ContractDeploymentIndexed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExtendedIndexingMetrics_ContractDeploymentIndexed_Call) Return() *ExtendedIndexingMetrics_ContractDeploymentIndexed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExtendedIndexingMetrics_ContractDeploymentIndexed_Call) RunAndReturn(run func(created int, updated int)) *ExtendedIndexingMetrics_ContractDeploymentIndexed_Call { + _c.Run(run) + return _c +} + +// FTTransferIndexed provides a mock function for the type ExtendedIndexingMetrics +func (_mock *ExtendedIndexingMetrics) FTTransferIndexed(count int) { + _mock.Called(count) + return +} + +// ExtendedIndexingMetrics_FTTransferIndexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FTTransferIndexed' +type ExtendedIndexingMetrics_FTTransferIndexed_Call struct { + *mock.Call +} + +// FTTransferIndexed is a helper method to define mock.On call +// - count int +func (_e *ExtendedIndexingMetrics_Expecter) FTTransferIndexed(count interface{}) *ExtendedIndexingMetrics_FTTransferIndexed_Call { + return &ExtendedIndexingMetrics_FTTransferIndexed_Call{Call: _e.mock.On("FTTransferIndexed", count)} +} + +func (_c *ExtendedIndexingMetrics_FTTransferIndexed_Call) Run(run func(count int)) *ExtendedIndexingMetrics_FTTransferIndexed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExtendedIndexingMetrics_FTTransferIndexed_Call) Return() *ExtendedIndexingMetrics_FTTransferIndexed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExtendedIndexingMetrics_FTTransferIndexed_Call) RunAndReturn(run func(count int)) *ExtendedIndexingMetrics_FTTransferIndexed_Call { + _c.Run(run) + return _c +} + +// NFTTransferIndexed provides a mock function for the type ExtendedIndexingMetrics +func (_mock *ExtendedIndexingMetrics) NFTTransferIndexed(count int) { + _mock.Called(count) + return +} + +// ExtendedIndexingMetrics_NFTTransferIndexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NFTTransferIndexed' +type ExtendedIndexingMetrics_NFTTransferIndexed_Call struct { + *mock.Call +} + +// NFTTransferIndexed is a helper method to define mock.On call +// - count int +func (_e *ExtendedIndexingMetrics_Expecter) NFTTransferIndexed(count interface{}) *ExtendedIndexingMetrics_NFTTransferIndexed_Call { + return &ExtendedIndexingMetrics_NFTTransferIndexed_Call{Call: _e.mock.On("NFTTransferIndexed", count)} +} + +func (_c *ExtendedIndexingMetrics_NFTTransferIndexed_Call) Run(run func(count int)) *ExtendedIndexingMetrics_NFTTransferIndexed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExtendedIndexingMetrics_NFTTransferIndexed_Call) Return() *ExtendedIndexingMetrics_NFTTransferIndexed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExtendedIndexingMetrics_NFTTransferIndexed_Call) RunAndReturn(run func(count int)) *ExtendedIndexingMetrics_NFTTransferIndexed_Call { + _c.Run(run) + return _c +} + +// ScheduledTransactionIndexed provides a mock function for the type ExtendedIndexingMetrics +func (_mock *ExtendedIndexingMetrics) ScheduledTransactionIndexed(scheduled int, executed int, failed int, canceled int, backfilled int) { + _mock.Called(scheduled, executed, failed, canceled, backfilled) + return +} + +// ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScheduledTransactionIndexed' +type ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call struct { + *mock.Call +} + +// ScheduledTransactionIndexed is a helper method to define mock.On call +// - scheduled int +// - executed int +// - failed int +// - canceled int +// - backfilled int +func (_e *ExtendedIndexingMetrics_Expecter) ScheduledTransactionIndexed(scheduled interface{}, executed interface{}, failed interface{}, canceled interface{}, backfilled interface{}) *ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call { + return &ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call{Call: _e.mock.On("ScheduledTransactionIndexed", scheduled, executed, failed, canceled, backfilled)} +} + +func (_c *ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call) Run(run func(scheduled int, executed int, failed int, canceled int, backfilled int)) *ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call) Return() *ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call { + _c.Call.Return() + return _c +} + +func (_c *ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call) RunAndReturn(run func(scheduled int, executed int, failed int, canceled int, backfilled int)) *ExtendedIndexingMetrics_ScheduledTransactionIndexed_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/finalized_header_cache.go b/module/mock/finalized_header_cache.go index 66f99b6979f..91603d8d4a9 100644 --- a/module/mock/finalized_header_cache.go +++ b/module/mock/finalized_header_cache.go @@ -1,47 +1,83 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewFinalizedHeaderCache creates a new instance of FinalizedHeaderCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFinalizedHeaderCache(t interface { + mock.TestingT + Cleanup(func()) +}) *FinalizedHeaderCache { + mock := &FinalizedHeaderCache{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // FinalizedHeaderCache is an autogenerated mock type for the FinalizedHeaderCache type type FinalizedHeaderCache struct { mock.Mock } -// Get provides a mock function with no fields -func (_m *FinalizedHeaderCache) Get() *flow.Header { - ret := _m.Called() +type FinalizedHeaderCache_Expecter struct { + mock *mock.Mock +} + +func (_m *FinalizedHeaderCache) EXPECT() *FinalizedHeaderCache_Expecter { + return &FinalizedHeaderCache_Expecter{mock: &_m.Mock} +} + +// Get provides a mock function for the type FinalizedHeaderCache +func (_mock *FinalizedHeaderCache) Get() *flow.Header { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Get") } var r0 *flow.Header - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - return r0 } -// NewFinalizedHeaderCache creates a new instance of FinalizedHeaderCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewFinalizedHeaderCache(t interface { - mock.TestingT - Cleanup(func()) -}) *FinalizedHeaderCache { - mock := &FinalizedHeaderCache{} - mock.Mock.Test(t) +// FinalizedHeaderCache_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type FinalizedHeaderCache_Get_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Get is a helper method to define mock.On call +func (_e *FinalizedHeaderCache_Expecter) Get() *FinalizedHeaderCache_Get_Call { + return &FinalizedHeaderCache_Get_Call{Call: _e.mock.On("Get")} +} - return mock +func (_c *FinalizedHeaderCache_Get_Call) Run(run func()) *FinalizedHeaderCache_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FinalizedHeaderCache_Get_Call) Return(header *flow.Header) *FinalizedHeaderCache_Get_Call { + _c.Call.Return(header) + return _c +} + +func (_c *FinalizedHeaderCache_Get_Call) RunAndReturn(run func() *flow.Header) *FinalizedHeaderCache_Get_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/finalizer.go b/module/mock/finalizer.go index 2891bdf6755..b8e8b2df2d0 100644 --- a/module/mock/finalizer.go +++ b/module/mock/finalizer.go @@ -1,45 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewFinalizer creates a new instance of Finalizer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFinalizer(t interface { + mock.TestingT + Cleanup(func()) +}) *Finalizer { + mock := &Finalizer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Finalizer is an autogenerated mock type for the Finalizer type type Finalizer struct { mock.Mock } -// MakeFinal provides a mock function with given fields: blockID -func (_m *Finalizer) MakeFinal(blockID flow.Identifier) error { - ret := _m.Called(blockID) +type Finalizer_Expecter struct { + mock *mock.Mock +} + +func (_m *Finalizer) EXPECT() *Finalizer_Expecter { + return &Finalizer_Expecter{mock: &_m.Mock} +} + +// MakeFinal provides a mock function for the type Finalizer +func (_mock *Finalizer) MakeFinal(blockID flow.Identifier) error { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for MakeFinal") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier) error); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) error); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Error(0) } - return r0 } -// NewFinalizer creates a new instance of Finalizer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewFinalizer(t interface { - mock.TestingT - Cleanup(func()) -}) *Finalizer { - mock := &Finalizer{} - mock.Mock.Test(t) +// Finalizer_MakeFinal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MakeFinal' +type Finalizer_MakeFinal_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// MakeFinal is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Finalizer_Expecter) MakeFinal(blockID interface{}) *Finalizer_MakeFinal_Call { + return &Finalizer_MakeFinal_Call{Call: _e.mock.On("MakeFinal", blockID)} +} - return mock +func (_c *Finalizer_MakeFinal_Call) Run(run func(blockID flow.Identifier)) *Finalizer_MakeFinal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Finalizer_MakeFinal_Call) Return(err error) *Finalizer_MakeFinal_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Finalizer_MakeFinal_Call) RunAndReturn(run func(blockID flow.Identifier) error) *Finalizer_MakeFinal_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/gossip_sub_metrics.go b/module/mock/gossip_sub_metrics.go index 572f484c9be..57ce8bfdfb4 100644 --- a/module/mock/gossip_sub_metrics.go +++ b/module/mock/gossip_sub_metrics.go @@ -1,296 +1,2181 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" + "time" + + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p/message" mock "github.com/stretchr/testify/mock" +) + +// NewGossipSubMetrics creates a new instance of GossipSubMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubMetrics { + mock := &GossipSubMetrics{} + mock.Mock.Test(t) - p2pmsg "github.com/onflow/flow-go/network/p2p/message" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // GossipSubMetrics is an autogenerated mock type for the GossipSubMetrics type type GossipSubMetrics struct { mock.Mock } -// AsyncProcessingFinished provides a mock function with given fields: duration -func (_m *GossipSubMetrics) AsyncProcessingFinished(duration time.Duration) { - _m.Called(duration) +type GossipSubMetrics_Expecter struct { + mock *mock.Mock } -// AsyncProcessingStarted provides a mock function with no fields -func (_m *GossipSubMetrics) AsyncProcessingStarted() { - _m.Called() +func (_m *GossipSubMetrics) EXPECT() *GossipSubMetrics_Expecter { + return &GossipSubMetrics_Expecter{mock: &_m.Mock} } -// OnActiveClusterIDsNotSetErr provides a mock function with no fields -func (_m *GossipSubMetrics) OnActiveClusterIDsNotSetErr() { - _m.Called() +// AsyncProcessingFinished provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) AsyncProcessingFinished(duration time.Duration) { + _mock.Called(duration) + return } -// OnAppSpecificScoreUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubMetrics) OnAppSpecificScoreUpdated(_a0 float64) { - _m.Called(_a0) +// GossipSubMetrics_AsyncProcessingFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingFinished' +type GossipSubMetrics_AsyncProcessingFinished_Call struct { + *mock.Call } -// OnBehaviourPenaltyUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubMetrics) OnBehaviourPenaltyUpdated(_a0 float64) { - _m.Called(_a0) +// AsyncProcessingFinished is a helper method to define mock.On call +// - duration time.Duration +func (_e *GossipSubMetrics_Expecter) AsyncProcessingFinished(duration interface{}) *GossipSubMetrics_AsyncProcessingFinished_Call { + return &GossipSubMetrics_AsyncProcessingFinished_Call{Call: _e.mock.On("AsyncProcessingFinished", duration)} } -// OnControlMessagesTruncated provides a mock function with given fields: messageType, diff -func (_m *GossipSubMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { - _m.Called(messageType, diff) +func (_c *GossipSubMetrics_AsyncProcessingFinished_Call) Run(run func(duration time.Duration)) *GossipSubMetrics_AsyncProcessingFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// OnFirstMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubMetrics) OnFirstMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *GossipSubMetrics_AsyncProcessingFinished_Call) Return() *GossipSubMetrics_AsyncProcessingFinished_Call { + _c.Call.Return() + return _c } -// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_AsyncProcessingFinished_Call) RunAndReturn(run func(duration time.Duration)) *GossipSubMetrics_AsyncProcessingFinished_Call { + _c.Run(run) + return _c } -// OnGraftInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnGraftInvalidTopicIdsExceedThreshold() { - _m.Called() +// AsyncProcessingStarted provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) AsyncProcessingStarted() { + _mock.Called() + return } -// OnGraftMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *GossipSubMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +// GossipSubMetrics_AsyncProcessingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingStarted' +type GossipSubMetrics_AsyncProcessingStarted_Call struct { + *mock.Call } -// OnIHaveControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *GossipSubMetrics) OnIHaveControlMessageIdsTruncated(diff int) { - _m.Called(diff) +// AsyncProcessingStarted is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) AsyncProcessingStarted() *GossipSubMetrics_AsyncProcessingStarted_Call { + return &GossipSubMetrics_AsyncProcessingStarted_Call{Call: _e.mock.On("AsyncProcessingStarted")} } -// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_AsyncProcessingStarted_Call) Run(run func()) *GossipSubMetrics_AsyncProcessingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_AsyncProcessingStarted_Call) Return() *GossipSubMetrics_AsyncProcessingStarted_Call { + _c.Call.Return() + return _c } -// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_AsyncProcessingStarted_Call) RunAndReturn(run func()) *GossipSubMetrics_AsyncProcessingStarted_Call { + _c.Run(run) + return _c } -// OnIHaveMessageIDsReceived provides a mock function with given fields: channel, msgIdCount -func (_m *GossipSubMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { - _m.Called(channel, msgIdCount) +// OnActiveClusterIDsNotSetErr provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnActiveClusterIDsNotSetErr() { + _mock.Called() + return } -// OnIHaveMessagesInspected provides a mock function with given fields: duplicateTopicIds, duplicateMessageIds, invalidTopicIds -func (_m *GossipSubMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) +// GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnActiveClusterIDsNotSetErr' +type GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call struct { + *mock.Call } -// OnIPColocationFactorUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubMetrics) OnIPColocationFactorUpdated(_a0 float64) { - _m.Called(_a0) +// OnActiveClusterIDsNotSetErr is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnActiveClusterIDsNotSetErr() *GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call { + return &GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call{Call: _e.mock.On("OnActiveClusterIDsNotSetErr")} } -// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call) Run(run func()) *GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnIWantControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *GossipSubMetrics) OnIWantControlMessageIdsTruncated(diff int) { - _m.Called(diff) +func (_c *GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call) Return() *GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Return() + return _c } -// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call) RunAndReturn(run func()) *GossipSubMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Run(run) + return _c } -// OnIWantMessageIDsReceived provides a mock function with given fields: msgIdCount -func (_m *GossipSubMetrics) OnIWantMessageIDsReceived(msgIdCount int) { - _m.Called(msgIdCount) +// OnAppSpecificScoreUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnAppSpecificScoreUpdated(f float64) { + _mock.Called(f) + return } -// OnIWantMessagesInspected provides a mock function with given fields: duplicateCount, cacheMissCount -func (_m *GossipSubMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { - _m.Called(duplicateCount, cacheMissCount) +// GossipSubMetrics_OnAppSpecificScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAppSpecificScoreUpdated' +type GossipSubMetrics_OnAppSpecificScoreUpdated_Call struct { + *mock.Call } -// OnIncomingRpcReceived provides a mock function with given fields: iHaveCount, iWantCount, graftCount, pruneCount, msgCount -func (_m *GossipSubMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { - _m.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) +// OnAppSpecificScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubMetrics_Expecter) OnAppSpecificScoreUpdated(f interface{}) *GossipSubMetrics_OnAppSpecificScoreUpdated_Call { + return &GossipSubMetrics_OnAppSpecificScoreUpdated_Call{Call: _e.mock.On("OnAppSpecificScoreUpdated", f)} } -// OnInvalidControlMessageNotificationSent provides a mock function with no fields -func (_m *GossipSubMetrics) OnInvalidControlMessageNotificationSent() { - _m.Called() +func (_c *GossipSubMetrics_OnAppSpecificScoreUpdated_Call) Run(run func(f float64)) *GossipSubMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c } -// OnInvalidMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubMetrics) OnInvalidMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *GossipSubMetrics_OnAppSpecificScoreUpdated_Call) Return() *GossipSubMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Return() + return _c } -// OnInvalidTopicIdDetectedForControlMessage provides a mock function with given fields: messageType -func (_m *GossipSubMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { - _m.Called(messageType) +func (_c *GossipSubMetrics_OnAppSpecificScoreUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubMetrics_OnAppSpecificScoreUpdated_Call { + _c.Run(run) + return _c } -// OnLocalMeshSizeUpdated provides a mock function with given fields: topic, size -func (_m *GossipSubMetrics) OnLocalMeshSizeUpdated(topic string, size int) { - _m.Called(topic, size) +// OnBehaviourPenaltyUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnBehaviourPenaltyUpdated(f float64) { + _mock.Called(f) + return } -// OnLocalPeerJoinedTopic provides a mock function with no fields -func (_m *GossipSubMetrics) OnLocalPeerJoinedTopic() { - _m.Called() +// GossipSubMetrics_OnBehaviourPenaltyUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBehaviourPenaltyUpdated' +type GossipSubMetrics_OnBehaviourPenaltyUpdated_Call struct { + *mock.Call } -// OnLocalPeerLeftTopic provides a mock function with no fields -func (_m *GossipSubMetrics) OnLocalPeerLeftTopic() { - _m.Called() +// OnBehaviourPenaltyUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubMetrics_Expecter) OnBehaviourPenaltyUpdated(f interface{}) *GossipSubMetrics_OnBehaviourPenaltyUpdated_Call { + return &GossipSubMetrics_OnBehaviourPenaltyUpdated_Call{Call: _e.mock.On("OnBehaviourPenaltyUpdated", f)} } -// OnMeshMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubMetrics) OnMeshMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *GossipSubMetrics_OnBehaviourPenaltyUpdated_Call) Run(run func(f float64)) *GossipSubMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c } -// OnMessageDeliveredToAllSubscribers provides a mock function with given fields: size -func (_m *GossipSubMetrics) OnMessageDeliveredToAllSubscribers(size int) { - _m.Called(size) +func (_c *GossipSubMetrics_OnBehaviourPenaltyUpdated_Call) Return() *GossipSubMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Return() + return _c } -// OnMessageDuplicate provides a mock function with given fields: size -func (_m *GossipSubMetrics) OnMessageDuplicate(size int) { - _m.Called(size) +func (_c *GossipSubMetrics_OnBehaviourPenaltyUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Run(run) + return _c } -// OnMessageEnteredValidation provides a mock function with given fields: size -func (_m *GossipSubMetrics) OnMessageEnteredValidation(size int) { - _m.Called(size) +// OnControlMessagesTruncated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { + _mock.Called(messageType, diff) + return } -// OnMessageRejected provides a mock function with given fields: size, reason -func (_m *GossipSubMetrics) OnMessageRejected(size int, reason string) { - _m.Called(size, reason) +// GossipSubMetrics_OnControlMessagesTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnControlMessagesTruncated' +type GossipSubMetrics_OnControlMessagesTruncated_Call struct { + *mock.Call } -// OnOutboundRpcDropped provides a mock function with no fields -func (_m *GossipSubMetrics) OnOutboundRpcDropped() { - _m.Called() +// OnControlMessagesTruncated is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +// - diff int +func (_e *GossipSubMetrics_Expecter) OnControlMessagesTruncated(messageType interface{}, diff interface{}) *GossipSubMetrics_OnControlMessagesTruncated_Call { + return &GossipSubMetrics_OnControlMessagesTruncated_Call{Call: _e.mock.On("OnControlMessagesTruncated", messageType, diff)} } -// OnOverallPeerScoreUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubMetrics) OnOverallPeerScoreUpdated(_a0 float64) { - _m.Called(_a0) +func (_c *GossipSubMetrics_OnControlMessagesTruncated_Call) Run(run func(messageType p2pmsg.ControlMessageType, diff int)) *GossipSubMetrics_OnControlMessagesTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnPeerAddedToProtocol provides a mock function with given fields: protocol -func (_m *GossipSubMetrics) OnPeerAddedToProtocol(protocol string) { - _m.Called(protocol) +func (_c *GossipSubMetrics_OnControlMessagesTruncated_Call) Return() *GossipSubMetrics_OnControlMessagesTruncated_Call { + _c.Call.Return() + return _c } -// OnPeerGraftTopic provides a mock function with given fields: topic -func (_m *GossipSubMetrics) OnPeerGraftTopic(topic string) { - _m.Called(topic) +func (_c *GossipSubMetrics_OnControlMessagesTruncated_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType, diff int)) *GossipSubMetrics_OnControlMessagesTruncated_Call { + _c.Run(run) + return _c } -// OnPeerPruneTopic provides a mock function with given fields: topic -func (_m *GossipSubMetrics) OnPeerPruneTopic(topic string) { - _m.Called(topic) +// OnFirstMessageDeliveredUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnFirstMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return } -// OnPeerRemovedFromProtocol provides a mock function with no fields -func (_m *GossipSubMetrics) OnPeerRemovedFromProtocol() { - _m.Called() +// GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFirstMessageDeliveredUpdated' +type GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call struct { + *mock.Call } -// OnPeerThrottled provides a mock function with no fields -func (_m *GossipSubMetrics) OnPeerThrottled() { - _m.Called() +// OnFirstMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *GossipSubMetrics_Expecter) OnFirstMessageDeliveredUpdated(topic interface{}, f interface{}) *GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call { + return &GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call{Call: _e.mock.On("OnFirstMessageDeliveredUpdated", topic, f)} } -// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnPruneInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnPruneInvalidTopicIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call) Return() *GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c } -// OnPruneMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *GossipSubMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +func (_c *GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *GossipSubMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Run(run) + return _c } -// OnPublishMessageInspected provides a mock function with given fields: totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount -func (_m *GossipSubMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { - _m.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) +// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return } -// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function with no fields -func (_m *GossipSubMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { - _m.Called() +// GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftDuplicateTopicIdsExceedThreshold' +type GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call } -// OnRpcReceived provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *GossipSubMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +// OnGraftDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnGraftDuplicateTopicIdsExceedThreshold() *GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + return &GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftDuplicateTopicIdsExceedThreshold")} } -// OnRpcRejectedFromUnknownSender provides a mock function with no fields -func (_m *GossipSubMetrics) OnRpcRejectedFromUnknownSender() { - _m.Called() +func (_c *GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnRpcSent provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *GossipSubMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +func (_c *GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c } -// OnTimeInMeshUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubMetrics) OnTimeInMeshUpdated(_a0 channels.Topic, _a1 time.Duration) { - _m.Called(_a0, _a1) +func (_c *GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c } -// OnUndeliveredMessage provides a mock function with no fields -func (_m *GossipSubMetrics) OnUndeliveredMessage() { - _m.Called() +// OnGraftInvalidTopicIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnGraftInvalidTopicIdsExceedThreshold() { + _mock.Called() + return } -// OnUnstakedPeerInspectionFailed provides a mock function with no fields -func (_m *GossipSubMetrics) OnUnstakedPeerInspectionFailed() { - _m.Called() +// GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftInvalidTopicIdsExceedThreshold' +type GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call } -// SetWarningStateCount provides a mock function with given fields: _a0 -func (_m *GossipSubMetrics) SetWarningStateCount(_a0 uint) { - _m.Called(_a0) +// OnGraftInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnGraftInvalidTopicIdsExceedThreshold() *GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + return &GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftInvalidTopicIdsExceedThreshold")} } -// NewGossipSubMetrics creates a new instance of GossipSubMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubMetrics { - mock := &GossipSubMetrics{} - mock.Mock.Test(t) +func (_c *GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnGraftMessageInspected provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// GossipSubMetrics_OnGraftMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftMessageInspected' +type GossipSubMetrics_OnGraftMessageInspected_Call struct { + *mock.Call +} + +// OnGraftMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *GossipSubMetrics_Expecter) OnGraftMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *GossipSubMetrics_OnGraftMessageInspected_Call { + return &GossipSubMetrics_OnGraftMessageInspected_Call{Call: _e.mock.On("OnGraftMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *GossipSubMetrics_OnGraftMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubMetrics_OnGraftMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnGraftMessageInspected_Call) Return() *GossipSubMetrics_OnGraftMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnGraftMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubMetrics_OnGraftMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnIHaveControlMessageIdsTruncated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIHaveControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveControlMessageIdsTruncated' +type GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIHaveControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *GossipSubMetrics_Expecter) OnIHaveControlMessageIdsTruncated(diff interface{}) *GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call { + return &GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIHaveControlMessageIdsTruncated", diff)} +} + +func (_c *GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call) Run(run func(diff int)) *GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call) Return() *GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *GossipSubMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateMessageIdsExceedThreshold' +type GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnIHaveDuplicateMessageIdsExceedThreshold() *GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + return &GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateMessageIdsExceedThreshold")} +} + +func (_c *GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateTopicIdsExceedThreshold' +type GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnIHaveDuplicateTopicIdsExceedThreshold() *GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + return &GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateTopicIdsExceedThreshold")} +} + +func (_c *GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveInvalidTopicIdsExceedThreshold' +type GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnIHaveInvalidTopicIdsExceedThreshold() *GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + return &GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveInvalidTopicIdsExceedThreshold")} +} + +func (_c *GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessageIDsReceived provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { + _mock.Called(channel, msgIdCount) + return +} + +// GossipSubMetrics_OnIHaveMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessageIDsReceived' +type GossipSubMetrics_OnIHaveMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIHaveMessageIDsReceived is a helper method to define mock.On call +// - channel string +// - msgIdCount int +func (_e *GossipSubMetrics_Expecter) OnIHaveMessageIDsReceived(channel interface{}, msgIdCount interface{}) *GossipSubMetrics_OnIHaveMessageIDsReceived_Call { + return &GossipSubMetrics_OnIHaveMessageIDsReceived_Call{Call: _e.mock.On("OnIHaveMessageIDsReceived", channel, msgIdCount)} +} + +func (_c *GossipSubMetrics_OnIHaveMessageIDsReceived_Call) Run(run func(channel string, msgIdCount int)) *GossipSubMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIHaveMessageIDsReceived_Call) Return() *GossipSubMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIHaveMessageIDsReceived_Call) RunAndReturn(run func(channel string, msgIdCount int)) *GossipSubMetrics_OnIHaveMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessagesInspected provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) + return +} + +// GossipSubMetrics_OnIHaveMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessagesInspected' +type GossipSubMetrics_OnIHaveMessagesInspected_Call struct { + *mock.Call +} + +// OnIHaveMessagesInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - duplicateMessageIds int +// - invalidTopicIds int +func (_e *GossipSubMetrics_Expecter) OnIHaveMessagesInspected(duplicateTopicIds interface{}, duplicateMessageIds interface{}, invalidTopicIds interface{}) *GossipSubMetrics_OnIHaveMessagesInspected_Call { + return &GossipSubMetrics_OnIHaveMessagesInspected_Call{Call: _e.mock.On("OnIHaveMessagesInspected", duplicateTopicIds, duplicateMessageIds, invalidTopicIds)} +} + +func (_c *GossipSubMetrics_OnIHaveMessagesInspected_Call) Run(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *GossipSubMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIHaveMessagesInspected_Call) Return() *GossipSubMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIHaveMessagesInspected_Call) RunAndReturn(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *GossipSubMetrics_OnIHaveMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIPColocationFactorUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIPColocationFactorUpdated(f float64) { + _mock.Called(f) + return +} + +// GossipSubMetrics_OnIPColocationFactorUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIPColocationFactorUpdated' +type GossipSubMetrics_OnIPColocationFactorUpdated_Call struct { + *mock.Call +} + +// OnIPColocationFactorUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubMetrics_Expecter) OnIPColocationFactorUpdated(f interface{}) *GossipSubMetrics_OnIPColocationFactorUpdated_Call { + return &GossipSubMetrics_OnIPColocationFactorUpdated_Call{Call: _e.mock.On("OnIPColocationFactorUpdated", f)} +} + +func (_c *GossipSubMetrics_OnIPColocationFactorUpdated_Call) Run(run func(f float64)) *GossipSubMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIPColocationFactorUpdated_Call) Return() *GossipSubMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIPColocationFactorUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubMetrics_OnIPColocationFactorUpdated_Call { + _c.Run(run) + return _c +} + +// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantCacheMissMessageIdsExceedThreshold' +type GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantCacheMissMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnIWantCacheMissMessageIdsExceedThreshold() *GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + return &GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantCacheMissMessageIdsExceedThreshold")} +} + +func (_c *GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantControlMessageIdsTruncated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIWantControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantControlMessageIdsTruncated' +type GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIWantControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *GossipSubMetrics_Expecter) OnIWantControlMessageIdsTruncated(diff interface{}) *GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call { + return &GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIWantControlMessageIdsTruncated", diff)} +} + +func (_c *GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call) Run(run func(diff int)) *GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call) Return() *GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *GossipSubMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantDuplicateMessageIdsExceedThreshold' +type GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnIWantDuplicateMessageIdsExceedThreshold() *GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + return &GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantDuplicateMessageIdsExceedThreshold")} +} + +func (_c *GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantMessageIDsReceived provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIWantMessageIDsReceived(msgIdCount int) { + _mock.Called(msgIdCount) + return +} + +// GossipSubMetrics_OnIWantMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessageIDsReceived' +type GossipSubMetrics_OnIWantMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIWantMessageIDsReceived is a helper method to define mock.On call +// - msgIdCount int +func (_e *GossipSubMetrics_Expecter) OnIWantMessageIDsReceived(msgIdCount interface{}) *GossipSubMetrics_OnIWantMessageIDsReceived_Call { + return &GossipSubMetrics_OnIWantMessageIDsReceived_Call{Call: _e.mock.On("OnIWantMessageIDsReceived", msgIdCount)} +} + +func (_c *GossipSubMetrics_OnIWantMessageIDsReceived_Call) Run(run func(msgIdCount int)) *GossipSubMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIWantMessageIDsReceived_Call) Return() *GossipSubMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIWantMessageIDsReceived_Call) RunAndReturn(run func(msgIdCount int)) *GossipSubMetrics_OnIWantMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIWantMessagesInspected provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { + _mock.Called(duplicateCount, cacheMissCount) + return +} + +// GossipSubMetrics_OnIWantMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessagesInspected' +type GossipSubMetrics_OnIWantMessagesInspected_Call struct { + *mock.Call +} + +// OnIWantMessagesInspected is a helper method to define mock.On call +// - duplicateCount int +// - cacheMissCount int +func (_e *GossipSubMetrics_Expecter) OnIWantMessagesInspected(duplicateCount interface{}, cacheMissCount interface{}) *GossipSubMetrics_OnIWantMessagesInspected_Call { + return &GossipSubMetrics_OnIWantMessagesInspected_Call{Call: _e.mock.On("OnIWantMessagesInspected", duplicateCount, cacheMissCount)} +} + +func (_c *GossipSubMetrics_OnIWantMessagesInspected_Call) Run(run func(duplicateCount int, cacheMissCount int)) *GossipSubMetrics_OnIWantMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIWantMessagesInspected_Call) Return() *GossipSubMetrics_OnIWantMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIWantMessagesInspected_Call) RunAndReturn(run func(duplicateCount int, cacheMissCount int)) *GossipSubMetrics_OnIWantMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIncomingRpcReceived provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { + _mock.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) + return +} + +// GossipSubMetrics_OnIncomingRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIncomingRpcReceived' +type GossipSubMetrics_OnIncomingRpcReceived_Call struct { + *mock.Call +} + +// OnIncomingRpcReceived is a helper method to define mock.On call +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +// - msgCount int +func (_e *GossipSubMetrics_Expecter) OnIncomingRpcReceived(iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}, msgCount interface{}) *GossipSubMetrics_OnIncomingRpcReceived_Call { + return &GossipSubMetrics_OnIncomingRpcReceived_Call{Call: _e.mock.On("OnIncomingRpcReceived", iHaveCount, iWantCount, graftCount, pruneCount, msgCount)} +} + +func (_c *GossipSubMetrics_OnIncomingRpcReceived_Call) Run(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *GossipSubMetrics_OnIncomingRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnIncomingRpcReceived_Call) Return() *GossipSubMetrics_OnIncomingRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnIncomingRpcReceived_Call) RunAndReturn(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *GossipSubMetrics_OnIncomingRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnInvalidControlMessageNotificationSent provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnInvalidControlMessageNotificationSent() { + _mock.Called() + return +} + +// GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidControlMessageNotificationSent' +type GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call struct { + *mock.Call +} + +// OnInvalidControlMessageNotificationSent is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnInvalidControlMessageNotificationSent() *GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call { + return &GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call{Call: _e.mock.On("OnInvalidControlMessageNotificationSent")} +} + +func (_c *GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call) Run(run func()) *GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call) Return() *GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call) RunAndReturn(run func()) *GossipSubMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Run(run) + return _c +} + +// OnInvalidMessageDeliveredUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnInvalidMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidMessageDeliveredUpdated' +type GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnInvalidMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *GossipSubMetrics_Expecter) OnInvalidMessageDeliveredUpdated(topic interface{}, f interface{}) *GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call { + return &GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call{Call: _e.mock.On("OnInvalidMessageDeliveredUpdated", topic, f)} +} + +func (_c *GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call) Return() *GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *GossipSubMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnInvalidTopicIdDetectedForControlMessage provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { + _mock.Called(messageType) + return +} + +// GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidTopicIdDetectedForControlMessage' +type GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call struct { + *mock.Call +} + +// OnInvalidTopicIdDetectedForControlMessage is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +func (_e *GossipSubMetrics_Expecter) OnInvalidTopicIdDetectedForControlMessage(messageType interface{}) *GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + return &GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call{Call: _e.mock.On("OnInvalidTopicIdDetectedForControlMessage", messageType)} +} + +func (_c *GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Run(run func(messageType p2pmsg.ControlMessageType)) *GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Return() *GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType)) *GossipSubMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Run(run) + return _c +} + +// OnLocalMeshSizeUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnLocalMeshSizeUpdated(topic string, size int) { + _mock.Called(topic, size) + return +} + +// GossipSubMetrics_OnLocalMeshSizeUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalMeshSizeUpdated' +type GossipSubMetrics_OnLocalMeshSizeUpdated_Call struct { + *mock.Call +} + +// OnLocalMeshSizeUpdated is a helper method to define mock.On call +// - topic string +// - size int +func (_e *GossipSubMetrics_Expecter) OnLocalMeshSizeUpdated(topic interface{}, size interface{}) *GossipSubMetrics_OnLocalMeshSizeUpdated_Call { + return &GossipSubMetrics_OnLocalMeshSizeUpdated_Call{Call: _e.mock.On("OnLocalMeshSizeUpdated", topic, size)} +} + +func (_c *GossipSubMetrics_OnLocalMeshSizeUpdated_Call) Run(run func(topic string, size int)) *GossipSubMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnLocalMeshSizeUpdated_Call) Return() *GossipSubMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnLocalMeshSizeUpdated_Call) RunAndReturn(run func(topic string, size int)) *GossipSubMetrics_OnLocalMeshSizeUpdated_Call { + _c.Run(run) + return _c +} + +// OnLocalPeerJoinedTopic provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnLocalPeerJoinedTopic() { + _mock.Called() + return +} + +// GossipSubMetrics_OnLocalPeerJoinedTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerJoinedTopic' +type GossipSubMetrics_OnLocalPeerJoinedTopic_Call struct { + *mock.Call +} + +// OnLocalPeerJoinedTopic is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnLocalPeerJoinedTopic() *GossipSubMetrics_OnLocalPeerJoinedTopic_Call { + return &GossipSubMetrics_OnLocalPeerJoinedTopic_Call{Call: _e.mock.On("OnLocalPeerJoinedTopic")} +} + +func (_c *GossipSubMetrics_OnLocalPeerJoinedTopic_Call) Run(run func()) *GossipSubMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnLocalPeerJoinedTopic_Call) Return() *GossipSubMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnLocalPeerJoinedTopic_Call) RunAndReturn(run func()) *GossipSubMetrics_OnLocalPeerJoinedTopic_Call { + _c.Run(run) + return _c +} + +// OnLocalPeerLeftTopic provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnLocalPeerLeftTopic() { + _mock.Called() + return +} + +// GossipSubMetrics_OnLocalPeerLeftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerLeftTopic' +type GossipSubMetrics_OnLocalPeerLeftTopic_Call struct { + *mock.Call +} + +// OnLocalPeerLeftTopic is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnLocalPeerLeftTopic() *GossipSubMetrics_OnLocalPeerLeftTopic_Call { + return &GossipSubMetrics_OnLocalPeerLeftTopic_Call{Call: _e.mock.On("OnLocalPeerLeftTopic")} +} + +func (_c *GossipSubMetrics_OnLocalPeerLeftTopic_Call) Run(run func()) *GossipSubMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnLocalPeerLeftTopic_Call) Return() *GossipSubMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnLocalPeerLeftTopic_Call) RunAndReturn(run func()) *GossipSubMetrics_OnLocalPeerLeftTopic_Call { + _c.Run(run) + return _c +} + +// OnMeshMessageDeliveredUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnMeshMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMeshMessageDeliveredUpdated' +type GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnMeshMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *GossipSubMetrics_Expecter) OnMeshMessageDeliveredUpdated(topic interface{}, f interface{}) *GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call { + return &GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call{Call: _e.mock.On("OnMeshMessageDeliveredUpdated", topic, f)} +} + +func (_c *GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call) Return() *GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *GossipSubMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnMessageDeliveredToAllSubscribers provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnMessageDeliveredToAllSubscribers(size int) { + _mock.Called(size) + return +} + +// GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDeliveredToAllSubscribers' +type GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call struct { + *mock.Call +} + +// OnMessageDeliveredToAllSubscribers is a helper method to define mock.On call +// - size int +func (_e *GossipSubMetrics_Expecter) OnMessageDeliveredToAllSubscribers(size interface{}) *GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call { + return &GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call{Call: _e.mock.On("OnMessageDeliveredToAllSubscribers", size)} +} + +func (_c *GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call) Run(run func(size int)) *GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call) Return() *GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call) RunAndReturn(run func(size int)) *GossipSubMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Run(run) + return _c +} + +// OnMessageDuplicate provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnMessageDuplicate(size int) { + _mock.Called(size) + return +} + +// GossipSubMetrics_OnMessageDuplicate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDuplicate' +type GossipSubMetrics_OnMessageDuplicate_Call struct { + *mock.Call +} + +// OnMessageDuplicate is a helper method to define mock.On call +// - size int +func (_e *GossipSubMetrics_Expecter) OnMessageDuplicate(size interface{}) *GossipSubMetrics_OnMessageDuplicate_Call { + return &GossipSubMetrics_OnMessageDuplicate_Call{Call: _e.mock.On("OnMessageDuplicate", size)} +} + +func (_c *GossipSubMetrics_OnMessageDuplicate_Call) Run(run func(size int)) *GossipSubMetrics_OnMessageDuplicate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnMessageDuplicate_Call) Return() *GossipSubMetrics_OnMessageDuplicate_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnMessageDuplicate_Call) RunAndReturn(run func(size int)) *GossipSubMetrics_OnMessageDuplicate_Call { + _c.Run(run) + return _c +} + +// OnMessageEnteredValidation provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnMessageEnteredValidation(size int) { + _mock.Called(size) + return +} + +// GossipSubMetrics_OnMessageEnteredValidation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageEnteredValidation' +type GossipSubMetrics_OnMessageEnteredValidation_Call struct { + *mock.Call +} + +// OnMessageEnteredValidation is a helper method to define mock.On call +// - size int +func (_e *GossipSubMetrics_Expecter) OnMessageEnteredValidation(size interface{}) *GossipSubMetrics_OnMessageEnteredValidation_Call { + return &GossipSubMetrics_OnMessageEnteredValidation_Call{Call: _e.mock.On("OnMessageEnteredValidation", size)} +} + +func (_c *GossipSubMetrics_OnMessageEnteredValidation_Call) Run(run func(size int)) *GossipSubMetrics_OnMessageEnteredValidation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnMessageEnteredValidation_Call) Return() *GossipSubMetrics_OnMessageEnteredValidation_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnMessageEnteredValidation_Call) RunAndReturn(run func(size int)) *GossipSubMetrics_OnMessageEnteredValidation_Call { + _c.Run(run) + return _c +} + +// OnMessageRejected provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnMessageRejected(size int, reason string) { + _mock.Called(size, reason) + return +} + +// GossipSubMetrics_OnMessageRejected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageRejected' +type GossipSubMetrics_OnMessageRejected_Call struct { + *mock.Call +} + +// OnMessageRejected is a helper method to define mock.On call +// - size int +// - reason string +func (_e *GossipSubMetrics_Expecter) OnMessageRejected(size interface{}, reason interface{}) *GossipSubMetrics_OnMessageRejected_Call { + return &GossipSubMetrics_OnMessageRejected_Call{Call: _e.mock.On("OnMessageRejected", size, reason)} +} + +func (_c *GossipSubMetrics_OnMessageRejected_Call) Run(run func(size int, reason string)) *GossipSubMetrics_OnMessageRejected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnMessageRejected_Call) Return() *GossipSubMetrics_OnMessageRejected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnMessageRejected_Call) RunAndReturn(run func(size int, reason string)) *GossipSubMetrics_OnMessageRejected_Call { + _c.Run(run) + return _c +} + +// OnOutboundRpcDropped provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnOutboundRpcDropped() { + _mock.Called() + return +} + +// GossipSubMetrics_OnOutboundRpcDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOutboundRpcDropped' +type GossipSubMetrics_OnOutboundRpcDropped_Call struct { + *mock.Call +} + +// OnOutboundRpcDropped is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnOutboundRpcDropped() *GossipSubMetrics_OnOutboundRpcDropped_Call { + return &GossipSubMetrics_OnOutboundRpcDropped_Call{Call: _e.mock.On("OnOutboundRpcDropped")} +} + +func (_c *GossipSubMetrics_OnOutboundRpcDropped_Call) Run(run func()) *GossipSubMetrics_OnOutboundRpcDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnOutboundRpcDropped_Call) Return() *GossipSubMetrics_OnOutboundRpcDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnOutboundRpcDropped_Call) RunAndReturn(run func()) *GossipSubMetrics_OnOutboundRpcDropped_Call { + _c.Run(run) + return _c +} + +// OnOverallPeerScoreUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnOverallPeerScoreUpdated(f float64) { + _mock.Called(f) + return +} + +// GossipSubMetrics_OnOverallPeerScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOverallPeerScoreUpdated' +type GossipSubMetrics_OnOverallPeerScoreUpdated_Call struct { + *mock.Call +} + +// OnOverallPeerScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubMetrics_Expecter) OnOverallPeerScoreUpdated(f interface{}) *GossipSubMetrics_OnOverallPeerScoreUpdated_Call { + return &GossipSubMetrics_OnOverallPeerScoreUpdated_Call{Call: _e.mock.On("OnOverallPeerScoreUpdated", f)} +} + +func (_c *GossipSubMetrics_OnOverallPeerScoreUpdated_Call) Run(run func(f float64)) *GossipSubMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnOverallPeerScoreUpdated_Call) Return() *GossipSubMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnOverallPeerScoreUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubMetrics_OnOverallPeerScoreUpdated_Call { + _c.Run(run) + return _c +} + +// OnPeerAddedToProtocol provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPeerAddedToProtocol(protocol string) { + _mock.Called(protocol) + return +} + +// GossipSubMetrics_OnPeerAddedToProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerAddedToProtocol' +type GossipSubMetrics_OnPeerAddedToProtocol_Call struct { + *mock.Call +} + +// OnPeerAddedToProtocol is a helper method to define mock.On call +// - protocol string +func (_e *GossipSubMetrics_Expecter) OnPeerAddedToProtocol(protocol interface{}) *GossipSubMetrics_OnPeerAddedToProtocol_Call { + return &GossipSubMetrics_OnPeerAddedToProtocol_Call{Call: _e.mock.On("OnPeerAddedToProtocol", protocol)} +} + +func (_c *GossipSubMetrics_OnPeerAddedToProtocol_Call) Run(run func(protocol string)) *GossipSubMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnPeerAddedToProtocol_Call) Return() *GossipSubMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPeerAddedToProtocol_Call) RunAndReturn(run func(protocol string)) *GossipSubMetrics_OnPeerAddedToProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerGraftTopic provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPeerGraftTopic(topic string) { + _mock.Called(topic) + return +} + +// GossipSubMetrics_OnPeerGraftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerGraftTopic' +type GossipSubMetrics_OnPeerGraftTopic_Call struct { + *mock.Call +} + +// OnPeerGraftTopic is a helper method to define mock.On call +// - topic string +func (_e *GossipSubMetrics_Expecter) OnPeerGraftTopic(topic interface{}) *GossipSubMetrics_OnPeerGraftTopic_Call { + return &GossipSubMetrics_OnPeerGraftTopic_Call{Call: _e.mock.On("OnPeerGraftTopic", topic)} +} + +func (_c *GossipSubMetrics_OnPeerGraftTopic_Call) Run(run func(topic string)) *GossipSubMetrics_OnPeerGraftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnPeerGraftTopic_Call) Return() *GossipSubMetrics_OnPeerGraftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPeerGraftTopic_Call) RunAndReturn(run func(topic string)) *GossipSubMetrics_OnPeerGraftTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerPruneTopic provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPeerPruneTopic(topic string) { + _mock.Called(topic) + return +} + +// GossipSubMetrics_OnPeerPruneTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerPruneTopic' +type GossipSubMetrics_OnPeerPruneTopic_Call struct { + *mock.Call +} + +// OnPeerPruneTopic is a helper method to define mock.On call +// - topic string +func (_e *GossipSubMetrics_Expecter) OnPeerPruneTopic(topic interface{}) *GossipSubMetrics_OnPeerPruneTopic_Call { + return &GossipSubMetrics_OnPeerPruneTopic_Call{Call: _e.mock.On("OnPeerPruneTopic", topic)} +} + +func (_c *GossipSubMetrics_OnPeerPruneTopic_Call) Run(run func(topic string)) *GossipSubMetrics_OnPeerPruneTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnPeerPruneTopic_Call) Return() *GossipSubMetrics_OnPeerPruneTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPeerPruneTopic_Call) RunAndReturn(run func(topic string)) *GossipSubMetrics_OnPeerPruneTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerRemovedFromProtocol provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPeerRemovedFromProtocol() { + _mock.Called() + return +} + +// GossipSubMetrics_OnPeerRemovedFromProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerRemovedFromProtocol' +type GossipSubMetrics_OnPeerRemovedFromProtocol_Call struct { + *mock.Call +} + +// OnPeerRemovedFromProtocol is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnPeerRemovedFromProtocol() *GossipSubMetrics_OnPeerRemovedFromProtocol_Call { + return &GossipSubMetrics_OnPeerRemovedFromProtocol_Call{Call: _e.mock.On("OnPeerRemovedFromProtocol")} +} + +func (_c *GossipSubMetrics_OnPeerRemovedFromProtocol_Call) Run(run func()) *GossipSubMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnPeerRemovedFromProtocol_Call) Return() *GossipSubMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPeerRemovedFromProtocol_Call) RunAndReturn(run func()) *GossipSubMetrics_OnPeerRemovedFromProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerThrottled provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPeerThrottled() { + _mock.Called() + return +} + +// GossipSubMetrics_OnPeerThrottled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerThrottled' +type GossipSubMetrics_OnPeerThrottled_Call struct { + *mock.Call +} + +// OnPeerThrottled is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnPeerThrottled() *GossipSubMetrics_OnPeerThrottled_Call { + return &GossipSubMetrics_OnPeerThrottled_Call{Call: _e.mock.On("OnPeerThrottled")} +} + +func (_c *GossipSubMetrics_OnPeerThrottled_Call) Run(run func()) *GossipSubMetrics_OnPeerThrottled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnPeerThrottled_Call) Return() *GossipSubMetrics_OnPeerThrottled_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPeerThrottled_Call) RunAndReturn(run func()) *GossipSubMetrics_OnPeerThrottled_Call { + _c.Run(run) + return _c +} + +// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneDuplicateTopicIdsExceedThreshold' +type GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnPruneDuplicateTopicIdsExceedThreshold() *GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + return &GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneDuplicateTopicIdsExceedThreshold")} +} + +func (_c *GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneInvalidTopicIdsExceedThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPruneInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneInvalidTopicIdsExceedThreshold' +type GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnPruneInvalidTopicIdsExceedThreshold() *GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + return &GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneInvalidTopicIdsExceedThreshold")} +} + +func (_c *GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Return() *GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneMessageInspected provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// GossipSubMetrics_OnPruneMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneMessageInspected' +type GossipSubMetrics_OnPruneMessageInspected_Call struct { + *mock.Call +} + +// OnPruneMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *GossipSubMetrics_Expecter) OnPruneMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *GossipSubMetrics_OnPruneMessageInspected_Call { + return &GossipSubMetrics_OnPruneMessageInspected_Call{Call: _e.mock.On("OnPruneMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *GossipSubMetrics_OnPruneMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubMetrics_OnPruneMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnPruneMessageInspected_Call) Return() *GossipSubMetrics_OnPruneMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPruneMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubMetrics_OnPruneMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessageInspected provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { + _mock.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) + return +} + +// GossipSubMetrics_OnPublishMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessageInspected' +type GossipSubMetrics_OnPublishMessageInspected_Call struct { + *mock.Call +} + +// OnPublishMessageInspected is a helper method to define mock.On call +// - totalErrCount int +// - invalidTopicIdsCount int +// - invalidSubscriptionsCount int +// - invalidSendersCount int +func (_e *GossipSubMetrics_Expecter) OnPublishMessageInspected(totalErrCount interface{}, invalidTopicIdsCount interface{}, invalidSubscriptionsCount interface{}, invalidSendersCount interface{}) *GossipSubMetrics_OnPublishMessageInspected_Call { + return &GossipSubMetrics_OnPublishMessageInspected_Call{Call: _e.mock.On("OnPublishMessageInspected", totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount)} +} + +func (_c *GossipSubMetrics_OnPublishMessageInspected_Call) Run(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *GossipSubMetrics_OnPublishMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnPublishMessageInspected_Call) Return() *GossipSubMetrics_OnPublishMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPublishMessageInspected_Call) RunAndReturn(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *GossipSubMetrics_OnPublishMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { + _mock.Called() + return +} + +// GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessagesInspectionErrorExceedsThreshold' +type GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call struct { + *mock.Call +} + +// OnPublishMessagesInspectionErrorExceedsThreshold is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnPublishMessagesInspectionErrorExceedsThreshold() *GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + return &GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call{Call: _e.mock.On("OnPublishMessagesInspectionErrorExceedsThreshold")} +} + +func (_c *GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Run(run func()) *GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Return() *GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) RunAndReturn(run func()) *GossipSubMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Run(run) + return _c +} + +// OnRpcReceived provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// GossipSubMetrics_OnRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcReceived' +type GossipSubMetrics_OnRpcReceived_Call struct { + *mock.Call +} + +// OnRpcReceived is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *GossipSubMetrics_Expecter) OnRpcReceived(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *GossipSubMetrics_OnRpcReceived_Call { + return &GossipSubMetrics_OnRpcReceived_Call{Call: _e.mock.On("OnRpcReceived", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *GossipSubMetrics_OnRpcReceived_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *GossipSubMetrics_OnRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnRpcReceived_Call) Return() *GossipSubMetrics_OnRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnRpcReceived_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *GossipSubMetrics_OnRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnRpcRejectedFromUnknownSender provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnRpcRejectedFromUnknownSender() { + _mock.Called() + return +} + +// GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcRejectedFromUnknownSender' +type GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call struct { + *mock.Call +} + +// OnRpcRejectedFromUnknownSender is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnRpcRejectedFromUnknownSender() *GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call { + return &GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call{Call: _e.mock.On("OnRpcRejectedFromUnknownSender")} +} + +func (_c *GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call) Run(run func()) *GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call) Return() *GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call) RunAndReturn(run func()) *GossipSubMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Run(run) + return _c +} + +// OnRpcSent provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// GossipSubMetrics_OnRpcSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcSent' +type GossipSubMetrics_OnRpcSent_Call struct { + *mock.Call +} + +// OnRpcSent is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *GossipSubMetrics_Expecter) OnRpcSent(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *GossipSubMetrics_OnRpcSent_Call { + return &GossipSubMetrics_OnRpcSent_Call{Call: _e.mock.On("OnRpcSent", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *GossipSubMetrics_OnRpcSent_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *GossipSubMetrics_OnRpcSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnRpcSent_Call) Return() *GossipSubMetrics_OnRpcSent_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnRpcSent_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *GossipSubMetrics_OnRpcSent_Call { + _c.Run(run) + return _c +} + +// OnTimeInMeshUpdated provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnTimeInMeshUpdated(topic channels.Topic, duration time.Duration) { + _mock.Called(topic, duration) + return +} + +// GossipSubMetrics_OnTimeInMeshUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTimeInMeshUpdated' +type GossipSubMetrics_OnTimeInMeshUpdated_Call struct { + *mock.Call +} + +// OnTimeInMeshUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - duration time.Duration +func (_e *GossipSubMetrics_Expecter) OnTimeInMeshUpdated(topic interface{}, duration interface{}) *GossipSubMetrics_OnTimeInMeshUpdated_Call { + return &GossipSubMetrics_OnTimeInMeshUpdated_Call{Call: _e.mock.On("OnTimeInMeshUpdated", topic, duration)} +} + +func (_c *GossipSubMetrics_OnTimeInMeshUpdated_Call) Run(run func(topic channels.Topic, duration time.Duration)) *GossipSubMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_OnTimeInMeshUpdated_Call) Return() *GossipSubMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnTimeInMeshUpdated_Call) RunAndReturn(run func(topic channels.Topic, duration time.Duration)) *GossipSubMetrics_OnTimeInMeshUpdated_Call { + _c.Run(run) + return _c +} + +// OnUndeliveredMessage provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnUndeliveredMessage() { + _mock.Called() + return +} + +// GossipSubMetrics_OnUndeliveredMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUndeliveredMessage' +type GossipSubMetrics_OnUndeliveredMessage_Call struct { + *mock.Call +} + +// OnUndeliveredMessage is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnUndeliveredMessage() *GossipSubMetrics_OnUndeliveredMessage_Call { + return &GossipSubMetrics_OnUndeliveredMessage_Call{Call: _e.mock.On("OnUndeliveredMessage")} +} + +func (_c *GossipSubMetrics_OnUndeliveredMessage_Call) Run(run func()) *GossipSubMetrics_OnUndeliveredMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnUndeliveredMessage_Call) Return() *GossipSubMetrics_OnUndeliveredMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnUndeliveredMessage_Call) RunAndReturn(run func()) *GossipSubMetrics_OnUndeliveredMessage_Call { + _c.Run(run) + return _c +} + +// OnUnstakedPeerInspectionFailed provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) OnUnstakedPeerInspectionFailed() { + _mock.Called() + return +} + +// GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnstakedPeerInspectionFailed' +type GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call struct { + *mock.Call +} + +// OnUnstakedPeerInspectionFailed is a helper method to define mock.On call +func (_e *GossipSubMetrics_Expecter) OnUnstakedPeerInspectionFailed() *GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call { + return &GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call{Call: _e.mock.On("OnUnstakedPeerInspectionFailed")} +} + +func (_c *GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call) Run(run func()) *GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call) Return() *GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call) RunAndReturn(run func()) *GossipSubMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Run(run) + return _c +} + +// SetWarningStateCount provides a mock function for the type GossipSubMetrics +func (_mock *GossipSubMetrics) SetWarningStateCount(v uint) { + _mock.Called(v) + return +} + +// GossipSubMetrics_SetWarningStateCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetWarningStateCount' +type GossipSubMetrics_SetWarningStateCount_Call struct { + *mock.Call +} + +// SetWarningStateCount is a helper method to define mock.On call +// - v uint +func (_e *GossipSubMetrics_Expecter) SetWarningStateCount(v interface{}) *GossipSubMetrics_SetWarningStateCount_Call { + return &GossipSubMetrics_SetWarningStateCount_Call{Call: _e.mock.On("SetWarningStateCount", v)} +} + +func (_c *GossipSubMetrics_SetWarningStateCount_Call) Run(run func(v uint)) *GossipSubMetrics_SetWarningStateCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubMetrics_SetWarningStateCount_Call) Return() *GossipSubMetrics_SetWarningStateCount_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubMetrics_SetWarningStateCount_Call) RunAndReturn(run func(v uint)) *GossipSubMetrics_SetWarningStateCount_Call { + _c.Run(run) + return _c } diff --git a/module/mock/gossip_sub_rpc_inspector_metrics.go b/module/mock/gossip_sub_rpc_inspector_metrics.go index f6d1c520c87..d2819a761db 100644 --- a/module/mock/gossip_sub_rpc_inspector_metrics.go +++ b/module/mock/gossip_sub_rpc_inspector_metrics.go @@ -1,39 +1,186 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewGossipSubRpcInspectorMetrics creates a new instance of GossipSubRpcInspectorMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubRpcInspectorMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubRpcInspectorMetrics { + mock := &GossipSubRpcInspectorMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // GossipSubRpcInspectorMetrics is an autogenerated mock type for the GossipSubRpcInspectorMetrics type type GossipSubRpcInspectorMetrics struct { mock.Mock } -// OnIHaveMessageIDsReceived provides a mock function with given fields: channel, msgIdCount -func (_m *GossipSubRpcInspectorMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { - _m.Called(channel, msgIdCount) +type GossipSubRpcInspectorMetrics_Expecter struct { + mock *mock.Mock } -// OnIWantMessageIDsReceived provides a mock function with given fields: msgIdCount -func (_m *GossipSubRpcInspectorMetrics) OnIWantMessageIDsReceived(msgIdCount int) { - _m.Called(msgIdCount) +func (_m *GossipSubRpcInspectorMetrics) EXPECT() *GossipSubRpcInspectorMetrics_Expecter { + return &GossipSubRpcInspectorMetrics_Expecter{mock: &_m.Mock} } -// OnIncomingRpcReceived provides a mock function with given fields: iHaveCount, iWantCount, graftCount, pruneCount, msgCount -func (_m *GossipSubRpcInspectorMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { - _m.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) +// OnIHaveMessageIDsReceived provides a mock function for the type GossipSubRpcInspectorMetrics +func (_mock *GossipSubRpcInspectorMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { + _mock.Called(channel, msgIdCount) + return } -// NewGossipSubRpcInspectorMetrics creates a new instance of GossipSubRpcInspectorMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubRpcInspectorMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubRpcInspectorMetrics { - mock := &GossipSubRpcInspectorMetrics{} - mock.Mock.Test(t) +// GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessageIDsReceived' +type GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnIHaveMessageIDsReceived is a helper method to define mock.On call +// - channel string +// - msgIdCount int +func (_e *GossipSubRpcInspectorMetrics_Expecter) OnIHaveMessageIDsReceived(channel interface{}, msgIdCount interface{}) *GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call { + return &GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call{Call: _e.mock.On("OnIHaveMessageIDsReceived", channel, msgIdCount)} +} - return mock +func (_c *GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call) Run(run func(channel string, msgIdCount int)) *GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call) Return() *GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call) RunAndReturn(run func(channel string, msgIdCount int)) *GossipSubRpcInspectorMetrics_OnIHaveMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIWantMessageIDsReceived provides a mock function for the type GossipSubRpcInspectorMetrics +func (_mock *GossipSubRpcInspectorMetrics) OnIWantMessageIDsReceived(msgIdCount int) { + _mock.Called(msgIdCount) + return +} + +// GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessageIDsReceived' +type GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIWantMessageIDsReceived is a helper method to define mock.On call +// - msgIdCount int +func (_e *GossipSubRpcInspectorMetrics_Expecter) OnIWantMessageIDsReceived(msgIdCount interface{}) *GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call { + return &GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call{Call: _e.mock.On("OnIWantMessageIDsReceived", msgIdCount)} +} + +func (_c *GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call) Run(run func(msgIdCount int)) *GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call) Return() *GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call) RunAndReturn(run func(msgIdCount int)) *GossipSubRpcInspectorMetrics_OnIWantMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIncomingRpcReceived provides a mock function for the type GossipSubRpcInspectorMetrics +func (_mock *GossipSubRpcInspectorMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { + _mock.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) + return +} + +// GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIncomingRpcReceived' +type GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call struct { + *mock.Call +} + +// OnIncomingRpcReceived is a helper method to define mock.On call +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +// - msgCount int +func (_e *GossipSubRpcInspectorMetrics_Expecter) OnIncomingRpcReceived(iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}, msgCount interface{}) *GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call { + return &GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call{Call: _e.mock.On("OnIncomingRpcReceived", iHaveCount, iWantCount, graftCount, pruneCount, msgCount)} +} + +func (_c *GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call) Run(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call) Return() *GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call) RunAndReturn(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *GossipSubRpcInspectorMetrics_OnIncomingRpcReceived_Call { + _c.Run(run) + return _c } diff --git a/module/mock/gossip_sub_rpc_validation_inspector_metrics.go b/module/mock/gossip_sub_rpc_validation_inspector_metrics.go index eb61983370e..2e06c3e33b2 100644 --- a/module/mock/gossip_sub_rpc_validation_inspector_metrics.go +++ b/module/mock/gossip_sub_rpc_validation_inspector_metrics.go @@ -1,170 +1,1138 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "time" + + "github.com/onflow/flow-go/network/p2p/message" mock "github.com/stretchr/testify/mock" +) + +// NewGossipSubRpcValidationInspectorMetrics creates a new instance of GossipSubRpcValidationInspectorMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubRpcValidationInspectorMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubRpcValidationInspectorMetrics { + mock := &GossipSubRpcValidationInspectorMetrics{} + mock.Mock.Test(t) - p2pmsg "github.com/onflow/flow-go/network/p2p/message" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // GossipSubRpcValidationInspectorMetrics is an autogenerated mock type for the GossipSubRpcValidationInspectorMetrics type type GossipSubRpcValidationInspectorMetrics struct { mock.Mock } -// AsyncProcessingFinished provides a mock function with given fields: duration -func (_m *GossipSubRpcValidationInspectorMetrics) AsyncProcessingFinished(duration time.Duration) { - _m.Called(duration) +type GossipSubRpcValidationInspectorMetrics_Expecter struct { + mock *mock.Mock } -// AsyncProcessingStarted provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) AsyncProcessingStarted() { - _m.Called() +func (_m *GossipSubRpcValidationInspectorMetrics) EXPECT() *GossipSubRpcValidationInspectorMetrics_Expecter { + return &GossipSubRpcValidationInspectorMetrics_Expecter{mock: &_m.Mock} } -// OnActiveClusterIDsNotSetErr provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnActiveClusterIDsNotSetErr() { - _m.Called() +// AsyncProcessingFinished provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) AsyncProcessingFinished(duration time.Duration) { + _mock.Called(duration) + return } -// OnControlMessagesTruncated provides a mock function with given fields: messageType, diff -func (_m *GossipSubRpcValidationInspectorMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { - _m.Called(messageType, diff) +// GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingFinished' +type GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call struct { + *mock.Call } -// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { - _m.Called() +// AsyncProcessingFinished is a helper method to define mock.On call +// - duration time.Duration +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) AsyncProcessingFinished(duration interface{}) *GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call { + return &GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call{Call: _e.mock.On("AsyncProcessingFinished", duration)} } -// OnGraftInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnGraftInvalidTopicIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call) Run(run func(duration time.Duration)) *GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// OnGraftMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *GossipSubRpcValidationInspectorMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +func (_c *GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call) Return() *GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call { + _c.Call.Return() + return _c } -// OnIHaveControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *GossipSubRpcValidationInspectorMetrics) OnIHaveControlMessageIdsTruncated(diff int) { - _m.Called(diff) +func (_c *GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call) RunAndReturn(run func(duration time.Duration)) *GossipSubRpcValidationInspectorMetrics_AsyncProcessingFinished_Call { + _c.Run(run) + return _c } -// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { - _m.Called() +// AsyncProcessingStarted provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) AsyncProcessingStarted() { + _mock.Called() + return } -// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { - _m.Called() +// GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingStarted' +type GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call struct { + *mock.Call } -// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { - _m.Called() +// AsyncProcessingStarted is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) AsyncProcessingStarted() *GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call { + return &GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call{Call: _e.mock.On("AsyncProcessingStarted")} } -// OnIHaveMessageIDsReceived provides a mock function with given fields: channel, msgIdCount -func (_m *GossipSubRpcValidationInspectorMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { - _m.Called(channel, msgIdCount) +func (_c *GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnIHaveMessagesInspected provides a mock function with given fields: duplicateTopicIds, duplicateMessageIds, invalidTopicIds -func (_m *GossipSubRpcValidationInspectorMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) +func (_c *GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call) Return() *GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call { + _c.Call.Return() + return _c } -// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { - _m.Called() +func (_c *GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_AsyncProcessingStarted_Call { + _c.Run(run) + return _c } -// OnIWantControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *GossipSubRpcValidationInspectorMetrics) OnIWantControlMessageIdsTruncated(diff int) { - _m.Called(diff) +// OnActiveClusterIDsNotSetErr provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnActiveClusterIDsNotSetErr() { + _mock.Called() + return } -// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { - _m.Called() +// GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnActiveClusterIDsNotSetErr' +type GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call struct { + *mock.Call } -// OnIWantMessageIDsReceived provides a mock function with given fields: msgIdCount -func (_m *GossipSubRpcValidationInspectorMetrics) OnIWantMessageIDsReceived(msgIdCount int) { - _m.Called(msgIdCount) +// OnActiveClusterIDsNotSetErr is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnActiveClusterIDsNotSetErr() *GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call { + return &GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call{Call: _e.mock.On("OnActiveClusterIDsNotSetErr")} } -// OnIWantMessagesInspected provides a mock function with given fields: duplicateCount, cacheMissCount -func (_m *GossipSubRpcValidationInspectorMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { - _m.Called(duplicateCount, cacheMissCount) +func (_c *GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnIncomingRpcReceived provides a mock function with given fields: iHaveCount, iWantCount, graftCount, pruneCount, msgCount -func (_m *GossipSubRpcValidationInspectorMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { - _m.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) +func (_c *GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Return() + return _c } -// OnInvalidControlMessageNotificationSent provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnInvalidControlMessageNotificationSent() { - _m.Called() +func (_c *GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Run(run) + return _c } -// OnInvalidTopicIdDetectedForControlMessage provides a mock function with given fields: messageType -func (_m *GossipSubRpcValidationInspectorMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { - _m.Called(messageType) +// OnControlMessagesTruncated provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { + _mock.Called(messageType, diff) + return } -// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { - _m.Called() +// GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnControlMessagesTruncated' +type GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call struct { + *mock.Call } -// OnPruneInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnPruneInvalidTopicIdsExceedThreshold() { - _m.Called() +// OnControlMessagesTruncated is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +// - diff int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnControlMessagesTruncated(messageType interface{}, diff interface{}) *GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call { + return &GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call{Call: _e.mock.On("OnControlMessagesTruncated", messageType, diff)} } -// OnPruneMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *GossipSubRpcValidationInspectorMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +func (_c *GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call) Run(run func(messageType p2pmsg.ControlMessageType, diff int)) *GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnPublishMessageInspected provides a mock function with given fields: totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount -func (_m *GossipSubRpcValidationInspectorMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { - _m.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) +func (_c *GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call { + _c.Call.Return() + return _c } -// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { - _m.Called() +func (_c *GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType, diff int)) *GossipSubRpcValidationInspectorMetrics_OnControlMessagesTruncated_Call { + _c.Run(run) + return _c } -// OnRpcRejectedFromUnknownSender provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnRpcRejectedFromUnknownSender() { - _m.Called() +// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return } -// OnUnstakedPeerInspectionFailed provides a mock function with no fields -func (_m *GossipSubRpcValidationInspectorMetrics) OnUnstakedPeerInspectionFailed() { - _m.Called() +// GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftDuplicateTopicIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call } -// NewGossipSubRpcValidationInspectorMetrics creates a new instance of GossipSubRpcValidationInspectorMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubRpcValidationInspectorMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubRpcValidationInspectorMetrics { - mock := &GossipSubRpcValidationInspectorMetrics{} - mock.Mock.Test(t) +// OnGraftDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnGraftDuplicateTopicIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftDuplicateTopicIdsExceedThreshold")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnGraftInvalidTopicIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnGraftInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftInvalidTopicIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnGraftInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnGraftInvalidTopicIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftInvalidTopicIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnGraftMessageInspected provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftMessageInspected' +type GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call struct { + *mock.Call +} + +// OnGraftMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnGraftMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call { + return &GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call{Call: _e.mock.On("OnGraftMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubRpcValidationInspectorMetrics_OnGraftMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnIHaveControlMessageIdsTruncated provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIHaveControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveControlMessageIdsTruncated' +type GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIHaveControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIHaveControlMessageIdsTruncated(diff interface{}) *GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIHaveControlMessageIdsTruncated", diff)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call) Run(run func(diff int)) *GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *GossipSubRpcValidationInspectorMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateMessageIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIHaveDuplicateMessageIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateMessageIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateTopicIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIHaveDuplicateTopicIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateTopicIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveInvalidTopicIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIHaveInvalidTopicIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveInvalidTopicIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessageIDsReceived provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { + _mock.Called(channel, msgIdCount) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessageIDsReceived' +type GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIHaveMessageIDsReceived is a helper method to define mock.On call +// - channel string +// - msgIdCount int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIHaveMessageIDsReceived(channel interface{}, msgIdCount interface{}) *GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call{Call: _e.mock.On("OnIHaveMessageIDsReceived", channel, msgIdCount)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call) Run(run func(channel string, msgIdCount int)) *GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call) RunAndReturn(run func(channel string, msgIdCount int)) *GossipSubRpcValidationInspectorMetrics_OnIHaveMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessagesInspected provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessagesInspected' +type GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call struct { + *mock.Call +} + +// OnIHaveMessagesInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - duplicateMessageIds int +// - invalidTopicIds int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIHaveMessagesInspected(duplicateTopicIds interface{}, duplicateMessageIds interface{}, invalidTopicIds interface{}) *GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call{Call: _e.mock.On("OnIHaveMessagesInspected", duplicateTopicIds, duplicateMessageIds, invalidTopicIds)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call) Run(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call) RunAndReturn(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *GossipSubRpcValidationInspectorMetrics_OnIHaveMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantCacheMissMessageIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantCacheMissMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIWantCacheMissMessageIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantCacheMissMessageIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantControlMessageIdsTruncated provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIWantControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantControlMessageIdsTruncated' +type GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIWantControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIWantControlMessageIdsTruncated(diff interface{}) *GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIWantControlMessageIdsTruncated", diff)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call) Run(run func(diff int)) *GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *GossipSubRpcValidationInspectorMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantDuplicateMessageIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIWantDuplicateMessageIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantDuplicateMessageIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantMessageIDsReceived provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIWantMessageIDsReceived(msgIdCount int) { + _mock.Called(msgIdCount) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessageIDsReceived' +type GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIWantMessageIDsReceived is a helper method to define mock.On call +// - msgIdCount int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIWantMessageIDsReceived(msgIdCount interface{}) *GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call{Call: _e.mock.On("OnIWantMessageIDsReceived", msgIdCount)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call) Run(run func(msgIdCount int)) *GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call) RunAndReturn(run func(msgIdCount int)) *GossipSubRpcValidationInspectorMetrics_OnIWantMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIWantMessagesInspected provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { + _mock.Called(duplicateCount, cacheMissCount) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessagesInspected' +type GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call struct { + *mock.Call +} + +// OnIWantMessagesInspected is a helper method to define mock.On call +// - duplicateCount int +// - cacheMissCount int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIWantMessagesInspected(duplicateCount interface{}, cacheMissCount interface{}) *GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call{Call: _e.mock.On("OnIWantMessagesInspected", duplicateCount, cacheMissCount)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call) Run(run func(duplicateCount int, cacheMissCount int)) *GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call) RunAndReturn(run func(duplicateCount int, cacheMissCount int)) *GossipSubRpcValidationInspectorMetrics_OnIWantMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIncomingRpcReceived provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { + _mock.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIncomingRpcReceived' +type GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call struct { + *mock.Call +} + +// OnIncomingRpcReceived is a helper method to define mock.On call +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +// - msgCount int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnIncomingRpcReceived(iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}, msgCount interface{}) *GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call { + return &GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call{Call: _e.mock.On("OnIncomingRpcReceived", iHaveCount, iWantCount, graftCount, pruneCount, msgCount)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call) Run(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call) RunAndReturn(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *GossipSubRpcValidationInspectorMetrics_OnIncomingRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnInvalidControlMessageNotificationSent provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnInvalidControlMessageNotificationSent() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidControlMessageNotificationSent' +type GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call struct { + *mock.Call +} + +// OnInvalidControlMessageNotificationSent is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnInvalidControlMessageNotificationSent() *GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call { + return &GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call{Call: _e.mock.On("OnInvalidControlMessageNotificationSent")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Run(run) + return _c +} + +// OnInvalidTopicIdDetectedForControlMessage provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { + _mock.Called(messageType) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidTopicIdDetectedForControlMessage' +type GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call struct { + *mock.Call +} + +// OnInvalidTopicIdDetectedForControlMessage is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnInvalidTopicIdDetectedForControlMessage(messageType interface{}) *GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + return &GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call{Call: _e.mock.On("OnInvalidTopicIdDetectedForControlMessage", messageType)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Run(run func(messageType p2pmsg.ControlMessageType)) *GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType)) *GossipSubRpcValidationInspectorMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Run(run) + return _c +} + +// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneDuplicateTopicIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnPruneDuplicateTopicIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneDuplicateTopicIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneInvalidTopicIdsExceedThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnPruneInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneInvalidTopicIdsExceedThreshold' +type GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnPruneInvalidTopicIdsExceedThreshold() *GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneInvalidTopicIdsExceedThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneMessageInspected provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneMessageInspected' +type GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call struct { + *mock.Call +} + +// OnPruneMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnPruneMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call { + return &GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call{Call: _e.mock.On("OnPruneMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *GossipSubRpcValidationInspectorMetrics_OnPruneMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessageInspected provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { + _mock.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) + return +} + +// GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessageInspected' +type GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call struct { + *mock.Call +} + +// OnPublishMessageInspected is a helper method to define mock.On call +// - totalErrCount int +// - invalidTopicIdsCount int +// - invalidSubscriptionsCount int +// - invalidSendersCount int +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnPublishMessageInspected(totalErrCount interface{}, invalidTopicIdsCount interface{}, invalidSubscriptionsCount interface{}, invalidSendersCount interface{}) *GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call { + return &GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call{Call: _e.mock.On("OnPublishMessageInspected", totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount)} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call) Run(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call) RunAndReturn(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *GossipSubRpcValidationInspectorMetrics_OnPublishMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessagesInspectionErrorExceedsThreshold' +type GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call struct { + *mock.Call +} + +// OnPublishMessagesInspectionErrorExceedsThreshold is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnPublishMessagesInspectionErrorExceedsThreshold() *GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + return &GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call{Call: _e.mock.On("OnPublishMessagesInspectionErrorExceedsThreshold")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Run(run) + return _c +} + +// OnRpcRejectedFromUnknownSender provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnRpcRejectedFromUnknownSender() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcRejectedFromUnknownSender' +type GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call struct { + *mock.Call +} + +// OnRpcRejectedFromUnknownSender is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnRpcRejectedFromUnknownSender() *GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call { + return &GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call{Call: _e.mock.On("OnRpcRejectedFromUnknownSender")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Run(run) + return _c +} + +// OnUnstakedPeerInspectionFailed provides a mock function for the type GossipSubRpcValidationInspectorMetrics +func (_mock *GossipSubRpcValidationInspectorMetrics) OnUnstakedPeerInspectionFailed() { + _mock.Called() + return +} + +// GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnstakedPeerInspectionFailed' +type GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call struct { + *mock.Call +} + +// OnUnstakedPeerInspectionFailed is a helper method to define mock.On call +func (_e *GossipSubRpcValidationInspectorMetrics_Expecter) OnUnstakedPeerInspectionFailed() *GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call { + return &GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call{Call: _e.mock.On("OnUnstakedPeerInspectionFailed")} +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call) Run(run func()) *GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call) Return() *GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call) RunAndReturn(run func()) *GossipSubRpcValidationInspectorMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Run(run) + return _c } diff --git a/module/mock/gossip_sub_scoring_metrics.go b/module/mock/gossip_sub_scoring_metrics.go index b71dc48f749..4b3520b26e2 100644 --- a/module/mock/gossip_sub_scoring_metrics.go +++ b/module/mock/gossip_sub_scoring_metrics.go @@ -1,74 +1,423 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" - mock "github.com/stretchr/testify/mock" + "time" - time "time" + "github.com/onflow/flow-go/network/channels" + mock "github.com/stretchr/testify/mock" ) +// NewGossipSubScoringMetrics creates a new instance of GossipSubScoringMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubScoringMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubScoringMetrics { + mock := &GossipSubScoringMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // GossipSubScoringMetrics is an autogenerated mock type for the GossipSubScoringMetrics type type GossipSubScoringMetrics struct { mock.Mock } -// OnAppSpecificScoreUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubScoringMetrics) OnAppSpecificScoreUpdated(_a0 float64) { - _m.Called(_a0) +type GossipSubScoringMetrics_Expecter struct { + mock *mock.Mock } -// OnBehaviourPenaltyUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubScoringMetrics) OnBehaviourPenaltyUpdated(_a0 float64) { - _m.Called(_a0) +func (_m *GossipSubScoringMetrics) EXPECT() *GossipSubScoringMetrics_Expecter { + return &GossipSubScoringMetrics_Expecter{mock: &_m.Mock} } -// OnFirstMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubScoringMetrics) OnFirstMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +// OnAppSpecificScoreUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnAppSpecificScoreUpdated(f float64) { + _mock.Called(f) + return } -// OnIPColocationFactorUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubScoringMetrics) OnIPColocationFactorUpdated(_a0 float64) { - _m.Called(_a0) +// GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAppSpecificScoreUpdated' +type GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call struct { + *mock.Call } -// OnInvalidMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubScoringMetrics) OnInvalidMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +// OnAppSpecificScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubScoringMetrics_Expecter) OnAppSpecificScoreUpdated(f interface{}) *GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call { + return &GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call{Call: _e.mock.On("OnAppSpecificScoreUpdated", f)} } -// OnMeshMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubScoringMetrics) OnMeshMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call) Run(run func(f float64)) *GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c } -// OnOverallPeerScoreUpdated provides a mock function with given fields: _a0 -func (_m *GossipSubScoringMetrics) OnOverallPeerScoreUpdated(_a0 float64) { - _m.Called(_a0) +func (_c *GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call) Return() *GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Return() + return _c } -// OnTimeInMeshUpdated provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubScoringMetrics) OnTimeInMeshUpdated(_a0 channels.Topic, _a1 time.Duration) { - _m.Called(_a0, _a1) +func (_c *GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubScoringMetrics_OnAppSpecificScoreUpdated_Call { + _c.Run(run) + return _c } -// SetWarningStateCount provides a mock function with given fields: _a0 -func (_m *GossipSubScoringMetrics) SetWarningStateCount(_a0 uint) { - _m.Called(_a0) +// OnBehaviourPenaltyUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnBehaviourPenaltyUpdated(f float64) { + _mock.Called(f) + return } -// NewGossipSubScoringMetrics creates a new instance of GossipSubScoringMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubScoringMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubScoringMetrics { - mock := &GossipSubScoringMetrics{} - mock.Mock.Test(t) +// GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBehaviourPenaltyUpdated' +type GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnBehaviourPenaltyUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubScoringMetrics_Expecter) OnBehaviourPenaltyUpdated(f interface{}) *GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call { + return &GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call{Call: _e.mock.On("OnBehaviourPenaltyUpdated", f)} +} - return mock +func (_c *GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call) Run(run func(f float64)) *GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call) Return() *GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubScoringMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Run(run) + return _c +} + +// OnFirstMessageDeliveredUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnFirstMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFirstMessageDeliveredUpdated' +type GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnFirstMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *GossipSubScoringMetrics_Expecter) OnFirstMessageDeliveredUpdated(topic interface{}, f interface{}) *GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call { + return &GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call{Call: _e.mock.On("OnFirstMessageDeliveredUpdated", topic, f)} +} + +func (_c *GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call) Return() *GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *GossipSubScoringMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnIPColocationFactorUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnIPColocationFactorUpdated(f float64) { + _mock.Called(f) + return +} + +// GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIPColocationFactorUpdated' +type GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call struct { + *mock.Call +} + +// OnIPColocationFactorUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubScoringMetrics_Expecter) OnIPColocationFactorUpdated(f interface{}) *GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call { + return &GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call{Call: _e.mock.On("OnIPColocationFactorUpdated", f)} +} + +func (_c *GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call) Run(run func(f float64)) *GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call) Return() *GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubScoringMetrics_OnIPColocationFactorUpdated_Call { + _c.Run(run) + return _c +} + +// OnInvalidMessageDeliveredUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnInvalidMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidMessageDeliveredUpdated' +type GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnInvalidMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *GossipSubScoringMetrics_Expecter) OnInvalidMessageDeliveredUpdated(topic interface{}, f interface{}) *GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call { + return &GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call{Call: _e.mock.On("OnInvalidMessageDeliveredUpdated", topic, f)} +} + +func (_c *GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call) Return() *GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *GossipSubScoringMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnMeshMessageDeliveredUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnMeshMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMeshMessageDeliveredUpdated' +type GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnMeshMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *GossipSubScoringMetrics_Expecter) OnMeshMessageDeliveredUpdated(topic interface{}, f interface{}) *GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call { + return &GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call{Call: _e.mock.On("OnMeshMessageDeliveredUpdated", topic, f)} +} + +func (_c *GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call) Return() *GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *GossipSubScoringMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnOverallPeerScoreUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnOverallPeerScoreUpdated(f float64) { + _mock.Called(f) + return +} + +// GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOverallPeerScoreUpdated' +type GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call struct { + *mock.Call +} + +// OnOverallPeerScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *GossipSubScoringMetrics_Expecter) OnOverallPeerScoreUpdated(f interface{}) *GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call { + return &GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call{Call: _e.mock.On("OnOverallPeerScoreUpdated", f)} +} + +func (_c *GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call) Run(run func(f float64)) *GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call) Return() *GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call) RunAndReturn(run func(f float64)) *GossipSubScoringMetrics_OnOverallPeerScoreUpdated_Call { + _c.Run(run) + return _c +} + +// OnTimeInMeshUpdated provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) OnTimeInMeshUpdated(topic channels.Topic, duration time.Duration) { + _mock.Called(topic, duration) + return +} + +// GossipSubScoringMetrics_OnTimeInMeshUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTimeInMeshUpdated' +type GossipSubScoringMetrics_OnTimeInMeshUpdated_Call struct { + *mock.Call +} + +// OnTimeInMeshUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - duration time.Duration +func (_e *GossipSubScoringMetrics_Expecter) OnTimeInMeshUpdated(topic interface{}, duration interface{}) *GossipSubScoringMetrics_OnTimeInMeshUpdated_Call { + return &GossipSubScoringMetrics_OnTimeInMeshUpdated_Call{Call: _e.mock.On("OnTimeInMeshUpdated", topic, duration)} +} + +func (_c *GossipSubScoringMetrics_OnTimeInMeshUpdated_Call) Run(run func(topic channels.Topic, duration time.Duration)) *GossipSubScoringMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_OnTimeInMeshUpdated_Call) Return() *GossipSubScoringMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_OnTimeInMeshUpdated_Call) RunAndReturn(run func(topic channels.Topic, duration time.Duration)) *GossipSubScoringMetrics_OnTimeInMeshUpdated_Call { + _c.Run(run) + return _c +} + +// SetWarningStateCount provides a mock function for the type GossipSubScoringMetrics +func (_mock *GossipSubScoringMetrics) SetWarningStateCount(v uint) { + _mock.Called(v) + return +} + +// GossipSubScoringMetrics_SetWarningStateCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetWarningStateCount' +type GossipSubScoringMetrics_SetWarningStateCount_Call struct { + *mock.Call +} + +// SetWarningStateCount is a helper method to define mock.On call +// - v uint +func (_e *GossipSubScoringMetrics_Expecter) SetWarningStateCount(v interface{}) *GossipSubScoringMetrics_SetWarningStateCount_Call { + return &GossipSubScoringMetrics_SetWarningStateCount_Call{Call: _e.mock.On("SetWarningStateCount", v)} +} + +func (_c *GossipSubScoringMetrics_SetWarningStateCount_Call) Run(run func(v uint)) *GossipSubScoringMetrics_SetWarningStateCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubScoringMetrics_SetWarningStateCount_Call) Return() *GossipSubScoringMetrics_SetWarningStateCount_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringMetrics_SetWarningStateCount_Call) RunAndReturn(run func(v uint)) *GossipSubScoringMetrics_SetWarningStateCount_Call { + _c.Run(run) + return _c } diff --git a/module/mock/gossip_sub_scoring_registry_metrics.go b/module/mock/gossip_sub_scoring_registry_metrics.go index a93a480a348..cbc72114e59 100644 --- a/module/mock/gossip_sub_scoring_registry_metrics.go +++ b/module/mock/gossip_sub_scoring_registry_metrics.go @@ -1,23 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// GossipSubScoringRegistryMetrics is an autogenerated mock type for the GossipSubScoringRegistryMetrics type -type GossipSubScoringRegistryMetrics struct { - mock.Mock -} - -// DuplicateMessagePenalties provides a mock function with given fields: penalty -func (_m *GossipSubScoringRegistryMetrics) DuplicateMessagePenalties(penalty float64) { - _m.Called(penalty) -} - -// DuplicateMessagesCounts provides a mock function with given fields: count -func (_m *GossipSubScoringRegistryMetrics) DuplicateMessagesCounts(count float64) { - _m.Called(count) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewGossipSubScoringRegistryMetrics creates a new instance of GossipSubScoringRegistryMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -32,3 +21,96 @@ func NewGossipSubScoringRegistryMetrics(t interface { return mock } + +// GossipSubScoringRegistryMetrics is an autogenerated mock type for the GossipSubScoringRegistryMetrics type +type GossipSubScoringRegistryMetrics struct { + mock.Mock +} + +type GossipSubScoringRegistryMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *GossipSubScoringRegistryMetrics) EXPECT() *GossipSubScoringRegistryMetrics_Expecter { + return &GossipSubScoringRegistryMetrics_Expecter{mock: &_m.Mock} +} + +// DuplicateMessagePenalties provides a mock function for the type GossipSubScoringRegistryMetrics +func (_mock *GossipSubScoringRegistryMetrics) DuplicateMessagePenalties(penalty float64) { + _mock.Called(penalty) + return +} + +// GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessagePenalties' +type GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call struct { + *mock.Call +} + +// DuplicateMessagePenalties is a helper method to define mock.On call +// - penalty float64 +func (_e *GossipSubScoringRegistryMetrics_Expecter) DuplicateMessagePenalties(penalty interface{}) *GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call { + return &GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call{Call: _e.mock.On("DuplicateMessagePenalties", penalty)} +} + +func (_c *GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call) Run(run func(penalty float64)) *GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call) Return() *GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call) RunAndReturn(run func(penalty float64)) *GossipSubScoringRegistryMetrics_DuplicateMessagePenalties_Call { + _c.Run(run) + return _c +} + +// DuplicateMessagesCounts provides a mock function for the type GossipSubScoringRegistryMetrics +func (_mock *GossipSubScoringRegistryMetrics) DuplicateMessagesCounts(count float64) { + _mock.Called(count) + return +} + +// GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessagesCounts' +type GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call struct { + *mock.Call +} + +// DuplicateMessagesCounts is a helper method to define mock.On call +// - count float64 +func (_e *GossipSubScoringRegistryMetrics_Expecter) DuplicateMessagesCounts(count interface{}) *GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call { + return &GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call{Call: _e.mock.On("DuplicateMessagesCounts", count)} +} + +func (_c *GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call) Run(run func(count float64)) *GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call) Return() *GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call) RunAndReturn(run func(count float64)) *GossipSubScoringRegistryMetrics_DuplicateMessagesCounts_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/grpc_connection_pool_metrics.go b/module/mock/grpc_connection_pool_metrics.go index 98e13123393..0d12289d695 100644 --- a/module/mock/grpc_connection_pool_metrics.go +++ b/module/mock/grpc_connection_pool_metrics.go @@ -1,59 +1,280 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewGRPCConnectionPoolMetrics creates a new instance of GRPCConnectionPoolMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGRPCConnectionPoolMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *GRPCConnectionPoolMetrics { + mock := &GRPCConnectionPoolMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // GRPCConnectionPoolMetrics is an autogenerated mock type for the GRPCConnectionPoolMetrics type type GRPCConnectionPoolMetrics struct { mock.Mock } -// ConnectionAddedToPool provides a mock function with no fields -func (_m *GRPCConnectionPoolMetrics) ConnectionAddedToPool() { - _m.Called() +type GRPCConnectionPoolMetrics_Expecter struct { + mock *mock.Mock } -// ConnectionFromPoolEvicted provides a mock function with no fields -func (_m *GRPCConnectionPoolMetrics) ConnectionFromPoolEvicted() { - _m.Called() +func (_m *GRPCConnectionPoolMetrics) EXPECT() *GRPCConnectionPoolMetrics_Expecter { + return &GRPCConnectionPoolMetrics_Expecter{mock: &_m.Mock} } -// ConnectionFromPoolInvalidated provides a mock function with no fields -func (_m *GRPCConnectionPoolMetrics) ConnectionFromPoolInvalidated() { - _m.Called() +// ConnectionAddedToPool provides a mock function for the type GRPCConnectionPoolMetrics +func (_mock *GRPCConnectionPoolMetrics) ConnectionAddedToPool() { + _mock.Called() + return } -// ConnectionFromPoolReused provides a mock function with no fields -func (_m *GRPCConnectionPoolMetrics) ConnectionFromPoolReused() { - _m.Called() +// GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionAddedToPool' +type GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call struct { + *mock.Call } -// ConnectionFromPoolUpdated provides a mock function with no fields -func (_m *GRPCConnectionPoolMetrics) ConnectionFromPoolUpdated() { - _m.Called() +// ConnectionAddedToPool is a helper method to define mock.On call +func (_e *GRPCConnectionPoolMetrics_Expecter) ConnectionAddedToPool() *GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call { + return &GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call{Call: _e.mock.On("ConnectionAddedToPool")} } -// NewConnectionEstablished provides a mock function with no fields -func (_m *GRPCConnectionPoolMetrics) NewConnectionEstablished() { - _m.Called() +func (_c *GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call) Run(run func()) *GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// TotalConnectionsInPool provides a mock function with given fields: connectionCount, connectionPoolSize -func (_m *GRPCConnectionPoolMetrics) TotalConnectionsInPool(connectionCount uint, connectionPoolSize uint) { - _m.Called(connectionCount, connectionPoolSize) +func (_c *GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call) Return() *GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call { + _c.Call.Return() + return _c } -// NewGRPCConnectionPoolMetrics creates a new instance of GRPCConnectionPoolMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGRPCConnectionPoolMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *GRPCConnectionPoolMetrics { - mock := &GRPCConnectionPoolMetrics{} - mock.Mock.Test(t) +func (_c *GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call) RunAndReturn(run func()) *GRPCConnectionPoolMetrics_ConnectionAddedToPool_Call { + _c.Run(run) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ConnectionFromPoolEvicted provides a mock function for the type GRPCConnectionPoolMetrics +func (_mock *GRPCConnectionPoolMetrics) ConnectionFromPoolEvicted() { + _mock.Called() + return +} - return mock +// GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolEvicted' +type GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call struct { + *mock.Call +} + +// ConnectionFromPoolEvicted is a helper method to define mock.On call +func (_e *GRPCConnectionPoolMetrics_Expecter) ConnectionFromPoolEvicted() *GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call { + return &GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call{Call: _e.mock.On("ConnectionFromPoolEvicted")} +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call) Run(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call) Return() *GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call { + _c.Call.Return() + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call) RunAndReturn(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolEvicted_Call { + _c.Run(run) + return _c +} + +// ConnectionFromPoolInvalidated provides a mock function for the type GRPCConnectionPoolMetrics +func (_mock *GRPCConnectionPoolMetrics) ConnectionFromPoolInvalidated() { + _mock.Called() + return +} + +// GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolInvalidated' +type GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call struct { + *mock.Call +} + +// ConnectionFromPoolInvalidated is a helper method to define mock.On call +func (_e *GRPCConnectionPoolMetrics_Expecter) ConnectionFromPoolInvalidated() *GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call { + return &GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call{Call: _e.mock.On("ConnectionFromPoolInvalidated")} +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call) Run(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call) Return() *GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call { + _c.Call.Return() + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call) RunAndReturn(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolInvalidated_Call { + _c.Run(run) + return _c +} + +// ConnectionFromPoolReused provides a mock function for the type GRPCConnectionPoolMetrics +func (_mock *GRPCConnectionPoolMetrics) ConnectionFromPoolReused() { + _mock.Called() + return +} + +// GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolReused' +type GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call struct { + *mock.Call +} + +// ConnectionFromPoolReused is a helper method to define mock.On call +func (_e *GRPCConnectionPoolMetrics_Expecter) ConnectionFromPoolReused() *GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call { + return &GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call{Call: _e.mock.On("ConnectionFromPoolReused")} +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call) Run(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call) Return() *GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call { + _c.Call.Return() + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call) RunAndReturn(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolReused_Call { + _c.Run(run) + return _c +} + +// ConnectionFromPoolUpdated provides a mock function for the type GRPCConnectionPoolMetrics +func (_mock *GRPCConnectionPoolMetrics) ConnectionFromPoolUpdated() { + _mock.Called() + return +} + +// GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectionFromPoolUpdated' +type GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call struct { + *mock.Call +} + +// ConnectionFromPoolUpdated is a helper method to define mock.On call +func (_e *GRPCConnectionPoolMetrics_Expecter) ConnectionFromPoolUpdated() *GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call { + return &GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call{Call: _e.mock.On("ConnectionFromPoolUpdated")} +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call) Run(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call) Return() *GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call) RunAndReturn(run func()) *GRPCConnectionPoolMetrics_ConnectionFromPoolUpdated_Call { + _c.Run(run) + return _c +} + +// NewConnectionEstablished provides a mock function for the type GRPCConnectionPoolMetrics +func (_mock *GRPCConnectionPoolMetrics) NewConnectionEstablished() { + _mock.Called() + return +} + +// GRPCConnectionPoolMetrics_NewConnectionEstablished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewConnectionEstablished' +type GRPCConnectionPoolMetrics_NewConnectionEstablished_Call struct { + *mock.Call +} + +// NewConnectionEstablished is a helper method to define mock.On call +func (_e *GRPCConnectionPoolMetrics_Expecter) NewConnectionEstablished() *GRPCConnectionPoolMetrics_NewConnectionEstablished_Call { + return &GRPCConnectionPoolMetrics_NewConnectionEstablished_Call{Call: _e.mock.On("NewConnectionEstablished")} +} + +func (_c *GRPCConnectionPoolMetrics_NewConnectionEstablished_Call) Run(run func()) *GRPCConnectionPoolMetrics_NewConnectionEstablished_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GRPCConnectionPoolMetrics_NewConnectionEstablished_Call) Return() *GRPCConnectionPoolMetrics_NewConnectionEstablished_Call { + _c.Call.Return() + return _c +} + +func (_c *GRPCConnectionPoolMetrics_NewConnectionEstablished_Call) RunAndReturn(run func()) *GRPCConnectionPoolMetrics_NewConnectionEstablished_Call { + _c.Run(run) + return _c +} + +// TotalConnectionsInPool provides a mock function for the type GRPCConnectionPoolMetrics +func (_mock *GRPCConnectionPoolMetrics) TotalConnectionsInPool(connectionCount uint, connectionPoolSize uint) { + _mock.Called(connectionCount, connectionPoolSize) + return +} + +// GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TotalConnectionsInPool' +type GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call struct { + *mock.Call +} + +// TotalConnectionsInPool is a helper method to define mock.On call +// - connectionCount uint +// - connectionPoolSize uint +func (_e *GRPCConnectionPoolMetrics_Expecter) TotalConnectionsInPool(connectionCount interface{}, connectionPoolSize interface{}) *GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call { + return &GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call{Call: _e.mock.On("TotalConnectionsInPool", connectionCount, connectionPoolSize)} +} + +func (_c *GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call) Run(run func(connectionCount uint, connectionPoolSize uint)) *GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + var arg1 uint + if args[1] != nil { + arg1 = args[1].(uint) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call) Return() *GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call { + _c.Call.Return() + return _c +} + +func (_c *GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call) RunAndReturn(run func(connectionCount uint, connectionPoolSize uint)) *GRPCConnectionPoolMetrics_TotalConnectionsInPool_Call { + _c.Run(run) + return _c } diff --git a/module/mock/hero_cache_metrics.go b/module/mock/hero_cache_metrics.go index 4459b8a27a8..3b012eeb137 100644 --- a/module/mock/hero_cache_metrics.go +++ b/module/mock/hero_cache_metrics.go @@ -1,74 +1,400 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewHeroCacheMetrics creates a new instance of HeroCacheMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewHeroCacheMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *HeroCacheMetrics { + mock := &HeroCacheMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // HeroCacheMetrics is an autogenerated mock type for the HeroCacheMetrics type type HeroCacheMetrics struct { mock.Mock } -// BucketAvailableSlots provides a mock function with given fields: _a0, _a1 -func (_m *HeroCacheMetrics) BucketAvailableSlots(_a0 uint64, _a1 uint64) { - _m.Called(_a0, _a1) +type HeroCacheMetrics_Expecter struct { + mock *mock.Mock } -// OnEntityEjectionDueToEmergency provides a mock function with no fields -func (_m *HeroCacheMetrics) OnEntityEjectionDueToEmergency() { - _m.Called() +func (_m *HeroCacheMetrics) EXPECT() *HeroCacheMetrics_Expecter { + return &HeroCacheMetrics_Expecter{mock: &_m.Mock} } -// OnEntityEjectionDueToFullCapacity provides a mock function with no fields -func (_m *HeroCacheMetrics) OnEntityEjectionDueToFullCapacity() { - _m.Called() +// BucketAvailableSlots provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) BucketAvailableSlots(v uint64, v1 uint64) { + _mock.Called(v, v1) + return } -// OnKeyGetFailure provides a mock function with no fields -func (_m *HeroCacheMetrics) OnKeyGetFailure() { - _m.Called() +// HeroCacheMetrics_BucketAvailableSlots_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BucketAvailableSlots' +type HeroCacheMetrics_BucketAvailableSlots_Call struct { + *mock.Call } -// OnKeyGetSuccess provides a mock function with no fields -func (_m *HeroCacheMetrics) OnKeyGetSuccess() { - _m.Called() +// BucketAvailableSlots is a helper method to define mock.On call +// - v uint64 +// - v1 uint64 +func (_e *HeroCacheMetrics_Expecter) BucketAvailableSlots(v interface{}, v1 interface{}) *HeroCacheMetrics_BucketAvailableSlots_Call { + return &HeroCacheMetrics_BucketAvailableSlots_Call{Call: _e.mock.On("BucketAvailableSlots", v, v1)} } -// OnKeyPutAttempt provides a mock function with given fields: size -func (_m *HeroCacheMetrics) OnKeyPutAttempt(size uint32) { - _m.Called(size) +func (_c *HeroCacheMetrics_BucketAvailableSlots_Call) Run(run func(v uint64, v1 uint64)) *HeroCacheMetrics_BucketAvailableSlots_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnKeyPutDeduplicated provides a mock function with no fields -func (_m *HeroCacheMetrics) OnKeyPutDeduplicated() { - _m.Called() +func (_c *HeroCacheMetrics_BucketAvailableSlots_Call) Return() *HeroCacheMetrics_BucketAvailableSlots_Call { + _c.Call.Return() + return _c } -// OnKeyPutDrop provides a mock function with no fields -func (_m *HeroCacheMetrics) OnKeyPutDrop() { - _m.Called() +func (_c *HeroCacheMetrics_BucketAvailableSlots_Call) RunAndReturn(run func(v uint64, v1 uint64)) *HeroCacheMetrics_BucketAvailableSlots_Call { + _c.Run(run) + return _c } -// OnKeyPutSuccess provides a mock function with given fields: size -func (_m *HeroCacheMetrics) OnKeyPutSuccess(size uint32) { - _m.Called(size) +// OnEntityEjectionDueToEmergency provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnEntityEjectionDueToEmergency() { + _mock.Called() + return } -// OnKeyRemoved provides a mock function with given fields: size -func (_m *HeroCacheMetrics) OnKeyRemoved(size uint32) { - _m.Called(size) +// HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnEntityEjectionDueToEmergency' +type HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call struct { + *mock.Call } -// NewHeroCacheMetrics creates a new instance of HeroCacheMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewHeroCacheMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *HeroCacheMetrics { - mock := &HeroCacheMetrics{} - mock.Mock.Test(t) +// OnEntityEjectionDueToEmergency is a helper method to define mock.On call +func (_e *HeroCacheMetrics_Expecter) OnEntityEjectionDueToEmergency() *HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call { + return &HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call{Call: _e.mock.On("OnEntityEjectionDueToEmergency")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call) Run(run func()) *HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call) Return() *HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call) RunAndReturn(run func()) *HeroCacheMetrics_OnEntityEjectionDueToEmergency_Call { + _c.Run(run) + return _c +} + +// OnEntityEjectionDueToFullCapacity provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnEntityEjectionDueToFullCapacity() { + _mock.Called() + return +} + +// HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnEntityEjectionDueToFullCapacity' +type HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call struct { + *mock.Call +} + +// OnEntityEjectionDueToFullCapacity is a helper method to define mock.On call +func (_e *HeroCacheMetrics_Expecter) OnEntityEjectionDueToFullCapacity() *HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call { + return &HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call{Call: _e.mock.On("OnEntityEjectionDueToFullCapacity")} +} + +func (_c *HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call) Run(run func()) *HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call) Return() *HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call) RunAndReturn(run func()) *HeroCacheMetrics_OnEntityEjectionDueToFullCapacity_Call { + _c.Run(run) + return _c +} + +// OnKeyGetFailure provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnKeyGetFailure() { + _mock.Called() + return +} + +// HeroCacheMetrics_OnKeyGetFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnKeyGetFailure' +type HeroCacheMetrics_OnKeyGetFailure_Call struct { + *mock.Call +} + +// OnKeyGetFailure is a helper method to define mock.On call +func (_e *HeroCacheMetrics_Expecter) OnKeyGetFailure() *HeroCacheMetrics_OnKeyGetFailure_Call { + return &HeroCacheMetrics_OnKeyGetFailure_Call{Call: _e.mock.On("OnKeyGetFailure")} +} + +func (_c *HeroCacheMetrics_OnKeyGetFailure_Call) Run(run func()) *HeroCacheMetrics_OnKeyGetFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HeroCacheMetrics_OnKeyGetFailure_Call) Return() *HeroCacheMetrics_OnKeyGetFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnKeyGetFailure_Call) RunAndReturn(run func()) *HeroCacheMetrics_OnKeyGetFailure_Call { + _c.Run(run) + return _c +} + +// OnKeyGetSuccess provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnKeyGetSuccess() { + _mock.Called() + return +} + +// HeroCacheMetrics_OnKeyGetSuccess_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnKeyGetSuccess' +type HeroCacheMetrics_OnKeyGetSuccess_Call struct { + *mock.Call +} + +// OnKeyGetSuccess is a helper method to define mock.On call +func (_e *HeroCacheMetrics_Expecter) OnKeyGetSuccess() *HeroCacheMetrics_OnKeyGetSuccess_Call { + return &HeroCacheMetrics_OnKeyGetSuccess_Call{Call: _e.mock.On("OnKeyGetSuccess")} +} + +func (_c *HeroCacheMetrics_OnKeyGetSuccess_Call) Run(run func()) *HeroCacheMetrics_OnKeyGetSuccess_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HeroCacheMetrics_OnKeyGetSuccess_Call) Return() *HeroCacheMetrics_OnKeyGetSuccess_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnKeyGetSuccess_Call) RunAndReturn(run func()) *HeroCacheMetrics_OnKeyGetSuccess_Call { + _c.Run(run) + return _c +} + +// OnKeyPutAttempt provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnKeyPutAttempt(size uint32) { + _mock.Called(size) + return +} + +// HeroCacheMetrics_OnKeyPutAttempt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnKeyPutAttempt' +type HeroCacheMetrics_OnKeyPutAttempt_Call struct { + *mock.Call +} + +// OnKeyPutAttempt is a helper method to define mock.On call +// - size uint32 +func (_e *HeroCacheMetrics_Expecter) OnKeyPutAttempt(size interface{}) *HeroCacheMetrics_OnKeyPutAttempt_Call { + return &HeroCacheMetrics_OnKeyPutAttempt_Call{Call: _e.mock.On("OnKeyPutAttempt", size)} +} + +func (_c *HeroCacheMetrics_OnKeyPutAttempt_Call) Run(run func(size uint32)) *HeroCacheMetrics_OnKeyPutAttempt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint32 + if args[0] != nil { + arg0 = args[0].(uint32) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutAttempt_Call) Return() *HeroCacheMetrics_OnKeyPutAttempt_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutAttempt_Call) RunAndReturn(run func(size uint32)) *HeroCacheMetrics_OnKeyPutAttempt_Call { + _c.Run(run) + return _c +} + +// OnKeyPutDeduplicated provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnKeyPutDeduplicated() { + _mock.Called() + return +} + +// HeroCacheMetrics_OnKeyPutDeduplicated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnKeyPutDeduplicated' +type HeroCacheMetrics_OnKeyPutDeduplicated_Call struct { + *mock.Call +} + +// OnKeyPutDeduplicated is a helper method to define mock.On call +func (_e *HeroCacheMetrics_Expecter) OnKeyPutDeduplicated() *HeroCacheMetrics_OnKeyPutDeduplicated_Call { + return &HeroCacheMetrics_OnKeyPutDeduplicated_Call{Call: _e.mock.On("OnKeyPutDeduplicated")} +} + +func (_c *HeroCacheMetrics_OnKeyPutDeduplicated_Call) Run(run func()) *HeroCacheMetrics_OnKeyPutDeduplicated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutDeduplicated_Call) Return() *HeroCacheMetrics_OnKeyPutDeduplicated_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutDeduplicated_Call) RunAndReturn(run func()) *HeroCacheMetrics_OnKeyPutDeduplicated_Call { + _c.Run(run) + return _c +} + +// OnKeyPutDrop provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnKeyPutDrop() { + _mock.Called() + return +} + +// HeroCacheMetrics_OnKeyPutDrop_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnKeyPutDrop' +type HeroCacheMetrics_OnKeyPutDrop_Call struct { + *mock.Call +} + +// OnKeyPutDrop is a helper method to define mock.On call +func (_e *HeroCacheMetrics_Expecter) OnKeyPutDrop() *HeroCacheMetrics_OnKeyPutDrop_Call { + return &HeroCacheMetrics_OnKeyPutDrop_Call{Call: _e.mock.On("OnKeyPutDrop")} +} + +func (_c *HeroCacheMetrics_OnKeyPutDrop_Call) Run(run func()) *HeroCacheMetrics_OnKeyPutDrop_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutDrop_Call) Return() *HeroCacheMetrics_OnKeyPutDrop_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutDrop_Call) RunAndReturn(run func()) *HeroCacheMetrics_OnKeyPutDrop_Call { + _c.Run(run) + return _c +} + +// OnKeyPutSuccess provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnKeyPutSuccess(size uint32) { + _mock.Called(size) + return +} + +// HeroCacheMetrics_OnKeyPutSuccess_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnKeyPutSuccess' +type HeroCacheMetrics_OnKeyPutSuccess_Call struct { + *mock.Call +} + +// OnKeyPutSuccess is a helper method to define mock.On call +// - size uint32 +func (_e *HeroCacheMetrics_Expecter) OnKeyPutSuccess(size interface{}) *HeroCacheMetrics_OnKeyPutSuccess_Call { + return &HeroCacheMetrics_OnKeyPutSuccess_Call{Call: _e.mock.On("OnKeyPutSuccess", size)} +} + +func (_c *HeroCacheMetrics_OnKeyPutSuccess_Call) Run(run func(size uint32)) *HeroCacheMetrics_OnKeyPutSuccess_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint32 + if args[0] != nil { + arg0 = args[0].(uint32) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutSuccess_Call) Return() *HeroCacheMetrics_OnKeyPutSuccess_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnKeyPutSuccess_Call) RunAndReturn(run func(size uint32)) *HeroCacheMetrics_OnKeyPutSuccess_Call { + _c.Run(run) + return _c +} + +// OnKeyRemoved provides a mock function for the type HeroCacheMetrics +func (_mock *HeroCacheMetrics) OnKeyRemoved(size uint32) { + _mock.Called(size) + return +} + +// HeroCacheMetrics_OnKeyRemoved_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnKeyRemoved' +type HeroCacheMetrics_OnKeyRemoved_Call struct { + *mock.Call +} + +// OnKeyRemoved is a helper method to define mock.On call +// - size uint32 +func (_e *HeroCacheMetrics_Expecter) OnKeyRemoved(size interface{}) *HeroCacheMetrics_OnKeyRemoved_Call { + return &HeroCacheMetrics_OnKeyRemoved_Call{Call: _e.mock.On("OnKeyRemoved", size)} +} + +func (_c *HeroCacheMetrics_OnKeyRemoved_Call) Run(run func(size uint32)) *HeroCacheMetrics_OnKeyRemoved_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint32 + if args[0] != nil { + arg0 = args[0].(uint32) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HeroCacheMetrics_OnKeyRemoved_Call) Return() *HeroCacheMetrics_OnKeyRemoved_Call { + _c.Call.Return() + return _c +} + +func (_c *HeroCacheMetrics_OnKeyRemoved_Call) RunAndReturn(run func(size uint32)) *HeroCacheMetrics_OnKeyRemoved_Call { + _c.Run(run) + return _c } diff --git a/module/mock/hot_stuff.go b/module/mock/hot_stuff.go index 1d1caa7c72b..f063b9fd6a3 100644 --- a/module/mock/hot_stuff.go +++ b/module/mock/hot_stuff.go @@ -1,79 +1,210 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewHotStuff creates a new instance of HotStuff. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewHotStuff(t interface { + mock.TestingT + Cleanup(func()) +}) *HotStuff { + mock := &HotStuff{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // HotStuff is an autogenerated mock type for the HotStuff type type HotStuff struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *HotStuff) Done() <-chan struct{} { - ret := _m.Called() +type HotStuff_Expecter struct { + mock *mock.Mock +} + +func (_m *HotStuff) EXPECT() *HotStuff_Expecter { + return &HotStuff_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type HotStuff +func (_mock *HotStuff) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *HotStuff) Ready() <-chan struct{} { - ret := _m.Called() +// HotStuff_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type HotStuff_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *HotStuff_Expecter) Done() *HotStuff_Done_Call { + return &HotStuff_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *HotStuff_Done_Call) Run(run func()) *HotStuff_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HotStuff_Done_Call) Return(valCh <-chan struct{}) *HotStuff_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *HotStuff_Done_Call) RunAndReturn(run func() <-chan struct{}) *HotStuff_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type HotStuff +func (_mock *HotStuff) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *HotStuff) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// HotStuff_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type HotStuff_Ready_Call struct { + *mock.Call } -// SubmitProposal provides a mock function with given fields: proposal -func (_m *HotStuff) SubmitProposal(proposal *model.SignedProposal) { - _m.Called(proposal) +// Ready is a helper method to define mock.On call +func (_e *HotStuff_Expecter) Ready() *HotStuff_Ready_Call { + return &HotStuff_Ready_Call{Call: _e.mock.On("Ready")} } -// NewHotStuff creates a new instance of HotStuff. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewHotStuff(t interface { - mock.TestingT - Cleanup(func()) -}) *HotStuff { - mock := &HotStuff{} - mock.Mock.Test(t) +func (_c *HotStuff_Ready_Call) Run(run func()) *HotStuff_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *HotStuff_Ready_Call) Return(valCh <-chan struct{}) *HotStuff_Ready_Call { + _c.Call.Return(valCh) + return _c +} - return mock +func (_c *HotStuff_Ready_Call) RunAndReturn(run func() <-chan struct{}) *HotStuff_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type HotStuff +func (_mock *HotStuff) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// HotStuff_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type HotStuff_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *HotStuff_Expecter) Start(signalerContext interface{}) *HotStuff_Start_Call { + return &HotStuff_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *HotStuff_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *HotStuff_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotStuff_Start_Call) Return() *HotStuff_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *HotStuff_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *HotStuff_Start_Call { + _c.Run(run) + return _c +} + +// SubmitProposal provides a mock function for the type HotStuff +func (_mock *HotStuff) SubmitProposal(proposal *model.SignedProposal) { + _mock.Called(proposal) + return +} + +// HotStuff_SubmitProposal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitProposal' +type HotStuff_SubmitProposal_Call struct { + *mock.Call +} + +// SubmitProposal is a helper method to define mock.On call +// - proposal *model.SignedProposal +func (_e *HotStuff_Expecter) SubmitProposal(proposal interface{}) *HotStuff_SubmitProposal_Call { + return &HotStuff_SubmitProposal_Call{Call: _e.mock.On("SubmitProposal", proposal)} +} + +func (_c *HotStuff_SubmitProposal_Call) Run(run func(proposal *model.SignedProposal)) *HotStuff_SubmitProposal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.SignedProposal + if args[0] != nil { + arg0 = args[0].(*model.SignedProposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotStuff_SubmitProposal_Call) Return() *HotStuff_SubmitProposal_Call { + _c.Call.Return() + return _c +} + +func (_c *HotStuff_SubmitProposal_Call) RunAndReturn(run func(proposal *model.SignedProposal)) *HotStuff_SubmitProposal_Call { + _c.Run(run) + return _c } diff --git a/module/mock/hot_stuff_follower.go b/module/mock/hot_stuff_follower.go index 04dd13126be..fbb4ff120b7 100644 --- a/module/mock/hot_stuff_follower.go +++ b/module/mock/hot_stuff_follower.go @@ -1,79 +1,210 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/consensus/hotstuff/model" ) +// NewHotStuffFollower creates a new instance of HotStuffFollower. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewHotStuffFollower(t interface { + mock.TestingT + Cleanup(func()) +}) *HotStuffFollower { + mock := &HotStuffFollower{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // HotStuffFollower is an autogenerated mock type for the HotStuffFollower type type HotStuffFollower struct { mock.Mock } -// AddCertifiedBlock provides a mock function with given fields: certifiedBlock -func (_m *HotStuffFollower) AddCertifiedBlock(certifiedBlock *model.CertifiedBlock) { - _m.Called(certifiedBlock) +type HotStuffFollower_Expecter struct { + mock *mock.Mock +} + +func (_m *HotStuffFollower) EXPECT() *HotStuffFollower_Expecter { + return &HotStuffFollower_Expecter{mock: &_m.Mock} } -// Done provides a mock function with no fields -func (_m *HotStuffFollower) Done() <-chan struct{} { - ret := _m.Called() +// AddCertifiedBlock provides a mock function for the type HotStuffFollower +func (_mock *HotStuffFollower) AddCertifiedBlock(certifiedBlock *model.CertifiedBlock) { + _mock.Called(certifiedBlock) + return +} + +// HotStuffFollower_AddCertifiedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddCertifiedBlock' +type HotStuffFollower_AddCertifiedBlock_Call struct { + *mock.Call +} + +// AddCertifiedBlock is a helper method to define mock.On call +// - certifiedBlock *model.CertifiedBlock +func (_e *HotStuffFollower_Expecter) AddCertifiedBlock(certifiedBlock interface{}) *HotStuffFollower_AddCertifiedBlock_Call { + return &HotStuffFollower_AddCertifiedBlock_Call{Call: _e.mock.On("AddCertifiedBlock", certifiedBlock)} +} + +func (_c *HotStuffFollower_AddCertifiedBlock_Call) Run(run func(certifiedBlock *model.CertifiedBlock)) *HotStuffFollower_AddCertifiedBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *model.CertifiedBlock + if args[0] != nil { + arg0 = args[0].(*model.CertifiedBlock) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotStuffFollower_AddCertifiedBlock_Call) Return() *HotStuffFollower_AddCertifiedBlock_Call { + _c.Call.Return() + return _c +} + +func (_c *HotStuffFollower_AddCertifiedBlock_Call) RunAndReturn(run func(certifiedBlock *model.CertifiedBlock)) *HotStuffFollower_AddCertifiedBlock_Call { + _c.Run(run) + return _c +} + +// Done provides a mock function for the type HotStuffFollower +func (_mock *HotStuffFollower) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *HotStuffFollower) Ready() <-chan struct{} { - ret := _m.Called() +// HotStuffFollower_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type HotStuffFollower_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *HotStuffFollower_Expecter) Done() *HotStuffFollower_Done_Call { + return &HotStuffFollower_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *HotStuffFollower_Done_Call) Run(run func()) *HotStuffFollower_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HotStuffFollower_Done_Call) Return(valCh <-chan struct{}) *HotStuffFollower_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *HotStuffFollower_Done_Call) RunAndReturn(run func() <-chan struct{}) *HotStuffFollower_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type HotStuffFollower +func (_mock *HotStuffFollower) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *HotStuffFollower) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// HotStuffFollower_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type HotStuffFollower_Ready_Call struct { + *mock.Call } -// NewHotStuffFollower creates a new instance of HotStuffFollower. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewHotStuffFollower(t interface { - mock.TestingT - Cleanup(func()) -}) *HotStuffFollower { - mock := &HotStuffFollower{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *HotStuffFollower_Expecter) Ready() *HotStuffFollower_Ready_Call { + return &HotStuffFollower_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *HotStuffFollower_Ready_Call) Run(run func()) *HotStuffFollower_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *HotStuffFollower_Ready_Call) Return(valCh <-chan struct{}) *HotStuffFollower_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *HotStuffFollower_Ready_Call) RunAndReturn(run func() <-chan struct{}) *HotStuffFollower_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type HotStuffFollower +func (_mock *HotStuffFollower) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// HotStuffFollower_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type HotStuffFollower_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *HotStuffFollower_Expecter) Start(signalerContext interface{}) *HotStuffFollower_Start_Call { + return &HotStuffFollower_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *HotStuffFollower_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *HotStuffFollower_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotStuffFollower_Start_Call) Return() *HotStuffFollower_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *HotStuffFollower_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *HotStuffFollower_Start_Call { + _c.Run(run) + return _c } diff --git a/module/mock/hotstuff_metrics.go b/module/mock/hotstuff_metrics.go index 296e7a1d8e1..7015a62c8b4 100644 --- a/module/mock/hotstuff_metrics.go +++ b/module/mock/hotstuff_metrics.go @@ -1,113 +1,728 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewHotstuffMetrics creates a new instance of HotstuffMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewHotstuffMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *HotstuffMetrics { + mock := &HotstuffMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // HotstuffMetrics is an autogenerated mock type for the HotstuffMetrics type type HotstuffMetrics struct { mock.Mock } -// BlockProcessingDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) BlockProcessingDuration(duration time.Duration) { - _m.Called(duration) +type HotstuffMetrics_Expecter struct { + mock *mock.Mock } -// CommitteeProcessingDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) CommitteeProcessingDuration(duration time.Duration) { - _m.Called(duration) +func (_m *HotstuffMetrics) EXPECT() *HotstuffMetrics_Expecter { + return &HotstuffMetrics_Expecter{mock: &_m.Mock} } -// CountSkipped provides a mock function with no fields -func (_m *HotstuffMetrics) CountSkipped() { - _m.Called() +// BlockProcessingDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) BlockProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return } -// CountTimeout provides a mock function with no fields -func (_m *HotstuffMetrics) CountTimeout() { - _m.Called() +// HotstuffMetrics_BlockProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProcessingDuration' +type HotstuffMetrics_BlockProcessingDuration_Call struct { + *mock.Call } -// HotStuffBusyDuration provides a mock function with given fields: duration, event -func (_m *HotstuffMetrics) HotStuffBusyDuration(duration time.Duration, event string) { - _m.Called(duration, event) +// BlockProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) BlockProcessingDuration(duration interface{}) *HotstuffMetrics_BlockProcessingDuration_Call { + return &HotstuffMetrics_BlockProcessingDuration_Call{Call: _e.mock.On("BlockProcessingDuration", duration)} } -// HotStuffIdleDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) HotStuffIdleDuration(duration time.Duration) { - _m.Called(duration) +func (_c *HotstuffMetrics_BlockProcessingDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_BlockProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// HotStuffWaitDuration provides a mock function with given fields: duration, event -func (_m *HotstuffMetrics) HotStuffWaitDuration(duration time.Duration, event string) { - _m.Called(duration, event) +func (_c *HotstuffMetrics_BlockProcessingDuration_Call) Return() *HotstuffMetrics_BlockProcessingDuration_Call { + _c.Call.Return() + return _c } -// PayloadProductionDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) PayloadProductionDuration(duration time.Duration) { - _m.Called(duration) +func (_c *HotstuffMetrics_BlockProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_BlockProcessingDuration_Call { + _c.Run(run) + return _c } -// SetCurView provides a mock function with given fields: view -func (_m *HotstuffMetrics) SetCurView(view uint64) { - _m.Called(view) +// CommitteeProcessingDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) CommitteeProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return } -// SetQCView provides a mock function with given fields: view -func (_m *HotstuffMetrics) SetQCView(view uint64) { - _m.Called(view) +// HotstuffMetrics_CommitteeProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CommitteeProcessingDuration' +type HotstuffMetrics_CommitteeProcessingDuration_Call struct { + *mock.Call } -// SetTCView provides a mock function with given fields: view -func (_m *HotstuffMetrics) SetTCView(view uint64) { - _m.Called(view) +// CommitteeProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) CommitteeProcessingDuration(duration interface{}) *HotstuffMetrics_CommitteeProcessingDuration_Call { + return &HotstuffMetrics_CommitteeProcessingDuration_Call{Call: _e.mock.On("CommitteeProcessingDuration", duration)} } -// SetTimeout provides a mock function with given fields: duration -func (_m *HotstuffMetrics) SetTimeout(duration time.Duration) { - _m.Called(duration) +func (_c *HotstuffMetrics_CommitteeProcessingDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_CommitteeProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// SignerProcessingDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) SignerProcessingDuration(duration time.Duration) { - _m.Called(duration) +func (_c *HotstuffMetrics_CommitteeProcessingDuration_Call) Return() *HotstuffMetrics_CommitteeProcessingDuration_Call { + _c.Call.Return() + return _c } -// TimeoutCollectorsRange provides a mock function with given fields: lowestRetainedView, newestViewCreatedCollector, activeCollectors -func (_m *HotstuffMetrics) TimeoutCollectorsRange(lowestRetainedView uint64, newestViewCreatedCollector uint64, activeCollectors int) { - _m.Called(lowestRetainedView, newestViewCreatedCollector, activeCollectors) +func (_c *HotstuffMetrics_CommitteeProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_CommitteeProcessingDuration_Call { + _c.Run(run) + return _c } -// TimeoutObjectProcessingDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) TimeoutObjectProcessingDuration(duration time.Duration) { - _m.Called(duration) +// CountSkipped provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) CountSkipped() { + _mock.Called() + return } -// ValidatorProcessingDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) ValidatorProcessingDuration(duration time.Duration) { - _m.Called(duration) +// HotstuffMetrics_CountSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CountSkipped' +type HotstuffMetrics_CountSkipped_Call struct { + *mock.Call } -// VoteProcessingDuration provides a mock function with given fields: duration -func (_m *HotstuffMetrics) VoteProcessingDuration(duration time.Duration) { - _m.Called(duration) +// CountSkipped is a helper method to define mock.On call +func (_e *HotstuffMetrics_Expecter) CountSkipped() *HotstuffMetrics_CountSkipped_Call { + return &HotstuffMetrics_CountSkipped_Call{Call: _e.mock.On("CountSkipped")} } -// NewHotstuffMetrics creates a new instance of HotstuffMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewHotstuffMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *HotstuffMetrics { - mock := &HotstuffMetrics{} - mock.Mock.Test(t) +func (_c *HotstuffMetrics_CountSkipped_Call) Run(run func()) *HotstuffMetrics_CountSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *HotstuffMetrics_CountSkipped_Call) Return() *HotstuffMetrics_CountSkipped_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *HotstuffMetrics_CountSkipped_Call) RunAndReturn(run func()) *HotstuffMetrics_CountSkipped_Call { + _c.Run(run) + return _c +} + +// CountTimeout provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) CountTimeout() { + _mock.Called() + return +} + +// HotstuffMetrics_CountTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CountTimeout' +type HotstuffMetrics_CountTimeout_Call struct { + *mock.Call +} + +// CountTimeout is a helper method to define mock.On call +func (_e *HotstuffMetrics_Expecter) CountTimeout() *HotstuffMetrics_CountTimeout_Call { + return &HotstuffMetrics_CountTimeout_Call{Call: _e.mock.On("CountTimeout")} +} + +func (_c *HotstuffMetrics_CountTimeout_Call) Run(run func()) *HotstuffMetrics_CountTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HotstuffMetrics_CountTimeout_Call) Return() *HotstuffMetrics_CountTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_CountTimeout_Call) RunAndReturn(run func()) *HotstuffMetrics_CountTimeout_Call { + _c.Run(run) + return _c +} + +// HotStuffBusyDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) HotStuffBusyDuration(duration time.Duration, event string) { + _mock.Called(duration, event) + return +} + +// HotstuffMetrics_HotStuffBusyDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HotStuffBusyDuration' +type HotstuffMetrics_HotStuffBusyDuration_Call struct { + *mock.Call +} + +// HotStuffBusyDuration is a helper method to define mock.On call +// - duration time.Duration +// - event string +func (_e *HotstuffMetrics_Expecter) HotStuffBusyDuration(duration interface{}, event interface{}) *HotstuffMetrics_HotStuffBusyDuration_Call { + return &HotstuffMetrics_HotStuffBusyDuration_Call{Call: _e.mock.On("HotStuffBusyDuration", duration, event)} +} + +func (_c *HotstuffMetrics_HotStuffBusyDuration_Call) Run(run func(duration time.Duration, event string)) *HotstuffMetrics_HotStuffBusyDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_HotStuffBusyDuration_Call) Return() *HotstuffMetrics_HotStuffBusyDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_HotStuffBusyDuration_Call) RunAndReturn(run func(duration time.Duration, event string)) *HotstuffMetrics_HotStuffBusyDuration_Call { + _c.Run(run) + return _c +} + +// HotStuffIdleDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) HotStuffIdleDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// HotstuffMetrics_HotStuffIdleDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HotStuffIdleDuration' +type HotstuffMetrics_HotStuffIdleDuration_Call struct { + *mock.Call +} + +// HotStuffIdleDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) HotStuffIdleDuration(duration interface{}) *HotstuffMetrics_HotStuffIdleDuration_Call { + return &HotstuffMetrics_HotStuffIdleDuration_Call{Call: _e.mock.On("HotStuffIdleDuration", duration)} +} + +func (_c *HotstuffMetrics_HotStuffIdleDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_HotStuffIdleDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_HotStuffIdleDuration_Call) Return() *HotstuffMetrics_HotStuffIdleDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_HotStuffIdleDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_HotStuffIdleDuration_Call { + _c.Run(run) + return _c +} + +// HotStuffWaitDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) HotStuffWaitDuration(duration time.Duration, event string) { + _mock.Called(duration, event) + return +} + +// HotstuffMetrics_HotStuffWaitDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HotStuffWaitDuration' +type HotstuffMetrics_HotStuffWaitDuration_Call struct { + *mock.Call +} + +// HotStuffWaitDuration is a helper method to define mock.On call +// - duration time.Duration +// - event string +func (_e *HotstuffMetrics_Expecter) HotStuffWaitDuration(duration interface{}, event interface{}) *HotstuffMetrics_HotStuffWaitDuration_Call { + return &HotstuffMetrics_HotStuffWaitDuration_Call{Call: _e.mock.On("HotStuffWaitDuration", duration, event)} +} + +func (_c *HotstuffMetrics_HotStuffWaitDuration_Call) Run(run func(duration time.Duration, event string)) *HotstuffMetrics_HotStuffWaitDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_HotStuffWaitDuration_Call) Return() *HotstuffMetrics_HotStuffWaitDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_HotStuffWaitDuration_Call) RunAndReturn(run func(duration time.Duration, event string)) *HotstuffMetrics_HotStuffWaitDuration_Call { + _c.Run(run) + return _c +} + +// PayloadProductionDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) PayloadProductionDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// HotstuffMetrics_PayloadProductionDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PayloadProductionDuration' +type HotstuffMetrics_PayloadProductionDuration_Call struct { + *mock.Call +} + +// PayloadProductionDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) PayloadProductionDuration(duration interface{}) *HotstuffMetrics_PayloadProductionDuration_Call { + return &HotstuffMetrics_PayloadProductionDuration_Call{Call: _e.mock.On("PayloadProductionDuration", duration)} +} + +func (_c *HotstuffMetrics_PayloadProductionDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_PayloadProductionDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_PayloadProductionDuration_Call) Return() *HotstuffMetrics_PayloadProductionDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_PayloadProductionDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_PayloadProductionDuration_Call { + _c.Run(run) + return _c +} + +// SetCurView provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) SetCurView(view uint64) { + _mock.Called(view) + return +} + +// HotstuffMetrics_SetCurView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetCurView' +type HotstuffMetrics_SetCurView_Call struct { + *mock.Call +} + +// SetCurView is a helper method to define mock.On call +// - view uint64 +func (_e *HotstuffMetrics_Expecter) SetCurView(view interface{}) *HotstuffMetrics_SetCurView_Call { + return &HotstuffMetrics_SetCurView_Call{Call: _e.mock.On("SetCurView", view)} +} + +func (_c *HotstuffMetrics_SetCurView_Call) Run(run func(view uint64)) *HotstuffMetrics_SetCurView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_SetCurView_Call) Return() *HotstuffMetrics_SetCurView_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_SetCurView_Call) RunAndReturn(run func(view uint64)) *HotstuffMetrics_SetCurView_Call { + _c.Run(run) + return _c +} + +// SetQCView provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) SetQCView(view uint64) { + _mock.Called(view) + return +} + +// HotstuffMetrics_SetQCView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetQCView' +type HotstuffMetrics_SetQCView_Call struct { + *mock.Call +} + +// SetQCView is a helper method to define mock.On call +// - view uint64 +func (_e *HotstuffMetrics_Expecter) SetQCView(view interface{}) *HotstuffMetrics_SetQCView_Call { + return &HotstuffMetrics_SetQCView_Call{Call: _e.mock.On("SetQCView", view)} +} + +func (_c *HotstuffMetrics_SetQCView_Call) Run(run func(view uint64)) *HotstuffMetrics_SetQCView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_SetQCView_Call) Return() *HotstuffMetrics_SetQCView_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_SetQCView_Call) RunAndReturn(run func(view uint64)) *HotstuffMetrics_SetQCView_Call { + _c.Run(run) + return _c +} + +// SetTCView provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) SetTCView(view uint64) { + _mock.Called(view) + return +} + +// HotstuffMetrics_SetTCView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetTCView' +type HotstuffMetrics_SetTCView_Call struct { + *mock.Call +} + +// SetTCView is a helper method to define mock.On call +// - view uint64 +func (_e *HotstuffMetrics_Expecter) SetTCView(view interface{}) *HotstuffMetrics_SetTCView_Call { + return &HotstuffMetrics_SetTCView_Call{Call: _e.mock.On("SetTCView", view)} +} + +func (_c *HotstuffMetrics_SetTCView_Call) Run(run func(view uint64)) *HotstuffMetrics_SetTCView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_SetTCView_Call) Return() *HotstuffMetrics_SetTCView_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_SetTCView_Call) RunAndReturn(run func(view uint64)) *HotstuffMetrics_SetTCView_Call { + _c.Run(run) + return _c +} + +// SetTimeout provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) SetTimeout(duration time.Duration) { + _mock.Called(duration) + return +} + +// HotstuffMetrics_SetTimeout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetTimeout' +type HotstuffMetrics_SetTimeout_Call struct { + *mock.Call +} + +// SetTimeout is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) SetTimeout(duration interface{}) *HotstuffMetrics_SetTimeout_Call { + return &HotstuffMetrics_SetTimeout_Call{Call: _e.mock.On("SetTimeout", duration)} +} + +func (_c *HotstuffMetrics_SetTimeout_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_SetTimeout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_SetTimeout_Call) Return() *HotstuffMetrics_SetTimeout_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_SetTimeout_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_SetTimeout_Call { + _c.Run(run) + return _c +} + +// SignerProcessingDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) SignerProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// HotstuffMetrics_SignerProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SignerProcessingDuration' +type HotstuffMetrics_SignerProcessingDuration_Call struct { + *mock.Call +} + +// SignerProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) SignerProcessingDuration(duration interface{}) *HotstuffMetrics_SignerProcessingDuration_Call { + return &HotstuffMetrics_SignerProcessingDuration_Call{Call: _e.mock.On("SignerProcessingDuration", duration)} +} + +func (_c *HotstuffMetrics_SignerProcessingDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_SignerProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_SignerProcessingDuration_Call) Return() *HotstuffMetrics_SignerProcessingDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_SignerProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_SignerProcessingDuration_Call { + _c.Run(run) + return _c +} + +// TimeoutCollectorsRange provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) TimeoutCollectorsRange(lowestRetainedView uint64, newestViewCreatedCollector uint64, activeCollectors int) { + _mock.Called(lowestRetainedView, newestViewCreatedCollector, activeCollectors) + return +} + +// HotstuffMetrics_TimeoutCollectorsRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TimeoutCollectorsRange' +type HotstuffMetrics_TimeoutCollectorsRange_Call struct { + *mock.Call +} + +// TimeoutCollectorsRange is a helper method to define mock.On call +// - lowestRetainedView uint64 +// - newestViewCreatedCollector uint64 +// - activeCollectors int +func (_e *HotstuffMetrics_Expecter) TimeoutCollectorsRange(lowestRetainedView interface{}, newestViewCreatedCollector interface{}, activeCollectors interface{}) *HotstuffMetrics_TimeoutCollectorsRange_Call { + return &HotstuffMetrics_TimeoutCollectorsRange_Call{Call: _e.mock.On("TimeoutCollectorsRange", lowestRetainedView, newestViewCreatedCollector, activeCollectors)} +} + +func (_c *HotstuffMetrics_TimeoutCollectorsRange_Call) Run(run func(lowestRetainedView uint64, newestViewCreatedCollector uint64, activeCollectors int)) *HotstuffMetrics_TimeoutCollectorsRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_TimeoutCollectorsRange_Call) Return() *HotstuffMetrics_TimeoutCollectorsRange_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_TimeoutCollectorsRange_Call) RunAndReturn(run func(lowestRetainedView uint64, newestViewCreatedCollector uint64, activeCollectors int)) *HotstuffMetrics_TimeoutCollectorsRange_Call { + _c.Run(run) + return _c +} + +// TimeoutObjectProcessingDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) TimeoutObjectProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// HotstuffMetrics_TimeoutObjectProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TimeoutObjectProcessingDuration' +type HotstuffMetrics_TimeoutObjectProcessingDuration_Call struct { + *mock.Call +} + +// TimeoutObjectProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) TimeoutObjectProcessingDuration(duration interface{}) *HotstuffMetrics_TimeoutObjectProcessingDuration_Call { + return &HotstuffMetrics_TimeoutObjectProcessingDuration_Call{Call: _e.mock.On("TimeoutObjectProcessingDuration", duration)} +} + +func (_c *HotstuffMetrics_TimeoutObjectProcessingDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_TimeoutObjectProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_TimeoutObjectProcessingDuration_Call) Return() *HotstuffMetrics_TimeoutObjectProcessingDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_TimeoutObjectProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_TimeoutObjectProcessingDuration_Call { + _c.Run(run) + return _c +} + +// ValidatorProcessingDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) ValidatorProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// HotstuffMetrics_ValidatorProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidatorProcessingDuration' +type HotstuffMetrics_ValidatorProcessingDuration_Call struct { + *mock.Call +} + +// ValidatorProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) ValidatorProcessingDuration(duration interface{}) *HotstuffMetrics_ValidatorProcessingDuration_Call { + return &HotstuffMetrics_ValidatorProcessingDuration_Call{Call: _e.mock.On("ValidatorProcessingDuration", duration)} +} + +func (_c *HotstuffMetrics_ValidatorProcessingDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_ValidatorProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_ValidatorProcessingDuration_Call) Return() *HotstuffMetrics_ValidatorProcessingDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_ValidatorProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_ValidatorProcessingDuration_Call { + _c.Run(run) + return _c +} + +// VoteProcessingDuration provides a mock function for the type HotstuffMetrics +func (_mock *HotstuffMetrics) VoteProcessingDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// HotstuffMetrics_VoteProcessingDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VoteProcessingDuration' +type HotstuffMetrics_VoteProcessingDuration_Call struct { + *mock.Call +} + +// VoteProcessingDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *HotstuffMetrics_Expecter) VoteProcessingDuration(duration interface{}) *HotstuffMetrics_VoteProcessingDuration_Call { + return &HotstuffMetrics_VoteProcessingDuration_Call{Call: _e.mock.On("VoteProcessingDuration", duration)} +} + +func (_c *HotstuffMetrics_VoteProcessingDuration_Call) Run(run func(duration time.Duration)) *HotstuffMetrics_VoteProcessingDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HotstuffMetrics_VoteProcessingDuration_Call) Return() *HotstuffMetrics_VoteProcessingDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *HotstuffMetrics_VoteProcessingDuration_Call) RunAndReturn(run func(duration time.Duration)) *HotstuffMetrics_VoteProcessingDuration_Call { + _c.Run(run) + return _c } diff --git a/module/mock/identifier_provider.go b/module/mock/identifier_provider.go index 5836f825c4e..8418b960324 100644 --- a/module/mock/identifier_provider.go +++ b/module/mock/identifier_provider.go @@ -1,47 +1,83 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewIdentifierProvider creates a new instance of IdentifierProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIdentifierProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *IdentifierProvider { + mock := &IdentifierProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IdentifierProvider is an autogenerated mock type for the IdentifierProvider type type IdentifierProvider struct { mock.Mock } -// Identifiers provides a mock function with no fields -func (_m *IdentifierProvider) Identifiers() flow.IdentifierList { - ret := _m.Called() +type IdentifierProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *IdentifierProvider) EXPECT() *IdentifierProvider_Expecter { + return &IdentifierProvider_Expecter{mock: &_m.Mock} +} + +// Identifiers provides a mock function for the type IdentifierProvider +func (_mock *IdentifierProvider) Identifiers() flow.IdentifierList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Identifiers") } var r0 flow.IdentifierList - if rf, ok := ret.Get(0).(func() flow.IdentifierList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentifierList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentifierList) } } - return r0 } -// NewIdentifierProvider creates a new instance of IdentifierProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIdentifierProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *IdentifierProvider { - mock := &IdentifierProvider{} - mock.Mock.Test(t) +// IdentifierProvider_Identifiers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Identifiers' +type IdentifierProvider_Identifiers_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Identifiers is a helper method to define mock.On call +func (_e *IdentifierProvider_Expecter) Identifiers() *IdentifierProvider_Identifiers_Call { + return &IdentifierProvider_Identifiers_Call{Call: _e.mock.On("Identifiers")} +} - return mock +func (_c *IdentifierProvider_Identifiers_Call) Run(run func()) *IdentifierProvider_Identifiers_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IdentifierProvider_Identifiers_Call) Return(identifierList flow.IdentifierList) *IdentifierProvider_Identifiers_Call { + _c.Call.Return(identifierList) + return _c +} + +func (_c *IdentifierProvider_Identifiers_Call) RunAndReturn(run func() flow.IdentifierList) *IdentifierProvider_Identifiers_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/identity_provider.go b/module/mock/identity_provider.go index b2641ffb105..ebf600232b1 100644 --- a/module/mock/identity_provider.go +++ b/module/mock/identity_provider.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewIdentityProvider creates a new instance of IdentityProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIdentityProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *IdentityProvider { + mock := &IdentityProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IdentityProvider is an autogenerated mock type for the IdentityProvider type type IdentityProvider struct { mock.Mock } -// ByNodeID provides a mock function with given fields: _a0 -func (_m *IdentityProvider) ByNodeID(_a0 flow.Identifier) (*flow.Identity, bool) { - ret := _m.Called(_a0) +type IdentityProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *IdentityProvider) EXPECT() *IdentityProvider_Expecter { + return &IdentityProvider_Expecter{mock: &_m.Mock} +} + +// ByNodeID provides a mock function for the type IdentityProvider +func (_mock *IdentityProvider) ByNodeID(identifier flow.Identifier) (*flow.Identity, bool) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for ByNodeID") @@ -24,29 +47,61 @@ func (_m *IdentityProvider) ByNodeID(_a0 flow.Identifier) (*flow.Identity, bool) var r0 *flow.Identity var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Identity, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Identity, bool)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Identity); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Identity); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Identity) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// ByPeerID provides a mock function with given fields: _a0 -func (_m *IdentityProvider) ByPeerID(_a0 peer.ID) (*flow.Identity, bool) { - ret := _m.Called(_a0) +// IdentityProvider_ByNodeID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByNodeID' +type IdentityProvider_ByNodeID_Call struct { + *mock.Call +} + +// ByNodeID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *IdentityProvider_Expecter) ByNodeID(identifier interface{}) *IdentityProvider_ByNodeID_Call { + return &IdentityProvider_ByNodeID_Call{Call: _e.mock.On("ByNodeID", identifier)} +} + +func (_c *IdentityProvider_ByNodeID_Call) Run(run func(identifier flow.Identifier)) *IdentityProvider_ByNodeID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IdentityProvider_ByNodeID_Call) Return(identity *flow.Identity, b bool) *IdentityProvider_ByNodeID_Call { + _c.Call.Return(identity, b) + return _c +} + +func (_c *IdentityProvider_ByNodeID_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.Identity, bool)) *IdentityProvider_ByNodeID_Call { + _c.Call.Return(run) + return _c +} + +// ByPeerID provides a mock function for the type IdentityProvider +func (_mock *IdentityProvider) ByPeerID(iD peer.ID) (*flow.Identity, bool) { + ret := _mock.Called(iD) if len(ret) == 0 { panic("no return value specified for ByPeerID") @@ -54,56 +109,107 @@ func (_m *IdentityProvider) ByPeerID(_a0 peer.ID) (*flow.Identity, bool) { var r0 *flow.Identity var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (*flow.Identity, bool)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (*flow.Identity, bool)); ok { + return returnFunc(iD) } - if rf, ok := ret.Get(0).(func(peer.ID) *flow.Identity); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(peer.ID) *flow.Identity); ok { + r0 = returnFunc(iD) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Identity) } } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(iD) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Identities provides a mock function with given fields: _a0 -func (_m *IdentityProvider) Identities(_a0 flow.IdentityFilter[flow.Identity]) flow.IdentityList { - ret := _m.Called(_a0) +// IdentityProvider_ByPeerID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByPeerID' +type IdentityProvider_ByPeerID_Call struct { + *mock.Call +} + +// ByPeerID is a helper method to define mock.On call +// - iD peer.ID +func (_e *IdentityProvider_Expecter) ByPeerID(iD interface{}) *IdentityProvider_ByPeerID_Call { + return &IdentityProvider_ByPeerID_Call{Call: _e.mock.On("ByPeerID", iD)} +} + +func (_c *IdentityProvider_ByPeerID_Call) Run(run func(iD peer.ID)) *IdentityProvider_ByPeerID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IdentityProvider_ByPeerID_Call) Return(identity *flow.Identity, b bool) *IdentityProvider_ByPeerID_Call { + _c.Call.Return(identity, b) + return _c +} + +func (_c *IdentityProvider_ByPeerID_Call) RunAndReturn(run func(iD peer.ID) (*flow.Identity, bool)) *IdentityProvider_ByPeerID_Call { + _c.Call.Return(run) + return _c +} + +// Identities provides a mock function for the type IdentityProvider +func (_mock *IdentityProvider) Identities(identityFilter flow.IdentityFilter[flow.Identity]) flow.IdentityList { + ret := _mock.Called(identityFilter) if len(ret) == 0 { panic("no return value specified for Identities") } var r0 flow.IdentityList - if rf, ok := ret.Get(0).(func(flow.IdentityFilter[flow.Identity]) flow.IdentityList); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.IdentityFilter[flow.Identity]) flow.IdentityList); ok { + r0 = returnFunc(identityFilter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentityList) } } - return r0 } -// NewIdentityProvider creates a new instance of IdentityProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIdentityProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *IdentityProvider { - mock := &IdentityProvider{} - mock.Mock.Test(t) +// IdentityProvider_Identities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Identities' +type IdentityProvider_Identities_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Identities is a helper method to define mock.On call +// - identityFilter flow.IdentityFilter[flow.Identity] +func (_e *IdentityProvider_Expecter) Identities(identityFilter interface{}) *IdentityProvider_Identities_Call { + return &IdentityProvider_Identities_Call{Call: _e.mock.On("Identities", identityFilter)} +} - return mock +func (_c *IdentityProvider_Identities_Call) Run(run func(identityFilter flow.IdentityFilter[flow.Identity])) *IdentityProvider_Identities_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.IdentityFilter[flow.Identity] + if args[0] != nil { + arg0 = args[0].(flow.IdentityFilter[flow.Identity]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IdentityProvider_Identities_Call) Return(v flow.IdentityList) *IdentityProvider_Identities_Call { + _c.Call.Return(v) + return _c +} + +func (_c *IdentityProvider_Identities_Call) RunAndReturn(run func(identityFilter flow.IdentityFilter[flow.Identity]) flow.IdentityList) *IdentityProvider_Identities_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/iterator_creator.go b/module/mock/iterator_creator.go index 82d6600d155..64236906f76 100644 --- a/module/mock/iterator_creator.go +++ b/module/mock/iterator_creator.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - module "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" ) +// NewIteratorCreator creates a new instance of IteratorCreator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIteratorCreator(t interface { + mock.TestingT + Cleanup(func()) +}) *IteratorCreator { + mock := &IteratorCreator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IteratorCreator is an autogenerated mock type for the IteratorCreator type type IteratorCreator struct { mock.Mock } -// Create provides a mock function with no fields -func (_m *IteratorCreator) Create() (module.BlockIterator, bool, error) { - ret := _m.Called() +type IteratorCreator_Expecter struct { + mock *mock.Mock +} + +func (_m *IteratorCreator) EXPECT() *IteratorCreator_Expecter { + return &IteratorCreator_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type IteratorCreator +func (_mock *IteratorCreator) Create() (module.BlockIterator, bool, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Create") @@ -23,62 +47,98 @@ func (_m *IteratorCreator) Create() (module.BlockIterator, bool, error) { var r0 module.BlockIterator var r1 bool var r2 error - if rf, ok := ret.Get(0).(func() (module.BlockIterator, bool, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (module.BlockIterator, bool, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() module.BlockIterator); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() module.BlockIterator); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(module.BlockIterator) } } - - if rf, ok := ret.Get(1).(func() bool); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// IteratorState provides a mock function with no fields -func (_m *IteratorCreator) IteratorState() module.IteratorStateReader { - ret := _m.Called() +// IteratorCreator_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type IteratorCreator_Create_Call struct { + *mock.Call +} + +// Create is a helper method to define mock.On call +func (_e *IteratorCreator_Expecter) Create() *IteratorCreator_Create_Call { + return &IteratorCreator_Create_Call{Call: _e.mock.On("Create")} +} + +func (_c *IteratorCreator_Create_Call) Run(run func()) *IteratorCreator_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IteratorCreator_Create_Call) Return(fromSavedIndexToLatest module.BlockIterator, hasNext bool, exception error) *IteratorCreator_Create_Call { + _c.Call.Return(fromSavedIndexToLatest, hasNext, exception) + return _c +} + +func (_c *IteratorCreator_Create_Call) RunAndReturn(run func() (module.BlockIterator, bool, error)) *IteratorCreator_Create_Call { + _c.Call.Return(run) + return _c +} + +// IteratorState provides a mock function for the type IteratorCreator +func (_mock *IteratorCreator) IteratorState() module.IteratorStateReader { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for IteratorState") } var r0 module.IteratorStateReader - if rf, ok := ret.Get(0).(func() module.IteratorStateReader); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() module.IteratorStateReader); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(module.IteratorStateReader) } } - return r0 } -// NewIteratorCreator creates a new instance of IteratorCreator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIteratorCreator(t interface { - mock.TestingT - Cleanup(func()) -}) *IteratorCreator { - mock := &IteratorCreator{} - mock.Mock.Test(t) +// IteratorCreator_IteratorState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IteratorState' +type IteratorCreator_IteratorState_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// IteratorState is a helper method to define mock.On call +func (_e *IteratorCreator_Expecter) IteratorState() *IteratorCreator_IteratorState_Call { + return &IteratorCreator_IteratorState_Call{Call: _e.mock.On("IteratorState")} +} - return mock +func (_c *IteratorCreator_IteratorState_Call) Run(run func()) *IteratorCreator_IteratorState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IteratorCreator_IteratorState_Call) Return(iteratorStateReader module.IteratorStateReader) *IteratorCreator_IteratorState_Call { + _c.Call.Return(iteratorStateReader) + return _c +} + +func (_c *IteratorCreator_IteratorState_Call) RunAndReturn(run func() module.IteratorStateReader) *IteratorCreator_IteratorState_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/iterator_state.go b/module/mock/iterator_state.go index 6b832d9567f..e11cfbab134 100644 --- a/module/mock/iterator_state.go +++ b/module/mock/iterator_state.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewIteratorState creates a new instance of IteratorState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIteratorState(t interface { + mock.TestingT + Cleanup(func()) +}) *IteratorState { + mock := &IteratorState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // IteratorState is an autogenerated mock type for the IteratorState type type IteratorState struct { mock.Mock } -// LoadState provides a mock function with no fields -func (_m *IteratorState) LoadState() (uint64, error) { - ret := _m.Called() +type IteratorState_Expecter struct { + mock *mock.Mock +} + +func (_m *IteratorState) EXPECT() *IteratorState_Expecter { + return &IteratorState_Expecter{mock: &_m.Mock} +} + +// LoadState provides a mock function for the type IteratorState +func (_mock *IteratorState) LoadState() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LoadState") @@ -19,52 +45,96 @@ func (_m *IteratorState) LoadState() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// SaveState provides a mock function with given fields: _a0 -func (_m *IteratorState) SaveState(_a0 uint64) error { - ret := _m.Called(_a0) +// IteratorState_LoadState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LoadState' +type IteratorState_LoadState_Call struct { + *mock.Call +} + +// LoadState is a helper method to define mock.On call +func (_e *IteratorState_Expecter) LoadState() *IteratorState_LoadState_Call { + return &IteratorState_LoadState_Call{Call: _e.mock.On("LoadState")} +} + +func (_c *IteratorState_LoadState_Call) Run(run func()) *IteratorState_LoadState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IteratorState_LoadState_Call) Return(progress uint64, exception error) *IteratorState_LoadState_Call { + _c.Call.Return(progress, exception) + return _c +} + +func (_c *IteratorState_LoadState_Call) RunAndReturn(run func() (uint64, error)) *IteratorState_LoadState_Call { + _c.Call.Return(run) + return _c +} + +// SaveState provides a mock function for the type IteratorState +func (_mock *IteratorState) SaveState(v uint64) error { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for SaveState") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(v) } else { r0 = ret.Error(0) } - return r0 } -// NewIteratorState creates a new instance of IteratorState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIteratorState(t interface { - mock.TestingT - Cleanup(func()) -}) *IteratorState { - mock := &IteratorState{} - mock.Mock.Test(t) +// IteratorState_SaveState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SaveState' +type IteratorState_SaveState_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SaveState is a helper method to define mock.On call +// - v uint64 +func (_e *IteratorState_Expecter) SaveState(v interface{}) *IteratorState_SaveState_Call { + return &IteratorState_SaveState_Call{Call: _e.mock.On("SaveState", v)} +} - return mock +func (_c *IteratorState_SaveState_Call) Run(run func(v uint64)) *IteratorState_SaveState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IteratorState_SaveState_Call) Return(exception error) *IteratorState_SaveState_Call { + _c.Call.Return(exception) + return _c +} + +func (_c *IteratorState_SaveState_Call) RunAndReturn(run func(v uint64) error) *IteratorState_SaveState_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/iterator_state_reader.go b/module/mock/iterator_state_reader.go index cac08633302..ca7b7035fe1 100644 --- a/module/mock/iterator_state_reader.go +++ b/module/mock/iterator_state_reader.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewIteratorStateReader creates a new instance of IteratorStateReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIteratorStateReader(t interface { + mock.TestingT + Cleanup(func()) +}) *IteratorStateReader { + mock := &IteratorStateReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // IteratorStateReader is an autogenerated mock type for the IteratorStateReader type type IteratorStateReader struct { mock.Mock } -// LoadState provides a mock function with no fields -func (_m *IteratorStateReader) LoadState() (uint64, error) { - ret := _m.Called() +type IteratorStateReader_Expecter struct { + mock *mock.Mock +} + +func (_m *IteratorStateReader) EXPECT() *IteratorStateReader_Expecter { + return &IteratorStateReader_Expecter{mock: &_m.Mock} +} + +// LoadState provides a mock function for the type IteratorStateReader +func (_mock *IteratorStateReader) LoadState() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LoadState") @@ -19,34 +45,45 @@ func (_m *IteratorStateReader) LoadState() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewIteratorStateReader creates a new instance of IteratorStateReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIteratorStateReader(t interface { - mock.TestingT - Cleanup(func()) -}) *IteratorStateReader { - mock := &IteratorStateReader{} - mock.Mock.Test(t) +// IteratorStateReader_LoadState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LoadState' +type IteratorStateReader_LoadState_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// LoadState is a helper method to define mock.On call +func (_e *IteratorStateReader_Expecter) LoadState() *IteratorStateReader_LoadState_Call { + return &IteratorStateReader_LoadState_Call{Call: _e.mock.On("LoadState")} +} - return mock +func (_c *IteratorStateReader_LoadState_Call) Run(run func()) *IteratorStateReader_LoadState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IteratorStateReader_LoadState_Call) Return(progress uint64, exception error) *IteratorStateReader_LoadState_Call { + _c.Call.Return(progress, exception) + return _c +} + +func (_c *IteratorStateReader_LoadState_Call) RunAndReturn(run func() (uint64, error)) *IteratorStateReader_LoadState_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/iterator_state_writer.go b/module/mock/iterator_state_writer.go index 9801672458c..35e5862e646 100644 --- a/module/mock/iterator_state_writer.go +++ b/module/mock/iterator_state_writer.go @@ -1,42 +1,87 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewIteratorStateWriter creates a new instance of IteratorStateWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIteratorStateWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *IteratorStateWriter { + mock := &IteratorStateWriter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // IteratorStateWriter is an autogenerated mock type for the IteratorStateWriter type type IteratorStateWriter struct { mock.Mock } -// SaveState provides a mock function with given fields: _a0 -func (_m *IteratorStateWriter) SaveState(_a0 uint64) error { - ret := _m.Called(_a0) +type IteratorStateWriter_Expecter struct { + mock *mock.Mock +} + +func (_m *IteratorStateWriter) EXPECT() *IteratorStateWriter_Expecter { + return &IteratorStateWriter_Expecter{mock: &_m.Mock} +} + +// SaveState provides a mock function for the type IteratorStateWriter +func (_mock *IteratorStateWriter) SaveState(v uint64) error { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for SaveState") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(v) } else { r0 = ret.Error(0) } - return r0 } -// NewIteratorStateWriter creates a new instance of IteratorStateWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIteratorStateWriter(t interface { - mock.TestingT - Cleanup(func()) -}) *IteratorStateWriter { - mock := &IteratorStateWriter{} - mock.Mock.Test(t) +// IteratorStateWriter_SaveState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SaveState' +type IteratorStateWriter_SaveState_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SaveState is a helper method to define mock.On call +// - v uint64 +func (_e *IteratorStateWriter_Expecter) SaveState(v interface{}) *IteratorStateWriter_SaveState_Call { + return &IteratorStateWriter_SaveState_Call{Call: _e.mock.On("SaveState", v)} +} - return mock +func (_c *IteratorStateWriter_SaveState_Call) Run(run func(v uint64)) *IteratorStateWriter_SaveState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IteratorStateWriter_SaveState_Call) Return(exception error) *IteratorStateWriter_SaveState_Call { + _c.Call.Return(exception) + return _c +} + +func (_c *IteratorStateWriter_SaveState_Call) RunAndReturn(run func(v uint64) error) *IteratorStateWriter_SaveState_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/job.go b/module/mock/job.go index f2b04faaf0a..69ef3c0179a 100644 --- a/module/mock/job.go +++ b/module/mock/job.go @@ -1,45 +1,81 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - module "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" ) +// NewJob creates a new instance of Job. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewJob(t interface { + mock.TestingT + Cleanup(func()) +}) *Job { + mock := &Job{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Job is an autogenerated mock type for the Job type type Job struct { mock.Mock } -// ID provides a mock function with no fields -func (_m *Job) ID() module.JobID { - ret := _m.Called() +type Job_Expecter struct { + mock *mock.Mock +} + +func (_m *Job) EXPECT() *Job_Expecter { + return &Job_Expecter{mock: &_m.Mock} +} + +// ID provides a mock function for the type Job +func (_mock *Job) ID() module.JobID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 module.JobID - if rf, ok := ret.Get(0).(func() module.JobID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() module.JobID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(module.JobID) } - return r0 } -// NewJob creates a new instance of Job. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewJob(t interface { - mock.TestingT - Cleanup(func()) -}) *Job { - mock := &Job{} - mock.Mock.Test(t) +// Job_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type Job_ID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ID is a helper method to define mock.On call +func (_e *Job_Expecter) ID() *Job_ID_Call { + return &Job_ID_Call{Call: _e.mock.On("ID")} +} - return mock +func (_c *Job_ID_Call) Run(run func()) *Job_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Job_ID_Call) Return(jobID module.JobID) *Job_ID_Call { + _c.Call.Return(jobID) + return _c +} + +func (_c *Job_ID_Call) RunAndReturn(run func() module.JobID) *Job_ID_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/job_consumer.go b/module/mock/job_consumer.go index 670fad92308..7e6d2f20860 100644 --- a/module/mock/job_consumer.go +++ b/module/mock/job_consumer.go @@ -1,109 +1,286 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - module "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" ) +// NewJobConsumer creates a new instance of JobConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewJobConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *JobConsumer { + mock := &JobConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // JobConsumer is an autogenerated mock type for the JobConsumer type type JobConsumer struct { mock.Mock } -// Check provides a mock function with no fields -func (_m *JobConsumer) Check() { - _m.Called() +type JobConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *JobConsumer) EXPECT() *JobConsumer_Expecter { + return &JobConsumer_Expecter{mock: &_m.Mock} +} + +// Check provides a mock function for the type JobConsumer +func (_mock *JobConsumer) Check() { + _mock.Called() + return +} + +// JobConsumer_Check_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Check' +type JobConsumer_Check_Call struct { + *mock.Call +} + +// Check is a helper method to define mock.On call +func (_e *JobConsumer_Expecter) Check() *JobConsumer_Check_Call { + return &JobConsumer_Check_Call{Call: _e.mock.On("Check")} } -// LastProcessedIndex provides a mock function with no fields -func (_m *JobConsumer) LastProcessedIndex() uint64 { - ret := _m.Called() +func (_c *JobConsumer_Check_Call) Run(run func()) *JobConsumer_Check_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *JobConsumer_Check_Call) Return() *JobConsumer_Check_Call { + _c.Call.Return() + return _c +} + +func (_c *JobConsumer_Check_Call) RunAndReturn(run func()) *JobConsumer_Check_Call { + _c.Run(run) + return _c +} + +// LastProcessedIndex provides a mock function for the type JobConsumer +func (_mock *JobConsumer) LastProcessedIndex() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LastProcessedIndex") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NotifyJobIsDone provides a mock function with given fields: _a0 -func (_m *JobConsumer) NotifyJobIsDone(_a0 module.JobID) uint64 { - ret := _m.Called(_a0) +// JobConsumer_LastProcessedIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LastProcessedIndex' +type JobConsumer_LastProcessedIndex_Call struct { + *mock.Call +} + +// LastProcessedIndex is a helper method to define mock.On call +func (_e *JobConsumer_Expecter) LastProcessedIndex() *JobConsumer_LastProcessedIndex_Call { + return &JobConsumer_LastProcessedIndex_Call{Call: _e.mock.On("LastProcessedIndex")} +} + +func (_c *JobConsumer_LastProcessedIndex_Call) Run(run func()) *JobConsumer_LastProcessedIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *JobConsumer_LastProcessedIndex_Call) Return(v uint64) *JobConsumer_LastProcessedIndex_Call { + _c.Call.Return(v) + return _c +} + +func (_c *JobConsumer_LastProcessedIndex_Call) RunAndReturn(run func() uint64) *JobConsumer_LastProcessedIndex_Call { + _c.Call.Return(run) + return _c +} + +// NotifyJobIsDone provides a mock function for the type JobConsumer +func (_mock *JobConsumer) NotifyJobIsDone(jobID module.JobID) uint64 { + ret := _mock.Called(jobID) if len(ret) == 0 { panic("no return value specified for NotifyJobIsDone") } var r0 uint64 - if rf, ok := ret.Get(0).(func(module.JobID) uint64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(module.JobID) uint64); ok { + r0 = returnFunc(jobID) } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Size provides a mock function with no fields -func (_m *JobConsumer) Size() uint { - ret := _m.Called() +// JobConsumer_NotifyJobIsDone_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NotifyJobIsDone' +type JobConsumer_NotifyJobIsDone_Call struct { + *mock.Call +} + +// NotifyJobIsDone is a helper method to define mock.On call +// - jobID module.JobID +func (_e *JobConsumer_Expecter) NotifyJobIsDone(jobID interface{}) *JobConsumer_NotifyJobIsDone_Call { + return &JobConsumer_NotifyJobIsDone_Call{Call: _e.mock.On("NotifyJobIsDone", jobID)} +} + +func (_c *JobConsumer_NotifyJobIsDone_Call) Run(run func(jobID module.JobID)) *JobConsumer_NotifyJobIsDone_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 module.JobID + if args[0] != nil { + arg0 = args[0].(module.JobID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *JobConsumer_NotifyJobIsDone_Call) Return(v uint64) *JobConsumer_NotifyJobIsDone_Call { + _c.Call.Return(v) + return _c +} + +func (_c *JobConsumer_NotifyJobIsDone_Call) RunAndReturn(run func(jobID module.JobID) uint64) *JobConsumer_NotifyJobIsDone_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type JobConsumer +func (_mock *JobConsumer) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Start provides a mock function with no fields -func (_m *JobConsumer) Start() error { - ret := _m.Called() +// JobConsumer_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type JobConsumer_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *JobConsumer_Expecter) Size() *JobConsumer_Size_Call { + return &JobConsumer_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *JobConsumer_Size_Call) Run(run func()) *JobConsumer_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *JobConsumer_Size_Call) Return(v uint) *JobConsumer_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *JobConsumer_Size_Call) RunAndReturn(run func() uint) *JobConsumer_Size_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type JobConsumer +func (_mock *JobConsumer) Start() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Start") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Stop provides a mock function with no fields -func (_m *JobConsumer) Stop() { - _m.Called() +// JobConsumer_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type JobConsumer_Start_Call struct { + *mock.Call } -// NewJobConsumer creates a new instance of JobConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewJobConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *JobConsumer { - mock := &JobConsumer{} - mock.Mock.Test(t) +// Start is a helper method to define mock.On call +func (_e *JobConsumer_Expecter) Start() *JobConsumer_Start_Call { + return &JobConsumer_Start_Call{Call: _e.mock.On("Start")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *JobConsumer_Start_Call) Run(run func()) *JobConsumer_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *JobConsumer_Start_Call) Return(err error) *JobConsumer_Start_Call { + _c.Call.Return(err) + return _c +} + +func (_c *JobConsumer_Start_Call) RunAndReturn(run func() error) *JobConsumer_Start_Call { + _c.Call.Return(run) + return _c +} + +// Stop provides a mock function for the type JobConsumer +func (_mock *JobConsumer) Stop() { + _mock.Called() + return +} + +// JobConsumer_Stop_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Stop' +type JobConsumer_Stop_Call struct { + *mock.Call +} + +// Stop is a helper method to define mock.On call +func (_e *JobConsumer_Expecter) Stop() *JobConsumer_Stop_Call { + return &JobConsumer_Stop_Call{Call: _e.mock.On("Stop")} +} + +func (_c *JobConsumer_Stop_Call) Run(run func()) *JobConsumer_Stop_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *JobConsumer_Stop_Call) Return() *JobConsumer_Stop_Call { + _c.Call.Return() + return _c +} + +func (_c *JobConsumer_Stop_Call) RunAndReturn(run func()) *JobConsumer_Stop_Call { + _c.Run(run) + return _c } diff --git a/module/mock/job_queue.go b/module/mock/job_queue.go index 7f6356965e2..9df8ca1dd77 100644 --- a/module/mock/job_queue.go +++ b/module/mock/job_queue.go @@ -1,45 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - module "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" ) +// NewJobQueue creates a new instance of JobQueue. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewJobQueue(t interface { + mock.TestingT + Cleanup(func()) +}) *JobQueue { + mock := &JobQueue{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // JobQueue is an autogenerated mock type for the JobQueue type type JobQueue struct { mock.Mock } -// Add provides a mock function with given fields: job -func (_m *JobQueue) Add(job module.Job) error { - ret := _m.Called(job) +type JobQueue_Expecter struct { + mock *mock.Mock +} + +func (_m *JobQueue) EXPECT() *JobQueue_Expecter { + return &JobQueue_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type JobQueue +func (_mock *JobQueue) Add(job module.Job) error { + ret := _mock.Called(job) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(module.Job) error); ok { - r0 = rf(job) + if returnFunc, ok := ret.Get(0).(func(module.Job) error); ok { + r0 = returnFunc(job) } else { r0 = ret.Error(0) } - return r0 } -// NewJobQueue creates a new instance of JobQueue. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewJobQueue(t interface { - mock.TestingT - Cleanup(func()) -}) *JobQueue { - mock := &JobQueue{} - mock.Mock.Test(t) +// JobQueue_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type JobQueue_Add_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Add is a helper method to define mock.On call +// - job module.Job +func (_e *JobQueue_Expecter) Add(job interface{}) *JobQueue_Add_Call { + return &JobQueue_Add_Call{Call: _e.mock.On("Add", job)} +} - return mock +func (_c *JobQueue_Add_Call) Run(run func(job module.Job)) *JobQueue_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 module.Job + if args[0] != nil { + arg0 = args[0].(module.Job) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *JobQueue_Add_Call) Return(err error) *JobQueue_Add_Call { + _c.Call.Return(err) + return _c +} + +func (_c *JobQueue_Add_Call) RunAndReturn(run func(job module.Job) error) *JobQueue_Add_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/jobs.go b/module/mock/jobs.go index 6a7376b2d07..aab6b6b7d92 100644 --- a/module/mock/jobs.go +++ b/module/mock/jobs.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - module "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" ) +// NewJobs creates a new instance of Jobs. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewJobs(t interface { + mock.TestingT + Cleanup(func()) +}) *Jobs { + mock := &Jobs{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Jobs is an autogenerated mock type for the Jobs type type Jobs struct { mock.Mock } -// AtIndex provides a mock function with given fields: index -func (_m *Jobs) AtIndex(index uint64) (module.Job, error) { - ret := _m.Called(index) +type Jobs_Expecter struct { + mock *mock.Mock +} + +func (_m *Jobs) EXPECT() *Jobs_Expecter { + return &Jobs_Expecter{mock: &_m.Mock} +} + +// AtIndex provides a mock function for the type Jobs +func (_mock *Jobs) AtIndex(index uint64) (module.Job, error) { + ret := _mock.Called(index) if len(ret) == 0 { panic("no return value specified for AtIndex") @@ -22,29 +46,61 @@ func (_m *Jobs) AtIndex(index uint64) (module.Job, error) { var r0 module.Job var r1 error - if rf, ok := ret.Get(0).(func(uint64) (module.Job, error)); ok { - return rf(index) + if returnFunc, ok := ret.Get(0).(func(uint64) (module.Job, error)); ok { + return returnFunc(index) } - if rf, ok := ret.Get(0).(func(uint64) module.Job); ok { - r0 = rf(index) + if returnFunc, ok := ret.Get(0).(func(uint64) module.Job); ok { + r0 = returnFunc(index) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(module.Job) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(index) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(index) } else { r1 = ret.Error(1) } - return r0, r1 } -// Head provides a mock function with no fields -func (_m *Jobs) Head() (uint64, error) { - ret := _m.Called() +// Jobs_AtIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtIndex' +type Jobs_AtIndex_Call struct { + *mock.Call +} + +// AtIndex is a helper method to define mock.On call +// - index uint64 +func (_e *Jobs_Expecter) AtIndex(index interface{}) *Jobs_AtIndex_Call { + return &Jobs_AtIndex_Call{Call: _e.mock.On("AtIndex", index)} +} + +func (_c *Jobs_AtIndex_Call) Run(run func(index uint64)) *Jobs_AtIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Jobs_AtIndex_Call) Return(job module.Job, err error) *Jobs_AtIndex_Call { + _c.Call.Return(job, err) + return _c +} + +func (_c *Jobs_AtIndex_Call) RunAndReturn(run func(index uint64) (module.Job, error)) *Jobs_AtIndex_Call { + _c.Call.Return(run) + return _c +} + +// Head provides a mock function for the type Jobs +func (_mock *Jobs) Head() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Head") @@ -52,34 +108,45 @@ func (_m *Jobs) Head() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewJobs creates a new instance of Jobs. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewJobs(t interface { - mock.TestingT - Cleanup(func()) -}) *Jobs { - mock := &Jobs{} - mock.Mock.Test(t) +// Jobs_Head_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Head' +type Jobs_Head_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Head is a helper method to define mock.On call +func (_e *Jobs_Expecter) Head() *Jobs_Head_Call { + return &Jobs_Head_Call{Call: _e.mock.On("Head")} +} - return mock +func (_c *Jobs_Head_Call) Run(run func()) *Jobs_Head_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Jobs_Head_Call) Return(v uint64, err error) *Jobs_Head_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Jobs_Head_Call) RunAndReturn(run func() (uint64, error)) *Jobs_Head_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/ledger_metrics.go b/module/mock/ledger_metrics.go index e2168fe1b32..4202ef41472 100644 --- a/module/mock/ledger_metrics.go +++ b/module/mock/ledger_metrics.go @@ -1,113 +1,711 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewLedgerMetrics creates a new instance of LedgerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLedgerMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *LedgerMetrics { + mock := &LedgerMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LedgerMetrics is an autogenerated mock type for the LedgerMetrics type type LedgerMetrics struct { mock.Mock } -// ForestApproxMemorySize provides a mock function with given fields: bytes -func (_m *LedgerMetrics) ForestApproxMemorySize(bytes uint64) { - _m.Called(bytes) +type LedgerMetrics_Expecter struct { + mock *mock.Mock } -// ForestNumberOfTrees provides a mock function with given fields: number -func (_m *LedgerMetrics) ForestNumberOfTrees(number uint64) { - _m.Called(number) +func (_m *LedgerMetrics) EXPECT() *LedgerMetrics_Expecter { + return &LedgerMetrics_Expecter{mock: &_m.Mock} } -// LatestTrieMaxDepthTouched provides a mock function with given fields: maxDepth -func (_m *LedgerMetrics) LatestTrieMaxDepthTouched(maxDepth uint16) { - _m.Called(maxDepth) +// ForestApproxMemorySize provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) ForestApproxMemorySize(bytes uint64) { + _mock.Called(bytes) + return } -// LatestTrieRegCount provides a mock function with given fields: number -func (_m *LedgerMetrics) LatestTrieRegCount(number uint64) { - _m.Called(number) +// LedgerMetrics_ForestApproxMemorySize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ForestApproxMemorySize' +type LedgerMetrics_ForestApproxMemorySize_Call struct { + *mock.Call } -// LatestTrieRegCountDiff provides a mock function with given fields: number -func (_m *LedgerMetrics) LatestTrieRegCountDiff(number int64) { - _m.Called(number) +// ForestApproxMemorySize is a helper method to define mock.On call +// - bytes uint64 +func (_e *LedgerMetrics_Expecter) ForestApproxMemorySize(bytes interface{}) *LedgerMetrics_ForestApproxMemorySize_Call { + return &LedgerMetrics_ForestApproxMemorySize_Call{Call: _e.mock.On("ForestApproxMemorySize", bytes)} } -// LatestTrieRegSize provides a mock function with given fields: size -func (_m *LedgerMetrics) LatestTrieRegSize(size uint64) { - _m.Called(size) +func (_c *LedgerMetrics_ForestApproxMemorySize_Call) Run(run func(bytes uint64)) *LedgerMetrics_ForestApproxMemorySize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c } -// LatestTrieRegSizeDiff provides a mock function with given fields: size -func (_m *LedgerMetrics) LatestTrieRegSizeDiff(size int64) { - _m.Called(size) +func (_c *LedgerMetrics_ForestApproxMemorySize_Call) Return() *LedgerMetrics_ForestApproxMemorySize_Call { + _c.Call.Return() + return _c } -// ProofSize provides a mock function with given fields: bytes -func (_m *LedgerMetrics) ProofSize(bytes uint32) { - _m.Called(bytes) +func (_c *LedgerMetrics_ForestApproxMemorySize_Call) RunAndReturn(run func(bytes uint64)) *LedgerMetrics_ForestApproxMemorySize_Call { + _c.Run(run) + return _c } -// ReadDuration provides a mock function with given fields: duration -func (_m *LedgerMetrics) ReadDuration(duration time.Duration) { - _m.Called(duration) +// ForestNumberOfTrees provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) ForestNumberOfTrees(number uint64) { + _mock.Called(number) + return } -// ReadDurationPerItem provides a mock function with given fields: duration -func (_m *LedgerMetrics) ReadDurationPerItem(duration time.Duration) { - _m.Called(duration) +// LedgerMetrics_ForestNumberOfTrees_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ForestNumberOfTrees' +type LedgerMetrics_ForestNumberOfTrees_Call struct { + *mock.Call } -// ReadValuesNumber provides a mock function with given fields: number -func (_m *LedgerMetrics) ReadValuesNumber(number uint64) { - _m.Called(number) +// ForestNumberOfTrees is a helper method to define mock.On call +// - number uint64 +func (_e *LedgerMetrics_Expecter) ForestNumberOfTrees(number interface{}) *LedgerMetrics_ForestNumberOfTrees_Call { + return &LedgerMetrics_ForestNumberOfTrees_Call{Call: _e.mock.On("ForestNumberOfTrees", number)} } -// ReadValuesSize provides a mock function with given fields: byte -func (_m *LedgerMetrics) ReadValuesSize(byte uint64) { - _m.Called(byte) +func (_c *LedgerMetrics_ForestNumberOfTrees_Call) Run(run func(number uint64)) *LedgerMetrics_ForestNumberOfTrees_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c } -// UpdateCount provides a mock function with no fields -func (_m *LedgerMetrics) UpdateCount() { - _m.Called() +func (_c *LedgerMetrics_ForestNumberOfTrees_Call) Return() *LedgerMetrics_ForestNumberOfTrees_Call { + _c.Call.Return() + return _c } -// UpdateDuration provides a mock function with given fields: duration -func (_m *LedgerMetrics) UpdateDuration(duration time.Duration) { - _m.Called(duration) +func (_c *LedgerMetrics_ForestNumberOfTrees_Call) RunAndReturn(run func(number uint64)) *LedgerMetrics_ForestNumberOfTrees_Call { + _c.Run(run) + return _c } -// UpdateDurationPerItem provides a mock function with given fields: duration -func (_m *LedgerMetrics) UpdateDurationPerItem(duration time.Duration) { - _m.Called(duration) +// LatestTrieMaxDepthTouched provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) LatestTrieMaxDepthTouched(maxDepth uint16) { + _mock.Called(maxDepth) + return } -// UpdateValuesNumber provides a mock function with given fields: number -func (_m *LedgerMetrics) UpdateValuesNumber(number uint64) { - _m.Called(number) +// LedgerMetrics_LatestTrieMaxDepthTouched_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieMaxDepthTouched' +type LedgerMetrics_LatestTrieMaxDepthTouched_Call struct { + *mock.Call } -// UpdateValuesSize provides a mock function with given fields: byte -func (_m *LedgerMetrics) UpdateValuesSize(byte uint64) { - _m.Called(byte) +// LatestTrieMaxDepthTouched is a helper method to define mock.On call +// - maxDepth uint16 +func (_e *LedgerMetrics_Expecter) LatestTrieMaxDepthTouched(maxDepth interface{}) *LedgerMetrics_LatestTrieMaxDepthTouched_Call { + return &LedgerMetrics_LatestTrieMaxDepthTouched_Call{Call: _e.mock.On("LatestTrieMaxDepthTouched", maxDepth)} } -// NewLedgerMetrics creates a new instance of LedgerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLedgerMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *LedgerMetrics { - mock := &LedgerMetrics{} - mock.Mock.Test(t) +func (_c *LedgerMetrics_LatestTrieMaxDepthTouched_Call) Run(run func(maxDepth uint16)) *LedgerMetrics_LatestTrieMaxDepthTouched_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint16 + if args[0] != nil { + arg0 = args[0].(uint16) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *LedgerMetrics_LatestTrieMaxDepthTouched_Call) Return() *LedgerMetrics_LatestTrieMaxDepthTouched_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *LedgerMetrics_LatestTrieMaxDepthTouched_Call) RunAndReturn(run func(maxDepth uint16)) *LedgerMetrics_LatestTrieMaxDepthTouched_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegCount provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) LatestTrieRegCount(number uint64) { + _mock.Called(number) + return +} + +// LedgerMetrics_LatestTrieRegCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegCount' +type LedgerMetrics_LatestTrieRegCount_Call struct { + *mock.Call +} + +// LatestTrieRegCount is a helper method to define mock.On call +// - number uint64 +func (_e *LedgerMetrics_Expecter) LatestTrieRegCount(number interface{}) *LedgerMetrics_LatestTrieRegCount_Call { + return &LedgerMetrics_LatestTrieRegCount_Call{Call: _e.mock.On("LatestTrieRegCount", number)} +} + +func (_c *LedgerMetrics_LatestTrieRegCount_Call) Run(run func(number uint64)) *LedgerMetrics_LatestTrieRegCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegCount_Call) Return() *LedgerMetrics_LatestTrieRegCount_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegCount_Call) RunAndReturn(run func(number uint64)) *LedgerMetrics_LatestTrieRegCount_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegCountDiff provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) LatestTrieRegCountDiff(number int64) { + _mock.Called(number) + return +} + +// LedgerMetrics_LatestTrieRegCountDiff_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegCountDiff' +type LedgerMetrics_LatestTrieRegCountDiff_Call struct { + *mock.Call +} + +// LatestTrieRegCountDiff is a helper method to define mock.On call +// - number int64 +func (_e *LedgerMetrics_Expecter) LatestTrieRegCountDiff(number interface{}) *LedgerMetrics_LatestTrieRegCountDiff_Call { + return &LedgerMetrics_LatestTrieRegCountDiff_Call{Call: _e.mock.On("LatestTrieRegCountDiff", number)} +} + +func (_c *LedgerMetrics_LatestTrieRegCountDiff_Call) Run(run func(number int64)) *LedgerMetrics_LatestTrieRegCountDiff_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int64 + if args[0] != nil { + arg0 = args[0].(int64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegCountDiff_Call) Return() *LedgerMetrics_LatestTrieRegCountDiff_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegCountDiff_Call) RunAndReturn(run func(number int64)) *LedgerMetrics_LatestTrieRegCountDiff_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegSize provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) LatestTrieRegSize(size uint64) { + _mock.Called(size) + return +} + +// LedgerMetrics_LatestTrieRegSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegSize' +type LedgerMetrics_LatestTrieRegSize_Call struct { + *mock.Call +} + +// LatestTrieRegSize is a helper method to define mock.On call +// - size uint64 +func (_e *LedgerMetrics_Expecter) LatestTrieRegSize(size interface{}) *LedgerMetrics_LatestTrieRegSize_Call { + return &LedgerMetrics_LatestTrieRegSize_Call{Call: _e.mock.On("LatestTrieRegSize", size)} +} + +func (_c *LedgerMetrics_LatestTrieRegSize_Call) Run(run func(size uint64)) *LedgerMetrics_LatestTrieRegSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegSize_Call) Return() *LedgerMetrics_LatestTrieRegSize_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegSize_Call) RunAndReturn(run func(size uint64)) *LedgerMetrics_LatestTrieRegSize_Call { + _c.Run(run) + return _c +} + +// LatestTrieRegSizeDiff provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) LatestTrieRegSizeDiff(size int64) { + _mock.Called(size) + return +} + +// LedgerMetrics_LatestTrieRegSizeDiff_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestTrieRegSizeDiff' +type LedgerMetrics_LatestTrieRegSizeDiff_Call struct { + *mock.Call +} + +// LatestTrieRegSizeDiff is a helper method to define mock.On call +// - size int64 +func (_e *LedgerMetrics_Expecter) LatestTrieRegSizeDiff(size interface{}) *LedgerMetrics_LatestTrieRegSizeDiff_Call { + return &LedgerMetrics_LatestTrieRegSizeDiff_Call{Call: _e.mock.On("LatestTrieRegSizeDiff", size)} +} + +func (_c *LedgerMetrics_LatestTrieRegSizeDiff_Call) Run(run func(size int64)) *LedgerMetrics_LatestTrieRegSizeDiff_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int64 + if args[0] != nil { + arg0 = args[0].(int64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegSizeDiff_Call) Return() *LedgerMetrics_LatestTrieRegSizeDiff_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_LatestTrieRegSizeDiff_Call) RunAndReturn(run func(size int64)) *LedgerMetrics_LatestTrieRegSizeDiff_Call { + _c.Run(run) + return _c +} + +// ProofSize provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) ProofSize(bytes uint32) { + _mock.Called(bytes) + return +} + +// LedgerMetrics_ProofSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProofSize' +type LedgerMetrics_ProofSize_Call struct { + *mock.Call +} + +// ProofSize is a helper method to define mock.On call +// - bytes uint32 +func (_e *LedgerMetrics_Expecter) ProofSize(bytes interface{}) *LedgerMetrics_ProofSize_Call { + return &LedgerMetrics_ProofSize_Call{Call: _e.mock.On("ProofSize", bytes)} +} + +func (_c *LedgerMetrics_ProofSize_Call) Run(run func(bytes uint32)) *LedgerMetrics_ProofSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint32 + if args[0] != nil { + arg0 = args[0].(uint32) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_ProofSize_Call) Return() *LedgerMetrics_ProofSize_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_ProofSize_Call) RunAndReturn(run func(bytes uint32)) *LedgerMetrics_ProofSize_Call { + _c.Run(run) + return _c +} + +// ReadDuration provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) ReadDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// LedgerMetrics_ReadDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadDuration' +type LedgerMetrics_ReadDuration_Call struct { + *mock.Call +} + +// ReadDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *LedgerMetrics_Expecter) ReadDuration(duration interface{}) *LedgerMetrics_ReadDuration_Call { + return &LedgerMetrics_ReadDuration_Call{Call: _e.mock.On("ReadDuration", duration)} +} + +func (_c *LedgerMetrics_ReadDuration_Call) Run(run func(duration time.Duration)) *LedgerMetrics_ReadDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_ReadDuration_Call) Return() *LedgerMetrics_ReadDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_ReadDuration_Call) RunAndReturn(run func(duration time.Duration)) *LedgerMetrics_ReadDuration_Call { + _c.Run(run) + return _c +} + +// ReadDurationPerItem provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) ReadDurationPerItem(duration time.Duration) { + _mock.Called(duration) + return +} + +// LedgerMetrics_ReadDurationPerItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadDurationPerItem' +type LedgerMetrics_ReadDurationPerItem_Call struct { + *mock.Call +} + +// ReadDurationPerItem is a helper method to define mock.On call +// - duration time.Duration +func (_e *LedgerMetrics_Expecter) ReadDurationPerItem(duration interface{}) *LedgerMetrics_ReadDurationPerItem_Call { + return &LedgerMetrics_ReadDurationPerItem_Call{Call: _e.mock.On("ReadDurationPerItem", duration)} +} + +func (_c *LedgerMetrics_ReadDurationPerItem_Call) Run(run func(duration time.Duration)) *LedgerMetrics_ReadDurationPerItem_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_ReadDurationPerItem_Call) Return() *LedgerMetrics_ReadDurationPerItem_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_ReadDurationPerItem_Call) RunAndReturn(run func(duration time.Duration)) *LedgerMetrics_ReadDurationPerItem_Call { + _c.Run(run) + return _c +} + +// ReadValuesNumber provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) ReadValuesNumber(number uint64) { + _mock.Called(number) + return +} + +// LedgerMetrics_ReadValuesNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadValuesNumber' +type LedgerMetrics_ReadValuesNumber_Call struct { + *mock.Call +} + +// ReadValuesNumber is a helper method to define mock.On call +// - number uint64 +func (_e *LedgerMetrics_Expecter) ReadValuesNumber(number interface{}) *LedgerMetrics_ReadValuesNumber_Call { + return &LedgerMetrics_ReadValuesNumber_Call{Call: _e.mock.On("ReadValuesNumber", number)} +} + +func (_c *LedgerMetrics_ReadValuesNumber_Call) Run(run func(number uint64)) *LedgerMetrics_ReadValuesNumber_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_ReadValuesNumber_Call) Return() *LedgerMetrics_ReadValuesNumber_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_ReadValuesNumber_Call) RunAndReturn(run func(number uint64)) *LedgerMetrics_ReadValuesNumber_Call { + _c.Run(run) + return _c +} + +// ReadValuesSize provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) ReadValuesSize(byte uint64) { + _mock.Called(byte) + return +} + +// LedgerMetrics_ReadValuesSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadValuesSize' +type LedgerMetrics_ReadValuesSize_Call struct { + *mock.Call +} + +// ReadValuesSize is a helper method to define mock.On call +// - byte uint64 +func (_e *LedgerMetrics_Expecter) ReadValuesSize(byte interface{}) *LedgerMetrics_ReadValuesSize_Call { + return &LedgerMetrics_ReadValuesSize_Call{Call: _e.mock.On("ReadValuesSize", byte)} +} + +func (_c *LedgerMetrics_ReadValuesSize_Call) Run(run func(byte uint64)) *LedgerMetrics_ReadValuesSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_ReadValuesSize_Call) Return() *LedgerMetrics_ReadValuesSize_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_ReadValuesSize_Call) RunAndReturn(run func(byte uint64)) *LedgerMetrics_ReadValuesSize_Call { + _c.Run(run) + return _c +} + +// UpdateCount provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) UpdateCount() { + _mock.Called() + return +} + +// LedgerMetrics_UpdateCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateCount' +type LedgerMetrics_UpdateCount_Call struct { + *mock.Call +} + +// UpdateCount is a helper method to define mock.On call +func (_e *LedgerMetrics_Expecter) UpdateCount() *LedgerMetrics_UpdateCount_Call { + return &LedgerMetrics_UpdateCount_Call{Call: _e.mock.On("UpdateCount")} +} + +func (_c *LedgerMetrics_UpdateCount_Call) Run(run func()) *LedgerMetrics_UpdateCount_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LedgerMetrics_UpdateCount_Call) Return() *LedgerMetrics_UpdateCount_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_UpdateCount_Call) RunAndReturn(run func()) *LedgerMetrics_UpdateCount_Call { + _c.Run(run) + return _c +} + +// UpdateDuration provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) UpdateDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// LedgerMetrics_UpdateDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateDuration' +type LedgerMetrics_UpdateDuration_Call struct { + *mock.Call +} + +// UpdateDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *LedgerMetrics_Expecter) UpdateDuration(duration interface{}) *LedgerMetrics_UpdateDuration_Call { + return &LedgerMetrics_UpdateDuration_Call{Call: _e.mock.On("UpdateDuration", duration)} +} + +func (_c *LedgerMetrics_UpdateDuration_Call) Run(run func(duration time.Duration)) *LedgerMetrics_UpdateDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_UpdateDuration_Call) Return() *LedgerMetrics_UpdateDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_UpdateDuration_Call) RunAndReturn(run func(duration time.Duration)) *LedgerMetrics_UpdateDuration_Call { + _c.Run(run) + return _c +} + +// UpdateDurationPerItem provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) UpdateDurationPerItem(duration time.Duration) { + _mock.Called(duration) + return +} + +// LedgerMetrics_UpdateDurationPerItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateDurationPerItem' +type LedgerMetrics_UpdateDurationPerItem_Call struct { + *mock.Call +} + +// UpdateDurationPerItem is a helper method to define mock.On call +// - duration time.Duration +func (_e *LedgerMetrics_Expecter) UpdateDurationPerItem(duration interface{}) *LedgerMetrics_UpdateDurationPerItem_Call { + return &LedgerMetrics_UpdateDurationPerItem_Call{Call: _e.mock.On("UpdateDurationPerItem", duration)} +} + +func (_c *LedgerMetrics_UpdateDurationPerItem_Call) Run(run func(duration time.Duration)) *LedgerMetrics_UpdateDurationPerItem_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_UpdateDurationPerItem_Call) Return() *LedgerMetrics_UpdateDurationPerItem_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_UpdateDurationPerItem_Call) RunAndReturn(run func(duration time.Duration)) *LedgerMetrics_UpdateDurationPerItem_Call { + _c.Run(run) + return _c +} + +// UpdateValuesNumber provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) UpdateValuesNumber(number uint64) { + _mock.Called(number) + return +} + +// LedgerMetrics_UpdateValuesNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateValuesNumber' +type LedgerMetrics_UpdateValuesNumber_Call struct { + *mock.Call +} + +// UpdateValuesNumber is a helper method to define mock.On call +// - number uint64 +func (_e *LedgerMetrics_Expecter) UpdateValuesNumber(number interface{}) *LedgerMetrics_UpdateValuesNumber_Call { + return &LedgerMetrics_UpdateValuesNumber_Call{Call: _e.mock.On("UpdateValuesNumber", number)} +} + +func (_c *LedgerMetrics_UpdateValuesNumber_Call) Run(run func(number uint64)) *LedgerMetrics_UpdateValuesNumber_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_UpdateValuesNumber_Call) Return() *LedgerMetrics_UpdateValuesNumber_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_UpdateValuesNumber_Call) RunAndReturn(run func(number uint64)) *LedgerMetrics_UpdateValuesNumber_Call { + _c.Run(run) + return _c +} + +// UpdateValuesSize provides a mock function for the type LedgerMetrics +func (_mock *LedgerMetrics) UpdateValuesSize(byte uint64) { + _mock.Called(byte) + return +} + +// LedgerMetrics_UpdateValuesSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateValuesSize' +type LedgerMetrics_UpdateValuesSize_Call struct { + *mock.Call +} + +// UpdateValuesSize is a helper method to define mock.On call +// - byte uint64 +func (_e *LedgerMetrics_Expecter) UpdateValuesSize(byte interface{}) *LedgerMetrics_UpdateValuesSize_Call { + return &LedgerMetrics_UpdateValuesSize_Call{Call: _e.mock.On("UpdateValuesSize", byte)} +} + +func (_c *LedgerMetrics_UpdateValuesSize_Call) Run(run func(byte uint64)) *LedgerMetrics_UpdateValuesSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LedgerMetrics_UpdateValuesSize_Call) Return() *LedgerMetrics_UpdateValuesSize_Call { + _c.Call.Return() + return _c +} + +func (_c *LedgerMetrics_UpdateValuesSize_Call) RunAndReturn(run func(byte uint64)) *LedgerMetrics_UpdateValuesSize_Call { + _c.Run(run) + return _c } diff --git a/module/mock/lib_p2_p_connection_metrics.go b/module/mock/lib_p2_p_connection_metrics.go index 81baeeae880..f638f9a2042 100644 --- a/module/mock/lib_p2_p_connection_metrics.go +++ b/module/mock/lib_p2_p_connection_metrics.go @@ -1,23 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// LibP2PConnectionMetrics is an autogenerated mock type for the LibP2PConnectionMetrics type -type LibP2PConnectionMetrics struct { - mock.Mock -} - -// InboundConnections provides a mock function with given fields: connectionCount -func (_m *LibP2PConnectionMetrics) InboundConnections(connectionCount uint) { - _m.Called(connectionCount) -} - -// OutboundConnections provides a mock function with given fields: connectionCount -func (_m *LibP2PConnectionMetrics) OutboundConnections(connectionCount uint) { - _m.Called(connectionCount) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewLibP2PConnectionMetrics creates a new instance of LibP2PConnectionMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -32,3 +21,96 @@ func NewLibP2PConnectionMetrics(t interface { return mock } + +// LibP2PConnectionMetrics is an autogenerated mock type for the LibP2PConnectionMetrics type +type LibP2PConnectionMetrics struct { + mock.Mock +} + +type LibP2PConnectionMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *LibP2PConnectionMetrics) EXPECT() *LibP2PConnectionMetrics_Expecter { + return &LibP2PConnectionMetrics_Expecter{mock: &_m.Mock} +} + +// InboundConnections provides a mock function for the type LibP2PConnectionMetrics +func (_mock *LibP2PConnectionMetrics) InboundConnections(connectionCount uint) { + _mock.Called(connectionCount) + return +} + +// LibP2PConnectionMetrics_InboundConnections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InboundConnections' +type LibP2PConnectionMetrics_InboundConnections_Call struct { + *mock.Call +} + +// InboundConnections is a helper method to define mock.On call +// - connectionCount uint +func (_e *LibP2PConnectionMetrics_Expecter) InboundConnections(connectionCount interface{}) *LibP2PConnectionMetrics_InboundConnections_Call { + return &LibP2PConnectionMetrics_InboundConnections_Call{Call: _e.mock.On("InboundConnections", connectionCount)} +} + +func (_c *LibP2PConnectionMetrics_InboundConnections_Call) Run(run func(connectionCount uint)) *LibP2PConnectionMetrics_InboundConnections_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PConnectionMetrics_InboundConnections_Call) Return() *LibP2PConnectionMetrics_InboundConnections_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PConnectionMetrics_InboundConnections_Call) RunAndReturn(run func(connectionCount uint)) *LibP2PConnectionMetrics_InboundConnections_Call { + _c.Run(run) + return _c +} + +// OutboundConnections provides a mock function for the type LibP2PConnectionMetrics +func (_mock *LibP2PConnectionMetrics) OutboundConnections(connectionCount uint) { + _mock.Called(connectionCount) + return +} + +// LibP2PConnectionMetrics_OutboundConnections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OutboundConnections' +type LibP2PConnectionMetrics_OutboundConnections_Call struct { + *mock.Call +} + +// OutboundConnections is a helper method to define mock.On call +// - connectionCount uint +func (_e *LibP2PConnectionMetrics_Expecter) OutboundConnections(connectionCount interface{}) *LibP2PConnectionMetrics_OutboundConnections_Call { + return &LibP2PConnectionMetrics_OutboundConnections_Call{Call: _e.mock.On("OutboundConnections", connectionCount)} +} + +func (_c *LibP2PConnectionMetrics_OutboundConnections_Call) Run(run func(connectionCount uint)) *LibP2PConnectionMetrics_OutboundConnections_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PConnectionMetrics_OutboundConnections_Call) Return() *LibP2PConnectionMetrics_OutboundConnections_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PConnectionMetrics_OutboundConnections_Call) RunAndReturn(run func(connectionCount uint)) *LibP2PConnectionMetrics_OutboundConnections_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/lib_p2_p_metrics.go b/module/mock/lib_p2_p_metrics.go index 7526b312810..8b26953b35b 100644 --- a/module/mock/lib_p2_p_metrics.go +++ b/module/mock/lib_p2_p_metrics.go @@ -1,477 +1,3600 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" - mock "github.com/stretchr/testify/mock" - - network "github.com/libp2p/go-libp2p/core/network" + "time" - p2pmsg "github.com/onflow/flow-go/network/p2p/message" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p/message" + mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewLibP2PMetrics creates a new instance of LibP2PMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLibP2PMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *LibP2PMetrics { + mock := &LibP2PMetrics{} + mock.Mock.Test(t) - protocol "github.com/libp2p/go-libp2p/core/protocol" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // LibP2PMetrics is an autogenerated mock type for the LibP2PMetrics type type LibP2PMetrics struct { mock.Mock } -// AllowConn provides a mock function with given fields: dir, usefd -func (_m *LibP2PMetrics) AllowConn(dir network.Direction, usefd bool) { - _m.Called(dir, usefd) +type LibP2PMetrics_Expecter struct { + mock *mock.Mock } -// AllowMemory provides a mock function with given fields: size -func (_m *LibP2PMetrics) AllowMemory(size int) { - _m.Called(size) +func (_m *LibP2PMetrics) EXPECT() *LibP2PMetrics_Expecter { + return &LibP2PMetrics_Expecter{mock: &_m.Mock} } -// AllowPeer provides a mock function with given fields: p -func (_m *LibP2PMetrics) AllowPeer(p peer.ID) { - _m.Called(p) +// AllowConn provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AllowConn(dir network.Direction, usefd bool) { + _mock.Called(dir, usefd) + return } -// AllowProtocol provides a mock function with given fields: proto -func (_m *LibP2PMetrics) AllowProtocol(proto protocol.ID) { - _m.Called(proto) +// LibP2PMetrics_AllowConn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowConn' +type LibP2PMetrics_AllowConn_Call struct { + *mock.Call } -// AllowService provides a mock function with given fields: svc -func (_m *LibP2PMetrics) AllowService(svc string) { - _m.Called(svc) +// AllowConn is a helper method to define mock.On call +// - dir network.Direction +// - usefd bool +func (_e *LibP2PMetrics_Expecter) AllowConn(dir interface{}, usefd interface{}) *LibP2PMetrics_AllowConn_Call { + return &LibP2PMetrics_AllowConn_Call{Call: _e.mock.On("AllowConn", dir, usefd)} } -// AllowStream provides a mock function with given fields: p, dir -func (_m *LibP2PMetrics) AllowStream(p peer.ID, dir network.Direction) { - _m.Called(p, dir) +func (_c *LibP2PMetrics_AllowConn_Call) Run(run func(dir network.Direction, usefd bool)) *LibP2PMetrics_AllowConn_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.Direction + if args[0] != nil { + arg0 = args[0].(network.Direction) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c } -// AsyncProcessingFinished provides a mock function with given fields: duration -func (_m *LibP2PMetrics) AsyncProcessingFinished(duration time.Duration) { - _m.Called(duration) +func (_c *LibP2PMetrics_AllowConn_Call) Return() *LibP2PMetrics_AllowConn_Call { + _c.Call.Return() + return _c } -// AsyncProcessingStarted provides a mock function with no fields -func (_m *LibP2PMetrics) AsyncProcessingStarted() { - _m.Called() +func (_c *LibP2PMetrics_AllowConn_Call) RunAndReturn(run func(dir network.Direction, usefd bool)) *LibP2PMetrics_AllowConn_Call { + _c.Run(run) + return _c } -// BlockConn provides a mock function with given fields: dir, usefd -func (_m *LibP2PMetrics) BlockConn(dir network.Direction, usefd bool) { - _m.Called(dir, usefd) +// AllowMemory provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AllowMemory(size int) { + _mock.Called(size) + return } -// BlockMemory provides a mock function with given fields: size -func (_m *LibP2PMetrics) BlockMemory(size int) { - _m.Called(size) +// LibP2PMetrics_AllowMemory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowMemory' +type LibP2PMetrics_AllowMemory_Call struct { + *mock.Call } -// BlockPeer provides a mock function with given fields: p -func (_m *LibP2PMetrics) BlockPeer(p peer.ID) { - _m.Called(p) +// AllowMemory is a helper method to define mock.On call +// - size int +func (_e *LibP2PMetrics_Expecter) AllowMemory(size interface{}) *LibP2PMetrics_AllowMemory_Call { + return &LibP2PMetrics_AllowMemory_Call{Call: _e.mock.On("AllowMemory", size)} } -// BlockProtocol provides a mock function with given fields: proto -func (_m *LibP2PMetrics) BlockProtocol(proto protocol.ID) { - _m.Called(proto) +func (_c *LibP2PMetrics_AllowMemory_Call) Run(run func(size int)) *LibP2PMetrics_AllowMemory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c } -// BlockProtocolPeer provides a mock function with given fields: proto, p -func (_m *LibP2PMetrics) BlockProtocolPeer(proto protocol.ID, p peer.ID) { - _m.Called(proto, p) +func (_c *LibP2PMetrics_AllowMemory_Call) Return() *LibP2PMetrics_AllowMemory_Call { + _c.Call.Return() + return _c } -// BlockService provides a mock function with given fields: svc -func (_m *LibP2PMetrics) BlockService(svc string) { - _m.Called(svc) +func (_c *LibP2PMetrics_AllowMemory_Call) RunAndReturn(run func(size int)) *LibP2PMetrics_AllowMemory_Call { + _c.Run(run) + return _c } -// BlockServicePeer provides a mock function with given fields: svc, p -func (_m *LibP2PMetrics) BlockServicePeer(svc string, p peer.ID) { - _m.Called(svc, p) +// AllowPeer provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AllowPeer(p peer.ID) { + _mock.Called(p) + return } -// BlockStream provides a mock function with given fields: p, dir -func (_m *LibP2PMetrics) BlockStream(p peer.ID, dir network.Direction) { - _m.Called(p, dir) +// LibP2PMetrics_AllowPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowPeer' +type LibP2PMetrics_AllowPeer_Call struct { + *mock.Call } -// DNSLookupDuration provides a mock function with given fields: duration -func (_m *LibP2PMetrics) DNSLookupDuration(duration time.Duration) { - _m.Called(duration) +// AllowPeer is a helper method to define mock.On call +// - p peer.ID +func (_e *LibP2PMetrics_Expecter) AllowPeer(p interface{}) *LibP2PMetrics_AllowPeer_Call { + return &LibP2PMetrics_AllowPeer_Call{Call: _e.mock.On("AllowPeer", p)} } -// DuplicateMessagePenalties provides a mock function with given fields: penalty -func (_m *LibP2PMetrics) DuplicateMessagePenalties(penalty float64) { - _m.Called(penalty) +func (_c *LibP2PMetrics_AllowPeer_Call) Run(run func(p peer.ID)) *LibP2PMetrics_AllowPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c } -// DuplicateMessagesCounts provides a mock function with given fields: count -func (_m *LibP2PMetrics) DuplicateMessagesCounts(count float64) { - _m.Called(count) +func (_c *LibP2PMetrics_AllowPeer_Call) Return() *LibP2PMetrics_AllowPeer_Call { + _c.Call.Return() + return _c } -// InboundConnections provides a mock function with given fields: connectionCount -func (_m *LibP2PMetrics) InboundConnections(connectionCount uint) { - _m.Called(connectionCount) +func (_c *LibP2PMetrics_AllowPeer_Call) RunAndReturn(run func(p peer.ID)) *LibP2PMetrics_AllowPeer_Call { + _c.Run(run) + return _c } -// OnActiveClusterIDsNotSetErr provides a mock function with no fields -func (_m *LibP2PMetrics) OnActiveClusterIDsNotSetErr() { - _m.Called() +// AllowProtocol provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AllowProtocol(proto protocol.ID) { + _mock.Called(proto) + return } -// OnAppSpecificScoreUpdated provides a mock function with given fields: _a0 -func (_m *LibP2PMetrics) OnAppSpecificScoreUpdated(_a0 float64) { - _m.Called(_a0) +// LibP2PMetrics_AllowProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowProtocol' +type LibP2PMetrics_AllowProtocol_Call struct { + *mock.Call } -// OnBehaviourPenaltyUpdated provides a mock function with given fields: _a0 -func (_m *LibP2PMetrics) OnBehaviourPenaltyUpdated(_a0 float64) { - _m.Called(_a0) +// AllowProtocol is a helper method to define mock.On call +// - proto protocol.ID +func (_e *LibP2PMetrics_Expecter) AllowProtocol(proto interface{}) *LibP2PMetrics_AllowProtocol_Call { + return &LibP2PMetrics_AllowProtocol_Call{Call: _e.mock.On("AllowProtocol", proto)} } -// OnControlMessagesTruncated provides a mock function with given fields: messageType, diff -func (_m *LibP2PMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { - _m.Called(messageType, diff) +func (_c *LibP2PMetrics_AllowProtocol_Call) Run(run func(proto protocol.ID)) *LibP2PMetrics_AllowProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + run( + arg0, + ) + }) + return _c } -// OnDNSCacheHit provides a mock function with no fields -func (_m *LibP2PMetrics) OnDNSCacheHit() { - _m.Called() +func (_c *LibP2PMetrics_AllowProtocol_Call) Return() *LibP2PMetrics_AllowProtocol_Call { + _c.Call.Return() + return _c } -// OnDNSCacheInvalidated provides a mock function with no fields -func (_m *LibP2PMetrics) OnDNSCacheInvalidated() { - _m.Called() +func (_c *LibP2PMetrics_AllowProtocol_Call) RunAndReturn(run func(proto protocol.ID)) *LibP2PMetrics_AllowProtocol_Call { + _c.Run(run) + return _c } -// OnDNSCacheMiss provides a mock function with no fields -func (_m *LibP2PMetrics) OnDNSCacheMiss() { - _m.Called() +// AllowService provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AllowService(svc string) { + _mock.Called(svc) + return } -// OnDNSLookupRequestDropped provides a mock function with no fields -func (_m *LibP2PMetrics) OnDNSLookupRequestDropped() { - _m.Called() +// LibP2PMetrics_AllowService_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowService' +type LibP2PMetrics_AllowService_Call struct { + *mock.Call } -// OnDialRetryBudgetResetToDefault provides a mock function with no fields -func (_m *LibP2PMetrics) OnDialRetryBudgetResetToDefault() { - _m.Called() +// AllowService is a helper method to define mock.On call +// - svc string +func (_e *LibP2PMetrics_Expecter) AllowService(svc interface{}) *LibP2PMetrics_AllowService_Call { + return &LibP2PMetrics_AllowService_Call{Call: _e.mock.On("AllowService", svc)} } -// OnDialRetryBudgetUpdated provides a mock function with given fields: budget -func (_m *LibP2PMetrics) OnDialRetryBudgetUpdated(budget uint64) { - _m.Called(budget) +func (_c *LibP2PMetrics_AllowService_Call) Run(run func(svc string)) *LibP2PMetrics_AllowService_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c } -// OnEstablishStreamFailure provides a mock function with given fields: duration, attempts -func (_m *LibP2PMetrics) OnEstablishStreamFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +func (_c *LibP2PMetrics_AllowService_Call) Return() *LibP2PMetrics_AllowService_Call { + _c.Call.Return() + return _c } -// OnFirstMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *LibP2PMetrics) OnFirstMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *LibP2PMetrics_AllowService_Call) RunAndReturn(run func(svc string)) *LibP2PMetrics_AllowService_Call { + _c.Run(run) + return _c } -// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { - _m.Called() +// AllowStream provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AllowStream(p peer.ID, dir network.Direction) { + _mock.Called(p, dir) + return } -// OnGraftInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnGraftInvalidTopicIdsExceedThreshold() { - _m.Called() +// LibP2PMetrics_AllowStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowStream' +type LibP2PMetrics_AllowStream_Call struct { + *mock.Call } -// OnGraftMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *LibP2PMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +// AllowStream is a helper method to define mock.On call +// - p peer.ID +// - dir network.Direction +func (_e *LibP2PMetrics_Expecter) AllowStream(p interface{}, dir interface{}) *LibP2PMetrics_AllowStream_Call { + return &LibP2PMetrics_AllowStream_Call{Call: _e.mock.On("AllowStream", p, dir)} } -// OnIHaveControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *LibP2PMetrics) OnIHaveControlMessageIdsTruncated(diff int) { - _m.Called(diff) +func (_c *LibP2PMetrics_AllowStream_Call) Run(run func(p peer.ID, dir network.Direction)) *LibP2PMetrics_AllowStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.Direction + if args[1] != nil { + arg1 = args[1].(network.Direction) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { - _m.Called() +func (_c *LibP2PMetrics_AllowStream_Call) Return() *LibP2PMetrics_AllowStream_Call { + _c.Call.Return() + return _c } -// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { - _m.Called() +func (_c *LibP2PMetrics_AllowStream_Call) RunAndReturn(run func(p peer.ID, dir network.Direction)) *LibP2PMetrics_AllowStream_Call { + _c.Run(run) + return _c } -// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { - _m.Called() +// AsyncProcessingFinished provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AsyncProcessingFinished(duration time.Duration) { + _mock.Called(duration) + return } -// OnIHaveMessageIDsReceived provides a mock function with given fields: channel, msgIdCount -func (_m *LibP2PMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { - _m.Called(channel, msgIdCount) +// LibP2PMetrics_AsyncProcessingFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingFinished' +type LibP2PMetrics_AsyncProcessingFinished_Call struct { + *mock.Call } -// OnIHaveMessagesInspected provides a mock function with given fields: duplicateTopicIds, duplicateMessageIds, invalidTopicIds -func (_m *LibP2PMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) +// AsyncProcessingFinished is a helper method to define mock.On call +// - duration time.Duration +func (_e *LibP2PMetrics_Expecter) AsyncProcessingFinished(duration interface{}) *LibP2PMetrics_AsyncProcessingFinished_Call { + return &LibP2PMetrics_AsyncProcessingFinished_Call{Call: _e.mock.On("AsyncProcessingFinished", duration)} } -// OnIPColocationFactorUpdated provides a mock function with given fields: _a0 -func (_m *LibP2PMetrics) OnIPColocationFactorUpdated(_a0 float64) { - _m.Called(_a0) +func (_c *LibP2PMetrics_AsyncProcessingFinished_Call) Run(run func(duration time.Duration)) *LibP2PMetrics_AsyncProcessingFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { - _m.Called() +func (_c *LibP2PMetrics_AsyncProcessingFinished_Call) Return() *LibP2PMetrics_AsyncProcessingFinished_Call { + _c.Call.Return() + return _c } -// OnIWantControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *LibP2PMetrics) OnIWantControlMessageIdsTruncated(diff int) { - _m.Called(diff) +func (_c *LibP2PMetrics_AsyncProcessingFinished_Call) RunAndReturn(run func(duration time.Duration)) *LibP2PMetrics_AsyncProcessingFinished_Call { + _c.Run(run) + return _c } -// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { - _m.Called() +// AsyncProcessingStarted provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) AsyncProcessingStarted() { + _mock.Called() + return } -// OnIWantMessageIDsReceived provides a mock function with given fields: msgIdCount -func (_m *LibP2PMetrics) OnIWantMessageIDsReceived(msgIdCount int) { - _m.Called(msgIdCount) +// LibP2PMetrics_AsyncProcessingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingStarted' +type LibP2PMetrics_AsyncProcessingStarted_Call struct { + *mock.Call } -// OnIWantMessagesInspected provides a mock function with given fields: duplicateCount, cacheMissCount -func (_m *LibP2PMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { - _m.Called(duplicateCount, cacheMissCount) +// AsyncProcessingStarted is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) AsyncProcessingStarted() *LibP2PMetrics_AsyncProcessingStarted_Call { + return &LibP2PMetrics_AsyncProcessingStarted_Call{Call: _e.mock.On("AsyncProcessingStarted")} } -// OnIncomingRpcReceived provides a mock function with given fields: iHaveCount, iWantCount, graftCount, pruneCount, msgCount -func (_m *LibP2PMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { - _m.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) +func (_c *LibP2PMetrics_AsyncProcessingStarted_Call) Run(run func()) *LibP2PMetrics_AsyncProcessingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnInvalidControlMessageNotificationSent provides a mock function with no fields -func (_m *LibP2PMetrics) OnInvalidControlMessageNotificationSent() { - _m.Called() +func (_c *LibP2PMetrics_AsyncProcessingStarted_Call) Return() *LibP2PMetrics_AsyncProcessingStarted_Call { + _c.Call.Return() + return _c } -// OnInvalidMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *LibP2PMetrics) OnInvalidMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *LibP2PMetrics_AsyncProcessingStarted_Call) RunAndReturn(run func()) *LibP2PMetrics_AsyncProcessingStarted_Call { + _c.Run(run) + return _c } -// OnInvalidTopicIdDetectedForControlMessage provides a mock function with given fields: messageType -func (_m *LibP2PMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { - _m.Called(messageType) +// BlockConn provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockConn(dir network.Direction, usefd bool) { + _mock.Called(dir, usefd) + return } -// OnLocalMeshSizeUpdated provides a mock function with given fields: topic, size -func (_m *LibP2PMetrics) OnLocalMeshSizeUpdated(topic string, size int) { - _m.Called(topic, size) +// LibP2PMetrics_BlockConn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockConn' +type LibP2PMetrics_BlockConn_Call struct { + *mock.Call } -// OnLocalPeerJoinedTopic provides a mock function with no fields -func (_m *LibP2PMetrics) OnLocalPeerJoinedTopic() { - _m.Called() +// BlockConn is a helper method to define mock.On call +// - dir network.Direction +// - usefd bool +func (_e *LibP2PMetrics_Expecter) BlockConn(dir interface{}, usefd interface{}) *LibP2PMetrics_BlockConn_Call { + return &LibP2PMetrics_BlockConn_Call{Call: _e.mock.On("BlockConn", dir, usefd)} } -// OnLocalPeerLeftTopic provides a mock function with no fields -func (_m *LibP2PMetrics) OnLocalPeerLeftTopic() { - _m.Called() +func (_c *LibP2PMetrics_BlockConn_Call) Run(run func(dir network.Direction, usefd bool)) *LibP2PMetrics_BlockConn_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.Direction + if args[0] != nil { + arg0 = args[0].(network.Direction) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnMeshMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *LibP2PMetrics) OnMeshMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *LibP2PMetrics_BlockConn_Call) Return() *LibP2PMetrics_BlockConn_Call { + _c.Call.Return() + return _c } -// OnMessageDeliveredToAllSubscribers provides a mock function with given fields: size -func (_m *LibP2PMetrics) OnMessageDeliveredToAllSubscribers(size int) { - _m.Called(size) +func (_c *LibP2PMetrics_BlockConn_Call) RunAndReturn(run func(dir network.Direction, usefd bool)) *LibP2PMetrics_BlockConn_Call { + _c.Run(run) + return _c } -// OnMessageDuplicate provides a mock function with given fields: size -func (_m *LibP2PMetrics) OnMessageDuplicate(size int) { - _m.Called(size) +// BlockMemory provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockMemory(size int) { + _mock.Called(size) + return } -// OnMessageEnteredValidation provides a mock function with given fields: size -func (_m *LibP2PMetrics) OnMessageEnteredValidation(size int) { - _m.Called(size) +// LibP2PMetrics_BlockMemory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockMemory' +type LibP2PMetrics_BlockMemory_Call struct { + *mock.Call } -// OnMessageRejected provides a mock function with given fields: size, reason -func (_m *LibP2PMetrics) OnMessageRejected(size int, reason string) { - _m.Called(size, reason) +// BlockMemory is a helper method to define mock.On call +// - size int +func (_e *LibP2PMetrics_Expecter) BlockMemory(size interface{}) *LibP2PMetrics_BlockMemory_Call { + return &LibP2PMetrics_BlockMemory_Call{Call: _e.mock.On("BlockMemory", size)} } -// OnOutboundRpcDropped provides a mock function with no fields -func (_m *LibP2PMetrics) OnOutboundRpcDropped() { - _m.Called() +func (_c *LibP2PMetrics_BlockMemory_Call) Run(run func(size int)) *LibP2PMetrics_BlockMemory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c } -// OnOverallPeerScoreUpdated provides a mock function with given fields: _a0 -func (_m *LibP2PMetrics) OnOverallPeerScoreUpdated(_a0 float64) { - _m.Called(_a0) +func (_c *LibP2PMetrics_BlockMemory_Call) Return() *LibP2PMetrics_BlockMemory_Call { + _c.Call.Return() + return _c } -// OnPeerAddedToProtocol provides a mock function with given fields: _a0 -func (_m *LibP2PMetrics) OnPeerAddedToProtocol(_a0 string) { - _m.Called(_a0) +func (_c *LibP2PMetrics_BlockMemory_Call) RunAndReturn(run func(size int)) *LibP2PMetrics_BlockMemory_Call { + _c.Run(run) + return _c } -// OnPeerDialFailure provides a mock function with given fields: duration, attempts -func (_m *LibP2PMetrics) OnPeerDialFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// BlockPeer provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockPeer(p peer.ID) { + _mock.Called(p) + return } -// OnPeerDialed provides a mock function with given fields: duration, attempts -func (_m *LibP2PMetrics) OnPeerDialed(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// LibP2PMetrics_BlockPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockPeer' +type LibP2PMetrics_BlockPeer_Call struct { + *mock.Call } -// OnPeerGraftTopic provides a mock function with given fields: topic -func (_m *LibP2PMetrics) OnPeerGraftTopic(topic string) { - _m.Called(topic) +// BlockPeer is a helper method to define mock.On call +// - p peer.ID +func (_e *LibP2PMetrics_Expecter) BlockPeer(p interface{}) *LibP2PMetrics_BlockPeer_Call { + return &LibP2PMetrics_BlockPeer_Call{Call: _e.mock.On("BlockPeer", p)} } -// OnPeerPruneTopic provides a mock function with given fields: topic -func (_m *LibP2PMetrics) OnPeerPruneTopic(topic string) { - _m.Called(topic) +func (_c *LibP2PMetrics_BlockPeer_Call) Run(run func(p peer.ID)) *LibP2PMetrics_BlockPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c } -// OnPeerRemovedFromProtocol provides a mock function with no fields -func (_m *LibP2PMetrics) OnPeerRemovedFromProtocol() { - _m.Called() +func (_c *LibP2PMetrics_BlockPeer_Call) Return() *LibP2PMetrics_BlockPeer_Call { + _c.Call.Return() + return _c } -// OnPeerThrottled provides a mock function with no fields -func (_m *LibP2PMetrics) OnPeerThrottled() { - _m.Called() +func (_c *LibP2PMetrics_BlockPeer_Call) RunAndReturn(run func(p peer.ID)) *LibP2PMetrics_BlockPeer_Call { + _c.Run(run) + return _c } -// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { - _m.Called() +// BlockProtocol provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockProtocol(proto protocol.ID) { + _mock.Called(proto) + return } -// OnPruneInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnPruneInvalidTopicIdsExceedThreshold() { - _m.Called() +// LibP2PMetrics_BlockProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProtocol' +type LibP2PMetrics_BlockProtocol_Call struct { + *mock.Call } -// OnPruneMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *LibP2PMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +// BlockProtocol is a helper method to define mock.On call +// - proto protocol.ID +func (_e *LibP2PMetrics_Expecter) BlockProtocol(proto interface{}) *LibP2PMetrics_BlockProtocol_Call { + return &LibP2PMetrics_BlockProtocol_Call{Call: _e.mock.On("BlockProtocol", proto)} } -// OnPublishMessageInspected provides a mock function with given fields: totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount -func (_m *LibP2PMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { - _m.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) +func (_c *LibP2PMetrics_BlockProtocol_Call) Run(run func(proto protocol.ID)) *LibP2PMetrics_BlockProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + run( + arg0, + ) + }) + return _c } -// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function with no fields -func (_m *LibP2PMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { - _m.Called() +func (_c *LibP2PMetrics_BlockProtocol_Call) Return() *LibP2PMetrics_BlockProtocol_Call { + _c.Call.Return() + return _c } -// OnRpcReceived provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *LibP2PMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +func (_c *LibP2PMetrics_BlockProtocol_Call) RunAndReturn(run func(proto protocol.ID)) *LibP2PMetrics_BlockProtocol_Call { + _c.Run(run) + return _c } -// OnRpcRejectedFromUnknownSender provides a mock function with no fields -func (_m *LibP2PMetrics) OnRpcRejectedFromUnknownSender() { - _m.Called() +// BlockProtocolPeer provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockProtocolPeer(proto protocol.ID, p peer.ID) { + _mock.Called(proto, p) + return } -// OnRpcSent provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *LibP2PMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +// LibP2PMetrics_BlockProtocolPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProtocolPeer' +type LibP2PMetrics_BlockProtocolPeer_Call struct { + *mock.Call } -// OnStreamCreated provides a mock function with given fields: duration, attempts -func (_m *LibP2PMetrics) OnStreamCreated(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// BlockProtocolPeer is a helper method to define mock.On call +// - proto protocol.ID +// - p peer.ID +func (_e *LibP2PMetrics_Expecter) BlockProtocolPeer(proto interface{}, p interface{}) *LibP2PMetrics_BlockProtocolPeer_Call { + return &LibP2PMetrics_BlockProtocolPeer_Call{Call: _e.mock.On("BlockProtocolPeer", proto, p)} } -// OnStreamCreationFailure provides a mock function with given fields: duration, attempts -func (_m *LibP2PMetrics) OnStreamCreationFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +func (_c *LibP2PMetrics_BlockProtocolPeer_Call) Run(run func(proto protocol.ID, p peer.ID)) *LibP2PMetrics_BlockProtocolPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnStreamCreationRetryBudgetResetToDefault provides a mock function with no fields -func (_m *LibP2PMetrics) OnStreamCreationRetryBudgetResetToDefault() { - _m.Called() +func (_c *LibP2PMetrics_BlockProtocolPeer_Call) Return() *LibP2PMetrics_BlockProtocolPeer_Call { + _c.Call.Return() + return _c } -// OnStreamCreationRetryBudgetUpdated provides a mock function with given fields: budget -func (_m *LibP2PMetrics) OnStreamCreationRetryBudgetUpdated(budget uint64) { - _m.Called(budget) +func (_c *LibP2PMetrics_BlockProtocolPeer_Call) RunAndReturn(run func(proto protocol.ID, p peer.ID)) *LibP2PMetrics_BlockProtocolPeer_Call { + _c.Run(run) + return _c } -// OnStreamEstablished provides a mock function with given fields: duration, attempts -func (_m *LibP2PMetrics) OnStreamEstablished(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// BlockService provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockService(svc string) { + _mock.Called(svc) + return } -// OnTimeInMeshUpdated provides a mock function with given fields: _a0, _a1 -func (_m *LibP2PMetrics) OnTimeInMeshUpdated(_a0 channels.Topic, _a1 time.Duration) { - _m.Called(_a0, _a1) +// LibP2PMetrics_BlockService_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockService' +type LibP2PMetrics_BlockService_Call struct { + *mock.Call } -// OnUndeliveredMessage provides a mock function with no fields -func (_m *LibP2PMetrics) OnUndeliveredMessage() { - _m.Called() +// BlockService is a helper method to define mock.On call +// - svc string +func (_e *LibP2PMetrics_Expecter) BlockService(svc interface{}) *LibP2PMetrics_BlockService_Call { + return &LibP2PMetrics_BlockService_Call{Call: _e.mock.On("BlockService", svc)} } -// OnUnstakedPeerInspectionFailed provides a mock function with no fields -func (_m *LibP2PMetrics) OnUnstakedPeerInspectionFailed() { - _m.Called() +func (_c *LibP2PMetrics_BlockService_Call) Run(run func(svc string)) *LibP2PMetrics_BlockService_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c } -// OutboundConnections provides a mock function with given fields: connectionCount -func (_m *LibP2PMetrics) OutboundConnections(connectionCount uint) { - _m.Called(connectionCount) +func (_c *LibP2PMetrics_BlockService_Call) Return() *LibP2PMetrics_BlockService_Call { + _c.Call.Return() + return _c } -// RoutingTablePeerAdded provides a mock function with no fields -func (_m *LibP2PMetrics) RoutingTablePeerAdded() { - _m.Called() +func (_c *LibP2PMetrics_BlockService_Call) RunAndReturn(run func(svc string)) *LibP2PMetrics_BlockService_Call { + _c.Run(run) + return _c } -// RoutingTablePeerRemoved provides a mock function with no fields -func (_m *LibP2PMetrics) RoutingTablePeerRemoved() { - _m.Called() +// BlockServicePeer provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockServicePeer(svc string, p peer.ID) { + _mock.Called(svc, p) + return } -// SetWarningStateCount provides a mock function with given fields: _a0 -func (_m *LibP2PMetrics) SetWarningStateCount(_a0 uint) { - _m.Called(_a0) +// LibP2PMetrics_BlockServicePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockServicePeer' +type LibP2PMetrics_BlockServicePeer_Call struct { + *mock.Call } -// NewLibP2PMetrics creates a new instance of LibP2PMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLibP2PMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *LibP2PMetrics { - mock := &LibP2PMetrics{} - mock.Mock.Test(t) +// BlockServicePeer is a helper method to define mock.On call +// - svc string +// - p peer.ID +func (_e *LibP2PMetrics_Expecter) BlockServicePeer(svc interface{}, p interface{}) *LibP2PMetrics_BlockServicePeer_Call { + return &LibP2PMetrics_BlockServicePeer_Call{Call: _e.mock.On("BlockServicePeer", svc, p)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *LibP2PMetrics_BlockServicePeer_Call) Run(run func(svc string, p peer.ID)) *LibP2PMetrics_BlockServicePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return mock +func (_c *LibP2PMetrics_BlockServicePeer_Call) Return() *LibP2PMetrics_BlockServicePeer_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_BlockServicePeer_Call) RunAndReturn(run func(svc string, p peer.ID)) *LibP2PMetrics_BlockServicePeer_Call { + _c.Run(run) + return _c +} + +// BlockStream provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) BlockStream(p peer.ID, dir network.Direction) { + _mock.Called(p, dir) + return +} + +// LibP2PMetrics_BlockStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockStream' +type LibP2PMetrics_BlockStream_Call struct { + *mock.Call +} + +// BlockStream is a helper method to define mock.On call +// - p peer.ID +// - dir network.Direction +func (_e *LibP2PMetrics_Expecter) BlockStream(p interface{}, dir interface{}) *LibP2PMetrics_BlockStream_Call { + return &LibP2PMetrics_BlockStream_Call{Call: _e.mock.On("BlockStream", p, dir)} +} + +func (_c *LibP2PMetrics_BlockStream_Call) Run(run func(p peer.ID, dir network.Direction)) *LibP2PMetrics_BlockStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.Direction + if args[1] != nil { + arg1 = args[1].(network.Direction) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_BlockStream_Call) Return() *LibP2PMetrics_BlockStream_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_BlockStream_Call) RunAndReturn(run func(p peer.ID, dir network.Direction)) *LibP2PMetrics_BlockStream_Call { + _c.Run(run) + return _c +} + +// DNSLookupDuration provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) DNSLookupDuration(duration time.Duration) { + _mock.Called(duration) + return +} + +// LibP2PMetrics_DNSLookupDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DNSLookupDuration' +type LibP2PMetrics_DNSLookupDuration_Call struct { + *mock.Call +} + +// DNSLookupDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *LibP2PMetrics_Expecter) DNSLookupDuration(duration interface{}) *LibP2PMetrics_DNSLookupDuration_Call { + return &LibP2PMetrics_DNSLookupDuration_Call{Call: _e.mock.On("DNSLookupDuration", duration)} +} + +func (_c *LibP2PMetrics_DNSLookupDuration_Call) Run(run func(duration time.Duration)) *LibP2PMetrics_DNSLookupDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_DNSLookupDuration_Call) Return() *LibP2PMetrics_DNSLookupDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_DNSLookupDuration_Call) RunAndReturn(run func(duration time.Duration)) *LibP2PMetrics_DNSLookupDuration_Call { + _c.Run(run) + return _c +} + +// DuplicateMessagePenalties provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) DuplicateMessagePenalties(penalty float64) { + _mock.Called(penalty) + return +} + +// LibP2PMetrics_DuplicateMessagePenalties_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessagePenalties' +type LibP2PMetrics_DuplicateMessagePenalties_Call struct { + *mock.Call +} + +// DuplicateMessagePenalties is a helper method to define mock.On call +// - penalty float64 +func (_e *LibP2PMetrics_Expecter) DuplicateMessagePenalties(penalty interface{}) *LibP2PMetrics_DuplicateMessagePenalties_Call { + return &LibP2PMetrics_DuplicateMessagePenalties_Call{Call: _e.mock.On("DuplicateMessagePenalties", penalty)} +} + +func (_c *LibP2PMetrics_DuplicateMessagePenalties_Call) Run(run func(penalty float64)) *LibP2PMetrics_DuplicateMessagePenalties_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_DuplicateMessagePenalties_Call) Return() *LibP2PMetrics_DuplicateMessagePenalties_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_DuplicateMessagePenalties_Call) RunAndReturn(run func(penalty float64)) *LibP2PMetrics_DuplicateMessagePenalties_Call { + _c.Run(run) + return _c +} + +// DuplicateMessagesCounts provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) DuplicateMessagesCounts(count float64) { + _mock.Called(count) + return +} + +// LibP2PMetrics_DuplicateMessagesCounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessagesCounts' +type LibP2PMetrics_DuplicateMessagesCounts_Call struct { + *mock.Call +} + +// DuplicateMessagesCounts is a helper method to define mock.On call +// - count float64 +func (_e *LibP2PMetrics_Expecter) DuplicateMessagesCounts(count interface{}) *LibP2PMetrics_DuplicateMessagesCounts_Call { + return &LibP2PMetrics_DuplicateMessagesCounts_Call{Call: _e.mock.On("DuplicateMessagesCounts", count)} +} + +func (_c *LibP2PMetrics_DuplicateMessagesCounts_Call) Run(run func(count float64)) *LibP2PMetrics_DuplicateMessagesCounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_DuplicateMessagesCounts_Call) Return() *LibP2PMetrics_DuplicateMessagesCounts_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_DuplicateMessagesCounts_Call) RunAndReturn(run func(count float64)) *LibP2PMetrics_DuplicateMessagesCounts_Call { + _c.Run(run) + return _c +} + +// InboundConnections provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) InboundConnections(connectionCount uint) { + _mock.Called(connectionCount) + return +} + +// LibP2PMetrics_InboundConnections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InboundConnections' +type LibP2PMetrics_InboundConnections_Call struct { + *mock.Call +} + +// InboundConnections is a helper method to define mock.On call +// - connectionCount uint +func (_e *LibP2PMetrics_Expecter) InboundConnections(connectionCount interface{}) *LibP2PMetrics_InboundConnections_Call { + return &LibP2PMetrics_InboundConnections_Call{Call: _e.mock.On("InboundConnections", connectionCount)} +} + +func (_c *LibP2PMetrics_InboundConnections_Call) Run(run func(connectionCount uint)) *LibP2PMetrics_InboundConnections_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_InboundConnections_Call) Return() *LibP2PMetrics_InboundConnections_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_InboundConnections_Call) RunAndReturn(run func(connectionCount uint)) *LibP2PMetrics_InboundConnections_Call { + _c.Run(run) + return _c +} + +// OnActiveClusterIDsNotSetErr provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnActiveClusterIDsNotSetErr() { + _mock.Called() + return +} + +// LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnActiveClusterIDsNotSetErr' +type LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call struct { + *mock.Call +} + +// OnActiveClusterIDsNotSetErr is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnActiveClusterIDsNotSetErr() *LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call { + return &LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call{Call: _e.mock.On("OnActiveClusterIDsNotSetErr")} +} + +func (_c *LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call) Run(run func()) *LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call) Return() *LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call) RunAndReturn(run func()) *LibP2PMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Run(run) + return _c +} + +// OnAppSpecificScoreUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnAppSpecificScoreUpdated(f float64) { + _mock.Called(f) + return +} + +// LibP2PMetrics_OnAppSpecificScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAppSpecificScoreUpdated' +type LibP2PMetrics_OnAppSpecificScoreUpdated_Call struct { + *mock.Call +} + +// OnAppSpecificScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *LibP2PMetrics_Expecter) OnAppSpecificScoreUpdated(f interface{}) *LibP2PMetrics_OnAppSpecificScoreUpdated_Call { + return &LibP2PMetrics_OnAppSpecificScoreUpdated_Call{Call: _e.mock.On("OnAppSpecificScoreUpdated", f)} +} + +func (_c *LibP2PMetrics_OnAppSpecificScoreUpdated_Call) Run(run func(f float64)) *LibP2PMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnAppSpecificScoreUpdated_Call) Return() *LibP2PMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnAppSpecificScoreUpdated_Call) RunAndReturn(run func(f float64)) *LibP2PMetrics_OnAppSpecificScoreUpdated_Call { + _c.Run(run) + return _c +} + +// OnBehaviourPenaltyUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnBehaviourPenaltyUpdated(f float64) { + _mock.Called(f) + return +} + +// LibP2PMetrics_OnBehaviourPenaltyUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBehaviourPenaltyUpdated' +type LibP2PMetrics_OnBehaviourPenaltyUpdated_Call struct { + *mock.Call +} + +// OnBehaviourPenaltyUpdated is a helper method to define mock.On call +// - f float64 +func (_e *LibP2PMetrics_Expecter) OnBehaviourPenaltyUpdated(f interface{}) *LibP2PMetrics_OnBehaviourPenaltyUpdated_Call { + return &LibP2PMetrics_OnBehaviourPenaltyUpdated_Call{Call: _e.mock.On("OnBehaviourPenaltyUpdated", f)} +} + +func (_c *LibP2PMetrics_OnBehaviourPenaltyUpdated_Call) Run(run func(f float64)) *LibP2PMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnBehaviourPenaltyUpdated_Call) Return() *LibP2PMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnBehaviourPenaltyUpdated_Call) RunAndReturn(run func(f float64)) *LibP2PMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Run(run) + return _c +} + +// OnControlMessagesTruncated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { + _mock.Called(messageType, diff) + return +} + +// LibP2PMetrics_OnControlMessagesTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnControlMessagesTruncated' +type LibP2PMetrics_OnControlMessagesTruncated_Call struct { + *mock.Call +} + +// OnControlMessagesTruncated is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +// - diff int +func (_e *LibP2PMetrics_Expecter) OnControlMessagesTruncated(messageType interface{}, diff interface{}) *LibP2PMetrics_OnControlMessagesTruncated_Call { + return &LibP2PMetrics_OnControlMessagesTruncated_Call{Call: _e.mock.On("OnControlMessagesTruncated", messageType, diff)} +} + +func (_c *LibP2PMetrics_OnControlMessagesTruncated_Call) Run(run func(messageType p2pmsg.ControlMessageType, diff int)) *LibP2PMetrics_OnControlMessagesTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnControlMessagesTruncated_Call) Return() *LibP2PMetrics_OnControlMessagesTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnControlMessagesTruncated_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType, diff int)) *LibP2PMetrics_OnControlMessagesTruncated_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheHit provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnDNSCacheHit() { + _mock.Called() + return +} + +// LibP2PMetrics_OnDNSCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheHit' +type LibP2PMetrics_OnDNSCacheHit_Call struct { + *mock.Call +} + +// OnDNSCacheHit is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnDNSCacheHit() *LibP2PMetrics_OnDNSCacheHit_Call { + return &LibP2PMetrics_OnDNSCacheHit_Call{Call: _e.mock.On("OnDNSCacheHit")} +} + +func (_c *LibP2PMetrics_OnDNSCacheHit_Call) Run(run func()) *LibP2PMetrics_OnDNSCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnDNSCacheHit_Call) Return() *LibP2PMetrics_OnDNSCacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnDNSCacheHit_Call) RunAndReturn(run func()) *LibP2PMetrics_OnDNSCacheHit_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheInvalidated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnDNSCacheInvalidated() { + _mock.Called() + return +} + +// LibP2PMetrics_OnDNSCacheInvalidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheInvalidated' +type LibP2PMetrics_OnDNSCacheInvalidated_Call struct { + *mock.Call +} + +// OnDNSCacheInvalidated is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnDNSCacheInvalidated() *LibP2PMetrics_OnDNSCacheInvalidated_Call { + return &LibP2PMetrics_OnDNSCacheInvalidated_Call{Call: _e.mock.On("OnDNSCacheInvalidated")} +} + +func (_c *LibP2PMetrics_OnDNSCacheInvalidated_Call) Run(run func()) *LibP2PMetrics_OnDNSCacheInvalidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnDNSCacheInvalidated_Call) Return() *LibP2PMetrics_OnDNSCacheInvalidated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnDNSCacheInvalidated_Call) RunAndReturn(run func()) *LibP2PMetrics_OnDNSCacheInvalidated_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheMiss provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnDNSCacheMiss() { + _mock.Called() + return +} + +// LibP2PMetrics_OnDNSCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheMiss' +type LibP2PMetrics_OnDNSCacheMiss_Call struct { + *mock.Call +} + +// OnDNSCacheMiss is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnDNSCacheMiss() *LibP2PMetrics_OnDNSCacheMiss_Call { + return &LibP2PMetrics_OnDNSCacheMiss_Call{Call: _e.mock.On("OnDNSCacheMiss")} +} + +func (_c *LibP2PMetrics_OnDNSCacheMiss_Call) Run(run func()) *LibP2PMetrics_OnDNSCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnDNSCacheMiss_Call) Return() *LibP2PMetrics_OnDNSCacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnDNSCacheMiss_Call) RunAndReturn(run func()) *LibP2PMetrics_OnDNSCacheMiss_Call { + _c.Run(run) + return _c +} + +// OnDNSLookupRequestDropped provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnDNSLookupRequestDropped() { + _mock.Called() + return +} + +// LibP2PMetrics_OnDNSLookupRequestDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSLookupRequestDropped' +type LibP2PMetrics_OnDNSLookupRequestDropped_Call struct { + *mock.Call +} + +// OnDNSLookupRequestDropped is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnDNSLookupRequestDropped() *LibP2PMetrics_OnDNSLookupRequestDropped_Call { + return &LibP2PMetrics_OnDNSLookupRequestDropped_Call{Call: _e.mock.On("OnDNSLookupRequestDropped")} +} + +func (_c *LibP2PMetrics_OnDNSLookupRequestDropped_Call) Run(run func()) *LibP2PMetrics_OnDNSLookupRequestDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnDNSLookupRequestDropped_Call) Return() *LibP2PMetrics_OnDNSLookupRequestDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnDNSLookupRequestDropped_Call) RunAndReturn(run func()) *LibP2PMetrics_OnDNSLookupRequestDropped_Call { + _c.Run(run) + return _c +} + +// OnDialRetryBudgetResetToDefault provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnDialRetryBudgetResetToDefault() { + _mock.Called() + return +} + +// LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDialRetryBudgetResetToDefault' +type LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call struct { + *mock.Call +} + +// OnDialRetryBudgetResetToDefault is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnDialRetryBudgetResetToDefault() *LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call { + return &LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call{Call: _e.mock.On("OnDialRetryBudgetResetToDefault")} +} + +func (_c *LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call) Run(run func()) *LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call) Return() *LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call) RunAndReturn(run func()) *LibP2PMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Run(run) + return _c +} + +// OnDialRetryBudgetUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnDialRetryBudgetUpdated(budget uint64) { + _mock.Called(budget) + return +} + +// LibP2PMetrics_OnDialRetryBudgetUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDialRetryBudgetUpdated' +type LibP2PMetrics_OnDialRetryBudgetUpdated_Call struct { + *mock.Call +} + +// OnDialRetryBudgetUpdated is a helper method to define mock.On call +// - budget uint64 +func (_e *LibP2PMetrics_Expecter) OnDialRetryBudgetUpdated(budget interface{}) *LibP2PMetrics_OnDialRetryBudgetUpdated_Call { + return &LibP2PMetrics_OnDialRetryBudgetUpdated_Call{Call: _e.mock.On("OnDialRetryBudgetUpdated", budget)} +} + +func (_c *LibP2PMetrics_OnDialRetryBudgetUpdated_Call) Run(run func(budget uint64)) *LibP2PMetrics_OnDialRetryBudgetUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnDialRetryBudgetUpdated_Call) Return() *LibP2PMetrics_OnDialRetryBudgetUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnDialRetryBudgetUpdated_Call) RunAndReturn(run func(budget uint64)) *LibP2PMetrics_OnDialRetryBudgetUpdated_Call { + _c.Run(run) + return _c +} + +// OnEstablishStreamFailure provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnEstablishStreamFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// LibP2PMetrics_OnEstablishStreamFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnEstablishStreamFailure' +type LibP2PMetrics_OnEstablishStreamFailure_Call struct { + *mock.Call +} + +// OnEstablishStreamFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *LibP2PMetrics_Expecter) OnEstablishStreamFailure(duration interface{}, attempts interface{}) *LibP2PMetrics_OnEstablishStreamFailure_Call { + return &LibP2PMetrics_OnEstablishStreamFailure_Call{Call: _e.mock.On("OnEstablishStreamFailure", duration, attempts)} +} + +func (_c *LibP2PMetrics_OnEstablishStreamFailure_Call) Run(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnEstablishStreamFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnEstablishStreamFailure_Call) Return() *LibP2PMetrics_OnEstablishStreamFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnEstablishStreamFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnEstablishStreamFailure_Call { + _c.Run(run) + return _c +} + +// OnFirstMessageDeliveredUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnFirstMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFirstMessageDeliveredUpdated' +type LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnFirstMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *LibP2PMetrics_Expecter) OnFirstMessageDeliveredUpdated(topic interface{}, f interface{}) *LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call { + return &LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call{Call: _e.mock.On("OnFirstMessageDeliveredUpdated", topic, f)} +} + +func (_c *LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call) Return() *LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *LibP2PMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftDuplicateTopicIdsExceedThreshold' +type LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnGraftDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnGraftDuplicateTopicIdsExceedThreshold() *LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + return &LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftDuplicateTopicIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnGraftInvalidTopicIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnGraftInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftInvalidTopicIdsExceedThreshold' +type LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnGraftInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnGraftInvalidTopicIdsExceedThreshold() *LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + return &LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftInvalidTopicIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnGraftMessageInspected provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// LibP2PMetrics_OnGraftMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftMessageInspected' +type LibP2PMetrics_OnGraftMessageInspected_Call struct { + *mock.Call +} + +// OnGraftMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *LibP2PMetrics_Expecter) OnGraftMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *LibP2PMetrics_OnGraftMessageInspected_Call { + return &LibP2PMetrics_OnGraftMessageInspected_Call{Call: _e.mock.On("OnGraftMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *LibP2PMetrics_OnGraftMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *LibP2PMetrics_OnGraftMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnGraftMessageInspected_Call) Return() *LibP2PMetrics_OnGraftMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnGraftMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *LibP2PMetrics_OnGraftMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnIHaveControlMessageIdsTruncated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIHaveControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveControlMessageIdsTruncated' +type LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIHaveControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *LibP2PMetrics_Expecter) OnIHaveControlMessageIdsTruncated(diff interface{}) *LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call { + return &LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIHaveControlMessageIdsTruncated", diff)} +} + +func (_c *LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call) Run(run func(diff int)) *LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call) Return() *LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *LibP2PMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateMessageIdsExceedThreshold' +type LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnIHaveDuplicateMessageIdsExceedThreshold() *LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + return &LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateMessageIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateTopicIdsExceedThreshold' +type LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnIHaveDuplicateTopicIdsExceedThreshold() *LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + return &LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateTopicIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveInvalidTopicIdsExceedThreshold' +type LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnIHaveInvalidTopicIdsExceedThreshold() *LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + return &LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveInvalidTopicIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessageIDsReceived provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { + _mock.Called(channel, msgIdCount) + return +} + +// LibP2PMetrics_OnIHaveMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessageIDsReceived' +type LibP2PMetrics_OnIHaveMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIHaveMessageIDsReceived is a helper method to define mock.On call +// - channel string +// - msgIdCount int +func (_e *LibP2PMetrics_Expecter) OnIHaveMessageIDsReceived(channel interface{}, msgIdCount interface{}) *LibP2PMetrics_OnIHaveMessageIDsReceived_Call { + return &LibP2PMetrics_OnIHaveMessageIDsReceived_Call{Call: _e.mock.On("OnIHaveMessageIDsReceived", channel, msgIdCount)} +} + +func (_c *LibP2PMetrics_OnIHaveMessageIDsReceived_Call) Run(run func(channel string, msgIdCount int)) *LibP2PMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIHaveMessageIDsReceived_Call) Return() *LibP2PMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIHaveMessageIDsReceived_Call) RunAndReturn(run func(channel string, msgIdCount int)) *LibP2PMetrics_OnIHaveMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessagesInspected provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) + return +} + +// LibP2PMetrics_OnIHaveMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessagesInspected' +type LibP2PMetrics_OnIHaveMessagesInspected_Call struct { + *mock.Call +} + +// OnIHaveMessagesInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - duplicateMessageIds int +// - invalidTopicIds int +func (_e *LibP2PMetrics_Expecter) OnIHaveMessagesInspected(duplicateTopicIds interface{}, duplicateMessageIds interface{}, invalidTopicIds interface{}) *LibP2PMetrics_OnIHaveMessagesInspected_Call { + return &LibP2PMetrics_OnIHaveMessagesInspected_Call{Call: _e.mock.On("OnIHaveMessagesInspected", duplicateTopicIds, duplicateMessageIds, invalidTopicIds)} +} + +func (_c *LibP2PMetrics_OnIHaveMessagesInspected_Call) Run(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *LibP2PMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIHaveMessagesInspected_Call) Return() *LibP2PMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIHaveMessagesInspected_Call) RunAndReturn(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *LibP2PMetrics_OnIHaveMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIPColocationFactorUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIPColocationFactorUpdated(f float64) { + _mock.Called(f) + return +} + +// LibP2PMetrics_OnIPColocationFactorUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIPColocationFactorUpdated' +type LibP2PMetrics_OnIPColocationFactorUpdated_Call struct { + *mock.Call +} + +// OnIPColocationFactorUpdated is a helper method to define mock.On call +// - f float64 +func (_e *LibP2PMetrics_Expecter) OnIPColocationFactorUpdated(f interface{}) *LibP2PMetrics_OnIPColocationFactorUpdated_Call { + return &LibP2PMetrics_OnIPColocationFactorUpdated_Call{Call: _e.mock.On("OnIPColocationFactorUpdated", f)} +} + +func (_c *LibP2PMetrics_OnIPColocationFactorUpdated_Call) Run(run func(f float64)) *LibP2PMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIPColocationFactorUpdated_Call) Return() *LibP2PMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIPColocationFactorUpdated_Call) RunAndReturn(run func(f float64)) *LibP2PMetrics_OnIPColocationFactorUpdated_Call { + _c.Run(run) + return _c +} + +// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantCacheMissMessageIdsExceedThreshold' +type LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantCacheMissMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnIWantCacheMissMessageIdsExceedThreshold() *LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + return &LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantCacheMissMessageIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantControlMessageIdsTruncated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIWantControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantControlMessageIdsTruncated' +type LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIWantControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *LibP2PMetrics_Expecter) OnIWantControlMessageIdsTruncated(diff interface{}) *LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call { + return &LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIWantControlMessageIdsTruncated", diff)} +} + +func (_c *LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call) Run(run func(diff int)) *LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call) Return() *LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *LibP2PMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantDuplicateMessageIdsExceedThreshold' +type LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnIWantDuplicateMessageIdsExceedThreshold() *LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + return &LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantDuplicateMessageIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantMessageIDsReceived provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIWantMessageIDsReceived(msgIdCount int) { + _mock.Called(msgIdCount) + return +} + +// LibP2PMetrics_OnIWantMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessageIDsReceived' +type LibP2PMetrics_OnIWantMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIWantMessageIDsReceived is a helper method to define mock.On call +// - msgIdCount int +func (_e *LibP2PMetrics_Expecter) OnIWantMessageIDsReceived(msgIdCount interface{}) *LibP2PMetrics_OnIWantMessageIDsReceived_Call { + return &LibP2PMetrics_OnIWantMessageIDsReceived_Call{Call: _e.mock.On("OnIWantMessageIDsReceived", msgIdCount)} +} + +func (_c *LibP2PMetrics_OnIWantMessageIDsReceived_Call) Run(run func(msgIdCount int)) *LibP2PMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIWantMessageIDsReceived_Call) Return() *LibP2PMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIWantMessageIDsReceived_Call) RunAndReturn(run func(msgIdCount int)) *LibP2PMetrics_OnIWantMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIWantMessagesInspected provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { + _mock.Called(duplicateCount, cacheMissCount) + return +} + +// LibP2PMetrics_OnIWantMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessagesInspected' +type LibP2PMetrics_OnIWantMessagesInspected_Call struct { + *mock.Call +} + +// OnIWantMessagesInspected is a helper method to define mock.On call +// - duplicateCount int +// - cacheMissCount int +func (_e *LibP2PMetrics_Expecter) OnIWantMessagesInspected(duplicateCount interface{}, cacheMissCount interface{}) *LibP2PMetrics_OnIWantMessagesInspected_Call { + return &LibP2PMetrics_OnIWantMessagesInspected_Call{Call: _e.mock.On("OnIWantMessagesInspected", duplicateCount, cacheMissCount)} +} + +func (_c *LibP2PMetrics_OnIWantMessagesInspected_Call) Run(run func(duplicateCount int, cacheMissCount int)) *LibP2PMetrics_OnIWantMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIWantMessagesInspected_Call) Return() *LibP2PMetrics_OnIWantMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIWantMessagesInspected_Call) RunAndReturn(run func(duplicateCount int, cacheMissCount int)) *LibP2PMetrics_OnIWantMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIncomingRpcReceived provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { + _mock.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) + return +} + +// LibP2PMetrics_OnIncomingRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIncomingRpcReceived' +type LibP2PMetrics_OnIncomingRpcReceived_Call struct { + *mock.Call +} + +// OnIncomingRpcReceived is a helper method to define mock.On call +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +// - msgCount int +func (_e *LibP2PMetrics_Expecter) OnIncomingRpcReceived(iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}, msgCount interface{}) *LibP2PMetrics_OnIncomingRpcReceived_Call { + return &LibP2PMetrics_OnIncomingRpcReceived_Call{Call: _e.mock.On("OnIncomingRpcReceived", iHaveCount, iWantCount, graftCount, pruneCount, msgCount)} +} + +func (_c *LibP2PMetrics_OnIncomingRpcReceived_Call) Run(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *LibP2PMetrics_OnIncomingRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnIncomingRpcReceived_Call) Return() *LibP2PMetrics_OnIncomingRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnIncomingRpcReceived_Call) RunAndReturn(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *LibP2PMetrics_OnIncomingRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnInvalidControlMessageNotificationSent provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnInvalidControlMessageNotificationSent() { + _mock.Called() + return +} + +// LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidControlMessageNotificationSent' +type LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call struct { + *mock.Call +} + +// OnInvalidControlMessageNotificationSent is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnInvalidControlMessageNotificationSent() *LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call { + return &LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call{Call: _e.mock.On("OnInvalidControlMessageNotificationSent")} +} + +func (_c *LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call) Run(run func()) *LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call) Return() *LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call) RunAndReturn(run func()) *LibP2PMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Run(run) + return _c +} + +// OnInvalidMessageDeliveredUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnInvalidMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidMessageDeliveredUpdated' +type LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnInvalidMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *LibP2PMetrics_Expecter) OnInvalidMessageDeliveredUpdated(topic interface{}, f interface{}) *LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call { + return &LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call{Call: _e.mock.On("OnInvalidMessageDeliveredUpdated", topic, f)} +} + +func (_c *LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call) Return() *LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *LibP2PMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnInvalidTopicIdDetectedForControlMessage provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { + _mock.Called(messageType) + return +} + +// LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidTopicIdDetectedForControlMessage' +type LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call struct { + *mock.Call +} + +// OnInvalidTopicIdDetectedForControlMessage is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +func (_e *LibP2PMetrics_Expecter) OnInvalidTopicIdDetectedForControlMessage(messageType interface{}) *LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + return &LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call{Call: _e.mock.On("OnInvalidTopicIdDetectedForControlMessage", messageType)} +} + +func (_c *LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Run(run func(messageType p2pmsg.ControlMessageType)) *LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Return() *LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType)) *LibP2PMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Run(run) + return _c +} + +// OnLocalMeshSizeUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnLocalMeshSizeUpdated(topic string, size int) { + _mock.Called(topic, size) + return +} + +// LibP2PMetrics_OnLocalMeshSizeUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalMeshSizeUpdated' +type LibP2PMetrics_OnLocalMeshSizeUpdated_Call struct { + *mock.Call +} + +// OnLocalMeshSizeUpdated is a helper method to define mock.On call +// - topic string +// - size int +func (_e *LibP2PMetrics_Expecter) OnLocalMeshSizeUpdated(topic interface{}, size interface{}) *LibP2PMetrics_OnLocalMeshSizeUpdated_Call { + return &LibP2PMetrics_OnLocalMeshSizeUpdated_Call{Call: _e.mock.On("OnLocalMeshSizeUpdated", topic, size)} +} + +func (_c *LibP2PMetrics_OnLocalMeshSizeUpdated_Call) Run(run func(topic string, size int)) *LibP2PMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnLocalMeshSizeUpdated_Call) Return() *LibP2PMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnLocalMeshSizeUpdated_Call) RunAndReturn(run func(topic string, size int)) *LibP2PMetrics_OnLocalMeshSizeUpdated_Call { + _c.Run(run) + return _c +} + +// OnLocalPeerJoinedTopic provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnLocalPeerJoinedTopic() { + _mock.Called() + return +} + +// LibP2PMetrics_OnLocalPeerJoinedTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerJoinedTopic' +type LibP2PMetrics_OnLocalPeerJoinedTopic_Call struct { + *mock.Call +} + +// OnLocalPeerJoinedTopic is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnLocalPeerJoinedTopic() *LibP2PMetrics_OnLocalPeerJoinedTopic_Call { + return &LibP2PMetrics_OnLocalPeerJoinedTopic_Call{Call: _e.mock.On("OnLocalPeerJoinedTopic")} +} + +func (_c *LibP2PMetrics_OnLocalPeerJoinedTopic_Call) Run(run func()) *LibP2PMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnLocalPeerJoinedTopic_Call) Return() *LibP2PMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnLocalPeerJoinedTopic_Call) RunAndReturn(run func()) *LibP2PMetrics_OnLocalPeerJoinedTopic_Call { + _c.Run(run) + return _c +} + +// OnLocalPeerLeftTopic provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnLocalPeerLeftTopic() { + _mock.Called() + return +} + +// LibP2PMetrics_OnLocalPeerLeftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerLeftTopic' +type LibP2PMetrics_OnLocalPeerLeftTopic_Call struct { + *mock.Call +} + +// OnLocalPeerLeftTopic is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnLocalPeerLeftTopic() *LibP2PMetrics_OnLocalPeerLeftTopic_Call { + return &LibP2PMetrics_OnLocalPeerLeftTopic_Call{Call: _e.mock.On("OnLocalPeerLeftTopic")} +} + +func (_c *LibP2PMetrics_OnLocalPeerLeftTopic_Call) Run(run func()) *LibP2PMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnLocalPeerLeftTopic_Call) Return() *LibP2PMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnLocalPeerLeftTopic_Call) RunAndReturn(run func()) *LibP2PMetrics_OnLocalPeerLeftTopic_Call { + _c.Run(run) + return _c +} + +// OnMeshMessageDeliveredUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnMeshMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMeshMessageDeliveredUpdated' +type LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnMeshMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *LibP2PMetrics_Expecter) OnMeshMessageDeliveredUpdated(topic interface{}, f interface{}) *LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call { + return &LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call{Call: _e.mock.On("OnMeshMessageDeliveredUpdated", topic, f)} +} + +func (_c *LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call) Return() *LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *LibP2PMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnMessageDeliveredToAllSubscribers provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnMessageDeliveredToAllSubscribers(size int) { + _mock.Called(size) + return +} + +// LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDeliveredToAllSubscribers' +type LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call struct { + *mock.Call +} + +// OnMessageDeliveredToAllSubscribers is a helper method to define mock.On call +// - size int +func (_e *LibP2PMetrics_Expecter) OnMessageDeliveredToAllSubscribers(size interface{}) *LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call { + return &LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call{Call: _e.mock.On("OnMessageDeliveredToAllSubscribers", size)} +} + +func (_c *LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call) Run(run func(size int)) *LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call) Return() *LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call) RunAndReturn(run func(size int)) *LibP2PMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Run(run) + return _c +} + +// OnMessageDuplicate provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnMessageDuplicate(size int) { + _mock.Called(size) + return +} + +// LibP2PMetrics_OnMessageDuplicate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDuplicate' +type LibP2PMetrics_OnMessageDuplicate_Call struct { + *mock.Call +} + +// OnMessageDuplicate is a helper method to define mock.On call +// - size int +func (_e *LibP2PMetrics_Expecter) OnMessageDuplicate(size interface{}) *LibP2PMetrics_OnMessageDuplicate_Call { + return &LibP2PMetrics_OnMessageDuplicate_Call{Call: _e.mock.On("OnMessageDuplicate", size)} +} + +func (_c *LibP2PMetrics_OnMessageDuplicate_Call) Run(run func(size int)) *LibP2PMetrics_OnMessageDuplicate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnMessageDuplicate_Call) Return() *LibP2PMetrics_OnMessageDuplicate_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnMessageDuplicate_Call) RunAndReturn(run func(size int)) *LibP2PMetrics_OnMessageDuplicate_Call { + _c.Run(run) + return _c +} + +// OnMessageEnteredValidation provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnMessageEnteredValidation(size int) { + _mock.Called(size) + return +} + +// LibP2PMetrics_OnMessageEnteredValidation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageEnteredValidation' +type LibP2PMetrics_OnMessageEnteredValidation_Call struct { + *mock.Call +} + +// OnMessageEnteredValidation is a helper method to define mock.On call +// - size int +func (_e *LibP2PMetrics_Expecter) OnMessageEnteredValidation(size interface{}) *LibP2PMetrics_OnMessageEnteredValidation_Call { + return &LibP2PMetrics_OnMessageEnteredValidation_Call{Call: _e.mock.On("OnMessageEnteredValidation", size)} +} + +func (_c *LibP2PMetrics_OnMessageEnteredValidation_Call) Run(run func(size int)) *LibP2PMetrics_OnMessageEnteredValidation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnMessageEnteredValidation_Call) Return() *LibP2PMetrics_OnMessageEnteredValidation_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnMessageEnteredValidation_Call) RunAndReturn(run func(size int)) *LibP2PMetrics_OnMessageEnteredValidation_Call { + _c.Run(run) + return _c +} + +// OnMessageRejected provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnMessageRejected(size int, reason string) { + _mock.Called(size, reason) + return +} + +// LibP2PMetrics_OnMessageRejected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageRejected' +type LibP2PMetrics_OnMessageRejected_Call struct { + *mock.Call +} + +// OnMessageRejected is a helper method to define mock.On call +// - size int +// - reason string +func (_e *LibP2PMetrics_Expecter) OnMessageRejected(size interface{}, reason interface{}) *LibP2PMetrics_OnMessageRejected_Call { + return &LibP2PMetrics_OnMessageRejected_Call{Call: _e.mock.On("OnMessageRejected", size, reason)} +} + +func (_c *LibP2PMetrics_OnMessageRejected_Call) Run(run func(size int, reason string)) *LibP2PMetrics_OnMessageRejected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnMessageRejected_Call) Return() *LibP2PMetrics_OnMessageRejected_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnMessageRejected_Call) RunAndReturn(run func(size int, reason string)) *LibP2PMetrics_OnMessageRejected_Call { + _c.Run(run) + return _c +} + +// OnOutboundRpcDropped provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnOutboundRpcDropped() { + _mock.Called() + return +} + +// LibP2PMetrics_OnOutboundRpcDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOutboundRpcDropped' +type LibP2PMetrics_OnOutboundRpcDropped_Call struct { + *mock.Call +} + +// OnOutboundRpcDropped is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnOutboundRpcDropped() *LibP2PMetrics_OnOutboundRpcDropped_Call { + return &LibP2PMetrics_OnOutboundRpcDropped_Call{Call: _e.mock.On("OnOutboundRpcDropped")} +} + +func (_c *LibP2PMetrics_OnOutboundRpcDropped_Call) Run(run func()) *LibP2PMetrics_OnOutboundRpcDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnOutboundRpcDropped_Call) Return() *LibP2PMetrics_OnOutboundRpcDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnOutboundRpcDropped_Call) RunAndReturn(run func()) *LibP2PMetrics_OnOutboundRpcDropped_Call { + _c.Run(run) + return _c +} + +// OnOverallPeerScoreUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnOverallPeerScoreUpdated(f float64) { + _mock.Called(f) + return +} + +// LibP2PMetrics_OnOverallPeerScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOverallPeerScoreUpdated' +type LibP2PMetrics_OnOverallPeerScoreUpdated_Call struct { + *mock.Call +} + +// OnOverallPeerScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *LibP2PMetrics_Expecter) OnOverallPeerScoreUpdated(f interface{}) *LibP2PMetrics_OnOverallPeerScoreUpdated_Call { + return &LibP2PMetrics_OnOverallPeerScoreUpdated_Call{Call: _e.mock.On("OnOverallPeerScoreUpdated", f)} +} + +func (_c *LibP2PMetrics_OnOverallPeerScoreUpdated_Call) Run(run func(f float64)) *LibP2PMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnOverallPeerScoreUpdated_Call) Return() *LibP2PMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnOverallPeerScoreUpdated_Call) RunAndReturn(run func(f float64)) *LibP2PMetrics_OnOverallPeerScoreUpdated_Call { + _c.Run(run) + return _c +} + +// OnPeerAddedToProtocol provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPeerAddedToProtocol(protocol1 string) { + _mock.Called(protocol1) + return +} + +// LibP2PMetrics_OnPeerAddedToProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerAddedToProtocol' +type LibP2PMetrics_OnPeerAddedToProtocol_Call struct { + *mock.Call +} + +// OnPeerAddedToProtocol is a helper method to define mock.On call +// - protocol1 string +func (_e *LibP2PMetrics_Expecter) OnPeerAddedToProtocol(protocol1 interface{}) *LibP2PMetrics_OnPeerAddedToProtocol_Call { + return &LibP2PMetrics_OnPeerAddedToProtocol_Call{Call: _e.mock.On("OnPeerAddedToProtocol", protocol1)} +} + +func (_c *LibP2PMetrics_OnPeerAddedToProtocol_Call) Run(run func(protocol1 string)) *LibP2PMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnPeerAddedToProtocol_Call) Return() *LibP2PMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPeerAddedToProtocol_Call) RunAndReturn(run func(protocol1 string)) *LibP2PMetrics_OnPeerAddedToProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerDialFailure provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPeerDialFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// LibP2PMetrics_OnPeerDialFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerDialFailure' +type LibP2PMetrics_OnPeerDialFailure_Call struct { + *mock.Call +} + +// OnPeerDialFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *LibP2PMetrics_Expecter) OnPeerDialFailure(duration interface{}, attempts interface{}) *LibP2PMetrics_OnPeerDialFailure_Call { + return &LibP2PMetrics_OnPeerDialFailure_Call{Call: _e.mock.On("OnPeerDialFailure", duration, attempts)} +} + +func (_c *LibP2PMetrics_OnPeerDialFailure_Call) Run(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnPeerDialFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnPeerDialFailure_Call) Return() *LibP2PMetrics_OnPeerDialFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPeerDialFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnPeerDialFailure_Call { + _c.Run(run) + return _c +} + +// OnPeerDialed provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPeerDialed(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// LibP2PMetrics_OnPeerDialed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerDialed' +type LibP2PMetrics_OnPeerDialed_Call struct { + *mock.Call +} + +// OnPeerDialed is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *LibP2PMetrics_Expecter) OnPeerDialed(duration interface{}, attempts interface{}) *LibP2PMetrics_OnPeerDialed_Call { + return &LibP2PMetrics_OnPeerDialed_Call{Call: _e.mock.On("OnPeerDialed", duration, attempts)} +} + +func (_c *LibP2PMetrics_OnPeerDialed_Call) Run(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnPeerDialed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnPeerDialed_Call) Return() *LibP2PMetrics_OnPeerDialed_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPeerDialed_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnPeerDialed_Call { + _c.Run(run) + return _c +} + +// OnPeerGraftTopic provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPeerGraftTopic(topic string) { + _mock.Called(topic) + return +} + +// LibP2PMetrics_OnPeerGraftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerGraftTopic' +type LibP2PMetrics_OnPeerGraftTopic_Call struct { + *mock.Call +} + +// OnPeerGraftTopic is a helper method to define mock.On call +// - topic string +func (_e *LibP2PMetrics_Expecter) OnPeerGraftTopic(topic interface{}) *LibP2PMetrics_OnPeerGraftTopic_Call { + return &LibP2PMetrics_OnPeerGraftTopic_Call{Call: _e.mock.On("OnPeerGraftTopic", topic)} +} + +func (_c *LibP2PMetrics_OnPeerGraftTopic_Call) Run(run func(topic string)) *LibP2PMetrics_OnPeerGraftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnPeerGraftTopic_Call) Return() *LibP2PMetrics_OnPeerGraftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPeerGraftTopic_Call) RunAndReturn(run func(topic string)) *LibP2PMetrics_OnPeerGraftTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerPruneTopic provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPeerPruneTopic(topic string) { + _mock.Called(topic) + return +} + +// LibP2PMetrics_OnPeerPruneTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerPruneTopic' +type LibP2PMetrics_OnPeerPruneTopic_Call struct { + *mock.Call +} + +// OnPeerPruneTopic is a helper method to define mock.On call +// - topic string +func (_e *LibP2PMetrics_Expecter) OnPeerPruneTopic(topic interface{}) *LibP2PMetrics_OnPeerPruneTopic_Call { + return &LibP2PMetrics_OnPeerPruneTopic_Call{Call: _e.mock.On("OnPeerPruneTopic", topic)} +} + +func (_c *LibP2PMetrics_OnPeerPruneTopic_Call) Run(run func(topic string)) *LibP2PMetrics_OnPeerPruneTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnPeerPruneTopic_Call) Return() *LibP2PMetrics_OnPeerPruneTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPeerPruneTopic_Call) RunAndReturn(run func(topic string)) *LibP2PMetrics_OnPeerPruneTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerRemovedFromProtocol provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPeerRemovedFromProtocol() { + _mock.Called() + return +} + +// LibP2PMetrics_OnPeerRemovedFromProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerRemovedFromProtocol' +type LibP2PMetrics_OnPeerRemovedFromProtocol_Call struct { + *mock.Call +} + +// OnPeerRemovedFromProtocol is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnPeerRemovedFromProtocol() *LibP2PMetrics_OnPeerRemovedFromProtocol_Call { + return &LibP2PMetrics_OnPeerRemovedFromProtocol_Call{Call: _e.mock.On("OnPeerRemovedFromProtocol")} +} + +func (_c *LibP2PMetrics_OnPeerRemovedFromProtocol_Call) Run(run func()) *LibP2PMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnPeerRemovedFromProtocol_Call) Return() *LibP2PMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPeerRemovedFromProtocol_Call) RunAndReturn(run func()) *LibP2PMetrics_OnPeerRemovedFromProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerThrottled provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPeerThrottled() { + _mock.Called() + return +} + +// LibP2PMetrics_OnPeerThrottled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerThrottled' +type LibP2PMetrics_OnPeerThrottled_Call struct { + *mock.Call +} + +// OnPeerThrottled is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnPeerThrottled() *LibP2PMetrics_OnPeerThrottled_Call { + return &LibP2PMetrics_OnPeerThrottled_Call{Call: _e.mock.On("OnPeerThrottled")} +} + +func (_c *LibP2PMetrics_OnPeerThrottled_Call) Run(run func()) *LibP2PMetrics_OnPeerThrottled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnPeerThrottled_Call) Return() *LibP2PMetrics_OnPeerThrottled_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPeerThrottled_Call) RunAndReturn(run func()) *LibP2PMetrics_OnPeerThrottled_Call { + _c.Run(run) + return _c +} + +// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneDuplicateTopicIdsExceedThreshold' +type LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnPruneDuplicateTopicIdsExceedThreshold() *LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + return &LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneDuplicateTopicIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneInvalidTopicIdsExceedThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPruneInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneInvalidTopicIdsExceedThreshold' +type LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnPruneInvalidTopicIdsExceedThreshold() *LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + return &LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneInvalidTopicIdsExceedThreshold")} +} + +func (_c *LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Run(run func()) *LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Return() *LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneMessageInspected provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// LibP2PMetrics_OnPruneMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneMessageInspected' +type LibP2PMetrics_OnPruneMessageInspected_Call struct { + *mock.Call +} + +// OnPruneMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *LibP2PMetrics_Expecter) OnPruneMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *LibP2PMetrics_OnPruneMessageInspected_Call { + return &LibP2PMetrics_OnPruneMessageInspected_Call{Call: _e.mock.On("OnPruneMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *LibP2PMetrics_OnPruneMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *LibP2PMetrics_OnPruneMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnPruneMessageInspected_Call) Return() *LibP2PMetrics_OnPruneMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPruneMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *LibP2PMetrics_OnPruneMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessageInspected provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { + _mock.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) + return +} + +// LibP2PMetrics_OnPublishMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessageInspected' +type LibP2PMetrics_OnPublishMessageInspected_Call struct { + *mock.Call +} + +// OnPublishMessageInspected is a helper method to define mock.On call +// - totalErrCount int +// - invalidTopicIdsCount int +// - invalidSubscriptionsCount int +// - invalidSendersCount int +func (_e *LibP2PMetrics_Expecter) OnPublishMessageInspected(totalErrCount interface{}, invalidTopicIdsCount interface{}, invalidSubscriptionsCount interface{}, invalidSendersCount interface{}) *LibP2PMetrics_OnPublishMessageInspected_Call { + return &LibP2PMetrics_OnPublishMessageInspected_Call{Call: _e.mock.On("OnPublishMessageInspected", totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount)} +} + +func (_c *LibP2PMetrics_OnPublishMessageInspected_Call) Run(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *LibP2PMetrics_OnPublishMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnPublishMessageInspected_Call) Return() *LibP2PMetrics_OnPublishMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPublishMessageInspected_Call) RunAndReturn(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *LibP2PMetrics_OnPublishMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { + _mock.Called() + return +} + +// LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessagesInspectionErrorExceedsThreshold' +type LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call struct { + *mock.Call +} + +// OnPublishMessagesInspectionErrorExceedsThreshold is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnPublishMessagesInspectionErrorExceedsThreshold() *LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + return &LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call{Call: _e.mock.On("OnPublishMessagesInspectionErrorExceedsThreshold")} +} + +func (_c *LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Run(run func()) *LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Return() *LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) RunAndReturn(run func()) *LibP2PMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Run(run) + return _c +} + +// OnRpcReceived provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// LibP2PMetrics_OnRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcReceived' +type LibP2PMetrics_OnRpcReceived_Call struct { + *mock.Call +} + +// OnRpcReceived is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *LibP2PMetrics_Expecter) OnRpcReceived(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *LibP2PMetrics_OnRpcReceived_Call { + return &LibP2PMetrics_OnRpcReceived_Call{Call: _e.mock.On("OnRpcReceived", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *LibP2PMetrics_OnRpcReceived_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LibP2PMetrics_OnRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnRpcReceived_Call) Return() *LibP2PMetrics_OnRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnRpcReceived_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LibP2PMetrics_OnRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnRpcRejectedFromUnknownSender provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnRpcRejectedFromUnknownSender() { + _mock.Called() + return +} + +// LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcRejectedFromUnknownSender' +type LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call struct { + *mock.Call +} + +// OnRpcRejectedFromUnknownSender is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnRpcRejectedFromUnknownSender() *LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call { + return &LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call{Call: _e.mock.On("OnRpcRejectedFromUnknownSender")} +} + +func (_c *LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call) Run(run func()) *LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call) Return() *LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call) RunAndReturn(run func()) *LibP2PMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Run(run) + return _c +} + +// OnRpcSent provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// LibP2PMetrics_OnRpcSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcSent' +type LibP2PMetrics_OnRpcSent_Call struct { + *mock.Call +} + +// OnRpcSent is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *LibP2PMetrics_Expecter) OnRpcSent(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *LibP2PMetrics_OnRpcSent_Call { + return &LibP2PMetrics_OnRpcSent_Call{Call: _e.mock.On("OnRpcSent", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *LibP2PMetrics_OnRpcSent_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LibP2PMetrics_OnRpcSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnRpcSent_Call) Return() *LibP2PMetrics_OnRpcSent_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnRpcSent_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LibP2PMetrics_OnRpcSent_Call { + _c.Run(run) + return _c +} + +// OnStreamCreated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnStreamCreated(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// LibP2PMetrics_OnStreamCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreated' +type LibP2PMetrics_OnStreamCreated_Call struct { + *mock.Call +} + +// OnStreamCreated is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *LibP2PMetrics_Expecter) OnStreamCreated(duration interface{}, attempts interface{}) *LibP2PMetrics_OnStreamCreated_Call { + return &LibP2PMetrics_OnStreamCreated_Call{Call: _e.mock.On("OnStreamCreated", duration, attempts)} +} + +func (_c *LibP2PMetrics_OnStreamCreated_Call) Run(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnStreamCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreated_Call) Return() *LibP2PMetrics_OnStreamCreated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreated_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnStreamCreated_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationFailure provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnStreamCreationFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// LibP2PMetrics_OnStreamCreationFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationFailure' +type LibP2PMetrics_OnStreamCreationFailure_Call struct { + *mock.Call +} + +// OnStreamCreationFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *LibP2PMetrics_Expecter) OnStreamCreationFailure(duration interface{}, attempts interface{}) *LibP2PMetrics_OnStreamCreationFailure_Call { + return &LibP2PMetrics_OnStreamCreationFailure_Call{Call: _e.mock.On("OnStreamCreationFailure", duration, attempts)} +} + +func (_c *LibP2PMetrics_OnStreamCreationFailure_Call) Run(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnStreamCreationFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreationFailure_Call) Return() *LibP2PMetrics_OnStreamCreationFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreationFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnStreamCreationFailure_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationRetryBudgetResetToDefault provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnStreamCreationRetryBudgetResetToDefault() { + _mock.Called() + return +} + +// LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationRetryBudgetResetToDefault' +type LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call struct { + *mock.Call +} + +// OnStreamCreationRetryBudgetResetToDefault is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnStreamCreationRetryBudgetResetToDefault() *LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + return &LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call{Call: _e.mock.On("OnStreamCreationRetryBudgetResetToDefault")} +} + +func (_c *LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) Run(run func()) *LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) Return() *LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) RunAndReturn(run func()) *LibP2PMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationRetryBudgetUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnStreamCreationRetryBudgetUpdated(budget uint64) { + _mock.Called(budget) + return +} + +// LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationRetryBudgetUpdated' +type LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call struct { + *mock.Call +} + +// OnStreamCreationRetryBudgetUpdated is a helper method to define mock.On call +// - budget uint64 +func (_e *LibP2PMetrics_Expecter) OnStreamCreationRetryBudgetUpdated(budget interface{}) *LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call { + return &LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call{Call: _e.mock.On("OnStreamCreationRetryBudgetUpdated", budget)} +} + +func (_c *LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call) Run(run func(budget uint64)) *LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call) Return() *LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call) RunAndReturn(run func(budget uint64)) *LibP2PMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Run(run) + return _c +} + +// OnStreamEstablished provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnStreamEstablished(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// LibP2PMetrics_OnStreamEstablished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamEstablished' +type LibP2PMetrics_OnStreamEstablished_Call struct { + *mock.Call +} + +// OnStreamEstablished is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *LibP2PMetrics_Expecter) OnStreamEstablished(duration interface{}, attempts interface{}) *LibP2PMetrics_OnStreamEstablished_Call { + return &LibP2PMetrics_OnStreamEstablished_Call{Call: _e.mock.On("OnStreamEstablished", duration, attempts)} +} + +func (_c *LibP2PMetrics_OnStreamEstablished_Call) Run(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnStreamEstablished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnStreamEstablished_Call) Return() *LibP2PMetrics_OnStreamEstablished_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnStreamEstablished_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *LibP2PMetrics_OnStreamEstablished_Call { + _c.Run(run) + return _c +} + +// OnTimeInMeshUpdated provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnTimeInMeshUpdated(topic channels.Topic, duration time.Duration) { + _mock.Called(topic, duration) + return +} + +// LibP2PMetrics_OnTimeInMeshUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTimeInMeshUpdated' +type LibP2PMetrics_OnTimeInMeshUpdated_Call struct { + *mock.Call +} + +// OnTimeInMeshUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - duration time.Duration +func (_e *LibP2PMetrics_Expecter) OnTimeInMeshUpdated(topic interface{}, duration interface{}) *LibP2PMetrics_OnTimeInMeshUpdated_Call { + return &LibP2PMetrics_OnTimeInMeshUpdated_Call{Call: _e.mock.On("OnTimeInMeshUpdated", topic, duration)} +} + +func (_c *LibP2PMetrics_OnTimeInMeshUpdated_Call) Run(run func(topic channels.Topic, duration time.Duration)) *LibP2PMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OnTimeInMeshUpdated_Call) Return() *LibP2PMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnTimeInMeshUpdated_Call) RunAndReturn(run func(topic channels.Topic, duration time.Duration)) *LibP2PMetrics_OnTimeInMeshUpdated_Call { + _c.Run(run) + return _c +} + +// OnUndeliveredMessage provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnUndeliveredMessage() { + _mock.Called() + return +} + +// LibP2PMetrics_OnUndeliveredMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUndeliveredMessage' +type LibP2PMetrics_OnUndeliveredMessage_Call struct { + *mock.Call +} + +// OnUndeliveredMessage is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnUndeliveredMessage() *LibP2PMetrics_OnUndeliveredMessage_Call { + return &LibP2PMetrics_OnUndeliveredMessage_Call{Call: _e.mock.On("OnUndeliveredMessage")} +} + +func (_c *LibP2PMetrics_OnUndeliveredMessage_Call) Run(run func()) *LibP2PMetrics_OnUndeliveredMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnUndeliveredMessage_Call) Return() *LibP2PMetrics_OnUndeliveredMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnUndeliveredMessage_Call) RunAndReturn(run func()) *LibP2PMetrics_OnUndeliveredMessage_Call { + _c.Run(run) + return _c +} + +// OnUnstakedPeerInspectionFailed provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OnUnstakedPeerInspectionFailed() { + _mock.Called() + return +} + +// LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnstakedPeerInspectionFailed' +type LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call struct { + *mock.Call +} + +// OnUnstakedPeerInspectionFailed is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) OnUnstakedPeerInspectionFailed() *LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call { + return &LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call{Call: _e.mock.On("OnUnstakedPeerInspectionFailed")} +} + +func (_c *LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call) Run(run func()) *LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call) Return() *LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call) RunAndReturn(run func()) *LibP2PMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Run(run) + return _c +} + +// OutboundConnections provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) OutboundConnections(connectionCount uint) { + _mock.Called(connectionCount) + return +} + +// LibP2PMetrics_OutboundConnections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OutboundConnections' +type LibP2PMetrics_OutboundConnections_Call struct { + *mock.Call +} + +// OutboundConnections is a helper method to define mock.On call +// - connectionCount uint +func (_e *LibP2PMetrics_Expecter) OutboundConnections(connectionCount interface{}) *LibP2PMetrics_OutboundConnections_Call { + return &LibP2PMetrics_OutboundConnections_Call{Call: _e.mock.On("OutboundConnections", connectionCount)} +} + +func (_c *LibP2PMetrics_OutboundConnections_Call) Run(run func(connectionCount uint)) *LibP2PMetrics_OutboundConnections_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_OutboundConnections_Call) Return() *LibP2PMetrics_OutboundConnections_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_OutboundConnections_Call) RunAndReturn(run func(connectionCount uint)) *LibP2PMetrics_OutboundConnections_Call { + _c.Run(run) + return _c +} + +// RoutingTablePeerAdded provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) RoutingTablePeerAdded() { + _mock.Called() + return +} + +// LibP2PMetrics_RoutingTablePeerAdded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTablePeerAdded' +type LibP2PMetrics_RoutingTablePeerAdded_Call struct { + *mock.Call +} + +// RoutingTablePeerAdded is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) RoutingTablePeerAdded() *LibP2PMetrics_RoutingTablePeerAdded_Call { + return &LibP2PMetrics_RoutingTablePeerAdded_Call{Call: _e.mock.On("RoutingTablePeerAdded")} +} + +func (_c *LibP2PMetrics_RoutingTablePeerAdded_Call) Run(run func()) *LibP2PMetrics_RoutingTablePeerAdded_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_RoutingTablePeerAdded_Call) Return() *LibP2PMetrics_RoutingTablePeerAdded_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_RoutingTablePeerAdded_Call) RunAndReturn(run func()) *LibP2PMetrics_RoutingTablePeerAdded_Call { + _c.Run(run) + return _c +} + +// RoutingTablePeerRemoved provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) RoutingTablePeerRemoved() { + _mock.Called() + return +} + +// LibP2PMetrics_RoutingTablePeerRemoved_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTablePeerRemoved' +type LibP2PMetrics_RoutingTablePeerRemoved_Call struct { + *mock.Call +} + +// RoutingTablePeerRemoved is a helper method to define mock.On call +func (_e *LibP2PMetrics_Expecter) RoutingTablePeerRemoved() *LibP2PMetrics_RoutingTablePeerRemoved_Call { + return &LibP2PMetrics_RoutingTablePeerRemoved_Call{Call: _e.mock.On("RoutingTablePeerRemoved")} +} + +func (_c *LibP2PMetrics_RoutingTablePeerRemoved_Call) Run(run func()) *LibP2PMetrics_RoutingTablePeerRemoved_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PMetrics_RoutingTablePeerRemoved_Call) Return() *LibP2PMetrics_RoutingTablePeerRemoved_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_RoutingTablePeerRemoved_Call) RunAndReturn(run func()) *LibP2PMetrics_RoutingTablePeerRemoved_Call { + _c.Run(run) + return _c +} + +// SetWarningStateCount provides a mock function for the type LibP2PMetrics +func (_mock *LibP2PMetrics) SetWarningStateCount(v uint) { + _mock.Called(v) + return +} + +// LibP2PMetrics_SetWarningStateCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetWarningStateCount' +type LibP2PMetrics_SetWarningStateCount_Call struct { + *mock.Call +} + +// SetWarningStateCount is a helper method to define mock.On call +// - v uint +func (_e *LibP2PMetrics_Expecter) SetWarningStateCount(v interface{}) *LibP2PMetrics_SetWarningStateCount_Call { + return &LibP2PMetrics_SetWarningStateCount_Call{Call: _e.mock.On("SetWarningStateCount", v)} +} + +func (_c *LibP2PMetrics_SetWarningStateCount_Call) Run(run func(v uint)) *LibP2PMetrics_SetWarningStateCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PMetrics_SetWarningStateCount_Call) Return() *LibP2PMetrics_SetWarningStateCount_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PMetrics_SetWarningStateCount_Call) RunAndReturn(run func(v uint)) *LibP2PMetrics_SetWarningStateCount_Call { + _c.Run(run) + return _c } diff --git a/module/mock/local.go b/module/mock/local.go index db5aa9679fb..fe13c1ba2e6 100644 --- a/module/mock/local.go +++ b/module/mock/local.go @@ -1,82 +1,226 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - - hash "github.com/onflow/crypto/hash" - + "github.com/onflow/crypto" + "github.com/onflow/crypto/hash" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewLocal creates a new instance of Local. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLocal(t interface { + mock.TestingT + Cleanup(func()) +}) *Local { + mock := &Local{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Local is an autogenerated mock type for the Local type type Local struct { mock.Mock } -// Address provides a mock function with no fields -func (_m *Local) Address() string { - ret := _m.Called() +type Local_Expecter struct { + mock *mock.Mock +} + +func (_m *Local) EXPECT() *Local_Expecter { + return &Local_Expecter{mock: &_m.Mock} +} + +// Address provides a mock function for the type Local +func (_mock *Local) Address() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Address") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// NodeID provides a mock function with no fields -func (_m *Local) NodeID() flow.Identifier { - ret := _m.Called() +// Local_Address_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Address' +type Local_Address_Call struct { + *mock.Call +} + +// Address is a helper method to define mock.On call +func (_e *Local_Expecter) Address() *Local_Address_Call { + return &Local_Address_Call{Call: _e.mock.On("Address")} +} + +func (_c *Local_Address_Call) Run(run func()) *Local_Address_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Local_Address_Call) Return(s string) *Local_Address_Call { + _c.Call.Return(s) + return _c +} + +func (_c *Local_Address_Call) RunAndReturn(run func() string) *Local_Address_Call { + _c.Call.Return(run) + return _c +} + +// NodeID provides a mock function for the type Local +func (_mock *Local) NodeID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NodeID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// NotMeFilter provides a mock function with no fields -func (_m *Local) NotMeFilter() flow.IdentityFilter[flow.Identity] { - ret := _m.Called() +// Local_NodeID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NodeID' +type Local_NodeID_Call struct { + *mock.Call +} + +// NodeID is a helper method to define mock.On call +func (_e *Local_Expecter) NodeID() *Local_NodeID_Call { + return &Local_NodeID_Call{Call: _e.mock.On("NodeID")} +} + +func (_c *Local_NodeID_Call) Run(run func()) *Local_NodeID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Local_NodeID_Call) Return(identifier flow.Identifier) *Local_NodeID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *Local_NodeID_Call) RunAndReturn(run func() flow.Identifier) *Local_NodeID_Call { + _c.Call.Return(run) + return _c +} + +// NotMeFilter provides a mock function for the type Local +func (_mock *Local) NotMeFilter() flow.IdentityFilter[flow.Identity] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NotMeFilter") } var r0 flow.IdentityFilter[flow.Identity] - if rf, ok := ret.Get(0).(func() flow.IdentityFilter[flow.Identity]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentityFilter[flow.Identity]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentityFilter[flow.Identity]) } } + return r0 +} +// Local_NotMeFilter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NotMeFilter' +type Local_NotMeFilter_Call struct { + *mock.Call +} + +// NotMeFilter is a helper method to define mock.On call +func (_e *Local_Expecter) NotMeFilter() *Local_NotMeFilter_Call { + return &Local_NotMeFilter_Call{Call: _e.mock.On("NotMeFilter")} +} + +func (_c *Local_NotMeFilter_Call) Run(run func()) *Local_NotMeFilter_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Local_NotMeFilter_Call) Return(identityFilter flow.IdentityFilter[flow.Identity]) *Local_NotMeFilter_Call { + _c.Call.Return(identityFilter) + return _c +} + +func (_c *Local_NotMeFilter_Call) RunAndReturn(run func() flow.IdentityFilter[flow.Identity]) *Local_NotMeFilter_Call { + _c.Call.Return(run) + return _c +} + +// Role provides a mock function for the type Local +func (_mock *Local) Role() flow.Role { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Role") + } + + var r0 flow.Role + if returnFunc, ok := ret.Get(0).(func() flow.Role); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(flow.Role) + } return r0 } -// Sign provides a mock function with given fields: _a0, _a1 -func (_m *Local) Sign(_a0 []byte, _a1 hash.Hasher) (crypto.Signature, error) { - ret := _m.Called(_a0, _a1) +// Local_Role_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Role' +type Local_Role_Call struct { + *mock.Call +} + +// Role is a helper method to define mock.On call +func (_e *Local_Expecter) Role() *Local_Role_Call { + return &Local_Role_Call{Call: _e.mock.On("Role")} +} + +func (_c *Local_Role_Call) Run(run func()) *Local_Role_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Local_Role_Call) Return(role flow.Role) *Local_Role_Call { + _c.Call.Return(role) + return _c +} + +func (_c *Local_Role_Call) RunAndReturn(run func() flow.Role) *Local_Role_Call { + _c.Call.Return(run) + return _c +} + +// Sign provides a mock function for the type Local +func (_mock *Local) Sign(bytes []byte, hasher hash.Hasher) (crypto.Signature, error) { + ret := _mock.Called(bytes, hasher) if len(ret) == 0 { panic("no return value specified for Sign") @@ -84,29 +228,67 @@ func (_m *Local) Sign(_a0 []byte, _a1 hash.Hasher) (crypto.Signature, error) { var r0 crypto.Signature var r1 error - if rf, ok := ret.Get(0).(func([]byte, hash.Hasher) (crypto.Signature, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func([]byte, hash.Hasher) (crypto.Signature, error)); ok { + return returnFunc(bytes, hasher) } - if rf, ok := ret.Get(0).(func([]byte, hash.Hasher) crypto.Signature); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func([]byte, hash.Hasher) crypto.Signature); ok { + r0 = returnFunc(bytes, hasher) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.Signature) } } - - if rf, ok := ret.Get(1).(func([]byte, hash.Hasher) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func([]byte, hash.Hasher) error); ok { + r1 = returnFunc(bytes, hasher) } else { r1 = ret.Error(1) } - return r0, r1 } -// SignFunc provides a mock function with given fields: _a0, _a1, _a2 -func (_m *Local) SignFunc(_a0 []byte, _a1 hash.Hasher, _a2 func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) (crypto.Signature, error) { - ret := _m.Called(_a0, _a1, _a2) +// Local_Sign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sign' +type Local_Sign_Call struct { + *mock.Call +} + +// Sign is a helper method to define mock.On call +// - bytes []byte +// - hasher hash.Hasher +func (_e *Local_Expecter) Sign(bytes interface{}, hasher interface{}) *Local_Sign_Call { + return &Local_Sign_Call{Call: _e.mock.On("Sign", bytes, hasher)} +} + +func (_c *Local_Sign_Call) Run(run func(bytes []byte, hasher hash.Hasher)) *Local_Sign_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 hash.Hasher + if args[1] != nil { + arg1 = args[1].(hash.Hasher) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Local_Sign_Call) Return(signature crypto.Signature, err error) *Local_Sign_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *Local_Sign_Call) RunAndReturn(run func(bytes []byte, hasher hash.Hasher) (crypto.Signature, error)) *Local_Sign_Call { + _c.Call.Return(run) + return _c +} + +// SignFunc provides a mock function for the type Local +func (_mock *Local) SignFunc(bytes []byte, hasher hash.Hasher, fn func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) (crypto.Signature, error) { + ret := _mock.Called(bytes, hasher, fn) if len(ret) == 0 { panic("no return value specified for SignFunc") @@ -114,36 +296,66 @@ func (_m *Local) SignFunc(_a0 []byte, _a1 hash.Hasher, _a2 func(crypto.PrivateKe var r0 crypto.Signature var r1 error - if rf, ok := ret.Get(0).(func([]byte, hash.Hasher, func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) (crypto.Signature, error)); ok { - return rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func([]byte, hash.Hasher, func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) (crypto.Signature, error)); ok { + return returnFunc(bytes, hasher, fn) } - if rf, ok := ret.Get(0).(func([]byte, hash.Hasher, func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) crypto.Signature); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func([]byte, hash.Hasher, func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) crypto.Signature); ok { + r0 = returnFunc(bytes, hasher, fn) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.Signature) } } - - if rf, ok := ret.Get(1).(func([]byte, hash.Hasher, func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) error); ok { - r1 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(1).(func([]byte, hash.Hasher, func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) error); ok { + r1 = returnFunc(bytes, hasher, fn) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewLocal creates a new instance of Local. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLocal(t interface { - mock.TestingT - Cleanup(func()) -}) *Local { - mock := &Local{} - mock.Mock.Test(t) +// Local_SignFunc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SignFunc' +type Local_SignFunc_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SignFunc is a helper method to define mock.On call +// - bytes []byte +// - hasher hash.Hasher +// - fn func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error) +func (_e *Local_Expecter) SignFunc(bytes interface{}, hasher interface{}, fn interface{}) *Local_SignFunc_Call { + return &Local_SignFunc_Call{Call: _e.mock.On("SignFunc", bytes, hasher, fn)} +} - return mock +func (_c *Local_SignFunc_Call) Run(run func(bytes []byte, hasher hash.Hasher, fn func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error))) *Local_SignFunc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 hash.Hasher + if args[1] != nil { + arg1 = args[1].(hash.Hasher) + } + var arg2 func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error) + if args[2] != nil { + arg2 = args[2].(func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Local_SignFunc_Call) Return(signature crypto.Signature, err error) *Local_SignFunc_Call { + _c.Call.Return(signature, err) + return _c +} + +func (_c *Local_SignFunc_Call) RunAndReturn(run func(bytes []byte, hasher hash.Hasher, fn func(crypto.PrivateKey, []byte, hash.Hasher) (crypto.Signature, error)) (crypto.Signature, error)) *Local_SignFunc_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/local_gossip_sub_router_metrics.go b/module/mock/local_gossip_sub_router_metrics.go index 11417d02ba6..416027c49c9 100644 --- a/module/mock/local_gossip_sub_router_metrics.go +++ b/module/mock/local_gossip_sub_router_metrics.go @@ -1,104 +1,694 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewLocalGossipSubRouterMetrics creates a new instance of LocalGossipSubRouterMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLocalGossipSubRouterMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *LocalGossipSubRouterMetrics { + mock := &LocalGossipSubRouterMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // LocalGossipSubRouterMetrics is an autogenerated mock type for the LocalGossipSubRouterMetrics type type LocalGossipSubRouterMetrics struct { mock.Mock } -// OnLocalMeshSizeUpdated provides a mock function with given fields: topic, size -func (_m *LocalGossipSubRouterMetrics) OnLocalMeshSizeUpdated(topic string, size int) { - _m.Called(topic, size) +type LocalGossipSubRouterMetrics_Expecter struct { + mock *mock.Mock } -// OnLocalPeerJoinedTopic provides a mock function with no fields -func (_m *LocalGossipSubRouterMetrics) OnLocalPeerJoinedTopic() { - _m.Called() +func (_m *LocalGossipSubRouterMetrics) EXPECT() *LocalGossipSubRouterMetrics_Expecter { + return &LocalGossipSubRouterMetrics_Expecter{mock: &_m.Mock} } -// OnLocalPeerLeftTopic provides a mock function with no fields -func (_m *LocalGossipSubRouterMetrics) OnLocalPeerLeftTopic() { - _m.Called() +// OnLocalMeshSizeUpdated provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnLocalMeshSizeUpdated(topic string, size int) { + _mock.Called(topic, size) + return } -// OnMessageDeliveredToAllSubscribers provides a mock function with given fields: size -func (_m *LocalGossipSubRouterMetrics) OnMessageDeliveredToAllSubscribers(size int) { - _m.Called(size) +// LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalMeshSizeUpdated' +type LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call struct { + *mock.Call } -// OnMessageDuplicate provides a mock function with given fields: size -func (_m *LocalGossipSubRouterMetrics) OnMessageDuplicate(size int) { - _m.Called(size) +// OnLocalMeshSizeUpdated is a helper method to define mock.On call +// - topic string +// - size int +func (_e *LocalGossipSubRouterMetrics_Expecter) OnLocalMeshSizeUpdated(topic interface{}, size interface{}) *LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call { + return &LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call{Call: _e.mock.On("OnLocalMeshSizeUpdated", topic, size)} } -// OnMessageEnteredValidation provides a mock function with given fields: size -func (_m *LocalGossipSubRouterMetrics) OnMessageEnteredValidation(size int) { - _m.Called(size) +func (_c *LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call) Run(run func(topic string, size int)) *LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnMessageRejected provides a mock function with given fields: size, reason -func (_m *LocalGossipSubRouterMetrics) OnMessageRejected(size int, reason string) { - _m.Called(size, reason) +func (_c *LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call) Return() *LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Return() + return _c } -// OnOutboundRpcDropped provides a mock function with no fields -func (_m *LocalGossipSubRouterMetrics) OnOutboundRpcDropped() { - _m.Called() +func (_c *LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call) RunAndReturn(run func(topic string, size int)) *LocalGossipSubRouterMetrics_OnLocalMeshSizeUpdated_Call { + _c.Run(run) + return _c } -// OnPeerAddedToProtocol provides a mock function with given fields: protocol -func (_m *LocalGossipSubRouterMetrics) OnPeerAddedToProtocol(protocol string) { - _m.Called(protocol) +// OnLocalPeerJoinedTopic provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnLocalPeerJoinedTopic() { + _mock.Called() + return } -// OnPeerGraftTopic provides a mock function with given fields: topic -func (_m *LocalGossipSubRouterMetrics) OnPeerGraftTopic(topic string) { - _m.Called(topic) +// LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerJoinedTopic' +type LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call struct { + *mock.Call } -// OnPeerPruneTopic provides a mock function with given fields: topic -func (_m *LocalGossipSubRouterMetrics) OnPeerPruneTopic(topic string) { - _m.Called(topic) +// OnLocalPeerJoinedTopic is a helper method to define mock.On call +func (_e *LocalGossipSubRouterMetrics_Expecter) OnLocalPeerJoinedTopic() *LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call { + return &LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call{Call: _e.mock.On("OnLocalPeerJoinedTopic")} } -// OnPeerRemovedFromProtocol provides a mock function with no fields -func (_m *LocalGossipSubRouterMetrics) OnPeerRemovedFromProtocol() { - _m.Called() +func (_c *LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call) Run(run func()) *LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnPeerThrottled provides a mock function with no fields -func (_m *LocalGossipSubRouterMetrics) OnPeerThrottled() { - _m.Called() +func (_c *LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call) Return() *LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Return() + return _c } -// OnRpcReceived provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *LocalGossipSubRouterMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +func (_c *LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call) RunAndReturn(run func()) *LocalGossipSubRouterMetrics_OnLocalPeerJoinedTopic_Call { + _c.Run(run) + return _c } -// OnRpcSent provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *LocalGossipSubRouterMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +// OnLocalPeerLeftTopic provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnLocalPeerLeftTopic() { + _mock.Called() + return } -// OnUndeliveredMessage provides a mock function with no fields -func (_m *LocalGossipSubRouterMetrics) OnUndeliveredMessage() { - _m.Called() +// LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerLeftTopic' +type LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call struct { + *mock.Call } -// NewLocalGossipSubRouterMetrics creates a new instance of LocalGossipSubRouterMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLocalGossipSubRouterMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *LocalGossipSubRouterMetrics { - mock := &LocalGossipSubRouterMetrics{} - mock.Mock.Test(t) +// OnLocalPeerLeftTopic is a helper method to define mock.On call +func (_e *LocalGossipSubRouterMetrics_Expecter) OnLocalPeerLeftTopic() *LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call { + return &LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call{Call: _e.mock.On("OnLocalPeerLeftTopic")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call) Run(run func()) *LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call) Return() *LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call) RunAndReturn(run func()) *LocalGossipSubRouterMetrics_OnLocalPeerLeftTopic_Call { + _c.Run(run) + return _c +} + +// OnMessageDeliveredToAllSubscribers provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnMessageDeliveredToAllSubscribers(size int) { + _mock.Called(size) + return +} + +// LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDeliveredToAllSubscribers' +type LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call struct { + *mock.Call +} + +// OnMessageDeliveredToAllSubscribers is a helper method to define mock.On call +// - size int +func (_e *LocalGossipSubRouterMetrics_Expecter) OnMessageDeliveredToAllSubscribers(size interface{}) *LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call { + return &LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call{Call: _e.mock.On("OnMessageDeliveredToAllSubscribers", size)} +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call) Run(run func(size int)) *LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call) Return() *LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call) RunAndReturn(run func(size int)) *LocalGossipSubRouterMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Run(run) + return _c +} + +// OnMessageDuplicate provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnMessageDuplicate(size int) { + _mock.Called(size) + return +} + +// LocalGossipSubRouterMetrics_OnMessageDuplicate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDuplicate' +type LocalGossipSubRouterMetrics_OnMessageDuplicate_Call struct { + *mock.Call +} + +// OnMessageDuplicate is a helper method to define mock.On call +// - size int +func (_e *LocalGossipSubRouterMetrics_Expecter) OnMessageDuplicate(size interface{}) *LocalGossipSubRouterMetrics_OnMessageDuplicate_Call { + return &LocalGossipSubRouterMetrics_OnMessageDuplicate_Call{Call: _e.mock.On("OnMessageDuplicate", size)} +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageDuplicate_Call) Run(run func(size int)) *LocalGossipSubRouterMetrics_OnMessageDuplicate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageDuplicate_Call) Return() *LocalGossipSubRouterMetrics_OnMessageDuplicate_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageDuplicate_Call) RunAndReturn(run func(size int)) *LocalGossipSubRouterMetrics_OnMessageDuplicate_Call { + _c.Run(run) + return _c +} + +// OnMessageEnteredValidation provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnMessageEnteredValidation(size int) { + _mock.Called(size) + return +} + +// LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageEnteredValidation' +type LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call struct { + *mock.Call +} + +// OnMessageEnteredValidation is a helper method to define mock.On call +// - size int +func (_e *LocalGossipSubRouterMetrics_Expecter) OnMessageEnteredValidation(size interface{}) *LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call { + return &LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call{Call: _e.mock.On("OnMessageEnteredValidation", size)} +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call) Run(run func(size int)) *LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call) Return() *LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call) RunAndReturn(run func(size int)) *LocalGossipSubRouterMetrics_OnMessageEnteredValidation_Call { + _c.Run(run) + return _c +} + +// OnMessageRejected provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnMessageRejected(size int, reason string) { + _mock.Called(size, reason) + return +} + +// LocalGossipSubRouterMetrics_OnMessageRejected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageRejected' +type LocalGossipSubRouterMetrics_OnMessageRejected_Call struct { + *mock.Call +} + +// OnMessageRejected is a helper method to define mock.On call +// - size int +// - reason string +func (_e *LocalGossipSubRouterMetrics_Expecter) OnMessageRejected(size interface{}, reason interface{}) *LocalGossipSubRouterMetrics_OnMessageRejected_Call { + return &LocalGossipSubRouterMetrics_OnMessageRejected_Call{Call: _e.mock.On("OnMessageRejected", size, reason)} +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageRejected_Call) Run(run func(size int, reason string)) *LocalGossipSubRouterMetrics_OnMessageRejected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageRejected_Call) Return() *LocalGossipSubRouterMetrics_OnMessageRejected_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnMessageRejected_Call) RunAndReturn(run func(size int, reason string)) *LocalGossipSubRouterMetrics_OnMessageRejected_Call { + _c.Run(run) + return _c +} + +// OnOutboundRpcDropped provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnOutboundRpcDropped() { + _mock.Called() + return +} + +// LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOutboundRpcDropped' +type LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call struct { + *mock.Call +} + +// OnOutboundRpcDropped is a helper method to define mock.On call +func (_e *LocalGossipSubRouterMetrics_Expecter) OnOutboundRpcDropped() *LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call { + return &LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call{Call: _e.mock.On("OnOutboundRpcDropped")} +} + +func (_c *LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call) Run(run func()) *LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call) Return() *LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call) RunAndReturn(run func()) *LocalGossipSubRouterMetrics_OnOutboundRpcDropped_Call { + _c.Run(run) + return _c +} + +// OnPeerAddedToProtocol provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnPeerAddedToProtocol(protocol string) { + _mock.Called(protocol) + return +} + +// LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerAddedToProtocol' +type LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call struct { + *mock.Call +} + +// OnPeerAddedToProtocol is a helper method to define mock.On call +// - protocol string +func (_e *LocalGossipSubRouterMetrics_Expecter) OnPeerAddedToProtocol(protocol interface{}) *LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call { + return &LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call{Call: _e.mock.On("OnPeerAddedToProtocol", protocol)} +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call) Run(run func(protocol string)) *LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call) Return() *LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call) RunAndReturn(run func(protocol string)) *LocalGossipSubRouterMetrics_OnPeerAddedToProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerGraftTopic provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnPeerGraftTopic(topic string) { + _mock.Called(topic) + return +} + +// LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerGraftTopic' +type LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call struct { + *mock.Call +} + +// OnPeerGraftTopic is a helper method to define mock.On call +// - topic string +func (_e *LocalGossipSubRouterMetrics_Expecter) OnPeerGraftTopic(topic interface{}) *LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call { + return &LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call{Call: _e.mock.On("OnPeerGraftTopic", topic)} +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call) Run(run func(topic string)) *LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call) Return() *LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call) RunAndReturn(run func(topic string)) *LocalGossipSubRouterMetrics_OnPeerGraftTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerPruneTopic provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnPeerPruneTopic(topic string) { + _mock.Called(topic) + return +} + +// LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerPruneTopic' +type LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call struct { + *mock.Call +} + +// OnPeerPruneTopic is a helper method to define mock.On call +// - topic string +func (_e *LocalGossipSubRouterMetrics_Expecter) OnPeerPruneTopic(topic interface{}) *LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call { + return &LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call{Call: _e.mock.On("OnPeerPruneTopic", topic)} +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call) Run(run func(topic string)) *LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call) Return() *LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call) RunAndReturn(run func(topic string)) *LocalGossipSubRouterMetrics_OnPeerPruneTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerRemovedFromProtocol provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnPeerRemovedFromProtocol() { + _mock.Called() + return +} + +// LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerRemovedFromProtocol' +type LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call struct { + *mock.Call +} + +// OnPeerRemovedFromProtocol is a helper method to define mock.On call +func (_e *LocalGossipSubRouterMetrics_Expecter) OnPeerRemovedFromProtocol() *LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call { + return &LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call{Call: _e.mock.On("OnPeerRemovedFromProtocol")} +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call) Run(run func()) *LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call) Return() *LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call) RunAndReturn(run func()) *LocalGossipSubRouterMetrics_OnPeerRemovedFromProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerThrottled provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnPeerThrottled() { + _mock.Called() + return +} + +// LocalGossipSubRouterMetrics_OnPeerThrottled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerThrottled' +type LocalGossipSubRouterMetrics_OnPeerThrottled_Call struct { + *mock.Call +} + +// OnPeerThrottled is a helper method to define mock.On call +func (_e *LocalGossipSubRouterMetrics_Expecter) OnPeerThrottled() *LocalGossipSubRouterMetrics_OnPeerThrottled_Call { + return &LocalGossipSubRouterMetrics_OnPeerThrottled_Call{Call: _e.mock.On("OnPeerThrottled")} +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerThrottled_Call) Run(run func()) *LocalGossipSubRouterMetrics_OnPeerThrottled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerThrottled_Call) Return() *LocalGossipSubRouterMetrics_OnPeerThrottled_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnPeerThrottled_Call) RunAndReturn(run func()) *LocalGossipSubRouterMetrics_OnPeerThrottled_Call { + _c.Run(run) + return _c +} + +// OnRpcReceived provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// LocalGossipSubRouterMetrics_OnRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcReceived' +type LocalGossipSubRouterMetrics_OnRpcReceived_Call struct { + *mock.Call +} + +// OnRpcReceived is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *LocalGossipSubRouterMetrics_Expecter) OnRpcReceived(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *LocalGossipSubRouterMetrics_OnRpcReceived_Call { + return &LocalGossipSubRouterMetrics_OnRpcReceived_Call{Call: _e.mock.On("OnRpcReceived", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *LocalGossipSubRouterMetrics_OnRpcReceived_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LocalGossipSubRouterMetrics_OnRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnRpcReceived_Call) Return() *LocalGossipSubRouterMetrics_OnRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnRpcReceived_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LocalGossipSubRouterMetrics_OnRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnRpcSent provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// LocalGossipSubRouterMetrics_OnRpcSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcSent' +type LocalGossipSubRouterMetrics_OnRpcSent_Call struct { + *mock.Call +} + +// OnRpcSent is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *LocalGossipSubRouterMetrics_Expecter) OnRpcSent(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *LocalGossipSubRouterMetrics_OnRpcSent_Call { + return &LocalGossipSubRouterMetrics_OnRpcSent_Call{Call: _e.mock.On("OnRpcSent", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *LocalGossipSubRouterMetrics_OnRpcSent_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LocalGossipSubRouterMetrics_OnRpcSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnRpcSent_Call) Return() *LocalGossipSubRouterMetrics_OnRpcSent_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnRpcSent_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *LocalGossipSubRouterMetrics_OnRpcSent_Call { + _c.Run(run) + return _c +} + +// OnUndeliveredMessage provides a mock function for the type LocalGossipSubRouterMetrics +func (_mock *LocalGossipSubRouterMetrics) OnUndeliveredMessage() { + _mock.Called() + return +} + +// LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUndeliveredMessage' +type LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call struct { + *mock.Call +} + +// OnUndeliveredMessage is a helper method to define mock.On call +func (_e *LocalGossipSubRouterMetrics_Expecter) OnUndeliveredMessage() *LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call { + return &LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call{Call: _e.mock.On("OnUndeliveredMessage")} +} + +func (_c *LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call) Run(run func()) *LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call) Return() *LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call) RunAndReturn(run func()) *LocalGossipSubRouterMetrics_OnUndeliveredMessage_Call { + _c.Run(run) + return _c } diff --git a/module/mock/machine_account_metrics.go b/module/mock/machine_account_metrics.go index c764f0e2f9b..55d7dba5399 100644 --- a/module/mock/machine_account_metrics.go +++ b/module/mock/machine_account_metrics.go @@ -1,39 +1,156 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewMachineAccountMetrics creates a new instance of MachineAccountMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMachineAccountMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *MachineAccountMetrics { + mock := &MachineAccountMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // MachineAccountMetrics is an autogenerated mock type for the MachineAccountMetrics type type MachineAccountMetrics struct { mock.Mock } -// AccountBalance provides a mock function with given fields: bal -func (_m *MachineAccountMetrics) AccountBalance(bal float64) { - _m.Called(bal) +type MachineAccountMetrics_Expecter struct { + mock *mock.Mock } -// IsMisconfigured provides a mock function with given fields: misconfigured -func (_m *MachineAccountMetrics) IsMisconfigured(misconfigured bool) { - _m.Called(misconfigured) +func (_m *MachineAccountMetrics) EXPECT() *MachineAccountMetrics_Expecter { + return &MachineAccountMetrics_Expecter{mock: &_m.Mock} } -// RecommendedMinBalance provides a mock function with given fields: bal -func (_m *MachineAccountMetrics) RecommendedMinBalance(bal float64) { - _m.Called(bal) +// AccountBalance provides a mock function for the type MachineAccountMetrics +func (_mock *MachineAccountMetrics) AccountBalance(bal float64) { + _mock.Called(bal) + return } -// NewMachineAccountMetrics creates a new instance of MachineAccountMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMachineAccountMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *MachineAccountMetrics { - mock := &MachineAccountMetrics{} - mock.Mock.Test(t) +// MachineAccountMetrics_AccountBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AccountBalance' +type MachineAccountMetrics_AccountBalance_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// AccountBalance is a helper method to define mock.On call +// - bal float64 +func (_e *MachineAccountMetrics_Expecter) AccountBalance(bal interface{}) *MachineAccountMetrics_AccountBalance_Call { + return &MachineAccountMetrics_AccountBalance_Call{Call: _e.mock.On("AccountBalance", bal)} +} - return mock +func (_c *MachineAccountMetrics_AccountBalance_Call) Run(run func(bal float64)) *MachineAccountMetrics_AccountBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MachineAccountMetrics_AccountBalance_Call) Return() *MachineAccountMetrics_AccountBalance_Call { + _c.Call.Return() + return _c +} + +func (_c *MachineAccountMetrics_AccountBalance_Call) RunAndReturn(run func(bal float64)) *MachineAccountMetrics_AccountBalance_Call { + _c.Run(run) + return _c +} + +// IsMisconfigured provides a mock function for the type MachineAccountMetrics +func (_mock *MachineAccountMetrics) IsMisconfigured(misconfigured bool) { + _mock.Called(misconfigured) + return +} + +// MachineAccountMetrics_IsMisconfigured_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsMisconfigured' +type MachineAccountMetrics_IsMisconfigured_Call struct { + *mock.Call +} + +// IsMisconfigured is a helper method to define mock.On call +// - misconfigured bool +func (_e *MachineAccountMetrics_Expecter) IsMisconfigured(misconfigured interface{}) *MachineAccountMetrics_IsMisconfigured_Call { + return &MachineAccountMetrics_IsMisconfigured_Call{Call: _e.mock.On("IsMisconfigured", misconfigured)} +} + +func (_c *MachineAccountMetrics_IsMisconfigured_Call) Run(run func(misconfigured bool)) *MachineAccountMetrics_IsMisconfigured_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 bool + if args[0] != nil { + arg0 = args[0].(bool) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MachineAccountMetrics_IsMisconfigured_Call) Return() *MachineAccountMetrics_IsMisconfigured_Call { + _c.Call.Return() + return _c +} + +func (_c *MachineAccountMetrics_IsMisconfigured_Call) RunAndReturn(run func(misconfigured bool)) *MachineAccountMetrics_IsMisconfigured_Call { + _c.Run(run) + return _c +} + +// RecommendedMinBalance provides a mock function for the type MachineAccountMetrics +func (_mock *MachineAccountMetrics) RecommendedMinBalance(bal float64) { + _mock.Called(bal) + return +} + +// MachineAccountMetrics_RecommendedMinBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RecommendedMinBalance' +type MachineAccountMetrics_RecommendedMinBalance_Call struct { + *mock.Call +} + +// RecommendedMinBalance is a helper method to define mock.On call +// - bal float64 +func (_e *MachineAccountMetrics_Expecter) RecommendedMinBalance(bal interface{}) *MachineAccountMetrics_RecommendedMinBalance_Call { + return &MachineAccountMetrics_RecommendedMinBalance_Call{Call: _e.mock.On("RecommendedMinBalance", bal)} +} + +func (_c *MachineAccountMetrics_RecommendedMinBalance_Call) Run(run func(bal float64)) *MachineAccountMetrics_RecommendedMinBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MachineAccountMetrics_RecommendedMinBalance_Call) Return() *MachineAccountMetrics_RecommendedMinBalance_Call { + _c.Call.Return() + return _c +} + +func (_c *MachineAccountMetrics_RecommendedMinBalance_Call) RunAndReturn(run func(bal float64)) *MachineAccountMetrics_RecommendedMinBalance_Call { + _c.Run(run) + return _c } diff --git a/module/mock/mempool_metrics.go b/module/mock/mempool_metrics.go index 60e215820dc..ee0cda5aa75 100644 --- a/module/mock/mempool_metrics.go +++ b/module/mock/mempool_metrics.go @@ -1,50 +1,140 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - module "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module" mock "github.com/stretchr/testify/mock" ) +// NewMempoolMetrics creates a new instance of MempoolMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMempoolMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *MempoolMetrics { + mock := &MempoolMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MempoolMetrics is an autogenerated mock type for the MempoolMetrics type type MempoolMetrics struct { mock.Mock } -// MempoolEntries provides a mock function with given fields: resource, entries -func (_m *MempoolMetrics) MempoolEntries(resource string, entries uint) { - _m.Called(resource, entries) +type MempoolMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *MempoolMetrics) EXPECT() *MempoolMetrics_Expecter { + return &MempoolMetrics_Expecter{mock: &_m.Mock} +} + +// MempoolEntries provides a mock function for the type MempoolMetrics +func (_mock *MempoolMetrics) MempoolEntries(resource string, entries uint) { + _mock.Called(resource, entries) + return } -// Register provides a mock function with given fields: resource, entriesFunc -func (_m *MempoolMetrics) Register(resource string, entriesFunc module.EntriesFunc) error { - ret := _m.Called(resource, entriesFunc) +// MempoolMetrics_MempoolEntries_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MempoolEntries' +type MempoolMetrics_MempoolEntries_Call struct { + *mock.Call +} + +// MempoolEntries is a helper method to define mock.On call +// - resource string +// - entries uint +func (_e *MempoolMetrics_Expecter) MempoolEntries(resource interface{}, entries interface{}) *MempoolMetrics_MempoolEntries_Call { + return &MempoolMetrics_MempoolEntries_Call{Call: _e.mock.On("MempoolEntries", resource, entries)} +} + +func (_c *MempoolMetrics_MempoolEntries_Call) Run(run func(resource string, entries uint)) *MempoolMetrics_MempoolEntries_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint + if args[1] != nil { + arg1 = args[1].(uint) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MempoolMetrics_MempoolEntries_Call) Return() *MempoolMetrics_MempoolEntries_Call { + _c.Call.Return() + return _c +} + +func (_c *MempoolMetrics_MempoolEntries_Call) RunAndReturn(run func(resource string, entries uint)) *MempoolMetrics_MempoolEntries_Call { + _c.Run(run) + return _c +} + +// Register provides a mock function for the type MempoolMetrics +func (_mock *MempoolMetrics) Register(resource string, entriesFunc module.EntriesFunc) error { + ret := _mock.Called(resource, entriesFunc) if len(ret) == 0 { panic("no return value specified for Register") } var r0 error - if rf, ok := ret.Get(0).(func(string, module.EntriesFunc) error); ok { - r0 = rf(resource, entriesFunc) + if returnFunc, ok := ret.Get(0).(func(string, module.EntriesFunc) error); ok { + r0 = returnFunc(resource, entriesFunc) } else { r0 = ret.Error(0) } - return r0 } -// NewMempoolMetrics creates a new instance of MempoolMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMempoolMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *MempoolMetrics { - mock := &MempoolMetrics{} - mock.Mock.Test(t) +// MempoolMetrics_Register_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Register' +type MempoolMetrics_Register_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Register is a helper method to define mock.On call +// - resource string +// - entriesFunc module.EntriesFunc +func (_e *MempoolMetrics_Expecter) Register(resource interface{}, entriesFunc interface{}) *MempoolMetrics_Register_Call { + return &MempoolMetrics_Register_Call{Call: _e.mock.On("Register", resource, entriesFunc)} +} - return mock +func (_c *MempoolMetrics_Register_Call) Run(run func(resource string, entriesFunc module.EntriesFunc)) *MempoolMetrics_Register_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 module.EntriesFunc + if args[1] != nil { + arg1 = args[1].(module.EntriesFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MempoolMetrics_Register_Call) Return(err error) *MempoolMetrics_Register_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MempoolMetrics_Register_Call) RunAndReturn(run func(resource string, entriesFunc module.EntriesFunc) error) *MempoolMetrics_Register_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/network_core_metrics.go b/module/mock/network_core_metrics.go index a391d4f9458..9e0a6a2536a 100644 --- a/module/mock/network_core_metrics.go +++ b/module/mock/network_core_metrics.go @@ -1,100 +1,700 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "time" + + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewNetworkCoreMetrics creates a new instance of NetworkCoreMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNetworkCoreMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *NetworkCoreMetrics { + mock := &NetworkCoreMetrics{} + mock.Mock.Test(t) - time "time" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // NetworkCoreMetrics is an autogenerated mock type for the NetworkCoreMetrics type type NetworkCoreMetrics struct { mock.Mock } -// DuplicateInboundMessagesDropped provides a mock function with given fields: topic, protocol, messageType -func (_m *NetworkCoreMetrics) DuplicateInboundMessagesDropped(topic string, protocol string, messageType string) { - _m.Called(topic, protocol, messageType) +type NetworkCoreMetrics_Expecter struct { + mock *mock.Mock } -// InboundMessageReceived provides a mock function with given fields: sizeBytes, topic, protocol, messageType -func (_m *NetworkCoreMetrics) InboundMessageReceived(sizeBytes int, topic string, protocol string, messageType string) { - _m.Called(sizeBytes, topic, protocol, messageType) +func (_m *NetworkCoreMetrics) EXPECT() *NetworkCoreMetrics_Expecter { + return &NetworkCoreMetrics_Expecter{mock: &_m.Mock} } -// MessageAdded provides a mock function with given fields: priority -func (_m *NetworkCoreMetrics) MessageAdded(priority int) { - _m.Called(priority) +// DuplicateInboundMessagesDropped provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) DuplicateInboundMessagesDropped(topic string, protocol string, messageType string) { + _mock.Called(topic, protocol, messageType) + return } -// MessageProcessingFinished provides a mock function with given fields: topic, duration -func (_m *NetworkCoreMetrics) MessageProcessingFinished(topic string, duration time.Duration) { - _m.Called(topic, duration) +// NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateInboundMessagesDropped' +type NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call struct { + *mock.Call } -// MessageProcessingStarted provides a mock function with given fields: topic -func (_m *NetworkCoreMetrics) MessageProcessingStarted(topic string) { - _m.Called(topic) +// DuplicateInboundMessagesDropped is a helper method to define mock.On call +// - topic string +// - protocol string +// - messageType string +func (_e *NetworkCoreMetrics_Expecter) DuplicateInboundMessagesDropped(topic interface{}, protocol interface{}, messageType interface{}) *NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call { + return &NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call{Call: _e.mock.On("DuplicateInboundMessagesDropped", topic, protocol, messageType)} } -// MessageRemoved provides a mock function with given fields: priority -func (_m *NetworkCoreMetrics) MessageRemoved(priority int) { - _m.Called(priority) +func (_c *NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call) Run(run func(topic string, protocol string, messageType string)) *NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c } -// OnMisbehaviorReported provides a mock function with given fields: channel, misbehaviorType -func (_m *NetworkCoreMetrics) OnMisbehaviorReported(channel string, misbehaviorType string) { - _m.Called(channel, misbehaviorType) +func (_c *NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call) Return() *NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call { + _c.Call.Return() + return _c } -// OnRateLimitedPeer provides a mock function with given fields: pid, role, msgType, topic, reason -func (_m *NetworkCoreMetrics) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { - _m.Called(pid, role, msgType, topic, reason) +func (_c *NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call) RunAndReturn(run func(topic string, protocol string, messageType string)) *NetworkCoreMetrics_DuplicateInboundMessagesDropped_Call { + _c.Run(run) + return _c } -// OnUnauthorizedMessage provides a mock function with given fields: role, msgType, topic, offense -func (_m *NetworkCoreMetrics) OnUnauthorizedMessage(role string, msgType string, topic string, offense string) { - _m.Called(role, msgType, topic, offense) +// InboundMessageReceived provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) InboundMessageReceived(sizeBytes int, topic string, protocol string, messageType string) { + _mock.Called(sizeBytes, topic, protocol, messageType) + return } -// OnViolationReportSkipped provides a mock function with no fields -func (_m *NetworkCoreMetrics) OnViolationReportSkipped() { - _m.Called() +// NetworkCoreMetrics_InboundMessageReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InboundMessageReceived' +type NetworkCoreMetrics_InboundMessageReceived_Call struct { + *mock.Call } -// OutboundMessageSent provides a mock function with given fields: sizeBytes, topic, protocol, messageType -func (_m *NetworkCoreMetrics) OutboundMessageSent(sizeBytes int, topic string, protocol string, messageType string) { - _m.Called(sizeBytes, topic, protocol, messageType) +// InboundMessageReceived is a helper method to define mock.On call +// - sizeBytes int +// - topic string +// - protocol string +// - messageType string +func (_e *NetworkCoreMetrics_Expecter) InboundMessageReceived(sizeBytes interface{}, topic interface{}, protocol interface{}, messageType interface{}) *NetworkCoreMetrics_InboundMessageReceived_Call { + return &NetworkCoreMetrics_InboundMessageReceived_Call{Call: _e.mock.On("InboundMessageReceived", sizeBytes, topic, protocol, messageType)} } -// QueueDuration provides a mock function with given fields: duration, priority -func (_m *NetworkCoreMetrics) QueueDuration(duration time.Duration, priority int) { - _m.Called(duration, priority) +func (_c *NetworkCoreMetrics_InboundMessageReceived_Call) Run(run func(sizeBytes int, topic string, protocol string, messageType string)) *NetworkCoreMetrics_InboundMessageReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c } -// UnicastMessageSendingCompleted provides a mock function with given fields: topic -func (_m *NetworkCoreMetrics) UnicastMessageSendingCompleted(topic string) { - _m.Called(topic) +func (_c *NetworkCoreMetrics_InboundMessageReceived_Call) Return() *NetworkCoreMetrics_InboundMessageReceived_Call { + _c.Call.Return() + return _c } -// UnicastMessageSendingStarted provides a mock function with given fields: topic -func (_m *NetworkCoreMetrics) UnicastMessageSendingStarted(topic string) { - _m.Called(topic) +func (_c *NetworkCoreMetrics_InboundMessageReceived_Call) RunAndReturn(run func(sizeBytes int, topic string, protocol string, messageType string)) *NetworkCoreMetrics_InboundMessageReceived_Call { + _c.Run(run) + return _c } -// NewNetworkCoreMetrics creates a new instance of NetworkCoreMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNetworkCoreMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *NetworkCoreMetrics { - mock := &NetworkCoreMetrics{} - mock.Mock.Test(t) +// MessageAdded provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) MessageAdded(priority int) { + _mock.Called(priority) + return +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NetworkCoreMetrics_MessageAdded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageAdded' +type NetworkCoreMetrics_MessageAdded_Call struct { + *mock.Call +} - return mock +// MessageAdded is a helper method to define mock.On call +// - priority int +func (_e *NetworkCoreMetrics_Expecter) MessageAdded(priority interface{}) *NetworkCoreMetrics_MessageAdded_Call { + return &NetworkCoreMetrics_MessageAdded_Call{Call: _e.mock.On("MessageAdded", priority)} +} + +func (_c *NetworkCoreMetrics_MessageAdded_Call) Run(run func(priority int)) *NetworkCoreMetrics_MessageAdded_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_MessageAdded_Call) Return() *NetworkCoreMetrics_MessageAdded_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_MessageAdded_Call) RunAndReturn(run func(priority int)) *NetworkCoreMetrics_MessageAdded_Call { + _c.Run(run) + return _c +} + +// MessageProcessingFinished provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) MessageProcessingFinished(topic string, duration time.Duration) { + _mock.Called(topic, duration) + return +} + +// NetworkCoreMetrics_MessageProcessingFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageProcessingFinished' +type NetworkCoreMetrics_MessageProcessingFinished_Call struct { + *mock.Call +} + +// MessageProcessingFinished is a helper method to define mock.On call +// - topic string +// - duration time.Duration +func (_e *NetworkCoreMetrics_Expecter) MessageProcessingFinished(topic interface{}, duration interface{}) *NetworkCoreMetrics_MessageProcessingFinished_Call { + return &NetworkCoreMetrics_MessageProcessingFinished_Call{Call: _e.mock.On("MessageProcessingFinished", topic, duration)} +} + +func (_c *NetworkCoreMetrics_MessageProcessingFinished_Call) Run(run func(topic string, duration time.Duration)) *NetworkCoreMetrics_MessageProcessingFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_MessageProcessingFinished_Call) Return() *NetworkCoreMetrics_MessageProcessingFinished_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_MessageProcessingFinished_Call) RunAndReturn(run func(topic string, duration time.Duration)) *NetworkCoreMetrics_MessageProcessingFinished_Call { + _c.Run(run) + return _c +} + +// MessageProcessingStarted provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) MessageProcessingStarted(topic string) { + _mock.Called(topic) + return +} + +// NetworkCoreMetrics_MessageProcessingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageProcessingStarted' +type NetworkCoreMetrics_MessageProcessingStarted_Call struct { + *mock.Call +} + +// MessageProcessingStarted is a helper method to define mock.On call +// - topic string +func (_e *NetworkCoreMetrics_Expecter) MessageProcessingStarted(topic interface{}) *NetworkCoreMetrics_MessageProcessingStarted_Call { + return &NetworkCoreMetrics_MessageProcessingStarted_Call{Call: _e.mock.On("MessageProcessingStarted", topic)} +} + +func (_c *NetworkCoreMetrics_MessageProcessingStarted_Call) Run(run func(topic string)) *NetworkCoreMetrics_MessageProcessingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_MessageProcessingStarted_Call) Return() *NetworkCoreMetrics_MessageProcessingStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_MessageProcessingStarted_Call) RunAndReturn(run func(topic string)) *NetworkCoreMetrics_MessageProcessingStarted_Call { + _c.Run(run) + return _c +} + +// MessageRemoved provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) MessageRemoved(priority int) { + _mock.Called(priority) + return +} + +// NetworkCoreMetrics_MessageRemoved_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageRemoved' +type NetworkCoreMetrics_MessageRemoved_Call struct { + *mock.Call +} + +// MessageRemoved is a helper method to define mock.On call +// - priority int +func (_e *NetworkCoreMetrics_Expecter) MessageRemoved(priority interface{}) *NetworkCoreMetrics_MessageRemoved_Call { + return &NetworkCoreMetrics_MessageRemoved_Call{Call: _e.mock.On("MessageRemoved", priority)} +} + +func (_c *NetworkCoreMetrics_MessageRemoved_Call) Run(run func(priority int)) *NetworkCoreMetrics_MessageRemoved_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_MessageRemoved_Call) Return() *NetworkCoreMetrics_MessageRemoved_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_MessageRemoved_Call) RunAndReturn(run func(priority int)) *NetworkCoreMetrics_MessageRemoved_Call { + _c.Run(run) + return _c +} + +// OnMisbehaviorReported provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) OnMisbehaviorReported(channel string, misbehaviorType string) { + _mock.Called(channel, misbehaviorType) + return +} + +// NetworkCoreMetrics_OnMisbehaviorReported_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMisbehaviorReported' +type NetworkCoreMetrics_OnMisbehaviorReported_Call struct { + *mock.Call +} + +// OnMisbehaviorReported is a helper method to define mock.On call +// - channel string +// - misbehaviorType string +func (_e *NetworkCoreMetrics_Expecter) OnMisbehaviorReported(channel interface{}, misbehaviorType interface{}) *NetworkCoreMetrics_OnMisbehaviorReported_Call { + return &NetworkCoreMetrics_OnMisbehaviorReported_Call{Call: _e.mock.On("OnMisbehaviorReported", channel, misbehaviorType)} +} + +func (_c *NetworkCoreMetrics_OnMisbehaviorReported_Call) Run(run func(channel string, misbehaviorType string)) *NetworkCoreMetrics_OnMisbehaviorReported_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_OnMisbehaviorReported_Call) Return() *NetworkCoreMetrics_OnMisbehaviorReported_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_OnMisbehaviorReported_Call) RunAndReturn(run func(channel string, misbehaviorType string)) *NetworkCoreMetrics_OnMisbehaviorReported_Call { + _c.Run(run) + return _c +} + +// OnRateLimitedPeer provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { + _mock.Called(pid, role, msgType, topic, reason) + return +} + +// NetworkCoreMetrics_OnRateLimitedPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRateLimitedPeer' +type NetworkCoreMetrics_OnRateLimitedPeer_Call struct { + *mock.Call +} + +// OnRateLimitedPeer is a helper method to define mock.On call +// - pid peer.ID +// - role string +// - msgType string +// - topic string +// - reason string +func (_e *NetworkCoreMetrics_Expecter) OnRateLimitedPeer(pid interface{}, role interface{}, msgType interface{}, topic interface{}, reason interface{}) *NetworkCoreMetrics_OnRateLimitedPeer_Call { + return &NetworkCoreMetrics_OnRateLimitedPeer_Call{Call: _e.mock.On("OnRateLimitedPeer", pid, role, msgType, topic, reason)} +} + +func (_c *NetworkCoreMetrics_OnRateLimitedPeer_Call) Run(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *NetworkCoreMetrics_OnRateLimitedPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + var arg4 string + if args[4] != nil { + arg4 = args[4].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_OnRateLimitedPeer_Call) Return() *NetworkCoreMetrics_OnRateLimitedPeer_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_OnRateLimitedPeer_Call) RunAndReturn(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *NetworkCoreMetrics_OnRateLimitedPeer_Call { + _c.Run(run) + return _c +} + +// OnUnauthorizedMessage provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) OnUnauthorizedMessage(role string, msgType string, topic string, offense string) { + _mock.Called(role, msgType, topic, offense) + return +} + +// NetworkCoreMetrics_OnUnauthorizedMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnauthorizedMessage' +type NetworkCoreMetrics_OnUnauthorizedMessage_Call struct { + *mock.Call +} + +// OnUnauthorizedMessage is a helper method to define mock.On call +// - role string +// - msgType string +// - topic string +// - offense string +func (_e *NetworkCoreMetrics_Expecter) OnUnauthorizedMessage(role interface{}, msgType interface{}, topic interface{}, offense interface{}) *NetworkCoreMetrics_OnUnauthorizedMessage_Call { + return &NetworkCoreMetrics_OnUnauthorizedMessage_Call{Call: _e.mock.On("OnUnauthorizedMessage", role, msgType, topic, offense)} +} + +func (_c *NetworkCoreMetrics_OnUnauthorizedMessage_Call) Run(run func(role string, msgType string, topic string, offense string)) *NetworkCoreMetrics_OnUnauthorizedMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_OnUnauthorizedMessage_Call) Return() *NetworkCoreMetrics_OnUnauthorizedMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_OnUnauthorizedMessage_Call) RunAndReturn(run func(role string, msgType string, topic string, offense string)) *NetworkCoreMetrics_OnUnauthorizedMessage_Call { + _c.Run(run) + return _c +} + +// OnViolationReportSkipped provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) OnViolationReportSkipped() { + _mock.Called() + return +} + +// NetworkCoreMetrics_OnViolationReportSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnViolationReportSkipped' +type NetworkCoreMetrics_OnViolationReportSkipped_Call struct { + *mock.Call +} + +// OnViolationReportSkipped is a helper method to define mock.On call +func (_e *NetworkCoreMetrics_Expecter) OnViolationReportSkipped() *NetworkCoreMetrics_OnViolationReportSkipped_Call { + return &NetworkCoreMetrics_OnViolationReportSkipped_Call{Call: _e.mock.On("OnViolationReportSkipped")} +} + +func (_c *NetworkCoreMetrics_OnViolationReportSkipped_Call) Run(run func()) *NetworkCoreMetrics_OnViolationReportSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkCoreMetrics_OnViolationReportSkipped_Call) Return() *NetworkCoreMetrics_OnViolationReportSkipped_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_OnViolationReportSkipped_Call) RunAndReturn(run func()) *NetworkCoreMetrics_OnViolationReportSkipped_Call { + _c.Run(run) + return _c +} + +// OutboundMessageSent provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) OutboundMessageSent(sizeBytes int, topic string, protocol string, messageType string) { + _mock.Called(sizeBytes, topic, protocol, messageType) + return +} + +// NetworkCoreMetrics_OutboundMessageSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OutboundMessageSent' +type NetworkCoreMetrics_OutboundMessageSent_Call struct { + *mock.Call +} + +// OutboundMessageSent is a helper method to define mock.On call +// - sizeBytes int +// - topic string +// - protocol string +// - messageType string +func (_e *NetworkCoreMetrics_Expecter) OutboundMessageSent(sizeBytes interface{}, topic interface{}, protocol interface{}, messageType interface{}) *NetworkCoreMetrics_OutboundMessageSent_Call { + return &NetworkCoreMetrics_OutboundMessageSent_Call{Call: _e.mock.On("OutboundMessageSent", sizeBytes, topic, protocol, messageType)} +} + +func (_c *NetworkCoreMetrics_OutboundMessageSent_Call) Run(run func(sizeBytes int, topic string, protocol string, messageType string)) *NetworkCoreMetrics_OutboundMessageSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_OutboundMessageSent_Call) Return() *NetworkCoreMetrics_OutboundMessageSent_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_OutboundMessageSent_Call) RunAndReturn(run func(sizeBytes int, topic string, protocol string, messageType string)) *NetworkCoreMetrics_OutboundMessageSent_Call { + _c.Run(run) + return _c +} + +// QueueDuration provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) QueueDuration(duration time.Duration, priority int) { + _mock.Called(duration, priority) + return +} + +// NetworkCoreMetrics_QueueDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QueueDuration' +type NetworkCoreMetrics_QueueDuration_Call struct { + *mock.Call +} + +// QueueDuration is a helper method to define mock.On call +// - duration time.Duration +// - priority int +func (_e *NetworkCoreMetrics_Expecter) QueueDuration(duration interface{}, priority interface{}) *NetworkCoreMetrics_QueueDuration_Call { + return &NetworkCoreMetrics_QueueDuration_Call{Call: _e.mock.On("QueueDuration", duration, priority)} +} + +func (_c *NetworkCoreMetrics_QueueDuration_Call) Run(run func(duration time.Duration, priority int)) *NetworkCoreMetrics_QueueDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_QueueDuration_Call) Return() *NetworkCoreMetrics_QueueDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_QueueDuration_Call) RunAndReturn(run func(duration time.Duration, priority int)) *NetworkCoreMetrics_QueueDuration_Call { + _c.Run(run) + return _c +} + +// UnicastMessageSendingCompleted provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) UnicastMessageSendingCompleted(topic string) { + _mock.Called(topic) + return +} + +// NetworkCoreMetrics_UnicastMessageSendingCompleted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnicastMessageSendingCompleted' +type NetworkCoreMetrics_UnicastMessageSendingCompleted_Call struct { + *mock.Call +} + +// UnicastMessageSendingCompleted is a helper method to define mock.On call +// - topic string +func (_e *NetworkCoreMetrics_Expecter) UnicastMessageSendingCompleted(topic interface{}) *NetworkCoreMetrics_UnicastMessageSendingCompleted_Call { + return &NetworkCoreMetrics_UnicastMessageSendingCompleted_Call{Call: _e.mock.On("UnicastMessageSendingCompleted", topic)} +} + +func (_c *NetworkCoreMetrics_UnicastMessageSendingCompleted_Call) Run(run func(topic string)) *NetworkCoreMetrics_UnicastMessageSendingCompleted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_UnicastMessageSendingCompleted_Call) Return() *NetworkCoreMetrics_UnicastMessageSendingCompleted_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_UnicastMessageSendingCompleted_Call) RunAndReturn(run func(topic string)) *NetworkCoreMetrics_UnicastMessageSendingCompleted_Call { + _c.Run(run) + return _c +} + +// UnicastMessageSendingStarted provides a mock function for the type NetworkCoreMetrics +func (_mock *NetworkCoreMetrics) UnicastMessageSendingStarted(topic string) { + _mock.Called(topic) + return +} + +// NetworkCoreMetrics_UnicastMessageSendingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnicastMessageSendingStarted' +type NetworkCoreMetrics_UnicastMessageSendingStarted_Call struct { + *mock.Call +} + +// UnicastMessageSendingStarted is a helper method to define mock.On call +// - topic string +func (_e *NetworkCoreMetrics_Expecter) UnicastMessageSendingStarted(topic interface{}) *NetworkCoreMetrics_UnicastMessageSendingStarted_Call { + return &NetworkCoreMetrics_UnicastMessageSendingStarted_Call{Call: _e.mock.On("UnicastMessageSendingStarted", topic)} +} + +func (_c *NetworkCoreMetrics_UnicastMessageSendingStarted_Call) Run(run func(topic string)) *NetworkCoreMetrics_UnicastMessageSendingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkCoreMetrics_UnicastMessageSendingStarted_Call) Return() *NetworkCoreMetrics_UnicastMessageSendingStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkCoreMetrics_UnicastMessageSendingStarted_Call) RunAndReturn(run func(topic string)) *NetworkCoreMetrics_UnicastMessageSendingStarted_Call { + _c.Run(run) + return _c } diff --git a/module/mock/network_inbound_queue_metrics.go b/module/mock/network_inbound_queue_metrics.go index 090baca793e..7d7b0ba363b 100644 --- a/module/mock/network_inbound_queue_metrics.go +++ b/module/mock/network_inbound_queue_metrics.go @@ -1,43 +1,164 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewNetworkInboundQueueMetrics creates a new instance of NetworkInboundQueueMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNetworkInboundQueueMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *NetworkInboundQueueMetrics { + mock := &NetworkInboundQueueMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // NetworkInboundQueueMetrics is an autogenerated mock type for the NetworkInboundQueueMetrics type type NetworkInboundQueueMetrics struct { mock.Mock } -// MessageAdded provides a mock function with given fields: priority -func (_m *NetworkInboundQueueMetrics) MessageAdded(priority int) { - _m.Called(priority) +type NetworkInboundQueueMetrics_Expecter struct { + mock *mock.Mock } -// MessageRemoved provides a mock function with given fields: priority -func (_m *NetworkInboundQueueMetrics) MessageRemoved(priority int) { - _m.Called(priority) +func (_m *NetworkInboundQueueMetrics) EXPECT() *NetworkInboundQueueMetrics_Expecter { + return &NetworkInboundQueueMetrics_Expecter{mock: &_m.Mock} } -// QueueDuration provides a mock function with given fields: duration, priority -func (_m *NetworkInboundQueueMetrics) QueueDuration(duration time.Duration, priority int) { - _m.Called(duration, priority) +// MessageAdded provides a mock function for the type NetworkInboundQueueMetrics +func (_mock *NetworkInboundQueueMetrics) MessageAdded(priority int) { + _mock.Called(priority) + return } -// NewNetworkInboundQueueMetrics creates a new instance of NetworkInboundQueueMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNetworkInboundQueueMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *NetworkInboundQueueMetrics { - mock := &NetworkInboundQueueMetrics{} - mock.Mock.Test(t) +// NetworkInboundQueueMetrics_MessageAdded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageAdded' +type NetworkInboundQueueMetrics_MessageAdded_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// MessageAdded is a helper method to define mock.On call +// - priority int +func (_e *NetworkInboundQueueMetrics_Expecter) MessageAdded(priority interface{}) *NetworkInboundQueueMetrics_MessageAdded_Call { + return &NetworkInboundQueueMetrics_MessageAdded_Call{Call: _e.mock.On("MessageAdded", priority)} +} - return mock +func (_c *NetworkInboundQueueMetrics_MessageAdded_Call) Run(run func(priority int)) *NetworkInboundQueueMetrics_MessageAdded_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkInboundQueueMetrics_MessageAdded_Call) Return() *NetworkInboundQueueMetrics_MessageAdded_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkInboundQueueMetrics_MessageAdded_Call) RunAndReturn(run func(priority int)) *NetworkInboundQueueMetrics_MessageAdded_Call { + _c.Run(run) + return _c +} + +// MessageRemoved provides a mock function for the type NetworkInboundQueueMetrics +func (_mock *NetworkInboundQueueMetrics) MessageRemoved(priority int) { + _mock.Called(priority) + return +} + +// NetworkInboundQueueMetrics_MessageRemoved_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageRemoved' +type NetworkInboundQueueMetrics_MessageRemoved_Call struct { + *mock.Call +} + +// MessageRemoved is a helper method to define mock.On call +// - priority int +func (_e *NetworkInboundQueueMetrics_Expecter) MessageRemoved(priority interface{}) *NetworkInboundQueueMetrics_MessageRemoved_Call { + return &NetworkInboundQueueMetrics_MessageRemoved_Call{Call: _e.mock.On("MessageRemoved", priority)} +} + +func (_c *NetworkInboundQueueMetrics_MessageRemoved_Call) Run(run func(priority int)) *NetworkInboundQueueMetrics_MessageRemoved_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkInboundQueueMetrics_MessageRemoved_Call) Return() *NetworkInboundQueueMetrics_MessageRemoved_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkInboundQueueMetrics_MessageRemoved_Call) RunAndReturn(run func(priority int)) *NetworkInboundQueueMetrics_MessageRemoved_Call { + _c.Run(run) + return _c +} + +// QueueDuration provides a mock function for the type NetworkInboundQueueMetrics +func (_mock *NetworkInboundQueueMetrics) QueueDuration(duration time.Duration, priority int) { + _mock.Called(duration, priority) + return +} + +// NetworkInboundQueueMetrics_QueueDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QueueDuration' +type NetworkInboundQueueMetrics_QueueDuration_Call struct { + *mock.Call +} + +// QueueDuration is a helper method to define mock.On call +// - duration time.Duration +// - priority int +func (_e *NetworkInboundQueueMetrics_Expecter) QueueDuration(duration interface{}, priority interface{}) *NetworkInboundQueueMetrics_QueueDuration_Call { + return &NetworkInboundQueueMetrics_QueueDuration_Call{Call: _e.mock.On("QueueDuration", duration, priority)} +} + +func (_c *NetworkInboundQueueMetrics_QueueDuration_Call) Run(run func(duration time.Duration, priority int)) *NetworkInboundQueueMetrics_QueueDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkInboundQueueMetrics_QueueDuration_Call) Return() *NetworkInboundQueueMetrics_QueueDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkInboundQueueMetrics_QueueDuration_Call) RunAndReturn(run func(duration time.Duration, priority int)) *NetworkInboundQueueMetrics_QueueDuration_Call { + _c.Run(run) + return _c } diff --git a/module/mock/network_metrics.go b/module/mock/network_metrics.go index a5bab21f319..ee118e026c5 100644 --- a/module/mock/network_metrics.go +++ b/module/mock/network_metrics.go @@ -1,547 +1,4261 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" - mock "github.com/stretchr/testify/mock" - - network "github.com/libp2p/go-libp2p/core/network" + "time" - p2pmsg "github.com/onflow/flow-go/network/p2p/message" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p/message" + mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewNetworkMetrics creates a new instance of NetworkMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNetworkMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *NetworkMetrics { + mock := &NetworkMetrics{} + mock.Mock.Test(t) - protocol "github.com/libp2p/go-libp2p/core/protocol" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // NetworkMetrics is an autogenerated mock type for the NetworkMetrics type type NetworkMetrics struct { mock.Mock } -// AllowConn provides a mock function with given fields: dir, usefd -func (_m *NetworkMetrics) AllowConn(dir network.Direction, usefd bool) { - _m.Called(dir, usefd) +type NetworkMetrics_Expecter struct { + mock *mock.Mock } -// AllowMemory provides a mock function with given fields: size -func (_m *NetworkMetrics) AllowMemory(size int) { - _m.Called(size) +func (_m *NetworkMetrics) EXPECT() *NetworkMetrics_Expecter { + return &NetworkMetrics_Expecter{mock: &_m.Mock} } -// AllowPeer provides a mock function with given fields: p -func (_m *NetworkMetrics) AllowPeer(p peer.ID) { - _m.Called(p) +// AllowConn provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AllowConn(dir network.Direction, usefd bool) { + _mock.Called(dir, usefd) + return } -// AllowProtocol provides a mock function with given fields: proto -func (_m *NetworkMetrics) AllowProtocol(proto protocol.ID) { - _m.Called(proto) +// NetworkMetrics_AllowConn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowConn' +type NetworkMetrics_AllowConn_Call struct { + *mock.Call } -// AllowService provides a mock function with given fields: svc -func (_m *NetworkMetrics) AllowService(svc string) { - _m.Called(svc) +// AllowConn is a helper method to define mock.On call +// - dir network.Direction +// - usefd bool +func (_e *NetworkMetrics_Expecter) AllowConn(dir interface{}, usefd interface{}) *NetworkMetrics_AllowConn_Call { + return &NetworkMetrics_AllowConn_Call{Call: _e.mock.On("AllowConn", dir, usefd)} } -// AllowStream provides a mock function with given fields: p, dir -func (_m *NetworkMetrics) AllowStream(p peer.ID, dir network.Direction) { - _m.Called(p, dir) +func (_c *NetworkMetrics_AllowConn_Call) Run(run func(dir network.Direction, usefd bool)) *NetworkMetrics_AllowConn_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.Direction + if args[0] != nil { + arg0 = args[0].(network.Direction) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c } -// AsyncProcessingFinished provides a mock function with given fields: duration -func (_m *NetworkMetrics) AsyncProcessingFinished(duration time.Duration) { - _m.Called(duration) +func (_c *NetworkMetrics_AllowConn_Call) Return() *NetworkMetrics_AllowConn_Call { + _c.Call.Return() + return _c } -// AsyncProcessingStarted provides a mock function with no fields -func (_m *NetworkMetrics) AsyncProcessingStarted() { - _m.Called() +func (_c *NetworkMetrics_AllowConn_Call) RunAndReturn(run func(dir network.Direction, usefd bool)) *NetworkMetrics_AllowConn_Call { + _c.Run(run) + return _c } -// BlockConn provides a mock function with given fields: dir, usefd -func (_m *NetworkMetrics) BlockConn(dir network.Direction, usefd bool) { - _m.Called(dir, usefd) +// AllowMemory provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AllowMemory(size int) { + _mock.Called(size) + return } -// BlockMemory provides a mock function with given fields: size -func (_m *NetworkMetrics) BlockMemory(size int) { - _m.Called(size) +// NetworkMetrics_AllowMemory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowMemory' +type NetworkMetrics_AllowMemory_Call struct { + *mock.Call } -// BlockPeer provides a mock function with given fields: p -func (_m *NetworkMetrics) BlockPeer(p peer.ID) { - _m.Called(p) +// AllowMemory is a helper method to define mock.On call +// - size int +func (_e *NetworkMetrics_Expecter) AllowMemory(size interface{}) *NetworkMetrics_AllowMemory_Call { + return &NetworkMetrics_AllowMemory_Call{Call: _e.mock.On("AllowMemory", size)} } -// BlockProtocol provides a mock function with given fields: proto -func (_m *NetworkMetrics) BlockProtocol(proto protocol.ID) { - _m.Called(proto) +func (_c *NetworkMetrics_AllowMemory_Call) Run(run func(size int)) *NetworkMetrics_AllowMemory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c } -// BlockProtocolPeer provides a mock function with given fields: proto, p -func (_m *NetworkMetrics) BlockProtocolPeer(proto protocol.ID, p peer.ID) { - _m.Called(proto, p) +func (_c *NetworkMetrics_AllowMemory_Call) Return() *NetworkMetrics_AllowMemory_Call { + _c.Call.Return() + return _c } -// BlockService provides a mock function with given fields: svc -func (_m *NetworkMetrics) BlockService(svc string) { - _m.Called(svc) +func (_c *NetworkMetrics_AllowMemory_Call) RunAndReturn(run func(size int)) *NetworkMetrics_AllowMemory_Call { + _c.Run(run) + return _c } -// BlockServicePeer provides a mock function with given fields: svc, p -func (_m *NetworkMetrics) BlockServicePeer(svc string, p peer.ID) { - _m.Called(svc, p) +// AllowPeer provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AllowPeer(p peer.ID) { + _mock.Called(p) + return } -// BlockStream provides a mock function with given fields: p, dir -func (_m *NetworkMetrics) BlockStream(p peer.ID, dir network.Direction) { - _m.Called(p, dir) +// NetworkMetrics_AllowPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowPeer' +type NetworkMetrics_AllowPeer_Call struct { + *mock.Call } -// DNSLookupDuration provides a mock function with given fields: duration -func (_m *NetworkMetrics) DNSLookupDuration(duration time.Duration) { - _m.Called(duration) +// AllowPeer is a helper method to define mock.On call +// - p peer.ID +func (_e *NetworkMetrics_Expecter) AllowPeer(p interface{}) *NetworkMetrics_AllowPeer_Call { + return &NetworkMetrics_AllowPeer_Call{Call: _e.mock.On("AllowPeer", p)} } -// DuplicateInboundMessagesDropped provides a mock function with given fields: topic, _a1, messageType -func (_m *NetworkMetrics) DuplicateInboundMessagesDropped(topic string, _a1 string, messageType string) { - _m.Called(topic, _a1, messageType) +func (_c *NetworkMetrics_AllowPeer_Call) Run(run func(p peer.ID)) *NetworkMetrics_AllowPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c } -// DuplicateMessagePenalties provides a mock function with given fields: penalty -func (_m *NetworkMetrics) DuplicateMessagePenalties(penalty float64) { - _m.Called(penalty) +func (_c *NetworkMetrics_AllowPeer_Call) Return() *NetworkMetrics_AllowPeer_Call { + _c.Call.Return() + return _c } -// DuplicateMessagesCounts provides a mock function with given fields: count -func (_m *NetworkMetrics) DuplicateMessagesCounts(count float64) { - _m.Called(count) +func (_c *NetworkMetrics_AllowPeer_Call) RunAndReturn(run func(p peer.ID)) *NetworkMetrics_AllowPeer_Call { + _c.Run(run) + return _c } -// InboundConnections provides a mock function with given fields: connectionCount -func (_m *NetworkMetrics) InboundConnections(connectionCount uint) { - _m.Called(connectionCount) +// AllowProtocol provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AllowProtocol(proto protocol.ID) { + _mock.Called(proto) + return } -// InboundMessageReceived provides a mock function with given fields: sizeBytes, topic, _a2, messageType -func (_m *NetworkMetrics) InboundMessageReceived(sizeBytes int, topic string, _a2 string, messageType string) { - _m.Called(sizeBytes, topic, _a2, messageType) +// NetworkMetrics_AllowProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowProtocol' +type NetworkMetrics_AllowProtocol_Call struct { + *mock.Call } -// MessageAdded provides a mock function with given fields: priority -func (_m *NetworkMetrics) MessageAdded(priority int) { - _m.Called(priority) +// AllowProtocol is a helper method to define mock.On call +// - proto protocol.ID +func (_e *NetworkMetrics_Expecter) AllowProtocol(proto interface{}) *NetworkMetrics_AllowProtocol_Call { + return &NetworkMetrics_AllowProtocol_Call{Call: _e.mock.On("AllowProtocol", proto)} } -// MessageProcessingFinished provides a mock function with given fields: topic, duration -func (_m *NetworkMetrics) MessageProcessingFinished(topic string, duration time.Duration) { - _m.Called(topic, duration) +func (_c *NetworkMetrics_AllowProtocol_Call) Run(run func(proto protocol.ID)) *NetworkMetrics_AllowProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + run( + arg0, + ) + }) + return _c } -// MessageProcessingStarted provides a mock function with given fields: topic -func (_m *NetworkMetrics) MessageProcessingStarted(topic string) { - _m.Called(topic) +func (_c *NetworkMetrics_AllowProtocol_Call) Return() *NetworkMetrics_AllowProtocol_Call { + _c.Call.Return() + return _c } -// MessageRemoved provides a mock function with given fields: priority -func (_m *NetworkMetrics) MessageRemoved(priority int) { - _m.Called(priority) +func (_c *NetworkMetrics_AllowProtocol_Call) RunAndReturn(run func(proto protocol.ID)) *NetworkMetrics_AllowProtocol_Call { + _c.Run(run) + return _c } -// OnActiveClusterIDsNotSetErr provides a mock function with no fields -func (_m *NetworkMetrics) OnActiveClusterIDsNotSetErr() { - _m.Called() +// AllowService provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AllowService(svc string) { + _mock.Called(svc) + return } -// OnAppSpecificScoreUpdated provides a mock function with given fields: _a0 -func (_m *NetworkMetrics) OnAppSpecificScoreUpdated(_a0 float64) { - _m.Called(_a0) +// NetworkMetrics_AllowService_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowService' +type NetworkMetrics_AllowService_Call struct { + *mock.Call } -// OnBehaviourPenaltyUpdated provides a mock function with given fields: _a0 -func (_m *NetworkMetrics) OnBehaviourPenaltyUpdated(_a0 float64) { - _m.Called(_a0) +// AllowService is a helper method to define mock.On call +// - svc string +func (_e *NetworkMetrics_Expecter) AllowService(svc interface{}) *NetworkMetrics_AllowService_Call { + return &NetworkMetrics_AllowService_Call{Call: _e.mock.On("AllowService", svc)} } -// OnControlMessagesTruncated provides a mock function with given fields: messageType, diff -func (_m *NetworkMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { - _m.Called(messageType, diff) +func (_c *NetworkMetrics_AllowService_Call) Run(run func(svc string)) *NetworkMetrics_AllowService_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c } -// OnDNSCacheHit provides a mock function with no fields -func (_m *NetworkMetrics) OnDNSCacheHit() { - _m.Called() +func (_c *NetworkMetrics_AllowService_Call) Return() *NetworkMetrics_AllowService_Call { + _c.Call.Return() + return _c } -// OnDNSCacheInvalidated provides a mock function with no fields -func (_m *NetworkMetrics) OnDNSCacheInvalidated() { - _m.Called() +func (_c *NetworkMetrics_AllowService_Call) RunAndReturn(run func(svc string)) *NetworkMetrics_AllowService_Call { + _c.Run(run) + return _c } -// OnDNSCacheMiss provides a mock function with no fields -func (_m *NetworkMetrics) OnDNSCacheMiss() { - _m.Called() +// AllowStream provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AllowStream(p peer.ID, dir network.Direction) { + _mock.Called(p, dir) + return } -// OnDNSLookupRequestDropped provides a mock function with no fields -func (_m *NetworkMetrics) OnDNSLookupRequestDropped() { - _m.Called() +// NetworkMetrics_AllowStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowStream' +type NetworkMetrics_AllowStream_Call struct { + *mock.Call } -// OnDialRetryBudgetResetToDefault provides a mock function with no fields -func (_m *NetworkMetrics) OnDialRetryBudgetResetToDefault() { - _m.Called() +// AllowStream is a helper method to define mock.On call +// - p peer.ID +// - dir network.Direction +func (_e *NetworkMetrics_Expecter) AllowStream(p interface{}, dir interface{}) *NetworkMetrics_AllowStream_Call { + return &NetworkMetrics_AllowStream_Call{Call: _e.mock.On("AllowStream", p, dir)} } -// OnDialRetryBudgetUpdated provides a mock function with given fields: budget -func (_m *NetworkMetrics) OnDialRetryBudgetUpdated(budget uint64) { - _m.Called(budget) +func (_c *NetworkMetrics_AllowStream_Call) Run(run func(p peer.ID, dir network.Direction)) *NetworkMetrics_AllowStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.Direction + if args[1] != nil { + arg1 = args[1].(network.Direction) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnEstablishStreamFailure provides a mock function with given fields: duration, attempts -func (_m *NetworkMetrics) OnEstablishStreamFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +func (_c *NetworkMetrics_AllowStream_Call) Return() *NetworkMetrics_AllowStream_Call { + _c.Call.Return() + return _c } -// OnFirstMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *NetworkMetrics) OnFirstMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *NetworkMetrics_AllowStream_Call) RunAndReturn(run func(p peer.ID, dir network.Direction)) *NetworkMetrics_AllowStream_Call { + _c.Run(run) + return _c } -// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { - _m.Called() +// AsyncProcessingFinished provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AsyncProcessingFinished(duration time.Duration) { + _mock.Called(duration) + return } -// OnGraftInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnGraftInvalidTopicIdsExceedThreshold() { - _m.Called() +// NetworkMetrics_AsyncProcessingFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingFinished' +type NetworkMetrics_AsyncProcessingFinished_Call struct { + *mock.Call } -// OnGraftMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *NetworkMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +// AsyncProcessingFinished is a helper method to define mock.On call +// - duration time.Duration +func (_e *NetworkMetrics_Expecter) AsyncProcessingFinished(duration interface{}) *NetworkMetrics_AsyncProcessingFinished_Call { + return &NetworkMetrics_AsyncProcessingFinished_Call{Call: _e.mock.On("AsyncProcessingFinished", duration)} } -// OnIHaveControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *NetworkMetrics) OnIHaveControlMessageIdsTruncated(diff int) { - _m.Called(diff) +func (_c *NetworkMetrics_AsyncProcessingFinished_Call) Run(run func(duration time.Duration)) *NetworkMetrics_AsyncProcessingFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { - _m.Called() +func (_c *NetworkMetrics_AsyncProcessingFinished_Call) Return() *NetworkMetrics_AsyncProcessingFinished_Call { + _c.Call.Return() + return _c } -// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { - _m.Called() +func (_c *NetworkMetrics_AsyncProcessingFinished_Call) RunAndReturn(run func(duration time.Duration)) *NetworkMetrics_AsyncProcessingFinished_Call { + _c.Run(run) + return _c } -// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { - _m.Called() +// AsyncProcessingStarted provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) AsyncProcessingStarted() { + _mock.Called() + return } -// OnIHaveMessageIDsReceived provides a mock function with given fields: channel, msgIdCount -func (_m *NetworkMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { - _m.Called(channel, msgIdCount) +// NetworkMetrics_AsyncProcessingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AsyncProcessingStarted' +type NetworkMetrics_AsyncProcessingStarted_Call struct { + *mock.Call } -// OnIHaveMessagesInspected provides a mock function with given fields: duplicateTopicIds, duplicateMessageIds, invalidTopicIds -func (_m *NetworkMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) +// AsyncProcessingStarted is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) AsyncProcessingStarted() *NetworkMetrics_AsyncProcessingStarted_Call { + return &NetworkMetrics_AsyncProcessingStarted_Call{Call: _e.mock.On("AsyncProcessingStarted")} } -// OnIPColocationFactorUpdated provides a mock function with given fields: _a0 -func (_m *NetworkMetrics) OnIPColocationFactorUpdated(_a0 float64) { - _m.Called(_a0) +func (_c *NetworkMetrics_AsyncProcessingStarted_Call) Run(run func()) *NetworkMetrics_AsyncProcessingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { - _m.Called() +func (_c *NetworkMetrics_AsyncProcessingStarted_Call) Return() *NetworkMetrics_AsyncProcessingStarted_Call { + _c.Call.Return() + return _c } -// OnIWantControlMessageIdsTruncated provides a mock function with given fields: diff -func (_m *NetworkMetrics) OnIWantControlMessageIdsTruncated(diff int) { - _m.Called(diff) +func (_c *NetworkMetrics_AsyncProcessingStarted_Call) RunAndReturn(run func()) *NetworkMetrics_AsyncProcessingStarted_Call { + _c.Run(run) + return _c } -// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { - _m.Called() +// BlockConn provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockConn(dir network.Direction, usefd bool) { + _mock.Called(dir, usefd) + return } -// OnIWantMessageIDsReceived provides a mock function with given fields: msgIdCount -func (_m *NetworkMetrics) OnIWantMessageIDsReceived(msgIdCount int) { - _m.Called(msgIdCount) +// NetworkMetrics_BlockConn_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockConn' +type NetworkMetrics_BlockConn_Call struct { + *mock.Call } -// OnIWantMessagesInspected provides a mock function with given fields: duplicateCount, cacheMissCount -func (_m *NetworkMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { - _m.Called(duplicateCount, cacheMissCount) +// BlockConn is a helper method to define mock.On call +// - dir network.Direction +// - usefd bool +func (_e *NetworkMetrics_Expecter) BlockConn(dir interface{}, usefd interface{}) *NetworkMetrics_BlockConn_Call { + return &NetworkMetrics_BlockConn_Call{Call: _e.mock.On("BlockConn", dir, usefd)} } -// OnIncomingRpcReceived provides a mock function with given fields: iHaveCount, iWantCount, graftCount, pruneCount, msgCount -func (_m *NetworkMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { - _m.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) +func (_c *NetworkMetrics_BlockConn_Call) Run(run func(dir network.Direction, usefd bool)) *NetworkMetrics_BlockConn_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.Direction + if args[0] != nil { + arg0 = args[0].(network.Direction) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnInvalidControlMessageNotificationSent provides a mock function with no fields -func (_m *NetworkMetrics) OnInvalidControlMessageNotificationSent() { - _m.Called() +func (_c *NetworkMetrics_BlockConn_Call) Return() *NetworkMetrics_BlockConn_Call { + _c.Call.Return() + return _c } -// OnInvalidMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *NetworkMetrics) OnInvalidMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *NetworkMetrics_BlockConn_Call) RunAndReturn(run func(dir network.Direction, usefd bool)) *NetworkMetrics_BlockConn_Call { + _c.Run(run) + return _c } -// OnInvalidTopicIdDetectedForControlMessage provides a mock function with given fields: messageType -func (_m *NetworkMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { - _m.Called(messageType) +// BlockMemory provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockMemory(size int) { + _mock.Called(size) + return } -// OnLocalMeshSizeUpdated provides a mock function with given fields: topic, size -func (_m *NetworkMetrics) OnLocalMeshSizeUpdated(topic string, size int) { - _m.Called(topic, size) +// NetworkMetrics_BlockMemory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockMemory' +type NetworkMetrics_BlockMemory_Call struct { + *mock.Call } -// OnLocalPeerJoinedTopic provides a mock function with no fields -func (_m *NetworkMetrics) OnLocalPeerJoinedTopic() { - _m.Called() +// BlockMemory is a helper method to define mock.On call +// - size int +func (_e *NetworkMetrics_Expecter) BlockMemory(size interface{}) *NetworkMetrics_BlockMemory_Call { + return &NetworkMetrics_BlockMemory_Call{Call: _e.mock.On("BlockMemory", size)} } -// OnLocalPeerLeftTopic provides a mock function with no fields -func (_m *NetworkMetrics) OnLocalPeerLeftTopic() { - _m.Called() +func (_c *NetworkMetrics_BlockMemory_Call) Run(run func(size int)) *NetworkMetrics_BlockMemory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c } -// OnMeshMessageDeliveredUpdated provides a mock function with given fields: _a0, _a1 -func (_m *NetworkMetrics) OnMeshMessageDeliveredUpdated(_a0 channels.Topic, _a1 float64) { - _m.Called(_a0, _a1) +func (_c *NetworkMetrics_BlockMemory_Call) Return() *NetworkMetrics_BlockMemory_Call { + _c.Call.Return() + return _c } -// OnMessageDeliveredToAllSubscribers provides a mock function with given fields: size -func (_m *NetworkMetrics) OnMessageDeliveredToAllSubscribers(size int) { - _m.Called(size) +func (_c *NetworkMetrics_BlockMemory_Call) RunAndReturn(run func(size int)) *NetworkMetrics_BlockMemory_Call { + _c.Run(run) + return _c } -// OnMessageDuplicate provides a mock function with given fields: size -func (_m *NetworkMetrics) OnMessageDuplicate(size int) { - _m.Called(size) +// BlockPeer provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockPeer(p peer.ID) { + _mock.Called(p) + return } -// OnMessageEnteredValidation provides a mock function with given fields: size -func (_m *NetworkMetrics) OnMessageEnteredValidation(size int) { - _m.Called(size) +// NetworkMetrics_BlockPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockPeer' +type NetworkMetrics_BlockPeer_Call struct { + *mock.Call } -// OnMessageRejected provides a mock function with given fields: size, reason -func (_m *NetworkMetrics) OnMessageRejected(size int, reason string) { - _m.Called(size, reason) +// BlockPeer is a helper method to define mock.On call +// - p peer.ID +func (_e *NetworkMetrics_Expecter) BlockPeer(p interface{}) *NetworkMetrics_BlockPeer_Call { + return &NetworkMetrics_BlockPeer_Call{Call: _e.mock.On("BlockPeer", p)} } -// OnMisbehaviorReported provides a mock function with given fields: channel, misbehaviorType -func (_m *NetworkMetrics) OnMisbehaviorReported(channel string, misbehaviorType string) { - _m.Called(channel, misbehaviorType) +func (_c *NetworkMetrics_BlockPeer_Call) Run(run func(p peer.ID)) *NetworkMetrics_BlockPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c } -// OnOutboundRpcDropped provides a mock function with no fields -func (_m *NetworkMetrics) OnOutboundRpcDropped() { - _m.Called() +func (_c *NetworkMetrics_BlockPeer_Call) Return() *NetworkMetrics_BlockPeer_Call { + _c.Call.Return() + return _c } -// OnOverallPeerScoreUpdated provides a mock function with given fields: _a0 -func (_m *NetworkMetrics) OnOverallPeerScoreUpdated(_a0 float64) { - _m.Called(_a0) +func (_c *NetworkMetrics_BlockPeer_Call) RunAndReturn(run func(p peer.ID)) *NetworkMetrics_BlockPeer_Call { + _c.Run(run) + return _c } -// OnPeerAddedToProtocol provides a mock function with given fields: _a0 -func (_m *NetworkMetrics) OnPeerAddedToProtocol(_a0 string) { - _m.Called(_a0) +// BlockProtocol provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockProtocol(proto protocol.ID) { + _mock.Called(proto) + return } -// OnPeerDialFailure provides a mock function with given fields: duration, attempts -func (_m *NetworkMetrics) OnPeerDialFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// NetworkMetrics_BlockProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProtocol' +type NetworkMetrics_BlockProtocol_Call struct { + *mock.Call } -// OnPeerDialed provides a mock function with given fields: duration, attempts -func (_m *NetworkMetrics) OnPeerDialed(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// BlockProtocol is a helper method to define mock.On call +// - proto protocol.ID +func (_e *NetworkMetrics_Expecter) BlockProtocol(proto interface{}) *NetworkMetrics_BlockProtocol_Call { + return &NetworkMetrics_BlockProtocol_Call{Call: _e.mock.On("BlockProtocol", proto)} } -// OnPeerGraftTopic provides a mock function with given fields: topic -func (_m *NetworkMetrics) OnPeerGraftTopic(topic string) { - _m.Called(topic) +func (_c *NetworkMetrics_BlockProtocol_Call) Run(run func(proto protocol.ID)) *NetworkMetrics_BlockProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + run( + arg0, + ) + }) + return _c } -// OnPeerPruneTopic provides a mock function with given fields: topic -func (_m *NetworkMetrics) OnPeerPruneTopic(topic string) { - _m.Called(topic) +func (_c *NetworkMetrics_BlockProtocol_Call) Return() *NetworkMetrics_BlockProtocol_Call { + _c.Call.Return() + return _c } -// OnPeerRemovedFromProtocol provides a mock function with no fields -func (_m *NetworkMetrics) OnPeerRemovedFromProtocol() { - _m.Called() +func (_c *NetworkMetrics_BlockProtocol_Call) RunAndReturn(run func(proto protocol.ID)) *NetworkMetrics_BlockProtocol_Call { + _c.Run(run) + return _c } -// OnPeerThrottled provides a mock function with no fields -func (_m *NetworkMetrics) OnPeerThrottled() { - _m.Called() +// BlockProtocolPeer provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockProtocolPeer(proto protocol.ID, p peer.ID) { + _mock.Called(proto, p) + return } -// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { - _m.Called() +// NetworkMetrics_BlockProtocolPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProtocolPeer' +type NetworkMetrics_BlockProtocolPeer_Call struct { + *mock.Call } -// OnPruneInvalidTopicIdsExceedThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnPruneInvalidTopicIdsExceedThreshold() { - _m.Called() +// BlockProtocolPeer is a helper method to define mock.On call +// - proto protocol.ID +// - p peer.ID +func (_e *NetworkMetrics_Expecter) BlockProtocolPeer(proto interface{}, p interface{}) *NetworkMetrics_BlockProtocolPeer_Call { + return &NetworkMetrics_BlockProtocolPeer_Call{Call: _e.mock.On("BlockProtocolPeer", proto, p)} } -// OnPruneMessageInspected provides a mock function with given fields: duplicateTopicIds, invalidTopicIds -func (_m *NetworkMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { - _m.Called(duplicateTopicIds, invalidTopicIds) +func (_c *NetworkMetrics_BlockProtocolPeer_Call) Run(run func(proto protocol.ID, p peer.ID)) *NetworkMetrics_BlockProtocolPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnPublishMessageInspected provides a mock function with given fields: totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount -func (_m *NetworkMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { - _m.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) +func (_c *NetworkMetrics_BlockProtocolPeer_Call) Return() *NetworkMetrics_BlockProtocolPeer_Call { + _c.Call.Return() + return _c } -// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function with no fields -func (_m *NetworkMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { - _m.Called() +func (_c *NetworkMetrics_BlockProtocolPeer_Call) RunAndReturn(run func(proto protocol.ID, p peer.ID)) *NetworkMetrics_BlockProtocolPeer_Call { + _c.Run(run) + return _c } -// OnRateLimitedPeer provides a mock function with given fields: pid, role, msgType, topic, reason -func (_m *NetworkMetrics) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { - _m.Called(pid, role, msgType, topic, reason) +// BlockService provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockService(svc string) { + _mock.Called(svc) + return } -// OnRpcReceived provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *NetworkMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +// NetworkMetrics_BlockService_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockService' +type NetworkMetrics_BlockService_Call struct { + *mock.Call } -// OnRpcRejectedFromUnknownSender provides a mock function with no fields -func (_m *NetworkMetrics) OnRpcRejectedFromUnknownSender() { - _m.Called() +// BlockService is a helper method to define mock.On call +// - svc string +func (_e *NetworkMetrics_Expecter) BlockService(svc interface{}) *NetworkMetrics_BlockService_Call { + return &NetworkMetrics_BlockService_Call{Call: _e.mock.On("BlockService", svc)} } -// OnRpcSent provides a mock function with given fields: msgCount, iHaveCount, iWantCount, graftCount, pruneCount -func (_m *NetworkMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { - _m.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) +func (_c *NetworkMetrics_BlockService_Call) Run(run func(svc string)) *NetworkMetrics_BlockService_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c } -// OnStreamCreated provides a mock function with given fields: duration, attempts -func (_m *NetworkMetrics) OnStreamCreated(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +func (_c *NetworkMetrics_BlockService_Call) Return() *NetworkMetrics_BlockService_Call { + _c.Call.Return() + return _c } -// OnStreamCreationFailure provides a mock function with given fields: duration, attempts -func (_m *NetworkMetrics) OnStreamCreationFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +func (_c *NetworkMetrics_BlockService_Call) RunAndReturn(run func(svc string)) *NetworkMetrics_BlockService_Call { + _c.Run(run) + return _c } -// OnStreamCreationRetryBudgetResetToDefault provides a mock function with no fields -func (_m *NetworkMetrics) OnStreamCreationRetryBudgetResetToDefault() { - _m.Called() +// BlockServicePeer provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockServicePeer(svc string, p peer.ID) { + _mock.Called(svc, p) + return } -// OnStreamCreationRetryBudgetUpdated provides a mock function with given fields: budget -func (_m *NetworkMetrics) OnStreamCreationRetryBudgetUpdated(budget uint64) { - _m.Called(budget) +// NetworkMetrics_BlockServicePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockServicePeer' +type NetworkMetrics_BlockServicePeer_Call struct { + *mock.Call } -// OnStreamEstablished provides a mock function with given fields: duration, attempts -func (_m *NetworkMetrics) OnStreamEstablished(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// BlockServicePeer is a helper method to define mock.On call +// - svc string +// - p peer.ID +func (_e *NetworkMetrics_Expecter) BlockServicePeer(svc interface{}, p interface{}) *NetworkMetrics_BlockServicePeer_Call { + return &NetworkMetrics_BlockServicePeer_Call{Call: _e.mock.On("BlockServicePeer", svc, p)} } -// OnTimeInMeshUpdated provides a mock function with given fields: _a0, _a1 -func (_m *NetworkMetrics) OnTimeInMeshUpdated(_a0 channels.Topic, _a1 time.Duration) { - _m.Called(_a0, _a1) +func (_c *NetworkMetrics_BlockServicePeer_Call) Run(run func(svc string, p peer.ID)) *NetworkMetrics_BlockServicePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OnUnauthorizedMessage provides a mock function with given fields: role, msgType, topic, offense -func (_m *NetworkMetrics) OnUnauthorizedMessage(role string, msgType string, topic string, offense string) { - _m.Called(role, msgType, topic, offense) +func (_c *NetworkMetrics_BlockServicePeer_Call) Return() *NetworkMetrics_BlockServicePeer_Call { + _c.Call.Return() + return _c } -// OnUndeliveredMessage provides a mock function with no fields -func (_m *NetworkMetrics) OnUndeliveredMessage() { - _m.Called() +func (_c *NetworkMetrics_BlockServicePeer_Call) RunAndReturn(run func(svc string, p peer.ID)) *NetworkMetrics_BlockServicePeer_Call { + _c.Run(run) + return _c } -// OnUnstakedPeerInspectionFailed provides a mock function with no fields -func (_m *NetworkMetrics) OnUnstakedPeerInspectionFailed() { - _m.Called() +// BlockStream provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) BlockStream(p peer.ID, dir network.Direction) { + _mock.Called(p, dir) + return } -// OnViolationReportSkipped provides a mock function with no fields -func (_m *NetworkMetrics) OnViolationReportSkipped() { - _m.Called() +// NetworkMetrics_BlockStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockStream' +type NetworkMetrics_BlockStream_Call struct { + *mock.Call } -// OutboundConnections provides a mock function with given fields: connectionCount -func (_m *NetworkMetrics) OutboundConnections(connectionCount uint) { - _m.Called(connectionCount) +// BlockStream is a helper method to define mock.On call +// - p peer.ID +// - dir network.Direction +func (_e *NetworkMetrics_Expecter) BlockStream(p interface{}, dir interface{}) *NetworkMetrics_BlockStream_Call { + return &NetworkMetrics_BlockStream_Call{Call: _e.mock.On("BlockStream", p, dir)} } -// OutboundMessageSent provides a mock function with given fields: sizeBytes, topic, _a2, messageType -func (_m *NetworkMetrics) OutboundMessageSent(sizeBytes int, topic string, _a2 string, messageType string) { - _m.Called(sizeBytes, topic, _a2, messageType) +func (_c *NetworkMetrics_BlockStream_Call) Run(run func(p peer.ID, dir network.Direction)) *NetworkMetrics_BlockStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.Direction + if args[1] != nil { + arg1 = args[1].(network.Direction) + } + run( + arg0, + arg1, + ) + }) + return _c } -// QueueDuration provides a mock function with given fields: duration, priority -func (_m *NetworkMetrics) QueueDuration(duration time.Duration, priority int) { - _m.Called(duration, priority) +func (_c *NetworkMetrics_BlockStream_Call) Return() *NetworkMetrics_BlockStream_Call { + _c.Call.Return() + return _c } -// RoutingTablePeerAdded provides a mock function with no fields -func (_m *NetworkMetrics) RoutingTablePeerAdded() { - _m.Called() +func (_c *NetworkMetrics_BlockStream_Call) RunAndReturn(run func(p peer.ID, dir network.Direction)) *NetworkMetrics_BlockStream_Call { + _c.Run(run) + return _c } -// RoutingTablePeerRemoved provides a mock function with no fields -func (_m *NetworkMetrics) RoutingTablePeerRemoved() { - _m.Called() +// DNSLookupDuration provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) DNSLookupDuration(duration time.Duration) { + _mock.Called(duration) + return } -// SetWarningStateCount provides a mock function with given fields: _a0 -func (_m *NetworkMetrics) SetWarningStateCount(_a0 uint) { - _m.Called(_a0) +// NetworkMetrics_DNSLookupDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DNSLookupDuration' +type NetworkMetrics_DNSLookupDuration_Call struct { + *mock.Call } -// UnicastMessageSendingCompleted provides a mock function with given fields: topic -func (_m *NetworkMetrics) UnicastMessageSendingCompleted(topic string) { - _m.Called(topic) +// DNSLookupDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *NetworkMetrics_Expecter) DNSLookupDuration(duration interface{}) *NetworkMetrics_DNSLookupDuration_Call { + return &NetworkMetrics_DNSLookupDuration_Call{Call: _e.mock.On("DNSLookupDuration", duration)} } -// UnicastMessageSendingStarted provides a mock function with given fields: topic -func (_m *NetworkMetrics) UnicastMessageSendingStarted(topic string) { - _m.Called(topic) +func (_c *NetworkMetrics_DNSLookupDuration_Call) Run(run func(duration time.Duration)) *NetworkMetrics_DNSLookupDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c } -// NewNetworkMetrics creates a new instance of NetworkMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNetworkMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *NetworkMetrics { - mock := &NetworkMetrics{} - mock.Mock.Test(t) +func (_c *NetworkMetrics_DNSLookupDuration_Call) Return() *NetworkMetrics_DNSLookupDuration_Call { + _c.Call.Return() + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *NetworkMetrics_DNSLookupDuration_Call) RunAndReturn(run func(duration time.Duration)) *NetworkMetrics_DNSLookupDuration_Call { + _c.Run(run) + return _c +} - return mock +// DuplicateInboundMessagesDropped provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) DuplicateInboundMessagesDropped(topic string, protocol1 string, messageType string) { + _mock.Called(topic, protocol1, messageType) + return +} + +// NetworkMetrics_DuplicateInboundMessagesDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateInboundMessagesDropped' +type NetworkMetrics_DuplicateInboundMessagesDropped_Call struct { + *mock.Call +} + +// DuplicateInboundMessagesDropped is a helper method to define mock.On call +// - topic string +// - protocol1 string +// - messageType string +func (_e *NetworkMetrics_Expecter) DuplicateInboundMessagesDropped(topic interface{}, protocol1 interface{}, messageType interface{}) *NetworkMetrics_DuplicateInboundMessagesDropped_Call { + return &NetworkMetrics_DuplicateInboundMessagesDropped_Call{Call: _e.mock.On("DuplicateInboundMessagesDropped", topic, protocol1, messageType)} +} + +func (_c *NetworkMetrics_DuplicateInboundMessagesDropped_Call) Run(run func(topic string, protocol1 string, messageType string)) *NetworkMetrics_DuplicateInboundMessagesDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *NetworkMetrics_DuplicateInboundMessagesDropped_Call) Return() *NetworkMetrics_DuplicateInboundMessagesDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_DuplicateInboundMessagesDropped_Call) RunAndReturn(run func(topic string, protocol1 string, messageType string)) *NetworkMetrics_DuplicateInboundMessagesDropped_Call { + _c.Run(run) + return _c +} + +// DuplicateMessagePenalties provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) DuplicateMessagePenalties(penalty float64) { + _mock.Called(penalty) + return +} + +// NetworkMetrics_DuplicateMessagePenalties_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessagePenalties' +type NetworkMetrics_DuplicateMessagePenalties_Call struct { + *mock.Call +} + +// DuplicateMessagePenalties is a helper method to define mock.On call +// - penalty float64 +func (_e *NetworkMetrics_Expecter) DuplicateMessagePenalties(penalty interface{}) *NetworkMetrics_DuplicateMessagePenalties_Call { + return &NetworkMetrics_DuplicateMessagePenalties_Call{Call: _e.mock.On("DuplicateMessagePenalties", penalty)} +} + +func (_c *NetworkMetrics_DuplicateMessagePenalties_Call) Run(run func(penalty float64)) *NetworkMetrics_DuplicateMessagePenalties_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_DuplicateMessagePenalties_Call) Return() *NetworkMetrics_DuplicateMessagePenalties_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_DuplicateMessagePenalties_Call) RunAndReturn(run func(penalty float64)) *NetworkMetrics_DuplicateMessagePenalties_Call { + _c.Run(run) + return _c +} + +// DuplicateMessagesCounts provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) DuplicateMessagesCounts(count float64) { + _mock.Called(count) + return +} + +// NetworkMetrics_DuplicateMessagesCounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessagesCounts' +type NetworkMetrics_DuplicateMessagesCounts_Call struct { + *mock.Call +} + +// DuplicateMessagesCounts is a helper method to define mock.On call +// - count float64 +func (_e *NetworkMetrics_Expecter) DuplicateMessagesCounts(count interface{}) *NetworkMetrics_DuplicateMessagesCounts_Call { + return &NetworkMetrics_DuplicateMessagesCounts_Call{Call: _e.mock.On("DuplicateMessagesCounts", count)} +} + +func (_c *NetworkMetrics_DuplicateMessagesCounts_Call) Run(run func(count float64)) *NetworkMetrics_DuplicateMessagesCounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_DuplicateMessagesCounts_Call) Return() *NetworkMetrics_DuplicateMessagesCounts_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_DuplicateMessagesCounts_Call) RunAndReturn(run func(count float64)) *NetworkMetrics_DuplicateMessagesCounts_Call { + _c.Run(run) + return _c +} + +// InboundConnections provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) InboundConnections(connectionCount uint) { + _mock.Called(connectionCount) + return +} + +// NetworkMetrics_InboundConnections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InboundConnections' +type NetworkMetrics_InboundConnections_Call struct { + *mock.Call +} + +// InboundConnections is a helper method to define mock.On call +// - connectionCount uint +func (_e *NetworkMetrics_Expecter) InboundConnections(connectionCount interface{}) *NetworkMetrics_InboundConnections_Call { + return &NetworkMetrics_InboundConnections_Call{Call: _e.mock.On("InboundConnections", connectionCount)} +} + +func (_c *NetworkMetrics_InboundConnections_Call) Run(run func(connectionCount uint)) *NetworkMetrics_InboundConnections_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_InboundConnections_Call) Return() *NetworkMetrics_InboundConnections_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_InboundConnections_Call) RunAndReturn(run func(connectionCount uint)) *NetworkMetrics_InboundConnections_Call { + _c.Run(run) + return _c +} + +// InboundMessageReceived provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) InboundMessageReceived(sizeBytes int, topic string, protocol1 string, messageType string) { + _mock.Called(sizeBytes, topic, protocol1, messageType) + return +} + +// NetworkMetrics_InboundMessageReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InboundMessageReceived' +type NetworkMetrics_InboundMessageReceived_Call struct { + *mock.Call +} + +// InboundMessageReceived is a helper method to define mock.On call +// - sizeBytes int +// - topic string +// - protocol1 string +// - messageType string +func (_e *NetworkMetrics_Expecter) InboundMessageReceived(sizeBytes interface{}, topic interface{}, protocol1 interface{}, messageType interface{}) *NetworkMetrics_InboundMessageReceived_Call { + return &NetworkMetrics_InboundMessageReceived_Call{Call: _e.mock.On("InboundMessageReceived", sizeBytes, topic, protocol1, messageType)} +} + +func (_c *NetworkMetrics_InboundMessageReceived_Call) Run(run func(sizeBytes int, topic string, protocol1 string, messageType string)) *NetworkMetrics_InboundMessageReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NetworkMetrics_InboundMessageReceived_Call) Return() *NetworkMetrics_InboundMessageReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_InboundMessageReceived_Call) RunAndReturn(run func(sizeBytes int, topic string, protocol1 string, messageType string)) *NetworkMetrics_InboundMessageReceived_Call { + _c.Run(run) + return _c +} + +// MessageAdded provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) MessageAdded(priority int) { + _mock.Called(priority) + return +} + +// NetworkMetrics_MessageAdded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageAdded' +type NetworkMetrics_MessageAdded_Call struct { + *mock.Call +} + +// MessageAdded is a helper method to define mock.On call +// - priority int +func (_e *NetworkMetrics_Expecter) MessageAdded(priority interface{}) *NetworkMetrics_MessageAdded_Call { + return &NetworkMetrics_MessageAdded_Call{Call: _e.mock.On("MessageAdded", priority)} +} + +func (_c *NetworkMetrics_MessageAdded_Call) Run(run func(priority int)) *NetworkMetrics_MessageAdded_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_MessageAdded_Call) Return() *NetworkMetrics_MessageAdded_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_MessageAdded_Call) RunAndReturn(run func(priority int)) *NetworkMetrics_MessageAdded_Call { + _c.Run(run) + return _c +} + +// MessageProcessingFinished provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) MessageProcessingFinished(topic string, duration time.Duration) { + _mock.Called(topic, duration) + return +} + +// NetworkMetrics_MessageProcessingFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageProcessingFinished' +type NetworkMetrics_MessageProcessingFinished_Call struct { + *mock.Call +} + +// MessageProcessingFinished is a helper method to define mock.On call +// - topic string +// - duration time.Duration +func (_e *NetworkMetrics_Expecter) MessageProcessingFinished(topic interface{}, duration interface{}) *NetworkMetrics_MessageProcessingFinished_Call { + return &NetworkMetrics_MessageProcessingFinished_Call{Call: _e.mock.On("MessageProcessingFinished", topic, duration)} +} + +func (_c *NetworkMetrics_MessageProcessingFinished_Call) Run(run func(topic string, duration time.Duration)) *NetworkMetrics_MessageProcessingFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_MessageProcessingFinished_Call) Return() *NetworkMetrics_MessageProcessingFinished_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_MessageProcessingFinished_Call) RunAndReturn(run func(topic string, duration time.Duration)) *NetworkMetrics_MessageProcessingFinished_Call { + _c.Run(run) + return _c +} + +// MessageProcessingStarted provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) MessageProcessingStarted(topic string) { + _mock.Called(topic) + return +} + +// NetworkMetrics_MessageProcessingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageProcessingStarted' +type NetworkMetrics_MessageProcessingStarted_Call struct { + *mock.Call +} + +// MessageProcessingStarted is a helper method to define mock.On call +// - topic string +func (_e *NetworkMetrics_Expecter) MessageProcessingStarted(topic interface{}) *NetworkMetrics_MessageProcessingStarted_Call { + return &NetworkMetrics_MessageProcessingStarted_Call{Call: _e.mock.On("MessageProcessingStarted", topic)} +} + +func (_c *NetworkMetrics_MessageProcessingStarted_Call) Run(run func(topic string)) *NetworkMetrics_MessageProcessingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_MessageProcessingStarted_Call) Return() *NetworkMetrics_MessageProcessingStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_MessageProcessingStarted_Call) RunAndReturn(run func(topic string)) *NetworkMetrics_MessageProcessingStarted_Call { + _c.Run(run) + return _c +} + +// MessageRemoved provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) MessageRemoved(priority int) { + _mock.Called(priority) + return +} + +// NetworkMetrics_MessageRemoved_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MessageRemoved' +type NetworkMetrics_MessageRemoved_Call struct { + *mock.Call +} + +// MessageRemoved is a helper method to define mock.On call +// - priority int +func (_e *NetworkMetrics_Expecter) MessageRemoved(priority interface{}) *NetworkMetrics_MessageRemoved_Call { + return &NetworkMetrics_MessageRemoved_Call{Call: _e.mock.On("MessageRemoved", priority)} +} + +func (_c *NetworkMetrics_MessageRemoved_Call) Run(run func(priority int)) *NetworkMetrics_MessageRemoved_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_MessageRemoved_Call) Return() *NetworkMetrics_MessageRemoved_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_MessageRemoved_Call) RunAndReturn(run func(priority int)) *NetworkMetrics_MessageRemoved_Call { + _c.Run(run) + return _c +} + +// OnActiveClusterIDsNotSetErr provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnActiveClusterIDsNotSetErr() { + _mock.Called() + return +} + +// NetworkMetrics_OnActiveClusterIDsNotSetErr_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnActiveClusterIDsNotSetErr' +type NetworkMetrics_OnActiveClusterIDsNotSetErr_Call struct { + *mock.Call +} + +// OnActiveClusterIDsNotSetErr is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnActiveClusterIDsNotSetErr() *NetworkMetrics_OnActiveClusterIDsNotSetErr_Call { + return &NetworkMetrics_OnActiveClusterIDsNotSetErr_Call{Call: _e.mock.On("OnActiveClusterIDsNotSetErr")} +} + +func (_c *NetworkMetrics_OnActiveClusterIDsNotSetErr_Call) Run(run func()) *NetworkMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnActiveClusterIDsNotSetErr_Call) Return() *NetworkMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnActiveClusterIDsNotSetErr_Call) RunAndReturn(run func()) *NetworkMetrics_OnActiveClusterIDsNotSetErr_Call { + _c.Run(run) + return _c +} + +// OnAppSpecificScoreUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnAppSpecificScoreUpdated(f float64) { + _mock.Called(f) + return +} + +// NetworkMetrics_OnAppSpecificScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAppSpecificScoreUpdated' +type NetworkMetrics_OnAppSpecificScoreUpdated_Call struct { + *mock.Call +} + +// OnAppSpecificScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *NetworkMetrics_Expecter) OnAppSpecificScoreUpdated(f interface{}) *NetworkMetrics_OnAppSpecificScoreUpdated_Call { + return &NetworkMetrics_OnAppSpecificScoreUpdated_Call{Call: _e.mock.On("OnAppSpecificScoreUpdated", f)} +} + +func (_c *NetworkMetrics_OnAppSpecificScoreUpdated_Call) Run(run func(f float64)) *NetworkMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnAppSpecificScoreUpdated_Call) Return() *NetworkMetrics_OnAppSpecificScoreUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnAppSpecificScoreUpdated_Call) RunAndReturn(run func(f float64)) *NetworkMetrics_OnAppSpecificScoreUpdated_Call { + _c.Run(run) + return _c +} + +// OnBehaviourPenaltyUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnBehaviourPenaltyUpdated(f float64) { + _mock.Called(f) + return +} + +// NetworkMetrics_OnBehaviourPenaltyUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBehaviourPenaltyUpdated' +type NetworkMetrics_OnBehaviourPenaltyUpdated_Call struct { + *mock.Call +} + +// OnBehaviourPenaltyUpdated is a helper method to define mock.On call +// - f float64 +func (_e *NetworkMetrics_Expecter) OnBehaviourPenaltyUpdated(f interface{}) *NetworkMetrics_OnBehaviourPenaltyUpdated_Call { + return &NetworkMetrics_OnBehaviourPenaltyUpdated_Call{Call: _e.mock.On("OnBehaviourPenaltyUpdated", f)} +} + +func (_c *NetworkMetrics_OnBehaviourPenaltyUpdated_Call) Run(run func(f float64)) *NetworkMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnBehaviourPenaltyUpdated_Call) Return() *NetworkMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnBehaviourPenaltyUpdated_Call) RunAndReturn(run func(f float64)) *NetworkMetrics_OnBehaviourPenaltyUpdated_Call { + _c.Run(run) + return _c +} + +// OnControlMessagesTruncated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnControlMessagesTruncated(messageType p2pmsg.ControlMessageType, diff int) { + _mock.Called(messageType, diff) + return +} + +// NetworkMetrics_OnControlMessagesTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnControlMessagesTruncated' +type NetworkMetrics_OnControlMessagesTruncated_Call struct { + *mock.Call +} + +// OnControlMessagesTruncated is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +// - diff int +func (_e *NetworkMetrics_Expecter) OnControlMessagesTruncated(messageType interface{}, diff interface{}) *NetworkMetrics_OnControlMessagesTruncated_Call { + return &NetworkMetrics_OnControlMessagesTruncated_Call{Call: _e.mock.On("OnControlMessagesTruncated", messageType, diff)} +} + +func (_c *NetworkMetrics_OnControlMessagesTruncated_Call) Run(run func(messageType p2pmsg.ControlMessageType, diff int)) *NetworkMetrics_OnControlMessagesTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnControlMessagesTruncated_Call) Return() *NetworkMetrics_OnControlMessagesTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnControlMessagesTruncated_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType, diff int)) *NetworkMetrics_OnControlMessagesTruncated_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheHit provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnDNSCacheHit() { + _mock.Called() + return +} + +// NetworkMetrics_OnDNSCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheHit' +type NetworkMetrics_OnDNSCacheHit_Call struct { + *mock.Call +} + +// OnDNSCacheHit is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnDNSCacheHit() *NetworkMetrics_OnDNSCacheHit_Call { + return &NetworkMetrics_OnDNSCacheHit_Call{Call: _e.mock.On("OnDNSCacheHit")} +} + +func (_c *NetworkMetrics_OnDNSCacheHit_Call) Run(run func()) *NetworkMetrics_OnDNSCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnDNSCacheHit_Call) Return() *NetworkMetrics_OnDNSCacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnDNSCacheHit_Call) RunAndReturn(run func()) *NetworkMetrics_OnDNSCacheHit_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheInvalidated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnDNSCacheInvalidated() { + _mock.Called() + return +} + +// NetworkMetrics_OnDNSCacheInvalidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheInvalidated' +type NetworkMetrics_OnDNSCacheInvalidated_Call struct { + *mock.Call +} + +// OnDNSCacheInvalidated is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnDNSCacheInvalidated() *NetworkMetrics_OnDNSCacheInvalidated_Call { + return &NetworkMetrics_OnDNSCacheInvalidated_Call{Call: _e.mock.On("OnDNSCacheInvalidated")} +} + +func (_c *NetworkMetrics_OnDNSCacheInvalidated_Call) Run(run func()) *NetworkMetrics_OnDNSCacheInvalidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnDNSCacheInvalidated_Call) Return() *NetworkMetrics_OnDNSCacheInvalidated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnDNSCacheInvalidated_Call) RunAndReturn(run func()) *NetworkMetrics_OnDNSCacheInvalidated_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheMiss provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnDNSCacheMiss() { + _mock.Called() + return +} + +// NetworkMetrics_OnDNSCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheMiss' +type NetworkMetrics_OnDNSCacheMiss_Call struct { + *mock.Call +} + +// OnDNSCacheMiss is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnDNSCacheMiss() *NetworkMetrics_OnDNSCacheMiss_Call { + return &NetworkMetrics_OnDNSCacheMiss_Call{Call: _e.mock.On("OnDNSCacheMiss")} +} + +func (_c *NetworkMetrics_OnDNSCacheMiss_Call) Run(run func()) *NetworkMetrics_OnDNSCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnDNSCacheMiss_Call) Return() *NetworkMetrics_OnDNSCacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnDNSCacheMiss_Call) RunAndReturn(run func()) *NetworkMetrics_OnDNSCacheMiss_Call { + _c.Run(run) + return _c +} + +// OnDNSLookupRequestDropped provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnDNSLookupRequestDropped() { + _mock.Called() + return +} + +// NetworkMetrics_OnDNSLookupRequestDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSLookupRequestDropped' +type NetworkMetrics_OnDNSLookupRequestDropped_Call struct { + *mock.Call +} + +// OnDNSLookupRequestDropped is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnDNSLookupRequestDropped() *NetworkMetrics_OnDNSLookupRequestDropped_Call { + return &NetworkMetrics_OnDNSLookupRequestDropped_Call{Call: _e.mock.On("OnDNSLookupRequestDropped")} +} + +func (_c *NetworkMetrics_OnDNSLookupRequestDropped_Call) Run(run func()) *NetworkMetrics_OnDNSLookupRequestDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnDNSLookupRequestDropped_Call) Return() *NetworkMetrics_OnDNSLookupRequestDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnDNSLookupRequestDropped_Call) RunAndReturn(run func()) *NetworkMetrics_OnDNSLookupRequestDropped_Call { + _c.Run(run) + return _c +} + +// OnDialRetryBudgetResetToDefault provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnDialRetryBudgetResetToDefault() { + _mock.Called() + return +} + +// NetworkMetrics_OnDialRetryBudgetResetToDefault_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDialRetryBudgetResetToDefault' +type NetworkMetrics_OnDialRetryBudgetResetToDefault_Call struct { + *mock.Call +} + +// OnDialRetryBudgetResetToDefault is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnDialRetryBudgetResetToDefault() *NetworkMetrics_OnDialRetryBudgetResetToDefault_Call { + return &NetworkMetrics_OnDialRetryBudgetResetToDefault_Call{Call: _e.mock.On("OnDialRetryBudgetResetToDefault")} +} + +func (_c *NetworkMetrics_OnDialRetryBudgetResetToDefault_Call) Run(run func()) *NetworkMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnDialRetryBudgetResetToDefault_Call) Return() *NetworkMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnDialRetryBudgetResetToDefault_Call) RunAndReturn(run func()) *NetworkMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Run(run) + return _c +} + +// OnDialRetryBudgetUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnDialRetryBudgetUpdated(budget uint64) { + _mock.Called(budget) + return +} + +// NetworkMetrics_OnDialRetryBudgetUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDialRetryBudgetUpdated' +type NetworkMetrics_OnDialRetryBudgetUpdated_Call struct { + *mock.Call +} + +// OnDialRetryBudgetUpdated is a helper method to define mock.On call +// - budget uint64 +func (_e *NetworkMetrics_Expecter) OnDialRetryBudgetUpdated(budget interface{}) *NetworkMetrics_OnDialRetryBudgetUpdated_Call { + return &NetworkMetrics_OnDialRetryBudgetUpdated_Call{Call: _e.mock.On("OnDialRetryBudgetUpdated", budget)} +} + +func (_c *NetworkMetrics_OnDialRetryBudgetUpdated_Call) Run(run func(budget uint64)) *NetworkMetrics_OnDialRetryBudgetUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnDialRetryBudgetUpdated_Call) Return() *NetworkMetrics_OnDialRetryBudgetUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnDialRetryBudgetUpdated_Call) RunAndReturn(run func(budget uint64)) *NetworkMetrics_OnDialRetryBudgetUpdated_Call { + _c.Run(run) + return _c +} + +// OnEstablishStreamFailure provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnEstablishStreamFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// NetworkMetrics_OnEstablishStreamFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnEstablishStreamFailure' +type NetworkMetrics_OnEstablishStreamFailure_Call struct { + *mock.Call +} + +// OnEstablishStreamFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *NetworkMetrics_Expecter) OnEstablishStreamFailure(duration interface{}, attempts interface{}) *NetworkMetrics_OnEstablishStreamFailure_Call { + return &NetworkMetrics_OnEstablishStreamFailure_Call{Call: _e.mock.On("OnEstablishStreamFailure", duration, attempts)} +} + +func (_c *NetworkMetrics_OnEstablishStreamFailure_Call) Run(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnEstablishStreamFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnEstablishStreamFailure_Call) Return() *NetworkMetrics_OnEstablishStreamFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnEstablishStreamFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnEstablishStreamFailure_Call { + _c.Run(run) + return _c +} + +// OnFirstMessageDeliveredUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnFirstMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// NetworkMetrics_OnFirstMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFirstMessageDeliveredUpdated' +type NetworkMetrics_OnFirstMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnFirstMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *NetworkMetrics_Expecter) OnFirstMessageDeliveredUpdated(topic interface{}, f interface{}) *NetworkMetrics_OnFirstMessageDeliveredUpdated_Call { + return &NetworkMetrics_OnFirstMessageDeliveredUpdated_Call{Call: _e.mock.On("OnFirstMessageDeliveredUpdated", topic, f)} +} + +func (_c *NetworkMetrics_OnFirstMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *NetworkMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnFirstMessageDeliveredUpdated_Call) Return() *NetworkMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnFirstMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *NetworkMetrics_OnFirstMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnGraftDuplicateTopicIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnGraftDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftDuplicateTopicIdsExceedThreshold' +type NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnGraftDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnGraftDuplicateTopicIdsExceedThreshold() *NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + return &NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftDuplicateTopicIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) Return() *NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnGraftDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnGraftInvalidTopicIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnGraftInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftInvalidTopicIdsExceedThreshold' +type NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnGraftInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnGraftInvalidTopicIdsExceedThreshold() *NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + return &NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnGraftInvalidTopicIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) Return() *NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnGraftInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnGraftMessageInspected provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnGraftMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// NetworkMetrics_OnGraftMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnGraftMessageInspected' +type NetworkMetrics_OnGraftMessageInspected_Call struct { + *mock.Call +} + +// OnGraftMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *NetworkMetrics_Expecter) OnGraftMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *NetworkMetrics_OnGraftMessageInspected_Call { + return &NetworkMetrics_OnGraftMessageInspected_Call{Call: _e.mock.On("OnGraftMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *NetworkMetrics_OnGraftMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *NetworkMetrics_OnGraftMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnGraftMessageInspected_Call) Return() *NetworkMetrics_OnGraftMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnGraftMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *NetworkMetrics_OnGraftMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnIHaveControlMessageIdsTruncated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIHaveControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveControlMessageIdsTruncated' +type NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIHaveControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *NetworkMetrics_Expecter) OnIHaveControlMessageIdsTruncated(diff interface{}) *NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call { + return &NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIHaveControlMessageIdsTruncated", diff)} +} + +func (_c *NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call) Run(run func(diff int)) *NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call) Return() *NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *NetworkMetrics_OnIHaveControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateMessageIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIHaveDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateMessageIdsExceedThreshold' +type NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnIHaveDuplicateMessageIdsExceedThreshold() *NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + return &NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateMessageIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) Return() *NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnIHaveDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveDuplicateTopicIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIHaveDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveDuplicateTopicIdsExceedThreshold' +type NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnIHaveDuplicateTopicIdsExceedThreshold() *NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + return &NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveDuplicateTopicIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) Return() *NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnIHaveDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveInvalidTopicIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIHaveInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveInvalidTopicIdsExceedThreshold' +type NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIHaveInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnIHaveInvalidTopicIdsExceedThreshold() *NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + return &NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnIHaveInvalidTopicIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) Return() *NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnIHaveInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessageIDsReceived provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIHaveMessageIDsReceived(channel string, msgIdCount int) { + _mock.Called(channel, msgIdCount) + return +} + +// NetworkMetrics_OnIHaveMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessageIDsReceived' +type NetworkMetrics_OnIHaveMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIHaveMessageIDsReceived is a helper method to define mock.On call +// - channel string +// - msgIdCount int +func (_e *NetworkMetrics_Expecter) OnIHaveMessageIDsReceived(channel interface{}, msgIdCount interface{}) *NetworkMetrics_OnIHaveMessageIDsReceived_Call { + return &NetworkMetrics_OnIHaveMessageIDsReceived_Call{Call: _e.mock.On("OnIHaveMessageIDsReceived", channel, msgIdCount)} +} + +func (_c *NetworkMetrics_OnIHaveMessageIDsReceived_Call) Run(run func(channel string, msgIdCount int)) *NetworkMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIHaveMessageIDsReceived_Call) Return() *NetworkMetrics_OnIHaveMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIHaveMessageIDsReceived_Call) RunAndReturn(run func(channel string, msgIdCount int)) *NetworkMetrics_OnIHaveMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIHaveMessagesInspected provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIHaveMessagesInspected(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, duplicateMessageIds, invalidTopicIds) + return +} + +// NetworkMetrics_OnIHaveMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIHaveMessagesInspected' +type NetworkMetrics_OnIHaveMessagesInspected_Call struct { + *mock.Call +} + +// OnIHaveMessagesInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - duplicateMessageIds int +// - invalidTopicIds int +func (_e *NetworkMetrics_Expecter) OnIHaveMessagesInspected(duplicateTopicIds interface{}, duplicateMessageIds interface{}, invalidTopicIds interface{}) *NetworkMetrics_OnIHaveMessagesInspected_Call { + return &NetworkMetrics_OnIHaveMessagesInspected_Call{Call: _e.mock.On("OnIHaveMessagesInspected", duplicateTopicIds, duplicateMessageIds, invalidTopicIds)} +} + +func (_c *NetworkMetrics_OnIHaveMessagesInspected_Call) Run(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *NetworkMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIHaveMessagesInspected_Call) Return() *NetworkMetrics_OnIHaveMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIHaveMessagesInspected_Call) RunAndReturn(run func(duplicateTopicIds int, duplicateMessageIds int, invalidTopicIds int)) *NetworkMetrics_OnIHaveMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIPColocationFactorUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIPColocationFactorUpdated(f float64) { + _mock.Called(f) + return +} + +// NetworkMetrics_OnIPColocationFactorUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIPColocationFactorUpdated' +type NetworkMetrics_OnIPColocationFactorUpdated_Call struct { + *mock.Call +} + +// OnIPColocationFactorUpdated is a helper method to define mock.On call +// - f float64 +func (_e *NetworkMetrics_Expecter) OnIPColocationFactorUpdated(f interface{}) *NetworkMetrics_OnIPColocationFactorUpdated_Call { + return &NetworkMetrics_OnIPColocationFactorUpdated_Call{Call: _e.mock.On("OnIPColocationFactorUpdated", f)} +} + +func (_c *NetworkMetrics_OnIPColocationFactorUpdated_Call) Run(run func(f float64)) *NetworkMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIPColocationFactorUpdated_Call) Return() *NetworkMetrics_OnIPColocationFactorUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIPColocationFactorUpdated_Call) RunAndReturn(run func(f float64)) *NetworkMetrics_OnIPColocationFactorUpdated_Call { + _c.Run(run) + return _c +} + +// OnIWantCacheMissMessageIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIWantCacheMissMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantCacheMissMessageIdsExceedThreshold' +type NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantCacheMissMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnIWantCacheMissMessageIdsExceedThreshold() *NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + return &NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantCacheMissMessageIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) Return() *NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnIWantCacheMissMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantControlMessageIdsTruncated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIWantControlMessageIdsTruncated(diff int) { + _mock.Called(diff) + return +} + +// NetworkMetrics_OnIWantControlMessageIdsTruncated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantControlMessageIdsTruncated' +type NetworkMetrics_OnIWantControlMessageIdsTruncated_Call struct { + *mock.Call +} + +// OnIWantControlMessageIdsTruncated is a helper method to define mock.On call +// - diff int +func (_e *NetworkMetrics_Expecter) OnIWantControlMessageIdsTruncated(diff interface{}) *NetworkMetrics_OnIWantControlMessageIdsTruncated_Call { + return &NetworkMetrics_OnIWantControlMessageIdsTruncated_Call{Call: _e.mock.On("OnIWantControlMessageIdsTruncated", diff)} +} + +func (_c *NetworkMetrics_OnIWantControlMessageIdsTruncated_Call) Run(run func(diff int)) *NetworkMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIWantControlMessageIdsTruncated_Call) Return() *NetworkMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIWantControlMessageIdsTruncated_Call) RunAndReturn(run func(diff int)) *NetworkMetrics_OnIWantControlMessageIdsTruncated_Call { + _c.Run(run) + return _c +} + +// OnIWantDuplicateMessageIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIWantDuplicateMessageIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantDuplicateMessageIdsExceedThreshold' +type NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnIWantDuplicateMessageIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnIWantDuplicateMessageIdsExceedThreshold() *NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + return &NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call{Call: _e.mock.On("OnIWantDuplicateMessageIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) Return() *NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnIWantDuplicateMessageIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnIWantMessageIDsReceived provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIWantMessageIDsReceived(msgIdCount int) { + _mock.Called(msgIdCount) + return +} + +// NetworkMetrics_OnIWantMessageIDsReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessageIDsReceived' +type NetworkMetrics_OnIWantMessageIDsReceived_Call struct { + *mock.Call +} + +// OnIWantMessageIDsReceived is a helper method to define mock.On call +// - msgIdCount int +func (_e *NetworkMetrics_Expecter) OnIWantMessageIDsReceived(msgIdCount interface{}) *NetworkMetrics_OnIWantMessageIDsReceived_Call { + return &NetworkMetrics_OnIWantMessageIDsReceived_Call{Call: _e.mock.On("OnIWantMessageIDsReceived", msgIdCount)} +} + +func (_c *NetworkMetrics_OnIWantMessageIDsReceived_Call) Run(run func(msgIdCount int)) *NetworkMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIWantMessageIDsReceived_Call) Return() *NetworkMetrics_OnIWantMessageIDsReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIWantMessageIDsReceived_Call) RunAndReturn(run func(msgIdCount int)) *NetworkMetrics_OnIWantMessageIDsReceived_Call { + _c.Run(run) + return _c +} + +// OnIWantMessagesInspected provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIWantMessagesInspected(duplicateCount int, cacheMissCount int) { + _mock.Called(duplicateCount, cacheMissCount) + return +} + +// NetworkMetrics_OnIWantMessagesInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIWantMessagesInspected' +type NetworkMetrics_OnIWantMessagesInspected_Call struct { + *mock.Call +} + +// OnIWantMessagesInspected is a helper method to define mock.On call +// - duplicateCount int +// - cacheMissCount int +func (_e *NetworkMetrics_Expecter) OnIWantMessagesInspected(duplicateCount interface{}, cacheMissCount interface{}) *NetworkMetrics_OnIWantMessagesInspected_Call { + return &NetworkMetrics_OnIWantMessagesInspected_Call{Call: _e.mock.On("OnIWantMessagesInspected", duplicateCount, cacheMissCount)} +} + +func (_c *NetworkMetrics_OnIWantMessagesInspected_Call) Run(run func(duplicateCount int, cacheMissCount int)) *NetworkMetrics_OnIWantMessagesInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIWantMessagesInspected_Call) Return() *NetworkMetrics_OnIWantMessagesInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIWantMessagesInspected_Call) RunAndReturn(run func(duplicateCount int, cacheMissCount int)) *NetworkMetrics_OnIWantMessagesInspected_Call { + _c.Run(run) + return _c +} + +// OnIncomingRpcReceived provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnIncomingRpcReceived(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int) { + _mock.Called(iHaveCount, iWantCount, graftCount, pruneCount, msgCount) + return +} + +// NetworkMetrics_OnIncomingRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnIncomingRpcReceived' +type NetworkMetrics_OnIncomingRpcReceived_Call struct { + *mock.Call +} + +// OnIncomingRpcReceived is a helper method to define mock.On call +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +// - msgCount int +func (_e *NetworkMetrics_Expecter) OnIncomingRpcReceived(iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}, msgCount interface{}) *NetworkMetrics_OnIncomingRpcReceived_Call { + return &NetworkMetrics_OnIncomingRpcReceived_Call{Call: _e.mock.On("OnIncomingRpcReceived", iHaveCount, iWantCount, graftCount, pruneCount, msgCount)} +} + +func (_c *NetworkMetrics_OnIncomingRpcReceived_Call) Run(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *NetworkMetrics_OnIncomingRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnIncomingRpcReceived_Call) Return() *NetworkMetrics_OnIncomingRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnIncomingRpcReceived_Call) RunAndReturn(run func(iHaveCount int, iWantCount int, graftCount int, pruneCount int, msgCount int)) *NetworkMetrics_OnIncomingRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnInvalidControlMessageNotificationSent provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnInvalidControlMessageNotificationSent() { + _mock.Called() + return +} + +// NetworkMetrics_OnInvalidControlMessageNotificationSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidControlMessageNotificationSent' +type NetworkMetrics_OnInvalidControlMessageNotificationSent_Call struct { + *mock.Call +} + +// OnInvalidControlMessageNotificationSent is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnInvalidControlMessageNotificationSent() *NetworkMetrics_OnInvalidControlMessageNotificationSent_Call { + return &NetworkMetrics_OnInvalidControlMessageNotificationSent_Call{Call: _e.mock.On("OnInvalidControlMessageNotificationSent")} +} + +func (_c *NetworkMetrics_OnInvalidControlMessageNotificationSent_Call) Run(run func()) *NetworkMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnInvalidControlMessageNotificationSent_Call) Return() *NetworkMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnInvalidControlMessageNotificationSent_Call) RunAndReturn(run func()) *NetworkMetrics_OnInvalidControlMessageNotificationSent_Call { + _c.Run(run) + return _c +} + +// OnInvalidMessageDeliveredUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnInvalidMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidMessageDeliveredUpdated' +type NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnInvalidMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *NetworkMetrics_Expecter) OnInvalidMessageDeliveredUpdated(topic interface{}, f interface{}) *NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call { + return &NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call{Call: _e.mock.On("OnInvalidMessageDeliveredUpdated", topic, f)} +} + +func (_c *NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call) Return() *NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *NetworkMetrics_OnInvalidMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnInvalidTopicIdDetectedForControlMessage provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnInvalidTopicIdDetectedForControlMessage(messageType p2pmsg.ControlMessageType) { + _mock.Called(messageType) + return +} + +// NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidTopicIdDetectedForControlMessage' +type NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call struct { + *mock.Call +} + +// OnInvalidTopicIdDetectedForControlMessage is a helper method to define mock.On call +// - messageType p2pmsg.ControlMessageType +func (_e *NetworkMetrics_Expecter) OnInvalidTopicIdDetectedForControlMessage(messageType interface{}) *NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + return &NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call{Call: _e.mock.On("OnInvalidTopicIdDetectedForControlMessage", messageType)} +} + +func (_c *NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Run(run func(messageType p2pmsg.ControlMessageType)) *NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2pmsg.ControlMessageType + if args[0] != nil { + arg0 = args[0].(p2pmsg.ControlMessageType) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) Return() *NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call) RunAndReturn(run func(messageType p2pmsg.ControlMessageType)) *NetworkMetrics_OnInvalidTopicIdDetectedForControlMessage_Call { + _c.Run(run) + return _c +} + +// OnLocalMeshSizeUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnLocalMeshSizeUpdated(topic string, size int) { + _mock.Called(topic, size) + return +} + +// NetworkMetrics_OnLocalMeshSizeUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalMeshSizeUpdated' +type NetworkMetrics_OnLocalMeshSizeUpdated_Call struct { + *mock.Call +} + +// OnLocalMeshSizeUpdated is a helper method to define mock.On call +// - topic string +// - size int +func (_e *NetworkMetrics_Expecter) OnLocalMeshSizeUpdated(topic interface{}, size interface{}) *NetworkMetrics_OnLocalMeshSizeUpdated_Call { + return &NetworkMetrics_OnLocalMeshSizeUpdated_Call{Call: _e.mock.On("OnLocalMeshSizeUpdated", topic, size)} +} + +func (_c *NetworkMetrics_OnLocalMeshSizeUpdated_Call) Run(run func(topic string, size int)) *NetworkMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnLocalMeshSizeUpdated_Call) Return() *NetworkMetrics_OnLocalMeshSizeUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnLocalMeshSizeUpdated_Call) RunAndReturn(run func(topic string, size int)) *NetworkMetrics_OnLocalMeshSizeUpdated_Call { + _c.Run(run) + return _c +} + +// OnLocalPeerJoinedTopic provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnLocalPeerJoinedTopic() { + _mock.Called() + return +} + +// NetworkMetrics_OnLocalPeerJoinedTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerJoinedTopic' +type NetworkMetrics_OnLocalPeerJoinedTopic_Call struct { + *mock.Call +} + +// OnLocalPeerJoinedTopic is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnLocalPeerJoinedTopic() *NetworkMetrics_OnLocalPeerJoinedTopic_Call { + return &NetworkMetrics_OnLocalPeerJoinedTopic_Call{Call: _e.mock.On("OnLocalPeerJoinedTopic")} +} + +func (_c *NetworkMetrics_OnLocalPeerJoinedTopic_Call) Run(run func()) *NetworkMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnLocalPeerJoinedTopic_Call) Return() *NetworkMetrics_OnLocalPeerJoinedTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnLocalPeerJoinedTopic_Call) RunAndReturn(run func()) *NetworkMetrics_OnLocalPeerJoinedTopic_Call { + _c.Run(run) + return _c +} + +// OnLocalPeerLeftTopic provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnLocalPeerLeftTopic() { + _mock.Called() + return +} + +// NetworkMetrics_OnLocalPeerLeftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnLocalPeerLeftTopic' +type NetworkMetrics_OnLocalPeerLeftTopic_Call struct { + *mock.Call +} + +// OnLocalPeerLeftTopic is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnLocalPeerLeftTopic() *NetworkMetrics_OnLocalPeerLeftTopic_Call { + return &NetworkMetrics_OnLocalPeerLeftTopic_Call{Call: _e.mock.On("OnLocalPeerLeftTopic")} +} + +func (_c *NetworkMetrics_OnLocalPeerLeftTopic_Call) Run(run func()) *NetworkMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnLocalPeerLeftTopic_Call) Return() *NetworkMetrics_OnLocalPeerLeftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnLocalPeerLeftTopic_Call) RunAndReturn(run func()) *NetworkMetrics_OnLocalPeerLeftTopic_Call { + _c.Run(run) + return _c +} + +// OnMeshMessageDeliveredUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnMeshMessageDeliveredUpdated(topic channels.Topic, f float64) { + _mock.Called(topic, f) + return +} + +// NetworkMetrics_OnMeshMessageDeliveredUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMeshMessageDeliveredUpdated' +type NetworkMetrics_OnMeshMessageDeliveredUpdated_Call struct { + *mock.Call +} + +// OnMeshMessageDeliveredUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - f float64 +func (_e *NetworkMetrics_Expecter) OnMeshMessageDeliveredUpdated(topic interface{}, f interface{}) *NetworkMetrics_OnMeshMessageDeliveredUpdated_Call { + return &NetworkMetrics_OnMeshMessageDeliveredUpdated_Call{Call: _e.mock.On("OnMeshMessageDeliveredUpdated", topic, f)} +} + +func (_c *NetworkMetrics_OnMeshMessageDeliveredUpdated_Call) Run(run func(topic channels.Topic, f float64)) *NetworkMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnMeshMessageDeliveredUpdated_Call) Return() *NetworkMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnMeshMessageDeliveredUpdated_Call) RunAndReturn(run func(topic channels.Topic, f float64)) *NetworkMetrics_OnMeshMessageDeliveredUpdated_Call { + _c.Run(run) + return _c +} + +// OnMessageDeliveredToAllSubscribers provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnMessageDeliveredToAllSubscribers(size int) { + _mock.Called(size) + return +} + +// NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDeliveredToAllSubscribers' +type NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call struct { + *mock.Call +} + +// OnMessageDeliveredToAllSubscribers is a helper method to define mock.On call +// - size int +func (_e *NetworkMetrics_Expecter) OnMessageDeliveredToAllSubscribers(size interface{}) *NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call { + return &NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call{Call: _e.mock.On("OnMessageDeliveredToAllSubscribers", size)} +} + +func (_c *NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call) Run(run func(size int)) *NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call) Return() *NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call) RunAndReturn(run func(size int)) *NetworkMetrics_OnMessageDeliveredToAllSubscribers_Call { + _c.Run(run) + return _c +} + +// OnMessageDuplicate provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnMessageDuplicate(size int) { + _mock.Called(size) + return +} + +// NetworkMetrics_OnMessageDuplicate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageDuplicate' +type NetworkMetrics_OnMessageDuplicate_Call struct { + *mock.Call +} + +// OnMessageDuplicate is a helper method to define mock.On call +// - size int +func (_e *NetworkMetrics_Expecter) OnMessageDuplicate(size interface{}) *NetworkMetrics_OnMessageDuplicate_Call { + return &NetworkMetrics_OnMessageDuplicate_Call{Call: _e.mock.On("OnMessageDuplicate", size)} +} + +func (_c *NetworkMetrics_OnMessageDuplicate_Call) Run(run func(size int)) *NetworkMetrics_OnMessageDuplicate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnMessageDuplicate_Call) Return() *NetworkMetrics_OnMessageDuplicate_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnMessageDuplicate_Call) RunAndReturn(run func(size int)) *NetworkMetrics_OnMessageDuplicate_Call { + _c.Run(run) + return _c +} + +// OnMessageEnteredValidation provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnMessageEnteredValidation(size int) { + _mock.Called(size) + return +} + +// NetworkMetrics_OnMessageEnteredValidation_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageEnteredValidation' +type NetworkMetrics_OnMessageEnteredValidation_Call struct { + *mock.Call +} + +// OnMessageEnteredValidation is a helper method to define mock.On call +// - size int +func (_e *NetworkMetrics_Expecter) OnMessageEnteredValidation(size interface{}) *NetworkMetrics_OnMessageEnteredValidation_Call { + return &NetworkMetrics_OnMessageEnteredValidation_Call{Call: _e.mock.On("OnMessageEnteredValidation", size)} +} + +func (_c *NetworkMetrics_OnMessageEnteredValidation_Call) Run(run func(size int)) *NetworkMetrics_OnMessageEnteredValidation_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnMessageEnteredValidation_Call) Return() *NetworkMetrics_OnMessageEnteredValidation_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnMessageEnteredValidation_Call) RunAndReturn(run func(size int)) *NetworkMetrics_OnMessageEnteredValidation_Call { + _c.Run(run) + return _c +} + +// OnMessageRejected provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnMessageRejected(size int, reason string) { + _mock.Called(size, reason) + return +} + +// NetworkMetrics_OnMessageRejected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMessageRejected' +type NetworkMetrics_OnMessageRejected_Call struct { + *mock.Call +} + +// OnMessageRejected is a helper method to define mock.On call +// - size int +// - reason string +func (_e *NetworkMetrics_Expecter) OnMessageRejected(size interface{}, reason interface{}) *NetworkMetrics_OnMessageRejected_Call { + return &NetworkMetrics_OnMessageRejected_Call{Call: _e.mock.On("OnMessageRejected", size, reason)} +} + +func (_c *NetworkMetrics_OnMessageRejected_Call) Run(run func(size int, reason string)) *NetworkMetrics_OnMessageRejected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnMessageRejected_Call) Return() *NetworkMetrics_OnMessageRejected_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnMessageRejected_Call) RunAndReturn(run func(size int, reason string)) *NetworkMetrics_OnMessageRejected_Call { + _c.Run(run) + return _c +} + +// OnMisbehaviorReported provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnMisbehaviorReported(channel string, misbehaviorType string) { + _mock.Called(channel, misbehaviorType) + return +} + +// NetworkMetrics_OnMisbehaviorReported_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnMisbehaviorReported' +type NetworkMetrics_OnMisbehaviorReported_Call struct { + *mock.Call +} + +// OnMisbehaviorReported is a helper method to define mock.On call +// - channel string +// - misbehaviorType string +func (_e *NetworkMetrics_Expecter) OnMisbehaviorReported(channel interface{}, misbehaviorType interface{}) *NetworkMetrics_OnMisbehaviorReported_Call { + return &NetworkMetrics_OnMisbehaviorReported_Call{Call: _e.mock.On("OnMisbehaviorReported", channel, misbehaviorType)} +} + +func (_c *NetworkMetrics_OnMisbehaviorReported_Call) Run(run func(channel string, misbehaviorType string)) *NetworkMetrics_OnMisbehaviorReported_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnMisbehaviorReported_Call) Return() *NetworkMetrics_OnMisbehaviorReported_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnMisbehaviorReported_Call) RunAndReturn(run func(channel string, misbehaviorType string)) *NetworkMetrics_OnMisbehaviorReported_Call { + _c.Run(run) + return _c +} + +// OnOutboundRpcDropped provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnOutboundRpcDropped() { + _mock.Called() + return +} + +// NetworkMetrics_OnOutboundRpcDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOutboundRpcDropped' +type NetworkMetrics_OnOutboundRpcDropped_Call struct { + *mock.Call +} + +// OnOutboundRpcDropped is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnOutboundRpcDropped() *NetworkMetrics_OnOutboundRpcDropped_Call { + return &NetworkMetrics_OnOutboundRpcDropped_Call{Call: _e.mock.On("OnOutboundRpcDropped")} +} + +func (_c *NetworkMetrics_OnOutboundRpcDropped_Call) Run(run func()) *NetworkMetrics_OnOutboundRpcDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnOutboundRpcDropped_Call) Return() *NetworkMetrics_OnOutboundRpcDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnOutboundRpcDropped_Call) RunAndReturn(run func()) *NetworkMetrics_OnOutboundRpcDropped_Call { + _c.Run(run) + return _c +} + +// OnOverallPeerScoreUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnOverallPeerScoreUpdated(f float64) { + _mock.Called(f) + return +} + +// NetworkMetrics_OnOverallPeerScoreUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnOverallPeerScoreUpdated' +type NetworkMetrics_OnOverallPeerScoreUpdated_Call struct { + *mock.Call +} + +// OnOverallPeerScoreUpdated is a helper method to define mock.On call +// - f float64 +func (_e *NetworkMetrics_Expecter) OnOverallPeerScoreUpdated(f interface{}) *NetworkMetrics_OnOverallPeerScoreUpdated_Call { + return &NetworkMetrics_OnOverallPeerScoreUpdated_Call{Call: _e.mock.On("OnOverallPeerScoreUpdated", f)} +} + +func (_c *NetworkMetrics_OnOverallPeerScoreUpdated_Call) Run(run func(f float64)) *NetworkMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 float64 + if args[0] != nil { + arg0 = args[0].(float64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnOverallPeerScoreUpdated_Call) Return() *NetworkMetrics_OnOverallPeerScoreUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnOverallPeerScoreUpdated_Call) RunAndReturn(run func(f float64)) *NetworkMetrics_OnOverallPeerScoreUpdated_Call { + _c.Run(run) + return _c +} + +// OnPeerAddedToProtocol provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPeerAddedToProtocol(protocol1 string) { + _mock.Called(protocol1) + return +} + +// NetworkMetrics_OnPeerAddedToProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerAddedToProtocol' +type NetworkMetrics_OnPeerAddedToProtocol_Call struct { + *mock.Call +} + +// OnPeerAddedToProtocol is a helper method to define mock.On call +// - protocol1 string +func (_e *NetworkMetrics_Expecter) OnPeerAddedToProtocol(protocol1 interface{}) *NetworkMetrics_OnPeerAddedToProtocol_Call { + return &NetworkMetrics_OnPeerAddedToProtocol_Call{Call: _e.mock.On("OnPeerAddedToProtocol", protocol1)} +} + +func (_c *NetworkMetrics_OnPeerAddedToProtocol_Call) Run(run func(protocol1 string)) *NetworkMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnPeerAddedToProtocol_Call) Return() *NetworkMetrics_OnPeerAddedToProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPeerAddedToProtocol_Call) RunAndReturn(run func(protocol1 string)) *NetworkMetrics_OnPeerAddedToProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerDialFailure provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPeerDialFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// NetworkMetrics_OnPeerDialFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerDialFailure' +type NetworkMetrics_OnPeerDialFailure_Call struct { + *mock.Call +} + +// OnPeerDialFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *NetworkMetrics_Expecter) OnPeerDialFailure(duration interface{}, attempts interface{}) *NetworkMetrics_OnPeerDialFailure_Call { + return &NetworkMetrics_OnPeerDialFailure_Call{Call: _e.mock.On("OnPeerDialFailure", duration, attempts)} +} + +func (_c *NetworkMetrics_OnPeerDialFailure_Call) Run(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnPeerDialFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnPeerDialFailure_Call) Return() *NetworkMetrics_OnPeerDialFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPeerDialFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnPeerDialFailure_Call { + _c.Run(run) + return _c +} + +// OnPeerDialed provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPeerDialed(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// NetworkMetrics_OnPeerDialed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerDialed' +type NetworkMetrics_OnPeerDialed_Call struct { + *mock.Call +} + +// OnPeerDialed is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *NetworkMetrics_Expecter) OnPeerDialed(duration interface{}, attempts interface{}) *NetworkMetrics_OnPeerDialed_Call { + return &NetworkMetrics_OnPeerDialed_Call{Call: _e.mock.On("OnPeerDialed", duration, attempts)} +} + +func (_c *NetworkMetrics_OnPeerDialed_Call) Run(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnPeerDialed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnPeerDialed_Call) Return() *NetworkMetrics_OnPeerDialed_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPeerDialed_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnPeerDialed_Call { + _c.Run(run) + return _c +} + +// OnPeerGraftTopic provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPeerGraftTopic(topic string) { + _mock.Called(topic) + return +} + +// NetworkMetrics_OnPeerGraftTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerGraftTopic' +type NetworkMetrics_OnPeerGraftTopic_Call struct { + *mock.Call +} + +// OnPeerGraftTopic is a helper method to define mock.On call +// - topic string +func (_e *NetworkMetrics_Expecter) OnPeerGraftTopic(topic interface{}) *NetworkMetrics_OnPeerGraftTopic_Call { + return &NetworkMetrics_OnPeerGraftTopic_Call{Call: _e.mock.On("OnPeerGraftTopic", topic)} +} + +func (_c *NetworkMetrics_OnPeerGraftTopic_Call) Run(run func(topic string)) *NetworkMetrics_OnPeerGraftTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnPeerGraftTopic_Call) Return() *NetworkMetrics_OnPeerGraftTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPeerGraftTopic_Call) RunAndReturn(run func(topic string)) *NetworkMetrics_OnPeerGraftTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerPruneTopic provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPeerPruneTopic(topic string) { + _mock.Called(topic) + return +} + +// NetworkMetrics_OnPeerPruneTopic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerPruneTopic' +type NetworkMetrics_OnPeerPruneTopic_Call struct { + *mock.Call +} + +// OnPeerPruneTopic is a helper method to define mock.On call +// - topic string +func (_e *NetworkMetrics_Expecter) OnPeerPruneTopic(topic interface{}) *NetworkMetrics_OnPeerPruneTopic_Call { + return &NetworkMetrics_OnPeerPruneTopic_Call{Call: _e.mock.On("OnPeerPruneTopic", topic)} +} + +func (_c *NetworkMetrics_OnPeerPruneTopic_Call) Run(run func(topic string)) *NetworkMetrics_OnPeerPruneTopic_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnPeerPruneTopic_Call) Return() *NetworkMetrics_OnPeerPruneTopic_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPeerPruneTopic_Call) RunAndReturn(run func(topic string)) *NetworkMetrics_OnPeerPruneTopic_Call { + _c.Run(run) + return _c +} + +// OnPeerRemovedFromProtocol provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPeerRemovedFromProtocol() { + _mock.Called() + return +} + +// NetworkMetrics_OnPeerRemovedFromProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerRemovedFromProtocol' +type NetworkMetrics_OnPeerRemovedFromProtocol_Call struct { + *mock.Call +} + +// OnPeerRemovedFromProtocol is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnPeerRemovedFromProtocol() *NetworkMetrics_OnPeerRemovedFromProtocol_Call { + return &NetworkMetrics_OnPeerRemovedFromProtocol_Call{Call: _e.mock.On("OnPeerRemovedFromProtocol")} +} + +func (_c *NetworkMetrics_OnPeerRemovedFromProtocol_Call) Run(run func()) *NetworkMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnPeerRemovedFromProtocol_Call) Return() *NetworkMetrics_OnPeerRemovedFromProtocol_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPeerRemovedFromProtocol_Call) RunAndReturn(run func()) *NetworkMetrics_OnPeerRemovedFromProtocol_Call { + _c.Run(run) + return _c +} + +// OnPeerThrottled provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPeerThrottled() { + _mock.Called() + return +} + +// NetworkMetrics_OnPeerThrottled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerThrottled' +type NetworkMetrics_OnPeerThrottled_Call struct { + *mock.Call +} + +// OnPeerThrottled is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnPeerThrottled() *NetworkMetrics_OnPeerThrottled_Call { + return &NetworkMetrics_OnPeerThrottled_Call{Call: _e.mock.On("OnPeerThrottled")} +} + +func (_c *NetworkMetrics_OnPeerThrottled_Call) Run(run func()) *NetworkMetrics_OnPeerThrottled_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnPeerThrottled_Call) Return() *NetworkMetrics_OnPeerThrottled_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPeerThrottled_Call) RunAndReturn(run func()) *NetworkMetrics_OnPeerThrottled_Call { + _c.Run(run) + return _c +} + +// OnPruneDuplicateTopicIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPruneDuplicateTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneDuplicateTopicIdsExceedThreshold' +type NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneDuplicateTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnPruneDuplicateTopicIdsExceedThreshold() *NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + return &NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneDuplicateTopicIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) Return() *NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnPruneDuplicateTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneInvalidTopicIdsExceedThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPruneInvalidTopicIdsExceedThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneInvalidTopicIdsExceedThreshold' +type NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call struct { + *mock.Call +} + +// OnPruneInvalidTopicIdsExceedThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnPruneInvalidTopicIdsExceedThreshold() *NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + return &NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call{Call: _e.mock.On("OnPruneInvalidTopicIdsExceedThreshold")} +} + +func (_c *NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Run(run func()) *NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) Return() *NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnPruneInvalidTopicIdsExceedThreshold_Call { + _c.Run(run) + return _c +} + +// OnPruneMessageInspected provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPruneMessageInspected(duplicateTopicIds int, invalidTopicIds int) { + _mock.Called(duplicateTopicIds, invalidTopicIds) + return +} + +// NetworkMetrics_OnPruneMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPruneMessageInspected' +type NetworkMetrics_OnPruneMessageInspected_Call struct { + *mock.Call +} + +// OnPruneMessageInspected is a helper method to define mock.On call +// - duplicateTopicIds int +// - invalidTopicIds int +func (_e *NetworkMetrics_Expecter) OnPruneMessageInspected(duplicateTopicIds interface{}, invalidTopicIds interface{}) *NetworkMetrics_OnPruneMessageInspected_Call { + return &NetworkMetrics_OnPruneMessageInspected_Call{Call: _e.mock.On("OnPruneMessageInspected", duplicateTopicIds, invalidTopicIds)} +} + +func (_c *NetworkMetrics_OnPruneMessageInspected_Call) Run(run func(duplicateTopicIds int, invalidTopicIds int)) *NetworkMetrics_OnPruneMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnPruneMessageInspected_Call) Return() *NetworkMetrics_OnPruneMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPruneMessageInspected_Call) RunAndReturn(run func(duplicateTopicIds int, invalidTopicIds int)) *NetworkMetrics_OnPruneMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessageInspected provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPublishMessageInspected(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int) { + _mock.Called(totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount) + return +} + +// NetworkMetrics_OnPublishMessageInspected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessageInspected' +type NetworkMetrics_OnPublishMessageInspected_Call struct { + *mock.Call +} + +// OnPublishMessageInspected is a helper method to define mock.On call +// - totalErrCount int +// - invalidTopicIdsCount int +// - invalidSubscriptionsCount int +// - invalidSendersCount int +func (_e *NetworkMetrics_Expecter) OnPublishMessageInspected(totalErrCount interface{}, invalidTopicIdsCount interface{}, invalidSubscriptionsCount interface{}, invalidSendersCount interface{}) *NetworkMetrics_OnPublishMessageInspected_Call { + return &NetworkMetrics_OnPublishMessageInspected_Call{Call: _e.mock.On("OnPublishMessageInspected", totalErrCount, invalidTopicIdsCount, invalidSubscriptionsCount, invalidSendersCount)} +} + +func (_c *NetworkMetrics_OnPublishMessageInspected_Call) Run(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *NetworkMetrics_OnPublishMessageInspected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnPublishMessageInspected_Call) Return() *NetworkMetrics_OnPublishMessageInspected_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPublishMessageInspected_Call) RunAndReturn(run func(totalErrCount int, invalidTopicIdsCount int, invalidSubscriptionsCount int, invalidSendersCount int)) *NetworkMetrics_OnPublishMessageInspected_Call { + _c.Run(run) + return _c +} + +// OnPublishMessagesInspectionErrorExceedsThreshold provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnPublishMessagesInspectionErrorExceedsThreshold() { + _mock.Called() + return +} + +// NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPublishMessagesInspectionErrorExceedsThreshold' +type NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call struct { + *mock.Call +} + +// OnPublishMessagesInspectionErrorExceedsThreshold is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnPublishMessagesInspectionErrorExceedsThreshold() *NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + return &NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call{Call: _e.mock.On("OnPublishMessagesInspectionErrorExceedsThreshold")} +} + +func (_c *NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Run(run func()) *NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) Return() *NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call) RunAndReturn(run func()) *NetworkMetrics_OnPublishMessagesInspectionErrorExceedsThreshold_Call { + _c.Run(run) + return _c +} + +// OnRateLimitedPeer provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { + _mock.Called(pid, role, msgType, topic, reason) + return +} + +// NetworkMetrics_OnRateLimitedPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRateLimitedPeer' +type NetworkMetrics_OnRateLimitedPeer_Call struct { + *mock.Call +} + +// OnRateLimitedPeer is a helper method to define mock.On call +// - pid peer.ID +// - role string +// - msgType string +// - topic string +// - reason string +func (_e *NetworkMetrics_Expecter) OnRateLimitedPeer(pid interface{}, role interface{}, msgType interface{}, topic interface{}, reason interface{}) *NetworkMetrics_OnRateLimitedPeer_Call { + return &NetworkMetrics_OnRateLimitedPeer_Call{Call: _e.mock.On("OnRateLimitedPeer", pid, role, msgType, topic, reason)} +} + +func (_c *NetworkMetrics_OnRateLimitedPeer_Call) Run(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *NetworkMetrics_OnRateLimitedPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + var arg4 string + if args[4] != nil { + arg4 = args[4].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnRateLimitedPeer_Call) Return() *NetworkMetrics_OnRateLimitedPeer_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnRateLimitedPeer_Call) RunAndReturn(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *NetworkMetrics_OnRateLimitedPeer_Call { + _c.Run(run) + return _c +} + +// OnRpcReceived provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnRpcReceived(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// NetworkMetrics_OnRpcReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcReceived' +type NetworkMetrics_OnRpcReceived_Call struct { + *mock.Call +} + +// OnRpcReceived is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *NetworkMetrics_Expecter) OnRpcReceived(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *NetworkMetrics_OnRpcReceived_Call { + return &NetworkMetrics_OnRpcReceived_Call{Call: _e.mock.On("OnRpcReceived", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *NetworkMetrics_OnRpcReceived_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *NetworkMetrics_OnRpcReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnRpcReceived_Call) Return() *NetworkMetrics_OnRpcReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnRpcReceived_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *NetworkMetrics_OnRpcReceived_Call { + _c.Run(run) + return _c +} + +// OnRpcRejectedFromUnknownSender provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnRpcRejectedFromUnknownSender() { + _mock.Called() + return +} + +// NetworkMetrics_OnRpcRejectedFromUnknownSender_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcRejectedFromUnknownSender' +type NetworkMetrics_OnRpcRejectedFromUnknownSender_Call struct { + *mock.Call +} + +// OnRpcRejectedFromUnknownSender is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnRpcRejectedFromUnknownSender() *NetworkMetrics_OnRpcRejectedFromUnknownSender_Call { + return &NetworkMetrics_OnRpcRejectedFromUnknownSender_Call{Call: _e.mock.On("OnRpcRejectedFromUnknownSender")} +} + +func (_c *NetworkMetrics_OnRpcRejectedFromUnknownSender_Call) Run(run func()) *NetworkMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnRpcRejectedFromUnknownSender_Call) Return() *NetworkMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnRpcRejectedFromUnknownSender_Call) RunAndReturn(run func()) *NetworkMetrics_OnRpcRejectedFromUnknownSender_Call { + _c.Run(run) + return _c +} + +// OnRpcSent provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnRpcSent(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int) { + _mock.Called(msgCount, iHaveCount, iWantCount, graftCount, pruneCount) + return +} + +// NetworkMetrics_OnRpcSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRpcSent' +type NetworkMetrics_OnRpcSent_Call struct { + *mock.Call +} + +// OnRpcSent is a helper method to define mock.On call +// - msgCount int +// - iHaveCount int +// - iWantCount int +// - graftCount int +// - pruneCount int +func (_e *NetworkMetrics_Expecter) OnRpcSent(msgCount interface{}, iHaveCount interface{}, iWantCount interface{}, graftCount interface{}, pruneCount interface{}) *NetworkMetrics_OnRpcSent_Call { + return &NetworkMetrics_OnRpcSent_Call{Call: _e.mock.On("OnRpcSent", msgCount, iHaveCount, iWantCount, graftCount, pruneCount)} +} + +func (_c *NetworkMetrics_OnRpcSent_Call) Run(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *NetworkMetrics_OnRpcSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + var arg3 int + if args[3] != nil { + arg3 = args[3].(int) + } + var arg4 int + if args[4] != nil { + arg4 = args[4].(int) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnRpcSent_Call) Return() *NetworkMetrics_OnRpcSent_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnRpcSent_Call) RunAndReturn(run func(msgCount int, iHaveCount int, iWantCount int, graftCount int, pruneCount int)) *NetworkMetrics_OnRpcSent_Call { + _c.Run(run) + return _c +} + +// OnStreamCreated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnStreamCreated(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// NetworkMetrics_OnStreamCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreated' +type NetworkMetrics_OnStreamCreated_Call struct { + *mock.Call +} + +// OnStreamCreated is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *NetworkMetrics_Expecter) OnStreamCreated(duration interface{}, attempts interface{}) *NetworkMetrics_OnStreamCreated_Call { + return &NetworkMetrics_OnStreamCreated_Call{Call: _e.mock.On("OnStreamCreated", duration, attempts)} +} + +func (_c *NetworkMetrics_OnStreamCreated_Call) Run(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnStreamCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnStreamCreated_Call) Return() *NetworkMetrics_OnStreamCreated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnStreamCreated_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnStreamCreated_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationFailure provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnStreamCreationFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// NetworkMetrics_OnStreamCreationFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationFailure' +type NetworkMetrics_OnStreamCreationFailure_Call struct { + *mock.Call +} + +// OnStreamCreationFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *NetworkMetrics_Expecter) OnStreamCreationFailure(duration interface{}, attempts interface{}) *NetworkMetrics_OnStreamCreationFailure_Call { + return &NetworkMetrics_OnStreamCreationFailure_Call{Call: _e.mock.On("OnStreamCreationFailure", duration, attempts)} +} + +func (_c *NetworkMetrics_OnStreamCreationFailure_Call) Run(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnStreamCreationFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnStreamCreationFailure_Call) Return() *NetworkMetrics_OnStreamCreationFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnStreamCreationFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnStreamCreationFailure_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationRetryBudgetResetToDefault provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnStreamCreationRetryBudgetResetToDefault() { + _mock.Called() + return +} + +// NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationRetryBudgetResetToDefault' +type NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call struct { + *mock.Call +} + +// OnStreamCreationRetryBudgetResetToDefault is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnStreamCreationRetryBudgetResetToDefault() *NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + return &NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call{Call: _e.mock.On("OnStreamCreationRetryBudgetResetToDefault")} +} + +func (_c *NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) Run(run func()) *NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) Return() *NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) RunAndReturn(run func()) *NetworkMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationRetryBudgetUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnStreamCreationRetryBudgetUpdated(budget uint64) { + _mock.Called(budget) + return +} + +// NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationRetryBudgetUpdated' +type NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call struct { + *mock.Call +} + +// OnStreamCreationRetryBudgetUpdated is a helper method to define mock.On call +// - budget uint64 +func (_e *NetworkMetrics_Expecter) OnStreamCreationRetryBudgetUpdated(budget interface{}) *NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call { + return &NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call{Call: _e.mock.On("OnStreamCreationRetryBudgetUpdated", budget)} +} + +func (_c *NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call) Run(run func(budget uint64)) *NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call) Return() *NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call) RunAndReturn(run func(budget uint64)) *NetworkMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Run(run) + return _c +} + +// OnStreamEstablished provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnStreamEstablished(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// NetworkMetrics_OnStreamEstablished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamEstablished' +type NetworkMetrics_OnStreamEstablished_Call struct { + *mock.Call +} + +// OnStreamEstablished is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *NetworkMetrics_Expecter) OnStreamEstablished(duration interface{}, attempts interface{}) *NetworkMetrics_OnStreamEstablished_Call { + return &NetworkMetrics_OnStreamEstablished_Call{Call: _e.mock.On("OnStreamEstablished", duration, attempts)} +} + +func (_c *NetworkMetrics_OnStreamEstablished_Call) Run(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnStreamEstablished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnStreamEstablished_Call) Return() *NetworkMetrics_OnStreamEstablished_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnStreamEstablished_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *NetworkMetrics_OnStreamEstablished_Call { + _c.Run(run) + return _c +} + +// OnTimeInMeshUpdated provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnTimeInMeshUpdated(topic channels.Topic, duration time.Duration) { + _mock.Called(topic, duration) + return +} + +// NetworkMetrics_OnTimeInMeshUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnTimeInMeshUpdated' +type NetworkMetrics_OnTimeInMeshUpdated_Call struct { + *mock.Call +} + +// OnTimeInMeshUpdated is a helper method to define mock.On call +// - topic channels.Topic +// - duration time.Duration +func (_e *NetworkMetrics_Expecter) OnTimeInMeshUpdated(topic interface{}, duration interface{}) *NetworkMetrics_OnTimeInMeshUpdated_Call { + return &NetworkMetrics_OnTimeInMeshUpdated_Call{Call: _e.mock.On("OnTimeInMeshUpdated", topic, duration)} +} + +func (_c *NetworkMetrics_OnTimeInMeshUpdated_Call) Run(run func(topic channels.Topic, duration time.Duration)) *NetworkMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnTimeInMeshUpdated_Call) Return() *NetworkMetrics_OnTimeInMeshUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnTimeInMeshUpdated_Call) RunAndReturn(run func(topic channels.Topic, duration time.Duration)) *NetworkMetrics_OnTimeInMeshUpdated_Call { + _c.Run(run) + return _c +} + +// OnUnauthorizedMessage provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnUnauthorizedMessage(role string, msgType string, topic string, offense string) { + _mock.Called(role, msgType, topic, offense) + return +} + +// NetworkMetrics_OnUnauthorizedMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnauthorizedMessage' +type NetworkMetrics_OnUnauthorizedMessage_Call struct { + *mock.Call +} + +// OnUnauthorizedMessage is a helper method to define mock.On call +// - role string +// - msgType string +// - topic string +// - offense string +func (_e *NetworkMetrics_Expecter) OnUnauthorizedMessage(role interface{}, msgType interface{}, topic interface{}, offense interface{}) *NetworkMetrics_OnUnauthorizedMessage_Call { + return &NetworkMetrics_OnUnauthorizedMessage_Call{Call: _e.mock.On("OnUnauthorizedMessage", role, msgType, topic, offense)} +} + +func (_c *NetworkMetrics_OnUnauthorizedMessage_Call) Run(run func(role string, msgType string, topic string, offense string)) *NetworkMetrics_OnUnauthorizedMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OnUnauthorizedMessage_Call) Return() *NetworkMetrics_OnUnauthorizedMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnUnauthorizedMessage_Call) RunAndReturn(run func(role string, msgType string, topic string, offense string)) *NetworkMetrics_OnUnauthorizedMessage_Call { + _c.Run(run) + return _c +} + +// OnUndeliveredMessage provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnUndeliveredMessage() { + _mock.Called() + return +} + +// NetworkMetrics_OnUndeliveredMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUndeliveredMessage' +type NetworkMetrics_OnUndeliveredMessage_Call struct { + *mock.Call +} + +// OnUndeliveredMessage is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnUndeliveredMessage() *NetworkMetrics_OnUndeliveredMessage_Call { + return &NetworkMetrics_OnUndeliveredMessage_Call{Call: _e.mock.On("OnUndeliveredMessage")} +} + +func (_c *NetworkMetrics_OnUndeliveredMessage_Call) Run(run func()) *NetworkMetrics_OnUndeliveredMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnUndeliveredMessage_Call) Return() *NetworkMetrics_OnUndeliveredMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnUndeliveredMessage_Call) RunAndReturn(run func()) *NetworkMetrics_OnUndeliveredMessage_Call { + _c.Run(run) + return _c +} + +// OnUnstakedPeerInspectionFailed provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnUnstakedPeerInspectionFailed() { + _mock.Called() + return +} + +// NetworkMetrics_OnUnstakedPeerInspectionFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnstakedPeerInspectionFailed' +type NetworkMetrics_OnUnstakedPeerInspectionFailed_Call struct { + *mock.Call +} + +// OnUnstakedPeerInspectionFailed is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnUnstakedPeerInspectionFailed() *NetworkMetrics_OnUnstakedPeerInspectionFailed_Call { + return &NetworkMetrics_OnUnstakedPeerInspectionFailed_Call{Call: _e.mock.On("OnUnstakedPeerInspectionFailed")} +} + +func (_c *NetworkMetrics_OnUnstakedPeerInspectionFailed_Call) Run(run func()) *NetworkMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnUnstakedPeerInspectionFailed_Call) Return() *NetworkMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnUnstakedPeerInspectionFailed_Call) RunAndReturn(run func()) *NetworkMetrics_OnUnstakedPeerInspectionFailed_Call { + _c.Run(run) + return _c +} + +// OnViolationReportSkipped provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OnViolationReportSkipped() { + _mock.Called() + return +} + +// NetworkMetrics_OnViolationReportSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnViolationReportSkipped' +type NetworkMetrics_OnViolationReportSkipped_Call struct { + *mock.Call +} + +// OnViolationReportSkipped is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) OnViolationReportSkipped() *NetworkMetrics_OnViolationReportSkipped_Call { + return &NetworkMetrics_OnViolationReportSkipped_Call{Call: _e.mock.On("OnViolationReportSkipped")} +} + +func (_c *NetworkMetrics_OnViolationReportSkipped_Call) Run(run func()) *NetworkMetrics_OnViolationReportSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_OnViolationReportSkipped_Call) Return() *NetworkMetrics_OnViolationReportSkipped_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OnViolationReportSkipped_Call) RunAndReturn(run func()) *NetworkMetrics_OnViolationReportSkipped_Call { + _c.Run(run) + return _c +} + +// OutboundConnections provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OutboundConnections(connectionCount uint) { + _mock.Called(connectionCount) + return +} + +// NetworkMetrics_OutboundConnections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OutboundConnections' +type NetworkMetrics_OutboundConnections_Call struct { + *mock.Call +} + +// OutboundConnections is a helper method to define mock.On call +// - connectionCount uint +func (_e *NetworkMetrics_Expecter) OutboundConnections(connectionCount interface{}) *NetworkMetrics_OutboundConnections_Call { + return &NetworkMetrics_OutboundConnections_Call{Call: _e.mock.On("OutboundConnections", connectionCount)} +} + +func (_c *NetworkMetrics_OutboundConnections_Call) Run(run func(connectionCount uint)) *NetworkMetrics_OutboundConnections_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OutboundConnections_Call) Return() *NetworkMetrics_OutboundConnections_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OutboundConnections_Call) RunAndReturn(run func(connectionCount uint)) *NetworkMetrics_OutboundConnections_Call { + _c.Run(run) + return _c +} + +// OutboundMessageSent provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) OutboundMessageSent(sizeBytes int, topic string, protocol1 string, messageType string) { + _mock.Called(sizeBytes, topic, protocol1, messageType) + return +} + +// NetworkMetrics_OutboundMessageSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OutboundMessageSent' +type NetworkMetrics_OutboundMessageSent_Call struct { + *mock.Call +} + +// OutboundMessageSent is a helper method to define mock.On call +// - sizeBytes int +// - topic string +// - protocol1 string +// - messageType string +func (_e *NetworkMetrics_Expecter) OutboundMessageSent(sizeBytes interface{}, topic interface{}, protocol1 interface{}, messageType interface{}) *NetworkMetrics_OutboundMessageSent_Call { + return &NetworkMetrics_OutboundMessageSent_Call{Call: _e.mock.On("OutboundMessageSent", sizeBytes, topic, protocol1, messageType)} +} + +func (_c *NetworkMetrics_OutboundMessageSent_Call) Run(run func(sizeBytes int, topic string, protocol1 string, messageType string)) *NetworkMetrics_OutboundMessageSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NetworkMetrics_OutboundMessageSent_Call) Return() *NetworkMetrics_OutboundMessageSent_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_OutboundMessageSent_Call) RunAndReturn(run func(sizeBytes int, topic string, protocol1 string, messageType string)) *NetworkMetrics_OutboundMessageSent_Call { + _c.Run(run) + return _c +} + +// QueueDuration provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) QueueDuration(duration time.Duration, priority int) { + _mock.Called(duration, priority) + return +} + +// NetworkMetrics_QueueDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QueueDuration' +type NetworkMetrics_QueueDuration_Call struct { + *mock.Call +} + +// QueueDuration is a helper method to define mock.On call +// - duration time.Duration +// - priority int +func (_e *NetworkMetrics_Expecter) QueueDuration(duration interface{}, priority interface{}) *NetworkMetrics_QueueDuration_Call { + return &NetworkMetrics_QueueDuration_Call{Call: _e.mock.On("QueueDuration", duration, priority)} +} + +func (_c *NetworkMetrics_QueueDuration_Call) Run(run func(duration time.Duration, priority int)) *NetworkMetrics_QueueDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NetworkMetrics_QueueDuration_Call) Return() *NetworkMetrics_QueueDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_QueueDuration_Call) RunAndReturn(run func(duration time.Duration, priority int)) *NetworkMetrics_QueueDuration_Call { + _c.Run(run) + return _c +} + +// RoutingTablePeerAdded provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) RoutingTablePeerAdded() { + _mock.Called() + return +} + +// NetworkMetrics_RoutingTablePeerAdded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTablePeerAdded' +type NetworkMetrics_RoutingTablePeerAdded_Call struct { + *mock.Call +} + +// RoutingTablePeerAdded is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) RoutingTablePeerAdded() *NetworkMetrics_RoutingTablePeerAdded_Call { + return &NetworkMetrics_RoutingTablePeerAdded_Call{Call: _e.mock.On("RoutingTablePeerAdded")} +} + +func (_c *NetworkMetrics_RoutingTablePeerAdded_Call) Run(run func()) *NetworkMetrics_RoutingTablePeerAdded_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_RoutingTablePeerAdded_Call) Return() *NetworkMetrics_RoutingTablePeerAdded_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_RoutingTablePeerAdded_Call) RunAndReturn(run func()) *NetworkMetrics_RoutingTablePeerAdded_Call { + _c.Run(run) + return _c +} + +// RoutingTablePeerRemoved provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) RoutingTablePeerRemoved() { + _mock.Called() + return +} + +// NetworkMetrics_RoutingTablePeerRemoved_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTablePeerRemoved' +type NetworkMetrics_RoutingTablePeerRemoved_Call struct { + *mock.Call +} + +// RoutingTablePeerRemoved is a helper method to define mock.On call +func (_e *NetworkMetrics_Expecter) RoutingTablePeerRemoved() *NetworkMetrics_RoutingTablePeerRemoved_Call { + return &NetworkMetrics_RoutingTablePeerRemoved_Call{Call: _e.mock.On("RoutingTablePeerRemoved")} +} + +func (_c *NetworkMetrics_RoutingTablePeerRemoved_Call) Run(run func()) *NetworkMetrics_RoutingTablePeerRemoved_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkMetrics_RoutingTablePeerRemoved_Call) Return() *NetworkMetrics_RoutingTablePeerRemoved_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_RoutingTablePeerRemoved_Call) RunAndReturn(run func()) *NetworkMetrics_RoutingTablePeerRemoved_Call { + _c.Run(run) + return _c +} + +// SetWarningStateCount provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) SetWarningStateCount(v uint) { + _mock.Called(v) + return +} + +// NetworkMetrics_SetWarningStateCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetWarningStateCount' +type NetworkMetrics_SetWarningStateCount_Call struct { + *mock.Call +} + +// SetWarningStateCount is a helper method to define mock.On call +// - v uint +func (_e *NetworkMetrics_Expecter) SetWarningStateCount(v interface{}) *NetworkMetrics_SetWarningStateCount_Call { + return &NetworkMetrics_SetWarningStateCount_Call{Call: _e.mock.On("SetWarningStateCount", v)} +} + +func (_c *NetworkMetrics_SetWarningStateCount_Call) Run(run func(v uint)) *NetworkMetrics_SetWarningStateCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_SetWarningStateCount_Call) Return() *NetworkMetrics_SetWarningStateCount_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_SetWarningStateCount_Call) RunAndReturn(run func(v uint)) *NetworkMetrics_SetWarningStateCount_Call { + _c.Run(run) + return _c +} + +// UnicastMessageSendingCompleted provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) UnicastMessageSendingCompleted(topic string) { + _mock.Called(topic) + return +} + +// NetworkMetrics_UnicastMessageSendingCompleted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnicastMessageSendingCompleted' +type NetworkMetrics_UnicastMessageSendingCompleted_Call struct { + *mock.Call +} + +// UnicastMessageSendingCompleted is a helper method to define mock.On call +// - topic string +func (_e *NetworkMetrics_Expecter) UnicastMessageSendingCompleted(topic interface{}) *NetworkMetrics_UnicastMessageSendingCompleted_Call { + return &NetworkMetrics_UnicastMessageSendingCompleted_Call{Call: _e.mock.On("UnicastMessageSendingCompleted", topic)} +} + +func (_c *NetworkMetrics_UnicastMessageSendingCompleted_Call) Run(run func(topic string)) *NetworkMetrics_UnicastMessageSendingCompleted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_UnicastMessageSendingCompleted_Call) Return() *NetworkMetrics_UnicastMessageSendingCompleted_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_UnicastMessageSendingCompleted_Call) RunAndReturn(run func(topic string)) *NetworkMetrics_UnicastMessageSendingCompleted_Call { + _c.Run(run) + return _c +} + +// UnicastMessageSendingStarted provides a mock function for the type NetworkMetrics +func (_mock *NetworkMetrics) UnicastMessageSendingStarted(topic string) { + _mock.Called(topic) + return +} + +// NetworkMetrics_UnicastMessageSendingStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnicastMessageSendingStarted' +type NetworkMetrics_UnicastMessageSendingStarted_Call struct { + *mock.Call +} + +// UnicastMessageSendingStarted is a helper method to define mock.On call +// - topic string +func (_e *NetworkMetrics_Expecter) UnicastMessageSendingStarted(topic interface{}) *NetworkMetrics_UnicastMessageSendingStarted_Call { + return &NetworkMetrics_UnicastMessageSendingStarted_Call{Call: _e.mock.On("UnicastMessageSendingStarted", topic)} +} + +func (_c *NetworkMetrics_UnicastMessageSendingStarted_Call) Run(run func(topic string)) *NetworkMetrics_UnicastMessageSendingStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NetworkMetrics_UnicastMessageSendingStarted_Call) Return() *NetworkMetrics_UnicastMessageSendingStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkMetrics_UnicastMessageSendingStarted_Call) RunAndReturn(run func(topic string)) *NetworkMetrics_UnicastMessageSendingStarted_Call { + _c.Run(run) + return _c } diff --git a/module/mock/network_security_metrics.go b/module/mock/network_security_metrics.go index f8d50d5b71b..fc1e060a970 100644 --- a/module/mock/network_security_metrics.go +++ b/module/mock/network_security_metrics.go @@ -1,43 +1,192 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewNetworkSecurityMetrics creates a new instance of NetworkSecurityMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNetworkSecurityMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *NetworkSecurityMetrics { + mock := &NetworkSecurityMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // NetworkSecurityMetrics is an autogenerated mock type for the NetworkSecurityMetrics type type NetworkSecurityMetrics struct { mock.Mock } -// OnRateLimitedPeer provides a mock function with given fields: pid, role, msgType, topic, reason -func (_m *NetworkSecurityMetrics) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { - _m.Called(pid, role, msgType, topic, reason) +type NetworkSecurityMetrics_Expecter struct { + mock *mock.Mock } -// OnUnauthorizedMessage provides a mock function with given fields: role, msgType, topic, offense -func (_m *NetworkSecurityMetrics) OnUnauthorizedMessage(role string, msgType string, topic string, offense string) { - _m.Called(role, msgType, topic, offense) +func (_m *NetworkSecurityMetrics) EXPECT() *NetworkSecurityMetrics_Expecter { + return &NetworkSecurityMetrics_Expecter{mock: &_m.Mock} } -// OnViolationReportSkipped provides a mock function with no fields -func (_m *NetworkSecurityMetrics) OnViolationReportSkipped() { - _m.Called() +// OnRateLimitedPeer provides a mock function for the type NetworkSecurityMetrics +func (_mock *NetworkSecurityMetrics) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { + _mock.Called(pid, role, msgType, topic, reason) + return } -// NewNetworkSecurityMetrics creates a new instance of NetworkSecurityMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNetworkSecurityMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *NetworkSecurityMetrics { - mock := &NetworkSecurityMetrics{} - mock.Mock.Test(t) +// NetworkSecurityMetrics_OnRateLimitedPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRateLimitedPeer' +type NetworkSecurityMetrics_OnRateLimitedPeer_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnRateLimitedPeer is a helper method to define mock.On call +// - pid peer.ID +// - role string +// - msgType string +// - topic string +// - reason string +func (_e *NetworkSecurityMetrics_Expecter) OnRateLimitedPeer(pid interface{}, role interface{}, msgType interface{}, topic interface{}, reason interface{}) *NetworkSecurityMetrics_OnRateLimitedPeer_Call { + return &NetworkSecurityMetrics_OnRateLimitedPeer_Call{Call: _e.mock.On("OnRateLimitedPeer", pid, role, msgType, topic, reason)} +} - return mock +func (_c *NetworkSecurityMetrics_OnRateLimitedPeer_Call) Run(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *NetworkSecurityMetrics_OnRateLimitedPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + var arg4 string + if args[4] != nil { + arg4 = args[4].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *NetworkSecurityMetrics_OnRateLimitedPeer_Call) Return() *NetworkSecurityMetrics_OnRateLimitedPeer_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkSecurityMetrics_OnRateLimitedPeer_Call) RunAndReturn(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *NetworkSecurityMetrics_OnRateLimitedPeer_Call { + _c.Run(run) + return _c +} + +// OnUnauthorizedMessage provides a mock function for the type NetworkSecurityMetrics +func (_mock *NetworkSecurityMetrics) OnUnauthorizedMessage(role string, msgType string, topic string, offense string) { + _mock.Called(role, msgType, topic, offense) + return +} + +// NetworkSecurityMetrics_OnUnauthorizedMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnauthorizedMessage' +type NetworkSecurityMetrics_OnUnauthorizedMessage_Call struct { + *mock.Call +} + +// OnUnauthorizedMessage is a helper method to define mock.On call +// - role string +// - msgType string +// - topic string +// - offense string +func (_e *NetworkSecurityMetrics_Expecter) OnUnauthorizedMessage(role interface{}, msgType interface{}, topic interface{}, offense interface{}) *NetworkSecurityMetrics_OnUnauthorizedMessage_Call { + return &NetworkSecurityMetrics_OnUnauthorizedMessage_Call{Call: _e.mock.On("OnUnauthorizedMessage", role, msgType, topic, offense)} +} + +func (_c *NetworkSecurityMetrics_OnUnauthorizedMessage_Call) Run(run func(role string, msgType string, topic string, offense string)) *NetworkSecurityMetrics_OnUnauthorizedMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NetworkSecurityMetrics_OnUnauthorizedMessage_Call) Return() *NetworkSecurityMetrics_OnUnauthorizedMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkSecurityMetrics_OnUnauthorizedMessage_Call) RunAndReturn(run func(role string, msgType string, topic string, offense string)) *NetworkSecurityMetrics_OnUnauthorizedMessage_Call { + _c.Run(run) + return _c +} + +// OnViolationReportSkipped provides a mock function for the type NetworkSecurityMetrics +func (_mock *NetworkSecurityMetrics) OnViolationReportSkipped() { + _mock.Called() + return +} + +// NetworkSecurityMetrics_OnViolationReportSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnViolationReportSkipped' +type NetworkSecurityMetrics_OnViolationReportSkipped_Call struct { + *mock.Call +} + +// OnViolationReportSkipped is a helper method to define mock.On call +func (_e *NetworkSecurityMetrics_Expecter) OnViolationReportSkipped() *NetworkSecurityMetrics_OnViolationReportSkipped_Call { + return &NetworkSecurityMetrics_OnViolationReportSkipped_Call{Call: _e.mock.On("OnViolationReportSkipped")} +} + +func (_c *NetworkSecurityMetrics_OnViolationReportSkipped_Call) Run(run func()) *NetworkSecurityMetrics_OnViolationReportSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NetworkSecurityMetrics_OnViolationReportSkipped_Call) Return() *NetworkSecurityMetrics_OnViolationReportSkipped_Call { + _c.Call.Return() + return _c +} + +func (_c *NetworkSecurityMetrics_OnViolationReportSkipped_Call) RunAndReturn(run func()) *NetworkSecurityMetrics_OnViolationReportSkipped_Call { + _c.Run(run) + return _c } diff --git a/module/mock/new_job_listener.go b/module/mock/new_job_listener.go index 1e4d864f8a5..d8ba0fc3052 100644 --- a/module/mock/new_job_listener.go +++ b/module/mock/new_job_listener.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// NewJobListener is an autogenerated mock type for the NewJobListener type -type NewJobListener struct { - mock.Mock -} - -// Check provides a mock function with no fields -func (_m *NewJobListener) Check() { - _m.Called() -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewNewJobListener creates a new instance of NewJobListener. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,49 @@ func NewNewJobListener(t interface { return mock } + +// NewJobListener is an autogenerated mock type for the NewJobListener type +type NewJobListener struct { + mock.Mock +} + +type NewJobListener_Expecter struct { + mock *mock.Mock +} + +func (_m *NewJobListener) EXPECT() *NewJobListener_Expecter { + return &NewJobListener_Expecter{mock: &_m.Mock} +} + +// Check provides a mock function for the type NewJobListener +func (_mock *NewJobListener) Check() { + _mock.Called() + return +} + +// NewJobListener_Check_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Check' +type NewJobListener_Check_Call struct { + *mock.Call +} + +// Check is a helper method to define mock.On call +func (_e *NewJobListener_Expecter) Check() *NewJobListener_Check_Call { + return &NewJobListener_Check_Call{Call: _e.mock.On("Check")} +} + +func (_c *NewJobListener_Check_Call) Run(run func()) *NewJobListener_Check_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NewJobListener_Check_Call) Return() *NewJobListener_Check_Call { + _c.Call.Return() + return _c +} + +func (_c *NewJobListener_Check_Call) RunAndReturn(run func()) *NewJobListener_Check_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/pending_block_buffer.go b/module/mock/pending_block_buffer.go index f9ecd30f752..420a11a7b66 100644 --- a/module/mock/pending_block_buffer.go +++ b/module/mock/pending_block_buffer.go @@ -1,38 +1,95 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewPendingBlockBuffer creates a new instance of PendingBlockBuffer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPendingBlockBuffer(t interface { + mock.TestingT + Cleanup(func()) +}) *PendingBlockBuffer { + mock := &PendingBlockBuffer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // PendingBlockBuffer is an autogenerated mock type for the PendingBlockBuffer type type PendingBlockBuffer struct { mock.Mock } -// Add provides a mock function with given fields: block -func (_m *PendingBlockBuffer) Add(block flow.Slashable[*flow.Proposal]) bool { - ret := _m.Called(block) +type PendingBlockBuffer_Expecter struct { + mock *mock.Mock +} + +func (_m *PendingBlockBuffer) EXPECT() *PendingBlockBuffer_Expecter { + return &PendingBlockBuffer_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type PendingBlockBuffer +func (_mock *PendingBlockBuffer) Add(block flow.Slashable[*flow.Proposal]) bool { + ret := _mock.Called(block) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Slashable[*flow.Proposal]) bool); ok { - r0 = rf(block) + if returnFunc, ok := ret.Get(0).(func(flow.Slashable[*flow.Proposal]) bool); ok { + r0 = returnFunc(block) } else { r0 = ret.Get(0).(bool) } - return r0 } -// ByID provides a mock function with given fields: blockID -func (_m *PendingBlockBuffer) ByID(blockID flow.Identifier) (flow.Slashable[*flow.Proposal], bool) { - ret := _m.Called(blockID) +// PendingBlockBuffer_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type PendingBlockBuffer_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - block flow.Slashable[*flow.Proposal] +func (_e *PendingBlockBuffer_Expecter) Add(block interface{}) *PendingBlockBuffer_Add_Call { + return &PendingBlockBuffer_Add_Call{Call: _e.mock.On("Add", block)} +} + +func (_c *PendingBlockBuffer_Add_Call) Run(run func(block flow.Slashable[*flow.Proposal])) *PendingBlockBuffer_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[*flow.Proposal] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[*flow.Proposal]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingBlockBuffer_Add_Call) Return(b bool) *PendingBlockBuffer_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *PendingBlockBuffer_Add_Call) RunAndReturn(run func(block flow.Slashable[*flow.Proposal]) bool) *PendingBlockBuffer_Add_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type PendingBlockBuffer +func (_mock *PendingBlockBuffer) ByID(blockID flow.Identifier) (flow.Slashable[*flow.Proposal], bool) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -40,27 +97,59 @@ func (_m *PendingBlockBuffer) ByID(blockID flow.Identifier) (flow.Slashable[*flo var r0 flow.Slashable[*flow.Proposal] var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.Slashable[*flow.Proposal], bool)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Slashable[*flow.Proposal], bool)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.Slashable[*flow.Proposal]); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Slashable[*flow.Proposal]); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Get(0).(flow.Slashable[*flow.Proposal]) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// ByParentID provides a mock function with given fields: parentID -func (_m *PendingBlockBuffer) ByParentID(parentID flow.Identifier) ([]flow.Slashable[*flow.Proposal], bool) { - ret := _m.Called(parentID) +// PendingBlockBuffer_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type PendingBlockBuffer_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *PendingBlockBuffer_Expecter) ByID(blockID interface{}) *PendingBlockBuffer_ByID_Call { + return &PendingBlockBuffer_ByID_Call{Call: _e.mock.On("ByID", blockID)} +} + +func (_c *PendingBlockBuffer_ByID_Call) Run(run func(blockID flow.Identifier)) *PendingBlockBuffer_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingBlockBuffer_ByID_Call) Return(slashable flow.Slashable[*flow.Proposal], b bool) *PendingBlockBuffer_ByID_Call { + _c.Call.Return(slashable, b) + return _c +} + +func (_c *PendingBlockBuffer_ByID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.Slashable[*flow.Proposal], bool)) *PendingBlockBuffer_ByID_Call { + _c.Call.Return(run) + return _c +} + +// ByParentID provides a mock function for the type PendingBlockBuffer +func (_mock *PendingBlockBuffer) ByParentID(parentID flow.Identifier) ([]flow.Slashable[*flow.Proposal], bool) { + ret := _mock.Called(parentID) if len(ret) == 0 { panic("no return value specified for ByParentID") @@ -68,64 +157,178 @@ func (_m *PendingBlockBuffer) ByParentID(parentID flow.Identifier) ([]flow.Slash var r0 []flow.Slashable[*flow.Proposal] var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Slashable[*flow.Proposal], bool)); ok { - return rf(parentID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Slashable[*flow.Proposal], bool)); ok { + return returnFunc(parentID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.Slashable[*flow.Proposal]); ok { - r0 = rf(parentID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.Slashable[*flow.Proposal]); ok { + r0 = returnFunc(parentID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Slashable[*flow.Proposal]) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(parentID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(parentID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// DropForParent provides a mock function with given fields: parentID -func (_m *PendingBlockBuffer) DropForParent(parentID flow.Identifier) { - _m.Called(parentID) +// PendingBlockBuffer_ByParentID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByParentID' +type PendingBlockBuffer_ByParentID_Call struct { + *mock.Call } -// PruneByView provides a mock function with given fields: view -func (_m *PendingBlockBuffer) PruneByView(view uint64) { - _m.Called(view) +// ByParentID is a helper method to define mock.On call +// - parentID flow.Identifier +func (_e *PendingBlockBuffer_Expecter) ByParentID(parentID interface{}) *PendingBlockBuffer_ByParentID_Call { + return &PendingBlockBuffer_ByParentID_Call{Call: _e.mock.On("ByParentID", parentID)} } -// Size provides a mock function with no fields -func (_m *PendingBlockBuffer) Size() uint { - ret := _m.Called() +func (_c *PendingBlockBuffer_ByParentID_Call) Run(run func(parentID flow.Identifier)) *PendingBlockBuffer_ByParentID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingBlockBuffer_ByParentID_Call) Return(slashables []flow.Slashable[*flow.Proposal], b bool) *PendingBlockBuffer_ByParentID_Call { + _c.Call.Return(slashables, b) + return _c +} + +func (_c *PendingBlockBuffer_ByParentID_Call) RunAndReturn(run func(parentID flow.Identifier) ([]flow.Slashable[*flow.Proposal], bool)) *PendingBlockBuffer_ByParentID_Call { + _c.Call.Return(run) + return _c +} + +// DropForParent provides a mock function for the type PendingBlockBuffer +func (_mock *PendingBlockBuffer) DropForParent(parentID flow.Identifier) { + _mock.Called(parentID) + return +} + +// PendingBlockBuffer_DropForParent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DropForParent' +type PendingBlockBuffer_DropForParent_Call struct { + *mock.Call +} + +// DropForParent is a helper method to define mock.On call +// - parentID flow.Identifier +func (_e *PendingBlockBuffer_Expecter) DropForParent(parentID interface{}) *PendingBlockBuffer_DropForParent_Call { + return &PendingBlockBuffer_DropForParent_Call{Call: _e.mock.On("DropForParent", parentID)} +} + +func (_c *PendingBlockBuffer_DropForParent_Call) Run(run func(parentID flow.Identifier)) *PendingBlockBuffer_DropForParent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingBlockBuffer_DropForParent_Call) Return() *PendingBlockBuffer_DropForParent_Call { + _c.Call.Return() + return _c +} + +func (_c *PendingBlockBuffer_DropForParent_Call) RunAndReturn(run func(parentID flow.Identifier)) *PendingBlockBuffer_DropForParent_Call { + _c.Run(run) + return _c +} + +// PruneByView provides a mock function for the type PendingBlockBuffer +func (_mock *PendingBlockBuffer) PruneByView(view uint64) { + _mock.Called(view) + return +} + +// PendingBlockBuffer_PruneByView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneByView' +type PendingBlockBuffer_PruneByView_Call struct { + *mock.Call +} + +// PruneByView is a helper method to define mock.On call +// - view uint64 +func (_e *PendingBlockBuffer_Expecter) PruneByView(view interface{}) *PendingBlockBuffer_PruneByView_Call { + return &PendingBlockBuffer_PruneByView_Call{Call: _e.mock.On("PruneByView", view)} +} + +func (_c *PendingBlockBuffer_PruneByView_Call) Run(run func(view uint64)) *PendingBlockBuffer_PruneByView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingBlockBuffer_PruneByView_Call) Return() *PendingBlockBuffer_PruneByView_Call { + _c.Call.Return() + return _c +} + +func (_c *PendingBlockBuffer_PruneByView_Call) RunAndReturn(run func(view uint64)) *PendingBlockBuffer_PruneByView_Call { + _c.Run(run) + return _c +} + +// Size provides a mock function for the type PendingBlockBuffer +func (_mock *PendingBlockBuffer) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewPendingBlockBuffer creates a new instance of PendingBlockBuffer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPendingBlockBuffer(t interface { - mock.TestingT - Cleanup(func()) -}) *PendingBlockBuffer { - mock := &PendingBlockBuffer{} - mock.Mock.Test(t) +// PendingBlockBuffer_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type PendingBlockBuffer_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *PendingBlockBuffer_Expecter) Size() *PendingBlockBuffer_Size_Call { + return &PendingBlockBuffer_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *PendingBlockBuffer_Size_Call) Run(run func()) *PendingBlockBuffer_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PendingBlockBuffer_Size_Call) Return(v uint) *PendingBlockBuffer_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *PendingBlockBuffer_Size_Call) RunAndReturn(run func() uint) *PendingBlockBuffer_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/pending_cluster_block_buffer.go b/module/mock/pending_cluster_block_buffer.go index d23cf6228a4..15d5829cf9d 100644 --- a/module/mock/pending_cluster_block_buffer.go +++ b/module/mock/pending_cluster_block_buffer.go @@ -1,40 +1,96 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cluster "github.com/onflow/flow-go/model/cluster" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewPendingClusterBlockBuffer creates a new instance of PendingClusterBlockBuffer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPendingClusterBlockBuffer(t interface { + mock.TestingT + Cleanup(func()) +}) *PendingClusterBlockBuffer { + mock := &PendingClusterBlockBuffer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // PendingClusterBlockBuffer is an autogenerated mock type for the PendingClusterBlockBuffer type type PendingClusterBlockBuffer struct { mock.Mock } -// Add provides a mock function with given fields: block -func (_m *PendingClusterBlockBuffer) Add(block flow.Slashable[*cluster.Proposal]) bool { - ret := _m.Called(block) +type PendingClusterBlockBuffer_Expecter struct { + mock *mock.Mock +} + +func (_m *PendingClusterBlockBuffer) EXPECT() *PendingClusterBlockBuffer_Expecter { + return &PendingClusterBlockBuffer_Expecter{mock: &_m.Mock} +} + +// Add provides a mock function for the type PendingClusterBlockBuffer +func (_mock *PendingClusterBlockBuffer) Add(block flow.Slashable[*cluster.Proposal]) bool { + ret := _mock.Called(block) if len(ret) == 0 { panic("no return value specified for Add") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Slashable[*cluster.Proposal]) bool); ok { - r0 = rf(block) + if returnFunc, ok := ret.Get(0).(func(flow.Slashable[*cluster.Proposal]) bool); ok { + r0 = returnFunc(block) } else { r0 = ret.Get(0).(bool) } - return r0 } -// ByID provides a mock function with given fields: blockID -func (_m *PendingClusterBlockBuffer) ByID(blockID flow.Identifier) (flow.Slashable[*cluster.Proposal], bool) { - ret := _m.Called(blockID) +// PendingClusterBlockBuffer_Add_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Add' +type PendingClusterBlockBuffer_Add_Call struct { + *mock.Call +} + +// Add is a helper method to define mock.On call +// - block flow.Slashable[*cluster.Proposal] +func (_e *PendingClusterBlockBuffer_Expecter) Add(block interface{}) *PendingClusterBlockBuffer_Add_Call { + return &PendingClusterBlockBuffer_Add_Call{Call: _e.mock.On("Add", block)} +} + +func (_c *PendingClusterBlockBuffer_Add_Call) Run(run func(block flow.Slashable[*cluster.Proposal])) *PendingClusterBlockBuffer_Add_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Slashable[*cluster.Proposal] + if args[0] != nil { + arg0 = args[0].(flow.Slashable[*cluster.Proposal]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingClusterBlockBuffer_Add_Call) Return(b bool) *PendingClusterBlockBuffer_Add_Call { + _c.Call.Return(b) + return _c +} + +func (_c *PendingClusterBlockBuffer_Add_Call) RunAndReturn(run func(block flow.Slashable[*cluster.Proposal]) bool) *PendingClusterBlockBuffer_Add_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type PendingClusterBlockBuffer +func (_mock *PendingClusterBlockBuffer) ByID(blockID flow.Identifier) (flow.Slashable[*cluster.Proposal], bool) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -42,27 +98,59 @@ func (_m *PendingClusterBlockBuffer) ByID(blockID flow.Identifier) (flow.Slashab var r0 flow.Slashable[*cluster.Proposal] var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.Slashable[*cluster.Proposal], bool)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Slashable[*cluster.Proposal], bool)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.Slashable[*cluster.Proposal]); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Slashable[*cluster.Proposal]); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Get(0).(flow.Slashable[*cluster.Proposal]) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// ByParentID provides a mock function with given fields: parentID -func (_m *PendingClusterBlockBuffer) ByParentID(parentID flow.Identifier) ([]flow.Slashable[*cluster.Proposal], bool) { - ret := _m.Called(parentID) +// PendingClusterBlockBuffer_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type PendingClusterBlockBuffer_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *PendingClusterBlockBuffer_Expecter) ByID(blockID interface{}) *PendingClusterBlockBuffer_ByID_Call { + return &PendingClusterBlockBuffer_ByID_Call{Call: _e.mock.On("ByID", blockID)} +} + +func (_c *PendingClusterBlockBuffer_ByID_Call) Run(run func(blockID flow.Identifier)) *PendingClusterBlockBuffer_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingClusterBlockBuffer_ByID_Call) Return(slashable flow.Slashable[*cluster.Proposal], b bool) *PendingClusterBlockBuffer_ByID_Call { + _c.Call.Return(slashable, b) + return _c +} + +func (_c *PendingClusterBlockBuffer_ByID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.Slashable[*cluster.Proposal], bool)) *PendingClusterBlockBuffer_ByID_Call { + _c.Call.Return(run) + return _c +} + +// ByParentID provides a mock function for the type PendingClusterBlockBuffer +func (_mock *PendingClusterBlockBuffer) ByParentID(parentID flow.Identifier) ([]flow.Slashable[*cluster.Proposal], bool) { + ret := _mock.Called(parentID) if len(ret) == 0 { panic("no return value specified for ByParentID") @@ -70,64 +158,178 @@ func (_m *PendingClusterBlockBuffer) ByParentID(parentID flow.Identifier) ([]flo var r0 []flow.Slashable[*cluster.Proposal] var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Slashable[*cluster.Proposal], bool)); ok { - return rf(parentID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Slashable[*cluster.Proposal], bool)); ok { + return returnFunc(parentID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.Slashable[*cluster.Proposal]); ok { - r0 = rf(parentID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.Slashable[*cluster.Proposal]); ok { + r0 = returnFunc(parentID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Slashable[*cluster.Proposal]) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(parentID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(parentID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// DropForParent provides a mock function with given fields: parentID -func (_m *PendingClusterBlockBuffer) DropForParent(parentID flow.Identifier) { - _m.Called(parentID) +// PendingClusterBlockBuffer_ByParentID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByParentID' +type PendingClusterBlockBuffer_ByParentID_Call struct { + *mock.Call +} + +// ByParentID is a helper method to define mock.On call +// - parentID flow.Identifier +func (_e *PendingClusterBlockBuffer_Expecter) ByParentID(parentID interface{}) *PendingClusterBlockBuffer_ByParentID_Call { + return &PendingClusterBlockBuffer_ByParentID_Call{Call: _e.mock.On("ByParentID", parentID)} } -// PruneByView provides a mock function with given fields: view -func (_m *PendingClusterBlockBuffer) PruneByView(view uint64) { - _m.Called(view) +func (_c *PendingClusterBlockBuffer_ByParentID_Call) Run(run func(parentID flow.Identifier)) *PendingClusterBlockBuffer_ByParentID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingClusterBlockBuffer_ByParentID_Call) Return(slashables []flow.Slashable[*cluster.Proposal], b bool) *PendingClusterBlockBuffer_ByParentID_Call { + _c.Call.Return(slashables, b) + return _c +} + +func (_c *PendingClusterBlockBuffer_ByParentID_Call) RunAndReturn(run func(parentID flow.Identifier) ([]flow.Slashable[*cluster.Proposal], bool)) *PendingClusterBlockBuffer_ByParentID_Call { + _c.Call.Return(run) + return _c +} + +// DropForParent provides a mock function for the type PendingClusterBlockBuffer +func (_mock *PendingClusterBlockBuffer) DropForParent(parentID flow.Identifier) { + _mock.Called(parentID) + return +} + +// PendingClusterBlockBuffer_DropForParent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DropForParent' +type PendingClusterBlockBuffer_DropForParent_Call struct { + *mock.Call +} + +// DropForParent is a helper method to define mock.On call +// - parentID flow.Identifier +func (_e *PendingClusterBlockBuffer_Expecter) DropForParent(parentID interface{}) *PendingClusterBlockBuffer_DropForParent_Call { + return &PendingClusterBlockBuffer_DropForParent_Call{Call: _e.mock.On("DropForParent", parentID)} +} + +func (_c *PendingClusterBlockBuffer_DropForParent_Call) Run(run func(parentID flow.Identifier)) *PendingClusterBlockBuffer_DropForParent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingClusterBlockBuffer_DropForParent_Call) Return() *PendingClusterBlockBuffer_DropForParent_Call { + _c.Call.Return() + return _c +} + +func (_c *PendingClusterBlockBuffer_DropForParent_Call) RunAndReturn(run func(parentID flow.Identifier)) *PendingClusterBlockBuffer_DropForParent_Call { + _c.Run(run) + return _c +} + +// PruneByView provides a mock function for the type PendingClusterBlockBuffer +func (_mock *PendingClusterBlockBuffer) PruneByView(view uint64) { + _mock.Called(view) + return +} + +// PendingClusterBlockBuffer_PruneByView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PruneByView' +type PendingClusterBlockBuffer_PruneByView_Call struct { + *mock.Call +} + +// PruneByView is a helper method to define mock.On call +// - view uint64 +func (_e *PendingClusterBlockBuffer_Expecter) PruneByView(view interface{}) *PendingClusterBlockBuffer_PruneByView_Call { + return &PendingClusterBlockBuffer_PruneByView_Call{Call: _e.mock.On("PruneByView", view)} } -// Size provides a mock function with no fields -func (_m *PendingClusterBlockBuffer) Size() uint { - ret := _m.Called() +func (_c *PendingClusterBlockBuffer_PruneByView_Call) Run(run func(view uint64)) *PendingClusterBlockBuffer_PruneByView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PendingClusterBlockBuffer_PruneByView_Call) Return() *PendingClusterBlockBuffer_PruneByView_Call { + _c.Call.Return() + return _c +} + +func (_c *PendingClusterBlockBuffer_PruneByView_Call) RunAndReturn(run func(view uint64)) *PendingClusterBlockBuffer_PruneByView_Call { + _c.Run(run) + return _c +} + +// Size provides a mock function for the type PendingClusterBlockBuffer +func (_mock *PendingClusterBlockBuffer) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewPendingClusterBlockBuffer creates a new instance of PendingClusterBlockBuffer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPendingClusterBlockBuffer(t interface { - mock.TestingT - Cleanup(func()) -}) *PendingClusterBlockBuffer { - mock := &PendingClusterBlockBuffer{} - mock.Mock.Test(t) +// PendingClusterBlockBuffer_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type PendingClusterBlockBuffer_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *PendingClusterBlockBuffer_Expecter) Size() *PendingClusterBlockBuffer_Size_Call { + return &PendingClusterBlockBuffer_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *PendingClusterBlockBuffer_Size_Call) Run(run func()) *PendingClusterBlockBuffer_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PendingClusterBlockBuffer_Size_Call) Return(v uint) *PendingClusterBlockBuffer_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *PendingClusterBlockBuffer_Size_Call) RunAndReturn(run func() uint) *PendingClusterBlockBuffer_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/ping_metrics.go b/module/mock/ping_metrics.go index 79699dac4ce..e88192ebe08 100644 --- a/module/mock/ping_metrics.go +++ b/module/mock/ping_metrics.go @@ -1,29 +1,16 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - mock "github.com/stretchr/testify/mock" + "time" - time "time" + "github.com/onflow/flow-go/model/flow" + mock "github.com/stretchr/testify/mock" ) -// PingMetrics is an autogenerated mock type for the PingMetrics type -type PingMetrics struct { - mock.Mock -} - -// NodeInfo provides a mock function with given fields: node, nodeInfo, version, sealedHeight, hotstuffCurView -func (_m *PingMetrics) NodeInfo(node *flow.Identity, nodeInfo string, version string, sealedHeight uint64, hotstuffCurView uint64) { - _m.Called(node, nodeInfo, version, sealedHeight, hotstuffCurView) -} - -// NodeReachable provides a mock function with given fields: node, nodeInfo, rtt -func (_m *PingMetrics) NodeReachable(node *flow.Identity, nodeInfo string, rtt time.Duration) { - _m.Called(node, nodeInfo, rtt) -} - // NewPingMetrics creates a new instance of PingMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewPingMetrics(t interface { @@ -37,3 +24,132 @@ func NewPingMetrics(t interface { return mock } + +// PingMetrics is an autogenerated mock type for the PingMetrics type +type PingMetrics struct { + mock.Mock +} + +type PingMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *PingMetrics) EXPECT() *PingMetrics_Expecter { + return &PingMetrics_Expecter{mock: &_m.Mock} +} + +// NodeInfo provides a mock function for the type PingMetrics +func (_mock *PingMetrics) NodeInfo(node *flow.Identity, nodeInfo string, version string, sealedHeight uint64, hotstuffCurView uint64) { + _mock.Called(node, nodeInfo, version, sealedHeight, hotstuffCurView) + return +} + +// PingMetrics_NodeInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NodeInfo' +type PingMetrics_NodeInfo_Call struct { + *mock.Call +} + +// NodeInfo is a helper method to define mock.On call +// - node *flow.Identity +// - nodeInfo string +// - version string +// - sealedHeight uint64 +// - hotstuffCurView uint64 +func (_e *PingMetrics_Expecter) NodeInfo(node interface{}, nodeInfo interface{}, version interface{}, sealedHeight interface{}, hotstuffCurView interface{}) *PingMetrics_NodeInfo_Call { + return &PingMetrics_NodeInfo_Call{Call: _e.mock.On("NodeInfo", node, nodeInfo, version, sealedHeight, hotstuffCurView)} +} + +func (_c *PingMetrics_NodeInfo_Call) Run(run func(node *flow.Identity, nodeInfo string, version string, sealedHeight uint64, hotstuffCurView uint64)) *PingMetrics_NodeInfo_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Identity + if args[0] != nil { + arg0 = args[0].(*flow.Identity) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + var arg4 uint64 + if args[4] != nil { + arg4 = args[4].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *PingMetrics_NodeInfo_Call) Return() *PingMetrics_NodeInfo_Call { + _c.Call.Return() + return _c +} + +func (_c *PingMetrics_NodeInfo_Call) RunAndReturn(run func(node *flow.Identity, nodeInfo string, version string, sealedHeight uint64, hotstuffCurView uint64)) *PingMetrics_NodeInfo_Call { + _c.Run(run) + return _c +} + +// NodeReachable provides a mock function for the type PingMetrics +func (_mock *PingMetrics) NodeReachable(node *flow.Identity, nodeInfo string, rtt time.Duration) { + _mock.Called(node, nodeInfo, rtt) + return +} + +// PingMetrics_NodeReachable_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NodeReachable' +type PingMetrics_NodeReachable_Call struct { + *mock.Call +} + +// NodeReachable is a helper method to define mock.On call +// - node *flow.Identity +// - nodeInfo string +// - rtt time.Duration +func (_e *PingMetrics_Expecter) NodeReachable(node interface{}, nodeInfo interface{}, rtt interface{}) *PingMetrics_NodeReachable_Call { + return &PingMetrics_NodeReachable_Call{Call: _e.mock.On("NodeReachable", node, nodeInfo, rtt)} +} + +func (_c *PingMetrics_NodeReachable_Call) Run(run func(node *flow.Identity, nodeInfo string, rtt time.Duration)) *PingMetrics_NodeReachable_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Identity + if args[0] != nil { + arg0 = args[0].(*flow.Identity) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 time.Duration + if args[2] != nil { + arg2 = args[2].(time.Duration) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *PingMetrics_NodeReachable_Call) Return() *PingMetrics_NodeReachable_Call { + _c.Call.Return() + return _c +} + +func (_c *PingMetrics_NodeReachable_Call) RunAndReturn(run func(node *flow.Identity, nodeInfo string, rtt time.Duration)) *PingMetrics_NodeReachable_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/private_key.go b/module/mock/private_key.go deleted file mode 100644 index 4fbf10cc4da..00000000000 --- a/module/mock/private_key.go +++ /dev/null @@ -1,171 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - crypto "github.com/onflow/crypto" - hash "github.com/onflow/crypto/hash" - - mock "github.com/stretchr/testify/mock" -) - -// PrivateKey is an autogenerated mock type for the PrivateKey type -type PrivateKey struct { - mock.Mock -} - -// Algorithm provides a mock function with no fields -func (_m *PrivateKey) Algorithm() crypto.SigningAlgorithm { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Algorithm") - } - - var r0 crypto.SigningAlgorithm - if rf, ok := ret.Get(0).(func() crypto.SigningAlgorithm); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(crypto.SigningAlgorithm) - } - - return r0 -} - -// Encode provides a mock function with no fields -func (_m *PrivateKey) Encode() []byte { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Encode") - } - - var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - return r0 -} - -// Equals provides a mock function with given fields: _a0 -func (_m *PrivateKey) Equals(_a0 crypto.PrivateKey) bool { - ret := _m.Called(_a0) - - if len(ret) == 0 { - panic("no return value specified for Equals") - } - - var r0 bool - if rf, ok := ret.Get(0).(func(crypto.PrivateKey) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -// PublicKey provides a mock function with no fields -func (_m *PrivateKey) PublicKey() crypto.PublicKey { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for PublicKey") - } - - var r0 crypto.PublicKey - if rf, ok := ret.Get(0).(func() crypto.PublicKey); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.PublicKey) - } - } - - return r0 -} - -// Sign provides a mock function with given fields: _a0, _a1 -func (_m *PrivateKey) Sign(_a0 []byte, _a1 hash.Hasher) (crypto.Signature, error) { - ret := _m.Called(_a0, _a1) - - if len(ret) == 0 { - panic("no return value specified for Sign") - } - - var r0 crypto.Signature - var r1 error - if rf, ok := ret.Get(0).(func([]byte, hash.Hasher) (crypto.Signature, error)); ok { - return rf(_a0, _a1) - } - if rf, ok := ret.Get(0).(func([]byte, hash.Hasher) crypto.Signature); ok { - r0 = rf(_a0, _a1) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.Signature) - } - } - - if rf, ok := ret.Get(1).(func([]byte, hash.Hasher) error); ok { - r1 = rf(_a0, _a1) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Size provides a mock function with no fields -func (_m *PrivateKey) Size() int { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Size") - } - - var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(int) - } - - return r0 -} - -// String provides a mock function with no fields -func (_m *PrivateKey) String() string { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for String") - } - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// NewPrivateKey creates a new instance of PrivateKey. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPrivateKey(t interface { - mock.TestingT - Cleanup(func()) -}) *PrivateKey { - mock := &PrivateKey{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/module/mock/processing_notifier.go b/module/mock/processing_notifier.go index 325696ce0dd..ad891dae9bd 100644 --- a/module/mock/processing_notifier.go +++ b/module/mock/processing_notifier.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) -// ProcessingNotifier is an autogenerated mock type for the ProcessingNotifier type -type ProcessingNotifier struct { - mock.Mock -} - -// Notify provides a mock function with given fields: entityID -func (_m *ProcessingNotifier) Notify(entityID flow.Identifier) { - _m.Called(entityID) -} - // NewProcessingNotifier creates a new instance of ProcessingNotifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewProcessingNotifier(t interface { @@ -30,3 +22,56 @@ func NewProcessingNotifier(t interface { return mock } + +// ProcessingNotifier is an autogenerated mock type for the ProcessingNotifier type +type ProcessingNotifier struct { + mock.Mock +} + +type ProcessingNotifier_Expecter struct { + mock *mock.Mock +} + +func (_m *ProcessingNotifier) EXPECT() *ProcessingNotifier_Expecter { + return &ProcessingNotifier_Expecter{mock: &_m.Mock} +} + +// Notify provides a mock function for the type ProcessingNotifier +func (_mock *ProcessingNotifier) Notify(entityID flow.Identifier) { + _mock.Called(entityID) + return +} + +// ProcessingNotifier_Notify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Notify' +type ProcessingNotifier_Notify_Call struct { + *mock.Call +} + +// Notify is a helper method to define mock.On call +// - entityID flow.Identifier +func (_e *ProcessingNotifier_Expecter) Notify(entityID interface{}) *ProcessingNotifier_Notify_Call { + return &ProcessingNotifier_Notify_Call{Call: _e.mock.On("Notify", entityID)} +} + +func (_c *ProcessingNotifier_Notify_Call) Run(run func(entityID flow.Identifier)) *ProcessingNotifier_Notify_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProcessingNotifier_Notify_Call) Return() *ProcessingNotifier_Notify_Call { + _c.Call.Return() + return _c +} + +func (_c *ProcessingNotifier_Notify_Call) RunAndReturn(run func(entityID flow.Identifier)) *ProcessingNotifier_Notify_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/provider_metrics.go b/module/mock/provider_metrics.go index 1f4ddd2e0ab..bb34ef45e12 100644 --- a/module/mock/provider_metrics.go +++ b/module/mock/provider_metrics.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// ProviderMetrics is an autogenerated mock type for the ProviderMetrics type -type ProviderMetrics struct { - mock.Mock -} - -// ChunkDataPackRequestProcessed provides a mock function with no fields -func (_m *ProviderMetrics) ChunkDataPackRequestProcessed() { - _m.Called() -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewProviderMetrics creates a new instance of ProviderMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,49 @@ func NewProviderMetrics(t interface { return mock } + +// ProviderMetrics is an autogenerated mock type for the ProviderMetrics type +type ProviderMetrics struct { + mock.Mock +} + +type ProviderMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *ProviderMetrics) EXPECT() *ProviderMetrics_Expecter { + return &ProviderMetrics_Expecter{mock: &_m.Mock} +} + +// ChunkDataPackRequestProcessed provides a mock function for the type ProviderMetrics +func (_mock *ProviderMetrics) ChunkDataPackRequestProcessed() { + _mock.Called() + return +} + +// ProviderMetrics_ChunkDataPackRequestProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChunkDataPackRequestProcessed' +type ProviderMetrics_ChunkDataPackRequestProcessed_Call struct { + *mock.Call +} + +// ChunkDataPackRequestProcessed is a helper method to define mock.On call +func (_e *ProviderMetrics_Expecter) ChunkDataPackRequestProcessed() *ProviderMetrics_ChunkDataPackRequestProcessed_Call { + return &ProviderMetrics_ChunkDataPackRequestProcessed_Call{Call: _e.mock.On("ChunkDataPackRequestProcessed")} +} + +func (_c *ProviderMetrics_ChunkDataPackRequestProcessed_Call) Run(run func()) *ProviderMetrics_ChunkDataPackRequestProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ProviderMetrics_ChunkDataPackRequestProcessed_Call) Return() *ProviderMetrics_ChunkDataPackRequestProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *ProviderMetrics_ChunkDataPackRequestProcessed_Call) RunAndReturn(run func()) *ProviderMetrics_ChunkDataPackRequestProcessed_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/public_key.go b/module/mock/public_key.go deleted file mode 100644 index 1b640f67df3..00000000000 --- a/module/mock/public_key.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - crypto "github.com/onflow/crypto" - hash "github.com/onflow/crypto/hash" - - mock "github.com/stretchr/testify/mock" -) - -// PublicKey is an autogenerated mock type for the PublicKey type -type PublicKey struct { - mock.Mock -} - -// Algorithm provides a mock function with no fields -func (_m *PublicKey) Algorithm() crypto.SigningAlgorithm { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Algorithm") - } - - var r0 crypto.SigningAlgorithm - if rf, ok := ret.Get(0).(func() crypto.SigningAlgorithm); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(crypto.SigningAlgorithm) - } - - return r0 -} - -// Encode provides a mock function with no fields -func (_m *PublicKey) Encode() []byte { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Encode") - } - - var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - return r0 -} - -// EncodeCompressed provides a mock function with no fields -func (_m *PublicKey) EncodeCompressed() []byte { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for EncodeCompressed") - } - - var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - return r0 -} - -// Equals provides a mock function with given fields: _a0 -func (_m *PublicKey) Equals(_a0 crypto.PublicKey) bool { - ret := _m.Called(_a0) - - if len(ret) == 0 { - panic("no return value specified for Equals") - } - - var r0 bool - if rf, ok := ret.Get(0).(func(crypto.PublicKey) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -// Size provides a mock function with no fields -func (_m *PublicKey) Size() int { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Size") - } - - var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(int) - } - - return r0 -} - -// String provides a mock function with no fields -func (_m *PublicKey) String() string { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for String") - } - - var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - return r0 -} - -// Verify provides a mock function with given fields: _a0, _a1, _a2 -func (_m *PublicKey) Verify(_a0 crypto.Signature, _a1 []byte, _a2 hash.Hasher) (bool, error) { - ret := _m.Called(_a0, _a1, _a2) - - if len(ret) == 0 { - panic("no return value specified for Verify") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(crypto.Signature, []byte, hash.Hasher) (bool, error)); ok { - return rf(_a0, _a1, _a2) - } - if rf, ok := ret.Get(0).(func(crypto.Signature, []byte, hash.Hasher) bool); ok { - r0 = rf(_a0, _a1, _a2) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(crypto.Signature, []byte, hash.Hasher) error); ok { - r1 = rf(_a0, _a1, _a2) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewPublicKey creates a new instance of PublicKey. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPublicKey(t interface { - mock.TestingT - Cleanup(func()) -}) *PublicKey { - mock := &PublicKey{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/module/mock/qc_contract_client.go b/module/mock/qc_contract_client.go index 8b568c51f2e..2dcc723a100 100644 --- a/module/mock/qc_contract_client.go +++ b/module/mock/qc_contract_client.go @@ -1,40 +1,103 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - model "github.com/onflow/flow-go/consensus/hotstuff/model" + "github.com/onflow/flow-go/consensus/hotstuff/model" mock "github.com/stretchr/testify/mock" ) +// NewQCContractClient creates a new instance of QCContractClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewQCContractClient(t interface { + mock.TestingT + Cleanup(func()) +}) *QCContractClient { + mock := &QCContractClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // QCContractClient is an autogenerated mock type for the QCContractClient type type QCContractClient struct { mock.Mock } -// SubmitVote provides a mock function with given fields: ctx, vote -func (_m *QCContractClient) SubmitVote(ctx context.Context, vote *model.Vote) error { - ret := _m.Called(ctx, vote) +type QCContractClient_Expecter struct { + mock *mock.Mock +} + +func (_m *QCContractClient) EXPECT() *QCContractClient_Expecter { + return &QCContractClient_Expecter{mock: &_m.Mock} +} + +// SubmitVote provides a mock function for the type QCContractClient +func (_mock *QCContractClient) SubmitVote(ctx context.Context, vote *model.Vote) error { + ret := _mock.Called(ctx, vote) if len(ret) == 0 { panic("no return value specified for SubmitVote") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *model.Vote) error); ok { - r0 = rf(ctx, vote) + if returnFunc, ok := ret.Get(0).(func(context.Context, *model.Vote) error); ok { + r0 = returnFunc(ctx, vote) } else { r0 = ret.Error(0) } - return r0 } -// Voted provides a mock function with given fields: ctx -func (_m *QCContractClient) Voted(ctx context.Context) (bool, error) { - ret := _m.Called(ctx) +// QCContractClient_SubmitVote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitVote' +type QCContractClient_SubmitVote_Call struct { + *mock.Call +} + +// SubmitVote is a helper method to define mock.On call +// - ctx context.Context +// - vote *model.Vote +func (_e *QCContractClient_Expecter) SubmitVote(ctx interface{}, vote interface{}) *QCContractClient_SubmitVote_Call { + return &QCContractClient_SubmitVote_Call{Call: _e.mock.On("SubmitVote", ctx, vote)} +} + +func (_c *QCContractClient_SubmitVote_Call) Run(run func(ctx context.Context, vote *model.Vote)) *QCContractClient_SubmitVote_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *model.Vote + if args[1] != nil { + arg1 = args[1].(*model.Vote) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *QCContractClient_SubmitVote_Call) Return(err error) *QCContractClient_SubmitVote_Call { + _c.Call.Return(err) + return _c +} + +func (_c *QCContractClient_SubmitVote_Call) RunAndReturn(run func(ctx context.Context, vote *model.Vote) error) *QCContractClient_SubmitVote_Call { + _c.Call.Return(run) + return _c +} + +// Voted provides a mock function for the type QCContractClient +func (_mock *QCContractClient) Voted(ctx context.Context) (bool, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for Voted") @@ -42,34 +105,52 @@ func (_m *QCContractClient) Voted(ctx context.Context) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (bool, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) (bool, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) bool); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) bool); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewQCContractClient creates a new instance of QCContractClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewQCContractClient(t interface { - mock.TestingT - Cleanup(func()) -}) *QCContractClient { - mock := &QCContractClient{} - mock.Mock.Test(t) +// QCContractClient_Voted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Voted' +type QCContractClient_Voted_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Voted is a helper method to define mock.On call +// - ctx context.Context +func (_e *QCContractClient_Expecter) Voted(ctx interface{}) *QCContractClient_Voted_Call { + return &QCContractClient_Voted_Call{Call: _e.mock.On("Voted", ctx)} +} - return mock +func (_c *QCContractClient_Voted_Call) Run(run func(ctx context.Context)) *QCContractClient_Voted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *QCContractClient_Voted_Call) Return(b bool, err error) *QCContractClient_Voted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *QCContractClient_Voted_Call) RunAndReturn(run func(ctx context.Context) (bool, error)) *QCContractClient_Voted_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/random_beacon_key_store.go b/module/mock/random_beacon_key_store.go index 3d1963e08d7..2f1ab71d9e9 100644 --- a/module/mock/random_beacon_key_store.go +++ b/module/mock/random_beacon_key_store.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" + "github.com/onflow/crypto" mock "github.com/stretchr/testify/mock" ) +// NewRandomBeaconKeyStore creates a new instance of RandomBeaconKeyStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRandomBeaconKeyStore(t interface { + mock.TestingT + Cleanup(func()) +}) *RandomBeaconKeyStore { + mock := &RandomBeaconKeyStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RandomBeaconKeyStore is an autogenerated mock type for the RandomBeaconKeyStore type type RandomBeaconKeyStore struct { mock.Mock } -// ByView provides a mock function with given fields: view -func (_m *RandomBeaconKeyStore) ByView(view uint64) (crypto.PrivateKey, error) { - ret := _m.Called(view) +type RandomBeaconKeyStore_Expecter struct { + mock *mock.Mock +} + +func (_m *RandomBeaconKeyStore) EXPECT() *RandomBeaconKeyStore_Expecter { + return &RandomBeaconKeyStore_Expecter{mock: &_m.Mock} +} + +// ByView provides a mock function for the type RandomBeaconKeyStore +func (_mock *RandomBeaconKeyStore) ByView(view uint64) (crypto.PrivateKey, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for ByView") @@ -22,36 +46,54 @@ func (_m *RandomBeaconKeyStore) ByView(view uint64) (crypto.PrivateKey, error) { var r0 crypto.PrivateKey var r1 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewRandomBeaconKeyStore creates a new instance of RandomBeaconKeyStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRandomBeaconKeyStore(t interface { - mock.TestingT - Cleanup(func()) -}) *RandomBeaconKeyStore { - mock := &RandomBeaconKeyStore{} - mock.Mock.Test(t) +// RandomBeaconKeyStore_ByView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByView' +type RandomBeaconKeyStore_ByView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByView is a helper method to define mock.On call +// - view uint64 +func (_e *RandomBeaconKeyStore_Expecter) ByView(view interface{}) *RandomBeaconKeyStore_ByView_Call { + return &RandomBeaconKeyStore_ByView_Call{Call: _e.mock.On("ByView", view)} +} - return mock +func (_c *RandomBeaconKeyStore_ByView_Call) Run(run func(view uint64)) *RandomBeaconKeyStore_ByView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RandomBeaconKeyStore_ByView_Call) Return(privateKey crypto.PrivateKey, err error) *RandomBeaconKeyStore_ByView_Call { + _c.Call.Return(privateKey, err) + return _c +} + +func (_c *RandomBeaconKeyStore_ByView_Call) RunAndReturn(run func(view uint64) (crypto.PrivateKey, error)) *RandomBeaconKeyStore_ByView_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/rate_limited_blockstore_metrics.go b/module/mock/rate_limited_blockstore_metrics.go index e63e92e81fb..803f4dad033 100644 --- a/module/mock/rate_limited_blockstore_metrics.go +++ b/module/mock/rate_limited_blockstore_metrics.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// RateLimitedBlockstoreMetrics is an autogenerated mock type for the RateLimitedBlockstoreMetrics type -type RateLimitedBlockstoreMetrics struct { - mock.Mock -} - -// BytesRead provides a mock function with given fields: _a0 -func (_m *RateLimitedBlockstoreMetrics) BytesRead(_a0 int) { - _m.Called(_a0) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewRateLimitedBlockstoreMetrics creates a new instance of RateLimitedBlockstoreMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,56 @@ func NewRateLimitedBlockstoreMetrics(t interface { return mock } + +// RateLimitedBlockstoreMetrics is an autogenerated mock type for the RateLimitedBlockstoreMetrics type +type RateLimitedBlockstoreMetrics struct { + mock.Mock +} + +type RateLimitedBlockstoreMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *RateLimitedBlockstoreMetrics) EXPECT() *RateLimitedBlockstoreMetrics_Expecter { + return &RateLimitedBlockstoreMetrics_Expecter{mock: &_m.Mock} +} + +// BytesRead provides a mock function for the type RateLimitedBlockstoreMetrics +func (_mock *RateLimitedBlockstoreMetrics) BytesRead(n int) { + _mock.Called(n) + return +} + +// RateLimitedBlockstoreMetrics_BytesRead_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BytesRead' +type RateLimitedBlockstoreMetrics_BytesRead_Call struct { + *mock.Call +} + +// BytesRead is a helper method to define mock.On call +// - n int +func (_e *RateLimitedBlockstoreMetrics_Expecter) BytesRead(n interface{}) *RateLimitedBlockstoreMetrics_BytesRead_Call { + return &RateLimitedBlockstoreMetrics_BytesRead_Call{Call: _e.mock.On("BytesRead", n)} +} + +func (_c *RateLimitedBlockstoreMetrics_BytesRead_Call) Run(run func(n int)) *RateLimitedBlockstoreMetrics_BytesRead_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RateLimitedBlockstoreMetrics_BytesRead_Call) Return() *RateLimitedBlockstoreMetrics_BytesRead_Call { + _c.Call.Return() + return _c +} + +func (_c *RateLimitedBlockstoreMetrics_BytesRead_Call) RunAndReturn(run func(n int)) *RateLimitedBlockstoreMetrics_BytesRead_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/readonly_sealing_lag_rate_limiter_config.go b/module/mock/readonly_sealing_lag_rate_limiter_config.go index e28d6670412..2bf84e231ea 100644 --- a/module/mock/readonly_sealing_lag_rate_limiter_config.go +++ b/module/mock/readonly_sealing_lag_rate_limiter_config.go @@ -1,96 +1,212 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewReadonlySealingLagRateLimiterConfig creates a new instance of ReadonlySealingLagRateLimiterConfig. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReadonlySealingLagRateLimiterConfig(t interface { + mock.TestingT + Cleanup(func()) +}) *ReadonlySealingLagRateLimiterConfig { + mock := &ReadonlySealingLagRateLimiterConfig{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // ReadonlySealingLagRateLimiterConfig is an autogenerated mock type for the ReadonlySealingLagRateLimiterConfig type type ReadonlySealingLagRateLimiterConfig struct { mock.Mock } -// HalvingInterval provides a mock function with no fields -func (_m *ReadonlySealingLagRateLimiterConfig) HalvingInterval() uint { - ret := _m.Called() +type ReadonlySealingLagRateLimiterConfig_Expecter struct { + mock *mock.Mock +} + +func (_m *ReadonlySealingLagRateLimiterConfig) EXPECT() *ReadonlySealingLagRateLimiterConfig_Expecter { + return &ReadonlySealingLagRateLimiterConfig_Expecter{mock: &_m.Mock} +} + +// HalvingInterval provides a mock function for the type ReadonlySealingLagRateLimiterConfig +func (_mock *ReadonlySealingLagRateLimiterConfig) HalvingInterval() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HalvingInterval") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// MaxSealingLag provides a mock function with no fields -func (_m *ReadonlySealingLagRateLimiterConfig) MaxSealingLag() uint { - ret := _m.Called() +// ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HalvingInterval' +type ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call struct { + *mock.Call +} + +// HalvingInterval is a helper method to define mock.On call +func (_e *ReadonlySealingLagRateLimiterConfig_Expecter) HalvingInterval() *ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call { + return &ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call{Call: _e.mock.On("HalvingInterval")} +} + +func (_c *ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call) Run(run func()) *ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call) Return(v uint) *ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call) RunAndReturn(run func() uint) *ReadonlySealingLagRateLimiterConfig_HalvingInterval_Call { + _c.Call.Return(run) + return _c +} + +// MaxSealingLag provides a mock function for the type ReadonlySealingLagRateLimiterConfig +func (_mock *ReadonlySealingLagRateLimiterConfig) MaxSealingLag() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MaxSealingLag") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// MinCollectionSize provides a mock function with no fields -func (_m *ReadonlySealingLagRateLimiterConfig) MinCollectionSize() uint { - ret := _m.Called() +// ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MaxSealingLag' +type ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call struct { + *mock.Call +} + +// MaxSealingLag is a helper method to define mock.On call +func (_e *ReadonlySealingLagRateLimiterConfig_Expecter) MaxSealingLag() *ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call { + return &ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call{Call: _e.mock.On("MaxSealingLag")} +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call) Run(run func()) *ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call) Return(v uint) *ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call) RunAndReturn(run func() uint) *ReadonlySealingLagRateLimiterConfig_MaxSealingLag_Call { + _c.Call.Return(run) + return _c +} + +// MinCollectionSize provides a mock function for the type ReadonlySealingLagRateLimiterConfig +func (_mock *ReadonlySealingLagRateLimiterConfig) MinCollectionSize() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MinCollectionSize") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// MinSealingLag provides a mock function with no fields -func (_m *ReadonlySealingLagRateLimiterConfig) MinSealingLag() uint { - ret := _m.Called() +// ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MinCollectionSize' +type ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call struct { + *mock.Call +} + +// MinCollectionSize is a helper method to define mock.On call +func (_e *ReadonlySealingLagRateLimiterConfig_Expecter) MinCollectionSize() *ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call { + return &ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call{Call: _e.mock.On("MinCollectionSize")} +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call) Run(run func()) *ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call) Return(v uint) *ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call) RunAndReturn(run func() uint) *ReadonlySealingLagRateLimiterConfig_MinCollectionSize_Call { + _c.Call.Return(run) + return _c +} + +// MinSealingLag provides a mock function for the type ReadonlySealingLagRateLimiterConfig +func (_mock *ReadonlySealingLagRateLimiterConfig) MinSealingLag() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MinSealingLag") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewReadonlySealingLagRateLimiterConfig creates a new instance of ReadonlySealingLagRateLimiterConfig. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReadonlySealingLagRateLimiterConfig(t interface { - mock.TestingT - Cleanup(func()) -}) *ReadonlySealingLagRateLimiterConfig { - mock := &ReadonlySealingLagRateLimiterConfig{} - mock.Mock.Test(t) +// ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MinSealingLag' +type ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// MinSealingLag is a helper method to define mock.On call +func (_e *ReadonlySealingLagRateLimiterConfig_Expecter) MinSealingLag() *ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call { + return &ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call{Call: _e.mock.On("MinSealingLag")} +} - return mock +func (_c *ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call) Run(run func()) *ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call) Return(v uint) *ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call) RunAndReturn(run func() uint) *ReadonlySealingLagRateLimiterConfig_MinSealingLag_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/ready_done_aware.go b/module/mock/ready_done_aware.go index 3d1573b776d..9d245a4d3dc 100644 --- a/module/mock/ready_done_aware.go +++ b/module/mock/ready_done_aware.go @@ -1,64 +1,128 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewReadyDoneAware creates a new instance of ReadyDoneAware. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReadyDoneAware(t interface { + mock.TestingT + Cleanup(func()) +}) *ReadyDoneAware { + mock := &ReadyDoneAware{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // ReadyDoneAware is an autogenerated mock type for the ReadyDoneAware type type ReadyDoneAware struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *ReadyDoneAware) Done() <-chan struct{} { - ret := _m.Called() +type ReadyDoneAware_Expecter struct { + mock *mock.Mock +} + +func (_m *ReadyDoneAware) EXPECT() *ReadyDoneAware_Expecter { + return &ReadyDoneAware_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type ReadyDoneAware +func (_mock *ReadyDoneAware) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *ReadyDoneAware) Ready() <-chan struct{} { - ret := _m.Called() +// ReadyDoneAware_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type ReadyDoneAware_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *ReadyDoneAware_Expecter) Done() *ReadyDoneAware_Done_Call { + return &ReadyDoneAware_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *ReadyDoneAware_Done_Call) Run(run func()) *ReadyDoneAware_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReadyDoneAware_Done_Call) Return(valCh <-chan struct{}) *ReadyDoneAware_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ReadyDoneAware_Done_Call) RunAndReturn(run func() <-chan struct{}) *ReadyDoneAware_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type ReadyDoneAware +func (_mock *ReadyDoneAware) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// NewReadyDoneAware creates a new instance of ReadyDoneAware. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReadyDoneAware(t interface { - mock.TestingT - Cleanup(func()) -}) *ReadyDoneAware { - mock := &ReadyDoneAware{} - mock.Mock.Test(t) +// ReadyDoneAware_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type ReadyDoneAware_Ready_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Ready is a helper method to define mock.On call +func (_e *ReadyDoneAware_Expecter) Ready() *ReadyDoneAware_Ready_Call { + return &ReadyDoneAware_Ready_Call{Call: _e.mock.On("Ready")} +} - return mock +func (_c *ReadyDoneAware_Ready_Call) Run(run func()) *ReadyDoneAware_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReadyDoneAware_Ready_Call) Return(valCh <-chan struct{}) *ReadyDoneAware_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ReadyDoneAware_Ready_Call) RunAndReturn(run func() <-chan struct{}) *ReadyDoneAware_Ready_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/receipt_validator.go b/module/mock/receipt_validator.go index 57073a227c4..9e67f45c288 100644 --- a/module/mock/receipt_validator.go +++ b/module/mock/receipt_validator.go @@ -1,63 +1,139 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewReceiptValidator creates a new instance of ReceiptValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReceiptValidator(t interface { + mock.TestingT + Cleanup(func()) +}) *ReceiptValidator { + mock := &ReceiptValidator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ReceiptValidator is an autogenerated mock type for the ReceiptValidator type type ReceiptValidator struct { mock.Mock } -// Validate provides a mock function with given fields: receipt -func (_m *ReceiptValidator) Validate(receipt *flow.ExecutionReceipt) error { - ret := _m.Called(receipt) +type ReceiptValidator_Expecter struct { + mock *mock.Mock +} + +func (_m *ReceiptValidator) EXPECT() *ReceiptValidator_Expecter { + return &ReceiptValidator_Expecter{mock: &_m.Mock} +} + +// Validate provides a mock function for the type ReceiptValidator +func (_mock *ReceiptValidator) Validate(receipt *flow.ExecutionReceipt) error { + ret := _mock.Called(receipt) if len(ret) == 0 { panic("no return value specified for Validate") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt) error); ok { - r0 = rf(receipt) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt) error); ok { + r0 = returnFunc(receipt) } else { r0 = ret.Error(0) } - return r0 } -// ValidatePayload provides a mock function with given fields: candidate -func (_m *ReceiptValidator) ValidatePayload(candidate *flow.Block) error { - ret := _m.Called(candidate) +// ReceiptValidator_Validate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Validate' +type ReceiptValidator_Validate_Call struct { + *mock.Call +} + +// Validate is a helper method to define mock.On call +// - receipt *flow.ExecutionReceipt +func (_e *ReceiptValidator_Expecter) Validate(receipt interface{}) *ReceiptValidator_Validate_Call { + return &ReceiptValidator_Validate_Call{Call: _e.mock.On("Validate", receipt)} +} + +func (_c *ReceiptValidator_Validate_Call) Run(run func(receipt *flow.ExecutionReceipt)) *ReceiptValidator_Validate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReceiptValidator_Validate_Call) Return(err error) *ReceiptValidator_Validate_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ReceiptValidator_Validate_Call) RunAndReturn(run func(receipt *flow.ExecutionReceipt) error) *ReceiptValidator_Validate_Call { + _c.Call.Return(run) + return _c +} + +// ValidatePayload provides a mock function for the type ReceiptValidator +func (_mock *ReceiptValidator) ValidatePayload(candidate *flow.Block) error { + ret := _mock.Called(candidate) if len(ret) == 0 { panic("no return value specified for ValidatePayload") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.Block) error); ok { - r0 = rf(candidate) + if returnFunc, ok := ret.Get(0).(func(*flow.Block) error); ok { + r0 = returnFunc(candidate) } else { r0 = ret.Error(0) } - return r0 } -// NewReceiptValidator creates a new instance of ReceiptValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReceiptValidator(t interface { - mock.TestingT - Cleanup(func()) -}) *ReceiptValidator { - mock := &ReceiptValidator{} - mock.Mock.Test(t) +// ReceiptValidator_ValidatePayload_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidatePayload' +type ReceiptValidator_ValidatePayload_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ValidatePayload is a helper method to define mock.On call +// - candidate *flow.Block +func (_e *ReceiptValidator_Expecter) ValidatePayload(candidate interface{}) *ReceiptValidator_ValidatePayload_Call { + return &ReceiptValidator_ValidatePayload_Call{Call: _e.mock.On("ValidatePayload", candidate)} +} - return mock +func (_c *ReceiptValidator_ValidatePayload_Call) Run(run func(candidate *flow.Block)) *ReceiptValidator_ValidatePayload_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Block + if args[0] != nil { + arg0 = args[0].(*flow.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReceiptValidator_ValidatePayload_Call) Return(err error) *ReceiptValidator_ValidatePayload_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ReceiptValidator_ValidatePayload_Call) RunAndReturn(run func(candidate *flow.Block) error) *ReceiptValidator_ValidatePayload_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/requester.go b/module/mock/requester.go index 289423aecc0..803b12e4a92 100644 --- a/module/mock/requester.go +++ b/module/mock/requester.go @@ -1,42 +1,162 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewRequester creates a new instance of Requester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRequester(t interface { + mock.TestingT + Cleanup(func()) +}) *Requester { + mock := &Requester{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Requester is an autogenerated mock type for the Requester type type Requester struct { mock.Mock } -// EntityByID provides a mock function with given fields: entityID, selector -func (_m *Requester) EntityByID(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { - _m.Called(entityID, selector) +type Requester_Expecter struct { + mock *mock.Mock } -// Force provides a mock function with no fields -func (_m *Requester) Force() { - _m.Called() +func (_m *Requester) EXPECT() *Requester_Expecter { + return &Requester_Expecter{mock: &_m.Mock} } -// Query provides a mock function with given fields: key, selector -func (_m *Requester) Query(key flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { - _m.Called(key, selector) +// EntityByID provides a mock function for the type Requester +func (_mock *Requester) EntityByID(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { + _mock.Called(entityID, selector) + return } -// NewRequester creates a new instance of Requester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRequester(t interface { - mock.TestingT - Cleanup(func()) -}) *Requester { - mock := &Requester{} - mock.Mock.Test(t) +// Requester_EntityByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EntityByID' +type Requester_EntityByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// EntityByID is a helper method to define mock.On call +// - entityID flow.Identifier +// - selector flow.IdentityFilter[flow.Identity] +func (_e *Requester_Expecter) EntityByID(entityID interface{}, selector interface{}) *Requester_EntityByID_Call { + return &Requester_EntityByID_Call{Call: _e.mock.On("EntityByID", entityID, selector)} +} - return mock +func (_c *Requester_EntityByID_Call) Run(run func(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity])) *Requester_EntityByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.IdentityFilter[flow.Identity] + if args[1] != nil { + arg1 = args[1].(flow.IdentityFilter[flow.Identity]) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Requester_EntityByID_Call) Return() *Requester_EntityByID_Call { + _c.Call.Return() + return _c +} + +func (_c *Requester_EntityByID_Call) RunAndReturn(run func(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity])) *Requester_EntityByID_Call { + _c.Run(run) + return _c +} + +// EntityBySecondaryKey provides a mock function for the type Requester +func (_mock *Requester) EntityBySecondaryKey(queryKey flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { + _mock.Called(queryKey, selector) + return +} + +// Requester_EntityBySecondaryKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EntityBySecondaryKey' +type Requester_EntityBySecondaryKey_Call struct { + *mock.Call +} + +// EntityBySecondaryKey is a helper method to define mock.On call +// - queryKey flow.Identifier +// - selector flow.IdentityFilter[flow.Identity] +func (_e *Requester_Expecter) EntityBySecondaryKey(queryKey interface{}, selector interface{}) *Requester_EntityBySecondaryKey_Call { + return &Requester_EntityBySecondaryKey_Call{Call: _e.mock.On("EntityBySecondaryKey", queryKey, selector)} +} + +func (_c *Requester_EntityBySecondaryKey_Call) Run(run func(queryKey flow.Identifier, selector flow.IdentityFilter[flow.Identity])) *Requester_EntityBySecondaryKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.IdentityFilter[flow.Identity] + if args[1] != nil { + arg1 = args[1].(flow.IdentityFilter[flow.Identity]) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Requester_EntityBySecondaryKey_Call) Return() *Requester_EntityBySecondaryKey_Call { + _c.Call.Return() + return _c +} + +func (_c *Requester_EntityBySecondaryKey_Call) RunAndReturn(run func(queryKey flow.Identifier, selector flow.IdentityFilter[flow.Identity])) *Requester_EntityBySecondaryKey_Call { + _c.Run(run) + return _c +} + +// Force provides a mock function for the type Requester +func (_mock *Requester) Force() { + _mock.Called() + return +} + +// Requester_Force_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Force' +type Requester_Force_Call struct { + *mock.Call +} + +// Force is a helper method to define mock.On call +func (_e *Requester_Expecter) Force() *Requester_Force_Call { + return &Requester_Force_Call{Call: _e.mock.On("Force")} +} + +func (_c *Requester_Force_Call) Run(run func()) *Requester_Force_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Requester_Force_Call) Return() *Requester_Force_Call { + _c.Call.Return() + return _c +} + +func (_c *Requester_Force_Call) RunAndReturn(run func()) *Requester_Force_Call { + _c.Run(run) + return _c } diff --git a/module/mock/resolver_metrics.go b/module/mock/resolver_metrics.go index 8e391c14f4a..7ad2fa9f9ac 100644 --- a/module/mock/resolver_metrics.go +++ b/module/mock/resolver_metrics.go @@ -1,53 +1,210 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewResolverMetrics creates a new instance of ResolverMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewResolverMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *ResolverMetrics { + mock := &ResolverMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ResolverMetrics is an autogenerated mock type for the ResolverMetrics type type ResolverMetrics struct { mock.Mock } -// DNSLookupDuration provides a mock function with given fields: duration -func (_m *ResolverMetrics) DNSLookupDuration(duration time.Duration) { - _m.Called(duration) +type ResolverMetrics_Expecter struct { + mock *mock.Mock } -// OnDNSCacheHit provides a mock function with no fields -func (_m *ResolverMetrics) OnDNSCacheHit() { - _m.Called() +func (_m *ResolverMetrics) EXPECT() *ResolverMetrics_Expecter { + return &ResolverMetrics_Expecter{mock: &_m.Mock} } -// OnDNSCacheInvalidated provides a mock function with no fields -func (_m *ResolverMetrics) OnDNSCacheInvalidated() { - _m.Called() +// DNSLookupDuration provides a mock function for the type ResolverMetrics +func (_mock *ResolverMetrics) DNSLookupDuration(duration time.Duration) { + _mock.Called(duration) + return } -// OnDNSCacheMiss provides a mock function with no fields -func (_m *ResolverMetrics) OnDNSCacheMiss() { - _m.Called() +// ResolverMetrics_DNSLookupDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DNSLookupDuration' +type ResolverMetrics_DNSLookupDuration_Call struct { + *mock.Call } -// OnDNSLookupRequestDropped provides a mock function with no fields -func (_m *ResolverMetrics) OnDNSLookupRequestDropped() { - _m.Called() +// DNSLookupDuration is a helper method to define mock.On call +// - duration time.Duration +func (_e *ResolverMetrics_Expecter) DNSLookupDuration(duration interface{}) *ResolverMetrics_DNSLookupDuration_Call { + return &ResolverMetrics_DNSLookupDuration_Call{Call: _e.mock.On("DNSLookupDuration", duration)} } -// NewResolverMetrics creates a new instance of ResolverMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewResolverMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *ResolverMetrics { - mock := &ResolverMetrics{} - mock.Mock.Test(t) +func (_c *ResolverMetrics_DNSLookupDuration_Call) Run(run func(duration time.Duration)) *ResolverMetrics_DNSLookupDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ResolverMetrics_DNSLookupDuration_Call) Return() *ResolverMetrics_DNSLookupDuration_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *ResolverMetrics_DNSLookupDuration_Call) RunAndReturn(run func(duration time.Duration)) *ResolverMetrics_DNSLookupDuration_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheHit provides a mock function for the type ResolverMetrics +func (_mock *ResolverMetrics) OnDNSCacheHit() { + _mock.Called() + return +} + +// ResolverMetrics_OnDNSCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheHit' +type ResolverMetrics_OnDNSCacheHit_Call struct { + *mock.Call +} + +// OnDNSCacheHit is a helper method to define mock.On call +func (_e *ResolverMetrics_Expecter) OnDNSCacheHit() *ResolverMetrics_OnDNSCacheHit_Call { + return &ResolverMetrics_OnDNSCacheHit_Call{Call: _e.mock.On("OnDNSCacheHit")} +} + +func (_c *ResolverMetrics_OnDNSCacheHit_Call) Run(run func()) *ResolverMetrics_OnDNSCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ResolverMetrics_OnDNSCacheHit_Call) Return() *ResolverMetrics_OnDNSCacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *ResolverMetrics_OnDNSCacheHit_Call) RunAndReturn(run func()) *ResolverMetrics_OnDNSCacheHit_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheInvalidated provides a mock function for the type ResolverMetrics +func (_mock *ResolverMetrics) OnDNSCacheInvalidated() { + _mock.Called() + return +} + +// ResolverMetrics_OnDNSCacheInvalidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheInvalidated' +type ResolverMetrics_OnDNSCacheInvalidated_Call struct { + *mock.Call +} + +// OnDNSCacheInvalidated is a helper method to define mock.On call +func (_e *ResolverMetrics_Expecter) OnDNSCacheInvalidated() *ResolverMetrics_OnDNSCacheInvalidated_Call { + return &ResolverMetrics_OnDNSCacheInvalidated_Call{Call: _e.mock.On("OnDNSCacheInvalidated")} +} + +func (_c *ResolverMetrics_OnDNSCacheInvalidated_Call) Run(run func()) *ResolverMetrics_OnDNSCacheInvalidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ResolverMetrics_OnDNSCacheInvalidated_Call) Return() *ResolverMetrics_OnDNSCacheInvalidated_Call { + _c.Call.Return() + return _c +} + +func (_c *ResolverMetrics_OnDNSCacheInvalidated_Call) RunAndReturn(run func()) *ResolverMetrics_OnDNSCacheInvalidated_Call { + _c.Run(run) + return _c +} + +// OnDNSCacheMiss provides a mock function for the type ResolverMetrics +func (_mock *ResolverMetrics) OnDNSCacheMiss() { + _mock.Called() + return +} + +// ResolverMetrics_OnDNSCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSCacheMiss' +type ResolverMetrics_OnDNSCacheMiss_Call struct { + *mock.Call +} + +// OnDNSCacheMiss is a helper method to define mock.On call +func (_e *ResolverMetrics_Expecter) OnDNSCacheMiss() *ResolverMetrics_OnDNSCacheMiss_Call { + return &ResolverMetrics_OnDNSCacheMiss_Call{Call: _e.mock.On("OnDNSCacheMiss")} +} + +func (_c *ResolverMetrics_OnDNSCacheMiss_Call) Run(run func()) *ResolverMetrics_OnDNSCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ResolverMetrics_OnDNSCacheMiss_Call) Return() *ResolverMetrics_OnDNSCacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *ResolverMetrics_OnDNSCacheMiss_Call) RunAndReturn(run func()) *ResolverMetrics_OnDNSCacheMiss_Call { + _c.Run(run) + return _c +} + +// OnDNSLookupRequestDropped provides a mock function for the type ResolverMetrics +func (_mock *ResolverMetrics) OnDNSLookupRequestDropped() { + _mock.Called() + return +} + +// ResolverMetrics_OnDNSLookupRequestDropped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDNSLookupRequestDropped' +type ResolverMetrics_OnDNSLookupRequestDropped_Call struct { + *mock.Call +} + +// OnDNSLookupRequestDropped is a helper method to define mock.On call +func (_e *ResolverMetrics_Expecter) OnDNSLookupRequestDropped() *ResolverMetrics_OnDNSLookupRequestDropped_Call { + return &ResolverMetrics_OnDNSLookupRequestDropped_Call{Call: _e.mock.On("OnDNSLookupRequestDropped")} +} + +func (_c *ResolverMetrics_OnDNSLookupRequestDropped_Call) Run(run func()) *ResolverMetrics_OnDNSLookupRequestDropped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ResolverMetrics_OnDNSLookupRequestDropped_Call) Return() *ResolverMetrics_OnDNSLookupRequestDropped_Call { + _c.Call.Return() + return _c +} + +func (_c *ResolverMetrics_OnDNSLookupRequestDropped_Call) RunAndReturn(run func()) *ResolverMetrics_OnDNSLookupRequestDropped_Call { + _c.Run(run) + return _c } diff --git a/module/mock/rest_metrics.go b/module/mock/rest_metrics.go index ac9fdfb82e6..d62ce1476a8 100644 --- a/module/mock/rest_metrics.go +++ b/module/mock/rest_metrics.go @@ -1,51 +1,248 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" + "time" - metrics "github.com/slok/go-http-metrics/metrics" + "github.com/slok/go-http-metrics/metrics" mock "github.com/stretchr/testify/mock" - - time "time" ) +// NewRestMetrics creates a new instance of RestMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRestMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *RestMetrics { + mock := &RestMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RestMetrics is an autogenerated mock type for the RestMetrics type type RestMetrics struct { mock.Mock } -// AddInflightRequests provides a mock function with given fields: ctx, props, quantity -func (_m *RestMetrics) AddInflightRequests(ctx context.Context, props metrics.HTTPProperties, quantity int) { - _m.Called(ctx, props, quantity) +type RestMetrics_Expecter struct { + mock *mock.Mock } -// AddTotalRequests provides a mock function with given fields: ctx, method, routeName -func (_m *RestMetrics) AddTotalRequests(ctx context.Context, method string, routeName string) { - _m.Called(ctx, method, routeName) +func (_m *RestMetrics) EXPECT() *RestMetrics_Expecter { + return &RestMetrics_Expecter{mock: &_m.Mock} } -// ObserveHTTPRequestDuration provides a mock function with given fields: ctx, props, duration -func (_m *RestMetrics) ObserveHTTPRequestDuration(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration) { - _m.Called(ctx, props, duration) +// AddInflightRequests provides a mock function for the type RestMetrics +func (_mock *RestMetrics) AddInflightRequests(ctx context.Context, props metrics.HTTPProperties, quantity int) { + _mock.Called(ctx, props, quantity) + return } -// ObserveHTTPResponseSize provides a mock function with given fields: ctx, props, sizeBytes -func (_m *RestMetrics) ObserveHTTPResponseSize(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64) { - _m.Called(ctx, props, sizeBytes) +// RestMetrics_AddInflightRequests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddInflightRequests' +type RestMetrics_AddInflightRequests_Call struct { + *mock.Call } -// NewRestMetrics creates a new instance of RestMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRestMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *RestMetrics { - mock := &RestMetrics{} - mock.Mock.Test(t) +// AddInflightRequests is a helper method to define mock.On call +// - ctx context.Context +// - props metrics.HTTPProperties +// - quantity int +func (_e *RestMetrics_Expecter) AddInflightRequests(ctx interface{}, props interface{}, quantity interface{}) *RestMetrics_AddInflightRequests_Call { + return &RestMetrics_AddInflightRequests_Call{Call: _e.mock.On("AddInflightRequests", ctx, props, quantity)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *RestMetrics_AddInflightRequests_Call) Run(run func(ctx context.Context, props metrics.HTTPProperties, quantity int)) *RestMetrics_AddInflightRequests_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 metrics.HTTPProperties + if args[1] != nil { + arg1 = args[1].(metrics.HTTPProperties) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} - return mock +func (_c *RestMetrics_AddInflightRequests_Call) Return() *RestMetrics_AddInflightRequests_Call { + _c.Call.Return() + return _c +} + +func (_c *RestMetrics_AddInflightRequests_Call) RunAndReturn(run func(ctx context.Context, props metrics.HTTPProperties, quantity int)) *RestMetrics_AddInflightRequests_Call { + _c.Run(run) + return _c +} + +// AddTotalRequests provides a mock function for the type RestMetrics +func (_mock *RestMetrics) AddTotalRequests(ctx context.Context, method string, routeName string) { + _mock.Called(ctx, method, routeName) + return +} + +// RestMetrics_AddTotalRequests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddTotalRequests' +type RestMetrics_AddTotalRequests_Call struct { + *mock.Call +} + +// AddTotalRequests is a helper method to define mock.On call +// - ctx context.Context +// - method string +// - routeName string +func (_e *RestMetrics_Expecter) AddTotalRequests(ctx interface{}, method interface{}, routeName interface{}) *RestMetrics_AddTotalRequests_Call { + return &RestMetrics_AddTotalRequests_Call{Call: _e.mock.On("AddTotalRequests", ctx, method, routeName)} +} + +func (_c *RestMetrics_AddTotalRequests_Call) Run(run func(ctx context.Context, method string, routeName string)) *RestMetrics_AddTotalRequests_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *RestMetrics_AddTotalRequests_Call) Return() *RestMetrics_AddTotalRequests_Call { + _c.Call.Return() + return _c +} + +func (_c *RestMetrics_AddTotalRequests_Call) RunAndReturn(run func(ctx context.Context, method string, routeName string)) *RestMetrics_AddTotalRequests_Call { + _c.Run(run) + return _c +} + +// ObserveHTTPRequestDuration provides a mock function for the type RestMetrics +func (_mock *RestMetrics) ObserveHTTPRequestDuration(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration) { + _mock.Called(ctx, props, duration) + return +} + +// RestMetrics_ObserveHTTPRequestDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ObserveHTTPRequestDuration' +type RestMetrics_ObserveHTTPRequestDuration_Call struct { + *mock.Call +} + +// ObserveHTTPRequestDuration is a helper method to define mock.On call +// - ctx context.Context +// - props metrics.HTTPReqProperties +// - duration time.Duration +func (_e *RestMetrics_Expecter) ObserveHTTPRequestDuration(ctx interface{}, props interface{}, duration interface{}) *RestMetrics_ObserveHTTPRequestDuration_Call { + return &RestMetrics_ObserveHTTPRequestDuration_Call{Call: _e.mock.On("ObserveHTTPRequestDuration", ctx, props, duration)} +} + +func (_c *RestMetrics_ObserveHTTPRequestDuration_Call) Run(run func(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration)) *RestMetrics_ObserveHTTPRequestDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 metrics.HTTPReqProperties + if args[1] != nil { + arg1 = args[1].(metrics.HTTPReqProperties) + } + var arg2 time.Duration + if args[2] != nil { + arg2 = args[2].(time.Duration) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *RestMetrics_ObserveHTTPRequestDuration_Call) Return() *RestMetrics_ObserveHTTPRequestDuration_Call { + _c.Call.Return() + return _c +} + +func (_c *RestMetrics_ObserveHTTPRequestDuration_Call) RunAndReturn(run func(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration)) *RestMetrics_ObserveHTTPRequestDuration_Call { + _c.Run(run) + return _c +} + +// ObserveHTTPResponseSize provides a mock function for the type RestMetrics +func (_mock *RestMetrics) ObserveHTTPResponseSize(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64) { + _mock.Called(ctx, props, sizeBytes) + return +} + +// RestMetrics_ObserveHTTPResponseSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ObserveHTTPResponseSize' +type RestMetrics_ObserveHTTPResponseSize_Call struct { + *mock.Call +} + +// ObserveHTTPResponseSize is a helper method to define mock.On call +// - ctx context.Context +// - props metrics.HTTPReqProperties +// - sizeBytes int64 +func (_e *RestMetrics_Expecter) ObserveHTTPResponseSize(ctx interface{}, props interface{}, sizeBytes interface{}) *RestMetrics_ObserveHTTPResponseSize_Call { + return &RestMetrics_ObserveHTTPResponseSize_Call{Call: _e.mock.On("ObserveHTTPResponseSize", ctx, props, sizeBytes)} +} + +func (_c *RestMetrics_ObserveHTTPResponseSize_Call) Run(run func(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64)) *RestMetrics_ObserveHTTPResponseSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 metrics.HTTPReqProperties + if args[1] != nil { + arg1 = args[1].(metrics.HTTPReqProperties) + } + var arg2 int64 + if args[2] != nil { + arg2 = args[2].(int64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *RestMetrics_ObserveHTTPResponseSize_Call) Return() *RestMetrics_ObserveHTTPResponseSize_Call { + _c.Call.Return() + return _c +} + +func (_c *RestMetrics_ObserveHTTPResponseSize_Call) RunAndReturn(run func(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64)) *RestMetrics_ObserveHTTPResponseSize_Call { + _c.Run(run) + return _c } diff --git a/module/mock/runtime_metrics.go b/module/mock/runtime_metrics.go index 7ad3aaa5e41..006d0f283e5 100644 --- a/module/mock/runtime_metrics.go +++ b/module/mock/runtime_metrics.go @@ -1,58 +1,264 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewRuntimeMetrics creates a new instance of RuntimeMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRuntimeMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *RuntimeMetrics { + mock := &RuntimeMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RuntimeMetrics is an autogenerated mock type for the RuntimeMetrics type type RuntimeMetrics struct { mock.Mock } -// RuntimeSetNumberOfAccounts provides a mock function with given fields: count -func (_m *RuntimeMetrics) RuntimeSetNumberOfAccounts(count uint64) { - _m.Called(count) +type RuntimeMetrics_Expecter struct { + mock *mock.Mock } -// RuntimeTransactionChecked provides a mock function with given fields: dur -func (_m *RuntimeMetrics) RuntimeTransactionChecked(dur time.Duration) { - _m.Called(dur) +func (_m *RuntimeMetrics) EXPECT() *RuntimeMetrics_Expecter { + return &RuntimeMetrics_Expecter{mock: &_m.Mock} } -// RuntimeTransactionInterpreted provides a mock function with given fields: dur -func (_m *RuntimeMetrics) RuntimeTransactionInterpreted(dur time.Duration) { - _m.Called(dur) +// RuntimeSetNumberOfAccounts provides a mock function for the type RuntimeMetrics +func (_mock *RuntimeMetrics) RuntimeSetNumberOfAccounts(count uint64) { + _mock.Called(count) + return } -// RuntimeTransactionParsed provides a mock function with given fields: dur -func (_m *RuntimeMetrics) RuntimeTransactionParsed(dur time.Duration) { - _m.Called(dur) +// RuntimeMetrics_RuntimeSetNumberOfAccounts_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeSetNumberOfAccounts' +type RuntimeMetrics_RuntimeSetNumberOfAccounts_Call struct { + *mock.Call } -// RuntimeTransactionProgramsCacheHit provides a mock function with no fields -func (_m *RuntimeMetrics) RuntimeTransactionProgramsCacheHit() { - _m.Called() +// RuntimeSetNumberOfAccounts is a helper method to define mock.On call +// - count uint64 +func (_e *RuntimeMetrics_Expecter) RuntimeSetNumberOfAccounts(count interface{}) *RuntimeMetrics_RuntimeSetNumberOfAccounts_Call { + return &RuntimeMetrics_RuntimeSetNumberOfAccounts_Call{Call: _e.mock.On("RuntimeSetNumberOfAccounts", count)} } -// RuntimeTransactionProgramsCacheMiss provides a mock function with no fields -func (_m *RuntimeMetrics) RuntimeTransactionProgramsCacheMiss() { - _m.Called() +func (_c *RuntimeMetrics_RuntimeSetNumberOfAccounts_Call) Run(run func(count uint64)) *RuntimeMetrics_RuntimeSetNumberOfAccounts_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c } -// NewRuntimeMetrics creates a new instance of RuntimeMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRuntimeMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *RuntimeMetrics { - mock := &RuntimeMetrics{} - mock.Mock.Test(t) +func (_c *RuntimeMetrics_RuntimeSetNumberOfAccounts_Call) Return() *RuntimeMetrics_RuntimeSetNumberOfAccounts_Call { + _c.Call.Return() + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *RuntimeMetrics_RuntimeSetNumberOfAccounts_Call) RunAndReturn(run func(count uint64)) *RuntimeMetrics_RuntimeSetNumberOfAccounts_Call { + _c.Run(run) + return _c +} - return mock +// RuntimeTransactionChecked provides a mock function for the type RuntimeMetrics +func (_mock *RuntimeMetrics) RuntimeTransactionChecked(dur time.Duration) { + _mock.Called(dur) + return +} + +// RuntimeMetrics_RuntimeTransactionChecked_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionChecked' +type RuntimeMetrics_RuntimeTransactionChecked_Call struct { + *mock.Call +} + +// RuntimeTransactionChecked is a helper method to define mock.On call +// - dur time.Duration +func (_e *RuntimeMetrics_Expecter) RuntimeTransactionChecked(dur interface{}) *RuntimeMetrics_RuntimeTransactionChecked_Call { + return &RuntimeMetrics_RuntimeTransactionChecked_Call{Call: _e.mock.On("RuntimeTransactionChecked", dur)} +} + +func (_c *RuntimeMetrics_RuntimeTransactionChecked_Call) Run(run func(dur time.Duration)) *RuntimeMetrics_RuntimeTransactionChecked_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionChecked_Call) Return() *RuntimeMetrics_RuntimeTransactionChecked_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionChecked_Call) RunAndReturn(run func(dur time.Duration)) *RuntimeMetrics_RuntimeTransactionChecked_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionInterpreted provides a mock function for the type RuntimeMetrics +func (_mock *RuntimeMetrics) RuntimeTransactionInterpreted(dur time.Duration) { + _mock.Called(dur) + return +} + +// RuntimeMetrics_RuntimeTransactionInterpreted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionInterpreted' +type RuntimeMetrics_RuntimeTransactionInterpreted_Call struct { + *mock.Call +} + +// RuntimeTransactionInterpreted is a helper method to define mock.On call +// - dur time.Duration +func (_e *RuntimeMetrics_Expecter) RuntimeTransactionInterpreted(dur interface{}) *RuntimeMetrics_RuntimeTransactionInterpreted_Call { + return &RuntimeMetrics_RuntimeTransactionInterpreted_Call{Call: _e.mock.On("RuntimeTransactionInterpreted", dur)} +} + +func (_c *RuntimeMetrics_RuntimeTransactionInterpreted_Call) Run(run func(dur time.Duration)) *RuntimeMetrics_RuntimeTransactionInterpreted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionInterpreted_Call) Return() *RuntimeMetrics_RuntimeTransactionInterpreted_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionInterpreted_Call) RunAndReturn(run func(dur time.Duration)) *RuntimeMetrics_RuntimeTransactionInterpreted_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionParsed provides a mock function for the type RuntimeMetrics +func (_mock *RuntimeMetrics) RuntimeTransactionParsed(dur time.Duration) { + _mock.Called(dur) + return +} + +// RuntimeMetrics_RuntimeTransactionParsed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionParsed' +type RuntimeMetrics_RuntimeTransactionParsed_Call struct { + *mock.Call +} + +// RuntimeTransactionParsed is a helper method to define mock.On call +// - dur time.Duration +func (_e *RuntimeMetrics_Expecter) RuntimeTransactionParsed(dur interface{}) *RuntimeMetrics_RuntimeTransactionParsed_Call { + return &RuntimeMetrics_RuntimeTransactionParsed_Call{Call: _e.mock.On("RuntimeTransactionParsed", dur)} +} + +func (_c *RuntimeMetrics_RuntimeTransactionParsed_Call) Run(run func(dur time.Duration)) *RuntimeMetrics_RuntimeTransactionParsed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionParsed_Call) Return() *RuntimeMetrics_RuntimeTransactionParsed_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionParsed_Call) RunAndReturn(run func(dur time.Duration)) *RuntimeMetrics_RuntimeTransactionParsed_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheHit provides a mock function for the type RuntimeMetrics +func (_mock *RuntimeMetrics) RuntimeTransactionProgramsCacheHit() { + _mock.Called() + return +} + +// RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheHit' +type RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheHit is a helper method to define mock.On call +func (_e *RuntimeMetrics_Expecter) RuntimeTransactionProgramsCacheHit() *RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call { + return &RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheHit")} +} + +func (_c *RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call) Run(run func()) *RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call) Return() *RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call) RunAndReturn(run func()) *RuntimeMetrics_RuntimeTransactionProgramsCacheHit_Call { + _c.Run(run) + return _c +} + +// RuntimeTransactionProgramsCacheMiss provides a mock function for the type RuntimeMetrics +func (_mock *RuntimeMetrics) RuntimeTransactionProgramsCacheMiss() { + _mock.Called() + return +} + +// RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RuntimeTransactionProgramsCacheMiss' +type RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call struct { + *mock.Call +} + +// RuntimeTransactionProgramsCacheMiss is a helper method to define mock.On call +func (_e *RuntimeMetrics_Expecter) RuntimeTransactionProgramsCacheMiss() *RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call { + return &RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call{Call: _e.mock.On("RuntimeTransactionProgramsCacheMiss")} +} + +func (_c *RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call) Run(run func()) *RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call) Return() *RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call { + _c.Call.Return() + return _c +} + +func (_c *RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call) RunAndReturn(run func()) *RuntimeMetrics_RuntimeTransactionProgramsCacheMiss_Call { + _c.Run(run) + return _c } diff --git a/module/mock/sdk_client_wrapper.go b/module/mock/sdk_client_wrapper.go index 6c84cc52855..5d6688d587f 100644 --- a/module/mock/sdk_client_wrapper.go +++ b/module/mock/sdk_client_wrapper.go @@ -1,25 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - cadence "github.com/onflow/cadence" - - flow "github.com/onflow/flow-go-sdk" + "context" + "github.com/onflow/cadence" + "github.com/onflow/flow-go-sdk" mock "github.com/stretchr/testify/mock" ) +// NewSDKClientWrapper creates a new instance of SDKClientWrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSDKClientWrapper(t interface { + mock.TestingT + Cleanup(func()) +}) *SDKClientWrapper { + mock := &SDKClientWrapper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SDKClientWrapper is an autogenerated mock type for the SDKClientWrapper type type SDKClientWrapper struct { mock.Mock } -// ExecuteScriptAtBlockID provides a mock function with given fields: _a0, _a1, _a2, _a3 -func (_m *SDKClientWrapper) ExecuteScriptAtBlockID(_a0 context.Context, _a1 flow.Identifier, _a2 []byte, _a3 []cadence.Value) (cadence.Value, error) { - ret := _m.Called(_a0, _a1, _a2, _a3) +type SDKClientWrapper_Expecter struct { + mock *mock.Mock +} + +func (_m *SDKClientWrapper) EXPECT() *SDKClientWrapper_Expecter { + return &SDKClientWrapper_Expecter{mock: &_m.Mock} +} + +// ExecuteScriptAtBlockID provides a mock function for the type SDKClientWrapper +func (_mock *SDKClientWrapper) ExecuteScriptAtBlockID(context1 context.Context, identifier flow.Identifier, bytes []byte, values []cadence.Value) (cadence.Value, error) { + ret := _mock.Called(context1, identifier, bytes, values) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtBlockID") @@ -27,29 +49,79 @@ func (_m *SDKClientWrapper) ExecuteScriptAtBlockID(_a0 context.Context, _a1 flow var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) (cadence.Value, error)); ok { - return rf(_a0, _a1, _a2, _a3) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) (cadence.Value, error)); ok { + return returnFunc(context1, identifier, bytes, values) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) cadence.Value); ok { - r0 = rf(_a0, _a1, _a2, _a3) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, []byte, []cadence.Value) cadence.Value); ok { + r0 = returnFunc(context1, identifier, bytes, values) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, []cadence.Value) error); ok { - r1 = rf(_a0, _a1, _a2, _a3) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, []byte, []cadence.Value) error); ok { + r1 = returnFunc(context1, identifier, bytes, values) } else { r1 = ret.Error(1) } - return r0, r1 } -// ExecuteScriptAtLatestBlock provides a mock function with given fields: _a0, _a1, _a2 -func (_m *SDKClientWrapper) ExecuteScriptAtLatestBlock(_a0 context.Context, _a1 []byte, _a2 []cadence.Value) (cadence.Value, error) { - ret := _m.Called(_a0, _a1, _a2) +// SDKClientWrapper_ExecuteScriptAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtBlockID' +type SDKClientWrapper_ExecuteScriptAtBlockID_Call struct { + *mock.Call +} + +// ExecuteScriptAtBlockID is a helper method to define mock.On call +// - context1 context.Context +// - identifier flow.Identifier +// - bytes []byte +// - values []cadence.Value +func (_e *SDKClientWrapper_Expecter) ExecuteScriptAtBlockID(context1 interface{}, identifier interface{}, bytes interface{}, values interface{}) *SDKClientWrapper_ExecuteScriptAtBlockID_Call { + return &SDKClientWrapper_ExecuteScriptAtBlockID_Call{Call: _e.mock.On("ExecuteScriptAtBlockID", context1, identifier, bytes, values)} +} + +func (_c *SDKClientWrapper_ExecuteScriptAtBlockID_Call) Run(run func(context1 context.Context, identifier flow.Identifier, bytes []byte, values []cadence.Value)) *SDKClientWrapper_ExecuteScriptAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + var arg3 []cadence.Value + if args[3] != nil { + arg3 = args[3].([]cadence.Value) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *SDKClientWrapper_ExecuteScriptAtBlockID_Call) Return(value cadence.Value, err error) *SDKClientWrapper_ExecuteScriptAtBlockID_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *SDKClientWrapper_ExecuteScriptAtBlockID_Call) RunAndReturn(run func(context1 context.Context, identifier flow.Identifier, bytes []byte, values []cadence.Value) (cadence.Value, error)) *SDKClientWrapper_ExecuteScriptAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ExecuteScriptAtLatestBlock provides a mock function for the type SDKClientWrapper +func (_mock *SDKClientWrapper) ExecuteScriptAtLatestBlock(context1 context.Context, bytes []byte, values []cadence.Value) (cadence.Value, error) { + ret := _mock.Called(context1, bytes, values) if len(ret) == 0 { panic("no return value specified for ExecuteScriptAtLatestBlock") @@ -57,29 +129,73 @@ func (_m *SDKClientWrapper) ExecuteScriptAtLatestBlock(_a0 context.Context, _a1 var r0 cadence.Value var r1 error - if rf, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) (cadence.Value, error)); ok { - return rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) (cadence.Value, error)); ok { + return returnFunc(context1, bytes, values) } - if rf, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) cadence.Value); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, []cadence.Value) cadence.Value); ok { + r0 = returnFunc(context1, bytes, values) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cadence.Value) } } - - if rf, ok := ret.Get(1).(func(context.Context, []byte, []cadence.Value) error); ok { - r1 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, []cadence.Value) error); ok { + r1 = returnFunc(context1, bytes, values) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccount provides a mock function with given fields: _a0, _a1 -func (_m *SDKClientWrapper) GetAccount(_a0 context.Context, _a1 flow.Address) (*flow.Account, error) { - ret := _m.Called(_a0, _a1) +// SDKClientWrapper_ExecuteScriptAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteScriptAtLatestBlock' +type SDKClientWrapper_ExecuteScriptAtLatestBlock_Call struct { + *mock.Call +} + +// ExecuteScriptAtLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - bytes []byte +// - values []cadence.Value +func (_e *SDKClientWrapper_Expecter) ExecuteScriptAtLatestBlock(context1 interface{}, bytes interface{}, values interface{}) *SDKClientWrapper_ExecuteScriptAtLatestBlock_Call { + return &SDKClientWrapper_ExecuteScriptAtLatestBlock_Call{Call: _e.mock.On("ExecuteScriptAtLatestBlock", context1, bytes, values)} +} + +func (_c *SDKClientWrapper_ExecuteScriptAtLatestBlock_Call) Run(run func(context1 context.Context, bytes []byte, values []cadence.Value)) *SDKClientWrapper_ExecuteScriptAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 []cadence.Value + if args[2] != nil { + arg2 = args[2].([]cadence.Value) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *SDKClientWrapper_ExecuteScriptAtLatestBlock_Call) Return(value cadence.Value, err error) *SDKClientWrapper_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(value, err) + return _c +} + +func (_c *SDKClientWrapper_ExecuteScriptAtLatestBlock_Call) RunAndReturn(run func(context1 context.Context, bytes []byte, values []cadence.Value) (cadence.Value, error)) *SDKClientWrapper_ExecuteScriptAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetAccount provides a mock function for the type SDKClientWrapper +func (_mock *SDKClientWrapper) GetAccount(context1 context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(context1, address) if len(ret) == 0 { panic("no return value specified for GetAccount") @@ -87,29 +203,67 @@ func (_m *SDKClientWrapper) GetAccount(_a0 context.Context, _a1 flow.Address) (* var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(context1, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(context1, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(context1, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetAccountAtLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *SDKClientWrapper) GetAccountAtLatestBlock(_a0 context.Context, _a1 flow.Address) (*flow.Account, error) { - ret := _m.Called(_a0, _a1) +// SDKClientWrapper_GetAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccount' +type SDKClientWrapper_GetAccount_Call struct { + *mock.Call +} + +// GetAccount is a helper method to define mock.On call +// - context1 context.Context +// - address flow.Address +func (_e *SDKClientWrapper_Expecter) GetAccount(context1 interface{}, address interface{}) *SDKClientWrapper_GetAccount_Call { + return &SDKClientWrapper_GetAccount_Call{Call: _e.mock.On("GetAccount", context1, address)} +} + +func (_c *SDKClientWrapper_GetAccount_Call) Run(run func(context1 context.Context, address flow.Address)) *SDKClientWrapper_GetAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SDKClientWrapper_GetAccount_Call) Return(account *flow.Account, err error) *SDKClientWrapper_GetAccount_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *SDKClientWrapper_GetAccount_Call) RunAndReturn(run func(context1 context.Context, address flow.Address) (*flow.Account, error)) *SDKClientWrapper_GetAccount_Call { + _c.Call.Return(run) + return _c +} + +// GetAccountAtLatestBlock provides a mock function for the type SDKClientWrapper +func (_mock *SDKClientWrapper) GetAccountAtLatestBlock(context1 context.Context, address flow.Address) (*flow.Account, error) { + ret := _mock.Called(context1, address) if len(ret) == 0 { panic("no return value specified for GetAccountAtLatestBlock") @@ -117,29 +271,67 @@ func (_m *SDKClientWrapper) GetAccountAtLatestBlock(_a0 context.Context, _a1 flo var r0 *flow.Account var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) (*flow.Account, error)); ok { + return returnFunc(context1, address) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address) *flow.Account); ok { + r0 = returnFunc(context1, address) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Account) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address) error); ok { + r1 = returnFunc(context1, address) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetLatestBlock provides a mock function with given fields: _a0, _a1 -func (_m *SDKClientWrapper) GetLatestBlock(_a0 context.Context, _a1 bool) (*flow.Block, error) { - ret := _m.Called(_a0, _a1) +// SDKClientWrapper_GetAccountAtLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtLatestBlock' +type SDKClientWrapper_GetAccountAtLatestBlock_Call struct { + *mock.Call +} + +// GetAccountAtLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - address flow.Address +func (_e *SDKClientWrapper_Expecter) GetAccountAtLatestBlock(context1 interface{}, address interface{}) *SDKClientWrapper_GetAccountAtLatestBlock_Call { + return &SDKClientWrapper_GetAccountAtLatestBlock_Call{Call: _e.mock.On("GetAccountAtLatestBlock", context1, address)} +} + +func (_c *SDKClientWrapper_GetAccountAtLatestBlock_Call) Run(run func(context1 context.Context, address flow.Address)) *SDKClientWrapper_GetAccountAtLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SDKClientWrapper_GetAccountAtLatestBlock_Call) Return(account *flow.Account, err error) *SDKClientWrapper_GetAccountAtLatestBlock_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *SDKClientWrapper_GetAccountAtLatestBlock_Call) RunAndReturn(run func(context1 context.Context, address flow.Address) (*flow.Account, error)) *SDKClientWrapper_GetAccountAtLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetLatestBlock provides a mock function for the type SDKClientWrapper +func (_mock *SDKClientWrapper) GetLatestBlock(context1 context.Context, b bool) (*flow.Block, error) { + ret := _mock.Called(context1, b) if len(ret) == 0 { panic("no return value specified for GetLatestBlock") @@ -147,29 +339,67 @@ func (_m *SDKClientWrapper) GetLatestBlock(_a0 context.Context, _a1 bool) (*flow var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(context.Context, bool) (*flow.Block, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) (*flow.Block, error)); ok { + return returnFunc(context1, b) } - if rf, ok := ret.Get(0).(func(context.Context, bool) *flow.Block); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, bool) *flow.Block); ok { + r0 = returnFunc(context1, b) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(context.Context, bool) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, bool) error); ok { + r1 = returnFunc(context1, b) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetTransactionResult provides a mock function with given fields: _a0, _a1 -func (_m *SDKClientWrapper) GetTransactionResult(_a0 context.Context, _a1 flow.Identifier) (*flow.TransactionResult, error) { - ret := _m.Called(_a0, _a1) +// SDKClientWrapper_GetLatestBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLatestBlock' +type SDKClientWrapper_GetLatestBlock_Call struct { + *mock.Call +} + +// GetLatestBlock is a helper method to define mock.On call +// - context1 context.Context +// - b bool +func (_e *SDKClientWrapper_Expecter) GetLatestBlock(context1 interface{}, b interface{}) *SDKClientWrapper_GetLatestBlock_Call { + return &SDKClientWrapper_GetLatestBlock_Call{Call: _e.mock.On("GetLatestBlock", context1, b)} +} + +func (_c *SDKClientWrapper_GetLatestBlock_Call) Run(run func(context1 context.Context, b bool)) *SDKClientWrapper_GetLatestBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SDKClientWrapper_GetLatestBlock_Call) Return(block *flow.Block, err error) *SDKClientWrapper_GetLatestBlock_Call { + _c.Call.Return(block, err) + return _c +} + +func (_c *SDKClientWrapper_GetLatestBlock_Call) RunAndReturn(run func(context1 context.Context, b bool) (*flow.Block, error)) *SDKClientWrapper_GetLatestBlock_Call { + _c.Call.Return(run) + return _c +} + +// GetTransactionResult provides a mock function for the type SDKClientWrapper +func (_mock *SDKClientWrapper) GetTransactionResult(context1 context.Context, identifier flow.Identifier) (*flow.TransactionResult, error) { + ret := _mock.Called(context1, identifier) if len(ret) == 0 { panic("no return value specified for GetTransactionResult") @@ -177,54 +407,117 @@ func (_m *SDKClientWrapper) GetTransactionResult(_a0 context.Context, _a1 flow.I var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionResult, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) (*flow.TransactionResult, error)); ok { + return returnFunc(context1, identifier) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionResult); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) *flow.TransactionResult); ok { + r0 = returnFunc(context1, identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier) error); ok { + r1 = returnFunc(context1, identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// SendTransaction provides a mock function with given fields: _a0, _a1 -func (_m *SDKClientWrapper) SendTransaction(_a0 context.Context, _a1 flow.Transaction) error { - ret := _m.Called(_a0, _a1) +// SDKClientWrapper_GetTransactionResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTransactionResult' +type SDKClientWrapper_GetTransactionResult_Call struct { + *mock.Call +} + +// GetTransactionResult is a helper method to define mock.On call +// - context1 context.Context +// - identifier flow.Identifier +func (_e *SDKClientWrapper_Expecter) GetTransactionResult(context1 interface{}, identifier interface{}) *SDKClientWrapper_GetTransactionResult_Call { + return &SDKClientWrapper_GetTransactionResult_Call{Call: _e.mock.On("GetTransactionResult", context1, identifier)} +} + +func (_c *SDKClientWrapper_GetTransactionResult_Call) Run(run func(context1 context.Context, identifier flow.Identifier)) *SDKClientWrapper_GetTransactionResult_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SDKClientWrapper_GetTransactionResult_Call) Return(transactionResult *flow.TransactionResult, err error) *SDKClientWrapper_GetTransactionResult_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *SDKClientWrapper_GetTransactionResult_Call) RunAndReturn(run func(context1 context.Context, identifier flow.Identifier) (*flow.TransactionResult, error)) *SDKClientWrapper_GetTransactionResult_Call { + _c.Call.Return(run) + return _c +} + +// SendTransaction provides a mock function for the type SDKClientWrapper +func (_mock *SDKClientWrapper) SendTransaction(context1 context.Context, transaction flow.Transaction) error { + ret := _mock.Called(context1, transaction) if len(ret) == 0 { panic("no return value specified for SendTransaction") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Transaction) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Transaction) error); ok { + r0 = returnFunc(context1, transaction) } else { r0 = ret.Error(0) } - return r0 } -// NewSDKClientWrapper creates a new instance of SDKClientWrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSDKClientWrapper(t interface { - mock.TestingT - Cleanup(func()) -}) *SDKClientWrapper { - mock := &SDKClientWrapper{} - mock.Mock.Test(t) +// SDKClientWrapper_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' +type SDKClientWrapper_SendTransaction_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SendTransaction is a helper method to define mock.On call +// - context1 context.Context +// - transaction flow.Transaction +func (_e *SDKClientWrapper_Expecter) SendTransaction(context1 interface{}, transaction interface{}) *SDKClientWrapper_SendTransaction_Call { + return &SDKClientWrapper_SendTransaction_Call{Call: _e.mock.On("SendTransaction", context1, transaction)} +} - return mock +func (_c *SDKClientWrapper_SendTransaction_Call) Run(run func(context1 context.Context, transaction flow.Transaction)) *SDKClientWrapper_SendTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Transaction + if args[1] != nil { + arg1 = args[1].(flow.Transaction) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SDKClientWrapper_SendTransaction_Call) Return(err error) *SDKClientWrapper_SendTransaction_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SDKClientWrapper_SendTransaction_Call) RunAndReturn(run func(context1 context.Context, transaction flow.Transaction) error) *SDKClientWrapper_SendTransaction_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/seal_validator.go b/module/mock/seal_validator.go index d9195f240db..dfe5a8fa9bd 100644 --- a/module/mock/seal_validator.go +++ b/module/mock/seal_validator.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSealValidator creates a new instance of SealValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSealValidator(t interface { + mock.TestingT + Cleanup(func()) +}) *SealValidator { + mock := &SealValidator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SealValidator is an autogenerated mock type for the SealValidator type type SealValidator struct { mock.Mock } -// Validate provides a mock function with given fields: candidate -func (_m *SealValidator) Validate(candidate *flow.Block) (*flow.Seal, error) { - ret := _m.Called(candidate) +type SealValidator_Expecter struct { + mock *mock.Mock +} + +func (_m *SealValidator) EXPECT() *SealValidator_Expecter { + return &SealValidator_Expecter{mock: &_m.Mock} +} + +// Validate provides a mock function for the type SealValidator +func (_mock *SealValidator) Validate(candidate *flow.Block) (*flow.Seal, error) { + ret := _mock.Called(candidate) if len(ret) == 0 { panic("no return value specified for Validate") @@ -22,36 +46,54 @@ func (_m *SealValidator) Validate(candidate *flow.Block) (*flow.Seal, error) { var r0 *flow.Seal var r1 error - if rf, ok := ret.Get(0).(func(*flow.Block) (*flow.Seal, error)); ok { - return rf(candidate) + if returnFunc, ok := ret.Get(0).(func(*flow.Block) (*flow.Seal, error)); ok { + return returnFunc(candidate) } - if rf, ok := ret.Get(0).(func(*flow.Block) *flow.Seal); ok { - r0 = rf(candidate) + if returnFunc, ok := ret.Get(0).(func(*flow.Block) *flow.Seal); ok { + r0 = returnFunc(candidate) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Seal) } } - - if rf, ok := ret.Get(1).(func(*flow.Block) error); ok { - r1 = rf(candidate) + if returnFunc, ok := ret.Get(1).(func(*flow.Block) error); ok { + r1 = returnFunc(candidate) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSealValidator creates a new instance of SealValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSealValidator(t interface { - mock.TestingT - Cleanup(func()) -}) *SealValidator { - mock := &SealValidator{} - mock.Mock.Test(t) +// SealValidator_Validate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Validate' +type SealValidator_Validate_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Validate is a helper method to define mock.On call +// - candidate *flow.Block +func (_e *SealValidator_Expecter) Validate(candidate interface{}) *SealValidator_Validate_Call { + return &SealValidator_Validate_Call{Call: _e.mock.On("Validate", candidate)} +} - return mock +func (_c *SealValidator_Validate_Call) Run(run func(candidate *flow.Block)) *SealValidator_Validate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Block + if args[0] != nil { + arg0 = args[0].(*flow.Block) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealValidator_Validate_Call) Return(seal *flow.Seal, err error) *SealValidator_Validate_Call { + _c.Call.Return(seal, err) + return _c +} + +func (_c *SealValidator_Validate_Call) RunAndReturn(run func(candidate *flow.Block) (*flow.Seal, error)) *SealValidator_Validate_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/sealing_configs_getter.go b/module/mock/sealing_configs_getter.go index 21e76d9ceca..5579468c552 100644 --- a/module/mock/sealing_configs_getter.go +++ b/module/mock/sealing_configs_getter.go @@ -1,114 +1,256 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewSealingConfigsGetter creates a new instance of SealingConfigsGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSealingConfigsGetter(t interface { + mock.TestingT + Cleanup(func()) +}) *SealingConfigsGetter { + mock := &SealingConfigsGetter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // SealingConfigsGetter is an autogenerated mock type for the SealingConfigsGetter type type SealingConfigsGetter struct { mock.Mock } -// ApprovalRequestsThresholdConst provides a mock function with no fields -func (_m *SealingConfigsGetter) ApprovalRequestsThresholdConst() uint64 { - ret := _m.Called() +type SealingConfigsGetter_Expecter struct { + mock *mock.Mock +} + +func (_m *SealingConfigsGetter) EXPECT() *SealingConfigsGetter_Expecter { + return &SealingConfigsGetter_Expecter{mock: &_m.Mock} +} + +// ApprovalRequestsThresholdConst provides a mock function for the type SealingConfigsGetter +func (_mock *SealingConfigsGetter) ApprovalRequestsThresholdConst() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ApprovalRequestsThresholdConst") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// ChunkAlphaConst provides a mock function with no fields -func (_m *SealingConfigsGetter) ChunkAlphaConst() uint { - ret := _m.Called() +// SealingConfigsGetter_ApprovalRequestsThresholdConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ApprovalRequestsThresholdConst' +type SealingConfigsGetter_ApprovalRequestsThresholdConst_Call struct { + *mock.Call +} + +// ApprovalRequestsThresholdConst is a helper method to define mock.On call +func (_e *SealingConfigsGetter_Expecter) ApprovalRequestsThresholdConst() *SealingConfigsGetter_ApprovalRequestsThresholdConst_Call { + return &SealingConfigsGetter_ApprovalRequestsThresholdConst_Call{Call: _e.mock.On("ApprovalRequestsThresholdConst")} +} + +func (_c *SealingConfigsGetter_ApprovalRequestsThresholdConst_Call) Run(run func()) *SealingConfigsGetter_ApprovalRequestsThresholdConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsGetter_ApprovalRequestsThresholdConst_Call) Return(v uint64) *SealingConfigsGetter_ApprovalRequestsThresholdConst_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsGetter_ApprovalRequestsThresholdConst_Call) RunAndReturn(run func() uint64) *SealingConfigsGetter_ApprovalRequestsThresholdConst_Call { + _c.Call.Return(run) + return _c +} + +// ChunkAlphaConst provides a mock function for the type SealingConfigsGetter +func (_mock *SealingConfigsGetter) ChunkAlphaConst() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ChunkAlphaConst") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// EmergencySealingActiveConst provides a mock function with no fields -func (_m *SealingConfigsGetter) EmergencySealingActiveConst() bool { - ret := _m.Called() +// SealingConfigsGetter_ChunkAlphaConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChunkAlphaConst' +type SealingConfigsGetter_ChunkAlphaConst_Call struct { + *mock.Call +} + +// ChunkAlphaConst is a helper method to define mock.On call +func (_e *SealingConfigsGetter_Expecter) ChunkAlphaConst() *SealingConfigsGetter_ChunkAlphaConst_Call { + return &SealingConfigsGetter_ChunkAlphaConst_Call{Call: _e.mock.On("ChunkAlphaConst")} +} + +func (_c *SealingConfigsGetter_ChunkAlphaConst_Call) Run(run func()) *SealingConfigsGetter_ChunkAlphaConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsGetter_ChunkAlphaConst_Call) Return(v uint) *SealingConfigsGetter_ChunkAlphaConst_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsGetter_ChunkAlphaConst_Call) RunAndReturn(run func() uint) *SealingConfigsGetter_ChunkAlphaConst_Call { + _c.Call.Return(run) + return _c +} + +// EmergencySealingActiveConst provides a mock function for the type SealingConfigsGetter +func (_mock *SealingConfigsGetter) EmergencySealingActiveConst() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EmergencySealingActiveConst") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// RequireApprovalsForSealConstructionDynamicValue provides a mock function with no fields -func (_m *SealingConfigsGetter) RequireApprovalsForSealConstructionDynamicValue() uint { - ret := _m.Called() +// SealingConfigsGetter_EmergencySealingActiveConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EmergencySealingActiveConst' +type SealingConfigsGetter_EmergencySealingActiveConst_Call struct { + *mock.Call +} + +// EmergencySealingActiveConst is a helper method to define mock.On call +func (_e *SealingConfigsGetter_Expecter) EmergencySealingActiveConst() *SealingConfigsGetter_EmergencySealingActiveConst_Call { + return &SealingConfigsGetter_EmergencySealingActiveConst_Call{Call: _e.mock.On("EmergencySealingActiveConst")} +} + +func (_c *SealingConfigsGetter_EmergencySealingActiveConst_Call) Run(run func()) *SealingConfigsGetter_EmergencySealingActiveConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsGetter_EmergencySealingActiveConst_Call) Return(b bool) *SealingConfigsGetter_EmergencySealingActiveConst_Call { + _c.Call.Return(b) + return _c +} + +func (_c *SealingConfigsGetter_EmergencySealingActiveConst_Call) RunAndReturn(run func() bool) *SealingConfigsGetter_EmergencySealingActiveConst_Call { + _c.Call.Return(run) + return _c +} + +// RequireApprovalsForSealConstructionDynamicValue provides a mock function for the type SealingConfigsGetter +func (_mock *SealingConfigsGetter) RequireApprovalsForSealConstructionDynamicValue() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RequireApprovalsForSealConstructionDynamicValue") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// RequireApprovalsForSealVerificationConst provides a mock function with no fields -func (_m *SealingConfigsGetter) RequireApprovalsForSealVerificationConst() uint { - ret := _m.Called() +// SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequireApprovalsForSealConstructionDynamicValue' +type SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call struct { + *mock.Call +} + +// RequireApprovalsForSealConstructionDynamicValue is a helper method to define mock.On call +func (_e *SealingConfigsGetter_Expecter) RequireApprovalsForSealConstructionDynamicValue() *SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call { + return &SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call{Call: _e.mock.On("RequireApprovalsForSealConstructionDynamicValue")} +} + +func (_c *SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call) Run(run func()) *SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call) Return(v uint) *SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call) RunAndReturn(run func() uint) *SealingConfigsGetter_RequireApprovalsForSealConstructionDynamicValue_Call { + _c.Call.Return(run) + return _c +} + +// RequireApprovalsForSealVerificationConst provides a mock function for the type SealingConfigsGetter +func (_mock *SealingConfigsGetter) RequireApprovalsForSealVerificationConst() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RequireApprovalsForSealVerificationConst") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewSealingConfigsGetter creates a new instance of SealingConfigsGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSealingConfigsGetter(t interface { - mock.TestingT - Cleanup(func()) -}) *SealingConfigsGetter { - mock := &SealingConfigsGetter{} - mock.Mock.Test(t) +// SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequireApprovalsForSealVerificationConst' +type SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RequireApprovalsForSealVerificationConst is a helper method to define mock.On call +func (_e *SealingConfigsGetter_Expecter) RequireApprovalsForSealVerificationConst() *SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call { + return &SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call{Call: _e.mock.On("RequireApprovalsForSealVerificationConst")} +} - return mock +func (_c *SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call) Run(run func()) *SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call) Return(v uint) *SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call) RunAndReturn(run func() uint) *SealingConfigsGetter_RequireApprovalsForSealVerificationConst_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/sealing_configs_setter.go b/module/mock/sealing_configs_setter.go index 7aadddc1f07..8786281e02b 100644 --- a/module/mock/sealing_configs_setter.go +++ b/module/mock/sealing_configs_setter.go @@ -1,132 +1,307 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewSealingConfigsSetter creates a new instance of SealingConfigsSetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSealingConfigsSetter(t interface { + mock.TestingT + Cleanup(func()) +}) *SealingConfigsSetter { + mock := &SealingConfigsSetter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // SealingConfigsSetter is an autogenerated mock type for the SealingConfigsSetter type type SealingConfigsSetter struct { mock.Mock } -// ApprovalRequestsThresholdConst provides a mock function with no fields -func (_m *SealingConfigsSetter) ApprovalRequestsThresholdConst() uint64 { - ret := _m.Called() +type SealingConfigsSetter_Expecter struct { + mock *mock.Mock +} + +func (_m *SealingConfigsSetter) EXPECT() *SealingConfigsSetter_Expecter { + return &SealingConfigsSetter_Expecter{mock: &_m.Mock} +} + +// ApprovalRequestsThresholdConst provides a mock function for the type SealingConfigsSetter +func (_mock *SealingConfigsSetter) ApprovalRequestsThresholdConst() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ApprovalRequestsThresholdConst") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// ChunkAlphaConst provides a mock function with no fields -func (_m *SealingConfigsSetter) ChunkAlphaConst() uint { - ret := _m.Called() +// SealingConfigsSetter_ApprovalRequestsThresholdConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ApprovalRequestsThresholdConst' +type SealingConfigsSetter_ApprovalRequestsThresholdConst_Call struct { + *mock.Call +} + +// ApprovalRequestsThresholdConst is a helper method to define mock.On call +func (_e *SealingConfigsSetter_Expecter) ApprovalRequestsThresholdConst() *SealingConfigsSetter_ApprovalRequestsThresholdConst_Call { + return &SealingConfigsSetter_ApprovalRequestsThresholdConst_Call{Call: _e.mock.On("ApprovalRequestsThresholdConst")} +} + +func (_c *SealingConfigsSetter_ApprovalRequestsThresholdConst_Call) Run(run func()) *SealingConfigsSetter_ApprovalRequestsThresholdConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsSetter_ApprovalRequestsThresholdConst_Call) Return(v uint64) *SealingConfigsSetter_ApprovalRequestsThresholdConst_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsSetter_ApprovalRequestsThresholdConst_Call) RunAndReturn(run func() uint64) *SealingConfigsSetter_ApprovalRequestsThresholdConst_Call { + _c.Call.Return(run) + return _c +} + +// ChunkAlphaConst provides a mock function for the type SealingConfigsSetter +func (_mock *SealingConfigsSetter) ChunkAlphaConst() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ChunkAlphaConst") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// EmergencySealingActiveConst provides a mock function with no fields -func (_m *SealingConfigsSetter) EmergencySealingActiveConst() bool { - ret := _m.Called() +// SealingConfigsSetter_ChunkAlphaConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChunkAlphaConst' +type SealingConfigsSetter_ChunkAlphaConst_Call struct { + *mock.Call +} + +// ChunkAlphaConst is a helper method to define mock.On call +func (_e *SealingConfigsSetter_Expecter) ChunkAlphaConst() *SealingConfigsSetter_ChunkAlphaConst_Call { + return &SealingConfigsSetter_ChunkAlphaConst_Call{Call: _e.mock.On("ChunkAlphaConst")} +} + +func (_c *SealingConfigsSetter_ChunkAlphaConst_Call) Run(run func()) *SealingConfigsSetter_ChunkAlphaConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsSetter_ChunkAlphaConst_Call) Return(v uint) *SealingConfigsSetter_ChunkAlphaConst_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsSetter_ChunkAlphaConst_Call) RunAndReturn(run func() uint) *SealingConfigsSetter_ChunkAlphaConst_Call { + _c.Call.Return(run) + return _c +} + +// EmergencySealingActiveConst provides a mock function for the type SealingConfigsSetter +func (_mock *SealingConfigsSetter) EmergencySealingActiveConst() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EmergencySealingActiveConst") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// RequireApprovalsForSealConstructionDynamicValue provides a mock function with no fields -func (_m *SealingConfigsSetter) RequireApprovalsForSealConstructionDynamicValue() uint { - ret := _m.Called() +// SealingConfigsSetter_EmergencySealingActiveConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EmergencySealingActiveConst' +type SealingConfigsSetter_EmergencySealingActiveConst_Call struct { + *mock.Call +} + +// EmergencySealingActiveConst is a helper method to define mock.On call +func (_e *SealingConfigsSetter_Expecter) EmergencySealingActiveConst() *SealingConfigsSetter_EmergencySealingActiveConst_Call { + return &SealingConfigsSetter_EmergencySealingActiveConst_Call{Call: _e.mock.On("EmergencySealingActiveConst")} +} + +func (_c *SealingConfigsSetter_EmergencySealingActiveConst_Call) Run(run func()) *SealingConfigsSetter_EmergencySealingActiveConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsSetter_EmergencySealingActiveConst_Call) Return(b bool) *SealingConfigsSetter_EmergencySealingActiveConst_Call { + _c.Call.Return(b) + return _c +} + +func (_c *SealingConfigsSetter_EmergencySealingActiveConst_Call) RunAndReturn(run func() bool) *SealingConfigsSetter_EmergencySealingActiveConst_Call { + _c.Call.Return(run) + return _c +} + +// RequireApprovalsForSealConstructionDynamicValue provides a mock function for the type SealingConfigsSetter +func (_mock *SealingConfigsSetter) RequireApprovalsForSealConstructionDynamicValue() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RequireApprovalsForSealConstructionDynamicValue") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// RequireApprovalsForSealVerificationConst provides a mock function with no fields -func (_m *SealingConfigsSetter) RequireApprovalsForSealVerificationConst() uint { - ret := _m.Called() +// SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequireApprovalsForSealConstructionDynamicValue' +type SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call struct { + *mock.Call +} + +// RequireApprovalsForSealConstructionDynamicValue is a helper method to define mock.On call +func (_e *SealingConfigsSetter_Expecter) RequireApprovalsForSealConstructionDynamicValue() *SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call { + return &SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call{Call: _e.mock.On("RequireApprovalsForSealConstructionDynamicValue")} +} + +func (_c *SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call) Run(run func()) *SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call) Return(v uint) *SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call) RunAndReturn(run func() uint) *SealingConfigsSetter_RequireApprovalsForSealConstructionDynamicValue_Call { + _c.Call.Return(run) + return _c +} + +// RequireApprovalsForSealVerificationConst provides a mock function for the type SealingConfigsSetter +func (_mock *SealingConfigsSetter) RequireApprovalsForSealVerificationConst() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RequireApprovalsForSealVerificationConst") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// SetRequiredApprovalsForSealingConstruction provides a mock function with given fields: newVal -func (_m *SealingConfigsSetter) SetRequiredApprovalsForSealingConstruction(newVal uint) error { - ret := _m.Called(newVal) +// SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequireApprovalsForSealVerificationConst' +type SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call struct { + *mock.Call +} + +// RequireApprovalsForSealVerificationConst is a helper method to define mock.On call +func (_e *SealingConfigsSetter_Expecter) RequireApprovalsForSealVerificationConst() *SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call { + return &SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call{Call: _e.mock.On("RequireApprovalsForSealVerificationConst")} +} + +func (_c *SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call) Run(run func()) *SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call) Return(v uint) *SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call) RunAndReturn(run func() uint) *SealingConfigsSetter_RequireApprovalsForSealVerificationConst_Call { + _c.Call.Return(run) + return _c +} + +// SetRequiredApprovalsForSealingConstruction provides a mock function for the type SealingConfigsSetter +func (_mock *SealingConfigsSetter) SetRequiredApprovalsForSealingConstruction(newVal uint) error { + ret := _mock.Called(newVal) if len(ret) == 0 { panic("no return value specified for SetRequiredApprovalsForSealingConstruction") } var r0 error - if rf, ok := ret.Get(0).(func(uint) error); ok { - r0 = rf(newVal) + if returnFunc, ok := ret.Get(0).(func(uint) error); ok { + r0 = returnFunc(newVal) } else { r0 = ret.Error(0) } - return r0 } -// NewSealingConfigsSetter creates a new instance of SealingConfigsSetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSealingConfigsSetter(t interface { - mock.TestingT - Cleanup(func()) -}) *SealingConfigsSetter { - mock := &SealingConfigsSetter{} - mock.Mock.Test(t) +// SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetRequiredApprovalsForSealingConstruction' +type SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SetRequiredApprovalsForSealingConstruction is a helper method to define mock.On call +// - newVal uint +func (_e *SealingConfigsSetter_Expecter) SetRequiredApprovalsForSealingConstruction(newVal interface{}) *SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call { + return &SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call{Call: _e.mock.On("SetRequiredApprovalsForSealingConstruction", newVal)} +} - return mock +func (_c *SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call) Run(run func(newVal uint)) *SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call) Return(err error) *SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call) RunAndReturn(run func(newVal uint) error) *SealingConfigsSetter_SetRequiredApprovalsForSealingConstruction_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/sealing_lag_rate_limiter_config.go b/module/mock/sealing_lag_rate_limiter_config.go index 15d51e3ba76..96d04bcfba4 100644 --- a/module/mock/sealing_lag_rate_limiter_config.go +++ b/module/mock/sealing_lag_rate_limiter_config.go @@ -1,168 +1,416 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewSealingLagRateLimiterConfig creates a new instance of SealingLagRateLimiterConfig. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSealingLagRateLimiterConfig(t interface { + mock.TestingT + Cleanup(func()) +}) *SealingLagRateLimiterConfig { + mock := &SealingLagRateLimiterConfig{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // SealingLagRateLimiterConfig is an autogenerated mock type for the SealingLagRateLimiterConfig type type SealingLagRateLimiterConfig struct { mock.Mock } -// HalvingInterval provides a mock function with no fields -func (_m *SealingLagRateLimiterConfig) HalvingInterval() uint { - ret := _m.Called() +type SealingLagRateLimiterConfig_Expecter struct { + mock *mock.Mock +} + +func (_m *SealingLagRateLimiterConfig) EXPECT() *SealingLagRateLimiterConfig_Expecter { + return &SealingLagRateLimiterConfig_Expecter{mock: &_m.Mock} +} + +// HalvingInterval provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) HalvingInterval() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HalvingInterval") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// MaxSealingLag provides a mock function with no fields -func (_m *SealingLagRateLimiterConfig) MaxSealingLag() uint { - ret := _m.Called() +// SealingLagRateLimiterConfig_HalvingInterval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HalvingInterval' +type SealingLagRateLimiterConfig_HalvingInterval_Call struct { + *mock.Call +} + +// HalvingInterval is a helper method to define mock.On call +func (_e *SealingLagRateLimiterConfig_Expecter) HalvingInterval() *SealingLagRateLimiterConfig_HalvingInterval_Call { + return &SealingLagRateLimiterConfig_HalvingInterval_Call{Call: _e.mock.On("HalvingInterval")} +} + +func (_c *SealingLagRateLimiterConfig_HalvingInterval_Call) Run(run func()) *SealingLagRateLimiterConfig_HalvingInterval_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_HalvingInterval_Call) Return(v uint) *SealingLagRateLimiterConfig_HalvingInterval_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingLagRateLimiterConfig_HalvingInterval_Call) RunAndReturn(run func() uint) *SealingLagRateLimiterConfig_HalvingInterval_Call { + _c.Call.Return(run) + return _c +} + +// MaxSealingLag provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) MaxSealingLag() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MaxSealingLag") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// MinCollectionSize provides a mock function with no fields -func (_m *SealingLagRateLimiterConfig) MinCollectionSize() uint { - ret := _m.Called() +// SealingLagRateLimiterConfig_MaxSealingLag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MaxSealingLag' +type SealingLagRateLimiterConfig_MaxSealingLag_Call struct { + *mock.Call +} + +// MaxSealingLag is a helper method to define mock.On call +func (_e *SealingLagRateLimiterConfig_Expecter) MaxSealingLag() *SealingLagRateLimiterConfig_MaxSealingLag_Call { + return &SealingLagRateLimiterConfig_MaxSealingLag_Call{Call: _e.mock.On("MaxSealingLag")} +} + +func (_c *SealingLagRateLimiterConfig_MaxSealingLag_Call) Run(run func()) *SealingLagRateLimiterConfig_MaxSealingLag_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_MaxSealingLag_Call) Return(v uint) *SealingLagRateLimiterConfig_MaxSealingLag_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingLagRateLimiterConfig_MaxSealingLag_Call) RunAndReturn(run func() uint) *SealingLagRateLimiterConfig_MaxSealingLag_Call { + _c.Call.Return(run) + return _c +} + +// MinCollectionSize provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) MinCollectionSize() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MinCollectionSize") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// MinSealingLag provides a mock function with no fields -func (_m *SealingLagRateLimiterConfig) MinSealingLag() uint { - ret := _m.Called() +// SealingLagRateLimiterConfig_MinCollectionSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MinCollectionSize' +type SealingLagRateLimiterConfig_MinCollectionSize_Call struct { + *mock.Call +} + +// MinCollectionSize is a helper method to define mock.On call +func (_e *SealingLagRateLimiterConfig_Expecter) MinCollectionSize() *SealingLagRateLimiterConfig_MinCollectionSize_Call { + return &SealingLagRateLimiterConfig_MinCollectionSize_Call{Call: _e.mock.On("MinCollectionSize")} +} + +func (_c *SealingLagRateLimiterConfig_MinCollectionSize_Call) Run(run func()) *SealingLagRateLimiterConfig_MinCollectionSize_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_MinCollectionSize_Call) Return(v uint) *SealingLagRateLimiterConfig_MinCollectionSize_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingLagRateLimiterConfig_MinCollectionSize_Call) RunAndReturn(run func() uint) *SealingLagRateLimiterConfig_MinCollectionSize_Call { + _c.Call.Return(run) + return _c +} + +// MinSealingLag provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) MinSealingLag() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for MinSealingLag") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// SetHalvingInterval provides a mock function with given fields: value -func (_m *SealingLagRateLimiterConfig) SetHalvingInterval(value uint) error { - ret := _m.Called(value) +// SealingLagRateLimiterConfig_MinSealingLag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MinSealingLag' +type SealingLagRateLimiterConfig_MinSealingLag_Call struct { + *mock.Call +} + +// MinSealingLag is a helper method to define mock.On call +func (_e *SealingLagRateLimiterConfig_Expecter) MinSealingLag() *SealingLagRateLimiterConfig_MinSealingLag_Call { + return &SealingLagRateLimiterConfig_MinSealingLag_Call{Call: _e.mock.On("MinSealingLag")} +} + +func (_c *SealingLagRateLimiterConfig_MinSealingLag_Call) Run(run func()) *SealingLagRateLimiterConfig_MinSealingLag_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_MinSealingLag_Call) Return(v uint) *SealingLagRateLimiterConfig_MinSealingLag_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SealingLagRateLimiterConfig_MinSealingLag_Call) RunAndReturn(run func() uint) *SealingLagRateLimiterConfig_MinSealingLag_Call { + _c.Call.Return(run) + return _c +} + +// SetHalvingInterval provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) SetHalvingInterval(value uint) error { + ret := _mock.Called(value) if len(ret) == 0 { panic("no return value specified for SetHalvingInterval") } var r0 error - if rf, ok := ret.Get(0).(func(uint) error); ok { - r0 = rf(value) + if returnFunc, ok := ret.Get(0).(func(uint) error); ok { + r0 = returnFunc(value) } else { r0 = ret.Error(0) } - return r0 } -// SetMaxSealingLag provides a mock function with given fields: value -func (_m *SealingLagRateLimiterConfig) SetMaxSealingLag(value uint) error { - ret := _m.Called(value) +// SealingLagRateLimiterConfig_SetHalvingInterval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetHalvingInterval' +type SealingLagRateLimiterConfig_SetHalvingInterval_Call struct { + *mock.Call +} + +// SetHalvingInterval is a helper method to define mock.On call +// - value uint +func (_e *SealingLagRateLimiterConfig_Expecter) SetHalvingInterval(value interface{}) *SealingLagRateLimiterConfig_SetHalvingInterval_Call { + return &SealingLagRateLimiterConfig_SetHalvingInterval_Call{Call: _e.mock.On("SetHalvingInterval", value)} +} + +func (_c *SealingLagRateLimiterConfig_SetHalvingInterval_Call) Run(run func(value uint)) *SealingLagRateLimiterConfig_SetHalvingInterval_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetHalvingInterval_Call) Return(err error) *SealingLagRateLimiterConfig_SetHalvingInterval_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetHalvingInterval_Call) RunAndReturn(run func(value uint) error) *SealingLagRateLimiterConfig_SetHalvingInterval_Call { + _c.Call.Return(run) + return _c +} + +// SetMaxSealingLag provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) SetMaxSealingLag(value uint) error { + ret := _mock.Called(value) if len(ret) == 0 { panic("no return value specified for SetMaxSealingLag") } var r0 error - if rf, ok := ret.Get(0).(func(uint) error); ok { - r0 = rf(value) + if returnFunc, ok := ret.Get(0).(func(uint) error); ok { + r0 = returnFunc(value) } else { r0 = ret.Error(0) } - return r0 } -// SetMinCollectionSize provides a mock function with given fields: value -func (_m *SealingLagRateLimiterConfig) SetMinCollectionSize(value uint) error { - ret := _m.Called(value) +// SealingLagRateLimiterConfig_SetMaxSealingLag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetMaxSealingLag' +type SealingLagRateLimiterConfig_SetMaxSealingLag_Call struct { + *mock.Call +} + +// SetMaxSealingLag is a helper method to define mock.On call +// - value uint +func (_e *SealingLagRateLimiterConfig_Expecter) SetMaxSealingLag(value interface{}) *SealingLagRateLimiterConfig_SetMaxSealingLag_Call { + return &SealingLagRateLimiterConfig_SetMaxSealingLag_Call{Call: _e.mock.On("SetMaxSealingLag", value)} +} + +func (_c *SealingLagRateLimiterConfig_SetMaxSealingLag_Call) Run(run func(value uint)) *SealingLagRateLimiterConfig_SetMaxSealingLag_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetMaxSealingLag_Call) Return(err error) *SealingLagRateLimiterConfig_SetMaxSealingLag_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetMaxSealingLag_Call) RunAndReturn(run func(value uint) error) *SealingLagRateLimiterConfig_SetMaxSealingLag_Call { + _c.Call.Return(run) + return _c +} + +// SetMinCollectionSize provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) SetMinCollectionSize(value uint) error { + ret := _mock.Called(value) if len(ret) == 0 { panic("no return value specified for SetMinCollectionSize") } var r0 error - if rf, ok := ret.Get(0).(func(uint) error); ok { - r0 = rf(value) + if returnFunc, ok := ret.Get(0).(func(uint) error); ok { + r0 = returnFunc(value) } else { r0 = ret.Error(0) } - return r0 } -// SetMinSealingLag provides a mock function with given fields: value -func (_m *SealingLagRateLimiterConfig) SetMinSealingLag(value uint) error { - ret := _m.Called(value) +// SealingLagRateLimiterConfig_SetMinCollectionSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetMinCollectionSize' +type SealingLagRateLimiterConfig_SetMinCollectionSize_Call struct { + *mock.Call +} + +// SetMinCollectionSize is a helper method to define mock.On call +// - value uint +func (_e *SealingLagRateLimiterConfig_Expecter) SetMinCollectionSize(value interface{}) *SealingLagRateLimiterConfig_SetMinCollectionSize_Call { + return &SealingLagRateLimiterConfig_SetMinCollectionSize_Call{Call: _e.mock.On("SetMinCollectionSize", value)} +} + +func (_c *SealingLagRateLimiterConfig_SetMinCollectionSize_Call) Run(run func(value uint)) *SealingLagRateLimiterConfig_SetMinCollectionSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetMinCollectionSize_Call) Return(err error) *SealingLagRateLimiterConfig_SetMinCollectionSize_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetMinCollectionSize_Call) RunAndReturn(run func(value uint) error) *SealingLagRateLimiterConfig_SetMinCollectionSize_Call { + _c.Call.Return(run) + return _c +} + +// SetMinSealingLag provides a mock function for the type SealingLagRateLimiterConfig +func (_mock *SealingLagRateLimiterConfig) SetMinSealingLag(value uint) error { + ret := _mock.Called(value) if len(ret) == 0 { panic("no return value specified for SetMinSealingLag") } var r0 error - if rf, ok := ret.Get(0).(func(uint) error); ok { - r0 = rf(value) + if returnFunc, ok := ret.Get(0).(func(uint) error); ok { + r0 = returnFunc(value) } else { r0 = ret.Error(0) } - return r0 } -// NewSealingLagRateLimiterConfig creates a new instance of SealingLagRateLimiterConfig. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSealingLagRateLimiterConfig(t interface { - mock.TestingT - Cleanup(func()) -}) *SealingLagRateLimiterConfig { - mock := &SealingLagRateLimiterConfig{} - mock.Mock.Test(t) +// SealingLagRateLimiterConfig_SetMinSealingLag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetMinSealingLag' +type SealingLagRateLimiterConfig_SetMinSealingLag_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SetMinSealingLag is a helper method to define mock.On call +// - value uint +func (_e *SealingLagRateLimiterConfig_Expecter) SetMinSealingLag(value interface{}) *SealingLagRateLimiterConfig_SetMinSealingLag_Call { + return &SealingLagRateLimiterConfig_SetMinSealingLag_Call{Call: _e.mock.On("SetMinSealingLag", value)} +} - return mock +func (_c *SealingLagRateLimiterConfig_SetMinSealingLag_Call) Run(run func(value uint)) *SealingLagRateLimiterConfig_SetMinSealingLag_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetMinSealingLag_Call) Return(err error) *SealingLagRateLimiterConfig_SetMinSealingLag_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SealingLagRateLimiterConfig_SetMinSealingLag_Call) RunAndReturn(run func(value uint) error) *SealingLagRateLimiterConfig_SetMinSealingLag_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/signer.go b/module/mock/signer.go deleted file mode 100644 index 9e8aba1932c..00000000000 --- a/module/mock/signer.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - crypto "github.com/onflow/crypto" - mock "github.com/stretchr/testify/mock" -) - -// signer is an autogenerated mock type for the signer type -type signer struct { - mock.Mock -} - -// decodePrivateKey provides a mock function with given fields: _a0 -func (_m *signer) decodePrivateKey(_a0 []byte) (crypto.PrivateKey, error) { - ret := _m.Called(_a0) - - if len(ret) == 0 { - panic("no return value specified for decodePrivateKey") - } - - var r0 crypto.PrivateKey - var r1 error - if rf, ok := ret.Get(0).(func([]byte) (crypto.PrivateKey, error)); ok { - return rf(_a0) - } - if rf, ok := ret.Get(0).(func([]byte) crypto.PrivateKey); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.PrivateKey) - } - } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// decodePublicKey provides a mock function with given fields: _a0 -func (_m *signer) decodePublicKey(_a0 []byte) (crypto.PublicKey, error) { - ret := _m.Called(_a0) - - if len(ret) == 0 { - panic("no return value specified for decodePublicKey") - } - - var r0 crypto.PublicKey - var r1 error - if rf, ok := ret.Get(0).(func([]byte) (crypto.PublicKey, error)); ok { - return rf(_a0) - } - if rf, ok := ret.Get(0).(func([]byte) crypto.PublicKey); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.PublicKey) - } - } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// decodePublicKeyCompressed provides a mock function with given fields: _a0 -func (_m *signer) decodePublicKeyCompressed(_a0 []byte) (crypto.PublicKey, error) { - ret := _m.Called(_a0) - - if len(ret) == 0 { - panic("no return value specified for decodePublicKeyCompressed") - } - - var r0 crypto.PublicKey - var r1 error - if rf, ok := ret.Get(0).(func([]byte) (crypto.PublicKey, error)); ok { - return rf(_a0) - } - if rf, ok := ret.Get(0).(func([]byte) crypto.PublicKey); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.PublicKey) - } - } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// generatePrivateKey provides a mock function with given fields: _a0 -func (_m *signer) generatePrivateKey(_a0 []byte) (crypto.PrivateKey, error) { - ret := _m.Called(_a0) - - if len(ret) == 0 { - panic("no return value specified for generatePrivateKey") - } - - var r0 crypto.PrivateKey - var r1 error - if rf, ok := ret.Get(0).(func([]byte) (crypto.PrivateKey, error)); ok { - return rf(_a0) - } - if rf, ok := ret.Get(0).(func([]byte) crypto.PrivateKey); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.PrivateKey) - } - } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// newSigner creates a new instance of signer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func newSigner(t interface { - mock.TestingT - Cleanup(func()) -}) *signer { - mock := &signer{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/module/mock/startable.go b/module/mock/startable.go index a2096729e14..9e23472450b 100644 --- a/module/mock/startable.go +++ b/module/mock/startable.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) -// Startable is an autogenerated mock type for the Startable type -type Startable struct { - mock.Mock -} - -// Start provides a mock function with given fields: _a0 -func (_m *Startable) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) -} - // NewStartable creates a new instance of Startable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewStartable(t interface { @@ -30,3 +22,56 @@ func NewStartable(t interface { return mock } + +// Startable is an autogenerated mock type for the Startable type +type Startable struct { + mock.Mock +} + +type Startable_Expecter struct { + mock *mock.Mock +} + +func (_m *Startable) EXPECT() *Startable_Expecter { + return &Startable_Expecter{mock: &_m.Mock} +} + +// Start provides a mock function for the type Startable +func (_mock *Startable) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// Startable_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type Startable_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *Startable_Expecter) Start(signalerContext interface{}) *Startable_Start_Call { + return &Startable_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *Startable_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *Startable_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Startable_Start_Call) Return() *Startable_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *Startable_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *Startable_Start_Call { + _c.Run(run) + return _c +} diff --git a/module/mock/sync_core.go b/module/mock/sync_core.go index ca5e9946bcf..30004111676 100644 --- a/module/mock/sync_core.go +++ b/module/mock/sync_core.go @@ -1,55 +1,222 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - chainsync "github.com/onflow/flow-go/model/chainsync" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/chainsync" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSyncCore creates a new instance of SyncCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSyncCore(t interface { + mock.TestingT + Cleanup(func()) +}) *SyncCore { + mock := &SyncCore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SyncCore is an autogenerated mock type for the SyncCore type type SyncCore struct { mock.Mock } -// BatchRequested provides a mock function with given fields: batch -func (_m *SyncCore) BatchRequested(batch chainsync.Batch) { - _m.Called(batch) +type SyncCore_Expecter struct { + mock *mock.Mock +} + +func (_m *SyncCore) EXPECT() *SyncCore_Expecter { + return &SyncCore_Expecter{mock: &_m.Mock} +} + +// BatchRequested provides a mock function for the type SyncCore +func (_mock *SyncCore) BatchRequested(batch chainsync.Batch) { + _mock.Called(batch) + return } -// HandleBlock provides a mock function with given fields: header -func (_m *SyncCore) HandleBlock(header *flow.Header) bool { - ret := _m.Called(header) +// SyncCore_BatchRequested_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRequested' +type SyncCore_BatchRequested_Call struct { + *mock.Call +} + +// BatchRequested is a helper method to define mock.On call +// - batch chainsync.Batch +func (_e *SyncCore_Expecter) BatchRequested(batch interface{}) *SyncCore_BatchRequested_Call { + return &SyncCore_BatchRequested_Call{Call: _e.mock.On("BatchRequested", batch)} +} + +func (_c *SyncCore_BatchRequested_Call) Run(run func(batch chainsync.Batch)) *SyncCore_BatchRequested_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 chainsync.Batch + if args[0] != nil { + arg0 = args[0].(chainsync.Batch) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SyncCore_BatchRequested_Call) Return() *SyncCore_BatchRequested_Call { + _c.Call.Return() + return _c +} + +func (_c *SyncCore_BatchRequested_Call) RunAndReturn(run func(batch chainsync.Batch)) *SyncCore_BatchRequested_Call { + _c.Run(run) + return _c +} + +// HandleBlock provides a mock function for the type SyncCore +func (_mock *SyncCore) HandleBlock(header *flow.Header) bool { + ret := _mock.Called(header) if len(ret) == 0 { panic("no return value specified for HandleBlock") } var r0 bool - if rf, ok := ret.Get(0).(func(*flow.Header) bool); ok { - r0 = rf(header) + if returnFunc, ok := ret.Get(0).(func(*flow.Header) bool); ok { + r0 = returnFunc(header) } else { r0 = ret.Get(0).(bool) } - return r0 } -// HandleHeight provides a mock function with given fields: final, height -func (_m *SyncCore) HandleHeight(final *flow.Header, height uint64) { - _m.Called(final, height) +// SyncCore_HandleBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleBlock' +type SyncCore_HandleBlock_Call struct { + *mock.Call +} + +// HandleBlock is a helper method to define mock.On call +// - header *flow.Header +func (_e *SyncCore_Expecter) HandleBlock(header interface{}) *SyncCore_HandleBlock_Call { + return &SyncCore_HandleBlock_Call{Call: _e.mock.On("HandleBlock", header)} +} + +func (_c *SyncCore_HandleBlock_Call) Run(run func(header *flow.Header)) *SyncCore_HandleBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SyncCore_HandleBlock_Call) Return(b bool) *SyncCore_HandleBlock_Call { + _c.Call.Return(b) + return _c +} + +func (_c *SyncCore_HandleBlock_Call) RunAndReturn(run func(header *flow.Header) bool) *SyncCore_HandleBlock_Call { + _c.Call.Return(run) + return _c +} + +// HandleHeight provides a mock function for the type SyncCore +func (_mock *SyncCore) HandleHeight(final *flow.Header, height uint64) { + _mock.Called(final, height) + return +} + +// SyncCore_HandleHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleHeight' +type SyncCore_HandleHeight_Call struct { + *mock.Call +} + +// HandleHeight is a helper method to define mock.On call +// - final *flow.Header +// - height uint64 +func (_e *SyncCore_Expecter) HandleHeight(final interface{}, height interface{}) *SyncCore_HandleHeight_Call { + return &SyncCore_HandleHeight_Call{Call: _e.mock.On("HandleHeight", final, height)} } -// RangeRequested provides a mock function with given fields: ran -func (_m *SyncCore) RangeRequested(ran chainsync.Range) { - _m.Called(ran) +func (_c *SyncCore_HandleHeight_Call) Run(run func(final *flow.Header, height uint64)) *SyncCore_HandleHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c } -// ScanPending provides a mock function with given fields: final -func (_m *SyncCore) ScanPending(final *flow.Header) ([]chainsync.Range, []chainsync.Batch) { - ret := _m.Called(final) +func (_c *SyncCore_HandleHeight_Call) Return() *SyncCore_HandleHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *SyncCore_HandleHeight_Call) RunAndReturn(run func(final *flow.Header, height uint64)) *SyncCore_HandleHeight_Call { + _c.Run(run) + return _c +} + +// RangeRequested provides a mock function for the type SyncCore +func (_mock *SyncCore) RangeRequested(ran chainsync.Range) { + _mock.Called(ran) + return +} + +// SyncCore_RangeRequested_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RangeRequested' +type SyncCore_RangeRequested_Call struct { + *mock.Call +} + +// RangeRequested is a helper method to define mock.On call +// - ran chainsync.Range +func (_e *SyncCore_Expecter) RangeRequested(ran interface{}) *SyncCore_RangeRequested_Call { + return &SyncCore_RangeRequested_Call{Call: _e.mock.On("RangeRequested", ran)} +} + +func (_c *SyncCore_RangeRequested_Call) Run(run func(ran chainsync.Range)) *SyncCore_RangeRequested_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 chainsync.Range + if args[0] != nil { + arg0 = args[0].(chainsync.Range) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SyncCore_RangeRequested_Call) Return() *SyncCore_RangeRequested_Call { + _c.Call.Return() + return _c +} + +func (_c *SyncCore_RangeRequested_Call) RunAndReturn(run func(ran chainsync.Range)) *SyncCore_RangeRequested_Call { + _c.Run(run) + return _c +} + +// ScanPending provides a mock function for the type SyncCore +func (_mock *SyncCore) ScanPending(final *flow.Header) ([]chainsync.Range, []chainsync.Batch) { + ret := _mock.Called(final) if len(ret) == 0 { panic("no return value specified for ScanPending") @@ -57,56 +224,113 @@ func (_m *SyncCore) ScanPending(final *flow.Header) ([]chainsync.Range, []chains var r0 []chainsync.Range var r1 []chainsync.Batch - if rf, ok := ret.Get(0).(func(*flow.Header) ([]chainsync.Range, []chainsync.Batch)); ok { - return rf(final) + if returnFunc, ok := ret.Get(0).(func(*flow.Header) ([]chainsync.Range, []chainsync.Batch)); ok { + return returnFunc(final) } - if rf, ok := ret.Get(0).(func(*flow.Header) []chainsync.Range); ok { - r0 = rf(final) + if returnFunc, ok := ret.Get(0).(func(*flow.Header) []chainsync.Range); ok { + r0 = returnFunc(final) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]chainsync.Range) } } - - if rf, ok := ret.Get(1).(func(*flow.Header) []chainsync.Batch); ok { - r1 = rf(final) + if returnFunc, ok := ret.Get(1).(func(*flow.Header) []chainsync.Batch); ok { + r1 = returnFunc(final) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]chainsync.Batch) } } - return r0, r1 } -// WithinTolerance provides a mock function with given fields: final, height -func (_m *SyncCore) WithinTolerance(final *flow.Header, height uint64) bool { - ret := _m.Called(final, height) +// SyncCore_ScanPending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScanPending' +type SyncCore_ScanPending_Call struct { + *mock.Call +} + +// ScanPending is a helper method to define mock.On call +// - final *flow.Header +func (_e *SyncCore_Expecter) ScanPending(final interface{}) *SyncCore_ScanPending_Call { + return &SyncCore_ScanPending_Call{Call: _e.mock.On("ScanPending", final)} +} + +func (_c *SyncCore_ScanPending_Call) Run(run func(final *flow.Header)) *SyncCore_ScanPending_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SyncCore_ScanPending_Call) Return(ranges []chainsync.Range, batchs []chainsync.Batch) *SyncCore_ScanPending_Call { + _c.Call.Return(ranges, batchs) + return _c +} + +func (_c *SyncCore_ScanPending_Call) RunAndReturn(run func(final *flow.Header) ([]chainsync.Range, []chainsync.Batch)) *SyncCore_ScanPending_Call { + _c.Call.Return(run) + return _c +} + +// WithinTolerance provides a mock function for the type SyncCore +func (_mock *SyncCore) WithinTolerance(final *flow.Header, height uint64) bool { + ret := _mock.Called(final, height) if len(ret) == 0 { panic("no return value specified for WithinTolerance") } var r0 bool - if rf, ok := ret.Get(0).(func(*flow.Header, uint64) bool); ok { - r0 = rf(final, height) + if returnFunc, ok := ret.Get(0).(func(*flow.Header, uint64) bool); ok { + r0 = returnFunc(final, height) } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewSyncCore creates a new instance of SyncCore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSyncCore(t interface { - mock.TestingT - Cleanup(func()) -}) *SyncCore { - mock := &SyncCore{} - mock.Mock.Test(t) +// SyncCore_WithinTolerance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithinTolerance' +type SyncCore_WithinTolerance_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WithinTolerance is a helper method to define mock.On call +// - final *flow.Header +// - height uint64 +func (_e *SyncCore_Expecter) WithinTolerance(final interface{}, height interface{}) *SyncCore_WithinTolerance_Call { + return &SyncCore_WithinTolerance_Call{Call: _e.mock.On("WithinTolerance", final, height)} +} - return mock +func (_c *SyncCore_WithinTolerance_Call) Run(run func(final *flow.Header, height uint64)) *SyncCore_WithinTolerance_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SyncCore_WithinTolerance_Call) Return(b bool) *SyncCore_WithinTolerance_Call { + _c.Call.Return(b) + return _c +} + +func (_c *SyncCore_WithinTolerance_Call) RunAndReturn(run func(final *flow.Header, height uint64) bool) *SyncCore_WithinTolerance_Call { + _c.Call.Return(run) + return _c } diff --git a/module/mock/threshold_signature_inspector.go b/module/mock/threshold_signature_inspector.go deleted file mode 100644 index 8740ef2536f..00000000000 --- a/module/mock/threshold_signature_inspector.go +++ /dev/null @@ -1,222 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - crypto "github.com/onflow/crypto" - mock "github.com/stretchr/testify/mock" -) - -// ThresholdSignatureInspector is an autogenerated mock type for the ThresholdSignatureInspector type -type ThresholdSignatureInspector struct { - mock.Mock -} - -// EnoughShares provides a mock function with no fields -func (_m *ThresholdSignatureInspector) EnoughShares() bool { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for EnoughShares") - } - - var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -// HasShare provides a mock function with given fields: index -func (_m *ThresholdSignatureInspector) HasShare(index int) (bool, error) { - ret := _m.Called(index) - - if len(ret) == 0 { - panic("no return value specified for HasShare") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(int) (bool, error)); ok { - return rf(index) - } - if rf, ok := ret.Get(0).(func(int) bool); ok { - r0 = rf(index) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int) error); ok { - r1 = rf(index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ThresholdSignature provides a mock function with no fields -func (_m *ThresholdSignatureInspector) ThresholdSignature() (crypto.Signature, error) { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for ThresholdSignature") - } - - var r0 crypto.Signature - var r1 error - if rf, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() crypto.Signature); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.Signature) - } - } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// TrustedAdd provides a mock function with given fields: index, share -func (_m *ThresholdSignatureInspector) TrustedAdd(index int, share crypto.Signature) (bool, error) { - ret := _m.Called(index, share) - - if len(ret) == 0 { - panic("no return value specified for TrustedAdd") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { - return rf(index, share) - } - if rf, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { - r0 = rf(index, share) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { - r1 = rf(index, share) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// VerifyAndAdd provides a mock function with given fields: index, share -func (_m *ThresholdSignatureInspector) VerifyAndAdd(index int, share crypto.Signature) (bool, bool, error) { - ret := _m.Called(index, share) - - if len(ret) == 0 { - panic("no return value specified for VerifyAndAdd") - } - - var r0 bool - var r1 bool - var r2 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) (bool, bool, error)); ok { - return rf(index, share) - } - if rf, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { - r0 = rf(index, share) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int, crypto.Signature) bool); ok { - r1 = rf(index, share) - } else { - r1 = ret.Get(1).(bool) - } - - if rf, ok := ret.Get(2).(func(int, crypto.Signature) error); ok { - r2 = rf(index, share) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// VerifyShare provides a mock function with given fields: index, share -func (_m *ThresholdSignatureInspector) VerifyShare(index int, share crypto.Signature) (bool, error) { - ret := _m.Called(index, share) - - if len(ret) == 0 { - panic("no return value specified for VerifyShare") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { - return rf(index, share) - } - if rf, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { - r0 = rf(index, share) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { - r1 = rf(index, share) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// VerifyThresholdSignature provides a mock function with given fields: thresholdSignature -func (_m *ThresholdSignatureInspector) VerifyThresholdSignature(thresholdSignature crypto.Signature) (bool, error) { - ret := _m.Called(thresholdSignature) - - if len(ret) == 0 { - panic("no return value specified for VerifyThresholdSignature") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(crypto.Signature) (bool, error)); ok { - return rf(thresholdSignature) - } - if rf, ok := ret.Get(0).(func(crypto.Signature) bool); ok { - r0 = rf(thresholdSignature) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(crypto.Signature) error); ok { - r1 = rf(thresholdSignature) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewThresholdSignatureInspector creates a new instance of ThresholdSignatureInspector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewThresholdSignatureInspector(t interface { - mock.TestingT - Cleanup(func()) -}) *ThresholdSignatureInspector { - mock := &ThresholdSignatureInspector{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/module/mock/threshold_signature_participant.go b/module/mock/threshold_signature_participant.go deleted file mode 100644 index 0506361e5c0..00000000000 --- a/module/mock/threshold_signature_participant.go +++ /dev/null @@ -1,252 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - crypto "github.com/onflow/crypto" - mock "github.com/stretchr/testify/mock" -) - -// ThresholdSignatureParticipant is an autogenerated mock type for the ThresholdSignatureParticipant type -type ThresholdSignatureParticipant struct { - mock.Mock -} - -// EnoughShares provides a mock function with no fields -func (_m *ThresholdSignatureParticipant) EnoughShares() bool { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for EnoughShares") - } - - var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(bool) - } - - return r0 -} - -// HasShare provides a mock function with given fields: index -func (_m *ThresholdSignatureParticipant) HasShare(index int) (bool, error) { - ret := _m.Called(index) - - if len(ret) == 0 { - panic("no return value specified for HasShare") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(int) (bool, error)); ok { - return rf(index) - } - if rf, ok := ret.Get(0).(func(int) bool); ok { - r0 = rf(index) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int) error); ok { - r1 = rf(index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// SignShare provides a mock function with no fields -func (_m *ThresholdSignatureParticipant) SignShare() (crypto.Signature, error) { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for SignShare") - } - - var r0 crypto.Signature - var r1 error - if rf, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() crypto.Signature); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.Signature) - } - } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ThresholdSignature provides a mock function with no fields -func (_m *ThresholdSignatureParticipant) ThresholdSignature() (crypto.Signature, error) { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for ThresholdSignature") - } - - var r0 crypto.Signature - var r1 error - if rf, ok := ret.Get(0).(func() (crypto.Signature, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() crypto.Signature); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(crypto.Signature) - } - } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// TrustedAdd provides a mock function with given fields: index, share -func (_m *ThresholdSignatureParticipant) TrustedAdd(index int, share crypto.Signature) (bool, error) { - ret := _m.Called(index, share) - - if len(ret) == 0 { - panic("no return value specified for TrustedAdd") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { - return rf(index, share) - } - if rf, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { - r0 = rf(index, share) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { - r1 = rf(index, share) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// VerifyAndAdd provides a mock function with given fields: index, share -func (_m *ThresholdSignatureParticipant) VerifyAndAdd(index int, share crypto.Signature) (bool, bool, error) { - ret := _m.Called(index, share) - - if len(ret) == 0 { - panic("no return value specified for VerifyAndAdd") - } - - var r0 bool - var r1 bool - var r2 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) (bool, bool, error)); ok { - return rf(index, share) - } - if rf, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { - r0 = rf(index, share) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int, crypto.Signature) bool); ok { - r1 = rf(index, share) - } else { - r1 = ret.Get(1).(bool) - } - - if rf, ok := ret.Get(2).(func(int, crypto.Signature) error); ok { - r2 = rf(index, share) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// VerifyShare provides a mock function with given fields: index, share -func (_m *ThresholdSignatureParticipant) VerifyShare(index int, share crypto.Signature) (bool, error) { - ret := _m.Called(index, share) - - if len(ret) == 0 { - panic("no return value specified for VerifyShare") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(int, crypto.Signature) (bool, error)); ok { - return rf(index, share) - } - if rf, ok := ret.Get(0).(func(int, crypto.Signature) bool); ok { - r0 = rf(index, share) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(int, crypto.Signature) error); ok { - r1 = rf(index, share) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// VerifyThresholdSignature provides a mock function with given fields: thresholdSignature -func (_m *ThresholdSignatureParticipant) VerifyThresholdSignature(thresholdSignature crypto.Signature) (bool, error) { - ret := _m.Called(thresholdSignature) - - if len(ret) == 0 { - panic("no return value specified for VerifyThresholdSignature") - } - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(crypto.Signature) (bool, error)); ok { - return rf(thresholdSignature) - } - if rf, ok := ret.Get(0).(func(crypto.Signature) bool); ok { - r0 = rf(thresholdSignature) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(crypto.Signature) error); ok { - r1 = rf(thresholdSignature) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewThresholdSignatureParticipant creates a new instance of ThresholdSignatureParticipant. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewThresholdSignatureParticipant(t interface { - mock.TestingT - Cleanup(func()) -}) *ThresholdSignatureParticipant { - mock := &ThresholdSignatureParticipant{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/module/mock/tracer.go b/module/mock/tracer.go index 28b0c1f160f..9c18efa3a81 100644 --- a/module/mock/tracer.go +++ b/module/mock/tracer.go @@ -1,103 +1,244 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + trace0 "github.com/onflow/flow-go/module/trace" mock "github.com/stretchr/testify/mock" + "go.opentelemetry.io/otel/trace" +) - moduletrace "github.com/onflow/flow-go/module/trace" +// NewTracer creates a new instance of Tracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTracer(t interface { + mock.TestingT + Cleanup(func()) +}) *Tracer { + mock := &Tracer{} + mock.Mock.Test(t) - trace "go.opentelemetry.io/otel/trace" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Tracer is an autogenerated mock type for the Tracer type type Tracer struct { mock.Mock } -// BlockRootSpan provides a mock function with given fields: blockID -func (_m *Tracer) BlockRootSpan(blockID flow.Identifier) trace.Span { - ret := _m.Called(blockID) +type Tracer_Expecter struct { + mock *mock.Mock +} + +func (_m *Tracer) EXPECT() *Tracer_Expecter { + return &Tracer_Expecter{mock: &_m.Mock} +} + +// BlockRootSpan provides a mock function for the type Tracer +func (_mock *Tracer) BlockRootSpan(blockID flow.Identifier) trace.Span { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for BlockRootSpan") } var r0 trace.Span - if rf, ok := ret.Get(0).(func(flow.Identifier) trace.Span); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) trace.Span); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(trace.Span) } } - return r0 } -// Done provides a mock function with no fields -func (_m *Tracer) Done() <-chan struct{} { - ret := _m.Called() +// Tracer_BlockRootSpan_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockRootSpan' +type Tracer_BlockRootSpan_Call struct { + *mock.Call +} + +// BlockRootSpan is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Tracer_Expecter) BlockRootSpan(blockID interface{}) *Tracer_BlockRootSpan_Call { + return &Tracer_BlockRootSpan_Call{Call: _e.mock.On("BlockRootSpan", blockID)} +} + +func (_c *Tracer_BlockRootSpan_Call) Run(run func(blockID flow.Identifier)) *Tracer_BlockRootSpan_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Tracer_BlockRootSpan_Call) Return(span trace.Span) *Tracer_BlockRootSpan_Call { + _c.Call.Return(span) + return _c +} + +func (_c *Tracer_BlockRootSpan_Call) RunAndReturn(run func(blockID flow.Identifier) trace.Span) *Tracer_BlockRootSpan_Call { + _c.Call.Return(run) + return _c +} + +// Done provides a mock function for the type Tracer +func (_mock *Tracer) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *Tracer) Ready() <-chan struct{} { - ret := _m.Called() +// Tracer_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Tracer_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Tracer_Expecter) Done() *Tracer_Done_Call { + return &Tracer_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Tracer_Done_Call) Run(run func()) *Tracer_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Tracer_Done_Call) Return(valCh <-chan struct{}) *Tracer_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Tracer_Done_Call) RunAndReturn(run func() <-chan struct{}) *Tracer_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type Tracer +func (_mock *Tracer) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// ShouldSample provides a mock function with given fields: entityID -func (_m *Tracer) ShouldSample(entityID flow.Identifier) bool { - ret := _m.Called(entityID) +// Tracer_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Tracer_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *Tracer_Expecter) Ready() *Tracer_Ready_Call { + return &Tracer_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *Tracer_Ready_Call) Run(run func()) *Tracer_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Tracer_Ready_Call) Return(valCh <-chan struct{}) *Tracer_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Tracer_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Tracer_Ready_Call { + _c.Call.Return(run) + return _c +} + +// ShouldSample provides a mock function for the type Tracer +func (_mock *Tracer) ShouldSample(entityID flow.Identifier) bool { + ret := _mock.Called(entityID) if len(ret) == 0 { panic("no return value specified for ShouldSample") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(entityID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(entityID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// StartBlockSpan provides a mock function with given fields: ctx, blockID, spanName, opts -func (_m *Tracer) StartBlockSpan(ctx context.Context, blockID flow.Identifier, spanName moduletrace.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { +// Tracer_ShouldSample_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ShouldSample' +type Tracer_ShouldSample_Call struct { + *mock.Call +} + +// ShouldSample is a helper method to define mock.On call +// - entityID flow.Identifier +func (_e *Tracer_Expecter) ShouldSample(entityID interface{}) *Tracer_ShouldSample_Call { + return &Tracer_ShouldSample_Call{Call: _e.mock.On("ShouldSample", entityID)} +} + +func (_c *Tracer_ShouldSample_Call) Run(run func(entityID flow.Identifier)) *Tracer_ShouldSample_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Tracer_ShouldSample_Call) Return(b bool) *Tracer_ShouldSample_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Tracer_ShouldSample_Call) RunAndReturn(run func(entityID flow.Identifier) bool) *Tracer_ShouldSample_Call { + _c.Call.Return(run) + return _c +} + +// StartBlockSpan provides a mock function for the type Tracer +func (_mock *Tracer) StartBlockSpan(ctx context.Context, blockID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { + // trace.SpanStartOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -105,7 +246,7 @@ func (_m *Tracer) StartBlockSpan(ctx context.Context, blockID flow.Identifier, s var _ca []interface{} _ca = append(_ca, ctx, blockID, spanName) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartBlockSpan") @@ -113,30 +254,86 @@ func (_m *Tracer) StartBlockSpan(ctx context.Context, blockID flow.Identifier, s var r0 trace.Span var r1 context.Context - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { - return rf(ctx, blockID, spanName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { + return returnFunc(ctx, blockID, spanName, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) trace.Span); ok { - r0 = rf(ctx, blockID, spanName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) trace.Span); ok { + r0 = returnFunc(ctx, blockID, spanName, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(trace.Span) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) context.Context); ok { - r1 = rf(ctx, blockID, spanName, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) context.Context); ok { + r1 = returnFunc(ctx, blockID, spanName, opts...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(context.Context) } } - return r0, r1 } -// StartCollectionSpan provides a mock function with given fields: ctx, collectionID, spanName, opts -func (_m *Tracer) StartCollectionSpan(ctx context.Context, collectionID flow.Identifier, spanName moduletrace.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { +// Tracer_StartBlockSpan_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartBlockSpan' +type Tracer_StartBlockSpan_Call struct { + *mock.Call +} + +// StartBlockSpan is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +// - spanName trace0.SpanName +// - opts ...trace.SpanStartOption +func (_e *Tracer_Expecter) StartBlockSpan(ctx interface{}, blockID interface{}, spanName interface{}, opts ...interface{}) *Tracer_StartBlockSpan_Call { + return &Tracer_StartBlockSpan_Call{Call: _e.mock.On("StartBlockSpan", + append([]interface{}{ctx, blockID, spanName}, opts...)...)} +} + +func (_c *Tracer_StartBlockSpan_Call) Run(run func(ctx context.Context, blockID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption)) *Tracer_StartBlockSpan_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 trace0.SpanName + if args[2] != nil { + arg2 = args[2].(trace0.SpanName) + } + var arg3 []trace.SpanStartOption + variadicArgs := make([]trace.SpanStartOption, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(trace.SpanStartOption) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *Tracer_StartBlockSpan_Call) Return(span trace.Span, context1 context.Context) *Tracer_StartBlockSpan_Call { + _c.Call.Return(span, context1) + return _c +} + +func (_c *Tracer_StartBlockSpan_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context)) *Tracer_StartBlockSpan_Call { + _c.Call.Return(run) + return _c +} + +// StartCollectionSpan provides a mock function for the type Tracer +func (_mock *Tracer) StartCollectionSpan(ctx context.Context, collectionID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { + // trace.SpanStartOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -144,7 +341,7 @@ func (_m *Tracer) StartCollectionSpan(ctx context.Context, collectionID flow.Ide var _ca []interface{} _ca = append(_ca, ctx, collectionID, spanName) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartCollectionSpan") @@ -152,30 +349,86 @@ func (_m *Tracer) StartCollectionSpan(ctx context.Context, collectionID flow.Ide var r0 trace.Span var r1 context.Context - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { - return rf(ctx, collectionID, spanName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { + return returnFunc(ctx, collectionID, spanName, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) trace.Span); ok { - r0 = rf(ctx, collectionID, spanName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) trace.Span); ok { + r0 = returnFunc(ctx, collectionID, spanName, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(trace.Span) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) context.Context); ok { - r1 = rf(ctx, collectionID, spanName, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) context.Context); ok { + r1 = returnFunc(ctx, collectionID, spanName, opts...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(context.Context) } } - return r0, r1 } -// StartSampledSpanFromParent provides a mock function with given fields: parentSpan, entityID, operationName, opts -func (_m *Tracer) StartSampledSpanFromParent(parentSpan trace.Span, entityID flow.Identifier, operationName moduletrace.SpanName, opts ...trace.SpanStartOption) trace.Span { +// Tracer_StartCollectionSpan_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartCollectionSpan' +type Tracer_StartCollectionSpan_Call struct { + *mock.Call +} + +// StartCollectionSpan is a helper method to define mock.On call +// - ctx context.Context +// - collectionID flow.Identifier +// - spanName trace0.SpanName +// - opts ...trace.SpanStartOption +func (_e *Tracer_Expecter) StartCollectionSpan(ctx interface{}, collectionID interface{}, spanName interface{}, opts ...interface{}) *Tracer_StartCollectionSpan_Call { + return &Tracer_StartCollectionSpan_Call{Call: _e.mock.On("StartCollectionSpan", + append([]interface{}{ctx, collectionID, spanName}, opts...)...)} +} + +func (_c *Tracer_StartCollectionSpan_Call) Run(run func(ctx context.Context, collectionID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption)) *Tracer_StartCollectionSpan_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 trace0.SpanName + if args[2] != nil { + arg2 = args[2].(trace0.SpanName) + } + var arg3 []trace.SpanStartOption + variadicArgs := make([]trace.SpanStartOption, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(trace.SpanStartOption) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *Tracer_StartCollectionSpan_Call) Return(span trace.Span, context1 context.Context) *Tracer_StartCollectionSpan_Call { + _c.Call.Return(span, context1) + return _c +} + +func (_c *Tracer_StartCollectionSpan_Call) RunAndReturn(run func(ctx context.Context, collectionID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context)) *Tracer_StartCollectionSpan_Call { + _c.Call.Return(run) + return _c +} + +// StartSampledSpanFromParent provides a mock function for the type Tracer +func (_mock *Tracer) StartSampledSpanFromParent(parentSpan trace.Span, entityID flow.Identifier, operationName trace0.SpanName, opts ...trace.SpanStartOption) trace.Span { + // trace.SpanStartOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -183,26 +436,83 @@ func (_m *Tracer) StartSampledSpanFromParent(parentSpan trace.Span, entityID flo var _ca []interface{} _ca = append(_ca, parentSpan, entityID, operationName) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartSampledSpanFromParent") } var r0 trace.Span - if rf, ok := ret.Get(0).(func(trace.Span, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) trace.Span); ok { - r0 = rf(parentSpan, entityID, operationName, opts...) + if returnFunc, ok := ret.Get(0).(func(trace.Span, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) trace.Span); ok { + r0 = returnFunc(parentSpan, entityID, operationName, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(trace.Span) } } - return r0 } -// StartSpanFromContext provides a mock function with given fields: ctx, operationName, opts -func (_m *Tracer) StartSpanFromContext(ctx context.Context, operationName moduletrace.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { +// Tracer_StartSampledSpanFromParent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartSampledSpanFromParent' +type Tracer_StartSampledSpanFromParent_Call struct { + *mock.Call +} + +// StartSampledSpanFromParent is a helper method to define mock.On call +// - parentSpan trace.Span +// - entityID flow.Identifier +// - operationName trace0.SpanName +// - opts ...trace.SpanStartOption +func (_e *Tracer_Expecter) StartSampledSpanFromParent(parentSpan interface{}, entityID interface{}, operationName interface{}, opts ...interface{}) *Tracer_StartSampledSpanFromParent_Call { + return &Tracer_StartSampledSpanFromParent_Call{Call: _e.mock.On("StartSampledSpanFromParent", + append([]interface{}{parentSpan, entityID, operationName}, opts...)...)} +} + +func (_c *Tracer_StartSampledSpanFromParent_Call) Run(run func(parentSpan trace.Span, entityID flow.Identifier, operationName trace0.SpanName, opts ...trace.SpanStartOption)) *Tracer_StartSampledSpanFromParent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 trace.Span + if args[0] != nil { + arg0 = args[0].(trace.Span) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 trace0.SpanName + if args[2] != nil { + arg2 = args[2].(trace0.SpanName) + } + var arg3 []trace.SpanStartOption + variadicArgs := make([]trace.SpanStartOption, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(trace.SpanStartOption) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *Tracer_StartSampledSpanFromParent_Call) Return(span trace.Span) *Tracer_StartSampledSpanFromParent_Call { + _c.Call.Return(span) + return _c +} + +func (_c *Tracer_StartSampledSpanFromParent_Call) RunAndReturn(run func(parentSpan trace.Span, entityID flow.Identifier, operationName trace0.SpanName, opts ...trace.SpanStartOption) trace.Span) *Tracer_StartSampledSpanFromParent_Call { + _c.Call.Return(run) + return _c +} + +// StartSpanFromContext provides a mock function for the type Tracer +func (_mock *Tracer) StartSpanFromContext(ctx context.Context, operationName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { + // trace.SpanStartOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -210,7 +520,7 @@ func (_m *Tracer) StartSpanFromContext(ctx context.Context, operationName module var _ca []interface{} _ca = append(_ca, ctx, operationName) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartSpanFromContext") @@ -218,30 +528,80 @@ func (_m *Tracer) StartSpanFromContext(ctx context.Context, operationName module var r0 trace.Span var r1 context.Context - if rf, ok := ret.Get(0).(func(context.Context, moduletrace.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { - return rf(ctx, operationName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, trace0.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { + return returnFunc(ctx, operationName, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, moduletrace.SpanName, ...trace.SpanStartOption) trace.Span); ok { - r0 = rf(ctx, operationName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, trace0.SpanName, ...trace.SpanStartOption) trace.Span); ok { + r0 = returnFunc(ctx, operationName, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(trace.Span) } } - - if rf, ok := ret.Get(1).(func(context.Context, moduletrace.SpanName, ...trace.SpanStartOption) context.Context); ok { - r1 = rf(ctx, operationName, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, trace0.SpanName, ...trace.SpanStartOption) context.Context); ok { + r1 = returnFunc(ctx, operationName, opts...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(context.Context) } } - return r0, r1 } -// StartSpanFromParent provides a mock function with given fields: parentSpan, operationName, opts -func (_m *Tracer) StartSpanFromParent(parentSpan trace.Span, operationName moduletrace.SpanName, opts ...trace.SpanStartOption) trace.Span { +// Tracer_StartSpanFromContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartSpanFromContext' +type Tracer_StartSpanFromContext_Call struct { + *mock.Call +} + +// StartSpanFromContext is a helper method to define mock.On call +// - ctx context.Context +// - operationName trace0.SpanName +// - opts ...trace.SpanStartOption +func (_e *Tracer_Expecter) StartSpanFromContext(ctx interface{}, operationName interface{}, opts ...interface{}) *Tracer_StartSpanFromContext_Call { + return &Tracer_StartSpanFromContext_Call{Call: _e.mock.On("StartSpanFromContext", + append([]interface{}{ctx, operationName}, opts...)...)} +} + +func (_c *Tracer_StartSpanFromContext_Call) Run(run func(ctx context.Context, operationName trace0.SpanName, opts ...trace.SpanStartOption)) *Tracer_StartSpanFromContext_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 trace0.SpanName + if args[1] != nil { + arg1 = args[1].(trace0.SpanName) + } + var arg2 []trace.SpanStartOption + variadicArgs := make([]trace.SpanStartOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(trace.SpanStartOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *Tracer_StartSpanFromContext_Call) Return(span trace.Span, context1 context.Context) *Tracer_StartSpanFromContext_Call { + _c.Call.Return(span, context1) + return _c +} + +func (_c *Tracer_StartSpanFromContext_Call) RunAndReturn(run func(ctx context.Context, operationName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context)) *Tracer_StartSpanFromContext_Call { + _c.Call.Return(run) + return _c +} + +// StartSpanFromParent provides a mock function for the type Tracer +func (_mock *Tracer) StartSpanFromParent(parentSpan trace.Span, operationName trace0.SpanName, opts ...trace.SpanStartOption) trace.Span { + // trace.SpanStartOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -249,26 +609,77 @@ func (_m *Tracer) StartSpanFromParent(parentSpan trace.Span, operationName modul var _ca []interface{} _ca = append(_ca, parentSpan, operationName) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartSpanFromParent") } var r0 trace.Span - if rf, ok := ret.Get(0).(func(trace.Span, moduletrace.SpanName, ...trace.SpanStartOption) trace.Span); ok { - r0 = rf(parentSpan, operationName, opts...) + if returnFunc, ok := ret.Get(0).(func(trace.Span, trace0.SpanName, ...trace.SpanStartOption) trace.Span); ok { + r0 = returnFunc(parentSpan, operationName, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(trace.Span) } } - return r0 } -// StartTransactionSpan provides a mock function with given fields: ctx, transactionID, spanName, opts -func (_m *Tracer) StartTransactionSpan(ctx context.Context, transactionID flow.Identifier, spanName moduletrace.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { +// Tracer_StartSpanFromParent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartSpanFromParent' +type Tracer_StartSpanFromParent_Call struct { + *mock.Call +} + +// StartSpanFromParent is a helper method to define mock.On call +// - parentSpan trace.Span +// - operationName trace0.SpanName +// - opts ...trace.SpanStartOption +func (_e *Tracer_Expecter) StartSpanFromParent(parentSpan interface{}, operationName interface{}, opts ...interface{}) *Tracer_StartSpanFromParent_Call { + return &Tracer_StartSpanFromParent_Call{Call: _e.mock.On("StartSpanFromParent", + append([]interface{}{parentSpan, operationName}, opts...)...)} +} + +func (_c *Tracer_StartSpanFromParent_Call) Run(run func(parentSpan trace.Span, operationName trace0.SpanName, opts ...trace.SpanStartOption)) *Tracer_StartSpanFromParent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 trace.Span + if args[0] != nil { + arg0 = args[0].(trace.Span) + } + var arg1 trace0.SpanName + if args[1] != nil { + arg1 = args[1].(trace0.SpanName) + } + var arg2 []trace.SpanStartOption + variadicArgs := make([]trace.SpanStartOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(trace.SpanStartOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *Tracer_StartSpanFromParent_Call) Return(span trace.Span) *Tracer_StartSpanFromParent_Call { + _c.Call.Return(span) + return _c +} + +func (_c *Tracer_StartSpanFromParent_Call) RunAndReturn(run func(parentSpan trace.Span, operationName trace0.SpanName, opts ...trace.SpanStartOption) trace.Span) *Tracer_StartSpanFromParent_Call { + _c.Call.Return(run) + return _c +} + +// StartTransactionSpan provides a mock function for the type Tracer +func (_mock *Tracer) StartTransactionSpan(ctx context.Context, transactionID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context) { + // trace.SpanStartOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -276,7 +687,7 @@ func (_m *Tracer) StartTransactionSpan(ctx context.Context, transactionID flow.I var _ca []interface{} _ca = append(_ca, ctx, transactionID, spanName) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for StartTransactionSpan") @@ -284,30 +695,86 @@ func (_m *Tracer) StartTransactionSpan(ctx context.Context, transactionID flow.I var r0 trace.Span var r1 context.Context - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { - return rf(ctx, transactionID, spanName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) (trace.Span, context.Context)); ok { + return returnFunc(ctx, transactionID, spanName, opts...) } - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) trace.Span); ok { - r0 = rf(ctx, transactionID, spanName, opts...) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) trace.Span); ok { + r0 = returnFunc(ctx, transactionID, spanName, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(trace.Span) } } - - if rf, ok := ret.Get(1).(func(context.Context, flow.Identifier, moduletrace.SpanName, ...trace.SpanStartOption) context.Context); ok { - r1 = rf(ctx, transactionID, spanName, opts...) + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Identifier, trace0.SpanName, ...trace.SpanStartOption) context.Context); ok { + r1 = returnFunc(ctx, transactionID, spanName, opts...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(context.Context) } } - return r0, r1 } -// WithSpanFromContext provides a mock function with given fields: ctx, operationName, f, opts -func (_m *Tracer) WithSpanFromContext(ctx context.Context, operationName moduletrace.SpanName, f func(), opts ...trace.SpanStartOption) { +// Tracer_StartTransactionSpan_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StartTransactionSpan' +type Tracer_StartTransactionSpan_Call struct { + *mock.Call +} + +// StartTransactionSpan is a helper method to define mock.On call +// - ctx context.Context +// - transactionID flow.Identifier +// - spanName trace0.SpanName +// - opts ...trace.SpanStartOption +func (_e *Tracer_Expecter) StartTransactionSpan(ctx interface{}, transactionID interface{}, spanName interface{}, opts ...interface{}) *Tracer_StartTransactionSpan_Call { + return &Tracer_StartTransactionSpan_Call{Call: _e.mock.On("StartTransactionSpan", + append([]interface{}{ctx, transactionID, spanName}, opts...)...)} +} + +func (_c *Tracer_StartTransactionSpan_Call) Run(run func(ctx context.Context, transactionID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption)) *Tracer_StartTransactionSpan_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 trace0.SpanName + if args[2] != nil { + arg2 = args[2].(trace0.SpanName) + } + var arg3 []trace.SpanStartOption + variadicArgs := make([]trace.SpanStartOption, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(trace.SpanStartOption) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *Tracer_StartTransactionSpan_Call) Return(span trace.Span, context1 context.Context) *Tracer_StartTransactionSpan_Call { + _c.Call.Return(span, context1) + return _c +} + +func (_c *Tracer_StartTransactionSpan_Call) RunAndReturn(run func(ctx context.Context, transactionID flow.Identifier, spanName trace0.SpanName, opts ...trace.SpanStartOption) (trace.Span, context.Context)) *Tracer_StartTransactionSpan_Call { + _c.Call.Return(run) + return _c +} + +// WithSpanFromContext provides a mock function for the type Tracer +func (_mock *Tracer) WithSpanFromContext(ctx context.Context, operationName trace0.SpanName, f func(), opts ...trace.SpanStartOption) { + // trace.SpanStartOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -315,19 +782,63 @@ func (_m *Tracer) WithSpanFromContext(ctx context.Context, operationName modulet var _ca []interface{} _ca = append(_ca, ctx, operationName, f) _ca = append(_ca, _va...) - _m.Called(_ca...) + _mock.Called(_ca...) + return } -// NewTracer creates a new instance of Tracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTracer(t interface { - mock.TestingT - Cleanup(func()) -}) *Tracer { - mock := &Tracer{} - mock.Mock.Test(t) +// Tracer_WithSpanFromContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithSpanFromContext' +type Tracer_WithSpanFromContext_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WithSpanFromContext is a helper method to define mock.On call +// - ctx context.Context +// - operationName trace0.SpanName +// - f func() +// - opts ...trace.SpanStartOption +func (_e *Tracer_Expecter) WithSpanFromContext(ctx interface{}, operationName interface{}, f interface{}, opts ...interface{}) *Tracer_WithSpanFromContext_Call { + return &Tracer_WithSpanFromContext_Call{Call: _e.mock.On("WithSpanFromContext", + append([]interface{}{ctx, operationName, f}, opts...)...)} +} - return mock +func (_c *Tracer_WithSpanFromContext_Call) Run(run func(ctx context.Context, operationName trace0.SpanName, f func(), opts ...trace.SpanStartOption)) *Tracer_WithSpanFromContext_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 trace0.SpanName + if args[1] != nil { + arg1 = args[1].(trace0.SpanName) + } + var arg2 func() + if args[2] != nil { + arg2 = args[2].(func()) + } + var arg3 []trace.SpanStartOption + variadicArgs := make([]trace.SpanStartOption, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(trace.SpanStartOption) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *Tracer_WithSpanFromContext_Call) Return() *Tracer_WithSpanFromContext_Call { + _c.Call.Return() + return _c +} + +func (_c *Tracer_WithSpanFromContext_Call) RunAndReturn(run func(ctx context.Context, operationName trace0.SpanName, f func(), opts ...trace.SpanStartOption)) *Tracer_WithSpanFromContext_Call { + _c.Run(run) + return _c } diff --git a/module/mock/transaction_error_messages_metrics.go b/module/mock/transaction_error_messages_metrics.go index 3a00b189b7b..48cb69e025c 100644 --- a/module/mock/transaction_error_messages_metrics.go +++ b/module/mock/transaction_error_messages_metrics.go @@ -1,48 +1,196 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewTransactionErrorMessagesMetrics creates a new instance of TransactionErrorMessagesMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionErrorMessagesMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionErrorMessagesMetrics { + mock := &TransactionErrorMessagesMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionErrorMessagesMetrics is an autogenerated mock type for the TransactionErrorMessagesMetrics type type TransactionErrorMessagesMetrics struct { mock.Mock } -// TxErrorsFetchFinished provides a mock function with given fields: duration, success, height -func (_m *TransactionErrorMessagesMetrics) TxErrorsFetchFinished(duration time.Duration, success bool, height uint64) { - _m.Called(duration, success, height) +type TransactionErrorMessagesMetrics_Expecter struct { + mock *mock.Mock } -// TxErrorsFetchRetried provides a mock function with no fields -func (_m *TransactionErrorMessagesMetrics) TxErrorsFetchRetried() { - _m.Called() +func (_m *TransactionErrorMessagesMetrics) EXPECT() *TransactionErrorMessagesMetrics_Expecter { + return &TransactionErrorMessagesMetrics_Expecter{mock: &_m.Mock} } -// TxErrorsFetchStarted provides a mock function with no fields -func (_m *TransactionErrorMessagesMetrics) TxErrorsFetchStarted() { - _m.Called() +// TxErrorsFetchFinished provides a mock function for the type TransactionErrorMessagesMetrics +func (_mock *TransactionErrorMessagesMetrics) TxErrorsFetchFinished(duration time.Duration, success bool, height uint64) { + _mock.Called(duration, success, height) + return } -// TxErrorsInitialHeight provides a mock function with given fields: height -func (_m *TransactionErrorMessagesMetrics) TxErrorsInitialHeight(height uint64) { - _m.Called(height) +// TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxErrorsFetchFinished' +type TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call struct { + *mock.Call } -// NewTransactionErrorMessagesMetrics creates a new instance of TransactionErrorMessagesMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionErrorMessagesMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionErrorMessagesMetrics { - mock := &TransactionErrorMessagesMetrics{} - mock.Mock.Test(t) +// TxErrorsFetchFinished is a helper method to define mock.On call +// - duration time.Duration +// - success bool +// - height uint64 +func (_e *TransactionErrorMessagesMetrics_Expecter) TxErrorsFetchFinished(duration interface{}, success interface{}, height interface{}) *TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call { + return &TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call{Call: _e.mock.On("TxErrorsFetchFinished", duration, success, height)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call) Run(run func(duration time.Duration, success bool, height uint64)) *TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} - return mock +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call) Return() *TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call) RunAndReturn(run func(duration time.Duration, success bool, height uint64)) *TransactionErrorMessagesMetrics_TxErrorsFetchFinished_Call { + _c.Run(run) + return _c +} + +// TxErrorsFetchRetried provides a mock function for the type TransactionErrorMessagesMetrics +func (_mock *TransactionErrorMessagesMetrics) TxErrorsFetchRetried() { + _mock.Called() + return +} + +// TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxErrorsFetchRetried' +type TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call struct { + *mock.Call +} + +// TxErrorsFetchRetried is a helper method to define mock.On call +func (_e *TransactionErrorMessagesMetrics_Expecter) TxErrorsFetchRetried() *TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call { + return &TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call{Call: _e.mock.On("TxErrorsFetchRetried")} +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call) Run(run func()) *TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call) Return() *TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call) RunAndReturn(run func()) *TransactionErrorMessagesMetrics_TxErrorsFetchRetried_Call { + _c.Run(run) + return _c +} + +// TxErrorsFetchStarted provides a mock function for the type TransactionErrorMessagesMetrics +func (_mock *TransactionErrorMessagesMetrics) TxErrorsFetchStarted() { + _mock.Called() + return +} + +// TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxErrorsFetchStarted' +type TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call struct { + *mock.Call +} + +// TxErrorsFetchStarted is a helper method to define mock.On call +func (_e *TransactionErrorMessagesMetrics_Expecter) TxErrorsFetchStarted() *TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call { + return &TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call{Call: _e.mock.On("TxErrorsFetchStarted")} +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call) Run(run func()) *TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call) Return() *TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call) RunAndReturn(run func()) *TransactionErrorMessagesMetrics_TxErrorsFetchStarted_Call { + _c.Run(run) + return _c +} + +// TxErrorsInitialHeight provides a mock function for the type TransactionErrorMessagesMetrics +func (_mock *TransactionErrorMessagesMetrics) TxErrorsInitialHeight(height uint64) { + _mock.Called(height) + return +} + +// TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TxErrorsInitialHeight' +type TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call struct { + *mock.Call +} + +// TxErrorsInitialHeight is a helper method to define mock.On call +// - height uint64 +func (_e *TransactionErrorMessagesMetrics_Expecter) TxErrorsInitialHeight(height interface{}) *TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call { + return &TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call{Call: _e.mock.On("TxErrorsInitialHeight", height)} +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call) Run(run func(height uint64)) *TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call) Return() *TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call) RunAndReturn(run func(height uint64)) *TransactionErrorMessagesMetrics_TxErrorsInitialHeight_Call { + _c.Run(run) + return _c } diff --git a/module/mock/transaction_metrics.go b/module/mock/transaction_metrics.go index 9544d83d3e3..f4bc0c93d8a 100644 --- a/module/mock/transaction_metrics.go +++ b/module/mock/transaction_metrics.go @@ -1,64 +1,342 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - mock "github.com/stretchr/testify/mock" + "time" - time "time" + "github.com/onflow/flow-go/model/flow" + mock "github.com/stretchr/testify/mock" ) +// NewTransactionMetrics creates a new instance of TransactionMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionMetrics { + mock := &TransactionMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionMetrics is an autogenerated mock type for the TransactionMetrics type type TransactionMetrics struct { mock.Mock } -// TransactionExecuted provides a mock function with given fields: txID, when -func (_m *TransactionMetrics) TransactionExecuted(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +type TransactionMetrics_Expecter struct { + mock *mock.Mock } -// TransactionExpired provides a mock function with given fields: txID -func (_m *TransactionMetrics) TransactionExpired(txID flow.Identifier) { - _m.Called(txID) +func (_m *TransactionMetrics) EXPECT() *TransactionMetrics_Expecter { + return &TransactionMetrics_Expecter{mock: &_m.Mock} } -// TransactionFinalized provides a mock function with given fields: txID, when -func (_m *TransactionMetrics) TransactionFinalized(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +// TransactionExecuted provides a mock function for the type TransactionMetrics +func (_mock *TransactionMetrics) TransactionExecuted(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return } -// TransactionReceived provides a mock function with given fields: txID, when -func (_m *TransactionMetrics) TransactionReceived(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +// TransactionMetrics_TransactionExecuted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionExecuted' +type TransactionMetrics_TransactionExecuted_Call struct { + *mock.Call } -// TransactionResultFetched provides a mock function with given fields: dur, size -func (_m *TransactionMetrics) TransactionResultFetched(dur time.Duration, size int) { - _m.Called(dur, size) +// TransactionExecuted is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *TransactionMetrics_Expecter) TransactionExecuted(txID interface{}, when interface{}) *TransactionMetrics_TransactionExecuted_Call { + return &TransactionMetrics_TransactionExecuted_Call{Call: _e.mock.On("TransactionExecuted", txID, when)} } -// TransactionSealed provides a mock function with given fields: txID, when -func (_m *TransactionMetrics) TransactionSealed(txID flow.Identifier, when time.Time) { - _m.Called(txID, when) +func (_c *TransactionMetrics_TransactionExecuted_Call) Run(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionExecuted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c } -// TransactionSubmissionFailed provides a mock function with no fields -func (_m *TransactionMetrics) TransactionSubmissionFailed() { - _m.Called() +func (_c *TransactionMetrics_TransactionExecuted_Call) Return() *TransactionMetrics_TransactionExecuted_Call { + _c.Call.Return() + return _c } -// NewTransactionMetrics creates a new instance of TransactionMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionMetrics { - mock := &TransactionMetrics{} - mock.Mock.Test(t) +func (_c *TransactionMetrics_TransactionExecuted_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionExecuted_Call { + _c.Run(run) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TransactionExpired provides a mock function for the type TransactionMetrics +func (_mock *TransactionMetrics) TransactionExpired(txID flow.Identifier) { + _mock.Called(txID) + return +} - return mock +// TransactionMetrics_TransactionExpired_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionExpired' +type TransactionMetrics_TransactionExpired_Call struct { + *mock.Call +} + +// TransactionExpired is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *TransactionMetrics_Expecter) TransactionExpired(txID interface{}) *TransactionMetrics_TransactionExpired_Call { + return &TransactionMetrics_TransactionExpired_Call{Call: _e.mock.On("TransactionExpired", txID)} +} + +func (_c *TransactionMetrics_TransactionExpired_Call) Run(run func(txID flow.Identifier)) *TransactionMetrics_TransactionExpired_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionMetrics_TransactionExpired_Call) Return() *TransactionMetrics_TransactionExpired_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionMetrics_TransactionExpired_Call) RunAndReturn(run func(txID flow.Identifier)) *TransactionMetrics_TransactionExpired_Call { + _c.Run(run) + return _c +} + +// TransactionFinalized provides a mock function for the type TransactionMetrics +func (_mock *TransactionMetrics) TransactionFinalized(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return +} + +// TransactionMetrics_TransactionFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionFinalized' +type TransactionMetrics_TransactionFinalized_Call struct { + *mock.Call +} + +// TransactionFinalized is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *TransactionMetrics_Expecter) TransactionFinalized(txID interface{}, when interface{}) *TransactionMetrics_TransactionFinalized_Call { + return &TransactionMetrics_TransactionFinalized_Call{Call: _e.mock.On("TransactionFinalized", txID, when)} +} + +func (_c *TransactionMetrics_TransactionFinalized_Call) Run(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionMetrics_TransactionFinalized_Call) Return() *TransactionMetrics_TransactionFinalized_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionMetrics_TransactionFinalized_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionFinalized_Call { + _c.Run(run) + return _c +} + +// TransactionReceived provides a mock function for the type TransactionMetrics +func (_mock *TransactionMetrics) TransactionReceived(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return +} + +// TransactionMetrics_TransactionReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionReceived' +type TransactionMetrics_TransactionReceived_Call struct { + *mock.Call +} + +// TransactionReceived is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *TransactionMetrics_Expecter) TransactionReceived(txID interface{}, when interface{}) *TransactionMetrics_TransactionReceived_Call { + return &TransactionMetrics_TransactionReceived_Call{Call: _e.mock.On("TransactionReceived", txID, when)} +} + +func (_c *TransactionMetrics_TransactionReceived_Call) Run(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionMetrics_TransactionReceived_Call) Return() *TransactionMetrics_TransactionReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionMetrics_TransactionReceived_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionReceived_Call { + _c.Run(run) + return _c +} + +// TransactionResultFetched provides a mock function for the type TransactionMetrics +func (_mock *TransactionMetrics) TransactionResultFetched(dur time.Duration, size int) { + _mock.Called(dur, size) + return +} + +// TransactionMetrics_TransactionResultFetched_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionResultFetched' +type TransactionMetrics_TransactionResultFetched_Call struct { + *mock.Call +} + +// TransactionResultFetched is a helper method to define mock.On call +// - dur time.Duration +// - size int +func (_e *TransactionMetrics_Expecter) TransactionResultFetched(dur interface{}, size interface{}) *TransactionMetrics_TransactionResultFetched_Call { + return &TransactionMetrics_TransactionResultFetched_Call{Call: _e.mock.On("TransactionResultFetched", dur, size)} +} + +func (_c *TransactionMetrics_TransactionResultFetched_Call) Run(run func(dur time.Duration, size int)) *TransactionMetrics_TransactionResultFetched_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionMetrics_TransactionResultFetched_Call) Return() *TransactionMetrics_TransactionResultFetched_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionMetrics_TransactionResultFetched_Call) RunAndReturn(run func(dur time.Duration, size int)) *TransactionMetrics_TransactionResultFetched_Call { + _c.Run(run) + return _c +} + +// TransactionSealed provides a mock function for the type TransactionMetrics +func (_mock *TransactionMetrics) TransactionSealed(txID flow.Identifier, when time.Time) { + _mock.Called(txID, when) + return +} + +// TransactionMetrics_TransactionSealed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionSealed' +type TransactionMetrics_TransactionSealed_Call struct { + *mock.Call +} + +// TransactionSealed is a helper method to define mock.On call +// - txID flow.Identifier +// - when time.Time +func (_e *TransactionMetrics_Expecter) TransactionSealed(txID interface{}, when interface{}) *TransactionMetrics_TransactionSealed_Call { + return &TransactionMetrics_TransactionSealed_Call{Call: _e.mock.On("TransactionSealed", txID, when)} +} + +func (_c *TransactionMetrics_TransactionSealed_Call) Run(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionSealed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionMetrics_TransactionSealed_Call) Return() *TransactionMetrics_TransactionSealed_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionMetrics_TransactionSealed_Call) RunAndReturn(run func(txID flow.Identifier, when time.Time)) *TransactionMetrics_TransactionSealed_Call { + _c.Run(run) + return _c +} + +// TransactionSubmissionFailed provides a mock function for the type TransactionMetrics +func (_mock *TransactionMetrics) TransactionSubmissionFailed() { + _mock.Called() + return +} + +// TransactionMetrics_TransactionSubmissionFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionSubmissionFailed' +type TransactionMetrics_TransactionSubmissionFailed_Call struct { + *mock.Call +} + +// TransactionSubmissionFailed is a helper method to define mock.On call +func (_e *TransactionMetrics_Expecter) TransactionSubmissionFailed() *TransactionMetrics_TransactionSubmissionFailed_Call { + return &TransactionMetrics_TransactionSubmissionFailed_Call{Call: _e.mock.On("TransactionSubmissionFailed")} +} + +func (_c *TransactionMetrics_TransactionSubmissionFailed_Call) Run(run func()) *TransactionMetrics_TransactionSubmissionFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionMetrics_TransactionSubmissionFailed_Call) Return() *TransactionMetrics_TransactionSubmissionFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionMetrics_TransactionSubmissionFailed_Call) RunAndReturn(run func()) *TransactionMetrics_TransactionSubmissionFailed_Call { + _c.Run(run) + return _c } diff --git a/module/mock/transaction_validation_metrics.go b/module/mock/transaction_validation_metrics.go index 43600bea3e2..d8a0f3b6ca8 100644 --- a/module/mock/transaction_validation_metrics.go +++ b/module/mock/transaction_validation_metrics.go @@ -1,39 +1,142 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewTransactionValidationMetrics creates a new instance of TransactionValidationMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionValidationMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionValidationMetrics { + mock := &TransactionValidationMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // TransactionValidationMetrics is an autogenerated mock type for the TransactionValidationMetrics type type TransactionValidationMetrics struct { mock.Mock } -// TransactionValidated provides a mock function with no fields -func (_m *TransactionValidationMetrics) TransactionValidated() { - _m.Called() +type TransactionValidationMetrics_Expecter struct { + mock *mock.Mock } -// TransactionValidationFailed provides a mock function with given fields: reason -func (_m *TransactionValidationMetrics) TransactionValidationFailed(reason string) { - _m.Called(reason) +func (_m *TransactionValidationMetrics) EXPECT() *TransactionValidationMetrics_Expecter { + return &TransactionValidationMetrics_Expecter{mock: &_m.Mock} } -// TransactionValidationSkipped provides a mock function with no fields -func (_m *TransactionValidationMetrics) TransactionValidationSkipped() { - _m.Called() +// TransactionValidated provides a mock function for the type TransactionValidationMetrics +func (_mock *TransactionValidationMetrics) TransactionValidated() { + _mock.Called() + return } -// NewTransactionValidationMetrics creates a new instance of TransactionValidationMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionValidationMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionValidationMetrics { - mock := &TransactionValidationMetrics{} - mock.Mock.Test(t) +// TransactionValidationMetrics_TransactionValidated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidated' +type TransactionValidationMetrics_TransactionValidated_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TransactionValidated is a helper method to define mock.On call +func (_e *TransactionValidationMetrics_Expecter) TransactionValidated() *TransactionValidationMetrics_TransactionValidated_Call { + return &TransactionValidationMetrics_TransactionValidated_Call{Call: _e.mock.On("TransactionValidated")} +} - return mock +func (_c *TransactionValidationMetrics_TransactionValidated_Call) Run(run func()) *TransactionValidationMetrics_TransactionValidated_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionValidationMetrics_TransactionValidated_Call) Return() *TransactionValidationMetrics_TransactionValidated_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionValidationMetrics_TransactionValidated_Call) RunAndReturn(run func()) *TransactionValidationMetrics_TransactionValidated_Call { + _c.Run(run) + return _c +} + +// TransactionValidationFailed provides a mock function for the type TransactionValidationMetrics +func (_mock *TransactionValidationMetrics) TransactionValidationFailed(reason string) { + _mock.Called(reason) + return +} + +// TransactionValidationMetrics_TransactionValidationFailed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidationFailed' +type TransactionValidationMetrics_TransactionValidationFailed_Call struct { + *mock.Call +} + +// TransactionValidationFailed is a helper method to define mock.On call +// - reason string +func (_e *TransactionValidationMetrics_Expecter) TransactionValidationFailed(reason interface{}) *TransactionValidationMetrics_TransactionValidationFailed_Call { + return &TransactionValidationMetrics_TransactionValidationFailed_Call{Call: _e.mock.On("TransactionValidationFailed", reason)} +} + +func (_c *TransactionValidationMetrics_TransactionValidationFailed_Call) Run(run func(reason string)) *TransactionValidationMetrics_TransactionValidationFailed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionValidationMetrics_TransactionValidationFailed_Call) Return() *TransactionValidationMetrics_TransactionValidationFailed_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionValidationMetrics_TransactionValidationFailed_Call) RunAndReturn(run func(reason string)) *TransactionValidationMetrics_TransactionValidationFailed_Call { + _c.Run(run) + return _c +} + +// TransactionValidationSkipped provides a mock function for the type TransactionValidationMetrics +func (_mock *TransactionValidationMetrics) TransactionValidationSkipped() { + _mock.Called() + return +} + +// TransactionValidationMetrics_TransactionValidationSkipped_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionValidationSkipped' +type TransactionValidationMetrics_TransactionValidationSkipped_Call struct { + *mock.Call +} + +// TransactionValidationSkipped is a helper method to define mock.On call +func (_e *TransactionValidationMetrics_Expecter) TransactionValidationSkipped() *TransactionValidationMetrics_TransactionValidationSkipped_Call { + return &TransactionValidationMetrics_TransactionValidationSkipped_Call{Call: _e.mock.On("TransactionValidationSkipped")} +} + +func (_c *TransactionValidationMetrics_TransactionValidationSkipped_Call) Run(run func()) *TransactionValidationMetrics_TransactionValidationSkipped_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TransactionValidationMetrics_TransactionValidationSkipped_Call) Return() *TransactionValidationMetrics_TransactionValidationSkipped_Call { + _c.Call.Return() + return _c +} + +func (_c *TransactionValidationMetrics_TransactionValidationSkipped_Call) RunAndReturn(run func()) *TransactionValidationMetrics_TransactionValidationSkipped_Call { + _c.Run(run) + return _c } diff --git a/module/mock/unicast_manager_metrics.go b/module/mock/unicast_manager_metrics.go index d085ab774be..e48bc584496 100644 --- a/module/mock/unicast_manager_metrics.go +++ b/module/mock/unicast_manager_metrics.go @@ -1,78 +1,460 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - mock "github.com/stretchr/testify/mock" + "time" - time "time" + mock "github.com/stretchr/testify/mock" ) +// NewUnicastManagerMetrics creates a new instance of UnicastManagerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewUnicastManagerMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *UnicastManagerMetrics { + mock := &UnicastManagerMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // UnicastManagerMetrics is an autogenerated mock type for the UnicastManagerMetrics type type UnicastManagerMetrics struct { mock.Mock } -// OnDialRetryBudgetResetToDefault provides a mock function with no fields -func (_m *UnicastManagerMetrics) OnDialRetryBudgetResetToDefault() { - _m.Called() +type UnicastManagerMetrics_Expecter struct { + mock *mock.Mock } -// OnDialRetryBudgetUpdated provides a mock function with given fields: budget -func (_m *UnicastManagerMetrics) OnDialRetryBudgetUpdated(budget uint64) { - _m.Called(budget) +func (_m *UnicastManagerMetrics) EXPECT() *UnicastManagerMetrics_Expecter { + return &UnicastManagerMetrics_Expecter{mock: &_m.Mock} } -// OnEstablishStreamFailure provides a mock function with given fields: duration, attempts -func (_m *UnicastManagerMetrics) OnEstablishStreamFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// OnDialRetryBudgetResetToDefault provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnDialRetryBudgetResetToDefault() { + _mock.Called() + return } -// OnPeerDialFailure provides a mock function with given fields: duration, attempts -func (_m *UnicastManagerMetrics) OnPeerDialFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDialRetryBudgetResetToDefault' +type UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call struct { + *mock.Call } -// OnPeerDialed provides a mock function with given fields: duration, attempts -func (_m *UnicastManagerMetrics) OnPeerDialed(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// OnDialRetryBudgetResetToDefault is a helper method to define mock.On call +func (_e *UnicastManagerMetrics_Expecter) OnDialRetryBudgetResetToDefault() *UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call { + return &UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call{Call: _e.mock.On("OnDialRetryBudgetResetToDefault")} } -// OnStreamCreated provides a mock function with given fields: duration, attempts -func (_m *UnicastManagerMetrics) OnStreamCreated(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +func (_c *UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call) Run(run func()) *UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnStreamCreationFailure provides a mock function with given fields: duration, attempts -func (_m *UnicastManagerMetrics) OnStreamCreationFailure(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +func (_c *UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call) Return() *UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Call.Return() + return _c } -// OnStreamCreationRetryBudgetResetToDefault provides a mock function with no fields -func (_m *UnicastManagerMetrics) OnStreamCreationRetryBudgetResetToDefault() { - _m.Called() +func (_c *UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call) RunAndReturn(run func()) *UnicastManagerMetrics_OnDialRetryBudgetResetToDefault_Call { + _c.Run(run) + return _c } -// OnStreamCreationRetryBudgetUpdated provides a mock function with given fields: budget -func (_m *UnicastManagerMetrics) OnStreamCreationRetryBudgetUpdated(budget uint64) { - _m.Called(budget) +// OnDialRetryBudgetUpdated provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnDialRetryBudgetUpdated(budget uint64) { + _mock.Called(budget) + return } -// OnStreamEstablished provides a mock function with given fields: duration, attempts -func (_m *UnicastManagerMetrics) OnStreamEstablished(duration time.Duration, attempts int) { - _m.Called(duration, attempts) +// UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDialRetryBudgetUpdated' +type UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call struct { + *mock.Call } -// NewUnicastManagerMetrics creates a new instance of UnicastManagerMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewUnicastManagerMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *UnicastManagerMetrics { - mock := &UnicastManagerMetrics{} - mock.Mock.Test(t) +// OnDialRetryBudgetUpdated is a helper method to define mock.On call +// - budget uint64 +func (_e *UnicastManagerMetrics_Expecter) OnDialRetryBudgetUpdated(budget interface{}) *UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call { + return &UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call{Call: _e.mock.On("OnDialRetryBudgetUpdated", budget)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call) Run(run func(budget uint64)) *UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call) Return() *UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call) RunAndReturn(run func(budget uint64)) *UnicastManagerMetrics_OnDialRetryBudgetUpdated_Call { + _c.Run(run) + return _c +} + +// OnEstablishStreamFailure provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnEstablishStreamFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// UnicastManagerMetrics_OnEstablishStreamFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnEstablishStreamFailure' +type UnicastManagerMetrics_OnEstablishStreamFailure_Call struct { + *mock.Call +} + +// OnEstablishStreamFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *UnicastManagerMetrics_Expecter) OnEstablishStreamFailure(duration interface{}, attempts interface{}) *UnicastManagerMetrics_OnEstablishStreamFailure_Call { + return &UnicastManagerMetrics_OnEstablishStreamFailure_Call{Call: _e.mock.On("OnEstablishStreamFailure", duration, attempts)} +} + +func (_c *UnicastManagerMetrics_OnEstablishStreamFailure_Call) Run(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnEstablishStreamFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnEstablishStreamFailure_Call) Return() *UnicastManagerMetrics_OnEstablishStreamFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnEstablishStreamFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnEstablishStreamFailure_Call { + _c.Run(run) + return _c +} + +// OnPeerDialFailure provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnPeerDialFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// UnicastManagerMetrics_OnPeerDialFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerDialFailure' +type UnicastManagerMetrics_OnPeerDialFailure_Call struct { + *mock.Call +} + +// OnPeerDialFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *UnicastManagerMetrics_Expecter) OnPeerDialFailure(duration interface{}, attempts interface{}) *UnicastManagerMetrics_OnPeerDialFailure_Call { + return &UnicastManagerMetrics_OnPeerDialFailure_Call{Call: _e.mock.On("OnPeerDialFailure", duration, attempts)} +} + +func (_c *UnicastManagerMetrics_OnPeerDialFailure_Call) Run(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnPeerDialFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnPeerDialFailure_Call) Return() *UnicastManagerMetrics_OnPeerDialFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnPeerDialFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnPeerDialFailure_Call { + _c.Run(run) + return _c +} + +// OnPeerDialed provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnPeerDialed(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// UnicastManagerMetrics_OnPeerDialed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnPeerDialed' +type UnicastManagerMetrics_OnPeerDialed_Call struct { + *mock.Call +} + +// OnPeerDialed is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *UnicastManagerMetrics_Expecter) OnPeerDialed(duration interface{}, attempts interface{}) *UnicastManagerMetrics_OnPeerDialed_Call { + return &UnicastManagerMetrics_OnPeerDialed_Call{Call: _e.mock.On("OnPeerDialed", duration, attempts)} +} + +func (_c *UnicastManagerMetrics_OnPeerDialed_Call) Run(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnPeerDialed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnPeerDialed_Call) Return() *UnicastManagerMetrics_OnPeerDialed_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnPeerDialed_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnPeerDialed_Call { + _c.Run(run) + return _c +} + +// OnStreamCreated provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnStreamCreated(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// UnicastManagerMetrics_OnStreamCreated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreated' +type UnicastManagerMetrics_OnStreamCreated_Call struct { + *mock.Call +} + +// OnStreamCreated is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *UnicastManagerMetrics_Expecter) OnStreamCreated(duration interface{}, attempts interface{}) *UnicastManagerMetrics_OnStreamCreated_Call { + return &UnicastManagerMetrics_OnStreamCreated_Call{Call: _e.mock.On("OnStreamCreated", duration, attempts)} +} + +func (_c *UnicastManagerMetrics_OnStreamCreated_Call) Run(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnStreamCreated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreated_Call) Return() *UnicastManagerMetrics_OnStreamCreated_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreated_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnStreamCreated_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationFailure provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnStreamCreationFailure(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// UnicastManagerMetrics_OnStreamCreationFailure_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationFailure' +type UnicastManagerMetrics_OnStreamCreationFailure_Call struct { + *mock.Call +} + +// OnStreamCreationFailure is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *UnicastManagerMetrics_Expecter) OnStreamCreationFailure(duration interface{}, attempts interface{}) *UnicastManagerMetrics_OnStreamCreationFailure_Call { + return &UnicastManagerMetrics_OnStreamCreationFailure_Call{Call: _e.mock.On("OnStreamCreationFailure", duration, attempts)} +} + +func (_c *UnicastManagerMetrics_OnStreamCreationFailure_Call) Run(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnStreamCreationFailure_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreationFailure_Call) Return() *UnicastManagerMetrics_OnStreamCreationFailure_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreationFailure_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnStreamCreationFailure_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationRetryBudgetResetToDefault provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnStreamCreationRetryBudgetResetToDefault() { + _mock.Called() + return +} + +// UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationRetryBudgetResetToDefault' +type UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call struct { + *mock.Call +} + +// OnStreamCreationRetryBudgetResetToDefault is a helper method to define mock.On call +func (_e *UnicastManagerMetrics_Expecter) OnStreamCreationRetryBudgetResetToDefault() *UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + return &UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call{Call: _e.mock.On("OnStreamCreationRetryBudgetResetToDefault")} +} + +func (_c *UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) Run(run func()) *UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) Return() *UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call) RunAndReturn(run func()) *UnicastManagerMetrics_OnStreamCreationRetryBudgetResetToDefault_Call { + _c.Run(run) + return _c +} + +// OnStreamCreationRetryBudgetUpdated provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnStreamCreationRetryBudgetUpdated(budget uint64) { + _mock.Called(budget) + return +} + +// UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamCreationRetryBudgetUpdated' +type UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call struct { + *mock.Call +} + +// OnStreamCreationRetryBudgetUpdated is a helper method to define mock.On call +// - budget uint64 +func (_e *UnicastManagerMetrics_Expecter) OnStreamCreationRetryBudgetUpdated(budget interface{}) *UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call { + return &UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call{Call: _e.mock.On("OnStreamCreationRetryBudgetUpdated", budget)} +} + +func (_c *UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call) Run(run func(budget uint64)) *UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call) Return() *UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call) RunAndReturn(run func(budget uint64)) *UnicastManagerMetrics_OnStreamCreationRetryBudgetUpdated_Call { + _c.Run(run) + return _c +} + +// OnStreamEstablished provides a mock function for the type UnicastManagerMetrics +func (_mock *UnicastManagerMetrics) OnStreamEstablished(duration time.Duration, attempts int) { + _mock.Called(duration, attempts) + return +} + +// UnicastManagerMetrics_OnStreamEstablished_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnStreamEstablished' +type UnicastManagerMetrics_OnStreamEstablished_Call struct { + *mock.Call +} + +// OnStreamEstablished is a helper method to define mock.On call +// - duration time.Duration +// - attempts int +func (_e *UnicastManagerMetrics_Expecter) OnStreamEstablished(duration interface{}, attempts interface{}) *UnicastManagerMetrics_OnStreamEstablished_Call { + return &UnicastManagerMetrics_OnStreamEstablished_Call{Call: _e.mock.On("OnStreamEstablished", duration, attempts)} +} + +func (_c *UnicastManagerMetrics_OnStreamEstablished_Call) Run(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnStreamEstablished_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 time.Duration + if args[0] != nil { + arg0 = args[0].(time.Duration) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamEstablished_Call) Return() *UnicastManagerMetrics_OnStreamEstablished_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManagerMetrics_OnStreamEstablished_Call) RunAndReturn(run func(duration time.Duration, attempts int)) *UnicastManagerMetrics_OnStreamEstablished_Call { + _c.Run(run) + return _c } diff --git a/module/mock/verification_metrics.go b/module/mock/verification_metrics.go index 81a92ab6f6d..5850b3fa4c9 100644 --- a/module/mock/verification_metrics.go +++ b/module/mock/verification_metrics.go @@ -1,109 +1,632 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewVerificationMetrics creates a new instance of VerificationMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVerificationMetrics(t interface { + mock.TestingT + Cleanup(func()) +}) *VerificationMetrics { + mock := &VerificationMetrics{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // VerificationMetrics is an autogenerated mock type for the VerificationMetrics type type VerificationMetrics struct { mock.Mock } -// OnAssignedChunkProcessedAtAssigner provides a mock function with no fields -func (_m *VerificationMetrics) OnAssignedChunkProcessedAtAssigner() { - _m.Called() +type VerificationMetrics_Expecter struct { + mock *mock.Mock } -// OnAssignedChunkReceivedAtFetcher provides a mock function with no fields -func (_m *VerificationMetrics) OnAssignedChunkReceivedAtFetcher() { - _m.Called() +func (_m *VerificationMetrics) EXPECT() *VerificationMetrics_Expecter { + return &VerificationMetrics_Expecter{mock: &_m.Mock} } -// OnBlockConsumerJobDone provides a mock function with given fields: _a0 -func (_m *VerificationMetrics) OnBlockConsumerJobDone(_a0 uint64) { - _m.Called(_a0) +// OnAssignedChunkProcessedAtAssigner provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnAssignedChunkProcessedAtAssigner() { + _mock.Called() + return } -// OnChunkConsumerJobDone provides a mock function with given fields: _a0 -func (_m *VerificationMetrics) OnChunkConsumerJobDone(_a0 uint64) { - _m.Called(_a0) +// VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAssignedChunkProcessedAtAssigner' +type VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call struct { + *mock.Call } -// OnChunkDataPackArrivedAtFetcher provides a mock function with no fields -func (_m *VerificationMetrics) OnChunkDataPackArrivedAtFetcher() { - _m.Called() +// OnAssignedChunkProcessedAtAssigner is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnAssignedChunkProcessedAtAssigner() *VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call { + return &VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call{Call: _e.mock.On("OnAssignedChunkProcessedAtAssigner")} } -// OnChunkDataPackRequestDispatchedInNetworkByRequester provides a mock function with no fields -func (_m *VerificationMetrics) OnChunkDataPackRequestDispatchedInNetworkByRequester() { - _m.Called() +func (_c *VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call) Run(run func()) *VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnChunkDataPackRequestReceivedByRequester provides a mock function with no fields -func (_m *VerificationMetrics) OnChunkDataPackRequestReceivedByRequester() { - _m.Called() +func (_c *VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call) Return() *VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call { + _c.Call.Return() + return _c } -// OnChunkDataPackRequestSentByFetcher provides a mock function with no fields -func (_m *VerificationMetrics) OnChunkDataPackRequestSentByFetcher() { - _m.Called() +func (_c *VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call) RunAndReturn(run func()) *VerificationMetrics_OnAssignedChunkProcessedAtAssigner_Call { + _c.Run(run) + return _c } -// OnChunkDataPackResponseReceivedFromNetworkByRequester provides a mock function with no fields -func (_m *VerificationMetrics) OnChunkDataPackResponseReceivedFromNetworkByRequester() { - _m.Called() +// OnAssignedChunkReceivedAtFetcher provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnAssignedChunkReceivedAtFetcher() { + _mock.Called() + return } -// OnChunkDataPackSentToFetcher provides a mock function with no fields -func (_m *VerificationMetrics) OnChunkDataPackSentToFetcher() { - _m.Called() +// VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAssignedChunkReceivedAtFetcher' +type VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call struct { + *mock.Call } -// OnChunksAssignmentDoneAtAssigner provides a mock function with given fields: chunks -func (_m *VerificationMetrics) OnChunksAssignmentDoneAtAssigner(chunks int) { - _m.Called(chunks) +// OnAssignedChunkReceivedAtFetcher is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnAssignedChunkReceivedAtFetcher() *VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call { + return &VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call{Call: _e.mock.On("OnAssignedChunkReceivedAtFetcher")} } -// OnExecutionResultReceivedAtAssignerEngine provides a mock function with no fields -func (_m *VerificationMetrics) OnExecutionResultReceivedAtAssignerEngine() { - _m.Called() +func (_c *VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call) Run(run func()) *VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// OnFinalizedBlockArrivedAtAssigner provides a mock function with given fields: height -func (_m *VerificationMetrics) OnFinalizedBlockArrivedAtAssigner(height uint64) { - _m.Called(height) +func (_c *VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call) Return() *VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call { + _c.Call.Return() + return _c } -// OnResultApprovalDispatchedInNetworkByVerifier provides a mock function with no fields -func (_m *VerificationMetrics) OnResultApprovalDispatchedInNetworkByVerifier() { - _m.Called() +func (_c *VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call) RunAndReturn(run func()) *VerificationMetrics_OnAssignedChunkReceivedAtFetcher_Call { + _c.Run(run) + return _c } -// OnVerifiableChunkReceivedAtVerifierEngine provides a mock function with no fields -func (_m *VerificationMetrics) OnVerifiableChunkReceivedAtVerifierEngine() { - _m.Called() +// OnBlockConsumerJobDone provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnBlockConsumerJobDone(v uint64) { + _mock.Called(v) + return } -// OnVerifiableChunkSentToVerifier provides a mock function with no fields -func (_m *VerificationMetrics) OnVerifiableChunkSentToVerifier() { - _m.Called() +// VerificationMetrics_OnBlockConsumerJobDone_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnBlockConsumerJobDone' +type VerificationMetrics_OnBlockConsumerJobDone_Call struct { + *mock.Call } -// SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester provides a mock function with given fields: attempts -func (_m *VerificationMetrics) SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester(attempts uint64) { - _m.Called(attempts) +// OnBlockConsumerJobDone is a helper method to define mock.On call +// - v uint64 +func (_e *VerificationMetrics_Expecter) OnBlockConsumerJobDone(v interface{}) *VerificationMetrics_OnBlockConsumerJobDone_Call { + return &VerificationMetrics_OnBlockConsumerJobDone_Call{Call: _e.mock.On("OnBlockConsumerJobDone", v)} } -// NewVerificationMetrics creates a new instance of VerificationMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVerificationMetrics(t interface { - mock.TestingT - Cleanup(func()) -}) *VerificationMetrics { - mock := &VerificationMetrics{} - mock.Mock.Test(t) +func (_c *VerificationMetrics_OnBlockConsumerJobDone_Call) Run(run func(v uint64)) *VerificationMetrics_OnBlockConsumerJobDone_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *VerificationMetrics_OnBlockConsumerJobDone_Call) Return() *VerificationMetrics_OnBlockConsumerJobDone_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *VerificationMetrics_OnBlockConsumerJobDone_Call) RunAndReturn(run func(v uint64)) *VerificationMetrics_OnBlockConsumerJobDone_Call { + _c.Run(run) + return _c +} + +// OnChunkConsumerJobDone provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunkConsumerJobDone(v uint64) { + _mock.Called(v) + return +} + +// VerificationMetrics_OnChunkConsumerJobDone_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunkConsumerJobDone' +type VerificationMetrics_OnChunkConsumerJobDone_Call struct { + *mock.Call +} + +// OnChunkConsumerJobDone is a helper method to define mock.On call +// - v uint64 +func (_e *VerificationMetrics_Expecter) OnChunkConsumerJobDone(v interface{}) *VerificationMetrics_OnChunkConsumerJobDone_Call { + return &VerificationMetrics_OnChunkConsumerJobDone_Call{Call: _e.mock.On("OnChunkConsumerJobDone", v)} +} + +func (_c *VerificationMetrics_OnChunkConsumerJobDone_Call) Run(run func(v uint64)) *VerificationMetrics_OnChunkConsumerJobDone_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VerificationMetrics_OnChunkConsumerJobDone_Call) Return() *VerificationMetrics_OnChunkConsumerJobDone_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunkConsumerJobDone_Call) RunAndReturn(run func(v uint64)) *VerificationMetrics_OnChunkConsumerJobDone_Call { + _c.Run(run) + return _c +} + +// OnChunkDataPackArrivedAtFetcher provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunkDataPackArrivedAtFetcher() { + _mock.Called() + return +} + +// VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunkDataPackArrivedAtFetcher' +type VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call struct { + *mock.Call +} + +// OnChunkDataPackArrivedAtFetcher is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnChunkDataPackArrivedAtFetcher() *VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call { + return &VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call{Call: _e.mock.On("OnChunkDataPackArrivedAtFetcher")} +} + +func (_c *VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call) Run(run func()) *VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call) Return() *VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call) RunAndReturn(run func()) *VerificationMetrics_OnChunkDataPackArrivedAtFetcher_Call { + _c.Run(run) + return _c +} + +// OnChunkDataPackRequestDispatchedInNetworkByRequester provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunkDataPackRequestDispatchedInNetworkByRequester() { + _mock.Called() + return +} + +// VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunkDataPackRequestDispatchedInNetworkByRequester' +type VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call struct { + *mock.Call +} + +// OnChunkDataPackRequestDispatchedInNetworkByRequester is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnChunkDataPackRequestDispatchedInNetworkByRequester() *VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call { + return &VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call{Call: _e.mock.On("OnChunkDataPackRequestDispatchedInNetworkByRequester")} +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call) Run(run func()) *VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call) Return() *VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call) RunAndReturn(run func()) *VerificationMetrics_OnChunkDataPackRequestDispatchedInNetworkByRequester_Call { + _c.Run(run) + return _c +} + +// OnChunkDataPackRequestReceivedByRequester provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunkDataPackRequestReceivedByRequester() { + _mock.Called() + return +} + +// VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunkDataPackRequestReceivedByRequester' +type VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call struct { + *mock.Call +} + +// OnChunkDataPackRequestReceivedByRequester is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnChunkDataPackRequestReceivedByRequester() *VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call { + return &VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call{Call: _e.mock.On("OnChunkDataPackRequestReceivedByRequester")} +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call) Run(run func()) *VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call) Return() *VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call) RunAndReturn(run func()) *VerificationMetrics_OnChunkDataPackRequestReceivedByRequester_Call { + _c.Run(run) + return _c +} + +// OnChunkDataPackRequestSentByFetcher provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunkDataPackRequestSentByFetcher() { + _mock.Called() + return +} + +// VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunkDataPackRequestSentByFetcher' +type VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call struct { + *mock.Call +} + +// OnChunkDataPackRequestSentByFetcher is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnChunkDataPackRequestSentByFetcher() *VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call { + return &VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call{Call: _e.mock.On("OnChunkDataPackRequestSentByFetcher")} +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call) Run(run func()) *VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call) Return() *VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call) RunAndReturn(run func()) *VerificationMetrics_OnChunkDataPackRequestSentByFetcher_Call { + _c.Run(run) + return _c +} + +// OnChunkDataPackResponseReceivedFromNetworkByRequester provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunkDataPackResponseReceivedFromNetworkByRequester() { + _mock.Called() + return +} + +// VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunkDataPackResponseReceivedFromNetworkByRequester' +type VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call struct { + *mock.Call +} + +// OnChunkDataPackResponseReceivedFromNetworkByRequester is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnChunkDataPackResponseReceivedFromNetworkByRequester() *VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call { + return &VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call{Call: _e.mock.On("OnChunkDataPackResponseReceivedFromNetworkByRequester")} +} + +func (_c *VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call) Run(run func()) *VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call) Return() *VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call) RunAndReturn(run func()) *VerificationMetrics_OnChunkDataPackResponseReceivedFromNetworkByRequester_Call { + _c.Run(run) + return _c +} + +// OnChunkDataPackSentToFetcher provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunkDataPackSentToFetcher() { + _mock.Called() + return +} + +// VerificationMetrics_OnChunkDataPackSentToFetcher_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunkDataPackSentToFetcher' +type VerificationMetrics_OnChunkDataPackSentToFetcher_Call struct { + *mock.Call +} + +// OnChunkDataPackSentToFetcher is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnChunkDataPackSentToFetcher() *VerificationMetrics_OnChunkDataPackSentToFetcher_Call { + return &VerificationMetrics_OnChunkDataPackSentToFetcher_Call{Call: _e.mock.On("OnChunkDataPackSentToFetcher")} +} + +func (_c *VerificationMetrics_OnChunkDataPackSentToFetcher_Call) Run(run func()) *VerificationMetrics_OnChunkDataPackSentToFetcher_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackSentToFetcher_Call) Return() *VerificationMetrics_OnChunkDataPackSentToFetcher_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunkDataPackSentToFetcher_Call) RunAndReturn(run func()) *VerificationMetrics_OnChunkDataPackSentToFetcher_Call { + _c.Run(run) + return _c +} + +// OnChunksAssignmentDoneAtAssigner provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnChunksAssignmentDoneAtAssigner(chunks int) { + _mock.Called(chunks) + return +} + +// VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnChunksAssignmentDoneAtAssigner' +type VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call struct { + *mock.Call +} + +// OnChunksAssignmentDoneAtAssigner is a helper method to define mock.On call +// - chunks int +func (_e *VerificationMetrics_Expecter) OnChunksAssignmentDoneAtAssigner(chunks interface{}) *VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call { + return &VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call{Call: _e.mock.On("OnChunksAssignmentDoneAtAssigner", chunks)} +} + +func (_c *VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call) Run(run func(chunks int)) *VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call) Return() *VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call) RunAndReturn(run func(chunks int)) *VerificationMetrics_OnChunksAssignmentDoneAtAssigner_Call { + _c.Run(run) + return _c +} + +// OnExecutionResultReceivedAtAssignerEngine provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnExecutionResultReceivedAtAssignerEngine() { + _mock.Called() + return +} + +// VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnExecutionResultReceivedAtAssignerEngine' +type VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call struct { + *mock.Call +} + +// OnExecutionResultReceivedAtAssignerEngine is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnExecutionResultReceivedAtAssignerEngine() *VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call { + return &VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call{Call: _e.mock.On("OnExecutionResultReceivedAtAssignerEngine")} +} + +func (_c *VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call) Run(run func()) *VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call) Return() *VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call) RunAndReturn(run func()) *VerificationMetrics_OnExecutionResultReceivedAtAssignerEngine_Call { + _c.Run(run) + return _c +} + +// OnFinalizedBlockArrivedAtAssigner provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnFinalizedBlockArrivedAtAssigner(height uint64) { + _mock.Called(height) + return +} + +// VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnFinalizedBlockArrivedAtAssigner' +type VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call struct { + *mock.Call +} + +// OnFinalizedBlockArrivedAtAssigner is a helper method to define mock.On call +// - height uint64 +func (_e *VerificationMetrics_Expecter) OnFinalizedBlockArrivedAtAssigner(height interface{}) *VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call { + return &VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call{Call: _e.mock.On("OnFinalizedBlockArrivedAtAssigner", height)} +} + +func (_c *VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call) Run(run func(height uint64)) *VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call) Return() *VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call) RunAndReturn(run func(height uint64)) *VerificationMetrics_OnFinalizedBlockArrivedAtAssigner_Call { + _c.Run(run) + return _c +} + +// OnResultApprovalDispatchedInNetworkByVerifier provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnResultApprovalDispatchedInNetworkByVerifier() { + _mock.Called() + return +} + +// VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnResultApprovalDispatchedInNetworkByVerifier' +type VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call struct { + *mock.Call +} + +// OnResultApprovalDispatchedInNetworkByVerifier is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnResultApprovalDispatchedInNetworkByVerifier() *VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call { + return &VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call{Call: _e.mock.On("OnResultApprovalDispatchedInNetworkByVerifier")} +} + +func (_c *VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call) Run(run func()) *VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call) Return() *VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call) RunAndReturn(run func()) *VerificationMetrics_OnResultApprovalDispatchedInNetworkByVerifier_Call { + _c.Run(run) + return _c +} + +// OnVerifiableChunkReceivedAtVerifierEngine provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnVerifiableChunkReceivedAtVerifierEngine() { + _mock.Called() + return +} + +// VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnVerifiableChunkReceivedAtVerifierEngine' +type VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call struct { + *mock.Call +} + +// OnVerifiableChunkReceivedAtVerifierEngine is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnVerifiableChunkReceivedAtVerifierEngine() *VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call { + return &VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call{Call: _e.mock.On("OnVerifiableChunkReceivedAtVerifierEngine")} +} + +func (_c *VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call) Run(run func()) *VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call) Return() *VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call) RunAndReturn(run func()) *VerificationMetrics_OnVerifiableChunkReceivedAtVerifierEngine_Call { + _c.Run(run) + return _c +} + +// OnVerifiableChunkSentToVerifier provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) OnVerifiableChunkSentToVerifier() { + _mock.Called() + return +} + +// VerificationMetrics_OnVerifiableChunkSentToVerifier_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnVerifiableChunkSentToVerifier' +type VerificationMetrics_OnVerifiableChunkSentToVerifier_Call struct { + *mock.Call +} + +// OnVerifiableChunkSentToVerifier is a helper method to define mock.On call +func (_e *VerificationMetrics_Expecter) OnVerifiableChunkSentToVerifier() *VerificationMetrics_OnVerifiableChunkSentToVerifier_Call { + return &VerificationMetrics_OnVerifiableChunkSentToVerifier_Call{Call: _e.mock.On("OnVerifiableChunkSentToVerifier")} +} + +func (_c *VerificationMetrics_OnVerifiableChunkSentToVerifier_Call) Run(run func()) *VerificationMetrics_OnVerifiableChunkSentToVerifier_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VerificationMetrics_OnVerifiableChunkSentToVerifier_Call) Return() *VerificationMetrics_OnVerifiableChunkSentToVerifier_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_OnVerifiableChunkSentToVerifier_Call) RunAndReturn(run func()) *VerificationMetrics_OnVerifiableChunkSentToVerifier_Call { + _c.Run(run) + return _c +} + +// SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester provides a mock function for the type VerificationMetrics +func (_mock *VerificationMetrics) SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester(attempts uint64) { + _mock.Called(attempts) + return +} + +// VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester' +type VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call struct { + *mock.Call +} + +// SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester is a helper method to define mock.On call +// - attempts uint64 +func (_e *VerificationMetrics_Expecter) SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester(attempts interface{}) *VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call { + return &VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call{Call: _e.mock.On("SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester", attempts)} +} + +func (_c *VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call) Run(run func(attempts uint64)) *VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call) Return() *VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call { + _c.Call.Return() + return _c +} + +func (_c *VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call) RunAndReturn(run func(attempts uint64)) *VerificationMetrics_SetMaxChunkDataPackAttemptsForNextUnsealedHeightAtRequester_Call { + _c.Run(run) + return _c } diff --git a/module/mock/wal_metrics.go b/module/mock/wal_metrics.go index 6ff334241c5..dc3966ff08c 100644 --- a/module/mock/wal_metrics.go +++ b/module/mock/wal_metrics.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// WALMetrics is an autogenerated mock type for the WALMetrics type -type WALMetrics struct { - mock.Mock -} - -// ExecutionCheckpointSize provides a mock function with given fields: bytes -func (_m *WALMetrics) ExecutionCheckpointSize(bytes uint64) { - _m.Called(bytes) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewWALMetrics creates a new instance of WALMetrics. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,56 @@ func NewWALMetrics(t interface { return mock } + +// WALMetrics is an autogenerated mock type for the WALMetrics type +type WALMetrics struct { + mock.Mock +} + +type WALMetrics_Expecter struct { + mock *mock.Mock +} + +func (_m *WALMetrics) EXPECT() *WALMetrics_Expecter { + return &WALMetrics_Expecter{mock: &_m.Mock} +} + +// ExecutionCheckpointSize provides a mock function for the type WALMetrics +func (_mock *WALMetrics) ExecutionCheckpointSize(bytes uint64) { + _mock.Called(bytes) + return +} + +// WALMetrics_ExecutionCheckpointSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecutionCheckpointSize' +type WALMetrics_ExecutionCheckpointSize_Call struct { + *mock.Call +} + +// ExecutionCheckpointSize is a helper method to define mock.On call +// - bytes uint64 +func (_e *WALMetrics_Expecter) ExecutionCheckpointSize(bytes interface{}) *WALMetrics_ExecutionCheckpointSize_Call { + return &WALMetrics_ExecutionCheckpointSize_Call{Call: _e.mock.On("ExecutionCheckpointSize", bytes)} +} + +func (_c *WALMetrics_ExecutionCheckpointSize_Call) Run(run func(bytes uint64)) *WALMetrics_ExecutionCheckpointSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *WALMetrics_ExecutionCheckpointSize_Call) Return() *WALMetrics_ExecutionCheckpointSize_Call { + _c.Call.Return() + return _c +} + +func (_c *WALMetrics_ExecutionCheckpointSize_Call) RunAndReturn(run func(bytes uint64)) *WALMetrics_ExecutionCheckpointSize_Call { + _c.Run(run) + return _c +} diff --git a/module/observable/observer.go b/module/observable/observer.go index 2b53363552d..9a4b55ba364 100644 --- a/module/observable/observer.go +++ b/module/observable/observer.go @@ -2,7 +2,7 @@ package observable type Observer interface { // conveys an item that is emitted by the Observable to the observer - OnNext(interface{}) + OnNext(any) // indicates that the Observable has terminated with a specified error condition and that it will be emitting no further items OnError(err error) // indicates that the Observable has completed successfully and that it will be emitting no further items diff --git a/module/requester.go b/module/requester.go index 93b3f8a66f2..18fec24783a 100644 --- a/module/requester.go +++ b/module/requester.go @@ -4,22 +4,27 @@ import ( "github.com/onflow/flow-go/model/flow" ) +// Requester provides an interface to request entities from other nodes in the network. +// When the Requester is instructed to retrieve some entity, the Requester handles sending request messages and retrying requests. +// Requested entities are passed to a Handler function, which is configured elsewhere (see [module/requester.Engine.WithHandle]). type Requester interface { - // EntityByID will request an entity through the request engine backing - // the interface. The additional selector will be applied to the subset - // of valid providers for the entity and allows finer-grained control - // over which providers to request a given entity from. Use `filter.Any` - // if no additional restrictions are required. Data integrity of response - // will be checked upon arrival. This function should be used for requesting - // entites by their IDs. + // EntityByID will enqueue the given entity for request by its ID (content hash). + // The selector will be applied to the subset of valid providers configured globally for the Requester instance. + // This allows finer-grained control over which providers to request from on a per-entity basis. + // Use `filter.Any` if no additional restrictions are required. + // Received entities will be verified for integrity using their ID function. + // Idempotent w.r.t. `queryKey` (if prior request is still ongoing, we just continue trying). + // Concurrency safe. EntityByID(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity]) - // Query will request data through the request engine backing the interface. - // The additional selector will be applied to the subset - // of valid providers for the data and allows finer-grained control - // over which providers to request data from. Doesn't perform integrity check - // can be used to get entities without knowing their ID. - Query(key flow.Identifier, selector flow.IdentityFilter[flow.Identity]) + // EntityBySecondaryKey will enqueue the given entity for request by some secondary identifier (NOT its content hash). + // The selector will be applied to the subset of valid providers configured globally for the Requester instance. + // This allows finer-grained control over which providers to request from on a per-entity basis. + // Use `filter.Any` if no additional restrictions are required. + // CAUTION: NOT BFT, because received entities WILL NOT be verified for integrity using their ID function. + // Idempotent w.r.t. `queryKey` (if prior request is still ongoing, we just continue trying). + // Concurrency safe. + EntityBySecondaryKey(queryKey flow.Identifier, selector flow.IdentityFilter[flow.Identity]) // Force will force the dispatcher to send all possible batches immediately. // It can be used in cases where responsiveness is of utmost importance, at @@ -32,7 +37,8 @@ type NoopRequester struct{} func (n NoopRequester) EntityByID(entityID flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { } -func (n NoopRequester) Query(key flow.Identifier, selector flow.IdentityFilter[flow.Identity]) {} +func (n NoopRequester) EntityBySecondaryKey(key flow.Identifier, selector flow.IdentityFilter[flow.Identity]) { +} func (n NoopRequester) Force() {} diff --git a/module/signature/aggregation.go b/module/signature/aggregation.go index d56651d2221..c4812646cce 100644 --- a/module/signature/aggregation.go +++ b/module/signature/aggregation.go @@ -74,7 +74,7 @@ func NewSignatureAggregatorSameMessage( // // This function does not update the internal state. // The function errors: -// - InvalidSignerIdxError if the signer index is out of bound +// - [InvalidSignerIdxError] if the signer index is out of bound // - generic error for unexpected runtime failures // // The function does not return an error for any invalid signature. @@ -92,8 +92,8 @@ func (s *SignatureAggregatorSameMessage) Verify(signer int, sig crypto.Signature // key at the input index. If the verification passes, the signature is added to the internal // signature state. // The function errors: -// - InvalidSignerIdxError if the signer index is out of bound -// - DuplicatedSignerIdxError if a signature from the same signer index has already been added +// - [InvalidSignerIdxError] if the signer index is out of bound +// - [DuplicatedSignerIdxError] if a signature from the same signer index has already been added // - generic error for unexpected runtime failures // // The function does not return an error for any invalid signature. @@ -128,8 +128,8 @@ func (s *SignatureAggregatorSameMessage) add(signer int, sig crypto.Signature) { // outputs valid signatures. This would detect if TrustedAdd has added any invalid // signature. // The function errors: -// - InvalidSignerIdxError if the signer index is out of bound -// - DuplicatedSignerIdxError if a signature from the same signer index has already been added +// - [InvalidSignerIdxError] if the signer index is out of bound +// - [DuplicatedSignerIdxError] if a signature from the same signer index has already been added // // The function is not thread-safe. func (s *SignatureAggregatorSameMessage) TrustedAdd(signer int, sig crypto.Signature) error { @@ -147,7 +147,7 @@ func (s *SignatureAggregatorSameMessage) TrustedAdd(signer int, sig crypto.Signa // HasSignature checks if a signer has already provided a valid signature. // The function errors: -// - InvalidSignerIdxError if the signer index is out of bound +// - [InvalidSignerIdxError] if the signer index is out of bound // // The function is not thread-safe. func (s *SignatureAggregatorSameMessage) HasSignature(signer int) (bool, error) { @@ -168,12 +168,12 @@ func (s *SignatureAggregatorSameMessage) HasSignature(signer int) (bool, error) // cases, the function discards the generated aggregate and errors. // The function is not thread-safe. // Returns: -// - InsufficientSignaturesError if no signatures have been added yet -// - InvalidSignatureIncludedError if: +// - [InsufficientSignaturesError] if no signatures have been added yet +// - [InvalidSignatureIncludedError] if: // -- some signature(s), included via TrustedAdd, fail to deserialize (regardless of the aggregated public key) // -- Or all signatures deserialize correctly but some signature(s), included via TrustedAdd, are // invalid (while aggregated public key is valid) -// - ErrIdentityPublicKey if the signer's public keys add up to the BLS identity public key. +// - [ErrIdentityPublicKey] if the signer's public keys add up to the BLS identity public key. // Any aggregated signature would fail the cryptographic verification if verified against the // the identity public key. This case can only happen if public keys were forged to sum up to // an identity public key. Under the assumption that PoPs of all keys are valid, an identity @@ -236,8 +236,8 @@ func (s *SignatureAggregatorSameMessage) Aggregate() ([]int, crypto.Signature, e // `agg_key` is equal to the identity public key (because of equivocation). If the caller needs to // differentiate this case, `crypto.IsIdentityPublicKey` can be used to test the returned `agg_key` // - (false, nil, err) with error types: -// -- InsufficientSignaturesError if no signer indices are given (`signers` is empty) -// -- InvalidSignerIdxError if some signer indices are out of bound +// -- [InsufficientSignaturesError] if no signer indices are given (`signers` is empty) +// -- [InvalidSignerIdxError] if some signer indices are out of bound // -- generic error in case of an unexpected runtime failure func (s *SignatureAggregatorSameMessage) VerifyAggregate(signers []int, sig crypto.Signature) (bool, crypto.PublicKey, error) { keys := make([]crypto.PublicKey, 0, len(signers)) @@ -311,7 +311,7 @@ func NewPublicKeyAggregator(publicKeys []crypto.PublicKey) (*PublicKeyAggregator // // The aggregation errors if: // - generic error if input signers is empty. -// - InvalidSignerIdxError if any signer is out of bound. +// - [InvalidSignerIdxError] if any signer is out of bound. // - other generic errors are unexpected during normal operations. func (p *PublicKeyAggregator) KeyAggregate(signers []int) (crypto.PublicKey, error) { // check for empty list diff --git a/module/signature/aggregation_test.go b/module/signature/aggregation_test.go index 565534e7b78..30584fdaab8 100644 --- a/module/signature/aggregation_test.go +++ b/module/signature/aggregation_test.go @@ -41,7 +41,7 @@ func createAggregationData(t *testing.T, rand *mrand.Rand, signersNumber int) ( keys := make([]crypto.PublicKey, 0, signersNumber) sigs := make([]crypto.Signature, 0, signersNumber) seed := make([]byte, crypto.KeyGenSeedMinLen) - for i := 0; i < signersNumber; i++ { + for range signersNumber { _, err := rand.Read(seed) require.NoError(t, err) sk, err := crypto.GeneratePrivateKey(crypto.BLSBLS12381, seed) @@ -115,7 +115,7 @@ func TestAggregatorSameMessage(t *testing.T) { assert.True(t, expectedKey.Equals(aggKey)) // check signers sort.Ints(signers) - for i := 0; i < subSet; i++ { + for i := range subSet { index := i + subSet assert.Equal(t, index, signers[i]) } @@ -144,7 +144,7 @@ func TestAggregatorSameMessage(t *testing.T) { assert.True(t, expectedKey.Equals(aggKey)) // check signers sort.Ints(signers) - for i := 0; i < signersNum; i++ { + for i := range signersNum { assert.Equal(t, i, signers[i]) } }) @@ -419,7 +419,7 @@ func TestKeyAggregator(t *testing.T) { indices := make([]int, 0, signersNum) keys := make([]crypto.PublicKey, 0, signersNum) seed := make([]byte, crypto.KeyGenSeedMinLen) - for i := 0; i < signersNum; i++ { + for i := range signersNum { indices = append(indices, i) _, err := rand.Read(seed) require.NoError(t, err) @@ -492,7 +492,7 @@ func TestKeyAggregator(t *testing.T) { // iterate over different random cases to make sure // the delta algorithm works rounds := 30 - for i := 0; i < rounds; i++ { + for range rounds { go func() { // test module concurrency low := rand.Intn(signersNum - 1) high := low + 1 + rand.Intn(signersNum-1-low) diff --git a/module/signature/errors.go b/module/signature/errors.go index bad77f35768..6b3c2c318c8 100644 --- a/module/signature/errors.go +++ b/module/signature/errors.go @@ -36,7 +36,7 @@ type InvalidSignatureIncludedError struct { err error } -func NewInvalidSignatureIncludedErrorf(msg string, args ...interface{}) error { +func NewInvalidSignatureIncludedErrorf(msg string, args ...any) error { return InvalidSignatureIncludedError{ err: fmt.Errorf(msg, args...), } @@ -58,7 +58,7 @@ type InvalidSignerIdxError struct { err error } -func NewInvalidSignerIdxErrorf(msg string, args ...interface{}) error { +func NewInvalidSignerIdxErrorf(msg string, args ...any) error { return InvalidSignerIdxError{ err: fmt.Errorf(msg, args...), } @@ -80,7 +80,7 @@ type DuplicatedSignerIdxError struct { err error } -func NewDuplicatedSignerIdxErrorf(msg string, args ...interface{}) error { +func NewDuplicatedSignerIdxErrorf(msg string, args ...any) error { return DuplicatedSignerIdxError{ err: fmt.Errorf(msg, args...), } @@ -102,7 +102,7 @@ type InsufficientSignaturesError struct { err error } -func NewInsufficientSignaturesErrorf(msg string, args ...interface{}) error { +func NewInsufficientSignaturesErrorf(msg string, args ...any) error { return InsufficientSignaturesError{ err: fmt.Errorf(msg, args...), } @@ -124,7 +124,7 @@ type InvalidSignerIndicesError struct { err error } -func NewInvalidSignerIndicesErrorf(msg string, args ...interface{}) error { +func NewInvalidSignerIndicesErrorf(msg string, args ...any) error { return InvalidSignerIndicesError{ err: fmt.Errorf(msg, args...), } @@ -146,7 +146,7 @@ type InvalidSigTypesError struct { err error } -func NewInvalidSigTypesErrorf(msg string, args ...interface{}) error { +func NewInvalidSigTypesErrorf(msg string, args ...any) error { return InvalidSigTypesError{ err: fmt.Errorf(msg, args...), } diff --git a/module/signature/signer_indices.go b/module/signature/signer_indices.go index 30bf3faadb8..ec1f81d8abb 100644 --- a/module/signature/signer_indices.go +++ b/module/signature/signer_indices.go @@ -267,7 +267,7 @@ func decodeSignerIndices( // decode bits to Identifiers indices := make([]int, 0, numberCanonicalNodes) - for i := 0; i < numberCanonicalNodes; i++ { + for i := range numberCanonicalNodes { if bitutils.ReadBit(signerIndices, i) == 1 { indices = append(indices, i) } diff --git a/module/state_synchronization/indexer/collection_executed_metric.go b/module/state_synchronization/indexer/collection_executed_metric.go index ec1ac58b054..9713135c3af 100644 --- a/module/state_synchronization/indexer/collection_executed_metric.go +++ b/module/state_synchronization/indexer/collection_executed_metric.go @@ -58,12 +58,11 @@ func (c *CollectionExecutedMetricImpl) CollectionFinalized(light *flow.LightColl lightID := light.ID() if ti, found := c.collectionsToMarkFinalized.Get(lightID); found { - block, err := c.blocks.ByCollectionID(lightID) + blockID, err := c.blocks.BlockIDByCollectionID(lightID) if err != nil { c.log.Warn().Err(err).Msg("could not find block by collection ID") return } - blockID := block.ID() for _, t := range light.Transactions { c.accessMetrics.TransactionFinalized(t, ti) diff --git a/module/state_synchronization/indexer/extended/account_ft_transfers.go b/module/state_synchronization/indexer/extended/account_ft_transfers.go new file mode 100644 index 00000000000..c47f3b50e9f --- /dev/null +++ b/module/state_synchronization/indexer/extended/account_ft_transfers.go @@ -0,0 +1,134 @@ +package extended + +import ( + "fmt" + "math/big" + + "github.com/jordanschalm/lockctx" + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/transfers" + "github.com/onflow/flow-go/storage" +) + +const ( + accountFTTransfersIndexerName = "account_ft_transfers" + + // omitFlowFees set whether or not to omit flow fees transfers from the index. + omitFlowFees = true +) + +var bigZero = new(big.Int) + +// FungibleTokenTransfers indexes fungible token transfer events for a block. +type FungibleTokenTransfers struct { + log zerolog.Logger + ftParser *transfers.FTParser + ftStore storage.FungibleTokenTransfersBootstrapper + metrics module.ExtendedIndexingMetrics +} + +type FungibleTokenTransfersMetadata struct { + // FilteredCount is the number of transfers that were omitted. + FilteredCount int +} + +var _ Indexer = (*FungibleTokenTransfers)(nil) +var _ IndexProcessor[access.FungibleTokenTransfer, FungibleTokenTransfersMetadata] = (*FungibleTokenTransfers)(nil) + +// NewFungibleTokenTransfers creates a new [FungibleTokenTransfers] indexer. +func NewFungibleTokenTransfers( + log zerolog.Logger, + chainID flow.ChainID, + ftStore storage.FungibleTokenTransfersBootstrapper, + metrics module.ExtendedIndexingMetrics, +) *FungibleTokenTransfers { + return &FungibleTokenTransfers{ + log: log.With().Str("component", "account_ft_transfers_indexer").Logger(), + ftParser: transfers.NewFTParser(chainID, omitFlowFees), + ftStore: ftStore, + metrics: metrics, + } +} + +// Name returns the name of the indexer. +func (a *FungibleTokenTransfers) Name() string { + return accountFTTransfersIndexerName +} + +// NextHeight returns the next height that the indexer will index. +// +// No error returns are expected during normal operation. +func (a *FungibleTokenTransfers) NextHeight() (uint64, error) { + return nextHeight(a.ftStore) +} + +// IndexBlockData indexes FT transfer data for the given height. +// If the header in `data` does not match the expected height, an error is returned. +// +// The caller must hold the [storage.LockIndexFungibleTokenTransfers] lock until the batch is committed. +// +// CAUTION: Not safe for concurrent use. +// +// Expected error returns during normal operations: +// - [ErrAlreadyIndexed]: if the data is already indexed for the height. +// - [ErrFutureHeight]: if the data is for a future height. +func (a *FungibleTokenTransfers) IndexBlockData(lctx lockctx.Proof, data BlockData, batch storage.ReaderBatchWriter) error { + expectedHeight, err := a.NextHeight() + if err != nil { + return fmt.Errorf("failed to get next height: %w", err) + } + if data.Header.Height > expectedHeight { + return ErrFutureHeight + } + if data.Header.Height < expectedHeight { + return ErrAlreadyIndexed + } + + ftEntries, _, err := a.ProcessBlockData(data) + if err != nil { + return err + } + + if err := a.ftStore.Store(lctx, batch, data.Header.Height, ftEntries); err != nil { + return fmt.Errorf("failed to store fungible token transfers: %w", err) + } + + a.metrics.FTTransferIndexed(len(ftEntries)) + + return nil +} + +// ProcessBlockData processes the block data and returns the indexed fungible token transfer entries. +// +// No error returns are expected during normal operation. +func (a *FungibleTokenTransfers) ProcessBlockData(data BlockData) ([]access.FungibleTokenTransfer, FungibleTokenTransfersMetadata, error) { + ftEntries, err := a.ftParser.Parse(data.Events, data.Header.Height) + if err != nil { + return nil, FungibleTokenTransfersMetadata{}, fmt.Errorf("failed to parse fungible token transfers: %w", err) + } + filtered := a.filterFTTransfers(ftEntries) + return filtered, FungibleTokenTransfersMetadata{ + FilteredCount: len(ftEntries) - len(filtered), + }, nil +} + +// filterFTTransfers filters out transfers that do not need to be indexed. +func (a *FungibleTokenTransfers) filterFTTransfers(transfers []access.FungibleTokenTransfer) []access.FungibleTokenTransfer { + filtered := make([]access.FungibleTokenTransfer, 0) + for _, transfer := range transfers { + // skip zero amount transfers + if transfer.Amount == nil || transfer.Amount.Cmp(bigZero) == 0 { + continue + } + // skip self transfers + if transfer.SourceAddress == transfer.RecipientAddress { + continue + } + filtered = append(filtered, transfer) + } + return filtered +} diff --git a/module/state_synchronization/indexer/extended/account_ft_transfers_test.go b/module/state_synchronization/indexer/extended/account_ft_transfers_test.go new file mode 100644 index 00000000000..40379677999 --- /dev/null +++ b/module/state_synchronization/indexer/extended/account_ft_transfers_test.go @@ -0,0 +1,479 @@ +package extended + +import ( + "fmt" + "math/big" + "testing" + + "github.com/jordanschalm/lockctx" + "github.com/onflow/cadence" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/transfers/testutil" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/utils/unittest" +) + +// mockFTBootstrapper implements storage.FungibleTokenTransfersBootstrapper for testing. +type mockFTBootstrapper struct { + latestHeight uint64 + latestHeightErr error + firstHeight uint64 + isInitialized bool + storeErr error + storedHeight uint64 + storedTransfers []access.FungibleTokenTransfer +} + +func (m *mockFTBootstrapper) ByAddress(_ flow.Address, _ *access.TransferCursor) (storage.FungibleTokenTransferIterator, error) { + return nil, nil +} + +func (m *mockFTBootstrapper) LatestIndexedHeight() (uint64, error) { + return m.latestHeight, m.latestHeightErr +} + +func (m *mockFTBootstrapper) UninitializedFirstHeight() (uint64, bool) { + return m.firstHeight, m.isInitialized +} + +func (m *mockFTBootstrapper) FirstIndexedHeight() (uint64, error) { + if m.latestHeightErr != nil { + return 0, m.latestHeightErr + } + return m.firstHeight, nil +} + +func (m *mockFTBootstrapper) Store(_ lockctx.Proof, _ storage.ReaderBatchWriter, height uint64, transfers []access.FungibleTokenTransfer) error { + m.storedHeight = height + m.storedTransfers = transfers + return m.storeErr +} + +// ===== TestFilterFTTransfers ===== + +func TestFilterFTTransfers(t *testing.T) { + t.Parallel() + + a := &FungibleTokenTransfers{} + + t.Run("empty input returns empty output", func(t *testing.T) { + result := a.filterFTTransfers(nil) + assert.Empty(t, result) + }) + + t.Run("filters out zero-amount transfers", func(t *testing.T) { + addr := flow.HexToAddress("0x1234567890abcdef") + transfers := []access.FungibleTokenTransfer{ + { + RecipientAddress: addr, + Amount: big.NewInt(0), + TokenType: "A.0x1.FlowToken", + }, + } + + result := a.filterFTTransfers(transfers) + assert.Empty(t, result) + }) + + t.Run("non-zero amount transfers are kept regardless of recipient", func(t *testing.T) { + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + flowFeesAddress := sc.FlowFees.Address + otherAddress := flow.HexToAddress("0x1234567890abcdef") + + transfers := []access.FungibleTokenTransfer{ + { + RecipientAddress: flowFeesAddress, + Amount: big.NewInt(100), + TokenType: "A.0x1.FlowToken", + }, + { + RecipientAddress: otherAddress, + Amount: big.NewInt(200), + TokenType: "A.0x1.FlowToken", + }, + } + + result := a.filterFTTransfers(transfers) + require.Len(t, result, 2) + }) + + t.Run("mixed: only non-zero amount transfers are kept", func(t *testing.T) { + addr := flow.HexToAddress("0x1234567890abcdef") + transfers := []access.FungibleTokenTransfer{ + { + RecipientAddress: addr, + Amount: big.NewInt(200), + TokenType: "A.0x1.FlowToken", + }, + { + RecipientAddress: addr, + Amount: big.NewInt(0), + TokenType: "A.0x1.FlowToken", + }, + { + RecipientAddress: addr, + Amount: big.NewInt(999), + TokenType: "A.0x2.USDC", + }, + } + + result := a.filterFTTransfers(transfers) + require.Len(t, result, 2) + assert.Equal(t, big.NewInt(200), result[0].Amount) + assert.Equal(t, big.NewInt(999), result[1].Amount) + }) + + t.Run("filters out self-transfers", func(t *testing.T) { + addr := flow.HexToAddress("0x1234567890abcdef") + transfers := []access.FungibleTokenTransfer{ + { + SourceAddress: addr, + RecipientAddress: addr, + Amount: big.NewInt(100), + TokenType: "A.0x1.FlowToken", + }, + } + + result := a.filterFTTransfers(transfers) + assert.Empty(t, result) + }) + + t.Run("filters out zero-address self-transfer", func(t *testing.T) { + // Both source and recipient are the zero address (e.g. a mint with no from/to). + transfers := []access.FungibleTokenTransfer{ + { + SourceAddress: flow.Address{}, + RecipientAddress: flow.Address{}, + Amount: big.NewInt(100), + TokenType: "A.0x1.FlowToken", + }, + } + + result := a.filterFTTransfers(transfers) + assert.Empty(t, result) + }) + + t.Run("keeps transfer with distinct source and recipient", func(t *testing.T) { + src := flow.HexToAddress("0x0000000000000001") + dst := flow.HexToAddress("0x0000000000000002") + transfers := []access.FungibleTokenTransfer{ + { + SourceAddress: src, + RecipientAddress: dst, + Amount: big.NewInt(100), + TokenType: "A.0x1.FlowToken", + }, + } + + result := a.filterFTTransfers(transfers) + require.Len(t, result, 1) + assert.Equal(t, src, result[0].SourceAddress) + assert.Equal(t, dst, result[0].RecipientAddress) + }) + + t.Run("mixed: self-transfers filtered, regular transfers kept", func(t *testing.T) { + addrA := flow.HexToAddress("0x0000000000000001") + addrB := flow.HexToAddress("0x0000000000000002") + transfers := []access.FungibleTokenTransfer{ + {SourceAddress: addrA, RecipientAddress: addrA, Amount: big.NewInt(100), TokenType: "A.0x1.FlowToken"}, + {SourceAddress: addrA, RecipientAddress: addrB, Amount: big.NewInt(200), TokenType: "A.0x1.FlowToken"}, + {SourceAddress: addrB, RecipientAddress: addrB, Amount: big.NewInt(300), TokenType: "A.0x1.FlowToken"}, + } + + result := a.filterFTTransfers(transfers) + require.Len(t, result, 1) + assert.Equal(t, addrA, result[0].SourceAddress) + assert.Equal(t, addrB, result[0].RecipientAddress) + assert.Equal(t, big.NewInt(200), result[0].Amount) + }) +} + +// ===== TestFungibleTokenTransfers_NextHeight ===== + +func TestFungibleTokenTransfers_NextHeight(t *testing.T) { + t.Parallel() + + t.Run("initialized store returns latestHeight+1", func(t *testing.T) { + ftStore := &mockFTBootstrapper{ + latestHeight: 99, + latestHeightErr: nil, + } + + a := &FungibleTokenTransfers{ftStore: ftStore} + height, err := a.NextHeight() + require.NoError(t, err) + assert.Equal(t, uint64(100), height) + }) + + t.Run("uninitialized store returns firstHeight", func(t *testing.T) { + ftStore := &mockFTBootstrapper{ + latestHeightErr: storage.ErrNotBootstrapped, + firstHeight: 50, + isInitialized: false, + } + + a := &FungibleTokenTransfers{ftStore: ftStore} + height, err := a.NextHeight() + require.NoError(t, err) + assert.Equal(t, uint64(50), height) + }) + + t.Run("store error propagates", func(t *testing.T) { + ftErr := fmt.Errorf("FT storage failure") + ftStore := &mockFTBootstrapper{ + latestHeightErr: ftErr, + } + + a := &FungibleTokenTransfers{ftStore: ftStore} + _, err := a.NextHeight() + require.Error(t, err) + assert.ErrorIs(t, err, ftErr) + }) +} + +// ===== TestFungibleTokenTransfers_Name ===== + +func TestFungibleTokenTransfers_Name(t *testing.T) { + t.Parallel() + + a := &FungibleTokenTransfers{} + assert.Equal(t, "account_ft_transfers", a.Name()) +} + +// ===== TestFungibleTokenTransfers_ProcessBlockData ===== + +func TestFungibleTokenTransfers_ProcessBlockData(t *testing.T) { + t.Parallel() + + t.Run("empty block returns empty entries and zero filtered count", func(t *testing.T) { + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, &mockFTBootstrapper{latestHeight: 99}, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + entries, meta, err := a.ProcessBlockData(data) + require.NoError(t, err) + assert.Empty(t, entries) + assert.Equal(t, 0, meta.FilteredCount) + }) + + t.Run("self-transfer is filtered and counted in metadata", func(t *testing.T) { + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, &mockFTBootstrapper{latestHeight: 99}, metrics.NewNoopCollector()) + + addr := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + amount := cadence.UFix64(5_00000000) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &addr, txID, 0, 0, 1, 50, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &addr, txID, 0, 1, 1, 50, amount), + }, + } + + entries, meta, err := a.ProcessBlockData(data) + require.NoError(t, err) + assert.Empty(t, entries) + assert.Equal(t, 1, meta.FilteredCount) + }) + + t.Run("valid transfer returned with zero filtered count", func(t *testing.T) { + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, &mockFTBootstrapper{latestHeight: 99}, metrics.NewNoopCollector()) + + src := unittest.RandomAddressFixture() + dst := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + amount := cadence.UFix64(10_00000000) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &src, txID, 0, 0, 1, 50, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &dst, txID, 0, 1, 1, 50, amount), + }, + } + + entries, meta, err := a.ProcessBlockData(data) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, src, entries[0].SourceAddress) + assert.Equal(t, dst, entries[0].RecipientAddress) + assert.Equal(t, 0, meta.FilteredCount) + }) + + t.Run("does not depend on indexer height state", func(t *testing.T) { + // ProcessBlockData should work regardless of the indexer's height state + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, &mockFTBootstrapper{latestHeight: 50}, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(200)), + Events: []flow.Event{}, + } + + entries, meta, err := a.ProcessBlockData(data) + require.NoError(t, err) + assert.Empty(t, entries) + assert.Equal(t, 0, meta.FilteredCount) + }) +} + +// ===== TestFungibleTokenTransfers_IndexBlockData ===== + +func TestFungibleTokenTransfers_IndexBlockData(t *testing.T) { + t.Parallel() + + t.Run("empty block stores empty transfer slice", func(t *testing.T) { + ftStore := &mockFTBootstrapper{latestHeight: 99} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.NoError(t, err) + assert.Equal(t, uint64(100), ftStore.storedHeight) + assert.Empty(t, ftStore.storedTransfers) + }) + + t.Run("future height returns ErrFutureHeight", func(t *testing.T) { + ftStore := &mockFTBootstrapper{latestHeight: 99} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(101)), // next expected is 100 + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.ErrorIs(t, err, ErrFutureHeight) + }) + + t.Run("already indexed returns ErrAlreadyIndexed", func(t *testing.T) { + ftStore := &mockFTBootstrapper{latestHeight: 99} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(99)), // next expected is 100 + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.ErrorIs(t, err, ErrAlreadyIndexed) + }) + + t.Run("NextHeight error propagates", func(t *testing.T) { + nextHeightErr := fmt.Errorf("next height failure") + ftStore := &mockFTBootstrapper{latestHeightErr: nextHeightErr} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.Error(t, err) + assert.ErrorIs(t, err, nextHeightErr) + }) + + t.Run("store error propagates", func(t *testing.T) { + storeErr := fmt.Errorf("FT storage failure") + ftStore := &mockFTBootstrapper{latestHeight: 99, storeErr: storeErr} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.Error(t, err) + assert.ErrorIs(t, err, storeErr) + }) + + // Tests that the flow fees transfer is excluded by the parser when a FeesDeducted event + // is present, since the indexer is created with omitFlowFees=true. + t.Run("flow fees transfer omitted when FeesDeducted event is present", func(t *testing.T) { + ftStore := &mockFTBootstrapper{latestHeight: 99} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + payer := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + flowFeesAddress := testutil.FlowFeesAddress(flow.Testnet) + feeAmount := cadence.UFix64(1_00000000) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &payer, txID, 0, 0, 1, 50, feeAmount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &flowFeesAddress, txID, 0, 1, 1, 50, feeAmount), + testutil.MakeFlowFeesEvent(t, flow.Testnet, txID, 0, 2, feeAmount), + }, + } + + err := a.IndexBlockData(nil, data, nil) + require.NoError(t, err) + assert.Equal(t, uint64(100), ftStore.storedHeight) + assert.Empty(t, ftStore.storedTransfers) + }) + + // Tests that a self-transfer (same source and recipient address) is not stored. + t.Run("self-transfer is not stored", func(t *testing.T) { + ftStore := &mockFTBootstrapper{latestHeight: 99} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + addr := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + amount := cadence.UFix64(5_00000000) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &addr, txID, 0, 0, 1, 50, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &addr, txID, 0, 1, 1, 50, amount), + }, + } + + err := a.IndexBlockData(nil, data, nil) + require.NoError(t, err) + assert.Equal(t, uint64(100), ftStore.storedHeight) + assert.Empty(t, ftStore.storedTransfers) + }) + + // Tests that a regular transfer to the flow fees address (no FeesDeducted event) is indexed. + // The parser only omits transfers that are paired with a FeesDeducted event. + t.Run("transfer to flow fees address without FeesDeducted event is indexed", func(t *testing.T) { + ftStore := &mockFTBootstrapper{latestHeight: 99} + a := NewFungibleTokenTransfers(unittest.Logger(), flow.Testnet, ftStore, metrics.NewNoopCollector()) + + payer := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + flowFeesAddress := testutil.FlowFeesAddress(flow.Testnet) + amount := cadence.UFix64(5_00000000) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &payer, txID, 0, 0, 1, 50, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &flowFeesAddress, txID, 0, 1, 1, 50, amount), + // No FeesDeducted event — treated as a regular transfer. + }, + } + + err := a.IndexBlockData(nil, data, nil) + require.NoError(t, err) + assert.Equal(t, uint64(100), ftStore.storedHeight) + require.Len(t, ftStore.storedTransfers, 1) + }) +} diff --git a/module/state_synchronization/indexer/extended/account_nft_transfers.go b/module/state_synchronization/indexer/extended/account_nft_transfers.go new file mode 100644 index 00000000000..92acd6e6040 --- /dev/null +++ b/module/state_synchronization/indexer/extended/account_nft_transfers.go @@ -0,0 +1,103 @@ +package extended + +import ( + "fmt" + + "github.com/jordanschalm/lockctx" + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/transfers" + "github.com/onflow/flow-go/storage" +) + +const accountNFTTransfersIndexerName = "account_nft_transfers" + +// NonFungibleTokenTransfers indexes non-fungible token transfer events for a block. +type NonFungibleTokenTransfers struct { + log zerolog.Logger + nftParser *transfers.NFTParser + nftStore storage.NonFungibleTokenTransfersBootstrapper + metrics module.ExtendedIndexingMetrics +} + +type NonFungibleTokenTransfersMetadata struct{} + +var _ Indexer = (*NonFungibleTokenTransfers)(nil) +var _ IndexProcessor[access.NonFungibleTokenTransfer, NonFungibleTokenTransfersMetadata] = (*NonFungibleTokenTransfers)(nil) + +// NewNonFungibleTokenTransfers creates a new [NonFungibleTokenTransfers] indexer. +func NewNonFungibleTokenTransfers( + log zerolog.Logger, + chainID flow.ChainID, + nftStore storage.NonFungibleTokenTransfersBootstrapper, + metrics module.ExtendedIndexingMetrics, +) *NonFungibleTokenTransfers { + return &NonFungibleTokenTransfers{ + log: log.With().Str("component", "account_nft_transfers_indexer").Logger(), + nftParser: transfers.NewNFTParser(chainID), + nftStore: nftStore, + metrics: metrics, + } +} + +// Name returns the name of the indexer. +func (a *NonFungibleTokenTransfers) Name() string { + return accountNFTTransfersIndexerName +} + +// NextHeight returns the next height that the indexer will index. +// +// No error returns are expected during normal operation. +func (a *NonFungibleTokenTransfers) NextHeight() (uint64, error) { + return nextHeight(a.nftStore) +} + +// IndexBlockData indexes NFT transfer data for the given height. +// If the header in `data` does not match the expected height, an error is returned. +// +// The caller must hold the [storage.LockIndexNonFungibleTokenTransfers] lock until the batch is committed. +// +// CAUTION: Not safe for concurrent use. +// +// Expected error returns during normal operations: +// - [ErrAlreadyIndexed]: if the data is already indexed for the height. +// - [ErrFutureHeight]: if the data is for a future height. +func (a *NonFungibleTokenTransfers) IndexBlockData(lctx lockctx.Proof, data BlockData, batch storage.ReaderBatchWriter) error { + expectedHeight, err := a.NextHeight() + if err != nil { + return fmt.Errorf("failed to get next height: %w", err) + } + if data.Header.Height > expectedHeight { + return ErrFutureHeight + } + if data.Header.Height < expectedHeight { + return ErrAlreadyIndexed + } + + nftEntries, _, err := a.ProcessBlockData(data) + if err != nil { + return err + } + + if err := a.nftStore.Store(lctx, batch, data.Header.Height, nftEntries); err != nil { + return fmt.Errorf("failed to store non-fungible token transfers: %w", err) + } + + a.metrics.NFTTransferIndexed(len(nftEntries)) + + return nil +} + +// ProcessBlockData processes the block data and returns the indexed non-fungible token transfer entries. +// +// No error returns are expected during normal operation. +func (a *NonFungibleTokenTransfers) ProcessBlockData(data BlockData) ([]access.NonFungibleTokenTransfer, NonFungibleTokenTransfersMetadata, error) { + nftEntries, err := a.nftParser.Parse(data.Events, data.Header.Height) + if err != nil { + return nil, NonFungibleTokenTransfersMetadata{}, fmt.Errorf("failed to parse non-fungible token transfers: %w", err) + } + return nftEntries, NonFungibleTokenTransfersMetadata{}, nil +} diff --git a/module/state_synchronization/indexer/extended/account_nft_transfers_test.go b/module/state_synchronization/indexer/extended/account_nft_transfers_test.go new file mode 100644 index 00000000000..032bedaef0a --- /dev/null +++ b/module/state_synchronization/indexer/extended/account_nft_transfers_test.go @@ -0,0 +1,215 @@ +package extended + +import ( + "fmt" + "testing" + + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/utils/unittest" +) + +// mockNFTBootstrapper implements storage.NonFungibleTokenTransfersBootstrapper for testing. +type mockNFTBootstrapper struct { + latestHeight uint64 + latestHeightErr error + firstHeight uint64 + isInitialized bool + storeErr error + storedHeight uint64 + storedTransfers []access.NonFungibleTokenTransfer +} + +func (m *mockNFTBootstrapper) ByAddress(_ flow.Address, _ *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error) { + return nil, nil +} + +func (m *mockNFTBootstrapper) LatestIndexedHeight() (uint64, error) { + return m.latestHeight, m.latestHeightErr +} + +func (m *mockNFTBootstrapper) UninitializedFirstHeight() (uint64, bool) { + return m.firstHeight, m.isInitialized +} + +func (m *mockNFTBootstrapper) FirstIndexedHeight() (uint64, error) { + if m.latestHeightErr != nil { + return 0, m.latestHeightErr + } + return m.firstHeight, nil +} + +func (m *mockNFTBootstrapper) Store(_ lockctx.Proof, _ storage.ReaderBatchWriter, height uint64, transfers []access.NonFungibleTokenTransfer) error { + m.storedHeight = height + m.storedTransfers = transfers + return m.storeErr +} + +// ===== TestNonFungibleTokenTransfers_NextHeight ===== + +func TestNonFungibleTokenTransfers_NextHeight(t *testing.T) { + t.Parallel() + + t.Run("initialized store returns latestHeight+1", func(t *testing.T) { + nftStore := &mockNFTBootstrapper{ + latestHeight: 99, + latestHeightErr: nil, + } + + a := &NonFungibleTokenTransfers{nftStore: nftStore} + height, err := a.NextHeight() + require.NoError(t, err) + assert.Equal(t, uint64(100), height) + }) + + t.Run("uninitialized store returns firstHeight", func(t *testing.T) { + nftStore := &mockNFTBootstrapper{ + latestHeightErr: storage.ErrNotBootstrapped, + firstHeight: 50, + isInitialized: false, + } + + a := &NonFungibleTokenTransfers{nftStore: nftStore} + height, err := a.NextHeight() + require.NoError(t, err) + assert.Equal(t, uint64(50), height) + }) + + t.Run("store error propagates", func(t *testing.T) { + nftErr := fmt.Errorf("NFT storage failure") + nftStore := &mockNFTBootstrapper{ + latestHeightErr: nftErr, + } + + a := &NonFungibleTokenTransfers{nftStore: nftStore} + _, err := a.NextHeight() + require.Error(t, err) + assert.ErrorIs(t, err, nftErr) + }) +} + +// ===== TestNonFungibleTokenTransfers_Name ===== + +func TestNonFungibleTokenTransfers_Name(t *testing.T) { + t.Parallel() + + a := &NonFungibleTokenTransfers{} + assert.Equal(t, "account_nft_transfers", a.Name()) +} + +// ===== TestNonFungibleTokenTransfers_ProcessBlockData ===== + +func TestNonFungibleTokenTransfers_ProcessBlockData(t *testing.T) { + t.Parallel() + + t.Run("empty block returns empty entries", func(t *testing.T) { + a := NewNonFungibleTokenTransfers(unittest.Logger(), flow.Testnet, &mockNFTBootstrapper{latestHeight: 99}, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + entries, meta, err := a.ProcessBlockData(data) + require.NoError(t, err) + assert.Empty(t, entries) + assert.Equal(t, NonFungibleTokenTransfersMetadata{}, meta) + }) + + t.Run("does not depend on indexer height state", func(t *testing.T) { + // ProcessBlockData should work regardless of the indexer's height state + a := NewNonFungibleTokenTransfers(unittest.Logger(), flow.Testnet, &mockNFTBootstrapper{latestHeight: 50}, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(200)), + Events: []flow.Event{}, + } + + entries, _, err := a.ProcessBlockData(data) + require.NoError(t, err) + assert.Empty(t, entries) + }) +} + +// ===== TestNonFungibleTokenTransfers_IndexBlockData ===== + +func TestNonFungibleTokenTransfers_IndexBlockData(t *testing.T) { + t.Parallel() + + t.Run("empty block stores empty transfer slice", func(t *testing.T) { + nftStore := &mockNFTBootstrapper{latestHeight: 99} + a := NewNonFungibleTokenTransfers(unittest.Logger(), flow.Testnet, nftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.NoError(t, err) + assert.Equal(t, uint64(100), nftStore.storedHeight) + assert.Empty(t, nftStore.storedTransfers) + }) + + t.Run("future height returns ErrFutureHeight", func(t *testing.T) { + nftStore := &mockNFTBootstrapper{latestHeight: 99} + a := NewNonFungibleTokenTransfers(unittest.Logger(), flow.Testnet, nftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(101)), // next expected is 100 + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.ErrorIs(t, err, ErrFutureHeight) + }) + + t.Run("already indexed returns ErrAlreadyIndexed", func(t *testing.T) { + nftStore := &mockNFTBootstrapper{latestHeight: 99} + a := NewNonFungibleTokenTransfers(unittest.Logger(), flow.Testnet, nftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(99)), // next expected is 100 + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.ErrorIs(t, err, ErrAlreadyIndexed) + }) + + t.Run("NextHeight error propagates", func(t *testing.T) { + nextHeightErr := fmt.Errorf("next height failure") + nftStore := &mockNFTBootstrapper{latestHeightErr: nextHeightErr} + a := NewNonFungibleTokenTransfers(unittest.Logger(), flow.Testnet, nftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.Error(t, err) + assert.ErrorIs(t, err, nextHeightErr) + }) + + t.Run("store error propagates", func(t *testing.T) { + storeErr := fmt.Errorf("NFT storage failure") + nftStore := &mockNFTBootstrapper{latestHeight: 99, storeErr: storeErr} + a := NewNonFungibleTokenTransfers(unittest.Logger(), flow.Testnet, nftStore, metrics.NewNoopCollector()) + + data := BlockData{ + Header: unittest.BlockHeaderFixture(unittest.WithHeaderHeight(100)), + Events: []flow.Event{}, + } + + err := a.IndexBlockData(nil, data, nil) + require.Error(t, err) + assert.ErrorIs(t, err, storeErr) + }) +} diff --git a/module/state_synchronization/indexer/extended/account_transactions.go b/module/state_synchronization/indexer/extended/account_transactions.go new file mode 100644 index 00000000000..a72fb830018 --- /dev/null +++ b/module/state_synchronization/indexer/extended/account_transactions.go @@ -0,0 +1,237 @@ +package extended + +import ( + "errors" + "fmt" + "slices" + + "github.com/jordanschalm/lockctx" + "github.com/rs/zerolog" + + "github.com/onflow/cadence" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/access/systemcollection" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" + "github.com/onflow/flow-go/storage" +) + +const accountTransactionsIndexerName = "account_transactions" + +// AccountTransactions indexes account-transaction associations for a block. +type AccountTransactions struct { + log zerolog.Logger + store storage.AccountTransactionsBootstrapper + chainID flow.ChainID + lockManager storage.LockManager + serviceAccount flow.Address + scheduledExecutorAccount flow.Address + systemCollections *systemcollection.Versioned +} + +type AccountTransactionsMetadata struct{} + +var _ Indexer = (*AccountTransactions)(nil) +var _ IndexProcessor[access.AccountTransaction, AccountTransactionsMetadata] = (*AccountTransactions)(nil) + +func NewAccountTransactions( + log zerolog.Logger, + store storage.AccountTransactionsBootstrapper, + chainID flow.ChainID, + lockManager storage.LockManager, +) (*AccountTransactions, error) { + sc := systemcontracts.SystemContractsForChain(chainID) + systemCollections, err := systemcollection.NewVersioned(chainID.Chain(), systemcollection.Default(chainID)) + if err != nil { + return nil, fmt.Errorf("failed to create system collection set: %w", err) + } + + return &AccountTransactions{ + log: log.With().Str("component", "account_tx_indexer").Logger(), + store: store, + chainID: chainID, + lockManager: lockManager, + serviceAccount: sc.FlowServiceAccount.Address, + scheduledExecutorAccount: sc.ScheduledTransactionExecutor.Address, + systemCollections: systemCollections, + }, nil +} + +// Name returns the name of the indexer. +func (a *AccountTransactions) Name() string { + return accountTransactionsIndexerName +} + +// NextHeight returns the next height that the indexer will index. +// +// No error returns are expected during normal operation. +func (a *AccountTransactions) NextHeight() (uint64, error) { + height, err := a.store.LatestIndexedHeight() + if err == nil { + return height + 1, nil + } + + if !errors.Is(err, storage.ErrNotBootstrapped) { + return 0, fmt.Errorf("failed to get latest indexed height: %w", err) + } + + firstHeight, isInitialized := a.store.UninitializedFirstHeight() + if isInitialized { + // this shouldn't happen and would indicate a bug or inconsistent state. + return 0, fmt.Errorf("failed to get latest indexed height, but index is initialized: %w", err) + } + + return firstHeight, nil +} + +// IndexBlockData indexes the block data for the given height. +// If the header in `data` does not match the expected height, an error is returned. +// +// The caller must hold the [storage.LockIndexAccountTransactions] lock until the batch is committed. +// +// CAUTION: Not safe for concurrent use. +// +// Expected error returns during normal operations: +// - [ErrAlreadyIndexed]: if the data is already indexed for the height. +// - [ErrFutureHeight]: if the data is for a future height. +func (a *AccountTransactions) IndexBlockData(lctx lockctx.Proof, data BlockData, batch storage.ReaderBatchWriter) error { + expectedHeight, err := a.NextHeight() + if err != nil { + return fmt.Errorf("failed to get latest indexed height: %w", err) + } + if data.Header.Height > expectedHeight { + return ErrFutureHeight + } + if data.Header.Height < expectedHeight { + return ErrAlreadyIndexed + } + + entries, _, err := a.ProcessBlockData(data) + if err != nil { + return fmt.Errorf("failed to build account transactions from block data: %w", err) + } + + if err := a.store.Store(lctx, batch, data.Header.Height, entries); err != nil { + // since we have already checked that the height is not already indexed, no errors are expected + // here and indicate concurrent indexing which is not supported. + return fmt.Errorf("failed to store account transactions: %w", err) + } + + return nil +} + +// ProcessBlockData processes the block data and returns the indexed account transaction entries. +// +// No error returns are expected during normal operation. +func (a *AccountTransactions) ProcessBlockData(data BlockData) ([]access.AccountTransaction, AccountTransactionsMetadata, error) { + chain := a.chainID.Chain() + entries := make([]access.AccountTransaction, 0) + + addRole := func(addrRoles map[flow.Address][]access.TransactionRole, addr flow.Address, role access.TransactionRole) { + if _, ok := addrRoles[addr]; !ok { + addrRoles[addr] = make([]access.TransactionRole, 0) + } + addrRoles[addr] = append(addrRoles[addr], role) + } + + eventsByTxIndex := groupEventsByTxIndex(data.Events) + + // By the Flow protocol, system chunk transactions always appear after all user transactions + // in a block. Once the first system transaction is encountered, all subsequent transactions + // are also part of the system chunk. + isSystemChunk := false + for i, tx := range data.Transactions { + txIndex := uint32(i) + txID := tx.ID() + + // all tx after the first system tx are in the system chunk + if !isSystemChunk { + _, isSystemChunk = a.systemCollections.SearchAll(txID) + } + + // Track roles per address. An address can have multiple roles (e.g., payer AND authorizer). + addrRoles := make(map[flow.Address][]access.TransactionRole) + + addRole(addrRoles, tx.Payer, access.TransactionRolePayer) + addRole(addrRoles, tx.ProposalKey.Address, access.TransactionRoleProposer) + for _, auth := range tx.Authorizers { + // the service account authorizes all system transactions, and the scheduled tx executor + // account authorizes all scheduled transactions. skip indexing since we can derive them + // as needed. + if isSystemChunk { + if auth == a.serviceAccount || auth == a.scheduledExecutorAccount { + continue + } + } + addRole(addrRoles, auth, access.TransactionRoleAuthorizer) + } + + seen := make(map[flow.Address]struct{}) + for _, event := range eventsByTxIndex[txIndex] { + eventAddresses, err := a.extractAddresses(event) + if err != nil { + return nil, AccountTransactionsMetadata{}, fmt.Errorf("failed to extract addresses from event: %w", err) + } + for _, addr := range eventAddresses { + // only add the role once for an address per transaction + if _, ok := seen[addr]; ok { + continue + } + seen[addr] = struct{}{} + + // since `extractAddresses` returns all [cadence.Address] fields in the event, it's possible + // that the event contains invalid addresses, or addresses from a different chain. + // Only index addresses that are actually valid for the current chain. + if chain.IsValid(addr) { + addRole(addrRoles, addr, access.TransactionRoleInteracted) + } + } + } + + for addr, roles := range addrRoles { + slices.Sort(roles) // sort roles in ascending order + entries = append(entries, access.AccountTransaction{ + Address: addr, + BlockHeight: data.Header.Height, + TransactionID: txID, + TransactionIndex: txIndex, + Roles: roles, + }) + } + } + return entries, AccountTransactionsMetadata{}, nil +} + +// extractAddresses extracts all addresses referenced in a flow event. +// +// No error returns are expected during normal operation. +func (a *AccountTransactions) extractAddresses(event flow.Event) ([]flow.Address, error) { + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode event payload: %w", err) + } + + addresses := make([]flow.Address, 0) + + fields := cadence.FieldsMappedByName(cadenceEvent) + for _, field := range fields { + switch v := field.(type) { + case cadence.Address: + addresses = append(addresses, flow.Address(v)) + case cadence.Optional: + if v.Value == nil { + continue + } + + addr, ok := v.Value.(cadence.Address) + if !ok { + continue + } + + addresses = append(addresses, flow.Address(addr)) + } + } + return addresses, nil +} diff --git a/module/state_synchronization/indexer/extended/account_transactions_test.go b/module/state_synchronization/indexer/extended/account_transactions_test.go new file mode 100644 index 00000000000..e2bfc208157 --- /dev/null +++ b/module/state_synchronization/indexer/extended/account_transactions_test.go @@ -0,0 +1,1120 @@ +package extended + +import ( + "fmt" + "os" + "testing" + + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/encoding/ccf" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// ===== Basic Indexing Tests ===== + +func TestAccountTransactionsIndexer(t *testing.T) { + t.Parallel() + const testHeight = uint64(100) + + t.Run("empty block", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: nil, + Events: []flow.Event{}, + }) + + // Verify height was updated + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, testHeight, latest) + + // No transactions for any address + assertTransactionCount(t, store, testHeight, unittest.RandomAddressFixture(), 0) + }) + + t.Run("single transaction with distinct accounts", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + proposer := unittest.RandomAddressFixture() + auth1 := unittest.RandomAddressFixture() + auth2 := unittest.RandomAddressFixture() + + tx := unittest.TransactionBodyFixture( + func(tb *flow.TransactionBody) { + tb.Payer = payer + tb.ProposalKey = flow.ProposalKey{Address: proposer} + tb.Authorizers = []flow.Address{auth1, auth2} + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, []access.TransactionRole{access.TransactionRolePayer}) + assertAccountTxRoles(t, store, testHeight, proposer, txID, []access.TransactionRole{access.TransactionRoleProposer}) + assertAccountTxRoles(t, store, testHeight, auth1, txID, []access.TransactionRole{access.TransactionRoleAuthorizer}) + assertAccountTxRoles(t, store, testHeight, auth2, txID, []access.TransactionRole{access.TransactionRoleAuthorizer}) + }) + + t.Run("payer is also authorizer", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + proposer := unittest.RandomAddressFixture() + + tx := unittest.TransactionBodyFixture( + func(tb *flow.TransactionBody) { + tb.Payer = payer + tb.ProposalKey = flow.ProposalKey{Address: proposer} + tb.Authorizers = []flow.Address{payer} + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, []access.TransactionRole{access.TransactionRoleAuthorizer, access.TransactionRolePayer}) + assertAccountTxRoles(t, store, testHeight, proposer, txID, []access.TransactionRole{access.TransactionRoleProposer}) + // payer should be deduplicated to one entry + assertTransactionCount(t, store, testHeight, payer, 1) + }) + + t.Run("payer is all roles", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + + tx := unittest.TransactionBodyFixture( + func(tb *flow.TransactionBody) { + tb.Payer = payer + tb.ProposalKey = flow.ProposalKey{Address: payer} + tb.Authorizers = []flow.Address{payer} + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, []access.TransactionRole{access.TransactionRoleAuthorizer, access.TransactionRolePayer, access.TransactionRoleProposer}) + assertTransactionCount(t, store, testHeight, payer, 1) + }) + + t.Run("multiple transactions", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + account1 := unittest.RandomAddressFixture() + account2 := unittest.RandomAddressFixture() + account3 := unittest.RandomAddressFixture() + + tx1 := unittest.TransactionBodyFixture( + func(tb *flow.TransactionBody) { + tb.Payer = account1 + tb.ProposalKey = flow.ProposalKey{Address: account1} + tb.Authorizers = []flow.Address{account1} + }, + ) + + tx2 := unittest.TransactionBodyFixture( + func(tb *flow.TransactionBody) { + tb.Payer = account2 + tb.ProposalKey = flow.ProposalKey{Address: account2} + tb.Authorizers = []flow.Address{account2} + }, + ) + + tx3 := unittest.TransactionBodyFixture( + func(tb *flow.TransactionBody) { + tb.Payer = account3 + tb.ProposalKey = flow.ProposalKey{Address: account3} + tb.Authorizers = []flow.Address{account3} + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx1, &tx2, &tx3}, + Events: []flow.Event{}, + }) + + allRoles := []access.TransactionRole{access.TransactionRoleAuthorizer, access.TransactionRolePayer, access.TransactionRoleProposer} + assertAccountTxRoles(t, store, testHeight, account1, tx1.ID(), allRoles) + assertAccountTxRoles(t, store, testHeight, account2, tx2.ID(), allRoles) + assertAccountTxRoles(t, store, testHeight, account3, tx3.ID(), allRoles) + + // Each account should only have 1 transaction + assertTransactionCount(t, store, testHeight, account1, 1) + assertTransactionCount(t, store, testHeight, account2, 1) + assertTransactionCount(t, store, testHeight, account3, 1) + }) +} + +// ===== Event Address Extraction Tests ===== + +func TestAccountTransactionsIndexer_EventAddresses(t *testing.T) { + t.Parallel() + const testHeight = uint64(100) + + simpleTx := func(payer flow.Address) flow.TransactionBody { + return unittest.TransactionBodyFixture(func(tb *flow.TransactionBody) { + tb.Payer = payer + tb.ProposalKey = flow.ProposalKey{Address: payer} + tb.Authorizers = []flow.Address{payer} + }) + } + + // Common role sets for simpleTx (payer=proposer=authorizer) and event-only addresses + simpleTxRoles := []access.TransactionRole{access.TransactionRoleAuthorizer, access.TransactionRolePayer, access.TransactionRoleProposer} + interactionRoles := []access.TransactionRole{access.TransactionRoleInteracted} + + // --- Generic event address extraction --- + // Tests that extractAddresses handles all cadence field types correctly in a single event: + // Address fields are extracted, Optional
(non-nil) are extracted, + // Optional
(nil) are skipped, and non-address fields are ignored. + + t.Run("extracts addresses from mixed event field types", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + directAddr := unittest.RandomAddressFixture() + optionalAddr := unittest.RandomAddressFixture() + tx := simpleTx(payer) + + event := createTestEvent(t, 0, "ComplexEvent", + []cadence.Field{ + {Identifier: "name", Type: cadence.StringType}, // non-address: ignored + {Identifier: "creator", Type: cadence.AddressType}, // Address: extracted + {Identifier: "amount", Type: cadence.UFix64Type}, // non-address: ignored + {Identifier: "recipient", Type: cadence.NewOptionalType(cadence.AddressType)}, // Optional
non-nil: extracted + {Identifier: "nilAddr", Type: cadence.NewOptionalType(cadence.AddressType)}, // Optional
nil: skipped + {Identifier: "optNum", Type: cadence.NewOptionalType(cadence.UInt64Type)}, // Optional: ignored + {Identifier: "count", Type: cadence.UInt64Type}, // non-address: ignored + }, + []cadence.Value{ + cadence.String("test"), + cadence.NewAddress(directAddr), + cadence.UFix64(100_00000000), + cadence.NewOptional(cadence.NewAddress(optionalAddr)), + cadence.NewOptional(nil), + cadence.NewOptional(cadence.UInt64(42)), + cadence.UInt64(5), + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{event}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, directAddr, txID, interactionRoles) + assertAccountTxRoles(t, store, testHeight, optionalAddr, txID, interactionRoles) + // payer + 2 event addresses = 3 total entries for this tx + assertTransactionCount(t, store, testHeight, payer, 1) + assertTransactionCount(t, store, testHeight, directAddr, 1) + assertTransactionCount(t, store, testHeight, optionalAddr, 1) + }) + + // --- FT/NFT event tests --- + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + ftAddr := sc.FungibleToken.Address.Hex() + nftAddr := sc.NonFungibleToken.Address.Hex() + ftDepositedType := flow.EventType(fmt.Sprintf("A.%s.FungibleToken.Deposited", ftAddr)) + ftWithdrawnType := flow.EventType(fmt.Sprintf("A.%s.FungibleToken.Withdrawn", ftAddr)) + nftDepositedType := flow.EventType(fmt.Sprintf("A.%s.NonFungibleToken.Deposited", nftAddr)) + nftWithdrawnType := flow.EventType(fmt.Sprintf("A.%s.NonFungibleToken.Withdrawn", nftAddr)) + + t.Run("FT deposited event adds recipient", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + tx := simpleTx(payer) + depositEvent := createFTDepositedEvent(t, ftDepositedType, 0, &recipient) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{depositEvent}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, recipient, txID, interactionRoles) + }) + + t.Run("FT withdrawn event adds sender", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + sender := unittest.RandomAddressFixture() + tx := simpleTx(payer) + withdrawEvent := createFTWithdrawnEvent(t, ftWithdrawnType, 0, &sender) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{withdrawEvent}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, sender, txID, interactionRoles) + }) + + t.Run("NFT deposited event adds recipient", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + tx := simpleTx(payer) + depositEvent := createNFTDepositedEvent(t, nftDepositedType, 0, &recipient) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{depositEvent}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, recipient, txID, interactionRoles) + }) + + t.Run("NFT withdrawn event adds sender", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + sender := unittest.RandomAddressFixture() + tx := simpleTx(payer) + withdrawEvent := createNFTWithdrawnEvent(t, nftWithdrawnType, 0, &sender) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{withdrawEvent}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, sender, txID, interactionRoles) + }) + + t.Run("FT event with nil address is skipped", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + tx := simpleTx(payer) + depositEvent := createFTDepositedEvent(t, ftDepositedType, 0, nil) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{depositEvent}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertTransactionCount(t, store, testHeight, payer, 1) + }) + + // --- Deduplication tests --- + + t.Run("event address same as payer does not duplicate", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + tx := simpleTx(payer) + + event := createTestEvent(t, 0, "AccountCreated", + []cadence.Field{ + {Identifier: "address", Type: cadence.AddressType}, + }, + []cadence.Value{ + cadence.NewAddress(payer), + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{event}, + }) + + // Payer should appear exactly once despite also being in the event + assertTransactionCount(t, store, testHeight, payer, 1) + // Payer has all simpleTx roles plus Interaction from the event + simpleTxPlusInteraction := []access.TransactionRole{ + access.TransactionRoleAuthorizer, access.TransactionRolePayer, access.TransactionRoleProposer, access.TransactionRoleInteracted, + } + assertAccountTxRoles(t, store, testHeight, payer, tx.ID(), simpleTxPlusInteraction) + }) + + t.Run("duplicate event addresses in same transaction are deduplicated", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + eventAddr := unittest.RandomAddressFixture() + tx := simpleTx(payer) + + // Two different events both referencing the same address + event1 := createTestEvent(t, 0, "Transfer", + []cadence.Field{ + {Identifier: "to", Type: cadence.AddressType}, + }, + []cadence.Value{ + cadence.NewAddress(eventAddr), + }, + ) + event2 := createTestEvent(t, 0, "Approval", + []cadence.Field{ + {Identifier: "from", Type: cadence.AddressType}, + }, + []cadence.Value{ + cadence.NewAddress(eventAddr), + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{event1, event2}, + }) + + // eventAddr should appear exactly once with a single Interaction role + assertTransactionCount(t, store, testHeight, eventAddr, 1) + assertAccountTxRoles(t, store, testHeight, eventAddr, tx.ID(), interactionRoles) + }) + + t.Run("event address does not override authorizer status", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + + // recipient is an authorizer on the transaction + tx := unittest.TransactionBodyFixture(func(tb *flow.TransactionBody) { + tb.Payer = payer + tb.ProposalKey = flow.ProposalKey{Address: payer} + tb.Authorizers = []flow.Address{recipient} + }) + + // event also references recipient (as non-authorizer), should not downgrade + event := createTestEvent(t, 0, "Transfer", + []cadence.Field{ + {Identifier: "to", Type: cadence.AddressType}, + }, + []cadence.Value{ + cadence.NewAddress(recipient), + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{event}, + }) + + txID := tx.ID() + // recipient is authorizer and also referenced in event → both roles preserved + assertAccountTxRoles(t, store, testHeight, recipient, txID, []access.TransactionRole{access.TransactionRoleAuthorizer, access.TransactionRoleInteracted}) + // payer is payer + proposer (not authorizer in this test) + assertAccountTxRoles(t, store, testHeight, payer, txID, []access.TransactionRole{access.TransactionRolePayer, access.TransactionRoleProposer}) + assertTransactionCount(t, store, testHeight, recipient, 1) + }) + + // --- Multi-event / multi-transaction tests --- + + t.Run("multiple events in same transaction", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + tx := simpleTx(payer) + + withdrawEvent := createFTWithdrawnEvent(t, ftWithdrawnType, 0, &sender) + depositEvent := createFTDepositedEvent(t, ftDepositedType, 0, &recipient) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{withdrawEvent, depositEvent}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, sender, txID, interactionRoles) + assertAccountTxRoles(t, store, testHeight, recipient, txID, interactionRoles) + }) + + t.Run("events across multiple transactions with correct txIndex", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + account1 := unittest.RandomAddressFixture() + account2 := unittest.RandomAddressFixture() + recipient1 := unittest.RandomAddressFixture() + recipient2 := unittest.RandomAddressFixture() + + tx1 := simpleTx(account1) + tx2 := simpleTx(account2) + + event1 := createFTDepositedEvent(t, ftDepositedType, 0, &recipient1) + event2 := createNFTDepositedEvent(t, nftDepositedType, 1, &recipient2) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx1, &tx2}, + Events: []flow.Event{event1, event2}, + }) + + // tx1: account1 (payer+proposer+authorizer) + recipient1 (from FT event) + assertAccountTxRoles(t, store, testHeight, account1, tx1.ID(), simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, recipient1, tx1.ID(), interactionRoles) + + // tx2: account2 (payer+proposer+authorizer) + recipient2 (from NFT event) + assertAccountTxRoles(t, store, testHeight, account2, tx2.ID(), simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, recipient2, tx2.ID(), interactionRoles) + + // recipients should only be associated with their respective transactions + assertTransactionCount(t, store, testHeight, recipient1, 1) + assertTransactionCount(t, store, testHeight, recipient2, 1) + }) + + t.Run("mixed generic and FT events in same block", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + createdAddr := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + tx := simpleTx(payer) + + accountCreatedEvent := createTestEvent(t, 0, "AccountCreated", + []cadence.Field{ + {Identifier: "address", Type: cadence.AddressType}, + }, + []cadence.Value{ + cadence.NewAddress(createdAddr), + }, + ) + ftDepositEvent := createFTDepositedEvent(t, ftDepositedType, 0, &recipient) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{accountCreatedEvent, ftDepositEvent}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertAccountTxRoles(t, store, testHeight, createdAddr, txID, interactionRoles) + assertAccountTxRoles(t, store, testHeight, recipient, txID, interactionRoles) + }) + + // --- Invalid address filtering --- + + t.Run("event address invalid for chain is ignored", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + tx := simpleTx(payer) + + // Use an address that is invalid for testnet's linear code address scheme. + invalidAddr := flow.BytesToAddress([]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}) + require.False(t, flow.Testnet.Chain().IsValid(invalidAddr), "test requires an invalid address") + + event := createTestEvent(t, 0, "SomeEvent", + []cadence.Field{ + {Identifier: "account", Type: cadence.AddressType}, + }, + []cadence.Value{ + cadence.NewAddress(invalidAddr), + }, + ) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{event}, + }) + + txID := tx.ID() + assertAccountTxRoles(t, store, testHeight, payer, txID, simpleTxRoles) + assertTransactionCount(t, store, testHeight, invalidAddr, 0) + }) + + // --- Error tests --- + + t.Run("malformed event payload returns error", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + tx := simpleTx(payer) + + badEvent := flow.Event{ + Type: ftDepositedType, + TransactionIndex: 0, + EventIndex: 0, + Payload: []byte("not valid ccf"), + } + + err := indexBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{badEvent}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to extract addresses from event") + + // Store should not have been initialized + _, err = store.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) +} + +// ===== ProcessBlockData Tests ===== + +func TestAccountTransactionsIndexer_ProcessBlockData(t *testing.T) { + t.Parallel() + const testHeight = uint64(100) + + t.Run("empty block returns empty entries", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, _, _, _ := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + entries, meta, err := indexer.ProcessBlockData(BlockData{ + Header: header, + }) + require.NoError(t, err) + assert.Empty(t, entries) + assert.Equal(t, AccountTransactionsMetadata{}, meta) + }) + + t.Run("returns correct entries for single transaction", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, _, _, _ := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + payer := unittest.RandomAddressFixture() + tx := unittest.TransactionBodyFixture(func(tb *flow.TransactionBody) { + tb.Payer = payer + tb.ProposalKey = flow.ProposalKey{Address: payer} + tb.Authorizers = []flow.Address{payer} + }) + + entries, _, err := indexer.ProcessBlockData(BlockData{ + Header: header, + Transactions: []*flow.TransactionBody{&tx}, + Events: []flow.Event{}, + }) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, payer, entries[0].Address) + assert.Equal(t, tx.ID(), entries[0].TransactionID) + }) + + t.Run("does not depend on indexer height state", func(t *testing.T) { + // ProcessBlockData should work regardless of the indexer's height state + indexer, _, _, _ := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight+50)) + + entries, _, err := indexer.ProcessBlockData(BlockData{ + Header: header, + }) + require.NoError(t, err) + assert.Empty(t, entries) + }) +} + +// ===== Height Validation Tests ===== + +func TestAccountTransactionsIndexer_HeightValidation(t *testing.T) { + t.Parallel() + const testHeight = uint64(100) + + t.Run("uninitialized indexer accepts first expected height", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + indexBlock(t, indexer, lm, db, BlockData{ + Header: header, + }) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, testHeight, latest) + }) + + t.Run("uninitialized indexer returns ErrFutureHeight for wrong height", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight+10)) + indexer, _, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + err := indexBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + }) + require.ErrorIs(t, err, ErrFutureHeight) + }) + + t.Run("uninitialized indexer returns ErrAlreadyIndexed for height below first", func(t *testing.T) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight-5)) + indexer, _, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + err := indexBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + }) + require.ErrorIs(t, err, ErrAlreadyIndexed) + }) + + t.Run("initialized indexer accepts next sequential height", func(t *testing.T) { + indexer, store, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + // Initialize by indexing the first block + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexBlock(t, indexer, lm, db, BlockData{Header: header1}) + + // Index the next sequential block + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight+1)) + indexBlock(t, indexer, lm, db, BlockData{Header: header2}) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, testHeight+1, latest) + }) + + t.Run("initialized indexer returns ErrFutureHeight for non-sequential height", func(t *testing.T) { + indexer, _, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + // Initialize + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexBlock(t, indexer, lm, db, BlockData{Header: header1}) + + // Skip a height + header3 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight+5)) + err := indexBlockExpectError(t, indexer, lm, db, BlockData{Header: header3}) + require.ErrorIs(t, err, ErrFutureHeight) + }) + + t.Run("initialized indexer returns ErrAlreadyIndexed for past height", func(t *testing.T) { + indexer, _, lm, db := newAccountTxIndexerForTest(t, flow.Testnet, testHeight) + + // Initialize + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + indexBlock(t, indexer, lm, db, BlockData{Header: header1}) + + // Try to re-index the same height + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + err := indexBlockExpectError(t, indexer, lm, db, BlockData{Header: header2}) + require.ErrorIs(t, err, ErrAlreadyIndexed) + }) +} + +// ===== Mock-Based Error Path Tests ===== + +func TestAccountTransactionsIndexer_NextHeight(t *testing.T) { + t.Parallel() + + t.Run("unexpected error from LatestIndexedHeight propagates", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsBootstrapper(t) + unexpectedErr := fmt.Errorf("disk I/O error") + mockStore.On("LatestIndexedHeight").Return(uint64(0), unexpectedErr) + + lm := storage.NewTestingLockManager() + indexer, err := NewAccountTransactions(unittest.Logger(), mockStore, flow.Testnet, lm) + require.NoError(t, err) + + _, err = indexer.NextHeight() + require.Error(t, err) + require.ErrorIs(t, err, unexpectedErr) + }) + + t.Run("inconsistent state: not bootstrapped but initialized", func(t *testing.T) { + mockStore := storagemock.NewAccountTransactionsBootstrapper(t) + mockStore.On("LatestIndexedHeight").Return(uint64(0), storage.ErrNotBootstrapped) + mockStore.On("UninitializedFirstHeight").Return(uint64(42), true) + + lm := storage.NewTestingLockManager() + indexer, err := NewAccountTransactions(unittest.Logger(), mockStore, flow.Testnet, lm) + require.NoError(t, err) + + _, err = indexer.NextHeight() + require.Error(t, err) + assert.Contains(t, err.Error(), "but index is initialized") + }) +} + +func TestAccountTransactionsIndexer_StoreErrorPropagation(t *testing.T) { + t.Parallel() + + const testHeight = uint64(100) + + mockStore := storagemock.NewAccountTransactionsBootstrapper(t) + // NextHeight() calls LatestIndexedHeight -> returns 99 -> NextHeight = 100 + mockStore.On("LatestIndexedHeight").Return(testHeight-1, nil) + + storeErr := fmt.Errorf("unexpected storage error") + mockStore.On("Store", mock.Anything, mock.Anything, testHeight, mock.Anything).Return(storeErr) + + lm := storage.NewTestingLockManager() + indexer, err := NewAccountTransactions(unittest.Logger(), mockStore, flow.Testnet, lm) + require.NoError(t, err) + + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + + // Call IndexBlockData directly with nil batch since the mock Store doesn't use it + err = unittest.WithLock(t, lm, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return indexer.IndexBlockData(lctx, BlockData{Header: header}, nil) + }) + require.Error(t, err) + require.ErrorIs(t, err, storeErr) +} + +// ===== Test Setup Helpers ===== + +func newAccountTxIndexerForTest( + t *testing.T, + chainID flow.ChainID, + latestHeight uint64, +) (*AccountTransactions, storage.AccountTransactionsBootstrapper, storage.LockManager, storage.DB) { + pdb, dbDir := unittest.TempPebbleDB(t) + db := pebbleimpl.ToDB(pdb) + t.Cleanup(func() { + require.NoError(t, db.Close()) + require.NoError(t, os.RemoveAll(dbDir)) + }) + + lm := storage.NewTestingLockManager() + store, err := indexes.NewAccountTransactionsBootstrapper(db, latestHeight) + require.NoError(t, err) + + indexer, err := NewAccountTransactions(unittest.Logger(), store, chainID, lm) + require.NoError(t, err) + return indexer, store, lm, db +} + +// createTestEvent creates a CCF-encoded flow event with arbitrary cadence fields. +func createTestEvent( + t *testing.T, + txIndex uint32, + eventTypeName string, + fields []cadence.Field, + values []cadence.Value, +) flow.Event { + location := common.NewAddressLocation(nil, common.Address{}, "Test") + eventCadenceType := cadence.NewEventType(location, eventTypeName, fields, nil) + event := cadence.NewEvent(values).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: flow.EventType("A..Test." + eventTypeName), + TransactionIndex: txIndex, + EventIndex: 0, + Payload: payload, + } +} + +// indexBlock runs IndexBlockData with proper locking and batch commit. +func indexBlock( + t *testing.T, + indexer *AccountTransactions, + lm storage.LockManager, + db storage.DB, + data BlockData, +) { + err := unittest.WithLock(t, lm, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return indexer.IndexBlockData(lctx, data, rw) + }) + }) + require.NoError(t, err) +} + +// indexBlockExpectError runs IndexBlockData and returns the error. +func indexBlockExpectError( + t *testing.T, + indexer *AccountTransactions, + lm storage.LockManager, + db storage.DB, + data BlockData, +) error { + return unittest.WithLock(t, lm, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return indexer.IndexBlockData(lctx, data, rw) + }) + }) +} + +// assertAccountTxRoles verifies that a specific transaction is indexed for the given address +// with the expected roles. +func assertAccountTxRoles( + t *testing.T, + store storage.AccountTransactionsReader, + height uint64, + addr flow.Address, + txID flow.Identifier, + expectedRoles []access.TransactionRole, +) { + t.Helper() + iter, err := store.ByAddress(addr, nil) + require.NoError(t, err) + + for entry := range iter { + r, err := entry.Value() + require.NoError(t, err) + if r.TransactionID == txID && r.BlockHeight == height { + assert.Equal(t, expectedRoles, r.Roles, + "address %s tx %s: expected roles=%v, got roles=%v", addr, txID, expectedRoles, r.Roles) + return + } + } + t.Errorf("transaction %s not found for address %s at height %d", txID, addr, height) +} + +// assertTransactionCount verifies the total number of transactions for an address at a height. +func assertTransactionCount( + t *testing.T, + store storage.AccountTransactionsReader, + height uint64, + addr flow.Address, + expectedCount int, +) { + t.Helper() + iter, err := store.ByAddress(addr, nil) + require.NoError(t, err) + + var count int + for entry := range iter { + r, err := entry.Value() + require.NoError(t, err) + if r.BlockHeight == height { + count++ + } + } + require.Equal(t, expectedCount, count, + "expected %d transactions for address %s at height %d", expectedCount, addr, height) +} + +// ===== CCF Event Creation Helpers ===== + +// createFTDepositedEvent creates a CCF-encoded FungibleToken.Deposited event +func createFTDepositedEvent(t *testing.T, eventType flow.EventType, txIndex uint32, toAddr *flow.Address) flow.Event { + var toValue cadence.Value + if toAddr != nil { + toValue = cadence.NewOptional(cadence.NewAddress(*toAddr)) + } else { + toValue = cadence.NewOptional(nil) + } + + location := common.NewAddressLocation(nil, common.Address{}, "FungibleToken") + eventCadenceType := cadence.NewEventType( + location, + "FungibleToken.Deposited", + []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "amount", Type: cadence.UFix64Type}, + {Identifier: "to", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "toUUID", Type: cadence.UInt64Type}, + {Identifier: "depositedUUID", Type: cadence.UInt64Type}, + {Identifier: "balanceAfter", Type: cadence.UFix64Type}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String("A.0x1.FlowToken.Vault"), + cadence.UFix64(100_00000000), // 100.0 + toValue, + cadence.UInt64(1), + cadence.UInt64(2), + cadence.UFix64(200_00000000), + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: eventType, + TransactionIndex: txIndex, + EventIndex: 0, + Payload: payload, + } +} + +// createFTWithdrawnEvent creates a CCF-encoded FungibleToken.Withdrawn event +func createFTWithdrawnEvent(t *testing.T, eventType flow.EventType, txIndex uint32, fromAddr *flow.Address) flow.Event { + var fromValue cadence.Value + if fromAddr != nil { + fromValue = cadence.NewOptional(cadence.NewAddress(*fromAddr)) + } else { + fromValue = cadence.NewOptional(nil) + } + + location := common.NewAddressLocation(nil, common.Address{}, "FungibleToken") + eventCadenceType := cadence.NewEventType( + location, + "FungibleToken.Withdrawn", + []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "amount", Type: cadence.UFix64Type}, + {Identifier: "from", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "fromUUID", Type: cadence.UInt64Type}, + {Identifier: "withdrawnUUID", Type: cadence.UInt64Type}, + {Identifier: "balanceAfter", Type: cadence.UFix64Type}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String("A.0x1.FlowToken.Vault"), + cadence.UFix64(50_00000000), + fromValue, + cadence.UInt64(1), + cadence.UInt64(3), + cadence.UFix64(150_00000000), + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: eventType, + TransactionIndex: txIndex, + EventIndex: 0, + Payload: payload, + } +} + +// createNFTDepositedEvent creates a CCF-encoded NonFungibleToken.Deposited event +func createNFTDepositedEvent(t *testing.T, eventType flow.EventType, txIndex uint32, toAddr *flow.Address) flow.Event { + var toValue cadence.Value + if toAddr != nil { + toValue = cadence.NewOptional(cadence.NewAddress(*toAddr)) + } else { + toValue = cadence.NewOptional(nil) + } + + location := common.NewAddressLocation(nil, common.Address{}, "NonFungibleToken") + eventCadenceType := cadence.NewEventType( + location, + "NonFungibleToken.Deposited", + []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "uuid", Type: cadence.UInt64Type}, + {Identifier: "to", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "collectionUUID", Type: cadence.UInt64Type}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String("A.0x1.TopShot.NFT"), + cadence.UInt64(42), + cadence.UInt64(100), + toValue, + cadence.UInt64(5), + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: eventType, + TransactionIndex: txIndex, + EventIndex: 0, + Payload: payload, + } +} + +// createNFTWithdrawnEvent creates a CCF-encoded NonFungibleToken.Withdrawn event +func createNFTWithdrawnEvent(t *testing.T, eventType flow.EventType, txIndex uint32, fromAddr *flow.Address) flow.Event { + var fromValue cadence.Value + if fromAddr != nil { + fromValue = cadence.NewOptional(cadence.NewAddress(*fromAddr)) + } else { + fromValue = cadence.NewOptional(nil) + } + + location := common.NewAddressLocation(nil, common.Address{}, "NonFungibleToken") + eventCadenceType := cadence.NewEventType( + location, + "NonFungibleToken.Withdrawn", + []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "uuid", Type: cadence.UInt64Type}, + {Identifier: "from", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "providerUUID", Type: cadence.UInt64Type}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String("A.0x1.TopShot.NFT"), + cadence.UInt64(42), + cadence.UInt64(100), + fromValue, + cadence.UInt64(5), + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: eventType, + TransactionIndex: txIndex, + EventIndex: 0, + Payload: payload, + } +} diff --git a/module/state_synchronization/indexer/extended/bootstrap/bootstrap.go b/module/state_synchronization/indexer/extended/bootstrap/bootstrap.go new file mode 100644 index 00000000000..f3409c24b8f --- /dev/null +++ b/module/state_synchronization/indexer/extended/bootstrap/bootstrap.go @@ -0,0 +1,187 @@ +package bootstrap + +import ( + "fmt" + "time" + + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/execution" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + pstorage "github.com/onflow/flow-go/storage/pebble" + "github.com/onflow/flow-go/utils" +) + +type Storage struct { + DB storage.DB + AccountTransactionsBootstrapper storage.AccountTransactionsBootstrapper + FungibleTokenTransfersBootstrapper storage.FungibleTokenTransfersBootstrapper + NonFungibleTokenTransfersBootstrapper storage.NonFungibleTokenTransfersBootstrapper + ScheduledTransactionsBootstrapper storage.ScheduledTransactionsIndexBootstrapper + ContractDeploymentsBootstrapper storage.ContractDeploymentsIndexBootstrapper +} + +// OpenExtendedIndexDB opens the pebble database for extended indexes and creates the account +// transactions bootstrapper store. This must run synchronously during node initialization so +// that the store is available for consumers (e.g. the ExtendedBackend) before async components +// start. +// +// No error returns are expected during normal operation. +func OpenExtendedIndexDB( + log zerolog.Logger, + dbPath string, + sealedRootHeight uint64, +) (Storage, error) { + indexerDB, err := pstorage.SafeOpen( + log.With().Str("pebbledb", "indexer").Logger(), + dbPath, + ) + if err != nil { + return Storage{}, fmt.Errorf("could not open indexer db: %w", err) + } + + indexerStorageDB := pebbleimpl.ToDB(indexerDB) + accountTxStore, err := indexes.NewAccountTransactionsBootstrapper(indexerStorageDB, sealedRootHeight) + if err != nil { + if closeErr := indexerDB.Close(); closeErr != nil { + log.Error().Err(closeErr).Msg("error closing indexer db") + } + return Storage{}, fmt.Errorf("could not create account transactions index: %w", err) + } + + ftStore, err := indexes.NewFungibleTokenTransfersBootstrapper(indexerStorageDB, sealedRootHeight) + if err != nil { + if closeErr := indexerDB.Close(); closeErr != nil { + log.Error().Err(closeErr).Msg("error closing indexer db") + } + return Storage{}, fmt.Errorf("could not create fungible token transfers index: %w", err) + } + + nftStore, err := indexes.NewNonFungibleTokenTransfersBootstrapper(indexerStorageDB, sealedRootHeight) + if err != nil { + if closeErr := indexerDB.Close(); closeErr != nil { + log.Error().Err(closeErr).Msg("error closing indexer db") + } + return Storage{}, fmt.Errorf("could not create non-fungible token transfers index: %w", err) + } + + scheduledTxStore, err := indexes.NewScheduledTransactionsBootstrapper(indexerStorageDB, sealedRootHeight) + if err != nil { + if closeErr := indexerDB.Close(); closeErr != nil { + log.Error().Err(closeErr).Msg("error closing indexer db") + } + return Storage{}, fmt.Errorf("could not create scheduled transactions index: %w", err) + } + + contractDeploymentsStore, err := indexes.NewContractDeploymentsBootstrapper(indexerStorageDB, sealedRootHeight) + if err != nil { + if closeErr := indexerDB.Close(); closeErr != nil { + log.Error().Err(closeErr).Msg("error closing indexer db") + } + return Storage{}, fmt.Errorf("could not create contract deployments index: %w", err) + } + + return Storage{ + DB: indexerStorageDB, + AccountTransactionsBootstrapper: accountTxStore, + FungibleTokenTransfersBootstrapper: ftStore, + NonFungibleTokenTransfersBootstrapper: nftStore, + ScheduledTransactionsBootstrapper: scheduledTxStore, + ContractDeploymentsBootstrapper: contractDeploymentsStore, + }, nil +} + +func BootstrapIndexers( + log zerolog.Logger, + chainID flow.ChainID, + extendedStorage Storage, + lockManager storage.LockManager, + state protocol.State, + index storage.Index, + headers storage.Headers, + guarantees storage.Guarantees, + collections storage.Collections, + events storage.Events, + results storage.LightTransactionResults, + scriptExecutor execution.ScriptExecutor, + registers storage.RegisterIndex, + backfillDelay time.Duration, +) (*extended.ExtendedIndexer, error) { + accountTransactions, err := extended.NewAccountTransactions( + log, + extendedStorage.AccountTransactionsBootstrapper, + chainID, + utils.NotNil(lockManager), + ) + if err != nil { + return nil, fmt.Errorf("could not create account transactions indexer: %w", err) + } + + extendedMetrics := metrics.NewExtendedIndexingCollector() + + ftTransfers := extended.NewFungibleTokenTransfers( + log, + chainID, + extendedStorage.FungibleTokenTransfersBootstrapper, + extendedMetrics, + ) + + nftTransfers := extended.NewNonFungibleTokenTransfers( + log, + chainID, + extendedStorage.NonFungibleTokenTransfersBootstrapper, + extendedMetrics, + ) + + scheduledTransactions := extended.NewScheduledTransactions( + log, + extendedStorage.ScheduledTransactionsBootstrapper, + scriptExecutor, + extendedMetrics, + chainID, + ) + + contracts := extended.NewContracts( + log, + extendedStorage.ContractDeploymentsBootstrapper, + registers, + scriptExecutor, + extendedMetrics, + ) + + extendedIndexers := []extended.Indexer{ + accountTransactions, + ftTransfers, + nftTransfers, + scheduledTransactions, + contracts, + } + + extendedIndexer, err := extended.NewExtendedIndexer( + log, + extendedMetrics, + extendedStorage.DB, + lockManager, + state, + index, + headers, + guarantees, + collections, + events, + results, + extendedIndexers, + chainID, + backfillDelay, + ) + if err != nil { + return nil, fmt.Errorf("could not create extended indexer: %w", err) + } + + return extendedIndexer, nil +} diff --git a/module/state_synchronization/indexer/extended/contracts.go b/module/state_synchronization/indexer/extended/contracts.go new file mode 100644 index 00000000000..39ab5c3e37d --- /dev/null +++ b/module/state_synchronization/indexer/extended/contracts.go @@ -0,0 +1,303 @@ +package extended + +import ( + "bytes" + "errors" + "fmt" + "time" + + "github.com/jordanschalm/lockctx" + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/fvm/storage/state" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" + "github.com/onflow/flow-go/storage" +) + +const ( + contractsIndexerName = "contracts" + + flowAccountContractAdded flow.EventType = "flow.AccountContractAdded" + flowAccountContractUpdated flow.EventType = "flow.AccountContractUpdated" + flowAccountContractRemoved flow.EventType = "flow.AccountContractRemoved" + + // contractsBootstrapMaxIterationDuration is the maximum time the bootstrap scan holds a + // pebble iterator open before releasing it and resuming from a cursor. Pebble defers + // compaction while any iterator is open, so keeping iterations short lets compaction run + // between batches and prevents read-amplification from building up during the potentially + // hours-long initial scan. + contractsBootstrapMaxIterationDuration = 30 * time.Second +) + +// snapshotProvider is the subset of execution.ScriptExecutor used by the Contracts indexer. +type snapshotProvider interface { + GetStorageSnapshot(height uint64) (snapshot.StorageSnapshot, error) + RegisterValue(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) +} + +// registerScanner can efficiently scan all registers with a given key prefix in a single +// forward pass. Used during bootstrap to load all deployed contracts without iterating +// every account address. +type registerScanner interface { + ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] +} + +// Contracts indexes contract deployment lifecycle events and writes to the contract deployments +// index. Handles [flow.AccountContractAdded] and [flow.AccountContractUpdated] events. +// [flow.AccountContractRemoved] is not currently permitted; encountering one returns an error. +// +// On first bootstrapping, the indexer will load all deployed contracts from storage at the bootstrap +// height and include placeholder deployment objects for all contracts that are deployed at that height. +// Any contracts that are deployed in the same block as the bootstrap height will not have placeholder +// deployment objects created since there are already deployment objects for those contracts. +// +// CAUTION: Not safe for concurrent use. +type Contracts struct { + log zerolog.Logger + metrics module.ExtendedIndexingMetrics + store storage.ContractDeploymentsIndexBootstrapper + registers registerScanner + scriptExecutor snapshotProvider +} + +var _ Indexer = (*Contracts)(nil) +var _ IndexProcessor[access.ContractDeployment, ContractsMetadata] = (*Contracts)(nil) + +// ContractsMetadata contains indexing metrics for a single block's contract events. +type ContractsMetadata struct { + Created int + Updated int +} + +// NewContracts creates a new Contracts indexer backed by store. +func NewContracts( + log zerolog.Logger, + store storage.ContractDeploymentsIndexBootstrapper, + registers registerScanner, + scriptExecutor snapshotProvider, + metrics module.ExtendedIndexingMetrics, +) *Contracts { + return &Contracts{ + log: log.With().Str("component", "contracts_indexer").Logger(), + metrics: metrics, + store: store, + registers: registers, + scriptExecutor: scriptExecutor, + } +} + +// Name returns the name of this indexer. +func (c *Contracts) Name() string { return contractsIndexerName } + +// NextHeight returns the next block height to index. +// +// No error returns are expected during normal operation. +func (c *Contracts) NextHeight() (uint64, error) { + return nextHeight(c.store) +} + +// IndexBlockData processes one block's events and transactions and updates the contract +// deployments index. +// +// The caller must hold the [storage.LockIndexContractDeployments] lock until the batch is committed. +// +// CAUTION: Not safe for concurrent use. +// +// Expected error returns during normal operations: +// - [ErrAlreadyIndexed]: if the data is already indexed for the height +func (c *Contracts) IndexBlockData(lctx lockctx.Proof, data BlockData, rw storage.ReaderBatchWriter) error { + deployments, meta, err := c.ProcessBlockData(data) + if err != nil { + return err + } + + // if storage is not bootstrapped yet, do an initial load of all deployed contracts and include it in + // the initial store operation. + // TODO: avoid doing this check on every block. in the mean time, this is a fast check + if bootstrapHeight, isInitialized := c.store.UninitializedFirstHeight(); !isInitialized { + // keep track of the contracts with deployments in this block. these can be skipped during the + // initial load since the deployment object is already created. + updatedContracts := make(map[string]bool, len(deployments)) + for _, deployment := range deployments { + updatedContracts[access.ContractID(deployment.Address, deployment.ContractName)] = true + } + + // TODO: this will currently load all contracts into memory, then store them in one large batch. + // this is probably ok for now since there is a relatively small number of contracts. This should + // be updated to allow storing the contracts in smaller batches. + + loader := newDeployedContractsLoader(c.log, c.scriptExecutor, c.registers) + bootstrapContracts, err := loader.Load(bootstrapHeight, updatedContracts) + if err != nil { + return fmt.Errorf("failed to load deployed contracts: %w", err) + } + deployments = append(deployments, bootstrapContracts...) + } + + if err := c.store.Store(lctx, rw, data.Header.Height, deployments); err != nil { + if errors.Is(err, storage.ErrAlreadyExists) { + return ErrAlreadyIndexed + } + return fmt.Errorf("failed to store contract deployments for block %s: %w", data.Header.ID(), err) + } + + c.metrics.ContractDeploymentIndexed(meta.Created, meta.Updated) // ignores bootstrap deployments + return nil +} + +// ProcessBlockData processes the block data and returns the indexed contract deployment entries +// along with metadata containing the counts of created and updated contracts. +// +// No error returns are expected during normal operation. +func (c *Contracts) ProcessBlockData(data BlockData) ([]access.ContractDeployment, ContractsMetadata, error) { + deployments, created, updated, err := c.collectDeployments(data) + if err != nil { + return nil, ContractsMetadata{}, fmt.Errorf("failed to collect contract deployments for block %s: %w", data.Header.ID(), err) + } + + return deployments, ContractsMetadata{Created: created, Updated: updated}, nil +} + +// collectDeployments iterates the block events and builds a [access.ContractDeployment] for +// each AccountContractAdded or AccountContractUpdated event found. Returns the deployments +// and the counts of created and updated contracts. +// +// No error returns are expected during normal operation. +func (c *Contracts) collectDeployments(data BlockData) (deployments []access.ContractDeployment, created, updated int, err error) { + retriever := newContractRetriever(c.scriptExecutor, data.Header.Height) + + for _, event := range data.Events { + switch event.Type { + case flowAccountContractAdded: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, 0, 0, fmt.Errorf("failed to decode %s event payload: %w", event.Type, err) + } + e, err := events.DecodeAccountContractAdded(cadenceEvent) + if err != nil { + return nil, 0, 0, fmt.Errorf("failed to decode %s event: %w", event.Type, err) + } + + // script executor gets data at the end of the block, so code here should be the updated version + code, err := retriever.contractCode(e.Address, e.ContractName, data.Header.Height) + if err != nil { + return nil, 0, 0, fmt.Errorf("failed to get contract code: %w", err) + } + + // make sure the hash of the code fetched from state matches the hash in the event + if !bytes.Equal(e.CodeHash, access.CadenceCodeHash(code)) { + return nil, 0, 0, fmt.Errorf("code hash mismatch for %s event: %s", event.Type, e.ContractName) + } + + deployments = append(deployments, access.ContractDeployment{ + ContractName: e.ContractName, + Address: e.Address, + BlockHeight: data.Header.Height, + TransactionID: event.TransactionID, + TransactionIndex: event.TransactionIndex, + EventIndex: event.EventIndex, + Code: code, + CodeHash: e.CodeHash, + }) + created++ + + case flowAccountContractUpdated: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, 0, 0, fmt.Errorf("failed to decode %s event payload: %w", event.Type, err) + } + e, err := events.DecodeAccountContractUpdated(cadenceEvent) + if err != nil { + return nil, 0, 0, fmt.Errorf("failed to decode %s event: %w", event.Type, err) + } + + // script executor gets data at the end of the block, so code here should be the updated version + code, err := retriever.contractCode(e.Address, e.ContractName, data.Header.Height) + if err != nil { + return nil, 0, 0, fmt.Errorf("failed to get account code: %w", err) + } + + // make sure the hash of the code fetched from state matches the hash in the event + if !bytes.Equal(e.CodeHash, access.CadenceCodeHash(code)) { + return nil, 0, 0, fmt.Errorf("code hash mismatch for %s event: %s", event.Type, e.ContractName) + } + + deployments = append(deployments, access.ContractDeployment{ + ContractName: e.ContractName, + Address: e.Address, + BlockHeight: data.Header.Height, + TransactionID: event.TransactionID, + TransactionIndex: event.TransactionIndex, + EventIndex: event.EventIndex, + Code: code, + CodeHash: e.CodeHash, + }) + updated++ + + case flowAccountContractRemoved: + // contract removal is not currently supported. receiving this event is unexpected. + // + // Eventually, we can indicated deleted by setting the code to nil and adding the + // `IsDeleted` flag. + return nil, 0, 0, fmt.Errorf("unexpected %s event in block %s tx %s: not supported", + event.Type, data.Header.ID(), event.TransactionID) + } + } + + return deployments, created, updated, nil +} + +// contractRetriever is a helper for retrieving contract code from the snapshot at the given height. +// It lazily sets up the accounts instance, so unused instances are cheap to create. +// +// CAUTION: Not safe for concurrent use. +type contractRetriever struct { + height uint64 + accounts environment.Accounts + scriptExecutor snapshotProvider +} + +func newContractRetriever(scriptExecutor snapshotProvider, height uint64) *contractRetriever { + return &contractRetriever{ + height: height, + scriptExecutor: scriptExecutor, + } +} + +// contractCode returns the code for the given contract at the given height. +// +// CAUTION: Not safe for concurrent use. +// +// No error returns are expected during normal operation. +func (c *contractRetriever) contractCode( + address flow.Address, + contractName string, + height uint64, +) ([]byte, error) { + if c.height != height { + return nil, fmt.Errorf("height mismatch: %d != %d", c.height, height) + } + + // lazily setup accounts since many blocks will not have any contract updates. + if c.accounts == nil { + snapshot, err := c.scriptExecutor.GetStorageSnapshot(height) + if err != nil { + return nil, fmt.Errorf("failed to get storage snapshot: %w", err) + } + + txnState := state.NewTransactionState(snapshot, state.DefaultParameters()) + c.accounts = environment.NewAccounts(txnState) + } + + code, err := c.accounts.GetContract(contractName, address) + if err != nil { + return nil, fmt.Errorf("error while getting contract: %w", err) + } + + return code, nil +} diff --git a/module/state_synchronization/indexer/extended/contracts_loader.go b/module/state_synchronization/indexer/extended/contracts_loader.go new file mode 100644 index 00000000000..8b3bbecef22 --- /dev/null +++ b/module/state_synchronization/indexer/extended/contracts_loader.go @@ -0,0 +1,210 @@ +package extended + +import ( + "fmt" + "time" + + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/fvm/environment" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/util" + "github.com/onflow/flow-go/utils/slices" +) + +// deployedContractsLoader is a helper for loading deployed contracts from storage at the given height. +// It scans all code registers at the given height and returns a [access.ContractDeployment] placeholder record +// for each deployed contract. +// +// All loaded contracts have their IsPlaceholder flag set to true, their BlockHeight set to +// the scanned height, and the TransactionID, TxIndex, and EventIndex fields are undefined (0). +// +// CAUTION: Not safe for concurrent use. +type deployedContractsLoader struct { + log zerolog.Logger + scriptExecutor snapshotProvider + registers registerScanner +} + +func newDeployedContractsLoader( + log zerolog.Logger, + scriptExecutor snapshotProvider, + registers registerScanner, +) *deployedContractsLoader { + return &deployedContractsLoader{ + log: log, + scriptExecutor: scriptExecutor, + registers: registers, + } +} + +// load scans all code registers at the given height and returns a +// access.ContractDeployment placeholder record for each deployed contract not already +// covered by seenContracts. +// +// All loaded contracts have their IsPlaceholder flag set to true, their BlockHeight set to +// the scanned height, and the TransactionID, TxIndex, and EventIndex fields are undefined (0). +// +// CAUTION: Not safe for concurrent use. +// +// No error returns are expected during normal operation. +func (c *deployedContractsLoader) Load(height uint64, seenContracts map[string]bool) ([]access.ContractDeployment, error) { + var deployments []access.ContractDeployment + var deletedCount int + start := time.Now() + defer func() { + c.log.Info(). + Uint64("height", height). + Int("contracts", len(deployments)). + Int("skipped_updated_in_block", len(seenContracts)). + Int("deleted", deletedCount). + Str("duration", time.Since(start).String()). + Msg("loaded contracts during bootstrap") + }() + + // log progress since this may be a long operation + progress := util.LogProgress(c.log, + // use the upper byte of the address as the progress total + util.DefaultLogProgressConfig("loading contracts", 255), + ) + + lastAddressByte := 0 + logProgress := func(addressByte byte) { + current := int(addressByte) + if diff := current - lastAddressByte; diff > 0 { + progress(diff) + lastAddressByte = current + } + } + + // loadedContracts maps contracts in initial scan + // [address] → [contract name] → [index in deployments slice] + // Used after the scan to mark deleted contracts and verify all expected contracts are present. + loadedContracts := make(map[flow.Address]map[string]int) + + // Scan all contract code registers. This could take a long time, so interrupt the scan every + // [contractsBootstrapMaxIterationDuration] and release the iterator to avoid blocking compaction + // for too long. + var lastRegisterID *flow.RegisterID + for { + batchStart := time.Now() + timedOut := false + + for item, err := range c.registers.ByKeyPrefix(flow.CodeKeyPrefix, height, lastRegisterID) { + if err != nil { + return nil, fmt.Errorf("error scanning contract code registers: %w", err) + } + + registerID := item.Cursor() + deployment, isNew, err := c.parseContractRegister(registerID, item.Value, seenContracts, height) + if err != nil { + return nil, fmt.Errorf("error processing contract: %w", err) + } + + if isNew { + deployments = append(deployments, deployment) + + if _, ok := loadedContracts[deployment.Address]; !ok { + loadedContracts[deployment.Address] = make(map[string]int) + } + loadedContracts[deployment.Address][deployment.ContractName] = len(deployments) - 1 + } + + logProgress(registerID.Owner[0]) + + // If we've held the iterator open too long, record the lastRegisterID and release it so + // compaction can proceed before we resume. + if time.Since(batchStart) >= contractsBootstrapMaxIterationDuration { + lastRegisterID = ®isterID + timedOut = true + break + } + } + + if !timedOut { + break + } + } + + // For each address with loaded contracts, fetch the names register once to: + // 1. Set IsDeleted for contracts whose names are absent from the register + // 2. Verify every name in the register has a corresponding deployment (loaded here or already + // seen in the current block via seenContracts). + deletedCount = 0 + for address, byName := range loadedContracts { + registerValue, err := c.scriptExecutor.RegisterValue(flow.ContractNamesRegisterID(address), height) + if err != nil { + return nil, fmt.Errorf("error getting contract names for %s: %w", address, err) + } + + contractNames, err := environment.DecodeContractNames(registerValue) + if err != nil { + return nil, fmt.Errorf("error decoding contract names for %s: %w", address, err) + } + + registeredNames := slices.ToMap(contractNames) + + // when a contract is deleted, its name is removed from the contract names register. In the + // current implementation, its code is also set to nil. However, there are contracts on mainnet + // where the content is not nil, but the name is removed. Handle both cases by using the + // contract names register as the source of truth. + for name, idx := range byName { + if _, ok := registeredNames[name]; !ok { + deployments[idx].IsDeleted = true + deletedCount++ + } + } + + // verify that all contracts listed in the contract names register are present in the loaded contracts. + for name := range registeredNames { + if _, ok := byName[name]; !ok { + if !seenContracts[access.ContractID(address, name)] { + return nil, fmt.Errorf("contract %q not found in initial load for %s", name, address) + } + } + } + } + + logProgress(255) // log to 100% + + return deployments, nil +} + +// parseContractRegister parses a contract register and returns a [access.ContractDeployment] placeholder record. +// Returns false and an empty deployment if the contract was already seen. +// The returned deployment has BlockHeight set to height. +// +// No error returns are expected during normal operation. +func (c *deployedContractsLoader) parseContractRegister( + reg flow.RegisterID, + getRegistryValue func() (flow.RegisterValue, error), + seenContracts map[string]bool, + height uint64, +) (access.ContractDeployment, bool, error) { + if reg.Owner == "" { + return access.ContractDeployment{}, false, fmt.Errorf("found contract with empty owner: %q", reg) + } + + address := flow.BytesToAddress([]byte(reg.Owner)) + contractName := flow.KeyContractName(reg.Key) + contractID := access.ContractID(address, contractName) + + if seenContracts[contractID] { + return access.ContractDeployment{}, false, nil + } + + code, err := getRegistryValue() + if err != nil { + return access.ContractDeployment{}, false, fmt.Errorf("error reading contract code for %s: %w", contractID, err) + } + + return access.ContractDeployment{ + ContractName: contractName, + Address: address, + BlockHeight: height, + Code: code, + CodeHash: access.CadenceCodeHash(code), + IsPlaceholder: true, + }, true, nil +} diff --git a/module/state_synchronization/indexer/extended/contracts_test.go b/module/state_synchronization/indexer/extended/contracts_test.go new file mode 100644 index 00000000000..3712e455219 --- /dev/null +++ b/module/state_synchronization/indexer/extended/contracts_test.go @@ -0,0 +1,1010 @@ +package extended_test + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/fxamacker/cbor/v2" + "github.com/jordanschalm/lockctx" + "github.com/onflow/cadence" + "github.com/onflow/cadence/encoding/ccf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/fvm/environment" + fvmsnapshot "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + executionmock "github.com/onflow/flow-go/module/execution/mock" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes" + iterutil "github.com/onflow/flow-go/storage/indexes/iterator" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" + + . "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" +) + +const ( + // contractsBootstrapHeight is the height of the first indexed block. + // The index bootstraps at this height (loadDeployedContracts is called here). + contractsBootstrapHeight = uint64(100) + + // contractsEventHeight is the height of the block that contains contract events. + // Events at this height are processed AFTER the index is bootstrapped. + contractsEventHeight = uint64(101) + + // Contract event type names used to build test events. + eventContractAdded = "flow.AccountContractAdded" + eventContractUpdated = "flow.AccountContractUpdated" + eventContractRemoved = "flow.AccountContractRemoved" +) + +// collectContractPage is a test helper that creates an iterator from the store and collects +// results via CollectResults, returning the deployments slice. No filter or cursor is applied. +func collectContractPage(t *testing.T, iter storage.ContractDeploymentIterator, limit uint32) []access.ContractDeployment { + t.Helper() + collected, _, err := iterutil.CollectResults(iter, limit, nil) + require.NoError(t, err) + return collected +} + +// ===== Happy-path tests ===== + +// TestContractsIndexer_NextHeight_NotBootstrapped verifies that NextHeight returns the +// configured first height before any blocks have been indexed. +func TestContractsIndexer_NextHeight_NotBootstrapped(t *testing.T) { + t.Parallel() + + runWithContractsIndexer(t, contractsBootstrapHeight, nil, nil, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, _ storage.LockManager, _ storage.DB) { + height, err := indexer.NextHeight() + require.NoError(t, err) + assert.Equal(t, contractsBootstrapHeight, height) + }) +} + +// TestContractsIndexer_ContractAdded verifies that an AccountContractAdded event creates +// a deployment entry with all fields correctly stored. +func TestContractsIndexer_ContractAdded(t *testing.T) { + t.Parallel() + + deployingTxID := unittest.IdentifierFixture() + address := unittest.RandomAddressFixture() + contractName := "MyContract" + code := []byte("access(all) contract MyContract {}") + codeHash := access.CadenceCodeHash(code) + + expected := access.ContractDeployment{ + Address: address, + ContractName: contractName, + BlockHeight: contractsEventHeight, + TransactionID: deployingTxID, + TransactionIndex: 0, + EventIndex: 0, + Code: code, + CodeHash: codeHash, + } + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, store storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Step 1: bootstrap block — no events, empty snapshot. + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: bootstrapHeader, Events: []flow.Event{}}) + require.NoError(t, err) + + // Step 2: event block — contract deployed. + eventHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + snap := makeContractSnapshot(t, address, map[string][]byte{contractName: code}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight). + Return(snap, nil).Once() + + event := makeContractEvent(t, eventContractAdded, address, contractName, codeHash, 0, 0) + event.TransactionID = deployingTxID + err = indexContractsBlock(t, indexer, lm, db, BlockData{Header: eventHeader, Events: []flow.Event{event}}) + require.NoError(t, err) + + deployment, err := store.ByContract(address, contractName) + require.NoError(t, err) + + assertContractDeployment(t, expected, deployment) + }) +} + +// TestContractsIndexer_ContractUpdated verifies that an AccountContractUpdated event at a +// subsequent block creates a new deployment entry for the same contract. +func TestContractsIndexer_ContractAddedThenUpdated(t *testing.T) { + t.Parallel() + + address := unittest.RandomAddressFixture() + contractName := "MyContract" + codeV1 := []byte("access(all) contract MyContract { let x: Int; init() { self.x = 1 } }") + codeV2 := []byte("access(all) contract MyContract { let x: Int; init() { self.x = 2 } }") + codeHashV1 := access.CadenceCodeHash(codeV1) + codeHashV2 := access.CadenceCodeHash(codeV2) + + updateTxID := unittest.IdentifierFixture() + addTxID := unittest.IdentifierFixture() + + expectedAdd := access.ContractDeployment{ + Address: address, + ContractName: contractName, + BlockHeight: contractsEventHeight, + TransactionID: addTxID, + Code: codeV1, + CodeHash: codeHashV1, + } + expectedUpdate := access.ContractDeployment{ + Address: address, + ContractName: contractName, + BlockHeight: contractsEventHeight + 1, + TransactionID: updateTxID, + TransactionIndex: 1, + Code: codeV2, + CodeHash: codeHashV2, + } + + addEvent := makeContractEvent(t, eventContractAdded, address, contractName, codeHashV1, 0, 0) + addEvent.TransactionID = addTxID + + updateEvent := makeContractEvent(t, eventContractUpdated, address, contractName, codeHashV2, 1, 0) + updateEvent.TransactionID = updateTxID + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, store storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Bootstrap block. + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: bootstrapHeader, Events: []flow.Event{}}) + require.NoError(t, err) + + firstHeight, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, contractsBootstrapHeight, firstHeight) + + allIter, err := store.All(nil) + require.NoError(t, err) + assert.Empty(t, collectContractPage(t, allIter, 1)) + + // Height 101: AccountContractAdded + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + snap1 := makeContractSnapshot(t, address, map[string][]byte{contractName: codeV1}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight).Return(snap1, nil).Once() + + err = indexContractsBlock(t, indexer, lm, db, BlockData{Header: header1, Events: []flow.Event{addEvent}}) + require.NoError(t, err) + + // Height 102: AccountContractUpdated + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight+1)) + snap2 := makeContractSnapshot(t, address, map[string][]byte{contractName: codeV2}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight+1).Return(snap2, nil).Once() + + err = indexContractsBlock(t, indexer, lm, db, BlockData{Header: header2, Events: []flow.Event{updateEvent}}) + require.NoError(t, err) + + latestHeight, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, contractsEventHeight+1, latestHeight) + + // ByContract returns the most recent deployment (height 102). + latest, err := store.ByContract(address, contractName) + require.NoError(t, err) + assertContractDeployment(t, expectedUpdate, latest) + + // DeploymentsByContract returns both deployments, most recent first. + depIter, err := store.DeploymentsByContract(address, contractName, nil) + require.NoError(t, err) + deployments := collectContractPage(t, depIter, 10) + require.Len(t, deployments, 2) + assertContractDeployment(t, expectedUpdate, deployments[0]) + assertContractDeployment(t, expectedAdd, deployments[1]) + }) +} + +// TestContractsIndexer_MultipleContractsInOneBlock verifies that multiple AccountContractAdded +// events in a single block each produce a separate deployment entry. It covers two sub-cases: +// two contracts on the same address (exercising per-block snapshot caching — GetStorageSnapshot +// must be called only once for that address) and one contract on a different address. +func TestContractsIndexer_MultipleContractsInOneBlock(t *testing.T) { + t.Parallel() + + addr1 := unittest.RandomAddressFixture() + addr2 := unittest.RandomAddressFixture() + codeA := []byte("access(all) contract Alpha {}") + codeB := []byte("access(all) contract Beta {}") + codeG := []byte("access(all) contract Gamma {}") + hashA := access.CadenceCodeHash(codeA) + hashB := access.CadenceCodeHash(codeB) + hashG := access.CadenceCodeHash(codeG) + + expectedAlpha := access.ContractDeployment{ + Address: addr1, + ContractName: "Alpha", + BlockHeight: contractsEventHeight, + Code: codeA, + CodeHash: hashA, + } + expectedBeta := access.ContractDeployment{ + Address: addr1, + ContractName: "Beta", + BlockHeight: contractsEventHeight, + EventIndex: 1, + Code: codeB, + CodeHash: hashB, + } + expectedGamma := access.ContractDeployment{ + Address: addr2, + ContractName: "Gamma", + BlockHeight: contractsEventHeight, + TransactionIndex: 1, + Code: codeG, + CodeHash: hashG, + } + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, store storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Bootstrap block. + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: bootstrapHeader, Events: []flow.Event{}}) + require.NoError(t, err) + + // Event block: addr1 deploys Alpha and Beta (same account, caching exercised), + // addr2 deploys Gamma. GetStorageSnapshot is called exactly once per the .Once() mock. + snap := makeMultiAccountSnapshot(t, + addr1, map[string][]byte{"Alpha": codeA, "Beta": codeB}, + addr2, map[string][]byte{"Gamma": codeG}, + ) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight).Return(snap, nil).Once() + + eventHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + eventA := makeContractEvent(t, eventContractAdded, addr1, "Alpha", hashA, 0, 0) + eventB := makeContractEvent(t, eventContractAdded, addr1, "Beta", hashB, 0, 1) + eventG := makeContractEvent(t, eventContractAdded, addr2, "Gamma", hashG, 1, 0) + err = indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: eventHeader, + Events: []flow.Event{eventA, eventB, eventG}, + }) + require.NoError(t, err) + + alpha, err := store.ByContract(addr1, "Alpha") + require.NoError(t, err) + assertContractDeployment(t, expectedAlpha, alpha) + + beta, err := store.ByContract(addr1, "Beta") + require.NoError(t, err) + assertContractDeployment(t, expectedBeta, beta) + + gamma, err := store.ByContract(addr2, "Gamma") + require.NoError(t, err) + assertContractDeployment(t, expectedGamma, gamma) + + // ByAddress returns only contracts for the requested account. + addr1Iter, err := store.ByAddress(addr1, nil) + require.NoError(t, err) + assert.Len(t, collectContractPage(t, addr1Iter, 10), 2) + + addr2Iter, err := store.ByAddress(addr2, nil) + require.NoError(t, err) + assert.Len(t, collectContractPage(t, addr2Iter, 10), 1) + + // All() returns all three contracts. + allIter, err := store.All(nil) + require.NoError(t, err) + assert.Len(t, collectContractPage(t, allIter, 10), 3) + }) +} + +// TestContractsIndexer_ByAddress verifies that ByAddress returns only contracts for the +// requested account, across multiple indexed blocks. +func TestContractsIndexer_ByAddress(t *testing.T) { + t.Parallel() + + addr1 := unittest.RandomAddressFixture() + addr2 := unittest.RandomAddressFixture() + code1 := []byte("access(all) contract Foo {}") + code2 := []byte("access(all) contract Bar {}") + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, store storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Bootstrap block. + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: bootstrapHeader, Events: []flow.Event{}}) + require.NoError(t, err) + + // Block 101: addr1 deploys Foo. + snap1 := makeContractSnapshot(t, addr1, map[string][]byte{"Foo": code1}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight). + Return(snap1, nil).Once() + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + err = indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{makeContractEvent(t, eventContractAdded, addr1, "Foo", access.CadenceCodeHash(code1), 0, 0)}, + }) + require.NoError(t, err) + + // Block 102: addr2 deploys Bar. + snap2 := makeContractSnapshot(t, addr2, map[string][]byte{"Bar": code2}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight+1). + Return(snap2, nil).Once() + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight+1)) + err = indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{makeContractEvent(t, eventContractAdded, addr2, "Bar", access.CadenceCodeHash(code2), 0, 0)}, + }) + require.NoError(t, err) + + // ByAddress(addr1) returns only Foo. + iter1, err := store.ByAddress(addr1, nil) + require.NoError(t, err) + deps1 := collectContractPage(t, iter1, 10) + require.Len(t, deps1, 1) + assert.Equal(t, addr1, deps1[0].Address) + assert.Equal(t, "Foo", deps1[0].ContractName) + + // ByAddress(addr2) returns only Bar. + iter2, err := store.ByAddress(addr2, nil) + require.NoError(t, err) + deps2 := collectContractPage(t, iter2, 10) + require.Len(t, deps2, 1) + assert.Equal(t, addr2, deps2[0].Address) + assert.Equal(t, "Bar", deps2[0].ContractName) + }) +} + +// TestContractsIndexer_BackfillMultipleBlocks verifies that starting the index at a root +// height and backfilling several subsequent blocks processes each block in order and accumulates +// deployment records correctly. +func TestContractsIndexer_BackfillMultipleBlocks(t *testing.T) { + t.Parallel() + + // Three distinct contracts deployed across three blocks. + addrs := make([]flow.Address, 3) + codes := make([][]byte, 3) + hashes := make([][]byte, 3) + for i := range addrs { + addrs[i] = unittest.RandomAddressFixture() + codes[i] = fmt.Appendf(nil, "access(all) contract C%d {}", i) + hashes[i] = access.CadenceCodeHash(codes[i]) + } + + scriptExecutor := executionmock.NewScriptExecutor(t) + firstHeight := contractsBootstrapHeight + runWithContractsIndexer(t, firstHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, store storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Root block: no events, but loadDeployedContracts is called. + root := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(firstHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: root, Events: []flow.Event{}}) + require.NoError(t, err) + + // Index three blocks, one contract added per block. + for i := range 3 { + h := firstHeight + uint64(i+1) + contractName := fmt.Sprintf("C%d", i) + snap := makeContractSnapshot(t, addrs[i], map[string][]byte{contractName: codes[i]}) + scriptExecutor.On("GetStorageSnapshot", h).Return(snap, nil).Once() + + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(h)) + event := makeContractEvent(t, eventContractAdded, addrs[i], contractName, hashes[i], 0, 0) + err = indexContractsBlock(t, indexer, lm, db, BlockData{Header: header, Events: []flow.Event{event}}) + require.NoError(t, err) + } + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, firstHeight+3, latest) + + // All() returns all three contracts. + allIter, err := store.All(nil) + require.NoError(t, err) + assert.Len(t, collectContractPage(t, allIter, 10), 3) + }) +} + +// TestContractsIndexer_Bootstrap_PreExistingContracts verifies that loadDeployedContracts +// finds contracts pre-loaded into the fakeRegisters and stores placeholder deployments for +// them, while skipping any contract already covered by the bootstrap block's own events. +func TestContractsIndexer_Bootstrap_PreExistingContracts(t *testing.T) { + t.Parallel() + + addr1 := unittest.RandomAddressFixture() + addr2 := unittest.RandomAddressFixture() + codeAlpha := []byte("access(all) contract Alpha {}") + codeBeta := []byte("access(all) contract Beta {}") + codeGamma := []byte("access(all) contract Gamma {}") + + // addr1 has Alpha and Beta pre-deployed; addr2 has Gamma. Alpha is also in the + // bootstrap block's events, so it should NOT get a placeholder. + registers := &fakeRegisters{ + Entries: []flow.RegisterEntry{ + {Key: flow.ContractRegisterID(addr1, "Alpha"), Value: codeAlpha}, + {Key: flow.ContractRegisterID(addr1, "Beta"), Value: codeBeta}, + {Key: flow.ContractRegisterID(addr2, "Gamma"), Value: codeGamma}, + }, + } + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, registers, scriptExecutor, func(indexer *Contracts, store storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Bootstrap block also deploys Alpha — that deployment gets a real record, not a placeholder. + alphaHash := access.CadenceCodeHash(codeAlpha) + snap := makeContractSnapshot(t, addr1, map[string][]byte{"Alpha": codeAlpha}) + scriptExecutor.On("GetStorageSnapshot", contractsBootstrapHeight).Return(snap, nil).Once() + + // loadDeployedContracts verifies the code-register scan against the contract names register. + scriptExecutor.On("RegisterValue", flow.ContractNamesRegisterID(addr1), contractsBootstrapHeight). + Return(encodeContractNames(t, "Alpha", "Beta"), nil) + scriptExecutor.On("RegisterValue", flow.ContractNamesRegisterID(addr2), contractsBootstrapHeight). + Return(encodeContractNames(t, "Gamma"), nil) + + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + alphaEvent := makeContractEvent(t, eventContractAdded, addr1, "Alpha", alphaHash, 0, 0) + err := indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: bootstrapHeader, + Events: []flow.Event{alphaEvent}, + }) + require.NoError(t, err) + + // Alpha: real deployment from the event — not a placeholder. + alpha, err := store.ByContract(addr1, "Alpha") + require.NoError(t, err) + assertContractDeployment(t, access.ContractDeployment{ + Address: addr1, + ContractName: "Alpha", + BlockHeight: contractsBootstrapHeight, + Code: codeAlpha, + CodeHash: alphaHash, + }, alpha) + assert.False(t, alpha.IsPlaceholder) + + // Beta: placeholder from loadDeployedContracts. + beta, err := store.ByContract(addr1, "Beta") + require.NoError(t, err) + assertContractDeployment(t, access.ContractDeployment{ + Address: addr1, + ContractName: "Beta", + BlockHeight: contractsBootstrapHeight, + Code: codeBeta, + CodeHash: access.CadenceCodeHash(codeBeta), + IsPlaceholder: true, + }, beta) + + // Gamma: placeholder from loadDeployedContracts. + gamma, err := store.ByContract(addr2, "Gamma") + require.NoError(t, err) + assertContractDeployment(t, access.ContractDeployment{ + Address: addr2, + ContractName: "Gamma", + BlockHeight: contractsBootstrapHeight, + Code: codeGamma, + CodeHash: access.CadenceCodeHash(codeGamma), + IsPlaceholder: true, + }, gamma) + + // All() returns all three contracts. + allIter, err := store.All(nil) + require.NoError(t, err) + assert.Len(t, collectContractPage(t, allIter, 10), 3) + }) +} + +// TestContractsIndexer_Bootstrap_MarksDeletedContracts verifies that loadDeployedContracts loads +// all code registers (including those with empty values representing deleted contracts) and marks +// them as deleted if their name is absent from the contract names register. The contract names +// register is the source of truth: contracts present in code registers but absent from the names +// register are indexed with IsDeleted=true. +func TestContractsIndexer_Bootstrap_MarksDeletedContracts(t *testing.T) { + t.Parallel() + + addr := unittest.RandomAddressFixture() + codeAlpha := []byte("access(all) contract Alpha {}") + codeBeta := []byte("access(all) contract Beta {}") + codeDeleted := []byte{} + + // Alpha and Beta are live; Deleted was removed (empty value in pebble). + registers := &fakeRegisters{ + Entries: []flow.RegisterEntry{ + {Key: flow.ContractRegisterID(addr, "Alpha"), Value: codeAlpha}, + {Key: flow.ContractRegisterID(addr, "Beta"), Value: codeBeta}, + {Key: flow.ContractRegisterID(addr, "Deleted"), Value: codeDeleted}, + }, + } + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, registers, scriptExecutor, func(indexer *Contracts, store storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // The contract names register only contains the two live contracts; the deleted one + // was already removed from it when the contract was removed. + scriptExecutor.On("RegisterValue", flow.ContractNamesRegisterID(addr), contractsBootstrapHeight). + Return(encodeContractNames(t, "Alpha", "Beta"), nil) + + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: bootstrapHeader, + Events: []flow.Event{}, + }) + require.NoError(t, err) + + // Alpha and Beta get placeholder deployments. + alpha, err := store.ByContract(addr, "Alpha") + require.NoError(t, err) + assertContractDeployment(t, access.ContractDeployment{ + Address: addr, + ContractName: "Alpha", + BlockHeight: contractsBootstrapHeight, + Code: codeAlpha, + CodeHash: access.CadenceCodeHash(codeAlpha), + IsPlaceholder: true, + }, alpha) + + beta, err := store.ByContract(addr, "Beta") + require.NoError(t, err) + assertContractDeployment(t, access.ContractDeployment{ + Address: addr, + ContractName: "Beta", + BlockHeight: contractsBootstrapHeight, + Code: codeBeta, + CodeHash: access.CadenceCodeHash(codeBeta), + IsPlaceholder: true, + }, beta) + + // Deleted contract is indexed but marked as deleted. + deleted, err := store.ByContract(addr, "Deleted") + require.NoError(t, err) + assertContractDeployment(t, access.ContractDeployment{ + Address: addr, + ContractName: "Deleted", + BlockHeight: contractsBootstrapHeight, + Code: codeDeleted, + CodeHash: access.CadenceCodeHash(codeDeleted), + IsPlaceholder: true, + IsDeleted: true, + }, deleted) + + // All() returns all three contracts (including deleted). + allIter, err := store.All(nil) + require.NoError(t, err) + assert.Len(t, collectContractPage(t, allIter, 10), 3) + }) +} + +// ===== ProcessBlockData tests ===== + +// TestContractsIndexer_ProcessBlockData_NoEvents verifies that ProcessBlockData returns +// empty entries and zero counts for a block with no contract events. +func TestContractsIndexer_ProcessBlockData_NoEvents(t *testing.T) { + t.Parallel() + + runWithContractsIndexer(t, contractsBootstrapHeight, nil, nil, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, _ storage.LockManager, _ storage.DB) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + + entries, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{}}) + require.NoError(t, err) + assert.Empty(t, entries) + assert.Equal(t, 0, meta.Created) + assert.Equal(t, 0, meta.Updated) + }) +} + +// TestContractsIndexer_ProcessBlockData_ContractAdded verifies that ProcessBlockData returns +// the correct deployment entry and metadata for an AccountContractAdded event. +func TestContractsIndexer_ProcessBlockData_ContractAdded(t *testing.T) { + t.Parallel() + + address := unittest.RandomAddressFixture() + contractName := "MyContract" + code := []byte("access(all) contract MyContract {}") + codeHash := access.CadenceCodeHash(code) + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, _ storage.LockManager, _ storage.DB) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + snap := makeContractSnapshot(t, address, map[string][]byte{contractName: code}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight).Return(snap, nil).Once() + + event := makeContractEvent(t, eventContractAdded, address, contractName, codeHash, 0, 0) + + entries, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{event}}) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, address, entries[0].Address) + assert.Equal(t, contractName, entries[0].ContractName) + assert.Equal(t, code, entries[0].Code) + assert.Equal(t, 1, meta.Created) + assert.Equal(t, 0, meta.Updated) + }) +} + +// TestContractsIndexer_ProcessBlockData_ContractUpdated verifies that ProcessBlockData returns +// the correct metadata counts when processing an AccountContractUpdated event. +func TestContractsIndexer_ProcessBlockData_ContractUpdated(t *testing.T) { + t.Parallel() + + address := unittest.RandomAddressFixture() + contractName := "MyContract" + code := []byte("access(all) contract MyContract { let x: Int; init() { self.x = 2 } }") + codeHash := access.CadenceCodeHash(code) + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, _ storage.LockManager, _ storage.DB) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + snap := makeContractSnapshot(t, address, map[string][]byte{contractName: code}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight).Return(snap, nil).Once() + + event := makeContractEvent(t, eventContractUpdated, address, contractName, codeHash, 0, 0) + + entries, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{event}}) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, 0, meta.Created) + assert.Equal(t, 1, meta.Updated) + }) +} + +// TestContractsIndexer_ProcessBlockData_DoesNotDependOnHeight verifies that ProcessBlockData +// can be called with any height without checking the indexer's height state. +func TestContractsIndexer_ProcessBlockData_DoesNotDependOnHeight(t *testing.T) { + t.Parallel() + + runWithContractsIndexer(t, contractsBootstrapHeight, nil, nil, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, _ storage.LockManager, _ storage.DB) { + // Use a height far beyond what the indexer expects + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight+100)) + + entries, _, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{}}) + require.NoError(t, err) + assert.Empty(t, entries) + }) +} + +// TestContractsIndexer_ProcessBlockData_ContractRemoved verifies that ProcessBlockData returns +// an error when encountering a ContractRemoved event (same as IndexBlockData). +func TestContractsIndexer_ProcessBlockData_ContractRemoved(t *testing.T) { + t.Parallel() + + address := unittest.RandomAddressFixture() + runWithContractsIndexer(t, contractsBootstrapHeight, nil, nil, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, _ storage.LockManager, _ storage.DB) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + removedEvent := makeContractEvent(t, eventContractRemoved, address, "SomeContract", make([]byte, 32), 0, 0) + + _, _, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{removedEvent}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "not supported") + }) +} + +// ===== Error and edge-case tests ===== + +// TestContractsIndexer_AlreadyIndexed verifies that attempting to index the same height +// twice returns ErrAlreadyIndexed. +func TestContractsIndexer_AlreadyIndexed(t *testing.T) { + t.Parallel() + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: header, Events: []flow.Event{}}) + require.NoError(t, err) + + err = indexContractsBlock(t, indexer, lm, db, BlockData{Header: header, Events: []flow.Event{}}) + require.ErrorIs(t, err, ErrAlreadyIndexed) + }) +} + +// TestContractsIndexer_ContractRemoved verifies that an AccountContractRemoved event +// returns an error (contract removal is not supported). collectDeployments fails before +// loadDeployedContracts, so no script executor is needed. +func TestContractsIndexer_ContractRemoved(t *testing.T) { + t.Parallel() + + address := unittest.RandomAddressFixture() + // collectDeployments errors for ContractRemoved before loadDeployedContracts runs, + // so no GetStorageSnapshot call is made — use nil executor. + runWithContractsIndexer(t, contractsBootstrapHeight, nil, nil, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + removedEvent := makeContractEvent(t, eventContractRemoved, address, "SomeContract", make([]byte, 32), 0, 0) + + err := indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{removedEvent}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "not supported") + }) +} + +// TestContractsIndexer_CodeHashMismatch verifies that when the code fetched from the snapshot +// does not match the hash in the event, IndexBlockData returns an error. +func TestContractsIndexer_CodeHashMismatch(t *testing.T) { + t.Parallel() + + address := unittest.RandomAddressFixture() + contractName := "Mismatch" + eventCode := []byte("access(all) contract Mismatch {}") + differentCode := []byte("access(all) contract Different {}") + // Event carries hash of eventCode, but the snapshot holds differentCode. + eventHash := access.CadenceCodeHash(eventCode) + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Bootstrap block. + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: bootstrapHeader, Events: []flow.Event{}}) + require.NoError(t, err) + + // Event block: snapshot has differentCode, but event hash is for eventCode. + eventHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + snap := makeContractSnapshot(t, address, map[string][]byte{contractName: differentCode}) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight).Return(snap, nil).Once() + + event := makeContractEvent(t, eventContractAdded, address, contractName, eventHash, 0, 0) + err = indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: eventHeader, + Events: []flow.Event{event}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "code hash mismatch") + }) +} + +// TestContractsIndexer_ScriptExecutorError verifies that an error from GetStorageSnapshot +// is propagated and causes IndexBlockData to fail. +func TestContractsIndexer_ScriptExecutorError(t *testing.T) { + t.Parallel() + + address := unittest.RandomAddressFixture() + scriptErr := fmt.Errorf("storage unavailable") + + scriptExecutor := executionmock.NewScriptExecutor(t) + runWithContractsIndexer(t, contractsBootstrapHeight, &fakeRegisters{}, scriptExecutor, func(indexer *Contracts, _ storage.ContractDeploymentsIndexBootstrapper, lm storage.LockManager, db storage.DB) { + // Bootstrap block. + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsBootstrapHeight)) + err := indexContractsBlock(t, indexer, lm, db, BlockData{Header: bootstrapHeader, Events: []flow.Event{}}) + require.NoError(t, err) + + // Event block: GetStorageSnapshot fails. + eventHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(contractsEventHeight)) + scriptExecutor.On("GetStorageSnapshot", contractsEventHeight).Return(nil, scriptErr).Once() + + codeHash := access.CadenceCodeHash([]byte("access(all) contract MyContract {}")) + event := makeContractEvent(t, eventContractAdded, address, "MyContract", codeHash, 0, 0) + + err = indexContractsBlock(t, indexer, lm, db, BlockData{ + Header: eventHeader, + Events: []flow.Event{event}, + }) + require.Error(t, err) + require.ErrorIs(t, err, scriptErr) + }) +} + +// TestContractsIndexer_NextHeight_MockErrors verifies error propagation from the store. +func TestContractsIndexer_NextHeight_MockErrors(t *testing.T) { + t.Parallel() + + t.Run("unexpected error from LatestIndexedHeight propagates", func(t *testing.T) { + t.Parallel() + + mockStore := storagemock.NewContractDeploymentsIndexBootstrapper(t) + unexpectedErr := fmt.Errorf("unexpected error") + mockStore.On("LatestIndexedHeight").Return(uint64(0), unexpectedErr) + + indexer := NewContracts(unittest.Logger(), mockStore, nil, nil, &metrics.NoopCollector{}) + + _, err := indexer.NextHeight() + require.Error(t, err) + require.ErrorIs(t, err, unexpectedErr) + }) + + t.Run("inconsistent state: not bootstrapped but initialized", func(t *testing.T) { + t.Parallel() + + mockStore := storagemock.NewContractDeploymentsIndexBootstrapper(t) + mockStore.On("LatestIndexedHeight").Return(uint64(0), storage.ErrNotBootstrapped) + mockStore.On("UninitializedFirstHeight").Return(uint64(42), true) + + indexer := NewContracts(unittest.Logger(), mockStore, nil, nil, &metrics.NoopCollector{}) + + _, err := indexer.NextHeight() + require.Error(t, err) + assert.Contains(t, err.Error(), "but index is initialized") + }) + + t.Run("store error from Store propagates", func(t *testing.T) { + t.Parallel() + + const testHeight = uint64(100) + mockStore := storagemock.NewContractDeploymentsIndexBootstrapper(t) + storeErr := fmt.Errorf("unexpected storage error") + // Store is already initialized so loadDeployedContracts is skipped. + mockStore.On("UninitializedFirstHeight").Return(testHeight, true) + mockStore.On("Store", mock.Anything, mock.Anything, testHeight, mock.Anything).Return(storeErr) + + lm := storage.NewTestingLockManager() + indexer := NewContracts(unittest.Logger(), mockStore, nil, nil, &metrics.NoopCollector{}) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + + err := unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return indexer.IndexBlockData(lctx, BlockData{Header: header, Events: []flow.Event{}}, nil) + }) + require.Error(t, err) + require.ErrorIs(t, err, storeErr) + }) +} + +// ===== Test Setup Helpers ===== + +// fakeRegisters is a minimal registerScanner for tests. Populate Entries with register +// entries that should appear in the ByKeyPrefix scan (e.g. code registers for +// pre-existing contracts at the bootstrap height). +type fakeRegisters struct { + Entries []flow.RegisterEntry +} + +func (r *fakeRegisters) ByKeyPrefix(keyPrefix string, _ uint64, _ *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] { + return func(yield func(storage.IteratorEntry[flow.RegisterValue, flow.RegisterID], error) bool) { + for _, e := range r.Entries { + if !strings.HasPrefix(e.Key.Key, keyPrefix) { + continue + } + entry := fakeRegisterEntry{id: e.Key, val: e.Value} + if !yield(entry, nil) { + return + } + } + } +} + +type fakeRegisterEntry struct { + id flow.RegisterID + val flow.RegisterValue +} + +func (e fakeRegisterEntry) Cursor() flow.RegisterID { return e.id } +func (e fakeRegisterEntry) Value() (flow.RegisterValue, error) { return e.val, nil } + +// runWithContractsIndexer creates a temporary pebble DB and a Contracts indexer with the given +// registers and scriptExecutor, then calls f with the indexer, store, lock manager, and DB. +func runWithContractsIndexer( + t *testing.T, + firstHeight uint64, + registers *fakeRegisters, + scriptExecutor *executionmock.ScriptExecutor, + f func(*Contracts, storage.ContractDeploymentsIndexBootstrapper, storage.LockManager, storage.DB), +) { + unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { + db := pebbleimpl.ToDB(pdb) + lm := storage.NewTestingLockManager() + store, err := indexes.NewContractDeploymentsBootstrapper(db, firstHeight) + require.NoError(t, err) + indexer := NewContracts(unittest.Logger(), store, registers, scriptExecutor, &metrics.NoopCollector{}) + f(indexer, store, lm, db) + }) +} + +// indexContractsBlock runs IndexBlockData with proper locking and batch commit and returns any error. +func indexContractsBlock( + t *testing.T, + indexer *Contracts, + lm storage.LockManager, + db storage.DB, + data BlockData, +) error { + t.Helper() + return unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return indexer.IndexBlockData(lctx, data, rw) + }) + }) +} + +// makeContractSnapshot builds a MapStorageSnapshot containing a single account with the +// given contracts. The snapshot can be used to satisfy GetStorageSnapshot for a given height. +func makeContractSnapshot(t *testing.T, address flow.Address, contracts map[string][]byte) fvmsnapshot.MapStorageSnapshot { + t.Helper() + snap := make(fvmsnapshot.MapStorageSnapshot) + + // Mark account as existing via a valid account status register. + status := environment.NewAccountStatus() + snap[flow.AccountStatusRegisterID(address)] = status.ToBytes() + + // Encode and store contract names. + names := make([]string, 0, len(contracts)) + for name := range contracts { + names = append(names, name) + } + var nameBuf bytes.Buffer + require.NoError(t, cbor.NewEncoder(&nameBuf).Encode(names)) + snap[flow.ContractNamesRegisterID(address)] = nameBuf.Bytes() + + // Store each contract's code. + for name, code := range contracts { + snap[flow.ContractRegisterID(address, name)] = flow.RegisterValue(code) + } + return snap +} + +// encodeContractNames returns the CBOR-encoded contract names register value for the given names, +// matching the encoding used by accounts.setContractNames. +func encodeContractNames(t *testing.T, names ...string) flow.RegisterValue { + t.Helper() + var buf bytes.Buffer + require.NoError(t, cbor.NewEncoder(&buf).Encode(names)) + return buf.Bytes() +} + +// makeMultiAccountSnapshot builds a MapStorageSnapshot containing two accounts with contracts. +func makeMultiAccountSnapshot( + t *testing.T, + addr1 flow.Address, contracts1 map[string][]byte, + addr2 flow.Address, contracts2 map[string][]byte, +) fvmsnapshot.MapStorageSnapshot { + t.Helper() + snap := make(fvmsnapshot.MapStorageSnapshot) + for k, v := range makeContractSnapshot(t, addr1, contracts1) { + snap[k] = v + } + for k, v := range makeContractSnapshot(t, addr2, contracts2) { + snap[k] = v + } + return snap +} + +// ===== Event Creation Helpers ===== + +func makeContractEvent( + t *testing.T, + eventTypeName string, + address flow.Address, + contractName string, + codeHash []byte, + txIndex uint32, + eventIndex uint32, +) flow.Event { + t.Helper() + + eventType := cadence.NewEventType( + nil, + eventTypeName, + []cadence.Field{ + {Identifier: "address", Type: cadence.AddressType}, + {Identifier: "codeHash", Type: cadence.NewConstantSizedArrayType(32, cadence.UInt8Type)}, + {Identifier: "contract", Type: cadence.StringType}, + }, + nil, + ) + + hashValues := make([]cadence.Value, 32) + for i, b := range codeHash { + hashValues[i] = cadence.UInt8(b) + } + + event := cadence.NewEvent([]cadence.Value{ + cadence.NewAddress(address), + cadence.NewArray(hashValues).WithType(cadence.NewConstantSizedArrayType(32, cadence.UInt8Type)), + cadence.String(contractName), + }).WithType(eventType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: flow.EventType(eventTypeName), + TransactionIndex: txIndex, + EventIndex: eventIndex, + Payload: payload, + } +} + +func assertContractDeployment(t *testing.T, expected access.ContractDeployment, actual access.ContractDeployment) { + assert.Equal(t, expected.Address, actual.Address) + assert.Equal(t, expected.ContractName, actual.ContractName) + assert.Equal(t, expected.BlockHeight, actual.BlockHeight) + assert.Equal(t, expected.TransactionID, actual.TransactionID) + assert.Equal(t, expected.TransactionIndex, actual.TransactionIndex) + assert.Equal(t, expected.EventIndex, actual.EventIndex) + assert.Equal(t, expected.Code, actual.Code) + assert.Equal(t, expected.CodeHash, actual.CodeHash) + assert.Equal(t, expected.IsPlaceholder, actual.IsPlaceholder) + assert.Equal(t, expected.IsDeleted, actual.IsDeleted) +} diff --git a/module/state_synchronization/indexer/extended/events/contract.go b/module/state_synchronization/indexer/extended/events/contract.go new file mode 100644 index 00000000000..15ef5161f74 --- /dev/null +++ b/module/state_synchronization/indexer/extended/events/contract.go @@ -0,0 +1,140 @@ +package events + +import ( + "fmt" + + "github.com/onflow/cadence" + + "github.com/onflow/flow-go/model/flow" +) + +// AccountContractAddedEvent represents a decoded flow.AccountContractAdded event, +// emitted when a new contract is deployed to an account. +type AccountContractAddedEvent struct { + // Address is the account address to which the contract was deployed. + Address flow.Address + // CodeHash is the 32-byte hash of the deployed contract code. + CodeHash []byte + // ContractName is the name of the deployed contract (e.g. "EVM"). + ContractName string +} + +// AccountContractUpdatedEvent represents a decoded flow.AccountContractUpdated event, +// emitted when an existing contract on an account is updated. +type AccountContractUpdatedEvent struct { + // Address is the account address whose contract was updated. + Address flow.Address + // CodeHash is the 32-byte hash of the updated contract code. + CodeHash []byte + // ContractName is the name of the updated contract. + ContractName string +} + +// AccountContractRemovedEvent represents a decoded flow.AccountContractRemoved event, +// emitted when a contract is removed from an account. +type AccountContractRemovedEvent struct { + // Address is the account address from which the contract was removed. + Address flow.Address + // CodeHash is the 32-byte hash of the removed contract code. + CodeHash []byte + // ContractName is the name of the removed contract. + ContractName string +} + +// DecodeAccountContractAdded extracts fields from a flow.AccountContractAdded event. +// +// Any error indicates that the event is malformed. +// +// No error returns are expected during normal operation. +func DecodeAccountContractAdded(event cadence.Event) (*AccountContractAddedEvent, error) { + type raw struct { + Address cadence.Address `cadence:"address"` + CodeHash cadence.Value `cadence:"codeHash"` + ContractName string `cadence:"contract"` + } + var r raw + if err := cadence.DecodeFields(event, &r); err != nil { + return nil, fmt.Errorf("failed to decode AccountContractAdded event: %w", err) + } + hash, err := decodeCodeHashValue(r.CodeHash) + if err != nil { + return nil, fmt.Errorf("failed to decode AccountContractAdded 'codeHash' field: %w", err) + } + return &AccountContractAddedEvent{ + Address: flow.Address(r.Address), + CodeHash: hash, + ContractName: r.ContractName, + }, nil +} + +// DecodeAccountContractUpdated extracts fields from a flow.AccountContractUpdated event. +// +// Any error indicates that the event is malformed. +// +// No error returns are expected during normal operation. +func DecodeAccountContractUpdated(event cadence.Event) (*AccountContractUpdatedEvent, error) { + type raw struct { + Address cadence.Address `cadence:"address"` + CodeHash cadence.Value `cadence:"codeHash"` + ContractName string `cadence:"contract"` + } + var r raw + if err := cadence.DecodeFields(event, &r); err != nil { + return nil, fmt.Errorf("failed to decode AccountContractUpdated event: %w", err) + } + hash, err := decodeCodeHashValue(r.CodeHash) + if err != nil { + return nil, fmt.Errorf("failed to decode AccountContractUpdated 'codeHash' field: %w", err) + } + return &AccountContractUpdatedEvent{ + Address: flow.Address(r.Address), + CodeHash: hash, + ContractName: r.ContractName, + }, nil +} + +// DecodeAccountContractRemoved extracts fields from a flow.AccountContractRemoved event. +// +// Any error indicates that the event is malformed. +// +// No error returns are expected during normal operation. +func DecodeAccountContractRemoved(event cadence.Event) (*AccountContractRemovedEvent, error) { + type raw struct { + Address cadence.Address `cadence:"address"` + CodeHash cadence.Value `cadence:"codeHash"` + ContractName string `cadence:"contract"` + } + var r raw + if err := cadence.DecodeFields(event, &r); err != nil { + return nil, fmt.Errorf("failed to decode AccountContractRemoved event: %w", err) + } + hash, err := decodeCodeHashValue(r.CodeHash) + if err != nil { + return nil, fmt.Errorf("failed to decode AccountContractRemoved 'codeHash' field: %w", err) + } + return &AccountContractRemovedEvent{ + Address: flow.Address(r.Address), + CodeHash: hash, + ContractName: r.ContractName, + }, nil +} + +// decodeCodeHashValue extracts a []byte from a Cadence constant-sized array of UInt8 values +// ([UInt8; 32]). Returns an error if the value is not a cadence.Array or contains non-UInt8 elements. +// +// No error returns are expected during normal operation. +func decodeCodeHashValue(v cadence.Value) ([]byte, error) { + arr, ok := v.(cadence.Array) + if !ok { + return nil, fmt.Errorf("expected cadence.Array, got %T", v) + } + result := make([]byte, len(arr.Values)) + for i, elem := range arr.Values { + b, ok := elem.(cadence.UInt8) + if !ok { + return nil, fmt.Errorf("expected cadence.UInt8 at index %d, got %T", i, elem) + } + result[i] = byte(b) + } + return result, nil +} diff --git a/module/state_synchronization/indexer/extended/events/ft.go b/module/state_synchronization/indexer/extended/events/ft.go new file mode 100644 index 00000000000..b521ab58299 --- /dev/null +++ b/module/state_synchronization/indexer/extended/events/ft.go @@ -0,0 +1,124 @@ +package events + +import ( + "fmt" + + "github.com/onflow/cadence" + + "github.com/onflow/flow-go/model/flow" +) + +// FTWithdrawnEvent represents a decoded FungibleToken.Withdrawn event. +type FTWithdrawnEvent struct { + Type string // Token type identifier (e.g., "A.f233dcee88fe0abe.FlowToken.Vault") + Amount cadence.UFix64 // Amount in UFix64 (Cadence-side denomination) + From flow.Address // Address the tokens were withdrawn from + FromUUID uint64 // UUID of the source vault + WithdrawnUUID uint64 // UUID of the withdrawn vault + BalanceAfter cadence.UFix64 // Balance after the tokens were withdrawn (in UFix64) +} + +// FTDepositedEvent represents a decoded FungibleToken.Deposited event. +type FTDepositedEvent struct { + Type string // Token type identifier (e.g., "A.f233dcee88fe0abe.FlowToken.Vault") + Amount cadence.UFix64 // Amount in UFix64 (Cadence-side denomination) + To flow.Address // Address the tokens were deposited to + ToUUID uint64 // UUID of the destination vault + DepositedUUID uint64 // UUID of the deposited vault + BalanceAfter cadence.UFix64 // Balance after the tokens were deposited (in UFix64) +} + +// DecodeFTDeposited extracts fields from a FungibleToken.Deposited event. +// +// Any error indicates that the event is malformed. +func DecodeFTDeposited(event cadence.Event) (*FTDepositedEvent, error) { + type ftDepositedEventRaw struct { + Type string `cadence:"type"` + Amount cadence.UFix64 `cadence:"amount"` + To cadence.Optional `cadence:"to"` + ToUUID uint64 `cadence:"toUUID"` + DepositedUUID uint64 `cadence:"depositedUUID"` + BalanceAfter cadence.UFix64 `cadence:"balanceAfter"` + } + + var raw ftDepositedEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode FT deposited event: %w", err) + } + + to, err := AddressFromOptional(raw.To) + if err != nil { + return nil, fmt.Errorf("failed to decode FT deposited 'to' field: %w", err) + } + + return &FTDepositedEvent{ + Type: raw.Type, + Amount: raw.Amount, + To: to, + ToUUID: raw.ToUUID, + DepositedUUID: raw.DepositedUUID, + BalanceAfter: raw.BalanceAfter, + }, nil +} + +// DecodeFTWithdrawn extracts fields from a FungibleToken.Withdrawn event. +// +// Any error indicates that the event is malformed. +func DecodeFTWithdrawn(event cadence.Event) (*FTWithdrawnEvent, error) { + type ftWithdrawnEventRaw struct { + Type string `cadence:"type"` + Amount cadence.UFix64 `cadence:"amount"` + From cadence.Optional `cadence:"from"` + FromUUID uint64 `cadence:"fromUUID"` + WithdrawnUUID uint64 `cadence:"withdrawnUUID"` + BalanceAfter cadence.UFix64 `cadence:"balanceAfter"` + } + + var raw ftWithdrawnEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode FT withdrawn event: %w", err) + } + + from, err := AddressFromOptional(raw.From) + if err != nil { + return nil, fmt.Errorf("failed to decode FT withdrawn 'from' field: %w", err) + } + + return &FTWithdrawnEvent{ + Type: raw.Type, + Amount: raw.Amount, + From: from, + FromUUID: raw.FromUUID, + WithdrawnUUID: raw.WithdrawnUUID, + BalanceAfter: raw.BalanceAfter, + }, nil +} + +// FlowFeesEvent represents a decoded FlowFees.FeesDeducted event. +type FlowFeesEvent struct { + Amount cadence.UFix64 + ExecutionEffort uint64 + InclusionEffort uint64 +} + +// DecodeFlowFees extracts fields from a FlowFees.FeesDeducted event. +// +// Any error indicates that the event is malformed. +func DecodeFlowFees(event cadence.Event) (*FlowFeesEvent, error) { + type flowFeesEventRaw struct { + Amount cadence.UFix64 `cadence:"amount"` + ExecutionEffort uint64 `cadence:"executionEffort"` + InclusionEffort uint64 `cadence:"inclusionEffort"` + } + + var raw flowFeesEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode FlowFees.FeesDeducted event: %w", err) + } + + return &FlowFeesEvent{ + Amount: raw.Amount, + ExecutionEffort: raw.ExecutionEffort, + InclusionEffort: raw.InclusionEffort, + }, nil +} diff --git a/module/state_synchronization/indexer/extended/events/helpers.go b/module/state_synchronization/indexer/extended/events/helpers.go new file mode 100644 index 00000000000..6d90d9db695 --- /dev/null +++ b/module/state_synchronization/indexer/extended/events/helpers.go @@ -0,0 +1,94 @@ +package events + +import ( + "encoding/hex" + "fmt" + + "github.com/ethereum/go-ethereum/common" + "github.com/onflow/cadence" + "github.com/onflow/cadence/encoding/ccf" + + "github.com/onflow/flow-go/model/flow" +) + +// DecodePayload decodes the CCF payload of a [flow.Event] into a [cadence.Event]. +// +// Any error indicates that the event payload is malformed. +func DecodePayload(event flow.Event) (cadence.Event, error) { + value, err := ccf.Decode(nil, event.Payload) + if err != nil { + return cadence.Event{}, fmt.Errorf("failed to decode CCF payload for %s: %w", event.Type, err) + } + + cadenceEvent, ok := value.(cadence.Event) + if !ok { + return cadence.Event{}, fmt.Errorf("decoded value is not an event for %s: %T", event.Type, value) + } + + return cadenceEvent, nil +} + +// AddressFromOptional extracts an address from a [cadence.Optional] value. +// Returns a zero address if the optional is empty (nil value). +// +// Any error indicates that the provided optional value is not a valid address. +func AddressFromOptional(opt cadence.Optional) (flow.Address, error) { + if opt.Value == nil { + return flow.Address{}, nil + } + + addr, ok := opt.Value.(cadence.Address) + if !ok { + return flow.Address{}, fmt.Errorf("unexpected type in optional address field: %T", opt.Value) + } + + return flow.BytesToAddress(addr.Bytes()), nil +} + +// PathFromOptional extracts a path string from a [cadence.Optional] containing a [cadence.Path]. +// Returns the path string (e.g "/public/identifier"), or "" if the optional is empty. +// +// Any error indicates that the optional value is not a valid path. +func PathFromOptional(opt cadence.Optional) (string, error) { + if opt.Value == nil { + return "", nil + } + path, ok := opt.Value.(cadence.Path) + if !ok { + return "", fmt.Errorf("unexpected type in optional path field: %T", opt.Value) + } + return path.String(), nil +} + +// EnumToType extracts the raw value from a Cadence enum and converts it to T. +// Cadence enums encode their raw value in a field named "rawValue". +// +// Any error indicates that the enum is malformed or the rawValue is not convertible to T. +func EnumToType[T any](enum cadence.Enum) (T, error) { + var zero T + raw := enum.SearchFieldByName("rawValue") + if raw == nil { + return zero, fmt.Errorf("enum has no rawValue field") + } + v, ok := raw.(T) + if !ok { + return zero, fmt.Errorf("expected %T rawValue, got %T", zero, raw) + } + return v, nil +} + +// HexToEVMAddress decodes a hex string to an EVM address. +// This is the same logic as `common.HexToAddress`, except it returns an error if the hex string is +// not valid hex or an incorrect length. +// +// Any error indicates that the hex string is malformed. +func HexToEVMAddress(hexStr string) (common.Address, error) { + addrBytes, err := hex.DecodeString(hexStr) + if err != nil { + return common.Address{}, fmt.Errorf("invalid hex string: %w", err) + } + if len(addrBytes) != common.AddressLength { + return common.Address{}, fmt.Errorf("invalid EVM address length: %d", len(addrBytes)) + } + return common.BytesToAddress(addrBytes), nil +} diff --git a/module/state_synchronization/indexer/extended/events/helpers_test.go b/module/state_synchronization/indexer/extended/events/helpers_test.go new file mode 100644 index 00000000000..0a70d614094 --- /dev/null +++ b/module/state_synchronization/indexer/extended/events/helpers_test.go @@ -0,0 +1,228 @@ +package events + +import ( + "testing" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/encoding/ccf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" +) + +// ========================================================================== +// AddressFromOptional Tests +// ========================================================================== + +func TestAddressFromOptional(t *testing.T) { + t.Run("valid address", func(t *testing.T) { + expected := unittest.RandomAddressFixture() + opt := cadence.NewOptional(cadence.NewAddress(expected)) + addr, err := AddressFromOptional(opt) + require.NoError(t, err) + assert.Equal(t, expected, addr) + }) + + t.Run("nil optional value", func(t *testing.T) { + opt := cadence.NewOptional(nil) + addr, err := AddressFromOptional(opt) + require.NoError(t, err) + assert.Equal(t, flow.Address{}, addr) + }) + + t.Run("non-address value in optional returns error", func(t *testing.T) { + opt := cadence.NewOptional(cadence.String("not an address")) + _, err := AddressFromOptional(opt) + require.Error(t, err) + assert.Contains(t, err.Error(), "unexpected type") + }) +} + +// ========================================================================== +// PathFromOptional Tests +// ========================================================================== + +func TestPathFromOptional(t *testing.T) { + t.Run("valid path", func(t *testing.T) { + path := cadence.Path{Domain: common.PathDomainStorage, Identifier: "flowToken"} + opt := cadence.NewOptional(path) + result, err := PathFromOptional(opt) + require.NoError(t, err) + assert.Equal(t, path.String(), result) + }) + + t.Run("nil optional value", func(t *testing.T) { + opt := cadence.NewOptional(nil) + result, err := PathFromOptional(opt) + require.NoError(t, err) + assert.Equal(t, "", result) + }) + + t.Run("non-path value in optional returns error", func(t *testing.T) { + opt := cadence.NewOptional(cadence.String("not a path")) + _, err := PathFromOptional(opt) + require.Error(t, err) + assert.Contains(t, err.Error(), "unexpected type") + }) +} + +// ========================================================================== +// DecodePayload Tests +// ========================================================================== + +func TestDecodePayload_InvalidPayload(t *testing.T) { + event := flow.Event{ + Type: "A.1234.SomeContract.SomeEvent", + Payload: []byte("garbage"), + } + _, err := DecodePayload(event) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to decode CCF payload") +} + +func TestDecodePayload_NonEventPayload(t *testing.T) { + // Encode a valid Cadence value that is not an Event. + payload, err := ccf.Encode(cadence.String("not an event")) + require.NoError(t, err) + + event := flow.Event{ + Type: "A.1234.SomeContract.SomeEvent", + Payload: payload, + } + _, err = DecodePayload(event) + require.Error(t, err) + assert.Contains(t, err.Error(), "not an event") +} + +// ========================================================================== +// Contract Event Decoder Tests +// ========================================================================== + +// makeContractCadenceEvent builds a cadence.Event for a contract lifecycle event type +// (e.g. "flow.AccountContractAdded") with the given address, code hash, and contract name. +func makeContractCadenceEvent(eventTypeName string, addr flow.Address, codeHash []byte, contractName string) cadence.Event { + hashValues := make([]cadence.Value, 32) + for i, b := range codeHash { + hashValues[i] = cadence.UInt8(b) + } + eventType := cadence.NewEventType( + nil, + eventTypeName, + []cadence.Field{ + {Identifier: "address", Type: cadence.AddressType}, + {Identifier: "codeHash", Type: cadence.NewConstantSizedArrayType(32, cadence.UInt8Type)}, + {Identifier: "contract", Type: cadence.StringType}, + }, + nil, + ) + return cadence.NewEvent([]cadence.Value{ + cadence.NewAddress(addr), + cadence.NewArray(hashValues).WithType(cadence.NewConstantSizedArrayType(32, cadence.UInt8Type)), + cadence.String(contractName), + }).WithType(eventType) +} + +func TestDecodeAccountContractAdded(t *testing.T) { + addr := unittest.RandomAddressFixture() + codeHash := make([]byte, 32) + for i := range codeHash { + codeHash[i] = byte(i) + } + + t.Run("valid event decodes all fields", func(t *testing.T) { + event := makeContractCadenceEvent("flow.AccountContractAdded", addr, codeHash, "MyContract") + result, err := DecodeAccountContractAdded(event) + require.NoError(t, err) + assert.Equal(t, addr, result.Address) + assert.Equal(t, "MyContract", result.ContractName) + assert.Equal(t, codeHash, result.CodeHash) + }) + + t.Run("non-array code hash returns error", func(t *testing.T) { + // Build an event where codeHash is a String instead of [UInt8; 32]. + eventType := cadence.NewEventType(nil, "flow.AccountContractAdded", []cadence.Field{ + {Identifier: "address", Type: cadence.AddressType}, + {Identifier: "codeHash", Type: cadence.StringType}, + {Identifier: "contract", Type: cadence.StringType}, + }, nil) + event := cadence.NewEvent([]cadence.Value{ + cadence.NewAddress(addr), + cadence.String("notanarrayofbytes"), + cadence.String("MyContract"), + }).WithType(eventType) + + _, err := DecodeAccountContractAdded(event) + require.Error(t, err) + assert.Contains(t, err.Error(), "codeHash") + }) +} + +func TestDecodeAccountContractUpdated(t *testing.T) { + addr := unittest.RandomAddressFixture() + codeHash := make([]byte, 32) + for i := range codeHash { + codeHash[i] = byte(i + 1) + } + + t.Run("valid event decodes all fields", func(t *testing.T) { + event := makeContractCadenceEvent("flow.AccountContractUpdated", addr, codeHash, "UpdatedContract") + result, err := DecodeAccountContractUpdated(event) + require.NoError(t, err) + assert.Equal(t, addr, result.Address) + assert.Equal(t, "UpdatedContract", result.ContractName) + assert.Equal(t, codeHash, result.CodeHash) + }) +} + +func TestDecodeAccountContractRemoved(t *testing.T) { + addr := unittest.RandomAddressFixture() + codeHash := make([]byte, 32) + for i := range codeHash { + codeHash[i] = byte(i + 2) + } + + t.Run("valid event decodes all fields", func(t *testing.T) { + event := makeContractCadenceEvent("flow.AccountContractRemoved", addr, codeHash, "RemovedContract") + result, err := DecodeAccountContractRemoved(event) + require.NoError(t, err) + assert.Equal(t, addr, result.Address) + assert.Equal(t, "RemovedContract", result.ContractName) + assert.Equal(t, codeHash, result.CodeHash) + }) +} + +// ========================================================================== +// decodeCodeHashValue Tests +// ========================================================================== + +func TestDecodeCodeHashValue(t *testing.T) { + t.Run("non-array returns error", func(t *testing.T) { + _, err := decodeCodeHashValue(cadence.String("notanarray")) + require.Error(t, err) + assert.Contains(t, err.Error(), "expected cadence.Array") + }) + + t.Run("array with non-UInt8 element returns error", func(t *testing.T) { + val := cadence.NewArray([]cadence.Value{cadence.String("notabyte")}) + _, err := decodeCodeHashValue(val) + require.Error(t, err) + assert.Contains(t, err.Error(), "expected cadence.UInt8") + }) + + t.Run("valid UInt8 array roundtrips correctly", func(t *testing.T) { + hash := make([]byte, 32) + for i := range hash { + hash[i] = byte(i) + } + vals := make([]cadence.Value, 32) + for i, b := range hash { + vals[i] = cadence.UInt8(b) + } + result, err := decodeCodeHashValue(cadence.NewArray(vals)) + require.NoError(t, err) + assert.Equal(t, hash, result) + }) +} diff --git a/module/state_synchronization/indexer/extended/events/nft.go b/module/state_synchronization/indexer/extended/events/nft.go new file mode 100644 index 00000000000..1a06468d787 --- /dev/null +++ b/module/state_synchronization/indexer/extended/events/nft.go @@ -0,0 +1,89 @@ +package events + +import ( + "fmt" + + "github.com/onflow/cadence" + + "github.com/onflow/flow-go/model/flow" +) + +// NFTWithdrawnEvent represents a decoded NonFungibleToken.Withdrawn event. +type NFTWithdrawnEvent struct { + Type string + ID uint64 // NFT ID + UUID uint64 + From flow.Address + ProviderUUID uint64 +} + +// NFTDepositedEvent represents a decoded NonFungibleToken.Deposited event. +type NFTDepositedEvent struct { + Type string + ID uint64 // NFT ID + UUID uint64 + To flow.Address + CollectionUUID uint64 +} + +// DecodeNFTDeposited extracts fields from a NonFungibleToken.Deposited event. +// +// Any error indicates that the event is malformed. +func DecodeNFTDeposited(event cadence.Event) (*NFTDepositedEvent, error) { + type nftDepositedEventRaw struct { + Type string `cadence:"type"` + ID uint64 `cadence:"id"` + UUID uint64 `cadence:"uuid"` + To cadence.Optional `cadence:"to"` + CollectionUUID uint64 `cadence:"collectionUUID"` + } + + var raw nftDepositedEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode NFT deposited event: %w", err) + } + + to, err := AddressFromOptional(raw.To) + if err != nil { + return nil, fmt.Errorf("failed to decode NFT deposited 'to' field: %w", err) + } + + return &NFTDepositedEvent{ + Type: raw.Type, + ID: raw.ID, + UUID: raw.UUID, + To: to, + CollectionUUID: raw.CollectionUUID, + }, nil +} + +// DecodeNFTWithdrawn extracts fields from a NonFungibleToken.Withdrawn event. +// +// Any error indicates that the event is malformed. +func DecodeNFTWithdrawn(event cadence.Event) (*NFTWithdrawnEvent, error) { + type nftWithdrawnEventRaw struct { + Type string `cadence:"type"` + ID uint64 `cadence:"id"` + UUID uint64 `cadence:"uuid"` + From cadence.Optional `cadence:"from"` + ProviderUUID uint64 `cadence:"providerUUID"` + } + + var raw nftWithdrawnEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode NFT withdrawn event: %w", err) + } + + from, err := AddressFromOptional(raw.From) + if err != nil { + return nil, fmt.Errorf("failed to decode NFT withdrawn 'from' field: %w", err) + } + + return &NFTWithdrawnEvent{ + Type: raw.Type, + ID: raw.ID, + UUID: raw.UUID, + From: from, + ProviderUUID: raw.ProviderUUID, + }, nil +} diff --git a/module/state_synchronization/indexer/extended/events/scheduled_transaction.go b/module/state_synchronization/indexer/extended/events/scheduled_transaction.go new file mode 100644 index 00000000000..428eddd6d45 --- /dev/null +++ b/module/state_synchronization/indexer/extended/events/scheduled_transaction.go @@ -0,0 +1,187 @@ +package events + +import ( + "fmt" + + "github.com/onflow/cadence" + + "github.com/onflow/flow-go/model/flow" +) + +// TransactionSchedulerScheduledEvent represents a decoded FlowTransactionScheduler.Scheduled event, +// emitted when a new scheduled transaction is registered. +type TransactionSchedulerScheduledEvent struct { + ID uint64 + Priority uint8 + Timestamp cadence.UFix64 + ExecutionEffort uint64 + Fees cadence.UFix64 + TransactionHandlerOwner flow.Address + TransactionHandlerTypeIdentifier string + TransactionHandlerUUID uint64 + TransactionHandlerPublicPath string +} + +// TransactionSchedulerPendingExecutionEvent represents a decoded FlowTransactionScheduler.PendingExecution event, +// emitted when a scheduled transaction's timestamp is reached and it is ready for execution. +type TransactionSchedulerPendingExecutionEvent struct { + ID uint64 + Priority uint8 + ExecutionEffort uint64 + Fees cadence.UFix64 + TransactionHandlerOwner flow.Address + TransactionHandlerTypeIdentifier string +} + +// TransactionSchedulerExecutedEvent represents a decoded FlowTransactionScheduler.Executed event, +// emitted when a scheduled transaction has been successfully executed. +type TransactionSchedulerExecutedEvent struct { + ID uint64 + Priority uint8 + ExecutionEffort uint64 + TransactionHandlerOwner flow.Address + TransactionHandlerTypeIdentifier string + TransactionHandlerUUID uint64 + TransactionHandlerPublicPath string +} + +// TransactionSchedulerCanceledEvent represents a decoded FlowTransactionScheduler.Canceled event, +// emitted when a scheduled transaction is cancelled by its creator. +type TransactionSchedulerCanceledEvent struct { + ID uint64 + Priority uint8 + FeesReturned cadence.UFix64 + FeesDeducted cadence.UFix64 + TransactionHandlerOwner flow.Address + TransactionHandlerTypeIdentifier string +} + +// DecodeTransactionSchedulerScheduled extracts fields from a FlowTransactionScheduler.Scheduled event. +// +// Any error indicates that the event is malformed. +func DecodeTransactionSchedulerScheduled(event cadence.Event) (*TransactionSchedulerScheduledEvent, error) { + type scheduledEventRaw struct { + ID uint64 `cadence:"id"` + Priority uint8 `cadence:"priority"` + Timestamp cadence.UFix64 `cadence:"timestamp"` + ExecutionEffort uint64 `cadence:"executionEffort"` + Fees cadence.UFix64 `cadence:"fees"` + TransactionHandlerOwner cadence.Address `cadence:"transactionHandlerOwner"` + TransactionHandlerTypeIdentifier string `cadence:"transactionHandlerTypeIdentifier"` + TransactionHandlerUUID uint64 `cadence:"transactionHandlerUUID"` + TransactionHandlerPublicPath cadence.Optional `cadence:"transactionHandlerPublicPath"` + } + + var raw scheduledEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode Scheduled event: %w", err) + } + + publicPath, err := PathFromOptional(raw.TransactionHandlerPublicPath) + if err != nil { + return nil, fmt.Errorf("failed to decode Scheduled 'transactionHandlerPublicPath' field: %w", err) + } + + return &TransactionSchedulerScheduledEvent{ + ID: raw.ID, + Priority: raw.Priority, + Timestamp: raw.Timestamp, + ExecutionEffort: raw.ExecutionEffort, + Fees: raw.Fees, + TransactionHandlerOwner: flow.Address(raw.TransactionHandlerOwner), + TransactionHandlerTypeIdentifier: raw.TransactionHandlerTypeIdentifier, + TransactionHandlerUUID: raw.TransactionHandlerUUID, + TransactionHandlerPublicPath: publicPath, + }, nil +} + +// DecodeTransactionSchedulerPendingExecution extracts fields from a FlowTransactionScheduler.PendingExecution event. +// +// Any error indicates that the event is malformed. +func DecodeTransactionSchedulerPendingExecution(event cadence.Event) (*TransactionSchedulerPendingExecutionEvent, error) { + type pendingExecutionEventRaw struct { + ID uint64 `cadence:"id"` + Priority uint8 `cadence:"priority"` + ExecutionEffort uint64 `cadence:"executionEffort"` + Fees cadence.UFix64 `cadence:"fees"` + TransactionHandlerOwner cadence.Address `cadence:"transactionHandlerOwner"` + TransactionHandlerTypeIdentifier string `cadence:"transactionHandlerTypeIdentifier"` + } + + var raw pendingExecutionEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode PendingExecution event: %w", err) + } + + return &TransactionSchedulerPendingExecutionEvent{ + ID: raw.ID, + Priority: raw.Priority, + ExecutionEffort: raw.ExecutionEffort, + Fees: raw.Fees, + TransactionHandlerOwner: flow.Address(raw.TransactionHandlerOwner), + TransactionHandlerTypeIdentifier: raw.TransactionHandlerTypeIdentifier, + }, nil +} + +// DecodeTransactionSchedulerExecuted extracts fields from a FlowTransactionScheduler.Executed event. +// +// Any error indicates that the event is malformed. +func DecodeTransactionSchedulerExecuted(event cadence.Event) (*TransactionSchedulerExecutedEvent, error) { + type executedEventRaw struct { + ID uint64 `cadence:"id"` + Priority uint8 `cadence:"priority"` + ExecutionEffort uint64 `cadence:"executionEffort"` + TransactionHandlerOwner cadence.Address `cadence:"transactionHandlerOwner"` + TransactionHandlerTypeIdentifier string `cadence:"transactionHandlerTypeIdentifier"` + TransactionHandlerUUID uint64 `cadence:"transactionHandlerUUID"` + TransactionHandlerPublicPath cadence.Optional `cadence:"transactionHandlerPublicPath"` + } + + var raw executedEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode Executed event: %w", err) + } + + publicPath, err := PathFromOptional(raw.TransactionHandlerPublicPath) + if err != nil { + return nil, fmt.Errorf("failed to decode Executed 'transactionHandlerPublicPath' field: %w", err) + } + + return &TransactionSchedulerExecutedEvent{ + ID: raw.ID, + Priority: raw.Priority, + ExecutionEffort: raw.ExecutionEffort, + TransactionHandlerOwner: flow.Address(raw.TransactionHandlerOwner), + TransactionHandlerTypeIdentifier: raw.TransactionHandlerTypeIdentifier, + TransactionHandlerUUID: raw.TransactionHandlerUUID, + TransactionHandlerPublicPath: publicPath, + }, nil +} + +// DecodeTransactionSchedulerCanceled extracts fields from a FlowTransactionScheduler.Canceled event. +// +// Any error indicates that the event is malformed. +func DecodeTransactionSchedulerCanceled(event cadence.Event) (*TransactionSchedulerCanceledEvent, error) { + type canceledEventRaw struct { + ID uint64 `cadence:"id"` + Priority uint8 `cadence:"priority"` + FeesReturned cadence.UFix64 `cadence:"feesReturned"` + FeesDeducted cadence.UFix64 `cadence:"feesDeducted"` + TransactionHandlerOwner cadence.Address `cadence:"transactionHandlerOwner"` + TransactionHandlerTypeIdentifier string `cadence:"transactionHandlerTypeIdentifier"` + } + + var raw canceledEventRaw + if err := cadence.DecodeFields(event, &raw); err != nil { + return nil, fmt.Errorf("failed to decode Canceled event: %w", err) + } + + return &TransactionSchedulerCanceledEvent{ + ID: raw.ID, + Priority: raw.Priority, + FeesReturned: raw.FeesReturned, + FeesDeducted: raw.FeesDeducted, + TransactionHandlerOwner: flow.Address(raw.TransactionHandlerOwner), + TransactionHandlerTypeIdentifier: raw.TransactionHandlerTypeIdentifier, + }, nil +} diff --git a/module/state_synchronization/indexer/extended/extended_indexer.go b/module/state_synchronization/indexer/extended/extended_indexer.go new file mode 100644 index 00000000000..b019935bb4f --- /dev/null +++ b/module/state_synchronization/indexer/extended/extended_indexer.go @@ -0,0 +1,430 @@ +package extended + +import ( + "errors" + "fmt" + "sync" + "time" + + "github.com/jordanschalm/lockctx" + "github.com/rs/zerolog" + + "github.com/onflow/flow-go/engine" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/access/systemcollection" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage" +) + +const ( + // DefaultBackfillDelay defines the delay between consecutive backfill attempts. + // Set carefully to avoid overwhelming the system. + // With the default value of 5ms, the maximum catch-up rate is approximately + // 200 blocks per second. + DefaultBackfillDelay = 5 * time.Millisecond +) + +// ExtendedIndexer orchestrates indexing for all extended indexers. +// +// Indexing is performed in a single-threaded loop, where each iteration indexes the next height for +// all indexers. Indexers are grouped by their next height to reduce database lookups. All data for +// each height is written to a batch and committed at once. +// +// NOT CONCURRENCY SAFE. +type ExtendedIndexer struct { + component.Component + + log zerolog.Logger + db storage.DB + lockManager storage.LockManager + metrics module.ExtendedIndexingMetrics + backfillDelay time.Duration + + chainID flow.ChainID + state protocol.State + headers storage.Headers + index storage.Index + collections storage.Collections + guarantees storage.Guarantees + events storage.Events + results storage.LightTransactionResults + + systemCollections *access.Versioned[access.SystemCollectionBuilder] + + indexers []Indexer + notifier engine.Notifier + + // mu protects the latestBlockData field which is written in another goroutine via IndexBlockData. + mu sync.RWMutex + + // latestBlockData is the latest block data received via IndexBlockData. + // This represents the "live" block data that is being indexed. + latestBlockData *BlockData +} + +var _ IndexerManager = (*ExtendedIndexer)(nil) + +func NewExtendedIndexer( + log zerolog.Logger, + metrics module.ExtendedIndexingMetrics, + db storage.DB, + lockManager storage.LockManager, + state protocol.State, + index storage.Index, + headers storage.Headers, + guarantees storage.Guarantees, + collections storage.Collections, + events storage.Events, + results storage.LightTransactionResults, + indexers []Indexer, + chainID flow.ChainID, + backfillDelay time.Duration, +) (*ExtendedIndexer, error) { + if metrics == nil { + // this is here mostly for anyone that imports this within an external package. + return nil, fmt.Errorf("metrics cannot be nil. use a no-op metrics collector instead") + } + + log = log.With().Str("component", "extended_indexer").Logger() + c := &ExtendedIndexer{ + log: log, + db: db, + lockManager: lockManager, + metrics: metrics, + backfillDelay: backfillDelay, + indexers: indexers, + notifier: engine.NewNotifier(), + + chainID: chainID, + state: state, + headers: headers, + index: index, + guarantees: guarantees, + collections: collections, + events: events, + results: results, + systemCollections: systemcollection.Default(chainID), + } + + c.Component = component.NewComponentManagerBuilder(). + AddWorker(c.ingestLoop). + Build() + + return c, nil +} + +// IndexBlockExecutionData captures the block data and makes it available to the indexers. +// +// No error returns are expected during normal operation. +func (c *ExtendedIndexer) IndexBlockExecutionData( + data *execution_data.BlockExecutionDataEntity, +) error { + header, err := c.state.AtBlockID(data.BlockID).Head() + if err != nil { + return fmt.Errorf("failed to get block by id: %w", err) + } + + txs, events, err := c.extractDataFromExecutionData(data) + if err != nil { + return fmt.Errorf("failed to extract data from execution data: %w", err) + } + + return c.IndexBlockData(header, txs, events) +} + +// IndexBlockData stores block data and exposes it to the indexers. +// It must be called sequentially, with blocks provided in strictly +// increasing height order. +// +// Typically, this method is invoked when the latest block is received. +// If the indexer is fully caught up, this latest block will be the next +// one to process, and indexing it will advance the indexed height. +// +// If the indexer is still catching up, however, the latest block is not +// immediately needed because the indexer must first process older blocks. +// +// For this reason, we do not index the latest block right away. Instead, +// we cache it and notify the worker to proceed with the next job. +// +// If the next job is to process the latest block, the cached +// c.latestBlockData will be used. Otherwise, if the job is to process +// older blocks, the cache is ignored and the worker fetches the required +// block data for indexing. +// +// No error returns are expected during normal operation. +func (c *ExtendedIndexer) IndexBlockData( + header *flow.Header, + transactions []*flow.TransactionBody, + events []flow.Event, +) error { + c.mu.Lock() + defer c.mu.Unlock() + + if c.latestBlockData != nil { + if header.Height > c.latestBlockData.Header.Height+1 { + return fmt.Errorf("unexpected block received: expected height %d, got %d", c.latestBlockData.Header.Height+1, header.Height) + } + if header.Height <= c.latestBlockData.Header.Height { + return nil + } + } + + c.latestBlockData = &BlockData{ + Header: header, + Transactions: transactions, + Events: events, + } + c.notifier.Notify() + + return nil +} + +// ingestLoop is the main ingestion loop for the extended indexer. +// It indexes the next heights for all indexers, and handles backfilling from storage. +// +// NOT CONCURRENCY SAFE! Only one instance may be run at a time. +func (c *ExtendedIndexer) ingestLoop(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { + ready() + + timer := time.NewTimer(c.backfillDelay) + for { + select { + case <-ctx.Done(): + return + case <-c.notifier.Channel(): + case <-timer.C: + } + + hasBackfillingIndexers, err := c.indexNextHeights() + if err != nil { + ctx.Throw(fmt.Errorf("failed to check all: %w", err)) + return + } + + // once all indexers are caught up with the live height, stop resetting the backfill timer + // so the only notification will be for new live blocks. + if hasBackfillingIndexers { + timer.Reset(c.backfillDelay) + } + } +} + +// indexNextHeights indexes the next heights for all indexers. +// This is the main indexing method which handles processing for all configured indexer. On each call, +// it passes data for the next height to each indexer, and stores data from all indexers in a single batch. +// Indexers are not required to be at the same height. +// +// NOT CONCURRENCY SAFE. +// +// No error returns are expected during normal operation. +func (c *ExtendedIndexer) indexNextHeights() (bool, error) { + c.mu.RLock() + latestBlockData := c.latestBlockData + c.mu.RUnlock() + + // group indexers by their next height to allow the indexers to share input data. + liveGroup, backfillGroups, err := buildGroupLookup(c.indexers, latestBlockData) + if err != nil { + return false, fmt.Errorf("failed to build group lookup: %w", err) + } + + if len(liveGroup) > 0 { + err = c.runIndexers(liveGroup, latestBlockData) + if err != nil { + return false, fmt.Errorf("failed to index live indexers: %w", err) + } + } + + // this is a trailing indicator. this will be true if any indexer was backfilled in this iteration. + // if all indexers catch up, it will take one more iteration to register as all caught up. + hasBackfillingIndexers := len(backfillGroups) > 0 + + for height, group := range backfillGroups { + data, err := c.blockDataFromStorage(height) + if err != nil { + if !errors.Is(err, storage.ErrNotFound) { + return false, fmt.Errorf("failed to get block data for height %d: %w", height, err) + } + + // on startup, it's possible that indexers are already caught up, but the live block has + // not been provided yet. in this case, skip the group until the live block is known. + // this check will ensure backfilling progresses if and only if the live block is also + // progressing. + if latestBlockData == nil { + continue + } + + // if the live block is known, it must have all data available since this height is below + // the `latestBlockData` height. otherwise the database is in an inconsistent state. + return false, fmt.Errorf("failed to get block data for height %d when latest block %d is known: %w", + height, latestBlockData.Header.Height, err) + } + + err = c.runIndexers(group, &data) + if err != nil { + return false, fmt.Errorf("failed to index backfill indexers: %w", err) + } + } + + return hasBackfillingIndexers, nil +} + +// runIndexers indexes the data for all indexers in the group. +// +// No error returns are expected during normal operation. +func (c *ExtendedIndexer) runIndexers(indexers []Indexer, data *BlockData) error { + height := data.Header.Height + return storage.WithLocks(c.lockManager, storage.LockGroupAccessExtendedIndexers, func(lctx lockctx.Context) error { + return c.db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + // index the data for all indexers in the group + for _, indexer := range indexers { + if err := indexer.IndexBlockData(lctx, *data, rw); err != nil { + if errors.Is(err, ErrAlreadyIndexed) { + continue + } + // ErrFutureHeight is not expected since we have already checked that `data`'s height + // is the next height. If it is not, there is a bug. + return fmt.Errorf("failed to index block data for %s at height %d: %w", indexer.Name(), height, err) + } + + c.metrics.BlockIndexedExtended(indexer.Name(), height) + } + + return nil + }) + }) +} + +// blockDataFromStorage loads the block data for the given height. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if any data is not available for the height. +func (c *ExtendedIndexer) blockDataFromStorage(height uint64) (BlockData, error) { + // special handling for the spork root block which has no transactions or events. + if height == c.state.Params().SporkRootBlockHeight() { + return BlockData{ + Header: c.state.Params().SporkRootBlock().ToHeader(), + }, nil + } + + blockID, err := c.headers.BlockIDByHeight(height) + if err != nil { + return BlockData{}, fmt.Errorf("failed to get block id by height: %w", err) + } + + header, err := c.headers.ByBlockID(blockID) + if err != nil { + return BlockData{}, fmt.Errorf("failed to get header by id: %w", err) + } + + // all we need are the guarantees for the block, so use the index to avoid loading unnecessary + // execution payload data. + blockIndex, err := c.index.ByBlockID(blockID) + if err != nil { + return BlockData{}, fmt.Errorf("failed to get block index by block id: %w", err) + } + + events, err := c.events.ByBlockID(blockID) + if err != nil { + return BlockData{}, fmt.Errorf("failed to get events by block id: %w", err) + } + + // getting events returns an empty slice and no error if no events are found. This could mean + // either that the block has no events, or that they have not been indexed yet. In this case, also + // check if there were any transaction results. All blocks should have at least one system tx. + // if not, then assume the block is not indexed yet. + // Note: we need to check both because it's possible the system transaction failed and did not + // produce any events. It is very uncommon for a block to have no events, so this logic will + // rarely be run. + if len(events) == 0 { + results, err := c.results.ByBlockID(blockID) + if err != nil { + return BlockData{}, fmt.Errorf("failed to get results by block id: %w", err) + } + + // results will similarly return an empty slice and no error if no results are found + // or if the block's execution data is not indexed yet. + if len(results) == 0 { + return BlockData{}, fmt.Errorf("results for block %d not indexed yet: %w", height, storage.ErrNotFound) + } + } + + var transactions []*flow.TransactionBody + for _, guaranteeID := range blockIndex.GuaranteeIDs { + guarantee, err := c.guarantees.ByID(guaranteeID) + if err != nil { + return BlockData{}, fmt.Errorf("failed to get guarantee by id: %w", err) + } + collection, err := c.collections.ByID(guarantee.CollectionID) + if err != nil { + return BlockData{}, fmt.Errorf("failed to get collection by id: %w", err) + } + transactions = append(transactions, collection.Transactions...) + } + + // the system collection is not indexed, so construct it. + sysCollection, err := c.systemCollections. + ByHeight(height). + SystemCollection(c.chainID.Chain(), access.StaticEventProvider(events)) + if err != nil { + return BlockData{}, fmt.Errorf("could not construct system collection: %w", err) + } + transactions = append(transactions, sysCollection.Transactions...) + + return BlockData{ + Header: header, + Transactions: transactions, + Events: events, + }, nil +} + +// extractDataFromExecutionData extracts the transaction and event data from the execution data. +// +// No error returns are expected during normal operation. +func (c *ExtendedIndexer) extractDataFromExecutionData(data *execution_data.BlockExecutionDataEntity) ([]*flow.TransactionBody, []flow.Event, error) { + txs := make([]*flow.TransactionBody, 0) + events := make([]flow.Event, 0) + for i, chunk := range data.ChunkExecutionDatas { + // block execution data should include collections for ALL chunks, including the system chunk. + if chunk.Collection == nil { + return nil, nil, fmt.Errorf("chunk %d collection is nil", i) + } + txs = append(txs, chunk.Collection.Transactions...) + events = append(events, chunk.Events...) + } + return txs, events, nil +} + +// buildGroupLookup builds a map of indexers by their next height to index. +// This allows the indexing loop to lookup data for a height once, and pass it to all indexers in the group. +// If `latestBlockData` is not nil, it will also return the group of indexers at the "live" height. +// All indexers that are ahead of the live block will be skipped. +// +// No error returns are expected during normal operation. +func buildGroupLookup(indexers []Indexer, latestBlockData *BlockData) ([]Indexer, map[uint64][]Indexer, error) { + backfillGroups := make(map[uint64][]Indexer) + liveGroup := make([]Indexer, 0) + for _, indexer := range indexers { + nextHeight, err := indexer.NextHeight() + if err != nil { + return nil, nil, fmt.Errorf("failed to get next height for indexer %s: %w", indexer.Name(), err) + } + if latestBlockData != nil { + if nextHeight > latestBlockData.Header.Height { + continue // skip all indexers that are ahead of the live block + } + if nextHeight == latestBlockData.Header.Height { + liveGroup = append(liveGroup, indexer) + continue + } + } + backfillGroups[nextHeight] = append(backfillGroups[nextHeight], indexer) + } + + return liveGroup, backfillGroups, nil +} diff --git a/module/state_synchronization/indexer/extended/extended_indexer_test.go b/module/state_synchronization/indexer/extended/extended_indexer_test.go new file mode 100644 index 00000000000..bb19c9032dc --- /dev/null +++ b/module/state_synchronization/indexer/extended/extended_indexer_test.go @@ -0,0 +1,664 @@ +package extended_test + +import ( + "context" + "errors" + "fmt" + "os" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/testutil" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" + extendedmock "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/mock" + "github.com/onflow/flow-go/state/protocol" + protocolmock "github.com/onflow/flow-go/state/protocol/mock" + "github.com/onflow/flow-go/storage" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" + "github.com/onflow/flow-go/utils/unittest/fixtures" +) + +const testTimeout = 5 * time.Second + +type ExtendedIndexerSuite struct { + suite.Suite + + g *fixtures.GeneratorSuite + + db storage.DB + dbDir string + headers *storagemock.Headers + index *storagemock.Index + guarantees *storagemock.Guarantees + collections *storagemock.Collections + events *storagemock.Events + results *storagemock.LightTransactionResults + + ext *extended.ExtendedIndexer + cancel context.CancelFunc +} + +func TestExtendedIndexer(t *testing.T) { + suite.Run(t, new(ExtendedIndexerSuite)) +} + +func (s *ExtendedIndexerSuite) SetupTest() { + s.g = fixtures.NewGeneratorSuite(fixtures.WithChainID(flow.Testnet)) + + pdb, dbDir := unittest.TempPebbleDB(s.T()) + s.db = pebbleimpl.ToDB(pdb) + s.dbDir = dbDir + + s.headers = storagemock.NewHeaders(s.T()) + s.index = storagemock.NewIndex(s.T()) + s.guarantees = storagemock.NewGuarantees(s.T()) + s.collections = storagemock.NewCollections(s.T()) + s.events = storagemock.NewEvents(s.T()) + s.results = storagemock.NewLightTransactionResults(s.T()) +} + +func (s *ExtendedIndexerSuite) TearDownTest() { + if s.cancel != nil { + s.cancel() + } + if s.ext != nil { + unittest.RequireCloseBefore(s.T(), s.ext.Done(), testTimeout, "timeout waiting for shutdown") + } + + require.NoError(s.T(), s.db.Close()) + require.NoError(s.T(), os.RemoveAll(s.dbDir)) +} + +// configureStorage sets up storage mocks to return fixture data for exact IDs. +// Each mock uses exact argument matchers rather than mock.Anything. +// Expectations use Maybe() because timing-dependent tests may not call all of them. +// Correctness is verified via assertBackfilledBlockData/assertLiveBlockData assertions. +func (s *ExtendedIndexerSuite) configureStorage(blocks map[uint64]*blockFixtures) { + for height, block := range blocks { + blockID := block.Header.ID() + + s.headers.On("BlockIDByHeight", height).Return(blockID, nil).Maybe() + s.headers.On("ByBlockID", blockID).Return(block.Header, nil).Maybe() + s.index.On("ByBlockID", blockID).Return(block.Index, nil).Maybe() + s.events.On("ByBlockID", blockID).Return(block.Events, nil).Maybe() + + for _, guarantee := range block.Guarantees { + s.guarantees.On("ByID", guarantee.ID()).Return(guarantee, nil).Maybe() + } + + for _, collection := range block.Collections { + s.collections.On("ByID", collection.ID()).Return(collection, nil).Maybe() + } + } + + // Catch-all for heights not in the fixture map (e.g., when indexers overshoot the target). + s.headers.On("BlockIDByHeight", mock.AnythingOfType("uint64")).Maybe().Return(flow.ZeroID, storage.ErrNotFound) +} + +// newExtendedIndexer creates a new extended indexer with the given state, indexers, and backfill delay. +func (s *ExtendedIndexerSuite) newExtendedIndexer( + state protocol.State, + indexers []extended.Indexer, + backfillDelay time.Duration, +) { + ext, err := extended.NewExtendedIndexer( + unittest.Logger(), + metrics.NewNoopCollector(), + s.db, + storage.NewTestingLockManager(), + state, + s.index, + s.headers, + s.guarantees, + s.collections, + s.events, + s.results, + indexers, + flow.Testnet, + backfillDelay, + ) + require.NoError(s.T(), err) + s.ext = ext +} + +// startComponent starts the extended indexer with an irrecoverable signaler context that requires no +// errors are thrown +func (s *ExtendedIndexerSuite) startComponent() { + ctx, cancel := context.WithCancel(context.Background()) + s.cancel = cancel + signalerCtx := irrecoverable.NewMockSignalerContext(s.T(), ctx) + s.ext.Start(signalerCtx) + unittest.RequireComponentsReadyBefore(s.T(), testTimeout, s.ext) +} + +// startComponentWithCallback starts the extended indexer with an irrecoverable signaler context that +// calls the provided callback when an error is thrown. +func (s *ExtendedIndexerSuite) startComponentWithCallback(fn func(error)) { + ctx, cancel := context.WithCancel(context.Background()) + s.cancel = cancel + signalerCtx := irrecoverable.NewMockSignalerContextWithCallback(s.T(), ctx, fn) + s.ext.Start(signalerCtx) + unittest.RequireComponentsReadyBefore(s.T(), testTimeout, s.ext) +} + +// provideBlock provides a block to the extended indexer. +// This is used when testing backfill mode and the actual block data is not read +func (s *ExtendedIndexerSuite) provideBlock(height uint64) { + header := s.g.Headers().Fixture(fixtures.Header.WithHeight(height)) + require.NoError(s.T(), s.ext.IndexBlockData(header, nil, nil)) +} + +// provideLiveBlock provides a live block to the extended indexer with complete data. +func (s *ExtendedIndexerSuite) provideLiveBlock(block *blockFixtures) { + require.NoError(s.T(), s.ext.IndexBlockData(block.Header, block.allTransactions(), block.Events)) +} + +// ===== Assertions ===== + +// assertBackfilledBlockData verifies that the received BlockData for a backfilled block contains +// the expected user transactions from the guarantee->collection->transaction pipeline, followed by +// system transactions appended by the system collection builder, and all events grouped by tx index. +func (s *ExtendedIndexerSuite) assertBackfilledBlockData(m *mockIndexer, fixture *blockFixtures) { + s.T().Helper() + data := m.blockDataForHeight(fixture.Header.Height) + require.NotNil(s.T(), data, "no block data received for height %d", fixture.Header.Height) + + assert.Equal(s.T(), fixture.Header, data.Header) + + // Backfilled data should contain user transactions + system transactions in exact order. + expectedTxs := fixture.allTransactions() + require.Len(s.T(), data.Transactions, len(expectedTxs), + "transaction count mismatch at height %d: expected %d user + %d system = %d total, got %d", + fixture.Header.Height, + len(fixture.userTransactions()), len(fixture.SystemCollection.Transactions), len(expectedTxs), + len(data.Transactions)) + + for i, expectedTx := range expectedTxs { + assert.Equal(s.T(), expectedTx.ID(), data.Transactions[i].ID(), "transaction %d mismatch at height %d", i, fixture.Header.Height) + } + + s.assertEventGroups(data.Events, fixture.Events) +} + +// assertLiveBlockData verifies that the received BlockData for a live block matches +// the expected fixture data: user transactions followed by system transactions, and all +// events grouped by tx index. +func (s *ExtendedIndexerSuite) assertLiveBlockData(m *mockIndexer, fixture *blockFixtures) { + s.T().Helper() + data := m.blockDataForHeight(fixture.Header.Height) + require.NotNil(s.T(), data, "no block data received for height %d", fixture.Header.Height) + + assert.Equal(s.T(), fixture.Header, data.Header) + + // Live data contains user transactions followed by system transactions. + expectedTxs := fixture.allTransactions() + + require.Len(s.T(), data.Transactions, len(expectedTxs), "transaction count mismatch at height %d", fixture.Header.Height) + for i, expectedTx := range expectedTxs { + assert.Equal(s.T(), expectedTx.ID(), data.Transactions[i].ID(), "transaction %d mismatch at height %d", i, fixture.Header.Height) + } + + s.assertEventGroups(data.Events, fixture.Events) +} + +// assertEventGroups verifies that the actual events match the expected events. +func (s *ExtendedIndexerSuite) assertEventGroups(actual []flow.Event, allEvents []flow.Event) { + s.T().Helper() + assert.Equal(s.T(), allEvents, actual) +} + +// ===== Tests ===== + +// TestAllLive verifies that when all indexers are caught up to the live height, +// calling IndexBlockData processes the block for all indexers in a single iteration. +func (s *ExtendedIndexerSuite) TestAllLive() { + liveHeight := uint64(11) + + block := generateBlockFixtures(s.T(), s.g, liveHeight) + + idx1 := newMockIndexer(s.T(), "a", liveHeight, liveHeight) + idx2 := newMockIndexer(s.T(), "b", liveHeight, liveHeight) + + s.newExtendedIndexer(protocolmock.NewState(s.T()), []extended.Indexer{idx1, idx2}, time.Hour) + s.startComponent() + + s.provideLiveBlock(block) + + unittest.RequireCloseBefore(s.T(), idx1.done, testTimeout, "timeout waiting for idx1") + unittest.RequireCloseBefore(s.T(), idx2.done, testTimeout, "timeout waiting for idx2") + + s.assertLiveBlockData(idx1, block) + s.assertLiveBlockData(idx2, block) +} + +// TestAllBackfilling verifies that when all indexers are behind, the timer-driven +// loop fetches data from storage and processes each indexer independently until they reach a target. +func (s *ExtendedIndexerSuite) TestAllBackfilling() { + blocks := make(map[uint64]*blockFixtures) + for h := uint64(2); h <= 6; h++ { + blocks[h] = generateBlockFixtures(s.T(), s.g, h) + } + s.configureStorage(blocks) + + // idx1 starts at 2, idx2 starts at 4 -- both backfill from storage. + idx1 := newMockIndexer(s.T(), "a", 2, 6) + idx2 := newMockIndexer(s.T(), "b", 4, 6) + + s.newExtendedIndexer(newMockState(s.T()), []extended.Indexer{idx1, idx2}, time.Millisecond) + s.startComponent() + + // No IndexBlockData call -- backfill is driven entirely by the timer and storage. + unittest.RequireCloseBefore(s.T(), idx1.done, testTimeout, "timeout waiting for idx1 backfill") + unittest.RequireCloseBefore(s.T(), idx2.done, testTimeout, "timeout waiting for idx2 backfill") + + // Verify backfilled data exercises the guarantee->collection->transaction pipeline. + for h := uint64(2); h <= 6; h++ { + s.assertBackfilledBlockData(idx1, blocks[h]) + } + for h := uint64(4); h <= 6; h++ { + s.assertBackfilledBlockData(idx2, blocks[h]) + } +} + +// TestSplitLiveAndBackfill verifies that one indexer processes live data immediately +// while another backfills from storage concurrently in the same iteration loop. +func (s *ExtendedIndexerSuite) TestSplitLiveAndBackfill() { + liveHeight := uint64(8) + + // Generate storage fixtures for all heights that may be queried during backfill. + // The live indexer at liveHeight may also attempt a storage lookup before the live block arrives. + blocks := make(map[uint64]*blockFixtures) + for h := uint64(3); h <= liveHeight; h++ { + blocks[h] = generateBlockFixtures(s.T(), s.g, h) + } + s.configureStorage(blocks) + + liveIdx := newMockIndexer(s.T(), "live", liveHeight, liveHeight) + backfillIdx := newMockIndexer(s.T(), "backfill", 3, liveHeight) + + s.newExtendedIndexer(newMockState(s.T()), []extended.Indexer{liveIdx, backfillIdx}, time.Millisecond) + s.startComponent() + + // Use provideLiveBlock so both the live and backfill paths use the same block header and data. + // This allows asserting height liveHeight for all indexers regardless of which path was used. + s.provideLiveBlock(blocks[liveHeight]) + + unittest.RequireCloseBefore(s.T(), liveIdx.done, testTimeout, "timeout waiting for live indexer") + unittest.RequireCloseBefore(s.T(), backfillIdx.done, testTimeout, "timeout waiting for backfill indexer") + + // Verify the live indexer received the correct data at liveHeight. + s.assertLiveBlockData(liveIdx, blocks[liveHeight]) + + // Verify backfilled data for all heights, including liveHeight. + // backfillIdx may process liveHeight via either the live or storage path, but both + // produce the same data since provideLiveBlock provides allTransactions(). + for h := uint64(3); h <= liveHeight; h++ { + s.assertBackfilledBlockData(backfillIdx, blocks[h]) + } +} + +// TestCatchUpAndContinueLive verifies that an indexer backfills from storage, +// catches up to the live height, and then processes subsequent live blocks via IndexBlockData. +func (s *ExtendedIndexerSuite) TestCatchUpAndContinueLive() { + liveHeight := uint64(5) + + // Generate storage fixtures for heights 2..liveHeight+1 so the backfill can access all needed data. + blocks := make(map[uint64]*blockFixtures) + for h := uint64(2); h <= liveHeight+1; h++ { + blocks[h] = generateBlockFixtures(s.T(), s.g, h) + } + s.configureStorage(blocks) + + // idx starts at height 2, needs to backfill 2..5, then process live block at 6. + idx := newMockIndexer(s.T(), "a", 2, liveHeight+1) + + s.newExtendedIndexer(newMockState(s.T()), []extended.Indexer{idx}, time.Millisecond) + s.startComponent() + + // Wait until the indexer has processed at least one block from storage before providing + // the live block, ensuring the "catch up" path is exercised. + require.Eventually(s.T(), func() bool { + return idx.nextHeight.Load() > 2 + }, testTimeout, time.Millisecond, "indexer should have made backfill progress from storage") + + // Provide a live block -- the indexer should process it after catching up. + s.provideBlock(liveHeight + 1) + + unittest.RequireCloseBefore(s.T(), idx.done, testTimeout, "timeout waiting for catch-up and live processing") + + // Verify backfilled data for heights that came from storage. + for h := uint64(2); h <= liveHeight; h++ { + s.assertBackfilledBlockData(idx, blocks[h]) + } +} + +// TestUninitializedBeforeLiveData verifies that when the component starts and no +// IndexBlockData has been called yet, the timer-driven loop still processes blocks from storage. +func (s *ExtendedIndexerSuite) TestUninitializedBeforeLiveData() { + blocks := make(map[uint64]*blockFixtures) + for h := uint64(5); h <= 8; h++ { + blocks[h] = generateBlockFixtures(s.T(), s.g, h) + } + s.configureStorage(blocks) + + // Indexer starts at height 5 -- storage has data, but no live block provided. + idx := newMockIndexer(s.T(), "a", 5, 8) + + s.newExtendedIndexer(newMockState(s.T()), []extended.Indexer{idx}, time.Millisecond) + s.startComponent() + + // No IndexBlockData call. hasBackfillingIndexers returns true when latestBlockData==nil, + // so the timer keeps firing and blockData fetches from storage. + unittest.RequireCloseBefore(s.T(), idx.done, testTimeout, "timeout waiting for processing without live data") + + for h := uint64(5); h <= 8; h++ { + s.assertBackfilledBlockData(idx, blocks[h]) + } +} + +// TestBackfillStorageNotFound verifies that when a live block has been received and storage +// returns ErrNotFound for a backfill height below the live height, the error is thrown via +// the irrecoverable context. Once a live block is known, all prior heights must be present +// in storage; a missing block indicates database inconsistency. +func (s *ExtendedIndexerSuite) TestBackfillStorageNotFound() { + s.headers.On("BlockIDByHeight", uint64(3)).Return(flow.ZeroID, storage.ErrNotFound) + + idx := extendedmock.NewIndexer(s.T()) + idx.On("NextHeight").Return(uint64(3), nil) + + s.newExtendedIndexer(newMockState(s.T()), []extended.Indexer{idx}, time.Millisecond) + + // Provide a live block at height 5 before starting so latestBlockData is set from the + // first iteration. Height 3 is below the live height and must be in storage. + s.provideBlock(5) + + thrown := make(chan error, 1) + s.startComponentWithCallback(func(err error) { + thrown <- err + }) + + select { + case err := <-thrown: + assert.ErrorIs(s.T(), err, storage.ErrNotFound) + case <-time.After(testTimeout): + s.T().Fatal("timeout waiting for thrown error") + } +} + +// TestBackfillRetryOnNotFound verifies that when no live block has been received yet and +// storage returns ErrNotFound, the indexer retries on subsequent timer ticks rather than +// treating it as a fatal error. Once storage has the data, the indexer processes it successfully. +func (s *ExtendedIndexerSuite) TestBackfillRetryOnNotFound() { + block := generateBlockFixtures(s.T(), s.g, 5) + blockID := block.Header.ID() + + // BlockIDByHeight returns ErrNotFound until the available flag is set. + available := atomic.NewBool(false) + s.headers. + On("BlockIDByHeight", uint64(5)). + Return(func(uint64) (flow.Identifier, error) { + if !available.Load() { + return flow.ZeroID, storage.ErrNotFound + } + return blockID, nil + }) + + // Remaining storage mocks are only called after available=true. + s.headers.On("ByBlockID", blockID).Return(block.Header, nil) + s.index.On("ByBlockID", blockID).Return(block.Index, nil) + s.events.On("ByBlockID", blockID).Return(block.Events, nil) + for _, guarantee := range block.Guarantees { + s.guarantees.On("ByID", guarantee.ID()).Return(guarantee, nil) + } + for _, collection := range block.Collections { + s.collections.On("ByID", collection.ID()).Return(collection, nil) + } + + idx := newMockIndexer(s.T(), "a", 5, 5) + + s.newExtendedIndexer(newMockState(s.T()), []extended.Indexer{idx}, time.Millisecond) + s.startComponent() + + // Let a few timer iterations pass with ErrNotFound -- indexer should not have advanced. + require.Never(s.T(), func() bool { + return idx.nextHeight.Load() > 5 // startHeight + }, 50*time.Millisecond, time.Millisecond, "indexer should not have advanced") + + // Make data available -- next timer tick should process it. + available.Store(true) + + unittest.RequireCloseBefore(s.T(), idx.done, testTimeout, "timeout waiting for indexer after data became available") + assert.Equal(s.T(), uint64(6), idx.nextHeight.Load()) + + s.assertBackfilledBlockData(idx, block) +} + +// ===== Error Handling Tests ===== + +// TestIndexerError verifies that when a sub-indexer returns an unexpected error, +// it is thrown via the irrecoverable context. +func (s *ExtendedIndexerSuite) TestIndexerError() { + liveHeight := uint64(11) + indexerErr := errors.New("indexer failed") + + idx := extendedmock.NewIndexer(s.T()) + idx.On("Name").Return("a") + idx.On("NextHeight").Return(liveHeight, nil) + idx.On("IndexBlockData", mock.Anything, mock.Anything, mock.Anything).Return(indexerErr).Once() + + s.newExtendedIndexer(protocolmock.NewState(s.T()), []extended.Indexer{idx}, time.Hour) + + thrown := make(chan error, 1) + s.startComponentWithCallback(func(err error) { + thrown <- err + }) + + s.provideBlock(liveHeight) + + select { + case err := <-thrown: + s.Assert().ErrorIs(err, indexerErr) + case <-time.After(testTimeout): + s.T().Fatal("timeout waiting for thrown error") + } +} + +// TestBackfillError verifies that errors during backfill are thrown via the irrecoverable context. +func (s *ExtendedIndexerSuite) TestBackfillError() { + block := generateBlockFixtures(s.T(), s.g, 3) + s.configureStorage(map[uint64]*blockFixtures{3: block}) + + backfillErr := errors.New("backfill failed") + + idx := extendedmock.NewIndexer(s.T()) + idx.On("Name").Return("a") + idx.On("NextHeight").Return(uint64(3), nil) + idx.On("IndexBlockData", mock.Anything, mock.Anything, mock.Anything).Return(backfillErr).Once() + + s.newExtendedIndexer(newMockState(s.T()), []extended.Indexer{idx}, time.Millisecond) + + thrown := make(chan error, 1) + s.startComponentWithCallback(func(err error) { + thrown <- err + }) + + select { + case err := <-thrown: + s.Assert().ErrorIs(err, backfillErr) + case <-time.After(testTimeout): + s.T().Fatal("timeout waiting for thrown error") + } +} + +// TestAlreadyIndexedSkipped verifies that ErrAlreadyIndexed from a sub-indexer +// is treated as a skip rather than an error. +func (s *ExtendedIndexerSuite) TestAlreadyIndexedSkipped() { + liveHeight := uint64(11) + + idx1 := extendedmock.NewIndexer(s.T()) + idx2 := extendedmock.NewIndexer(s.T()) + idx2.On("Name").Return("b") + idx1.On("NextHeight").Return(liveHeight, nil) + idx2.On("NextHeight").Return(liveHeight, nil) + // idx1 returns ErrAlreadyIndexed — should be skipped without error + idx1.On("IndexBlockData", mock.Anything, mock.Anything, mock.Anything). + Return(extended.ErrAlreadyIndexed).Once() + + // idx2 succeeds — signals done + done := make(chan struct{}) + idx2.On("IndexBlockData", mock.Anything, mock.Anything, mock.Anything). + Return(nil).Once().Run(func(args mock.Arguments) { + close(done) + }) + + s.newExtendedIndexer(protocolmock.NewState(s.T()), []extended.Indexer{idx1, idx2}, time.Hour) + s.startComponent() + + s.provideBlock(liveHeight) + + unittest.RequireCloseBefore(s.T(), done, testTimeout, "timeout waiting for idx2") +} + +// TestNonSequentialHeight verifies that IndexBlockData rejects non-sequential heights +// after the first block has been provided. +func (s *ExtendedIndexerSuite) TestNonSequentialHeight() { + idx := newMockIndexer(s.T(), "a", 11, 0) + s.newExtendedIndexer(protocolmock.NewState(s.T()), []extended.Indexer{idx}, time.Hour) + s.startComponent() + + // First call succeeds + s.provideBlock(11) + + // Non-sequential height is rejected + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(13)) + err := s.ext.IndexBlockData(header, nil, nil) + s.Assert().Error(err) + s.Assert().Contains(err.Error(), fmt.Sprintf("unexpected block received: expected height %d, got %d", 12, 13)) +} + +// mockIndexer wraps the mock with atomic state tracking. +type mockIndexer struct { + *extendedmock.Indexer + nextHeight *atomic.Uint64 + done chan struct{} + receivedData sync.Map // maps uint64 (height) -> extended.BlockData +} + +// blockDataForHeight returns the BlockData received for the given height, or nil if not received. +func (m *mockIndexer) blockDataForHeight(height uint64) *extended.BlockData { + val, ok := m.receivedData.Load(height) + if !ok { + return nil + } + data := val.(extended.BlockData) + return &data +} + +// newMockIndexer creates a mock indexer using an atomic counter for NextHeight. +// Each successful IndexBlockData call advances the counter to data.Header.Height + 1. +// The done channel is closed when the targetHeight is processed (0 means never). +func newMockIndexer( + t *testing.T, + name string, + startHeight uint64, + targetHeight uint64, +) *mockIndexer { + idx := extendedmock.NewIndexer(t) + nextHeight := atomic.NewUint64(startHeight) + done := make(chan struct{}) + var doneOnce sync.Once + + m := &mockIndexer{Indexer: idx, nextHeight: nextHeight, done: done} + + idx.On("Name").Return(name) + + idx.On("NextHeight").Return(func() (uint64, error) { + return nextHeight.Load(), nil + }) + idx.On("IndexBlockData", mock.Anything, mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + data := args.Get(1).(extended.BlockData) + nextHeight.Store(data.Header.Height + 1) + m.receivedData.Store(data.Header.Height, data) + if targetHeight > 0 && data.Header.Height == targetHeight { + doneOnce.Do(func() { close(done) }) + } + }). + Return(nil) + + return m +} + +// newMockState returns a mock protocol.State where Params().SporkRootBlockHeight() returns 0. +func newMockState(t *testing.T) protocol.State { + params := protocolmock.NewParams(t) + params.On("SporkRootBlockHeight").Return(uint64(0)) + + state := protocolmock.NewState(t) + state.On("Params").Return(params) + return state +} + +// blockFixtures holds all data for a single block used in suite tests. +type blockFixtures struct { + Header *flow.Header + Index *flow.Index + Events []flow.Event + Guarantees []*flow.CollectionGuarantee + Collections []*flow.Collection + SystemCollection *flow.Collection +} + +// userTransactions returns all transactions from the block's user collections. +func (b *blockFixtures) userTransactions() []*flow.TransactionBody { + var txs []*flow.TransactionBody + for _, coll := range b.Collections { + txs = append(txs, coll.Transactions...) + } + return txs +} + +// allTransactions returns user transactions followed by system transactions. +func (b *blockFixtures) allTransactions() []*flow.TransactionBody { + txs := b.userTransactions() + txs = append(txs, b.SystemCollection.Transactions...) + return txs +} + +// generateBlockFixtures creates internally consistent fixture data for a block at the given height. +// The returned blockFixtures contain complete data including user collections, system transactions, +// and events. +func generateBlockFixtures(t *testing.T, g *fixtures.GeneratorSuite, height uint64) *blockFixtures { + // CompleteFixture takes a parent block and creates a child, so use height-1 for the parent + // to get the resulting block at the desired height. + parent := g.Blocks().Fixture(fixtures.Block.WithHeight(height - 1)) + fixture := testutil.CompleteFixture(t, g, parent) + require.Equal(t, height, fixture.Block.Height, "generated block has unexpected height") + + // Extract system collection from the last chunk (system chunk). + // Note: ExpectedCollections contains only user collections; the system collection + // is stored in the last ChunkExecutionData, not in ExpectedCollections. + chunks := fixture.ExecutionData.ChunkExecutionDatas + systemCollection := chunks[len(chunks)-1].Collection + + return &blockFixtures{ + Header: fixture.Block.ToHeader(), + Collections: fixture.ExpectedCollections, + Guarantees: fixture.Guarantees, + Events: fixture.ExpectedEvents, + Index: fixture.Index, + SystemCollection: systemCollection, + } +} diff --git a/module/state_synchronization/indexer/extended/helpers.go b/module/state_synchronization/indexer/extended/helpers.go new file mode 100644 index 00000000000..5811d2dadca --- /dev/null +++ b/module/state_synchronization/indexer/extended/helpers.go @@ -0,0 +1,60 @@ +package extended + +import ( + "errors" + "fmt" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// groupEventsByTxIndex returns a map of events grouped by transaction index in the original event order. +func groupEventsByTxIndex(events []flow.Event) map[uint32][]flow.Event { + eventsByTxIndex := make(map[uint32][]flow.Event) + for _, event := range events { + eventsByTxIndex[event.TransactionIndex] = append(eventsByTxIndex[event.TransactionIndex], event) + } + return eventsByTxIndex +} + +// flattenEvents converts a map of events grouped by transaction index into a flat slice. +// The order of events within each transaction group is preserved, but the order across groups is +// non-deterministic. Returns nil for nil or empty input. +func flattenEvents(eventsByTxIndex map[uint32][]flow.Event) []flow.Event { + if len(eventsByTxIndex) == 0 { + return nil + } + var events []flow.Event + for _, txEvents := range eventsByTxIndex { + events = append(events, txEvents...) + } + return events +} + +// heightProvider is the common interface between FT and NFT bootstrapper stores needed to +// determine the next height to index. +type heightProvider interface { + LatestIndexedHeight() (uint64, error) + UninitializedFirstHeight() (uint64, bool) +} + +// nextHeight computes the next height for a store that implements [heightProvider]. +// +// No error returns are expected during normal operation. +func nextHeight(store heightProvider) (uint64, error) { + height, err := store.LatestIndexedHeight() + if err == nil { + return height + 1, nil + } + + if !errors.Is(err, storage.ErrNotBootstrapped) { + return 0, fmt.Errorf("failed to get latest indexed height: %w", err) + } + + firstHeight, isInitialized := store.UninitializedFirstHeight() + if isInitialized { + return 0, fmt.Errorf("failed to get latest indexed height, but index is initialized: %w", err) + } + + return firstHeight, nil +} diff --git a/module/state_synchronization/indexer/extended/helpers_test.go b/module/state_synchronization/indexer/extended/helpers_test.go new file mode 100644 index 00000000000..1637035ed55 --- /dev/null +++ b/module/state_synchronization/indexer/extended/helpers_test.go @@ -0,0 +1,167 @@ +package extended + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// mockHeightProvider is a simple mock implementing the heightProvider interface. +type mockHeightProvider struct { + latestHeight uint64 + latestHeightErr error + firstHeight uint64 + isInitialized bool +} + +func (m *mockHeightProvider) LatestIndexedHeight() (uint64, error) { + return m.latestHeight, m.latestHeightErr +} + +func (m *mockHeightProvider) UninitializedFirstHeight() (uint64, bool) { + return m.firstHeight, m.isInitialized +} + +// ===== TestNextHeight ===== + +func TestNextHeight(t *testing.T) { + t.Parallel() + + t.Run("initialized store returns latestHeight+1", func(t *testing.T) { + store := &mockHeightProvider{ + latestHeight: 99, + latestHeightErr: nil, + } + + height, err := nextHeight(store) + require.NoError(t, err) + assert.Equal(t, uint64(100), height) + }) + + t.Run("uninitialized store returns firstHeight", func(t *testing.T) { + store := &mockHeightProvider{ + latestHeightErr: storage.ErrNotBootstrapped, + firstHeight: 42, + isInitialized: false, + } + + height, err := nextHeight(store) + require.NoError(t, err) + assert.Equal(t, uint64(42), height) + }) + + t.Run("unexpected error from LatestIndexedHeight propagates", func(t *testing.T) { + unexpectedErr := fmt.Errorf("disk I/O error") + store := &mockHeightProvider{ + latestHeightErr: unexpectedErr, + } + + _, err := nextHeight(store) + require.Error(t, err) + assert.ErrorIs(t, err, unexpectedErr) + }) + + t.Run("inconsistent state: not bootstrapped but isInitialized returns error", func(t *testing.T) { + store := &mockHeightProvider{ + latestHeightErr: storage.ErrNotBootstrapped, + firstHeight: 42, + isInitialized: true, + } + + _, err := nextHeight(store) + require.Error(t, err) + assert.Contains(t, err.Error(), "but index is initialized") + }) +} + +// ===== TestFlattenEvents ===== + +func TestFlattenEvents(t *testing.T) { + t.Parallel() + + t.Run("nil map returns nil", func(t *testing.T) { + result := flattenEvents(nil) + assert.Nil(t, result) + }) + + t.Run("empty map returns nil", func(t *testing.T) { + result := flattenEvents(map[uint32][]flow.Event{}) + assert.Nil(t, result) + }) + + t.Run("single tx single event", func(t *testing.T) { + event := flow.Event{TransactionIndex: 0, EventIndex: 0, Type: "A.Test.Foo"} + result := flattenEvents(map[uint32][]flow.Event{ + 0: {event}, + }) + require.Len(t, result, 1) + assert.Equal(t, event, result[0]) + }) + + t.Run("single tx multiple events preserves order", func(t *testing.T) { + event0 := flow.Event{TransactionIndex: 0, EventIndex: 0, Type: "A.Test.First"} + event1 := flow.Event{TransactionIndex: 0, EventIndex: 1, Type: "A.Test.Second"} + event2 := flow.Event{TransactionIndex: 0, EventIndex: 2, Type: "A.Test.Third"} + result := flattenEvents(map[uint32][]flow.Event{ + 0: {event0, event1, event2}, + }) + require.Len(t, result, 3) + assert.Equal(t, event0, result[0]) + assert.Equal(t, event1, result[1]) + assert.Equal(t, event2, result[2]) + }) + + t.Run("multiple txs multiple events all included", func(t *testing.T) { + eventsA := []flow.Event{ + {TransactionIndex: 0, EventIndex: 0, Type: "A.Test.A0"}, + {TransactionIndex: 0, EventIndex: 1, Type: "A.Test.A1"}, + } + eventsB := []flow.Event{ + {TransactionIndex: 1, EventIndex: 0, Type: "A.Test.B0"}, + } + eventsC := []flow.Event{ + {TransactionIndex: 2, EventIndex: 0, Type: "A.Test.C0"}, + {TransactionIndex: 2, EventIndex: 1, Type: "A.Test.C1"}, + {TransactionIndex: 2, EventIndex: 2, Type: "A.Test.C2"}, + } + result := flattenEvents(map[uint32][]flow.Event{ + 0: eventsA, + 1: eventsB, + 2: eventsC, + }) + require.Len(t, result, 6) + + // Map iteration order is non-deterministic, so verify all events are present + // by checking set membership rather than exact ordering across tx groups. + eventTypes := make(map[flow.EventType]bool) + for _, e := range result { + eventTypes[e.Type] = true + } + assert.True(t, eventTypes["A.Test.A0"]) + assert.True(t, eventTypes["A.Test.A1"]) + assert.True(t, eventTypes["A.Test.B0"]) + assert.True(t, eventTypes["A.Test.C0"]) + assert.True(t, eventTypes["A.Test.C1"]) + assert.True(t, eventTypes["A.Test.C2"]) + }) + + t.Run("events order is preserved within each tx group", func(t *testing.T) { + events := []flow.Event{ + {TransactionIndex: 5, EventIndex: 0, Type: "A.Test.First"}, + {TransactionIndex: 5, EventIndex: 1, Type: "A.Test.Second"}, + {TransactionIndex: 5, EventIndex: 2, Type: "A.Test.Third"}, + } + result := flattenEvents(map[uint32][]flow.Event{ + 5: events, + }) + require.Len(t, result, 3) + for i, e := range result { + assert.Equal(t, events[i], e) + } + }) +} diff --git a/module/state_synchronization/indexer/extended/indexer.go b/module/state_synchronization/indexer/extended/indexer.go new file mode 100644 index 00000000000..dbf852c425c --- /dev/null +++ b/module/state_synchronization/indexer/extended/indexer.go @@ -0,0 +1,75 @@ +package extended + +import ( + "errors" + + "github.com/jordanschalm/lockctx" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/storage" +) + +var ( + ErrAlreadyIndexed = errors.New("data already indexed for height") + ErrFutureHeight = errors.New("cannot index future height") +) + +type BlockData struct { + Header *flow.Header + Transactions []*flow.TransactionBody + Events []flow.Event +} + +type Indexer interface { + // Name returns the name of the indexer. + Name() string + + // IndexBlockData indexes the block data for the given height. + // If the header in `data` does not match the expected height, an error is returned. + // + // CAUTION: Not safe for concurrent use. + // + // Expected error returns during normal operations: + // - [ErrAlreadyIndexed]: if the data is already indexed for the height. + // - [ErrFutureHeight]: if the data is for a future height. + IndexBlockData(lctx lockctx.Proof, data BlockData, batch storage.ReaderBatchWriter) error + + // NextHeight returns the next height that the indexer will index. + // + // No error returns are expected during normal operation. + NextHeight() (uint64, error) +} + +// IndexerManager orchestrates indexing for all extended indexers. It handles both indexing from the +// latest block submitted via the Index methods, and backfilling from storage. +type IndexerManager interface { + // IndexBlockExecutionData indexes the block data for the given height. + // If the header in `data` does not match the expected height, an error is returned. + // + // Not safe for concurrent use. + // + // No error returns are expected during normal operation. + IndexBlockExecutionData(data *execution_data.BlockExecutionDataEntity) error + + // IndexBlockData indexes the block data for the given height. + // If the header in `data` does not match the expected height, an error is returned. + // + // Not safe for concurrent use. + // + // No error returns are expected during normal operation. + IndexBlockData(header *flow.Header, transactions []*flow.TransactionBody, events []flow.Event) error +} + +// IndexProcessor is a helper interface for indexers that need to process the block data and return +// indexed data for a specific type. The second type parameter M allows each indexer to return +// indexer-specific metadata alongside the indexed entries. +// +// Safe for concurrent use. +type IndexProcessor[T any, M any] interface { + // ProcessBlockData processes the block data and returns the indexed data for the given type + // along with indexer-specific metadata. + // + // No error returns are expected during normal operation. + ProcessBlockData(data BlockData) ([]T, M, error) +} diff --git a/module/state_synchronization/indexer/extended/mock/contract_script_executor.go b/module/state_synchronization/indexer/extended/mock/contract_script_executor.go new file mode 100644 index 00000000000..8bbd2a15084 --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/contract_script_executor.go @@ -0,0 +1,113 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "context" + + "github.com/onflow/flow-go/model/flow" + mock "github.com/stretchr/testify/mock" +) + +// newContractScriptExecutor creates a new instance of contractScriptExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newContractScriptExecutor(t interface { + mock.TestingT + Cleanup(func()) +}) *contractScriptExecutor { + mock := &contractScriptExecutor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// contractScriptExecutor is an autogenerated mock type for the contractScriptExecutor type +type contractScriptExecutor struct { + mock.Mock +} + +type contractScriptExecutor_Expecter struct { + mock *mock.Mock +} + +func (_m *contractScriptExecutor) EXPECT() *contractScriptExecutor_Expecter { + return &contractScriptExecutor_Expecter{mock: &_m.Mock} +} + +// GetAccountAtBlockHeight provides a mock function for the type contractScriptExecutor +func (_mock *contractScriptExecutor) GetAccountAtBlockHeight(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error) { + ret := _mock.Called(ctx, address, height) + + if len(ret) == 0 { + panic("no return value specified for GetAccountAtBlockHeight") + } + + var r0 *flow.Account + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) (*flow.Account, error)); ok { + return returnFunc(ctx, address, height) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Address, uint64) *flow.Account); ok { + r0 = returnFunc(ctx, address, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*flow.Account) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, flow.Address, uint64) error); ok { + r1 = returnFunc(ctx, address, height) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// contractScriptExecutor_GetAccountAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAccountAtBlockHeight' +type contractScriptExecutor_GetAccountAtBlockHeight_Call struct { + *mock.Call +} + +// GetAccountAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - address flow.Address +// - height uint64 +func (_e *contractScriptExecutor_Expecter) GetAccountAtBlockHeight(ctx interface{}, address interface{}, height interface{}) *contractScriptExecutor_GetAccountAtBlockHeight_Call { + return &contractScriptExecutor_GetAccountAtBlockHeight_Call{Call: _e.mock.On("GetAccountAtBlockHeight", ctx, address, height)} +} + +func (_c *contractScriptExecutor_GetAccountAtBlockHeight_Call) Run(run func(ctx context.Context, address flow.Address, height uint64)) *contractScriptExecutor_GetAccountAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Address + if args[1] != nil { + arg1 = args[1].(flow.Address) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *contractScriptExecutor_GetAccountAtBlockHeight_Call) Return(account *flow.Account, err error) *contractScriptExecutor_GetAccountAtBlockHeight_Call { + _c.Call.Return(account, err) + return _c +} + +func (_c *contractScriptExecutor_GetAccountAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, address flow.Address, height uint64) (*flow.Account, error)) *contractScriptExecutor_GetAccountAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/mock/height_provider.go b/module/state_synchronization/indexer/extended/mock/height_provider.go new file mode 100644 index 00000000000..26778b06ce7 --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/height_provider.go @@ -0,0 +1,142 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// newHeightProvider creates a new instance of heightProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newHeightProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *heightProvider { + mock := &heightProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// heightProvider is an autogenerated mock type for the heightProvider type +type heightProvider struct { + mock.Mock +} + +type heightProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *heightProvider) EXPECT() *heightProvider_Expecter { + return &heightProvider_Expecter{mock: &_m.Mock} +} + +// LatestIndexedHeight provides a mock function for the type heightProvider +func (_mock *heightProvider) LatestIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// heightProvider_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type heightProvider_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *heightProvider_Expecter) LatestIndexedHeight() *heightProvider_LatestIndexedHeight_Call { + return &heightProvider_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *heightProvider_LatestIndexedHeight_Call) Run(run func()) *heightProvider_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *heightProvider_LatestIndexedHeight_Call) Return(v uint64, err error) *heightProvider_LatestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *heightProvider_LatestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *heightProvider_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// UninitializedFirstHeight provides a mock function for the type heightProvider +func (_mock *heightProvider) UninitializedFirstHeight() (uint64, bool) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for UninitializedFirstHeight") + } + + var r0 uint64 + var r1 bool + if returnFunc, ok := ret.Get(0).(func() (uint64, bool)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() + } else { + r1 = ret.Get(1).(bool) + } + return r0, r1 +} + +// heightProvider_UninitializedFirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UninitializedFirstHeight' +type heightProvider_UninitializedFirstHeight_Call struct { + *mock.Call +} + +// UninitializedFirstHeight is a helper method to define mock.On call +func (_e *heightProvider_Expecter) UninitializedFirstHeight() *heightProvider_UninitializedFirstHeight_Call { + return &heightProvider_UninitializedFirstHeight_Call{Call: _e.mock.On("UninitializedFirstHeight")} +} + +func (_c *heightProvider_UninitializedFirstHeight_Call) Run(run func()) *heightProvider_UninitializedFirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *heightProvider_UninitializedFirstHeight_Call) Return(v uint64, b bool) *heightProvider_UninitializedFirstHeight_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *heightProvider_UninitializedFirstHeight_Call) RunAndReturn(run func() (uint64, bool)) *heightProvider_UninitializedFirstHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/mock/index_processor.go b/module/state_synchronization/indexer/extended/mock/index_processor.go new file mode 100644 index 00000000000..753d52467d0 --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/index_processor.go @@ -0,0 +1,107 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" + mock "github.com/stretchr/testify/mock" +) + +// NewIndexProcessor creates a new instance of IndexProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIndexProcessor[T any, M any](t interface { + mock.TestingT + Cleanup(func()) +}) *IndexProcessor[T, M] { + mock := &IndexProcessor[T, M]{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// IndexProcessor is an autogenerated mock type for the IndexProcessor type +type IndexProcessor[T any, M any] struct { + mock.Mock +} + +type IndexProcessor_Expecter[T any, M any] struct { + mock *mock.Mock +} + +func (_m *IndexProcessor[T, M]) EXPECT() *IndexProcessor_Expecter[T, M] { + return &IndexProcessor_Expecter[T, M]{mock: &_m.Mock} +} + +// ProcessBlockData provides a mock function for the type IndexProcessor +func (_mock *IndexProcessor[T, M]) ProcessBlockData(data extended.BlockData) ([]T, M, error) { + ret := _mock.Called(data) + + if len(ret) == 0 { + panic("no return value specified for ProcessBlockData") + } + + var r0 []T + var r1 M + var r2 error + if returnFunc, ok := ret.Get(0).(func(extended.BlockData) ([]T, M, error)); ok { + return returnFunc(data) + } + if returnFunc, ok := ret.Get(0).(func(extended.BlockData) []T); ok { + r0 = returnFunc(data) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]T) + } + } + if returnFunc, ok := ret.Get(1).(func(extended.BlockData) M); ok { + r1 = returnFunc(data) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(M) + } + } + if returnFunc, ok := ret.Get(2).(func(extended.BlockData) error); ok { + r2 = returnFunc(data) + } else { + r2 = ret.Error(2) + } + return r0, r1, r2 +} + +// IndexProcessor_ProcessBlockData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessBlockData' +type IndexProcessor_ProcessBlockData_Call[T any, M any] struct { + *mock.Call +} + +// ProcessBlockData is a helper method to define mock.On call +// - data extended.BlockData +func (_e *IndexProcessor_Expecter[T, M]) ProcessBlockData(data interface{}) *IndexProcessor_ProcessBlockData_Call[T, M] { + return &IndexProcessor_ProcessBlockData_Call[T, M]{Call: _e.mock.On("ProcessBlockData", data)} +} + +func (_c *IndexProcessor_ProcessBlockData_Call[T, M]) Run(run func(data extended.BlockData)) *IndexProcessor_ProcessBlockData_Call[T, M] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 extended.BlockData + if args[0] != nil { + arg0 = args[0].(extended.BlockData) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IndexProcessor_ProcessBlockData_Call[T, M]) Return(vs []T, v M, err error) *IndexProcessor_ProcessBlockData_Call[T, M] { + _c.Call.Return(vs, v, err) + return _c +} + +func (_c *IndexProcessor_ProcessBlockData_Call[T, M]) RunAndReturn(run func(data extended.BlockData) ([]T, M, error)) *IndexProcessor_ProcessBlockData_Call[T, M] { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/mock/indexer.go b/module/state_synchronization/indexer/extended/mock/indexer.go new file mode 100644 index 00000000000..63d6ed2abcf --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/indexer.go @@ -0,0 +1,199 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewIndexer creates a new instance of Indexer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIndexer(t interface { + mock.TestingT + Cleanup(func()) +}) *Indexer { + mock := &Indexer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// Indexer is an autogenerated mock type for the Indexer type +type Indexer struct { + mock.Mock +} + +type Indexer_Expecter struct { + mock *mock.Mock +} + +func (_m *Indexer) EXPECT() *Indexer_Expecter { + return &Indexer_Expecter{mock: &_m.Mock} +} + +// IndexBlockData provides a mock function for the type Indexer +func (_mock *Indexer) IndexBlockData(lctx lockctx.Proof, data extended.BlockData, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(lctx, data, batch) + + if len(ret) == 0 { + panic("no return value specified for IndexBlockData") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, extended.BlockData, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(lctx, data, batch) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Indexer_IndexBlockData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IndexBlockData' +type Indexer_IndexBlockData_Call struct { + *mock.Call +} + +// IndexBlockData is a helper method to define mock.On call +// - lctx lockctx.Proof +// - data extended.BlockData +// - batch storage.ReaderBatchWriter +func (_e *Indexer_Expecter) IndexBlockData(lctx interface{}, data interface{}, batch interface{}) *Indexer_IndexBlockData_Call { + return &Indexer_IndexBlockData_Call{Call: _e.mock.On("IndexBlockData", lctx, data, batch)} +} + +func (_c *Indexer_IndexBlockData_Call) Run(run func(lctx lockctx.Proof, data extended.BlockData, batch storage.ReaderBatchWriter)) *Indexer_IndexBlockData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 extended.BlockData + if args[1] != nil { + arg1 = args[1].(extended.BlockData) + } + var arg2 storage.ReaderBatchWriter + if args[2] != nil { + arg2 = args[2].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Indexer_IndexBlockData_Call) Return(err error) *Indexer_IndexBlockData_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Indexer_IndexBlockData_Call) RunAndReturn(run func(lctx lockctx.Proof, data extended.BlockData, batch storage.ReaderBatchWriter) error) *Indexer_IndexBlockData_Call { + _c.Call.Return(run) + return _c +} + +// Name provides a mock function for the type Indexer +func (_mock *Indexer) Name() string { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Name") + } + + var r0 string + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(string) + } + return r0 +} + +// Indexer_Name_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Name' +type Indexer_Name_Call struct { + *mock.Call +} + +// Name is a helper method to define mock.On call +func (_e *Indexer_Expecter) Name() *Indexer_Name_Call { + return &Indexer_Name_Call{Call: _e.mock.On("Name")} +} + +func (_c *Indexer_Name_Call) Run(run func()) *Indexer_Name_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Indexer_Name_Call) Return(s string) *Indexer_Name_Call { + _c.Call.Return(s) + return _c +} + +func (_c *Indexer_Name_Call) RunAndReturn(run func() string) *Indexer_Name_Call { + _c.Call.Return(run) + return _c +} + +// NextHeight provides a mock function for the type Indexer +func (_mock *Indexer) NextHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for NextHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Indexer_NextHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NextHeight' +type Indexer_NextHeight_Call struct { + *mock.Call +} + +// NextHeight is a helper method to define mock.On call +func (_e *Indexer_Expecter) NextHeight() *Indexer_NextHeight_Call { + return &Indexer_NextHeight_Call{Call: _e.mock.On("NextHeight")} +} + +func (_c *Indexer_NextHeight_Call) Run(run func()) *Indexer_NextHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Indexer_NextHeight_Call) Return(v uint64, err error) *Indexer_NextHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Indexer_NextHeight_Call) RunAndReturn(run func() (uint64, error)) *Indexer_NextHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/mock/indexer_manager.go b/module/state_synchronization/indexer/extended/mock/indexer_manager.go new file mode 100644 index 00000000000..323f9e323c8 --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/indexer_manager.go @@ -0,0 +1,152 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" + mock "github.com/stretchr/testify/mock" +) + +// NewIndexerManager creates a new instance of IndexerManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIndexerManager(t interface { + mock.TestingT + Cleanup(func()) +}) *IndexerManager { + mock := &IndexerManager{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// IndexerManager is an autogenerated mock type for the IndexerManager type +type IndexerManager struct { + mock.Mock +} + +type IndexerManager_Expecter struct { + mock *mock.Mock +} + +func (_m *IndexerManager) EXPECT() *IndexerManager_Expecter { + return &IndexerManager_Expecter{mock: &_m.Mock} +} + +// IndexBlockData provides a mock function for the type IndexerManager +func (_mock *IndexerManager) IndexBlockData(header *flow.Header, transactions []*flow.TransactionBody, events []flow.Event) error { + ret := _mock.Called(header, transactions, events) + + if len(ret) == 0 { + panic("no return value specified for IndexBlockData") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(*flow.Header, []*flow.TransactionBody, []flow.Event) error); ok { + r0 = returnFunc(header, transactions, events) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// IndexerManager_IndexBlockData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IndexBlockData' +type IndexerManager_IndexBlockData_Call struct { + *mock.Call +} + +// IndexBlockData is a helper method to define mock.On call +// - header *flow.Header +// - transactions []*flow.TransactionBody +// - events []flow.Event +func (_e *IndexerManager_Expecter) IndexBlockData(header interface{}, transactions interface{}, events interface{}) *IndexerManager_IndexBlockData_Call { + return &IndexerManager_IndexBlockData_Call{Call: _e.mock.On("IndexBlockData", header, transactions, events)} +} + +func (_c *IndexerManager_IndexBlockData_Call) Run(run func(header *flow.Header, transactions []*flow.TransactionBody, events []flow.Event)) *IndexerManager_IndexBlockData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + var arg1 []*flow.TransactionBody + if args[1] != nil { + arg1 = args[1].([]*flow.TransactionBody) + } + var arg2 []flow.Event + if args[2] != nil { + arg2 = args[2].([]flow.Event) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *IndexerManager_IndexBlockData_Call) Return(err error) *IndexerManager_IndexBlockData_Call { + _c.Call.Return(err) + return _c +} + +func (_c *IndexerManager_IndexBlockData_Call) RunAndReturn(run func(header *flow.Header, transactions []*flow.TransactionBody, events []flow.Event) error) *IndexerManager_IndexBlockData_Call { + _c.Call.Return(run) + return _c +} + +// IndexBlockExecutionData provides a mock function for the type IndexerManager +func (_mock *IndexerManager) IndexBlockExecutionData(data *execution_data.BlockExecutionDataEntity) error { + ret := _mock.Called(data) + + if len(ret) == 0 { + panic("no return value specified for IndexBlockExecutionData") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(*execution_data.BlockExecutionDataEntity) error); ok { + r0 = returnFunc(data) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// IndexerManager_IndexBlockExecutionData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IndexBlockExecutionData' +type IndexerManager_IndexBlockExecutionData_Call struct { + *mock.Call +} + +// IndexBlockExecutionData is a helper method to define mock.On call +// - data *execution_data.BlockExecutionDataEntity +func (_e *IndexerManager_Expecter) IndexBlockExecutionData(data interface{}) *IndexerManager_IndexBlockExecutionData_Call { + return &IndexerManager_IndexBlockExecutionData_Call{Call: _e.mock.On("IndexBlockExecutionData", data)} +} + +func (_c *IndexerManager_IndexBlockExecutionData_Call) Run(run func(data *execution_data.BlockExecutionDataEntity)) *IndexerManager_IndexBlockExecutionData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *execution_data.BlockExecutionDataEntity + if args[0] != nil { + arg0 = args[0].(*execution_data.BlockExecutionDataEntity) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IndexerManager_IndexBlockExecutionData_Call) Return(err error) *IndexerManager_IndexBlockExecutionData_Call { + _c.Call.Return(err) + return _c +} + +func (_c *IndexerManager_IndexBlockExecutionData_Call) RunAndReturn(run func(data *execution_data.BlockExecutionDataEntity) error) *IndexerManager_IndexBlockExecutionData_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/mock/register_scanner.go b/module/state_synchronization/indexer/extended/mock/register_scanner.go new file mode 100644 index 00000000000..82aeeada12e --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/register_scanner.go @@ -0,0 +1,103 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// newRegisterScanner creates a new instance of registerScanner. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newRegisterScanner(t interface { + mock.TestingT + Cleanup(func()) +}) *registerScanner { + mock := ®isterScanner{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// registerScanner is an autogenerated mock type for the registerScanner type +type registerScanner struct { + mock.Mock +} + +type registerScanner_Expecter struct { + mock *mock.Mock +} + +func (_m *registerScanner) EXPECT() *registerScanner_Expecter { + return ®isterScanner_Expecter{mock: &_m.Mock} +} + +// ByKeyPrefix provides a mock function for the type registerScanner +func (_mock *registerScanner) ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] { + ret := _mock.Called(keyPrefix, height, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByKeyPrefix") + } + + var r0 storage.IndexIterator[flow.RegisterValue, flow.RegisterID] + if returnFunc, ok := ret.Get(0).(func(string, uint64, *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]); ok { + r0 = returnFunc(keyPrefix, height, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) + } + } + return r0 +} + +// registerScanner_ByKeyPrefix_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByKeyPrefix' +type registerScanner_ByKeyPrefix_Call struct { + *mock.Call +} + +// ByKeyPrefix is a helper method to define mock.On call +// - keyPrefix string +// - height uint64 +// - cursor *flow.RegisterID +func (_e *registerScanner_Expecter) ByKeyPrefix(keyPrefix interface{}, height interface{}, cursor interface{}) *registerScanner_ByKeyPrefix_Call { + return ®isterScanner_ByKeyPrefix_Call{Call: _e.mock.On("ByKeyPrefix", keyPrefix, height, cursor)} +} + +func (_c *registerScanner_ByKeyPrefix_Call) Run(run func(keyPrefix string, height uint64, cursor *flow.RegisterID)) *registerScanner_ByKeyPrefix_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.RegisterID + if args[2] != nil { + arg2 = args[2].(*flow.RegisterID) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *registerScanner_ByKeyPrefix_Call) Return(indexIterator storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *registerScanner_ByKeyPrefix_Call { + _c.Call.Return(indexIterator) + return _c +} + +func (_c *registerScanner_ByKeyPrefix_Call) RunAndReturn(run func(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *registerScanner_ByKeyPrefix_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/mock/script_executor.go b/module/state_synchronization/indexer/extended/mock/script_executor.go new file mode 100644 index 00000000000..54a92740214 --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/script_executor.go @@ -0,0 +1,118 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "context" + + mock "github.com/stretchr/testify/mock" +) + +// newScriptExecutor creates a new instance of scriptExecutor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newScriptExecutor(t interface { + mock.TestingT + Cleanup(func()) +}) *scriptExecutor { + mock := &scriptExecutor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// scriptExecutor is an autogenerated mock type for the scriptExecutor type +type scriptExecutor struct { + mock.Mock +} + +type scriptExecutor_Expecter struct { + mock *mock.Mock +} + +func (_m *scriptExecutor) EXPECT() *scriptExecutor_Expecter { + return &scriptExecutor_Expecter{mock: &_m.Mock} +} + +// ExecuteAtBlockHeight provides a mock function for the type scriptExecutor +func (_mock *scriptExecutor) ExecuteAtBlockHeight(ctx context.Context, script []byte, arguments [][]byte, height uint64) ([]byte, error) { + ret := _mock.Called(ctx, script, arguments, height) + + if len(ret) == 0 { + panic("no return value specified for ExecuteAtBlockHeight") + } + + var r0 []byte + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, uint64) ([]byte, error)); ok { + return returnFunc(ctx, script, arguments, height) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte, [][]byte, uint64) []byte); ok { + r0 = returnFunc(ctx, script, arguments, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, []byte, [][]byte, uint64) error); ok { + r1 = returnFunc(ctx, script, arguments, height) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// scriptExecutor_ExecuteAtBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExecuteAtBlockHeight' +type scriptExecutor_ExecuteAtBlockHeight_Call struct { + *mock.Call +} + +// ExecuteAtBlockHeight is a helper method to define mock.On call +// - ctx context.Context +// - script []byte +// - arguments [][]byte +// - height uint64 +func (_e *scriptExecutor_Expecter) ExecuteAtBlockHeight(ctx interface{}, script interface{}, arguments interface{}, height interface{}) *scriptExecutor_ExecuteAtBlockHeight_Call { + return &scriptExecutor_ExecuteAtBlockHeight_Call{Call: _e.mock.On("ExecuteAtBlockHeight", ctx, script, arguments, height)} +} + +func (_c *scriptExecutor_ExecuteAtBlockHeight_Call) Run(run func(ctx context.Context, script []byte, arguments [][]byte, height uint64)) *scriptExecutor_ExecuteAtBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 [][]byte + if args[2] != nil { + arg2 = args[2].([][]byte) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *scriptExecutor_ExecuteAtBlockHeight_Call) Return(bytes []byte, err error) *scriptExecutor_ExecuteAtBlockHeight_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *scriptExecutor_ExecuteAtBlockHeight_Call) RunAndReturn(run func(ctx context.Context, script []byte, arguments [][]byte, height uint64) ([]byte, error)) *scriptExecutor_ExecuteAtBlockHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/mock/snapshot_provider.go b/module/state_synchronization/indexer/extended/mock/snapshot_provider.go new file mode 100644 index 00000000000..67456e57a2e --- /dev/null +++ b/module/state_synchronization/indexer/extended/mock/snapshot_provider.go @@ -0,0 +1,168 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/fvm/storage/snapshot" + "github.com/onflow/flow-go/model/flow" + mock "github.com/stretchr/testify/mock" +) + +// newSnapshotProvider creates a new instance of snapshotProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func newSnapshotProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *snapshotProvider { + mock := &snapshotProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// snapshotProvider is an autogenerated mock type for the snapshotProvider type +type snapshotProvider struct { + mock.Mock +} + +type snapshotProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *snapshotProvider) EXPECT() *snapshotProvider_Expecter { + return &snapshotProvider_Expecter{mock: &_m.Mock} +} + +// GetStorageSnapshot provides a mock function for the type snapshotProvider +func (_mock *snapshotProvider) GetStorageSnapshot(height uint64) (snapshot.StorageSnapshot, error) { + ret := _mock.Called(height) + + if len(ret) == 0 { + panic("no return value specified for GetStorageSnapshot") + } + + var r0 snapshot.StorageSnapshot + var r1 error + if returnFunc, ok := ret.Get(0).(func(uint64) (snapshot.StorageSnapshot, error)); ok { + return returnFunc(height) + } + if returnFunc, ok := ret.Get(0).(func(uint64) snapshot.StorageSnapshot); ok { + r0 = returnFunc(height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(snapshot.StorageSnapshot) + } + } + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// snapshotProvider_GetStorageSnapshot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStorageSnapshot' +type snapshotProvider_GetStorageSnapshot_Call struct { + *mock.Call +} + +// GetStorageSnapshot is a helper method to define mock.On call +// - height uint64 +func (_e *snapshotProvider_Expecter) GetStorageSnapshot(height interface{}) *snapshotProvider_GetStorageSnapshot_Call { + return &snapshotProvider_GetStorageSnapshot_Call{Call: _e.mock.On("GetStorageSnapshot", height)} +} + +func (_c *snapshotProvider_GetStorageSnapshot_Call) Run(run func(height uint64)) *snapshotProvider_GetStorageSnapshot_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *snapshotProvider_GetStorageSnapshot_Call) Return(storageSnapshot snapshot.StorageSnapshot, err error) *snapshotProvider_GetStorageSnapshot_Call { + _c.Call.Return(storageSnapshot, err) + return _c +} + +func (_c *snapshotProvider_GetStorageSnapshot_Call) RunAndReturn(run func(height uint64) (snapshot.StorageSnapshot, error)) *snapshotProvider_GetStorageSnapshot_Call { + _c.Call.Return(run) + return _c +} + +// RegisterValue provides a mock function for the type snapshotProvider +func (_mock *snapshotProvider) RegisterValue(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { + ret := _mock.Called(ID, height) + + if len(ret) == 0 { + panic("no return value specified for RegisterValue") + } + + var r0 flow.RegisterValue + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { + return returnFunc(ID, height) + } + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { + r0 = returnFunc(ID, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(flow.RegisterValue) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { + r1 = returnFunc(ID, height) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// snapshotProvider_RegisterValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterValue' +type snapshotProvider_RegisterValue_Call struct { + *mock.Call +} + +// RegisterValue is a helper method to define mock.On call +// - ID flow.RegisterID +// - height uint64 +func (_e *snapshotProvider_Expecter) RegisterValue(ID interface{}, height interface{}) *snapshotProvider_RegisterValue_Call { + return &snapshotProvider_RegisterValue_Call{Call: _e.mock.On("RegisterValue", ID, height)} +} + +func (_c *snapshotProvider_RegisterValue_Call) Run(run func(ID flow.RegisterID, height uint64)) *snapshotProvider_RegisterValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *snapshotProvider_RegisterValue_Call) Return(v flow.RegisterValue, err error) *snapshotProvider_RegisterValue_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *snapshotProvider_RegisterValue_Call) RunAndReturn(run func(ID flow.RegisterID, height uint64) (flow.RegisterValue, error)) *snapshotProvider_RegisterValue_Call { + _c.Call.Return(run) + return _c +} diff --git a/module/state_synchronization/indexer/extended/scheduled_transaction_data.go b/module/state_synchronization/indexer/extended/scheduled_transaction_data.go new file mode 100644 index 00000000000..1acc415bb8d --- /dev/null +++ b/module/state_synchronization/indexer/extended/scheduled_transaction_data.go @@ -0,0 +1,137 @@ +package extended + +import ( + "fmt" + + "github.com/onflow/cadence" + jsoncdc "github.com/onflow/cadence/encoding/json" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" +) + +// getTransactionDataScriptTemplate is a Cadence script template for batch-fetching +// FlowTransactionScheduler.TransactionData by ID. The %s placeholder is replaced with +// the FlowTransactionScheduler contract address hex string. +// +// The script accepts a single [UInt64] argument (the scheduled transaction IDs to fetch) +// and returns [FlowTransactionScheduler.TransactionData?], where each element corresponds +// to the input ID in order. Elements are nil for IDs that do not exist. +const getTransactionDataScriptTemplate = ` +import FlowTransactionScheduler from 0x%s + +/// Returns the TransactionData for each of the given scheduled transaction IDs. +/// Returns nil for any ID that does not exist. +access(all) fun main(ids: [UInt64]): [FlowTransactionScheduler.TransactionData?] { + let results: [FlowTransactionScheduler.TransactionData?] = [] + for id in ids { + results.append(FlowTransactionScheduler.getTransactionData(id: id)) + } + return results +} +` + +// EncodeGetTransactionDataArg encodes a slice of scheduled transaction IDs as a +// JSON-CDC [UInt64] array suitable for passing as the script argument when executing +// a script generated from [getTransactionDataScriptTemplate]. +// +// No error returns are expected during normal operation. +func EncodeGetTransactionDataArg(ids []uint64) ([]byte, error) { + values := make([]cadence.Value, len(ids)) + for i, id := range ids { + values[i] = cadence.UInt64(id) + } + encoded, err := jsoncdc.Encode(cadence.NewArray(values)) + if err != nil { + return nil, fmt.Errorf("failed to JSON-CDC encode IDs array: %w", err) + } + return encoded, nil +} + +// DecodeTransactionDataResults decodes the JSON-CDC response from a batch +// GetTransactionData script execution. The ids slice must match the order of IDs +// passed when the script was called. +// +// Returns a map from scheduled transaction ID to decoded [access.ScheduledTransaction]. +// IDs for which the contract returned nil (not found on-chain) are omitted from the map. +// The returned entries have [access.ScheduledTxStatusScheduled] status, since +// TransactionData reflects the initially scheduled state. +// +// Any error indicates that the response is malformed. +func DecodeTransactionDataResults(response []byte, ids []uint64) (map[uint64]*access.ScheduledTransaction, error) { + value, err := jsoncdc.Decode(nil, response) + if err != nil { + return nil, fmt.Errorf("failed to JSON-CDC decode script result: %w", err) + } + + array, ok := value.(cadence.Array) + if !ok { + return nil, fmt.Errorf("expected Array result, got %T", value) + } + + if len(array.Values) != len(ids) { + return nil, fmt.Errorf("expected %d results, got %d", len(ids), len(array.Values)) + } + + results := make(map[uint64]*access.ScheduledTransaction, len(ids)) + for i, elem := range array.Values { + opt, ok := elem.(cadence.Optional) + if !ok { + return nil, fmt.Errorf("expected Optional at index %d, got %T", i, elem) + } + if opt.Value == nil { + continue + } + + tx, err := decodeTransactionData(opt.Value) + if err != nil { + return nil, fmt.Errorf("failed to decode TransactionData at index %d (id=%d): %w", i, ids[i], err) + } + results[ids[i]] = &tx + } + + return results, nil +} + +// decodeTransactionData decodes a Cadence FlowTransactionScheduler.TransactionData +// struct value into an [access.ScheduledTransaction]. +// +// Any error indicates that the value is malformed. +func decodeTransactionData(value cadence.Value) (access.ScheduledTransaction, error) { + type transactionDataRaw struct { + ID uint64 `cadence:"id"` + Priority cadence.Enum `cadence:"priority"` + Timestamp cadence.UFix64 `cadence:"scheduledTimestamp"` + ExecutionEffort uint64 `cadence:"executionEffort"` + Fees cadence.UFix64 `cadence:"fees"` + TransactionHandlerOwner cadence.Address `cadence:"handlerAddress"` + TransactionHandlerTypeIdentifier string `cadence:"handlerTypeIdentifier"` + } + + composite, ok := value.(cadence.Composite) + if !ok { + return access.ScheduledTransaction{}, fmt.Errorf("expected Composite value, got %T", value) + } + + var raw transactionDataRaw + if err := cadence.DecodeFields(composite, &raw); err != nil { + return access.ScheduledTransaction{}, fmt.Errorf("failed to decode TransactionData fields: %w", err) + } + + priorityRaw, err := events.EnumToType[cadence.UInt8](raw.Priority) + if err != nil { + return access.ScheduledTransaction{}, fmt.Errorf("failed to decode TransactionData 'priority' field: %w", err) + } + + return access.ScheduledTransaction{ + ID: raw.ID, + Priority: access.ScheduledTransactionPriority(priorityRaw), + Timestamp: uint64(raw.Timestamp), + ExecutionEffort: raw.ExecutionEffort, + Fees: uint64(raw.Fees), + TransactionHandlerOwner: flow.Address(raw.TransactionHandlerOwner), + TransactionHandlerTypeIdentifier: raw.TransactionHandlerTypeIdentifier, + Status: access.ScheduledTxStatusScheduled, + }, nil +} diff --git a/module/state_synchronization/indexer/extended/scheduled_transaction_data_test.go b/module/state_synchronization/indexer/extended/scheduled_transaction_data_test.go new file mode 100644 index 00000000000..9678367e418 --- /dev/null +++ b/module/state_synchronization/indexer/extended/scheduled_transaction_data_test.go @@ -0,0 +1,255 @@ +package extended_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/common" + jsoncdc "github.com/onflow/cadence/encoding/json" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/utils/unittest" + + . "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" +) + +// ===== EncodeGetTransactionDataArg ===== + +// TestEncodeGetTransactionDataArg_Empty verifies that encoding an empty slice produces a +// valid JSON-CDC array that can be decoded. +func TestEncodeGetTransactionDataArg_Empty(t *testing.T) { + t.Parallel() + + encoded, err := EncodeGetTransactionDataArg(nil) + require.NoError(t, err) + require.NotEmpty(t, encoded) + + value, err := jsoncdc.Decode(nil, encoded) + require.NoError(t, err) + + arr, ok := value.(cadence.Array) + require.True(t, ok) + assert.Empty(t, arr.Values) +} + +// TestEncodeGetTransactionDataArg_NonEmpty verifies that encoding a non-empty slice produces +// a valid JSON-CDC array with the expected UInt64 values. +func TestEncodeGetTransactionDataArg_NonEmpty(t *testing.T) { + t.Parallel() + + ids := []uint64{1, 42, 99} + encoded, err := EncodeGetTransactionDataArg(ids) + require.NoError(t, err) + require.NotEmpty(t, encoded) + + value, err := jsoncdc.Decode(nil, encoded) + require.NoError(t, err) + + arr, ok := value.(cadence.Array) + require.True(t, ok) + require.Len(t, arr.Values, 3) + + assert.Equal(t, cadence.UInt64(1), arr.Values[0]) + assert.Equal(t, cadence.UInt64(42), arr.Values[1]) + assert.Equal(t, cadence.UInt64(99), arr.Values[2]) +} + +// ===== DecodeTransactionDataResults ===== + +// TestDecodeTransactionDataResults_AllFound verifies that when all Optional elements are present +// (non-nil), DecodeTransactionDataResults returns a map with an entry for every ID. +func TestDecodeTransactionDataResults_AllFound(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + + ids := []uint64{5, 7} + comp5 := makeDecodeTransactionDataOptional(sc, 5, 1, 1000, 300, 100, owner, "A.abc.Contract.Handler") + comp7 := makeDecodeTransactionDataOptional(sc, 7, 2, 2000, 400, 150, owner, "A.def.Contract.Handler") + + response := encodeOptionalArray(t, comp5, comp7) + + results, err := DecodeTransactionDataResults(response, ids) + require.NoError(t, err) + require.Len(t, results, 2) + + tx5, ok := results[5] + require.True(t, ok) + assert.Equal(t, uint64(5), tx5.ID) + assert.Equal(t, access.ScheduledTxStatusScheduled, tx5.Status) + tx7, ok := results[7] + require.True(t, ok) + assert.Equal(t, uint64(7), tx7.ID) +} + +// TestDecodeTransactionDataResults_SomeNil verifies that nil Optional elements are omitted +// from the returned map, while non-nil elements are included. +func TestDecodeTransactionDataResults_SomeNil(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + + ids := []uint64{1, 2, 3} + comp1 := makeDecodeTransactionDataOptional(sc, 1, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler") + nilOpt := cadence.NewOptional(nil) + comp3 := makeDecodeTransactionDataOptional(sc, 3, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler") + + response := encodeOptionalArray(t, comp1, nilOpt, comp3) + + results, err := DecodeTransactionDataResults(response, ids) + require.NoError(t, err) + require.Len(t, results, 2) + + _, ok := results[2] + assert.False(t, ok, "nil Optional for ID 2 should be omitted") + + _, ok = results[1] + assert.True(t, ok) + _, ok = results[3] + assert.True(t, ok) +} + +// TestDecodeTransactionDataResults_WrongCount verifies that an error is returned when the +// number of results does not match the number of IDs. +func TestDecodeTransactionDataResults_WrongCount(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + + ids := []uint64{1, 2} + // Only one element in the response instead of two. + comp1 := makeDecodeTransactionDataOptional(sc, 1, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler") + response := encodeOptionalArray(t, comp1) + + _, err := DecodeTransactionDataResults(response, ids) + require.Error(t, err) + assert.Contains(t, err.Error(), "expected 2 results, got 1") +} + +// TestDecodeTransactionDataResults_NonArray verifies that an error is returned when the +// response does not decode to a cadence.Array. +func TestDecodeTransactionDataResults_NonArray(t *testing.T) { + t.Parallel() + + // Encode a single UInt64, not an array. + notArray, err := jsoncdc.Encode(cadence.UInt64(42)) + require.NoError(t, err) + + _, err = DecodeTransactionDataResults(notArray, []uint64{1}) + require.Error(t, err) + assert.Contains(t, err.Error(), "expected Array result") +} + +// TestDecodeTransactionDataResults_NonOptionalElement verifies that an error is returned when +// an array element is not a cadence.Optional. +func TestDecodeTransactionDataResults_NonOptionalElement(t *testing.T) { + t.Parallel() + + // Encode an array with a UInt64 instead of Optional. + notOptional := cadence.UInt64(99) + arr := cadence.NewArray([]cadence.Value{notOptional}) + response, err := jsoncdc.Encode(arr) + require.NoError(t, err) + + _, err = DecodeTransactionDataResults(response, []uint64{1}) + require.Error(t, err) + assert.Contains(t, err.Error(), "expected Optional at index 0") +} + +// TestDecodeTransactionDataResults_MalformedComposite verifies that an error is returned when +// a non-nil Optional contains a value that is not a valid TransactionData composite. +func TestDecodeTransactionDataResults_MalformedComposite(t *testing.T) { + t.Parallel() + + // An Optional wrapping a plain UInt64 (not a Composite). + badOpt := cadence.NewOptional(cadence.UInt64(42)) + arr := cadence.NewArray([]cadence.Value{badOpt}) + response, err := jsoncdc.Encode(arr) + require.NoError(t, err) + + _, err = DecodeTransactionDataResults(response, []uint64{1}) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to decode TransactionData at index 0") +} + +// TestDecodeTransactionDataResults_Empty verifies that an empty IDs slice returns an empty map. +func TestDecodeTransactionDataResults_Empty(t *testing.T) { + t.Parallel() + + arr := cadence.NewArray([]cadence.Value{}) + response, err := jsoncdc.Encode(arr) + require.NoError(t, err) + + results, err := DecodeTransactionDataResults(response, []uint64{}) + require.NoError(t, err) + assert.Empty(t, results) +} + +// ===== Test Helpers ===== + +// makeDecodeTransactionDataOptional creates a cadence Optional wrapping a TransactionData +// struct. Used for DecodeTransactionDataResults tests, which expect Optional-wrapped elements. +func makeDecodeTransactionDataOptional( + sc *systemcontracts.SystemContracts, + id uint64, + priority uint8, + scheduledTimestamp uint64, + executionEffort uint64, + fees uint64, + owner flow.Address, + typeIdentifier string, +) cadence.Value { + addr := common.Address(sc.FlowTransactionScheduler.Address) + loc := common.NewAddressLocation(nil, addr, sc.FlowTransactionScheduler.Name) + + priorityEnumType := cadence.NewEnumType( + loc, + "Priority", + cadence.UInt8Type, + []cadence.Field{{Identifier: "rawValue", Type: cadence.UInt8Type}}, + nil, + ) + priorityEnum := cadence.NewEnum([]cadence.Value{cadence.UInt8(priority)}).WithType(priorityEnumType) + + typ := cadence.NewStructType( + loc, + "TransactionData", + []cadence.Field{ + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "priority", Type: priorityEnumType}, + {Identifier: "scheduledTimestamp", Type: cadence.UFix64Type}, + {Identifier: "executionEffort", Type: cadence.UInt64Type}, + {Identifier: "fees", Type: cadence.UFix64Type}, + {Identifier: "handlerAddress", Type: cadence.AddressType}, + {Identifier: "handlerTypeIdentifier", Type: cadence.StringType}, + }, + nil, + ) + comp := cadence.NewStruct([]cadence.Value{ + cadence.UInt64(id), + priorityEnum, + cadence.UFix64(scheduledTimestamp), + cadence.UInt64(executionEffort), + cadence.UFix64(fees), + cadence.NewAddress(owner), + cadence.String(typeIdentifier), + }).WithType(typ) + return cadence.NewOptional(comp) +} + +// encodeOptionalArray encodes a slice of cadence.Value elements as a JSON-CDC array. +func encodeOptionalArray(t *testing.T, elems ...cadence.Value) []byte { + t.Helper() + arr := cadence.NewArray(elems) + encoded, err := jsoncdc.Encode(arr) + require.NoError(t, err) + return encoded +} diff --git a/module/state_synchronization/indexer/extended/scheduled_transaction_requester.go b/module/state_synchronization/indexer/extended/scheduled_transaction_requester.go new file mode 100644 index 00000000000..9ae161a788a --- /dev/null +++ b/module/state_synchronization/indexer/extended/scheduled_transaction_requester.go @@ -0,0 +1,151 @@ +package extended + +import ( + "context" + "fmt" + "slices" + + "github.com/onflow/cadence" + jsoncdc "github.com/onflow/cadence/encoding/json" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +const maxLookupBatchSize = 50 + +// scriptExecutor is the subset of module/execution.ScriptExecutor used by ScheduledTransactionRequester. +// Defined locally to avoid an import cycle with module/execution. +type scriptExecutor interface { + ExecuteAtBlockHeight(ctx context.Context, script []byte, arguments [][]byte, height uint64) ([]byte, error) +} + +// ScheduledTransactionRequester fetches scheduled transaction data from on-chain state +// by executing Cadence scripts against the FlowTransactionScheduler contract. +// +// Not safe for concurrent use. +type ScheduledTransactionRequester struct { + executor scriptExecutor + script []byte +} + +// NewScheduledTransactionRequester creates a new ScheduledTransactionRequester. +func NewScheduledTransactionRequester(executor scriptExecutor, chainID flow.ChainID) *ScheduledTransactionRequester { + return &ScheduledTransactionRequester{ + executor: executor, + script: GetTransactionDataScript(chainID), + } +} + +// Fetch fetches scheduled transaction data for the given IDs from on-chain state at lookupHeight, +// and applies the status updates from the collected block data. +// +// No error returns are expected during normal operation. +func (r *ScheduledTransactionRequester) Fetch( + ctx context.Context, + lookupIDs []uint64, + lookupHeight uint64, + meta ScheduledTransactionsMetadata, +) ([]access.ScheduledTransaction, error) { + missingTxs, err := r.fetchMissingTxs(ctx, lookupIDs, lookupHeight) + if err != nil { + return nil, fmt.Errorf("failed to fetch missing scheduled transactions: %w", err) + } + + updatedTxs := make([]access.ScheduledTransaction, 0, len(missingTxs)) + for _, entry := range meta.ExecutedEntries { + if missing, ok := missingTxs[entry.Event.ID]; ok { + // set IsPlaceholder = true to signal that some information is missing because we don't know the original transaction. + missing.IsPlaceholder = true + missing.Status = access.ScheduledTxStatusExecuted + missing.ExecutedTransactionID = entry.TransactionID + updatedTxs = append(updatedTxs, missing) + } + } + for _, entry := range meta.CanceledEntries { + if missing, ok := missingTxs[entry.Event.ID]; ok { + // set IsPlaceholder = true to signal that some information is missing because we don't know the original transaction. + missing.IsPlaceholder = true + missing.Status = access.ScheduledTxStatusCancelled + missing.CancelledTransactionID = entry.TransactionID + missing.FeesReturned = uint64(entry.Event.FeesReturned) + missing.FeesDeducted = uint64(entry.Event.FeesDeducted) + updatedTxs = append(updatedTxs, missing) + } + } + for _, entry := range meta.FailedEntries { + if missing, ok := missingTxs[entry.ScheduledTxID]; ok { + // set IsPlaceholder = true to signal that some information is missing because we don't know the original transaction. + missing.IsPlaceholder = true + missing.Status = access.ScheduledTxStatusFailed + missing.ExecutedTransactionID = entry.TransactionID + updatedTxs = append(updatedTxs, missing) + } + } + + if len(updatedTxs) != len(missingTxs) { + return nil, fmt.Errorf("expected %d updated scheduled transactions, got %d", len(missingTxs), len(updatedTxs)) + } + + return updatedTxs, nil +} + +func (r *ScheduledTransactionRequester) fetchMissingTxs( + ctx context.Context, + lookupIDs []uint64, + height uint64, +) (map[uint64]access.ScheduledTransaction, error) { + missingTxs := make(map[uint64]access.ScheduledTransaction, len(lookupIDs)) + + for batch := range slices.Chunk(lookupIDs, maxLookupBatchSize) { + idsArg, err := EncodeGetTransactionDataArg(batch) + if err != nil { + return nil, fmt.Errorf("failed to build arguments: %w", err) + } + + response, err := r.executor.ExecuteAtBlockHeight(ctx, r.script, [][]byte{idsArg}, height) + if err != nil { + return nil, fmt.Errorf("failed to execute at block height: %w", err) + } + + results, err := jsoncdc.Decode(nil, response) + if err != nil { + return nil, fmt.Errorf("failed to decode scheduled transactions: %w", err) + } + + array, ok := results.(cadence.Array) + if !ok { + return nil, fmt.Errorf("expected Array result, got %T", results) + } + + if len(array.Values) != len(batch) { + return nil, fmt.Errorf("expected %d results from scheduled transaction data script, got %d", + len(batch), len(array.Values)) + } + + for i, result := range array.Values { + opt, ok := result.(cadence.Optional) + if !ok { + return nil, fmt.Errorf("expected Optional at index %d, got %T", i, result) + } + if opt.Value == nil { + return nil, fmt.Errorf("scheduled transaction %d had event, but is not found on-chain", batch[i]) + } + decoded, err := decodeTransactionData(opt.Value) + if err != nil { + return nil, fmt.Errorf("failed to decode scheduled transaction %d: %w", batch[i], err) + } + missingTxs[decoded.ID] = decoded + } + } + + return missingTxs, nil +} + +// GetTransactionDataScript returns the Cadence script used for JIT scheduled transaction +// lookups on the given chain. Exposed for testing. +func GetTransactionDataScript(chainID flow.ChainID) []byte { + sc := systemcontracts.SystemContractsForChain(chainID) + return []byte(fmt.Sprintf(getTransactionDataScriptTemplate, sc.FlowTransactionScheduler.Address.Hex())) +} diff --git a/module/state_synchronization/indexer/extended/scheduled_transaction_requester_test.go b/module/state_synchronization/indexer/extended/scheduled_transaction_requester_test.go new file mode 100644 index 00000000000..17e341fc795 --- /dev/null +++ b/module/state_synchronization/indexer/extended/scheduled_transaction_requester_test.go @@ -0,0 +1,240 @@ +package extended + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/onflow/cadence" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + executionmock "github.com/onflow/flow-go/module/execution/mock" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" + "github.com/onflow/flow-go/utils/unittest" +) + +const requesterTestHeight = uint64(200) + +// TestScheduledTransactionRequester_ExecutedEntry verifies that Fetch correctly applies +// Executed status and transaction ID to a fetched scheduled transaction. +func TestScheduledTransactionRequester_ExecutedEntry(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + executorMock := executionmock.NewScriptExecutor(t) + requester := NewScheduledTransactionRequester(executorMock, flow.Testnet) + + executedTxID := unittest.IdentifierFixture() + comp := MakeTransactionDataComposite(sc, 5, 1, 1000, 300, 100, owner, "A.abc.Contract.Handler") + executorMock.On("ExecuteAtBlockHeight", + mock.Anything, + GetTransactionDataScript(flow.Testnet), + encodeUInt64Args(t, 5), + requesterTestHeight, + ).Return(MakeJITScriptResponse(t, comp), nil).Once() + + meta := ScheduledTransactionsMetadata{ + ExecutedEntries: []ExecutedEntry{ + { + Event: &events.TransactionSchedulerExecutedEvent{ID: 5}, + TransactionID: executedTxID, + }, + }, + } + txs, err := requester.Fetch(context.Background(), []uint64{5}, requesterTestHeight, meta) + require.NoError(t, err) + require.Len(t, txs, 1) + assert.Equal(t, uint64(5), txs[0].ID) + assert.Equal(t, access.ScheduledTxStatusExecuted, txs[0].Status) + assert.Equal(t, executedTxID, txs[0].ExecutedTransactionID) +} + +// TestScheduledTransactionRequester_CancelledEntry verifies that Fetch correctly applies +// Cancelled status, transaction ID, and fee fields to a fetched scheduled transaction. +func TestScheduledTransactionRequester_CancelledEntry(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + executorMock := executionmock.NewScriptExecutor(t) + requester := NewScheduledTransactionRequester(executorMock, flow.Testnet) + + cancelTxID := unittest.IdentifierFixture() + comp := MakeTransactionDataComposite(sc, 7, 2, 2000, 400, 150, owner, "A.def.Contract.Handler") + executorMock.On("ExecuteAtBlockHeight", + mock.Anything, + GetTransactionDataScript(flow.Testnet), + encodeUInt64Args(t, 7), + requesterTestHeight, + ).Return(MakeJITScriptResponse(t, comp), nil).Once() + + meta := ScheduledTransactionsMetadata{ + CanceledEntries: []CanceledEntry{ + { + Event: &events.TransactionSchedulerCanceledEvent{ID: 7, FeesReturned: 50, FeesDeducted: 25}, + TransactionID: cancelTxID, + }, + }, + } + txs, err := requester.Fetch(context.Background(), []uint64{7}, requesterTestHeight, meta) + require.NoError(t, err) + require.Len(t, txs, 1) + assert.Equal(t, uint64(7), txs[0].ID) + assert.Equal(t, access.ScheduledTxStatusCancelled, txs[0].Status) + assert.Equal(t, cancelTxID, txs[0].CancelledTransactionID) + assert.Equal(t, uint64(50), txs[0].FeesReturned) + assert.Equal(t, uint64(25), txs[0].FeesDeducted) +} + +// TestScheduledTransactionRequester_FailedEntry verifies that Fetch correctly applies +// Failed status and transaction ID to a fetched scheduled transaction. +func TestScheduledTransactionRequester_FailedEntry(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + executorMock := executionmock.NewScriptExecutor(t) + requester := NewScheduledTransactionRequester(executorMock, flow.Testnet) + + executorTxID := unittest.IdentifierFixture() + comp := MakeTransactionDataComposite(sc, 42, 1, 3000, 200, 80, owner, "A.xyz.Contract.Handler") + executorMock.On("ExecuteAtBlockHeight", + mock.Anything, + GetTransactionDataScript(flow.Testnet), + encodeUInt64Args(t, 42), + requesterTestHeight, + ).Return(MakeJITScriptResponse(t, comp), nil).Once() + + meta := ScheduledTransactionsMetadata{ + FailedEntries: []FailedEntry{ + {ScheduledTxID: 42, TransactionID: executorTxID}, + }, + } + txs, err := requester.Fetch(context.Background(), []uint64{42}, requesterTestHeight, meta) + require.NoError(t, err) + require.Len(t, txs, 1) + assert.Equal(t, uint64(42), txs[0].ID) + assert.Equal(t, access.ScheduledTxStatusFailed, txs[0].Status) + assert.Equal(t, executorTxID, txs[0].ExecutedTransactionID) +} + +// TestScheduledTransactionRequester_NilOptional verifies that when the script returns a nil +// optional for an ID (transaction not found on-chain), Fetch returns an error. +func TestScheduledTransactionRequester_NilOptional(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + executorMock := executionmock.NewScriptExecutor(t) + requester := NewScheduledTransactionRequester(executorMock, flow.Testnet) + + // ID 10 exists on-chain; ID 11 does not (nil optional). + comp := MakeTransactionDataComposite(sc, 10, 1, 1000, 300, 100, owner, "A.abc.Contract.Handler") + response := MakeJITScriptResponseWithNils( + t, + []cadence.Composite{comp, comp}, // second entry is a nil optional; value is ignored + []bool{false, true}, + ) + executorMock.On("ExecuteAtBlockHeight", + mock.Anything, + GetTransactionDataScript(flow.Testnet), + encodeUInt64Args(t, 10, 11), + requesterTestHeight, + ).Return(response, nil).Once() + + meta := ScheduledTransactionsMetadata{ + ExecutedEntries: []ExecutedEntry{ + {Event: &events.TransactionSchedulerExecutedEvent{ID: 10}, TransactionID: unittest.IdentifierFixture()}, + {Event: &events.TransactionSchedulerExecutedEvent{ID: 11}, TransactionID: unittest.IdentifierFixture()}, + }, + } + _, err := requester.Fetch(context.Background(), []uint64{10, 11}, requesterTestHeight, meta) + require.Error(t, err) + require.ErrorContains(t, err, "is not found on-chain") +} + +// TestScheduledTransactionRequester_ScriptError verifies that an error from the script +// executor is propagated from Fetch. +func TestScheduledTransactionRequester_ScriptError(t *testing.T) { + t.Parallel() + + executorMock := executionmock.NewScriptExecutor(t) + requester := NewScheduledTransactionRequester(executorMock, flow.Testnet) + + scriptErr := fmt.Errorf("script execution failed") + executorMock.On("ExecuteAtBlockHeight", + mock.Anything, + GetTransactionDataScript(flow.Testnet), + encodeUInt64Args(t, 9), + requesterTestHeight, + ).Return([]byte(nil), scriptErr).Once() + + meta := ScheduledTransactionsMetadata{ + CanceledEntries: []CanceledEntry{ + {Event: &events.TransactionSchedulerCanceledEvent{ID: 9}}, + }, + } + _, err := requester.Fetch(context.Background(), []uint64{9}, requesterTestHeight, meta) + require.Error(t, err) + require.ErrorIs(t, err, scriptErr) +} + +// TestScheduledTransactionRequester_Batching verifies that when more than maxLookupBatchSize +// IDs are requested, multiple script calls are made in batches. +func TestScheduledTransactionRequester_Batching(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + executorMock := executionmock.NewScriptExecutor(t) + requester := NewScheduledTransactionRequester(executorMock, flow.Testnet) + + // maxLookupBatchSize is 50; use 51 IDs to force 2 batches. + const totalIDs = 51 + + var batch1Composites []cadence.Composite + for i := range 50 { + batch1Composites = append(batch1Composites, MakeTransactionDataComposite(sc, uint64(i+1), 1, 1000, 100, 50, owner, "A.abc.Contract.Handler")) + } + batch2Composite := MakeTransactionDataComposite(sc, 51, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler") + + batch1IDs := make([]uint64, 50) + for i := range 50 { + batch1IDs[i] = uint64(i + 1) + } + executorMock.On("ExecuteAtBlockHeight", + mock.Anything, + GetTransactionDataScript(flow.Testnet), + encodeUInt64Args(t, batch1IDs...), + requesterTestHeight, + ).Return(MakeJITScriptResponse(t, batch1Composites...), nil).Once() + executorMock.On("ExecuteAtBlockHeight", + mock.Anything, + GetTransactionDataScript(flow.Testnet), + encodeUInt64Args(t, 51), + requesterTestHeight, + ).Return(MakeJITScriptResponse(t, batch2Composite), nil).Once() + + lookupIDs := make([]uint64, totalIDs) + canceledEntries := make([]CanceledEntry, totalIDs) + for i := range totalIDs { + id := uint64(i + 1) + lookupIDs[i] = id + canceledEntries[i] = CanceledEntry{ + Event: &events.TransactionSchedulerCanceledEvent{ID: id}, + TransactionID: unittest.IdentifierFixture(), + } + } + + meta := ScheduledTransactionsMetadata{CanceledEntries: canceledEntries} + txs, err := requester.Fetch(context.Background(), lookupIDs, requesterTestHeight, meta) + require.NoError(t, err) + assert.Len(t, txs, totalIDs) +} diff --git a/module/state_synchronization/indexer/extended/scheduled_transactions.go b/module/state_synchronization/indexer/extended/scheduled_transactions.go new file mode 100644 index 00000000000..70ddd9a5d94 --- /dev/null +++ b/module/state_synchronization/indexer/extended/scheduled_transactions.go @@ -0,0 +1,461 @@ +package extended + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/jordanschalm/lockctx" + "github.com/rs/zerolog" + + jsoncdc "github.com/onflow/cadence/encoding/json" + + "github.com/onflow/cadence" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/access/systemcollection" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" + "github.com/onflow/flow-go/storage" +) + +const scheduledTransactionsIndexerName = "scheduled_transactions" + +// ScheduledTransactions indexes scheduled transaction lifecycle events from the +// FlowTransactionScheduler system contract. +// +// It processes Scheduled, PendingExecution, Executed, and Canceled events and writes +// corresponding entries to the scheduled transactions storage index. +// +// A scheduled transaction that appeared in a PendingExecution event but has no matching +// Executed event in the same block is considered failed. The corresponding Flow transaction +// that was submitted by the scheduled executor account is identified by its authorizer +// (the scheduled executor account) and an empty payer address. +// +// This indexer will automatically backfill any scheduled transactions that are executed or cancelled +// which were scheduled before the indexer was initialized. This is done by executing scripts when an +// unknown transaction is executed or cancelled within a block. There are a couple important +// considerations to keep in mind: +// 1. If there are many unknown transactions with a block, the script execution may be slow and block +// the indexing process until it completes. Since the extended indexers are run in a batch, this +// will block all other indexers that are indexing the same block. In general, there should be +// relatively few unknown transactions executed. However, if this becomes a problem, we will need +// to consider a more efficient way to backfill the index. +// 2. Since script executions are required to backfill the index, the indexer must be started after +// the registers db is initialized. +// +// Not safe for concurrent use. +type ScheduledTransactions struct { + log zerolog.Logger + store storage.ScheduledTransactionsIndexBootstrapper + metrics module.ExtendedIndexingMetrics + + // executorAddr resolves the executor authorizer address for a given block height. + // v0 system collections use FlowServiceAccount; v1 uses ScheduledTransactionExecutor. + executorAddr *access.Versioned[flow.Address] + + scheduledEventType flow.EventType + pendingExecutionType flow.EventType + executedEventType flow.EventType + canceledEventType flow.EventType + + requester *ScheduledTransactionRequester +} + +var _ Indexer = (*ScheduledTransactions)(nil) +var _ IndexProcessor[access.ScheduledTransaction, ScheduledTransactionsMetadata] = (*ScheduledTransactions)(nil) + +// ScheduledTransactionsMetadata collects all event-derived data for a single block's scheduled +// transaction lifecycle. It contains the newly scheduled transactions as well as the executed, +// canceled, and failed lifecycle entries. +// +// Note: the complete indexed dataset is NOT available from [IndexProcessor.ProcessBlockData] alone +// because backfilling missing transactions requires storage and script execution. The full dataset +// is only assembled inside [ScheduledTransactions.IndexBlockData]. +type ScheduledTransactionsMetadata struct { + NewTxs []access.ScheduledTransaction + ExecutedEntries []ExecutedEntry + CanceledEntries []CanceledEntry + FailedEntries []FailedEntry +} + +// ExecutedEntry pairs a decoded Executed event with the Flow transaction ID that emitted it. +type ExecutedEntry struct { + Event *events.TransactionSchedulerExecutedEvent + TransactionID flow.Identifier +} + +// CanceledEntry pairs a decoded Canceled event with the Flow transaction ID that emitted it. +type CanceledEntry struct { + Event *events.TransactionSchedulerCanceledEvent + TransactionID flow.Identifier +} + +// FailedEntry pairs a scheduled tx ID with the Flow transaction ID of the executor transaction +// that attempted (and failed) to execute the scheduled transaction. +type FailedEntry struct { + ScheduledTxID uint64 + TransactionID flow.Identifier +} + +// NewScheduledTransactions creates a new ScheduledTransactions indexer. +// +// No error returns are expected during normal operation. +func NewScheduledTransactions( + log zerolog.Logger, + store storage.ScheduledTransactionsIndexBootstrapper, + scriptExecutor scriptExecutor, + metrics module.ExtendedIndexingMetrics, + chainID flow.ChainID, +) *ScheduledTransactions { + sc := systemcontracts.SystemContractsForChain(chainID) + scheduler := sc.FlowTransactionScheduler + prefix := fmt.Sprintf("A.%s.%s.", scheduler.Address.Hex(), scheduler.Name) + + // Build a height-versioned executor address that matches the system collection builder versions. + // v0 uses FlowServiceAccount as the executor authorizer; v1 uses ScheduledTransactionExecutor. + versionMapper, ok := systemcollection.ChainHeightVersions[chainID] + if !ok { + versionMapper = access.NewStaticHeightVersionMapper(access.LatestBoundary) + } + executorAddr := access.NewVersioned(map[access.Version]flow.Address{ + systemcollection.Version0: sc.FlowServiceAccount.Address, + systemcollection.Version1: sc.ScheduledTransactionExecutor.Address, + access.VersionLatest: sc.ScheduledTransactionExecutor.Address, + }, versionMapper) + + return &ScheduledTransactions{ + log: log.With().Str("component", "scheduled_tx_indexer").Logger(), + store: store, + metrics: metrics, + requester: NewScheduledTransactionRequester(scriptExecutor, chainID), + executorAddr: executorAddr, + scheduledEventType: flow.EventType(prefix + "Scheduled"), + pendingExecutionType: flow.EventType(prefix + "PendingExecution"), + executedEventType: flow.EventType(prefix + "Executed"), + canceledEventType: flow.EventType(prefix + "Canceled"), + } +} + +// Name returns the indexer name. +func (s *ScheduledTransactions) Name() string { return scheduledTransactionsIndexerName } + +// NextHeight returns the next block height to index. +// +// No error returns are expected during normal operation. +func (s *ScheduledTransactions) NextHeight() (uint64, error) { + return nextHeight(s.store) +} + +// IndexBlockData processes one block's events and transactions, and updates the scheduled +// transactions index. +// +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until the batch is committed. +// +// CAUTION: Not safe for concurrent use. +// +// Expected error returns during normal operations: +// - [ErrAlreadyIndexed]: if the data is already indexed for the height +// - [ErrFutureHeight]: if the data is for a future height +func (s *ScheduledTransactions) IndexBlockData(lctx lockctx.Proof, data BlockData, rw storage.ReaderBatchWriter) error { + expectedHeight, err := s.NextHeight() + if err != nil { + return fmt.Errorf("failed to get next height: %w", err) + } + if data.Header.Height > expectedHeight { + return ErrFutureHeight + } + if data.Header.Height < expectedHeight { + return ErrAlreadyIndexed + } + + _, meta, err := s.ProcessBlockData(data) + if err != nil { + return err + } + + newTxs := meta.NewTxs + + // when a node is bootstrapped after a scheduled transaction was first scheduled, it will not exist + // in the local index. In this case, calls to Executed, Cancelled, and Failed will fail because the + // entry doesn't exist in the db. In practice, this is 100% of nodes since the indexes are reset + // at the beginning of each spork. + // + // The contract doesn't provide a way to query all unexecuted transactions, so we need to find their + // ID first, then query their data. This means it's not possible to backfill the index on startup + // without iterating all possible IDs. + // + // To work around this, the logic that follows performs a just-in-time lookup of the data for each + // unknown transaction that is executed or cancelled within a block. This is one in 3 steps: + // 1. Collect the IDs of all transactions that are not found when attempting to update. + // 2. Execute a script to lookup the data for each ID, and populate the executed/cancelled/failed updates + // 3. Store the updated transactions in the index. + var missingIDs []uint64 + + for _, entry := range meta.ExecutedEntries { + if err := s.store.Executed(lctx, rw, entry.Event.ID, entry.TransactionID); err != nil { + if !errors.Is(err, storage.ErrNotFound) { + return fmt.Errorf("failed to mark tx %d executed: %w", entry.Event.ID, err) + } + missingIDs = append(missingIDs, entry.Event.ID) + } + } + for _, entry := range meta.CanceledEntries { + if err := s.store.Cancelled(lctx, rw, entry.Event.ID, uint64(entry.Event.FeesReturned), uint64(entry.Event.FeesDeducted), entry.TransactionID); err != nil { + if !errors.Is(err, storage.ErrNotFound) { + return fmt.Errorf("failed to mark tx %d cancelled: %w", entry.Event.ID, err) + } + missingIDs = append(missingIDs, entry.Event.ID) + } + } + for _, entry := range meta.FailedEntries { + if err := s.store.Failed(lctx, rw, entry.ScheduledTxID, entry.TransactionID); err != nil { + if !errors.Is(err, storage.ErrNotFound) { + return fmt.Errorf("failed to mark tx %d failed: %w", entry.ScheduledTxID, err) + } + missingIDs = append(missingIDs, entry.ScheduledTxID) + } + } + if len(missingIDs) > 0 { + // scripts are executed against end of the block state, so the height must be before the current block, + // otherwise the executed/canceled events may not be found. Use one block before the current block. + // This is safe for genesis/spork root blocks because the root block does not execute transactions and + // thus will never have any scheduled transaction events, so the block here will always be after the root block. + missingTxs, err := s.requester.Fetch(context.TODO(), missingIDs, data.Header.Height-1, meta) + if err != nil { + return fmt.Errorf("failed to fetch scheduled transaction data from state: %w", err) + } + + newTxs = append(newTxs, missingTxs...) + } + + // at this point, all missing scheduled transactions should be present in the newTxs slice. + if len(newTxs) < len(missingIDs) { + return fmt.Errorf("missing backfilled scheduled transactions: expected %d, got %d", len(missingIDs), len(newTxs)) + } + + // finally store all new transactions in a single call to Store since store may only be called + // once per block. + if err := s.store.Store(lctx, rw, data.Header.Height, newTxs); err != nil { + if !errors.Is(err, storage.ErrAlreadyExists) { + return fmt.Errorf("failed to store new scheduled transactions: %w", err) + } + } + + s.metrics.ScheduledTransactionIndexed( + len(newTxs)-len(missingIDs), + len(meta.ExecutedEntries), + len(meta.FailedEntries), + len(meta.CanceledEntries), + len(missingIDs), + ) + + return nil +} + +// ProcessBlockData processes the block data and returns event-derived metadata for the block's +// scheduled transaction lifecycle events. +// +// The returned []access.ScheduledTransaction slice is always nil because all updates in the block +// cannot be represented by a single slice of objects. Instead, data is passed via +// [ScheduledTransactionsMetadata], partitioned into their respective lifecycle events. +// +// No error returns are expected during normal operation. +func (s *ScheduledTransactions) ProcessBlockData(data BlockData) ([]access.ScheduledTransaction, ScheduledTransactionsMetadata, error) { + meta, err := s.collectScheduledTransactionData(data) + if err != nil { + return nil, ScheduledTransactionsMetadata{}, fmt.Errorf("failed to collect scheduled transaction data: %w", err) + } + return nil, *meta, nil +} + +// collectScheduledTransactionData collects the scheduled transaction data from the block events. +// +// No error returns are expected during normal operation. +func (s *ScheduledTransactions) collectScheduledTransactionData(data BlockData) (*ScheduledTransactionsMetadata, error) { + var newTxs []access.ScheduledTransaction + var executedEntries []ExecutedEntry + var canceledEntries []CanceledEntry + var failedEntries []FailedEntry + + // pendingEventTxIndex is the transaction index of the transaction that emitted the PendingExecution events. + // This is the system transaction that added the scheduled transactions into the system collection. + var pendingEventTxIndex *uint32 + + // pendingIDs tracks the IDs that appear in PendingExecution events so we can match them with Executed events. + // Any missing IDs are considered failed. + pendingIDs := make(map[uint64]struct{}) + + // track which IDs have Scheduled, Canceled, and Executed events to ensure an ID doesn't show up + // more than once in the same block. This should not happen, and the indexer does not handle it. + seenIDs := make(map[uint64]uint32) + checkDuplicate := func(id uint64, eventIndex uint32) error { + if lastID, ok := seenIDs[id]; ok { + return fmt.Errorf("scheduled transaction ID %d appears more than once in block %d (txs %d and %d)", + id, data.Header.Height, lastID, eventIndex) + } + seenIDs[id] = eventIndex + return nil + } + + for _, event := range data.Events { + switch event.Type { + case s.scheduledEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode Scheduled event payload: %w", err) + } + e, err := events.DecodeTransactionSchedulerScheduled(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode Scheduled event: %w", err) + } + + if err := checkDuplicate(e.ID, event.TransactionIndex); err != nil { + return nil, err + } + + newTxs = append(newTxs, access.ScheduledTransaction{ + ID: e.ID, + Priority: access.ScheduledTransactionPriority(e.Priority), + Timestamp: uint64(e.Timestamp), + ExecutionEffort: e.ExecutionEffort, + Fees: uint64(e.Fees), + TransactionHandlerOwner: e.TransactionHandlerOwner, + TransactionHandlerTypeIdentifier: e.TransactionHandlerTypeIdentifier, + TransactionHandlerUUID: e.TransactionHandlerUUID, + TransactionHandlerPublicPath: e.TransactionHandlerPublicPath, + Status: access.ScheduledTxStatusScheduled, + CreatedTransactionID: event.TransactionID, + }) + + case s.pendingExecutionType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode PendingExecution event payload: %w", err) + } + e, err := events.DecodeTransactionSchedulerPendingExecution(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode PendingExecution event: %w", err) + } + pendingIDs[e.ID] = struct{}{} + if pendingEventTxIndex == nil { + pendingEventTxIndex = &event.TransactionIndex + } + + case s.executedEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode Executed event payload: %w", err) + } + e, err := events.DecodeTransactionSchedulerExecuted(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode Executed event: %w", err) + } + + if err := checkDuplicate(e.ID, event.TransactionIndex); err != nil { + return nil, err + } + + executedEntries = append(executedEntries, ExecutedEntry{Event: e, TransactionID: event.TransactionID}) + + // sanity check: every Executed event must have a corresponding PendingExecution event. + // otherwise, there is a bug in the indexer, or elsewhere in the system. + if _, ok := pendingIDs[e.ID]; !ok { + return nil, fmt.Errorf("Executed event for tx %d has no corresponding PendingExecution in block %d: protocol invariant violated", + e.ID, data.Header.Height) + } + delete(pendingIDs, e.ID) // remove it so we can find failed transactions + + case s.canceledEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode Canceled event payload: %w", err) + } + e, err := events.DecodeTransactionSchedulerCanceled(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode Canceled event: %w", err) + } + + if err := checkDuplicate(e.ID, event.TransactionIndex); err != nil { + return nil, err + } + + canceledEntries = append(canceledEntries, CanceledEntry{Event: e, TransactionID: event.TransactionID}) + } + } + + // Any remaining pendingIDs were scheduled for execution but not executed — they failed. + if len(pendingIDs) > 0 { + if pendingEventTxIndex == nil { + // this shouldn't be possible and indicates a bug in the indexer + return nil, fmt.Errorf("found pending scheduled transactions, but no PendingExecution event found in block %d", data.Header.Height) + } + + // find the transaction that attempted to execute the scheduled transactions, and mark it as failed. + // start searching from the system transaction that adds the scheduled transactions into the + // system collection to reduce overhead. + for _, tx := range data.Transactions[*pendingEventTxIndex:] { + if !s.isExecutorTransaction(tx, data.Header.Height) { + continue + } + + id, err := decodeScheduledTxIDArg(tx.Arguments[0]) + if err != nil { + return nil, fmt.Errorf("failed to decode scheduled tx ID from executor transaction: %w", err) + } + if _, ok := pendingIDs[id]; ok { + failedEntries = append(failedEntries, FailedEntry{ScheduledTxID: id, TransactionID: tx.ID()}) + delete(pendingIDs, id) + } + } + + // sanity check: after matching with the actual transaction in the block, pendingIDs should be empty. + // otherwise, there were pending execution events that did not have a corresponding executor transaction. + // this indicates there is a bug in the indexer, or elsewhere in the system. + if len(pendingIDs) > 0 { + ids := make([]string, 0, len(pendingIDs)) + for id := range pendingIDs { + ids = append(ids, strconv.FormatUint(id, 10)) + } + return nil, fmt.Errorf("PendingExecution tx (%s) have no corresponding executor transaction in block %d", + strings.Join(ids, ", "), data.Header.Height) + } + } + + return &ScheduledTransactionsMetadata{ + NewTxs: newTxs, + ExecutedEntries: executedEntries, + CanceledEntries: canceledEntries, + FailedEntries: failedEntries, + }, nil +} + +// isExecutorTransaction returns true if the transaction was submitted by the scheduled executor +// account for the given block height: sole authorizer matches the height-appropriate executor +// address, payer is the empty address, and the transaction has at least one argument (the +// scheduled tx ID). +func (s *ScheduledTransactions) isExecutorTransaction(tx *flow.TransactionBody, height uint64) bool { + return tx.Payer == flow.EmptyAddress && + len(tx.Authorizers) == 1 && + len(tx.Arguments) >= 1 && + tx.Authorizers[0] == s.executorAddr.ByHeight(height) +} + +// decodeScheduledTxIDArg decodes a JSON-CDC encoded UInt64 argument as a scheduled tx ID. +// +// Any error indicates a malformed argument. +func decodeScheduledTxIDArg(arg []byte) (uint64, error) { + value, err := jsoncdc.Decode(nil, arg) + if err != nil { + return 0, fmt.Errorf("failed to JSON-CDC decode argument: %w", err) + } + id, ok := value.(cadence.UInt64) + if !ok { + return 0, fmt.Errorf("expected UInt64 argument, got %T", value) + } + return uint64(id), nil +} diff --git a/module/state_synchronization/indexer/extended/scheduled_transactions_test.go b/module/state_synchronization/indexer/extended/scheduled_transactions_test.go new file mode 100644 index 00000000000..1c0b5bec5ac --- /dev/null +++ b/module/state_synchronization/indexer/extended/scheduled_transactions_test.go @@ -0,0 +1,1261 @@ +package extended_test + +import ( + "fmt" + "os" + "testing" + + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/encoding/ccf" + jsoncdc "github.com/onflow/cadence/encoding/json" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + executionmock "github.com/onflow/flow-go/module/execution/mock" + "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes" + "github.com/onflow/flow-go/storage/indexes/iterator" + storagemock "github.com/onflow/flow-go/storage/mock" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" + + . "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" +) + +const ( + scheduledTestHeight = uint64(100) // v0 range on testnet (boundary at 290050888) + scheduledTestHeightV1 = uint64(290050900) // v1 range on testnet +) + +// TestScheduledTransactionsIndexer_NoEvents verifies that indexing a block with no scheduler +// events stores an empty slice and advances the height. +func TestScheduledTransactionsIndexer_NoEvents(t *testing.T) { + t.Parallel() + + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{}, + }) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, scheduledTestHeight, latest) + + allIter, err := store.All(nil) + require.NoError(t, err) + allTxs, _, err := iterator.CollectResults(allIter, 1000, nil) + require.NoError(t, err) + assert.Empty(t, allTxs) +} + +// TestScheduledTransactionsIndexer_NextHeight_NotBootstrapped verifies that NextHeight returns +// the configured first height before any blocks have been indexed. +func TestScheduledTransactionsIndexer_NextHeight_NotBootstrapped(t *testing.T) { + t.Parallel() + + indexer, _, _, _ := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + + height, err := indexer.NextHeight() + require.NoError(t, err) + assert.Equal(t, scheduledTestHeight, height) +} + +// TestScheduledTransactionsIndexer_ScheduledEvent verifies that a Scheduled event creates a new +// entry with status Scheduled and all fields correctly parsed, including ScheduledTransactionID. +func TestScheduledTransactionsIndexer_ScheduledEvent(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + event := createScheduledEvent(t, sc, 1, 3, 1000, 500, 200, owner, "A.1234.SomeContract.Handler", 42, "") + schedulingTxID := unittest.IdentifierFixture() + event.TransactionID = schedulingTxID + + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{event}, + }) + + tx, err := store.ByID(1) + require.NoError(t, err) + assert.Equal(t, uint64(1), tx.ID) + assert.Equal(t, access.ScheduledTransactionPriority(3), tx.Priority) + assert.Equal(t, uint64(1000), tx.Timestamp) + assert.Equal(t, uint64(500), tx.ExecutionEffort) + assert.Equal(t, uint64(200), tx.Fees) + assert.Equal(t, owner, tx.TransactionHandlerOwner) + assert.Equal(t, "A.1234.SomeContract.Handler", tx.TransactionHandlerTypeIdentifier) + assert.Equal(t, uint64(42), tx.TransactionHandlerUUID) + assert.Equal(t, "", tx.TransactionHandlerPublicPath) + assert.Equal(t, access.ScheduledTxStatusScheduled, tx.Status) + assert.Equal(t, schedulingTxID, tx.CreatedTransactionID) +} + +// TestScheduledTransactionsIndexer_ScheduledEventPublicPath verifies that the optional +// transactionHandlerPublicPath field is correctly stored when present. +func TestScheduledTransactionsIndexer_ScheduledEventPublicPath(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + event := createScheduledEvent(t, sc, 1, 1, 1000, 100, 50, owner, "A.abcd.Contract.Handler", 10, "handlerCapability") + + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{event}, + }) + + tx, err := store.ByID(1) + require.NoError(t, err) + assert.Equal(t, "/public/handlerCapability", tx.TransactionHandlerPublicPath) +} + +// TestScheduledTransactionsIndexer_ExecutedWithPending verifies that a tx scheduled at height 1 +// and then executed at height 2 (with PendingExecution + Executed) is correctly updated to +// Executed status. Execution must occur in a separate block from scheduling because the storage +// layer reads only committed state. Verifies ExecutedTransactionID is set. +func TestScheduledTransactionsIndexer_ExecutedWithPending(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule tx with id=5 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + scheduledEvt := createScheduledEvent(t, sc, 5, 1, 2000, 300, 100, owner, "A.abc.Contract.Handler", 99, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{scheduledEvt}, + }) + + // Height 2: execute tx with id=5 + executedTxID := unittest.IdentifierFixture() + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+1)) + pendingEvt := createPendingExecutionEvent(t, sc, 5, 1, 300, 100, owner, "A.abc.Contract.Handler") + executedEvt := createExecutedEvent(t, sc, 5, 1, 300, owner, "A.abc.Contract.Handler", 99, "") + executedEvt.TransactionID = executedTxID + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pendingEvt, executedEvt}, + }) + + tx, err := store.ByID(5) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusExecuted, tx.Status) + assert.Equal(t, uint64(300), tx.ExecutionEffort) + assert.Equal(t, executedTxID, tx.ExecutedTransactionID) +} + +// TestScheduledTransactionsIndexer_CanceledEvent verifies that a Canceled event at height 2 +// updates an entry (created at height 1) to Cancelled status with correct fee fields. +// Verifies CancelledTransactionID is set. +func TestScheduledTransactionsIndexer_CanceledEvent(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule tx with id=7 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + scheduledEvt := createScheduledEvent(t, sc, 7, 2, 5000, 400, 150, owner, "A.def.Contract.Handler", 77, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{scheduledEvt}, + }) + + // Height 2: cancel tx with id=7 + cancelTxID := unittest.IdentifierFixture() + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+1)) + canceledEvt := createCanceledEvent(t, sc, 7, 2, 100, 50, owner, "A.def.Contract.Handler") + canceledEvt.TransactionID = cancelTxID + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{canceledEvt}, + }) + + tx, err := store.ByID(7) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusCancelled, tx.Status) + assert.Equal(t, uint64(100), tx.FeesReturned) + assert.Equal(t, uint64(50), tx.FeesDeducted) + assert.Equal(t, cancelTxID, tx.CancelledTransactionID) +} + +// TestScheduledTransactionsIndexer_FailedTransaction verifies that a scheduled tx with a +// PendingExecution event but no Executed event is marked as Failed when a corresponding +// executor transaction is present in the block. Verifies ExecutedTransactionID is set. +func TestScheduledTransactionsIndexer_FailedTransaction(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule tx with id=42 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + scheduledEvt := createScheduledEvent(t, sc, 42, 1, 3000, 200, 80, owner, "A.xyz.Contract.Handler", 15, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{scheduledEvt}, + }) + + // Height 2: PendingExecution for tx 42, no Executed event. + // The executor transaction attempted to execute the scheduled tx but failed. + // scheduledTestHeight falls in the v0 range on testnet, so the executor uses FlowServiceAccount. + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+1)) + pendingEvt := createPendingExecutionEvent(t, sc, 42, 1, 200, 80, owner, "A.xyz.Contract.Handler") + executorTx := makeExecutorTransactionBody(t, sc.FlowServiceAccount.Address, 42) + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pendingEvt}, + Transactions: []*flow.TransactionBody{executorTx}, + }) + + tx, err := store.ByID(42) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusFailed, tx.Status) + assert.Equal(t, executorTx.ID(), tx.ExecutedTransactionID) +} + +// TestScheduledTransactionsIndexer_FailedTransactionV1 verifies that the failed-tx detection +// path matches executor transactions authorized by ScheduledTransactionExecutor (v1 system +// collection format, used after the version boundary). +func TestScheduledTransactionsIndexer_FailedTransactionV1(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeightV1) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule tx with id=99 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeightV1)) + scheduledEvt := createScheduledEvent(t, sc, 99, 1, 3000, 200, 80, owner, "A.xyz.Contract.Handler", 15, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{scheduledEvt}, + }) + + // Height 2: PendingExecution for tx 99, no Executed event. + // v1 uses ScheduledTransactionExecutor.Address as the authorizer. + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeightV1+1)) + pendingEvt := createPendingExecutionEvent(t, sc, 99, 1, 200, 80, owner, "A.xyz.Contract.Handler") + executorTx := makeExecutorTransactionBody(t, sc.ScheduledTransactionExecutor.Address, 99) + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pendingEvt}, + Transactions: []*flow.TransactionBody{executorTx}, + }) + + tx, err := store.ByID(99) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusFailed, tx.Status) + assert.Equal(t, executorTx.ID(), tx.ExecutedTransactionID) +} + +// TestScheduledTransactionsIndexer_PendingWithoutExecuted verifies that a PendingExecution event +// without either a matching Executed event or a corresponding executor transaction returns an error. +func TestScheduledTransactionsIndexer_PendingWithoutExecuted(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + pendingEvt := createPendingExecutionEvent(t, sc, 10, 1, 300, 100, owner, "A.abc.Contract.Handler") + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{pendingEvt}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "have no corresponding executor transaction") +} + +// TestScheduledTransactionsIndexer_ExecutedWithoutPending verifies that an Executed event without +// a matching PendingExecution event returns an error (protocol invariant violation). +func TestScheduledTransactionsIndexer_ExecutedWithoutPending(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + executedEvt := createExecutedEvent(t, sc, 11, 1, 300, owner, "A.abc.Contract.Handler", 55, "") + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{executedEvt}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "protocol invariant violated") +} + +// TestScheduledTransactionsIndexer_DuplicateID verifies that having the same scheduled +// transaction ID appear more than once in a block (across Scheduled, Executed, or Canceled +// events) returns an error. +func TestScheduledTransactionsIndexer_DuplicateID(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + + t.Run("duplicate Scheduled events", func(t *testing.T) { + t.Parallel() + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + evt1 := createScheduledEvent(t, sc, 5, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler", 1, "") + evt2 := createScheduledEvent(t, sc, 5, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler", 2, "") + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{evt1, evt2}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "appears more than once") + }) + + t.Run("duplicate Executed events", func(t *testing.T) { + t.Parallel() + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + // One PendingExecution event allows the first Executed to pass the pendingIDs check. + // The second Executed with the same ID is caught by seenIDs before reaching pendingIDs. + pendingEvt := createPendingExecutionEvent(t, sc, 5, 1, 100, 50, owner, "A.abc.Contract.Handler") + executedEvt1 := createExecutedEvent(t, sc, 5, 1, 100, owner, "A.abc.Contract.Handler", 1, "") + executedEvt2 := createExecutedEvent(t, sc, 5, 1, 100, owner, "A.abc.Contract.Handler", 1, "") + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{pendingEvt, executedEvt1, executedEvt2}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "appears more than once") + }) + + t.Run("duplicate Canceled events", func(t *testing.T) { + t.Parallel() + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + canceledEvt1 := createCanceledEvent(t, sc, 5, 1, 100, 50, owner, "A.abc.Contract.Handler") + canceledEvt2 := createCanceledEvent(t, sc, 5, 1, 100, 50, owner, "A.abc.Contract.Handler") + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{canceledEvt1, canceledEvt2}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "appears more than once") + }) + + t.Run("Scheduled then Executed in same block", func(t *testing.T) { + t.Parallel() + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + scheduledEvt := createScheduledEvent(t, sc, 5, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler", 1, "") + executedEvt := createExecutedEvent(t, sc, 5, 1, 100, owner, "A.abc.Contract.Handler", 1, "") + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{scheduledEvt, executedEvt}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "appears more than once") + }) + + t.Run("Scheduled then Canceled in same block", func(t *testing.T) { + t.Parallel() + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + scheduledEvt := createScheduledEvent(t, sc, 5, 1, 1000, 100, 50, owner, "A.abc.Contract.Handler", 1, "") + canceledEvt := createCanceledEvent(t, sc, 5, 1, 100, 50, owner, "A.abc.Contract.Handler") + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{scheduledEvt, canceledEvt}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "appears more than once") + }) +} + +// ===== ProcessBlockData tests ===== + +// TestScheduledTransactionsIndexer_ProcessBlockData_NoEvents verifies that ProcessBlockData +// returns nil entries and empty metadata for a block with no scheduler events. +func TestScheduledTransactionsIndexer_ProcessBlockData_NoEvents(t *testing.T) { + t.Parallel() + + indexer, _, _, _ := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + entries, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{}}) + require.NoError(t, err) + assert.Nil(t, entries) + assert.Empty(t, meta.NewTxs) + assert.Empty(t, meta.ExecutedEntries) + assert.Empty(t, meta.CanceledEntries) + assert.Empty(t, meta.FailedEntries) +} + +// TestScheduledTransactionsIndexer_ProcessBlockData_ScheduledEvent verifies that ProcessBlockData +// populates NewTxs in the metadata for a Scheduled event. +func TestScheduledTransactionsIndexer_ProcessBlockData_ScheduledEvent(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, _, _, _ := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + event := createScheduledEvent(t, sc, 1, 3, 1000, 500, 200, owner, "A.1234.SomeContract.Handler", 42, "") + + entries, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{event}}) + require.NoError(t, err) + assert.Nil(t, entries) // always nil for scheduled txs + require.Len(t, meta.NewTxs, 1) + assert.Equal(t, uint64(1), meta.NewTxs[0].ID) + assert.Equal(t, access.ScheduledTransactionPriority(3), meta.NewTxs[0].Priority) + assert.Empty(t, meta.ExecutedEntries) + assert.Empty(t, meta.CanceledEntries) + assert.Empty(t, meta.FailedEntries) +} + +// TestScheduledTransactionsIndexer_ProcessBlockData_ExecutedEvent verifies that ProcessBlockData +// populates ExecutedEntries in the metadata for PendingExecution + Executed events. +func TestScheduledTransactionsIndexer_ProcessBlockData_ExecutedEvent(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, _, _, _ := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + pendingEvt := createPendingExecutionEvent(t, sc, 5, 1, 300, 100, owner, "A.abc.Contract.Handler") + executedEvt := createExecutedEvent(t, sc, 5, 1, 300, owner, "A.abc.Contract.Handler", 99, "") + + _, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{pendingEvt, executedEvt}}) + require.NoError(t, err) + require.Len(t, meta.ExecutedEntries, 1) + assert.Empty(t, meta.NewTxs) + assert.Empty(t, meta.CanceledEntries) +} + +// TestScheduledTransactionsIndexer_ProcessBlockData_CanceledEvent verifies that ProcessBlockData +// populates CanceledEntries in the metadata for a Canceled event. +func TestScheduledTransactionsIndexer_ProcessBlockData_CanceledEvent(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, _, _, _ := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + canceledEvt := createCanceledEvent(t, sc, 7, 2, 100, 50, owner, "A.def.Contract.Handler") + + _, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{canceledEvt}}) + require.NoError(t, err) + require.Len(t, meta.CanceledEntries, 1) + assert.Empty(t, meta.NewTxs) + assert.Empty(t, meta.ExecutedEntries) +} + +// TestScheduledTransactionsIndexer_ProcessBlockData_DoesNotDependOnHeight verifies that +// ProcessBlockData can be called with any height without checking the indexer's height state. +func TestScheduledTransactionsIndexer_ProcessBlockData_DoesNotDependOnHeight(t *testing.T) { + t.Parallel() + + indexer, _, _, _ := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+100)) + + entries, meta, err := indexer.ProcessBlockData(BlockData{Header: header, Events: []flow.Event{}}) + require.NoError(t, err) + assert.Nil(t, entries) + assert.Empty(t, meta.NewTxs) +} + +// TestScheduledTransactionsIndexer_AlreadyIndexed verifies that indexing the same height twice +// returns ErrAlreadyIndexed. +func TestScheduledTransactionsIndexer_AlreadyIndexed(t *testing.T) { + t.Parallel() + + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + // First index succeeds + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{}, + }) + + // Second index of same height returns ErrAlreadyIndexed + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{}, + }) + require.ErrorIs(t, err, ErrAlreadyIndexed) +} + +// TestScheduledTransactionsIndexer_FutureHeight verifies that indexing a future height (skipping +// heights) returns ErrFutureHeight. +func TestScheduledTransactionsIndexer_FutureHeight(t *testing.T) { + t.Parallel() + + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+5)) + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{}, + }) + require.ErrorIs(t, err, ErrFutureHeight) +} + +// TestScheduledTransactionsIndexer_MultipleScheduledInOneBlock verifies that multiple Scheduled +// events in a single block are all stored with correct fields. +func TestScheduledTransactionsIndexer_MultipleScheduledInOneBlock(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + evt1 := createScheduledEvent(t, sc, 1, 1, 1000, 100, 10, owner, "A.abc.Contract.HandlerA", 1, "") + evt2 := createScheduledEvent(t, sc, 2, 2, 2000, 200, 20, owner, "A.abc.Contract.HandlerB", 2, "") + evt3 := createScheduledEvent(t, sc, 3, 3, 3000, 300, 30, owner, "A.abc.Contract.HandlerC", 3, "") + + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{evt1, evt2, evt3}, + }) + + allIter2, err := store.All(nil) + require.NoError(t, err) + allTxs2, _, err := iterator.CollectResults(allIter2, 1000, nil) + require.NoError(t, err) + require.Len(t, allTxs2, 3) + + tx1, err := store.ByID(1) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTransactionPriority(1), tx1.Priority) + + tx2, err := store.ByID(2) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTransactionPriority(2), tx2.Priority) + + tx3, err := store.ByID(3) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTransactionPriority(3), tx3.Priority) +} + +// TestScheduledTransactionsIndexer_MultiplePendingExecuted verifies that multiple scheduled txs +// with PendingExecution and Executed events in the same block are all marked as Executed. +func TestScheduledTransactionsIndexer_MultiplePendingExecuted(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule txs 10 and 11 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + evt10 := createScheduledEvent(t, sc, 10, 1, 1000, 100, 10, owner, "A.abc.Contract.Handler", 10, "") + evt11 := createScheduledEvent(t, sc, 11, 1, 1000, 200, 10, owner, "A.abc.Contract.Handler", 11, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{evt10, evt11}, + }) + + // Height 2: execute both txs + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+1)) + pending10 := createPendingExecutionEvent(t, sc, 10, 1, 100, 10, owner, "A.abc.Contract.Handler") + pending11 := createPendingExecutionEvent(t, sc, 11, 1, 200, 10, owner, "A.abc.Contract.Handler") + executed10 := createExecutedEvent(t, sc, 10, 1, 100, owner, "A.abc.Contract.Handler", 10, "") + executed11 := createExecutedEvent(t, sc, 11, 1, 200, owner, "A.abc.Contract.Handler", 11, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pending10, pending11, executed10, executed11}, + }) + + tx10, err := store.ByID(10) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusExecuted, tx10.Status) + + tx11, err := store.ByID(11) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusExecuted, tx11.Status) +} + +// TestScheduledTransactionsIndexer_MixedFailedAndExecuted verifies that in a block where some +// scheduled txs succeed and others fail, each is correctly marked with the appropriate status. +func TestScheduledTransactionsIndexer_MixedFailedAndExecuted(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule txs 20 and 21 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + evt20 := createScheduledEvent(t, sc, 20, 1, 1000, 100, 10, owner, "A.abc.Contract.Handler", 20, "") + evt21 := createScheduledEvent(t, sc, 21, 1, 1000, 150, 10, owner, "A.abc.Contract.Handler", 21, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{evt20, evt21}, + }) + + // Height 2: tx 20 succeeds, tx 21 fails (executor tx present, no Executed event) + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+1)) + pending20 := createPendingExecutionEvent(t, sc, 20, 1, 100, 10, owner, "A.abc.Contract.Handler") + pending21 := createPendingExecutionEvent(t, sc, 21, 1, 150, 10, owner, "A.abc.Contract.Handler") + executed20 := createExecutedEvent(t, sc, 20, 1, 100, owner, "A.abc.Contract.Handler", 20, "") + executorTx21 := makeExecutorTransactionBody(t, sc.FlowServiceAccount.Address, 21) + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pending20, pending21, executed20}, + Transactions: []*flow.TransactionBody{executorTx21}, + }) + + tx20, err := store.ByID(20) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusExecuted, tx20.Status) + + tx21, err := store.ByID(21) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusFailed, tx21.Status) + assert.Equal(t, executorTx21.ID(), tx21.ExecutedTransactionID) +} + +// TestScheduledTransactionsIndexer_NonExecutorTxSkipped verifies that non-executor transactions +// (wrong payer, wrong authorizer, etc.) before the executor transaction are correctly skipped +// when searching for the executor of a failed scheduled transaction. +func TestScheduledTransactionsIndexer_NonExecutorTxSkipped(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule tx with id=30 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + scheduledEvt := createScheduledEvent(t, sc, 30, 1, 1000, 100, 10, owner, "A.abc.Contract.Handler", 30, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{scheduledEvt}, + }) + + // Height 2: PendingExecution for tx 30, a non-executor tx, then the real executor tx. + // The non-executor tx has the wrong payer and should be skipped. + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+1)) + pendingEvt := createPendingExecutionEvent(t, sc, 30, 1, 100, 10, owner, "A.abc.Contract.Handler") + nonExecutorTx := &flow.TransactionBody{ + Payer: unittest.RandomAddressFixture(), // wrong payer + Authorizers: []flow.Address{sc.FlowServiceAccount.Address}, + } + executorTx := makeExecutorTransactionBody(t, sc.FlowServiceAccount.Address, 30) + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pendingEvt}, + Transactions: []*flow.TransactionBody{nonExecutorTx, executorTx}, + }) + + tx, err := store.ByID(30) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusFailed, tx.Status) + assert.Equal(t, executorTx.ID(), tx.ExecutedTransactionID) +} + +// TestScheduledTransactionsIndexer_MixedFailedAndExecutedV1 is the v1 counterpart of +// TestScheduledTransactionsIndexer_MixedFailedAndExecuted, using ScheduledTransactionExecutor +// as the executor authorizer. +func TestScheduledTransactionsIndexer_MixedFailedAndExecutedV1(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeightV1) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule txs 20 and 21 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeightV1)) + evt20 := createScheduledEvent(t, sc, 20, 1, 1000, 100, 10, owner, "A.abc.Contract.Handler", 20, "") + evt21 := createScheduledEvent(t, sc, 21, 1, 1000, 150, 10, owner, "A.abc.Contract.Handler", 21, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{evt20, evt21}, + }) + + // Height 2: tx 20 succeeds, tx 21 fails (executor tx present, no Executed event) + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeightV1+1)) + pending20 := createPendingExecutionEvent(t, sc, 20, 1, 100, 10, owner, "A.abc.Contract.Handler") + pending21 := createPendingExecutionEvent(t, sc, 21, 1, 150, 10, owner, "A.abc.Contract.Handler") + executed20 := createExecutedEvent(t, sc, 20, 1, 100, owner, "A.abc.Contract.Handler", 20, "") + executorTx21 := makeExecutorTransactionBody(t, sc.ScheduledTransactionExecutor.Address, 21) + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pending20, pending21, executed20}, + Transactions: []*flow.TransactionBody{executorTx21}, + }) + + tx20, err := store.ByID(20) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusExecuted, tx20.Status) + + tx21, err := store.ByID(21) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusFailed, tx21.Status) + assert.Equal(t, executorTx21.ID(), tx21.ExecutedTransactionID) +} + +// TestScheduledTransactionsIndexer_NonExecutorTxSkippedV1 is the v1 counterpart of +// TestScheduledTransactionsIndexer_NonExecutorTxSkipped, using ScheduledTransactionExecutor +// as the executor authorizer. +func TestScheduledTransactionsIndexer_NonExecutorTxSkippedV1(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, store, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeightV1) + + owner := unittest.RandomAddressFixture() + + // Height 1: schedule tx with id=30 + header1 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeightV1)) + scheduledEvt := createScheduledEvent(t, sc, 30, 1, 1000, 100, 10, owner, "A.abc.Contract.Handler", 30, "") + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header1, + Events: []flow.Event{scheduledEvt}, + }) + + // Height 2: PendingExecution for tx 30, a non-executor tx, then the real executor tx. + // The non-executor tx has the wrong payer and should be skipped. + header2 := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeightV1+1)) + pendingEvt := createPendingExecutionEvent(t, sc, 30, 1, 100, 10, owner, "A.abc.Contract.Handler") + nonExecutorTx := &flow.TransactionBody{ + Payer: unittest.RandomAddressFixture(), // wrong payer + Authorizers: []flow.Address{sc.ScheduledTransactionExecutor.Address}, + } + executorTx := makeExecutorTransactionBody(t, sc.ScheduledTransactionExecutor.Address, 30) + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header2, + Events: []flow.Event{pendingEvt}, + Transactions: []*flow.TransactionBody{nonExecutorTx, executorTx}, + }) + + tx, err := store.ByID(30) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusFailed, tx.Status) + assert.Equal(t, executorTx.ID(), tx.ExecutedTransactionID) +} + +// TestScheduledTransactionsIndexer_ExecutorTxNoArguments verifies that a transaction with the +// correct executor address and payer but no arguments is not treated as an executor transaction. +// This distinguishes executor transactions from other system transactions (e.g. ProcessCallbacksTransaction) +// that share the same authorizer in v0. +func TestScheduledTransactionsIndexer_ExecutorTxNoArguments(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + pendingEvt := createPendingExecutionEvent(t, sc, 50, 1, 100, 10, owner, "A.abc.Contract.Handler") + // A system transaction with no arguments should not be matched as an executor tx, + // even though it has the right authorizer and payer. + noArgTx := &flow.TransactionBody{ + Payer: flow.EmptyAddress, + Authorizers: []flow.Address{sc.FlowServiceAccount.Address}, + Arguments: nil, + } + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{pendingEvt}, + Transactions: []*flow.TransactionBody{noArgTx}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "have no corresponding executor transaction") +} + +// TestScheduledTransactionsIndexer_ExecutorTxMalformedArg verifies that an executor transaction +// with an argument that cannot be decoded as a UInt64 returns an error. +func TestScheduledTransactionsIndexer_ExecutorTxMalformedArg(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + indexer, _, lm, db := newScheduledTxIndexerForTest(t, flow.Testnet, scheduledTestHeight) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + + owner := unittest.RandomAddressFixture() + pendingEvt := createPendingExecutionEvent(t, sc, 50, 1, 100, 10, owner, "A.abc.Contract.Handler") + + // Valid JSON-CDC encoding but wrong type (String instead of UInt64) + malformedArg, encErr := jsoncdc.Encode(cadence.String("not-a-uint64")) + require.NoError(t, encErr) + executorTx := &flow.TransactionBody{ + Payer: flow.EmptyAddress, + Authorizers: []flow.Address{sc.FlowServiceAccount.Address}, + Arguments: [][]byte{malformedArg}, + } + + err := indexScheduledBlockExpectError(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{pendingEvt}, + Transactions: []*flow.TransactionBody{executorTx}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to decode scheduled tx ID from executor transaction") +} + +// TestScheduledTransactionsIndexer_NextHeight_MockErrors verifies error propagation from the store. +func TestScheduledTransactionsIndexer_NextHeight_MockErrors(t *testing.T) { + t.Parallel() + + t.Run("unexpected error from LatestIndexedHeight propagates", func(t *testing.T) { + mockStore := storagemock.NewScheduledTransactionsIndexBootstrapper(t) + unexpectedErr := fmt.Errorf("disk I/O failure") + mockStore.On("LatestIndexedHeight").Return(uint64(0), unexpectedErr) + + indexer := NewScheduledTransactions(unittest.Logger(), mockStore, nil, metrics.NewNoopCollector(), flow.Testnet) + + _, err := indexer.NextHeight() + require.Error(t, err) + require.ErrorIs(t, err, unexpectedErr) + }) + + t.Run("inconsistent state: not bootstrapped but initialized", func(t *testing.T) { + mockStore := storagemock.NewScheduledTransactionsIndexBootstrapper(t) + mockStore.On("LatestIndexedHeight").Return(uint64(0), storage.ErrNotBootstrapped) + mockStore.On("UninitializedFirstHeight").Return(uint64(42), true) + + indexer := NewScheduledTransactions(unittest.Logger(), mockStore, nil, metrics.NewNoopCollector(), flow.Testnet) + + _, err := indexer.NextHeight() + require.Error(t, err) + assert.Contains(t, err.Error(), "but index is initialized") + }) + + t.Run("store error propagates from IndexBlockData", func(t *testing.T) { + const testHeight = uint64(100) + mockStore := storagemock.NewScheduledTransactionsIndexBootstrapper(t) + // LatestIndexedHeight returns testHeight-1, so NextHeight = testHeight + mockStore.On("LatestIndexedHeight").Return(testHeight-1, nil) + storeErr := fmt.Errorf("unexpected storage error") + mockStore.On("Store", mock.Anything, mock.Anything, testHeight, mock.Anything).Return(storeErr) + + lm := storage.NewTestingLockManager() + indexer := NewScheduledTransactions(unittest.Logger(), mockStore, nil, metrics.NewNoopCollector(), flow.Testnet) + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(testHeight)) + + err := unittest.WithLock(t, lm, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return indexer.IndexBlockData(lctx, BlockData{Header: header, Events: []flow.Event{}}, nil) + }) + require.Error(t, err) + require.ErrorIs(t, err, storeErr) + }) +} + +// ===== Test Setup Helpers ===== + +// newScheduledTxIndexerForTest creates a ScheduledTransactions indexer backed by a real pebble DB. +func newScheduledTxIndexerForTest( + t *testing.T, + chainID flow.ChainID, + firstHeight uint64, +) (*ScheduledTransactions, storage.ScheduledTransactionsIndexBootstrapper, storage.LockManager, storage.DB) { + pdb, dbDir := unittest.TempPebbleDB(t) + db := pebbleimpl.ToDB(pdb) + t.Cleanup(func() { + require.NoError(t, db.Close()) + require.NoError(t, os.RemoveAll(dbDir)) + }) + + lm := storage.NewTestingLockManager() + store, err := indexes.NewScheduledTransactionsBootstrapper(db, firstHeight) + require.NoError(t, err) + + indexer := NewScheduledTransactions(unittest.Logger(), store, nil, metrics.NewNoopCollector(), chainID) + return indexer, store, lm, db +} + +// indexScheduledBlock runs IndexBlockData with proper locking and batch commit. +func indexScheduledBlock( + t *testing.T, + indexer *ScheduledTransactions, + lm storage.LockManager, + db storage.DB, + data BlockData, +) { + err := unittest.WithLock(t, lm, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return indexer.IndexBlockData(lctx, data, rw) + }) + }) + require.NoError(t, err) +} + +// indexScheduledBlockExpectError runs IndexBlockData and returns the error. +func indexScheduledBlockExpectError( + t *testing.T, + indexer *ScheduledTransactions, + lm storage.LockManager, + db storage.DB, + data BlockData, +) error { + return unittest.WithLock(t, lm, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return indexer.IndexBlockData(lctx, data, rw) + }) + }) +} + +// ===== JIT Lookup Integration Test ===== + +// TestScheduledTransactionsIndexer_JITLookup verifies the end-to-end JIT path: when +// IndexBlockData encounters an unknown transaction (storage returns ErrNotFound), it +// delegates to the requester, and the result is written to storage. +// The script execution details are covered by TestScheduledTransactionRequester_* tests. +func TestScheduledTransactionsIndexer_JITLookup(t *testing.T) { + t.Parallel() + + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + owner := unittest.RandomAddressFixture() + + scriptExecutor := executionmock.NewScriptExecutor(t) + indexer, store, lm, db := newScheduledTxIndexerWithScriptExecutor(t, flow.Testnet, scheduledTestHeight, scriptExecutor) + + // Bootstrap so Executed/Cancelled/Failed return ErrNotFound on the next block, + // triggering the JIT path. + bootstrapHeader := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight)) + indexScheduledBlock(t, indexer, lm, db, BlockData{Header: bootstrapHeader, Events: []flow.Event{}}) + + executedTxID := unittest.IdentifierFixture() + header := unittest.BlockHeaderFixtureOnChain(flow.Testnet, unittest.WithHeaderHeight(scheduledTestHeight+1)) + pendingEvt := createPendingExecutionEvent(t, sc, 5, 1, 300, 100, owner, "A.abc.Contract.Handler") + executedEvt := createExecutedEvent(t, sc, 5, 1, 300, owner, "A.abc.Contract.Handler", 99, "") + executedEvt.TransactionID = executedTxID + + scriptHeight := header.Height - 1 + comp := MakeTransactionDataComposite(sc, 5, 1, 1000, 300, 100, owner, "A.abc.Contract.Handler") + scriptExecutor.On("ExecuteAtBlockHeight", + mock.Anything, mock.Anything, mock.Anything, scriptHeight, + ).Return(MakeJITScriptResponse(t, comp), nil).Once() + + indexScheduledBlock(t, indexer, lm, db, BlockData{ + Header: header, + Events: []flow.Event{pendingEvt, executedEvt}, + }) + + tx, err := store.ByID(5) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusExecuted, tx.Status) + assert.Equal(t, executedTxID, tx.ExecutedTransactionID) +} + +// ===== JIT Lookup Helpers ===== + +// newScheduledTxIndexerWithScriptExecutor creates an indexer backed by a real pebble DB +// with the given script executor. +func newScheduledTxIndexerWithScriptExecutor( + t *testing.T, + chainID flow.ChainID, + firstHeight uint64, + scriptExecutor *executionmock.ScriptExecutor, +) (*ScheduledTransactions, storage.ScheduledTransactionsIndexBootstrapper, storage.LockManager, storage.DB) { + pdb, dbDir := unittest.TempPebbleDB(t) + db := pebbleimpl.ToDB(pdb) + t.Cleanup(func() { + require.NoError(t, db.Close()) + require.NoError(t, os.RemoveAll(dbDir)) + }) + + lm := storage.NewTestingLockManager() + store, err := indexes.NewScheduledTransactionsBootstrapper(db, firstHeight) + require.NoError(t, err) + + indexer := NewScheduledTransactions(unittest.Logger(), store, scriptExecutor, metrics.NewNoopCollector(), chainID) + return indexer, store, lm, db +} + +// makeExecutorTransactionBody creates a transaction body that matches the executor transaction +// criteria: payer is the zero address, sole authorizer is the executor address, and the first +// argument is a JSON-CDC encoded UInt64 with the given scheduled tx ID. +func makeExecutorTransactionBody(t *testing.T, executorAddr flow.Address, scheduledTxID uint64) *flow.TransactionBody { + t.Helper() + arg, err := jsoncdc.Encode(cadence.UInt64(scheduledTxID)) + require.NoError(t, err) + return &flow.TransactionBody{ + Payer: flow.EmptyAddress, + Authorizers: []flow.Address{executorAddr}, + Arguments: [][]byte{arg}, + } +} + +// schedulerEventType returns the full event type string for the given event name. +func schedulerEventType(sc *systemcontracts.SystemContracts, eventName string) flow.EventType { + return flow.EventType(fmt.Sprintf("A.%s.%s.%s", + sc.FlowTransactionScheduler.Address.Hex(), + sc.FlowTransactionScheduler.Name, + eventName, + )) +} + +// schedulerEventLocation returns the Cadence address location for the scheduler contract. +func schedulerEventLocation(sc *systemcontracts.SystemContracts) common.Location { + addr := common.Address(sc.FlowTransactionScheduler.Address) + return common.NewAddressLocation(nil, addr, sc.FlowTransactionScheduler.Name) +} + +// createScheduledEvent builds a CCF-encoded Scheduled event for the FlowTransactionScheduler. +// If publicPath is empty, the transactionHandlerPublicPath field is set to nil. +func createScheduledEvent( + t *testing.T, + sc *systemcontracts.SystemContracts, + id uint64, + priority uint8, + timestamp uint64, + executionEffort uint64, + fees uint64, + owner flow.Address, + typeIdentifier string, + uuid uint64, + publicPath string, +) flow.Event { + t.Helper() + + var publicPathValue cadence.Value + if publicPath != "" { + path := cadence.MustNewPath(common.PathDomainPublic, publicPath) + publicPathValue = cadence.NewOptional(path) + } else { + publicPathValue = cadence.NewOptional(nil) + } + + location := schedulerEventLocation(sc) + eventCadenceType := cadence.NewEventType( + location, + "Scheduled", + []cadence.Field{ + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "priority", Type: cadence.UInt8Type}, + {Identifier: "timestamp", Type: cadence.UFix64Type}, + {Identifier: "executionEffort", Type: cadence.UInt64Type}, + {Identifier: "fees", Type: cadence.UFix64Type}, + {Identifier: "transactionHandlerOwner", Type: cadence.AddressType}, + {Identifier: "transactionHandlerTypeIdentifier", Type: cadence.StringType}, + {Identifier: "transactionHandlerUUID", Type: cadence.UInt64Type}, + {Identifier: "transactionHandlerPublicPath", Type: cadence.NewOptionalType(cadence.PublicPathType)}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.UInt64(id), + cadence.UInt8(priority), + cadence.UFix64(timestamp), + cadence.UInt64(executionEffort), + cadence.UFix64(fees), + cadence.NewAddress(owner), + cadence.String(typeIdentifier), + cadence.UInt64(uuid), + publicPathValue, + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: schedulerEventType(sc, "Scheduled"), + TransactionIndex: 0, + EventIndex: 0, + Payload: payload, + } +} + +// createPendingExecutionEvent builds a CCF-encoded PendingExecution event. +func createPendingExecutionEvent( + t *testing.T, + sc *systemcontracts.SystemContracts, + id uint64, + priority uint8, + executionEffort uint64, + fees uint64, + owner flow.Address, + typeIdentifier string, +) flow.Event { + t.Helper() + + location := schedulerEventLocation(sc) + eventCadenceType := cadence.NewEventType( + location, + "PendingExecution", + []cadence.Field{ + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "priority", Type: cadence.UInt8Type}, + {Identifier: "executionEffort", Type: cadence.UInt64Type}, + {Identifier: "fees", Type: cadence.UFix64Type}, + {Identifier: "transactionHandlerOwner", Type: cadence.AddressType}, + {Identifier: "transactionHandlerTypeIdentifier", Type: cadence.StringType}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.UInt64(id), + cadence.UInt8(priority), + cadence.UInt64(executionEffort), + cadence.UFix64(fees), + cadence.NewAddress(owner), + cadence.String(typeIdentifier), + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: schedulerEventType(sc, "PendingExecution"), + TransactionIndex: 0, + EventIndex: 1, + Payload: payload, + } +} + +// createExecutedEvent builds a CCF-encoded Executed event. +func createExecutedEvent( + t *testing.T, + sc *systemcontracts.SystemContracts, + id uint64, + priority uint8, + executionEffort uint64, + owner flow.Address, + typeIdentifier string, + uuid uint64, + publicPath string, +) flow.Event { + t.Helper() + + var publicPathValue cadence.Value + if publicPath != "" { + path := cadence.MustNewPath(common.PathDomainPublic, publicPath) + publicPathValue = cadence.NewOptional(path) + } else { + publicPathValue = cadence.NewOptional(nil) + } + + location := schedulerEventLocation(sc) + eventCadenceType := cadence.NewEventType( + location, + "Executed", + []cadence.Field{ + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "priority", Type: cadence.UInt8Type}, + {Identifier: "executionEffort", Type: cadence.UInt64Type}, + {Identifier: "transactionHandlerOwner", Type: cadence.AddressType}, + {Identifier: "transactionHandlerTypeIdentifier", Type: cadence.StringType}, + {Identifier: "transactionHandlerUUID", Type: cadence.UInt64Type}, + {Identifier: "transactionHandlerPublicPath", Type: cadence.NewOptionalType(cadence.PublicPathType)}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.UInt64(id), + cadence.UInt8(priority), + cadence.UInt64(executionEffort), + cadence.NewAddress(owner), + cadence.String(typeIdentifier), + cadence.UInt64(uuid), + publicPathValue, + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: schedulerEventType(sc, "Executed"), + TransactionIndex: 0, + EventIndex: 2, + Payload: payload, + } +} + +// createCanceledEvent builds a CCF-encoded Canceled event. +func createCanceledEvent( + t *testing.T, + sc *systemcontracts.SystemContracts, + id uint64, + priority uint8, + feesReturned uint64, + feesDeducted uint64, + owner flow.Address, + typeIdentifier string, +) flow.Event { + t.Helper() + + location := schedulerEventLocation(sc) + eventCadenceType := cadence.NewEventType( + location, + "Canceled", + []cadence.Field{ + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "priority", Type: cadence.UInt8Type}, + {Identifier: "feesReturned", Type: cadence.UFix64Type}, + {Identifier: "feesDeducted", Type: cadence.UFix64Type}, + {Identifier: "transactionHandlerOwner", Type: cadence.AddressType}, + {Identifier: "transactionHandlerTypeIdentifier", Type: cadence.StringType}, + }, + nil, + ) + + event := cadence.NewEvent([]cadence.Value{ + cadence.UInt64(id), + cadence.UInt8(priority), + cadence.UFix64(feesReturned), + cadence.UFix64(feesDeducted), + cadence.NewAddress(owner), + cadence.String(typeIdentifier), + }).WithType(eventCadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + return flow.Event{ + Type: schedulerEventType(sc, "Canceled"), + TransactionIndex: 0, + EventIndex: 0, + Payload: payload, + } +} diff --git a/module/state_synchronization/indexer/extended/test_helpers_test.go b/module/state_synchronization/indexer/extended/test_helpers_test.go new file mode 100644 index 00000000000..a15b9272bf9 --- /dev/null +++ b/module/state_synchronization/indexer/extended/test_helpers_test.go @@ -0,0 +1,105 @@ +package extended + +import ( + "testing" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/common" + jsoncdc "github.com/onflow/cadence/encoding/json" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/flow" +) + +// MakeTransactionDataComposite creates a cadence Struct value representing a +// FlowTransactionScheduler.TransactionData with the given fields. sc is used to +// derive the correct contract address location required for JSON-CDC encoding. +func MakeTransactionDataComposite( + sc *systemcontracts.SystemContracts, + id uint64, + priority uint8, + scheduledTimestamp uint64, + executionEffort uint64, + fees uint64, + owner flow.Address, + typeIdentifier string, +) cadence.Composite { + addr := common.Address(sc.FlowTransactionScheduler.Address) + loc := common.NewAddressLocation(nil, addr, sc.FlowTransactionScheduler.Name) + + priorityEnumType := cadence.NewEnumType( + loc, + "Priority", + cadence.UInt8Type, + []cadence.Field{{Identifier: "rawValue", Type: cadence.UInt8Type}}, + nil, + ) + priorityEnum := cadence.NewEnum([]cadence.Value{cadence.UInt8(priority)}).WithType(priorityEnumType) + + typ := cadence.NewStructType( + loc, + "TransactionData", + []cadence.Field{ + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "priority", Type: priorityEnumType}, + {Identifier: "scheduledTimestamp", Type: cadence.UFix64Type}, + {Identifier: "executionEffort", Type: cadence.UInt64Type}, + {Identifier: "fees", Type: cadence.UFix64Type}, + {Identifier: "handlerAddress", Type: cadence.AddressType}, + {Identifier: "handlerTypeIdentifier", Type: cadence.StringType}, + }, + nil, + ) + return cadence.NewStruct([]cadence.Value{ + cadence.UInt64(id), + priorityEnum, + cadence.UFix64(scheduledTimestamp), + cadence.UInt64(executionEffort), + cadence.UFix64(fees), + cadence.NewAddress(owner), + cadence.String(typeIdentifier), + }).WithType(typ) +} + +// MakeJITScriptResponse encodes a slice of TransactionData composites as a JSON-CDC array +// of optionals, matching the [FlowTransactionScheduler.TransactionData?] return type of the +// getTransactionData script. +func MakeJITScriptResponse(t *testing.T, composites ...cadence.Composite) []byte { + t.Helper() + values := make([]cadence.Value, len(composites)) + for i, c := range composites { + values[i] = cadence.NewOptional(c) + } + encoded, err := jsoncdc.Encode(cadence.NewArray(values)) + require.NoError(t, err) + return encoded +} + +// MakeJITScriptResponseWithNils encodes a mix of TransactionData composites and nil optionals +// as a JSON-CDC array of optionals. nils[i] == true means that slot is a nil optional. +func MakeJITScriptResponseWithNils(t *testing.T, composites []cadence.Composite, nils []bool) []byte { + t.Helper() + require.Equal(t, len(composites), len(nils), "composites and nils must have the same length") + values := make([]cadence.Value, len(composites)) + for i, c := range composites { + if nils[i] { + values[i] = cadence.NewOptional(nil) + } else { + values[i] = cadence.NewOptional(c) + } + } + encoded, err := jsoncdc.Encode(cadence.NewArray(values)) + require.NoError(t, err) + return encoded +} + +// encodeUInt64Args returns a slice of JSON-CDC encoded UInt64 values, one per id. +// This mirrors the per-ID encoding used by buildArgs when constructing the +// arguments slice for ExecuteAtBlockHeight. +func encodeUInt64Args(t *testing.T, ids ...uint64) [][]byte { + t.Helper() + args, err := EncodeGetTransactionDataArg(ids) + require.NoError(t, err) + return [][]byte{args} +} diff --git a/module/state_synchronization/indexer/extended/transfers/ft_group.go b/module/state_synchronization/indexer/extended/transfers/ft_group.go new file mode 100644 index 00000000000..c11cf055409 --- /dev/null +++ b/module/state_synchronization/indexer/extended/transfers/ft_group.go @@ -0,0 +1,192 @@ +package transfers + +import ( + "fmt" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" +) + +// ftDecodedWithdrawal wraps a decoded FT withdrawal event with its source [flow.Event] metadata. +type ftDecodedWithdrawal struct { + source flow.Event + decoded events.FTWithdrawnEvent + ancestorEvents []flow.Event // events from removed parent withdrawals in the event chain +} + +// ftDecodedDeposit wraps a decoded FT deposit event with its source [flow.Event] metadata. +type ftDecodedDeposit struct { + source flow.Event + decoded events.FTDepositedEvent +} + +// ftTxEventGroup holds decoded withdrawal and deposit events for a single transaction. +type ftTxEventGroup struct { + withdrawals []*ftDecodedWithdrawal + flowFees *events.FlowFeesEvent + + withdrawalByUUID map[uint64]int + matchedDeposits map[uint64]struct{} + + pairedResults []ftPairedResult + + flowFeesReceivers map[flow.Address]bool +} + +func newFTTxEventGroup(flowFeesReceivers map[flow.Address]bool) *ftTxEventGroup { + return &ftTxEventGroup{ + withdrawalByUUID: make(map[uint64]int), + matchedDeposits: make(map[uint64]struct{}), + flowFeesReceivers: flowFeesReceivers, + } +} + +// addWithdrawal adds a withdrawal event to the event group. +// +// No error returns are expected during normal operation. +func (g *ftTxEventGroup) addWithdrawal(event flow.Event, decoded *events.FTWithdrawnEvent) error { + w := &ftDecodedWithdrawal{source: event, decoded: *decoded} + + // 1. build a mapping of withdrawn vault UUID to the index in the `withdrawals` slice. + // this is used to identify the parent when there is a chain of withdrawals. + if _, exists := g.withdrawalByUUID[decoded.WithdrawnUUID]; exists { + return fmt.Errorf("duplicate withdrawal resource UUID %d in transaction %d", decoded.WithdrawnUUID, event.TransactionIndex) + } + g.withdrawals = append(g.withdrawals, w) + g.withdrawalByUUID[decoded.WithdrawnUUID] = len(g.withdrawals) - 1 + + // 2. check if withdrawal is from a stored vault or another withdrawn vault + parentIdx, ok := g.withdrawalByUUID[w.decoded.FromUUID] + if !ok { + return nil // withdrew from stored vault (or mint) + } + parent := g.withdrawals[parentIdx] + + // 3. build event ancestor chain: parent's ancestors + parent itself. + chain := make([]flow.Event, len(parent.ancestorEvents)+1) + copy(chain, parent.ancestorEvents) + chain[len(chain)-1] = parent.source + w.ancestorEvents = chain + + // 4. propagate the source address from parent to track sender + if w.decoded.From == flow.EmptyAddress && parent.decoded.From != flow.EmptyAddress { + w.decoded.From = parent.decoded.From + } + + // 5. Subtract child withdrawal amount from parent. this ensures the final amounts used in + // the deposit/withdraw pairing are correct. + if w.decoded.Amount <= parent.decoded.Amount { + parent.decoded.Amount -= w.decoded.Amount + } else { + return fmt.Errorf("child withdrawal amount %s (eventIdx=%d) is greater than the remaining parent withdrawal amount %s (eventIdx=%d) in transaction %d", + w.decoded.Amount.String(), w.source.EventIndex, parent.decoded.Amount.String(), parent.source.EventIndex, event.TransactionIndex) + } + + return nil +} + +// addDeposit adds a deposit event to the event group. +// +// No error returns are expected during normal operation. +func (g *ftTxEventGroup) addDeposit(event flow.Event, decoded *events.FTDepositedEvent) error { + d := &ftDecodedDeposit{source: event, decoded: *decoded} + + uuid := decoded.DepositedUUID + + // If the destination vault (toUUID) is a tracked withdrawal vault, the minted tokens are flowing + // into it and must be reflected in its tracked amount. + if destIdx, destOk := g.withdrawalByUUID[decoded.ToUUID]; destOk { + g.withdrawals[destIdx].decoded.Amount += decoded.Amount + } + + // 1. check if the deposit is a vault withdrawn in this transaction. + wIdx, ok := g.withdrawalByUUID[uuid] + if !ok { + // No corresponding withdrawal - treat as mint. + g.pairedResults = append(g.pairedResults, ftPairedResult{ + sourceEvents: mergeEvents(nil, d), + deposit: &d.decoded, + }) + return nil + } + w := g.withdrawals[wIdx] + + // 2. make sure the deposit and withdrawal match. + // if not, then there is likely a bug in the event parsing logic. + if w.decoded.Amount != d.decoded.Amount { + return fmt.Errorf("withdrawal amount %s (eventIdx=%d) is not equal to the deposit amount %s (eventIdx=%d) in transaction %d", + d.decoded.Amount.String(), d.source.EventIndex, w.decoded.Amount.String(), w.source.EventIndex, event.TransactionIndex) + } + + if w.decoded.Type != d.decoded.Type { + return fmt.Errorf("withdrawal token type %s (eventIdx=%d) is not equal to the deposit token type %s (eventIdx=%d) in transaction %d", + w.decoded.Type, w.source.EventIndex, d.decoded.Type, d.source.EventIndex, event.TransactionIndex) + } + + // 3. pair the deposit with the withdrawal. + g.matchedDeposits[uuid] = struct{}{} + g.pairedResults = append(g.pairedResults, ftPairedResult{ + sourceEvents: mergeEvents(w, d), + withdrawal: &w.decoded, + deposit: &d.decoded, + }) + return nil +} + +// addFlowFees adds a flow fees event to the event group. +// +// No error returns are expected during normal operation. +func (g *ftTxEventGroup) addFlowFees(decoded *events.FlowFeesEvent) error { + g.flowFees = decoded + + // a flow fees deposit always comes after the withdrawal and deposit events, so it will always have a pair. + // walk backwards to find the first pair that matches the flow fees deposit, since the flow fees + // event is always immediately following the withdrawal and deposit events. + // this ensures that if there was another transfer to the flow fees address for the same amount + // in the same transaction, it will be treated as a regular transfer. + for i := len(g.pairedResults) - 1; i >= 0; i-- { + pair := g.pairedResults[i] + if pair.deposit == nil { + continue + } + if g.flowFeesReceivers[pair.deposit.To] && pair.deposit.Amount == decoded.Amount { + g.pairedResults[i].isFlowFees = true + return nil + } + } + + // if we didn't find the fees transfer pair, then there is a bug in the event parsing logic. + return fmt.Errorf("flow fees deposit not found for amount %s", decoded.Amount.String()) +} + +// ResolvePairs returns all paired results. +func (g *ftTxEventGroup) ResolvePairs() []ftPairedResult { + // find all unmatched withdrawals + for uuid, wIdx := range g.withdrawalByUUID { + if _, ok := g.matchedDeposits[uuid]; ok { + continue + } + if g.withdrawals[wIdx].decoded.Amount == 0 { + // ignore fully consumed withdrawals (full amount was withdrawn into a child vault) + continue + } + // Unmatched withdrawal -- treat as burn. + g.pairedResults = append(g.pairedResults, ftPairedResult{ + sourceEvents: mergeEvents(g.withdrawals[wIdx], nil), + withdrawal: &g.withdrawals[wIdx].decoded, + }) + } + return g.pairedResults +} + +func mergeEvents(w *ftDecodedWithdrawal, d *ftDecodedDeposit) []flow.Event { + var events []flow.Event + if w != nil { + events = append(events, w.ancestorEvents...) + events = append(events, w.source) + } + if d != nil { + events = append(events, d.source) + } + return events +} diff --git a/module/state_synchronization/indexer/extended/transfers/ft_parser.go b/module/state_synchronization/indexer/extended/transfers/ft_parser.go new file mode 100644 index 00000000000..0088291a987 --- /dev/null +++ b/module/state_synchronization/indexer/extended/transfers/ft_parser.go @@ -0,0 +1,225 @@ +package transfers + +import ( + "fmt" + "math/big" + "strconv" + "strings" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" +) + +const ( + ftWithdrawnFormat = "A.%s.FungibleToken.Withdrawn" + ftDepositedFormat = "A.%s.FungibleToken.Deposited" + flowFeesFormat = "A.%s.FlowFees.FeesDeducted" +) + +// ftPairedResult holds a matched withdrawal/deposit pair, or an unpaired event. +// For paired events, both withdrawal and deposit are set. +// For mints (deposit-only), withdrawal is nil. +// For burns (withdrawal-only), deposit is nil. +type ftPairedResult struct { + sourceEvents []flow.Event // the flow.Event(s) that produced this result + withdrawal *events.FTWithdrawnEvent // nil for deposit-only (mint) + deposit *events.FTDepositedEvent // nil for withdrawal-only (burn) + isFlowFees bool // true if the result is a flow fees deposit +} + +// FTParser decodes FungibleToken transfer events from CCF-encoded payloads and converts them +// into the model types used by the storage index. +// +// All methods are safe for concurrent access. +type FTParser struct { + withdrawnEventType flow.EventType + depositedEventType flow.EventType + flowFeesEventType flow.EventType + flowFeesReceivers map[flow.Address]bool + omitFlowFees bool +} + +// NewFTParser creates a new fungible token transfer event parser. +func NewFTParser(chainID flow.ChainID, omitFlowFees bool) *FTParser { + sc := systemcontracts.SystemContractsForChain(chainID) + receivers := make(map[flow.Address]bool, len(sc.FlowFeesReceivers)) + for _, receiver := range sc.FlowFeesReceivers { + receivers[receiver.Address] = true + } + return &FTParser{ + withdrawnEventType: flow.EventType(fmt.Sprintf(ftWithdrawnFormat, sc.FungibleToken.Address)), + depositedEventType: flow.EventType(fmt.Sprintf(ftDepositedFormat, sc.FungibleToken.Address)), + flowFeesEventType: flow.EventType(fmt.Sprintf(flowFeesFormat, sc.FlowFees.Address)), + flowFeesReceivers: receivers, + omitFlowFees: omitFlowFees, + } +} + +// Parse extracts fungible token transfer events from the given events, pairs +// Withdrawn/Deposited events within each transaction, and returns fully-formed +// [access.FungibleTokenTransfer] objects. +// +// Events are paired by matching the `withdrawnUUID` field from Withdrawn events with the +// `depositedUUID` field from Deposited events within the same transaction. A single +// withdrawal may pair with multiple deposits (e.g. when a vault is split and deposited +// into several recipients). Each paired result uses the Deposited event's +// [flow.Event.EventIndex] and amount. Unpaired events produce records with a zero address +// for the missing side. +// +// No error returns are expected during normal operation. +func (p *FTParser) Parse(evts []flow.Event, blockHeight uint64) ([]access.FungibleTokenTransfer, error) { + groups, err := p.filterAndDecodeFT(evts) + if err != nil { + return nil, err + } + + paired := make([]ftPairedResult, 0) + for _, group := range groups { + paired = append(paired, group.ResolvePairs()...) + } + + return p.buildTransfers(paired, blockHeight) +} + +// filterAndDecodeFT filters events by type, decodes CCF payloads into typed domain events, +// and groups the results by transaction index. +// +// No error returns are expected during normal operation. +func (p *FTParser) filterAndDecodeFT(evts []flow.Event) (map[uint32]*ftTxEventGroup, error) { + txEventGroups := make(map[uint32]*ftTxEventGroup) + + ensureGroup := func(txIndex uint32) *ftTxEventGroup { + g, ok := txEventGroups[txIndex] + if !ok { + g = newFTTxEventGroup(p.flowFeesReceivers) + txEventGroups[txIndex] = g + } + return g + } + + for _, event := range evts { + switch event.Type { + case p.withdrawnEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + decoded, err := events.DecodeFTWithdrawn(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode withdrawn event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + g := ensureGroup(event.TransactionIndex) + err = g.addWithdrawal(event, decoded) + if err != nil { + return nil, fmt.Errorf("failed to add withdrawal event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + + case p.depositedEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + decoded, err := events.DecodeFTDeposited(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode deposited event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + g := ensureGroup(event.TransactionIndex) + err = g.addDeposit(event, decoded) + if err != nil { + return nil, fmt.Errorf("failed to add deposit event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + + case p.flowFeesEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + decoded, err := events.DecodeFlowFees(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode flow fees event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + g := ensureGroup(event.TransactionIndex) + err = g.addFlowFees(decoded) + if err != nil { + return nil, fmt.Errorf("failed to add flow fees event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + } + } + + return txEventGroups, nil +} + +// buildTransfers converts paired results into [access.FungibleTokenTransfer] model objects. +// +// No error returns are expected during normal operation. +func (p *FTParser) buildTransfers(paired []ftPairedResult, blockHeight uint64) ([]access.FungibleTokenTransfer, error) { + transfers := make([]access.FungibleTokenTransfer, 0, len(paired)) + for i, pair := range paired { + if len(pair.sourceEvents) == 0 { + return nil, fmt.Errorf("paired result has no source events") + } + if pair.withdrawal == nil && pair.deposit == nil { + return nil, fmt.Errorf("paired result has neither withdrawal nor deposit (events=%v)", pair.sourceEvents) + } + if pair.isFlowFees && p.omitFlowFees { + continue + } + + // make sure all events have the same core details. + txID := pair.sourceEvents[0].TransactionID + txIndex := pair.sourceEvents[0].TransactionIndex + eventIndices := make([]uint32, len(pair.sourceEvents)) + eventIndicesStr := make([]string, len(pair.sourceEvents)) + for i, event := range pair.sourceEvents { + eventIndices[i] = event.EventIndex + eventIndicesStr[i] = strconv.Itoa(int(event.EventIndex)) + + if txID != event.TransactionID { + return nil, fmt.Errorf("transaction ID mismatch for source event: %s != %s (tx=%d, evtIdx=%s)", + txID, event.TransactionID, txIndex, strings.Join(eventIndicesStr, ",")) + } + if txIndex != event.TransactionIndex { + return nil, fmt.Errorf("transaction index mismatch for source event: %d != %d (tx=%d, evtIdx=%s)", + txIndex, event.TransactionIndex, txIndex, strings.Join(eventIndicesStr, ",")) + } + } + + // all transfers must have at least one event! + if len(eventIndices) == 0 { + return nil, fmt.Errorf("no event indices for source events (tx=%s, pairIdx=%d)", txID, i) + } + + transfer := access.FungibleTokenTransfer{ + BlockHeight: blockHeight, + TransactionID: txID, + TransactionIndex: txIndex, + EventIndices: eventIndices, + } + + if pair.withdrawal != nil { + transfer.TokenType = pair.withdrawal.Type + transfer.Amount = new(big.Int).SetUint64(uint64(pair.withdrawal.Amount)) + transfer.SourceAddress = pair.withdrawal.From + } + + // Deposit amount takes precedence since a single withdrawal may be split across multiple deposits + if pair.deposit != nil { + transfer.TokenType = pair.deposit.Type + transfer.Amount = new(big.Int).SetUint64(uint64(pair.deposit.Amount)) + transfer.RecipientAddress = pair.deposit.To + } + + // sanity check: token type and amount of are required. + if transfer.TokenType == "" { + return nil, fmt.Errorf("token type is empty for transfer (tx=%s, evtIdxs=%s)", txID, strings.Join(eventIndicesStr, ",")) + } + if transfer.Amount == nil { + return nil, fmt.Errorf("amount is empty for transfer (tx=%s, evtIdxs=%s)", txID, strings.Join(eventIndicesStr, ",")) + } + + transfers = append(transfers, transfer) + } + return transfers, nil +} diff --git a/module/state_synchronization/indexer/extended/transfers/ft_parser_test.go b/module/state_synchronization/indexer/extended/transfers/ft_parser_test.go new file mode 100644 index 00000000000..13510820c1d --- /dev/null +++ b/module/state_synchronization/indexer/extended/transfers/ft_parser_test.go @@ -0,0 +1,714 @@ +package transfers + +import ( + "testing" + + "github.com/onflow/cadence" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/transfers/testutil" + "github.com/onflow/flow-go/utils/unittest" +) + +const testBlockHeight = uint64(100) + +// ========================================================================== +// FT Transfer Tests +// ========================================================================== + +func TestParseFTTransfers_EmptyEvents(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + + t.Run("nil input", func(t *testing.T) { + transfers, err := parser.Parse(nil, testBlockHeight) + require.NoError(t, err) + assert.Empty(t, transfers) + }) + + t.Run("empty slice", func(t *testing.T) { + transfers, err := parser.Parse([]flow.Event{}, testBlockHeight) + require.NoError(t, err) + assert.Empty(t, transfers) + }) +} + +func TestParseFTTransfers_PairedTransfer(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + uuid := uint64(42) + amount := cadence.UFix64(50_00000000) + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, 1, uuid, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 1, 1, uuid, amount), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, sender, recipient, amount, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_AmountMismatch verifies that a deposit paired by UUID with a withdrawal +// returns an error when their amounts don't match. Direct 1:N pairing by UUID is not supported; +// vault splits across multiple recipients use withdrawal chains instead (see +// TestParseFTTransfers_WithdrawalChainResolution). +func TestParseFTTransfers_AmountMismatch(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + uuid := uint64(42) + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, 1, uuid, cadence.UFix64(100_00000000)), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 1, 1, uuid, cadence.UFix64(40_00000000)), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.Error(t, err) + require.Empty(t, transfers) + assert.Contains(t, err.Error(), "not equal to the deposit amount") +} + +// TestParseFTTransfers_WithdrawalChainResolution verifies that when a vault is +// withdrawn and then sub-withdrawn into intermediate vaults (which have from=nil), +// the intermediate withdrawals inherit the source address from the original. +// +// Scenario: +// +// Withdraw 100 from Alice's stored vault (UUID=1) → temp vault UUID=50 (from=Alice) +// Withdraw 40 from temp vault 50 → temp vault UUID=51 (from=nil, fromUUID=50) +// Withdraw 25 from temp vault 50 → temp vault UUID=52 (from=nil, fromUUID=50) +// Deposit temp vault 51 into Bob +// Deposit temp vault 52 into Carol +// Deposit temp vault 50 (remaining 35) into Dave +func TestParseFTTransfers_WithdrawalChainResolution(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + carol := unittest.RandomAddressFixture() + dave := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + events := []flow.Event{ + // Original withdrawal from Alice's stored vault (UUID=1) → temp vault UUID=50 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 0, 1, 50, cadence.UFix64(100_00000000)), + // Sub-withdraw from temp vault 50 → temp vault UUID=51 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 1, 50, 51, cadence.UFix64(40_00000000)), + // Sub-withdraw from temp vault 50 → temp vault UUID=52 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 2, 50, 52, cadence.UFix64(25_00000000)), + // Deposits + testutil.MakeFTDepositedEvent(t, flow.Testnet, &bob, txID, 0, 3, 1, 51, cadence.UFix64(40_00000000)), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &carol, txID, 0, 4, 1, 52, cadence.UFix64(25_00000000)), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &dave, txID, 0, 5, 1, 50, cadence.UFix64(35_00000000)), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, bob, cadence.UFix64(40_00000000), 0, 1, 3), + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, carol, cadence.UFix64(25_00000000), 0, 2, 4), + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, dave, cadence.UFix64(35_00000000), 0, 5), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_DeepWithdrawalChain verifies chain resolution works for +// chains deeper than one level (A → B → C). +func TestParseFTTransfers_DeepWithdrawalChain(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + alice := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + events := []flow.Event{ + // Alice's vault (UUID=1) → temp vault 50 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 0, 1, 50, cadence.UFix64(100_00000000)), + // temp vault 50 → temp vault 51 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 1, 50, 51, cadence.UFix64(60_00000000)), + // temp vault 51 → temp vault 52 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 2, 51, 52, cadence.UFix64(30_00000000)), + // Deposit the deepest vault + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 3, 1, 52, cadence.UFix64(30_00000000)), + } + + expected := []access.FungibleTokenTransfer{ + // Paired: full chain from vault 1→50→51→52 + deposit + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, recipient, cadence.UFix64(30_00000000), 0, 1, 2, 3), + // Burn: vault 50 remainder (100 - 60 sub-withdrawn to vault 51) + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, flow.Address{}, cadence.UFix64(40_00000000), 0), + // Burn: vault 51 remainder (60 - 30 sub-withdrawn to vault 52) + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, flow.Address{}, cadence.UFix64(30_00000000), 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_FullyConsumedParent verifies behavior when a temp vault's +// entire content is re-withdrawn into a child vault. The parent withdrawal is fully +// consumed and produces no burn record, since its remaining amount is 0. +// +// Scenario: +// +// Withdraw 100 from Alice's stored vault (UUID=1) → temp vault UUID=50 (from=Alice) +// Withdraw 100 from temp vault 50 → temp vault UUID=51 (from=nil, fromUUID=50) [full amount] +// Deposit temp vault 51 into Bob +func TestParseFTTransfers_FullyConsumedParent(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 0, 1, 50, cadence.UFix64(100_00000000)), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 1, 50, 51, cadence.UFix64(100_00000000)), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &bob, txID, 0, 2, 1, 51, cadence.UFix64(100_00000000)), + } + + expected := []access.FungibleTokenTransfer{ + // Paired: Alice → Bob via chain 1→50→51; parent vault 50 fully consumed, no burn record. + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, bob, cadence.UFix64(100_00000000), 0, 1, 2), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_FullyConsumedByMultipleChildren verifies behavior when +// multiple children collectively consume a parent's full amount. The parent +// produces no burn record since its remaining amount is 0. +// +// Scenario: +// +// Withdraw 100 from Alice's stored vault → temp vault UUID=50 (from=Alice) +// Withdraw 60 from temp vault 50 → UUID=51 (from=nil) +// Withdraw 40 from temp vault 50 → UUID=52 (from=nil) +// Deposit 51 into Bob, Deposit 52 into Carol +func TestParseFTTransfers_FullyConsumedByMultipleChildren(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + carol := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 0, 1, 50, cadence.UFix64(100_00000000)), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 1, 50, 51, cadence.UFix64(60_00000000)), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 2, 50, 52, cadence.UFix64(40_00000000)), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &bob, txID, 0, 3, 1, 51, cadence.UFix64(60_00000000)), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &carol, txID, 0, 4, 1, 52, cadence.UFix64(40_00000000)), + } + + // Parent vault 50 is fully consumed by children 51 and 52, so no burn record is produced. + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, bob, cadence.UFix64(60_00000000), 0, 1, 3), + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, carol, cadence.UFix64(40_00000000), 0, 2, 4), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_UnpairedDeposit verifies that an unpaired deposit is treated as a mint. +func TestParseFTTransfers_UnpairedDeposit(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + amount := cadence.UFix64(100_00000000) + events := []flow.Event{ + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 3, 1, 99, amount), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, flow.Address{}, recipient, amount, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_UnpairedWithdrawal verifies that an unpaired withdrawal is treated as a burn. +func TestParseFTTransfers_UnpairedWithdrawal(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + sender := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + amount := cadence.UFix64(25_00000000) + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 5, 1, 77, amount), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, sender, flow.Address{}, amount, 5), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseFTTransfers_NilOptionalAddresses(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + txID := unittest.IdentifierFixture() + + uuid := uint64(10) + amount := cadence.UFix64(1_00000000) + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 0, 1, uuid, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, nil, txID, 0, 1, 1, uuid, amount), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, flow.Address{}, flow.Address{}, amount, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseFTTransfers_MultiplePairsInSameTx(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + txID := unittest.IdentifierFixture() + + sender1 := unittest.RandomAddressFixture() + recipient1 := unittest.RandomAddressFixture() + sender2 := unittest.RandomAddressFixture() + recipient2 := unittest.RandomAddressFixture() + + amount1 := cadence.UFix64(10_00000000) + amount2 := cadence.UFix64(20_00000000) + + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender1, txID, 0, 0, 1, 10, amount1), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient1, txID, 0, 1, 1, 10, amount1), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender2, txID, 0, 2, 1, 20, amount2), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient2, txID, 0, 3, 1, 20, amount2), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, sender1, recipient1, amount1, 0, 1), + testutil.MakeFTTransfer(testBlockHeight, txID, 0, sender2, recipient2, amount2, 2, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseFTTransfers_MixedPairedAndUnpaired(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + txID := unittest.IdentifierFixture() + + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + mintRecipient := unittest.RandomAddressFixture() + burnSender := unittest.RandomAddressFixture() + + amount := cadence.UFix64(10_00000000) + + events := []flow.Event{ + // Paired transfer + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, 1, 100, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 1, 1, 100, amount), + // Unpaired deposit (mint) + testutil.MakeFTDepositedEvent(t, flow.Testnet, &mintRecipient, txID, 0, 2, 1, 200, amount), + // Unpaired withdrawal (burn) + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &burnSender, txID, 0, 3, 1, 300, amount), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, sender, recipient, amount, 0, 1), + testutil.MakeFTTransfer(testBlockHeight, txID, 0, flow.Address{}, mintRecipient, amount, 2), + testutil.MakeFTTransfer(testBlockHeight, txID, 0, burnSender, flow.Address{}, amount, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_EventsAcrossTransactionsDoNotPair verifies that events +// with the same UUID but in different transactions are NOT paired together. +func TestParseFTTransfers_EventsAcrossTransactionsDoNotPair(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + sharedUUID := uint64(42) + amount := cadence.UFix64(10_00000000) + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID1, 0, 0, 1, sharedUUID, amount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient, txID2, 1, 0, 1, sharedUUID, amount), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID1, 0, sender, flow.Address{}, amount, 0), + testutil.MakeFTTransfer(testBlockHeight, txID2, 1, flow.Address{}, recipient, amount, 0), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_DepositBeforeWithdrawal verifies that when a deposit is processed +// before a withdrawal with the same UUID, they are NOT paired. Pairing is order-dependent: +// deposits can only match already-seen withdrawals. The deposit is treated as a mint and +// the withdrawal as a burn. +func TestParseFTTransfers_DepositBeforeWithdrawal(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + uuid := uint64(55) + amount := cadence.UFix64(30_00000000) + + // Deposit appears before withdrawal in the event list. + events := []flow.Event{ + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 0, 1, uuid, amount), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 1, 1, uuid, amount), + } + + // Deposit without matching withdrawal = mint; withdrawal without matching deposit = burn. + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, flow.Address{}, recipient, amount, 0), + testutil.MakeFTTransfer(testBlockHeight, txID, 0, sender, flow.Address{}, amount, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseFTTransfers_SkipsIrrelevantEvents(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + + events := []flow.Event{ + { + Type: "A.f233dcee88fe0abe.FlowToken.TokensMinted", + TransactionID: unittest.IdentifierFixture(), + TransactionIndex: 0, + EventIndex: 0, + Payload: []byte("irrelevant"), + }, + { + Type: "A.1234567890abcdef.SomeContract.SomeEvent", + TransactionID: unittest.IdentifierFixture(), + TransactionIndex: 0, + EventIndex: 1, + Payload: []byte("also irrelevant"), + }, + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.Empty(t, transfers) +} + +func TestParseFTTransfers_MalformedPayload(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + + t.Run("malformed withdrawn event", func(t *testing.T) { + events := []flow.Event{ + { + Type: testutil.FTWithdrawnEventType(flow.Testnet), + Payload: []byte("not valid ccf"), + }, + } + transfers, err := parser.Parse(events, testBlockHeight) + require.Error(t, err) + assert.Nil(t, transfers) + }) + + t.Run("malformed deposited event", func(t *testing.T) { + events := []flow.Event{ + { + Type: testutil.FTDepositedEventType(flow.Testnet), + Payload: []byte("not valid ccf"), + }, + } + transfers, err := parser.Parse(events, testBlockHeight) + require.Error(t, err) + assert.Nil(t, transfers) + }) +} + +// TestParseFTTransfers_DuplicateWithdrawalUUID verifies that two withdrawals with the same +// withdrawnUUID in the same transaction produce an error. +func TestParseFTTransfers_DuplicateWithdrawalUUID(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + sender := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, 1, 50, cadence.UFix64(100_00000000)), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 1, 1, 50, cadence.UFix64(50_00000000)), + } + + _, err := parser.Parse(events, testBlockHeight) + require.Error(t, err) + assert.Contains(t, err.Error(), "duplicate withdrawal resource UUID") +} + +// TestParseFTTransfers_MintDepositedIntoWithdrawalVault verifies that when a minted vault +// is deposited into an intermediate vault that was itself created by a withdrawal, the +// intermediate vault's tracked amount is updated to include the minted tokens. This allows +// subsequent child withdrawals from the intermediate vault to exceed its original withdrawal +// amount without error, as long as they don't exceed the updated tracked amount. +// +// This models the Flow staking rewards distribution pattern, where a small fee withdrawal +// creates an intermediate vault, a large mint is deposited into it, and rewards are then +// distributed to many stakers via child withdrawals from the same vault. +// +// Scenario: +// +// Withdraw 40 from Alice's stored vault → intermediate vault UUID=50 (tracked amount=40) +// Mint 100 tokens → new vault UUID=51 (no prior withdrawal) +// Deposit vault 51 (mint, depositedUUID=51) into vault 50 (toUUID=50) → vault 50 tracked amount=140 +// Withdraw 80 from vault 50 → vault UUID=52; 80 ≤ 140, vault 50 remaining=60 +// Deposit vault 52 into Bob +// Deposit vault 50 (remaining 60) into Carol +func TestParseFTTransfers_MintDepositedIntoWithdrawalVault(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + carol := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + events := []flow.Event{ + // Withdraw 40 from Alice's stored vault (fromUUID=1) → temp vault UUID=50 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 0, 1, 50, cadence.UFix64(40_00000000)), + // Mint 100 tokens (vault UUID=51) and deposit into vault 50 (toUUID=50). + // depositedUUID=51 has no prior withdrawal → treated as mint, but toUUID=50 + // is a tracked withdrawal vault so vault 50's tracked amount increases to 140. + testutil.MakeFTDepositedEvent(t, flow.Testnet, nil, txID, 0, 1, 50, 51, cadence.UFix64(100_00000000)), + // Withdraw 80 from vault 50 (fromUUID=50) → vault UUID=52; 80 ≤ 140 ✓, vault 50 remaining=60 + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 2, 50, 52, cadence.UFix64(80_00000000)), + // Deposit vault 52 into Bob + testutil.MakeFTDepositedEvent(t, flow.Testnet, &bob, txID, 0, 3, 1, 52, cadence.UFix64(80_00000000)), + // Deposit vault 50 (remaining 60) into Carol + testutil.MakeFTDepositedEvent(t, flow.Testnet, &carol, txID, 0, 4, 1, 50, cadence.UFix64(60_00000000)), + } + + expected := []access.FungibleTokenTransfer{ + // Mint: vault 51 deposited into vault 50 (no sender, no recipient address for temp vault) + testutil.MakeFTTransfer(testBlockHeight, txID, 0, flow.Address{}, flow.Address{}, cadence.UFix64(100_00000000), 1), + // Alice → Bob via vault 50→52 chain + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, bob, cadence.UFix64(80_00000000), 0, 2, 3), + // Alice → Carol: vault 50 remainder + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, carol, cadence.UFix64(60_00000000), 0, 4), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_ChildExceedsParentAmount verifies that a child withdrawal with an +// amount larger than the parent's remaining balance produces an error. +func TestParseFTTransfers_ChildExceedsParentAmount(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + sender := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, 1, 50, cadence.UFix64(50_00000000)), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 1, 50, 51, cadence.UFix64(60_00000000)), + } + + _, err := parser.Parse(events, testBlockHeight) + require.Error(t, err) + assert.Contains(t, err.Error(), "greater than the remaining parent") +} + +// TestParseFTTransfers_MultipleTransactionsInBlock verifies that events from +// different transactions in the same block are grouped and paired independently. +func TestParseFTTransfers_MultipleTransactionsInBlock(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + sender1 := unittest.RandomAddressFixture() + recipient1 := unittest.RandomAddressFixture() + sender2 := unittest.RandomAddressFixture() + recipient2 := unittest.RandomAddressFixture() + + amount1 := cadence.UFix64(10_00000000) + amount2 := cadence.UFix64(20_00000000) + + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender1, txID1, 0, 0, 1, 10, amount1), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient1, txID1, 0, 1, 1, 10, amount1), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &sender2, txID2, 1, 0, 1, 20, amount2), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &recipient2, txID2, 1, 1, 1, 20, amount2), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID1, 0, sender1, recipient1, amount1, 0, 1), + testutil.MakeFTTransfer(testBlockHeight, txID2, 1, sender2, recipient2, amount2, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseFTTransfers_FlowFees verifies that when omitFlowFees=false, a deposit to +// the FlowFees contract address that is paired with a FlowFees.FeesDeducted event is included +// in the parser output as a regular transfer. When omitFlowFees=true, the flow fees transfer is excluded. +func TestParseFTTransfers_FlowFees(t *testing.T) { + payer := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + flowFeesAddress := testutil.FlowFeesAddress(flow.Testnet) + + feeAmount := cadence.UFix64(1_00000000) + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &payer, txID, 0, 2, 1, 50, feeAmount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &flowFeesAddress, txID, 0, 3, 1, 50, feeAmount), + testutil.MakeFlowFeesEvent(t, flow.Testnet, txID, 0, 2, feeAmount), + } + + t.Run("flow fees included", func(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) // omitFlowFees = false + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, payer, flowFeesAddress, feeAmount, 2, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) + }) + + t.Run("flow fees omitted", func(t *testing.T) { + parser := NewFTParser(flow.Testnet, true) // omitFlowFees = true + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.Empty(t, transfers) + }) + + t.Run("flow fees omitted but transfer to flow fees address is included", func(t *testing.T) { + parser := NewFTParser(flow.Testnet, true) // omitFlowFees = true + + // prepend a transfer to the flow fees account in the same amount as the fees deducted. + // this should be treated as a regular transfer, and the correct events should be ignored. + events := append([]flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &payer, txID, 0, 0, 1, 49, feeAmount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &flowFeesAddress, txID, 0, 1, 1, 49, feeAmount), + }, events...) + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, payer, flowFeesAddress, feeAmount, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) + }) +} + +// TestParseFTTransfers_FlowFees_MultipleReceiverAddressesAcrossTxs verifies that fee +// deposits to different flow fee receiver addresses (across different transactions in the +// same block) are each correctly identified as fee transfers. +// +// Testnet has multiple fee receiver addresses. This test exercises two transactions where +// each pays fees to a distinct receiver. When omitFlowFees=true all fee transfers are +// excluded; when omitFlowFees=false all are included. +func TestParseFTTransfers_FlowFees_MultipleReceiverAddressesAcrossTxs(t *testing.T) { + sc := systemcontracts.SystemContractsForChain(flow.Testnet) + require.GreaterOrEqual(t, len(sc.FlowFeesReceivers), 2, "testnet must have at least 2 fee receiver addresses") + + payer1 := unittest.RandomAddressFixture() + payer2 := unittest.RandomAddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + receiver1 := sc.FlowFeesReceivers[0].Address + receiver2 := sc.FlowFeesReceivers[1].Address + + feeAmount1 := cadence.UFix64(1_00000000) + feeAmount2 := cadence.UFix64(2_00000000) + + // TX0 pays fees deposited to receiver1; TX1 pays fees deposited to receiver2. + events := []flow.Event{ + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &payer1, txID1, 0, 0, 1, 50, feeAmount1), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &receiver1, txID1, 0, 1, 1, 50, feeAmount1), + testutil.MakeFlowFeesEvent(t, flow.Testnet, txID1, 0, 2, feeAmount1), + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &payer2, txID2, 1, 0, 1, 60, feeAmount2), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &receiver2, txID2, 1, 1, 1, 60, feeAmount2), + testutil.MakeFlowFeesEvent(t, flow.Testnet, txID2, 1, 2, feeAmount2), + } + + t.Run("flow fees omitted for all receiver addresses", func(t *testing.T) { + parser := NewFTParser(flow.Testnet, true) + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.Empty(t, transfers) + }) + + t.Run("flow fees included for all receiver addresses", func(t *testing.T) { + parser := NewFTParser(flow.Testnet, false) + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID1, 0, payer1, receiver1, feeAmount1, 0, 1), + testutil.MakeFTTransfer(testBlockHeight, txID2, 1, payer2, receiver2, feeAmount2, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) + }) +} + +// TestParseFTTransfers_FlowFees_MixedTransfers verifies that when omitFlowFees=true, the +// flow fees transfer is excluded but regular transfers in the same transaction are preserved. +func TestParseFTTransfers_FlowFees_MixedTransfers(t *testing.T) { + parser := NewFTParser(flow.Testnet, true) + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + flowFeesAddress := testutil.FlowFeesAddress(flow.Testnet) + + transferAmount := cadence.UFix64(50_00000000) + feeAmount := cadence.UFix64(1_00000000) + + events := []flow.Event{ + // Regular transfer: alice → bob (fromUUID=1, withdrawnUUID=10) + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 0, 1, 10, transferAmount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &bob, txID, 0, 1, 1, 10, transferAmount), + // Fee payment: alice → FlowFees contract (fromUUID=1, withdrawnUUID=50) + testutil.MakeFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 2, 1, 50, feeAmount), + testutil.MakeFTDepositedEvent(t, flow.Testnet, &flowFeesAddress, txID, 0, 3, 1, 50, feeAmount), + testutil.MakeFlowFeesEvent(t, flow.Testnet, txID, 0, 4, feeAmount), + } + + expected := []access.FungibleTokenTransfer{ + testutil.MakeFTTransfer(testBlockHeight, txID, 0, alice, bob, transferAmount, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} diff --git a/module/state_synchronization/indexer/extended/transfers/nft_group.go b/module/state_synchronization/indexer/extended/transfers/nft_group.go new file mode 100644 index 00000000000..aac68901a0a --- /dev/null +++ b/module/state_synchronization/indexer/extended/transfers/nft_group.go @@ -0,0 +1,237 @@ +package transfers + +import ( + "fmt" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" +) + +// nftDecodedWithdrawal wraps a decoded NFT withdrawal event with its source [flow.Event] metadata. +type nftDecodedWithdrawal struct { + source flow.Event + decoded events.NFTWithdrawnEvent + ancestorEvents []flow.Event // events from parent withdrawals in the ProviderUUID chain +} + +// nftDecodedDeposit wraps a decoded NFT deposit event with its source [flow.Event] metadata. +type nftDecodedDeposit struct { + source flow.Event + decoded events.NFTDepositedEvent +} + +// nftWithdrawalRun groups consecutive Withdrawn events with the same source address. +// Consecutive same-address withdrawals for a single NFT represent multiple collection layers +// owned by the same account. +type nftWithdrawalRun struct { + address flow.Address + events []*nftDecodedWithdrawal +} + +// nftTxEventGroup holds decoded withdrawal and deposit events for a single transaction. +// +// pendingWithdrawals maps an NFT UUID to the ordered list of withdrawals not yet paired with a +// deposit. After a deposit is matched the entry is removed, so the same UUID may be withdrawn +// again within the same transaction (multi-hop transfers: A → B → C). +type nftTxEventGroup struct { + pendingWithdrawals map[uint64][]*nftDecodedWithdrawal + pairedResults []nftPairedResult +} + +func newNFTTxEventGroup() *nftTxEventGroup { + return &nftTxEventGroup{ + pendingWithdrawals: make(map[uint64][]*nftDecodedWithdrawal), + } +} + +// addWithdrawal adds a withdrawal event to the event group. +// +// No error returns are expected during normal operation. +func (g *nftTxEventGroup) addWithdrawal(event flow.Event, decoded *events.NFTWithdrawnEvent) error { + w := &nftDecodedWithdrawal{source: event, decoded: *decoded} + + existing := g.pendingWithdrawals[decoded.UUID] + if len(existing) == 0 { + // First withdrawal for this UUID. Check if the NFT's provider collection was itself + // withdrawn in this transaction and propagate the source address if missing. + parentPending := g.pendingWithdrawals[w.decoded.ProviderUUID] + if len(parentPending) > 0 { + parent := parentPending[len(parentPending)-1] + + // Build event ancestor chain: parent's ancestors + parent itself. + chain := make([]flow.Event, len(parent.ancestorEvents)+1) + copy(chain, parent.ancestorEvents) + chain[len(chain)-1] = parent.source + w.ancestorEvents = chain + + // Propagate source address from parent if this withdrawal has none. + if w.decoded.From == flow.EmptyAddress && parent.decoded.From != flow.EmptyAddress { + w.decoded.From = parent.decoded.From + } + } + } + + g.pendingWithdrawals[decoded.UUID] = append(existing, w) + return nil +} + +// addDeposit adds a deposit event to the event group. +// +// NFT transfers emit two separate Cadence events: a Withdrawn event when the NFT leaves the +// sender's collection, and a Deposited event when it enters the receiver's collection. To +// reconstruct a complete transfer record (sender → receiver), we must pair these events by +// matching the NFT's UUID and ID. A deposit without a matching withdrawal indicates a mint; +// a withdrawal without a matching deposit (resolved later in ResolvePairs) indicates a burn. +// +// UUID Reuse Problem: +// The `pendingWithdrawals` map is keyed by UUID. However, some NFT collections (e.g., TopShot) +// reuse Cadence resource UUIDs across distinct NFTs, meaning multiple NFTs with different IDs +// can share the same UUID within a transaction. Therefore, we filter pending withdrawals by +// both UUID and NFT ID — only withdrawals with a matching ID belong to this deposit; the rest +// remain pending for future deposits. +// +// No error returns are expected during normal operation. +func (g *nftTxEventGroup) addDeposit(event flow.Event, decoded *events.NFTDepositedEvent) error { + d := &nftDecodedDeposit{source: event, decoded: *decoded} + uuid := decoded.UUID + + pending := g.pendingWithdrawals[uuid] + if len(pending) == 0 { + // No corresponding withdrawal - treat as mint. + g.pairedResults = append(g.pairedResults, resolveNFTTransfers(nil, d)...) + return nil + } + + // Partition pending withdrawals by NFT ID. Some collections (e.g. TopShot) reuse Cadence + // resource UUIDs across distinct NFTs, so multiple NFTs with different IDs can share a UUID. + // Only withdrawals with a matching ID belong to this deposit; the rest stay pending. + // + // NFTs can be transferred multiple times within a transaction. capture all matching withdrawals + // to include in the transfer event indices. + var matching []*nftDecodedWithdrawal + var remaining []*nftDecodedWithdrawal + for _, w := range pending { + if w.decoded.ID == decoded.ID { + matching = append(matching, w) + } else { + remaining = append(remaining, w) + } + } + + if len(matching) == 0 { + // No withdrawal with a matching NFT ID - treat as mint. + g.pairedResults = append(g.pairedResults, resolveNFTTransfers(nil, d)...) + return nil + } + + // Validate token type against the matched withdrawals. + lastW := matching[len(matching)-1] + if lastW.decoded.Type != decoded.Type { + return fmt.Errorf("withdrawal token type %s (eventIdx=%d) is not equal to the deposit token type %s (eventIdx=%d) in transaction %d", + lastW.decoded.Type, lastW.source.EventIndex, decoded.Type, event.EventIndex, event.TransactionIndex) + } + + g.pairedResults = append(g.pairedResults, resolveNFTTransfers(matching, d)...) + + // Keep only non-matching withdrawals pending. If none remain, clean up the map entry + // so the same UUID can be withdrawn again within this transaction (multi-hop: A → B → C). + if len(remaining) == 0 { + delete(g.pendingWithdrawals, uuid) + } else { + g.pendingWithdrawals[uuid] = remaining + } + return nil +} + +// ResolvePairs returns all paired results including unmatched withdrawals (burns). +func (g *nftTxEventGroup) ResolvePairs() []nftPairedResult { + for _, pending := range g.pendingWithdrawals { + g.pairedResults = append(g.pairedResults, resolveNFTTransfers(pending, nil)...) + } + return g.pairedResults +} + +// resolveNFTTransfers converts a sequence of pending Withdrawn events (and an optional Deposited +// event) into one or more [nftPairedResult] objects. +// +// Consecutive withdrawals with the same source address are grouped into runs. Each run represents +// one or more collection layers owned by the same account. A change in source address between +// consecutive withdrawals indicates an ownership boundary and produces an intermediate transfer. +// +// Given runs [G0, G1, ..., GN] (G0 is innermost / earliest events, GN is outermost): +// - One final transfer: G0.address → deposit.To (or burn if deposit is nil), +// with all G0 events plus the deposit as source events. +// - One intermediate transfer per adjacent run pair (Gi → Gi-1 for i = 1..N): +// Gi.address → Gi-1.address, with [last event of Gi-1, first event of Gi] as source events. +func resolveNFTTransfers(pending []*nftDecodedWithdrawal, deposit *nftDecodedDeposit) []nftPairedResult { + if len(pending) == 0 { + if deposit == nil { + return nil + } + return []nftPairedResult{{ + sourceEvents: []flow.Event{deposit.source}, + deposit: &deposit.decoded, + }} + } + + runs := groupNFTIntoRuns(pending) + + var results []nftPairedResult + + // Final transfer: innermost run → deposit (or burn if deposit is nil). + innerRun := runs[0] + var finalSourceEvents []flow.Event + for _, w := range innerRun.events { + finalSourceEvents = append(finalSourceEvents, w.ancestorEvents...) + finalSourceEvents = append(finalSourceEvents, w.source) + } + if deposit != nil { + finalSourceEvents = append(finalSourceEvents, deposit.source) + results = append(results, nftPairedResult{ + sourceEvents: finalSourceEvents, + withdrawal: &innerRun.events[0].decoded, + deposit: &deposit.decoded, + }) + } else { + results = append(results, nftPairedResult{ + sourceEvents: finalSourceEvents, + withdrawal: &innerRun.events[0].decoded, + // recipientAddress is zero = burn + }) + } + + // Intermediate transfers: runs[i] → runs[i-1] for each adjacent run pair. + for i := 1; i < len(runs); i++ { + outerRun := runs[i] + prevInnerRun := runs[i-1] + + lastInner := prevInnerRun.events[len(prevInnerRun.events)-1] + firstOuter := outerRun.events[0] + + var sourceEvents []flow.Event + sourceEvents = append(sourceEvents, lastInner.ancestorEvents...) + sourceEvents = append(sourceEvents, lastInner.source) + sourceEvents = append(sourceEvents, firstOuter.ancestorEvents...) + sourceEvents = append(sourceEvents, firstOuter.source) + + results = append(results, nftPairedResult{ + sourceEvents: sourceEvents, + withdrawal: &firstOuter.decoded, + recipientAddress: prevInnerRun.address, + }) + } + + return results +} + +// groupNFTIntoRuns groups a sequence of withdrawals into runs of consecutive same-address events. +func groupNFTIntoRuns(pending []*nftDecodedWithdrawal) []nftWithdrawalRun { + var runs []nftWithdrawalRun + for _, w := range pending { + if len(runs) == 0 || runs[len(runs)-1].address != w.decoded.From { + runs = append(runs, nftWithdrawalRun{address: w.decoded.From}) + } + runs[len(runs)-1].events = append(runs[len(runs)-1].events, w) + } + return runs +} diff --git a/module/state_synchronization/indexer/extended/transfers/nft_parser.go b/module/state_synchronization/indexer/extended/transfers/nft_parser.go new file mode 100644 index 00000000000..e65eab32a4b --- /dev/null +++ b/module/state_synchronization/indexer/extended/transfers/nft_parser.go @@ -0,0 +1,198 @@ +package transfers + +import ( + "fmt" + "sort" + "strconv" + "strings" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/events" +) + +const ( + nftWithdrawnFormat = "A.%s.NonFungibleToken.Withdrawn" + nftDepositedFormat = "A.%s.NonFungibleToken.Deposited" +) + +// nftPairedResult holds a matched withdrawal/deposit pair, or an unpaired event. +// For paired events, both withdrawal and deposit are set. +// For mints (deposit-only), withdrawal is nil. +// For burns (withdrawal-only), deposit is nil and recipientAddress is zero. +// For intermediate transfers (multi-layer collections), deposit is nil and recipientAddress is set. +type nftPairedResult struct { + sourceEvents []flow.Event // the flow.Event(s) that produced this result + withdrawal *events.NFTWithdrawnEvent // nil for deposit-only (mint) + deposit *events.NFTDepositedEvent // nil for withdrawal-only (burn or intermediate transfer) + recipientAddress flow.Address // used for intermediate transfers when deposit is nil +} + +// NFTParser decodes NonFungibleToken transfer events from CCF-encoded payloads and converts them +// into the model types used by the storage index. +// +// All methods are safe for concurrent access. +type NFTParser struct { + withdrawnEventType flow.EventType + depositedEventType flow.EventType +} + +// NewNFTParser creates a new non-fungible token transfer event parser. +func NewNFTParser(chainID flow.ChainID) *NFTParser { + sc := systemcontracts.SystemContractsForChain(chainID) + return &NFTParser{ + withdrawnEventType: flow.EventType(fmt.Sprintf(nftWithdrawnFormat, sc.NonFungibleToken.Address)), + depositedEventType: flow.EventType(fmt.Sprintf(nftDepositedFormat, sc.NonFungibleToken.Address)), + } +} + +// Parse extracts non-fungible token transfer events from the given events, pairs +// Withdrawn/Deposited events within each transaction, and returns fully-formed +// [access.NonFungibleTokenTransfer] objects. +// +// Events are paired by matching the `uuid` field between Withdrawn and Deposited events within +// the same transaction. Each paired result uses the Deposited event's [flow.Event.EventIndex]. +// Unpaired events produce records with a zero address for the missing side. +// +// No error returns are expected during normal operation. +func (p *NFTParser) Parse(evts []flow.Event, blockHeight uint64) ([]access.NonFungibleTokenTransfer, error) { + groups, err := p.filterAndDecodeNFT(evts) + if err != nil { + return nil, err + } + + paired := make([]nftPairedResult, 0) + for _, group := range groups { + paired = append(paired, group.ResolvePairs()...) + } + + return p.buildTransfers(paired, blockHeight) +} + +// filterAndDecodeNFT filters events by type, decodes CCF payloads into typed domain events, +// and groups the results by transaction index. +// +// No error returns are expected during normal operation. +func (p *NFTParser) filterAndDecodeNFT(evts []flow.Event) (map[uint32]*nftTxEventGroup, error) { + txEventGroups := make(map[uint32]*nftTxEventGroup) + + ensureGroup := func(txIndex uint32) *nftTxEventGroup { + g, ok := txEventGroups[txIndex] + if !ok { + g = newNFTTxEventGroup() + txEventGroups[txIndex] = g + } + return g + } + + for _, event := range evts { + switch event.Type { + case p.withdrawnEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + decoded, err := events.DecodeNFTWithdrawn(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode withdrawn event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + g := ensureGroup(event.TransactionIndex) + err = g.addWithdrawal(event, decoded) + if err != nil { + return nil, fmt.Errorf("failed to add withdrawal event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + + case p.depositedEventType: + cadenceEvent, err := events.DecodePayload(event) + if err != nil { + return nil, fmt.Errorf("failed to decode event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + decoded, err := events.DecodeNFTDeposited(cadenceEvent) + if err != nil { + return nil, fmt.Errorf("failed to decode deposited event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + g := ensureGroup(event.TransactionIndex) + err = g.addDeposit(event, decoded) + if err != nil { + return nil, fmt.Errorf("failed to add deposit event %d in transaction %d: %w", event.EventIndex, event.TransactionIndex, err) + } + } + } + + return txEventGroups, nil +} + +// buildTransfers converts paired results into [access.NonFungibleTokenTransfer] model objects. +// +// No error returns are expected during normal operation. +func (p *NFTParser) buildTransfers(paired []nftPairedResult, blockHeight uint64) ([]access.NonFungibleTokenTransfer, error) { + transfers := make([]access.NonFungibleTokenTransfer, 0, len(paired)) + for i, pair := range paired { + if len(pair.sourceEvents) == 0 { + return nil, fmt.Errorf("paired result has no source events") + } + if pair.withdrawal == nil && pair.deposit == nil { + return nil, fmt.Errorf("paired result has neither withdrawal nor deposit (events=%v)", pair.sourceEvents) + } + + txID := pair.sourceEvents[0].TransactionID + txIndex := pair.sourceEvents[0].TransactionIndex + eventIndices := make([]uint32, len(pair.sourceEvents)) + eventIndicesStr := make([]string, len(pair.sourceEvents)) + for i, event := range pair.sourceEvents { + eventIndices[i] = event.EventIndex + eventIndicesStr[i] = strconv.Itoa(int(event.EventIndex)) + + if txID != event.TransactionID { + return nil, fmt.Errorf("transaction ID mismatch for source event: %s != %s (tx=%d, evtIdx=%s)", + txID, event.TransactionID, txIndex, strings.Join(eventIndicesStr, ",")) + } + if txIndex != event.TransactionIndex { + return nil, fmt.Errorf("transaction index mismatch for source event: %d != %d (tx=%d, evtIdx=%s)", + txIndex, event.TransactionIndex, txIndex, strings.Join(eventIndicesStr, ",")) + } + } + + if len(eventIndices) == 0 { + return nil, fmt.Errorf("no event indices for source events (tx=%s, pairIdx=%d)", txID, i) + } + + transfer := access.NonFungibleTokenTransfer{ + BlockHeight: blockHeight, + TransactionID: txID, + TransactionIndex: txIndex, + EventIndices: eventIndices, + } + + if pair.withdrawal != nil { + transfer.TokenType = pair.withdrawal.Type + transfer.SourceAddress = pair.withdrawal.From + transfer.ID = pair.withdrawal.ID + } + + if pair.deposit != nil { + transfer.TokenType = pair.deposit.Type + transfer.ID = pair.deposit.ID + transfer.RecipientAddress = pair.deposit.To + } else { + transfer.RecipientAddress = pair.recipientAddress + } + + if transfer.TokenType == "" { + return nil, fmt.Errorf("token type is empty for NFT transfer (tx=%s, evtIdx=%s)", + txID, strings.Join(eventIndicesStr, ",")) + } + + transfers = append(transfers, transfer) + } + // sort ascending. for transfers in the same transaction, sort ascending by the last event index, + // which is either the deposit event, or the withdrawal placeholder event. + sort.Slice(transfers, func(i, j int) bool { + if transfers[i].TransactionIndex == transfers[j].TransactionIndex { + return transfers[i].EventIndices[len(transfers[i].EventIndices)-1] < transfers[j].EventIndices[len(transfers[j].EventIndices)-1] + } + return transfers[i].TransactionIndex < transfers[j].TransactionIndex + }) + return transfers, nil +} diff --git a/module/state_synchronization/indexer/extended/transfers/nft_parser_test.go b/module/state_synchronization/indexer/extended/transfers/nft_parser_test.go new file mode 100644 index 00000000000..8bc0db9c568 --- /dev/null +++ b/module/state_synchronization/indexer/extended/transfers/nft_parser_test.go @@ -0,0 +1,511 @@ +package transfers + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended/transfers/testutil" + "github.com/onflow/flow-go/utils/unittest" +) + +// ========================================================================== +// NFT Transfer Tests +// ========================================================================== + +func TestParseNFTTransfers_PairedTransfer(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + nftUUID := uint64(100) + nftID := uint64(42) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, nftUUID, nftID), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 1, nftUUID, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, nftID, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseNFTTransfers_UnpairedDeposit(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + nftID := uint64(7) + events := []flow.Event{ + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 0, 999, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, flow.Address{}, recipient, nftID, 0), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseNFTTransfers_UnpairedWithdrawal(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + sender := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + nftID := uint64(13) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, 888, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, flow.Address{}, nftID, 0), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseNFTTransfers_NilOptionalAddresses(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + txID := unittest.IdentifierFixture() + + uuid := uint64(50) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, nil, txID, 0, 0, uuid, 1), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, nil, txID, 0, 1, uuid, 1), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, flow.Address{}, flow.Address{}, 1, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseNFTTransfers_MultiplePairsInSameTx(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + txID := unittest.IdentifierFixture() + + sender1 := unittest.RandomAddressFixture() + recipient1 := unittest.RandomAddressFixture() + sender2 := unittest.RandomAddressFixture() + recipient2 := unittest.RandomAddressFixture() + + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender1, txID, 0, 0, 10, 1), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient1, txID, 0, 1, 10, 1), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender2, txID, 0, 2, 20, 2), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient2, txID, 0, 3, 20, 2), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender1, recipient1, 1, 0, 1), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender2, recipient2, 2, 2, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_PairedUsesDepositEventIndex verifies that paired NFT transfers +// include both the Withdrawn and Deposited event indices. +func TestParseNFTTransfers_PairedUsesDepositEventIndex(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + uuid := uint64(1) + nftID := uint64(111) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, uuid, nftID), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 5, uuid, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, nftID, 0, 5), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseNFTTransfers_MalformedPayload(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + + t.Run("malformed withdrawn event", func(t *testing.T) { + events := []flow.Event{ + { + Type: testutil.NFTWithdrawnEventType(flow.Testnet), + Payload: []byte("not valid ccf"), + }, + } + transfers, err := parser.Parse(events, testBlockHeight) + require.Error(t, err) + assert.Nil(t, transfers) + }) + + t.Run("malformed deposited event", func(t *testing.T) { + events := []flow.Event{ + { + Type: testutil.NFTDepositedEventType(flow.Testnet), + Payload: []byte("not valid ccf"), + }, + } + transfers, err := parser.Parse(events, testBlockHeight) + require.Error(t, err) + assert.Nil(t, transfers) + }) +} + +// TestParseNFTTransfers_EventsAcrossTransactionsDoNotPair verifies that events +// with the same UUID but in different transactions are NOT paired together. +func TestParseNFTTransfers_EventsAcrossTransactionsDoNotPair(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + sharedUUID := uint64(42) + nftID := uint64(7) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID1, 0, 0, sharedUUID, nftID), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID2, 1, 0, sharedUUID, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID1, 0, sender, flow.Address{}, nftID, 0), + testutil.MakeNFTTransfer(testBlockHeight, txID2, 1, flow.Address{}, recipient, nftID, 0), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_DepositBeforeWithdrawal verifies that when a deposit is processed +// before a withdrawal with the same UUID, they are NOT paired. The deposit is treated as +// a mint and the withdrawal as a burn. +func TestParseNFTTransfers_DepositBeforeWithdrawal(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + uuid := uint64(55) + nftID := uint64(42) + events := []flow.Event{ + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 0, uuid, nftID), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 1, uuid, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, flow.Address{}, recipient, nftID, 0), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, flow.Address{}, nftID, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +func TestParseNFTTransfers_SkipsIrrelevantEvents(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + + events := []flow.Event{ + { + Type: "A.f233dcee88fe0abe.FlowToken.TokensMinted", + TransactionID: unittest.IdentifierFixture(), + TransactionIndex: 0, + EventIndex: 0, + Payload: []byte("irrelevant"), + }, + { + Type: "A.1234567890abcdef.SomeContract.SomeEvent", + TransactionID: unittest.IdentifierFixture(), + TransactionIndex: 0, + EventIndex: 1, + Payload: []byte("also irrelevant"), + }, + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.Empty(t, transfers) +} + +func TestParseNFTTransfers_MixedPairedAndUnpaired(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + txID := unittest.IdentifierFixture() + + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + mintRecipient := unittest.RandomAddressFixture() + burnSender := unittest.RandomAddressFixture() + + events := []flow.Event{ + // Paired transfer + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, 100, 1), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 1, 100, 1), + // Unpaired deposit (mint) + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &mintRecipient, txID, 0, 2, 200, 2), + // Unpaired withdrawal (burn) + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &burnSender, txID, 0, 3, 300, 3), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, 1, 0, 1), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, flow.Address{}, mintRecipient, 2, 2), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, burnSender, flow.Address{}, 3, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_MultipleWithdrawalsBeforeDeposit verifies that multiple Withdrawn events +// for the same NFT UUID within a transaction are valid and produce a single transfer. All +// withdrawal source events are included in the EventIndices of the resulting transfer. +func TestParseNFTTransfers_MultipleWithdrawalsBeforeDeposit(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + nftUUID := uint64(100) + nftID := uint64(42) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, nftUUID, nftID), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 1, nftUUID, nftID), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 2, nftUUID, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, nftID, 0, 1, 2), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_MultiHopTransfer verifies that an NFT transferred through multiple +// addresses within a single transaction (A → B → C) produces one transfer per hop. +func TestParseNFTTransfers_MultiHopTransfer(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + carol := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + nftUUID := uint64(100) + nftID := uint64(42) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &alice, txID, 0, 0, nftUUID, nftID), // A → out + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &bob, txID, 0, 1, nftUUID, nftID), // → B + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &bob, txID, 0, 2, nftUUID, nftID), // B → out + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &carol, txID, 0, 3, nftUUID, nftID), // → C + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, alice, bob, nftID, 0, 1), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, bob, carol, nftID, 2, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_MultiLayerCollectionTransfer verifies that when an NFT passes through +// multiple layers of collections owned by different accounts within a single transaction, an +// intermediate transfer is produced for each ownership boundary. +// +// Scenario (5 events, addresses labelled by number): +// +// W(addr1, idx=0), W(addr1, idx=1), W(addr2, idx=2), W(addr3, idx=3), D(addr4, idx=4) +// +// Expected transfers: +// +// addr3 → addr2 events [2, 3] (G2 → G1 boundary) +// addr2 → addr1 events [1, 2] (G1 → G0 boundary) +// addr1 → addr4 events [0, 1, 4] (innermost run → deposit) +func TestParseNFTTransfers_MultiLayerCollectionTransfer(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + addr1 := unittest.RandomAddressFixture() + addr2 := unittest.RandomAddressFixture() + addr3 := unittest.RandomAddressFixture() + addr4 := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + nftUUID := uint64(100) + nftID := uint64(42) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &addr1, txID, 0, 0, nftUUID, nftID), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &addr1, txID, 0, 1, nftUUID, nftID), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &addr2, txID, 0, 2, nftUUID, nftID), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &addr3, txID, 0, 3, nftUUID, nftID), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &addr4, txID, 0, 4, nftUUID, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, addr1, addr4, nftID, 0, 1, 4), // innermost → deposit + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, addr2, addr1, nftID, 1, 2), // G1 → G0 + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, addr3, addr2, nftID, 2, 3), // G2 → G1 + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_MultiLayerBurn verifies that when a multi-layer NFT withdrawal has no +// matching deposit, intermediate transfers are still produced for each ownership boundary and +// the innermost run produces a burn record. +// +// Scenario: +// +// W(addr1, idx=0), W(addr2, idx=1), W(addr3, idx=2), no deposit +// +// Expected transfers: +// +// addr3 → addr2 events [1, 2] +// addr2 → addr1 events [0, 1] +// addr1 → burn events [0] +func TestParseNFTTransfers_MultiLayerBurn(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + addr1 := unittest.RandomAddressFixture() + addr2 := unittest.RandomAddressFixture() + addr3 := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + nftUUID := uint64(100) + nftID := uint64(42) + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &addr1, txID, 0, 0, nftUUID, nftID), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &addr2, txID, 0, 1, nftUUID, nftID), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &addr3, txID, 0, 2, nftUUID, nftID), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, addr1, flow.Address{}, nftID, 0), // burn + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, addr2, addr1, nftID, 0, 1), // G1 → G0 + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, addr3, addr2, nftID, 1, 2), // G2 → G1 + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_DuplicateUUIDDifferentIDs verifies that when multiple distinct NFTs +// share the same UUID (as happens with early TopShot NFTs), withdrawals and deposits are +// correctly matched by NFT ID rather than mismatching across different NFTs. +func TestParseNFTTransfers_DuplicateUUIDDifferentIDs(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + txID := unittest.IdentifierFixture() + + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + + sharedUUID := uint64(6) // TopShot-style low UUID shared across NFTs + + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, sharedUUID, 45475), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 1, sharedUUID, 127424), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 2, sharedUUID, 29440), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 3, sharedUUID, 45475), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 4, sharedUUID, 127424), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 5, sharedUUID, 29440), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, 45475, 0, 3), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, 127424, 1, 4), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, 29440, 2, 5), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_DuplicateUUIDMixedWithUnpaired verifies correct handling when +// duplicate-UUID NFTs include both paired transfers and unpaired events (mints/burns). +func TestParseNFTTransfers_DuplicateUUIDMixedWithUnpaired(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + txID := unittest.IdentifierFixture() + + sender := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + mintRecipient := unittest.RandomAddressFixture() + + sharedUUID := uint64(3) + + events := []flow.Event{ + // Withdrawal for NFT 100 (will be paired) + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 0, sharedUUID, 100), + // Withdrawal for NFT 200 (no deposit - burn) + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender, txID, 0, 1, sharedUUID, 200), + // Deposit for NFT 100 (paired with withdrawal above) + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient, txID, 0, 2, sharedUUID, 100), + // Deposit for NFT 300 (no withdrawal - mint) + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &mintRecipient, txID, 0, 3, sharedUUID, 300), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, recipient, 100, 0, 2), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, sender, flow.Address{}, 200, 1), + testutil.MakeNFTTransfer(testBlockHeight, txID, 0, flow.Address{}, mintRecipient, 300, 3), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} + +// TestParseNFTTransfers_MultipleTransactionsInBlock verifies that events from +// different transactions in the same block are grouped and paired independently. +func TestParseNFTTransfers_MultipleTransactionsInBlock(t *testing.T) { + parser := NewNFTParser(flow.Testnet) + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + sender1 := unittest.RandomAddressFixture() + recipient1 := unittest.RandomAddressFixture() + sender2 := unittest.RandomAddressFixture() + recipient2 := unittest.RandomAddressFixture() + + events := []flow.Event{ + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender1, txID1, 0, 0, 10, 1), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient1, txID1, 0, 1, 10, 1), + testutil.MakeNFTWithdrawnEvent(t, flow.Testnet, &sender2, txID2, 1, 0, 20, 2), + testutil.MakeNFTDepositedEvent(t, flow.Testnet, &recipient2, txID2, 1, 1, 20, 2), + } + + expected := []access.NonFungibleTokenTransfer{ + testutil.MakeNFTTransfer(testBlockHeight, txID1, 0, sender1, recipient1, 1, 0, 1), + testutil.MakeNFTTransfer(testBlockHeight, txID2, 1, sender2, recipient2, 2, 0, 1), + } + + transfers, err := parser.Parse(events, testBlockHeight) + require.NoError(t, err) + assert.ElementsMatch(t, expected, transfers) +} diff --git a/module/state_synchronization/indexer/extended/transfers/testutil/testutil.go b/module/state_synchronization/indexer/extended/transfers/testutil/testutil.go new file mode 100644 index 00000000000..ae1d35c4c32 --- /dev/null +++ b/module/state_synchronization/indexer/extended/transfers/testutil/testutil.go @@ -0,0 +1,353 @@ +// Package testutil provides shared event-building helpers for FT transfer tests. +package testutil + +import ( + "fmt" + "math/big" + "testing" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/common" + "github.com/onflow/cadence/encoding/ccf" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/fvm/systemcontracts" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +const ( + // FTTokenType is the Cadence type string used for FlowToken in test events. + FTTokenType = "A.0000000000000001.FlowToken.Vault" + + // NFTTokenType is the Cadence type string used for a test NFT in test events. + NFTTokenType = "A.0000000000000002.TopShot.NFT" + + ftWithdrawnFormat = "A.%s.FungibleToken.Withdrawn" + ftDepositedFormat = "A.%s.FungibleToken.Deposited" + flowFeesFormat = "A.%s.FlowFees.FeesDeducted" + nftWithdrawnFormat = "A.%s.NonFungibleToken.Withdrawn" + nftDepositedFormat = "A.%s.NonFungibleToken.Deposited" +) + +// FTWithdrawnEventType returns the FungibleToken.Withdrawn event type for the given chain. +func FTWithdrawnEventType(chainID flow.ChainID) flow.EventType { + sc := systemcontracts.SystemContractsForChain(chainID) + return flow.EventType(fmt.Sprintf(ftWithdrawnFormat, sc.FungibleToken.Address)) +} + +// FTDepositedEventType returns the FungibleToken.Deposited event type for the given chain. +func FTDepositedEventType(chainID flow.ChainID) flow.EventType { + sc := systemcontracts.SystemContractsForChain(chainID) + return flow.EventType(fmt.Sprintf(ftDepositedFormat, sc.FungibleToken.Address)) +} + +// FlowFeesEventType returns the FlowFees.FeesDeducted event type for the given chain. +func FlowFeesEventType(chainID flow.ChainID) flow.EventType { + sc := systemcontracts.SystemContractsForChain(chainID) + return flow.EventType(fmt.Sprintf(flowFeesFormat, sc.FlowFees.Address)) +} + +// FlowFeesAddress returns the FlowFees contract address for the given chain. +func FlowFeesAddress(chainID flow.ChainID) flow.Address { + return systemcontracts.SystemContractsForChain(chainID).FlowFees.Address +} + +// MakeFTTransfer builds an [access.FungibleTokenTransfer] for use in test assertions. +func MakeFTTransfer( + blockHeight uint64, + txID flow.Identifier, + txIndex uint32, + source, recipient flow.Address, + amount cadence.UFix64, + eventIndices ...uint32, +) access.FungibleTokenTransfer { + return access.FungibleTokenTransfer{ + TransactionID: txID, + BlockHeight: blockHeight, + TransactionIndex: txIndex, + EventIndices: eventIndices, + TokenType: FTTokenType, + Amount: new(big.Int).SetUint64(uint64(amount)), + SourceAddress: source, + RecipientAddress: recipient, + } +} + +// MakeFTWithdrawnEvent creates a CCF-encoded FungibleToken.Withdrawn event. +func MakeFTWithdrawnEvent( + t testing.TB, + chainID flow.ChainID, + fromAddr *flow.Address, + txID flow.Identifier, + txIndex, eventIndex uint32, + fromUUID, withdrawnUUID uint64, + amount cadence.UFix64, +) flow.Event { + sc := systemcontracts.SystemContractsForChain(chainID) + eventType := flow.EventType(fmt.Sprintf(ftWithdrawnFormat, sc.FungibleToken.Address)) + + var fromValue cadence.Value + if fromAddr != nil { + fromValue = cadence.NewOptional(cadence.NewAddress(*fromAddr)) + } else { + fromValue = cadence.NewOptional(nil) + } + + loc := common.NewAddressLocation(nil, common.Address{}, "FungibleToken") + cadenceType := cadence.NewEventType(loc, "FungibleToken.Withdrawn", []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "amount", Type: cadence.UFix64Type}, + {Identifier: "from", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "fromUUID", Type: cadence.UInt64Type}, + {Identifier: "withdrawnUUID", Type: cadence.UInt64Type}, + {Identifier: "balanceAfter", Type: cadence.UFix64Type}, + }, nil) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String(FTTokenType), + amount, + fromValue, + cadence.UInt64(fromUUID), + cadence.UInt64(withdrawnUUID), + cadence.UFix64(150_00000000), + }).WithType(cadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + flowEvent, err := flow.NewEvent(flow.UntrustedEvent{ + Type: eventType, + TransactionID: txID, + TransactionIndex: txIndex, + EventIndex: eventIndex, + Payload: payload, + }) + require.NoError(t, err) + return *flowEvent +} + +// MakeFTDepositedEvent creates a CCF-encoded FungibleToken.Deposited event. +func MakeFTDepositedEvent( + t testing.TB, + chainID flow.ChainID, + toAddr *flow.Address, + txID flow.Identifier, + txIndex, eventIndex uint32, + toUUID uint64, + depositedUUID uint64, + amount cadence.UFix64, +) flow.Event { + sc := systemcontracts.SystemContractsForChain(chainID) + eventType := flow.EventType(fmt.Sprintf(ftDepositedFormat, sc.FungibleToken.Address)) + + var toValue cadence.Value + if toAddr != nil { + toValue = cadence.NewOptional(cadence.NewAddress(*toAddr)) + } else { + toValue = cadence.NewOptional(nil) + } + + loc := common.NewAddressLocation(nil, common.Address{}, "FungibleToken") + cadenceType := cadence.NewEventType(loc, "FungibleToken.Deposited", []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "amount", Type: cadence.UFix64Type}, + {Identifier: "to", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "toUUID", Type: cadence.UInt64Type}, + {Identifier: "depositedUUID", Type: cadence.UInt64Type}, + {Identifier: "balanceAfter", Type: cadence.UFix64Type}, + }, nil) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String(FTTokenType), + amount, + toValue, + cadence.UInt64(toUUID), + cadence.UInt64(depositedUUID), + cadence.UFix64(200_00000000), + }).WithType(cadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + flowEvent, err := flow.NewEvent(flow.UntrustedEvent{ + Type: eventType, + TransactionID: txID, + TransactionIndex: txIndex, + EventIndex: eventIndex, + Payload: payload, + }) + require.NoError(t, err) + return *flowEvent +} + +// NFTWithdrawnEventType returns the NonFungibleToken.Withdrawn event type for the given chain. +func NFTWithdrawnEventType(chainID flow.ChainID) flow.EventType { + sc := systemcontracts.SystemContractsForChain(chainID) + return flow.EventType(fmt.Sprintf(nftWithdrawnFormat, sc.NonFungibleToken.Address)) +} + +// NFTDepositedEventType returns the NonFungibleToken.Deposited event type for the given chain. +func NFTDepositedEventType(chainID flow.ChainID) flow.EventType { + sc := systemcontracts.SystemContractsForChain(chainID) + return flow.EventType(fmt.Sprintf(nftDepositedFormat, sc.NonFungibleToken.Address)) +} + +// MakeNFTTransfer builds an [access.NonFungibleTokenTransfer] for use in test assertions. +func MakeNFTTransfer( + blockHeight uint64, + txID flow.Identifier, + txIndex uint32, + source, recipient flow.Address, + nftID uint64, + eventIndices ...uint32, +) access.NonFungibleTokenTransfer { + return access.NonFungibleTokenTransfer{ + TransactionID: txID, + BlockHeight: blockHeight, + TransactionIndex: txIndex, + EventIndices: eventIndices, + TokenType: NFTTokenType, + ID: nftID, + SourceAddress: source, + RecipientAddress: recipient, + } +} + +// MakeNFTWithdrawnEvent creates a CCF-encoded NonFungibleToken.Withdrawn event. +func MakeNFTWithdrawnEvent( + t testing.TB, + chainID flow.ChainID, + fromAddr *flow.Address, + txID flow.Identifier, + txIndex, eventIndex uint32, + uuid, nftID uint64, +) flow.Event { + sc := systemcontracts.SystemContractsForChain(chainID) + eventType := flow.EventType(fmt.Sprintf(nftWithdrawnFormat, sc.NonFungibleToken.Address)) + + var fromValue cadence.Value + if fromAddr != nil { + fromValue = cadence.NewOptional(cadence.NewAddress(*fromAddr)) + } else { + fromValue = cadence.NewOptional(nil) + } + + loc := common.NewAddressLocation(nil, common.Address{}, "NonFungibleToken") + cadenceType := cadence.NewEventType(loc, "NonFungibleToken.Withdrawn", []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "uuid", Type: cadence.UInt64Type}, + {Identifier: "from", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "providerUUID", Type: cadence.UInt64Type}, + }, nil) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String(NFTTokenType), + cadence.UInt64(nftID), + cadence.UInt64(uuid), + fromValue, + cadence.UInt64(5), + }).WithType(cadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + flowEvent, err := flow.NewEvent(flow.UntrustedEvent{ + Type: eventType, + TransactionID: txID, + TransactionIndex: txIndex, + EventIndex: eventIndex, + Payload: payload, + }) + require.NoError(t, err) + return *flowEvent +} + +// MakeNFTDepositedEvent creates a CCF-encoded NonFungibleToken.Deposited event. +func MakeNFTDepositedEvent( + t testing.TB, + chainID flow.ChainID, + toAddr *flow.Address, + txID flow.Identifier, + txIndex, eventIndex uint32, + uuid, nftID uint64, +) flow.Event { + sc := systemcontracts.SystemContractsForChain(chainID) + eventType := flow.EventType(fmt.Sprintf(nftDepositedFormat, sc.NonFungibleToken.Address)) + + var toValue cadence.Value + if toAddr != nil { + toValue = cadence.NewOptional(cadence.NewAddress(*toAddr)) + } else { + toValue = cadence.NewOptional(nil) + } + + loc := common.NewAddressLocation(nil, common.Address{}, "NonFungibleToken") + cadenceType := cadence.NewEventType(loc, "NonFungibleToken.Deposited", []cadence.Field{ + {Identifier: "type", Type: cadence.StringType}, + {Identifier: "id", Type: cadence.UInt64Type}, + {Identifier: "uuid", Type: cadence.UInt64Type}, + {Identifier: "to", Type: cadence.NewOptionalType(cadence.AddressType)}, + {Identifier: "collectionUUID", Type: cadence.UInt64Type}, + }, nil) + + event := cadence.NewEvent([]cadence.Value{ + cadence.String(NFTTokenType), + cadence.UInt64(nftID), + cadence.UInt64(uuid), + toValue, + cadence.UInt64(5), + }).WithType(cadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + flowEvent, err := flow.NewEvent(flow.UntrustedEvent{ + Type: eventType, + TransactionID: txID, + TransactionIndex: txIndex, + EventIndex: eventIndex, + Payload: payload, + }) + require.NoError(t, err) + return *flowEvent +} + +// MakeFlowFeesEvent creates a CCF-encoded FlowFees.FeesDeducted event. +func MakeFlowFeesEvent( + t testing.TB, + chainID flow.ChainID, + txID flow.Identifier, + txIndex, eventIndex uint32, + amount cadence.UFix64, +) flow.Event { + sc := systemcontracts.SystemContractsForChain(chainID) + eventType := flow.EventType(fmt.Sprintf(flowFeesFormat, sc.FlowFees.Address)) + + loc := common.NewAddressLocation(nil, common.Address{}, "FlowFees") + cadenceType := cadence.NewEventType(loc, "FlowFees.FeesDeducted", []cadence.Field{ + {Identifier: "amount", Type: cadence.UFix64Type}, + {Identifier: "executionEffort", Type: cadence.UInt64Type}, + {Identifier: "inclusionEffort", Type: cadence.UInt64Type}, + }, nil) + + event := cadence.NewEvent([]cadence.Value{ + amount, + cadence.UInt64(500), + cadence.UInt64(1000), + }).WithType(cadenceType) + + payload, err := ccf.Encode(event) + require.NoError(t, err) + + flowEvent, err := flow.NewEvent(flow.UntrustedEvent{ + Type: eventType, + TransactionID: txID, + TransactionIndex: txIndex, + EventIndex: eventIndex, + Payload: payload, + }) + require.NoError(t, err) + return *flowEvent +} diff --git a/module/state_synchronization/indexer/indexer.go b/module/state_synchronization/indexer/indexer.go index db164a2c12d..f961f062312 100644 --- a/module/state_synchronization/indexer/indexer.go +++ b/module/state_synchronization/indexer/indexer.go @@ -70,13 +70,18 @@ func NewIndexer( indexer *IndexerCore, executionCache *cache.ExecutionDataCache, executionDataLatestHeight func() (uint64, error), - processedHeightInitializer storage.ConsumerProgressInitializer, + processedHeight storage.ConsumerProgress, ) (*Indexer, error) { + lastProcessedHeight, err := processedHeight.ProcessedIndex() + if err != nil { + return nil, fmt.Errorf("could not get last processed height: %w", err) + } + r := &Indexer{ log: log.With().Str("module", "execution_indexer").Logger(), exeDataNotifier: engine.NewNotifier(), blockIndexedNotifier: engine.NewNotifier(), - lastProcessedHeight: atomic.NewUint64(initHeight), + lastProcessedHeight: atomic.NewUint64(lastProcessedHeight), indexer: indexer, registers: registers, ProcessedHeightRecorder: execution_data.NewProcessedHeightRecorderManager(initHeight), @@ -89,9 +94,8 @@ func NewIndexer( jobConsumer, err := jobqueue.NewComponentConsumer( r.log, r.exeDataNotifier.Channel(), - processedHeightInitializer, + processedHeight, r.exeDataReader, - initHeight, r.processExecutionData, workersCount, searchAhead, @@ -158,17 +162,22 @@ func (i *Indexer) onBlockIndexed() error { highestIndexedHeight := i.jobConsumer.LastProcessedIndex() if lastProcessedHeight < highestIndexedHeight { + if lastProcessedHeight+1000 < highestIndexedHeight { + i.log.Warn().Msgf("notifying processed heights from %d to %d", lastProcessedHeight+1, highestIndexedHeight) + } // we need loop here because it's possible for a height to be missed here, // we should guarantee all heights are processed for height := lastProcessedHeight + 1; height <= highestIndexedHeight; height++ { - header, err := i.indexer.headers.ByHeight(height) - if err != nil { - // if the execution data is available, the block must be locally finalized - i.log.Error().Err(err).Msgf("could not get header for height %d:", height) - return fmt.Errorf("could not get header for height %d: %w", height, err) - } - - i.OnBlockProcessed(header.Height) + // Use BlockIDByHeight instead of ByHeight since we only need to verify the block exists + // and don't need the full header data. This avoids expensive header deserialization. + // _, err := i.indexer.headers.BlockIDByHeight(height) + // if err != nil { + // // if the execution data is available, the block must be locally finalized + // i.log.Error().Err(err).Msgf("could not get header for height %d:", height) + // return fmt.Errorf("could not get header for height %d: %w", height, err) + // } + + i.OnBlockProcessed(height) } i.lastProcessedHeight.Store(highestIndexedHeight) } diff --git a/module/state_synchronization/indexer/indexer_core.go b/module/state_synchronization/indexer/indexer_core.go index eceec2492ad..10c3d92118b 100644 --- a/module/state_synchronization/indexer/indexer_core.go +++ b/module/state_synchronization/indexer/indexer_core.go @@ -21,6 +21,7 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" "github.com/onflow/flow-go/storage" "github.com/onflow/flow-go/utils/logging" ) @@ -43,6 +44,8 @@ type IndexerCore struct { scheduledTransactions storage.ScheduledTransactions protocolDB storage.DB + extendedIndexer *extended.ExtendedIndexer + derivedChainData *derived.DerivedChainData serviceAddress flow.Address lockManager lockctx.Manager @@ -67,6 +70,7 @@ func New( collectionIndexer collections.CollectionIndexer, collectionExecutedMetric module.CollectionExecutedMetric, lockManager lockctx.Manager, + extendedIndexer *extended.ExtendedIndexer, ) *IndexerCore { log = log.With().Str("component", "execution_indexer").Logger() metrics.InitializeLatestHeight(registers.LatestHeight()) @@ -76,7 +80,8 @@ func New( Uint64("latest_height", registers.LatestHeight()). Msg("indexer initialized") - fvmEnv := systemcontracts.SystemContractsForChain(chainID).AsTemplateEnv() + sc := systemcontracts.SystemContractsForChain(chainID) + fvmEnv := sc.AsTemplateEnv() return &IndexerCore{ log: log, @@ -94,34 +99,13 @@ func New( serviceAddress: chainID.Chain().ServiceAddress(), derivedChainData: derivedChainData, + extendedIndexer: extendedIndexer, collectionIndexer: collectionIndexer, collectionExecutedMetric: collectionExecutedMetric, lockManager: lockManager, } } -// RegisterValue retrieves register values by the register IDs at the provided block height. -// Even if the register wasn't indexed at the provided height, returns the highest height the register was indexed at. -// If a register is not found it will return a nil value and not an error. -// -// Expected error returns during normal operation: -// - [storage.ErrHeightNotIndexed]: if the given height was not indexed yet or lower than the first indexed height. -func (c *IndexerCore) RegisterValue(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { - value, err := c.registers.Get(ID, height) - if err != nil { - // only return an error if the error doesn't match the not found error, since we have - // to gracefully handle not found values and instead assign nil, that is because the script executor - // expects that behaviour - if errors.Is(err, storage.ErrNotFound) { - return nil, nil - } - - return nil, err - } - - return value, nil -} - // IndexBlockData indexes all execution block data by height. // This method shouldn't be used concurrently. // Expected error returns during normal operations: @@ -300,6 +284,15 @@ func (c *IndexerCore) IndexBlockData(data *execution_data.BlockExecutionDataEnti return fmt.Errorf("failed to index block data at height %d: %w", header.Height, err) } + // Notify the extended indexer after all other indexing (including register writing) has + // completed. This ordering is required because some extended indexers (e.g. contracts) read + // from the register index when processing blocks, so the registers must be committed first. + if c.extendedIndexer != nil { + if err := c.extendedIndexer.IndexBlockExecutionData(data); err != nil { + return fmt.Errorf("could not index extended block data: %w", err) + } + } + c.metrics.BlockIndexed(header.Height, time.Since(start), eventCount, registerCount, resultCount) lg.Debug(). Dur("duration_ms", time.Since(start)). diff --git a/module/state_synchronization/indexer/indexer_core_test.go b/module/state_synchronization/indexer/indexer_core_test.go index 5317c791e5f..f4961439127 100644 --- a/module/state_synchronization/indexer/indexer_core_test.go +++ b/module/state_synchronization/indexer/indexer_core_test.go @@ -2,9 +2,11 @@ package indexer import ( "context" + "errors" "fmt" "os" "testing" + "time" "github.com/jordanschalm/lockctx" "github.com/rs/zerolog" @@ -21,9 +23,12 @@ import ( "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/executiondatasync/execution_data" "github.com/onflow/flow-go/module/executiondatasync/testutil" + "github.com/onflow/flow-go/module/irrecoverable" "github.com/onflow/flow-go/module/mempool/stdmap" "github.com/onflow/flow-go/module/metrics" + "github.com/onflow/flow-go/module/state_synchronization/indexer/extended" synctest "github.com/onflow/flow-go/module/state_synchronization/requester/unittest" + protocolmock "github.com/onflow/flow-go/state/protocol/mock" "github.com/onflow/flow-go/storage" storagemock "github.com/onflow/flow-go/storage/mock" "github.com/onflow/flow-go/storage/operation/pebbleimpl" @@ -52,7 +57,6 @@ type indexCoreTest struct { firstHeightStore func(t *testing.T) uint64 registersStore func(t *testing.T, entries flow.RegisterEntries, height uint64) error eventsStore func(t *testing.T, ID flow.Identifier, events []flow.EventsList) error - registersGet func(t *testing.T, IDs flow.RegisterID, height uint64) (flow.RegisterValue, error) } func newIndexCoreTest( @@ -161,15 +165,6 @@ func (i *indexCoreTest) setStoreTransactionResults(f func(*testing.T, flow.Ident return i } -func (i *indexCoreTest) setGetRegisters(f func(t *testing.T, ID flow.RegisterID, height uint64) (flow.RegisterValue, error)) *indexCoreTest { - i.registers. - On("Get", mock.AnythingOfType("flow.RegisterID"), mock.AnythingOfType("uint64")). - Return(func(IDs flow.RegisterID, height uint64) (flow.RegisterValue, error) { - return f(i.t, IDs, height) - }) - return i -} - func (i *indexCoreTest) useDefaultEvents() *indexCoreTest { i.events. On("BatchStore", @@ -242,6 +237,7 @@ func (i *indexCoreTest) initIndexer() *indexCoreTest { i.collectionIndexer, collectionExecutedMetric, lockManager, + nil, ) return i } @@ -251,11 +247,6 @@ func (i *indexCoreTest) runIndexBlockData() error { return i.indexer.IndexBlockData(i.data) } -func (i *indexCoreTest) runGetRegister(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { - i.initIndexer() - return i.indexer.RegisterValue(ID, height) -} - func TestExecutionState_IndexBlockData(t *testing.T) { g := fixtures.NewGeneratorSuite() blocks := g.Blocks().List(4) @@ -373,28 +364,181 @@ func TestExecutionState_IndexBlockData(t *testing.T) { err := test.indexer.IndexBlockData(tf.ExecutionDataEntity()) assert.NoError(t, err) }) -} -func TestExecutionState_RegisterValues(t *testing.T) { - g := fixtures.NewGeneratorSuite() - t.Run("Get value for single register", func(t *testing.T) { - blocks := g.Blocks().List(5) - height := blocks[1].Height - id := flow.RegisterID{ - Owner: "1", - Key: "2", + // test that extended indexer is invoked when configured + t.Run("Index account transactions", func(t *testing.T) { + test := newIndexCoreTest(t, g, blocks, tf.ExecutionDataEntity()).initIndexer() + + startHeight := tf.Block.Height - 1 + done := make(chan struct{}) + var gotHeight uint64 + stub := &testExtendedIndexer{ + name: "test", + latestHeight: startHeight, + indexBlockFn: func(data extended.BlockData) error { + gotHeight = data.Header.Height + close(done) + return nil + }, } - val := flow.RegisterValue("0x1") - values, err := newIndexCoreTest(t, g, blocks, nil). - initIndexer(). - setGetRegisters(func(t *testing.T, ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { - return val, nil - }). - runGetRegister(id, height) + mockState := newMockStateForBlock(t, tf.Block) + extendedIndexer, err := extended.NewExtendedIndexer( + test.indexer.log, + metrics.NewNoopCollector(), + test.indexer.protocolDB, + storage.NewTestingLockManager(), + mockState, + storagemock.NewIndex(t), + storagemock.NewHeaders(t), + storagemock.NewGuarantees(t), + test.collections, + test.events, + test.results, + []extended.Indexer{stub}, + test.indexer.chainID, + extended.DefaultBackfillDelay, + ) + require.NoError(t, err) + + // Start the ExtendedIndexer component so its ingest loop can process data + ctx, cancel := context.WithCancel(context.Background()) + signalerCtx := irrecoverable.NewMockSignalerContext(t, ctx) + extendedIndexer.Start(signalerCtx) + unittest.RequireComponentsReadyBefore(t, 5*time.Second, extendedIndexer) + t.Cleanup(func() { + cancel() + unittest.RequireCloseBefore(t, extendedIndexer.Done(), 5*time.Second, "timeout waiting for shutdown") + }) + + test.indexer.extendedIndexer = extendedIndexer + + test.events. + On("BatchStore", mocks.MatchLock(storage.LockInsertEvent), blockID, []flow.EventsList{tf.ExpectedEvents}, mock.Anything). + Return(nil) + test.results. + On("BatchStore", mocks.MatchLock(storage.LockInsertLightTransactionResult), mock.Anything, blockID, tf.ExpectedResults). + Return(nil) + test.registers. + On("Store", mock.Anything, tf.Block.Height). + Return(nil) + test.collectionIndexer.On("IndexCollections", tf.ExpectedCollections).Return(nil).Once() + for txID, scheduledTxID := range tf.ExpectedScheduledTransactions { + test.scheduledTransactions. + On("BatchIndex", mocks.MatchLock(storage.LockIndexScheduledTransaction), blockID, txID, scheduledTxID, mock.Anything). + Return(nil) + } + + err = test.indexer.IndexBlockData(tf.ExecutionDataEntity()) + require.NoError(t, err) + + // Wait for the async extended indexer to process the block + unittest.RequireCloseBefore(t, done, 5*time.Second, "timeout waiting for extended indexer") + assert.Equal(t, tf.Block.Height, gotHeight) + }) + + // test that account transactions are NOT indexed when accountTxIndex is nil + t.Run("Skip account transactions when disabled", func(t *testing.T) { + test := newIndexCoreTest(t, g, blocks, tf.ExecutionDataEntity()). + initIndexer() // Note: no useAccountTxIndex() + + test.events. + On("BatchStore", mocks.MatchLock(storage.LockInsertEvent), blockID, []flow.EventsList{tf.ExpectedEvents}, mock.Anything). + Return(nil) + test.results. + On("BatchStore", mocks.MatchLock(storage.LockInsertLightTransactionResult), mock.Anything, blockID, tf.ExpectedResults). + Return(nil) + test.registers. + On("Store", mock.Anything, tf.Block.Height). + Return(nil) + test.collectionIndexer.On("IndexCollections", tf.ExpectedCollections).Return(nil).Once() + for txID, scheduledTxID := range tf.ExpectedScheduledTransactions { + test.scheduledTransactions. + On("BatchIndex", mocks.MatchLock(storage.LockIndexScheduledTransaction), blockID, txID, scheduledTxID, mock.Anything). + Return(nil) + } + + // accountTxIndex.Store should NOT be called since it's nil + err := test.indexer.IndexBlockData(tf.ExecutionDataEntity()) assert.NoError(t, err) - assert.Equal(t, values, val) + }) + + // test that errors from the extended indexer are propagated via irrecoverable context + t.Run("Account transactions error propagation", func(t *testing.T) { + test := newIndexCoreTest(t, g, blocks, tf.ExecutionDataEntity()).initIndexer() + + startHeight := tf.Block.Height - 1 + expectedErr := errors.New("indexer failure") + stub := &testExtendedIndexer{ + name: "test", + latestHeight: startHeight, + indexBlockFn: func(data extended.BlockData) error { + return expectedErr + }, + } + + mockState := newMockStateForBlock(t, tf.Block) + extendedIndexer, err := extended.NewExtendedIndexer( + test.indexer.log, + metrics.NewNoopCollector(), + test.indexer.protocolDB, + storage.NewTestingLockManager(), + mockState, + storagemock.NewIndex(t), + storagemock.NewHeaders(t), + storagemock.NewGuarantees(t), + test.collections, + test.events, + test.results, + []extended.Indexer{stub}, + test.indexer.chainID, + extended.DefaultBackfillDelay, + ) + require.NoError(t, err) + + // Start the ExtendedIndexer with an error callback to capture thrown errors + thrown := make(chan error, 1) + ctx, cancel := context.WithCancel(context.Background()) + signalerCtx := irrecoverable.NewMockSignalerContextWithCallback(t, ctx, func(err error) { + thrown <- err + cancel() + }) + extendedIndexer.Start(signalerCtx) + unittest.RequireComponentsReadyBefore(t, 5*time.Second, extendedIndexer) + t.Cleanup(func() { + cancel() + }) + + test.indexer.extendedIndexer = extendedIndexer + + test.events. + On("BatchStore", mocks.MatchLock(storage.LockInsertEvent), blockID, []flow.EventsList{tf.ExpectedEvents}, mock.Anything). + Return(nil) + test.results. + On("BatchStore", mocks.MatchLock(storage.LockInsertLightTransactionResult), mock.Anything, blockID, tf.ExpectedResults). + Return(nil) + test.registers. + On("Store", mock.Anything, tf.Block.Height). + Return(nil) + test.collectionIndexer.On("IndexCollections", tf.ExpectedCollections).Return(nil).Once() + for txID, scheduledTxID := range tf.ExpectedScheduledTransactions { + test.scheduledTransactions. + On("BatchIndex", mocks.MatchLock(storage.LockIndexScheduledTransaction), blockID, txID, scheduledTxID, mock.Anything). + Return(nil) + } + + err = test.indexer.IndexBlockData(tf.ExecutionDataEntity()) + // IndexBlockData itself succeeds - the error is thrown asynchronously by the extended indexer + require.NoError(t, err) + + // Wait for the error to be thrown via irrecoverable context + select { + case err := <-thrown: + assert.ErrorIs(t, err, expectedErr) + case <-time.After(5 * time.Second): + t.Fatal("timeout waiting for error propagation") + } }) } @@ -409,10 +553,6 @@ func newBlockHeadersStorage(blocks []*flow.Block) storage.Headers { func TestIndexerIntegration_StoreAndGet(t *testing.T) { lockManager := storage.NewTestingLockManager() - regOwnerAddress := unittest.RandomAddressFixture() - regOwner := string(regOwnerAddress.Bytes()) - regKey := "code" - registerID := flow.NewRegisterID(regOwnerAddress, regKey) pdb, dbDir := unittest.TempPebbleDB(t) t.Cleanup(func() { @@ -425,117 +565,6 @@ func TestIndexerIntegration_StoreAndGet(t *testing.T) { derivedChainData, err := derived.NewDerivedChainData(derived.DefaultDerivedDataCacheSize) require.NoError(t, err) - // this test makes sure index values for a single register are correctly updated and always last value is returned - t.Run("Single Index Value Changes", func(t *testing.T) { - pebbleStorage.RunWithRegistersStorageAtInitialHeights(t, 0, 0, func(registers *pebbleStorage.Registers) { - index := New( - logger, - module.ExecutionStateIndexerMetrics(metrics), - pebbleimpl.ToDB(pdb), - registers, - nil, - nil, - nil, - nil, - nil, - nil, - flow.Testnet, - derivedChainData, - collectionsmock.NewCollectionIndexer(t), - nil, - lockManager, - ) - - values := [][]byte{[]byte("1"), []byte("1"), []byte("2"), []byte("3"), []byte("4")} - for i, val := range values { - testDesc := fmt.Sprintf("test iteration number %d failed with test value %s", i, val) - height := uint64(i + 1) - err := storeRegisterWithValue(index, height, regOwner, regKey, val) - require.NoError(t, err) - - results, err := index.RegisterValue(registerID, height) - require.NoError(t, err, testDesc) - assert.Equal(t, val, results) - } - }) - }) - - // this test makes sure if a register is not found the value returned is nil and without an error in order for this to be - // up to the specification script executor requires - t.Run("Missing Register", func(t *testing.T) { - pebbleStorage.RunWithRegistersStorageAtInitialHeights(t, 0, 0, func(registers *pebbleStorage.Registers) { - index := New( - logger, - module.ExecutionStateIndexerMetrics(metrics), - pebbleimpl.ToDB(pdb), - registers, - nil, - nil, - nil, - nil, - nil, - nil, - flow.Testnet, - derivedChainData, - collectionsmock.NewCollectionIndexer(t), - nil, - lockManager, - ) - - value, err := index.RegisterValue(registerID, 0) - require.Nil(t, value) - assert.NoError(t, err) - }) - }) - - // this test makes sure that even if indexed values for a single register are requested with higher height - // the correct highest height indexed value is returned. - // e.g. we index A{h(1) -> X}, A{h(2) -> Y}, when we request h(4) we get value Y - t.Run("Single Index Value At Later Heights", func(t *testing.T) { - pebbleStorage.RunWithRegistersStorageAtInitialHeights(t, 0, 0, func(registers *pebbleStorage.Registers) { - index := New( - logger, - module.ExecutionStateIndexerMetrics(metrics), - pebbleimpl.ToDB(pdb), - registers, - nil, - nil, - nil, - nil, - nil, - nil, - flow.Testnet, - derivedChainData, - collectionsmock.NewCollectionIndexer(t), - nil, - lockManager, - ) - - storeValues := [][]byte{[]byte("1"), []byte("2")} - - require.NoError(t, storeRegisterWithValue(index, 1, regOwner, regKey, storeValues[0])) - - require.NoError(t, index.indexRegisters(nil, 2)) - - value, err := index.RegisterValue(registerID, uint64(2)) - require.NoError(t, err) - assert.Equal(t, storeValues[0], value) - - require.NoError(t, index.indexRegisters(nil, 3)) - - err = storeRegisterWithValue(index, 4, regOwner, regKey, storeValues[1]) - require.NoError(t, err) - - value, err = index.RegisterValue(registerID, uint64(4)) - require.NoError(t, err) - assert.Equal(t, storeValues[1], value) - - value, err = index.RegisterValue(registerID, uint64(3)) - require.NoError(t, err) - assert.Equal(t, storeValues[0], value) - }) - }) - // this test makes sure we correctly handle weird payloads t.Run("Empty and Nil Payloads", func(t *testing.T) { pebbleStorage.RunWithRegistersStorageAtInitialHeights(t, 0, 0, func(registers *pebbleStorage.Registers) { @@ -555,6 +584,7 @@ func TestIndexerIntegration_StoreAndGet(t *testing.T) { collectionsmock.NewCollectionIndexer(t), nil, lockManager, + nil, // accountTxIndex ) require.NoError(t, index.indexRegisters(map[ledger.Path]*ledger.Payload{}, 1)) @@ -627,8 +657,32 @@ func TestCollectScheduledTransactions(t *testing.T) { }) } -// helper to store register at height and increment index range -func storeRegisterWithValue(indexer *IndexerCore, height uint64, owner string, key string, value []byte) error { - payload := LedgerPayloadFixture(owner, key, value) - return indexer.indexRegisters(map[ledger.Path]*ledger.Payload{ledger.DummyPath: payload}, height) +// newMockStateForBlock returns a mock protocol.State configured so that +// AtBlockID returns the block's header. +func newMockStateForBlock(t *testing.T, block *flow.Block) *protocolmock.State { + snapshot := protocolmock.NewSnapshot(t) + snapshot.On("Head").Return(block.ToHeader(), nil) + + state := protocolmock.NewState(t) + state.On("AtBlockID", block.ID()).Return(snapshot) + return state +} + +type testExtendedIndexer struct { + name string + latestHeight uint64 + indexBlockFn func(data extended.BlockData) error +} + +func (t *testExtendedIndexer) Name() string { return t.name } + +func (t *testExtendedIndexer) IndexBlockData(_ lockctx.Proof, data extended.BlockData, _ storage.ReaderBatchWriter) error { + if t.indexBlockFn != nil { + return t.indexBlockFn(data) + } + return nil +} + +func (t *testExtendedIndexer) NextHeight() (uint64, error) { + return t.latestHeight + 1, nil } diff --git a/module/state_synchronization/indexer/indexer_test.go b/module/state_synchronization/indexer/indexer_test.go index 202ae0fe099..1f25a67ab1f 100644 --- a/module/state_synchronization/indexer/indexer_test.go +++ b/module/state_synchronization/indexer/indexer_test.go @@ -83,7 +83,7 @@ func newIndexerTest(t *testing.T, g *fixtures.GeneratorSuite, blocks []*flow.Blo indexerCoreTest.indexer, exeCache, test.latestHeight, - &mockProgressInitializer{progress: progress}, + progress, ) require.NoError(t, err) @@ -119,14 +119,6 @@ func (w *indexerTest) run(ctx irrecoverable.SignalerContext, reachHeight uint64, unittest.RequireCloseBefore(w.t, w.worker.Done(), testTimeout, "timeout waiting for the consumer to be done") } -type mockProgressInitializer struct { - progress *mockProgress -} - -func (m *mockProgressInitializer) Initialize(defaultIndex uint64) (storage.ConsumerProgress, error) { - return m.progress, nil -} - var _ storage.ConsumerProgress = (*mockProgress)(nil) type mockProgress struct { diff --git a/module/state_synchronization/mock/execution_data_requester.go b/module/state_synchronization/mock/execution_data_requester.go index 40afda9ff30..12fa219a32e 100644 --- a/module/state_synchronization/mock/execution_data_requester.go +++ b/module/state_synchronization/mock/execution_data_requester.go @@ -1,40 +1,90 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataRequester creates a new instance of ExecutionDataRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataRequester(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataRequester { + mock := &ExecutionDataRequester{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataRequester is an autogenerated mock type for the ExecutionDataRequester type type ExecutionDataRequester struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *ExecutionDataRequester) Done() <-chan struct{} { - ret := _m.Called() +type ExecutionDataRequester_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionDataRequester) EXPECT() *ExecutionDataRequester_Expecter { + return &ExecutionDataRequester_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type ExecutionDataRequester +func (_mock *ExecutionDataRequester) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// HighestConsecutiveHeight provides a mock function with no fields -func (_m *ExecutionDataRequester) HighestConsecutiveHeight() (uint64, error) { - ret := _m.Called() +// ExecutionDataRequester_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type ExecutionDataRequester_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *ExecutionDataRequester_Expecter) Done() *ExecutionDataRequester_Done_Call { + return &ExecutionDataRequester_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *ExecutionDataRequester_Done_Call) Run(run func()) *ExecutionDataRequester_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataRequester_Done_Call) Return(valCh <-chan struct{}) *ExecutionDataRequester_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ExecutionDataRequester_Done_Call) RunAndReturn(run func() <-chan struct{}) *ExecutionDataRequester_Done_Call { + _c.Call.Return(run) + return _c +} + +// HighestConsecutiveHeight provides a mock function for the type ExecutionDataRequester +func (_mock *ExecutionDataRequester) HighestConsecutiveHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HighestConsecutiveHeight") @@ -42,59 +92,131 @@ func (_m *ExecutionDataRequester) HighestConsecutiveHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Ready provides a mock function with no fields -func (_m *ExecutionDataRequester) Ready() <-chan struct{} { - ret := _m.Called() +// ExecutionDataRequester_HighestConsecutiveHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HighestConsecutiveHeight' +type ExecutionDataRequester_HighestConsecutiveHeight_Call struct { + *mock.Call +} + +// HighestConsecutiveHeight is a helper method to define mock.On call +func (_e *ExecutionDataRequester_Expecter) HighestConsecutiveHeight() *ExecutionDataRequester_HighestConsecutiveHeight_Call { + return &ExecutionDataRequester_HighestConsecutiveHeight_Call{Call: _e.mock.On("HighestConsecutiveHeight")} +} + +func (_c *ExecutionDataRequester_HighestConsecutiveHeight_Call) Run(run func()) *ExecutionDataRequester_HighestConsecutiveHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionDataRequester_HighestConsecutiveHeight_Call) Return(v uint64, err error) *ExecutionDataRequester_HighestConsecutiveHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ExecutionDataRequester_HighestConsecutiveHeight_Call) RunAndReturn(run func() (uint64, error)) *ExecutionDataRequester_HighestConsecutiveHeight_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type ExecutionDataRequester +func (_mock *ExecutionDataRequester) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *ExecutionDataRequester) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// ExecutionDataRequester_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type ExecutionDataRequester_Ready_Call struct { + *mock.Call } -// NewExecutionDataRequester creates a new instance of ExecutionDataRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataRequester(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataRequester { - mock := &ExecutionDataRequester{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *ExecutionDataRequester_Expecter) Ready() *ExecutionDataRequester_Ready_Call { + return &ExecutionDataRequester_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ExecutionDataRequester_Ready_Call) Run(run func()) *ExecutionDataRequester_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *ExecutionDataRequester_Ready_Call) Return(valCh <-chan struct{}) *ExecutionDataRequester_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ExecutionDataRequester_Ready_Call) RunAndReturn(run func() <-chan struct{}) *ExecutionDataRequester_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type ExecutionDataRequester +func (_mock *ExecutionDataRequester) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// ExecutionDataRequester_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type ExecutionDataRequester_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *ExecutionDataRequester_Expecter) Start(signalerContext interface{}) *ExecutionDataRequester_Start_Call { + return &ExecutionDataRequester_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *ExecutionDataRequester_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *ExecutionDataRequester_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionDataRequester_Start_Call) Return() *ExecutionDataRequester_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *ExecutionDataRequester_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *ExecutionDataRequester_Start_Call { + _c.Run(run) + return _c } diff --git a/module/state_synchronization/mock/index_reporter.go b/module/state_synchronization/mock/index_reporter.go index bbf6138cd64..623c5c0ca3e 100644 --- a/module/state_synchronization/mock/index_reporter.go +++ b/module/state_synchronization/mock/index_reporter.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewIndexReporter creates a new instance of IndexReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIndexReporter(t interface { + mock.TestingT + Cleanup(func()) +}) *IndexReporter { + mock := &IndexReporter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // IndexReporter is an autogenerated mock type for the IndexReporter type type IndexReporter struct { mock.Mock } -// HighestIndexedHeight provides a mock function with no fields -func (_m *IndexReporter) HighestIndexedHeight() (uint64, error) { - ret := _m.Called() +type IndexReporter_Expecter struct { + mock *mock.Mock +} + +func (_m *IndexReporter) EXPECT() *IndexReporter_Expecter { + return &IndexReporter_Expecter{mock: &_m.Mock} +} + +// HighestIndexedHeight provides a mock function for the type IndexReporter +func (_mock *IndexReporter) HighestIndexedHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HighestIndexedHeight") @@ -19,27 +45,52 @@ func (_m *IndexReporter) HighestIndexedHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// LowestIndexedHeight provides a mock function with no fields -func (_m *IndexReporter) LowestIndexedHeight() (uint64, error) { - ret := _m.Called() +// IndexReporter_HighestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HighestIndexedHeight' +type IndexReporter_HighestIndexedHeight_Call struct { + *mock.Call +} + +// HighestIndexedHeight is a helper method to define mock.On call +func (_e *IndexReporter_Expecter) HighestIndexedHeight() *IndexReporter_HighestIndexedHeight_Call { + return &IndexReporter_HighestIndexedHeight_Call{Call: _e.mock.On("HighestIndexedHeight")} +} + +func (_c *IndexReporter_HighestIndexedHeight_Call) Run(run func()) *IndexReporter_HighestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IndexReporter_HighestIndexedHeight_Call) Return(v uint64, err error) *IndexReporter_HighestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *IndexReporter_HighestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *IndexReporter_HighestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LowestIndexedHeight provides a mock function for the type IndexReporter +func (_mock *IndexReporter) LowestIndexedHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LowestIndexedHeight") @@ -47,34 +98,45 @@ func (_m *IndexReporter) LowestIndexedHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewIndexReporter creates a new instance of IndexReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIndexReporter(t interface { - mock.TestingT - Cleanup(func()) -}) *IndexReporter { - mock := &IndexReporter{} - mock.Mock.Test(t) +// IndexReporter_LowestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LowestIndexedHeight' +type IndexReporter_LowestIndexedHeight_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// LowestIndexedHeight is a helper method to define mock.On call +func (_e *IndexReporter_Expecter) LowestIndexedHeight() *IndexReporter_LowestIndexedHeight_Call { + return &IndexReporter_LowestIndexedHeight_Call{Call: _e.mock.On("LowestIndexedHeight")} +} - return mock +func (_c *IndexReporter_LowestIndexedHeight_Call) Run(run func()) *IndexReporter_LowestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IndexReporter_LowestIndexedHeight_Call) Return(v uint64, err error) *IndexReporter_LowestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *IndexReporter_LowestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *IndexReporter_LowestIndexedHeight_Call { + _c.Call.Return(run) + return _c } diff --git a/module/state_synchronization/requester/execution_data_requester.go b/module/state_synchronization/requester/execution_data_requester.go index 6a7bb409728..234d34b1cb2 100644 --- a/module/state_synchronization/requester/execution_data_requester.go +++ b/module/state_synchronization/requester/execution_data_requester.go @@ -146,8 +146,8 @@ func New( edrMetrics module.ExecutionDataRequesterMetrics, downloader execution_data.Downloader, execDataCache *cache.ExecutionDataCache, - processedHeight storage.ConsumerProgressInitializer, - processedNotifications storage.ConsumerProgressInitializer, + processedHeight storage.ConsumerProgress, + processedNotifications storage.ConsumerProgress, state protocol.State, headers storage.Headers, cfg ExecutionDataConfig, @@ -186,7 +186,6 @@ func New( e.finalizationNotifier.Channel(), // to listen to finalization events to find newly sealed blocks processedHeight, // read and persist the downloaded height sealedBlockReader, // read sealed blocks by height - e.config.InitialBlockHeight, // initial "last processed" height for empty db e.processBlockJob, // process the sealed block job to download its execution data fetchWorkers, // the number of concurrent workers e.config.MaxSearchAhead, // max number of unsent notifications to allow before pausing new fetches @@ -233,7 +232,6 @@ func New( executionDataNotifier.Channel(), // listen for notifications from the block consumer processedNotifications, // read and persist the notified height e.executionDataReader, // read execution data by height - e.config.InitialBlockHeight, // initial "last processed" height for empty db e.processNotificationJob, // process the job to send notifications for an execution data 1, // use a single worker to ensure notification is delivered in consecutive order 0, // search ahead limit controlled by worker count diff --git a/module/state_synchronization/requester/execution_data_requester_test.go b/module/state_synchronization/requester/execution_data_requester_test.go index e90405a7f0b..4bf9607c85f 100644 --- a/module/state_synchronization/requester/execution_data_requester_test.go +++ b/module/state_synchronization/requester/execution_data_requester_test.go @@ -412,8 +412,10 @@ func (suite *ExecutionDataRequesterSuite) prepareRequesterTest(cfg *fetchTestRun edCache := cache.NewExecutionDataCache(suite.downloader, headers, seals, results, heroCache) followerDistributor := pubsub.NewFollowerDistributor() - processedHeight := store.NewConsumerProgress(pebbleimpl.ToDB(suite.db), module.ConsumeProgressExecutionDataRequesterBlockHeight) - processedNotification := store.NewConsumerProgress(pebbleimpl.ToDB(suite.db), module.ConsumeProgressExecutionDataRequesterNotification) + processedHeight, err := store.NewConsumerProgress(pebbleimpl.ToDB(suite.db), module.ConsumeProgressExecutionDataRequesterBlockHeight).Initialize(cfg.startHeight - 1) + suite.Require().NoError(err) + processedNotification, err := store.NewConsumerProgress(pebbleimpl.ToDB(suite.db), module.ConsumeProgressExecutionDataRequesterNotification).Initialize(cfg.startHeight - 1) + suite.Require().NoError(err) edr, err := New( logger, diff --git a/module/state_synchronization/requester/mock/execution_data_requester.go b/module/state_synchronization/requester/mock/execution_data_requester.go index f4ca43a1ef1..b74937924a4 100644 --- a/module/state_synchronization/requester/mock/execution_data_requester.go +++ b/module/state_synchronization/requester/mock/execution_data_requester.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - execution_data "github.com/onflow/flow-go/module/executiondatasync/execution_data" + "github.com/onflow/flow-go/module/executiondatasync/execution_data" mock "github.com/stretchr/testify/mock" ) +// NewExecutionDataRequester creates a new instance of ExecutionDataRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionDataRequester(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionDataRequester { + mock := &ExecutionDataRequester{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionDataRequester is an autogenerated mock type for the ExecutionDataRequester type type ExecutionDataRequester struct { mock.Mock } -// RequestExecutionData provides a mock function with given fields: ctx -func (_m *ExecutionDataRequester) RequestExecutionData(ctx context.Context) (*execution_data.BlockExecutionData, error) { - ret := _m.Called(ctx) +type ExecutionDataRequester_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionDataRequester) EXPECT() *ExecutionDataRequester_Expecter { + return &ExecutionDataRequester_Expecter{mock: &_m.Mock} +} + +// RequestExecutionData provides a mock function for the type ExecutionDataRequester +func (_mock *ExecutionDataRequester) RequestExecutionData(ctx context.Context) (*execution_data.BlockExecutionData, error) { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for RequestExecutionData") @@ -24,36 +48,54 @@ func (_m *ExecutionDataRequester) RequestExecutionData(ctx context.Context) (*ex var r0 *execution_data.BlockExecutionData var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*execution_data.BlockExecutionData, error)); ok { - return rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) (*execution_data.BlockExecutionData, error)); ok { + return returnFunc(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) *execution_data.BlockExecutionData); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) *execution_data.BlockExecutionData); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*execution_data.BlockExecutionData) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(ctx) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionDataRequester creates a new instance of ExecutionDataRequester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionDataRequester(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionDataRequester { - mock := &ExecutionDataRequester{} - mock.Mock.Test(t) +// ExecutionDataRequester_RequestExecutionData_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestExecutionData' +type ExecutionDataRequester_RequestExecutionData_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RequestExecutionData is a helper method to define mock.On call +// - ctx context.Context +func (_e *ExecutionDataRequester_Expecter) RequestExecutionData(ctx interface{}) *ExecutionDataRequester_RequestExecutionData_Call { + return &ExecutionDataRequester_RequestExecutionData_Call{Call: _e.mock.On("RequestExecutionData", ctx)} +} - return mock +func (_c *ExecutionDataRequester_RequestExecutionData_Call) Run(run func(ctx context.Context)) *ExecutionDataRequester_RequestExecutionData_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionDataRequester_RequestExecutionData_Call) Return(blockExecutionData *execution_data.BlockExecutionData, err error) *ExecutionDataRequester_RequestExecutionData_Call { + _c.Call.Return(blockExecutionData, err) + return _c +} + +func (_c *ExecutionDataRequester_RequestExecutionData_Call) RunAndReturn(run func(ctx context.Context) (*execution_data.BlockExecutionData, error)) *ExecutionDataRequester_RequestExecutionData_Call { + _c.Call.Return(run) + return _c } diff --git a/module/state_synchronization/requester/unittest/unittest.go b/module/state_synchronization/requester/unittest/unittest.go index fd350ffd444..d403ad2781b 100644 --- a/module/state_synchronization/requester/unittest/unittest.go +++ b/module/state_synchronization/requester/unittest/unittest.go @@ -29,7 +29,6 @@ func MockBlobService(bs blockstore.Blockstore) *mocknetwork.BlobService { wg.Add(len(cids)) for _, c := range cids { - c := c go func() { defer wg.Done() diff --git a/module/trace/trace_test.go b/module/trace/trace_test.go index f1011589930..be5ca1f3f2a 100644 --- a/module/trace/trace_test.go +++ b/module/trace/trace_test.go @@ -43,7 +43,6 @@ func BenchmarkStartBlockSpan(b *testing.B) { {name: "cacheHit", n: 100}, {name: "cacheMiss", n: 100000}, } { - t := t b.Run(t.name, func(b *testing.B) { randomIDs := make([]flow.Identifier, 0, t.n) for i := 0; i < t.n; i++ { diff --git a/module/upstream/upstream_connector.go b/module/upstream/upstream_connector.go index db8843cd619..506d7d23d9a 100644 --- a/module/upstream/upstream_connector.go +++ b/module/upstream/upstream_connector.go @@ -53,9 +53,7 @@ func (connector *upstreamConnector) Ready() <-chan struct{} { // spawn a connect worker for each bootstrap node for _, b := range connector.bootstrapIdentities { id := *b - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { lg := connector.logger.With().Str("bootstrap_node", id.NodeID.String()).Logger() backoff := retry.NewFibonacci(connector.retryInitialTimeout) @@ -69,7 +67,7 @@ func (connector *upstreamConnector) Ready() <-chan struct{} { lg.Info().Msg("successfully connected to bootstrap node") success.Store(true) } - }() + }) } wg.Wait() diff --git a/module/util/log_test.go b/module/util/log_test.go index da9f96fcace..6acc30b4441 100644 --- a/module/util/log_test.go +++ b/module/util/log_test.go @@ -26,7 +26,7 @@ func TestLogProgress40(t *testing.T) { total, ), ) - for i := 0; i < total; i++ { + for range total { logger(1) } @@ -99,7 +99,7 @@ func TestLogProgress43B(t *testing.T) { total, ), ) - for i := 0; i < total; i++ { + for range total { logger(1) } @@ -231,7 +231,7 @@ func TestLogProgressWhenTotalIs0(t *testing.T) { ), ) - for i := 0; i < 10; i++ { + for range 10 { logger(1) } @@ -261,7 +261,7 @@ func TestLogProgressMoreTicksThenTotal(t *testing.T) { ), ) - for i := 0; i < 5; i++ { + for range 5 { logger(1) } @@ -291,7 +291,7 @@ func TestLogProgressContinueLoggingAfter100(t *testing.T) { ), ) - for i := 0; i < 15; i++ { + for range 15 { logger(10) } @@ -327,7 +327,7 @@ func TestLogProgressNoDataForAWhile(t *testing.T) { ), ) - for i := 0; i < total; i++ { + for i := range total { // somewhere in the middle pause for a bit if i == 13 { <-time.After(3 * time.Millisecond) @@ -365,14 +365,12 @@ func TestLogProgressMultipleGoroutines(t *testing.T) { ) wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - for j := 0; j < 100; j++ { + for range 10 { + wg.Go(func() { + for range 100 { logger(1) } - }() + }) } wg.Wait() diff --git a/module/util/util.go b/module/util/util.go index 55a24fc19d1..c216aad1f41 100644 --- a/module/util/util.go +++ b/module/util/util.go @@ -87,7 +87,7 @@ func CheckClosed(done <-chan struct{}) bool { } // MergeChannels merges a list of channels into a single channel -func MergeChannels(channels interface{}) interface{} { +func MergeChannels(channels any) any { sliceType := reflect.TypeOf(channels) if sliceType.Kind() != reflect.Slice && sliceType.Kind() != reflect.Array { panic("argument must be an array or slice") diff --git a/module/validation/seal_validator.go b/module/validation/seal_validator.go index c6c5341a97e..229464afb13 100644 --- a/module/validation/seal_validator.go +++ b/module/validation/seal_validator.go @@ -8,6 +8,7 @@ import ( "github.com/onflow/flow-go/engine" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" + "github.com/onflow/flow-go/module/irrecoverable" "github.com/onflow/flow-go/module/signature" "github.com/onflow/flow-go/state/fork" "github.com/onflow/flow-go/state/protocol" @@ -241,18 +242,39 @@ func (s *sealValidator) Validate(candidate *flow.Block) (*flow.Seal, error) { return latestSeal, nil } -// validateSeal performs integrity checks of single seal. To be valid, we -// require that seal: -// 1) Contains correct number of approval signatures, one aggregated sig for each chunk. -// 2) Every aggregated signature contains valid signer ids. module.ChunkAssigner is used to perform this check. -// 3) Every aggregated signature contains valid signatures. +// validateSeal performs integrity checks of single seal. To be valid, we require that the seal: +// 1. `Seal.FinalState` is equal to the final state as committed to by the sealed execution result. +// 2. Contains correct number of approval signatures, one aggregated sig for each chunk. +// 3. Every aggregated signature contains valid signer ids. `module.ChunkAssigner` is used to perform this check. +// 4. Every aggregated signature contains valid signatures. +// // Returns: -// * nil - in case of success -// * engine.InvalidInputError - in case of malformed seal -// * exception - in case of unexpected error +// - nil - in case of success +// - engine.InvalidInputError - in case of malformed seal +// - exception - in case of unexpected error func (s *sealValidator) validateSeal(seal *flow.Seal, incorporatedResult *flow.IncorporatedResult) error { executionResult := incorporatedResult.Result + // Check that `Seal.FinalState` equals the final state of the execution result, i.e. the last chunk's `EndState`, returned by + // `executionResult.FinalStateCommitment()`. `Seal.FinalState` is a redundant copy of that value, included so that callers such as + // `Snapshot.Commit` can read the sealed state commitment directly from the seal without looking up the execution result. The verifier + // signatures are computed over the fields `{chunk.BlockID, ExecutionResultID, chunk.Index}` for each chunk in the execution result, + // so tampering with those fields in the seal would invalidate verifier signatures in seal, which is caught when checking those + // verifier signatures. Verifiers check the `IncorporatedResult` while consensus nodes check the correct construction of the seal for + // the `IncorporatedResult`. So the only remaining field that a Byzantine proposer could tamper with is the `Seal.FinalState`. We check + // this field first before the per-chunk work, because the check is cheap. But formally, there is no order dependence of the checks. + expectedFinalState, err := executionResult.FinalStateCommitment() + if err != nil { + // `FinalStateCommitment` is documented to fail only with `flow.ErrNoChunks`. That error cannot occur here: `incorporatedResult.Result` + // was loaded from local storage after being incorporated in an ancestor of the candidate block (not the candidate itself), so + // `ReceiptValidator.verifyChunksFormat` has already enforced `Chunks.Len() ≥ 1` (the system chunk is mandatory). Any error observed here + // therefore indicates a bug or storage corruption. + return irrecoverable.NewExceptionf("could not derive final state commitment for execution result %x: %w", executionResult.ID(), err) + } + if seal.FinalState != expectedFinalState { + return engine.NewInvalidInputErrorf("seal's final state %x does not match execution result (final state %x)", seal.FinalState, expectedFinalState) + } + // check that each chunk has an AggregatedSignature if len(seal.AggregatedApprovalSigs) != executionResult.Chunks.Len() { return engine.NewInvalidInputErrorf("mismatching signatures, expected: %d, got: %d", diff --git a/module/validation/seal_validator_test.go b/module/validation/seal_validator_test.go index f88d98f4e21..e396418aaa5 100644 --- a/module/validation/seal_validator_test.go +++ b/module/validation/seal_validator_test.go @@ -272,6 +272,49 @@ func (s *SealValidationSuite) TestSealDuplicatedApproval() { s.Require().True(engine.IsInvalidInputError(err)) } +// TestSealInvalidFinalState verifies that we reject a seal whose `FinalState` does not equal the +// final state from the sealed execution result (i.e. the last chunk's `EndState`). +// +// Background: `Seal.FinalState` is an auxiliary field whose value is supposed to copied from the +// sealed `ExecutionResult` (specifically `executionResult.FinalStateCommitment()`). The verifier +// attestations only cover `{BlockID, ExecutionResultID, ChunkIndex}` from the execution result. +// Verifiers do _not_ commit to `Seal.FinalState`. Without an explicit check by consensus nodes in +// the seal validator, a Byzantine consensus node could propose a block payload with valid aggregated +// approvals for a real incorporated execution result but set `Seal.FinalState` to an arbitrary non-empty +// value. The downstream `Snapshot.Commit` would then expose the poisoned commitment as the sealed state. +// +// We test with the following fork: +// +// ... <- LatestSealedBlock <- B0 <- B1{ Result[B0], Receipt[B0] } <- B2 <- ░newBlock{ Seal[B0]}░ +// +// The gap of 1 block, i.e. B2, is required to avoid a sealing edge-case +// (see test `TestSeal_EnforceGap` for more details). +func (s *SealValidationSuite) TestSealInvalidFinalState() { + _, _, newBlock, receipt, seal := s.generateBasicTestFork() + + // Sanity check for correct testing setup: the fixture's seal must agree with the execution result's final state. + // This guarantees that the subsequent mutation below is the _only_ deviation between the seal and the result. + expectedFinalState, err := receipt.ExecutionResult.FinalStateCommitment() + s.Require().NoError(err) + s.Require().Equal(expectedFinalState, seal.FinalState) + + // Attack Details: The Byzantine proposer publishes `newBlock` containing a seal for B0. The byzantine proposer complies with the + // protocol in that it includes the required number of valid verifier signatures in the seal. It truthfully sets all fields in the + // seal that are covered by the verifier signatures (BlockID, ResultID, ChunkIndex, AggregatedApprovalSigs), to not invalidate the + // aggregated verifier signatures. However, while the protocol mandates that `Seal.FinalState` is set to the `FinalStateCommitment` + // of the execution result previously incorporated in the fork, the byzantine proposer chooses a conflicting value. + // To mount such an attack, the proposer would build (and sign) their proposal with the poisoned `Seal.FinalState` from the start. + // The test takes the shortcut of mutating `Seal.FinalState` in place because `sealValidator.Validate` only inspects the block + // payload; proposer signatures will have been checked in production by the compliance layer before (which we omit here). + seal.FinalState[0] ^= 0xff // bitwise XOR with `0xFF`: inverts all bits + s.Require().NotEqual(flow.EmptyStateCommitment, seal.FinalState) // remains non-empty (NewSeal precondition) + s.Require().NotEqual(expectedFinalState, seal.FinalState) + + _, err = s.sealValidator.Validate(newBlock) + s.Require().Error(err) + s.Require().True(engine.IsInvalidInputError(err), err) +} + // TestSealInvalidChunkAssignment tests that we reject seal with invalid signerID of approval signature for // submitted seal. We test with the following fork: // diff --git a/network/alsp/manager/manager.go b/network/alsp/manager/manager.go index 6a7bf856411..8b5b37680dd 100644 --- a/network/alsp/manager/manager.go +++ b/network/alsp/manager/manager.go @@ -198,7 +198,7 @@ func NewMisbehaviorReportManager(cfg *MisbehaviorReportManagerConfig, consumer n ready() m.heartbeatLoop(ctx, cfg.HeartBeatInterval) // blocking call }) - for i := 0; i < defaultMisbehaviorReportManagerWorkers; i++ { + for range defaultMisbehaviorReportManagerWorkers { builder.AddWorker(m.workerPool.WorkerLogic()) } diff --git a/network/alsp/manager/manager_test.go b/network/alsp/manager/manager_test.go index 223a7a3f5fb..0a2a60aaef2 100644 --- a/network/alsp/manager/manager_test.go +++ b/network/alsp/manager/manager_test.go @@ -501,7 +501,7 @@ func TestHandleReportedMisbehavior_And_SlashingViolationsConsumer_Integration(t violationsConsumerFunc func(violation *network.Violation) violation *network.Violation }{ - {violationsConsumer.OnUnAuthorizedSenderError, &network.Violation{Identity: ids[invalidMessageIndex]}}, + {violationsConsumer.OnUnauthorizedSenderError, &network.Violation{Identity: ids[invalidMessageIndex]}}, {violationsConsumer.OnSenderEjectedError, &network.Violation{Identity: ids[senderEjectedIndex]}}, {violationsConsumer.OnUnauthorizedUnicastOnChannel, &network.Violation{Identity: ids[unauthorizedUnicastOnChannelIndex]}}, {violationsConsumer.OnUnauthorizedPublishOnChannel, &network.Violation{Identity: ids[unauthorizedPublishOnChannelIndex]}}, diff --git a/network/alsp/mock/spam_record_cache.go b/network/alsp/mock/spam_record_cache.go index 695611278d3..d218ade9afd 100644 --- a/network/alsp/mock/spam_record_cache.go +++ b/network/alsp/mock/spam_record_cache.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/alsp/model" mock "github.com/stretchr/testify/mock" - - model "github.com/onflow/flow-go/network/alsp/model" ) +// NewSpamRecordCache creates a new instance of SpamRecordCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSpamRecordCache(t interface { + mock.TestingT + Cleanup(func()) +}) *SpamRecordCache { + mock := &SpamRecordCache{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SpamRecordCache is an autogenerated mock type for the SpamRecordCache type type SpamRecordCache struct { mock.Mock } -// AdjustWithInit provides a mock function with given fields: originId, adjustFunc -func (_m *SpamRecordCache) AdjustWithInit(originId flow.Identifier, adjustFunc model.RecordAdjustFunc) (float64, error) { - ret := _m.Called(originId, adjustFunc) +type SpamRecordCache_Expecter struct { + mock *mock.Mock +} + +func (_m *SpamRecordCache) EXPECT() *SpamRecordCache_Expecter { + return &SpamRecordCache_Expecter{mock: &_m.Mock} +} + +// AdjustWithInit provides a mock function for the type SpamRecordCache +func (_mock *SpamRecordCache) AdjustWithInit(originId flow.Identifier, adjustFunc model.RecordAdjustFunc) (float64, error) { + ret := _mock.Called(originId, adjustFunc) if len(ret) == 0 { panic("no return value specified for AdjustWithInit") @@ -24,27 +47,65 @@ func (_m *SpamRecordCache) AdjustWithInit(originId flow.Identifier, adjustFunc m var r0 float64 var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, model.RecordAdjustFunc) (float64, error)); ok { - return rf(originId, adjustFunc) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, model.RecordAdjustFunc) (float64, error)); ok { + return returnFunc(originId, adjustFunc) } - if rf, ok := ret.Get(0).(func(flow.Identifier, model.RecordAdjustFunc) float64); ok { - r0 = rf(originId, adjustFunc) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, model.RecordAdjustFunc) float64); ok { + r0 = returnFunc(originId, adjustFunc) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(flow.Identifier, model.RecordAdjustFunc) error); ok { - r1 = rf(originId, adjustFunc) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, model.RecordAdjustFunc) error); ok { + r1 = returnFunc(originId, adjustFunc) } else { r1 = ret.Error(1) } - return r0, r1 } -// Get provides a mock function with given fields: originId -func (_m *SpamRecordCache) Get(originId flow.Identifier) (*model.ProtocolSpamRecord, bool) { - ret := _m.Called(originId) +// SpamRecordCache_AdjustWithInit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AdjustWithInit' +type SpamRecordCache_AdjustWithInit_Call struct { + *mock.Call +} + +// AdjustWithInit is a helper method to define mock.On call +// - originId flow.Identifier +// - adjustFunc model.RecordAdjustFunc +func (_e *SpamRecordCache_Expecter) AdjustWithInit(originId interface{}, adjustFunc interface{}) *SpamRecordCache_AdjustWithInit_Call { + return &SpamRecordCache_AdjustWithInit_Call{Call: _e.mock.On("AdjustWithInit", originId, adjustFunc)} +} + +func (_c *SpamRecordCache_AdjustWithInit_Call) Run(run func(originId flow.Identifier, adjustFunc model.RecordAdjustFunc)) *SpamRecordCache_AdjustWithInit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 model.RecordAdjustFunc + if args[1] != nil { + arg1 = args[1].(model.RecordAdjustFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SpamRecordCache_AdjustWithInit_Call) Return(f float64, err error) *SpamRecordCache_AdjustWithInit_Call { + _c.Call.Return(f, err) + return _c +} + +func (_c *SpamRecordCache_AdjustWithInit_Call) RunAndReturn(run func(originId flow.Identifier, adjustFunc model.RecordAdjustFunc) (float64, error)) *SpamRecordCache_AdjustWithInit_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type SpamRecordCache +func (_mock *SpamRecordCache) Get(originId flow.Identifier) (*model.ProtocolSpamRecord, bool) { + ret := _mock.Called(originId) if len(ret) == 0 { panic("no return value specified for Get") @@ -52,92 +113,195 @@ func (_m *SpamRecordCache) Get(originId flow.Identifier) (*model.ProtocolSpamRec var r0 *model.ProtocolSpamRecord var r1 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) (*model.ProtocolSpamRecord, bool)); ok { - return rf(originId) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*model.ProtocolSpamRecord, bool)); ok { + return returnFunc(originId) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *model.ProtocolSpamRecord); ok { - r0 = rf(originId) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *model.ProtocolSpamRecord); ok { + r0 = returnFunc(originId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.ProtocolSpamRecord) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) bool); ok { - r1 = rf(originId) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) bool); ok { + r1 = returnFunc(originId) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Identities provides a mock function with no fields -func (_m *SpamRecordCache) Identities() []flow.Identifier { - ret := _m.Called() +// SpamRecordCache_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type SpamRecordCache_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - originId flow.Identifier +func (_e *SpamRecordCache_Expecter) Get(originId interface{}) *SpamRecordCache_Get_Call { + return &SpamRecordCache_Get_Call{Call: _e.mock.On("Get", originId)} +} + +func (_c *SpamRecordCache_Get_Call) Run(run func(originId flow.Identifier)) *SpamRecordCache_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SpamRecordCache_Get_Call) Return(protocolSpamRecord *model.ProtocolSpamRecord, b bool) *SpamRecordCache_Get_Call { + _c.Call.Return(protocolSpamRecord, b) + return _c +} + +func (_c *SpamRecordCache_Get_Call) RunAndReturn(run func(originId flow.Identifier) (*model.ProtocolSpamRecord, bool)) *SpamRecordCache_Get_Call { + _c.Call.Return(run) + return _c +} + +// Identities provides a mock function for the type SpamRecordCache +func (_mock *SpamRecordCache) Identities() []flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Identities") } var r0 []flow.Identifier - if rf, ok := ret.Get(0).(func() []flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Identifier) } } - return r0 } -// Remove provides a mock function with given fields: originId -func (_m *SpamRecordCache) Remove(originId flow.Identifier) bool { - ret := _m.Called(originId) +// SpamRecordCache_Identities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Identities' +type SpamRecordCache_Identities_Call struct { + *mock.Call +} + +// Identities is a helper method to define mock.On call +func (_e *SpamRecordCache_Expecter) Identities() *SpamRecordCache_Identities_Call { + return &SpamRecordCache_Identities_Call{Call: _e.mock.On("Identities")} +} + +func (_c *SpamRecordCache_Identities_Call) Run(run func()) *SpamRecordCache_Identities_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SpamRecordCache_Identities_Call) Return(identifiers []flow.Identifier) *SpamRecordCache_Identities_Call { + _c.Call.Return(identifiers) + return _c +} + +func (_c *SpamRecordCache_Identities_Call) RunAndReturn(run func() []flow.Identifier) *SpamRecordCache_Identities_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type SpamRecordCache +func (_mock *SpamRecordCache) Remove(originId flow.Identifier) bool { + ret := _mock.Called(originId) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 bool - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(originId) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(originId) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Size provides a mock function with no fields -func (_m *SpamRecordCache) Size() uint { - ret := _m.Called() +// SpamRecordCache_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type SpamRecordCache_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - originId flow.Identifier +func (_e *SpamRecordCache_Expecter) Remove(originId interface{}) *SpamRecordCache_Remove_Call { + return &SpamRecordCache_Remove_Call{Call: _e.mock.On("Remove", originId)} +} + +func (_c *SpamRecordCache_Remove_Call) Run(run func(originId flow.Identifier)) *SpamRecordCache_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SpamRecordCache_Remove_Call) Return(b bool) *SpamRecordCache_Remove_Call { + _c.Call.Return(b) + return _c +} + +func (_c *SpamRecordCache_Remove_Call) RunAndReturn(run func(originId flow.Identifier) bool) *SpamRecordCache_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type SpamRecordCache +func (_mock *SpamRecordCache) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewSpamRecordCache creates a new instance of SpamRecordCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSpamRecordCache(t interface { - mock.TestingT - Cleanup(func()) -}) *SpamRecordCache { - mock := &SpamRecordCache{} - mock.Mock.Test(t) +// SpamRecordCache_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type SpamRecordCache_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *SpamRecordCache_Expecter) Size() *SpamRecordCache_Size_Call { + return &SpamRecordCache_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *SpamRecordCache_Size_Call) Run(run func()) *SpamRecordCache_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SpamRecordCache_Size_Call) Return(v uint) *SpamRecordCache_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *SpamRecordCache_Size_Call) RunAndReturn(run func() uint) *SpamRecordCache_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/network/channels/channel.go b/network/channels/channel.go index bbc3d24e868..a30c649f928 100644 --- a/network/channels/channel.go +++ b/network/channels/channel.go @@ -2,6 +2,7 @@ package channels import ( "regexp" + "slices" ) // Channel specifies a virtual and isolated communication medium. @@ -35,12 +36,7 @@ func (cl ChannelList) Swap(i, j int) { // Contains returns true if the ChannelList contains the given channel. func (cl ChannelList) Contains(channel Channel) bool { - for _, c := range cl { - if c == channel { - return true - } - } - return false + return slices.Contains(cl, channel) } // ExcludeChannels returns list of channels that are in the ChannelList but not in the other list. diff --git a/network/channels/channels.go b/network/channels/channels.go index 5cd3790a665..3f858c15548 100644 --- a/network/channels/channels.go +++ b/network/channels/channels.go @@ -2,6 +2,7 @@ package channels import ( "fmt" + "slices" "strings" "github.com/onflow/flow-go/model/flow" @@ -337,6 +338,20 @@ func SyncCluster(clusterID flow.ChainID) Channel { return Channel(fmt.Sprintf("%s-%s", SyncClusterPrefix, clusterID)) } +// NormalizeTopicForMetrics returns a normalized version of the topic suitable for use as a metrics label. +// For cluster topics (sync-cluster-*, consensus-cluster-*), it returns just the prefix to prevent +// unbounded cardinality growth during epoch transitions (each epoch creates new cluster IDs). +// For non-cluster topics, it returns the topic unchanged. +func NormalizeTopicForMetrics(topic string) string { + if strings.HasPrefix(topic, SyncClusterPrefix) { + return SyncClusterPrefix + } + if strings.HasPrefix(topic, ConsensusClusterPrefix) { + return ConsensusClusterPrefix + } + return topic +} + // IsValidNonClusterFlowTopic ensures the topic is a valid Flow network topic and // ensures the sporkID part of the Topic is equal to the current network sporkID. // Expected errors: @@ -371,10 +386,8 @@ func IsValidFlowClusterTopic(topic Topic, activeClusterIDS flow.ChainIDList) err return NewInvalidTopicErr(topic, fmt.Errorf("failed to get cluster ID from topic: %w", err)) } - for _, activeClusterID := range activeClusterIDS { - if clusterID == activeClusterID { - return nil - } + if slices.Contains(activeClusterIDS, clusterID) { + return nil } return NewUnknownClusterIdErr(clusterID, activeClusterIDS) diff --git a/network/channels/channels_test.go b/network/channels/channels_test.go index 37b2ca6c811..2e07466683a 100644 --- a/network/channels/channels_test.go +++ b/network/channels/channels_test.go @@ -129,3 +129,57 @@ func TestUniqueChannels_ClusterChannels(t *testing.T) { require.Contains(t, uniques, consensusCluster) // cluster channel require.Contains(t, uniques, PushTransactions) // non-cluster channel } + +// TestNormalizeTopicForMetrics verifies that cluster topics are normalized to their prefix +// (e.g., "sync-cluster-*" -> "sync-cluster") while non-cluster topics remain unchanged. +// This prevents unbounded metric cardinality growth during epoch transitions. +func TestNormalizeTopicForMetrics(t *testing.T) { + testCases := []struct { + name string + inputTopic string + expectedOutput string + }{ + { + name: "sync-cluster topic normalized", + inputTopic: "sync-cluster-cluster-123-abc123def456", + expectedOutput: SyncClusterPrefix, + }, + { + name: "consensus-cluster topic normalized", + inputTopic: "consensus-cluster-cluster-456-def789abc123", + expectedOutput: ConsensusClusterPrefix, + }, + { + name: "sync-cluster topic with different format normalized", + inputTopic: "sync-cluster-test-id", + expectedOutput: SyncClusterPrefix, + }, + { + name: "consensus-cluster topic with different format normalized", + inputTopic: "consensus-cluster-test-id", + expectedOutput: ConsensusClusterPrefix, + }, + { + name: "non-cluster topic unchanged", + inputTopic: "push-blocks/abc123", + expectedOutput: "push-blocks/abc123", + }, + { + name: "another non-cluster topic unchanged", + inputTopic: "consensus-committee/xyz789", + expectedOutput: "consensus-committee/xyz789", + }, + { + name: "empty string unchanged", + inputTopic: "", + expectedOutput: "", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result := NormalizeTopicForMetrics(tc.inputTopic) + assert.Equal(t, tc.expectedOutput, result) + }) + } +} diff --git a/network/codec.go b/network/codec.go index b1998a1b006..bb866908d91 100644 --- a/network/codec.go +++ b/network/codec.go @@ -10,7 +10,7 @@ import ( type Codec interface { NewEncoder(w io.Writer) Encoder NewDecoder(r io.Reader) Decoder - Encode(v interface{}) ([]byte, error) + Encode(v any) ([]byte, error) // Decode decodes a message. // Expected error returns during normal operations: @@ -22,7 +22,7 @@ type Codec interface { // Encoder encodes the given message into the underlying writer. type Encoder interface { - Encode(v interface{}) error + Encode(v any) error } // Decoder decodes from the underlying reader into the given message. diff --git a/network/codec/cbor/codec.go b/network/codec/cbor/codec.go index baadbb6d71c..c65cbefd489 100644 --- a/network/codec/cbor/codec.go +++ b/network/codec/cbor/codec.go @@ -47,7 +47,7 @@ func (c *Codec) NewDecoder(r io.Reader) network.Decoder { // NOTE: 'what' is the 'code' name for debugging / instrumentation. // NOTE: 'envelope' contains 'code' & serialized / encoded 'v'. // i.e. 1st byte is 'code' and remaining bytes are CBOR encoded 'v'. -func (c *Codec) Encode(v interface{}) ([]byte, error) { +func (c *Codec) Encode(v any) ([]byte, error) { // encode the value code, what, err := codec.MessageCodeFromInterface(v) diff --git a/network/codec/cbor/encoder.go b/network/codec/cbor/encoder.go index e7b14682403..ab550e7f864 100644 --- a/network/codec/cbor/encoder.go +++ b/network/codec/cbor/encoder.go @@ -18,7 +18,7 @@ type Encoder struct { // Encode will convert the given message into CBOR and write it to the // underlying encoder, followed by a new line. -func (e *Encoder) Encode(v interface{}) error { +func (e *Encoder) Encode(v any) error { // encode the value code, what, err := codec.MessageCodeFromInterface(v) if err != nil { diff --git a/network/codec/codes.go b/network/codec/codes.go index 84d39397dc6..9b1addbbead 100644 --- a/network/codec/codes.go +++ b/network/codec/codes.go @@ -65,7 +65,7 @@ const ( ) // MessageCodeFromInterface returns the correct Code based on the underlying type of message v. -func MessageCodeFromInterface(v interface{}) (MessageCode, string, error) { +func MessageCodeFromInterface(v any) (MessageCode, string, error) { s := what(v) switch v.(type) { // consensus @@ -231,6 +231,6 @@ func MessageCodeFromPayload(payload []byte) (MessageCode, error) { return MessageCode(payload[0]), nil } -func what(v interface{}) string { +func what(v any) string { return fmt.Sprintf("%T", v) } diff --git a/network/conduit.go b/network/conduit.go index 5002eb9a291..a8a02a3d7ab 100644 --- a/network/conduit.go +++ b/network/conduit.go @@ -35,19 +35,19 @@ type Conduit interface { // The event is published on the channels of this Conduit and will be received // by the nodes specified as part of the targetIDs. // TODO: function errors must be documented. - Publish(event interface{}, targetIDs ...flow.Identifier) error + Publish(event any, targetIDs ...flow.Identifier) error // Unicast sends the event in a reliable way to the given recipient. // It uses 1-1 direct messaging over the underlying network to deliver the event. // It returns an error if the unicast fails. // TODO: function errors must be documented. - Unicast(event interface{}, targetID flow.Identifier) error + Unicast(event any, targetID flow.Identifier) error // Multicast unreliably sends the specified event over the channel // to the specified number of recipients selected from the specified subset. // The recipients are selected randomly from the targetIDs. // TODO: function errors must be documented. - Multicast(event interface{}, num uint, targetIDs ...flow.Identifier) error + Multicast(event any, num uint, targetIDs ...flow.Identifier) error // Close unsubscribes from the channels of this conduit. After calling close, // the conduit can no longer be used to send a message. diff --git a/network/engine.go b/network/engine.go index 0997894096d..2716975a349 100644 --- a/network/engine.go +++ b/network/engine.go @@ -18,25 +18,25 @@ type Engine interface { // * Define a message queue on the component receiving the message // * Define a function (with a concrete argument type) on the component receiving // the message, which adds the message to the message queue - SubmitLocal(event interface{}) + SubmitLocal(event any) // Submit submits the given event from the node with the given origin ID // for processing in a non-blocking manner. It returns instantly and logs // a potential processing error internally when done. // Deprecated: Only applicable for use by the networking layer, which should use MessageProcessor instead - Submit(channel channels.Channel, originID flow.Identifier, event interface{}) + Submit(channel channels.Channel, originID flow.Identifier, event any) // ProcessLocal processes an event originating on the local node. // Deprecated: To synchronously process a local message: // * Define a function (with a concrete argument type) on the component receiving // the message, which blocks until the message is processed - ProcessLocal(event interface{}) error + ProcessLocal(event any) error // Process processes the given event from the node with the given origin ID // in a blocking manner. It returns the potential processing error when // done. // Deprecated: Only applicable for use by the networking layer, which should use MessageProcessor instead - Process(channel channels.Channel, originID flow.Identifier, event interface{}) error + Process(channel channels.Channel, originID flow.Identifier, event any) error } // MessageProcessor represents a component which receives messages from the @@ -56,5 +56,5 @@ type MessageProcessor interface { // // Some of the current error returns signal Byzantine behavior, such as forged or malformed // messages. These cases must be logged and routed to a dedicated violation reporting consumer. - Process(channel channels.Channel, originID flow.Identifier, message interface{}) error + Process(channel channels.Channel, originID flow.Identifier, message any) error } diff --git a/network/errors.go b/network/errors.go index f9edc2d291a..8f3babd5798 100644 --- a/network/errors.go +++ b/network/errors.go @@ -53,7 +53,7 @@ func (err TransientError) Unwrap() error { return err.Err } -func NewTransientErrorf(msg string, args ...interface{}) TransientError { +func NewTransientErrorf(msg string, args ...any) TransientError { return TransientError{ Err: fmt.Errorf(msg, args...), } diff --git a/network/internal/testutils/testUtil.go b/network/internal/testutils/testUtil.go index 6a8a4331ee5..84715619016 100644 --- a/network/internal/testutils/testUtil.go +++ b/network/internal/testutils/testUtil.go @@ -183,6 +183,7 @@ func NetworkConfigFixture( me := mock.NewLocal(t) me.On("NodeID").Return(myId.NodeID).Maybe() + me.On("Role").Return(myId.Role).Maybe() me.On("NotMeFilter").Return(filter.Not(filter.HasNodeID[flow.Identity](me.NodeID()))).Maybe() me.On("Address").Return(myId.Address).Maybe() @@ -218,6 +219,7 @@ func NetworkConfigFixture( SlashingViolationConsumerFactory: func(_ network.ConduitAdapter) network.ViolationsConsumer { return mocknetwork.NewViolationsConsumer(t) }, + UnicastStreamAuthorizer: func(_, _ flow.Role) bool { return true }, } for _, opt := range opts { diff --git a/network/message/authorization.go b/network/message/authorization.go index 7a7f33d518b..e2f4006db05 100644 --- a/network/message/authorization.go +++ b/network/message/authorization.go @@ -16,7 +16,9 @@ type ChannelAuthConfig struct { AllowedProtocols Protocols } -var authorizationConfigs map[string]MsgAuthConfig +var ( + authorizationConfigs map[string]MsgAuthConfig +) // MsgAuthConfig contains authorization information for a specific flow message. The authorization // is represented as a map from network channel -> list of all roles allowed to send the message on @@ -25,7 +27,7 @@ type MsgAuthConfig struct { // Name is the string representation of the message type. Name string // Type is a func that returns a new instance of message type. - Type func() interface{} + Type func() any // Config is the mapping of network channel to list of authorized flow roles. Config map[channels.Channel]ChannelAuthConfig } @@ -60,7 +62,7 @@ func initializeMessageAuthConfigsMap() { // consensus authorizationConfigs[BlockProposal] = MsgAuthConfig{ Name: BlockProposal, - Type: func() interface{} { + Type: func() any { return new(messages.Proposal) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -76,7 +78,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[BlockVote] = MsgAuthConfig{ Name: BlockVote, - Type: func() interface{} { + Type: func() any { return new(messages.BlockVote) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -88,7 +90,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[TimeoutObject] = MsgAuthConfig{ Name: TimeoutObject, - Type: func() interface{} { + Type: func() any { return new(messages.TimeoutObject) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -102,7 +104,7 @@ func initializeMessageAuthConfigsMap() { // protocol state sync authorizationConfigs[SyncRequest] = MsgAuthConfig{ Name: SyncRequest, - Type: func() interface{} { + Type: func() any { return new(messages.SyncRequest) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -118,7 +120,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[SyncResponse] = MsgAuthConfig{ Name: SyncResponse, - Type: func() interface{} { + Type: func() any { return new(messages.SyncResponse) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -134,7 +136,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[RangeRequest] = MsgAuthConfig{ Name: RangeRequest, - Type: func() interface{} { + Type: func() any { return new(messages.RangeRequest) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -150,7 +152,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[BatchRequest] = MsgAuthConfig{ Name: BatchRequest, - Type: func() interface{} { + Type: func() any { return new(messages.BatchRequest) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -166,7 +168,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[BlockResponse] = MsgAuthConfig{ Name: BlockResponse, - Type: func() interface{} { + Type: func() any { return new(messages.BlockResponse) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -180,7 +182,7 @@ func initializeMessageAuthConfigsMap() { // cluster consensus authorizationConfigs[ClusterBlockProposal] = MsgAuthConfig{ Name: ClusterBlockProposal, - Type: func() interface{} { + Type: func() any { return new(messages.ClusterProposal) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -192,7 +194,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[ClusterBlockVote] = MsgAuthConfig{ Name: ClusterBlockVote, - Type: func() interface{} { + Type: func() any { return new(messages.ClusterBlockVote) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -204,7 +206,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[ClusterTimeoutObject] = MsgAuthConfig{ Name: ClusterTimeoutObject, - Type: func() interface{} { + Type: func() any { return new(messages.ClusterTimeoutObject) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -216,7 +218,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[ClusterBlockResponse] = MsgAuthConfig{ Name: ClusterBlockResponse, - Type: func() interface{} { + Type: func() any { return new(messages.ClusterBlockResponse) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -230,7 +232,7 @@ func initializeMessageAuthConfigsMap() { // collections, guarantees & transactions authorizationConfigs[CollectionGuarantee] = MsgAuthConfig{ Name: CollectionGuarantee, - Type: func() interface{} { + Type: func() any { return new(messages.CollectionGuarantee) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -242,7 +244,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[TransactionBody] = MsgAuthConfig{ Name: TransactionBody, - Type: func() interface{} { + Type: func() any { return new(messages.TransactionBody) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -256,7 +258,7 @@ func initializeMessageAuthConfigsMap() { // core messages for execution & verification authorizationConfigs[ExecutionReceipt] = MsgAuthConfig{ Name: ExecutionReceipt, - Type: func() interface{} { + Type: func() any { return new(messages.ExecutionReceipt) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -268,7 +270,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[ResultApproval] = MsgAuthConfig{ Name: ResultApproval, - Type: func() interface{} { + Type: func() any { return new(messages.ResultApproval) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -282,7 +284,7 @@ func initializeMessageAuthConfigsMap() { // data exchange for execution of blocks authorizationConfigs[ChunkDataRequest] = MsgAuthConfig{ Name: ChunkDataRequest, - Type: func() interface{} { + Type: func() any { return new(messages.ChunkDataRequest) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -294,7 +296,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[ChunkDataResponse] = MsgAuthConfig{ Name: ChunkDataResponse, - Type: func() interface{} { + Type: func() any { return new(messages.ChunkDataResponse) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -308,7 +310,7 @@ func initializeMessageAuthConfigsMap() { // result approvals authorizationConfigs[ApprovalRequest] = MsgAuthConfig{ Name: ApprovalRequest, - Type: func() interface{} { + Type: func() any { return new(messages.ApprovalRequest) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -320,7 +322,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[ApprovalResponse] = MsgAuthConfig{ Name: ApprovalResponse, - Type: func() interface{} { + Type: func() any { return new(messages.ApprovalResponse) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -334,7 +336,7 @@ func initializeMessageAuthConfigsMap() { // generic entity exchange engines authorizationConfigs[EntityRequest] = MsgAuthConfig{ Name: EntityRequest, - Type: func() interface{} { + Type: func() any { return new(messages.EntityRequest) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -350,7 +352,7 @@ func initializeMessageAuthConfigsMap() { } authorizationConfigs[EntityResponse] = MsgAuthConfig{ Name: EntityResponse, - Type: func() interface{} { + Type: func() any { return new(messages.EntityResponse) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -368,7 +370,7 @@ func initializeMessageAuthConfigsMap() { // testing authorizationConfigs[TestMessage] = MsgAuthConfig{ Name: TestMessage, - Type: func() interface{} { + Type: func() any { return new(message.TestMessage) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -386,7 +388,7 @@ func initializeMessageAuthConfigsMap() { // DKG authorizationConfigs[DKGMessage] = MsgAuthConfig{ Name: DKGMessage, - Type: func() interface{} { + Type: func() any { return new(messages.DKGMessage) }, Config: map[channels.Channel]ChannelAuthConfig{ @@ -396,13 +398,53 @@ func initializeMessageAuthConfigsMap() { }, }, } + +} + +// unicastRoleAuthorization defines which sender roles are authorized to open +// unicast streams to each receiver role. This is a more restrictive check than +// channel-based authorization, applied before any message data is read. +// +// The map key is the receiver role, and the value is the list of sender roles +// allowed to initiate unicast streams to that receiver. +var unicastRoleAuthorization = map[flow.Role]flow.RoleList{ + // Consensus nodes can receive unicasts from: Consensus (sync), Execution (receipts), Verification (approvals) + flow.RoleConsensus: {flow.RoleConsensus, flow.RoleExecution, flow.RoleVerification}, + // Collection nodes can receive unicasts from: Consensus (sync), Execution (state requests), Collection (cluster sync), Access (collection requests) + flow.RoleCollection: {flow.RoleConsensus, flow.RoleExecution, flow.RoleCollection, flow.RoleAccess}, + // Execution nodes can receive unicasts from: Consensus (sync), Collection (collections) + flow.RoleExecution: {flow.RoleConsensus, flow.RoleCollection}, + // Verification nodes can receive unicasts from: Consensus (sync), Execution (chunk data) + flow.RoleVerification: {flow.RoleConsensus, flow.RoleExecution}, + // Access nodes can receive unicasts from: Consensus (sync), Collection (collection responses) + flow.RoleAccess: {flow.RoleConsensus, flow.RoleCollection}, +} + +// IsAuthorizedUnicastSenderRole checks whether the given sender role is authorized to open a unicast +// stream to the given receiver role. This is used for pre-authorization of unicast streams before +// any message data is read. +// +// This authorization is intentionally more restrictive than channel-based authorization. It is +// rather than derived from channel subscriptions, because channel subscriptions are broader than +// what is correct for unicast (e.g. Access nodes subscribe to RequestCollections to receive +// responses, but should not be unicast targets from other Access nodes). +func IsAuthorizedUnicastSenderRole(sender flow.Role, receiver flow.Role) bool { + senders, ok := unicastRoleAuthorization[receiver] + return ok && senders.Contains(sender) +} + +// AlwaysAuthorizedUnicastSenderRole is unicast stream authorizer that always returns true. +// +// This is used for the public network where peers are not authorized based on role. +func AlwaysAuthorizedUnicastSenderRole(sender, receiver flow.Role) bool { + return true } // GetMessageAuthConfig checks the underlying type and returns the correct // message auth Config. // Expected error returns during normal operations: // - ErrUnknownMsgType : if underlying type of v does not match any of the known message types -func GetMessageAuthConfig(v interface{}) (MsgAuthConfig, error) { +func GetMessageAuthConfig(v any) (MsgAuthConfig, error) { switch v.(type) { // consensus case *messages.Proposal: diff --git a/network/message/authorization_test.go b/network/message/authorization_test.go new file mode 100644 index 00000000000..34ede7094ac --- /dev/null +++ b/network/message/authorization_test.go @@ -0,0 +1,125 @@ +package message + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/channels" +) + +// TestIsAuthorizedUnicastSender verifies the expected authorization matrix for all role pairs. +func TestIsAuthorizedUnicastSender(t *testing.T) { + // Consensus nodes can send unicast to all roles (sync protocol) + for _, receiver := range flow.Roles() { + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleConsensus, receiver), "consensus -> %s should be authorized", receiver) + } + + // Execution nodes can unicast to: Consensus, Collection, Verification + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleExecution, flow.RoleConsensus)) + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleExecution, flow.RoleCollection)) + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleExecution, flow.RoleVerification)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleExecution, flow.RoleExecution)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleExecution, flow.RoleAccess)) + + // Collection nodes can unicast to: Collection, Execution, Access + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleCollection, flow.RoleCollection)) + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleCollection, flow.RoleExecution)) + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleCollection, flow.RoleAccess)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleCollection, flow.RoleConsensus)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleCollection, flow.RoleVerification)) + + // Verification nodes can unicast to: Consensus only + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleVerification, flow.RoleConsensus)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleVerification, flow.RoleCollection)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleVerification, flow.RoleExecution)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleVerification, flow.RoleVerification)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleVerification, flow.RoleAccess)) + + // Access nodes can unicast to: Collection only + require.True(t, IsAuthorizedUnicastSenderRole(flow.RoleAccess, flow.RoleCollection)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleAccess, flow.RoleConsensus)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleAccess, flow.RoleExecution)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleAccess, flow.RoleVerification)) + require.False(t, IsAuthorizedUnicastSenderRole(flow.RoleAccess, flow.RoleAccess)) +} + +// TestAlwaysAuthorizedUnicastSenderRole verifies that the public-network authorizer permits all role pairs. +func TestAlwaysAuthorizedUnicastSenderRole(t *testing.T) { + for _, sender := range flow.Roles() { + for _, receiver := range flow.Roles() { + require.True(t, AlwaysAuthorizedUnicastSenderRole(sender, receiver), + "AlwaysAuthorizedUnicastSenderRole should permit %s -> %s", sender, receiver) + } + } +} + +// TestIsAuthorizedUnicastSender_CrossValidation ensures that the explicit unicast role authorization +// stays consistent with the message authorization configs. It derives the maximum possible +// authorization from the configs and channel subscriptions, and verifies: +// 1. Every authorized pair in the explicit map is justified by at least one unicast message config. +// 2. Every pair derivable from the configs is authorized (with documented exceptions). +// +// This test will fail if a new unicast message type is added but the authorization map is not updated. +func TestIsAuthorizedUnicastSender_CrossValidation(t *testing.T) { + // Derive the maximum authorization from message auth configs. + // Skip test message types since they allow all roles on test channels and would + // make the derived map trivially allow everything. + derived := make(map[flow.Role]flow.RoleList) + for _, msgAuthConfig := range GetAllMessageAuthConfigs() { + if msgAuthConfig.Name == TestMessage { + continue + } + for channel, channelAuthConfig := range msgAuthConfig.Config { + if !channelAuthConfig.AllowedProtocols.Contains(ProtocolTypeUnicast) { + continue + } + receiverRoles, ok := channels.RolesByChannel(channel) + if !ok { + continue + } + for _, senderRole := range channelAuthConfig.AuthorizedRoles { + derived[senderRole] = derived[senderRole].Union(receiverRoles) + } + } + } + + // Check 1: every authorized pair must be justified by at least one unicast message config + for _, sender := range flow.Roles() { + derivedReceivers, ok := derived[sender] + for _, receiver := range flow.Roles() { + if IsAuthorizedUnicastSenderRole(sender, receiver) { + require.True(t, ok, "sender role %s is authorized but has no unicast message configs", sender) + require.True(t, derivedReceivers.Contains(receiver), + "IsAuthorizedUnicastSenderRole allows %s -> %s but no unicast message config supports this", sender, receiver) + } + } + } + + // Intentional restrictions: these (sender, receiver) pairs are derivable from the configs + // but intentionally excluded from the authorization map. + // - Access->Access, Access->Execution: The RequestCollections channel includes AN and EN + // as subscribers, but ANs should only send collection requests to LNs. + // - Execution->Execution, Execution->Access: The RequestCollections and ProvideReceiptsByBlockID + // channels include ENs/ANs as subscribers, but ENs do not need to unicast to themselves or ANs. + // - Verification->Verification: The ProvideApprovalsByChunk channel includes VNs as subscribers, + // but VNs only send approval responses to consensus nodes. + intentionalRestrictions := map[flow.Role]flow.RoleList{ + flow.RoleAccess: {flow.RoleAccess, flow.RoleExecution}, + flow.RoleExecution: {flow.RoleExecution, flow.RoleAccess}, + flow.RoleVerification: {flow.RoleVerification}, + } + + // Check 2: every derived pair must be authorized, except for intentional restrictions. + // This catches new unicast message types that require updating the authorization map. + for senderRole, derivedReceivers := range derived { + for _, receiver := range derivedReceivers { + if intentionalRestrictions[senderRole].Contains(receiver) { + continue // intentionally restricted + } + require.True(t, IsAuthorizedUnicastSenderRole(senderRole, receiver), + "message configs allow %s -> %s via unicast but IsAuthorizedUnicastSenderRole rejects it — update the authorization map or add to intentionalRestrictions", senderRole, receiver) + } + } +} diff --git a/network/message/errors.go b/network/message/errors.go index 5441027a7b0..1c6f6b66c74 100644 --- a/network/message/errors.go +++ b/network/message/errors.go @@ -14,7 +14,7 @@ var ( // UnknownMsgTypeErr indicates that no message auth configured for the message type v type UnknownMsgTypeErr struct { - MsgType interface{} + MsgType any } func (e UnknownMsgTypeErr) Error() string { @@ -22,7 +22,7 @@ func (e UnknownMsgTypeErr) Error() string { } // NewUnknownMsgTypeErr returns a new ErrUnknownMsgType -func NewUnknownMsgTypeErr(msgType interface{}) UnknownMsgTypeErr { +func NewUnknownMsgTypeErr(msgType any) UnknownMsgTypeErr { return UnknownMsgTypeErr{MsgType: msgType} } diff --git a/network/message/init.go b/network/message/init.go index 4bb3cb0dc60..b894ff2f11c 100644 --- a/network/message/init.go +++ b/network/message/init.go @@ -2,6 +2,7 @@ package message import ( "fmt" + "slices" ) var ( @@ -33,13 +34,7 @@ func validateMessageAuthConfigsMap(excludeList []string) { } func excludeConfig(name string, excludeList []string) bool { - for _, s := range excludeList { - if s == name { - return true - } - } - - return false + return slices.Contains(excludeList, name) } // string constants for all message types sent on the network diff --git a/network/message/message_scope.go b/network/message/message_scope.go index 0b93de7af19..ade43f7a2cb 100644 --- a/network/message/message_scope.go +++ b/network/message/message_scope.go @@ -35,7 +35,7 @@ func EventId(channel channels.Channel, payload []byte) (hash.Hash, error) { } // MessageType returns the type of the message payload. -func MessageType(decodedPayload interface{}) string { +func MessageType(decodedPayload any) string { return strings.TrimLeft(fmt.Sprintf("%T", decodedPayload), "*") } @@ -45,7 +45,7 @@ type IncomingMessageScope struct { targetIds flow.IdentifierList // the target node IDs (i.e., intended recipients). eventId hash.Hash // hash of the payload and channel. msg *Message // the raw message received. - decodedPayload interface{} // decoded payload of the message. + decodedPayload any // decoded payload of the message. protocol ProtocolType // the type of protocol used to receive the message. } @@ -54,7 +54,7 @@ type IncomingMessageScope struct { // safe to crash the node when receiving a message. // It errors if event id (i.e., hash of the payload and channel) cannot be computed, or if it fails to // convert the target IDs from bytes slice to a flow.IdentifierList. -func NewIncomingScope(originId flow.Identifier, protocol ProtocolType, msg *Message, decodedPayload interface{}) (*IncomingMessageScope, error) { +func NewIncomingScope(originId flow.Identifier, protocol ProtocolType, msg *Message, decodedPayload any) (*IncomingMessageScope, error) { eventId, err := EventId(channels.Channel(msg.ChannelID), msg.Payload) if err != nil { return nil, fmt.Errorf("could not compute event id: %w", err) @@ -82,7 +82,7 @@ func (m IncomingMessageScope) Proto() *Message { return m.msg } -func (m IncomingMessageScope) DecodedPayload() interface{} { +func (m IncomingMessageScope) DecodedPayload() any { return m.decodedPayload } @@ -112,12 +112,12 @@ func (m IncomingMessageScope) PayloadType() string { // OutgoingMessageScope captures the context around an outgoing message that is about to be sent. type OutgoingMessageScope struct { - targetIds flow.IdentifierList // the target node IDs. - topic channels.Topic // the topic, i.e., channel-id/spork-id. - payload interface{} // the payload to be sent. - encoder func(interface{}) ([]byte, error) // the encoder to encode the payload. - msg *Message // raw proto message sent on wire. - protocol ProtocolType // the type of protocol used to send the message. + targetIds flow.IdentifierList // the target node IDs. + topic channels.Topic // the topic, i.e., channel-id/spork-id. + payload any // the payload to be sent. + encoder func(any) ([]byte, error) // the encoder to encode the payload. + msg *Message // raw proto message sent on wire. + protocol ProtocolType // the type of protocol used to send the message. } // NewOutgoingScope creates a new outgoing message scope. @@ -128,8 +128,8 @@ type OutgoingMessageScope struct { func NewOutgoingScope( targetIds flow.IdentifierList, topic channels.Topic, - payload interface{}, - encoder func(interface{}) ([]byte, error), + payload any, + encoder func(any) ([]byte, error), protocolType ProtocolType) (*OutgoingMessageScope, error) { scope := &OutgoingMessageScope{ targetIds: targetIds, diff --git a/network/message/protocols.go b/network/message/protocols.go index 257bee15361..77ea48a946a 100644 --- a/network/message/protocols.go +++ b/network/message/protocols.go @@ -1,5 +1,7 @@ package message +import "slices" + const ( // ProtocolTypeUnicast is protocol type for unicast messages. ProtocolTypeUnicast ProtocolType = "unicast" @@ -20,11 +22,5 @@ type Protocols []ProtocolType // Contains returns true if the protocol is in the list of Protocols. func (pr Protocols) Contains(protocol ProtocolType) bool { - for _, p := range pr { - if p == protocol { - return true - } - } - - return false + return slices.Contains(pr, protocol) } diff --git a/network/message_scope.go b/network/message_scope.go index 4e4ded4b9cc..dfe771ac240 100644 --- a/network/message_scope.go +++ b/network/message_scope.go @@ -16,7 +16,7 @@ type IncomingMessageScope interface { Proto() *message.Message // DecodedPayload returns the decoded payload of the message. - DecodedPayload() interface{} + DecodedPayload() any // Protocol returns the type of protocol used to receive the message. Protocol() message.ProtocolType diff --git a/network/mock/basic_resolver.go b/network/mock/basic_resolver.go index 15c4ad5f3d6..bfc9f59ba86 100644 --- a/network/mock/basic_resolver.go +++ b/network/mock/basic_resolver.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - net "net" + "context" + "net" mock "github.com/stretchr/testify/mock" ) +// NewBasicResolver creates a new instance of BasicResolver. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBasicResolver(t interface { + mock.TestingT + Cleanup(func()) +}) *BasicResolver { + mock := &BasicResolver{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BasicResolver is an autogenerated mock type for the BasicResolver type type BasicResolver struct { mock.Mock } -// LookupIPAddr provides a mock function with given fields: _a0, _a1 -func (_m *BasicResolver) LookupIPAddr(_a0 context.Context, _a1 string) ([]net.IPAddr, error) { - ret := _m.Called(_a0, _a1) +type BasicResolver_Expecter struct { + mock *mock.Mock +} + +func (_m *BasicResolver) EXPECT() *BasicResolver_Expecter { + return &BasicResolver_Expecter{mock: &_m.Mock} +} + +// LookupIPAddr provides a mock function for the type BasicResolver +func (_mock *BasicResolver) LookupIPAddr(context1 context.Context, s string) ([]net.IPAddr, error) { + ret := _mock.Called(context1, s) if len(ret) == 0 { panic("no return value specified for LookupIPAddr") @@ -24,29 +48,67 @@ func (_m *BasicResolver) LookupIPAddr(_a0 context.Context, _a1 string) ([]net.IP var r0 []net.IPAddr var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) ([]net.IPAddr, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]net.IPAddr, error)); ok { + return returnFunc(context1, s) } - if rf, ok := ret.Get(0).(func(context.Context, string) []net.IPAddr); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, string) []net.IPAddr); ok { + r0 = returnFunc(context1, s) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]net.IPAddr) } } - - if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = returnFunc(context1, s) } else { r1 = ret.Error(1) } - return r0, r1 } -// LookupTXT provides a mock function with given fields: _a0, _a1 -func (_m *BasicResolver) LookupTXT(_a0 context.Context, _a1 string) ([]string, error) { - ret := _m.Called(_a0, _a1) +// BasicResolver_LookupIPAddr_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LookupIPAddr' +type BasicResolver_LookupIPAddr_Call struct { + *mock.Call +} + +// LookupIPAddr is a helper method to define mock.On call +// - context1 context.Context +// - s string +func (_e *BasicResolver_Expecter) LookupIPAddr(context1 interface{}, s interface{}) *BasicResolver_LookupIPAddr_Call { + return &BasicResolver_LookupIPAddr_Call{Call: _e.mock.On("LookupIPAddr", context1, s)} +} + +func (_c *BasicResolver_LookupIPAddr_Call) Run(run func(context1 context.Context, s string)) *BasicResolver_LookupIPAddr_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BasicResolver_LookupIPAddr_Call) Return(iPAddrs []net.IPAddr, err error) *BasicResolver_LookupIPAddr_Call { + _c.Call.Return(iPAddrs, err) + return _c +} + +func (_c *BasicResolver_LookupIPAddr_Call) RunAndReturn(run func(context1 context.Context, s string) ([]net.IPAddr, error)) *BasicResolver_LookupIPAddr_Call { + _c.Call.Return(run) + return _c +} + +// LookupTXT provides a mock function for the type BasicResolver +func (_mock *BasicResolver) LookupTXT(context1 context.Context, s string) ([]string, error) { + ret := _mock.Called(context1, s) if len(ret) == 0 { panic("no return value specified for LookupTXT") @@ -54,36 +116,60 @@ func (_m *BasicResolver) LookupTXT(_a0 context.Context, _a1 string) ([]string, e var r0 []string var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) ([]string, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]string, error)); ok { + return returnFunc(context1, s) } - if rf, ok := ret.Get(0).(func(context.Context, string) []string); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, string) []string); ok { + r0 = returnFunc(context1, s) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]string) } } - - if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = returnFunc(context1, s) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBasicResolver creates a new instance of BasicResolver. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBasicResolver(t interface { - mock.TestingT - Cleanup(func()) -}) *BasicResolver { - mock := &BasicResolver{} - mock.Mock.Test(t) +// BasicResolver_LookupTXT_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LookupTXT' +type BasicResolver_LookupTXT_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// LookupTXT is a helper method to define mock.On call +// - context1 context.Context +// - s string +func (_e *BasicResolver_Expecter) LookupTXT(context1 interface{}, s interface{}) *BasicResolver_LookupTXT_Call { + return &BasicResolver_LookupTXT_Call{Call: _e.mock.On("LookupTXT", context1, s)} +} - return mock +func (_c *BasicResolver_LookupTXT_Call) Run(run func(context1 context.Context, s string)) *BasicResolver_LookupTXT_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BasicResolver_LookupTXT_Call) Return(strings []string, err error) *BasicResolver_LookupTXT_Call { + _c.Call.Return(strings, err) + return _c +} + +func (_c *BasicResolver_LookupTXT_Call) RunAndReturn(run func(context1 context.Context, s string) ([]string, error)) *BasicResolver_LookupTXT_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/blob_getter.go b/network/mock/blob_getter.go index e543cec17b5..50530d1a6be 100644 --- a/network/mock/blob_getter.go +++ b/network/mock/blob_getter.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cid "github.com/ipfs/go-cid" - blobs "github.com/onflow/flow-go/module/blobs" - - context "context" + "context" + "github.com/ipfs/go-cid" + "github.com/onflow/flow-go/module/blobs" mock "github.com/stretchr/testify/mock" ) +// NewBlobGetter creates a new instance of BlobGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlobGetter(t interface { + mock.TestingT + Cleanup(func()) +}) *BlobGetter { + mock := &BlobGetter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BlobGetter is an autogenerated mock type for the BlobGetter type type BlobGetter struct { mock.Mock } -// GetBlob provides a mock function with given fields: ctx, c -func (_m *BlobGetter) GetBlob(ctx context.Context, c cid.Cid) (blobs.Blob, error) { - ret := _m.Called(ctx, c) +type BlobGetter_Expecter struct { + mock *mock.Mock +} + +func (_m *BlobGetter) EXPECT() *BlobGetter_Expecter { + return &BlobGetter_Expecter{mock: &_m.Mock} +} + +// GetBlob provides a mock function for the type BlobGetter +func (_mock *BlobGetter) GetBlob(ctx context.Context, c cid.Cid) (blobs.Blob, error) { + ret := _mock.Called(ctx, c) if len(ret) == 0 { panic("no return value specified for GetBlob") @@ -26,56 +49,119 @@ func (_m *BlobGetter) GetBlob(ctx context.Context, c cid.Cid) (blobs.Blob, error var r0 blobs.Blob var r1 error - if rf, ok := ret.Get(0).(func(context.Context, cid.Cid) (blobs.Blob, error)); ok { - return rf(ctx, c) + if returnFunc, ok := ret.Get(0).(func(context.Context, cid.Cid) (blobs.Blob, error)); ok { + return returnFunc(ctx, c) } - if rf, ok := ret.Get(0).(func(context.Context, cid.Cid) blobs.Blob); ok { - r0 = rf(ctx, c) + if returnFunc, ok := ret.Get(0).(func(context.Context, cid.Cid) blobs.Blob); ok { + r0 = returnFunc(ctx, c) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(blobs.Blob) } } - - if rf, ok := ret.Get(1).(func(context.Context, cid.Cid) error); ok { - r1 = rf(ctx, c) + if returnFunc, ok := ret.Get(1).(func(context.Context, cid.Cid) error); ok { + r1 = returnFunc(ctx, c) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlobs provides a mock function with given fields: ctx, ks -func (_m *BlobGetter) GetBlobs(ctx context.Context, ks []cid.Cid) <-chan blobs.Blob { - ret := _m.Called(ctx, ks) +// BlobGetter_GetBlob_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlob' +type BlobGetter_GetBlob_Call struct { + *mock.Call +} + +// GetBlob is a helper method to define mock.On call +// - ctx context.Context +// - c cid.Cid +func (_e *BlobGetter_Expecter) GetBlob(ctx interface{}, c interface{}) *BlobGetter_GetBlob_Call { + return &BlobGetter_GetBlob_Call{Call: _e.mock.On("GetBlob", ctx, c)} +} + +func (_c *BlobGetter_GetBlob_Call) Run(run func(ctx context.Context, c cid.Cid)) *BlobGetter_GetBlob_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 cid.Cid + if args[1] != nil { + arg1 = args[1].(cid.Cid) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlobGetter_GetBlob_Call) Return(v blobs.Blob, err error) *BlobGetter_GetBlob_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BlobGetter_GetBlob_Call) RunAndReturn(run func(ctx context.Context, c cid.Cid) (blobs.Blob, error)) *BlobGetter_GetBlob_Call { + _c.Call.Return(run) + return _c +} + +// GetBlobs provides a mock function for the type BlobGetter +func (_mock *BlobGetter) GetBlobs(ctx context.Context, ks []cid.Cid) <-chan blobs.Blob { + ret := _mock.Called(ctx, ks) if len(ret) == 0 { panic("no return value specified for GetBlobs") } var r0 <-chan blobs.Blob - if rf, ok := ret.Get(0).(func(context.Context, []cid.Cid) <-chan blobs.Blob); ok { - r0 = rf(ctx, ks) + if returnFunc, ok := ret.Get(0).(func(context.Context, []cid.Cid) <-chan blobs.Blob); ok { + r0 = returnFunc(ctx, ks) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan blobs.Blob) } } - return r0 } -// NewBlobGetter creates a new instance of BlobGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlobGetter(t interface { - mock.TestingT - Cleanup(func()) -}) *BlobGetter { - mock := &BlobGetter{} - mock.Mock.Test(t) +// BlobGetter_GetBlobs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlobs' +type BlobGetter_GetBlobs_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetBlobs is a helper method to define mock.On call +// - ctx context.Context +// - ks []cid.Cid +func (_e *BlobGetter_Expecter) GetBlobs(ctx interface{}, ks interface{}) *BlobGetter_GetBlobs_Call { + return &BlobGetter_GetBlobs_Call{Call: _e.mock.On("GetBlobs", ctx, ks)} +} - return mock +func (_c *BlobGetter_GetBlobs_Call) Run(run func(ctx context.Context, ks []cid.Cid)) *BlobGetter_GetBlobs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []cid.Cid + if args[1] != nil { + arg1 = args[1].([]cid.Cid) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlobGetter_GetBlobs_Call) Return(vCh <-chan blobs.Blob) *BlobGetter_GetBlobs_Call { + _c.Call.Return(vCh) + return _c +} + +func (_c *BlobGetter_GetBlobs_Call) RunAndReturn(run func(ctx context.Context, ks []cid.Cid) <-chan blobs.Blob) *BlobGetter_GetBlobs_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/blob_service.go b/network/mock/blob_service.go index 925d57933bb..1c543452899 100644 --- a/network/mock/blob_service.go +++ b/network/mock/blob_service.go @@ -1,102 +1,266 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cid "github.com/ipfs/go-cid" - blobs "github.com/onflow/flow-go/module/blobs" + "context" - context "context" + "github.com/ipfs/go-cid" + "github.com/onflow/flow-go/module/blobs" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network" + mock "github.com/stretchr/testify/mock" +) - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" +// NewBlobService creates a new instance of BlobService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlobService(t interface { + mock.TestingT + Cleanup(func()) +}) *BlobService { + mock := &BlobService{} + mock.Mock.Test(t) - mock "github.com/stretchr/testify/mock" + t.Cleanup(func() { mock.AssertExpectations(t) }) - network "github.com/onflow/flow-go/network" -) + return mock +} // BlobService is an autogenerated mock type for the BlobService type type BlobService struct { mock.Mock } -// AddBlob provides a mock function with given fields: ctx, b -func (_m *BlobService) AddBlob(ctx context.Context, b blobs.Blob) error { - ret := _m.Called(ctx, b) +type BlobService_Expecter struct { + mock *mock.Mock +} + +func (_m *BlobService) EXPECT() *BlobService_Expecter { + return &BlobService_Expecter{mock: &_m.Mock} +} + +// AddBlob provides a mock function for the type BlobService +func (_mock *BlobService) AddBlob(ctx context.Context, b blobs.Blob) error { + ret := _mock.Called(ctx, b) if len(ret) == 0 { panic("no return value specified for AddBlob") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, blobs.Blob) error); ok { - r0 = rf(ctx, b) + if returnFunc, ok := ret.Get(0).(func(context.Context, blobs.Blob) error); ok { + r0 = returnFunc(ctx, b) } else { r0 = ret.Error(0) } - return r0 } -// AddBlobs provides a mock function with given fields: ctx, bs -func (_m *BlobService) AddBlobs(ctx context.Context, bs []blobs.Blob) error { - ret := _m.Called(ctx, bs) +// BlobService_AddBlob_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlob' +type BlobService_AddBlob_Call struct { + *mock.Call +} + +// AddBlob is a helper method to define mock.On call +// - ctx context.Context +// - b blobs.Blob +func (_e *BlobService_Expecter) AddBlob(ctx interface{}, b interface{}) *BlobService_AddBlob_Call { + return &BlobService_AddBlob_Call{Call: _e.mock.On("AddBlob", ctx, b)} +} + +func (_c *BlobService_AddBlob_Call) Run(run func(ctx context.Context, b blobs.Blob)) *BlobService_AddBlob_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 blobs.Blob + if args[1] != nil { + arg1 = args[1].(blobs.Blob) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlobService_AddBlob_Call) Return(err error) *BlobService_AddBlob_Call { + _c.Call.Return(err) + return _c +} + +func (_c *BlobService_AddBlob_Call) RunAndReturn(run func(ctx context.Context, b blobs.Blob) error) *BlobService_AddBlob_Call { + _c.Call.Return(run) + return _c +} + +// AddBlobs provides a mock function for the type BlobService +func (_mock *BlobService) AddBlobs(ctx context.Context, bs []blobs.Blob) error { + ret := _mock.Called(ctx, bs) if len(ret) == 0 { panic("no return value specified for AddBlobs") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, []blobs.Blob) error); ok { - r0 = rf(ctx, bs) + if returnFunc, ok := ret.Get(0).(func(context.Context, []blobs.Blob) error); ok { + r0 = returnFunc(ctx, bs) } else { r0 = ret.Error(0) } - return r0 } -// DeleteBlob provides a mock function with given fields: ctx, c -func (_m *BlobService) DeleteBlob(ctx context.Context, c cid.Cid) error { - ret := _m.Called(ctx, c) +// BlobService_AddBlobs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlobs' +type BlobService_AddBlobs_Call struct { + *mock.Call +} + +// AddBlobs is a helper method to define mock.On call +// - ctx context.Context +// - bs []blobs.Blob +func (_e *BlobService_Expecter) AddBlobs(ctx interface{}, bs interface{}) *BlobService_AddBlobs_Call { + return &BlobService_AddBlobs_Call{Call: _e.mock.On("AddBlobs", ctx, bs)} +} + +func (_c *BlobService_AddBlobs_Call) Run(run func(ctx context.Context, bs []blobs.Blob)) *BlobService_AddBlobs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []blobs.Blob + if args[1] != nil { + arg1 = args[1].([]blobs.Blob) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlobService_AddBlobs_Call) Return(err error) *BlobService_AddBlobs_Call { + _c.Call.Return(err) + return _c +} + +func (_c *BlobService_AddBlobs_Call) RunAndReturn(run func(ctx context.Context, bs []blobs.Blob) error) *BlobService_AddBlobs_Call { + _c.Call.Return(run) + return _c +} + +// DeleteBlob provides a mock function for the type BlobService +func (_mock *BlobService) DeleteBlob(ctx context.Context, c cid.Cid) error { + ret := _mock.Called(ctx, c) if len(ret) == 0 { panic("no return value specified for DeleteBlob") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, cid.Cid) error); ok { - r0 = rf(ctx, c) + if returnFunc, ok := ret.Get(0).(func(context.Context, cid.Cid) error); ok { + r0 = returnFunc(ctx, c) } else { r0 = ret.Error(0) } - return r0 } -// Done provides a mock function with no fields -func (_m *BlobService) Done() <-chan struct{} { - ret := _m.Called() +// BlobService_DeleteBlob_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteBlob' +type BlobService_DeleteBlob_Call struct { + *mock.Call +} + +// DeleteBlob is a helper method to define mock.On call +// - ctx context.Context +// - c cid.Cid +func (_e *BlobService_Expecter) DeleteBlob(ctx interface{}, c interface{}) *BlobService_DeleteBlob_Call { + return &BlobService_DeleteBlob_Call{Call: _e.mock.On("DeleteBlob", ctx, c)} +} + +func (_c *BlobService_DeleteBlob_Call) Run(run func(ctx context.Context, c cid.Cid)) *BlobService_DeleteBlob_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 cid.Cid + if args[1] != nil { + arg1 = args[1].(cid.Cid) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlobService_DeleteBlob_Call) Return(err error) *BlobService_DeleteBlob_Call { + _c.Call.Return(err) + return _c +} + +func (_c *BlobService_DeleteBlob_Call) RunAndReturn(run func(ctx context.Context, c cid.Cid) error) *BlobService_DeleteBlob_Call { + _c.Call.Return(run) + return _c +} + +// Done provides a mock function for the type BlobService +func (_mock *BlobService) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// GetBlob provides a mock function with given fields: ctx, c -func (_m *BlobService) GetBlob(ctx context.Context, c cid.Cid) (blobs.Blob, error) { - ret := _m.Called(ctx, c) +// BlobService_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type BlobService_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *BlobService_Expecter) Done() *BlobService_Done_Call { + return &BlobService_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *BlobService_Done_Call) Run(run func()) *BlobService_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BlobService_Done_Call) Return(valCh <-chan struct{}) *BlobService_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *BlobService_Done_Call) RunAndReturn(run func() <-chan struct{}) *BlobService_Done_Call { + _c.Call.Return(run) + return _c +} + +// GetBlob provides a mock function for the type BlobService +func (_mock *BlobService) GetBlob(ctx context.Context, c cid.Cid) (blobs.Blob, error) { + ret := _mock.Called(ctx, c) if len(ret) == 0 { panic("no return value specified for GetBlob") @@ -104,119 +268,309 @@ func (_m *BlobService) GetBlob(ctx context.Context, c cid.Cid) (blobs.Blob, erro var r0 blobs.Blob var r1 error - if rf, ok := ret.Get(0).(func(context.Context, cid.Cid) (blobs.Blob, error)); ok { - return rf(ctx, c) + if returnFunc, ok := ret.Get(0).(func(context.Context, cid.Cid) (blobs.Blob, error)); ok { + return returnFunc(ctx, c) } - if rf, ok := ret.Get(0).(func(context.Context, cid.Cid) blobs.Blob); ok { - r0 = rf(ctx, c) + if returnFunc, ok := ret.Get(0).(func(context.Context, cid.Cid) blobs.Blob); ok { + r0 = returnFunc(ctx, c) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(blobs.Blob) } } - - if rf, ok := ret.Get(1).(func(context.Context, cid.Cid) error); ok { - r1 = rf(ctx, c) + if returnFunc, ok := ret.Get(1).(func(context.Context, cid.Cid) error); ok { + r1 = returnFunc(ctx, c) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetBlobs provides a mock function with given fields: ctx, ks -func (_m *BlobService) GetBlobs(ctx context.Context, ks []cid.Cid) <-chan blobs.Blob { - ret := _m.Called(ctx, ks) +// BlobService_GetBlob_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlob' +type BlobService_GetBlob_Call struct { + *mock.Call +} + +// GetBlob is a helper method to define mock.On call +// - ctx context.Context +// - c cid.Cid +func (_e *BlobService_Expecter) GetBlob(ctx interface{}, c interface{}) *BlobService_GetBlob_Call { + return &BlobService_GetBlob_Call{Call: _e.mock.On("GetBlob", ctx, c)} +} + +func (_c *BlobService_GetBlob_Call) Run(run func(ctx context.Context, c cid.Cid)) *BlobService_GetBlob_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 cid.Cid + if args[1] != nil { + arg1 = args[1].(cid.Cid) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlobService_GetBlob_Call) Return(v blobs.Blob, err error) *BlobService_GetBlob_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *BlobService_GetBlob_Call) RunAndReturn(run func(ctx context.Context, c cid.Cid) (blobs.Blob, error)) *BlobService_GetBlob_Call { + _c.Call.Return(run) + return _c +} + +// GetBlobs provides a mock function for the type BlobService +func (_mock *BlobService) GetBlobs(ctx context.Context, ks []cid.Cid) <-chan blobs.Blob { + ret := _mock.Called(ctx, ks) if len(ret) == 0 { panic("no return value specified for GetBlobs") } var r0 <-chan blobs.Blob - if rf, ok := ret.Get(0).(func(context.Context, []cid.Cid) <-chan blobs.Blob); ok { - r0 = rf(ctx, ks) + if returnFunc, ok := ret.Get(0).(func(context.Context, []cid.Cid) <-chan blobs.Blob); ok { + r0 = returnFunc(ctx, ks) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan blobs.Blob) } } - return r0 } -// GetSession provides a mock function with given fields: ctx -func (_m *BlobService) GetSession(ctx context.Context) network.BlobGetter { - ret := _m.Called(ctx) +// BlobService_GetBlobs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlobs' +type BlobService_GetBlobs_Call struct { + *mock.Call +} + +// GetBlobs is a helper method to define mock.On call +// - ctx context.Context +// - ks []cid.Cid +func (_e *BlobService_Expecter) GetBlobs(ctx interface{}, ks interface{}) *BlobService_GetBlobs_Call { + return &BlobService_GetBlobs_Call{Call: _e.mock.On("GetBlobs", ctx, ks)} +} + +func (_c *BlobService_GetBlobs_Call) Run(run func(ctx context.Context, ks []cid.Cid)) *BlobService_GetBlobs_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []cid.Cid + if args[1] != nil { + arg1 = args[1].([]cid.Cid) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlobService_GetBlobs_Call) Return(vCh <-chan blobs.Blob) *BlobService_GetBlobs_Call { + _c.Call.Return(vCh) + return _c +} + +func (_c *BlobService_GetBlobs_Call) RunAndReturn(run func(ctx context.Context, ks []cid.Cid) <-chan blobs.Blob) *BlobService_GetBlobs_Call { + _c.Call.Return(run) + return _c +} + +// GetSession provides a mock function for the type BlobService +func (_mock *BlobService) GetSession(ctx context.Context) network.BlobGetter { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for GetSession") } var r0 network.BlobGetter - if rf, ok := ret.Get(0).(func(context.Context) network.BlobGetter); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) network.BlobGetter); ok { + r0 = returnFunc(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.BlobGetter) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *BlobService) Ready() <-chan struct{} { - ret := _m.Called() +// BlobService_GetSession_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSession' +type BlobService_GetSession_Call struct { + *mock.Call +} + +// GetSession is a helper method to define mock.On call +// - ctx context.Context +func (_e *BlobService_Expecter) GetSession(ctx interface{}) *BlobService_GetSession_Call { + return &BlobService_GetSession_Call{Call: _e.mock.On("GetSession", ctx)} +} + +func (_c *BlobService_GetSession_Call) Run(run func(ctx context.Context)) *BlobService_GetSession_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlobService_GetSession_Call) Return(blobGetter network.BlobGetter) *BlobService_GetSession_Call { + _c.Call.Return(blobGetter) + return _c +} + +func (_c *BlobService_GetSession_Call) RunAndReturn(run func(ctx context.Context) network.BlobGetter) *BlobService_GetSession_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type BlobService +func (_mock *BlobService) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *BlobService) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// BlobService_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type BlobService_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *BlobService_Expecter) Ready() *BlobService_Ready_Call { + return &BlobService_Ready_Call{Call: _e.mock.On("Ready")} } -// TriggerReprovide provides a mock function with given fields: ctx -func (_m *BlobService) TriggerReprovide(ctx context.Context) error { - ret := _m.Called(ctx) +func (_c *BlobService_Ready_Call) Run(run func()) *BlobService_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BlobService_Ready_Call) Return(valCh <-chan struct{}) *BlobService_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *BlobService_Ready_Call) RunAndReturn(run func() <-chan struct{}) *BlobService_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type BlobService +func (_mock *BlobService) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// BlobService_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type BlobService_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *BlobService_Expecter) Start(signalerContext interface{}) *BlobService_Start_Call { + return &BlobService_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *BlobService_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *BlobService_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlobService_Start_Call) Return() *BlobService_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *BlobService_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *BlobService_Start_Call { + _c.Run(run) + return _c +} + +// TriggerReprovide provides a mock function for the type BlobService +func (_mock *BlobService) TriggerReprovide(ctx context.Context) error { + ret := _mock.Called(ctx) if len(ret) == 0 { panic("no return value specified for TriggerReprovide") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(ctx) + if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = returnFunc(ctx) } else { r0 = ret.Error(0) } - return r0 } -// NewBlobService creates a new instance of BlobService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlobService(t interface { - mock.TestingT - Cleanup(func()) -}) *BlobService { - mock := &BlobService{} - mock.Mock.Test(t) +// BlobService_TriggerReprovide_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TriggerReprovide' +type BlobService_TriggerReprovide_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TriggerReprovide is a helper method to define mock.On call +// - ctx context.Context +func (_e *BlobService_Expecter) TriggerReprovide(ctx interface{}) *BlobService_TriggerReprovide_Call { + return &BlobService_TriggerReprovide_Call{Call: _e.mock.On("TriggerReprovide", ctx)} +} - return mock +func (_c *BlobService_TriggerReprovide_Call) Run(run func(ctx context.Context)) *BlobService_TriggerReprovide_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlobService_TriggerReprovide_Call) Return(err error) *BlobService_TriggerReprovide_Call { + _c.Call.Return(err) + return _c +} + +func (_c *BlobService_TriggerReprovide_Call) RunAndReturn(run func(ctx context.Context) error) *BlobService_TriggerReprovide_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/codec.go b/network/mock/codec.go index 1f4c6662a00..eb8af8b0d2e 100644 --- a/network/mock/codec.go +++ b/network/mock/codec.go @@ -1,24 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - io "io" + "io" - messages "github.com/onflow/flow-go/model/messages" + "github.com/onflow/flow-go/model/messages" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewCodec creates a new instance of Codec. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCodec(t interface { + mock.TestingT + Cleanup(func()) +}) *Codec { + mock := &Codec{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Codec is an autogenerated mock type for the Codec type type Codec struct { mock.Mock } -// Decode provides a mock function with given fields: data -func (_m *Codec) Decode(data []byte) (messages.UntrustedMessage, error) { - ret := _m.Called(data) +type Codec_Expecter struct { + mock *mock.Mock +} + +func (_m *Codec) EXPECT() *Codec_Expecter { + return &Codec_Expecter{mock: &_m.Mock} +} + +// Decode provides a mock function for the type Codec +func (_mock *Codec) Decode(data []byte) (messages.UntrustedMessage, error) { + ret := _mock.Called(data) if len(ret) == 0 { panic("no return value specified for Decode") @@ -26,29 +49,61 @@ func (_m *Codec) Decode(data []byte) (messages.UntrustedMessage, error) { var r0 messages.UntrustedMessage var r1 error - if rf, ok := ret.Get(0).(func([]byte) (messages.UntrustedMessage, error)); ok { - return rf(data) + if returnFunc, ok := ret.Get(0).(func([]byte) (messages.UntrustedMessage, error)); ok { + return returnFunc(data) } - if rf, ok := ret.Get(0).(func([]byte) messages.UntrustedMessage); ok { - r0 = rf(data) + if returnFunc, ok := ret.Get(0).(func([]byte) messages.UntrustedMessage); ok { + r0 = returnFunc(data) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(messages.UntrustedMessage) } } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(data) + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(data) } else { r1 = ret.Error(1) } - return r0, r1 } -// Encode provides a mock function with given fields: v -func (_m *Codec) Encode(v interface{}) ([]byte, error) { - ret := _m.Called(v) +// Codec_Decode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Decode' +type Codec_Decode_Call struct { + *mock.Call +} + +// Decode is a helper method to define mock.On call +// - data []byte +func (_e *Codec_Expecter) Decode(data interface{}) *Codec_Decode_Call { + return &Codec_Decode_Call{Call: _e.mock.On("Decode", data)} +} + +func (_c *Codec_Decode_Call) Run(run func(data []byte)) *Codec_Decode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Codec_Decode_Call) Return(untrustedMessage messages.UntrustedMessage, err error) *Codec_Decode_Call { + _c.Call.Return(untrustedMessage, err) + return _c +} + +func (_c *Codec_Decode_Call) RunAndReturn(run func(data []byte) (messages.UntrustedMessage, error)) *Codec_Decode_Call { + _c.Call.Return(run) + return _c +} + +// Encode provides a mock function for the type Codec +func (_mock *Codec) Encode(v any) ([]byte, error) { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for Encode") @@ -56,76 +111,160 @@ func (_m *Codec) Encode(v interface{}) ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func(interface{}) ([]byte, error)); ok { - return rf(v) + if returnFunc, ok := ret.Get(0).(func(any) ([]byte, error)); ok { + return returnFunc(v) } - if rf, ok := ret.Get(0).(func(interface{}) []byte); ok { - r0 = rf(v) + if returnFunc, ok := ret.Get(0).(func(any) []byte); ok { + r0 = returnFunc(v) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func(interface{}) error); ok { - r1 = rf(v) + if returnFunc, ok := ret.Get(1).(func(any) error); ok { + r1 = returnFunc(v) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewDecoder provides a mock function with given fields: r -func (_m *Codec) NewDecoder(r io.Reader) network.Decoder { - ret := _m.Called(r) +// Codec_Encode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Encode' +type Codec_Encode_Call struct { + *mock.Call +} + +// Encode is a helper method to define mock.On call +// - v any +func (_e *Codec_Expecter) Encode(v interface{}) *Codec_Encode_Call { + return &Codec_Encode_Call{Call: _e.mock.On("Encode", v)} +} + +func (_c *Codec_Encode_Call) Run(run func(v any)) *Codec_Encode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Codec_Encode_Call) Return(bytes []byte, err error) *Codec_Encode_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Codec_Encode_Call) RunAndReturn(run func(v any) ([]byte, error)) *Codec_Encode_Call { + _c.Call.Return(run) + return _c +} + +// NewDecoder provides a mock function for the type Codec +func (_mock *Codec) NewDecoder(r io.Reader) network.Decoder { + ret := _mock.Called(r) if len(ret) == 0 { panic("no return value specified for NewDecoder") } var r0 network.Decoder - if rf, ok := ret.Get(0).(func(io.Reader) network.Decoder); ok { - r0 = rf(r) + if returnFunc, ok := ret.Get(0).(func(io.Reader) network.Decoder); ok { + r0 = returnFunc(r) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.Decoder) } } - return r0 } -// NewEncoder provides a mock function with given fields: w -func (_m *Codec) NewEncoder(w io.Writer) network.Encoder { - ret := _m.Called(w) +// Codec_NewDecoder_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewDecoder' +type Codec_NewDecoder_Call struct { + *mock.Call +} + +// NewDecoder is a helper method to define mock.On call +// - r io.Reader +func (_e *Codec_Expecter) NewDecoder(r interface{}) *Codec_NewDecoder_Call { + return &Codec_NewDecoder_Call{Call: _e.mock.On("NewDecoder", r)} +} + +func (_c *Codec_NewDecoder_Call) Run(run func(r io.Reader)) *Codec_NewDecoder_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 io.Reader + if args[0] != nil { + arg0 = args[0].(io.Reader) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Codec_NewDecoder_Call) Return(decoder network.Decoder) *Codec_NewDecoder_Call { + _c.Call.Return(decoder) + return _c +} + +func (_c *Codec_NewDecoder_Call) RunAndReturn(run func(r io.Reader) network.Decoder) *Codec_NewDecoder_Call { + _c.Call.Return(run) + return _c +} + +// NewEncoder provides a mock function for the type Codec +func (_mock *Codec) NewEncoder(w io.Writer) network.Encoder { + ret := _mock.Called(w) if len(ret) == 0 { panic("no return value specified for NewEncoder") } var r0 network.Encoder - if rf, ok := ret.Get(0).(func(io.Writer) network.Encoder); ok { - r0 = rf(w) + if returnFunc, ok := ret.Get(0).(func(io.Writer) network.Encoder); ok { + r0 = returnFunc(w) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.Encoder) } } - return r0 } -// NewCodec creates a new instance of Codec. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCodec(t interface { - mock.TestingT - Cleanup(func()) -}) *Codec { - mock := &Codec{} - mock.Mock.Test(t) +// Codec_NewEncoder_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewEncoder' +type Codec_NewEncoder_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NewEncoder is a helper method to define mock.On call +// - w io.Writer +func (_e *Codec_Expecter) NewEncoder(w interface{}) *Codec_NewEncoder_Call { + return &Codec_NewEncoder_Call{Call: _e.mock.On("NewEncoder", w)} +} - return mock +func (_c *Codec_NewEncoder_Call) Run(run func(w io.Writer)) *Codec_NewEncoder_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 io.Writer + if args[0] != nil { + arg0 = args[0].(io.Writer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Codec_NewEncoder_Call) Return(encoder network.Encoder) *Codec_NewEncoder_Call { + _c.Call.Return(encoder) + return _c +} + +func (_c *Codec_NewEncoder_Call) RunAndReturn(run func(w io.Writer) network.Encoder) *Codec_NewEncoder_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/compressor.go b/network/mock/compressor.go index 3392a78426e..3138f968464 100644 --- a/network/mock/compressor.go +++ b/network/mock/compressor.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - io "io" + "io" - network "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" ) +// NewCompressor creates a new instance of Compressor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCompressor(t interface { + mock.TestingT + Cleanup(func()) +}) *Compressor { + mock := &Compressor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Compressor is an autogenerated mock type for the Compressor type type Compressor struct { mock.Mock } -// NewReader provides a mock function with given fields: _a0 -func (_m *Compressor) NewReader(_a0 io.Reader) (io.ReadCloser, error) { - ret := _m.Called(_a0) +type Compressor_Expecter struct { + mock *mock.Mock +} + +func (_m *Compressor) EXPECT() *Compressor_Expecter { + return &Compressor_Expecter{mock: &_m.Mock} +} + +// NewReader provides a mock function for the type Compressor +func (_mock *Compressor) NewReader(reader io.Reader) (io.ReadCloser, error) { + ret := _mock.Called(reader) if len(ret) == 0 { panic("no return value specified for NewReader") @@ -24,29 +48,61 @@ func (_m *Compressor) NewReader(_a0 io.Reader) (io.ReadCloser, error) { var r0 io.ReadCloser var r1 error - if rf, ok := ret.Get(0).(func(io.Reader) (io.ReadCloser, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(io.Reader) (io.ReadCloser, error)); ok { + return returnFunc(reader) } - if rf, ok := ret.Get(0).(func(io.Reader) io.ReadCloser); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(io.Reader) io.ReadCloser); ok { + r0 = returnFunc(reader) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(io.ReadCloser) } } - - if rf, ok := ret.Get(1).(func(io.Reader) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(io.Reader) error); ok { + r1 = returnFunc(reader) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewWriter provides a mock function with given fields: _a0 -func (_m *Compressor) NewWriter(_a0 io.Writer) (network.WriteCloseFlusher, error) { - ret := _m.Called(_a0) +// Compressor_NewReader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewReader' +type Compressor_NewReader_Call struct { + *mock.Call +} + +// NewReader is a helper method to define mock.On call +// - reader io.Reader +func (_e *Compressor_Expecter) NewReader(reader interface{}) *Compressor_NewReader_Call { + return &Compressor_NewReader_Call{Call: _e.mock.On("NewReader", reader)} +} + +func (_c *Compressor_NewReader_Call) Run(run func(reader io.Reader)) *Compressor_NewReader_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 io.Reader + if args[0] != nil { + arg0 = args[0].(io.Reader) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compressor_NewReader_Call) Return(readCloser io.ReadCloser, err error) *Compressor_NewReader_Call { + _c.Call.Return(readCloser, err) + return _c +} + +func (_c *Compressor_NewReader_Call) RunAndReturn(run func(reader io.Reader) (io.ReadCloser, error)) *Compressor_NewReader_Call { + _c.Call.Return(run) + return _c +} + +// NewWriter provides a mock function for the type Compressor +func (_mock *Compressor) NewWriter(writer io.Writer) (network.WriteCloseFlusher, error) { + ret := _mock.Called(writer) if len(ret) == 0 { panic("no return value specified for NewWriter") @@ -54,36 +110,54 @@ func (_m *Compressor) NewWriter(_a0 io.Writer) (network.WriteCloseFlusher, error var r0 network.WriteCloseFlusher var r1 error - if rf, ok := ret.Get(0).(func(io.Writer) (network.WriteCloseFlusher, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(io.Writer) (network.WriteCloseFlusher, error)); ok { + return returnFunc(writer) } - if rf, ok := ret.Get(0).(func(io.Writer) network.WriteCloseFlusher); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(io.Writer) network.WriteCloseFlusher); ok { + r0 = returnFunc(writer) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.WriteCloseFlusher) } } - - if rf, ok := ret.Get(1).(func(io.Writer) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(io.Writer) error); ok { + r1 = returnFunc(writer) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewCompressor creates a new instance of Compressor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCompressor(t interface { - mock.TestingT - Cleanup(func()) -}) *Compressor { - mock := &Compressor{} - mock.Mock.Test(t) +// Compressor_NewWriter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewWriter' +type Compressor_NewWriter_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NewWriter is a helper method to define mock.On call +// - writer io.Writer +func (_e *Compressor_Expecter) NewWriter(writer interface{}) *Compressor_NewWriter_Call { + return &Compressor_NewWriter_Call{Call: _e.mock.On("NewWriter", writer)} +} - return mock +func (_c *Compressor_NewWriter_Call) Run(run func(writer io.Writer)) *Compressor_NewWriter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 io.Writer + if args[0] != nil { + arg0 = args[0].(io.Writer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Compressor_NewWriter_Call) Return(writeCloseFlusher network.WriteCloseFlusher, err error) *Compressor_NewWriter_Call { + _c.Call.Return(writeCloseFlusher, err) + return _c +} + +func (_c *Compressor_NewWriter_Call) RunAndReturn(run func(writer io.Writer) (network.WriteCloseFlusher, error)) *Compressor_NewWriter_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/conduit.go b/network/mock/conduit.go index d9d82ffaea0..f552834367d 100644 --- a/network/mock/conduit.go +++ b/network/mock/conduit.go @@ -1,39 +1,89 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewConduit creates a new instance of Conduit. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConduit(t interface { + mock.TestingT + Cleanup(func()) +}) *Conduit { + mock := &Conduit{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Conduit is an autogenerated mock type for the Conduit type type Conduit struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *Conduit) Close() error { - ret := _m.Called() +type Conduit_Expecter struct { + mock *mock.Mock +} + +func (_m *Conduit) EXPECT() *Conduit_Expecter { + return &Conduit_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type Conduit +func (_mock *Conduit) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Multicast provides a mock function with given fields: event, num, targetIDs -func (_m *Conduit) Multicast(event interface{}, num uint, targetIDs ...flow.Identifier) error { +// Conduit_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type Conduit_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *Conduit_Expecter) Close() *Conduit_Close_Call { + return &Conduit_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *Conduit_Close_Call) Run(run func()) *Conduit_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Conduit_Close_Call) Return(err error) *Conduit_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Conduit_Close_Call) RunAndReturn(run func() error) *Conduit_Close_Call { + _c.Call.Return(run) + return _c +} + +// Multicast provides a mock function for the type Conduit +func (_mock *Conduit) Multicast(event any, num uint, targetIDs ...flow.Identifier) error { + // flow.Identifier _va := make([]interface{}, len(targetIDs)) for _i := range targetIDs { _va[_i] = targetIDs[_i] @@ -41,24 +91,75 @@ func (_m *Conduit) Multicast(event interface{}, num uint, targetIDs ...flow.Iden var _ca []interface{} _ca = append(_ca, event, num) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for Multicast") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}, uint, ...flow.Identifier) error); ok { - r0 = rf(event, num, targetIDs...) + if returnFunc, ok := ret.Get(0).(func(any, uint, ...flow.Identifier) error); ok { + r0 = returnFunc(event, num, targetIDs...) } else { r0 = ret.Error(0) } - return r0 } -// Publish provides a mock function with given fields: event, targetIDs -func (_m *Conduit) Publish(event interface{}, targetIDs ...flow.Identifier) error { +// Conduit_Multicast_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Multicast' +type Conduit_Multicast_Call struct { + *mock.Call +} + +// Multicast is a helper method to define mock.On call +// - event any +// - num uint +// - targetIDs ...flow.Identifier +func (_e *Conduit_Expecter) Multicast(event interface{}, num interface{}, targetIDs ...interface{}) *Conduit_Multicast_Call { + return &Conduit_Multicast_Call{Call: _e.mock.On("Multicast", + append([]interface{}{event, num}, targetIDs...)...)} +} + +func (_c *Conduit_Multicast_Call) Run(run func(event any, num uint, targetIDs ...flow.Identifier)) *Conduit_Multicast_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + var arg1 uint + if args[1] != nil { + arg1 = args[1].(uint) + } + var arg2 []flow.Identifier + variadicArgs := make([]flow.Identifier, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(flow.Identifier) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *Conduit_Multicast_Call) Return(err error) *Conduit_Multicast_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Conduit_Multicast_Call) RunAndReturn(run func(event any, num uint, targetIDs ...flow.Identifier) error) *Conduit_Multicast_Call { + _c.Call.Return(run) + return _c +} + +// Publish provides a mock function for the type Conduit +func (_mock *Conduit) Publish(event any, targetIDs ...flow.Identifier) error { + // flow.Identifier _va := make([]interface{}, len(targetIDs)) for _i := range targetIDs { _va[_i] = targetIDs[_i] @@ -66,55 +167,159 @@ func (_m *Conduit) Publish(event interface{}, targetIDs ...flow.Identifier) erro var _ca []interface{} _ca = append(_ca, event) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for Publish") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}, ...flow.Identifier) error); ok { - r0 = rf(event, targetIDs...) + if returnFunc, ok := ret.Get(0).(func(any, ...flow.Identifier) error); ok { + r0 = returnFunc(event, targetIDs...) } else { r0 = ret.Error(0) } - return r0 } -// ReportMisbehavior provides a mock function with given fields: _a0 -func (_m *Conduit) ReportMisbehavior(_a0 network.MisbehaviorReport) { - _m.Called(_a0) +// Conduit_Publish_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Publish' +type Conduit_Publish_Call struct { + *mock.Call +} + +// Publish is a helper method to define mock.On call +// - event any +// - targetIDs ...flow.Identifier +func (_e *Conduit_Expecter) Publish(event interface{}, targetIDs ...interface{}) *Conduit_Publish_Call { + return &Conduit_Publish_Call{Call: _e.mock.On("Publish", + append([]interface{}{event}, targetIDs...)...)} +} + +func (_c *Conduit_Publish_Call) Run(run func(event any, targetIDs ...flow.Identifier)) *Conduit_Publish_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + var arg1 []flow.Identifier + variadicArgs := make([]flow.Identifier, len(args)-1) + for i, a := range args[1:] { + if a != nil { + variadicArgs[i] = a.(flow.Identifier) + } + } + arg1 = variadicArgs + run( + arg0, + arg1..., + ) + }) + return _c +} + +func (_c *Conduit_Publish_Call) Return(err error) *Conduit_Publish_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Conduit_Publish_Call) RunAndReturn(run func(event any, targetIDs ...flow.Identifier) error) *Conduit_Publish_Call { + _c.Call.Return(run) + return _c } -// Unicast provides a mock function with given fields: event, targetID -func (_m *Conduit) Unicast(event interface{}, targetID flow.Identifier) error { - ret := _m.Called(event, targetID) +// ReportMisbehavior provides a mock function for the type Conduit +func (_mock *Conduit) ReportMisbehavior(misbehaviorReport network.MisbehaviorReport) { + _mock.Called(misbehaviorReport) + return +} + +// Conduit_ReportMisbehavior_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReportMisbehavior' +type Conduit_ReportMisbehavior_Call struct { + *mock.Call +} + +// ReportMisbehavior is a helper method to define mock.On call +// - misbehaviorReport network.MisbehaviorReport +func (_e *Conduit_Expecter) ReportMisbehavior(misbehaviorReport interface{}) *Conduit_ReportMisbehavior_Call { + return &Conduit_ReportMisbehavior_Call{Call: _e.mock.On("ReportMisbehavior", misbehaviorReport)} +} + +func (_c *Conduit_ReportMisbehavior_Call) Run(run func(misbehaviorReport network.MisbehaviorReport)) *Conduit_ReportMisbehavior_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.MisbehaviorReport + if args[0] != nil { + arg0 = args[0].(network.MisbehaviorReport) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Conduit_ReportMisbehavior_Call) Return() *Conduit_ReportMisbehavior_Call { + _c.Call.Return() + return _c +} + +func (_c *Conduit_ReportMisbehavior_Call) RunAndReturn(run func(misbehaviorReport network.MisbehaviorReport)) *Conduit_ReportMisbehavior_Call { + _c.Run(run) + return _c +} + +// Unicast provides a mock function for the type Conduit +func (_mock *Conduit) Unicast(event any, targetID flow.Identifier) error { + ret := _mock.Called(event, targetID) if len(ret) == 0 { panic("no return value specified for Unicast") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}, flow.Identifier) error); ok { - r0 = rf(event, targetID) + if returnFunc, ok := ret.Get(0).(func(any, flow.Identifier) error); ok { + r0 = returnFunc(event, targetID) } else { r0 = ret.Error(0) } - return r0 } -// NewConduit creates a new instance of Conduit. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConduit(t interface { - mock.TestingT - Cleanup(func()) -}) *Conduit { - mock := &Conduit{} - mock.Mock.Test(t) +// Conduit_Unicast_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Unicast' +type Conduit_Unicast_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Unicast is a helper method to define mock.On call +// - event any +// - targetID flow.Identifier +func (_e *Conduit_Expecter) Unicast(event interface{}, targetID interface{}) *Conduit_Unicast_Call { + return &Conduit_Unicast_Call{Call: _e.mock.On("Unicast", event, targetID)} +} - return mock +func (_c *Conduit_Unicast_Call) Run(run func(event any, targetID flow.Identifier)) *Conduit_Unicast_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Conduit_Unicast_Call) Return(err error) *Conduit_Unicast_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Conduit_Unicast_Call) RunAndReturn(run func(event any, targetID flow.Identifier) error) *Conduit_Unicast_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/conduit_adapter.go b/network/mock/conduit_adapter.go index b2ccff46d04..42563b9a777 100644 --- a/network/mock/conduit_adapter.go +++ b/network/mock/conduit_adapter.go @@ -1,122 +1,357 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewConduitAdapter creates a new instance of ConduitAdapter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConduitAdapter(t interface { + mock.TestingT + Cleanup(func()) +}) *ConduitAdapter { + mock := &ConduitAdapter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ConduitAdapter is an autogenerated mock type for the ConduitAdapter type type ConduitAdapter struct { mock.Mock } -// MulticastOnChannel provides a mock function with given fields: _a0, _a1, _a2, _a3 -func (_m *ConduitAdapter) MulticastOnChannel(_a0 channels.Channel, _a1 interface{}, _a2 uint, _a3 ...flow.Identifier) error { - _va := make([]interface{}, len(_a3)) - for _i := range _a3 { - _va[_i] = _a3[_i] +type ConduitAdapter_Expecter struct { + mock *mock.Mock +} + +func (_m *ConduitAdapter) EXPECT() *ConduitAdapter_Expecter { + return &ConduitAdapter_Expecter{mock: &_m.Mock} +} + +// MulticastOnChannel provides a mock function for the type ConduitAdapter +func (_mock *ConduitAdapter) MulticastOnChannel(channel channels.Channel, v any, v1 uint, identifiers ...flow.Identifier) error { + // flow.Identifier + _va := make([]interface{}, len(identifiers)) + for _i := range identifiers { + _va[_i] = identifiers[_i] } var _ca []interface{} - _ca = append(_ca, _a0, _a1, _a2) + _ca = append(_ca, channel, v, v1) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for MulticastOnChannel") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel, interface{}, uint, ...flow.Identifier) error); ok { - r0 = rf(_a0, _a1, _a2, _a3...) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, any, uint, ...flow.Identifier) error); ok { + r0 = returnFunc(channel, v, v1, identifiers...) } else { r0 = ret.Error(0) } - return r0 } -// PublishOnChannel provides a mock function with given fields: _a0, _a1, _a2 -func (_m *ConduitAdapter) PublishOnChannel(_a0 channels.Channel, _a1 interface{}, _a2 ...flow.Identifier) error { - _va := make([]interface{}, len(_a2)) - for _i := range _a2 { - _va[_i] = _a2[_i] +// ConduitAdapter_MulticastOnChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MulticastOnChannel' +type ConduitAdapter_MulticastOnChannel_Call struct { + *mock.Call +} + +// MulticastOnChannel is a helper method to define mock.On call +// - channel channels.Channel +// - v any +// - v1 uint +// - identifiers ...flow.Identifier +func (_e *ConduitAdapter_Expecter) MulticastOnChannel(channel interface{}, v interface{}, v1 interface{}, identifiers ...interface{}) *ConduitAdapter_MulticastOnChannel_Call { + return &ConduitAdapter_MulticastOnChannel_Call{Call: _e.mock.On("MulticastOnChannel", + append([]interface{}{channel, v, v1}, identifiers...)...)} +} + +func (_c *ConduitAdapter_MulticastOnChannel_Call) Run(run func(channel channels.Channel, v any, v1 uint, identifiers ...flow.Identifier)) *ConduitAdapter_MulticastOnChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 any + if args[1] != nil { + arg1 = args[1].(any) + } + var arg2 uint + if args[2] != nil { + arg2 = args[2].(uint) + } + var arg3 []flow.Identifier + variadicArgs := make([]flow.Identifier, len(args)-3) + for i, a := range args[3:] { + if a != nil { + variadicArgs[i] = a.(flow.Identifier) + } + } + arg3 = variadicArgs + run( + arg0, + arg1, + arg2, + arg3..., + ) + }) + return _c +} + +func (_c *ConduitAdapter_MulticastOnChannel_Call) Return(err error) *ConduitAdapter_MulticastOnChannel_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConduitAdapter_MulticastOnChannel_Call) RunAndReturn(run func(channel channels.Channel, v any, v1 uint, identifiers ...flow.Identifier) error) *ConduitAdapter_MulticastOnChannel_Call { + _c.Call.Return(run) + return _c +} + +// PublishOnChannel provides a mock function for the type ConduitAdapter +func (_mock *ConduitAdapter) PublishOnChannel(channel channels.Channel, v any, identifiers ...flow.Identifier) error { + // flow.Identifier + _va := make([]interface{}, len(identifiers)) + for _i := range identifiers { + _va[_i] = identifiers[_i] } var _ca []interface{} - _ca = append(_ca, _a0, _a1) + _ca = append(_ca, channel, v) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for PublishOnChannel") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel, interface{}, ...flow.Identifier) error); ok { - r0 = rf(_a0, _a1, _a2...) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, any, ...flow.Identifier) error); ok { + r0 = returnFunc(channel, v, identifiers...) } else { r0 = ret.Error(0) } - return r0 } -// ReportMisbehaviorOnChannel provides a mock function with given fields: channel, report -func (_m *ConduitAdapter) ReportMisbehaviorOnChannel(channel channels.Channel, report network.MisbehaviorReport) { - _m.Called(channel, report) +// ConduitAdapter_PublishOnChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PublishOnChannel' +type ConduitAdapter_PublishOnChannel_Call struct { + *mock.Call +} + +// PublishOnChannel is a helper method to define mock.On call +// - channel channels.Channel +// - v any +// - identifiers ...flow.Identifier +func (_e *ConduitAdapter_Expecter) PublishOnChannel(channel interface{}, v interface{}, identifiers ...interface{}) *ConduitAdapter_PublishOnChannel_Call { + return &ConduitAdapter_PublishOnChannel_Call{Call: _e.mock.On("PublishOnChannel", + append([]interface{}{channel, v}, identifiers...)...)} +} + +func (_c *ConduitAdapter_PublishOnChannel_Call) Run(run func(channel channels.Channel, v any, identifiers ...flow.Identifier)) *ConduitAdapter_PublishOnChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 any + if args[1] != nil { + arg1 = args[1].(any) + } + var arg2 []flow.Identifier + variadicArgs := make([]flow.Identifier, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(flow.Identifier) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *ConduitAdapter_PublishOnChannel_Call) Return(err error) *ConduitAdapter_PublishOnChannel_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConduitAdapter_PublishOnChannel_Call) RunAndReturn(run func(channel channels.Channel, v any, identifiers ...flow.Identifier) error) *ConduitAdapter_PublishOnChannel_Call { + _c.Call.Return(run) + return _c } -// UnRegisterChannel provides a mock function with given fields: channel -func (_m *ConduitAdapter) UnRegisterChannel(channel channels.Channel) error { - ret := _m.Called(channel) +// ReportMisbehaviorOnChannel provides a mock function for the type ConduitAdapter +func (_mock *ConduitAdapter) ReportMisbehaviorOnChannel(channel channels.Channel, report network.MisbehaviorReport) { + _mock.Called(channel, report) + return +} + +// ConduitAdapter_ReportMisbehaviorOnChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReportMisbehaviorOnChannel' +type ConduitAdapter_ReportMisbehaviorOnChannel_Call struct { + *mock.Call +} + +// ReportMisbehaviorOnChannel is a helper method to define mock.On call +// - channel channels.Channel +// - report network.MisbehaviorReport +func (_e *ConduitAdapter_Expecter) ReportMisbehaviorOnChannel(channel interface{}, report interface{}) *ConduitAdapter_ReportMisbehaviorOnChannel_Call { + return &ConduitAdapter_ReportMisbehaviorOnChannel_Call{Call: _e.mock.On("ReportMisbehaviorOnChannel", channel, report)} +} + +func (_c *ConduitAdapter_ReportMisbehaviorOnChannel_Call) Run(run func(channel channels.Channel, report network.MisbehaviorReport)) *ConduitAdapter_ReportMisbehaviorOnChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 network.MisbehaviorReport + if args[1] != nil { + arg1 = args[1].(network.MisbehaviorReport) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ConduitAdapter_ReportMisbehaviorOnChannel_Call) Return() *ConduitAdapter_ReportMisbehaviorOnChannel_Call { + _c.Call.Return() + return _c +} + +func (_c *ConduitAdapter_ReportMisbehaviorOnChannel_Call) RunAndReturn(run func(channel channels.Channel, report network.MisbehaviorReport)) *ConduitAdapter_ReportMisbehaviorOnChannel_Call { + _c.Run(run) + return _c +} + +// UnRegisterChannel provides a mock function for the type ConduitAdapter +func (_mock *ConduitAdapter) UnRegisterChannel(channel channels.Channel) error { + ret := _mock.Called(channel) if len(ret) == 0 { panic("no return value specified for UnRegisterChannel") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel) error); ok { - r0 = rf(channel) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) error); ok { + r0 = returnFunc(channel) } else { r0 = ret.Error(0) } - return r0 } -// UnicastOnChannel provides a mock function with given fields: _a0, _a1, _a2 -func (_m *ConduitAdapter) UnicastOnChannel(_a0 channels.Channel, _a1 interface{}, _a2 flow.Identifier) error { - ret := _m.Called(_a0, _a1, _a2) +// ConduitAdapter_UnRegisterChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnRegisterChannel' +type ConduitAdapter_UnRegisterChannel_Call struct { + *mock.Call +} + +// UnRegisterChannel is a helper method to define mock.On call +// - channel channels.Channel +func (_e *ConduitAdapter_Expecter) UnRegisterChannel(channel interface{}) *ConduitAdapter_UnRegisterChannel_Call { + return &ConduitAdapter_UnRegisterChannel_Call{Call: _e.mock.On("UnRegisterChannel", channel)} +} + +func (_c *ConduitAdapter_UnRegisterChannel_Call) Run(run func(channel channels.Channel)) *ConduitAdapter_UnRegisterChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConduitAdapter_UnRegisterChannel_Call) Return(err error) *ConduitAdapter_UnRegisterChannel_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConduitAdapter_UnRegisterChannel_Call) RunAndReturn(run func(channel channels.Channel) error) *ConduitAdapter_UnRegisterChannel_Call { + _c.Call.Return(run) + return _c +} + +// UnicastOnChannel provides a mock function for the type ConduitAdapter +func (_mock *ConduitAdapter) UnicastOnChannel(channel channels.Channel, v any, identifier flow.Identifier) error { + ret := _mock.Called(channel, v, identifier) if len(ret) == 0 { panic("no return value specified for UnicastOnChannel") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel, interface{}, flow.Identifier) error); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, any, flow.Identifier) error); ok { + r0 = returnFunc(channel, v, identifier) } else { r0 = ret.Error(0) } - return r0 } -// NewConduitAdapter creates a new instance of ConduitAdapter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConduitAdapter(t interface { - mock.TestingT - Cleanup(func()) -}) *ConduitAdapter { - mock := &ConduitAdapter{} - mock.Mock.Test(t) +// ConduitAdapter_UnicastOnChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnicastOnChannel' +type ConduitAdapter_UnicastOnChannel_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UnicastOnChannel is a helper method to define mock.On call +// - channel channels.Channel +// - v any +// - identifier flow.Identifier +func (_e *ConduitAdapter_Expecter) UnicastOnChannel(channel interface{}, v interface{}, identifier interface{}) *ConduitAdapter_UnicastOnChannel_Call { + return &ConduitAdapter_UnicastOnChannel_Call{Call: _e.mock.On("UnicastOnChannel", channel, v, identifier)} +} - return mock +func (_c *ConduitAdapter_UnicastOnChannel_Call) Run(run func(channel channels.Channel, v any, identifier flow.Identifier)) *ConduitAdapter_UnicastOnChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 any + if args[1] != nil { + arg1 = args[1].(any) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ConduitAdapter_UnicastOnChannel_Call) Return(err error) *ConduitAdapter_UnicastOnChannel_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConduitAdapter_UnicastOnChannel_Call) RunAndReturn(run func(channel channels.Channel, v any, identifier flow.Identifier) error) *ConduitAdapter_UnicastOnChannel_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/conduit_factory.go b/network/mock/conduit_factory.go index 249b24b0d59..610ffd338a2 100644 --- a/network/mock/conduit_factory.go +++ b/network/mock/conduit_factory.go @@ -1,25 +1,47 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - channels "github.com/onflow/flow-go/network/channels" + "context" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewConduitFactory creates a new instance of ConduitFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConduitFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *ConduitFactory { + mock := &ConduitFactory{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ConduitFactory is an autogenerated mock type for the ConduitFactory type type ConduitFactory struct { mock.Mock } -// NewConduit provides a mock function with given fields: _a0, _a1 -func (_m *ConduitFactory) NewConduit(_a0 context.Context, _a1 channels.Channel) (network.Conduit, error) { - ret := _m.Called(_a0, _a1) +type ConduitFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *ConduitFactory) EXPECT() *ConduitFactory_Expecter { + return &ConduitFactory_Expecter{mock: &_m.Mock} +} + +// NewConduit provides a mock function for the type ConduitFactory +func (_mock *ConduitFactory) NewConduit(context1 context.Context, channel channels.Channel) (network.Conduit, error) { + ret := _mock.Called(context1, channel) if len(ret) == 0 { panic("no return value specified for NewConduit") @@ -27,54 +49,111 @@ func (_m *ConduitFactory) NewConduit(_a0 context.Context, _a1 channels.Channel) var r0 network.Conduit var r1 error - if rf, ok := ret.Get(0).(func(context.Context, channels.Channel) (network.Conduit, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, channels.Channel) (network.Conduit, error)); ok { + return returnFunc(context1, channel) } - if rf, ok := ret.Get(0).(func(context.Context, channels.Channel) network.Conduit); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, channels.Channel) network.Conduit); ok { + r0 = returnFunc(context1, channel) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.Conduit) } } - - if rf, ok := ret.Get(1).(func(context.Context, channels.Channel) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(context.Context, channels.Channel) error); ok { + r1 = returnFunc(context1, channel) } else { r1 = ret.Error(1) } - return r0, r1 } -// RegisterAdapter provides a mock function with given fields: _a0 -func (_m *ConduitFactory) RegisterAdapter(_a0 network.ConduitAdapter) error { - ret := _m.Called(_a0) +// ConduitFactory_NewConduit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewConduit' +type ConduitFactory_NewConduit_Call struct { + *mock.Call +} + +// NewConduit is a helper method to define mock.On call +// - context1 context.Context +// - channel channels.Channel +func (_e *ConduitFactory_Expecter) NewConduit(context1 interface{}, channel interface{}) *ConduitFactory_NewConduit_Call { + return &ConduitFactory_NewConduit_Call{Call: _e.mock.On("NewConduit", context1, channel)} +} + +func (_c *ConduitFactory_NewConduit_Call) Run(run func(context1 context.Context, channel channels.Channel)) *ConduitFactory_NewConduit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 channels.Channel + if args[1] != nil { + arg1 = args[1].(channels.Channel) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ConduitFactory_NewConduit_Call) Return(conduit network.Conduit, err error) *ConduitFactory_NewConduit_Call { + _c.Call.Return(conduit, err) + return _c +} + +func (_c *ConduitFactory_NewConduit_Call) RunAndReturn(run func(context1 context.Context, channel channels.Channel) (network.Conduit, error)) *ConduitFactory_NewConduit_Call { + _c.Call.Return(run) + return _c +} + +// RegisterAdapter provides a mock function for the type ConduitFactory +func (_mock *ConduitFactory) RegisterAdapter(conduitAdapter network.ConduitAdapter) error { + ret := _mock.Called(conduitAdapter) if len(ret) == 0 { panic("no return value specified for RegisterAdapter") } var r0 error - if rf, ok := ret.Get(0).(func(network.ConduitAdapter) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(network.ConduitAdapter) error); ok { + r0 = returnFunc(conduitAdapter) } else { r0 = ret.Error(0) } - return r0 } -// NewConduitFactory creates a new instance of ConduitFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConduitFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *ConduitFactory { - mock := &ConduitFactory{} - mock.Mock.Test(t) +// ConduitFactory_RegisterAdapter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterAdapter' +type ConduitFactory_RegisterAdapter_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RegisterAdapter is a helper method to define mock.On call +// - conduitAdapter network.ConduitAdapter +func (_e *ConduitFactory_Expecter) RegisterAdapter(conduitAdapter interface{}) *ConduitFactory_RegisterAdapter_Call { + return &ConduitFactory_RegisterAdapter_Call{Call: _e.mock.On("RegisterAdapter", conduitAdapter)} +} - return mock +func (_c *ConduitFactory_RegisterAdapter_Call) Run(run func(conduitAdapter network.ConduitAdapter)) *ConduitFactory_RegisterAdapter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.ConduitAdapter + if args[0] != nil { + arg0 = args[0].(network.ConduitAdapter) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConduitFactory_RegisterAdapter_Call) Return(err error) *ConduitFactory_RegisterAdapter_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConduitFactory_RegisterAdapter_Call) RunAndReturn(run func(conduitAdapter network.ConduitAdapter) error) *ConduitFactory_RegisterAdapter_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/connection.go b/network/mock/connection.go index d31100e1fea..3a3fad5d1c0 100644 --- a/network/mock/connection.go +++ b/network/mock/connection.go @@ -1,72 +1,142 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewConnection creates a new instance of Connection. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConnection(t interface { + mock.TestingT + Cleanup(func()) +}) *Connection { + mock := &Connection{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Connection is an autogenerated mock type for the Connection type type Connection struct { mock.Mock } -// Receive provides a mock function with no fields -func (_m *Connection) Receive() (interface{}, error) { - ret := _m.Called() +type Connection_Expecter struct { + mock *mock.Mock +} + +func (_m *Connection) EXPECT() *Connection_Expecter { + return &Connection_Expecter{mock: &_m.Mock} +} + +// Receive provides a mock function for the type Connection +func (_mock *Connection) Receive() (any, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Receive") } - var r0 interface{} + var r0 any var r1 error - if rf, ok := ret.Get(0).(func() (interface{}, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (any, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() interface{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() any); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(interface{}) + r0 = ret.Get(0).(any) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Send provides a mock function with given fields: msg -func (_m *Connection) Send(msg interface{}) error { - ret := _m.Called(msg) +// Connection_Receive_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Receive' +type Connection_Receive_Call struct { + *mock.Call +} + +// Receive is a helper method to define mock.On call +func (_e *Connection_Expecter) Receive() *Connection_Receive_Call { + return &Connection_Receive_Call{Call: _e.mock.On("Receive")} +} + +func (_c *Connection_Receive_Call) Run(run func()) *Connection_Receive_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Connection_Receive_Call) Return(v any, err error) *Connection_Receive_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Connection_Receive_Call) RunAndReturn(run func() (any, error)) *Connection_Receive_Call { + _c.Call.Return(run) + return _c +} + +// Send provides a mock function for the type Connection +func (_mock *Connection) Send(msg any) error { + ret := _mock.Called(msg) if len(ret) == 0 { panic("no return value specified for Send") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}) error); ok { - r0 = rf(msg) + if returnFunc, ok := ret.Get(0).(func(any) error); ok { + r0 = returnFunc(msg) } else { r0 = ret.Error(0) } - return r0 } -// NewConnection creates a new instance of Connection. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConnection(t interface { - mock.TestingT - Cleanup(func()) -}) *Connection { - mock := &Connection{} - mock.Mock.Test(t) +// Connection_Send_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Send' +type Connection_Send_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Send is a helper method to define mock.On call +// - msg any +func (_e *Connection_Expecter) Send(msg interface{}) *Connection_Send_Call { + return &Connection_Send_Call{Call: _e.mock.On("Send", msg)} +} - return mock +func (_c *Connection_Send_Call) Run(run func(msg any)) *Connection_Send_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Connection_Send_Call) Return(err error) *Connection_Send_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Connection_Send_Call) RunAndReturn(run func(msg any) error) *Connection_Send_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/decoder.go b/network/mock/decoder.go index 631f3977cff..eca3c21c9db 100644 --- a/network/mock/decoder.go +++ b/network/mock/decoder.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - messages "github.com/onflow/flow-go/model/messages" + "github.com/onflow/flow-go/model/messages" mock "github.com/stretchr/testify/mock" ) +// NewDecoder creates a new instance of Decoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDecoder(t interface { + mock.TestingT + Cleanup(func()) +}) *Decoder { + mock := &Decoder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Decoder is an autogenerated mock type for the Decoder type type Decoder struct { mock.Mock } -// Decode provides a mock function with no fields -func (_m *Decoder) Decode() (messages.UntrustedMessage, error) { - ret := _m.Called() +type Decoder_Expecter struct { + mock *mock.Mock +} + +func (_m *Decoder) EXPECT() *Decoder_Expecter { + return &Decoder_Expecter{mock: &_m.Mock} +} + +// Decode provides a mock function for the type Decoder +func (_mock *Decoder) Decode() (messages.UntrustedMessage, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Decode") @@ -22,36 +46,47 @@ func (_m *Decoder) Decode() (messages.UntrustedMessage, error) { var r0 messages.UntrustedMessage var r1 error - if rf, ok := ret.Get(0).(func() (messages.UntrustedMessage, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (messages.UntrustedMessage, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() messages.UntrustedMessage); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() messages.UntrustedMessage); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(messages.UntrustedMessage) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewDecoder creates a new instance of Decoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDecoder(t interface { - mock.TestingT - Cleanup(func()) -}) *Decoder { - mock := &Decoder{} - mock.Mock.Test(t) +// Decoder_Decode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Decode' +type Decoder_Decode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Decode is a helper method to define mock.On call +func (_e *Decoder_Expecter) Decode() *Decoder_Decode_Call { + return &Decoder_Decode_Call{Call: _e.mock.On("Decode")} +} - return mock +func (_c *Decoder_Decode_Call) Run(run func()) *Decoder_Decode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Decoder_Decode_Call) Return(untrustedMessage messages.UntrustedMessage, err error) *Decoder_Decode_Call { + _c.Call.Return(untrustedMessage, err) + return _c +} + +func (_c *Decoder_Decode_Call) RunAndReturn(run func() (messages.UntrustedMessage, error)) *Decoder_Decode_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/disallow_list_notification_consumer.go b/network/mock/disallow_list_notification_consumer.go index 4b983dfb817..5e7534c4c3e 100644 --- a/network/mock/disallow_list_notification_consumer.go +++ b/network/mock/disallow_list_notification_consumer.go @@ -1,27 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" ) -// DisallowListNotificationConsumer is an autogenerated mock type for the DisallowListNotificationConsumer type -type DisallowListNotificationConsumer struct { - mock.Mock -} - -// OnAllowListNotification provides a mock function with given fields: _a0 -func (_m *DisallowListNotificationConsumer) OnAllowListNotification(_a0 *network.AllowListingUpdate) { - _m.Called(_a0) -} - -// OnDisallowListNotification provides a mock function with given fields: _a0 -func (_m *DisallowListNotificationConsumer) OnDisallowListNotification(_a0 *network.DisallowListingUpdate) { - _m.Called(_a0) -} - // NewDisallowListNotificationConsumer creates a new instance of DisallowListNotificationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewDisallowListNotificationConsumer(t interface { @@ -35,3 +22,96 @@ func NewDisallowListNotificationConsumer(t interface { return mock } + +// DisallowListNotificationConsumer is an autogenerated mock type for the DisallowListNotificationConsumer type +type DisallowListNotificationConsumer struct { + mock.Mock +} + +type DisallowListNotificationConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *DisallowListNotificationConsumer) EXPECT() *DisallowListNotificationConsumer_Expecter { + return &DisallowListNotificationConsumer_Expecter{mock: &_m.Mock} +} + +// OnAllowListNotification provides a mock function for the type DisallowListNotificationConsumer +func (_mock *DisallowListNotificationConsumer) OnAllowListNotification(allowListingUpdate *network.AllowListingUpdate) { + _mock.Called(allowListingUpdate) + return +} + +// DisallowListNotificationConsumer_OnAllowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAllowListNotification' +type DisallowListNotificationConsumer_OnAllowListNotification_Call struct { + *mock.Call +} + +// OnAllowListNotification is a helper method to define mock.On call +// - allowListingUpdate *network.AllowListingUpdate +func (_e *DisallowListNotificationConsumer_Expecter) OnAllowListNotification(allowListingUpdate interface{}) *DisallowListNotificationConsumer_OnAllowListNotification_Call { + return &DisallowListNotificationConsumer_OnAllowListNotification_Call{Call: _e.mock.On("OnAllowListNotification", allowListingUpdate)} +} + +func (_c *DisallowListNotificationConsumer_OnAllowListNotification_Call) Run(run func(allowListingUpdate *network.AllowListingUpdate)) *DisallowListNotificationConsumer_OnAllowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.AllowListingUpdate + if args[0] != nil { + arg0 = args[0].(*network.AllowListingUpdate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DisallowListNotificationConsumer_OnAllowListNotification_Call) Return() *DisallowListNotificationConsumer_OnAllowListNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *DisallowListNotificationConsumer_OnAllowListNotification_Call) RunAndReturn(run func(allowListingUpdate *network.AllowListingUpdate)) *DisallowListNotificationConsumer_OnAllowListNotification_Call { + _c.Run(run) + return _c +} + +// OnDisallowListNotification provides a mock function for the type DisallowListNotificationConsumer +func (_mock *DisallowListNotificationConsumer) OnDisallowListNotification(disallowListingUpdate *network.DisallowListingUpdate) { + _mock.Called(disallowListingUpdate) + return +} + +// DisallowListNotificationConsumer_OnDisallowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDisallowListNotification' +type DisallowListNotificationConsumer_OnDisallowListNotification_Call struct { + *mock.Call +} + +// OnDisallowListNotification is a helper method to define mock.On call +// - disallowListingUpdate *network.DisallowListingUpdate +func (_e *DisallowListNotificationConsumer_Expecter) OnDisallowListNotification(disallowListingUpdate interface{}) *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + return &DisallowListNotificationConsumer_OnDisallowListNotification_Call{Call: _e.mock.On("OnDisallowListNotification", disallowListingUpdate)} +} + +func (_c *DisallowListNotificationConsumer_OnDisallowListNotification_Call) Run(run func(disallowListingUpdate *network.DisallowListingUpdate)) *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.DisallowListingUpdate + if args[0] != nil { + arg0 = args[0].(*network.DisallowListingUpdate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DisallowListNotificationConsumer_OnDisallowListNotification_Call) Return() *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *DisallowListNotificationConsumer_OnDisallowListNotification_Call) RunAndReturn(run func(disallowListingUpdate *network.DisallowListingUpdate)) *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + _c.Run(run) + return _c +} diff --git a/network/mock/encoder.go b/network/mock/encoder.go index 36600dfb412..bc908bda168 100644 --- a/network/mock/encoder.go +++ b/network/mock/encoder.go @@ -1,42 +1,87 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewEncoder creates a new instance of Encoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEncoder(t interface { + mock.TestingT + Cleanup(func()) +}) *Encoder { + mock := &Encoder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Encoder is an autogenerated mock type for the Encoder type type Encoder struct { mock.Mock } -// Encode provides a mock function with given fields: v -func (_m *Encoder) Encode(v interface{}) error { - ret := _m.Called(v) +type Encoder_Expecter struct { + mock *mock.Mock +} + +func (_m *Encoder) EXPECT() *Encoder_Expecter { + return &Encoder_Expecter{mock: &_m.Mock} +} + +// Encode provides a mock function for the type Encoder +func (_mock *Encoder) Encode(v any) error { + ret := _mock.Called(v) if len(ret) == 0 { panic("no return value specified for Encode") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}) error); ok { - r0 = rf(v) + if returnFunc, ok := ret.Get(0).(func(any) error); ok { + r0 = returnFunc(v) } else { r0 = ret.Error(0) } - return r0 } -// NewEncoder creates a new instance of Encoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEncoder(t interface { - mock.TestingT - Cleanup(func()) -}) *Encoder { - mock := &Encoder{} - mock.Mock.Test(t) +// Encoder_Encode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Encode' +type Encoder_Encode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Encode is a helper method to define mock.On call +// - v any +func (_e *Encoder_Expecter) Encode(v interface{}) *Encoder_Encode_Call { + return &Encoder_Encode_Call{Call: _e.mock.On("Encode", v)} +} - return mock +func (_c *Encoder_Encode_Call) Run(run func(v any)) *Encoder_Encode_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Encoder_Encode_Call) Return(err error) *Encoder_Encode_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Encoder_Encode_Call) RunAndReturn(run func(v any) error) *Encoder_Encode_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/engine.go b/network/mock/engine.go index a0c10674757..b956d4e26de 100644 --- a/network/mock/engine.go +++ b/network/mock/engine.go @@ -1,115 +1,336 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" ) +// NewEngine creates a new instance of Engine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEngine(t interface { + mock.TestingT + Cleanup(func()) +}) *Engine { + mock := &Engine{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Engine is an autogenerated mock type for the Engine type type Engine struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *Engine) Done() <-chan struct{} { - ret := _m.Called() +type Engine_Expecter struct { + mock *mock.Mock +} + +func (_m *Engine) EXPECT() *Engine_Expecter { + return &Engine_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type Engine +func (_mock *Engine) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Process provides a mock function with given fields: channel, originID, event -func (_m *Engine) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { - ret := _m.Called(channel, originID, event) +// Engine_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Engine_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Engine_Expecter) Done() *Engine_Done_Call { + return &Engine_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Engine_Done_Call) Run(run func()) *Engine_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Engine_Done_Call) Return(valCh <-chan struct{}) *Engine_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Engine_Done_Call) RunAndReturn(run func() <-chan struct{}) *Engine_Done_Call { + _c.Call.Return(run) + return _c +} + +// Process provides a mock function for the type Engine +func (_mock *Engine) Process(channel channels.Channel, originID flow.Identifier, event any) error { + ret := _mock.Called(channel, originID, event) if len(ret) == 0 { panic("no return value specified for Process") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel, flow.Identifier, interface{}) error); ok { - r0 = rf(channel, originID, event) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, flow.Identifier, any) error); ok { + r0 = returnFunc(channel, originID, event) } else { r0 = ret.Error(0) } - return r0 } -// ProcessLocal provides a mock function with given fields: event -func (_m *Engine) ProcessLocal(event interface{}) error { - ret := _m.Called(event) +// Engine_Process_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Process' +type Engine_Process_Call struct { + *mock.Call +} + +// Process is a helper method to define mock.On call +// - channel channels.Channel +// - originID flow.Identifier +// - event any +func (_e *Engine_Expecter) Process(channel interface{}, originID interface{}, event interface{}) *Engine_Process_Call { + return &Engine_Process_Call{Call: _e.mock.On("Process", channel, originID, event)} +} + +func (_c *Engine_Process_Call) Run(run func(channel channels.Channel, originID flow.Identifier, event any)) *Engine_Process_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 any + if args[2] != nil { + arg2 = args[2].(any) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Engine_Process_Call) Return(err error) *Engine_Process_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Engine_Process_Call) RunAndReturn(run func(channel channels.Channel, originID flow.Identifier, event any) error) *Engine_Process_Call { + _c.Call.Return(run) + return _c +} + +// ProcessLocal provides a mock function for the type Engine +func (_mock *Engine) ProcessLocal(event any) error { + ret := _mock.Called(event) if len(ret) == 0 { panic("no return value specified for ProcessLocal") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}) error); ok { - r0 = rf(event) + if returnFunc, ok := ret.Get(0).(func(any) error); ok { + r0 = returnFunc(event) } else { r0 = ret.Error(0) } - return r0 } -// Ready provides a mock function with no fields -func (_m *Engine) Ready() <-chan struct{} { - ret := _m.Called() +// Engine_ProcessLocal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessLocal' +type Engine_ProcessLocal_Call struct { + *mock.Call +} + +// ProcessLocal is a helper method to define mock.On call +// - event any +func (_e *Engine_Expecter) ProcessLocal(event interface{}) *Engine_ProcessLocal_Call { + return &Engine_ProcessLocal_Call{Call: _e.mock.On("ProcessLocal", event)} +} + +func (_c *Engine_ProcessLocal_Call) Run(run func(event any)) *Engine_ProcessLocal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Engine_ProcessLocal_Call) Return(err error) *Engine_ProcessLocal_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Engine_ProcessLocal_Call) RunAndReturn(run func(event any) error) *Engine_ProcessLocal_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type Engine +func (_mock *Engine) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Submit provides a mock function with given fields: channel, originID, event -func (_m *Engine) Submit(channel channels.Channel, originID flow.Identifier, event interface{}) { - _m.Called(channel, originID, event) +// Engine_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Engine_Ready_Call struct { + *mock.Call } -// SubmitLocal provides a mock function with given fields: event -func (_m *Engine) SubmitLocal(event interface{}) { - _m.Called(event) +// Ready is a helper method to define mock.On call +func (_e *Engine_Expecter) Ready() *Engine_Ready_Call { + return &Engine_Ready_Call{Call: _e.mock.On("Ready")} } -// NewEngine creates a new instance of Engine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEngine(t interface { - mock.TestingT - Cleanup(func()) -}) *Engine { - mock := &Engine{} - mock.Mock.Test(t) +func (_c *Engine_Ready_Call) Run(run func()) *Engine_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *Engine_Ready_Call) Return(valCh <-chan struct{}) *Engine_Ready_Call { + _c.Call.Return(valCh) + return _c +} - return mock +func (_c *Engine_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Engine_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Submit provides a mock function for the type Engine +func (_mock *Engine) Submit(channel channels.Channel, originID flow.Identifier, event any) { + _mock.Called(channel, originID, event) + return +} + +// Engine_Submit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Submit' +type Engine_Submit_Call struct { + *mock.Call +} + +// Submit is a helper method to define mock.On call +// - channel channels.Channel +// - originID flow.Identifier +// - event any +func (_e *Engine_Expecter) Submit(channel interface{}, originID interface{}, event interface{}) *Engine_Submit_Call { + return &Engine_Submit_Call{Call: _e.mock.On("Submit", channel, originID, event)} +} + +func (_c *Engine_Submit_Call) Run(run func(channel channels.Channel, originID flow.Identifier, event any)) *Engine_Submit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 any + if args[2] != nil { + arg2 = args[2].(any) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Engine_Submit_Call) Return() *Engine_Submit_Call { + _c.Call.Return() + return _c +} + +func (_c *Engine_Submit_Call) RunAndReturn(run func(channel channels.Channel, originID flow.Identifier, event any)) *Engine_Submit_Call { + _c.Run(run) + return _c +} + +// SubmitLocal provides a mock function for the type Engine +func (_mock *Engine) SubmitLocal(event any) { + _mock.Called(event) + return +} + +// Engine_SubmitLocal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitLocal' +type Engine_SubmitLocal_Call struct { + *mock.Call +} + +// SubmitLocal is a helper method to define mock.On call +// - event any +func (_e *Engine_Expecter) SubmitLocal(event interface{}) *Engine_SubmitLocal_Call { + return &Engine_SubmitLocal_Call{Call: _e.mock.On("SubmitLocal", event)} +} + +func (_c *Engine_SubmitLocal_Call) Run(run func(event any)) *Engine_SubmitLocal_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Engine_SubmitLocal_Call) Return() *Engine_SubmitLocal_Call { + _c.Call.Return() + return _c +} + +func (_c *Engine_SubmitLocal_Call) RunAndReturn(run func(event any)) *Engine_SubmitLocal_Call { + _c.Run(run) + return _c } diff --git a/network/mock/engine_registry.go b/network/mock/engine_registry.go index ef7c2378ec7..a4f073271fe 100644 --- a/network/mock/engine_registry.go +++ b/network/mock/engine_registry.go @@ -1,68 +1,140 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - datastore "github.com/ipfs/go-datastore" - channels "github.com/onflow/flow-go/network/channels" - - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/ipfs/go-datastore" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" +) - network "github.com/onflow/flow-go/network" +// NewEngineRegistry creates a new instance of EngineRegistry. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEngineRegistry(t interface { + mock.TestingT + Cleanup(func()) +}) *EngineRegistry { + mock := &EngineRegistry{} + mock.Mock.Test(t) - protocol "github.com/libp2p/go-libp2p/core/protocol" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // EngineRegistry is an autogenerated mock type for the EngineRegistry type type EngineRegistry struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *EngineRegistry) Done() <-chan struct{} { - ret := _m.Called() +type EngineRegistry_Expecter struct { + mock *mock.Mock +} + +func (_m *EngineRegistry) EXPECT() *EngineRegistry_Expecter { + return &EngineRegistry_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type EngineRegistry +func (_mock *EngineRegistry) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *EngineRegistry) Ready() <-chan struct{} { - ret := _m.Called() +// EngineRegistry_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type EngineRegistry_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *EngineRegistry_Expecter) Done() *EngineRegistry_Done_Call { + return &EngineRegistry_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *EngineRegistry_Done_Call) Run(run func()) *EngineRegistry_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EngineRegistry_Done_Call) Return(valCh <-chan struct{}) *EngineRegistry_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *EngineRegistry_Done_Call) RunAndReturn(run func() <-chan struct{}) *EngineRegistry_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type EngineRegistry +func (_mock *EngineRegistry) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Register provides a mock function with given fields: channel, messageProcessor -func (_m *EngineRegistry) Register(channel channels.Channel, messageProcessor network.MessageProcessor) (network.Conduit, error) { - ret := _m.Called(channel, messageProcessor) +// EngineRegistry_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type EngineRegistry_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *EngineRegistry_Expecter) Ready() *EngineRegistry_Ready_Call { + return &EngineRegistry_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *EngineRegistry_Ready_Call) Run(run func()) *EngineRegistry_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EngineRegistry_Ready_Call) Return(valCh <-chan struct{}) *EngineRegistry_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *EngineRegistry_Ready_Call) RunAndReturn(run func() <-chan struct{}) *EngineRegistry_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Register provides a mock function for the type EngineRegistry +func (_mock *EngineRegistry) Register(channel channels.Channel, messageProcessor network.MessageProcessor) (network.Conduit, error) { + ret := _mock.Called(channel, messageProcessor) if len(ret) == 0 { panic("no return value specified for Register") @@ -70,28 +142,67 @@ func (_m *EngineRegistry) Register(channel channels.Channel, messageProcessor ne var r0 network.Conduit var r1 error - if rf, ok := ret.Get(0).(func(channels.Channel, network.MessageProcessor) (network.Conduit, error)); ok { - return rf(channel, messageProcessor) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, network.MessageProcessor) (network.Conduit, error)); ok { + return returnFunc(channel, messageProcessor) } - if rf, ok := ret.Get(0).(func(channels.Channel, network.MessageProcessor) network.Conduit); ok { - r0 = rf(channel, messageProcessor) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, network.MessageProcessor) network.Conduit); ok { + r0 = returnFunc(channel, messageProcessor) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.Conduit) } } - - if rf, ok := ret.Get(1).(func(channels.Channel, network.MessageProcessor) error); ok { - r1 = rf(channel, messageProcessor) + if returnFunc, ok := ret.Get(1).(func(channels.Channel, network.MessageProcessor) error); ok { + r1 = returnFunc(channel, messageProcessor) } else { r1 = ret.Error(1) } - return r0, r1 } -// RegisterBlobService provides a mock function with given fields: channel, store, opts -func (_m *EngineRegistry) RegisterBlobService(channel channels.Channel, store datastore.Batching, opts ...network.BlobServiceOption) (network.BlobService, error) { +// EngineRegistry_Register_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Register' +type EngineRegistry_Register_Call struct { + *mock.Call +} + +// Register is a helper method to define mock.On call +// - channel channels.Channel +// - messageProcessor network.MessageProcessor +func (_e *EngineRegistry_Expecter) Register(channel interface{}, messageProcessor interface{}) *EngineRegistry_Register_Call { + return &EngineRegistry_Register_Call{Call: _e.mock.On("Register", channel, messageProcessor)} +} + +func (_c *EngineRegistry_Register_Call) Run(run func(channel channels.Channel, messageProcessor network.MessageProcessor)) *EngineRegistry_Register_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 network.MessageProcessor + if args[1] != nil { + arg1 = args[1].(network.MessageProcessor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EngineRegistry_Register_Call) Return(conduit network.Conduit, err error) *EngineRegistry_Register_Call { + _c.Call.Return(conduit, err) + return _c +} + +func (_c *EngineRegistry_Register_Call) RunAndReturn(run func(channel channels.Channel, messageProcessor network.MessageProcessor) (network.Conduit, error)) *EngineRegistry_Register_Call { + _c.Call.Return(run) + return _c +} + +// RegisterBlobService provides a mock function for the type EngineRegistry +func (_mock *EngineRegistry) RegisterBlobService(channel channels.Channel, store datastore.Batching, opts ...network.BlobServiceOption) (network.BlobService, error) { + // network.BlobServiceOption _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] @@ -99,7 +210,7 @@ func (_m *EngineRegistry) RegisterBlobService(channel channels.Channel, store da var _ca []interface{} _ca = append(_ca, channel, store) _ca = append(_ca, _va...) - ret := _m.Called(_ca...) + ret := _mock.Called(_ca...) if len(ret) == 0 { panic("no return value specified for RegisterBlobService") @@ -107,29 +218,78 @@ func (_m *EngineRegistry) RegisterBlobService(channel channels.Channel, store da var r0 network.BlobService var r1 error - if rf, ok := ret.Get(0).(func(channels.Channel, datastore.Batching, ...network.BlobServiceOption) (network.BlobService, error)); ok { - return rf(channel, store, opts...) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, datastore.Batching, ...network.BlobServiceOption) (network.BlobService, error)); ok { + return returnFunc(channel, store, opts...) } - if rf, ok := ret.Get(0).(func(channels.Channel, datastore.Batching, ...network.BlobServiceOption) network.BlobService); ok { - r0 = rf(channel, store, opts...) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, datastore.Batching, ...network.BlobServiceOption) network.BlobService); ok { + r0 = returnFunc(channel, store, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.BlobService) } } - - if rf, ok := ret.Get(1).(func(channels.Channel, datastore.Batching, ...network.BlobServiceOption) error); ok { - r1 = rf(channel, store, opts...) + if returnFunc, ok := ret.Get(1).(func(channels.Channel, datastore.Batching, ...network.BlobServiceOption) error); ok { + r1 = returnFunc(channel, store, opts...) } else { r1 = ret.Error(1) } - return r0, r1 } -// RegisterPingService provides a mock function with given fields: pingProtocolID, pingInfoProvider -func (_m *EngineRegistry) RegisterPingService(pingProtocolID protocol.ID, pingInfoProvider network.PingInfoProvider) (network.PingService, error) { - ret := _m.Called(pingProtocolID, pingInfoProvider) +// EngineRegistry_RegisterBlobService_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterBlobService' +type EngineRegistry_RegisterBlobService_Call struct { + *mock.Call +} + +// RegisterBlobService is a helper method to define mock.On call +// - channel channels.Channel +// - store datastore.Batching +// - opts ...network.BlobServiceOption +func (_e *EngineRegistry_Expecter) RegisterBlobService(channel interface{}, store interface{}, opts ...interface{}) *EngineRegistry_RegisterBlobService_Call { + return &EngineRegistry_RegisterBlobService_Call{Call: _e.mock.On("RegisterBlobService", + append([]interface{}{channel, store}, opts...)...)} +} + +func (_c *EngineRegistry_RegisterBlobService_Call) Run(run func(channel channels.Channel, store datastore.Batching, opts ...network.BlobServiceOption)) *EngineRegistry_RegisterBlobService_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 datastore.Batching + if args[1] != nil { + arg1 = args[1].(datastore.Batching) + } + var arg2 []network.BlobServiceOption + variadicArgs := make([]network.BlobServiceOption, len(args)-2) + for i, a := range args[2:] { + if a != nil { + variadicArgs[i] = a.(network.BlobServiceOption) + } + } + arg2 = variadicArgs + run( + arg0, + arg1, + arg2..., + ) + }) + return _c +} + +func (_c *EngineRegistry_RegisterBlobService_Call) Return(blobService network.BlobService, err error) *EngineRegistry_RegisterBlobService_Call { + _c.Call.Return(blobService, err) + return _c +} + +func (_c *EngineRegistry_RegisterBlobService_Call) RunAndReturn(run func(channel channels.Channel, store datastore.Batching, opts ...network.BlobServiceOption) (network.BlobService, error)) *EngineRegistry_RegisterBlobService_Call { + _c.Call.Return(run) + return _c +} + +// RegisterPingService provides a mock function for the type EngineRegistry +func (_mock *EngineRegistry) RegisterPingService(pingProtocolID protocol.ID, pingInfoProvider network.PingInfoProvider) (network.PingService, error) { + ret := _mock.Called(pingProtocolID, pingInfoProvider) if len(ret) == 0 { panic("no return value specified for RegisterPingService") @@ -137,41 +297,100 @@ func (_m *EngineRegistry) RegisterPingService(pingProtocolID protocol.ID, pingIn var r0 network.PingService var r1 error - if rf, ok := ret.Get(0).(func(protocol.ID, network.PingInfoProvider) (network.PingService, error)); ok { - return rf(pingProtocolID, pingInfoProvider) + if returnFunc, ok := ret.Get(0).(func(protocol.ID, network.PingInfoProvider) (network.PingService, error)); ok { + return returnFunc(pingProtocolID, pingInfoProvider) } - if rf, ok := ret.Get(0).(func(protocol.ID, network.PingInfoProvider) network.PingService); ok { - r0 = rf(pingProtocolID, pingInfoProvider) + if returnFunc, ok := ret.Get(0).(func(protocol.ID, network.PingInfoProvider) network.PingService); ok { + r0 = returnFunc(pingProtocolID, pingInfoProvider) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.PingService) } } - - if rf, ok := ret.Get(1).(func(protocol.ID, network.PingInfoProvider) error); ok { - r1 = rf(pingProtocolID, pingInfoProvider) + if returnFunc, ok := ret.Get(1).(func(protocol.ID, network.PingInfoProvider) error); ok { + r1 = returnFunc(pingProtocolID, pingInfoProvider) } else { r1 = ret.Error(1) } - return r0, r1 } -// Start provides a mock function with given fields: _a0 -func (_m *EngineRegistry) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// EngineRegistry_RegisterPingService_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterPingService' +type EngineRegistry_RegisterPingService_Call struct { + *mock.Call } -// NewEngineRegistry creates a new instance of EngineRegistry. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEngineRegistry(t interface { - mock.TestingT - Cleanup(func()) -}) *EngineRegistry { - mock := &EngineRegistry{} - mock.Mock.Test(t) +// RegisterPingService is a helper method to define mock.On call +// - pingProtocolID protocol.ID +// - pingInfoProvider network.PingInfoProvider +func (_e *EngineRegistry_Expecter) RegisterPingService(pingProtocolID interface{}, pingInfoProvider interface{}) *EngineRegistry_RegisterPingService_Call { + return &EngineRegistry_RegisterPingService_Call{Call: _e.mock.On("RegisterPingService", pingProtocolID, pingInfoProvider)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *EngineRegistry_RegisterPingService_Call) Run(run func(pingProtocolID protocol.ID, pingInfoProvider network.PingInfoProvider)) *EngineRegistry_RegisterPingService_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + var arg1 network.PingInfoProvider + if args[1] != nil { + arg1 = args[1].(network.PingInfoProvider) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return mock +func (_c *EngineRegistry_RegisterPingService_Call) Return(pingService network.PingService, err error) *EngineRegistry_RegisterPingService_Call { + _c.Call.Return(pingService, err) + return _c +} + +func (_c *EngineRegistry_RegisterPingService_Call) RunAndReturn(run func(pingProtocolID protocol.ID, pingInfoProvider network.PingInfoProvider) (network.PingService, error)) *EngineRegistry_RegisterPingService_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type EngineRegistry +func (_mock *EngineRegistry) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// EngineRegistry_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type EngineRegistry_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *EngineRegistry_Expecter) Start(signalerContext interface{}) *EngineRegistry_Start_Call { + return &EngineRegistry_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *EngineRegistry_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *EngineRegistry_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EngineRegistry_Start_Call) Return() *EngineRegistry_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *EngineRegistry_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *EngineRegistry_Start_Call { + _c.Run(run) + return _c } diff --git a/network/mock/incoming_message_scope.go b/network/mock/incoming_message_scope.go index 50a58fff6d8..4b780dddacc 100644 --- a/network/mock/incoming_message_scope.go +++ b/network/mock/incoming_message_scope.go @@ -1,203 +1,445 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - - message "github.com/onflow/flow-go/network/message" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/message" mock "github.com/stretchr/testify/mock" ) +// NewIncomingMessageScope creates a new instance of IncomingMessageScope. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIncomingMessageScope(t interface { + mock.TestingT + Cleanup(func()) +}) *IncomingMessageScope { + mock := &IncomingMessageScope{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IncomingMessageScope is an autogenerated mock type for the IncomingMessageScope type type IncomingMessageScope struct { mock.Mock } -// Channel provides a mock function with no fields -func (_m *IncomingMessageScope) Channel() channels.Channel { - ret := _m.Called() +type IncomingMessageScope_Expecter struct { + mock *mock.Mock +} + +func (_m *IncomingMessageScope) EXPECT() *IncomingMessageScope_Expecter { + return &IncomingMessageScope_Expecter{mock: &_m.Mock} +} + +// Channel provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) Channel() channels.Channel { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Channel") } var r0 channels.Channel - if rf, ok := ret.Get(0).(func() channels.Channel); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() channels.Channel); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(channels.Channel) } - return r0 } -// DecodedPayload provides a mock function with no fields -func (_m *IncomingMessageScope) DecodedPayload() interface{} { - ret := _m.Called() +// IncomingMessageScope_Channel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Channel' +type IncomingMessageScope_Channel_Call struct { + *mock.Call +} + +// Channel is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) Channel() *IncomingMessageScope_Channel_Call { + return &IncomingMessageScope_Channel_Call{Call: _e.mock.On("Channel")} +} + +func (_c *IncomingMessageScope_Channel_Call) Run(run func()) *IncomingMessageScope_Channel_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_Channel_Call) Return(channel channels.Channel) *IncomingMessageScope_Channel_Call { + _c.Call.Return(channel) + return _c +} + +func (_c *IncomingMessageScope_Channel_Call) RunAndReturn(run func() channels.Channel) *IncomingMessageScope_Channel_Call { + _c.Call.Return(run) + return _c +} + +// DecodedPayload provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) DecodedPayload() any { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for DecodedPayload") } - var r0 interface{} - if rf, ok := ret.Get(0).(func() interface{}); ok { - r0 = rf() + var r0 any + if returnFunc, ok := ret.Get(0).(func() any); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(interface{}) + r0 = ret.Get(0).(any) } } - return r0 } -// EventID provides a mock function with no fields -func (_m *IncomingMessageScope) EventID() []byte { - ret := _m.Called() +// IncomingMessageScope_DecodedPayload_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DecodedPayload' +type IncomingMessageScope_DecodedPayload_Call struct { + *mock.Call +} + +// DecodedPayload is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) DecodedPayload() *IncomingMessageScope_DecodedPayload_Call { + return &IncomingMessageScope_DecodedPayload_Call{Call: _e.mock.On("DecodedPayload")} +} + +func (_c *IncomingMessageScope_DecodedPayload_Call) Run(run func()) *IncomingMessageScope_DecodedPayload_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_DecodedPayload_Call) Return(v any) *IncomingMessageScope_DecodedPayload_Call { + _c.Call.Return(v) + return _c +} + +func (_c *IncomingMessageScope_DecodedPayload_Call) RunAndReturn(run func() any) *IncomingMessageScope_DecodedPayload_Call { + _c.Call.Return(run) + return _c +} + +// EventID provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) EventID() []byte { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EventID") } var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - return r0 } -// OriginId provides a mock function with no fields -func (_m *IncomingMessageScope) OriginId() flow.Identifier { - ret := _m.Called() +// IncomingMessageScope_EventID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EventID' +type IncomingMessageScope_EventID_Call struct { + *mock.Call +} + +// EventID is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) EventID() *IncomingMessageScope_EventID_Call { + return &IncomingMessageScope_EventID_Call{Call: _e.mock.On("EventID")} +} + +func (_c *IncomingMessageScope_EventID_Call) Run(run func()) *IncomingMessageScope_EventID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_EventID_Call) Return(bytes []byte) *IncomingMessageScope_EventID_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *IncomingMessageScope_EventID_Call) RunAndReturn(run func() []byte) *IncomingMessageScope_EventID_Call { + _c.Call.Return(run) + return _c +} + +// OriginId provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) OriginId() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for OriginId") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// PayloadType provides a mock function with no fields -func (_m *IncomingMessageScope) PayloadType() string { - ret := _m.Called() +// IncomingMessageScope_OriginId_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OriginId' +type IncomingMessageScope_OriginId_Call struct { + *mock.Call +} + +// OriginId is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) OriginId() *IncomingMessageScope_OriginId_Call { + return &IncomingMessageScope_OriginId_Call{Call: _e.mock.On("OriginId")} +} + +func (_c *IncomingMessageScope_OriginId_Call) Run(run func()) *IncomingMessageScope_OriginId_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_OriginId_Call) Return(identifier flow.Identifier) *IncomingMessageScope_OriginId_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *IncomingMessageScope_OriginId_Call) RunAndReturn(run func() flow.Identifier) *IncomingMessageScope_OriginId_Call { + _c.Call.Return(run) + return _c +} + +// PayloadType provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) PayloadType() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PayloadType") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// Proto provides a mock function with no fields -func (_m *IncomingMessageScope) Proto() *message.Message { - ret := _m.Called() +// IncomingMessageScope_PayloadType_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PayloadType' +type IncomingMessageScope_PayloadType_Call struct { + *mock.Call +} + +// PayloadType is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) PayloadType() *IncomingMessageScope_PayloadType_Call { + return &IncomingMessageScope_PayloadType_Call{Call: _e.mock.On("PayloadType")} +} + +func (_c *IncomingMessageScope_PayloadType_Call) Run(run func()) *IncomingMessageScope_PayloadType_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_PayloadType_Call) Return(s string) *IncomingMessageScope_PayloadType_Call { + _c.Call.Return(s) + return _c +} + +func (_c *IncomingMessageScope_PayloadType_Call) RunAndReturn(run func() string) *IncomingMessageScope_PayloadType_Call { + _c.Call.Return(run) + return _c +} + +// Proto provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) Proto() *message.Message { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Proto") } var r0 *message.Message - if rf, ok := ret.Get(0).(func() *message.Message); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *message.Message); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*message.Message) } } - return r0 } -// Protocol provides a mock function with no fields -func (_m *IncomingMessageScope) Protocol() message.ProtocolType { - ret := _m.Called() +// IncomingMessageScope_Proto_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Proto' +type IncomingMessageScope_Proto_Call struct { + *mock.Call +} + +// Proto is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) Proto() *IncomingMessageScope_Proto_Call { + return &IncomingMessageScope_Proto_Call{Call: _e.mock.On("Proto")} +} + +func (_c *IncomingMessageScope_Proto_Call) Run(run func()) *IncomingMessageScope_Proto_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_Proto_Call) Return(message1 *message.Message) *IncomingMessageScope_Proto_Call { + _c.Call.Return(message1) + return _c +} + +func (_c *IncomingMessageScope_Proto_Call) RunAndReturn(run func() *message.Message) *IncomingMessageScope_Proto_Call { + _c.Call.Return(run) + return _c +} + +// Protocol provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) Protocol() message.ProtocolType { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Protocol") } var r0 message.ProtocolType - if rf, ok := ret.Get(0).(func() message.ProtocolType); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() message.ProtocolType); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(message.ProtocolType) } - return r0 } -// Size provides a mock function with no fields -func (_m *IncomingMessageScope) Size() int { - ret := _m.Called() +// IncomingMessageScope_Protocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Protocol' +type IncomingMessageScope_Protocol_Call struct { + *mock.Call +} + +// Protocol is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) Protocol() *IncomingMessageScope_Protocol_Call { + return &IncomingMessageScope_Protocol_Call{Call: _e.mock.On("Protocol")} +} + +func (_c *IncomingMessageScope_Protocol_Call) Run(run func()) *IncomingMessageScope_Protocol_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_Protocol_Call) Return(protocolType message.ProtocolType) *IncomingMessageScope_Protocol_Call { + _c.Call.Return(protocolType) + return _c +} + +func (_c *IncomingMessageScope_Protocol_Call) RunAndReturn(run func() message.ProtocolType) *IncomingMessageScope_Protocol_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) Size() int { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(int) } - return r0 } -// TargetIDs provides a mock function with no fields -func (_m *IncomingMessageScope) TargetIDs() flow.IdentifierList { - ret := _m.Called() +// IncomingMessageScope_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type IncomingMessageScope_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) Size() *IncomingMessageScope_Size_Call { + return &IncomingMessageScope_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *IncomingMessageScope_Size_Call) Run(run func()) *IncomingMessageScope_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_Size_Call) Return(n int) *IncomingMessageScope_Size_Call { + _c.Call.Return(n) + return _c +} + +func (_c *IncomingMessageScope_Size_Call) RunAndReturn(run func() int) *IncomingMessageScope_Size_Call { + _c.Call.Return(run) + return _c +} + +// TargetIDs provides a mock function for the type IncomingMessageScope +func (_mock *IncomingMessageScope) TargetIDs() flow.IdentifierList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TargetIDs") } var r0 flow.IdentifierList - if rf, ok := ret.Get(0).(func() flow.IdentifierList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentifierList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentifierList) } } - return r0 } -// NewIncomingMessageScope creates a new instance of IncomingMessageScope. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIncomingMessageScope(t interface { - mock.TestingT - Cleanup(func()) -}) *IncomingMessageScope { - mock := &IncomingMessageScope{} - mock.Mock.Test(t) +// IncomingMessageScope_TargetIDs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TargetIDs' +type IncomingMessageScope_TargetIDs_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TargetIDs is a helper method to define mock.On call +func (_e *IncomingMessageScope_Expecter) TargetIDs() *IncomingMessageScope_TargetIDs_Call { + return &IncomingMessageScope_TargetIDs_Call{Call: _e.mock.On("TargetIDs")} +} - return mock +func (_c *IncomingMessageScope_TargetIDs_Call) Run(run func()) *IncomingMessageScope_TargetIDs_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IncomingMessageScope_TargetIDs_Call) Return(identifierList flow.IdentifierList) *IncomingMessageScope_TargetIDs_Call { + _c.Call.Return(identifierList) + return _c +} + +func (_c *IncomingMessageScope_TargetIDs_Call) RunAndReturn(run func() flow.IdentifierList) *IncomingMessageScope_TargetIDs_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/message_processor.go b/network/mock/message_processor.go index 0c39c0912ff..3802aa4c154 100644 --- a/network/mock/message_processor.go +++ b/network/mock/message_processor.go @@ -1,47 +1,101 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" ) +// NewMessageProcessor creates a new instance of MessageProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMessageProcessor(t interface { + mock.TestingT + Cleanup(func()) +}) *MessageProcessor { + mock := &MessageProcessor{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MessageProcessor is an autogenerated mock type for the MessageProcessor type type MessageProcessor struct { mock.Mock } -// Process provides a mock function with given fields: channel, originID, message -func (_m *MessageProcessor) Process(channel channels.Channel, originID flow.Identifier, message interface{}) error { - ret := _m.Called(channel, originID, message) +type MessageProcessor_Expecter struct { + mock *mock.Mock +} + +func (_m *MessageProcessor) EXPECT() *MessageProcessor_Expecter { + return &MessageProcessor_Expecter{mock: &_m.Mock} +} + +// Process provides a mock function for the type MessageProcessor +func (_mock *MessageProcessor) Process(channel channels.Channel, originID flow.Identifier, message any) error { + ret := _mock.Called(channel, originID, message) if len(ret) == 0 { panic("no return value specified for Process") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel, flow.Identifier, interface{}) error); ok { - r0 = rf(channel, originID, message) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, flow.Identifier, any) error); ok { + r0 = returnFunc(channel, originID, message) } else { r0 = ret.Error(0) } - return r0 } -// NewMessageProcessor creates a new instance of MessageProcessor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMessageProcessor(t interface { - mock.TestingT - Cleanup(func()) -}) *MessageProcessor { - mock := &MessageProcessor{} - mock.Mock.Test(t) +// MessageProcessor_Process_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Process' +type MessageProcessor_Process_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Process is a helper method to define mock.On call +// - channel channels.Channel +// - originID flow.Identifier +// - message any +func (_e *MessageProcessor_Expecter) Process(channel interface{}, originID interface{}, message interface{}) *MessageProcessor_Process_Call { + return &MessageProcessor_Process_Call{Call: _e.mock.On("Process", channel, originID, message)} +} - return mock +func (_c *MessageProcessor_Process_Call) Run(run func(channel channels.Channel, originID flow.Identifier, message any)) *MessageProcessor_Process_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 any + if args[2] != nil { + arg2 = args[2].(any) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *MessageProcessor_Process_Call) Return(err error) *MessageProcessor_Process_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MessageProcessor_Process_Call) RunAndReturn(run func(channel channels.Channel, originID flow.Identifier, message any) error) *MessageProcessor_Process_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/message_queue.go b/network/mock/message_queue.go index ef6a21a1da0..d6bae8e6e69 100644 --- a/network/mock/message_queue.go +++ b/network/mock/message_queue.go @@ -1,80 +1,177 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewMessageQueue creates a new instance of MessageQueue. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMessageQueue(t interface { + mock.TestingT + Cleanup(func()) +}) *MessageQueue { + mock := &MessageQueue{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // MessageQueue is an autogenerated mock type for the MessageQueue type type MessageQueue struct { mock.Mock } -// Insert provides a mock function with given fields: message -func (_m *MessageQueue) Insert(message interface{}) error { - ret := _m.Called(message) +type MessageQueue_Expecter struct { + mock *mock.Mock +} + +func (_m *MessageQueue) EXPECT() *MessageQueue_Expecter { + return &MessageQueue_Expecter{mock: &_m.Mock} +} + +// Insert provides a mock function for the type MessageQueue +func (_mock *MessageQueue) Insert(message any) error { + ret := _mock.Called(message) if len(ret) == 0 { panic("no return value specified for Insert") } var r0 error - if rf, ok := ret.Get(0).(func(interface{}) error); ok { - r0 = rf(message) + if returnFunc, ok := ret.Get(0).(func(any) error); ok { + r0 = returnFunc(message) } else { r0 = ret.Error(0) } - return r0 } -// Len provides a mock function with no fields -func (_m *MessageQueue) Len() int { - ret := _m.Called() +// MessageQueue_Insert_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Insert' +type MessageQueue_Insert_Call struct { + *mock.Call +} + +// Insert is a helper method to define mock.On call +// - message any +func (_e *MessageQueue_Expecter) Insert(message interface{}) *MessageQueue_Insert_Call { + return &MessageQueue_Insert_Call{Call: _e.mock.On("Insert", message)} +} + +func (_c *MessageQueue_Insert_Call) Run(run func(message any)) *MessageQueue_Insert_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 any + if args[0] != nil { + arg0 = args[0].(any) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MessageQueue_Insert_Call) Return(err error) *MessageQueue_Insert_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MessageQueue_Insert_Call) RunAndReturn(run func(message any) error) *MessageQueue_Insert_Call { + _c.Call.Return(run) + return _c +} + +// Len provides a mock function for the type MessageQueue +func (_mock *MessageQueue) Len() int { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Len") } var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(int) } - return r0 } -// Remove provides a mock function with no fields -func (_m *MessageQueue) Remove() interface{} { - ret := _m.Called() +// MessageQueue_Len_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Len' +type MessageQueue_Len_Call struct { + *mock.Call +} + +// Len is a helper method to define mock.On call +func (_e *MessageQueue_Expecter) Len() *MessageQueue_Len_Call { + return &MessageQueue_Len_Call{Call: _e.mock.On("Len")} +} + +func (_c *MessageQueue_Len_Call) Run(run func()) *MessageQueue_Len_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MessageQueue_Len_Call) Return(n int) *MessageQueue_Len_Call { + _c.Call.Return(n) + return _c +} + +func (_c *MessageQueue_Len_Call) RunAndReturn(run func() int) *MessageQueue_Len_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type MessageQueue +func (_mock *MessageQueue) Remove() any { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Remove") } - var r0 interface{} - if rf, ok := ret.Get(0).(func() interface{}); ok { - r0 = rf() + var r0 any + if returnFunc, ok := ret.Get(0).(func() any); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(interface{}) + r0 = ret.Get(0).(any) } } - return r0 } -// NewMessageQueue creates a new instance of MessageQueue. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMessageQueue(t interface { - mock.TestingT - Cleanup(func()) -}) *MessageQueue { - mock := &MessageQueue{} - mock.Mock.Test(t) +// MessageQueue_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type MessageQueue_Remove_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Remove is a helper method to define mock.On call +func (_e *MessageQueue_Expecter) Remove() *MessageQueue_Remove_Call { + return &MessageQueue_Remove_Call{Call: _e.mock.On("Remove")} +} - return mock +func (_c *MessageQueue_Remove_Call) Run(run func()) *MessageQueue_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MessageQueue_Remove_Call) Return(v any) *MessageQueue_Remove_Call { + _c.Call.Return(v) + return _c +} + +func (_c *MessageQueue_Remove_Call) RunAndReturn(run func() any) *MessageQueue_Remove_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/message_validator.go b/network/mock/message_validator.go index f0980e11102..0da04fe7426 100644 --- a/network/mock/message_validator.go +++ b/network/mock/message_validator.go @@ -1,45 +1,88 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" ) +// NewMessageValidator creates a new instance of MessageValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMessageValidator(t interface { + mock.TestingT + Cleanup(func()) +}) *MessageValidator { + mock := &MessageValidator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MessageValidator is an autogenerated mock type for the MessageValidator type type MessageValidator struct { mock.Mock } -// Validate provides a mock function with given fields: msg -func (_m *MessageValidator) Validate(msg network.IncomingMessageScope) bool { - ret := _m.Called(msg) +type MessageValidator_Expecter struct { + mock *mock.Mock +} + +func (_m *MessageValidator) EXPECT() *MessageValidator_Expecter { + return &MessageValidator_Expecter{mock: &_m.Mock} +} + +// Validate provides a mock function for the type MessageValidator +func (_mock *MessageValidator) Validate(msg network.IncomingMessageScope) bool { + ret := _mock.Called(msg) if len(ret) == 0 { panic("no return value specified for Validate") } var r0 bool - if rf, ok := ret.Get(0).(func(network.IncomingMessageScope) bool); ok { - r0 = rf(msg) + if returnFunc, ok := ret.Get(0).(func(network.IncomingMessageScope) bool); ok { + r0 = returnFunc(msg) } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewMessageValidator creates a new instance of MessageValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMessageValidator(t interface { - mock.TestingT - Cleanup(func()) -}) *MessageValidator { - mock := &MessageValidator{} - mock.Mock.Test(t) +// MessageValidator_Validate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Validate' +type MessageValidator_Validate_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Validate is a helper method to define mock.On call +// - msg network.IncomingMessageScope +func (_e *MessageValidator_Expecter) Validate(msg interface{}) *MessageValidator_Validate_Call { + return &MessageValidator_Validate_Call{Call: _e.mock.On("Validate", msg)} +} - return mock +func (_c *MessageValidator_Validate_Call) Run(run func(msg network.IncomingMessageScope)) *MessageValidator_Validate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.IncomingMessageScope + if args[0] != nil { + arg0 = args[0].(network.IncomingMessageScope) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MessageValidator_Validate_Call) Return(b bool) *MessageValidator_Validate_Call { + _c.Call.Return(b) + return _c +} + +func (_c *MessageValidator_Validate_Call) RunAndReturn(run func(msg network.IncomingMessageScope) bool) *MessageValidator_Validate_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/misbehavior_report.go b/network/mock/misbehavior_report.go index a0528feeb7f..5e835bf1241 100644 --- a/network/mock/misbehavior_report.go +++ b/network/mock/misbehavior_report.go @@ -1,85 +1,172 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewMisbehaviorReport creates a new instance of MisbehaviorReport. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMisbehaviorReport(t interface { + mock.TestingT + Cleanup(func()) +}) *MisbehaviorReport { + mock := &MisbehaviorReport{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MisbehaviorReport is an autogenerated mock type for the MisbehaviorReport type type MisbehaviorReport struct { mock.Mock } -// OriginId provides a mock function with no fields -func (_m *MisbehaviorReport) OriginId() flow.Identifier { - ret := _m.Called() +type MisbehaviorReport_Expecter struct { + mock *mock.Mock +} + +func (_m *MisbehaviorReport) EXPECT() *MisbehaviorReport_Expecter { + return &MisbehaviorReport_Expecter{mock: &_m.Mock} +} + +// OriginId provides a mock function for the type MisbehaviorReport +func (_mock *MisbehaviorReport) OriginId() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for OriginId") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// Penalty provides a mock function with no fields -func (_m *MisbehaviorReport) Penalty() float64 { - ret := _m.Called() +// MisbehaviorReport_OriginId_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OriginId' +type MisbehaviorReport_OriginId_Call struct { + *mock.Call +} + +// OriginId is a helper method to define mock.On call +func (_e *MisbehaviorReport_Expecter) OriginId() *MisbehaviorReport_OriginId_Call { + return &MisbehaviorReport_OriginId_Call{Call: _e.mock.On("OriginId")} +} + +func (_c *MisbehaviorReport_OriginId_Call) Run(run func()) *MisbehaviorReport_OriginId_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MisbehaviorReport_OriginId_Call) Return(identifier flow.Identifier) *MisbehaviorReport_OriginId_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *MisbehaviorReport_OriginId_Call) RunAndReturn(run func() flow.Identifier) *MisbehaviorReport_OriginId_Call { + _c.Call.Return(run) + return _c +} + +// Penalty provides a mock function for the type MisbehaviorReport +func (_mock *MisbehaviorReport) Penalty() float64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Penalty") } var r0 float64 - if rf, ok := ret.Get(0).(func() float64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() float64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(float64) } - return r0 } -// Reason provides a mock function with no fields -func (_m *MisbehaviorReport) Reason() network.Misbehavior { - ret := _m.Called() +// MisbehaviorReport_Penalty_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Penalty' +type MisbehaviorReport_Penalty_Call struct { + *mock.Call +} + +// Penalty is a helper method to define mock.On call +func (_e *MisbehaviorReport_Expecter) Penalty() *MisbehaviorReport_Penalty_Call { + return &MisbehaviorReport_Penalty_Call{Call: _e.mock.On("Penalty")} +} + +func (_c *MisbehaviorReport_Penalty_Call) Run(run func()) *MisbehaviorReport_Penalty_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MisbehaviorReport_Penalty_Call) Return(f float64) *MisbehaviorReport_Penalty_Call { + _c.Call.Return(f) + return _c +} + +func (_c *MisbehaviorReport_Penalty_Call) RunAndReturn(run func() float64) *MisbehaviorReport_Penalty_Call { + _c.Call.Return(run) + return _c +} + +// Reason provides a mock function for the type MisbehaviorReport +func (_mock *MisbehaviorReport) Reason() network.Misbehavior { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Reason") } var r0 network.Misbehavior - if rf, ok := ret.Get(0).(func() network.Misbehavior); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() network.Misbehavior); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(network.Misbehavior) } - return r0 } -// NewMisbehaviorReport creates a new instance of MisbehaviorReport. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMisbehaviorReport(t interface { - mock.TestingT - Cleanup(func()) -}) *MisbehaviorReport { - mock := &MisbehaviorReport{} - mock.Mock.Test(t) +// MisbehaviorReport_Reason_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reason' +type MisbehaviorReport_Reason_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Reason is a helper method to define mock.On call +func (_e *MisbehaviorReport_Expecter) Reason() *MisbehaviorReport_Reason_Call { + return &MisbehaviorReport_Reason_Call{Call: _e.mock.On("Reason")} +} - return mock +func (_c *MisbehaviorReport_Reason_Call) Run(run func()) *MisbehaviorReport_Reason_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MisbehaviorReport_Reason_Call) Return(misbehavior network.Misbehavior) *MisbehaviorReport_Reason_Call { + _c.Call.Return(misbehavior) + return _c +} + +func (_c *MisbehaviorReport_Reason_Call) RunAndReturn(run func() network.Misbehavior) *MisbehaviorReport_Reason_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/misbehavior_report_consumer.go b/network/mock/misbehavior_report_consumer.go index 27c1bf3acf9..83dcac91579 100644 --- a/network/mock/misbehavior_report_consumer.go +++ b/network/mock/misbehavior_report_consumer.go @@ -1,24 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) -// MisbehaviorReportConsumer is an autogenerated mock type for the MisbehaviorReportConsumer type -type MisbehaviorReportConsumer struct { - mock.Mock -} - -// ReportMisbehaviorOnChannel provides a mock function with given fields: channel, report -func (_m *MisbehaviorReportConsumer) ReportMisbehaviorOnChannel(channel channels.Channel, report network.MisbehaviorReport) { - _m.Called(channel, report) -} - // NewMisbehaviorReportConsumer creates a new instance of MisbehaviorReportConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewMisbehaviorReportConsumer(t interface { @@ -32,3 +23,62 @@ func NewMisbehaviorReportConsumer(t interface { return mock } + +// MisbehaviorReportConsumer is an autogenerated mock type for the MisbehaviorReportConsumer type +type MisbehaviorReportConsumer struct { + mock.Mock +} + +type MisbehaviorReportConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *MisbehaviorReportConsumer) EXPECT() *MisbehaviorReportConsumer_Expecter { + return &MisbehaviorReportConsumer_Expecter{mock: &_m.Mock} +} + +// ReportMisbehaviorOnChannel provides a mock function for the type MisbehaviorReportConsumer +func (_mock *MisbehaviorReportConsumer) ReportMisbehaviorOnChannel(channel channels.Channel, report network.MisbehaviorReport) { + _mock.Called(channel, report) + return +} + +// MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReportMisbehaviorOnChannel' +type MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call struct { + *mock.Call +} + +// ReportMisbehaviorOnChannel is a helper method to define mock.On call +// - channel channels.Channel +// - report network.MisbehaviorReport +func (_e *MisbehaviorReportConsumer_Expecter) ReportMisbehaviorOnChannel(channel interface{}, report interface{}) *MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call { + return &MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call{Call: _e.mock.On("ReportMisbehaviorOnChannel", channel, report)} +} + +func (_c *MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call) Run(run func(channel channels.Channel, report network.MisbehaviorReport)) *MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 network.MisbehaviorReport + if args[1] != nil { + arg1 = args[1].(network.MisbehaviorReport) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call) Return() *MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call { + _c.Call.Return() + return _c +} + +func (_c *MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call) RunAndReturn(run func(channel channels.Channel, report network.MisbehaviorReport)) *MisbehaviorReportConsumer_ReportMisbehaviorOnChannel_Call { + _c.Run(run) + return _c +} diff --git a/network/mock/misbehavior_report_manager.go b/network/mock/misbehavior_report_manager.go index a3fd58c28d0..d7d1f062cc8 100644 --- a/network/mock/misbehavior_report_manager.go +++ b/network/mock/misbehavior_report_manager.go @@ -1,81 +1,217 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - channels "github.com/onflow/flow-go/network/channels" - + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewMisbehaviorReportManager creates a new instance of MisbehaviorReportManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMisbehaviorReportManager(t interface { + mock.TestingT + Cleanup(func()) +}) *MisbehaviorReportManager { + mock := &MisbehaviorReportManager{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MisbehaviorReportManager is an autogenerated mock type for the MisbehaviorReportManager type type MisbehaviorReportManager struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *MisbehaviorReportManager) Done() <-chan struct{} { - ret := _m.Called() +type MisbehaviorReportManager_Expecter struct { + mock *mock.Mock +} + +func (_m *MisbehaviorReportManager) EXPECT() *MisbehaviorReportManager_Expecter { + return &MisbehaviorReportManager_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type MisbehaviorReportManager +func (_mock *MisbehaviorReportManager) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// HandleMisbehaviorReport provides a mock function with given fields: _a0, _a1 -func (_m *MisbehaviorReportManager) HandleMisbehaviorReport(_a0 channels.Channel, _a1 network.MisbehaviorReport) { - _m.Called(_a0, _a1) +// MisbehaviorReportManager_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type MisbehaviorReportManager_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *MisbehaviorReportManager_Expecter) Done() *MisbehaviorReportManager_Done_Call { + return &MisbehaviorReportManager_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *MisbehaviorReportManager_Done_Call) Run(run func()) *MisbehaviorReportManager_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MisbehaviorReportManager_Done_Call) Return(valCh <-chan struct{}) *MisbehaviorReportManager_Done_Call { + _c.Call.Return(valCh) + return _c } -// Ready provides a mock function with no fields -func (_m *MisbehaviorReportManager) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *MisbehaviorReportManager_Done_Call) RunAndReturn(run func() <-chan struct{}) *MisbehaviorReportManager_Done_Call { + _c.Call.Return(run) + return _c +} + +// HandleMisbehaviorReport provides a mock function for the type MisbehaviorReportManager +func (_mock *MisbehaviorReportManager) HandleMisbehaviorReport(channel channels.Channel, misbehaviorReport network.MisbehaviorReport) { + _mock.Called(channel, misbehaviorReport) + return +} + +// MisbehaviorReportManager_HandleMisbehaviorReport_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HandleMisbehaviorReport' +type MisbehaviorReportManager_HandleMisbehaviorReport_Call struct { + *mock.Call +} + +// HandleMisbehaviorReport is a helper method to define mock.On call +// - channel channels.Channel +// - misbehaviorReport network.MisbehaviorReport +func (_e *MisbehaviorReportManager_Expecter) HandleMisbehaviorReport(channel interface{}, misbehaviorReport interface{}) *MisbehaviorReportManager_HandleMisbehaviorReport_Call { + return &MisbehaviorReportManager_HandleMisbehaviorReport_Call{Call: _e.mock.On("HandleMisbehaviorReport", channel, misbehaviorReport)} +} + +func (_c *MisbehaviorReportManager_HandleMisbehaviorReport_Call) Run(run func(channel channels.Channel, misbehaviorReport network.MisbehaviorReport)) *MisbehaviorReportManager_HandleMisbehaviorReport_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 network.MisbehaviorReport + if args[1] != nil { + arg1 = args[1].(network.MisbehaviorReport) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MisbehaviorReportManager_HandleMisbehaviorReport_Call) Return() *MisbehaviorReportManager_HandleMisbehaviorReport_Call { + _c.Call.Return() + return _c +} + +func (_c *MisbehaviorReportManager_HandleMisbehaviorReport_Call) RunAndReturn(run func(channel channels.Channel, misbehaviorReport network.MisbehaviorReport)) *MisbehaviorReportManager_HandleMisbehaviorReport_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type MisbehaviorReportManager +func (_mock *MisbehaviorReportManager) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *MisbehaviorReportManager) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// MisbehaviorReportManager_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type MisbehaviorReportManager_Ready_Call struct { + *mock.Call } -// NewMisbehaviorReportManager creates a new instance of MisbehaviorReportManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMisbehaviorReportManager(t interface { - mock.TestingT - Cleanup(func()) -}) *MisbehaviorReportManager { - mock := &MisbehaviorReportManager{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *MisbehaviorReportManager_Expecter) Ready() *MisbehaviorReportManager_Ready_Call { + return &MisbehaviorReportManager_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *MisbehaviorReportManager_Ready_Call) Run(run func()) *MisbehaviorReportManager_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *MisbehaviorReportManager_Ready_Call) Return(valCh <-chan struct{}) *MisbehaviorReportManager_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *MisbehaviorReportManager_Ready_Call) RunAndReturn(run func() <-chan struct{}) *MisbehaviorReportManager_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type MisbehaviorReportManager +func (_mock *MisbehaviorReportManager) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// MisbehaviorReportManager_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type MisbehaviorReportManager_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *MisbehaviorReportManager_Expecter) Start(signalerContext interface{}) *MisbehaviorReportManager_Start_Call { + return &MisbehaviorReportManager_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *MisbehaviorReportManager_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *MisbehaviorReportManager_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MisbehaviorReportManager_Start_Call) Return() *MisbehaviorReportManager_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *MisbehaviorReportManager_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *MisbehaviorReportManager_Start_Call { + _c.Run(run) + return _c } diff --git a/network/mock/misbehavior_reporter.go b/network/mock/misbehavior_reporter.go index b6690f35d2c..8f9617ab6c6 100644 --- a/network/mock/misbehavior_reporter.go +++ b/network/mock/misbehavior_reporter.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" ) -// MisbehaviorReporter is an autogenerated mock type for the MisbehaviorReporter type -type MisbehaviorReporter struct { - mock.Mock -} - -// ReportMisbehavior provides a mock function with given fields: _a0 -func (_m *MisbehaviorReporter) ReportMisbehavior(_a0 network.MisbehaviorReport) { - _m.Called(_a0) -} - // NewMisbehaviorReporter creates a new instance of MisbehaviorReporter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewMisbehaviorReporter(t interface { @@ -30,3 +22,56 @@ func NewMisbehaviorReporter(t interface { return mock } + +// MisbehaviorReporter is an autogenerated mock type for the MisbehaviorReporter type +type MisbehaviorReporter struct { + mock.Mock +} + +type MisbehaviorReporter_Expecter struct { + mock *mock.Mock +} + +func (_m *MisbehaviorReporter) EXPECT() *MisbehaviorReporter_Expecter { + return &MisbehaviorReporter_Expecter{mock: &_m.Mock} +} + +// ReportMisbehavior provides a mock function for the type MisbehaviorReporter +func (_mock *MisbehaviorReporter) ReportMisbehavior(misbehaviorReport network.MisbehaviorReport) { + _mock.Called(misbehaviorReport) + return +} + +// MisbehaviorReporter_ReportMisbehavior_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReportMisbehavior' +type MisbehaviorReporter_ReportMisbehavior_Call struct { + *mock.Call +} + +// ReportMisbehavior is a helper method to define mock.On call +// - misbehaviorReport network.MisbehaviorReport +func (_e *MisbehaviorReporter_Expecter) ReportMisbehavior(misbehaviorReport interface{}) *MisbehaviorReporter_ReportMisbehavior_Call { + return &MisbehaviorReporter_ReportMisbehavior_Call{Call: _e.mock.On("ReportMisbehavior", misbehaviorReport)} +} + +func (_c *MisbehaviorReporter_ReportMisbehavior_Call) Run(run func(misbehaviorReport network.MisbehaviorReport)) *MisbehaviorReporter_ReportMisbehavior_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.MisbehaviorReport + if args[0] != nil { + arg0 = args[0].(network.MisbehaviorReport) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MisbehaviorReporter_ReportMisbehavior_Call) Return() *MisbehaviorReporter_ReportMisbehavior_Call { + _c.Call.Return() + return _c +} + +func (_c *MisbehaviorReporter_ReportMisbehavior_Call) RunAndReturn(run func(misbehaviorReport network.MisbehaviorReport)) *MisbehaviorReporter_ReportMisbehavior_Call { + _c.Run(run) + return _c +} diff --git a/network/mock/outgoing_message_scope.go b/network/mock/outgoing_message_scope.go index e888f89e761..d16329ed660 100644 --- a/network/mock/outgoing_message_scope.go +++ b/network/mock/outgoing_message_scope.go @@ -1,125 +1,263 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - - message "github.com/onflow/flow-go/network/message" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/message" mock "github.com/stretchr/testify/mock" ) +// NewOutgoingMessageScope creates a new instance of OutgoingMessageScope. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewOutgoingMessageScope(t interface { + mock.TestingT + Cleanup(func()) +}) *OutgoingMessageScope { + mock := &OutgoingMessageScope{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // OutgoingMessageScope is an autogenerated mock type for the OutgoingMessageScope type type OutgoingMessageScope struct { mock.Mock } -// PayloadType provides a mock function with no fields -func (_m *OutgoingMessageScope) PayloadType() string { - ret := _m.Called() +type OutgoingMessageScope_Expecter struct { + mock *mock.Mock +} + +func (_m *OutgoingMessageScope) EXPECT() *OutgoingMessageScope_Expecter { + return &OutgoingMessageScope_Expecter{mock: &_m.Mock} +} + +// PayloadType provides a mock function for the type OutgoingMessageScope +func (_mock *OutgoingMessageScope) PayloadType() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PayloadType") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// Proto provides a mock function with no fields -func (_m *OutgoingMessageScope) Proto() *message.Message { - ret := _m.Called() +// OutgoingMessageScope_PayloadType_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PayloadType' +type OutgoingMessageScope_PayloadType_Call struct { + *mock.Call +} + +// PayloadType is a helper method to define mock.On call +func (_e *OutgoingMessageScope_Expecter) PayloadType() *OutgoingMessageScope_PayloadType_Call { + return &OutgoingMessageScope_PayloadType_Call{Call: _e.mock.On("PayloadType")} +} + +func (_c *OutgoingMessageScope_PayloadType_Call) Run(run func()) *OutgoingMessageScope_PayloadType_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OutgoingMessageScope_PayloadType_Call) Return(s string) *OutgoingMessageScope_PayloadType_Call { + _c.Call.Return(s) + return _c +} + +func (_c *OutgoingMessageScope_PayloadType_Call) RunAndReturn(run func() string) *OutgoingMessageScope_PayloadType_Call { + _c.Call.Return(run) + return _c +} + +// Proto provides a mock function for the type OutgoingMessageScope +func (_mock *OutgoingMessageScope) Proto() *message.Message { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Proto") } var r0 *message.Message - if rf, ok := ret.Get(0).(func() *message.Message); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *message.Message); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*message.Message) } } - return r0 } -// Size provides a mock function with no fields -func (_m *OutgoingMessageScope) Size() int { - ret := _m.Called() +// OutgoingMessageScope_Proto_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Proto' +type OutgoingMessageScope_Proto_Call struct { + *mock.Call +} + +// Proto is a helper method to define mock.On call +func (_e *OutgoingMessageScope_Expecter) Proto() *OutgoingMessageScope_Proto_Call { + return &OutgoingMessageScope_Proto_Call{Call: _e.mock.On("Proto")} +} + +func (_c *OutgoingMessageScope_Proto_Call) Run(run func()) *OutgoingMessageScope_Proto_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OutgoingMessageScope_Proto_Call) Return(message1 *message.Message) *OutgoingMessageScope_Proto_Call { + _c.Call.Return(message1) + return _c +} + +func (_c *OutgoingMessageScope_Proto_Call) RunAndReturn(run func() *message.Message) *OutgoingMessageScope_Proto_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type OutgoingMessageScope +func (_mock *OutgoingMessageScope) Size() int { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 int - if rf, ok := ret.Get(0).(func() int); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() int); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(int) } - return r0 } -// TargetIds provides a mock function with no fields -func (_m *OutgoingMessageScope) TargetIds() flow.IdentifierList { - ret := _m.Called() +// OutgoingMessageScope_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type OutgoingMessageScope_Size_Call struct { + *mock.Call +} + +// Size is a helper method to define mock.On call +func (_e *OutgoingMessageScope_Expecter) Size() *OutgoingMessageScope_Size_Call { + return &OutgoingMessageScope_Size_Call{Call: _e.mock.On("Size")} +} + +func (_c *OutgoingMessageScope_Size_Call) Run(run func()) *OutgoingMessageScope_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OutgoingMessageScope_Size_Call) Return(n int) *OutgoingMessageScope_Size_Call { + _c.Call.Return(n) + return _c +} + +func (_c *OutgoingMessageScope_Size_Call) RunAndReturn(run func() int) *OutgoingMessageScope_Size_Call { + _c.Call.Return(run) + return _c +} + +// TargetIds provides a mock function for the type OutgoingMessageScope +func (_mock *OutgoingMessageScope) TargetIds() flow.IdentifierList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TargetIds") } var r0 flow.IdentifierList - if rf, ok := ret.Get(0).(func() flow.IdentifierList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentifierList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentifierList) } } - return r0 } -// Topic provides a mock function with no fields -func (_m *OutgoingMessageScope) Topic() channels.Topic { - ret := _m.Called() +// OutgoingMessageScope_TargetIds_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TargetIds' +type OutgoingMessageScope_TargetIds_Call struct { + *mock.Call +} + +// TargetIds is a helper method to define mock.On call +func (_e *OutgoingMessageScope_Expecter) TargetIds() *OutgoingMessageScope_TargetIds_Call { + return &OutgoingMessageScope_TargetIds_Call{Call: _e.mock.On("TargetIds")} +} + +func (_c *OutgoingMessageScope_TargetIds_Call) Run(run func()) *OutgoingMessageScope_TargetIds_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OutgoingMessageScope_TargetIds_Call) Return(identifierList flow.IdentifierList) *OutgoingMessageScope_TargetIds_Call { + _c.Call.Return(identifierList) + return _c +} + +func (_c *OutgoingMessageScope_TargetIds_Call) RunAndReturn(run func() flow.IdentifierList) *OutgoingMessageScope_TargetIds_Call { + _c.Call.Return(run) + return _c +} + +// Topic provides a mock function for the type OutgoingMessageScope +func (_mock *OutgoingMessageScope) Topic() channels.Topic { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Topic") } var r0 channels.Topic - if rf, ok := ret.Get(0).(func() channels.Topic); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() channels.Topic); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(channels.Topic) } - return r0 } -// NewOutgoingMessageScope creates a new instance of OutgoingMessageScope. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewOutgoingMessageScope(t interface { - mock.TestingT - Cleanup(func()) -}) *OutgoingMessageScope { - mock := &OutgoingMessageScope{} - mock.Mock.Test(t) +// OutgoingMessageScope_Topic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Topic' +type OutgoingMessageScope_Topic_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Topic is a helper method to define mock.On call +func (_e *OutgoingMessageScope_Expecter) Topic() *OutgoingMessageScope_Topic_Call { + return &OutgoingMessageScope_Topic_Call{Call: _e.mock.On("Topic")} +} - return mock +func (_c *OutgoingMessageScope_Topic_Call) Run(run func()) *OutgoingMessageScope_Topic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OutgoingMessageScope_Topic_Call) Return(topic channels.Topic) *OutgoingMessageScope_Topic_Call { + _c.Call.Return(topic) + return _c +} + +func (_c *OutgoingMessageScope_Topic_Call) RunAndReturn(run func() channels.Topic) *OutgoingMessageScope_Topic_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/ping_info_provider.go b/network/mock/ping_info_provider.go index cb0d46c9750..7355ffb1c6f 100644 --- a/network/mock/ping_info_provider.go +++ b/network/mock/ping_info_provider.go @@ -1,78 +1,168 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewPingInfoProvider creates a new instance of PingInfoProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPingInfoProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *PingInfoProvider { + mock := &PingInfoProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // PingInfoProvider is an autogenerated mock type for the PingInfoProvider type type PingInfoProvider struct { mock.Mock } -// HotstuffView provides a mock function with no fields -func (_m *PingInfoProvider) HotstuffView() uint64 { - ret := _m.Called() +type PingInfoProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *PingInfoProvider) EXPECT() *PingInfoProvider_Expecter { + return &PingInfoProvider_Expecter{mock: &_m.Mock} +} + +// HotstuffView provides a mock function for the type PingInfoProvider +func (_mock *PingInfoProvider) HotstuffView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for HotstuffView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// SealedBlockHeight provides a mock function with no fields -func (_m *PingInfoProvider) SealedBlockHeight() uint64 { - ret := _m.Called() +// PingInfoProvider_HotstuffView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HotstuffView' +type PingInfoProvider_HotstuffView_Call struct { + *mock.Call +} + +// HotstuffView is a helper method to define mock.On call +func (_e *PingInfoProvider_Expecter) HotstuffView() *PingInfoProvider_HotstuffView_Call { + return &PingInfoProvider_HotstuffView_Call{Call: _e.mock.On("HotstuffView")} +} + +func (_c *PingInfoProvider_HotstuffView_Call) Run(run func()) *PingInfoProvider_HotstuffView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PingInfoProvider_HotstuffView_Call) Return(v uint64) *PingInfoProvider_HotstuffView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *PingInfoProvider_HotstuffView_Call) RunAndReturn(run func() uint64) *PingInfoProvider_HotstuffView_Call { + _c.Call.Return(run) + return _c +} + +// SealedBlockHeight provides a mock function for the type PingInfoProvider +func (_mock *PingInfoProvider) SealedBlockHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SealedBlockHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// SoftwareVersion provides a mock function with no fields -func (_m *PingInfoProvider) SoftwareVersion() string { - ret := _m.Called() +// PingInfoProvider_SealedBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SealedBlockHeight' +type PingInfoProvider_SealedBlockHeight_Call struct { + *mock.Call +} + +// SealedBlockHeight is a helper method to define mock.On call +func (_e *PingInfoProvider_Expecter) SealedBlockHeight() *PingInfoProvider_SealedBlockHeight_Call { + return &PingInfoProvider_SealedBlockHeight_Call{Call: _e.mock.On("SealedBlockHeight")} +} + +func (_c *PingInfoProvider_SealedBlockHeight_Call) Run(run func()) *PingInfoProvider_SealedBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PingInfoProvider_SealedBlockHeight_Call) Return(v uint64) *PingInfoProvider_SealedBlockHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *PingInfoProvider_SealedBlockHeight_Call) RunAndReturn(run func() uint64) *PingInfoProvider_SealedBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// SoftwareVersion provides a mock function for the type PingInfoProvider +func (_mock *PingInfoProvider) SoftwareVersion() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SoftwareVersion") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// NewPingInfoProvider creates a new instance of PingInfoProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPingInfoProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *PingInfoProvider { - mock := &PingInfoProvider{} - mock.Mock.Test(t) +// PingInfoProvider_SoftwareVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SoftwareVersion' +type PingInfoProvider_SoftwareVersion_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SoftwareVersion is a helper method to define mock.On call +func (_e *PingInfoProvider_Expecter) SoftwareVersion() *PingInfoProvider_SoftwareVersion_Call { + return &PingInfoProvider_SoftwareVersion_Call{Call: _e.mock.On("SoftwareVersion")} +} - return mock +func (_c *PingInfoProvider_SoftwareVersion_Call) Run(run func()) *PingInfoProvider_SoftwareVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PingInfoProvider_SoftwareVersion_Call) Return(s string) *PingInfoProvider_SoftwareVersion_Call { + _c.Call.Return(s) + return _c +} + +func (_c *PingInfoProvider_SoftwareVersion_Call) RunAndReturn(run func() string) *PingInfoProvider_SoftwareVersion_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/ping_service.go b/network/mock/ping_service.go index 8e189e91d67..b70230c4841 100644 --- a/network/mock/ping_service.go +++ b/network/mock/ping_service.go @@ -1,26 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" + "time" - message "github.com/onflow/flow-go/network/message" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network/message" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewPingService creates a new instance of PingService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPingService(t interface { + mock.TestingT + Cleanup(func()) +}) *PingService { + mock := &PingService{} + mock.Mock.Test(t) - time "time" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // PingService is an autogenerated mock type for the PingService type type PingService struct { mock.Mock } -// Ping provides a mock function with given fields: ctx, peerID -func (_m *PingService) Ping(ctx context.Context, peerID peer.ID) (message.PingResponse, time.Duration, error) { - ret := _m.Called(ctx, peerID) +type PingService_Expecter struct { + mock *mock.Mock +} + +func (_m *PingService) EXPECT() *PingService_Expecter { + return &PingService_Expecter{mock: &_m.Mock} +} + +// Ping provides a mock function for the type PingService +func (_mock *PingService) Ping(ctx context.Context, peerID peer.ID) (message.PingResponse, time.Duration, error) { + ret := _mock.Called(ctx, peerID) if len(ret) == 0 { panic("no return value specified for Ping") @@ -29,40 +51,63 @@ func (_m *PingService) Ping(ctx context.Context, peerID peer.ID) (message.PingRe var r0 message.PingResponse var r1 time.Duration var r2 error - if rf, ok := ret.Get(0).(func(context.Context, peer.ID) (message.PingResponse, time.Duration, error)); ok { - return rf(ctx, peerID) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID) (message.PingResponse, time.Duration, error)); ok { + return returnFunc(ctx, peerID) } - if rf, ok := ret.Get(0).(func(context.Context, peer.ID) message.PingResponse); ok { - r0 = rf(ctx, peerID) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID) message.PingResponse); ok { + r0 = returnFunc(ctx, peerID) } else { r0 = ret.Get(0).(message.PingResponse) } - - if rf, ok := ret.Get(1).(func(context.Context, peer.ID) time.Duration); ok { - r1 = rf(ctx, peerID) + if returnFunc, ok := ret.Get(1).(func(context.Context, peer.ID) time.Duration); ok { + r1 = returnFunc(ctx, peerID) } else { r1 = ret.Get(1).(time.Duration) } - - if rf, ok := ret.Get(2).(func(context.Context, peer.ID) error); ok { - r2 = rf(ctx, peerID) + if returnFunc, ok := ret.Get(2).(func(context.Context, peer.ID) error); ok { + r2 = returnFunc(ctx, peerID) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewPingService creates a new instance of PingService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPingService(t interface { - mock.TestingT - Cleanup(func()) -}) *PingService { - mock := &PingService{} - mock.Mock.Test(t) +// PingService_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping' +type PingService_Ping_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Ping is a helper method to define mock.On call +// - ctx context.Context +// - peerID peer.ID +func (_e *PingService_Expecter) Ping(ctx interface{}, peerID interface{}) *PingService_Ping_Call { + return &PingService_Ping_Call{Call: _e.mock.On("Ping", ctx, peerID)} +} - return mock +func (_c *PingService_Ping_Call) Run(run func(ctx context.Context, peerID peer.ID)) *PingService_Ping_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PingService_Ping_Call) Return(pingResponse message.PingResponse, duration time.Duration, err error) *PingService_Ping_Call { + _c.Call.Return(pingResponse, duration, err) + return _c +} + +func (_c *PingService_Ping_Call) RunAndReturn(run func(ctx context.Context, peerID peer.ID) (message.PingResponse, time.Duration, error)) *PingService_Ping_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/subscription_manager.go b/network/mock/subscription_manager.go index ed6a3c45f90..365b1f51c99 100644 --- a/network/mock/subscription_manager.go +++ b/network/mock/subscription_manager.go @@ -1,42 +1,91 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewSubscriptionManager creates a new instance of SubscriptionManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscriptionManager(t interface { + mock.TestingT + Cleanup(func()) +}) *SubscriptionManager { + mock := &SubscriptionManager{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SubscriptionManager is an autogenerated mock type for the SubscriptionManager type type SubscriptionManager struct { mock.Mock } -// Channels provides a mock function with no fields -func (_m *SubscriptionManager) Channels() channels.ChannelList { - ret := _m.Called() +type SubscriptionManager_Expecter struct { + mock *mock.Mock +} + +func (_m *SubscriptionManager) EXPECT() *SubscriptionManager_Expecter { + return &SubscriptionManager_Expecter{mock: &_m.Mock} +} + +// Channels provides a mock function for the type SubscriptionManager +func (_mock *SubscriptionManager) Channels() channels.ChannelList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Channels") } var r0 channels.ChannelList - if rf, ok := ret.Get(0).(func() channels.ChannelList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() channels.ChannelList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(channels.ChannelList) } } - return r0 } -// GetEngine provides a mock function with given fields: channel -func (_m *SubscriptionManager) GetEngine(channel channels.Channel) (network.MessageProcessor, error) { - ret := _m.Called(channel) +// SubscriptionManager_Channels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Channels' +type SubscriptionManager_Channels_Call struct { + *mock.Call +} + +// Channels is a helper method to define mock.On call +func (_e *SubscriptionManager_Expecter) Channels() *SubscriptionManager_Channels_Call { + return &SubscriptionManager_Channels_Call{Call: _e.mock.On("Channels")} +} + +func (_c *SubscriptionManager_Channels_Call) Run(run func()) *SubscriptionManager_Channels_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SubscriptionManager_Channels_Call) Return(channelList channels.ChannelList) *SubscriptionManager_Channels_Call { + _c.Call.Return(channelList) + return _c +} + +func (_c *SubscriptionManager_Channels_Call) RunAndReturn(run func() channels.ChannelList) *SubscriptionManager_Channels_Call { + _c.Call.Return(run) + return _c +} + +// GetEngine provides a mock function for the type SubscriptionManager +func (_mock *SubscriptionManager) GetEngine(channel channels.Channel) (network.MessageProcessor, error) { + ret := _mock.Called(channel) if len(ret) == 0 { panic("no return value specified for GetEngine") @@ -44,72 +93,162 @@ func (_m *SubscriptionManager) GetEngine(channel channels.Channel) (network.Mess var r0 network.MessageProcessor var r1 error - if rf, ok := ret.Get(0).(func(channels.Channel) (network.MessageProcessor, error)); ok { - return rf(channel) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) (network.MessageProcessor, error)); ok { + return returnFunc(channel) } - if rf, ok := ret.Get(0).(func(channels.Channel) network.MessageProcessor); ok { - r0 = rf(channel) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) network.MessageProcessor); ok { + r0 = returnFunc(channel) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.MessageProcessor) } } - - if rf, ok := ret.Get(1).(func(channels.Channel) error); ok { - r1 = rf(channel) + if returnFunc, ok := ret.Get(1).(func(channels.Channel) error); ok { + r1 = returnFunc(channel) } else { r1 = ret.Error(1) } - return r0, r1 } -// Register provides a mock function with given fields: channel, engine -func (_m *SubscriptionManager) Register(channel channels.Channel, engine network.MessageProcessor) error { - ret := _m.Called(channel, engine) +// SubscriptionManager_GetEngine_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEngine' +type SubscriptionManager_GetEngine_Call struct { + *mock.Call +} + +// GetEngine is a helper method to define mock.On call +// - channel channels.Channel +func (_e *SubscriptionManager_Expecter) GetEngine(channel interface{}) *SubscriptionManager_GetEngine_Call { + return &SubscriptionManager_GetEngine_Call{Call: _e.mock.On("GetEngine", channel)} +} + +func (_c *SubscriptionManager_GetEngine_Call) Run(run func(channel channels.Channel)) *SubscriptionManager_GetEngine_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SubscriptionManager_GetEngine_Call) Return(messageProcessor network.MessageProcessor, err error) *SubscriptionManager_GetEngine_Call { + _c.Call.Return(messageProcessor, err) + return _c +} + +func (_c *SubscriptionManager_GetEngine_Call) RunAndReturn(run func(channel channels.Channel) (network.MessageProcessor, error)) *SubscriptionManager_GetEngine_Call { + _c.Call.Return(run) + return _c +} + +// Register provides a mock function for the type SubscriptionManager +func (_mock *SubscriptionManager) Register(channel channels.Channel, engine network.MessageProcessor) error { + ret := _mock.Called(channel, engine) if len(ret) == 0 { panic("no return value specified for Register") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel, network.MessageProcessor) error); ok { - r0 = rf(channel, engine) + if returnFunc, ok := ret.Get(0).(func(channels.Channel, network.MessageProcessor) error); ok { + r0 = returnFunc(channel, engine) } else { r0 = ret.Error(0) } - return r0 } -// Unregister provides a mock function with given fields: channel -func (_m *SubscriptionManager) Unregister(channel channels.Channel) error { - ret := _m.Called(channel) +// SubscriptionManager_Register_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Register' +type SubscriptionManager_Register_Call struct { + *mock.Call +} + +// Register is a helper method to define mock.On call +// - channel channels.Channel +// - engine network.MessageProcessor +func (_e *SubscriptionManager_Expecter) Register(channel interface{}, engine interface{}) *SubscriptionManager_Register_Call { + return &SubscriptionManager_Register_Call{Call: _e.mock.On("Register", channel, engine)} +} + +func (_c *SubscriptionManager_Register_Call) Run(run func(channel channels.Channel, engine network.MessageProcessor)) *SubscriptionManager_Register_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + var arg1 network.MessageProcessor + if args[1] != nil { + arg1 = args[1].(network.MessageProcessor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SubscriptionManager_Register_Call) Return(err error) *SubscriptionManager_Register_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SubscriptionManager_Register_Call) RunAndReturn(run func(channel channels.Channel, engine network.MessageProcessor) error) *SubscriptionManager_Register_Call { + _c.Call.Return(run) + return _c +} + +// Unregister provides a mock function for the type SubscriptionManager +func (_mock *SubscriptionManager) Unregister(channel channels.Channel) error { + ret := _mock.Called(channel) if len(ret) == 0 { panic("no return value specified for Unregister") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel) error); ok { - r0 = rf(channel) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) error); ok { + r0 = returnFunc(channel) } else { r0 = ret.Error(0) } - return r0 } -// NewSubscriptionManager creates a new instance of SubscriptionManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSubscriptionManager(t interface { - mock.TestingT - Cleanup(func()) -}) *SubscriptionManager { - mock := &SubscriptionManager{} - mock.Mock.Test(t) +// SubscriptionManager_Unregister_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Unregister' +type SubscriptionManager_Unregister_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Unregister is a helper method to define mock.On call +// - channel channels.Channel +func (_e *SubscriptionManager_Expecter) Unregister(channel interface{}) *SubscriptionManager_Unregister_Call { + return &SubscriptionManager_Unregister_Call{Call: _e.mock.On("Unregister", channel)} +} - return mock +func (_c *SubscriptionManager_Unregister_Call) Run(run func(channel channels.Channel)) *SubscriptionManager_Unregister_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SubscriptionManager_Unregister_Call) Return(err error) *SubscriptionManager_Unregister_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SubscriptionManager_Unregister_Call) RunAndReturn(run func(channel channels.Channel) error) *SubscriptionManager_Unregister_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/topology.go b/network/mock/topology.go index 55bf8e15038..717ad8fb68a 100644 --- a/network/mock/topology.go +++ b/network/mock/topology.go @@ -1,47 +1,90 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTopology creates a new instance of Topology. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTopology(t interface { + mock.TestingT + Cleanup(func()) +}) *Topology { + mock := &Topology{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Topology is an autogenerated mock type for the Topology type type Topology struct { mock.Mock } -// Fanout provides a mock function with given fields: ids -func (_m *Topology) Fanout(ids flow.IdentityList) flow.IdentityList { - ret := _m.Called(ids) +type Topology_Expecter struct { + mock *mock.Mock +} + +func (_m *Topology) EXPECT() *Topology_Expecter { + return &Topology_Expecter{mock: &_m.Mock} +} + +// Fanout provides a mock function for the type Topology +func (_mock *Topology) Fanout(ids flow.IdentityList) flow.IdentityList { + ret := _mock.Called(ids) if len(ret) == 0 { panic("no return value specified for Fanout") } var r0 flow.IdentityList - if rf, ok := ret.Get(0).(func(flow.IdentityList) flow.IdentityList); ok { - r0 = rf(ids) + if returnFunc, ok := ret.Get(0).(func(flow.IdentityList) flow.IdentityList); ok { + r0 = returnFunc(ids) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentityList) } } - return r0 } -// NewTopology creates a new instance of Topology. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTopology(t interface { - mock.TestingT - Cleanup(func()) -}) *Topology { - mock := &Topology{} - mock.Mock.Test(t) +// Topology_Fanout_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Fanout' +type Topology_Fanout_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Fanout is a helper method to define mock.On call +// - ids flow.IdentityList +func (_e *Topology_Expecter) Fanout(ids interface{}) *Topology_Fanout_Call { + return &Topology_Fanout_Call{Call: _e.mock.On("Fanout", ids)} +} - return mock +func (_c *Topology_Fanout_Call) Run(run func(ids flow.IdentityList)) *Topology_Fanout_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.IdentityList + if args[0] != nil { + arg0 = args[0].(flow.IdentityList) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Topology_Fanout_Call) Return(v flow.IdentityList) *Topology_Fanout_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Topology_Fanout_Call) RunAndReturn(run func(ids flow.IdentityList) flow.IdentityList) *Topology_Fanout_Call { + _c.Call.Return(run) + return _c } diff --git a/network/mock/underlay.go b/network/mock/underlay.go index 9ea08e42128..4b23f1eb6e5 100644 --- a/network/mock/underlay.go +++ b/network/mock/underlay.go @@ -1,120 +1,345 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" - - network "github.com/onflow/flow-go/network" ) +// NewUnderlay creates a new instance of Underlay. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewUnderlay(t interface { + mock.TestingT + Cleanup(func()) +}) *Underlay { + mock := &Underlay{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Underlay is an autogenerated mock type for the Underlay type type Underlay struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *Underlay) Done() <-chan struct{} { - ret := _m.Called() +type Underlay_Expecter struct { + mock *mock.Mock +} + +func (_m *Underlay) EXPECT() *Underlay_Expecter { + return &Underlay_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type Underlay +func (_mock *Underlay) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// OnAllowListNotification provides a mock function with given fields: _a0 -func (_m *Underlay) OnAllowListNotification(_a0 *network.AllowListingUpdate) { - _m.Called(_a0) +// Underlay_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type Underlay_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *Underlay_Expecter) Done() *Underlay_Done_Call { + return &Underlay_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *Underlay_Done_Call) Run(run func()) *Underlay_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Underlay_Done_Call) Return(valCh <-chan struct{}) *Underlay_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Underlay_Done_Call) RunAndReturn(run func() <-chan struct{}) *Underlay_Done_Call { + _c.Call.Return(run) + return _c +} + +// OnAllowListNotification provides a mock function for the type Underlay +func (_mock *Underlay) OnAllowListNotification(allowListingUpdate *network.AllowListingUpdate) { + _mock.Called(allowListingUpdate) + return +} + +// Underlay_OnAllowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAllowListNotification' +type Underlay_OnAllowListNotification_Call struct { + *mock.Call +} + +// OnAllowListNotification is a helper method to define mock.On call +// - allowListingUpdate *network.AllowListingUpdate +func (_e *Underlay_Expecter) OnAllowListNotification(allowListingUpdate interface{}) *Underlay_OnAllowListNotification_Call { + return &Underlay_OnAllowListNotification_Call{Call: _e.mock.On("OnAllowListNotification", allowListingUpdate)} +} + +func (_c *Underlay_OnAllowListNotification_Call) Run(run func(allowListingUpdate *network.AllowListingUpdate)) *Underlay_OnAllowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.AllowListingUpdate + if args[0] != nil { + arg0 = args[0].(*network.AllowListingUpdate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Underlay_OnAllowListNotification_Call) Return() *Underlay_OnAllowListNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *Underlay_OnAllowListNotification_Call) RunAndReturn(run func(allowListingUpdate *network.AllowListingUpdate)) *Underlay_OnAllowListNotification_Call { + _c.Run(run) + return _c +} + +// OnDisallowListNotification provides a mock function for the type Underlay +func (_mock *Underlay) OnDisallowListNotification(disallowListingUpdate *network.DisallowListingUpdate) { + _mock.Called(disallowListingUpdate) + return +} + +// Underlay_OnDisallowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDisallowListNotification' +type Underlay_OnDisallowListNotification_Call struct { + *mock.Call +} + +// OnDisallowListNotification is a helper method to define mock.On call +// - disallowListingUpdate *network.DisallowListingUpdate +func (_e *Underlay_Expecter) OnDisallowListNotification(disallowListingUpdate interface{}) *Underlay_OnDisallowListNotification_Call { + return &Underlay_OnDisallowListNotification_Call{Call: _e.mock.On("OnDisallowListNotification", disallowListingUpdate)} +} + +func (_c *Underlay_OnDisallowListNotification_Call) Run(run func(disallowListingUpdate *network.DisallowListingUpdate)) *Underlay_OnDisallowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.DisallowListingUpdate + if args[0] != nil { + arg0 = args[0].(*network.DisallowListingUpdate) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Underlay_OnDisallowListNotification_Call) Return() *Underlay_OnDisallowListNotification_Call { + _c.Call.Return() + return _c } -// OnDisallowListNotification provides a mock function with given fields: _a0 -func (_m *Underlay) OnDisallowListNotification(_a0 *network.DisallowListingUpdate) { - _m.Called(_a0) +func (_c *Underlay_OnDisallowListNotification_Call) RunAndReturn(run func(disallowListingUpdate *network.DisallowListingUpdate)) *Underlay_OnDisallowListNotification_Call { + _c.Run(run) + return _c } -// Ready provides a mock function with no fields -func (_m *Underlay) Ready() <-chan struct{} { - ret := _m.Called() +// Ready provides a mock function for the type Underlay +func (_mock *Underlay) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Subscribe provides a mock function with given fields: channel -func (_m *Underlay) Subscribe(channel channels.Channel) error { - ret := _m.Called(channel) +// Underlay_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type Underlay_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *Underlay_Expecter) Ready() *Underlay_Ready_Call { + return &Underlay_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *Underlay_Ready_Call) Run(run func()) *Underlay_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Underlay_Ready_Call) Return(valCh <-chan struct{}) *Underlay_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *Underlay_Ready_Call) RunAndReturn(run func() <-chan struct{}) *Underlay_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Subscribe provides a mock function for the type Underlay +func (_mock *Underlay) Subscribe(channel channels.Channel) error { + ret := _mock.Called(channel) if len(ret) == 0 { panic("no return value specified for Subscribe") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel) error); ok { - r0 = rf(channel) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) error); ok { + r0 = returnFunc(channel) } else { r0 = ret.Error(0) } - return r0 } -// Unsubscribe provides a mock function with given fields: channel -func (_m *Underlay) Unsubscribe(channel channels.Channel) error { - ret := _m.Called(channel) +// Underlay_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' +type Underlay_Subscribe_Call struct { + *mock.Call +} + +// Subscribe is a helper method to define mock.On call +// - channel channels.Channel +func (_e *Underlay_Expecter) Subscribe(channel interface{}) *Underlay_Subscribe_Call { + return &Underlay_Subscribe_Call{Call: _e.mock.On("Subscribe", channel)} +} + +func (_c *Underlay_Subscribe_Call) Run(run func(channel channels.Channel)) *Underlay_Subscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Underlay_Subscribe_Call) Return(err error) *Underlay_Subscribe_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Underlay_Subscribe_Call) RunAndReturn(run func(channel channels.Channel) error) *Underlay_Subscribe_Call { + _c.Call.Return(run) + return _c +} + +// Unsubscribe provides a mock function for the type Underlay +func (_mock *Underlay) Unsubscribe(channel channels.Channel) error { + ret := _mock.Called(channel) if len(ret) == 0 { panic("no return value specified for Unsubscribe") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Channel) error); ok { - r0 = rf(channel) + if returnFunc, ok := ret.Get(0).(func(channels.Channel) error); ok { + r0 = returnFunc(channel) } else { r0 = ret.Error(0) } - return r0 } -// UpdateNodeAddresses provides a mock function with no fields -func (_m *Underlay) UpdateNodeAddresses() { - _m.Called() +// Underlay_Unsubscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Unsubscribe' +type Underlay_Unsubscribe_Call struct { + *mock.Call } -// NewUnderlay creates a new instance of Underlay. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewUnderlay(t interface { - mock.TestingT - Cleanup(func()) -}) *Underlay { - mock := &Underlay{} - mock.Mock.Test(t) +// Unsubscribe is a helper method to define mock.On call +// - channel channels.Channel +func (_e *Underlay_Expecter) Unsubscribe(channel interface{}) *Underlay_Unsubscribe_Call { + return &Underlay_Unsubscribe_Call{Call: _e.mock.On("Unsubscribe", channel)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *Underlay_Unsubscribe_Call) Run(run func(channel channels.Channel)) *Underlay_Unsubscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Channel + if args[0] != nil { + arg0 = args[0].(channels.Channel) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *Underlay_Unsubscribe_Call) Return(err error) *Underlay_Unsubscribe_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Underlay_Unsubscribe_Call) RunAndReturn(run func(channel channels.Channel) error) *Underlay_Unsubscribe_Call { + _c.Call.Return(run) + return _c +} + +// UpdateNodeAddresses provides a mock function for the type Underlay +func (_mock *Underlay) UpdateNodeAddresses() { + _mock.Called() + return +} + +// Underlay_UpdateNodeAddresses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateNodeAddresses' +type Underlay_UpdateNodeAddresses_Call struct { + *mock.Call +} + +// UpdateNodeAddresses is a helper method to define mock.On call +func (_e *Underlay_Expecter) UpdateNodeAddresses() *Underlay_UpdateNodeAddresses_Call { + return &Underlay_UpdateNodeAddresses_Call{Call: _e.mock.On("UpdateNodeAddresses")} +} + +func (_c *Underlay_UpdateNodeAddresses_Call) Run(run func()) *Underlay_UpdateNodeAddresses_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Underlay_UpdateNodeAddresses_Call) Return() *Underlay_UpdateNodeAddresses_Call { + _c.Call.Return() + return _c +} + +func (_c *Underlay_UpdateNodeAddresses_Call) RunAndReturn(run func()) *Underlay_UpdateNodeAddresses_Call { + _c.Run(run) + return _c } diff --git a/network/mock/violations_consumer.go b/network/mock/violations_consumer.go index 9a5b824d1b4..c59f3dbb8f7 100644 --- a/network/mock/violations_consumer.go +++ b/network/mock/violations_consumer.go @@ -1,62 +1,317 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" ) +// NewViolationsConsumer creates a new instance of ViolationsConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewViolationsConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *ViolationsConsumer { + mock := &ViolationsConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ViolationsConsumer is an autogenerated mock type for the ViolationsConsumer type type ViolationsConsumer struct { mock.Mock } -// OnInvalidMsgError provides a mock function with given fields: violation -func (_m *ViolationsConsumer) OnInvalidMsgError(violation *network.Violation) { - _m.Called(violation) +type ViolationsConsumer_Expecter struct { + mock *mock.Mock } -// OnSenderEjectedError provides a mock function with given fields: violation -func (_m *ViolationsConsumer) OnSenderEjectedError(violation *network.Violation) { - _m.Called(violation) +func (_m *ViolationsConsumer) EXPECT() *ViolationsConsumer_Expecter { + return &ViolationsConsumer_Expecter{mock: &_m.Mock} } -// OnUnAuthorizedSenderError provides a mock function with given fields: violation -func (_m *ViolationsConsumer) OnUnAuthorizedSenderError(violation *network.Violation) { - _m.Called(violation) +// OnInvalidMsgError provides a mock function for the type ViolationsConsumer +func (_mock *ViolationsConsumer) OnInvalidMsgError(violation *network.Violation) { + _mock.Called(violation) + return } -// OnUnauthorizedPublishOnChannel provides a mock function with given fields: violation -func (_m *ViolationsConsumer) OnUnauthorizedPublishOnChannel(violation *network.Violation) { - _m.Called(violation) +// ViolationsConsumer_OnInvalidMsgError_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidMsgError' +type ViolationsConsumer_OnInvalidMsgError_Call struct { + *mock.Call } -// OnUnauthorizedUnicastOnChannel provides a mock function with given fields: violation -func (_m *ViolationsConsumer) OnUnauthorizedUnicastOnChannel(violation *network.Violation) { - _m.Called(violation) +// OnInvalidMsgError is a helper method to define mock.On call +// - violation *network.Violation +func (_e *ViolationsConsumer_Expecter) OnInvalidMsgError(violation interface{}) *ViolationsConsumer_OnInvalidMsgError_Call { + return &ViolationsConsumer_OnInvalidMsgError_Call{Call: _e.mock.On("OnInvalidMsgError", violation)} } -// OnUnexpectedError provides a mock function with given fields: violation -func (_m *ViolationsConsumer) OnUnexpectedError(violation *network.Violation) { - _m.Called(violation) +func (_c *ViolationsConsumer_OnInvalidMsgError_Call) Run(run func(violation *network.Violation)) *ViolationsConsumer_OnInvalidMsgError_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.Violation + if args[0] != nil { + arg0 = args[0].(*network.Violation) + } + run( + arg0, + ) + }) + return _c } -// OnUnknownMsgTypeError provides a mock function with given fields: violation -func (_m *ViolationsConsumer) OnUnknownMsgTypeError(violation *network.Violation) { - _m.Called(violation) +func (_c *ViolationsConsumer_OnInvalidMsgError_Call) Return() *ViolationsConsumer_OnInvalidMsgError_Call { + _c.Call.Return() + return _c } -// NewViolationsConsumer creates a new instance of ViolationsConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewViolationsConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *ViolationsConsumer { - mock := &ViolationsConsumer{} - mock.Mock.Test(t) +func (_c *ViolationsConsumer_OnInvalidMsgError_Call) RunAndReturn(run func(violation *network.Violation)) *ViolationsConsumer_OnInvalidMsgError_Call { + _c.Run(run) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnSenderEjectedError provides a mock function for the type ViolationsConsumer +func (_mock *ViolationsConsumer) OnSenderEjectedError(violation *network.Violation) { + _mock.Called(violation) + return +} - return mock +// ViolationsConsumer_OnSenderEjectedError_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnSenderEjectedError' +type ViolationsConsumer_OnSenderEjectedError_Call struct { + *mock.Call +} + +// OnSenderEjectedError is a helper method to define mock.On call +// - violation *network.Violation +func (_e *ViolationsConsumer_Expecter) OnSenderEjectedError(violation interface{}) *ViolationsConsumer_OnSenderEjectedError_Call { + return &ViolationsConsumer_OnSenderEjectedError_Call{Call: _e.mock.On("OnSenderEjectedError", violation)} +} + +func (_c *ViolationsConsumer_OnSenderEjectedError_Call) Run(run func(violation *network.Violation)) *ViolationsConsumer_OnSenderEjectedError_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.Violation + if args[0] != nil { + arg0 = args[0].(*network.Violation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ViolationsConsumer_OnSenderEjectedError_Call) Return() *ViolationsConsumer_OnSenderEjectedError_Call { + _c.Call.Return() + return _c +} + +func (_c *ViolationsConsumer_OnSenderEjectedError_Call) RunAndReturn(run func(violation *network.Violation)) *ViolationsConsumer_OnSenderEjectedError_Call { + _c.Run(run) + return _c +} + +// OnUnauthorizedPublishOnChannel provides a mock function for the type ViolationsConsumer +func (_mock *ViolationsConsumer) OnUnauthorizedPublishOnChannel(violation *network.Violation) { + _mock.Called(violation) + return +} + +// ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnauthorizedPublishOnChannel' +type ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call struct { + *mock.Call +} + +// OnUnauthorizedPublishOnChannel is a helper method to define mock.On call +// - violation *network.Violation +func (_e *ViolationsConsumer_Expecter) OnUnauthorizedPublishOnChannel(violation interface{}) *ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call { + return &ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call{Call: _e.mock.On("OnUnauthorizedPublishOnChannel", violation)} +} + +func (_c *ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call) Run(run func(violation *network.Violation)) *ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.Violation + if args[0] != nil { + arg0 = args[0].(*network.Violation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call) Return() *ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call { + _c.Call.Return() + return _c +} + +func (_c *ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call) RunAndReturn(run func(violation *network.Violation)) *ViolationsConsumer_OnUnauthorizedPublishOnChannel_Call { + _c.Run(run) + return _c +} + +// OnUnauthorizedSenderError provides a mock function for the type ViolationsConsumer +func (_mock *ViolationsConsumer) OnUnauthorizedSenderError(violation *network.Violation) { + _mock.Called(violation) + return +} + +// ViolationsConsumer_OnUnauthorizedSenderError_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnauthorizedSenderError' +type ViolationsConsumer_OnUnauthorizedSenderError_Call struct { + *mock.Call +} + +// OnUnauthorizedSenderError is a helper method to define mock.On call +// - violation *network.Violation +func (_e *ViolationsConsumer_Expecter) OnUnauthorizedSenderError(violation interface{}) *ViolationsConsumer_OnUnauthorizedSenderError_Call { + return &ViolationsConsumer_OnUnauthorizedSenderError_Call{Call: _e.mock.On("OnUnauthorizedSenderError", violation)} +} + +func (_c *ViolationsConsumer_OnUnauthorizedSenderError_Call) Run(run func(violation *network.Violation)) *ViolationsConsumer_OnUnauthorizedSenderError_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.Violation + if args[0] != nil { + arg0 = args[0].(*network.Violation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ViolationsConsumer_OnUnauthorizedSenderError_Call) Return() *ViolationsConsumer_OnUnauthorizedSenderError_Call { + _c.Call.Return() + return _c +} + +func (_c *ViolationsConsumer_OnUnauthorizedSenderError_Call) RunAndReturn(run func(violation *network.Violation)) *ViolationsConsumer_OnUnauthorizedSenderError_Call { + _c.Run(run) + return _c +} + +// OnUnauthorizedUnicastOnChannel provides a mock function for the type ViolationsConsumer +func (_mock *ViolationsConsumer) OnUnauthorizedUnicastOnChannel(violation *network.Violation) { + _mock.Called(violation) + return +} + +// ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnauthorizedUnicastOnChannel' +type ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call struct { + *mock.Call +} + +// OnUnauthorizedUnicastOnChannel is a helper method to define mock.On call +// - violation *network.Violation +func (_e *ViolationsConsumer_Expecter) OnUnauthorizedUnicastOnChannel(violation interface{}) *ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call { + return &ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call{Call: _e.mock.On("OnUnauthorizedUnicastOnChannel", violation)} +} + +func (_c *ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call) Run(run func(violation *network.Violation)) *ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.Violation + if args[0] != nil { + arg0 = args[0].(*network.Violation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call) Return() *ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call { + _c.Call.Return() + return _c +} + +func (_c *ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call) RunAndReturn(run func(violation *network.Violation)) *ViolationsConsumer_OnUnauthorizedUnicastOnChannel_Call { + _c.Run(run) + return _c +} + +// OnUnexpectedError provides a mock function for the type ViolationsConsumer +func (_mock *ViolationsConsumer) OnUnexpectedError(violation *network.Violation) { + _mock.Called(violation) + return +} + +// ViolationsConsumer_OnUnexpectedError_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnexpectedError' +type ViolationsConsumer_OnUnexpectedError_Call struct { + *mock.Call +} + +// OnUnexpectedError is a helper method to define mock.On call +// - violation *network.Violation +func (_e *ViolationsConsumer_Expecter) OnUnexpectedError(violation interface{}) *ViolationsConsumer_OnUnexpectedError_Call { + return &ViolationsConsumer_OnUnexpectedError_Call{Call: _e.mock.On("OnUnexpectedError", violation)} +} + +func (_c *ViolationsConsumer_OnUnexpectedError_Call) Run(run func(violation *network.Violation)) *ViolationsConsumer_OnUnexpectedError_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.Violation + if args[0] != nil { + arg0 = args[0].(*network.Violation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ViolationsConsumer_OnUnexpectedError_Call) Return() *ViolationsConsumer_OnUnexpectedError_Call { + _c.Call.Return() + return _c +} + +func (_c *ViolationsConsumer_OnUnexpectedError_Call) RunAndReturn(run func(violation *network.Violation)) *ViolationsConsumer_OnUnexpectedError_Call { + _c.Run(run) + return _c +} + +// OnUnknownMsgTypeError provides a mock function for the type ViolationsConsumer +func (_mock *ViolationsConsumer) OnUnknownMsgTypeError(violation *network.Violation) { + _mock.Called(violation) + return +} + +// ViolationsConsumer_OnUnknownMsgTypeError_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnUnknownMsgTypeError' +type ViolationsConsumer_OnUnknownMsgTypeError_Call struct { + *mock.Call +} + +// OnUnknownMsgTypeError is a helper method to define mock.On call +// - violation *network.Violation +func (_e *ViolationsConsumer_Expecter) OnUnknownMsgTypeError(violation interface{}) *ViolationsConsumer_OnUnknownMsgTypeError_Call { + return &ViolationsConsumer_OnUnknownMsgTypeError_Call{Call: _e.mock.On("OnUnknownMsgTypeError", violation)} +} + +func (_c *ViolationsConsumer_OnUnknownMsgTypeError_Call) Run(run func(violation *network.Violation)) *ViolationsConsumer_OnUnknownMsgTypeError_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *network.Violation + if args[0] != nil { + arg0 = args[0].(*network.Violation) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ViolationsConsumer_OnUnknownMsgTypeError_Call) Return() *ViolationsConsumer_OnUnknownMsgTypeError_Call { + _c.Call.Return() + return _c +} + +func (_c *ViolationsConsumer_OnUnknownMsgTypeError_Call) RunAndReturn(run func(violation *network.Violation)) *ViolationsConsumer_OnUnknownMsgTypeError_Call { + _c.Run(run) + return _c } diff --git a/network/mock/write_close_flusher.go b/network/mock/write_close_flusher.go index be3736694ea..d4acd1ec408 100644 --- a/network/mock/write_close_flusher.go +++ b/network/mock/write_close_flusher.go @@ -1,53 +1,131 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewWriteCloseFlusher creates a new instance of WriteCloseFlusher. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewWriteCloseFlusher(t interface { + mock.TestingT + Cleanup(func()) +}) *WriteCloseFlusher { + mock := &WriteCloseFlusher{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // WriteCloseFlusher is an autogenerated mock type for the WriteCloseFlusher type type WriteCloseFlusher struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *WriteCloseFlusher) Close() error { - ret := _m.Called() +type WriteCloseFlusher_Expecter struct { + mock *mock.Mock +} + +func (_m *WriteCloseFlusher) EXPECT() *WriteCloseFlusher_Expecter { + return &WriteCloseFlusher_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type WriteCloseFlusher +func (_mock *WriteCloseFlusher) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Flush provides a mock function with no fields -func (_m *WriteCloseFlusher) Flush() error { - ret := _m.Called() +// WriteCloseFlusher_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type WriteCloseFlusher_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *WriteCloseFlusher_Expecter) Close() *WriteCloseFlusher_Close_Call { + return &WriteCloseFlusher_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *WriteCloseFlusher_Close_Call) Run(run func()) *WriteCloseFlusher_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *WriteCloseFlusher_Close_Call) Return(err error) *WriteCloseFlusher_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WriteCloseFlusher_Close_Call) RunAndReturn(run func() error) *WriteCloseFlusher_Close_Call { + _c.Call.Return(run) + return _c +} + +// Flush provides a mock function for the type WriteCloseFlusher +func (_mock *WriteCloseFlusher) Flush() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Flush") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Write provides a mock function with given fields: p -func (_m *WriteCloseFlusher) Write(p []byte) (int, error) { - ret := _m.Called(p) +// WriteCloseFlusher_Flush_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Flush' +type WriteCloseFlusher_Flush_Call struct { + *mock.Call +} + +// Flush is a helper method to define mock.On call +func (_e *WriteCloseFlusher_Expecter) Flush() *WriteCloseFlusher_Flush_Call { + return &WriteCloseFlusher_Flush_Call{Call: _e.mock.On("Flush")} +} + +func (_c *WriteCloseFlusher_Flush_Call) Run(run func()) *WriteCloseFlusher_Flush_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *WriteCloseFlusher_Flush_Call) Return(err error) *WriteCloseFlusher_Flush_Call { + _c.Call.Return(err) + return _c +} + +func (_c *WriteCloseFlusher_Flush_Call) RunAndReturn(run func() error) *WriteCloseFlusher_Flush_Call { + _c.Call.Return(run) + return _c +} + +// Write provides a mock function for the type WriteCloseFlusher +func (_mock *WriteCloseFlusher) Write(p []byte) (int, error) { + ret := _mock.Called(p) if len(ret) == 0 { panic("no return value specified for Write") @@ -55,34 +133,52 @@ func (_m *WriteCloseFlusher) Write(p []byte) (int, error) { var r0 int var r1 error - if rf, ok := ret.Get(0).(func([]byte) (int, error)); ok { - return rf(p) + if returnFunc, ok := ret.Get(0).(func([]byte) (int, error)); ok { + return returnFunc(p) } - if rf, ok := ret.Get(0).(func([]byte) int); ok { - r0 = rf(p) + if returnFunc, ok := ret.Get(0).(func([]byte) int); ok { + r0 = returnFunc(p) } else { r0 = ret.Get(0).(int) } - - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(p) + if returnFunc, ok := ret.Get(1).(func([]byte) error); ok { + r1 = returnFunc(p) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewWriteCloseFlusher creates a new instance of WriteCloseFlusher. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewWriteCloseFlusher(t interface { - mock.TestingT - Cleanup(func()) -}) *WriteCloseFlusher { - mock := &WriteCloseFlusher{} - mock.Mock.Test(t) +// WriteCloseFlusher_Write_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Write' +type WriteCloseFlusher_Write_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Write is a helper method to define mock.On call +// - p []byte +func (_e *WriteCloseFlusher_Expecter) Write(p interface{}) *WriteCloseFlusher_Write_Call { + return &WriteCloseFlusher_Write_Call{Call: _e.mock.On("Write", p)} +} - return mock +func (_c *WriteCloseFlusher_Write_Call) Run(run func(p []byte)) *WriteCloseFlusher_Write_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *WriteCloseFlusher_Write_Call) Return(n int, err error) *WriteCloseFlusher_Write_Call { + _c.Call.Return(n, err) + return _c +} + +func (_c *WriteCloseFlusher_Write_Call) RunAndReturn(run func(p []byte) (int, error)) *WriteCloseFlusher_Write_Call { + _c.Call.Return(run) + return _c } diff --git a/network/netconf/config.go b/network/netconf/config.go index a14933a0498..1e6326d47f0 100644 --- a/network/netconf/config.go +++ b/network/netconf/config.go @@ -33,6 +33,10 @@ type Config struct { DNSCacheTTL time.Duration `validate:"gt=0s" mapstructure:"dns-cache-ttl"` // DisallowListNotificationCacheSize size of the queue for notifications about new peers in the disallow list. DisallowListNotificationCacheSize uint32 `validate:"gt=0" mapstructure:"disallow-list-notification-cache-size"` + // MessageQueueSize is the maximum number of messages that can be buffered in the inbound message queue. + // This limit prevents unbounded memory growth from message flooding attacks. + // If set to 0, a default value will be used. + MessageQueueSize uint32 `mapstructure:"message-queue-size"` } // AlspConfig is the config for the Application Layer Spam Prevention (ALSP) protocol. diff --git a/network/netconf/flags.go b/network/netconf/flags.go index db99cfcdaa6..3596e34d7c5 100644 --- a/network/netconf/flags.go +++ b/network/netconf/flags.go @@ -19,6 +19,7 @@ const ( peerUpdateInterval = "peerupdate-interval" dnsCacheTTL = "dns-cache-ttl" disallowListNotificationCacheSize = "disallow-list-notification-cache-size" + messageQueueSize = "message-queue-size" // resource manager config rootResourceManagerPrefix = "libp2p-resource-manager" memoryLimitRatioPrefix = "memory-limit-ratio" @@ -51,6 +52,7 @@ func AllFlagNames() []string { preferredUnicastsProtocols, receivedMessageCacheSize, peerUpdateInterval, + messageQueueSize, BuildFlagName(unicastKey, MessageTimeoutKey), BuildFlagName(unicastKey, unicastManagerKey, createStreamBackoffDelayKey), BuildFlagName(unicastKey, unicastManagerKey, streamZeroRetryResetThresholdKey), @@ -235,6 +237,10 @@ func InitializeNetworkFlags(flags *pflag.FlagSet, config *Config) { disallowListNotificationCacheSize, config.DisallowListNotificationCacheSize, "cache size for notification events from disallow list") + flags.Uint32( + messageQueueSize, + config.MessageQueueSize, + "maximum number of messages in the inbound message queue (0 = use default)") flags.Duration(peerUpdateInterval, config.PeerUpdateInterval, "how often to refresh the peer connections for the node") flags.Duration(BuildFlagName(unicastKey, MessageTimeoutKey), config.Unicast.MessageTimeout, "how long a unicast transmission can take to complete") flags.Duration(BuildFlagName(unicastKey, unicastManagerKey, createStreamBackoffDelayKey), config.Unicast.UnicastManager.CreateStreamBackoffDelay, diff --git a/network/network.go b/network/network.go index 32b1a172d3c..a6d897b40f2 100644 --- a/network/network.go +++ b/network/network.go @@ -62,14 +62,14 @@ type EngineRegistry interface { type ConduitAdapter interface { MisbehaviorReportConsumer // UnicastOnChannel sends the message in a reliable way to the given recipient. - UnicastOnChannel(channels.Channel, interface{}, flow.Identifier) error + UnicastOnChannel(channels.Channel, any, flow.Identifier) error // PublishOnChannel sends the message in an unreliable way to all the given recipients. - PublishOnChannel(channels.Channel, interface{}, ...flow.Identifier) error + PublishOnChannel(channels.Channel, any, ...flow.Identifier) error // MulticastOnChannel unreliably sends the specified event over the channel to randomly selected number of recipients // selected from the specified targetIDs. - MulticastOnChannel(channels.Channel, interface{}, uint, ...flow.Identifier) error + MulticastOnChannel(channels.Channel, any, uint, ...flow.Identifier) error // UnRegisterChannel unregisters the engine for the specified channel. The engine will no longer be able to send or // receive messages from that channel. @@ -98,8 +98,8 @@ type Underlay interface { // Connection represents an interface to read from & write to a connection. type Connection interface { - Send(msg interface{}) error - Receive() (interface{}, error) + Send(msg any) error + Receive() (any, error) } // MisbehaviorReportConsumer set of funcs used to handle MisbehaviorReport disseminated from misbehavior reporters. diff --git a/network/p2p/conduit/conduit.go b/network/p2p/conduit/conduit.go index 76758e6d7be..0ca75ba8a56 100644 --- a/network/p2p/conduit/conduit.go +++ b/network/p2p/conduit/conduit.go @@ -76,7 +76,7 @@ var _ network.Conduit = (*Conduit)(nil) // to subscribers of the given event on the network layer. It uses a // publish-subscribe layer and can thus not guarantee that the specified // recipients received the event. -func (c *Conduit) Publish(event interface{}, targetIDs ...flow.Identifier) error { +func (c *Conduit) Publish(event any, targetIDs ...flow.Identifier) error { if c.ctx.Err() != nil { return fmt.Errorf("conduit for channel %s closed", c.channel) } @@ -86,7 +86,7 @@ func (c *Conduit) Publish(event interface{}, targetIDs ...flow.Identifier) error // Unicast sends an event in a reliable way to the given recipient. // It uses 1-1 direct messaging over the underlying network to deliver the event. // It returns an error if the unicast fails. -func (c *Conduit) Unicast(event interface{}, targetID flow.Identifier) error { +func (c *Conduit) Unicast(event any, targetID flow.Identifier) error { if c.ctx.Err() != nil { return fmt.Errorf("conduit for channel %s closed", c.channel) } @@ -95,7 +95,7 @@ func (c *Conduit) Unicast(event interface{}, targetID flow.Identifier) error { // Multicast unreliably sends the specified event to the specified number of recipients selected from the specified subset. // The recipients are selected randomly from targetIDs -func (c *Conduit) Multicast(event interface{}, num uint, targetIDs ...flow.Identifier) error { +func (c *Conduit) Multicast(event any, num uint, targetIDs ...flow.Identifier) error { if c.ctx.Err() != nil { return fmt.Errorf("conduit for channel %s closed", c.channel) } diff --git a/network/p2p/inspector/validation/control_message_validation_inspector.go b/network/p2p/inspector/validation/control_message_validation_inspector.go index e88495b28fb..0f094511f27 100644 --- a/network/p2p/inspector/validation/control_message_validation_inspector.go +++ b/network/p2p/inspector/validation/control_message_validation_inspector.go @@ -2,6 +2,7 @@ package validation import ( "fmt" + "slices" "time" "github.com/go-playground/validator/v10" @@ -648,12 +649,7 @@ func (c *ControlMsgValidationInspector) inspectRpcPublishMessages(from peer.ID, subscribedTopics := c.topicOracle().GetTopics() hasSubscription := func(topic string) bool { - for _, subscribedTopic := range subscribedTopics { - if topic == subscribedTopic { - return true - } - } - return false + return slices.Contains(subscribedTopics, topic) } var errs *multierror.Error invalidTopicIdsCount := 0 diff --git a/network/p2p/keyutils/keyTranslator_test.go b/network/p2p/keyutils/keyTranslator_test.go index 4f630b1ffb4..c12987a28d4 100644 --- a/network/p2p/keyutils/keyTranslator_test.go +++ b/network/p2p/keyutils/keyTranslator_test.go @@ -36,7 +36,7 @@ func (k *KeyTranslatorTestSuite) TestPrivateKeyConversion() { loops := 50 for j, s := range sa { - for i := 0; i < loops; i++ { + for range loops { // generate seed seed := k.createSeed() // generate a Flow private key @@ -80,7 +80,7 @@ func (k *KeyTranslatorTestSuite) TestPublicKeyConversion() { loops := 50 for _, s := range sa { - for i := 0; i < loops; i++ { + for range loops { // generate seed seed := k.createSeed() fpk, err := fcrypto.GeneratePrivateKey(s, seed) @@ -113,7 +113,7 @@ func (k *KeyTranslatorTestSuite) TestPublicKeyRoundTrip() { sa := []fcrypto.SigningAlgorithm{fcrypto.ECDSAP256, fcrypto.ECDSASecp256k1} loops := 50 for _, s := range sa { - for i := 0; i < loops; i++ { + for range loops { // generate seed seed := k.createSeed() @@ -154,7 +154,7 @@ func (k *KeyTranslatorTestSuite) TestPeerIDGenerationIsConsistent() { // check that the LibP2P Id generation is deterministic var prev peer.ID - for i := 0; i < 100; i++ { + for i := range 100 { // generate a Libp2p Peer ID from the converted public key fpeerID, err := peer.IDFromPublicKey(lconverted) diff --git a/network/p2p/libp2pNode.go b/network/p2p/libp2pNode.go index e38342aacb7..0b18eb4d091 100644 --- a/network/p2p/libp2pNode.go +++ b/network/p2p/libp2pNode.go @@ -15,7 +15,6 @@ import ( "github.com/onflow/flow-go/module/component" "github.com/onflow/flow-go/module/irrecoverable" "github.com/onflow/flow-go/network" - flownet "github.com/onflow/flow-go/network" "github.com/onflow/flow-go/network/channels" "github.com/onflow/flow-go/network/p2p/unicast/protocols" ) @@ -117,7 +116,7 @@ type PubSub interface { // Unsubscribe cancels the subscriber and closes the topic. Unsubscribe(topic channels.Topic) error // Publish publishes the given payload on the topic. - Publish(ctx context.Context, messageScope flownet.OutgoingMessageScope) error + Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error // SetPubSub sets the node's pubsub implementation. // SetPubSub may be called at most once. SetPubSub(ps PubSubAdapter) diff --git a/network/p2p/mock/basic_rate_limiter.go b/network/p2p/mock/basic_rate_limiter.go index 19330e4c1ff..eda723875e3 100644 --- a/network/p2p/mock/basic_rate_limiter.go +++ b/network/p2p/mock/basic_rate_limiter.go @@ -1,92 +1,227 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewBasicRateLimiter creates a new instance of BasicRateLimiter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBasicRateLimiter(t interface { + mock.TestingT + Cleanup(func()) +}) *BasicRateLimiter { + mock := &BasicRateLimiter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BasicRateLimiter is an autogenerated mock type for the BasicRateLimiter type type BasicRateLimiter struct { mock.Mock } -// Allow provides a mock function with given fields: peerID, msgSize -func (_m *BasicRateLimiter) Allow(peerID peer.ID, msgSize int) bool { - ret := _m.Called(peerID, msgSize) +type BasicRateLimiter_Expecter struct { + mock *mock.Mock +} + +func (_m *BasicRateLimiter) EXPECT() *BasicRateLimiter_Expecter { + return &BasicRateLimiter_Expecter{mock: &_m.Mock} +} + +// Allow provides a mock function for the type BasicRateLimiter +func (_mock *BasicRateLimiter) Allow(peerID peer.ID, msgSize int) bool { + ret := _mock.Called(peerID, msgSize) if len(ret) == 0 { panic("no return value specified for Allow") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID, int) bool); ok { - r0 = rf(peerID, msgSize) + if returnFunc, ok := ret.Get(0).(func(peer.ID, int) bool); ok { + r0 = returnFunc(peerID, msgSize) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Done provides a mock function with no fields -func (_m *BasicRateLimiter) Done() <-chan struct{} { - ret := _m.Called() +// BasicRateLimiter_Allow_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Allow' +type BasicRateLimiter_Allow_Call struct { + *mock.Call +} + +// Allow is a helper method to define mock.On call +// - peerID peer.ID +// - msgSize int +func (_e *BasicRateLimiter_Expecter) Allow(peerID interface{}, msgSize interface{}) *BasicRateLimiter_Allow_Call { + return &BasicRateLimiter_Allow_Call{Call: _e.mock.On("Allow", peerID, msgSize)} +} + +func (_c *BasicRateLimiter_Allow_Call) Run(run func(peerID peer.ID, msgSize int)) *BasicRateLimiter_Allow_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BasicRateLimiter_Allow_Call) Return(b bool) *BasicRateLimiter_Allow_Call { + _c.Call.Return(b) + return _c +} + +func (_c *BasicRateLimiter_Allow_Call) RunAndReturn(run func(peerID peer.ID, msgSize int) bool) *BasicRateLimiter_Allow_Call { + _c.Call.Return(run) + return _c +} + +// Done provides a mock function for the type BasicRateLimiter +func (_mock *BasicRateLimiter) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *BasicRateLimiter) Ready() <-chan struct{} { - ret := _m.Called() +// BasicRateLimiter_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type BasicRateLimiter_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *BasicRateLimiter_Expecter) Done() *BasicRateLimiter_Done_Call { + return &BasicRateLimiter_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *BasicRateLimiter_Done_Call) Run(run func()) *BasicRateLimiter_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BasicRateLimiter_Done_Call) Return(valCh <-chan struct{}) *BasicRateLimiter_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *BasicRateLimiter_Done_Call) RunAndReturn(run func() <-chan struct{}) *BasicRateLimiter_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type BasicRateLimiter +func (_mock *BasicRateLimiter) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *BasicRateLimiter) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// BasicRateLimiter_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type BasicRateLimiter_Ready_Call struct { + *mock.Call } -// NewBasicRateLimiter creates a new instance of BasicRateLimiter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBasicRateLimiter(t interface { - mock.TestingT - Cleanup(func()) -}) *BasicRateLimiter { - mock := &BasicRateLimiter{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *BasicRateLimiter_Expecter) Ready() *BasicRateLimiter_Ready_Call { + return &BasicRateLimiter_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *BasicRateLimiter_Ready_Call) Run(run func()) *BasicRateLimiter_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *BasicRateLimiter_Ready_Call) Return(valCh <-chan struct{}) *BasicRateLimiter_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *BasicRateLimiter_Ready_Call) RunAndReturn(run func() <-chan struct{}) *BasicRateLimiter_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type BasicRateLimiter +func (_mock *BasicRateLimiter) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// BasicRateLimiter_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type BasicRateLimiter_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *BasicRateLimiter_Expecter) Start(signalerContext interface{}) *BasicRateLimiter_Start_Call { + return &BasicRateLimiter_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *BasicRateLimiter_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *BasicRateLimiter_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BasicRateLimiter_Start_Call) Return() *BasicRateLimiter_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *BasicRateLimiter_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *BasicRateLimiter_Start_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/collection_cluster_changes_consumer.go b/network/p2p/mock/collection_cluster_changes_consumer.go index 0476289512f..e97d45bfac1 100644 --- a/network/p2p/mock/collection_cluster_changes_consumer.go +++ b/network/p2p/mock/collection_cluster_changes_consumer.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) -// CollectionClusterChangesConsumer is an autogenerated mock type for the CollectionClusterChangesConsumer type -type CollectionClusterChangesConsumer struct { - mock.Mock -} - -// ActiveClustersChanged provides a mock function with given fields: _a0 -func (_m *CollectionClusterChangesConsumer) ActiveClustersChanged(_a0 flow.ChainIDList) { - _m.Called(_a0) -} - // NewCollectionClusterChangesConsumer creates a new instance of CollectionClusterChangesConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewCollectionClusterChangesConsumer(t interface { @@ -30,3 +22,56 @@ func NewCollectionClusterChangesConsumer(t interface { return mock } + +// CollectionClusterChangesConsumer is an autogenerated mock type for the CollectionClusterChangesConsumer type +type CollectionClusterChangesConsumer struct { + mock.Mock +} + +type CollectionClusterChangesConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *CollectionClusterChangesConsumer) EXPECT() *CollectionClusterChangesConsumer_Expecter { + return &CollectionClusterChangesConsumer_Expecter{mock: &_m.Mock} +} + +// ActiveClustersChanged provides a mock function for the type CollectionClusterChangesConsumer +func (_mock *CollectionClusterChangesConsumer) ActiveClustersChanged(chainIDList flow.ChainIDList) { + _mock.Called(chainIDList) + return +} + +// CollectionClusterChangesConsumer_ActiveClustersChanged_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ActiveClustersChanged' +type CollectionClusterChangesConsumer_ActiveClustersChanged_Call struct { + *mock.Call +} + +// ActiveClustersChanged is a helper method to define mock.On call +// - chainIDList flow.ChainIDList +func (_e *CollectionClusterChangesConsumer_Expecter) ActiveClustersChanged(chainIDList interface{}) *CollectionClusterChangesConsumer_ActiveClustersChanged_Call { + return &CollectionClusterChangesConsumer_ActiveClustersChanged_Call{Call: _e.mock.On("ActiveClustersChanged", chainIDList)} +} + +func (_c *CollectionClusterChangesConsumer_ActiveClustersChanged_Call) Run(run func(chainIDList flow.ChainIDList)) *CollectionClusterChangesConsumer_ActiveClustersChanged_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ChainIDList + if args[0] != nil { + arg0 = args[0].(flow.ChainIDList) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionClusterChangesConsumer_ActiveClustersChanged_Call) Return() *CollectionClusterChangesConsumer_ActiveClustersChanged_Call { + _c.Call.Return() + return _c +} + +func (_c *CollectionClusterChangesConsumer_ActiveClustersChanged_Call) RunAndReturn(run func(chainIDList flow.ChainIDList)) *CollectionClusterChangesConsumer_ActiveClustersChanged_Call { + _c.Run(run) + return _c +} diff --git a/network/p2p/mock/connection_gater.go b/network/p2p/mock/connection_gater.go index a033fe68fe7..f0fb3835c68 100644 --- a/network/p2p/mock/connection_gater.go +++ b/network/p2p/mock/connection_gater.go @@ -1,100 +1,270 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - control "github.com/libp2p/go-libp2p/core/control" + "github.com/libp2p/go-libp2p/core/control" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/multiformats/go-multiaddr" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) - multiaddr "github.com/multiformats/go-multiaddr" - - network "github.com/libp2p/go-libp2p/core/network" +// NewConnectionGater creates a new instance of ConnectionGater. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConnectionGater(t interface { + mock.TestingT + Cleanup(func()) +}) *ConnectionGater { + mock := &ConnectionGater{} + mock.Mock.Test(t) - p2p "github.com/onflow/flow-go/network/p2p" + t.Cleanup(func() { mock.AssertExpectations(t) }) - peer "github.com/libp2p/go-libp2p/core/peer" -) + return mock +} // ConnectionGater is an autogenerated mock type for the ConnectionGater type type ConnectionGater struct { mock.Mock } -// InterceptAccept provides a mock function with given fields: _a0 -func (_m *ConnectionGater) InterceptAccept(_a0 network.ConnMultiaddrs) bool { - ret := _m.Called(_a0) +type ConnectionGater_Expecter struct { + mock *mock.Mock +} + +func (_m *ConnectionGater) EXPECT() *ConnectionGater_Expecter { + return &ConnectionGater_Expecter{mock: &_m.Mock} +} + +// InterceptAccept provides a mock function for the type ConnectionGater +func (_mock *ConnectionGater) InterceptAccept(connMultiaddrs network.ConnMultiaddrs) bool { + ret := _mock.Called(connMultiaddrs) if len(ret) == 0 { panic("no return value specified for InterceptAccept") } var r0 bool - if rf, ok := ret.Get(0).(func(network.ConnMultiaddrs) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(network.ConnMultiaddrs) bool); ok { + r0 = returnFunc(connMultiaddrs) } else { r0 = ret.Get(0).(bool) } - return r0 } -// InterceptAddrDial provides a mock function with given fields: _a0, _a1 -func (_m *ConnectionGater) InterceptAddrDial(_a0 peer.ID, _a1 multiaddr.Multiaddr) bool { - ret := _m.Called(_a0, _a1) +// ConnectionGater_InterceptAccept_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InterceptAccept' +type ConnectionGater_InterceptAccept_Call struct { + *mock.Call +} + +// InterceptAccept is a helper method to define mock.On call +// - connMultiaddrs network.ConnMultiaddrs +func (_e *ConnectionGater_Expecter) InterceptAccept(connMultiaddrs interface{}) *ConnectionGater_InterceptAccept_Call { + return &ConnectionGater_InterceptAccept_Call{Call: _e.mock.On("InterceptAccept", connMultiaddrs)} +} + +func (_c *ConnectionGater_InterceptAccept_Call) Run(run func(connMultiaddrs network.ConnMultiaddrs)) *ConnectionGater_InterceptAccept_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.ConnMultiaddrs + if args[0] != nil { + arg0 = args[0].(network.ConnMultiaddrs) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectionGater_InterceptAccept_Call) Return(allow bool) *ConnectionGater_InterceptAccept_Call { + _c.Call.Return(allow) + return _c +} + +func (_c *ConnectionGater_InterceptAccept_Call) RunAndReturn(run func(connMultiaddrs network.ConnMultiaddrs) bool) *ConnectionGater_InterceptAccept_Call { + _c.Call.Return(run) + return _c +} + +// InterceptAddrDial provides a mock function for the type ConnectionGater +func (_mock *ConnectionGater) InterceptAddrDial(iD peer.ID, multiaddr1 multiaddr.Multiaddr) bool { + ret := _mock.Called(iD, multiaddr1) if len(ret) == 0 { panic("no return value specified for InterceptAddrDial") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID, multiaddr.Multiaddr) bool); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(peer.ID, multiaddr.Multiaddr) bool); ok { + r0 = returnFunc(iD, multiaddr1) } else { r0 = ret.Get(0).(bool) } - return r0 } -// InterceptPeerDial provides a mock function with given fields: p -func (_m *ConnectionGater) InterceptPeerDial(p peer.ID) bool { - ret := _m.Called(p) +// ConnectionGater_InterceptAddrDial_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InterceptAddrDial' +type ConnectionGater_InterceptAddrDial_Call struct { + *mock.Call +} + +// InterceptAddrDial is a helper method to define mock.On call +// - iD peer.ID +// - multiaddr1 multiaddr.Multiaddr +func (_e *ConnectionGater_Expecter) InterceptAddrDial(iD interface{}, multiaddr1 interface{}) *ConnectionGater_InterceptAddrDial_Call { + return &ConnectionGater_InterceptAddrDial_Call{Call: _e.mock.On("InterceptAddrDial", iD, multiaddr1)} +} + +func (_c *ConnectionGater_InterceptAddrDial_Call) Run(run func(iD peer.ID, multiaddr1 multiaddr.Multiaddr)) *ConnectionGater_InterceptAddrDial_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 multiaddr.Multiaddr + if args[1] != nil { + arg1 = args[1].(multiaddr.Multiaddr) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ConnectionGater_InterceptAddrDial_Call) Return(allow bool) *ConnectionGater_InterceptAddrDial_Call { + _c.Call.Return(allow) + return _c +} + +func (_c *ConnectionGater_InterceptAddrDial_Call) RunAndReturn(run func(iD peer.ID, multiaddr1 multiaddr.Multiaddr) bool) *ConnectionGater_InterceptAddrDial_Call { + _c.Call.Return(run) + return _c +} + +// InterceptPeerDial provides a mock function for the type ConnectionGater +func (_mock *ConnectionGater) InterceptPeerDial(p peer.ID) bool { + ret := _mock.Called(p) if len(ret) == 0 { panic("no return value specified for InterceptPeerDial") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID) bool); ok { - r0 = rf(p) + if returnFunc, ok := ret.Get(0).(func(peer.ID) bool); ok { + r0 = returnFunc(p) } else { r0 = ret.Get(0).(bool) } - return r0 } -// InterceptSecured provides a mock function with given fields: _a0, _a1, _a2 -func (_m *ConnectionGater) InterceptSecured(_a0 network.Direction, _a1 peer.ID, _a2 network.ConnMultiaddrs) bool { - ret := _m.Called(_a0, _a1, _a2) +// ConnectionGater_InterceptPeerDial_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InterceptPeerDial' +type ConnectionGater_InterceptPeerDial_Call struct { + *mock.Call +} + +// InterceptPeerDial is a helper method to define mock.On call +// - p peer.ID +func (_e *ConnectionGater_Expecter) InterceptPeerDial(p interface{}) *ConnectionGater_InterceptPeerDial_Call { + return &ConnectionGater_InterceptPeerDial_Call{Call: _e.mock.On("InterceptPeerDial", p)} +} + +func (_c *ConnectionGater_InterceptPeerDial_Call) Run(run func(p peer.ID)) *ConnectionGater_InterceptPeerDial_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectionGater_InterceptPeerDial_Call) Return(allow bool) *ConnectionGater_InterceptPeerDial_Call { + _c.Call.Return(allow) + return _c +} + +func (_c *ConnectionGater_InterceptPeerDial_Call) RunAndReturn(run func(p peer.ID) bool) *ConnectionGater_InterceptPeerDial_Call { + _c.Call.Return(run) + return _c +} + +// InterceptSecured provides a mock function for the type ConnectionGater +func (_mock *ConnectionGater) InterceptSecured(direction network.Direction, iD peer.ID, connMultiaddrs network.ConnMultiaddrs) bool { + ret := _mock.Called(direction, iD, connMultiaddrs) if len(ret) == 0 { panic("no return value specified for InterceptSecured") } var r0 bool - if rf, ok := ret.Get(0).(func(network.Direction, peer.ID, network.ConnMultiaddrs) bool); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(network.Direction, peer.ID, network.ConnMultiaddrs) bool); ok { + r0 = returnFunc(direction, iD, connMultiaddrs) } else { r0 = ret.Get(0).(bool) } - return r0 } -// InterceptUpgraded provides a mock function with given fields: _a0 -func (_m *ConnectionGater) InterceptUpgraded(_a0 network.Conn) (bool, control.DisconnectReason) { - ret := _m.Called(_a0) +// ConnectionGater_InterceptSecured_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InterceptSecured' +type ConnectionGater_InterceptSecured_Call struct { + *mock.Call +} + +// InterceptSecured is a helper method to define mock.On call +// - direction network.Direction +// - iD peer.ID +// - connMultiaddrs network.ConnMultiaddrs +func (_e *ConnectionGater_Expecter) InterceptSecured(direction interface{}, iD interface{}, connMultiaddrs interface{}) *ConnectionGater_InterceptSecured_Call { + return &ConnectionGater_InterceptSecured_Call{Call: _e.mock.On("InterceptSecured", direction, iD, connMultiaddrs)} +} + +func (_c *ConnectionGater_InterceptSecured_Call) Run(run func(direction network.Direction, iD peer.ID, connMultiaddrs network.ConnMultiaddrs)) *ConnectionGater_InterceptSecured_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.Direction + if args[0] != nil { + arg0 = args[0].(network.Direction) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + var arg2 network.ConnMultiaddrs + if args[2] != nil { + arg2 = args[2].(network.ConnMultiaddrs) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ConnectionGater_InterceptSecured_Call) Return(allow bool) *ConnectionGater_InterceptSecured_Call { + _c.Call.Return(allow) + return _c +} + +func (_c *ConnectionGater_InterceptSecured_Call) RunAndReturn(run func(direction network.Direction, iD peer.ID, connMultiaddrs network.ConnMultiaddrs) bool) *ConnectionGater_InterceptSecured_Call { + _c.Call.Return(run) + return _c +} + +// InterceptUpgraded provides a mock function for the type ConnectionGater +func (_mock *ConnectionGater) InterceptUpgraded(conn network.Conn) (bool, control.DisconnectReason) { + ret := _mock.Called(conn) if len(ret) == 0 { panic("no return value specified for InterceptUpgraded") @@ -102,39 +272,92 @@ func (_m *ConnectionGater) InterceptUpgraded(_a0 network.Conn) (bool, control.Di var r0 bool var r1 control.DisconnectReason - if rf, ok := ret.Get(0).(func(network.Conn) (bool, control.DisconnectReason)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(network.Conn) (bool, control.DisconnectReason)); ok { + return returnFunc(conn) } - if rf, ok := ret.Get(0).(func(network.Conn) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(network.Conn) bool); ok { + r0 = returnFunc(conn) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(network.Conn) control.DisconnectReason); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(network.Conn) control.DisconnectReason); ok { + r1 = returnFunc(conn) } else { r1 = ret.Get(1).(control.DisconnectReason) } - return r0, r1 } -// SetDisallowListOracle provides a mock function with given fields: oracle -func (_m *ConnectionGater) SetDisallowListOracle(oracle p2p.DisallowListOracle) { - _m.Called(oracle) +// ConnectionGater_InterceptUpgraded_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InterceptUpgraded' +type ConnectionGater_InterceptUpgraded_Call struct { + *mock.Call } -// NewConnectionGater creates a new instance of ConnectionGater. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConnectionGater(t interface { - mock.TestingT - Cleanup(func()) -}) *ConnectionGater { - mock := &ConnectionGater{} - mock.Mock.Test(t) +// InterceptUpgraded is a helper method to define mock.On call +// - conn network.Conn +func (_e *ConnectionGater_Expecter) InterceptUpgraded(conn interface{}) *ConnectionGater_InterceptUpgraded_Call { + return &ConnectionGater_InterceptUpgraded_Call{Call: _e.mock.On("InterceptUpgraded", conn)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ConnectionGater_InterceptUpgraded_Call) Run(run func(conn network.Conn)) *ConnectionGater_InterceptUpgraded_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.Conn + if args[0] != nil { + arg0 = args[0].(network.Conn) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *ConnectionGater_InterceptUpgraded_Call) Return(allow bool, reason control.DisconnectReason) *ConnectionGater_InterceptUpgraded_Call { + _c.Call.Return(allow, reason) + return _c +} + +func (_c *ConnectionGater_InterceptUpgraded_Call) RunAndReturn(run func(conn network.Conn) (bool, control.DisconnectReason)) *ConnectionGater_InterceptUpgraded_Call { + _c.Call.Return(run) + return _c +} + +// SetDisallowListOracle provides a mock function for the type ConnectionGater +func (_mock *ConnectionGater) SetDisallowListOracle(oracle p2p.DisallowListOracle) { + _mock.Called(oracle) + return +} + +// ConnectionGater_SetDisallowListOracle_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetDisallowListOracle' +type ConnectionGater_SetDisallowListOracle_Call struct { + *mock.Call +} + +// SetDisallowListOracle is a helper method to define mock.On call +// - oracle p2p.DisallowListOracle +func (_e *ConnectionGater_Expecter) SetDisallowListOracle(oracle interface{}) *ConnectionGater_SetDisallowListOracle_Call { + return &ConnectionGater_SetDisallowListOracle_Call{Call: _e.mock.On("SetDisallowListOracle", oracle)} +} + +func (_c *ConnectionGater_SetDisallowListOracle_Call) Run(run func(oracle p2p.DisallowListOracle)) *ConnectionGater_SetDisallowListOracle_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.DisallowListOracle + if args[0] != nil { + arg0 = args[0].(p2p.DisallowListOracle) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectionGater_SetDisallowListOracle_Call) Return() *ConnectionGater_SetDisallowListOracle_Call { + _c.Call.Return() + return _c +} + +func (_c *ConnectionGater_SetDisallowListOracle_Call) RunAndReturn(run func(oracle p2p.DisallowListOracle)) *ConnectionGater_SetDisallowListOracle_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/connector.go b/network/p2p/mock/connector.go index e5fcd5e2047..423382627bb 100644 --- a/network/p2p/mock/connector.go +++ b/network/p2p/mock/connector.go @@ -1,25 +1,16 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) -// Connector is an autogenerated mock type for the Connector type -type Connector struct { - mock.Mock -} - -// Connect provides a mock function with given fields: ctx, peerChan -func (_m *Connector) Connect(ctx context.Context, peerChan <-chan peer.AddrInfo) { - _m.Called(ctx, peerChan) -} - // NewConnector creates a new instance of Connector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewConnector(t interface { @@ -33,3 +24,62 @@ func NewConnector(t interface { return mock } + +// Connector is an autogenerated mock type for the Connector type +type Connector struct { + mock.Mock +} + +type Connector_Expecter struct { + mock *mock.Mock +} + +func (_m *Connector) EXPECT() *Connector_Expecter { + return &Connector_Expecter{mock: &_m.Mock} +} + +// Connect provides a mock function for the type Connector +func (_mock *Connector) Connect(ctx context.Context, peerChan <-chan peer.AddrInfo) { + _mock.Called(ctx, peerChan) + return +} + +// Connector_Connect_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Connect' +type Connector_Connect_Call struct { + *mock.Call +} + +// Connect is a helper method to define mock.On call +// - ctx context.Context +// - peerChan <-chan peer.AddrInfo +func (_e *Connector_Expecter) Connect(ctx interface{}, peerChan interface{}) *Connector_Connect_Call { + return &Connector_Connect_Call{Call: _e.mock.On("Connect", ctx, peerChan)} +} + +func (_c *Connector_Connect_Call) Run(run func(ctx context.Context, peerChan <-chan peer.AddrInfo)) *Connector_Connect_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 <-chan peer.AddrInfo + if args[1] != nil { + arg1 = args[1].(<-chan peer.AddrInfo) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Connector_Connect_Call) Return() *Connector_Connect_Call { + _c.Call.Return() + return _c +} + +func (_c *Connector_Connect_Call) RunAndReturn(run func(ctx context.Context, peerChan <-chan peer.AddrInfo)) *Connector_Connect_Call { + _c.Run(run) + return _c +} diff --git a/network/p2p/mock/connector_host.go b/network/p2p/mock/connector_host.go index 90615a861e7..35495f3e5a9 100644 --- a/network/p2p/mock/connector_host.go +++ b/network/p2p/mock/connector_host.go @@ -1,139 +1,332 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewConnectorHost creates a new instance of ConnectorHost. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConnectorHost(t interface { + mock.TestingT + Cleanup(func()) +}) *ConnectorHost { + mock := &ConnectorHost{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ConnectorHost is an autogenerated mock type for the ConnectorHost type type ConnectorHost struct { mock.Mock } -// ClosePeer provides a mock function with given fields: peerId -func (_m *ConnectorHost) ClosePeer(peerId peer.ID) error { - ret := _m.Called(peerId) +type ConnectorHost_Expecter struct { + mock *mock.Mock +} + +func (_m *ConnectorHost) EXPECT() *ConnectorHost_Expecter { + return &ConnectorHost_Expecter{mock: &_m.Mock} +} + +// ClosePeer provides a mock function for the type ConnectorHost +func (_mock *ConnectorHost) ClosePeer(peerId peer.ID) error { + ret := _mock.Called(peerId) if len(ret) == 0 { panic("no return value specified for ClosePeer") } var r0 error - if rf, ok := ret.Get(0).(func(peer.ID) error); ok { - r0 = rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) error); ok { + r0 = returnFunc(peerId) } else { r0 = ret.Error(0) } - return r0 } -// Connections provides a mock function with no fields -func (_m *ConnectorHost) Connections() []network.Conn { - ret := _m.Called() +// ConnectorHost_ClosePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClosePeer' +type ConnectorHost_ClosePeer_Call struct { + *mock.Call +} + +// ClosePeer is a helper method to define mock.On call +// - peerId peer.ID +func (_e *ConnectorHost_Expecter) ClosePeer(peerId interface{}) *ConnectorHost_ClosePeer_Call { + return &ConnectorHost_ClosePeer_Call{Call: _e.mock.On("ClosePeer", peerId)} +} + +func (_c *ConnectorHost_ClosePeer_Call) Run(run func(peerId peer.ID)) *ConnectorHost_ClosePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectorHost_ClosePeer_Call) Return(err error) *ConnectorHost_ClosePeer_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConnectorHost_ClosePeer_Call) RunAndReturn(run func(peerId peer.ID) error) *ConnectorHost_ClosePeer_Call { + _c.Call.Return(run) + return _c +} + +// Connections provides a mock function for the type ConnectorHost +func (_mock *ConnectorHost) Connections() []network.Conn { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Connections") } var r0 []network.Conn - if rf, ok := ret.Get(0).(func() []network.Conn); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []network.Conn); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]network.Conn) } } - return r0 } -// ID provides a mock function with no fields -func (_m *ConnectorHost) ID() peer.ID { - ret := _m.Called() +// ConnectorHost_Connections_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Connections' +type ConnectorHost_Connections_Call struct { + *mock.Call +} + +// Connections is a helper method to define mock.On call +func (_e *ConnectorHost_Expecter) Connections() *ConnectorHost_Connections_Call { + return &ConnectorHost_Connections_Call{Call: _e.mock.On("Connections")} +} + +func (_c *ConnectorHost_Connections_Call) Run(run func()) *ConnectorHost_Connections_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ConnectorHost_Connections_Call) Return(conns []network.Conn) *ConnectorHost_Connections_Call { + _c.Call.Return(conns) + return _c +} + +func (_c *ConnectorHost_Connections_Call) RunAndReturn(run func() []network.Conn) *ConnectorHost_Connections_Call { + _c.Call.Return(run) + return _c +} + +// ID provides a mock function for the type ConnectorHost +func (_mock *ConnectorHost) ID() peer.ID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 peer.ID - if rf, ok := ret.Get(0).(func() peer.ID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() peer.ID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(peer.ID) } - return r0 } -// IsConnectedTo provides a mock function with given fields: peerId -func (_m *ConnectorHost) IsConnectedTo(peerId peer.ID) bool { - ret := _m.Called(peerId) +// ConnectorHost_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type ConnectorHost_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *ConnectorHost_Expecter) ID() *ConnectorHost_ID_Call { + return &ConnectorHost_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *ConnectorHost_ID_Call) Run(run func()) *ConnectorHost_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ConnectorHost_ID_Call) Return(iD peer.ID) *ConnectorHost_ID_Call { + _c.Call.Return(iD) + return _c +} + +func (_c *ConnectorHost_ID_Call) RunAndReturn(run func() peer.ID) *ConnectorHost_ID_Call { + _c.Call.Return(run) + return _c +} + +// IsConnectedTo provides a mock function for the type ConnectorHost +func (_mock *ConnectorHost) IsConnectedTo(peerId peer.ID) bool { + ret := _mock.Called(peerId) if len(ret) == 0 { panic("no return value specified for IsConnectedTo") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID) bool); ok { - r0 = rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) bool); ok { + r0 = returnFunc(peerId) } else { r0 = ret.Get(0).(bool) } - return r0 } -// IsProtected provides a mock function with given fields: peerId -func (_m *ConnectorHost) IsProtected(peerId peer.ID) bool { - ret := _m.Called(peerId) +// ConnectorHost_IsConnectedTo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsConnectedTo' +type ConnectorHost_IsConnectedTo_Call struct { + *mock.Call +} + +// IsConnectedTo is a helper method to define mock.On call +// - peerId peer.ID +func (_e *ConnectorHost_Expecter) IsConnectedTo(peerId interface{}) *ConnectorHost_IsConnectedTo_Call { + return &ConnectorHost_IsConnectedTo_Call{Call: _e.mock.On("IsConnectedTo", peerId)} +} + +func (_c *ConnectorHost_IsConnectedTo_Call) Run(run func(peerId peer.ID)) *ConnectorHost_IsConnectedTo_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectorHost_IsConnectedTo_Call) Return(b bool) *ConnectorHost_IsConnectedTo_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ConnectorHost_IsConnectedTo_Call) RunAndReturn(run func(peerId peer.ID) bool) *ConnectorHost_IsConnectedTo_Call { + _c.Call.Return(run) + return _c +} + +// IsProtected provides a mock function for the type ConnectorHost +func (_mock *ConnectorHost) IsProtected(peerId peer.ID) bool { + ret := _mock.Called(peerId) if len(ret) == 0 { panic("no return value specified for IsProtected") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID) bool); ok { - r0 = rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) bool); ok { + r0 = returnFunc(peerId) } else { r0 = ret.Get(0).(bool) } - return r0 } -// PeerInfo provides a mock function with given fields: peerId -func (_m *ConnectorHost) PeerInfo(peerId peer.ID) peer.AddrInfo { - ret := _m.Called(peerId) +// ConnectorHost_IsProtected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsProtected' +type ConnectorHost_IsProtected_Call struct { + *mock.Call +} + +// IsProtected is a helper method to define mock.On call +// - peerId peer.ID +func (_e *ConnectorHost_Expecter) IsProtected(peerId interface{}) *ConnectorHost_IsProtected_Call { + return &ConnectorHost_IsProtected_Call{Call: _e.mock.On("IsProtected", peerId)} +} + +func (_c *ConnectorHost_IsProtected_Call) Run(run func(peerId peer.ID)) *ConnectorHost_IsProtected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectorHost_IsProtected_Call) Return(b bool) *ConnectorHost_IsProtected_Call { + _c.Call.Return(b) + return _c +} + +func (_c *ConnectorHost_IsProtected_Call) RunAndReturn(run func(peerId peer.ID) bool) *ConnectorHost_IsProtected_Call { + _c.Call.Return(run) + return _c +} + +// PeerInfo provides a mock function for the type ConnectorHost +func (_mock *ConnectorHost) PeerInfo(peerId peer.ID) peer.AddrInfo { + ret := _mock.Called(peerId) if len(ret) == 0 { panic("no return value specified for PeerInfo") } var r0 peer.AddrInfo - if rf, ok := ret.Get(0).(func(peer.ID) peer.AddrInfo); ok { - r0 = rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) peer.AddrInfo); ok { + r0 = returnFunc(peerId) } else { r0 = ret.Get(0).(peer.AddrInfo) } - return r0 } -// NewConnectorHost creates a new instance of ConnectorHost. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConnectorHost(t interface { - mock.TestingT - Cleanup(func()) -}) *ConnectorHost { - mock := &ConnectorHost{} - mock.Mock.Test(t) +// ConnectorHost_PeerInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PeerInfo' +type ConnectorHost_PeerInfo_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// PeerInfo is a helper method to define mock.On call +// - peerId peer.ID +func (_e *ConnectorHost_Expecter) PeerInfo(peerId interface{}) *ConnectorHost_PeerInfo_Call { + return &ConnectorHost_PeerInfo_Call{Call: _e.mock.On("PeerInfo", peerId)} +} - return mock +func (_c *ConnectorHost_PeerInfo_Call) Run(run func(peerId peer.ID)) *ConnectorHost_PeerInfo_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConnectorHost_PeerInfo_Call) Return(addrInfo peer.AddrInfo) *ConnectorHost_PeerInfo_Call { + _c.Call.Return(addrInfo) + return _c +} + +func (_c *ConnectorHost_PeerInfo_Call) RunAndReturn(run func(peerId peer.ID) peer.AddrInfo) *ConnectorHost_PeerInfo_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/core_p2_p.go b/network/p2p/mock/core_p2_p.go index e2fe3c123b6..331901ce288 100644 --- a/network/p2p/mock/core_p2_p.go +++ b/network/p2p/mock/core_p2_p.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - host "github.com/libp2p/go-libp2p/core/host" - component "github.com/onflow/flow-go/module/component" - - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/libp2p/go-libp2p/core/host" + "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" ) +// NewCoreP2P creates a new instance of CoreP2P. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCoreP2P(t interface { + mock.TestingT + Cleanup(func()) +}) *CoreP2P { + mock := &CoreP2P{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CoreP2P is an autogenerated mock type for the CoreP2P type type CoreP2P struct { mock.Mock } -// GetIPPort provides a mock function with no fields -func (_m *CoreP2P) GetIPPort() (string, string, error) { - ret := _m.Called() +type CoreP2P_Expecter struct { + mock *mock.Mock +} + +func (_m *CoreP2P) EXPECT() *CoreP2P_Expecter { + return &CoreP2P_Expecter{mock: &_m.Mock} +} + +// GetIPPort provides a mock function for the type CoreP2P +func (_mock *CoreP2P) GetIPPort() (string, string, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetIPPort") @@ -27,88 +49,220 @@ func (_m *CoreP2P) GetIPPort() (string, string, error) { var r0 string var r1 string var r2 error - if rf, ok := ret.Get(0).(func() (string, string, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (string, string, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func() string); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() string); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(string) } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// Host provides a mock function with no fields -func (_m *CoreP2P) Host() host.Host { - ret := _m.Called() +// CoreP2P_GetIPPort_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIPPort' +type CoreP2P_GetIPPort_Call struct { + *mock.Call +} + +// GetIPPort is a helper method to define mock.On call +func (_e *CoreP2P_Expecter) GetIPPort() *CoreP2P_GetIPPort_Call { + return &CoreP2P_GetIPPort_Call{Call: _e.mock.On("GetIPPort")} +} + +func (_c *CoreP2P_GetIPPort_Call) Run(run func()) *CoreP2P_GetIPPort_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CoreP2P_GetIPPort_Call) Return(s string, s1 string, err error) *CoreP2P_GetIPPort_Call { + _c.Call.Return(s, s1, err) + return _c +} + +func (_c *CoreP2P_GetIPPort_Call) RunAndReturn(run func() (string, string, error)) *CoreP2P_GetIPPort_Call { + _c.Call.Return(run) + return _c +} + +// Host provides a mock function for the type CoreP2P +func (_mock *CoreP2P) Host() host.Host { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Host") } var r0 host.Host - if rf, ok := ret.Get(0).(func() host.Host); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() host.Host); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(host.Host) } } - return r0 } -// SetComponentManager provides a mock function with given fields: cm -func (_m *CoreP2P) SetComponentManager(cm *component.ComponentManager) { - _m.Called(cm) +// CoreP2P_Host_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Host' +type CoreP2P_Host_Call struct { + *mock.Call +} + +// Host is a helper method to define mock.On call +func (_e *CoreP2P_Expecter) Host() *CoreP2P_Host_Call { + return &CoreP2P_Host_Call{Call: _e.mock.On("Host")} +} + +func (_c *CoreP2P_Host_Call) Run(run func()) *CoreP2P_Host_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// Start provides a mock function with given fields: ctx -func (_m *CoreP2P) Start(ctx irrecoverable.SignalerContext) { - _m.Called(ctx) +func (_c *CoreP2P_Host_Call) Return(host1 host.Host) *CoreP2P_Host_Call { + _c.Call.Return(host1) + return _c } -// Stop provides a mock function with no fields -func (_m *CoreP2P) Stop() error { - ret := _m.Called() +func (_c *CoreP2P_Host_Call) RunAndReturn(run func() host.Host) *CoreP2P_Host_Call { + _c.Call.Return(run) + return _c +} + +// SetComponentManager provides a mock function for the type CoreP2P +func (_mock *CoreP2P) SetComponentManager(cm *component.ComponentManager) { + _mock.Called(cm) + return +} + +// CoreP2P_SetComponentManager_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetComponentManager' +type CoreP2P_SetComponentManager_Call struct { + *mock.Call +} + +// SetComponentManager is a helper method to define mock.On call +// - cm *component.ComponentManager +func (_e *CoreP2P_Expecter) SetComponentManager(cm interface{}) *CoreP2P_SetComponentManager_Call { + return &CoreP2P_SetComponentManager_Call{Call: _e.mock.On("SetComponentManager", cm)} +} + +func (_c *CoreP2P_SetComponentManager_Call) Run(run func(cm *component.ComponentManager)) *CoreP2P_SetComponentManager_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *component.ComponentManager + if args[0] != nil { + arg0 = args[0].(*component.ComponentManager) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CoreP2P_SetComponentManager_Call) Return() *CoreP2P_SetComponentManager_Call { + _c.Call.Return() + return _c +} + +func (_c *CoreP2P_SetComponentManager_Call) RunAndReturn(run func(cm *component.ComponentManager)) *CoreP2P_SetComponentManager_Call { + _c.Run(run) + return _c +} + +// Start provides a mock function for the type CoreP2P +func (_mock *CoreP2P) Start(ctx irrecoverable.SignalerContext) { + _mock.Called(ctx) + return +} + +// CoreP2P_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type CoreP2P_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - ctx irrecoverable.SignalerContext +func (_e *CoreP2P_Expecter) Start(ctx interface{}) *CoreP2P_Start_Call { + return &CoreP2P_Start_Call{Call: _e.mock.On("Start", ctx)} +} + +func (_c *CoreP2P_Start_Call) Run(run func(ctx irrecoverable.SignalerContext)) *CoreP2P_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CoreP2P_Start_Call) Return() *CoreP2P_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *CoreP2P_Start_Call) RunAndReturn(run func(ctx irrecoverable.SignalerContext)) *CoreP2P_Start_Call { + _c.Run(run) + return _c +} + +// Stop provides a mock function for the type CoreP2P +func (_mock *CoreP2P) Stop() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Stop") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// NewCoreP2P creates a new instance of CoreP2P. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCoreP2P(t interface { - mock.TestingT - Cleanup(func()) -}) *CoreP2P { - mock := &CoreP2P{} - mock.Mock.Test(t) +// CoreP2P_Stop_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Stop' +type CoreP2P_Stop_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Stop is a helper method to define mock.On call +func (_e *CoreP2P_Expecter) Stop() *CoreP2P_Stop_Call { + return &CoreP2P_Stop_Call{Call: _e.mock.On("Stop")} +} - return mock +func (_c *CoreP2P_Stop_Call) Run(run func()) *CoreP2P_Stop_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CoreP2P_Stop_Call) Return(err error) *CoreP2P_Stop_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CoreP2P_Stop_Call) RunAndReturn(run func() error) *CoreP2P_Stop_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/disallow_list_cache.go b/network/p2p/mock/disallow_list_cache.go index 23e75b88f9e..71e488bf0bb 100644 --- a/network/p2p/mock/disallow_list_cache.go +++ b/network/p2p/mock/disallow_list_cache.go @@ -1,42 +1,104 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/onflow/flow-go/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewDisallowListCache creates a new instance of DisallowListCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDisallowListCache(t interface { + mock.TestingT + Cleanup(func()) +}) *DisallowListCache { + mock := &DisallowListCache{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DisallowListCache is an autogenerated mock type for the DisallowListCache type type DisallowListCache struct { mock.Mock } -// AllowFor provides a mock function with given fields: peerID, cause -func (_m *DisallowListCache) AllowFor(peerID peer.ID, cause network.DisallowListedCause) []network.DisallowListedCause { - ret := _m.Called(peerID, cause) +type DisallowListCache_Expecter struct { + mock *mock.Mock +} + +func (_m *DisallowListCache) EXPECT() *DisallowListCache_Expecter { + return &DisallowListCache_Expecter{mock: &_m.Mock} +} + +// AllowFor provides a mock function for the type DisallowListCache +func (_mock *DisallowListCache) AllowFor(peerID peer.ID, cause network.DisallowListedCause) []network.DisallowListedCause { + ret := _mock.Called(peerID, cause) if len(ret) == 0 { panic("no return value specified for AllowFor") } var r0 []network.DisallowListedCause - if rf, ok := ret.Get(0).(func(peer.ID, network.DisallowListedCause) []network.DisallowListedCause); ok { - r0 = rf(peerID, cause) + if returnFunc, ok := ret.Get(0).(func(peer.ID, network.DisallowListedCause) []network.DisallowListedCause); ok { + r0 = returnFunc(peerID, cause) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]network.DisallowListedCause) } } - return r0 } -// DisallowFor provides a mock function with given fields: peerID, cause -func (_m *DisallowListCache) DisallowFor(peerID peer.ID, cause network.DisallowListedCause) ([]network.DisallowListedCause, error) { - ret := _m.Called(peerID, cause) +// DisallowListCache_AllowFor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AllowFor' +type DisallowListCache_AllowFor_Call struct { + *mock.Call +} + +// AllowFor is a helper method to define mock.On call +// - peerID peer.ID +// - cause network.DisallowListedCause +func (_e *DisallowListCache_Expecter) AllowFor(peerID interface{}, cause interface{}) *DisallowListCache_AllowFor_Call { + return &DisallowListCache_AllowFor_Call{Call: _e.mock.On("AllowFor", peerID, cause)} +} + +func (_c *DisallowListCache_AllowFor_Call) Run(run func(peerID peer.ID, cause network.DisallowListedCause)) *DisallowListCache_AllowFor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.DisallowListedCause + if args[1] != nil { + arg1 = args[1].(network.DisallowListedCause) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DisallowListCache_AllowFor_Call) Return(disallowListedCauses []network.DisallowListedCause) *DisallowListCache_AllowFor_Call { + _c.Call.Return(disallowListedCauses) + return _c +} + +func (_c *DisallowListCache_AllowFor_Call) RunAndReturn(run func(peerID peer.ID, cause network.DisallowListedCause) []network.DisallowListedCause) *DisallowListCache_AllowFor_Call { + _c.Call.Return(run) + return _c +} + +// DisallowFor provides a mock function for the type DisallowListCache +func (_mock *DisallowListCache) DisallowFor(peerID peer.ID, cause network.DisallowListedCause) ([]network.DisallowListedCause, error) { + ret := _mock.Called(peerID, cause) if len(ret) == 0 { panic("no return value specified for DisallowFor") @@ -44,29 +106,67 @@ func (_m *DisallowListCache) DisallowFor(peerID peer.ID, cause network.DisallowL var r0 []network.DisallowListedCause var r1 error - if rf, ok := ret.Get(0).(func(peer.ID, network.DisallowListedCause) ([]network.DisallowListedCause, error)); ok { - return rf(peerID, cause) + if returnFunc, ok := ret.Get(0).(func(peer.ID, network.DisallowListedCause) ([]network.DisallowListedCause, error)); ok { + return returnFunc(peerID, cause) } - if rf, ok := ret.Get(0).(func(peer.ID, network.DisallowListedCause) []network.DisallowListedCause); ok { - r0 = rf(peerID, cause) + if returnFunc, ok := ret.Get(0).(func(peer.ID, network.DisallowListedCause) []network.DisallowListedCause); ok { + r0 = returnFunc(peerID, cause) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]network.DisallowListedCause) } } - - if rf, ok := ret.Get(1).(func(peer.ID, network.DisallowListedCause) error); ok { - r1 = rf(peerID, cause) + if returnFunc, ok := ret.Get(1).(func(peer.ID, network.DisallowListedCause) error); ok { + r1 = returnFunc(peerID, cause) } else { r1 = ret.Error(1) } - return r0, r1 } -// IsDisallowListed provides a mock function with given fields: peerID -func (_m *DisallowListCache) IsDisallowListed(peerID peer.ID) ([]network.DisallowListedCause, bool) { - ret := _m.Called(peerID) +// DisallowListCache_DisallowFor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DisallowFor' +type DisallowListCache_DisallowFor_Call struct { + *mock.Call +} + +// DisallowFor is a helper method to define mock.On call +// - peerID peer.ID +// - cause network.DisallowListedCause +func (_e *DisallowListCache_Expecter) DisallowFor(peerID interface{}, cause interface{}) *DisallowListCache_DisallowFor_Call { + return &DisallowListCache_DisallowFor_Call{Call: _e.mock.On("DisallowFor", peerID, cause)} +} + +func (_c *DisallowListCache_DisallowFor_Call) Run(run func(peerID peer.ID, cause network.DisallowListedCause)) *DisallowListCache_DisallowFor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.DisallowListedCause + if args[1] != nil { + arg1 = args[1].(network.DisallowListedCause) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DisallowListCache_DisallowFor_Call) Return(disallowListedCauses []network.DisallowListedCause, err error) *DisallowListCache_DisallowFor_Call { + _c.Call.Return(disallowListedCauses, err) + return _c +} + +func (_c *DisallowListCache_DisallowFor_Call) RunAndReturn(run func(peerID peer.ID, cause network.DisallowListedCause) ([]network.DisallowListedCause, error)) *DisallowListCache_DisallowFor_Call { + _c.Call.Return(run) + return _c +} + +// IsDisallowListed provides a mock function for the type DisallowListCache +func (_mock *DisallowListCache) IsDisallowListed(peerID peer.ID) ([]network.DisallowListedCause, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for IsDisallowListed") @@ -74,36 +174,54 @@ func (_m *DisallowListCache) IsDisallowListed(peerID peer.ID) ([]network.Disallo var r0 []network.DisallowListedCause var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) ([]network.DisallowListedCause, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) ([]network.DisallowListedCause, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) []network.DisallowListedCause); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) []network.DisallowListedCause); ok { + r0 = returnFunc(peerID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]network.DisallowListedCause) } } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// NewDisallowListCache creates a new instance of DisallowListCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDisallowListCache(t interface { - mock.TestingT - Cleanup(func()) -}) *DisallowListCache { - mock := &DisallowListCache{} - mock.Mock.Test(t) +// DisallowListCache_IsDisallowListed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsDisallowListed' +type DisallowListCache_IsDisallowListed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// IsDisallowListed is a helper method to define mock.On call +// - peerID peer.ID +func (_e *DisallowListCache_Expecter) IsDisallowListed(peerID interface{}) *DisallowListCache_IsDisallowListed_Call { + return &DisallowListCache_IsDisallowListed_Call{Call: _e.mock.On("IsDisallowListed", peerID)} +} - return mock +func (_c *DisallowListCache_IsDisallowListed_Call) Run(run func(peerID peer.ID)) *DisallowListCache_IsDisallowListed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DisallowListCache_IsDisallowListed_Call) Return(disallowListedCauses []network.DisallowListedCause, b bool) *DisallowListCache_IsDisallowListed_Call { + _c.Call.Return(disallowListedCauses, b) + return _c +} + +func (_c *DisallowListCache_IsDisallowListed_Call) RunAndReturn(run func(peerID peer.ID) ([]network.DisallowListedCause, bool)) *DisallowListCache_IsDisallowListed_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/disallow_list_notification_consumer.go b/network/p2p/mock/disallow_list_notification_consumer.go index 7f7f7103def..f1d2819820c 100644 --- a/network/p2p/mock/disallow_list_notification_consumer.go +++ b/network/p2p/mock/disallow_list_notification_consumer.go @@ -1,29 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/onflow/flow-go/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) -// DisallowListNotificationConsumer is an autogenerated mock type for the DisallowListNotificationConsumer type -type DisallowListNotificationConsumer struct { - mock.Mock -} - -// OnAllowListNotification provides a mock function with given fields: id, cause -func (_m *DisallowListNotificationConsumer) OnAllowListNotification(id peer.ID, cause network.DisallowListedCause) { - _m.Called(id, cause) -} - -// OnDisallowListNotification provides a mock function with given fields: id, cause -func (_m *DisallowListNotificationConsumer) OnDisallowListNotification(id peer.ID, cause network.DisallowListedCause) { - _m.Called(id, cause) -} - // NewDisallowListNotificationConsumer creates a new instance of DisallowListNotificationConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewDisallowListNotificationConsumer(t interface { @@ -37,3 +23,108 @@ func NewDisallowListNotificationConsumer(t interface { return mock } + +// DisallowListNotificationConsumer is an autogenerated mock type for the DisallowListNotificationConsumer type +type DisallowListNotificationConsumer struct { + mock.Mock +} + +type DisallowListNotificationConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *DisallowListNotificationConsumer) EXPECT() *DisallowListNotificationConsumer_Expecter { + return &DisallowListNotificationConsumer_Expecter{mock: &_m.Mock} +} + +// OnAllowListNotification provides a mock function for the type DisallowListNotificationConsumer +func (_mock *DisallowListNotificationConsumer) OnAllowListNotification(id peer.ID, cause network.DisallowListedCause) { + _mock.Called(id, cause) + return +} + +// DisallowListNotificationConsumer_OnAllowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAllowListNotification' +type DisallowListNotificationConsumer_OnAllowListNotification_Call struct { + *mock.Call +} + +// OnAllowListNotification is a helper method to define mock.On call +// - id peer.ID +// - cause network.DisallowListedCause +func (_e *DisallowListNotificationConsumer_Expecter) OnAllowListNotification(id interface{}, cause interface{}) *DisallowListNotificationConsumer_OnAllowListNotification_Call { + return &DisallowListNotificationConsumer_OnAllowListNotification_Call{Call: _e.mock.On("OnAllowListNotification", id, cause)} +} + +func (_c *DisallowListNotificationConsumer_OnAllowListNotification_Call) Run(run func(id peer.ID, cause network.DisallowListedCause)) *DisallowListNotificationConsumer_OnAllowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.DisallowListedCause + if args[1] != nil { + arg1 = args[1].(network.DisallowListedCause) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DisallowListNotificationConsumer_OnAllowListNotification_Call) Return() *DisallowListNotificationConsumer_OnAllowListNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *DisallowListNotificationConsumer_OnAllowListNotification_Call) RunAndReturn(run func(id peer.ID, cause network.DisallowListedCause)) *DisallowListNotificationConsumer_OnAllowListNotification_Call { + _c.Run(run) + return _c +} + +// OnDisallowListNotification provides a mock function for the type DisallowListNotificationConsumer +func (_mock *DisallowListNotificationConsumer) OnDisallowListNotification(id peer.ID, cause network.DisallowListedCause) { + _mock.Called(id, cause) + return +} + +// DisallowListNotificationConsumer_OnDisallowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDisallowListNotification' +type DisallowListNotificationConsumer_OnDisallowListNotification_Call struct { + *mock.Call +} + +// OnDisallowListNotification is a helper method to define mock.On call +// - id peer.ID +// - cause network.DisallowListedCause +func (_e *DisallowListNotificationConsumer_Expecter) OnDisallowListNotification(id interface{}, cause interface{}) *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + return &DisallowListNotificationConsumer_OnDisallowListNotification_Call{Call: _e.mock.On("OnDisallowListNotification", id, cause)} +} + +func (_c *DisallowListNotificationConsumer_OnDisallowListNotification_Call) Run(run func(id peer.ID, cause network.DisallowListedCause)) *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.DisallowListedCause + if args[1] != nil { + arg1 = args[1].(network.DisallowListedCause) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DisallowListNotificationConsumer_OnDisallowListNotification_Call) Return() *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *DisallowListNotificationConsumer_OnDisallowListNotification_Call) RunAndReturn(run func(id peer.ID, cause network.DisallowListedCause)) *DisallowListNotificationConsumer_OnDisallowListNotification_Call { + _c.Run(run) + return _c +} diff --git a/network/p2p/mock/disallow_list_oracle.go b/network/p2p/mock/disallow_list_oracle.go index 760569cc7cf..0d20426ac61 100644 --- a/network/p2p/mock/disallow_list_oracle.go +++ b/network/p2p/mock/disallow_list_oracle.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - network "github.com/onflow/flow-go/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewDisallowListOracle creates a new instance of DisallowListOracle. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDisallowListOracle(t interface { + mock.TestingT + Cleanup(func()) +}) *DisallowListOracle { + mock := &DisallowListOracle{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DisallowListOracle is an autogenerated mock type for the DisallowListOracle type type DisallowListOracle struct { mock.Mock } -// IsDisallowListed provides a mock function with given fields: peerId -func (_m *DisallowListOracle) IsDisallowListed(peerId peer.ID) ([]network.DisallowListedCause, bool) { - ret := _m.Called(peerId) +type DisallowListOracle_Expecter struct { + mock *mock.Mock +} + +func (_m *DisallowListOracle) EXPECT() *DisallowListOracle_Expecter { + return &DisallowListOracle_Expecter{mock: &_m.Mock} +} + +// IsDisallowListed provides a mock function for the type DisallowListOracle +func (_mock *DisallowListOracle) IsDisallowListed(peerId peer.ID) ([]network.DisallowListedCause, bool) { + ret := _mock.Called(peerId) if len(ret) == 0 { panic("no return value specified for IsDisallowListed") @@ -24,36 +47,54 @@ func (_m *DisallowListOracle) IsDisallowListed(peerId peer.ID) ([]network.Disall var r0 []network.DisallowListedCause var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) ([]network.DisallowListedCause, bool)); ok { - return rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) ([]network.DisallowListedCause, bool)); ok { + return returnFunc(peerId) } - if rf, ok := ret.Get(0).(func(peer.ID) []network.DisallowListedCause); ok { - r0 = rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) []network.DisallowListedCause); ok { + r0 = returnFunc(peerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]network.DisallowListedCause) } } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerId) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerId) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// NewDisallowListOracle creates a new instance of DisallowListOracle. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDisallowListOracle(t interface { - mock.TestingT - Cleanup(func()) -}) *DisallowListOracle { - mock := &DisallowListOracle{} - mock.Mock.Test(t) +// DisallowListOracle_IsDisallowListed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsDisallowListed' +type DisallowListOracle_IsDisallowListed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// IsDisallowListed is a helper method to define mock.On call +// - peerId peer.ID +func (_e *DisallowListOracle_Expecter) IsDisallowListed(peerId interface{}) *DisallowListOracle_IsDisallowListed_Call { + return &DisallowListOracle_IsDisallowListed_Call{Call: _e.mock.On("IsDisallowListed", peerId)} +} - return mock +func (_c *DisallowListOracle_IsDisallowListed_Call) Run(run func(peerId peer.ID)) *DisallowListOracle_IsDisallowListed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DisallowListOracle_IsDisallowListed_Call) Return(disallowListedCauses []network.DisallowListedCause, b bool) *DisallowListOracle_IsDisallowListed_Call { + _c.Call.Return(disallowListedCauses, b) + return _c +} + +func (_c *DisallowListOracle_IsDisallowListed_Call) RunAndReturn(run func(peerId peer.ID) ([]network.DisallowListedCause, bool)) *DisallowListOracle_IsDisallowListed_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/gossip_sub_application_specific_score_cache.go b/network/p2p/mock/gossip_sub_application_specific_score_cache.go index fc8a2481c57..4d2ad04384b 100644 --- a/network/p2p/mock/gossip_sub_application_specific_score_cache.go +++ b/network/p2p/mock/gossip_sub_application_specific_score_cache.go @@ -1,41 +1,109 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "time" + + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewGossipSubApplicationSpecificScoreCache creates a new instance of GossipSubApplicationSpecificScoreCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubApplicationSpecificScoreCache(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubApplicationSpecificScoreCache { + mock := &GossipSubApplicationSpecificScoreCache{} + mock.Mock.Test(t) - time "time" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // GossipSubApplicationSpecificScoreCache is an autogenerated mock type for the GossipSubApplicationSpecificScoreCache type type GossipSubApplicationSpecificScoreCache struct { mock.Mock } -// AdjustWithInit provides a mock function with given fields: peerID, score, _a2 -func (_m *GossipSubApplicationSpecificScoreCache) AdjustWithInit(peerID peer.ID, score float64, _a2 time.Time) error { - ret := _m.Called(peerID, score, _a2) +type GossipSubApplicationSpecificScoreCache_Expecter struct { + mock *mock.Mock +} + +func (_m *GossipSubApplicationSpecificScoreCache) EXPECT() *GossipSubApplicationSpecificScoreCache_Expecter { + return &GossipSubApplicationSpecificScoreCache_Expecter{mock: &_m.Mock} +} + +// AdjustWithInit provides a mock function for the type GossipSubApplicationSpecificScoreCache +func (_mock *GossipSubApplicationSpecificScoreCache) AdjustWithInit(peerID peer.ID, score float64, time1 time.Time) error { + ret := _mock.Called(peerID, score, time1) if len(ret) == 0 { panic("no return value specified for AdjustWithInit") } var r0 error - if rf, ok := ret.Get(0).(func(peer.ID, float64, time.Time) error); ok { - r0 = rf(peerID, score, _a2) + if returnFunc, ok := ret.Get(0).(func(peer.ID, float64, time.Time) error); ok { + r0 = returnFunc(peerID, score, time1) } else { r0 = ret.Error(0) } - return r0 } -// Get provides a mock function with given fields: peerID -func (_m *GossipSubApplicationSpecificScoreCache) Get(peerID peer.ID) (float64, time.Time, bool) { - ret := _m.Called(peerID) +// GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AdjustWithInit' +type GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call struct { + *mock.Call +} + +// AdjustWithInit is a helper method to define mock.On call +// - peerID peer.ID +// - score float64 +// - time1 time.Time +func (_e *GossipSubApplicationSpecificScoreCache_Expecter) AdjustWithInit(peerID interface{}, score interface{}, time1 interface{}) *GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call { + return &GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call{Call: _e.mock.On("AdjustWithInit", peerID, score, time1)} +} + +func (_c *GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call) Run(run func(peerID peer.ID, score float64, time1 time.Time)) *GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 float64 + if args[1] != nil { + arg1 = args[1].(float64) + } + var arg2 time.Time + if args[2] != nil { + arg2 = args[2].(time.Time) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call) Return(err error) *GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call { + _c.Call.Return(err) + return _c +} + +func (_c *GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call) RunAndReturn(run func(peerID peer.ID, score float64, time1 time.Time) error) *GossipSubApplicationSpecificScoreCache_AdjustWithInit_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type GossipSubApplicationSpecificScoreCache +func (_mock *GossipSubApplicationSpecificScoreCache) Get(peerID peer.ID) (float64, time.Time, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for Get") @@ -44,40 +112,57 @@ func (_m *GossipSubApplicationSpecificScoreCache) Get(peerID peer.ID) (float64, var r0 float64 var r1 time.Time var r2 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, time.Time, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, time.Time, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) time.Time); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) time.Time); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(time.Time) } - - if rf, ok := ret.Get(2).(func(peer.ID) bool); ok { - r2 = rf(peerID) + if returnFunc, ok := ret.Get(2).(func(peer.ID) bool); ok { + r2 = returnFunc(peerID) } else { r2 = ret.Get(2).(bool) } - return r0, r1, r2 } -// NewGossipSubApplicationSpecificScoreCache creates a new instance of GossipSubApplicationSpecificScoreCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubApplicationSpecificScoreCache(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubApplicationSpecificScoreCache { - mock := &GossipSubApplicationSpecificScoreCache{} - mock.Mock.Test(t) +// GossipSubApplicationSpecificScoreCache_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type GossipSubApplicationSpecificScoreCache_Get_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Get is a helper method to define mock.On call +// - peerID peer.ID +func (_e *GossipSubApplicationSpecificScoreCache_Expecter) Get(peerID interface{}) *GossipSubApplicationSpecificScoreCache_Get_Call { + return &GossipSubApplicationSpecificScoreCache_Get_Call{Call: _e.mock.On("Get", peerID)} +} - return mock +func (_c *GossipSubApplicationSpecificScoreCache_Get_Call) Run(run func(peerID peer.ID)) *GossipSubApplicationSpecificScoreCache_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubApplicationSpecificScoreCache_Get_Call) Return(f float64, time1 time.Time, b bool) *GossipSubApplicationSpecificScoreCache_Get_Call { + _c.Call.Return(f, time1, b) + return _c +} + +func (_c *GossipSubApplicationSpecificScoreCache_Get_Call) RunAndReturn(run func(peerID peer.ID) (float64, time.Time, bool)) *GossipSubApplicationSpecificScoreCache_Get_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/gossip_sub_builder.go b/network/p2p/mock/gossip_sub_builder.go index cd1b3004c20..4e079e2aa75 100644 --- a/network/p2p/mock/gossip_sub_builder.go +++ b/network/p2p/mock/gossip_sub_builder.go @@ -1,28 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - host "github.com/libp2p/go-libp2p/core/host" - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/libp2p/go-libp2p-pubsub" + "github.com/libp2p/go-libp2p/core/host" + "github.com/libp2p/go-libp2p/core/routing" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) - p2p "github.com/onflow/flow-go/network/p2p" +// NewGossipSubBuilder creates a new instance of GossipSubBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubBuilder(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubBuilder { + mock := &GossipSubBuilder{} + mock.Mock.Test(t) - pubsub "github.com/libp2p/go-libp2p-pubsub" + t.Cleanup(func() { mock.AssertExpectations(t) }) - routing "github.com/libp2p/go-libp2p/core/routing" -) + return mock +} // GossipSubBuilder is an autogenerated mock type for the GossipSubBuilder type type GossipSubBuilder struct { mock.Mock } -// Build provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) Build(_a0 irrecoverable.SignalerContext) (p2p.PubSubAdapter, error) { - ret := _m.Called(_a0) +type GossipSubBuilder_Expecter struct { + mock *mock.Mock +} + +func (_m *GossipSubBuilder) EXPECT() *GossipSubBuilder_Expecter { + return &GossipSubBuilder_Expecter{mock: &_m.Mock} +} + +// Build provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) Build(signalerContext irrecoverable.SignalerContext) (p2p.PubSubAdapter, error) { + ret := _mock.Called(signalerContext) if len(ret) == 0 { panic("no return value specified for Build") @@ -30,76 +50,374 @@ func (_m *GossipSubBuilder) Build(_a0 irrecoverable.SignalerContext) (p2p.PubSub var r0 p2p.PubSubAdapter var r1 error - if rf, ok := ret.Get(0).(func(irrecoverable.SignalerContext) (p2p.PubSubAdapter, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(irrecoverable.SignalerContext) (p2p.PubSubAdapter, error)); ok { + return returnFunc(signalerContext) } - if rf, ok := ret.Get(0).(func(irrecoverable.SignalerContext) p2p.PubSubAdapter); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(irrecoverable.SignalerContext) p2p.PubSubAdapter); ok { + r0 = returnFunc(signalerContext) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.PubSubAdapter) } } - - if rf, ok := ret.Get(1).(func(irrecoverable.SignalerContext) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(irrecoverable.SignalerContext) error); ok { + r1 = returnFunc(signalerContext) } else { r1 = ret.Error(1) } - return r0, r1 } -// EnableGossipSubScoringWithOverride provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) EnableGossipSubScoringWithOverride(_a0 *p2p.PeerScoringConfigOverride) { - _m.Called(_a0) +// GossipSubBuilder_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build' +type GossipSubBuilder_Build_Call struct { + *mock.Call } -// OverrideDefaultRpcInspectorFactory provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) OverrideDefaultRpcInspectorFactory(_a0 p2p.GossipSubRpcInspectorFactoryFunc) { - _m.Called(_a0) +// Build is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *GossipSubBuilder_Expecter) Build(signalerContext interface{}) *GossipSubBuilder_Build_Call { + return &GossipSubBuilder_Build_Call{Call: _e.mock.On("Build", signalerContext)} } -// OverrideDefaultValidateQueueSize provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) OverrideDefaultValidateQueueSize(_a0 int) { - _m.Called(_a0) +func (_c *GossipSubBuilder_Build_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *GossipSubBuilder_Build_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c } -// SetGossipSubConfigFunc provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) SetGossipSubConfigFunc(_a0 p2p.GossipSubAdapterConfigFunc) { - _m.Called(_a0) +func (_c *GossipSubBuilder_Build_Call) Return(pubSubAdapter p2p.PubSubAdapter, err error) *GossipSubBuilder_Build_Call { + _c.Call.Return(pubSubAdapter, err) + return _c } -// SetGossipSubFactory provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) SetGossipSubFactory(_a0 p2p.GossipSubFactoryFunc) { - _m.Called(_a0) +func (_c *GossipSubBuilder_Build_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext) (p2p.PubSubAdapter, error)) *GossipSubBuilder_Build_Call { + _c.Call.Return(run) + return _c } -// SetHost provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) SetHost(_a0 host.Host) { - _m.Called(_a0) +// EnableGossipSubScoringWithOverride provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) EnableGossipSubScoringWithOverride(peerScoringConfigOverride *p2p.PeerScoringConfigOverride) { + _mock.Called(peerScoringConfigOverride) + return } -// SetRoutingSystem provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) SetRoutingSystem(_a0 routing.Routing) { - _m.Called(_a0) +// GossipSubBuilder_EnableGossipSubScoringWithOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EnableGossipSubScoringWithOverride' +type GossipSubBuilder_EnableGossipSubScoringWithOverride_Call struct { + *mock.Call } -// SetSubscriptionFilter provides a mock function with given fields: _a0 -func (_m *GossipSubBuilder) SetSubscriptionFilter(_a0 pubsub.SubscriptionFilter) { - _m.Called(_a0) +// EnableGossipSubScoringWithOverride is a helper method to define mock.On call +// - peerScoringConfigOverride *p2p.PeerScoringConfigOverride +func (_e *GossipSubBuilder_Expecter) EnableGossipSubScoringWithOverride(peerScoringConfigOverride interface{}) *GossipSubBuilder_EnableGossipSubScoringWithOverride_Call { + return &GossipSubBuilder_EnableGossipSubScoringWithOverride_Call{Call: _e.mock.On("EnableGossipSubScoringWithOverride", peerScoringConfigOverride)} } -// NewGossipSubBuilder creates a new instance of GossipSubBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubBuilder(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubBuilder { - mock := &GossipSubBuilder{} - mock.Mock.Test(t) +func (_c *GossipSubBuilder_EnableGossipSubScoringWithOverride_Call) Run(run func(peerScoringConfigOverride *p2p.PeerScoringConfigOverride)) *GossipSubBuilder_EnableGossipSubScoringWithOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *p2p.PeerScoringConfigOverride + if args[0] != nil { + arg0 = args[0].(*p2p.PeerScoringConfigOverride) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *GossipSubBuilder_EnableGossipSubScoringWithOverride_Call) Return() *GossipSubBuilder_EnableGossipSubScoringWithOverride_Call { + _c.Call.Return() + return _c +} - return mock +func (_c *GossipSubBuilder_EnableGossipSubScoringWithOverride_Call) RunAndReturn(run func(peerScoringConfigOverride *p2p.PeerScoringConfigOverride)) *GossipSubBuilder_EnableGossipSubScoringWithOverride_Call { + _c.Run(run) + return _c +} + +// OverrideDefaultRpcInspectorFactory provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) OverrideDefaultRpcInspectorFactory(gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc) { + _mock.Called(gossipSubRpcInspectorFactoryFunc) + return +} + +// GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OverrideDefaultRpcInspectorFactory' +type GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call struct { + *mock.Call +} + +// OverrideDefaultRpcInspectorFactory is a helper method to define mock.On call +// - gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc +func (_e *GossipSubBuilder_Expecter) OverrideDefaultRpcInspectorFactory(gossipSubRpcInspectorFactoryFunc interface{}) *GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call { + return &GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call{Call: _e.mock.On("OverrideDefaultRpcInspectorFactory", gossipSubRpcInspectorFactoryFunc)} +} + +func (_c *GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call) Run(run func(gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc)) *GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.GossipSubRpcInspectorFactoryFunc + if args[0] != nil { + arg0 = args[0].(p2p.GossipSubRpcInspectorFactoryFunc) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call) Return() *GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call) RunAndReturn(run func(gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc)) *GossipSubBuilder_OverrideDefaultRpcInspectorFactory_Call { + _c.Run(run) + return _c +} + +// OverrideDefaultValidateQueueSize provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) OverrideDefaultValidateQueueSize(n int) { + _mock.Called(n) + return +} + +// GossipSubBuilder_OverrideDefaultValidateQueueSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OverrideDefaultValidateQueueSize' +type GossipSubBuilder_OverrideDefaultValidateQueueSize_Call struct { + *mock.Call +} + +// OverrideDefaultValidateQueueSize is a helper method to define mock.On call +// - n int +func (_e *GossipSubBuilder_Expecter) OverrideDefaultValidateQueueSize(n interface{}) *GossipSubBuilder_OverrideDefaultValidateQueueSize_Call { + return &GossipSubBuilder_OverrideDefaultValidateQueueSize_Call{Call: _e.mock.On("OverrideDefaultValidateQueueSize", n)} +} + +func (_c *GossipSubBuilder_OverrideDefaultValidateQueueSize_Call) Run(run func(n int)) *GossipSubBuilder_OverrideDefaultValidateQueueSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubBuilder_OverrideDefaultValidateQueueSize_Call) Return() *GossipSubBuilder_OverrideDefaultValidateQueueSize_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubBuilder_OverrideDefaultValidateQueueSize_Call) RunAndReturn(run func(n int)) *GossipSubBuilder_OverrideDefaultValidateQueueSize_Call { + _c.Run(run) + return _c +} + +// SetGossipSubConfigFunc provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) SetGossipSubConfigFunc(gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc) { + _mock.Called(gossipSubAdapterConfigFunc) + return +} + +// GossipSubBuilder_SetGossipSubConfigFunc_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetGossipSubConfigFunc' +type GossipSubBuilder_SetGossipSubConfigFunc_Call struct { + *mock.Call +} + +// SetGossipSubConfigFunc is a helper method to define mock.On call +// - gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc +func (_e *GossipSubBuilder_Expecter) SetGossipSubConfigFunc(gossipSubAdapterConfigFunc interface{}) *GossipSubBuilder_SetGossipSubConfigFunc_Call { + return &GossipSubBuilder_SetGossipSubConfigFunc_Call{Call: _e.mock.On("SetGossipSubConfigFunc", gossipSubAdapterConfigFunc)} +} + +func (_c *GossipSubBuilder_SetGossipSubConfigFunc_Call) Run(run func(gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc)) *GossipSubBuilder_SetGossipSubConfigFunc_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.GossipSubAdapterConfigFunc + if args[0] != nil { + arg0 = args[0].(p2p.GossipSubAdapterConfigFunc) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubBuilder_SetGossipSubConfigFunc_Call) Return() *GossipSubBuilder_SetGossipSubConfigFunc_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubBuilder_SetGossipSubConfigFunc_Call) RunAndReturn(run func(gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc)) *GossipSubBuilder_SetGossipSubConfigFunc_Call { + _c.Run(run) + return _c +} + +// SetGossipSubFactory provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) SetGossipSubFactory(gossipSubFactoryFunc p2p.GossipSubFactoryFunc) { + _mock.Called(gossipSubFactoryFunc) + return +} + +// GossipSubBuilder_SetGossipSubFactory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetGossipSubFactory' +type GossipSubBuilder_SetGossipSubFactory_Call struct { + *mock.Call +} + +// SetGossipSubFactory is a helper method to define mock.On call +// - gossipSubFactoryFunc p2p.GossipSubFactoryFunc +func (_e *GossipSubBuilder_Expecter) SetGossipSubFactory(gossipSubFactoryFunc interface{}) *GossipSubBuilder_SetGossipSubFactory_Call { + return &GossipSubBuilder_SetGossipSubFactory_Call{Call: _e.mock.On("SetGossipSubFactory", gossipSubFactoryFunc)} +} + +func (_c *GossipSubBuilder_SetGossipSubFactory_Call) Run(run func(gossipSubFactoryFunc p2p.GossipSubFactoryFunc)) *GossipSubBuilder_SetGossipSubFactory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.GossipSubFactoryFunc + if args[0] != nil { + arg0 = args[0].(p2p.GossipSubFactoryFunc) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubBuilder_SetGossipSubFactory_Call) Return() *GossipSubBuilder_SetGossipSubFactory_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubBuilder_SetGossipSubFactory_Call) RunAndReturn(run func(gossipSubFactoryFunc p2p.GossipSubFactoryFunc)) *GossipSubBuilder_SetGossipSubFactory_Call { + _c.Run(run) + return _c +} + +// SetHost provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) SetHost(host1 host.Host) { + _mock.Called(host1) + return +} + +// GossipSubBuilder_SetHost_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetHost' +type GossipSubBuilder_SetHost_Call struct { + *mock.Call +} + +// SetHost is a helper method to define mock.On call +// - host1 host.Host +func (_e *GossipSubBuilder_Expecter) SetHost(host1 interface{}) *GossipSubBuilder_SetHost_Call { + return &GossipSubBuilder_SetHost_Call{Call: _e.mock.On("SetHost", host1)} +} + +func (_c *GossipSubBuilder_SetHost_Call) Run(run func(host1 host.Host)) *GossipSubBuilder_SetHost_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 host.Host + if args[0] != nil { + arg0 = args[0].(host.Host) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubBuilder_SetHost_Call) Return() *GossipSubBuilder_SetHost_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubBuilder_SetHost_Call) RunAndReturn(run func(host1 host.Host)) *GossipSubBuilder_SetHost_Call { + _c.Run(run) + return _c +} + +// SetRoutingSystem provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) SetRoutingSystem(routing1 routing.Routing) { + _mock.Called(routing1) + return +} + +// GossipSubBuilder_SetRoutingSystem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetRoutingSystem' +type GossipSubBuilder_SetRoutingSystem_Call struct { + *mock.Call +} + +// SetRoutingSystem is a helper method to define mock.On call +// - routing1 routing.Routing +func (_e *GossipSubBuilder_Expecter) SetRoutingSystem(routing1 interface{}) *GossipSubBuilder_SetRoutingSystem_Call { + return &GossipSubBuilder_SetRoutingSystem_Call{Call: _e.mock.On("SetRoutingSystem", routing1)} +} + +func (_c *GossipSubBuilder_SetRoutingSystem_Call) Run(run func(routing1 routing.Routing)) *GossipSubBuilder_SetRoutingSystem_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 routing.Routing + if args[0] != nil { + arg0 = args[0].(routing.Routing) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubBuilder_SetRoutingSystem_Call) Return() *GossipSubBuilder_SetRoutingSystem_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubBuilder_SetRoutingSystem_Call) RunAndReturn(run func(routing1 routing.Routing)) *GossipSubBuilder_SetRoutingSystem_Call { + _c.Run(run) + return _c +} + +// SetSubscriptionFilter provides a mock function for the type GossipSubBuilder +func (_mock *GossipSubBuilder) SetSubscriptionFilter(subscriptionFilter pubsub.SubscriptionFilter) { + _mock.Called(subscriptionFilter) + return +} + +// GossipSubBuilder_SetSubscriptionFilter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetSubscriptionFilter' +type GossipSubBuilder_SetSubscriptionFilter_Call struct { + *mock.Call +} + +// SetSubscriptionFilter is a helper method to define mock.On call +// - subscriptionFilter pubsub.SubscriptionFilter +func (_e *GossipSubBuilder_Expecter) SetSubscriptionFilter(subscriptionFilter interface{}) *GossipSubBuilder_SetSubscriptionFilter_Call { + return &GossipSubBuilder_SetSubscriptionFilter_Call{Call: _e.mock.On("SetSubscriptionFilter", subscriptionFilter)} +} + +func (_c *GossipSubBuilder_SetSubscriptionFilter_Call) Run(run func(subscriptionFilter pubsub.SubscriptionFilter)) *GossipSubBuilder_SetSubscriptionFilter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 pubsub.SubscriptionFilter + if args[0] != nil { + arg0 = args[0].(pubsub.SubscriptionFilter) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubBuilder_SetSubscriptionFilter_Call) Return() *GossipSubBuilder_SetSubscriptionFilter_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubBuilder_SetSubscriptionFilter_Call) RunAndReturn(run func(subscriptionFilter pubsub.SubscriptionFilter)) *GossipSubBuilder_SetSubscriptionFilter_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/gossip_sub_inv_ctrl_msg_notif_consumer.go b/network/p2p/mock/gossip_sub_inv_ctrl_msg_notif_consumer.go index ffb33f60fc8..143cdd81981 100644 --- a/network/p2p/mock/gossip_sub_inv_ctrl_msg_notif_consumer.go +++ b/network/p2p/mock/gossip_sub_inv_ctrl_msg_notif_consumer.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - p2p "github.com/onflow/flow-go/network/p2p" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" ) -// GossipSubInvCtrlMsgNotifConsumer is an autogenerated mock type for the GossipSubInvCtrlMsgNotifConsumer type -type GossipSubInvCtrlMsgNotifConsumer struct { - mock.Mock -} - -// OnInvalidControlMessageNotification provides a mock function with given fields: _a0 -func (_m *GossipSubInvCtrlMsgNotifConsumer) OnInvalidControlMessageNotification(_a0 *p2p.InvCtrlMsgNotif) { - _m.Called(_a0) -} - // NewGossipSubInvCtrlMsgNotifConsumer creates a new instance of GossipSubInvCtrlMsgNotifConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewGossipSubInvCtrlMsgNotifConsumer(t interface { @@ -30,3 +22,56 @@ func NewGossipSubInvCtrlMsgNotifConsumer(t interface { return mock } + +// GossipSubInvCtrlMsgNotifConsumer is an autogenerated mock type for the GossipSubInvCtrlMsgNotifConsumer type +type GossipSubInvCtrlMsgNotifConsumer struct { + mock.Mock +} + +type GossipSubInvCtrlMsgNotifConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *GossipSubInvCtrlMsgNotifConsumer) EXPECT() *GossipSubInvCtrlMsgNotifConsumer_Expecter { + return &GossipSubInvCtrlMsgNotifConsumer_Expecter{mock: &_m.Mock} +} + +// OnInvalidControlMessageNotification provides a mock function for the type GossipSubInvCtrlMsgNotifConsumer +func (_mock *GossipSubInvCtrlMsgNotifConsumer) OnInvalidControlMessageNotification(invCtrlMsgNotif *p2p.InvCtrlMsgNotif) { + _mock.Called(invCtrlMsgNotif) + return +} + +// GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidControlMessageNotification' +type GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call struct { + *mock.Call +} + +// OnInvalidControlMessageNotification is a helper method to define mock.On call +// - invCtrlMsgNotif *p2p.InvCtrlMsgNotif +func (_e *GossipSubInvCtrlMsgNotifConsumer_Expecter) OnInvalidControlMessageNotification(invCtrlMsgNotif interface{}) *GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call { + return &GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call{Call: _e.mock.On("OnInvalidControlMessageNotification", invCtrlMsgNotif)} +} + +func (_c *GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call) Run(run func(invCtrlMsgNotif *p2p.InvCtrlMsgNotif)) *GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *p2p.InvCtrlMsgNotif + if args[0] != nil { + arg0 = args[0].(*p2p.InvCtrlMsgNotif) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call) Return() *GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call) RunAndReturn(run func(invCtrlMsgNotif *p2p.InvCtrlMsgNotif)) *GossipSubInvCtrlMsgNotifConsumer_OnInvalidControlMessageNotification_Call { + _c.Run(run) + return _c +} diff --git a/network/p2p/mock/gossip_sub_rpc_inspector.go b/network/p2p/mock/gossip_sub_rpc_inspector.go index df010a8c657..5aaf4060b6e 100644 --- a/network/p2p/mock/gossip_sub_rpc_inspector.go +++ b/network/p2p/mock/gossip_sub_rpc_inspector.go @@ -1,119 +1,313 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/libp2p/go-libp2p-pubsub" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewGossipSubRPCInspector creates a new instance of GossipSubRPCInspector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubRPCInspector(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubRPCInspector { + mock := &GossipSubRPCInspector{} + mock.Mock.Test(t) - pubsub "github.com/libp2p/go-libp2p-pubsub" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // GossipSubRPCInspector is an autogenerated mock type for the GossipSubRPCInspector type type GossipSubRPCInspector struct { mock.Mock } -// ActiveClustersChanged provides a mock function with given fields: _a0 -func (_m *GossipSubRPCInspector) ActiveClustersChanged(_a0 flow.ChainIDList) { - _m.Called(_a0) +type GossipSubRPCInspector_Expecter struct { + mock *mock.Mock +} + +func (_m *GossipSubRPCInspector) EXPECT() *GossipSubRPCInspector_Expecter { + return &GossipSubRPCInspector_Expecter{mock: &_m.Mock} +} + +// ActiveClustersChanged provides a mock function for the type GossipSubRPCInspector +func (_mock *GossipSubRPCInspector) ActiveClustersChanged(chainIDList flow.ChainIDList) { + _mock.Called(chainIDList) + return +} + +// GossipSubRPCInspector_ActiveClustersChanged_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ActiveClustersChanged' +type GossipSubRPCInspector_ActiveClustersChanged_Call struct { + *mock.Call } -// Done provides a mock function with no fields -func (_m *GossipSubRPCInspector) Done() <-chan struct{} { - ret := _m.Called() +// ActiveClustersChanged is a helper method to define mock.On call +// - chainIDList flow.ChainIDList +func (_e *GossipSubRPCInspector_Expecter) ActiveClustersChanged(chainIDList interface{}) *GossipSubRPCInspector_ActiveClustersChanged_Call { + return &GossipSubRPCInspector_ActiveClustersChanged_Call{Call: _e.mock.On("ActiveClustersChanged", chainIDList)} +} + +func (_c *GossipSubRPCInspector_ActiveClustersChanged_Call) Run(run func(chainIDList flow.ChainIDList)) *GossipSubRPCInspector_ActiveClustersChanged_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ChainIDList + if args[0] != nil { + arg0 = args[0].(flow.ChainIDList) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubRPCInspector_ActiveClustersChanged_Call) Return() *GossipSubRPCInspector_ActiveClustersChanged_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRPCInspector_ActiveClustersChanged_Call) RunAndReturn(run func(chainIDList flow.ChainIDList)) *GossipSubRPCInspector_ActiveClustersChanged_Call { + _c.Run(run) + return _c +} + +// Done provides a mock function for the type GossipSubRPCInspector +func (_mock *GossipSubRPCInspector) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Inspect provides a mock function with given fields: _a0, _a1 -func (_m *GossipSubRPCInspector) Inspect(_a0 peer.ID, _a1 *pubsub.RPC) error { - ret := _m.Called(_a0, _a1) +// GossipSubRPCInspector_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type GossipSubRPCInspector_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *GossipSubRPCInspector_Expecter) Done() *GossipSubRPCInspector_Done_Call { + return &GossipSubRPCInspector_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *GossipSubRPCInspector_Done_Call) Run(run func()) *GossipSubRPCInspector_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRPCInspector_Done_Call) Return(valCh <-chan struct{}) *GossipSubRPCInspector_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *GossipSubRPCInspector_Done_Call) RunAndReturn(run func() <-chan struct{}) *GossipSubRPCInspector_Done_Call { + _c.Call.Return(run) + return _c +} + +// Inspect provides a mock function for the type GossipSubRPCInspector +func (_mock *GossipSubRPCInspector) Inspect(iD peer.ID, rPC *pubsub.RPC) error { + ret := _mock.Called(iD, rPC) if len(ret) == 0 { panic("no return value specified for Inspect") } var r0 error - if rf, ok := ret.Get(0).(func(peer.ID, *pubsub.RPC) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(peer.ID, *pubsub.RPC) error); ok { + r0 = returnFunc(iD, rPC) } else { r0 = ret.Error(0) } - return r0 } -// Name provides a mock function with no fields -func (_m *GossipSubRPCInspector) Name() string { - ret := _m.Called() +// GossipSubRPCInspector_Inspect_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Inspect' +type GossipSubRPCInspector_Inspect_Call struct { + *mock.Call +} + +// Inspect is a helper method to define mock.On call +// - iD peer.ID +// - rPC *pubsub.RPC +func (_e *GossipSubRPCInspector_Expecter) Inspect(iD interface{}, rPC interface{}) *GossipSubRPCInspector_Inspect_Call { + return &GossipSubRPCInspector_Inspect_Call{Call: _e.mock.On("Inspect", iD, rPC)} +} + +func (_c *GossipSubRPCInspector_Inspect_Call) Run(run func(iD peer.ID, rPC *pubsub.RPC)) *GossipSubRPCInspector_Inspect_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 *pubsub.RPC + if args[1] != nil { + arg1 = args[1].(*pubsub.RPC) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubRPCInspector_Inspect_Call) Return(err error) *GossipSubRPCInspector_Inspect_Call { + _c.Call.Return(err) + return _c +} + +func (_c *GossipSubRPCInspector_Inspect_Call) RunAndReturn(run func(iD peer.ID, rPC *pubsub.RPC) error) *GossipSubRPCInspector_Inspect_Call { + _c.Call.Return(run) + return _c +} + +// Name provides a mock function for the type GossipSubRPCInspector +func (_mock *GossipSubRPCInspector) Name() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Name") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// Ready provides a mock function with no fields -func (_m *GossipSubRPCInspector) Ready() <-chan struct{} { - ret := _m.Called() +// GossipSubRPCInspector_Name_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Name' +type GossipSubRPCInspector_Name_Call struct { + *mock.Call +} + +// Name is a helper method to define mock.On call +func (_e *GossipSubRPCInspector_Expecter) Name() *GossipSubRPCInspector_Name_Call { + return &GossipSubRPCInspector_Name_Call{Call: _e.mock.On("Name")} +} + +func (_c *GossipSubRPCInspector_Name_Call) Run(run func()) *GossipSubRPCInspector_Name_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GossipSubRPCInspector_Name_Call) Return(s string) *GossipSubRPCInspector_Name_Call { + _c.Call.Return(s) + return _c +} + +func (_c *GossipSubRPCInspector_Name_Call) RunAndReturn(run func() string) *GossipSubRPCInspector_Name_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type GossipSubRPCInspector +func (_mock *GossipSubRPCInspector) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *GossipSubRPCInspector) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// GossipSubRPCInspector_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type GossipSubRPCInspector_Ready_Call struct { + *mock.Call } -// NewGossipSubRPCInspector creates a new instance of GossipSubRPCInspector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubRPCInspector(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubRPCInspector { - mock := &GossipSubRPCInspector{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *GossipSubRPCInspector_Expecter) Ready() *GossipSubRPCInspector_Ready_Call { + return &GossipSubRPCInspector_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *GossipSubRPCInspector_Ready_Call) Run(run func()) *GossipSubRPCInspector_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *GossipSubRPCInspector_Ready_Call) Return(valCh <-chan struct{}) *GossipSubRPCInspector_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *GossipSubRPCInspector_Ready_Call) RunAndReturn(run func() <-chan struct{}) *GossipSubRPCInspector_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type GossipSubRPCInspector +func (_mock *GossipSubRPCInspector) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// GossipSubRPCInspector_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type GossipSubRPCInspector_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *GossipSubRPCInspector_Expecter) Start(signalerContext interface{}) *GossipSubRPCInspector_Start_Call { + return &GossipSubRPCInspector_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *GossipSubRPCInspector_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *GossipSubRPCInspector_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubRPCInspector_Start_Call) Return() *GossipSubRPCInspector_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *GossipSubRPCInspector_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *GossipSubRPCInspector_Start_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/gossip_sub_spam_record_cache.go b/network/p2p/mock/gossip_sub_spam_record_cache.go index 7431f1eda1e..9a5705f0d21 100644 --- a/network/p2p/mock/gossip_sub_spam_record_cache.go +++ b/network/p2p/mock/gossip_sub_spam_record_cache.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - p2p "github.com/onflow/flow-go/network/p2p" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewGossipSubSpamRecordCache creates a new instance of GossipSubSpamRecordCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGossipSubSpamRecordCache(t interface { + mock.TestingT + Cleanup(func()) +}) *GossipSubSpamRecordCache { + mock := &GossipSubSpamRecordCache{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // GossipSubSpamRecordCache is an autogenerated mock type for the GossipSubSpamRecordCache type type GossipSubSpamRecordCache struct { mock.Mock } -// Adjust provides a mock function with given fields: peerID, updateFunc -func (_m *GossipSubSpamRecordCache) Adjust(peerID peer.ID, updateFunc p2p.UpdateFunction) (*p2p.GossipSubSpamRecord, error) { - ret := _m.Called(peerID, updateFunc) +type GossipSubSpamRecordCache_Expecter struct { + mock *mock.Mock +} + +func (_m *GossipSubSpamRecordCache) EXPECT() *GossipSubSpamRecordCache_Expecter { + return &GossipSubSpamRecordCache_Expecter{mock: &_m.Mock} +} + +// Adjust provides a mock function for the type GossipSubSpamRecordCache +func (_mock *GossipSubSpamRecordCache) Adjust(peerID peer.ID, updateFunc p2p.UpdateFunction) (*p2p.GossipSubSpamRecord, error) { + ret := _mock.Called(peerID, updateFunc) if len(ret) == 0 { panic("no return value specified for Adjust") @@ -24,29 +47,67 @@ func (_m *GossipSubSpamRecordCache) Adjust(peerID peer.ID, updateFunc p2p.Update var r0 *p2p.GossipSubSpamRecord var r1 error - if rf, ok := ret.Get(0).(func(peer.ID, p2p.UpdateFunction) (*p2p.GossipSubSpamRecord, error)); ok { - return rf(peerID, updateFunc) + if returnFunc, ok := ret.Get(0).(func(peer.ID, p2p.UpdateFunction) (*p2p.GossipSubSpamRecord, error)); ok { + return returnFunc(peerID, updateFunc) } - if rf, ok := ret.Get(0).(func(peer.ID, p2p.UpdateFunction) *p2p.GossipSubSpamRecord); ok { - r0 = rf(peerID, updateFunc) + if returnFunc, ok := ret.Get(0).(func(peer.ID, p2p.UpdateFunction) *p2p.GossipSubSpamRecord); ok { + r0 = returnFunc(peerID, updateFunc) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*p2p.GossipSubSpamRecord) } } - - if rf, ok := ret.Get(1).(func(peer.ID, p2p.UpdateFunction) error); ok { - r1 = rf(peerID, updateFunc) + if returnFunc, ok := ret.Get(1).(func(peer.ID, p2p.UpdateFunction) error); ok { + r1 = returnFunc(peerID, updateFunc) } else { r1 = ret.Error(1) } - return r0, r1 } -// Get provides a mock function with given fields: peerID -func (_m *GossipSubSpamRecordCache) Get(peerID peer.ID) (*p2p.GossipSubSpamRecord, error, bool) { - ret := _m.Called(peerID) +// GossipSubSpamRecordCache_Adjust_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Adjust' +type GossipSubSpamRecordCache_Adjust_Call struct { + *mock.Call +} + +// Adjust is a helper method to define mock.On call +// - peerID peer.ID +// - updateFunc p2p.UpdateFunction +func (_e *GossipSubSpamRecordCache_Expecter) Adjust(peerID interface{}, updateFunc interface{}) *GossipSubSpamRecordCache_Adjust_Call { + return &GossipSubSpamRecordCache_Adjust_Call{Call: _e.mock.On("Adjust", peerID, updateFunc)} +} + +func (_c *GossipSubSpamRecordCache_Adjust_Call) Run(run func(peerID peer.ID, updateFunc p2p.UpdateFunction)) *GossipSubSpamRecordCache_Adjust_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 p2p.UpdateFunction + if args[1] != nil { + arg1 = args[1].(p2p.UpdateFunction) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *GossipSubSpamRecordCache_Adjust_Call) Return(gossipSubSpamRecord *p2p.GossipSubSpamRecord, err error) *GossipSubSpamRecordCache_Adjust_Call { + _c.Call.Return(gossipSubSpamRecord, err) + return _c +} + +func (_c *GossipSubSpamRecordCache_Adjust_Call) RunAndReturn(run func(peerID peer.ID, updateFunc p2p.UpdateFunction) (*p2p.GossipSubSpamRecord, error)) *GossipSubSpamRecordCache_Adjust_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type GossipSubSpamRecordCache +func (_mock *GossipSubSpamRecordCache) Get(peerID peer.ID) (*p2p.GossipSubSpamRecord, error, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for Get") @@ -55,60 +116,110 @@ func (_m *GossipSubSpamRecordCache) Get(peerID peer.ID) (*p2p.GossipSubSpamRecor var r0 *p2p.GossipSubSpamRecord var r1 error var r2 bool - if rf, ok := ret.Get(0).(func(peer.ID) (*p2p.GossipSubSpamRecord, error, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (*p2p.GossipSubSpamRecord, error, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) *p2p.GossipSubSpamRecord); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) *p2p.GossipSubSpamRecord); ok { + r0 = returnFunc(peerID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*p2p.GossipSubSpamRecord) } } - - if rf, ok := ret.Get(1).(func(peer.ID) error); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) error); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Error(1) } - - if rf, ok := ret.Get(2).(func(peer.ID) bool); ok { - r2 = rf(peerID) + if returnFunc, ok := ret.Get(2).(func(peer.ID) bool); ok { + r2 = returnFunc(peerID) } else { r2 = ret.Get(2).(bool) } - return r0, r1, r2 } -// Has provides a mock function with given fields: peerID -func (_m *GossipSubSpamRecordCache) Has(peerID peer.ID) bool { - ret := _m.Called(peerID) +// GossipSubSpamRecordCache_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type GossipSubSpamRecordCache_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - peerID peer.ID +func (_e *GossipSubSpamRecordCache_Expecter) Get(peerID interface{}) *GossipSubSpamRecordCache_Get_Call { + return &GossipSubSpamRecordCache_Get_Call{Call: _e.mock.On("Get", peerID)} +} + +func (_c *GossipSubSpamRecordCache_Get_Call) Run(run func(peerID peer.ID)) *GossipSubSpamRecordCache_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubSpamRecordCache_Get_Call) Return(gossipSubSpamRecord *p2p.GossipSubSpamRecord, err error, b bool) *GossipSubSpamRecordCache_Get_Call { + _c.Call.Return(gossipSubSpamRecord, err, b) + return _c +} + +func (_c *GossipSubSpamRecordCache_Get_Call) RunAndReturn(run func(peerID peer.ID) (*p2p.GossipSubSpamRecord, error, bool)) *GossipSubSpamRecordCache_Get_Call { + _c.Call.Return(run) + return _c +} + +// Has provides a mock function for the type GossipSubSpamRecordCache +func (_mock *GossipSubSpamRecordCache) Has(peerID peer.ID) bool { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for Has") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID) bool); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) bool); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewGossipSubSpamRecordCache creates a new instance of GossipSubSpamRecordCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGossipSubSpamRecordCache(t interface { - mock.TestingT - Cleanup(func()) -}) *GossipSubSpamRecordCache { - mock := &GossipSubSpamRecordCache{} - mock.Mock.Test(t) +// GossipSubSpamRecordCache_Has_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Has' +type GossipSubSpamRecordCache_Has_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Has is a helper method to define mock.On call +// - peerID peer.ID +func (_e *GossipSubSpamRecordCache_Expecter) Has(peerID interface{}) *GossipSubSpamRecordCache_Has_Call { + return &GossipSubSpamRecordCache_Has_Call{Call: _e.mock.On("Has", peerID)} +} - return mock +func (_c *GossipSubSpamRecordCache_Has_Call) Run(run func(peerID peer.ID)) *GossipSubSpamRecordCache_Has_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *GossipSubSpamRecordCache_Has_Call) Return(b bool) *GossipSubSpamRecordCache_Has_Call { + _c.Call.Return(b) + return _c +} + +func (_c *GossipSubSpamRecordCache_Has_Call) RunAndReturn(run func(peerID peer.ID) bool) *GossipSubSpamRecordCache_Has_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/id_translator.go b/network/p2p/mock/id_translator.go index f4d536b9f55..314c1e367ce 100644 --- a/network/p2p/mock/id_translator.go +++ b/network/p2p/mock/id_translator.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewIDTranslator creates a new instance of IDTranslator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIDTranslator(t interface { + mock.TestingT + Cleanup(func()) +}) *IDTranslator { + mock := &IDTranslator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // IDTranslator is an autogenerated mock type for the IDTranslator type type IDTranslator struct { mock.Mock } -// GetFlowID provides a mock function with given fields: _a0 -func (_m *IDTranslator) GetFlowID(_a0 peer.ID) (flow.Identifier, error) { - ret := _m.Called(_a0) +type IDTranslator_Expecter struct { + mock *mock.Mock +} + +func (_m *IDTranslator) EXPECT() *IDTranslator_Expecter { + return &IDTranslator_Expecter{mock: &_m.Mock} +} + +// GetFlowID provides a mock function for the type IDTranslator +func (_mock *IDTranslator) GetFlowID(iD peer.ID) (flow.Identifier, error) { + ret := _mock.Called(iD) if len(ret) == 0 { panic("no return value specified for GetFlowID") @@ -24,29 +47,61 @@ func (_m *IDTranslator) GetFlowID(_a0 peer.ID) (flow.Identifier, error) { var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(peer.ID) (flow.Identifier, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (flow.Identifier, error)); ok { + return returnFunc(iD) } - if rf, ok := ret.Get(0).(func(peer.ID) flow.Identifier); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(peer.ID) flow.Identifier); ok { + r0 = returnFunc(iD) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(peer.ID) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(peer.ID) error); ok { + r1 = returnFunc(iD) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetPeerID provides a mock function with given fields: _a0 -func (_m *IDTranslator) GetPeerID(_a0 flow.Identifier) (peer.ID, error) { - ret := _m.Called(_a0) +// IDTranslator_GetFlowID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFlowID' +type IDTranslator_GetFlowID_Call struct { + *mock.Call +} + +// GetFlowID is a helper method to define mock.On call +// - iD peer.ID +func (_e *IDTranslator_Expecter) GetFlowID(iD interface{}) *IDTranslator_GetFlowID_Call { + return &IDTranslator_GetFlowID_Call{Call: _e.mock.On("GetFlowID", iD)} +} + +func (_c *IDTranslator_GetFlowID_Call) Run(run func(iD peer.ID)) *IDTranslator_GetFlowID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IDTranslator_GetFlowID_Call) Return(identifier flow.Identifier, err error) *IDTranslator_GetFlowID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *IDTranslator_GetFlowID_Call) RunAndReturn(run func(iD peer.ID) (flow.Identifier, error)) *IDTranslator_GetFlowID_Call { + _c.Call.Return(run) + return _c +} + +// GetPeerID provides a mock function for the type IDTranslator +func (_mock *IDTranslator) GetPeerID(identifier flow.Identifier) (peer.ID, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for GetPeerID") @@ -54,34 +109,52 @@ func (_m *IDTranslator) GetPeerID(_a0 flow.Identifier) (peer.ID, error) { var r0 peer.ID var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (peer.ID, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (peer.ID, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) peer.ID); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) peer.ID); ok { + r0 = returnFunc(identifier) } else { r0 = ret.Get(0).(peer.ID) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewIDTranslator creates a new instance of IDTranslator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIDTranslator(t interface { - mock.TestingT - Cleanup(func()) -}) *IDTranslator { - mock := &IDTranslator{} - mock.Mock.Test(t) +// IDTranslator_GetPeerID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPeerID' +type IDTranslator_GetPeerID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetPeerID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *IDTranslator_Expecter) GetPeerID(identifier interface{}) *IDTranslator_GetPeerID_Call { + return &IDTranslator_GetPeerID_Call{Call: _e.mock.On("GetPeerID", identifier)} +} - return mock +func (_c *IDTranslator_GetPeerID_Call) Run(run func(identifier flow.Identifier)) *IDTranslator_GetPeerID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IDTranslator_GetPeerID_Call) Return(iD peer.ID, err error) *IDTranslator_GetPeerID_Call { + _c.Call.Return(iD, err) + return _c +} + +func (_c *IDTranslator_GetPeerID_Call) RunAndReturn(run func(identifier flow.Identifier) (peer.ID, error)) *IDTranslator_GetPeerID_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/lib_p2_p_node.go b/network/p2p/mock/lib_p2_p_node.go index 98b497bc0e8..11e006fd325 100644 --- a/network/p2p/mock/lib_p2_p_node.go +++ b/network/p2p/mock/lib_p2_p_node.go @@ -1,89 +1,201 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - component "github.com/onflow/flow-go/module/component" - channels "github.com/onflow/flow-go/network/channels" - - context "context" - - corenetwork "github.com/libp2p/go-libp2p/core/network" - - flow "github.com/onflow/flow-go/model/flow" + "context" + + "github.com/libp2p/go-libp2p-kbucket" + "github.com/libp2p/go-libp2p/core/host" + network0 "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/libp2p/go-libp2p/core/routing" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p" + "github.com/onflow/flow-go/network/p2p/unicast/protocols" + mock "github.com/stretchr/testify/mock" +) - host "github.com/libp2p/go-libp2p/core/host" +// NewLibP2PNode creates a new instance of LibP2PNode. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLibP2PNode(t interface { + mock.TestingT + Cleanup(func()) +}) *LibP2PNode { + mock := &LibP2PNode{} + mock.Mock.Test(t) - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + t.Cleanup(func() { mock.AssertExpectations(t) }) - kbucket "github.com/libp2p/go-libp2p-kbucket" + return mock +} - mock "github.com/stretchr/testify/mock" +// LibP2PNode is an autogenerated mock type for the LibP2PNode type +type LibP2PNode struct { + mock.Mock +} - network "github.com/onflow/flow-go/network" +type LibP2PNode_Expecter struct { + mock *mock.Mock +} - p2p "github.com/onflow/flow-go/network/p2p" +func (_m *LibP2PNode) EXPECT() *LibP2PNode_Expecter { + return &LibP2PNode_Expecter{mock: &_m.Mock} +} - peer "github.com/libp2p/go-libp2p/core/peer" +// ActiveClustersChanged provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) ActiveClustersChanged(chainIDList flow.ChainIDList) { + _mock.Called(chainIDList) + return +} - protocol "github.com/libp2p/go-libp2p/core/protocol" +// LibP2PNode_ActiveClustersChanged_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ActiveClustersChanged' +type LibP2PNode_ActiveClustersChanged_Call struct { + *mock.Call +} - protocols "github.com/onflow/flow-go/network/p2p/unicast/protocols" +// ActiveClustersChanged is a helper method to define mock.On call +// - chainIDList flow.ChainIDList +func (_e *LibP2PNode_Expecter) ActiveClustersChanged(chainIDList interface{}) *LibP2PNode_ActiveClustersChanged_Call { + return &LibP2PNode_ActiveClustersChanged_Call{Call: _e.mock.On("ActiveClustersChanged", chainIDList)} +} - routing "github.com/libp2p/go-libp2p/core/routing" -) +func (_c *LibP2PNode_ActiveClustersChanged_Call) Run(run func(chainIDList flow.ChainIDList)) *LibP2PNode_ActiveClustersChanged_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ChainIDList + if args[0] != nil { + arg0 = args[0].(flow.ChainIDList) + } + run( + arg0, + ) + }) + return _c +} -// LibP2PNode is an autogenerated mock type for the LibP2PNode type -type LibP2PNode struct { - mock.Mock +func (_c *LibP2PNode_ActiveClustersChanged_Call) Return() *LibP2PNode_ActiveClustersChanged_Call { + _c.Call.Return() + return _c } -// ActiveClustersChanged provides a mock function with given fields: _a0 -func (_m *LibP2PNode) ActiveClustersChanged(_a0 flow.ChainIDList) { - _m.Called(_a0) +func (_c *LibP2PNode_ActiveClustersChanged_Call) RunAndReturn(run func(chainIDList flow.ChainIDList)) *LibP2PNode_ActiveClustersChanged_Call { + _c.Run(run) + return _c } -// ConnectToPeer provides a mock function with given fields: ctx, peerInfo -func (_m *LibP2PNode) ConnectToPeer(ctx context.Context, peerInfo peer.AddrInfo) error { - ret := _m.Called(ctx, peerInfo) +// ConnectToPeer provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) ConnectToPeer(ctx context.Context, peerInfo peer.AddrInfo) error { + ret := _mock.Called(ctx, peerInfo) if len(ret) == 0 { panic("no return value specified for ConnectToPeer") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, peer.AddrInfo) error); ok { - r0 = rf(ctx, peerInfo) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.AddrInfo) error); ok { + r0 = returnFunc(ctx, peerInfo) } else { r0 = ret.Error(0) } - return r0 } -// Done provides a mock function with no fields -func (_m *LibP2PNode) Done() <-chan struct{} { - ret := _m.Called() +// LibP2PNode_ConnectToPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectToPeer' +type LibP2PNode_ConnectToPeer_Call struct { + *mock.Call +} + +// ConnectToPeer is a helper method to define mock.On call +// - ctx context.Context +// - peerInfo peer.AddrInfo +func (_e *LibP2PNode_Expecter) ConnectToPeer(ctx interface{}, peerInfo interface{}) *LibP2PNode_ConnectToPeer_Call { + return &LibP2PNode_ConnectToPeer_Call{Call: _e.mock.On("ConnectToPeer", ctx, peerInfo)} +} + +func (_c *LibP2PNode_ConnectToPeer_Call) Run(run func(ctx context.Context, peerInfo peer.AddrInfo)) *LibP2PNode_ConnectToPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.AddrInfo + if args[1] != nil { + arg1 = args[1].(peer.AddrInfo) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PNode_ConnectToPeer_Call) Return(err error) *LibP2PNode_ConnectToPeer_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_ConnectToPeer_Call) RunAndReturn(run func(ctx context.Context, peerInfo peer.AddrInfo) error) *LibP2PNode_ConnectToPeer_Call { + _c.Call.Return(run) + return _c +} + +// Done provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// GetIPPort provides a mock function with no fields -func (_m *LibP2PNode) GetIPPort() (string, string, error) { - ret := _m.Called() +// LibP2PNode_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type LibP2PNode_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) Done() *LibP2PNode_Done_Call { + return &LibP2PNode_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *LibP2PNode_Done_Call) Run(run func()) *LibP2PNode_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_Done_Call) Return(valCh <-chan struct{}) *LibP2PNode_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *LibP2PNode_Done_Call) RunAndReturn(run func() <-chan struct{}) *LibP2PNode_Done_Call { + _c.Call.Return(run) + return _c +} + +// GetIPPort provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) GetIPPort() (string, string, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetIPPort") @@ -92,129 +204,304 @@ func (_m *LibP2PNode) GetIPPort() (string, string, error) { var r0 string var r1 string var r2 error - if rf, ok := ret.Get(0).(func() (string, string, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (string, string, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func() string); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() string); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(string) } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetLocalMeshPeers provides a mock function with given fields: topic -func (_m *LibP2PNode) GetLocalMeshPeers(topic channels.Topic) []peer.ID { - ret := _m.Called(topic) +// LibP2PNode_GetIPPort_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIPPort' +type LibP2PNode_GetIPPort_Call struct { + *mock.Call +} + +// GetIPPort is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) GetIPPort() *LibP2PNode_GetIPPort_Call { + return &LibP2PNode_GetIPPort_Call{Call: _e.mock.On("GetIPPort")} +} + +func (_c *LibP2PNode_GetIPPort_Call) Run(run func()) *LibP2PNode_GetIPPort_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_GetIPPort_Call) Return(s string, s1 string, err error) *LibP2PNode_GetIPPort_Call { + _c.Call.Return(s, s1, err) + return _c +} + +func (_c *LibP2PNode_GetIPPort_Call) RunAndReturn(run func() (string, string, error)) *LibP2PNode_GetIPPort_Call { + _c.Call.Return(run) + return _c +} + +// GetLocalMeshPeers provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) GetLocalMeshPeers(topic channels.Topic) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for GetLocalMeshPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// GetPeersForProtocol provides a mock function with given fields: pid -func (_m *LibP2PNode) GetPeersForProtocol(pid protocol.ID) peer.IDSlice { - ret := _m.Called(pid) +// LibP2PNode_GetLocalMeshPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLocalMeshPeers' +type LibP2PNode_GetLocalMeshPeers_Call struct { + *mock.Call +} + +// GetLocalMeshPeers is a helper method to define mock.On call +// - topic channels.Topic +func (_e *LibP2PNode_Expecter) GetLocalMeshPeers(topic interface{}) *LibP2PNode_GetLocalMeshPeers_Call { + return &LibP2PNode_GetLocalMeshPeers_Call{Call: _e.mock.On("GetLocalMeshPeers", topic)} +} + +func (_c *LibP2PNode_GetLocalMeshPeers_Call) Run(run func(topic channels.Topic)) *LibP2PNode_GetLocalMeshPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_GetLocalMeshPeers_Call) Return(iDs []peer.ID) *LibP2PNode_GetLocalMeshPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *LibP2PNode_GetLocalMeshPeers_Call) RunAndReturn(run func(topic channels.Topic) []peer.ID) *LibP2PNode_GetLocalMeshPeers_Call { + _c.Call.Return(run) + return _c +} + +// GetPeersForProtocol provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) GetPeersForProtocol(pid protocol.ID) peer.IDSlice { + ret := _mock.Called(pid) if len(ret) == 0 { panic("no return value specified for GetPeersForProtocol") } var r0 peer.IDSlice - if rf, ok := ret.Get(0).(func(protocol.ID) peer.IDSlice); ok { - r0 = rf(pid) + if returnFunc, ok := ret.Get(0).(func(protocol.ID) peer.IDSlice); ok { + r0 = returnFunc(pid) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(peer.IDSlice) } } - return r0 } -// HasSubscription provides a mock function with given fields: topic -func (_m *LibP2PNode) HasSubscription(topic channels.Topic) bool { - ret := _m.Called(topic) +// LibP2PNode_GetPeersForProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPeersForProtocol' +type LibP2PNode_GetPeersForProtocol_Call struct { + *mock.Call +} + +// GetPeersForProtocol is a helper method to define mock.On call +// - pid protocol.ID +func (_e *LibP2PNode_Expecter) GetPeersForProtocol(pid interface{}) *LibP2PNode_GetPeersForProtocol_Call { + return &LibP2PNode_GetPeersForProtocol_Call{Call: _e.mock.On("GetPeersForProtocol", pid)} +} + +func (_c *LibP2PNode_GetPeersForProtocol_Call) Run(run func(pid protocol.ID)) *LibP2PNode_GetPeersForProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_GetPeersForProtocol_Call) Return(iDSlice peer.IDSlice) *LibP2PNode_GetPeersForProtocol_Call { + _c.Call.Return(iDSlice) + return _c +} + +func (_c *LibP2PNode_GetPeersForProtocol_Call) RunAndReturn(run func(pid protocol.ID) peer.IDSlice) *LibP2PNode_GetPeersForProtocol_Call { + _c.Call.Return(run) + return _c +} + +// HasSubscription provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) HasSubscription(topic channels.Topic) bool { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for HasSubscription") } var r0 bool - if rf, ok := ret.Get(0).(func(channels.Topic) bool); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) bool); ok { + r0 = returnFunc(topic) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Host provides a mock function with no fields -func (_m *LibP2PNode) Host() host.Host { - ret := _m.Called() +// LibP2PNode_HasSubscription_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasSubscription' +type LibP2PNode_HasSubscription_Call struct { + *mock.Call +} + +// HasSubscription is a helper method to define mock.On call +// - topic channels.Topic +func (_e *LibP2PNode_Expecter) HasSubscription(topic interface{}) *LibP2PNode_HasSubscription_Call { + return &LibP2PNode_HasSubscription_Call{Call: _e.mock.On("HasSubscription", topic)} +} + +func (_c *LibP2PNode_HasSubscription_Call) Run(run func(topic channels.Topic)) *LibP2PNode_HasSubscription_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_HasSubscription_Call) Return(b bool) *LibP2PNode_HasSubscription_Call { + _c.Call.Return(b) + return _c +} + +func (_c *LibP2PNode_HasSubscription_Call) RunAndReturn(run func(topic channels.Topic) bool) *LibP2PNode_HasSubscription_Call { + _c.Call.Return(run) + return _c +} + +// Host provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Host() host.Host { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Host") } var r0 host.Host - if rf, ok := ret.Get(0).(func() host.Host); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() host.Host); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(host.Host) } } - return r0 } -// ID provides a mock function with no fields -func (_m *LibP2PNode) ID() peer.ID { - ret := _m.Called() +// LibP2PNode_Host_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Host' +type LibP2PNode_Host_Call struct { + *mock.Call +} + +// Host is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) Host() *LibP2PNode_Host_Call { + return &LibP2PNode_Host_Call{Call: _e.mock.On("Host")} +} + +func (_c *LibP2PNode_Host_Call) Run(run func()) *LibP2PNode_Host_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_Host_Call) Return(host1 host.Host) *LibP2PNode_Host_Call { + _c.Call.Return(host1) + return _c +} + +func (_c *LibP2PNode_Host_Call) RunAndReturn(run func() host.Host) *LibP2PNode_Host_Call { + _c.Call.Return(run) + return _c +} + +// ID provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) ID() peer.ID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 peer.ID - if rf, ok := ret.Get(0).(func() peer.ID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() peer.ID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(peer.ID) } - return r0 } -// IsConnected provides a mock function with given fields: peerID -func (_m *LibP2PNode) IsConnected(peerID peer.ID) (bool, error) { - ret := _m.Called(peerID) +// LibP2PNode_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type LibP2PNode_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) ID() *LibP2PNode_ID_Call { + return &LibP2PNode_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *LibP2PNode_ID_Call) Run(run func()) *LibP2PNode_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_ID_Call) Return(iD peer.ID) *LibP2PNode_ID_Call { + _c.Call.Return(iD) + return _c +} + +func (_c *LibP2PNode_ID_Call) RunAndReturn(run func() peer.ID) *LibP2PNode_ID_Call { + _c.Call.Return(run) + return _c +} + +// IsConnected provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) IsConnected(peerID peer.ID) (bool, error) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for IsConnected") @@ -222,27 +509,59 @@ func (_m *LibP2PNode) IsConnected(peerID peer.ID) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(peer.ID) (bool, error)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (bool, error)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) bool); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) bool); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(peer.ID) error); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) error); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Error(1) } - return r0, r1 } -// IsDisallowListed provides a mock function with given fields: peerId -func (_m *LibP2PNode) IsDisallowListed(peerId peer.ID) ([]network.DisallowListedCause, bool) { - ret := _m.Called(peerId) +// LibP2PNode_IsConnected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsConnected' +type LibP2PNode_IsConnected_Call struct { + *mock.Call +} + +// IsConnected is a helper method to define mock.On call +// - peerID peer.ID +func (_e *LibP2PNode_Expecter) IsConnected(peerID interface{}) *LibP2PNode_IsConnected_Call { + return &LibP2PNode_IsConnected_Call{Call: _e.mock.On("IsConnected", peerID)} +} + +func (_c *LibP2PNode_IsConnected_Call) Run(run func(peerID peer.ID)) *LibP2PNode_IsConnected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_IsConnected_Call) Return(b bool, err error) *LibP2PNode_IsConnected_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *LibP2PNode_IsConnected_Call) RunAndReturn(run func(peerID peer.ID) (bool, error)) *LibP2PNode_IsConnected_Call { + _c.Call.Return(run) + return _c +} + +// IsDisallowListed provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) IsDisallowListed(peerId peer.ID) ([]network.DisallowListedCause, bool) { + ret := _mock.Called(peerId) if len(ret) == 0 { panic("no return value specified for IsDisallowListed") @@ -250,274 +569,901 @@ func (_m *LibP2PNode) IsDisallowListed(peerId peer.ID) ([]network.DisallowListed var r0 []network.DisallowListedCause var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) ([]network.DisallowListedCause, bool)); ok { - return rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) ([]network.DisallowListedCause, bool)); ok { + return returnFunc(peerId) } - if rf, ok := ret.Get(0).(func(peer.ID) []network.DisallowListedCause); ok { - r0 = rf(peerId) + if returnFunc, ok := ret.Get(0).(func(peer.ID) []network.DisallowListedCause); ok { + r0 = returnFunc(peerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]network.DisallowListedCause) } } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerId) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerId) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// ListPeers provides a mock function with given fields: topic -func (_m *LibP2PNode) ListPeers(topic string) []peer.ID { - ret := _m.Called(topic) +// LibP2PNode_IsDisallowListed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsDisallowListed' +type LibP2PNode_IsDisallowListed_Call struct { + *mock.Call +} + +// IsDisallowListed is a helper method to define mock.On call +// - peerId peer.ID +func (_e *LibP2PNode_Expecter) IsDisallowListed(peerId interface{}) *LibP2PNode_IsDisallowListed_Call { + return &LibP2PNode_IsDisallowListed_Call{Call: _e.mock.On("IsDisallowListed", peerId)} +} + +func (_c *LibP2PNode_IsDisallowListed_Call) Run(run func(peerId peer.ID)) *LibP2PNode_IsDisallowListed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_IsDisallowListed_Call) Return(disallowListedCauses []network.DisallowListedCause, b bool) *LibP2PNode_IsDisallowListed_Call { + _c.Call.Return(disallowListedCauses, b) + return _c +} + +func (_c *LibP2PNode_IsDisallowListed_Call) RunAndReturn(run func(peerId peer.ID) ([]network.DisallowListedCause, bool)) *LibP2PNode_IsDisallowListed_Call { + _c.Call.Return(run) + return _c +} + +// ListPeers provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) ListPeers(topic string) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for ListPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(string) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(string) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// OnAllowListNotification provides a mock function with given fields: id, cause -func (_m *LibP2PNode) OnAllowListNotification(id peer.ID, cause network.DisallowListedCause) { - _m.Called(id, cause) +// LibP2PNode_ListPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPeers' +type LibP2PNode_ListPeers_Call struct { + *mock.Call +} + +// ListPeers is a helper method to define mock.On call +// - topic string +func (_e *LibP2PNode_Expecter) ListPeers(topic interface{}) *LibP2PNode_ListPeers_Call { + return &LibP2PNode_ListPeers_Call{Call: _e.mock.On("ListPeers", topic)} +} + +func (_c *LibP2PNode_ListPeers_Call) Run(run func(topic string)) *LibP2PNode_ListPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_ListPeers_Call) Return(iDs []peer.ID) *LibP2PNode_ListPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *LibP2PNode_ListPeers_Call) RunAndReturn(run func(topic string) []peer.ID) *LibP2PNode_ListPeers_Call { + _c.Call.Return(run) + return _c +} + +// OnAllowListNotification provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) OnAllowListNotification(id peer.ID, cause network.DisallowListedCause) { + _mock.Called(id, cause) + return +} + +// LibP2PNode_OnAllowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnAllowListNotification' +type LibP2PNode_OnAllowListNotification_Call struct { + *mock.Call +} + +// OnAllowListNotification is a helper method to define mock.On call +// - id peer.ID +// - cause network.DisallowListedCause +func (_e *LibP2PNode_Expecter) OnAllowListNotification(id interface{}, cause interface{}) *LibP2PNode_OnAllowListNotification_Call { + return &LibP2PNode_OnAllowListNotification_Call{Call: _e.mock.On("OnAllowListNotification", id, cause)} +} + +func (_c *LibP2PNode_OnAllowListNotification_Call) Run(run func(id peer.ID, cause network.DisallowListedCause)) *LibP2PNode_OnAllowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.DisallowListedCause + if args[1] != nil { + arg1 = args[1].(network.DisallowListedCause) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PNode_OnAllowListNotification_Call) Return() *LibP2PNode_OnAllowListNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PNode_OnAllowListNotification_Call) RunAndReturn(run func(id peer.ID, cause network.DisallowListedCause)) *LibP2PNode_OnAllowListNotification_Call { + _c.Run(run) + return _c +} + +// OnDisallowListNotification provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) OnDisallowListNotification(id peer.ID, cause network.DisallowListedCause) { + _mock.Called(id, cause) + return +} + +// LibP2PNode_OnDisallowListNotification_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnDisallowListNotification' +type LibP2PNode_OnDisallowListNotification_Call struct { + *mock.Call +} + +// OnDisallowListNotification is a helper method to define mock.On call +// - id peer.ID +// - cause network.DisallowListedCause +func (_e *LibP2PNode_Expecter) OnDisallowListNotification(id interface{}, cause interface{}) *LibP2PNode_OnDisallowListNotification_Call { + return &LibP2PNode_OnDisallowListNotification_Call{Call: _e.mock.On("OnDisallowListNotification", id, cause)} } -// OnDisallowListNotification provides a mock function with given fields: id, cause -func (_m *LibP2PNode) OnDisallowListNotification(id peer.ID, cause network.DisallowListedCause) { - _m.Called(id, cause) +func (_c *LibP2PNode_OnDisallowListNotification_Call) Run(run func(id peer.ID, cause network.DisallowListedCause)) *LibP2PNode_OnDisallowListNotification_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 network.DisallowListedCause + if args[1] != nil { + arg1 = args[1].(network.DisallowListedCause) + } + run( + arg0, + arg1, + ) + }) + return _c } -// OpenAndWriteOnStream provides a mock function with given fields: ctx, peerID, protectionTag, writingLogic -func (_m *LibP2PNode) OpenAndWriteOnStream(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(corenetwork.Stream) error) error { - ret := _m.Called(ctx, peerID, protectionTag, writingLogic) +func (_c *LibP2PNode_OnDisallowListNotification_Call) Return() *LibP2PNode_OnDisallowListNotification_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PNode_OnDisallowListNotification_Call) RunAndReturn(run func(id peer.ID, cause network.DisallowListedCause)) *LibP2PNode_OnDisallowListNotification_Call { + _c.Run(run) + return _c +} + +// OpenAndWriteOnStream provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) OpenAndWriteOnStream(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(stream network0.Stream) error) error { + ret := _mock.Called(ctx, peerID, protectionTag, writingLogic) if len(ret) == 0 { panic("no return value specified for OpenAndWriteOnStream") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, peer.ID, string, func(corenetwork.Stream) error) error); ok { - r0 = rf(ctx, peerID, protectionTag, writingLogic) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID, string, func(stream network0.Stream) error) error); ok { + r0 = returnFunc(ctx, peerID, protectionTag, writingLogic) } else { r0 = ret.Error(0) } - return r0 } -// PeerManagerComponent provides a mock function with no fields -func (_m *LibP2PNode) PeerManagerComponent() component.Component { - ret := _m.Called() +// LibP2PNode_OpenAndWriteOnStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OpenAndWriteOnStream' +type LibP2PNode_OpenAndWriteOnStream_Call struct { + *mock.Call +} + +// OpenAndWriteOnStream is a helper method to define mock.On call +// - ctx context.Context +// - peerID peer.ID +// - protectionTag string +// - writingLogic func(stream network0.Stream) error +func (_e *LibP2PNode_Expecter) OpenAndWriteOnStream(ctx interface{}, peerID interface{}, protectionTag interface{}, writingLogic interface{}) *LibP2PNode_OpenAndWriteOnStream_Call { + return &LibP2PNode_OpenAndWriteOnStream_Call{Call: _e.mock.On("OpenAndWriteOnStream", ctx, peerID, protectionTag, writingLogic)} +} + +func (_c *LibP2PNode_OpenAndWriteOnStream_Call) Run(run func(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(stream network0.Stream) error)) *LibP2PNode_OpenAndWriteOnStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 func(stream network0.Stream) error + if args[3] != nil { + arg3 = args[3].(func(stream network0.Stream) error) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *LibP2PNode_OpenAndWriteOnStream_Call) Return(err error) *LibP2PNode_OpenAndWriteOnStream_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_OpenAndWriteOnStream_Call) RunAndReturn(run func(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(stream network0.Stream) error) error) *LibP2PNode_OpenAndWriteOnStream_Call { + _c.Call.Return(run) + return _c +} + +// PeerManagerComponent provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) PeerManagerComponent() component.Component { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PeerManagerComponent") } var r0 component.Component - if rf, ok := ret.Get(0).(func() component.Component); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() component.Component); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(component.Component) } } - return r0 } -// PeerScoreExposer provides a mock function with no fields -func (_m *LibP2PNode) PeerScoreExposer() p2p.PeerScoreExposer { - ret := _m.Called() +// LibP2PNode_PeerManagerComponent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PeerManagerComponent' +type LibP2PNode_PeerManagerComponent_Call struct { + *mock.Call +} + +// PeerManagerComponent is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) PeerManagerComponent() *LibP2PNode_PeerManagerComponent_Call { + return &LibP2PNode_PeerManagerComponent_Call{Call: _e.mock.On("PeerManagerComponent")} +} + +func (_c *LibP2PNode_PeerManagerComponent_Call) Run(run func()) *LibP2PNode_PeerManagerComponent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_PeerManagerComponent_Call) Return(component1 component.Component) *LibP2PNode_PeerManagerComponent_Call { + _c.Call.Return(component1) + return _c +} + +func (_c *LibP2PNode_PeerManagerComponent_Call) RunAndReturn(run func() component.Component) *LibP2PNode_PeerManagerComponent_Call { + _c.Call.Return(run) + return _c +} + +// PeerScoreExposer provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) PeerScoreExposer() p2p.PeerScoreExposer { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PeerScoreExposer") } var r0 p2p.PeerScoreExposer - if rf, ok := ret.Get(0).(func() p2p.PeerScoreExposer); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() p2p.PeerScoreExposer); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.PeerScoreExposer) } } - return r0 } -// Publish provides a mock function with given fields: ctx, messageScope -func (_m *LibP2PNode) Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error { - ret := _m.Called(ctx, messageScope) +// LibP2PNode_PeerScoreExposer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PeerScoreExposer' +type LibP2PNode_PeerScoreExposer_Call struct { + *mock.Call +} + +// PeerScoreExposer is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) PeerScoreExposer() *LibP2PNode_PeerScoreExposer_Call { + return &LibP2PNode_PeerScoreExposer_Call{Call: _e.mock.On("PeerScoreExposer")} +} + +func (_c *LibP2PNode_PeerScoreExposer_Call) Run(run func()) *LibP2PNode_PeerScoreExposer_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_PeerScoreExposer_Call) Return(peerScoreExposer p2p.PeerScoreExposer) *LibP2PNode_PeerScoreExposer_Call { + _c.Call.Return(peerScoreExposer) + return _c +} + +func (_c *LibP2PNode_PeerScoreExposer_Call) RunAndReturn(run func() p2p.PeerScoreExposer) *LibP2PNode_PeerScoreExposer_Call { + _c.Call.Return(run) + return _c +} + +// Publish provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error { + ret := _mock.Called(ctx, messageScope) if len(ret) == 0 { panic("no return value specified for Publish") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, network.OutgoingMessageScope) error); ok { - r0 = rf(ctx, messageScope) + if returnFunc, ok := ret.Get(0).(func(context.Context, network.OutgoingMessageScope) error); ok { + r0 = returnFunc(ctx, messageScope) } else { r0 = ret.Error(0) } - return r0 } -// Ready provides a mock function with no fields -func (_m *LibP2PNode) Ready() <-chan struct{} { - ret := _m.Called() +// LibP2PNode_Publish_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Publish' +type LibP2PNode_Publish_Call struct { + *mock.Call +} + +// Publish is a helper method to define mock.On call +// - ctx context.Context +// - messageScope network.OutgoingMessageScope +func (_e *LibP2PNode_Expecter) Publish(ctx interface{}, messageScope interface{}) *LibP2PNode_Publish_Call { + return &LibP2PNode_Publish_Call{Call: _e.mock.On("Publish", ctx, messageScope)} +} + +func (_c *LibP2PNode_Publish_Call) Run(run func(ctx context.Context, messageScope network.OutgoingMessageScope)) *LibP2PNode_Publish_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 network.OutgoingMessageScope + if args[1] != nil { + arg1 = args[1].(network.OutgoingMessageScope) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PNode_Publish_Call) Return(err error) *LibP2PNode_Publish_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_Publish_Call) RunAndReturn(run func(ctx context.Context, messageScope network.OutgoingMessageScope) error) *LibP2PNode_Publish_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// RemovePeer provides a mock function with given fields: peerID -func (_m *LibP2PNode) RemovePeer(peerID peer.ID) error { - ret := _m.Called(peerID) +// LibP2PNode_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type LibP2PNode_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) Ready() *LibP2PNode_Ready_Call { + return &LibP2PNode_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *LibP2PNode_Ready_Call) Run(run func()) *LibP2PNode_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_Ready_Call) Return(valCh <-chan struct{}) *LibP2PNode_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *LibP2PNode_Ready_Call) RunAndReturn(run func() <-chan struct{}) *LibP2PNode_Ready_Call { + _c.Call.Return(run) + return _c +} + +// RemovePeer provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) RemovePeer(peerID peer.ID) error { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for RemovePeer") } var r0 error - if rf, ok := ret.Get(0).(func(peer.ID) error); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) error); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Error(0) } - return r0 } -// RequestPeerUpdate provides a mock function with no fields -func (_m *LibP2PNode) RequestPeerUpdate() { - _m.Called() +// LibP2PNode_RemovePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemovePeer' +type LibP2PNode_RemovePeer_Call struct { + *mock.Call +} + +// RemovePeer is a helper method to define mock.On call +// - peerID peer.ID +func (_e *LibP2PNode_Expecter) RemovePeer(peerID interface{}) *LibP2PNode_RemovePeer_Call { + return &LibP2PNode_RemovePeer_Call{Call: _e.mock.On("RemovePeer", peerID)} +} + +func (_c *LibP2PNode_RemovePeer_Call) Run(run func(peerID peer.ID)) *LibP2PNode_RemovePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_RemovePeer_Call) Return(err error) *LibP2PNode_RemovePeer_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_RemovePeer_Call) RunAndReturn(run func(peerID peer.ID) error) *LibP2PNode_RemovePeer_Call { + _c.Call.Return(run) + return _c +} + +// RequestPeerUpdate provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) RequestPeerUpdate() { + _mock.Called() + return +} + +// LibP2PNode_RequestPeerUpdate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestPeerUpdate' +type LibP2PNode_RequestPeerUpdate_Call struct { + *mock.Call } -// Routing provides a mock function with no fields -func (_m *LibP2PNode) Routing() routing.Routing { - ret := _m.Called() +// RequestPeerUpdate is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) RequestPeerUpdate() *LibP2PNode_RequestPeerUpdate_Call { + return &LibP2PNode_RequestPeerUpdate_Call{Call: _e.mock.On("RequestPeerUpdate")} +} + +func (_c *LibP2PNode_RequestPeerUpdate_Call) Run(run func()) *LibP2PNode_RequestPeerUpdate_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_RequestPeerUpdate_Call) Return() *LibP2PNode_RequestPeerUpdate_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PNode_RequestPeerUpdate_Call) RunAndReturn(run func()) *LibP2PNode_RequestPeerUpdate_Call { + _c.Run(run) + return _c +} + +// Routing provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Routing() routing.Routing { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Routing") } var r0 routing.Routing - if rf, ok := ret.Get(0).(func() routing.Routing); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() routing.Routing); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(routing.Routing) } } - return r0 } -// RoutingTable provides a mock function with no fields -func (_m *LibP2PNode) RoutingTable() *kbucket.RoutingTable { - ret := _m.Called() +// LibP2PNode_Routing_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Routing' +type LibP2PNode_Routing_Call struct { + *mock.Call +} + +// Routing is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) Routing() *LibP2PNode_Routing_Call { + return &LibP2PNode_Routing_Call{Call: _e.mock.On("Routing")} +} + +func (_c *LibP2PNode_Routing_Call) Run(run func()) *LibP2PNode_Routing_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_Routing_Call) Return(routing1 routing.Routing) *LibP2PNode_Routing_Call { + _c.Call.Return(routing1) + return _c +} + +func (_c *LibP2PNode_Routing_Call) RunAndReturn(run func() routing.Routing) *LibP2PNode_Routing_Call { + _c.Call.Return(run) + return _c +} + +// RoutingTable provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) RoutingTable() *kbucket.RoutingTable { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RoutingTable") } var r0 *kbucket.RoutingTable - if rf, ok := ret.Get(0).(func() *kbucket.RoutingTable); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *kbucket.RoutingTable); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*kbucket.RoutingTable) } } - return r0 } -// SetComponentManager provides a mock function with given fields: cm -func (_m *LibP2PNode) SetComponentManager(cm *component.ComponentManager) { - _m.Called(cm) +// LibP2PNode_RoutingTable_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTable' +type LibP2PNode_RoutingTable_Call struct { + *mock.Call +} + +// RoutingTable is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) RoutingTable() *LibP2PNode_RoutingTable_Call { + return &LibP2PNode_RoutingTable_Call{Call: _e.mock.On("RoutingTable")} +} + +func (_c *LibP2PNode_RoutingTable_Call) Run(run func()) *LibP2PNode_RoutingTable_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_RoutingTable_Call) Return(routingTable *kbucket.RoutingTable) *LibP2PNode_RoutingTable_Call { + _c.Call.Return(routingTable) + return _c +} + +func (_c *LibP2PNode_RoutingTable_Call) RunAndReturn(run func() *kbucket.RoutingTable) *LibP2PNode_RoutingTable_Call { + _c.Call.Return(run) + return _c +} + +// SetComponentManager provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) SetComponentManager(cm *component.ComponentManager) { + _mock.Called(cm) + return +} + +// LibP2PNode_SetComponentManager_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetComponentManager' +type LibP2PNode_SetComponentManager_Call struct { + *mock.Call +} + +// SetComponentManager is a helper method to define mock.On call +// - cm *component.ComponentManager +func (_e *LibP2PNode_Expecter) SetComponentManager(cm interface{}) *LibP2PNode_SetComponentManager_Call { + return &LibP2PNode_SetComponentManager_Call{Call: _e.mock.On("SetComponentManager", cm)} +} + +func (_c *LibP2PNode_SetComponentManager_Call) Run(run func(cm *component.ComponentManager)) *LibP2PNode_SetComponentManager_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *component.ComponentManager + if args[0] != nil { + arg0 = args[0].(*component.ComponentManager) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_SetComponentManager_Call) Return() *LibP2PNode_SetComponentManager_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PNode_SetComponentManager_Call) RunAndReturn(run func(cm *component.ComponentManager)) *LibP2PNode_SetComponentManager_Call { + _c.Run(run) + return _c +} + +// SetPubSub provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) SetPubSub(ps p2p.PubSubAdapter) { + _mock.Called(ps) + return +} + +// LibP2PNode_SetPubSub_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetPubSub' +type LibP2PNode_SetPubSub_Call struct { + *mock.Call +} + +// SetPubSub is a helper method to define mock.On call +// - ps p2p.PubSubAdapter +func (_e *LibP2PNode_Expecter) SetPubSub(ps interface{}) *LibP2PNode_SetPubSub_Call { + return &LibP2PNode_SetPubSub_Call{Call: _e.mock.On("SetPubSub", ps)} +} + +func (_c *LibP2PNode_SetPubSub_Call) Run(run func(ps p2p.PubSubAdapter)) *LibP2PNode_SetPubSub_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.PubSubAdapter + if args[0] != nil { + arg0 = args[0].(p2p.PubSubAdapter) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_SetPubSub_Call) Return() *LibP2PNode_SetPubSub_Call { + _c.Call.Return() + return _c } -// SetPubSub provides a mock function with given fields: ps -func (_m *LibP2PNode) SetPubSub(ps p2p.PubSubAdapter) { - _m.Called(ps) +func (_c *LibP2PNode_SetPubSub_Call) RunAndReturn(run func(ps p2p.PubSubAdapter)) *LibP2PNode_SetPubSub_Call { + _c.Run(run) + return _c } -// SetRouting provides a mock function with given fields: r -func (_m *LibP2PNode) SetRouting(r routing.Routing) error { - ret := _m.Called(r) +// SetRouting provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) SetRouting(r routing.Routing) error { + ret := _mock.Called(r) if len(ret) == 0 { panic("no return value specified for SetRouting") } var r0 error - if rf, ok := ret.Get(0).(func(routing.Routing) error); ok { - r0 = rf(r) + if returnFunc, ok := ret.Get(0).(func(routing.Routing) error); ok { + r0 = returnFunc(r) } else { r0 = ret.Error(0) } - return r0 } -// SetUnicastManager provides a mock function with given fields: uniMgr -func (_m *LibP2PNode) SetUnicastManager(uniMgr p2p.UnicastManager) { - _m.Called(uniMgr) +// LibP2PNode_SetRouting_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetRouting' +type LibP2PNode_SetRouting_Call struct { + *mock.Call +} + +// SetRouting is a helper method to define mock.On call +// - r routing.Routing +func (_e *LibP2PNode_Expecter) SetRouting(r interface{}) *LibP2PNode_SetRouting_Call { + return &LibP2PNode_SetRouting_Call{Call: _e.mock.On("SetRouting", r)} +} + +func (_c *LibP2PNode_SetRouting_Call) Run(run func(r routing.Routing)) *LibP2PNode_SetRouting_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 routing.Routing + if args[0] != nil { + arg0 = args[0].(routing.Routing) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_SetRouting_Call) Return(err error) *LibP2PNode_SetRouting_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_SetRouting_Call) RunAndReturn(run func(r routing.Routing) error) *LibP2PNode_SetRouting_Call { + _c.Call.Return(run) + return _c +} + +// SetUnicastManager provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) SetUnicastManager(uniMgr p2p.UnicastManager) { + _mock.Called(uniMgr) + return +} + +// LibP2PNode_SetUnicastManager_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetUnicastManager' +type LibP2PNode_SetUnicastManager_Call struct { + *mock.Call +} + +// SetUnicastManager is a helper method to define mock.On call +// - uniMgr p2p.UnicastManager +func (_e *LibP2PNode_Expecter) SetUnicastManager(uniMgr interface{}) *LibP2PNode_SetUnicastManager_Call { + return &LibP2PNode_SetUnicastManager_Call{Call: _e.mock.On("SetUnicastManager", uniMgr)} +} + +func (_c *LibP2PNode_SetUnicastManager_Call) Run(run func(uniMgr p2p.UnicastManager)) *LibP2PNode_SetUnicastManager_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.UnicastManager + if args[0] != nil { + arg0 = args[0].(p2p.UnicastManager) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_SetUnicastManager_Call) Return() *LibP2PNode_SetUnicastManager_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PNode_SetUnicastManager_Call) RunAndReturn(run func(uniMgr p2p.UnicastManager)) *LibP2PNode_SetUnicastManager_Call { + _c.Run(run) + return _c } -// Start provides a mock function with given fields: ctx -func (_m *LibP2PNode) Start(ctx irrecoverable.SignalerContext) { - _m.Called(ctx) +// Start provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Start(ctx irrecoverable.SignalerContext) { + _mock.Called(ctx) + return } -// Stop provides a mock function with no fields -func (_m *LibP2PNode) Stop() error { - ret := _m.Called() +// LibP2PNode_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type LibP2PNode_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - ctx irrecoverable.SignalerContext +func (_e *LibP2PNode_Expecter) Start(ctx interface{}) *LibP2PNode_Start_Call { + return &LibP2PNode_Start_Call{Call: _e.mock.On("Start", ctx)} +} + +func (_c *LibP2PNode_Start_Call) Run(run func(ctx irrecoverable.SignalerContext)) *LibP2PNode_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_Start_Call) Return() *LibP2PNode_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PNode_Start_Call) RunAndReturn(run func(ctx irrecoverable.SignalerContext)) *LibP2PNode_Start_Call { + _c.Run(run) + return _c +} + +// Stop provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Stop() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Stop") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Subscribe provides a mock function with given fields: topic, topicValidator -func (_m *LibP2PNode) Subscribe(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error) { - ret := _m.Called(topic, topicValidator) +// LibP2PNode_Stop_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Stop' +type LibP2PNode_Stop_Call struct { + *mock.Call +} + +// Stop is a helper method to define mock.On call +func (_e *LibP2PNode_Expecter) Stop() *LibP2PNode_Stop_Call { + return &LibP2PNode_Stop_Call{Call: _e.mock.On("Stop")} +} + +func (_c *LibP2PNode_Stop_Call) Run(run func()) *LibP2PNode_Stop_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LibP2PNode_Stop_Call) Return(err error) *LibP2PNode_Stop_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_Stop_Call) RunAndReturn(run func() error) *LibP2PNode_Stop_Call { + _c.Call.Return(run) + return _c +} + +// Subscribe provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Subscribe(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error) { + ret := _mock.Called(topic, topicValidator) if len(ret) == 0 { panic("no return value specified for Subscribe") @@ -525,77 +1471,208 @@ func (_m *LibP2PNode) Subscribe(topic channels.Topic, topicValidator p2p.TopicVa var r0 p2p.Subscription var r1 error - if rf, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) (p2p.Subscription, error)); ok { - return rf(topic, topicValidator) + if returnFunc, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) (p2p.Subscription, error)); ok { + return returnFunc(topic, topicValidator) } - if rf, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) p2p.Subscription); ok { - r0 = rf(topic, topicValidator) + if returnFunc, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) p2p.Subscription); ok { + r0 = returnFunc(topic, topicValidator) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.Subscription) } } - - if rf, ok := ret.Get(1).(func(channels.Topic, p2p.TopicValidatorFunc) error); ok { - r1 = rf(topic, topicValidator) + if returnFunc, ok := ret.Get(1).(func(channels.Topic, p2p.TopicValidatorFunc) error); ok { + r1 = returnFunc(topic, topicValidator) } else { r1 = ret.Error(1) } - return r0, r1 } -// Unsubscribe provides a mock function with given fields: topic -func (_m *LibP2PNode) Unsubscribe(topic channels.Topic) error { - ret := _m.Called(topic) +// LibP2PNode_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' +type LibP2PNode_Subscribe_Call struct { + *mock.Call +} + +// Subscribe is a helper method to define mock.On call +// - topic channels.Topic +// - topicValidator p2p.TopicValidatorFunc +func (_e *LibP2PNode_Expecter) Subscribe(topic interface{}, topicValidator interface{}) *LibP2PNode_Subscribe_Call { + return &LibP2PNode_Subscribe_Call{Call: _e.mock.On("Subscribe", topic, topicValidator)} +} + +func (_c *LibP2PNode_Subscribe_Call) Run(run func(topic channels.Topic, topicValidator p2p.TopicValidatorFunc)) *LibP2PNode_Subscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 p2p.TopicValidatorFunc + if args[1] != nil { + arg1 = args[1].(p2p.TopicValidatorFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LibP2PNode_Subscribe_Call) Return(subscription p2p.Subscription, err error) *LibP2PNode_Subscribe_Call { + _c.Call.Return(subscription, err) + return _c +} + +func (_c *LibP2PNode_Subscribe_Call) RunAndReturn(run func(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error)) *LibP2PNode_Subscribe_Call { + _c.Call.Return(run) + return _c +} + +// Unsubscribe provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) Unsubscribe(topic channels.Topic) error { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for Unsubscribe") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Topic) error); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) error); ok { + r0 = returnFunc(topic) } else { r0 = ret.Error(0) } - return r0 } -// WithDefaultUnicastProtocol provides a mock function with given fields: defaultHandler, preferred -func (_m *LibP2PNode) WithDefaultUnicastProtocol(defaultHandler corenetwork.StreamHandler, preferred []protocols.ProtocolName) error { - ret := _m.Called(defaultHandler, preferred) +// LibP2PNode_Unsubscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Unsubscribe' +type LibP2PNode_Unsubscribe_Call struct { + *mock.Call +} + +// Unsubscribe is a helper method to define mock.On call +// - topic channels.Topic +func (_e *LibP2PNode_Expecter) Unsubscribe(topic interface{}) *LibP2PNode_Unsubscribe_Call { + return &LibP2PNode_Unsubscribe_Call{Call: _e.mock.On("Unsubscribe", topic)} +} + +func (_c *LibP2PNode_Unsubscribe_Call) Run(run func(topic channels.Topic)) *LibP2PNode_Unsubscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_Unsubscribe_Call) Return(err error) *LibP2PNode_Unsubscribe_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_Unsubscribe_Call) RunAndReturn(run func(topic channels.Topic) error) *LibP2PNode_Unsubscribe_Call { + _c.Call.Return(run) + return _c +} + +// WithDefaultUnicastProtocol provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) WithDefaultUnicastProtocol(defaultHandler network0.StreamHandler, preferred []protocols.ProtocolName) error { + ret := _mock.Called(defaultHandler, preferred) if len(ret) == 0 { panic("no return value specified for WithDefaultUnicastProtocol") } var r0 error - if rf, ok := ret.Get(0).(func(corenetwork.StreamHandler, []protocols.ProtocolName) error); ok { - r0 = rf(defaultHandler, preferred) + if returnFunc, ok := ret.Get(0).(func(network0.StreamHandler, []protocols.ProtocolName) error); ok { + r0 = returnFunc(defaultHandler, preferred) } else { r0 = ret.Error(0) } - return r0 } -// WithPeersProvider provides a mock function with given fields: peersProvider -func (_m *LibP2PNode) WithPeersProvider(peersProvider p2p.PeersProvider) { - _m.Called(peersProvider) +// LibP2PNode_WithDefaultUnicastProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithDefaultUnicastProtocol' +type LibP2PNode_WithDefaultUnicastProtocol_Call struct { + *mock.Call } -// NewLibP2PNode creates a new instance of LibP2PNode. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLibP2PNode(t interface { - mock.TestingT - Cleanup(func()) -}) *LibP2PNode { - mock := &LibP2PNode{} - mock.Mock.Test(t) +// WithDefaultUnicastProtocol is a helper method to define mock.On call +// - defaultHandler network0.StreamHandler +// - preferred []protocols.ProtocolName +func (_e *LibP2PNode_Expecter) WithDefaultUnicastProtocol(defaultHandler interface{}, preferred interface{}) *LibP2PNode_WithDefaultUnicastProtocol_Call { + return &LibP2PNode_WithDefaultUnicastProtocol_Call{Call: _e.mock.On("WithDefaultUnicastProtocol", defaultHandler, preferred)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *LibP2PNode_WithDefaultUnicastProtocol_Call) Run(run func(defaultHandler network0.StreamHandler, preferred []protocols.ProtocolName)) *LibP2PNode_WithDefaultUnicastProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network0.StreamHandler + if args[0] != nil { + arg0 = args[0].(network0.StreamHandler) + } + var arg1 []protocols.ProtocolName + if args[1] != nil { + arg1 = args[1].([]protocols.ProtocolName) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return mock +func (_c *LibP2PNode_WithDefaultUnicastProtocol_Call) Return(err error) *LibP2PNode_WithDefaultUnicastProtocol_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LibP2PNode_WithDefaultUnicastProtocol_Call) RunAndReturn(run func(defaultHandler network0.StreamHandler, preferred []protocols.ProtocolName) error) *LibP2PNode_WithDefaultUnicastProtocol_Call { + _c.Call.Return(run) + return _c +} + +// WithPeersProvider provides a mock function for the type LibP2PNode +func (_mock *LibP2PNode) WithPeersProvider(peersProvider p2p.PeersProvider) { + _mock.Called(peersProvider) + return +} + +// LibP2PNode_WithPeersProvider_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithPeersProvider' +type LibP2PNode_WithPeersProvider_Call struct { + *mock.Call +} + +// WithPeersProvider is a helper method to define mock.On call +// - peersProvider p2p.PeersProvider +func (_e *LibP2PNode_Expecter) WithPeersProvider(peersProvider interface{}) *LibP2PNode_WithPeersProvider_Call { + return &LibP2PNode_WithPeersProvider_Call{Call: _e.mock.On("WithPeersProvider", peersProvider)} +} + +func (_c *LibP2PNode_WithPeersProvider_Call) Run(run func(peersProvider p2p.PeersProvider)) *LibP2PNode_WithPeersProvider_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.PeersProvider + if args[0] != nil { + arg0 = args[0].(p2p.PeersProvider) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LibP2PNode_WithPeersProvider_Call) Return() *LibP2PNode_WithPeersProvider_Call { + _c.Call.Return() + return _c +} + +func (_c *LibP2PNode_WithPeersProvider_Call) RunAndReturn(run func(peersProvider p2p.PeersProvider)) *LibP2PNode_WithPeersProvider_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/node_builder.go b/network/p2p/mock/node_builder.go index a8c1595ee39..49b31c355c2 100644 --- a/network/p2p/mock/node_builder.go +++ b/network/p2p/mock/node_builder.go @@ -1,35 +1,52 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - connmgr "github.com/libp2p/go-libp2p/core/connmgr" - - host "github.com/libp2p/go-libp2p/core/host" - - madns "github.com/multiformats/go-multiaddr-dns" - + "context" + + "github.com/libp2p/go-libp2p-pubsub" + "github.com/libp2p/go-libp2p/core/connmgr" + "github.com/libp2p/go-libp2p/core/host" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/routing" + "github.com/multiformats/go-multiaddr-dns" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) - network "github.com/libp2p/go-libp2p/core/network" - - p2p "github.com/onflow/flow-go/network/p2p" +// NewNodeBuilder creates a new instance of NodeBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNodeBuilder(t interface { + mock.TestingT + Cleanup(func()) +}) *NodeBuilder { + mock := &NodeBuilder{} + mock.Mock.Test(t) - pubsub "github.com/libp2p/go-libp2p-pubsub" + t.Cleanup(func() { mock.AssertExpectations(t) }) - routing "github.com/libp2p/go-libp2p/core/routing" -) + return mock +} // NodeBuilder is an autogenerated mock type for the NodeBuilder type type NodeBuilder struct { mock.Mock } -// Build provides a mock function with no fields -func (_m *NodeBuilder) Build() (p2p.LibP2PNode, error) { - ret := _m.Called() +type NodeBuilder_Expecter struct { + mock *mock.Mock +} + +func (_m *NodeBuilder) EXPECT() *NodeBuilder_Expecter { + return &NodeBuilder_Expecter{mock: &_m.Mock} +} + +// Build provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) Build() (p2p.LibP2PNode, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Build") @@ -37,256 +54,636 @@ func (_m *NodeBuilder) Build() (p2p.LibP2PNode, error) { var r0 p2p.LibP2PNode var r1 error - if rf, ok := ret.Get(0).(func() (p2p.LibP2PNode, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (p2p.LibP2PNode, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() p2p.LibP2PNode); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() p2p.LibP2PNode); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.LibP2PNode) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// OverrideDefaultRpcInspectorFactory provides a mock function with given fields: _a0 -func (_m *NodeBuilder) OverrideDefaultRpcInspectorFactory(_a0 p2p.GossipSubRpcInspectorFactoryFunc) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build' +type NodeBuilder_Build_Call struct { + *mock.Call +} + +// Build is a helper method to define mock.On call +func (_e *NodeBuilder_Expecter) Build() *NodeBuilder_Build_Call { + return &NodeBuilder_Build_Call{Call: _e.mock.On("Build")} +} + +func (_c *NodeBuilder_Build_Call) Run(run func()) *NodeBuilder_Build_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NodeBuilder_Build_Call) Return(libP2PNode p2p.LibP2PNode, err error) *NodeBuilder_Build_Call { + _c.Call.Return(libP2PNode, err) + return _c +} + +func (_c *NodeBuilder_Build_Call) RunAndReturn(run func() (p2p.LibP2PNode, error)) *NodeBuilder_Build_Call { + _c.Call.Return(run) + return _c +} + +// OverrideDefaultRpcInspectorFactory provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) OverrideDefaultRpcInspectorFactory(gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc) p2p.NodeBuilder { + ret := _mock.Called(gossipSubRpcInspectorFactoryFunc) if len(ret) == 0 { panic("no return value specified for OverrideDefaultRpcInspectorFactory") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(p2p.GossipSubRpcInspectorFactoryFunc) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(p2p.GossipSubRpcInspectorFactoryFunc) p2p.NodeBuilder); ok { + r0 = returnFunc(gossipSubRpcInspectorFactoryFunc) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// OverrideDefaultValidateQueueSize provides a mock function with given fields: _a0 -func (_m *NodeBuilder) OverrideDefaultValidateQueueSize(_a0 int) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_OverrideDefaultRpcInspectorFactory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OverrideDefaultRpcInspectorFactory' +type NodeBuilder_OverrideDefaultRpcInspectorFactory_Call struct { + *mock.Call +} + +// OverrideDefaultRpcInspectorFactory is a helper method to define mock.On call +// - gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc +func (_e *NodeBuilder_Expecter) OverrideDefaultRpcInspectorFactory(gossipSubRpcInspectorFactoryFunc interface{}) *NodeBuilder_OverrideDefaultRpcInspectorFactory_Call { + return &NodeBuilder_OverrideDefaultRpcInspectorFactory_Call{Call: _e.mock.On("OverrideDefaultRpcInspectorFactory", gossipSubRpcInspectorFactoryFunc)} +} + +func (_c *NodeBuilder_OverrideDefaultRpcInspectorFactory_Call) Run(run func(gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc)) *NodeBuilder_OverrideDefaultRpcInspectorFactory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.GossipSubRpcInspectorFactoryFunc + if args[0] != nil { + arg0 = args[0].(p2p.GossipSubRpcInspectorFactoryFunc) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_OverrideDefaultRpcInspectorFactory_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_OverrideDefaultRpcInspectorFactory_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_OverrideDefaultRpcInspectorFactory_Call) RunAndReturn(run func(gossipSubRpcInspectorFactoryFunc p2p.GossipSubRpcInspectorFactoryFunc) p2p.NodeBuilder) *NodeBuilder_OverrideDefaultRpcInspectorFactory_Call { + _c.Call.Return(run) + return _c +} + +// OverrideDefaultValidateQueueSize provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) OverrideDefaultValidateQueueSize(n int) p2p.NodeBuilder { + ret := _mock.Called(n) if len(ret) == 0 { panic("no return value specified for OverrideDefaultValidateQueueSize") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(int) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(int) p2p.NodeBuilder); ok { + r0 = returnFunc(n) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// OverrideGossipSubFactory provides a mock function with given fields: _a0, _a1 -func (_m *NodeBuilder) OverrideGossipSubFactory(_a0 p2p.GossipSubFactoryFunc, _a1 p2p.GossipSubAdapterConfigFunc) p2p.NodeBuilder { - ret := _m.Called(_a0, _a1) +// NodeBuilder_OverrideDefaultValidateQueueSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OverrideDefaultValidateQueueSize' +type NodeBuilder_OverrideDefaultValidateQueueSize_Call struct { + *mock.Call +} + +// OverrideDefaultValidateQueueSize is a helper method to define mock.On call +// - n int +func (_e *NodeBuilder_Expecter) OverrideDefaultValidateQueueSize(n interface{}) *NodeBuilder_OverrideDefaultValidateQueueSize_Call { + return &NodeBuilder_OverrideDefaultValidateQueueSize_Call{Call: _e.mock.On("OverrideDefaultValidateQueueSize", n)} +} + +func (_c *NodeBuilder_OverrideDefaultValidateQueueSize_Call) Run(run func(n int)) *NodeBuilder_OverrideDefaultValidateQueueSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_OverrideDefaultValidateQueueSize_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_OverrideDefaultValidateQueueSize_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_OverrideDefaultValidateQueueSize_Call) RunAndReturn(run func(n int) p2p.NodeBuilder) *NodeBuilder_OverrideDefaultValidateQueueSize_Call { + _c.Call.Return(run) + return _c +} + +// OverrideGossipSubFactory provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) OverrideGossipSubFactory(gossipSubFactoryFunc p2p.GossipSubFactoryFunc, gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc) p2p.NodeBuilder { + ret := _mock.Called(gossipSubFactoryFunc, gossipSubAdapterConfigFunc) if len(ret) == 0 { panic("no return value specified for OverrideGossipSubFactory") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(p2p.GossipSubFactoryFunc, p2p.GossipSubAdapterConfigFunc) p2p.NodeBuilder); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(p2p.GossipSubFactoryFunc, p2p.GossipSubAdapterConfigFunc) p2p.NodeBuilder); ok { + r0 = returnFunc(gossipSubFactoryFunc, gossipSubAdapterConfigFunc) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// OverrideGossipSubScoringConfig provides a mock function with given fields: _a0 -func (_m *NodeBuilder) OverrideGossipSubScoringConfig(_a0 *p2p.PeerScoringConfigOverride) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_OverrideGossipSubFactory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OverrideGossipSubFactory' +type NodeBuilder_OverrideGossipSubFactory_Call struct { + *mock.Call +} + +// OverrideGossipSubFactory is a helper method to define mock.On call +// - gossipSubFactoryFunc p2p.GossipSubFactoryFunc +// - gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc +func (_e *NodeBuilder_Expecter) OverrideGossipSubFactory(gossipSubFactoryFunc interface{}, gossipSubAdapterConfigFunc interface{}) *NodeBuilder_OverrideGossipSubFactory_Call { + return &NodeBuilder_OverrideGossipSubFactory_Call{Call: _e.mock.On("OverrideGossipSubFactory", gossipSubFactoryFunc, gossipSubAdapterConfigFunc)} +} + +func (_c *NodeBuilder_OverrideGossipSubFactory_Call) Run(run func(gossipSubFactoryFunc p2p.GossipSubFactoryFunc, gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc)) *NodeBuilder_OverrideGossipSubFactory_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.GossipSubFactoryFunc + if args[0] != nil { + arg0 = args[0].(p2p.GossipSubFactoryFunc) + } + var arg1 p2p.GossipSubAdapterConfigFunc + if args[1] != nil { + arg1 = args[1].(p2p.GossipSubAdapterConfigFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NodeBuilder_OverrideGossipSubFactory_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_OverrideGossipSubFactory_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_OverrideGossipSubFactory_Call) RunAndReturn(run func(gossipSubFactoryFunc p2p.GossipSubFactoryFunc, gossipSubAdapterConfigFunc p2p.GossipSubAdapterConfigFunc) p2p.NodeBuilder) *NodeBuilder_OverrideGossipSubFactory_Call { + _c.Call.Return(run) + return _c +} + +// OverrideGossipSubScoringConfig provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) OverrideGossipSubScoringConfig(peerScoringConfigOverride *p2p.PeerScoringConfigOverride) p2p.NodeBuilder { + ret := _mock.Called(peerScoringConfigOverride) if len(ret) == 0 { panic("no return value specified for OverrideGossipSubScoringConfig") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(*p2p.PeerScoringConfigOverride) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*p2p.PeerScoringConfigOverride) p2p.NodeBuilder); ok { + r0 = returnFunc(peerScoringConfigOverride) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// OverrideNodeConstructor provides a mock function with given fields: _a0 -func (_m *NodeBuilder) OverrideNodeConstructor(_a0 p2p.NodeConstructor) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_OverrideGossipSubScoringConfig_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OverrideGossipSubScoringConfig' +type NodeBuilder_OverrideGossipSubScoringConfig_Call struct { + *mock.Call +} + +// OverrideGossipSubScoringConfig is a helper method to define mock.On call +// - peerScoringConfigOverride *p2p.PeerScoringConfigOverride +func (_e *NodeBuilder_Expecter) OverrideGossipSubScoringConfig(peerScoringConfigOverride interface{}) *NodeBuilder_OverrideGossipSubScoringConfig_Call { + return &NodeBuilder_OverrideGossipSubScoringConfig_Call{Call: _e.mock.On("OverrideGossipSubScoringConfig", peerScoringConfigOverride)} +} + +func (_c *NodeBuilder_OverrideGossipSubScoringConfig_Call) Run(run func(peerScoringConfigOverride *p2p.PeerScoringConfigOverride)) *NodeBuilder_OverrideGossipSubScoringConfig_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *p2p.PeerScoringConfigOverride + if args[0] != nil { + arg0 = args[0].(*p2p.PeerScoringConfigOverride) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_OverrideGossipSubScoringConfig_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_OverrideGossipSubScoringConfig_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_OverrideGossipSubScoringConfig_Call) RunAndReturn(run func(peerScoringConfigOverride *p2p.PeerScoringConfigOverride) p2p.NodeBuilder) *NodeBuilder_OverrideGossipSubScoringConfig_Call { + _c.Call.Return(run) + return _c +} + +// OverrideNodeConstructor provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) OverrideNodeConstructor(nodeConstructor p2p.NodeConstructor) p2p.NodeBuilder { + ret := _mock.Called(nodeConstructor) if len(ret) == 0 { panic("no return value specified for OverrideNodeConstructor") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(p2p.NodeConstructor) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(p2p.NodeConstructor) p2p.NodeBuilder); ok { + r0 = returnFunc(nodeConstructor) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// SetBasicResolver provides a mock function with given fields: _a0 -func (_m *NodeBuilder) SetBasicResolver(_a0 madns.BasicResolver) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_OverrideNodeConstructor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OverrideNodeConstructor' +type NodeBuilder_OverrideNodeConstructor_Call struct { + *mock.Call +} + +// OverrideNodeConstructor is a helper method to define mock.On call +// - nodeConstructor p2p.NodeConstructor +func (_e *NodeBuilder_Expecter) OverrideNodeConstructor(nodeConstructor interface{}) *NodeBuilder_OverrideNodeConstructor_Call { + return &NodeBuilder_OverrideNodeConstructor_Call{Call: _e.mock.On("OverrideNodeConstructor", nodeConstructor)} +} + +func (_c *NodeBuilder_OverrideNodeConstructor_Call) Run(run func(nodeConstructor p2p.NodeConstructor)) *NodeBuilder_OverrideNodeConstructor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.NodeConstructor + if args[0] != nil { + arg0 = args[0].(p2p.NodeConstructor) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_OverrideNodeConstructor_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_OverrideNodeConstructor_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_OverrideNodeConstructor_Call) RunAndReturn(run func(nodeConstructor p2p.NodeConstructor) p2p.NodeBuilder) *NodeBuilder_OverrideNodeConstructor_Call { + _c.Call.Return(run) + return _c +} + +// SetBasicResolver provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) SetBasicResolver(basicResolver madns.BasicResolver) p2p.NodeBuilder { + ret := _mock.Called(basicResolver) if len(ret) == 0 { panic("no return value specified for SetBasicResolver") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(madns.BasicResolver) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(madns.BasicResolver) p2p.NodeBuilder); ok { + r0 = returnFunc(basicResolver) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// SetConnectionGater provides a mock function with given fields: _a0 -func (_m *NodeBuilder) SetConnectionGater(_a0 p2p.ConnectionGater) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_SetBasicResolver_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetBasicResolver' +type NodeBuilder_SetBasicResolver_Call struct { + *mock.Call +} + +// SetBasicResolver is a helper method to define mock.On call +// - basicResolver madns.BasicResolver +func (_e *NodeBuilder_Expecter) SetBasicResolver(basicResolver interface{}) *NodeBuilder_SetBasicResolver_Call { + return &NodeBuilder_SetBasicResolver_Call{Call: _e.mock.On("SetBasicResolver", basicResolver)} +} + +func (_c *NodeBuilder_SetBasicResolver_Call) Run(run func(basicResolver madns.BasicResolver)) *NodeBuilder_SetBasicResolver_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 madns.BasicResolver + if args[0] != nil { + arg0 = args[0].(madns.BasicResolver) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_SetBasicResolver_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_SetBasicResolver_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_SetBasicResolver_Call) RunAndReturn(run func(basicResolver madns.BasicResolver) p2p.NodeBuilder) *NodeBuilder_SetBasicResolver_Call { + _c.Call.Return(run) + return _c +} + +// SetConnectionGater provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) SetConnectionGater(connectionGater p2p.ConnectionGater) p2p.NodeBuilder { + ret := _mock.Called(connectionGater) if len(ret) == 0 { panic("no return value specified for SetConnectionGater") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(p2p.ConnectionGater) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(p2p.ConnectionGater) p2p.NodeBuilder); ok { + r0 = returnFunc(connectionGater) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// SetConnectionManager provides a mock function with given fields: _a0 -func (_m *NodeBuilder) SetConnectionManager(_a0 connmgr.ConnManager) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_SetConnectionGater_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetConnectionGater' +type NodeBuilder_SetConnectionGater_Call struct { + *mock.Call +} + +// SetConnectionGater is a helper method to define mock.On call +// - connectionGater p2p.ConnectionGater +func (_e *NodeBuilder_Expecter) SetConnectionGater(connectionGater interface{}) *NodeBuilder_SetConnectionGater_Call { + return &NodeBuilder_SetConnectionGater_Call{Call: _e.mock.On("SetConnectionGater", connectionGater)} +} + +func (_c *NodeBuilder_SetConnectionGater_Call) Run(run func(connectionGater p2p.ConnectionGater)) *NodeBuilder_SetConnectionGater_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.ConnectionGater + if args[0] != nil { + arg0 = args[0].(p2p.ConnectionGater) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_SetConnectionGater_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_SetConnectionGater_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_SetConnectionGater_Call) RunAndReturn(run func(connectionGater p2p.ConnectionGater) p2p.NodeBuilder) *NodeBuilder_SetConnectionGater_Call { + _c.Call.Return(run) + return _c +} + +// SetConnectionManager provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) SetConnectionManager(connManager connmgr.ConnManager) p2p.NodeBuilder { + ret := _mock.Called(connManager) if len(ret) == 0 { panic("no return value specified for SetConnectionManager") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(connmgr.ConnManager) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(connmgr.ConnManager) p2p.NodeBuilder); ok { + r0 = returnFunc(connManager) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// SetResourceManager provides a mock function with given fields: _a0 -func (_m *NodeBuilder) SetResourceManager(_a0 network.ResourceManager) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_SetConnectionManager_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetConnectionManager' +type NodeBuilder_SetConnectionManager_Call struct { + *mock.Call +} + +// SetConnectionManager is a helper method to define mock.On call +// - connManager connmgr.ConnManager +func (_e *NodeBuilder_Expecter) SetConnectionManager(connManager interface{}) *NodeBuilder_SetConnectionManager_Call { + return &NodeBuilder_SetConnectionManager_Call{Call: _e.mock.On("SetConnectionManager", connManager)} +} + +func (_c *NodeBuilder_SetConnectionManager_Call) Run(run func(connManager connmgr.ConnManager)) *NodeBuilder_SetConnectionManager_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 connmgr.ConnManager + if args[0] != nil { + arg0 = args[0].(connmgr.ConnManager) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_SetConnectionManager_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_SetConnectionManager_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_SetConnectionManager_Call) RunAndReturn(run func(connManager connmgr.ConnManager) p2p.NodeBuilder) *NodeBuilder_SetConnectionManager_Call { + _c.Call.Return(run) + return _c +} + +// SetResourceManager provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) SetResourceManager(resourceManager network.ResourceManager) p2p.NodeBuilder { + ret := _mock.Called(resourceManager) if len(ret) == 0 { panic("no return value specified for SetResourceManager") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(network.ResourceManager) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(network.ResourceManager) p2p.NodeBuilder); ok { + r0 = returnFunc(resourceManager) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// SetRoutingSystem provides a mock function with given fields: _a0 -func (_m *NodeBuilder) SetRoutingSystem(_a0 func(context.Context, host.Host) (routing.Routing, error)) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_SetResourceManager_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetResourceManager' +type NodeBuilder_SetResourceManager_Call struct { + *mock.Call +} + +// SetResourceManager is a helper method to define mock.On call +// - resourceManager network.ResourceManager +func (_e *NodeBuilder_Expecter) SetResourceManager(resourceManager interface{}) *NodeBuilder_SetResourceManager_Call { + return &NodeBuilder_SetResourceManager_Call{Call: _e.mock.On("SetResourceManager", resourceManager)} +} + +func (_c *NodeBuilder_SetResourceManager_Call) Run(run func(resourceManager network.ResourceManager)) *NodeBuilder_SetResourceManager_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.ResourceManager + if args[0] != nil { + arg0 = args[0].(network.ResourceManager) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_SetResourceManager_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_SetResourceManager_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_SetResourceManager_Call) RunAndReturn(run func(resourceManager network.ResourceManager) p2p.NodeBuilder) *NodeBuilder_SetResourceManager_Call { + _c.Call.Return(run) + return _c +} + +// SetRoutingSystem provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) SetRoutingSystem(fn func(context.Context, host.Host) (routing.Routing, error)) p2p.NodeBuilder { + ret := _mock.Called(fn) if len(ret) == 0 { panic("no return value specified for SetRoutingSystem") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(func(context.Context, host.Host) (routing.Routing, error)) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(func(context.Context, host.Host) (routing.Routing, error)) p2p.NodeBuilder); ok { + r0 = returnFunc(fn) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// SetSubscriptionFilter provides a mock function with given fields: _a0 -func (_m *NodeBuilder) SetSubscriptionFilter(_a0 pubsub.SubscriptionFilter) p2p.NodeBuilder { - ret := _m.Called(_a0) +// NodeBuilder_SetRoutingSystem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetRoutingSystem' +type NodeBuilder_SetRoutingSystem_Call struct { + *mock.Call +} + +// SetRoutingSystem is a helper method to define mock.On call +// - fn func(context.Context, host.Host) (routing.Routing, error) +func (_e *NodeBuilder_Expecter) SetRoutingSystem(fn interface{}) *NodeBuilder_SetRoutingSystem_Call { + return &NodeBuilder_SetRoutingSystem_Call{Call: _e.mock.On("SetRoutingSystem", fn)} +} + +func (_c *NodeBuilder_SetRoutingSystem_Call) Run(run func(fn func(context.Context, host.Host) (routing.Routing, error))) *NodeBuilder_SetRoutingSystem_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(context.Context, host.Host) (routing.Routing, error) + if args[0] != nil { + arg0 = args[0].(func(context.Context, host.Host) (routing.Routing, error)) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_SetRoutingSystem_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_SetRoutingSystem_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_SetRoutingSystem_Call) RunAndReturn(run func(fn func(context.Context, host.Host) (routing.Routing, error)) p2p.NodeBuilder) *NodeBuilder_SetRoutingSystem_Call { + _c.Call.Return(run) + return _c +} + +// SetSubscriptionFilter provides a mock function for the type NodeBuilder +func (_mock *NodeBuilder) SetSubscriptionFilter(subscriptionFilter pubsub.SubscriptionFilter) p2p.NodeBuilder { + ret := _mock.Called(subscriptionFilter) if len(ret) == 0 { panic("no return value specified for SetSubscriptionFilter") } var r0 p2p.NodeBuilder - if rf, ok := ret.Get(0).(func(pubsub.SubscriptionFilter) p2p.NodeBuilder); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(pubsub.SubscriptionFilter) p2p.NodeBuilder); ok { + r0 = returnFunc(subscriptionFilter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.NodeBuilder) } } - return r0 } -// NewNodeBuilder creates a new instance of NodeBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNodeBuilder(t interface { - mock.TestingT - Cleanup(func()) -}) *NodeBuilder { - mock := &NodeBuilder{} - mock.Mock.Test(t) +// NodeBuilder_SetSubscriptionFilter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetSubscriptionFilter' +type NodeBuilder_SetSubscriptionFilter_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SetSubscriptionFilter is a helper method to define mock.On call +// - subscriptionFilter pubsub.SubscriptionFilter +func (_e *NodeBuilder_Expecter) SetSubscriptionFilter(subscriptionFilter interface{}) *NodeBuilder_SetSubscriptionFilter_Call { + return &NodeBuilder_SetSubscriptionFilter_Call{Call: _e.mock.On("SetSubscriptionFilter", subscriptionFilter)} +} - return mock +func (_c *NodeBuilder_SetSubscriptionFilter_Call) Run(run func(subscriptionFilter pubsub.SubscriptionFilter)) *NodeBuilder_SetSubscriptionFilter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 pubsub.SubscriptionFilter + if args[0] != nil { + arg0 = args[0].(pubsub.SubscriptionFilter) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeBuilder_SetSubscriptionFilter_Call) Return(nodeBuilder p2p.NodeBuilder) *NodeBuilder_SetSubscriptionFilter_Call { + _c.Call.Return(nodeBuilder) + return _c +} + +func (_c *NodeBuilder_SetSubscriptionFilter_Call) RunAndReturn(run func(subscriptionFilter pubsub.SubscriptionFilter) p2p.NodeBuilder) *NodeBuilder_SetSubscriptionFilter_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/peer_connections.go b/network/p2p/mock/peer_connections.go index cd7b4348ecf..2a375f1f69d 100644 --- a/network/p2p/mock/peer_connections.go +++ b/network/p2p/mock/peer_connections.go @@ -1,21 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewPeerConnections creates a new instance of PeerConnections. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeerConnections(t interface { + mock.TestingT + Cleanup(func()) +}) *PeerConnections { + mock := &PeerConnections{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // PeerConnections is an autogenerated mock type for the PeerConnections type type PeerConnections struct { mock.Mock } -// IsConnected provides a mock function with given fields: peerID -func (_m *PeerConnections) IsConnected(peerID peer.ID) (bool, error) { - ret := _m.Called(peerID) +type PeerConnections_Expecter struct { + mock *mock.Mock +} + +func (_m *PeerConnections) EXPECT() *PeerConnections_Expecter { + return &PeerConnections_Expecter{mock: &_m.Mock} +} + +// IsConnected provides a mock function for the type PeerConnections +func (_mock *PeerConnections) IsConnected(peerID peer.ID) (bool, error) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for IsConnected") @@ -23,34 +46,52 @@ func (_m *PeerConnections) IsConnected(peerID peer.ID) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(peer.ID) (bool, error)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (bool, error)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) bool); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) bool); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(peer.ID) error); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) error); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewPeerConnections creates a new instance of PeerConnections. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPeerConnections(t interface { - mock.TestingT - Cleanup(func()) -}) *PeerConnections { - mock := &PeerConnections{} - mock.Mock.Test(t) +// PeerConnections_IsConnected_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsConnected' +type PeerConnections_IsConnected_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// IsConnected is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerConnections_Expecter) IsConnected(peerID interface{}) *PeerConnections_IsConnected_Call { + return &PeerConnections_IsConnected_Call{Call: _e.mock.On("IsConnected", peerID)} +} - return mock +func (_c *PeerConnections_IsConnected_Call) Run(run func(peerID peer.ID)) *PeerConnections_IsConnected_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerConnections_IsConnected_Call) Return(b bool, err error) *PeerConnections_IsConnected_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *PeerConnections_IsConnected_Call) RunAndReturn(run func(peerID peer.ID) (bool, error)) *PeerConnections_IsConnected_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/peer_management.go b/network/p2p/mock/peer_management.go index 0149b5028af..516d453df70 100644 --- a/network/p2p/mock/peer_management.go +++ b/network/p2p/mock/peer_management.go @@ -1,58 +1,112 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - component "github.com/onflow/flow-go/module/component" - channels "github.com/onflow/flow-go/network/channels" - - context "context" - - corenetwork "github.com/libp2p/go-libp2p/core/network" - - host "github.com/libp2p/go-libp2p/core/host" - - kbucket "github.com/libp2p/go-libp2p-kbucket" - + "context" + + "github.com/libp2p/go-libp2p-kbucket" + "github.com/libp2p/go-libp2p/core/host" + network0 "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/onflow/flow-go/module/component" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p" + "github.com/onflow/flow-go/network/p2p/unicast/protocols" mock "github.com/stretchr/testify/mock" +) - network "github.com/onflow/flow-go/network" - - p2p "github.com/onflow/flow-go/network/p2p" - - peer "github.com/libp2p/go-libp2p/core/peer" +// NewPeerManagement creates a new instance of PeerManagement. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeerManagement(t interface { + mock.TestingT + Cleanup(func()) +}) *PeerManagement { + mock := &PeerManagement{} + mock.Mock.Test(t) - protocol "github.com/libp2p/go-libp2p/core/protocol" + t.Cleanup(func() { mock.AssertExpectations(t) }) - protocols "github.com/onflow/flow-go/network/p2p/unicast/protocols" -) + return mock +} // PeerManagement is an autogenerated mock type for the PeerManagement type type PeerManagement struct { mock.Mock } -// ConnectToPeer provides a mock function with given fields: ctx, peerInfo -func (_m *PeerManagement) ConnectToPeer(ctx context.Context, peerInfo peer.AddrInfo) error { - ret := _m.Called(ctx, peerInfo) +type PeerManagement_Expecter struct { + mock *mock.Mock +} + +func (_m *PeerManagement) EXPECT() *PeerManagement_Expecter { + return &PeerManagement_Expecter{mock: &_m.Mock} +} + +// ConnectToPeer provides a mock function for the type PeerManagement +func (_mock *PeerManagement) ConnectToPeer(ctx context.Context, peerInfo peer.AddrInfo) error { + ret := _mock.Called(ctx, peerInfo) if len(ret) == 0 { panic("no return value specified for ConnectToPeer") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, peer.AddrInfo) error); ok { - r0 = rf(ctx, peerInfo) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.AddrInfo) error); ok { + r0 = returnFunc(ctx, peerInfo) } else { r0 = ret.Error(0) } - return r0 } -// GetIPPort provides a mock function with no fields -func (_m *PeerManagement) GetIPPort() (string, string, error) { - ret := _m.Called() +// PeerManagement_ConnectToPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConnectToPeer' +type PeerManagement_ConnectToPeer_Call struct { + *mock.Call +} + +// ConnectToPeer is a helper method to define mock.On call +// - ctx context.Context +// - peerInfo peer.AddrInfo +func (_e *PeerManagement_Expecter) ConnectToPeer(ctx interface{}, peerInfo interface{}) *PeerManagement_ConnectToPeer_Call { + return &PeerManagement_ConnectToPeer_Call{Call: _e.mock.On("ConnectToPeer", ctx, peerInfo)} +} + +func (_c *PeerManagement_ConnectToPeer_Call) Run(run func(ctx context.Context, peerInfo peer.AddrInfo)) *PeerManagement_ConnectToPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.AddrInfo + if args[1] != nil { + arg1 = args[1].(peer.AddrInfo) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PeerManagement_ConnectToPeer_Call) Return(err error) *PeerManagement_ConnectToPeer_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PeerManagement_ConnectToPeer_Call) RunAndReturn(run func(ctx context.Context, peerInfo peer.AddrInfo) error) *PeerManagement_ConnectToPeer_Call { + _c.Call.Return(run) + return _c +} + +// GetIPPort provides a mock function for the type PeerManagement +func (_mock *PeerManagement) GetIPPort() (string, string, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetIPPort") @@ -61,192 +115,486 @@ func (_m *PeerManagement) GetIPPort() (string, string, error) { var r0 string var r1 string var r2 error - if rf, ok := ret.Get(0).(func() (string, string, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (string, string, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - - if rf, ok := ret.Get(1).(func() string); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() string); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(string) } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// GetPeersForProtocol provides a mock function with given fields: pid -func (_m *PeerManagement) GetPeersForProtocol(pid protocol.ID) peer.IDSlice { - ret := _m.Called(pid) +// PeerManagement_GetIPPort_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIPPort' +type PeerManagement_GetIPPort_Call struct { + *mock.Call +} + +// GetIPPort is a helper method to define mock.On call +func (_e *PeerManagement_Expecter) GetIPPort() *PeerManagement_GetIPPort_Call { + return &PeerManagement_GetIPPort_Call{Call: _e.mock.On("GetIPPort")} +} + +func (_c *PeerManagement_GetIPPort_Call) Run(run func()) *PeerManagement_GetIPPort_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManagement_GetIPPort_Call) Return(s string, s1 string, err error) *PeerManagement_GetIPPort_Call { + _c.Call.Return(s, s1, err) + return _c +} + +func (_c *PeerManagement_GetIPPort_Call) RunAndReturn(run func() (string, string, error)) *PeerManagement_GetIPPort_Call { + _c.Call.Return(run) + return _c +} + +// GetPeersForProtocol provides a mock function for the type PeerManagement +func (_mock *PeerManagement) GetPeersForProtocol(pid protocol.ID) peer.IDSlice { + ret := _mock.Called(pid) if len(ret) == 0 { panic("no return value specified for GetPeersForProtocol") } var r0 peer.IDSlice - if rf, ok := ret.Get(0).(func(protocol.ID) peer.IDSlice); ok { - r0 = rf(pid) + if returnFunc, ok := ret.Get(0).(func(protocol.ID) peer.IDSlice); ok { + r0 = returnFunc(pid) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(peer.IDSlice) } } - return r0 } -// Host provides a mock function with no fields -func (_m *PeerManagement) Host() host.Host { - ret := _m.Called() +// PeerManagement_GetPeersForProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPeersForProtocol' +type PeerManagement_GetPeersForProtocol_Call struct { + *mock.Call +} + +// GetPeersForProtocol is a helper method to define mock.On call +// - pid protocol.ID +func (_e *PeerManagement_Expecter) GetPeersForProtocol(pid interface{}) *PeerManagement_GetPeersForProtocol_Call { + return &PeerManagement_GetPeersForProtocol_Call{Call: _e.mock.On("GetPeersForProtocol", pid)} +} + +func (_c *PeerManagement_GetPeersForProtocol_Call) Run(run func(pid protocol.ID)) *PeerManagement_GetPeersForProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManagement_GetPeersForProtocol_Call) Return(iDSlice peer.IDSlice) *PeerManagement_GetPeersForProtocol_Call { + _c.Call.Return(iDSlice) + return _c +} + +func (_c *PeerManagement_GetPeersForProtocol_Call) RunAndReturn(run func(pid protocol.ID) peer.IDSlice) *PeerManagement_GetPeersForProtocol_Call { + _c.Call.Return(run) + return _c +} + +// Host provides a mock function for the type PeerManagement +func (_mock *PeerManagement) Host() host.Host { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Host") } var r0 host.Host - if rf, ok := ret.Get(0).(func() host.Host); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() host.Host); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(host.Host) } } - return r0 } -// ID provides a mock function with no fields -func (_m *PeerManagement) ID() peer.ID { - ret := _m.Called() +// PeerManagement_Host_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Host' +type PeerManagement_Host_Call struct { + *mock.Call +} + +// Host is a helper method to define mock.On call +func (_e *PeerManagement_Expecter) Host() *PeerManagement_Host_Call { + return &PeerManagement_Host_Call{Call: _e.mock.On("Host")} +} + +func (_c *PeerManagement_Host_Call) Run(run func()) *PeerManagement_Host_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManagement_Host_Call) Return(host1 host.Host) *PeerManagement_Host_Call { + _c.Call.Return(host1) + return _c +} + +func (_c *PeerManagement_Host_Call) RunAndReturn(run func() host.Host) *PeerManagement_Host_Call { + _c.Call.Return(run) + return _c +} + +// ID provides a mock function for the type PeerManagement +func (_mock *PeerManagement) ID() peer.ID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 peer.ID - if rf, ok := ret.Get(0).(func() peer.ID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() peer.ID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(peer.ID) } - return r0 } -// ListPeers provides a mock function with given fields: topic -func (_m *PeerManagement) ListPeers(topic string) []peer.ID { - ret := _m.Called(topic) +// PeerManagement_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type PeerManagement_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *PeerManagement_Expecter) ID() *PeerManagement_ID_Call { + return &PeerManagement_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *PeerManagement_ID_Call) Run(run func()) *PeerManagement_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManagement_ID_Call) Return(iD peer.ID) *PeerManagement_ID_Call { + _c.Call.Return(iD) + return _c +} + +func (_c *PeerManagement_ID_Call) RunAndReturn(run func() peer.ID) *PeerManagement_ID_Call { + _c.Call.Return(run) + return _c +} + +// ListPeers provides a mock function for the type PeerManagement +func (_mock *PeerManagement) ListPeers(topic string) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for ListPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(string) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(string) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// PeerManagerComponent provides a mock function with no fields -func (_m *PeerManagement) PeerManagerComponent() component.Component { - ret := _m.Called() +// PeerManagement_ListPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPeers' +type PeerManagement_ListPeers_Call struct { + *mock.Call +} + +// ListPeers is a helper method to define mock.On call +// - topic string +func (_e *PeerManagement_Expecter) ListPeers(topic interface{}) *PeerManagement_ListPeers_Call { + return &PeerManagement_ListPeers_Call{Call: _e.mock.On("ListPeers", topic)} +} + +func (_c *PeerManagement_ListPeers_Call) Run(run func(topic string)) *PeerManagement_ListPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManagement_ListPeers_Call) Return(iDs []peer.ID) *PeerManagement_ListPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *PeerManagement_ListPeers_Call) RunAndReturn(run func(topic string) []peer.ID) *PeerManagement_ListPeers_Call { + _c.Call.Return(run) + return _c +} + +// PeerManagerComponent provides a mock function for the type PeerManagement +func (_mock *PeerManagement) PeerManagerComponent() component.Component { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PeerManagerComponent") } var r0 component.Component - if rf, ok := ret.Get(0).(func() component.Component); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() component.Component); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(component.Component) } } - return r0 } -// Publish provides a mock function with given fields: ctx, messageScope -func (_m *PeerManagement) Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error { - ret := _m.Called(ctx, messageScope) +// PeerManagement_PeerManagerComponent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PeerManagerComponent' +type PeerManagement_PeerManagerComponent_Call struct { + *mock.Call +} + +// PeerManagerComponent is a helper method to define mock.On call +func (_e *PeerManagement_Expecter) PeerManagerComponent() *PeerManagement_PeerManagerComponent_Call { + return &PeerManagement_PeerManagerComponent_Call{Call: _e.mock.On("PeerManagerComponent")} +} + +func (_c *PeerManagement_PeerManagerComponent_Call) Run(run func()) *PeerManagement_PeerManagerComponent_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManagement_PeerManagerComponent_Call) Return(component1 component.Component) *PeerManagement_PeerManagerComponent_Call { + _c.Call.Return(component1) + return _c +} + +func (_c *PeerManagement_PeerManagerComponent_Call) RunAndReturn(run func() component.Component) *PeerManagement_PeerManagerComponent_Call { + _c.Call.Return(run) + return _c +} + +// Publish provides a mock function for the type PeerManagement +func (_mock *PeerManagement) Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error { + ret := _mock.Called(ctx, messageScope) if len(ret) == 0 { panic("no return value specified for Publish") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, network.OutgoingMessageScope) error); ok { - r0 = rf(ctx, messageScope) + if returnFunc, ok := ret.Get(0).(func(context.Context, network.OutgoingMessageScope) error); ok { + r0 = returnFunc(ctx, messageScope) } else { r0 = ret.Error(0) } - return r0 } -// RemovePeer provides a mock function with given fields: peerID -func (_m *PeerManagement) RemovePeer(peerID peer.ID) error { - ret := _m.Called(peerID) +// PeerManagement_Publish_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Publish' +type PeerManagement_Publish_Call struct { + *mock.Call +} + +// Publish is a helper method to define mock.On call +// - ctx context.Context +// - messageScope network.OutgoingMessageScope +func (_e *PeerManagement_Expecter) Publish(ctx interface{}, messageScope interface{}) *PeerManagement_Publish_Call { + return &PeerManagement_Publish_Call{Call: _e.mock.On("Publish", ctx, messageScope)} +} + +func (_c *PeerManagement_Publish_Call) Run(run func(ctx context.Context, messageScope network.OutgoingMessageScope)) *PeerManagement_Publish_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 network.OutgoingMessageScope + if args[1] != nil { + arg1 = args[1].(network.OutgoingMessageScope) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PeerManagement_Publish_Call) Return(err error) *PeerManagement_Publish_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PeerManagement_Publish_Call) RunAndReturn(run func(ctx context.Context, messageScope network.OutgoingMessageScope) error) *PeerManagement_Publish_Call { + _c.Call.Return(run) + return _c +} + +// RemovePeer provides a mock function for the type PeerManagement +func (_mock *PeerManagement) RemovePeer(peerID peer.ID) error { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for RemovePeer") } var r0 error - if rf, ok := ret.Get(0).(func(peer.ID) error); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) error); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Error(0) } - return r0 } -// RequestPeerUpdate provides a mock function with no fields -func (_m *PeerManagement) RequestPeerUpdate() { - _m.Called() +// PeerManagement_RemovePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemovePeer' +type PeerManagement_RemovePeer_Call struct { + *mock.Call +} + +// RemovePeer is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerManagement_Expecter) RemovePeer(peerID interface{}) *PeerManagement_RemovePeer_Call { + return &PeerManagement_RemovePeer_Call{Call: _e.mock.On("RemovePeer", peerID)} +} + +func (_c *PeerManagement_RemovePeer_Call) Run(run func(peerID peer.ID)) *PeerManagement_RemovePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManagement_RemovePeer_Call) Return(err error) *PeerManagement_RemovePeer_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PeerManagement_RemovePeer_Call) RunAndReturn(run func(peerID peer.ID) error) *PeerManagement_RemovePeer_Call { + _c.Call.Return(run) + return _c +} + +// RequestPeerUpdate provides a mock function for the type PeerManagement +func (_mock *PeerManagement) RequestPeerUpdate() { + _mock.Called() + return +} + +// PeerManagement_RequestPeerUpdate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestPeerUpdate' +type PeerManagement_RequestPeerUpdate_Call struct { + *mock.Call } -// RoutingTable provides a mock function with no fields -func (_m *PeerManagement) RoutingTable() *kbucket.RoutingTable { - ret := _m.Called() +// RequestPeerUpdate is a helper method to define mock.On call +func (_e *PeerManagement_Expecter) RequestPeerUpdate() *PeerManagement_RequestPeerUpdate_Call { + return &PeerManagement_RequestPeerUpdate_Call{Call: _e.mock.On("RequestPeerUpdate")} +} + +func (_c *PeerManagement_RequestPeerUpdate_Call) Run(run func()) *PeerManagement_RequestPeerUpdate_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManagement_RequestPeerUpdate_Call) Return() *PeerManagement_RequestPeerUpdate_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerManagement_RequestPeerUpdate_Call) RunAndReturn(run func()) *PeerManagement_RequestPeerUpdate_Call { + _c.Run(run) + return _c +} + +// RoutingTable provides a mock function for the type PeerManagement +func (_mock *PeerManagement) RoutingTable() *kbucket.RoutingTable { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RoutingTable") } var r0 *kbucket.RoutingTable - if rf, ok := ret.Get(0).(func() *kbucket.RoutingTable); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *kbucket.RoutingTable); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*kbucket.RoutingTable) } } - return r0 } -// Subscribe provides a mock function with given fields: topic, topicValidator -func (_m *PeerManagement) Subscribe(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error) { - ret := _m.Called(topic, topicValidator) +// PeerManagement_RoutingTable_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTable' +type PeerManagement_RoutingTable_Call struct { + *mock.Call +} + +// RoutingTable is a helper method to define mock.On call +func (_e *PeerManagement_Expecter) RoutingTable() *PeerManagement_RoutingTable_Call { + return &PeerManagement_RoutingTable_Call{Call: _e.mock.On("RoutingTable")} +} + +func (_c *PeerManagement_RoutingTable_Call) Run(run func()) *PeerManagement_RoutingTable_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManagement_RoutingTable_Call) Return(routingTable *kbucket.RoutingTable) *PeerManagement_RoutingTable_Call { + _c.Call.Return(routingTable) + return _c +} + +func (_c *PeerManagement_RoutingTable_Call) RunAndReturn(run func() *kbucket.RoutingTable) *PeerManagement_RoutingTable_Call { + _c.Call.Return(run) + return _c +} + +// Subscribe provides a mock function for the type PeerManagement +func (_mock *PeerManagement) Subscribe(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error) { + ret := _mock.Called(topic, topicValidator) if len(ret) == 0 { panic("no return value specified for Subscribe") @@ -254,77 +602,208 @@ func (_m *PeerManagement) Subscribe(topic channels.Topic, topicValidator p2p.Top var r0 p2p.Subscription var r1 error - if rf, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) (p2p.Subscription, error)); ok { - return rf(topic, topicValidator) + if returnFunc, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) (p2p.Subscription, error)); ok { + return returnFunc(topic, topicValidator) } - if rf, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) p2p.Subscription); ok { - r0 = rf(topic, topicValidator) + if returnFunc, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) p2p.Subscription); ok { + r0 = returnFunc(topic, topicValidator) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.Subscription) } } - - if rf, ok := ret.Get(1).(func(channels.Topic, p2p.TopicValidatorFunc) error); ok { - r1 = rf(topic, topicValidator) + if returnFunc, ok := ret.Get(1).(func(channels.Topic, p2p.TopicValidatorFunc) error); ok { + r1 = returnFunc(topic, topicValidator) } else { r1 = ret.Error(1) } - return r0, r1 } -// Unsubscribe provides a mock function with given fields: topic -func (_m *PeerManagement) Unsubscribe(topic channels.Topic) error { - ret := _m.Called(topic) +// PeerManagement_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' +type PeerManagement_Subscribe_Call struct { + *mock.Call +} + +// Subscribe is a helper method to define mock.On call +// - topic channels.Topic +// - topicValidator p2p.TopicValidatorFunc +func (_e *PeerManagement_Expecter) Subscribe(topic interface{}, topicValidator interface{}) *PeerManagement_Subscribe_Call { + return &PeerManagement_Subscribe_Call{Call: _e.mock.On("Subscribe", topic, topicValidator)} +} + +func (_c *PeerManagement_Subscribe_Call) Run(run func(topic channels.Topic, topicValidator p2p.TopicValidatorFunc)) *PeerManagement_Subscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 p2p.TopicValidatorFunc + if args[1] != nil { + arg1 = args[1].(p2p.TopicValidatorFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PeerManagement_Subscribe_Call) Return(subscription p2p.Subscription, err error) *PeerManagement_Subscribe_Call { + _c.Call.Return(subscription, err) + return _c +} + +func (_c *PeerManagement_Subscribe_Call) RunAndReturn(run func(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error)) *PeerManagement_Subscribe_Call { + _c.Call.Return(run) + return _c +} + +// Unsubscribe provides a mock function for the type PeerManagement +func (_mock *PeerManagement) Unsubscribe(topic channels.Topic) error { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for Unsubscribe") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Topic) error); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) error); ok { + r0 = returnFunc(topic) } else { r0 = ret.Error(0) } - return r0 } -// WithDefaultUnicastProtocol provides a mock function with given fields: defaultHandler, preferred -func (_m *PeerManagement) WithDefaultUnicastProtocol(defaultHandler corenetwork.StreamHandler, preferred []protocols.ProtocolName) error { - ret := _m.Called(defaultHandler, preferred) +// PeerManagement_Unsubscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Unsubscribe' +type PeerManagement_Unsubscribe_Call struct { + *mock.Call +} + +// Unsubscribe is a helper method to define mock.On call +// - topic channels.Topic +func (_e *PeerManagement_Expecter) Unsubscribe(topic interface{}) *PeerManagement_Unsubscribe_Call { + return &PeerManagement_Unsubscribe_Call{Call: _e.mock.On("Unsubscribe", topic)} +} + +func (_c *PeerManagement_Unsubscribe_Call) Run(run func(topic channels.Topic)) *PeerManagement_Unsubscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManagement_Unsubscribe_Call) Return(err error) *PeerManagement_Unsubscribe_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PeerManagement_Unsubscribe_Call) RunAndReturn(run func(topic channels.Topic) error) *PeerManagement_Unsubscribe_Call { + _c.Call.Return(run) + return _c +} + +// WithDefaultUnicastProtocol provides a mock function for the type PeerManagement +func (_mock *PeerManagement) WithDefaultUnicastProtocol(defaultHandler network0.StreamHandler, preferred []protocols.ProtocolName) error { + ret := _mock.Called(defaultHandler, preferred) if len(ret) == 0 { panic("no return value specified for WithDefaultUnicastProtocol") } var r0 error - if rf, ok := ret.Get(0).(func(corenetwork.StreamHandler, []protocols.ProtocolName) error); ok { - r0 = rf(defaultHandler, preferred) + if returnFunc, ok := ret.Get(0).(func(network0.StreamHandler, []protocols.ProtocolName) error); ok { + r0 = returnFunc(defaultHandler, preferred) } else { r0 = ret.Error(0) } - return r0 } -// WithPeersProvider provides a mock function with given fields: peersProvider -func (_m *PeerManagement) WithPeersProvider(peersProvider p2p.PeersProvider) { - _m.Called(peersProvider) +// PeerManagement_WithDefaultUnicastProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithDefaultUnicastProtocol' +type PeerManagement_WithDefaultUnicastProtocol_Call struct { + *mock.Call } -// NewPeerManagement creates a new instance of PeerManagement. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPeerManagement(t interface { - mock.TestingT - Cleanup(func()) -}) *PeerManagement { - mock := &PeerManagement{} - mock.Mock.Test(t) +// WithDefaultUnicastProtocol is a helper method to define mock.On call +// - defaultHandler network0.StreamHandler +// - preferred []protocols.ProtocolName +func (_e *PeerManagement_Expecter) WithDefaultUnicastProtocol(defaultHandler interface{}, preferred interface{}) *PeerManagement_WithDefaultUnicastProtocol_Call { + return &PeerManagement_WithDefaultUnicastProtocol_Call{Call: _e.mock.On("WithDefaultUnicastProtocol", defaultHandler, preferred)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *PeerManagement_WithDefaultUnicastProtocol_Call) Run(run func(defaultHandler network0.StreamHandler, preferred []protocols.ProtocolName)) *PeerManagement_WithDefaultUnicastProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network0.StreamHandler + if args[0] != nil { + arg0 = args[0].(network0.StreamHandler) + } + var arg1 []protocols.ProtocolName + if args[1] != nil { + arg1 = args[1].([]protocols.ProtocolName) + } + run( + arg0, + arg1, + ) + }) + return _c +} - return mock +func (_c *PeerManagement_WithDefaultUnicastProtocol_Call) Return(err error) *PeerManagement_WithDefaultUnicastProtocol_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PeerManagement_WithDefaultUnicastProtocol_Call) RunAndReturn(run func(defaultHandler network0.StreamHandler, preferred []protocols.ProtocolName) error) *PeerManagement_WithDefaultUnicastProtocol_Call { + _c.Call.Return(run) + return _c +} + +// WithPeersProvider provides a mock function for the type PeerManagement +func (_mock *PeerManagement) WithPeersProvider(peersProvider p2p.PeersProvider) { + _mock.Called(peersProvider) + return +} + +// PeerManagement_WithPeersProvider_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithPeersProvider' +type PeerManagement_WithPeersProvider_Call struct { + *mock.Call +} + +// WithPeersProvider is a helper method to define mock.On call +// - peersProvider p2p.PeersProvider +func (_e *PeerManagement_Expecter) WithPeersProvider(peersProvider interface{}) *PeerManagement_WithPeersProvider_Call { + return &PeerManagement_WithPeersProvider_Call{Call: _e.mock.On("WithPeersProvider", peersProvider)} +} + +func (_c *PeerManagement_WithPeersProvider_Call) Run(run func(peersProvider p2p.PeersProvider)) *PeerManagement_WithPeersProvider_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.PeersProvider + if args[0] != nil { + arg0 = args[0].(p2p.PeersProvider) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManagement_WithPeersProvider_Call) Return() *PeerManagement_WithPeersProvider_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerManagement_WithPeersProvider_Call) RunAndReturn(run func(peersProvider p2p.PeersProvider)) *PeerManagement_WithPeersProvider_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/peer_manager.go b/network/p2p/mock/peer_manager.go index df48e1c28e0..584e1bfac0d 100644 --- a/network/p2p/mock/peer_manager.go +++ b/network/p2p/mock/peer_manager.go @@ -1,98 +1,350 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) - p2p "github.com/onflow/flow-go/network/p2p" +// NewPeerManager creates a new instance of PeerManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeerManager(t interface { + mock.TestingT + Cleanup(func()) +}) *PeerManager { + mock := &PeerManager{} + mock.Mock.Test(t) - peer "github.com/libp2p/go-libp2p/core/peer" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // PeerManager is an autogenerated mock type for the PeerManager type type PeerManager struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *PeerManager) Done() <-chan struct{} { - ret := _m.Called() +type PeerManager_Expecter struct { + mock *mock.Mock +} + +func (_m *PeerManager) EXPECT() *PeerManager_Expecter { + return &PeerManager_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type PeerManager +func (_mock *PeerManager) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// ForceUpdatePeers provides a mock function with given fields: _a0 -func (_m *PeerManager) ForceUpdatePeers(_a0 context.Context) { - _m.Called(_a0) +// PeerManager_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type PeerManager_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *PeerManager_Expecter) Done() *PeerManager_Done_Call { + return &PeerManager_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *PeerManager_Done_Call) Run(run func()) *PeerManager_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManager_Done_Call) Return(valCh <-chan struct{}) *PeerManager_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *PeerManager_Done_Call) RunAndReturn(run func() <-chan struct{}) *PeerManager_Done_Call { + _c.Call.Return(run) + return _c +} + +// ForceUpdatePeers provides a mock function for the type PeerManager +func (_mock *PeerManager) ForceUpdatePeers(context1 context.Context) { + _mock.Called(context1) + return +} + +// PeerManager_ForceUpdatePeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ForceUpdatePeers' +type PeerManager_ForceUpdatePeers_Call struct { + *mock.Call +} + +// ForceUpdatePeers is a helper method to define mock.On call +// - context1 context.Context +func (_e *PeerManager_Expecter) ForceUpdatePeers(context1 interface{}) *PeerManager_ForceUpdatePeers_Call { + return &PeerManager_ForceUpdatePeers_Call{Call: _e.mock.On("ForceUpdatePeers", context1)} +} + +func (_c *PeerManager_ForceUpdatePeers_Call) Run(run func(context1 context.Context)) *PeerManager_ForceUpdatePeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManager_ForceUpdatePeers_Call) Return() *PeerManager_ForceUpdatePeers_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerManager_ForceUpdatePeers_Call) RunAndReturn(run func(context1 context.Context)) *PeerManager_ForceUpdatePeers_Call { + _c.Run(run) + return _c +} + +// OnRateLimitedPeer provides a mock function for the type PeerManager +func (_mock *PeerManager) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { + _mock.Called(pid, role, msgType, topic, reason) + return +} + +// PeerManager_OnRateLimitedPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRateLimitedPeer' +type PeerManager_OnRateLimitedPeer_Call struct { + *mock.Call +} + +// OnRateLimitedPeer is a helper method to define mock.On call +// - pid peer.ID +// - role string +// - msgType string +// - topic string +// - reason string +func (_e *PeerManager_Expecter) OnRateLimitedPeer(pid interface{}, role interface{}, msgType interface{}, topic interface{}, reason interface{}) *PeerManager_OnRateLimitedPeer_Call { + return &PeerManager_OnRateLimitedPeer_Call{Call: _e.mock.On("OnRateLimitedPeer", pid, role, msgType, topic, reason)} +} + +func (_c *PeerManager_OnRateLimitedPeer_Call) Run(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *PeerManager_OnRateLimitedPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + var arg4 string + if args[4] != nil { + arg4 = args[4].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *PeerManager_OnRateLimitedPeer_Call) Return() *PeerManager_OnRateLimitedPeer_Call { + _c.Call.Return() + return _c } -// OnRateLimitedPeer provides a mock function with given fields: pid, role, msgType, topic, reason -func (_m *PeerManager) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { - _m.Called(pid, role, msgType, topic, reason) +func (_c *PeerManager_OnRateLimitedPeer_Call) RunAndReturn(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *PeerManager_OnRateLimitedPeer_Call { + _c.Run(run) + return _c } -// Ready provides a mock function with no fields -func (_m *PeerManager) Ready() <-chan struct{} { - ret := _m.Called() +// Ready provides a mock function for the type PeerManager +func (_mock *PeerManager) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// RequestPeerUpdate provides a mock function with no fields -func (_m *PeerManager) RequestPeerUpdate() { - _m.Called() +// PeerManager_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type PeerManager_Ready_Call struct { + *mock.Call } -// SetPeersProvider provides a mock function with given fields: _a0 -func (_m *PeerManager) SetPeersProvider(_a0 p2p.PeersProvider) { - _m.Called(_a0) +// Ready is a helper method to define mock.On call +func (_e *PeerManager_Expecter) Ready() *PeerManager_Ready_Call { + return &PeerManager_Ready_Call{Call: _e.mock.On("Ready")} } -// Start provides a mock function with given fields: _a0 -func (_m *PeerManager) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +func (_c *PeerManager_Ready_Call) Run(run func()) *PeerManager_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// NewPeerManager creates a new instance of PeerManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPeerManager(t interface { - mock.TestingT - Cleanup(func()) -}) *PeerManager { - mock := &PeerManager{} - mock.Mock.Test(t) +func (_c *PeerManager_Ready_Call) Return(valCh <-chan struct{}) *PeerManager_Ready_Call { + _c.Call.Return(valCh) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *PeerManager_Ready_Call) RunAndReturn(run func() <-chan struct{}) *PeerManager_Ready_Call { + _c.Call.Return(run) + return _c +} - return mock +// RequestPeerUpdate provides a mock function for the type PeerManager +func (_mock *PeerManager) RequestPeerUpdate() { + _mock.Called() + return +} + +// PeerManager_RequestPeerUpdate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RequestPeerUpdate' +type PeerManager_RequestPeerUpdate_Call struct { + *mock.Call +} + +// RequestPeerUpdate is a helper method to define mock.On call +func (_e *PeerManager_Expecter) RequestPeerUpdate() *PeerManager_RequestPeerUpdate_Call { + return &PeerManager_RequestPeerUpdate_Call{Call: _e.mock.On("RequestPeerUpdate")} +} + +func (_c *PeerManager_RequestPeerUpdate_Call) Run(run func()) *PeerManager_RequestPeerUpdate_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerManager_RequestPeerUpdate_Call) Return() *PeerManager_RequestPeerUpdate_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerManager_RequestPeerUpdate_Call) RunAndReturn(run func()) *PeerManager_RequestPeerUpdate_Call { + _c.Run(run) + return _c +} + +// SetPeersProvider provides a mock function for the type PeerManager +func (_mock *PeerManager) SetPeersProvider(peersProvider p2p.PeersProvider) { + _mock.Called(peersProvider) + return +} + +// PeerManager_SetPeersProvider_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetPeersProvider' +type PeerManager_SetPeersProvider_Call struct { + *mock.Call +} + +// SetPeersProvider is a helper method to define mock.On call +// - peersProvider p2p.PeersProvider +func (_e *PeerManager_Expecter) SetPeersProvider(peersProvider interface{}) *PeerManager_SetPeersProvider_Call { + return &PeerManager_SetPeersProvider_Call{Call: _e.mock.On("SetPeersProvider", peersProvider)} +} + +func (_c *PeerManager_SetPeersProvider_Call) Run(run func(peersProvider p2p.PeersProvider)) *PeerManager_SetPeersProvider_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.PeersProvider + if args[0] != nil { + arg0 = args[0].(p2p.PeersProvider) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManager_SetPeersProvider_Call) Return() *PeerManager_SetPeersProvider_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerManager_SetPeersProvider_Call) RunAndReturn(run func(peersProvider p2p.PeersProvider)) *PeerManager_SetPeersProvider_Call { + _c.Run(run) + return _c +} + +// Start provides a mock function for the type PeerManager +func (_mock *PeerManager) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// PeerManager_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type PeerManager_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *PeerManager_Expecter) Start(signalerContext interface{}) *PeerManager_Start_Call { + return &PeerManager_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *PeerManager_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *PeerManager_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerManager_Start_Call) Return() *PeerManager_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerManager_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *PeerManager_Start_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/peer_score.go b/network/p2p/mock/peer_score.go index d8fd9585bb0..4a3c2d66c3f 100644 --- a/network/p2p/mock/peer_score.go +++ b/network/p2p/mock/peer_score.go @@ -1,47 +1,83 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - p2p "github.com/onflow/flow-go/network/p2p" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" ) +// NewPeerScore creates a new instance of PeerScore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeerScore(t interface { + mock.TestingT + Cleanup(func()) +}) *PeerScore { + mock := &PeerScore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // PeerScore is an autogenerated mock type for the PeerScore type type PeerScore struct { mock.Mock } -// PeerScoreExposer provides a mock function with no fields -func (_m *PeerScore) PeerScoreExposer() p2p.PeerScoreExposer { - ret := _m.Called() +type PeerScore_Expecter struct { + mock *mock.Mock +} + +func (_m *PeerScore) EXPECT() *PeerScore_Expecter { + return &PeerScore_Expecter{mock: &_m.Mock} +} + +// PeerScoreExposer provides a mock function for the type PeerScore +func (_mock *PeerScore) PeerScoreExposer() p2p.PeerScoreExposer { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PeerScoreExposer") } var r0 p2p.PeerScoreExposer - if rf, ok := ret.Get(0).(func() p2p.PeerScoreExposer); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() p2p.PeerScoreExposer); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.PeerScoreExposer) } } - return r0 } -// NewPeerScore creates a new instance of PeerScore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPeerScore(t interface { - mock.TestingT - Cleanup(func()) -}) *PeerScore { - mock := &PeerScore{} - mock.Mock.Test(t) +// PeerScore_PeerScoreExposer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PeerScoreExposer' +type PeerScore_PeerScoreExposer_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// PeerScoreExposer is a helper method to define mock.On call +func (_e *PeerScore_Expecter) PeerScoreExposer() *PeerScore_PeerScoreExposer_Call { + return &PeerScore_PeerScoreExposer_Call{Call: _e.mock.On("PeerScoreExposer")} +} - return mock +func (_c *PeerScore_PeerScoreExposer_Call) Run(run func()) *PeerScore_PeerScoreExposer_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerScore_PeerScoreExposer_Call) Return(peerScoreExposer p2p.PeerScoreExposer) *PeerScore_PeerScoreExposer_Call { + _c.Call.Return(peerScoreExposer) + return _c +} + +func (_c *PeerScore_PeerScoreExposer_Call) RunAndReturn(run func() p2p.PeerScoreExposer) *PeerScore_PeerScoreExposer_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/peer_score_exposer.go b/network/p2p/mock/peer_score_exposer.go index a0d58bf7ff3..d8ec32df2eb 100644 --- a/network/p2p/mock/peer_score_exposer.go +++ b/network/p2p/mock/peer_score_exposer.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - p2p "github.com/onflow/flow-go/network/p2p" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewPeerScoreExposer creates a new instance of PeerScoreExposer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeerScoreExposer(t interface { + mock.TestingT + Cleanup(func()) +}) *PeerScoreExposer { + mock := &PeerScoreExposer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // PeerScoreExposer is an autogenerated mock type for the PeerScoreExposer type type PeerScoreExposer struct { mock.Mock } -// GetAppScore provides a mock function with given fields: peerID -func (_m *PeerScoreExposer) GetAppScore(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +type PeerScoreExposer_Expecter struct { + mock *mock.Mock +} + +func (_m *PeerScoreExposer) EXPECT() *PeerScoreExposer_Expecter { + return &PeerScoreExposer_Expecter{mock: &_m.Mock} +} + +// GetAppScore provides a mock function for the type PeerScoreExposer +func (_mock *PeerScoreExposer) GetAppScore(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetAppScore") @@ -24,27 +47,59 @@ func (_m *PeerScoreExposer) GetAppScore(peerID peer.ID) (float64, bool) { var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetBehaviourPenalty provides a mock function with given fields: peerID -func (_m *PeerScoreExposer) GetBehaviourPenalty(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +// PeerScoreExposer_GetAppScore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAppScore' +type PeerScoreExposer_GetAppScore_Call struct { + *mock.Call +} + +// GetAppScore is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreExposer_Expecter) GetAppScore(peerID interface{}) *PeerScoreExposer_GetAppScore_Call { + return &PeerScoreExposer_GetAppScore_Call{Call: _e.mock.On("GetAppScore", peerID)} +} + +func (_c *PeerScoreExposer_GetAppScore_Call) Run(run func(peerID peer.ID)) *PeerScoreExposer_GetAppScore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreExposer_GetAppScore_Call) Return(f float64, b bool) *PeerScoreExposer_GetAppScore_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreExposer_GetAppScore_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreExposer_GetAppScore_Call { + _c.Call.Return(run) + return _c +} + +// GetBehaviourPenalty provides a mock function for the type PeerScoreExposer +func (_mock *PeerScoreExposer) GetBehaviourPenalty(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetBehaviourPenalty") @@ -52,27 +107,59 @@ func (_m *PeerScoreExposer) GetBehaviourPenalty(peerID peer.ID) (float64, bool) var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetIPColocationFactor provides a mock function with given fields: peerID -func (_m *PeerScoreExposer) GetIPColocationFactor(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +// PeerScoreExposer_GetBehaviourPenalty_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBehaviourPenalty' +type PeerScoreExposer_GetBehaviourPenalty_Call struct { + *mock.Call +} + +// GetBehaviourPenalty is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreExposer_Expecter) GetBehaviourPenalty(peerID interface{}) *PeerScoreExposer_GetBehaviourPenalty_Call { + return &PeerScoreExposer_GetBehaviourPenalty_Call{Call: _e.mock.On("GetBehaviourPenalty", peerID)} +} + +func (_c *PeerScoreExposer_GetBehaviourPenalty_Call) Run(run func(peerID peer.ID)) *PeerScoreExposer_GetBehaviourPenalty_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreExposer_GetBehaviourPenalty_Call) Return(f float64, b bool) *PeerScoreExposer_GetBehaviourPenalty_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreExposer_GetBehaviourPenalty_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreExposer_GetBehaviourPenalty_Call { + _c.Call.Return(run) + return _c +} + +// GetIPColocationFactor provides a mock function for the type PeerScoreExposer +func (_mock *PeerScoreExposer) GetIPColocationFactor(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetIPColocationFactor") @@ -80,27 +167,59 @@ func (_m *PeerScoreExposer) GetIPColocationFactor(peerID peer.ID) (float64, bool var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetScore provides a mock function with given fields: peerID -func (_m *PeerScoreExposer) GetScore(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +// PeerScoreExposer_GetIPColocationFactor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIPColocationFactor' +type PeerScoreExposer_GetIPColocationFactor_Call struct { + *mock.Call +} + +// GetIPColocationFactor is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreExposer_Expecter) GetIPColocationFactor(peerID interface{}) *PeerScoreExposer_GetIPColocationFactor_Call { + return &PeerScoreExposer_GetIPColocationFactor_Call{Call: _e.mock.On("GetIPColocationFactor", peerID)} +} + +func (_c *PeerScoreExposer_GetIPColocationFactor_Call) Run(run func(peerID peer.ID)) *PeerScoreExposer_GetIPColocationFactor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreExposer_GetIPColocationFactor_Call) Return(f float64, b bool) *PeerScoreExposer_GetIPColocationFactor_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreExposer_GetIPColocationFactor_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreExposer_GetIPColocationFactor_Call { + _c.Call.Return(run) + return _c +} + +// GetScore provides a mock function for the type PeerScoreExposer +func (_mock *PeerScoreExposer) GetScore(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetScore") @@ -108,27 +227,59 @@ func (_m *PeerScoreExposer) GetScore(peerID peer.ID) (float64, bool) { var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetTopicScores provides a mock function with given fields: peerID -func (_m *PeerScoreExposer) GetTopicScores(peerID peer.ID) (map[string]p2p.TopicScoreSnapshot, bool) { - ret := _m.Called(peerID) +// PeerScoreExposer_GetScore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScore' +type PeerScoreExposer_GetScore_Call struct { + *mock.Call +} + +// GetScore is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreExposer_Expecter) GetScore(peerID interface{}) *PeerScoreExposer_GetScore_Call { + return &PeerScoreExposer_GetScore_Call{Call: _e.mock.On("GetScore", peerID)} +} + +func (_c *PeerScoreExposer_GetScore_Call) Run(run func(peerID peer.ID)) *PeerScoreExposer_GetScore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreExposer_GetScore_Call) Return(f float64, b bool) *PeerScoreExposer_GetScore_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreExposer_GetScore_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreExposer_GetScore_Call { + _c.Call.Return(run) + return _c +} + +// GetTopicScores provides a mock function for the type PeerScoreExposer +func (_mock *PeerScoreExposer) GetTopicScores(peerID peer.ID) (map[string]p2p.TopicScoreSnapshot, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetTopicScores") @@ -136,36 +287,54 @@ func (_m *PeerScoreExposer) GetTopicScores(peerID peer.ID) (map[string]p2p.Topic var r0 map[string]p2p.TopicScoreSnapshot var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (map[string]p2p.TopicScoreSnapshot, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (map[string]p2p.TopicScoreSnapshot, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) map[string]p2p.TopicScoreSnapshot); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) map[string]p2p.TopicScoreSnapshot); ok { + r0 = returnFunc(peerID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[string]p2p.TopicScoreSnapshot) } } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// NewPeerScoreExposer creates a new instance of PeerScoreExposer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPeerScoreExposer(t interface { - mock.TestingT - Cleanup(func()) -}) *PeerScoreExposer { - mock := &PeerScoreExposer{} - mock.Mock.Test(t) +// PeerScoreExposer_GetTopicScores_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTopicScores' +type PeerScoreExposer_GetTopicScores_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// GetTopicScores is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreExposer_Expecter) GetTopicScores(peerID interface{}) *PeerScoreExposer_GetTopicScores_Call { + return &PeerScoreExposer_GetTopicScores_Call{Call: _e.mock.On("GetTopicScores", peerID)} +} - return mock +func (_c *PeerScoreExposer_GetTopicScores_Call) Run(run func(peerID peer.ID)) *PeerScoreExposer_GetTopicScores_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreExposer_GetTopicScores_Call) Return(stringToTopicScoreSnapshot map[string]p2p.TopicScoreSnapshot, b bool) *PeerScoreExposer_GetTopicScores_Call { + _c.Call.Return(stringToTopicScoreSnapshot, b) + return _c +} + +func (_c *PeerScoreExposer_GetTopicScores_Call) RunAndReturn(run func(peerID peer.ID) (map[string]p2p.TopicScoreSnapshot, bool)) *PeerScoreExposer_GetTopicScores_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/peer_score_tracer.go b/network/p2p/mock/peer_score_tracer.go index 45b57b1c93f..095694f758e 100644 --- a/network/p2p/mock/peer_score_tracer.go +++ b/network/p2p/mock/peer_score_tracer.go @@ -1,46 +1,94 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "time" + + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) - p2p "github.com/onflow/flow-go/network/p2p" +// NewPeerScoreTracer creates a new instance of PeerScoreTracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPeerScoreTracer(t interface { + mock.TestingT + Cleanup(func()) +}) *PeerScoreTracer { + mock := &PeerScoreTracer{} + mock.Mock.Test(t) - peer "github.com/libp2p/go-libp2p/core/peer" + t.Cleanup(func() { mock.AssertExpectations(t) }) - time "time" -) + return mock +} // PeerScoreTracer is an autogenerated mock type for the PeerScoreTracer type type PeerScoreTracer struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *PeerScoreTracer) Done() <-chan struct{} { - ret := _m.Called() +type PeerScoreTracer_Expecter struct { + mock *mock.Mock +} + +func (_m *PeerScoreTracer) EXPECT() *PeerScoreTracer_Expecter { + return &PeerScoreTracer_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// GetAppScore provides a mock function with given fields: peerID -func (_m *PeerScoreTracer) GetAppScore(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +// PeerScoreTracer_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type PeerScoreTracer_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *PeerScoreTracer_Expecter) Done() *PeerScoreTracer_Done_Call { + return &PeerScoreTracer_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *PeerScoreTracer_Done_Call) Run(run func()) *PeerScoreTracer_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerScoreTracer_Done_Call) Return(valCh <-chan struct{}) *PeerScoreTracer_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *PeerScoreTracer_Done_Call) RunAndReturn(run func() <-chan struct{}) *PeerScoreTracer_Done_Call { + _c.Call.Return(run) + return _c +} + +// GetAppScore provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) GetAppScore(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetAppScore") @@ -48,27 +96,59 @@ func (_m *PeerScoreTracer) GetAppScore(peerID peer.ID) (float64, bool) { var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetBehaviourPenalty provides a mock function with given fields: peerID -func (_m *PeerScoreTracer) GetBehaviourPenalty(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +// PeerScoreTracer_GetAppScore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAppScore' +type PeerScoreTracer_GetAppScore_Call struct { + *mock.Call +} + +// GetAppScore is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreTracer_Expecter) GetAppScore(peerID interface{}) *PeerScoreTracer_GetAppScore_Call { + return &PeerScoreTracer_GetAppScore_Call{Call: _e.mock.On("GetAppScore", peerID)} +} + +func (_c *PeerScoreTracer_GetAppScore_Call) Run(run func(peerID peer.ID)) *PeerScoreTracer_GetAppScore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreTracer_GetAppScore_Call) Return(f float64, b bool) *PeerScoreTracer_GetAppScore_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreTracer_GetAppScore_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreTracer_GetAppScore_Call { + _c.Call.Return(run) + return _c +} + +// GetBehaviourPenalty provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) GetBehaviourPenalty(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetBehaviourPenalty") @@ -76,27 +156,59 @@ func (_m *PeerScoreTracer) GetBehaviourPenalty(peerID peer.ID) (float64, bool) { var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetIPColocationFactor provides a mock function with given fields: peerID -func (_m *PeerScoreTracer) GetIPColocationFactor(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +// PeerScoreTracer_GetBehaviourPenalty_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBehaviourPenalty' +type PeerScoreTracer_GetBehaviourPenalty_Call struct { + *mock.Call +} + +// GetBehaviourPenalty is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreTracer_Expecter) GetBehaviourPenalty(peerID interface{}) *PeerScoreTracer_GetBehaviourPenalty_Call { + return &PeerScoreTracer_GetBehaviourPenalty_Call{Call: _e.mock.On("GetBehaviourPenalty", peerID)} +} + +func (_c *PeerScoreTracer_GetBehaviourPenalty_Call) Run(run func(peerID peer.ID)) *PeerScoreTracer_GetBehaviourPenalty_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreTracer_GetBehaviourPenalty_Call) Return(f float64, b bool) *PeerScoreTracer_GetBehaviourPenalty_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreTracer_GetBehaviourPenalty_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreTracer_GetBehaviourPenalty_Call { + _c.Call.Return(run) + return _c +} + +// GetIPColocationFactor provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) GetIPColocationFactor(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetIPColocationFactor") @@ -104,27 +216,59 @@ func (_m *PeerScoreTracer) GetIPColocationFactor(peerID peer.ID) (float64, bool) var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetScore provides a mock function with given fields: peerID -func (_m *PeerScoreTracer) GetScore(peerID peer.ID) (float64, bool) { - ret := _m.Called(peerID) +// PeerScoreTracer_GetIPColocationFactor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIPColocationFactor' +type PeerScoreTracer_GetIPColocationFactor_Call struct { + *mock.Call +} + +// GetIPColocationFactor is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreTracer_Expecter) GetIPColocationFactor(peerID interface{}) *PeerScoreTracer_GetIPColocationFactor_Call { + return &PeerScoreTracer_GetIPColocationFactor_Call{Call: _e.mock.On("GetIPColocationFactor", peerID)} +} + +func (_c *PeerScoreTracer_GetIPColocationFactor_Call) Run(run func(peerID peer.ID)) *PeerScoreTracer_GetIPColocationFactor_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreTracer_GetIPColocationFactor_Call) Return(f float64, b bool) *PeerScoreTracer_GetIPColocationFactor_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreTracer_GetIPColocationFactor_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreTracer_GetIPColocationFactor_Call { + _c.Call.Return(run) + return _c +} + +// GetScore provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) GetScore(peerID peer.ID) (float64, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetScore") @@ -132,27 +276,59 @@ func (_m *PeerScoreTracer) GetScore(peerID peer.ID) (float64, bool) { var r0 float64 var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (float64, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(float64) } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// GetTopicScores provides a mock function with given fields: peerID -func (_m *PeerScoreTracer) GetTopicScores(peerID peer.ID) (map[string]p2p.TopicScoreSnapshot, bool) { - ret := _m.Called(peerID) +// PeerScoreTracer_GetScore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetScore' +type PeerScoreTracer_GetScore_Call struct { + *mock.Call +} + +// GetScore is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreTracer_Expecter) GetScore(peerID interface{}) *PeerScoreTracer_GetScore_Call { + return &PeerScoreTracer_GetScore_Call{Call: _e.mock.On("GetScore", peerID)} +} + +func (_c *PeerScoreTracer_GetScore_Call) Run(run func(peerID peer.ID)) *PeerScoreTracer_GetScore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreTracer_GetScore_Call) Return(f float64, b bool) *PeerScoreTracer_GetScore_Call { + _c.Call.Return(f, b) + return _c +} + +func (_c *PeerScoreTracer_GetScore_Call) RunAndReturn(run func(peerID peer.ID) (float64, bool)) *PeerScoreTracer_GetScore_Call { + _c.Call.Return(run) + return _c +} + +// GetTopicScores provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) GetTopicScores(peerID peer.ID) (map[string]p2p.TopicScoreSnapshot, bool) { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for GetTopicScores") @@ -160,84 +336,224 @@ func (_m *PeerScoreTracer) GetTopicScores(peerID peer.ID) (map[string]p2p.TopicS var r0 map[string]p2p.TopicScoreSnapshot var r1 bool - if rf, ok := ret.Get(0).(func(peer.ID) (map[string]p2p.TopicScoreSnapshot, bool)); ok { - return rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) (map[string]p2p.TopicScoreSnapshot, bool)); ok { + return returnFunc(peerID) } - if rf, ok := ret.Get(0).(func(peer.ID) map[string]p2p.TopicScoreSnapshot); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) map[string]p2p.TopicScoreSnapshot); ok { + r0 = returnFunc(peerID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[string]p2p.TopicScoreSnapshot) } } - - if rf, ok := ret.Get(1).(func(peer.ID) bool); ok { - r1 = rf(peerID) + if returnFunc, ok := ret.Get(1).(func(peer.ID) bool); ok { + r1 = returnFunc(peerID) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// Ready provides a mock function with no fields -func (_m *PeerScoreTracer) Ready() <-chan struct{} { - ret := _m.Called() +// PeerScoreTracer_GetTopicScores_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTopicScores' +type PeerScoreTracer_GetTopicScores_Call struct { + *mock.Call +} + +// GetTopicScores is a helper method to define mock.On call +// - peerID peer.ID +func (_e *PeerScoreTracer_Expecter) GetTopicScores(peerID interface{}) *PeerScoreTracer_GetTopicScores_Call { + return &PeerScoreTracer_GetTopicScores_Call{Call: _e.mock.On("GetTopicScores", peerID)} +} + +func (_c *PeerScoreTracer_GetTopicScores_Call) Run(run func(peerID peer.ID)) *PeerScoreTracer_GetTopicScores_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreTracer_GetTopicScores_Call) Return(stringToTopicScoreSnapshot map[string]p2p.TopicScoreSnapshot, b bool) *PeerScoreTracer_GetTopicScores_Call { + _c.Call.Return(stringToTopicScoreSnapshot, b) + return _c +} + +func (_c *PeerScoreTracer_GetTopicScores_Call) RunAndReturn(run func(peerID peer.ID) (map[string]p2p.TopicScoreSnapshot, bool)) *PeerScoreTracer_GetTopicScores_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *PeerScoreTracer) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// PeerScoreTracer_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type PeerScoreTracer_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *PeerScoreTracer_Expecter) Ready() *PeerScoreTracer_Ready_Call { + return &PeerScoreTracer_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *PeerScoreTracer_Ready_Call) Run(run func()) *PeerScoreTracer_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PeerScoreTracer_Ready_Call) Return(valCh <-chan struct{}) *PeerScoreTracer_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *PeerScoreTracer_Ready_Call) RunAndReturn(run func() <-chan struct{}) *PeerScoreTracer_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// PeerScoreTracer_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type PeerScoreTracer_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *PeerScoreTracer_Expecter) Start(signalerContext interface{}) *PeerScoreTracer_Start_Call { + return &PeerScoreTracer_Start_Call{Call: _e.mock.On("Start", signalerContext)} } -// UpdateInterval provides a mock function with no fields -func (_m *PeerScoreTracer) UpdateInterval() time.Duration { - ret := _m.Called() +func (_c *PeerScoreTracer_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *PeerScoreTracer_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreTracer_Start_Call) Return() *PeerScoreTracer_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerScoreTracer_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *PeerScoreTracer_Start_Call { + _c.Run(run) + return _c +} + +// UpdateInterval provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) UpdateInterval() time.Duration { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for UpdateInterval") } var r0 time.Duration - if rf, ok := ret.Get(0).(func() time.Duration); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() time.Duration); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(time.Duration) } - return r0 } -// UpdatePeerScoreSnapshots provides a mock function with given fields: _a0 -func (_m *PeerScoreTracer) UpdatePeerScoreSnapshots(_a0 map[peer.ID]*p2p.PeerScoreSnapshot) { - _m.Called(_a0) +// PeerScoreTracer_UpdateInterval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateInterval' +type PeerScoreTracer_UpdateInterval_Call struct { + *mock.Call } -// NewPeerScoreTracer creates a new instance of PeerScoreTracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPeerScoreTracer(t interface { - mock.TestingT - Cleanup(func()) -}) *PeerScoreTracer { - mock := &PeerScoreTracer{} - mock.Mock.Test(t) +// UpdateInterval is a helper method to define mock.On call +func (_e *PeerScoreTracer_Expecter) UpdateInterval() *PeerScoreTracer_UpdateInterval_Call { + return &PeerScoreTracer_UpdateInterval_Call{Call: _e.mock.On("UpdateInterval")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *PeerScoreTracer_UpdateInterval_Call) Run(run func()) *PeerScoreTracer_UpdateInterval_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *PeerScoreTracer_UpdateInterval_Call) Return(duration time.Duration) *PeerScoreTracer_UpdateInterval_Call { + _c.Call.Return(duration) + return _c +} + +func (_c *PeerScoreTracer_UpdateInterval_Call) RunAndReturn(run func() time.Duration) *PeerScoreTracer_UpdateInterval_Call { + _c.Call.Return(run) + return _c +} + +// UpdatePeerScoreSnapshots provides a mock function for the type PeerScoreTracer +func (_mock *PeerScoreTracer) UpdatePeerScoreSnapshots(iDToPeerScoreSnapshot map[peer.ID]*p2p.PeerScoreSnapshot) { + _mock.Called(iDToPeerScoreSnapshot) + return +} + +// PeerScoreTracer_UpdatePeerScoreSnapshots_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePeerScoreSnapshots' +type PeerScoreTracer_UpdatePeerScoreSnapshots_Call struct { + *mock.Call +} + +// UpdatePeerScoreSnapshots is a helper method to define mock.On call +// - iDToPeerScoreSnapshot map[peer.ID]*p2p.PeerScoreSnapshot +func (_e *PeerScoreTracer_Expecter) UpdatePeerScoreSnapshots(iDToPeerScoreSnapshot interface{}) *PeerScoreTracer_UpdatePeerScoreSnapshots_Call { + return &PeerScoreTracer_UpdatePeerScoreSnapshots_Call{Call: _e.mock.On("UpdatePeerScoreSnapshots", iDToPeerScoreSnapshot)} +} + +func (_c *PeerScoreTracer_UpdatePeerScoreSnapshots_Call) Run(run func(iDToPeerScoreSnapshot map[peer.ID]*p2p.PeerScoreSnapshot)) *PeerScoreTracer_UpdatePeerScoreSnapshots_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 map[peer.ID]*p2p.PeerScoreSnapshot + if args[0] != nil { + arg0 = args[0].(map[peer.ID]*p2p.PeerScoreSnapshot) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PeerScoreTracer_UpdatePeerScoreSnapshots_Call) Return() *PeerScoreTracer_UpdatePeerScoreSnapshots_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerScoreTracer_UpdatePeerScoreSnapshots_Call) RunAndReturn(run func(iDToPeerScoreSnapshot map[peer.ID]*p2p.PeerScoreSnapshot)) *PeerScoreTracer_UpdatePeerScoreSnapshots_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/peer_updater.go b/network/p2p/mock/peer_updater.go index 43c5fe69c5c..6b58d786467 100644 --- a/network/p2p/mock/peer_updater.go +++ b/network/p2p/mock/peer_updater.go @@ -1,25 +1,16 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) -// PeerUpdater is an autogenerated mock type for the PeerUpdater type -type PeerUpdater struct { - mock.Mock -} - -// UpdatePeers provides a mock function with given fields: ctx, peerIDs -func (_m *PeerUpdater) UpdatePeers(ctx context.Context, peerIDs peer.IDSlice) { - _m.Called(ctx, peerIDs) -} - // NewPeerUpdater creates a new instance of PeerUpdater. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewPeerUpdater(t interface { @@ -33,3 +24,62 @@ func NewPeerUpdater(t interface { return mock } + +// PeerUpdater is an autogenerated mock type for the PeerUpdater type +type PeerUpdater struct { + mock.Mock +} + +type PeerUpdater_Expecter struct { + mock *mock.Mock +} + +func (_m *PeerUpdater) EXPECT() *PeerUpdater_Expecter { + return &PeerUpdater_Expecter{mock: &_m.Mock} +} + +// UpdatePeers provides a mock function for the type PeerUpdater +func (_mock *PeerUpdater) UpdatePeers(ctx context.Context, peerIDs peer.IDSlice) { + _mock.Called(ctx, peerIDs) + return +} + +// PeerUpdater_UpdatePeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePeers' +type PeerUpdater_UpdatePeers_Call struct { + *mock.Call +} + +// UpdatePeers is a helper method to define mock.On call +// - ctx context.Context +// - peerIDs peer.IDSlice +func (_e *PeerUpdater_Expecter) UpdatePeers(ctx interface{}, peerIDs interface{}) *PeerUpdater_UpdatePeers_Call { + return &PeerUpdater_UpdatePeers_Call{Call: _e.mock.On("UpdatePeers", ctx, peerIDs)} +} + +func (_c *PeerUpdater_UpdatePeers_Call) Run(run func(ctx context.Context, peerIDs peer.IDSlice)) *PeerUpdater_UpdatePeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.IDSlice + if args[1] != nil { + arg1 = args[1].(peer.IDSlice) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PeerUpdater_UpdatePeers_Call) Return() *PeerUpdater_UpdatePeers_Call { + _c.Call.Return() + return _c +} + +func (_c *PeerUpdater_UpdatePeers_Call) RunAndReturn(run func(ctx context.Context, peerIDs peer.IDSlice)) *PeerUpdater_UpdatePeers_Call { + _c.Run(run) + return _c +} diff --git a/network/p2p/mock/protocol_peer_cache.go b/network/p2p/mock/protocol_peer_cache.go index 93b43754656..11261551bac 100644 --- a/network/p2p/mock/protocol_peer_cache.go +++ b/network/p2p/mock/protocol_peer_cache.go @@ -1,65 +1,223 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" mock "github.com/stretchr/testify/mock" +) + +// NewProtocolPeerCache creates a new instance of ProtocolPeerCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProtocolPeerCache(t interface { + mock.TestingT + Cleanup(func()) +}) *ProtocolPeerCache { + mock := &ProtocolPeerCache{} + mock.Mock.Test(t) - peer "github.com/libp2p/go-libp2p/core/peer" + t.Cleanup(func() { mock.AssertExpectations(t) }) - protocol "github.com/libp2p/go-libp2p/core/protocol" -) + return mock +} // ProtocolPeerCache is an autogenerated mock type for the ProtocolPeerCache type type ProtocolPeerCache struct { mock.Mock } -// AddProtocols provides a mock function with given fields: peerID, protocols -func (_m *ProtocolPeerCache) AddProtocols(peerID peer.ID, protocols []protocol.ID) { - _m.Called(peerID, protocols) +type ProtocolPeerCache_Expecter struct { + mock *mock.Mock +} + +func (_m *ProtocolPeerCache) EXPECT() *ProtocolPeerCache_Expecter { + return &ProtocolPeerCache_Expecter{mock: &_m.Mock} +} + +// AddProtocols provides a mock function for the type ProtocolPeerCache +func (_mock *ProtocolPeerCache) AddProtocols(peerID peer.ID, protocols []protocol.ID) { + _mock.Called(peerID, protocols) + return } -// GetPeers provides a mock function with given fields: pid -func (_m *ProtocolPeerCache) GetPeers(pid protocol.ID) peer.IDSlice { - ret := _m.Called(pid) +// ProtocolPeerCache_AddProtocols_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddProtocols' +type ProtocolPeerCache_AddProtocols_Call struct { + *mock.Call +} + +// AddProtocols is a helper method to define mock.On call +// - peerID peer.ID +// - protocols []protocol.ID +func (_e *ProtocolPeerCache_Expecter) AddProtocols(peerID interface{}, protocols interface{}) *ProtocolPeerCache_AddProtocols_Call { + return &ProtocolPeerCache_AddProtocols_Call{Call: _e.mock.On("AddProtocols", peerID, protocols)} +} + +func (_c *ProtocolPeerCache_AddProtocols_Call) Run(run func(peerID peer.ID, protocols []protocol.ID)) *ProtocolPeerCache_AddProtocols_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 []protocol.ID + if args[1] != nil { + arg1 = args[1].([]protocol.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ProtocolPeerCache_AddProtocols_Call) Return() *ProtocolPeerCache_AddProtocols_Call { + _c.Call.Return() + return _c +} + +func (_c *ProtocolPeerCache_AddProtocols_Call) RunAndReturn(run func(peerID peer.ID, protocols []protocol.ID)) *ProtocolPeerCache_AddProtocols_Call { + _c.Run(run) + return _c +} + +// GetPeers provides a mock function for the type ProtocolPeerCache +func (_mock *ProtocolPeerCache) GetPeers(pid protocol.ID) peer.IDSlice { + ret := _mock.Called(pid) if len(ret) == 0 { panic("no return value specified for GetPeers") } var r0 peer.IDSlice - if rf, ok := ret.Get(0).(func(protocol.ID) peer.IDSlice); ok { - r0 = rf(pid) + if returnFunc, ok := ret.Get(0).(func(protocol.ID) peer.IDSlice); ok { + r0 = returnFunc(pid) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(peer.IDSlice) } } - return r0 } -// RemovePeer provides a mock function with given fields: peerID -func (_m *ProtocolPeerCache) RemovePeer(peerID peer.ID) { - _m.Called(peerID) +// ProtocolPeerCache_GetPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPeers' +type ProtocolPeerCache_GetPeers_Call struct { + *mock.Call } -// RemoveProtocols provides a mock function with given fields: peerID, protocols -func (_m *ProtocolPeerCache) RemoveProtocols(peerID peer.ID, protocols []protocol.ID) { - _m.Called(peerID, protocols) +// GetPeers is a helper method to define mock.On call +// - pid protocol.ID +func (_e *ProtocolPeerCache_Expecter) GetPeers(pid interface{}) *ProtocolPeerCache_GetPeers_Call { + return &ProtocolPeerCache_GetPeers_Call{Call: _e.mock.On("GetPeers", pid)} } -// NewProtocolPeerCache creates a new instance of ProtocolPeerCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProtocolPeerCache(t interface { - mock.TestingT - Cleanup(func()) -}) *ProtocolPeerCache { - mock := &ProtocolPeerCache{} - mock.Mock.Test(t) +func (_c *ProtocolPeerCache_GetPeers_Call) Run(run func(pid protocol.ID)) *ProtocolPeerCache_GetPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + run( + arg0, + ) + }) + return _c +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *ProtocolPeerCache_GetPeers_Call) Return(iDSlice peer.IDSlice) *ProtocolPeerCache_GetPeers_Call { + _c.Call.Return(iDSlice) + return _c +} - return mock +func (_c *ProtocolPeerCache_GetPeers_Call) RunAndReturn(run func(pid protocol.ID) peer.IDSlice) *ProtocolPeerCache_GetPeers_Call { + _c.Call.Return(run) + return _c +} + +// RemovePeer provides a mock function for the type ProtocolPeerCache +func (_mock *ProtocolPeerCache) RemovePeer(peerID peer.ID) { + _mock.Called(peerID) + return +} + +// ProtocolPeerCache_RemovePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemovePeer' +type ProtocolPeerCache_RemovePeer_Call struct { + *mock.Call +} + +// RemovePeer is a helper method to define mock.On call +// - peerID peer.ID +func (_e *ProtocolPeerCache_Expecter) RemovePeer(peerID interface{}) *ProtocolPeerCache_RemovePeer_Call { + return &ProtocolPeerCache_RemovePeer_Call{Call: _e.mock.On("RemovePeer", peerID)} +} + +func (_c *ProtocolPeerCache_RemovePeer_Call) Run(run func(peerID peer.ID)) *ProtocolPeerCache_RemovePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProtocolPeerCache_RemovePeer_Call) Return() *ProtocolPeerCache_RemovePeer_Call { + _c.Call.Return() + return _c +} + +func (_c *ProtocolPeerCache_RemovePeer_Call) RunAndReturn(run func(peerID peer.ID)) *ProtocolPeerCache_RemovePeer_Call { + _c.Run(run) + return _c +} + +// RemoveProtocols provides a mock function for the type ProtocolPeerCache +func (_mock *ProtocolPeerCache) RemoveProtocols(peerID peer.ID, protocols []protocol.ID) { + _mock.Called(peerID, protocols) + return +} + +// ProtocolPeerCache_RemoveProtocols_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemoveProtocols' +type ProtocolPeerCache_RemoveProtocols_Call struct { + *mock.Call +} + +// RemoveProtocols is a helper method to define mock.On call +// - peerID peer.ID +// - protocols []protocol.ID +func (_e *ProtocolPeerCache_Expecter) RemoveProtocols(peerID interface{}, protocols interface{}) *ProtocolPeerCache_RemoveProtocols_Call { + return &ProtocolPeerCache_RemoveProtocols_Call{Call: _e.mock.On("RemoveProtocols", peerID, protocols)} +} + +func (_c *ProtocolPeerCache_RemoveProtocols_Call) Run(run func(peerID peer.ID, protocols []protocol.ID)) *ProtocolPeerCache_RemoveProtocols_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 []protocol.ID + if args[1] != nil { + arg1 = args[1].([]protocol.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ProtocolPeerCache_RemoveProtocols_Call) Return() *ProtocolPeerCache_RemoveProtocols_Call { + _c.Call.Return() + return _c +} + +func (_c *ProtocolPeerCache_RemoveProtocols_Call) RunAndReturn(run func(peerID peer.ID, protocols []protocol.ID)) *ProtocolPeerCache_RemoveProtocols_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/pub_sub.go b/network/p2p/mock/pub_sub.go index 02b5054a609..849c2b7b061 100644 --- a/network/p2p/mock/pub_sub.go +++ b/network/p2p/mock/pub_sub.go @@ -1,72 +1,199 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" - - channels "github.com/onflow/flow-go/network/channels" + "context" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) - network "github.com/onflow/flow-go/network" +// NewPubSub creates a new instance of PubSub. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPubSub(t interface { + mock.TestingT + Cleanup(func()) +}) *PubSub { + mock := &PubSub{} + mock.Mock.Test(t) - p2p "github.com/onflow/flow-go/network/p2p" + t.Cleanup(func() { mock.AssertExpectations(t) }) - peer "github.com/libp2p/go-libp2p/core/peer" -) + return mock +} // PubSub is an autogenerated mock type for the PubSub type type PubSub struct { mock.Mock } -// GetLocalMeshPeers provides a mock function with given fields: topic -func (_m *PubSub) GetLocalMeshPeers(topic channels.Topic) []peer.ID { - ret := _m.Called(topic) +type PubSub_Expecter struct { + mock *mock.Mock +} + +func (_m *PubSub) EXPECT() *PubSub_Expecter { + return &PubSub_Expecter{mock: &_m.Mock} +} + +// GetLocalMeshPeers provides a mock function for the type PubSub +func (_mock *PubSub) GetLocalMeshPeers(topic channels.Topic) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for GetLocalMeshPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// Publish provides a mock function with given fields: ctx, messageScope -func (_m *PubSub) Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error { - ret := _m.Called(ctx, messageScope) +// PubSub_GetLocalMeshPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLocalMeshPeers' +type PubSub_GetLocalMeshPeers_Call struct { + *mock.Call +} + +// GetLocalMeshPeers is a helper method to define mock.On call +// - topic channels.Topic +func (_e *PubSub_Expecter) GetLocalMeshPeers(topic interface{}) *PubSub_GetLocalMeshPeers_Call { + return &PubSub_GetLocalMeshPeers_Call{Call: _e.mock.On("GetLocalMeshPeers", topic)} +} + +func (_c *PubSub_GetLocalMeshPeers_Call) Run(run func(topic channels.Topic)) *PubSub_GetLocalMeshPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSub_GetLocalMeshPeers_Call) Return(iDs []peer.ID) *PubSub_GetLocalMeshPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *PubSub_GetLocalMeshPeers_Call) RunAndReturn(run func(topic channels.Topic) []peer.ID) *PubSub_GetLocalMeshPeers_Call { + _c.Call.Return(run) + return _c +} + +// Publish provides a mock function for the type PubSub +func (_mock *PubSub) Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error { + ret := _mock.Called(ctx, messageScope) if len(ret) == 0 { panic("no return value specified for Publish") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, network.OutgoingMessageScope) error); ok { - r0 = rf(ctx, messageScope) + if returnFunc, ok := ret.Get(0).(func(context.Context, network.OutgoingMessageScope) error); ok { + r0 = returnFunc(ctx, messageScope) } else { r0 = ret.Error(0) } - return r0 } -// SetPubSub provides a mock function with given fields: ps -func (_m *PubSub) SetPubSub(ps p2p.PubSubAdapter) { - _m.Called(ps) +// PubSub_Publish_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Publish' +type PubSub_Publish_Call struct { + *mock.Call +} + +// Publish is a helper method to define mock.On call +// - ctx context.Context +// - messageScope network.OutgoingMessageScope +func (_e *PubSub_Expecter) Publish(ctx interface{}, messageScope interface{}) *PubSub_Publish_Call { + return &PubSub_Publish_Call{Call: _e.mock.On("Publish", ctx, messageScope)} +} + +func (_c *PubSub_Publish_Call) Run(run func(ctx context.Context, messageScope network.OutgoingMessageScope)) *PubSub_Publish_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 network.OutgoingMessageScope + if args[1] != nil { + arg1 = args[1].(network.OutgoingMessageScope) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSub_Publish_Call) Return(err error) *PubSub_Publish_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PubSub_Publish_Call) RunAndReturn(run func(ctx context.Context, messageScope network.OutgoingMessageScope) error) *PubSub_Publish_Call { + _c.Call.Return(run) + return _c +} + +// SetPubSub provides a mock function for the type PubSub +func (_mock *PubSub) SetPubSub(ps p2p.PubSubAdapter) { + _mock.Called(ps) + return } -// Subscribe provides a mock function with given fields: topic, topicValidator -func (_m *PubSub) Subscribe(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error) { - ret := _m.Called(topic, topicValidator) +// PubSub_SetPubSub_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetPubSub' +type PubSub_SetPubSub_Call struct { + *mock.Call +} + +// SetPubSub is a helper method to define mock.On call +// - ps p2p.PubSubAdapter +func (_e *PubSub_Expecter) SetPubSub(ps interface{}) *PubSub_SetPubSub_Call { + return &PubSub_SetPubSub_Call{Call: _e.mock.On("SetPubSub", ps)} +} + +func (_c *PubSub_SetPubSub_Call) Run(run func(ps p2p.PubSubAdapter)) *PubSub_SetPubSub_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.PubSubAdapter + if args[0] != nil { + arg0 = args[0].(p2p.PubSubAdapter) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSub_SetPubSub_Call) Return() *PubSub_SetPubSub_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSub_SetPubSub_Call) RunAndReturn(run func(ps p2p.PubSubAdapter)) *PubSub_SetPubSub_Call { + _c.Run(run) + return _c +} + +// Subscribe provides a mock function for the type PubSub +func (_mock *PubSub) Subscribe(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error) { + ret := _mock.Called(topic, topicValidator) if len(ret) == 0 { panic("no return value specified for Subscribe") @@ -74,54 +201,111 @@ func (_m *PubSub) Subscribe(topic channels.Topic, topicValidator p2p.TopicValida var r0 p2p.Subscription var r1 error - if rf, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) (p2p.Subscription, error)); ok { - return rf(topic, topicValidator) + if returnFunc, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) (p2p.Subscription, error)); ok { + return returnFunc(topic, topicValidator) } - if rf, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) p2p.Subscription); ok { - r0 = rf(topic, topicValidator) + if returnFunc, ok := ret.Get(0).(func(channels.Topic, p2p.TopicValidatorFunc) p2p.Subscription); ok { + r0 = returnFunc(topic, topicValidator) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.Subscription) } } - - if rf, ok := ret.Get(1).(func(channels.Topic, p2p.TopicValidatorFunc) error); ok { - r1 = rf(topic, topicValidator) + if returnFunc, ok := ret.Get(1).(func(channels.Topic, p2p.TopicValidatorFunc) error); ok { + r1 = returnFunc(topic, topicValidator) } else { r1 = ret.Error(1) } - return r0, r1 } -// Unsubscribe provides a mock function with given fields: topic -func (_m *PubSub) Unsubscribe(topic channels.Topic) error { - ret := _m.Called(topic) +// PubSub_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' +type PubSub_Subscribe_Call struct { + *mock.Call +} + +// Subscribe is a helper method to define mock.On call +// - topic channels.Topic +// - topicValidator p2p.TopicValidatorFunc +func (_e *PubSub_Expecter) Subscribe(topic interface{}, topicValidator interface{}) *PubSub_Subscribe_Call { + return &PubSub_Subscribe_Call{Call: _e.mock.On("Subscribe", topic, topicValidator)} +} + +func (_c *PubSub_Subscribe_Call) Run(run func(topic channels.Topic, topicValidator p2p.TopicValidatorFunc)) *PubSub_Subscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + var arg1 p2p.TopicValidatorFunc + if args[1] != nil { + arg1 = args[1].(p2p.TopicValidatorFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSub_Subscribe_Call) Return(subscription p2p.Subscription, err error) *PubSub_Subscribe_Call { + _c.Call.Return(subscription, err) + return _c +} + +func (_c *PubSub_Subscribe_Call) RunAndReturn(run func(topic channels.Topic, topicValidator p2p.TopicValidatorFunc) (p2p.Subscription, error)) *PubSub_Subscribe_Call { + _c.Call.Return(run) + return _c +} + +// Unsubscribe provides a mock function for the type PubSub +func (_mock *PubSub) Unsubscribe(topic channels.Topic) error { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for Unsubscribe") } var r0 error - if rf, ok := ret.Get(0).(func(channels.Topic) error); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) error); ok { + r0 = returnFunc(topic) } else { r0 = ret.Error(0) } - return r0 } -// NewPubSub creates a new instance of PubSub. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPubSub(t interface { - mock.TestingT - Cleanup(func()) -}) *PubSub { - mock := &PubSub{} - mock.Mock.Test(t) +// PubSub_Unsubscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Unsubscribe' +type PubSub_Unsubscribe_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Unsubscribe is a helper method to define mock.On call +// - topic channels.Topic +func (_e *PubSub_Expecter) Unsubscribe(topic interface{}) *PubSub_Unsubscribe_Call { + return &PubSub_Unsubscribe_Call{Call: _e.mock.On("Unsubscribe", topic)} +} - return mock +func (_c *PubSub_Unsubscribe_Call) Run(run func(topic channels.Topic)) *PubSub_Unsubscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSub_Unsubscribe_Call) Return(err error) *PubSub_Unsubscribe_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PubSub_Unsubscribe_Call) RunAndReturn(run func(topic channels.Topic) error) *PubSub_Unsubscribe_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/pub_sub_adapter.go b/network/p2p/mock/pub_sub_adapter.go index 113eae03b06..65280bfb473 100644 --- a/network/p2p/mock/pub_sub_adapter.go +++ b/network/p2p/mock/pub_sub_adapter.go @@ -1,93 +1,233 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - channels "github.com/onflow/flow-go/network/channels" - - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) + +// NewPubSubAdapter creates a new instance of PubSubAdapter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPubSubAdapter(t interface { + mock.TestingT + Cleanup(func()) +}) *PubSubAdapter { + mock := &PubSubAdapter{} + mock.Mock.Test(t) - p2p "github.com/onflow/flow-go/network/p2p" + t.Cleanup(func() { mock.AssertExpectations(t) }) - peer "github.com/libp2p/go-libp2p/core/peer" -) + return mock +} // PubSubAdapter is an autogenerated mock type for the PubSubAdapter type type PubSubAdapter struct { mock.Mock } -// ActiveClustersChanged provides a mock function with given fields: _a0 -func (_m *PubSubAdapter) ActiveClustersChanged(_a0 flow.ChainIDList) { - _m.Called(_a0) +type PubSubAdapter_Expecter struct { + mock *mock.Mock } -// Done provides a mock function with no fields -func (_m *PubSubAdapter) Done() <-chan struct{} { - ret := _m.Called() +func (_m *PubSubAdapter) EXPECT() *PubSubAdapter_Expecter { + return &PubSubAdapter_Expecter{mock: &_m.Mock} +} + +// ActiveClustersChanged provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) ActiveClustersChanged(chainIDList flow.ChainIDList) { + _mock.Called(chainIDList) + return +} + +// PubSubAdapter_ActiveClustersChanged_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ActiveClustersChanged' +type PubSubAdapter_ActiveClustersChanged_Call struct { + *mock.Call +} + +// ActiveClustersChanged is a helper method to define mock.On call +// - chainIDList flow.ChainIDList +func (_e *PubSubAdapter_Expecter) ActiveClustersChanged(chainIDList interface{}) *PubSubAdapter_ActiveClustersChanged_Call { + return &PubSubAdapter_ActiveClustersChanged_Call{Call: _e.mock.On("ActiveClustersChanged", chainIDList)} +} + +func (_c *PubSubAdapter_ActiveClustersChanged_Call) Run(run func(chainIDList flow.ChainIDList)) *PubSubAdapter_ActiveClustersChanged_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ChainIDList + if args[0] != nil { + arg0 = args[0].(flow.ChainIDList) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapter_ActiveClustersChanged_Call) Return() *PubSubAdapter_ActiveClustersChanged_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapter_ActiveClustersChanged_Call) RunAndReturn(run func(chainIDList flow.ChainIDList)) *PubSubAdapter_ActiveClustersChanged_Call { + _c.Run(run) + return _c +} + +// Done provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// GetLocalMeshPeers provides a mock function with given fields: topic -func (_m *PubSubAdapter) GetLocalMeshPeers(topic channels.Topic) []peer.ID { - ret := _m.Called(topic) +// PubSubAdapter_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type PubSubAdapter_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *PubSubAdapter_Expecter) Done() *PubSubAdapter_Done_Call { + return &PubSubAdapter_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *PubSubAdapter_Done_Call) Run(run func()) *PubSubAdapter_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PubSubAdapter_Done_Call) Return(valCh <-chan struct{}) *PubSubAdapter_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *PubSubAdapter_Done_Call) RunAndReturn(run func() <-chan struct{}) *PubSubAdapter_Done_Call { + _c.Call.Return(run) + return _c +} + +// GetLocalMeshPeers provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) GetLocalMeshPeers(topic channels.Topic) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for GetLocalMeshPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// GetTopics provides a mock function with no fields -func (_m *PubSubAdapter) GetTopics() []string { - ret := _m.Called() +// PubSubAdapter_GetLocalMeshPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLocalMeshPeers' +type PubSubAdapter_GetLocalMeshPeers_Call struct { + *mock.Call +} + +// GetLocalMeshPeers is a helper method to define mock.On call +// - topic channels.Topic +func (_e *PubSubAdapter_Expecter) GetLocalMeshPeers(topic interface{}) *PubSubAdapter_GetLocalMeshPeers_Call { + return &PubSubAdapter_GetLocalMeshPeers_Call{Call: _e.mock.On("GetLocalMeshPeers", topic)} +} + +func (_c *PubSubAdapter_GetLocalMeshPeers_Call) Run(run func(topic channels.Topic)) *PubSubAdapter_GetLocalMeshPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapter_GetLocalMeshPeers_Call) Return(iDs []peer.ID) *PubSubAdapter_GetLocalMeshPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *PubSubAdapter_GetLocalMeshPeers_Call) RunAndReturn(run func(topic channels.Topic) []peer.ID) *PubSubAdapter_GetLocalMeshPeers_Call { + _c.Call.Return(run) + return _c +} + +// GetTopics provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) GetTopics() []string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetTopics") } var r0 []string - if rf, ok := ret.Get(0).(func() []string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []string); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]string) } } - return r0 } -// Join provides a mock function with given fields: topic -func (_m *PubSubAdapter) Join(topic string) (p2p.Topic, error) { - ret := _m.Called(topic) +// PubSubAdapter_GetTopics_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTopics' +type PubSubAdapter_GetTopics_Call struct { + *mock.Call +} + +// GetTopics is a helper method to define mock.On call +func (_e *PubSubAdapter_Expecter) GetTopics() *PubSubAdapter_GetTopics_Call { + return &PubSubAdapter_GetTopics_Call{Call: _e.mock.On("GetTopics")} +} + +func (_c *PubSubAdapter_GetTopics_Call) Run(run func()) *PubSubAdapter_GetTopics_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PubSubAdapter_GetTopics_Call) Return(strings []string) *PubSubAdapter_GetTopics_Call { + _c.Call.Return(strings) + return _c +} + +func (_c *PubSubAdapter_GetTopics_Call) RunAndReturn(run func() []string) *PubSubAdapter_GetTopics_Call { + _c.Call.Return(run) + return _c +} + +// Join provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) Join(topic string) (p2p.Topic, error) { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for Join") @@ -95,137 +235,347 @@ func (_m *PubSubAdapter) Join(topic string) (p2p.Topic, error) { var r0 p2p.Topic var r1 error - if rf, ok := ret.Get(0).(func(string) (p2p.Topic, error)); ok { - return rf(topic) + if returnFunc, ok := ret.Get(0).(func(string) (p2p.Topic, error)); ok { + return returnFunc(topic) } - if rf, ok := ret.Get(0).(func(string) p2p.Topic); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(string) p2p.Topic); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.Topic) } } - - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(topic) + if returnFunc, ok := ret.Get(1).(func(string) error); ok { + r1 = returnFunc(topic) } else { r1 = ret.Error(1) } - return r0, r1 } -// ListPeers provides a mock function with given fields: topic -func (_m *PubSubAdapter) ListPeers(topic string) []peer.ID { - ret := _m.Called(topic) +// PubSubAdapter_Join_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Join' +type PubSubAdapter_Join_Call struct { + *mock.Call +} + +// Join is a helper method to define mock.On call +// - topic string +func (_e *PubSubAdapter_Expecter) Join(topic interface{}) *PubSubAdapter_Join_Call { + return &PubSubAdapter_Join_Call{Call: _e.mock.On("Join", topic)} +} + +func (_c *PubSubAdapter_Join_Call) Run(run func(topic string)) *PubSubAdapter_Join_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapter_Join_Call) Return(topic1 p2p.Topic, err error) *PubSubAdapter_Join_Call { + _c.Call.Return(topic1, err) + return _c +} + +func (_c *PubSubAdapter_Join_Call) RunAndReturn(run func(topic string) (p2p.Topic, error)) *PubSubAdapter_Join_Call { + _c.Call.Return(run) + return _c +} + +// ListPeers provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) ListPeers(topic string) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for ListPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(string) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(string) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// PeerScoreExposer provides a mock function with no fields -func (_m *PubSubAdapter) PeerScoreExposer() p2p.PeerScoreExposer { - ret := _m.Called() +// PubSubAdapter_ListPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPeers' +type PubSubAdapter_ListPeers_Call struct { + *mock.Call +} + +// ListPeers is a helper method to define mock.On call +// - topic string +func (_e *PubSubAdapter_Expecter) ListPeers(topic interface{}) *PubSubAdapter_ListPeers_Call { + return &PubSubAdapter_ListPeers_Call{Call: _e.mock.On("ListPeers", topic)} +} + +func (_c *PubSubAdapter_ListPeers_Call) Run(run func(topic string)) *PubSubAdapter_ListPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapter_ListPeers_Call) Return(iDs []peer.ID) *PubSubAdapter_ListPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *PubSubAdapter_ListPeers_Call) RunAndReturn(run func(topic string) []peer.ID) *PubSubAdapter_ListPeers_Call { + _c.Call.Return(run) + return _c +} + +// PeerScoreExposer provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) PeerScoreExposer() p2p.PeerScoreExposer { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PeerScoreExposer") } var r0 p2p.PeerScoreExposer - if rf, ok := ret.Get(0).(func() p2p.PeerScoreExposer); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() p2p.PeerScoreExposer); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.PeerScoreExposer) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *PubSubAdapter) Ready() <-chan struct{} { - ret := _m.Called() +// PubSubAdapter_PeerScoreExposer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PeerScoreExposer' +type PubSubAdapter_PeerScoreExposer_Call struct { + *mock.Call +} + +// PeerScoreExposer is a helper method to define mock.On call +func (_e *PubSubAdapter_Expecter) PeerScoreExposer() *PubSubAdapter_PeerScoreExposer_Call { + return &PubSubAdapter_PeerScoreExposer_Call{Call: _e.mock.On("PeerScoreExposer")} +} + +func (_c *PubSubAdapter_PeerScoreExposer_Call) Run(run func()) *PubSubAdapter_PeerScoreExposer_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PubSubAdapter_PeerScoreExposer_Call) Return(peerScoreExposer p2p.PeerScoreExposer) *PubSubAdapter_PeerScoreExposer_Call { + _c.Call.Return(peerScoreExposer) + return _c +} + +func (_c *PubSubAdapter_PeerScoreExposer_Call) RunAndReturn(run func() p2p.PeerScoreExposer) *PubSubAdapter_PeerScoreExposer_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// RegisterTopicValidator provides a mock function with given fields: topic, topicValidator -func (_m *PubSubAdapter) RegisterTopicValidator(topic string, topicValidator p2p.TopicValidatorFunc) error { - ret := _m.Called(topic, topicValidator) +// PubSubAdapter_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type PubSubAdapter_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *PubSubAdapter_Expecter) Ready() *PubSubAdapter_Ready_Call { + return &PubSubAdapter_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *PubSubAdapter_Ready_Call) Run(run func()) *PubSubAdapter_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PubSubAdapter_Ready_Call) Return(valCh <-chan struct{}) *PubSubAdapter_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *PubSubAdapter_Ready_Call) RunAndReturn(run func() <-chan struct{}) *PubSubAdapter_Ready_Call { + _c.Call.Return(run) + return _c +} + +// RegisterTopicValidator provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) RegisterTopicValidator(topic string, topicValidator p2p.TopicValidatorFunc) error { + ret := _mock.Called(topic, topicValidator) if len(ret) == 0 { panic("no return value specified for RegisterTopicValidator") } var r0 error - if rf, ok := ret.Get(0).(func(string, p2p.TopicValidatorFunc) error); ok { - r0 = rf(topic, topicValidator) + if returnFunc, ok := ret.Get(0).(func(string, p2p.TopicValidatorFunc) error); ok { + r0 = returnFunc(topic, topicValidator) } else { r0 = ret.Error(0) } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *PubSubAdapter) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// PubSubAdapter_RegisterTopicValidator_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterTopicValidator' +type PubSubAdapter_RegisterTopicValidator_Call struct { + *mock.Call } -// UnregisterTopicValidator provides a mock function with given fields: topic -func (_m *PubSubAdapter) UnregisterTopicValidator(topic string) error { - ret := _m.Called(topic) +// RegisterTopicValidator is a helper method to define mock.On call +// - topic string +// - topicValidator p2p.TopicValidatorFunc +func (_e *PubSubAdapter_Expecter) RegisterTopicValidator(topic interface{}, topicValidator interface{}) *PubSubAdapter_RegisterTopicValidator_Call { + return &PubSubAdapter_RegisterTopicValidator_Call{Call: _e.mock.On("RegisterTopicValidator", topic, topicValidator)} +} + +func (_c *PubSubAdapter_RegisterTopicValidator_Call) Run(run func(topic string, topicValidator p2p.TopicValidatorFunc)) *PubSubAdapter_RegisterTopicValidator_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 p2p.TopicValidatorFunc + if args[1] != nil { + arg1 = args[1].(p2p.TopicValidatorFunc) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubAdapter_RegisterTopicValidator_Call) Return(err error) *PubSubAdapter_RegisterTopicValidator_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PubSubAdapter_RegisterTopicValidator_Call) RunAndReturn(run func(topic string, topicValidator p2p.TopicValidatorFunc) error) *PubSubAdapter_RegisterTopicValidator_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// PubSubAdapter_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type PubSubAdapter_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *PubSubAdapter_Expecter) Start(signalerContext interface{}) *PubSubAdapter_Start_Call { + return &PubSubAdapter_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *PubSubAdapter_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *PubSubAdapter_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapter_Start_Call) Return() *PubSubAdapter_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapter_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *PubSubAdapter_Start_Call { + _c.Run(run) + return _c +} + +// UnregisterTopicValidator provides a mock function for the type PubSubAdapter +func (_mock *PubSubAdapter) UnregisterTopicValidator(topic string) error { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for UnregisterTopicValidator") } var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(string) error); ok { + r0 = returnFunc(topic) } else { r0 = ret.Error(0) } - return r0 } -// NewPubSubAdapter creates a new instance of PubSubAdapter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPubSubAdapter(t interface { - mock.TestingT - Cleanup(func()) -}) *PubSubAdapter { - mock := &PubSubAdapter{} - mock.Mock.Test(t) +// PubSubAdapter_UnregisterTopicValidator_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnregisterTopicValidator' +type PubSubAdapter_UnregisterTopicValidator_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UnregisterTopicValidator is a helper method to define mock.On call +// - topic string +func (_e *PubSubAdapter_Expecter) UnregisterTopicValidator(topic interface{}) *PubSubAdapter_UnregisterTopicValidator_Call { + return &PubSubAdapter_UnregisterTopicValidator_Call{Call: _e.mock.On("UnregisterTopicValidator", topic)} +} - return mock +func (_c *PubSubAdapter_UnregisterTopicValidator_Call) Run(run func(topic string)) *PubSubAdapter_UnregisterTopicValidator_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapter_UnregisterTopicValidator_Call) Return(err error) *PubSubAdapter_UnregisterTopicValidator_Call { + _c.Call.Return(err) + return _c +} + +func (_c *PubSubAdapter_UnregisterTopicValidator_Call) RunAndReturn(run func(topic string) error) *PubSubAdapter_UnregisterTopicValidator_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/pub_sub_adapter_config.go b/network/p2p/mock/pub_sub_adapter_config.go index 1c7974c66ef..f4c122f98a5 100644 --- a/network/p2p/mock/pub_sub_adapter_config.go +++ b/network/p2p/mock/pub_sub_adapter_config.go @@ -1,76 +1,406 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - p2p "github.com/onflow/flow-go/network/p2p" + "time" + + "github.com/libp2p/go-libp2p/core/routing" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" +) - routing "github.com/libp2p/go-libp2p/core/routing" +// NewPubSubAdapterConfig creates a new instance of PubSubAdapterConfig. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPubSubAdapterConfig(t interface { + mock.TestingT + Cleanup(func()) +}) *PubSubAdapterConfig { + mock := &PubSubAdapterConfig{} + mock.Mock.Test(t) - time "time" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // PubSubAdapterConfig is an autogenerated mock type for the PubSubAdapterConfig type type PubSubAdapterConfig struct { mock.Mock } -// WithMessageIdFunction provides a mock function with given fields: f -func (_m *PubSubAdapterConfig) WithMessageIdFunction(f func([]byte) string) { - _m.Called(f) +type PubSubAdapterConfig_Expecter struct { + mock *mock.Mock } -// WithPeerGater provides a mock function with given fields: topicDeliveryWeights, sourceDecay -func (_m *PubSubAdapterConfig) WithPeerGater(topicDeliveryWeights map[string]float64, sourceDecay time.Duration) { - _m.Called(topicDeliveryWeights, sourceDecay) +func (_m *PubSubAdapterConfig) EXPECT() *PubSubAdapterConfig_Expecter { + return &PubSubAdapterConfig_Expecter{mock: &_m.Mock} } -// WithRoutingDiscovery provides a mock function with given fields: _a0 -func (_m *PubSubAdapterConfig) WithRoutingDiscovery(_a0 routing.ContentRouting) { - _m.Called(_a0) +// WithMessageIdFunction provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithMessageIdFunction(f func([]byte) string) { + _mock.Called(f) + return } -// WithRpcInspector provides a mock function with given fields: _a0 -func (_m *PubSubAdapterConfig) WithRpcInspector(_a0 p2p.GossipSubRPCInspector) { - _m.Called(_a0) +// PubSubAdapterConfig_WithMessageIdFunction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithMessageIdFunction' +type PubSubAdapterConfig_WithMessageIdFunction_Call struct { + *mock.Call } -// WithScoreOption provides a mock function with given fields: _a0 -func (_m *PubSubAdapterConfig) WithScoreOption(_a0 p2p.ScoreOptionBuilder) { - _m.Called(_a0) +// WithMessageIdFunction is a helper method to define mock.On call +// - f func([]byte) string +func (_e *PubSubAdapterConfig_Expecter) WithMessageIdFunction(f interface{}) *PubSubAdapterConfig_WithMessageIdFunction_Call { + return &PubSubAdapterConfig_WithMessageIdFunction_Call{Call: _e.mock.On("WithMessageIdFunction", f)} } -// WithScoreTracer provides a mock function with given fields: tracer -func (_m *PubSubAdapterConfig) WithScoreTracer(tracer p2p.PeerScoreTracer) { - _m.Called(tracer) +func (_c *PubSubAdapterConfig_WithMessageIdFunction_Call) Run(run func(f func([]byte) string)) *PubSubAdapterConfig_WithMessageIdFunction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func([]byte) string + if args[0] != nil { + arg0 = args[0].(func([]byte) string) + } + run( + arg0, + ) + }) + return _c } -// WithSubscriptionFilter provides a mock function with given fields: _a0 -func (_m *PubSubAdapterConfig) WithSubscriptionFilter(_a0 p2p.SubscriptionFilter) { - _m.Called(_a0) +func (_c *PubSubAdapterConfig_WithMessageIdFunction_Call) Return() *PubSubAdapterConfig_WithMessageIdFunction_Call { + _c.Call.Return() + return _c } -// WithTracer provides a mock function with given fields: t -func (_m *PubSubAdapterConfig) WithTracer(t p2p.PubSubTracer) { - _m.Called(t) +func (_c *PubSubAdapterConfig_WithMessageIdFunction_Call) RunAndReturn(run func(f func([]byte) string)) *PubSubAdapterConfig_WithMessageIdFunction_Call { + _c.Run(run) + return _c } -// WithValidateQueueSize provides a mock function with given fields: _a0 -func (_m *PubSubAdapterConfig) WithValidateQueueSize(_a0 int) { - _m.Called(_a0) +// WithPeerGater provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithPeerGater(topicDeliveryWeights map[string]float64, sourceDecay time.Duration) { + _mock.Called(topicDeliveryWeights, sourceDecay) + return } -// NewPubSubAdapterConfig creates a new instance of PubSubAdapterConfig. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPubSubAdapterConfig(t interface { - mock.TestingT - Cleanup(func()) -}) *PubSubAdapterConfig { - mock := &PubSubAdapterConfig{} - mock.Mock.Test(t) +// PubSubAdapterConfig_WithPeerGater_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithPeerGater' +type PubSubAdapterConfig_WithPeerGater_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WithPeerGater is a helper method to define mock.On call +// - topicDeliveryWeights map[string]float64 +// - sourceDecay time.Duration +func (_e *PubSubAdapterConfig_Expecter) WithPeerGater(topicDeliveryWeights interface{}, sourceDecay interface{}) *PubSubAdapterConfig_WithPeerGater_Call { + return &PubSubAdapterConfig_WithPeerGater_Call{Call: _e.mock.On("WithPeerGater", topicDeliveryWeights, sourceDecay)} +} - return mock +func (_c *PubSubAdapterConfig_WithPeerGater_Call) Run(run func(topicDeliveryWeights map[string]float64, sourceDecay time.Duration)) *PubSubAdapterConfig_WithPeerGater_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 map[string]float64 + if args[0] != nil { + arg0 = args[0].(map[string]float64) + } + var arg1 time.Duration + if args[1] != nil { + arg1 = args[1].(time.Duration) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithPeerGater_Call) Return() *PubSubAdapterConfig_WithPeerGater_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithPeerGater_Call) RunAndReturn(run func(topicDeliveryWeights map[string]float64, sourceDecay time.Duration)) *PubSubAdapterConfig_WithPeerGater_Call { + _c.Run(run) + return _c +} + +// WithRoutingDiscovery provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithRoutingDiscovery(contentRouting routing.ContentRouting) { + _mock.Called(contentRouting) + return +} + +// PubSubAdapterConfig_WithRoutingDiscovery_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithRoutingDiscovery' +type PubSubAdapterConfig_WithRoutingDiscovery_Call struct { + *mock.Call +} + +// WithRoutingDiscovery is a helper method to define mock.On call +// - contentRouting routing.ContentRouting +func (_e *PubSubAdapterConfig_Expecter) WithRoutingDiscovery(contentRouting interface{}) *PubSubAdapterConfig_WithRoutingDiscovery_Call { + return &PubSubAdapterConfig_WithRoutingDiscovery_Call{Call: _e.mock.On("WithRoutingDiscovery", contentRouting)} +} + +func (_c *PubSubAdapterConfig_WithRoutingDiscovery_Call) Run(run func(contentRouting routing.ContentRouting)) *PubSubAdapterConfig_WithRoutingDiscovery_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 routing.ContentRouting + if args[0] != nil { + arg0 = args[0].(routing.ContentRouting) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithRoutingDiscovery_Call) Return() *PubSubAdapterConfig_WithRoutingDiscovery_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithRoutingDiscovery_Call) RunAndReturn(run func(contentRouting routing.ContentRouting)) *PubSubAdapterConfig_WithRoutingDiscovery_Call { + _c.Run(run) + return _c +} + +// WithRpcInspector provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithRpcInspector(gossipSubRPCInspector p2p.GossipSubRPCInspector) { + _mock.Called(gossipSubRPCInspector) + return +} + +// PubSubAdapterConfig_WithRpcInspector_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithRpcInspector' +type PubSubAdapterConfig_WithRpcInspector_Call struct { + *mock.Call +} + +// WithRpcInspector is a helper method to define mock.On call +// - gossipSubRPCInspector p2p.GossipSubRPCInspector +func (_e *PubSubAdapterConfig_Expecter) WithRpcInspector(gossipSubRPCInspector interface{}) *PubSubAdapterConfig_WithRpcInspector_Call { + return &PubSubAdapterConfig_WithRpcInspector_Call{Call: _e.mock.On("WithRpcInspector", gossipSubRPCInspector)} +} + +func (_c *PubSubAdapterConfig_WithRpcInspector_Call) Run(run func(gossipSubRPCInspector p2p.GossipSubRPCInspector)) *PubSubAdapterConfig_WithRpcInspector_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.GossipSubRPCInspector + if args[0] != nil { + arg0 = args[0].(p2p.GossipSubRPCInspector) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithRpcInspector_Call) Return() *PubSubAdapterConfig_WithRpcInspector_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithRpcInspector_Call) RunAndReturn(run func(gossipSubRPCInspector p2p.GossipSubRPCInspector)) *PubSubAdapterConfig_WithRpcInspector_Call { + _c.Run(run) + return _c +} + +// WithScoreOption provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithScoreOption(scoreOptionBuilder p2p.ScoreOptionBuilder) { + _mock.Called(scoreOptionBuilder) + return +} + +// PubSubAdapterConfig_WithScoreOption_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithScoreOption' +type PubSubAdapterConfig_WithScoreOption_Call struct { + *mock.Call +} + +// WithScoreOption is a helper method to define mock.On call +// - scoreOptionBuilder p2p.ScoreOptionBuilder +func (_e *PubSubAdapterConfig_Expecter) WithScoreOption(scoreOptionBuilder interface{}) *PubSubAdapterConfig_WithScoreOption_Call { + return &PubSubAdapterConfig_WithScoreOption_Call{Call: _e.mock.On("WithScoreOption", scoreOptionBuilder)} +} + +func (_c *PubSubAdapterConfig_WithScoreOption_Call) Run(run func(scoreOptionBuilder p2p.ScoreOptionBuilder)) *PubSubAdapterConfig_WithScoreOption_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.ScoreOptionBuilder + if args[0] != nil { + arg0 = args[0].(p2p.ScoreOptionBuilder) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithScoreOption_Call) Return() *PubSubAdapterConfig_WithScoreOption_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithScoreOption_Call) RunAndReturn(run func(scoreOptionBuilder p2p.ScoreOptionBuilder)) *PubSubAdapterConfig_WithScoreOption_Call { + _c.Run(run) + return _c +} + +// WithScoreTracer provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithScoreTracer(tracer p2p.PeerScoreTracer) { + _mock.Called(tracer) + return +} + +// PubSubAdapterConfig_WithScoreTracer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithScoreTracer' +type PubSubAdapterConfig_WithScoreTracer_Call struct { + *mock.Call +} + +// WithScoreTracer is a helper method to define mock.On call +// - tracer p2p.PeerScoreTracer +func (_e *PubSubAdapterConfig_Expecter) WithScoreTracer(tracer interface{}) *PubSubAdapterConfig_WithScoreTracer_Call { + return &PubSubAdapterConfig_WithScoreTracer_Call{Call: _e.mock.On("WithScoreTracer", tracer)} +} + +func (_c *PubSubAdapterConfig_WithScoreTracer_Call) Run(run func(tracer p2p.PeerScoreTracer)) *PubSubAdapterConfig_WithScoreTracer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.PeerScoreTracer + if args[0] != nil { + arg0 = args[0].(p2p.PeerScoreTracer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithScoreTracer_Call) Return() *PubSubAdapterConfig_WithScoreTracer_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithScoreTracer_Call) RunAndReturn(run func(tracer p2p.PeerScoreTracer)) *PubSubAdapterConfig_WithScoreTracer_Call { + _c.Run(run) + return _c +} + +// WithSubscriptionFilter provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithSubscriptionFilter(subscriptionFilter p2p.SubscriptionFilter) { + _mock.Called(subscriptionFilter) + return +} + +// PubSubAdapterConfig_WithSubscriptionFilter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithSubscriptionFilter' +type PubSubAdapterConfig_WithSubscriptionFilter_Call struct { + *mock.Call +} + +// WithSubscriptionFilter is a helper method to define mock.On call +// - subscriptionFilter p2p.SubscriptionFilter +func (_e *PubSubAdapterConfig_Expecter) WithSubscriptionFilter(subscriptionFilter interface{}) *PubSubAdapterConfig_WithSubscriptionFilter_Call { + return &PubSubAdapterConfig_WithSubscriptionFilter_Call{Call: _e.mock.On("WithSubscriptionFilter", subscriptionFilter)} +} + +func (_c *PubSubAdapterConfig_WithSubscriptionFilter_Call) Run(run func(subscriptionFilter p2p.SubscriptionFilter)) *PubSubAdapterConfig_WithSubscriptionFilter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.SubscriptionFilter + if args[0] != nil { + arg0 = args[0].(p2p.SubscriptionFilter) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithSubscriptionFilter_Call) Return() *PubSubAdapterConfig_WithSubscriptionFilter_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithSubscriptionFilter_Call) RunAndReturn(run func(subscriptionFilter p2p.SubscriptionFilter)) *PubSubAdapterConfig_WithSubscriptionFilter_Call { + _c.Run(run) + return _c +} + +// WithTracer provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithTracer(t p2p.PubSubTracer) { + _mock.Called(t) + return +} + +// PubSubAdapterConfig_WithTracer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithTracer' +type PubSubAdapterConfig_WithTracer_Call struct { + *mock.Call +} + +// WithTracer is a helper method to define mock.On call +// - t p2p.PubSubTracer +func (_e *PubSubAdapterConfig_Expecter) WithTracer(t interface{}) *PubSubAdapterConfig_WithTracer_Call { + return &PubSubAdapterConfig_WithTracer_Call{Call: _e.mock.On("WithTracer", t)} +} + +func (_c *PubSubAdapterConfig_WithTracer_Call) Run(run func(t p2p.PubSubTracer)) *PubSubAdapterConfig_WithTracer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.PubSubTracer + if args[0] != nil { + arg0 = args[0].(p2p.PubSubTracer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithTracer_Call) Return() *PubSubAdapterConfig_WithTracer_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithTracer_Call) RunAndReturn(run func(t p2p.PubSubTracer)) *PubSubAdapterConfig_WithTracer_Call { + _c.Run(run) + return _c +} + +// WithValidateQueueSize provides a mock function for the type PubSubAdapterConfig +func (_mock *PubSubAdapterConfig) WithValidateQueueSize(n int) { + _mock.Called(n) + return +} + +// PubSubAdapterConfig_WithValidateQueueSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithValidateQueueSize' +type PubSubAdapterConfig_WithValidateQueueSize_Call struct { + *mock.Call +} + +// WithValidateQueueSize is a helper method to define mock.On call +// - n int +func (_e *PubSubAdapterConfig_Expecter) WithValidateQueueSize(n interface{}) *PubSubAdapterConfig_WithValidateQueueSize_Call { + return &PubSubAdapterConfig_WithValidateQueueSize_Call{Call: _e.mock.On("WithValidateQueueSize", n)} +} + +func (_c *PubSubAdapterConfig_WithValidateQueueSize_Call) Run(run func(n int)) *PubSubAdapterConfig_WithValidateQueueSize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 int + if args[0] != nil { + arg0 = args[0].(int) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubAdapterConfig_WithValidateQueueSize_Call) Return() *PubSubAdapterConfig_WithValidateQueueSize_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubAdapterConfig_WithValidateQueueSize_Call) RunAndReturn(run func(n int)) *PubSubAdapterConfig_WithValidateQueueSize_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/pub_sub_tracer.go b/network/p2p/mock/pub_sub_tracer.go index d4c05ba73d7..469d66f33c0 100644 --- a/network/p2p/mock/pub_sub_tracer.go +++ b/network/p2p/mock/pub_sub_tracer.go @@ -1,229 +1,1008 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - channels "github.com/onflow/flow-go/network/channels" - + "github.com/libp2p/go-libp2p-pubsub" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/onflow/flow-go/module/irrecoverable" + "github.com/onflow/flow-go/network/channels" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewPubSubTracer creates a new instance of PubSubTracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPubSubTracer(t interface { + mock.TestingT + Cleanup(func()) +}) *PubSubTracer { + mock := &PubSubTracer{} + mock.Mock.Test(t) - protocol "github.com/libp2p/go-libp2p/core/protocol" + t.Cleanup(func() { mock.AssertExpectations(t) }) - pubsub "github.com/libp2p/go-libp2p-pubsub" -) + return mock +} // PubSubTracer is an autogenerated mock type for the PubSubTracer type type PubSubTracer struct { mock.Mock } -// AddPeer provides a mock function with given fields: p, proto -func (_m *PubSubTracer) AddPeer(p peer.ID, proto protocol.ID) { - _m.Called(p, proto) +type PubSubTracer_Expecter struct { + mock *mock.Mock } -// DeliverMessage provides a mock function with given fields: msg -func (_m *PubSubTracer) DeliverMessage(msg *pubsub.Message) { - _m.Called(msg) +func (_m *PubSubTracer) EXPECT() *PubSubTracer_Expecter { + return &PubSubTracer_Expecter{mock: &_m.Mock} } -// Done provides a mock function with no fields -func (_m *PubSubTracer) Done() <-chan struct{} { - ret := _m.Called() +// AddPeer provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) AddPeer(p peer.ID, proto protocol.ID) { + _mock.Called(p, proto) + return +} + +// PubSubTracer_AddPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddPeer' +type PubSubTracer_AddPeer_Call struct { + *mock.Call +} + +// AddPeer is a helper method to define mock.On call +// - p peer.ID +// - proto protocol.ID +func (_e *PubSubTracer_Expecter) AddPeer(p interface{}, proto interface{}) *PubSubTracer_AddPeer_Call { + return &PubSubTracer_AddPeer_Call{Call: _e.mock.On("AddPeer", p, proto)} +} + +func (_c *PubSubTracer_AddPeer_Call) Run(run func(p peer.ID, proto protocol.ID)) *PubSubTracer_AddPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 protocol.ID + if args[1] != nil { + arg1 = args[1].(protocol.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubTracer_AddPeer_Call) Return() *PubSubTracer_AddPeer_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_AddPeer_Call) RunAndReturn(run func(p peer.ID, proto protocol.ID)) *PubSubTracer_AddPeer_Call { + _c.Run(run) + return _c +} + +// DeliverMessage provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) DeliverMessage(msg *pubsub.Message) { + _mock.Called(msg) + return +} + +// PubSubTracer_DeliverMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeliverMessage' +type PubSubTracer_DeliverMessage_Call struct { + *mock.Call +} + +// DeliverMessage is a helper method to define mock.On call +// - msg *pubsub.Message +func (_e *PubSubTracer_Expecter) DeliverMessage(msg interface{}) *PubSubTracer_DeliverMessage_Call { + return &PubSubTracer_DeliverMessage_Call{Call: _e.mock.On("DeliverMessage", msg)} +} + +func (_c *PubSubTracer_DeliverMessage_Call) Run(run func(msg *pubsub.Message)) *PubSubTracer_DeliverMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.Message + if args[0] != nil { + arg0 = args[0].(*pubsub.Message) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_DeliverMessage_Call) Return() *PubSubTracer_DeliverMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_DeliverMessage_Call) RunAndReturn(run func(msg *pubsub.Message)) *PubSubTracer_DeliverMessage_Call { + _c.Run(run) + return _c +} + +// Done provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// DropRPC provides a mock function with given fields: rpc, p -func (_m *PubSubTracer) DropRPC(rpc *pubsub.RPC, p peer.ID) { - _m.Called(rpc, p) +// PubSubTracer_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type PubSubTracer_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *PubSubTracer_Expecter) Done() *PubSubTracer_Done_Call { + return &PubSubTracer_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *PubSubTracer_Done_Call) Run(run func()) *PubSubTracer_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PubSubTracer_Done_Call) Return(valCh <-chan struct{}) *PubSubTracer_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *PubSubTracer_Done_Call) RunAndReturn(run func() <-chan struct{}) *PubSubTracer_Done_Call { + _c.Call.Return(run) + return _c +} + +// DropRPC provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) DropRPC(rpc *pubsub.RPC, p peer.ID) { + _mock.Called(rpc, p) + return +} + +// PubSubTracer_DropRPC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DropRPC' +type PubSubTracer_DropRPC_Call struct { + *mock.Call +} + +// DropRPC is a helper method to define mock.On call +// - rpc *pubsub.RPC +// - p peer.ID +func (_e *PubSubTracer_Expecter) DropRPC(rpc interface{}, p interface{}) *PubSubTracer_DropRPC_Call { + return &PubSubTracer_DropRPC_Call{Call: _e.mock.On("DropRPC", rpc, p)} +} + +func (_c *PubSubTracer_DropRPC_Call) Run(run func(rpc *pubsub.RPC, p peer.ID)) *PubSubTracer_DropRPC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.RPC + if args[0] != nil { + arg0 = args[0].(*pubsub.RPC) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubTracer_DropRPC_Call) Return() *PubSubTracer_DropRPC_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_DropRPC_Call) RunAndReturn(run func(rpc *pubsub.RPC, p peer.ID)) *PubSubTracer_DropRPC_Call { + _c.Run(run) + return _c +} + +// DuplicateMessage provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) DuplicateMessage(msg *pubsub.Message) { + _mock.Called(msg) + return +} + +// PubSubTracer_DuplicateMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessage' +type PubSubTracer_DuplicateMessage_Call struct { + *mock.Call +} + +// DuplicateMessage is a helper method to define mock.On call +// - msg *pubsub.Message +func (_e *PubSubTracer_Expecter) DuplicateMessage(msg interface{}) *PubSubTracer_DuplicateMessage_Call { + return &PubSubTracer_DuplicateMessage_Call{Call: _e.mock.On("DuplicateMessage", msg)} } -// DuplicateMessage provides a mock function with given fields: msg -func (_m *PubSubTracer) DuplicateMessage(msg *pubsub.Message) { - _m.Called(msg) +func (_c *PubSubTracer_DuplicateMessage_Call) Run(run func(msg *pubsub.Message)) *PubSubTracer_DuplicateMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.Message + if args[0] != nil { + arg0 = args[0].(*pubsub.Message) + } + run( + arg0, + ) + }) + return _c } -// DuplicateMessageCount provides a mock function with given fields: _a0 -func (_m *PubSubTracer) DuplicateMessageCount(_a0 peer.ID) float64 { - ret := _m.Called(_a0) +func (_c *PubSubTracer_DuplicateMessage_Call) Return() *PubSubTracer_DuplicateMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_DuplicateMessage_Call) RunAndReturn(run func(msg *pubsub.Message)) *PubSubTracer_DuplicateMessage_Call { + _c.Run(run) + return _c +} + +// DuplicateMessageCount provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) DuplicateMessageCount(iD peer.ID) float64 { + ret := _mock.Called(iD) if len(ret) == 0 { panic("no return value specified for DuplicateMessageCount") } var r0 float64 - if rf, ok := ret.Get(0).(func(peer.ID) float64); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(peer.ID) float64); ok { + r0 = returnFunc(iD) } else { r0 = ret.Get(0).(float64) } - return r0 } -// GetLocalMeshPeers provides a mock function with given fields: topic -func (_m *PubSubTracer) GetLocalMeshPeers(topic channels.Topic) []peer.ID { - ret := _m.Called(topic) +// PubSubTracer_DuplicateMessageCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DuplicateMessageCount' +type PubSubTracer_DuplicateMessageCount_Call struct { + *mock.Call +} + +// DuplicateMessageCount is a helper method to define mock.On call +// - iD peer.ID +func (_e *PubSubTracer_Expecter) DuplicateMessageCount(iD interface{}) *PubSubTracer_DuplicateMessageCount_Call { + return &PubSubTracer_DuplicateMessageCount_Call{Call: _e.mock.On("DuplicateMessageCount", iD)} +} + +func (_c *PubSubTracer_DuplicateMessageCount_Call) Run(run func(iD peer.ID)) *PubSubTracer_DuplicateMessageCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_DuplicateMessageCount_Call) Return(f float64) *PubSubTracer_DuplicateMessageCount_Call { + _c.Call.Return(f) + return _c +} + +func (_c *PubSubTracer_DuplicateMessageCount_Call) RunAndReturn(run func(iD peer.ID) float64) *PubSubTracer_DuplicateMessageCount_Call { + _c.Call.Return(run) + return _c +} + +// GetLocalMeshPeers provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) GetLocalMeshPeers(topic channels.Topic) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for GetLocalMeshPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// Graft provides a mock function with given fields: p, topic -func (_m *PubSubTracer) Graft(p peer.ID, topic string) { - _m.Called(p, topic) +// PubSubTracer_GetLocalMeshPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLocalMeshPeers' +type PubSubTracer_GetLocalMeshPeers_Call struct { + *mock.Call } -// Join provides a mock function with given fields: topic -func (_m *PubSubTracer) Join(topic string) { - _m.Called(topic) +// GetLocalMeshPeers is a helper method to define mock.On call +// - topic channels.Topic +func (_e *PubSubTracer_Expecter) GetLocalMeshPeers(topic interface{}) *PubSubTracer_GetLocalMeshPeers_Call { + return &PubSubTracer_GetLocalMeshPeers_Call{Call: _e.mock.On("GetLocalMeshPeers", topic)} } -// LastHighestIHaveRPCSize provides a mock function with no fields -func (_m *PubSubTracer) LastHighestIHaveRPCSize() int64 { - ret := _m.Called() +func (_c *PubSubTracer_GetLocalMeshPeers_Call) Run(run func(topic channels.Topic)) *PubSubTracer_GetLocalMeshPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_GetLocalMeshPeers_Call) Return(iDs []peer.ID) *PubSubTracer_GetLocalMeshPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *PubSubTracer_GetLocalMeshPeers_Call) RunAndReturn(run func(topic channels.Topic) []peer.ID) *PubSubTracer_GetLocalMeshPeers_Call { + _c.Call.Return(run) + return _c +} + +// Graft provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) Graft(p peer.ID, topic string) { + _mock.Called(p, topic) + return +} + +// PubSubTracer_Graft_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Graft' +type PubSubTracer_Graft_Call struct { + *mock.Call +} + +// Graft is a helper method to define mock.On call +// - p peer.ID +// - topic string +func (_e *PubSubTracer_Expecter) Graft(p interface{}, topic interface{}) *PubSubTracer_Graft_Call { + return &PubSubTracer_Graft_Call{Call: _e.mock.On("Graft", p, topic)} +} + +func (_c *PubSubTracer_Graft_Call) Run(run func(p peer.ID, topic string)) *PubSubTracer_Graft_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubTracer_Graft_Call) Return() *PubSubTracer_Graft_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_Graft_Call) RunAndReturn(run func(p peer.ID, topic string)) *PubSubTracer_Graft_Call { + _c.Run(run) + return _c +} + +// Join provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) Join(topic string) { + _mock.Called(topic) + return +} + +// PubSubTracer_Join_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Join' +type PubSubTracer_Join_Call struct { + *mock.Call +} + +// Join is a helper method to define mock.On call +// - topic string +func (_e *PubSubTracer_Expecter) Join(topic interface{}) *PubSubTracer_Join_Call { + return &PubSubTracer_Join_Call{Call: _e.mock.On("Join", topic)} +} + +func (_c *PubSubTracer_Join_Call) Run(run func(topic string)) *PubSubTracer_Join_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_Join_Call) Return() *PubSubTracer_Join_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_Join_Call) RunAndReturn(run func(topic string)) *PubSubTracer_Join_Call { + _c.Run(run) + return _c +} + +// LastHighestIHaveRPCSize provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) LastHighestIHaveRPCSize() int64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LastHighestIHaveRPCSize") } var r0 int64 - if rf, ok := ret.Get(0).(func() int64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() int64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(int64) } - return r0 } -// Leave provides a mock function with given fields: topic -func (_m *PubSubTracer) Leave(topic string) { - _m.Called(topic) +// PubSubTracer_LastHighestIHaveRPCSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LastHighestIHaveRPCSize' +type PubSubTracer_LastHighestIHaveRPCSize_Call struct { + *mock.Call } -// Prune provides a mock function with given fields: p, topic -func (_m *PubSubTracer) Prune(p peer.ID, topic string) { - _m.Called(p, topic) +// LastHighestIHaveRPCSize is a helper method to define mock.On call +func (_e *PubSubTracer_Expecter) LastHighestIHaveRPCSize() *PubSubTracer_LastHighestIHaveRPCSize_Call { + return &PubSubTracer_LastHighestIHaveRPCSize_Call{Call: _e.mock.On("LastHighestIHaveRPCSize")} } -// Ready provides a mock function with no fields -func (_m *PubSubTracer) Ready() <-chan struct{} { - ret := _m.Called() +func (_c *PubSubTracer_LastHighestIHaveRPCSize_Call) Run(run func()) *PubSubTracer_LastHighestIHaveRPCSize_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *PubSubTracer_LastHighestIHaveRPCSize_Call) Return(n int64) *PubSubTracer_LastHighestIHaveRPCSize_Call { + _c.Call.Return(n) + return _c +} + +func (_c *PubSubTracer_LastHighestIHaveRPCSize_Call) RunAndReturn(run func() int64) *PubSubTracer_LastHighestIHaveRPCSize_Call { + _c.Call.Return(run) + return _c +} + +// Leave provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) Leave(topic string) { + _mock.Called(topic) + return +} + +// PubSubTracer_Leave_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Leave' +type PubSubTracer_Leave_Call struct { + *mock.Call +} + +// Leave is a helper method to define mock.On call +// - topic string +func (_e *PubSubTracer_Expecter) Leave(topic interface{}) *PubSubTracer_Leave_Call { + return &PubSubTracer_Leave_Call{Call: _e.mock.On("Leave", topic)} +} + +func (_c *PubSubTracer_Leave_Call) Run(run func(topic string)) *PubSubTracer_Leave_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_Leave_Call) Return() *PubSubTracer_Leave_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_Leave_Call) RunAndReturn(run func(topic string)) *PubSubTracer_Leave_Call { + _c.Run(run) + return _c +} + +// Prune provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) Prune(p peer.ID, topic string) { + _mock.Called(p, topic) + return +} + +// PubSubTracer_Prune_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Prune' +type PubSubTracer_Prune_Call struct { + *mock.Call +} + +// Prune is a helper method to define mock.On call +// - p peer.ID +// - topic string +func (_e *PubSubTracer_Expecter) Prune(p interface{}, topic interface{}) *PubSubTracer_Prune_Call { + return &PubSubTracer_Prune_Call{Call: _e.mock.On("Prune", p, topic)} +} + +func (_c *PubSubTracer_Prune_Call) Run(run func(p peer.ID, topic string)) *PubSubTracer_Prune_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubTracer_Prune_Call) Return() *PubSubTracer_Prune_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_Prune_Call) RunAndReturn(run func(p peer.ID, topic string)) *PubSubTracer_Prune_Call { + _c.Run(run) + return _c +} + +// Ready provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// RecvRPC provides a mock function with given fields: rpc -func (_m *PubSubTracer) RecvRPC(rpc *pubsub.RPC) { - _m.Called(rpc) +// PubSubTracer_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type PubSubTracer_Ready_Call struct { + *mock.Call } -// RejectMessage provides a mock function with given fields: msg, reason -func (_m *PubSubTracer) RejectMessage(msg *pubsub.Message, reason string) { - _m.Called(msg, reason) +// Ready is a helper method to define mock.On call +func (_e *PubSubTracer_Expecter) Ready() *PubSubTracer_Ready_Call { + return &PubSubTracer_Ready_Call{Call: _e.mock.On("Ready")} } -// RemovePeer provides a mock function with given fields: p -func (_m *PubSubTracer) RemovePeer(p peer.ID) { - _m.Called(p) +func (_c *PubSubTracer_Ready_Call) Run(run func()) *PubSubTracer_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// SendRPC provides a mock function with given fields: rpc, p -func (_m *PubSubTracer) SendRPC(rpc *pubsub.RPC, p peer.ID) { - _m.Called(rpc, p) +func (_c *PubSubTracer_Ready_Call) Return(valCh <-chan struct{}) *PubSubTracer_Ready_Call { + _c.Call.Return(valCh) + return _c } -// Start provides a mock function with given fields: _a0 -func (_m *PubSubTracer) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +func (_c *PubSubTracer_Ready_Call) RunAndReturn(run func() <-chan struct{}) *PubSubTracer_Ready_Call { + _c.Call.Return(run) + return _c } -// ThrottlePeer provides a mock function with given fields: p -func (_m *PubSubTracer) ThrottlePeer(p peer.ID) { - _m.Called(p) +// RecvRPC provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) RecvRPC(rpc *pubsub.RPC) { + _mock.Called(rpc) + return } -// UndeliverableMessage provides a mock function with given fields: msg -func (_m *PubSubTracer) UndeliverableMessage(msg *pubsub.Message) { - _m.Called(msg) +// PubSubTracer_RecvRPC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RecvRPC' +type PubSubTracer_RecvRPC_Call struct { + *mock.Call } -// ValidateMessage provides a mock function with given fields: msg -func (_m *PubSubTracer) ValidateMessage(msg *pubsub.Message) { - _m.Called(msg) +// RecvRPC is a helper method to define mock.On call +// - rpc *pubsub.RPC +func (_e *PubSubTracer_Expecter) RecvRPC(rpc interface{}) *PubSubTracer_RecvRPC_Call { + return &PubSubTracer_RecvRPC_Call{Call: _e.mock.On("RecvRPC", rpc)} } -// WasIHaveRPCSent provides a mock function with given fields: messageID -func (_m *PubSubTracer) WasIHaveRPCSent(messageID string) bool { - ret := _m.Called(messageID) +func (_c *PubSubTracer_RecvRPC_Call) Run(run func(rpc *pubsub.RPC)) *PubSubTracer_RecvRPC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.RPC + if args[0] != nil { + arg0 = args[0].(*pubsub.RPC) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_RecvRPC_Call) Return() *PubSubTracer_RecvRPC_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_RecvRPC_Call) RunAndReturn(run func(rpc *pubsub.RPC)) *PubSubTracer_RecvRPC_Call { + _c.Run(run) + return _c +} + +// RejectMessage provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) RejectMessage(msg *pubsub.Message, reason string) { + _mock.Called(msg, reason) + return +} + +// PubSubTracer_RejectMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RejectMessage' +type PubSubTracer_RejectMessage_Call struct { + *mock.Call +} + +// RejectMessage is a helper method to define mock.On call +// - msg *pubsub.Message +// - reason string +func (_e *PubSubTracer_Expecter) RejectMessage(msg interface{}, reason interface{}) *PubSubTracer_RejectMessage_Call { + return &PubSubTracer_RejectMessage_Call{Call: _e.mock.On("RejectMessage", msg, reason)} +} + +func (_c *PubSubTracer_RejectMessage_Call) Run(run func(msg *pubsub.Message, reason string)) *PubSubTracer_RejectMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.Message + if args[0] != nil { + arg0 = args[0].(*pubsub.Message) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubTracer_RejectMessage_Call) Return() *PubSubTracer_RejectMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_RejectMessage_Call) RunAndReturn(run func(msg *pubsub.Message, reason string)) *PubSubTracer_RejectMessage_Call { + _c.Run(run) + return _c +} + +// RemovePeer provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) RemovePeer(p peer.ID) { + _mock.Called(p) + return +} + +// PubSubTracer_RemovePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RemovePeer' +type PubSubTracer_RemovePeer_Call struct { + *mock.Call +} + +// RemovePeer is a helper method to define mock.On call +// - p peer.ID +func (_e *PubSubTracer_Expecter) RemovePeer(p interface{}) *PubSubTracer_RemovePeer_Call { + return &PubSubTracer_RemovePeer_Call{Call: _e.mock.On("RemovePeer", p)} +} + +func (_c *PubSubTracer_RemovePeer_Call) Run(run func(p peer.ID)) *PubSubTracer_RemovePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_RemovePeer_Call) Return() *PubSubTracer_RemovePeer_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_RemovePeer_Call) RunAndReturn(run func(p peer.ID)) *PubSubTracer_RemovePeer_Call { + _c.Run(run) + return _c +} + +// SendRPC provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) SendRPC(rpc *pubsub.RPC, p peer.ID) { + _mock.Called(rpc, p) + return +} + +// PubSubTracer_SendRPC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendRPC' +type PubSubTracer_SendRPC_Call struct { + *mock.Call +} + +// SendRPC is a helper method to define mock.On call +// - rpc *pubsub.RPC +// - p peer.ID +func (_e *PubSubTracer_Expecter) SendRPC(rpc interface{}, p interface{}) *PubSubTracer_SendRPC_Call { + return &PubSubTracer_SendRPC_Call{Call: _e.mock.On("SendRPC", rpc, p)} +} + +func (_c *PubSubTracer_SendRPC_Call) Run(run func(rpc *pubsub.RPC, p peer.ID)) *PubSubTracer_SendRPC_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.RPC + if args[0] != nil { + arg0 = args[0].(*pubsub.RPC) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *PubSubTracer_SendRPC_Call) Return() *PubSubTracer_SendRPC_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_SendRPC_Call) RunAndReturn(run func(rpc *pubsub.RPC, p peer.ID)) *PubSubTracer_SendRPC_Call { + _c.Run(run) + return _c +} + +// Start provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// PubSubTracer_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type PubSubTracer_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *PubSubTracer_Expecter) Start(signalerContext interface{}) *PubSubTracer_Start_Call { + return &PubSubTracer_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *PubSubTracer_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *PubSubTracer_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_Start_Call) Return() *PubSubTracer_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *PubSubTracer_Start_Call { + _c.Run(run) + return _c +} + +// ThrottlePeer provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) ThrottlePeer(p peer.ID) { + _mock.Called(p) + return +} + +// PubSubTracer_ThrottlePeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ThrottlePeer' +type PubSubTracer_ThrottlePeer_Call struct { + *mock.Call +} + +// ThrottlePeer is a helper method to define mock.On call +// - p peer.ID +func (_e *PubSubTracer_Expecter) ThrottlePeer(p interface{}) *PubSubTracer_ThrottlePeer_Call { + return &PubSubTracer_ThrottlePeer_Call{Call: _e.mock.On("ThrottlePeer", p)} +} + +func (_c *PubSubTracer_ThrottlePeer_Call) Run(run func(p peer.ID)) *PubSubTracer_ThrottlePeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_ThrottlePeer_Call) Return() *PubSubTracer_ThrottlePeer_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_ThrottlePeer_Call) RunAndReturn(run func(p peer.ID)) *PubSubTracer_ThrottlePeer_Call { + _c.Run(run) + return _c +} + +// UndeliverableMessage provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) UndeliverableMessage(msg *pubsub.Message) { + _mock.Called(msg) + return +} + +// PubSubTracer_UndeliverableMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UndeliverableMessage' +type PubSubTracer_UndeliverableMessage_Call struct { + *mock.Call +} + +// UndeliverableMessage is a helper method to define mock.On call +// - msg *pubsub.Message +func (_e *PubSubTracer_Expecter) UndeliverableMessage(msg interface{}) *PubSubTracer_UndeliverableMessage_Call { + return &PubSubTracer_UndeliverableMessage_Call{Call: _e.mock.On("UndeliverableMessage", msg)} +} + +func (_c *PubSubTracer_UndeliverableMessage_Call) Run(run func(msg *pubsub.Message)) *PubSubTracer_UndeliverableMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.Message + if args[0] != nil { + arg0 = args[0].(*pubsub.Message) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_UndeliverableMessage_Call) Return() *PubSubTracer_UndeliverableMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_UndeliverableMessage_Call) RunAndReturn(run func(msg *pubsub.Message)) *PubSubTracer_UndeliverableMessage_Call { + _c.Run(run) + return _c +} + +// ValidateMessage provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) ValidateMessage(msg *pubsub.Message) { + _mock.Called(msg) + return +} + +// PubSubTracer_ValidateMessage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ValidateMessage' +type PubSubTracer_ValidateMessage_Call struct { + *mock.Call +} + +// ValidateMessage is a helper method to define mock.On call +// - msg *pubsub.Message +func (_e *PubSubTracer_Expecter) ValidateMessage(msg interface{}) *PubSubTracer_ValidateMessage_Call { + return &PubSubTracer_ValidateMessage_Call{Call: _e.mock.On("ValidateMessage", msg)} +} + +func (_c *PubSubTracer_ValidateMessage_Call) Run(run func(msg *pubsub.Message)) *PubSubTracer_ValidateMessage_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.Message + if args[0] != nil { + arg0 = args[0].(*pubsub.Message) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_ValidateMessage_Call) Return() *PubSubTracer_ValidateMessage_Call { + _c.Call.Return() + return _c +} + +func (_c *PubSubTracer_ValidateMessage_Call) RunAndReturn(run func(msg *pubsub.Message)) *PubSubTracer_ValidateMessage_Call { + _c.Run(run) + return _c +} + +// WasIHaveRPCSent provides a mock function for the type PubSubTracer +func (_mock *PubSubTracer) WasIHaveRPCSent(messageID string) bool { + ret := _mock.Called(messageID) if len(ret) == 0 { panic("no return value specified for WasIHaveRPCSent") } var r0 bool - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(messageID) + if returnFunc, ok := ret.Get(0).(func(string) bool); ok { + r0 = returnFunc(messageID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewPubSubTracer creates a new instance of PubSubTracer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPubSubTracer(t interface { - mock.TestingT - Cleanup(func()) -}) *PubSubTracer { - mock := &PubSubTracer{} - mock.Mock.Test(t) +// PubSubTracer_WasIHaveRPCSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WasIHaveRPCSent' +type PubSubTracer_WasIHaveRPCSent_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WasIHaveRPCSent is a helper method to define mock.On call +// - messageID string +func (_e *PubSubTracer_Expecter) WasIHaveRPCSent(messageID interface{}) *PubSubTracer_WasIHaveRPCSent_Call { + return &PubSubTracer_WasIHaveRPCSent_Call{Call: _e.mock.On("WasIHaveRPCSent", messageID)} +} - return mock +func (_c *PubSubTracer_WasIHaveRPCSent_Call) Run(run func(messageID string)) *PubSubTracer_WasIHaveRPCSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *PubSubTracer_WasIHaveRPCSent_Call) Return(b bool) *PubSubTracer_WasIHaveRPCSent_Call { + _c.Call.Return(b) + return _c +} + +func (_c *PubSubTracer_WasIHaveRPCSent_Call) RunAndReturn(run func(messageID string) bool) *PubSubTracer_WasIHaveRPCSent_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/rate_limiter.go b/network/p2p/mock/rate_limiter.go index 2d6f8f27b44..e64acc635fe 100644 --- a/network/p2p/mock/rate_limiter.go +++ b/network/p2p/mock/rate_limiter.go @@ -1,110 +1,278 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewRateLimiter creates a new instance of RateLimiter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRateLimiter(t interface { + mock.TestingT + Cleanup(func()) +}) *RateLimiter { + mock := &RateLimiter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RateLimiter is an autogenerated mock type for the RateLimiter type type RateLimiter struct { mock.Mock } -// Allow provides a mock function with given fields: peerID, msgSize -func (_m *RateLimiter) Allow(peerID peer.ID, msgSize int) bool { - ret := _m.Called(peerID, msgSize) +type RateLimiter_Expecter struct { + mock *mock.Mock +} + +func (_m *RateLimiter) EXPECT() *RateLimiter_Expecter { + return &RateLimiter_Expecter{mock: &_m.Mock} +} + +// Allow provides a mock function for the type RateLimiter +func (_mock *RateLimiter) Allow(peerID peer.ID, msgSize int) bool { + ret := _mock.Called(peerID, msgSize) if len(ret) == 0 { panic("no return value specified for Allow") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID, int) bool); ok { - r0 = rf(peerID, msgSize) + if returnFunc, ok := ret.Get(0).(func(peer.ID, int) bool); ok { + r0 = returnFunc(peerID, msgSize) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Done provides a mock function with no fields -func (_m *RateLimiter) Done() <-chan struct{} { - ret := _m.Called() +// RateLimiter_Allow_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Allow' +type RateLimiter_Allow_Call struct { + *mock.Call +} + +// Allow is a helper method to define mock.On call +// - peerID peer.ID +// - msgSize int +func (_e *RateLimiter_Expecter) Allow(peerID interface{}, msgSize interface{}) *RateLimiter_Allow_Call { + return &RateLimiter_Allow_Call{Call: _e.mock.On("Allow", peerID, msgSize)} +} + +func (_c *RateLimiter_Allow_Call) Run(run func(peerID peer.ID, msgSize int)) *RateLimiter_Allow_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 int + if args[1] != nil { + arg1 = args[1].(int) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RateLimiter_Allow_Call) Return(b bool) *RateLimiter_Allow_Call { + _c.Call.Return(b) + return _c +} + +func (_c *RateLimiter_Allow_Call) RunAndReturn(run func(peerID peer.ID, msgSize int) bool) *RateLimiter_Allow_Call { + _c.Call.Return(run) + return _c +} + +// Done provides a mock function for the type RateLimiter +func (_mock *RateLimiter) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// IsRateLimited provides a mock function with given fields: peerID -func (_m *RateLimiter) IsRateLimited(peerID peer.ID) bool { - ret := _m.Called(peerID) +// RateLimiter_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type RateLimiter_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *RateLimiter_Expecter) Done() *RateLimiter_Done_Call { + return &RateLimiter_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *RateLimiter_Done_Call) Run(run func()) *RateLimiter_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RateLimiter_Done_Call) Return(valCh <-chan struct{}) *RateLimiter_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *RateLimiter_Done_Call) RunAndReturn(run func() <-chan struct{}) *RateLimiter_Done_Call { + _c.Call.Return(run) + return _c +} + +// IsRateLimited provides a mock function for the type RateLimiter +func (_mock *RateLimiter) IsRateLimited(peerID peer.ID) bool { + ret := _mock.Called(peerID) if len(ret) == 0 { panic("no return value specified for IsRateLimited") } var r0 bool - if rf, ok := ret.Get(0).(func(peer.ID) bool); ok { - r0 = rf(peerID) + if returnFunc, ok := ret.Get(0).(func(peer.ID) bool); ok { + r0 = returnFunc(peerID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// Ready provides a mock function with no fields -func (_m *RateLimiter) Ready() <-chan struct{} { - ret := _m.Called() +// RateLimiter_IsRateLimited_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsRateLimited' +type RateLimiter_IsRateLimited_Call struct { + *mock.Call +} + +// IsRateLimited is a helper method to define mock.On call +// - peerID peer.ID +func (_e *RateLimiter_Expecter) IsRateLimited(peerID interface{}) *RateLimiter_IsRateLimited_Call { + return &RateLimiter_IsRateLimited_Call{Call: _e.mock.On("IsRateLimited", peerID)} +} + +func (_c *RateLimiter_IsRateLimited_Call) Run(run func(peerID peer.ID)) *RateLimiter_IsRateLimited_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RateLimiter_IsRateLimited_Call) Return(b bool) *RateLimiter_IsRateLimited_Call { + _c.Call.Return(b) + return _c +} + +func (_c *RateLimiter_IsRateLimited_Call) RunAndReturn(run func(peerID peer.ID) bool) *RateLimiter_IsRateLimited_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type RateLimiter +func (_mock *RateLimiter) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *RateLimiter) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// RateLimiter_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type RateLimiter_Ready_Call struct { + *mock.Call } -// NewRateLimiter creates a new instance of RateLimiter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRateLimiter(t interface { - mock.TestingT - Cleanup(func()) -}) *RateLimiter { - mock := &RateLimiter{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *RateLimiter_Expecter) Ready() *RateLimiter_Ready_Call { + return &RateLimiter_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *RateLimiter_Ready_Call) Run(run func()) *RateLimiter_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *RateLimiter_Ready_Call) Return(valCh <-chan struct{}) *RateLimiter_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *RateLimiter_Ready_Call) RunAndReturn(run func() <-chan struct{}) *RateLimiter_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type RateLimiter +func (_mock *RateLimiter) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// RateLimiter_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type RateLimiter_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *RateLimiter_Expecter) Start(signalerContext interface{}) *RateLimiter_Start_Call { + return &RateLimiter_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *RateLimiter_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *RateLimiter_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RateLimiter_Start_Call) Return() *RateLimiter_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *RateLimiter_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *RateLimiter_Start_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/rate_limiter_consumer.go b/network/p2p/mock/rate_limiter_consumer.go index 45ef6eb6f29..dc9819492d0 100644 --- a/network/p2p/mock/rate_limiter_consumer.go +++ b/network/p2p/mock/rate_limiter_consumer.go @@ -1,23 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) -// RateLimiterConsumer is an autogenerated mock type for the RateLimiterConsumer type -type RateLimiterConsumer struct { - mock.Mock -} - -// OnRateLimitedPeer provides a mock function with given fields: pid, role, msgType, topic, reason -func (_m *RateLimiterConsumer) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { - _m.Called(pid, role, msgType, topic, reason) -} - // NewRateLimiterConsumer creates a new instance of RateLimiterConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewRateLimiterConsumer(t interface { @@ -31,3 +22,80 @@ func NewRateLimiterConsumer(t interface { return mock } + +// RateLimiterConsumer is an autogenerated mock type for the RateLimiterConsumer type +type RateLimiterConsumer struct { + mock.Mock +} + +type RateLimiterConsumer_Expecter struct { + mock *mock.Mock +} + +func (_m *RateLimiterConsumer) EXPECT() *RateLimiterConsumer_Expecter { + return &RateLimiterConsumer_Expecter{mock: &_m.Mock} +} + +// OnRateLimitedPeer provides a mock function for the type RateLimiterConsumer +func (_mock *RateLimiterConsumer) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { + _mock.Called(pid, role, msgType, topic, reason) + return +} + +// RateLimiterConsumer_OnRateLimitedPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRateLimitedPeer' +type RateLimiterConsumer_OnRateLimitedPeer_Call struct { + *mock.Call +} + +// OnRateLimitedPeer is a helper method to define mock.On call +// - pid peer.ID +// - role string +// - msgType string +// - topic string +// - reason string +func (_e *RateLimiterConsumer_Expecter) OnRateLimitedPeer(pid interface{}, role interface{}, msgType interface{}, topic interface{}, reason interface{}) *RateLimiterConsumer_OnRateLimitedPeer_Call { + return &RateLimiterConsumer_OnRateLimitedPeer_Call{Call: _e.mock.On("OnRateLimitedPeer", pid, role, msgType, topic, reason)} +} + +func (_c *RateLimiterConsumer_OnRateLimitedPeer_Call) Run(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *RateLimiterConsumer_OnRateLimitedPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + var arg4 string + if args[4] != nil { + arg4 = args[4].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *RateLimiterConsumer_OnRateLimitedPeer_Call) Return() *RateLimiterConsumer_OnRateLimitedPeer_Call { + _c.Call.Return() + return _c +} + +func (_c *RateLimiterConsumer_OnRateLimitedPeer_Call) RunAndReturn(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *RateLimiterConsumer_OnRateLimitedPeer_Call { + _c.Run(run) + return _c +} diff --git a/network/p2p/mock/routable.go b/network/p2p/mock/routable.go index 46a86b93e19..f45726885dc 100644 --- a/network/p2p/mock/routable.go +++ b/network/p2p/mock/routable.go @@ -1,87 +1,181 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - kbucket "github.com/libp2p/go-libp2p-kbucket" + "github.com/libp2p/go-libp2p-kbucket" + "github.com/libp2p/go-libp2p/core/routing" mock "github.com/stretchr/testify/mock" - - routing "github.com/libp2p/go-libp2p/core/routing" ) +// NewRoutable creates a new instance of Routable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRoutable(t interface { + mock.TestingT + Cleanup(func()) +}) *Routable { + mock := &Routable{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Routable is an autogenerated mock type for the Routable type type Routable struct { mock.Mock } -// Routing provides a mock function with no fields -func (_m *Routable) Routing() routing.Routing { - ret := _m.Called() +type Routable_Expecter struct { + mock *mock.Mock +} + +func (_m *Routable) EXPECT() *Routable_Expecter { + return &Routable_Expecter{mock: &_m.Mock} +} + +// Routing provides a mock function for the type Routable +func (_mock *Routable) Routing() routing.Routing { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Routing") } var r0 routing.Routing - if rf, ok := ret.Get(0).(func() routing.Routing); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() routing.Routing); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(routing.Routing) } } - return r0 } -// RoutingTable provides a mock function with no fields -func (_m *Routable) RoutingTable() *kbucket.RoutingTable { - ret := _m.Called() +// Routable_Routing_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Routing' +type Routable_Routing_Call struct { + *mock.Call +} + +// Routing is a helper method to define mock.On call +func (_e *Routable_Expecter) Routing() *Routable_Routing_Call { + return &Routable_Routing_Call{Call: _e.mock.On("Routing")} +} + +func (_c *Routable_Routing_Call) Run(run func()) *Routable_Routing_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Routable_Routing_Call) Return(routing1 routing.Routing) *Routable_Routing_Call { + _c.Call.Return(routing1) + return _c +} + +func (_c *Routable_Routing_Call) RunAndReturn(run func() routing.Routing) *Routable_Routing_Call { + _c.Call.Return(run) + return _c +} + +// RoutingTable provides a mock function for the type Routable +func (_mock *Routable) RoutingTable() *kbucket.RoutingTable { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RoutingTable") } var r0 *kbucket.RoutingTable - if rf, ok := ret.Get(0).(func() *kbucket.RoutingTable); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *kbucket.RoutingTable); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*kbucket.RoutingTable) } } - return r0 } -// SetRouting provides a mock function with given fields: r -func (_m *Routable) SetRouting(r routing.Routing) error { - ret := _m.Called(r) +// Routable_RoutingTable_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RoutingTable' +type Routable_RoutingTable_Call struct { + *mock.Call +} + +// RoutingTable is a helper method to define mock.On call +func (_e *Routable_Expecter) RoutingTable() *Routable_RoutingTable_Call { + return &Routable_RoutingTable_Call{Call: _e.mock.On("RoutingTable")} +} + +func (_c *Routable_RoutingTable_Call) Run(run func()) *Routable_RoutingTable_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Routable_RoutingTable_Call) Return(routingTable *kbucket.RoutingTable) *Routable_RoutingTable_Call { + _c.Call.Return(routingTable) + return _c +} + +func (_c *Routable_RoutingTable_Call) RunAndReturn(run func() *kbucket.RoutingTable) *Routable_RoutingTable_Call { + _c.Call.Return(run) + return _c +} + +// SetRouting provides a mock function for the type Routable +func (_mock *Routable) SetRouting(r routing.Routing) error { + ret := _mock.Called(r) if len(ret) == 0 { panic("no return value specified for SetRouting") } var r0 error - if rf, ok := ret.Get(0).(func(routing.Routing) error); ok { - r0 = rf(r) + if returnFunc, ok := ret.Get(0).(func(routing.Routing) error); ok { + r0 = returnFunc(r) } else { r0 = ret.Error(0) } - return r0 } -// NewRoutable creates a new instance of Routable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRoutable(t interface { - mock.TestingT - Cleanup(func()) -}) *Routable { - mock := &Routable{} - mock.Mock.Test(t) +// Routable_SetRouting_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetRouting' +type Routable_SetRouting_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SetRouting is a helper method to define mock.On call +// - r routing.Routing +func (_e *Routable_Expecter) SetRouting(r interface{}) *Routable_SetRouting_Call { + return &Routable_SetRouting_Call{Call: _e.mock.On("SetRouting", r)} +} - return mock +func (_c *Routable_SetRouting_Call) Run(run func(r routing.Routing)) *Routable_SetRouting_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 routing.Routing + if args[0] != nil { + arg0 = args[0].(routing.Routing) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Routable_SetRouting_Call) Return(err error) *Routable_SetRouting_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Routable_SetRouting_Call) RunAndReturn(run func(r routing.Routing) error) *Routable_SetRouting_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/rpc_control_tracking.go b/network/p2p/mock/rpc_control_tracking.go index 91c8c9a1676..1666f39c58e 100644 --- a/network/p2p/mock/rpc_control_tracking.go +++ b/network/p2p/mock/rpc_control_tracking.go @@ -1,60 +1,131 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewRpcControlTracking creates a new instance of RpcControlTracking. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRpcControlTracking(t interface { + mock.TestingT + Cleanup(func()) +}) *RpcControlTracking { + mock := &RpcControlTracking{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // RpcControlTracking is an autogenerated mock type for the RpcControlTracking type type RpcControlTracking struct { mock.Mock } -// LastHighestIHaveRPCSize provides a mock function with no fields -func (_m *RpcControlTracking) LastHighestIHaveRPCSize() int64 { - ret := _m.Called() +type RpcControlTracking_Expecter struct { + mock *mock.Mock +} + +func (_m *RpcControlTracking) EXPECT() *RpcControlTracking_Expecter { + return &RpcControlTracking_Expecter{mock: &_m.Mock} +} + +// LastHighestIHaveRPCSize provides a mock function for the type RpcControlTracking +func (_mock *RpcControlTracking) LastHighestIHaveRPCSize() int64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LastHighestIHaveRPCSize") } var r0 int64 - if rf, ok := ret.Get(0).(func() int64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() int64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(int64) } - return r0 } -// WasIHaveRPCSent provides a mock function with given fields: messageID -func (_m *RpcControlTracking) WasIHaveRPCSent(messageID string) bool { - ret := _m.Called(messageID) +// RpcControlTracking_LastHighestIHaveRPCSize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LastHighestIHaveRPCSize' +type RpcControlTracking_LastHighestIHaveRPCSize_Call struct { + *mock.Call +} + +// LastHighestIHaveRPCSize is a helper method to define mock.On call +func (_e *RpcControlTracking_Expecter) LastHighestIHaveRPCSize() *RpcControlTracking_LastHighestIHaveRPCSize_Call { + return &RpcControlTracking_LastHighestIHaveRPCSize_Call{Call: _e.mock.On("LastHighestIHaveRPCSize")} +} + +func (_c *RpcControlTracking_LastHighestIHaveRPCSize_Call) Run(run func()) *RpcControlTracking_LastHighestIHaveRPCSize_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RpcControlTracking_LastHighestIHaveRPCSize_Call) Return(n int64) *RpcControlTracking_LastHighestIHaveRPCSize_Call { + _c.Call.Return(n) + return _c +} + +func (_c *RpcControlTracking_LastHighestIHaveRPCSize_Call) RunAndReturn(run func() int64) *RpcControlTracking_LastHighestIHaveRPCSize_Call { + _c.Call.Return(run) + return _c +} + +// WasIHaveRPCSent provides a mock function for the type RpcControlTracking +func (_mock *RpcControlTracking) WasIHaveRPCSent(messageID string) bool { + ret := _mock.Called(messageID) if len(ret) == 0 { panic("no return value specified for WasIHaveRPCSent") } var r0 bool - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(messageID) + if returnFunc, ok := ret.Get(0).(func(string) bool); ok { + r0 = returnFunc(messageID) } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewRpcControlTracking creates a new instance of RpcControlTracking. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRpcControlTracking(t interface { - mock.TestingT - Cleanup(func()) -}) *RpcControlTracking { - mock := &RpcControlTracking{} - mock.Mock.Test(t) +// RpcControlTracking_WasIHaveRPCSent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WasIHaveRPCSent' +type RpcControlTracking_WasIHaveRPCSent_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WasIHaveRPCSent is a helper method to define mock.On call +// - messageID string +func (_e *RpcControlTracking_Expecter) WasIHaveRPCSent(messageID interface{}) *RpcControlTracking_WasIHaveRPCSent_Call { + return &RpcControlTracking_WasIHaveRPCSent_Call{Call: _e.mock.On("WasIHaveRPCSent", messageID)} +} - return mock +func (_c *RpcControlTracking_WasIHaveRPCSent_Call) Run(run func(messageID string)) *RpcControlTracking_WasIHaveRPCSent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *RpcControlTracking_WasIHaveRPCSent_Call) Return(b bool) *RpcControlTracking_WasIHaveRPCSent_Call { + _c.Call.Return(b) + return _c +} + +func (_c *RpcControlTracking_WasIHaveRPCSent_Call) RunAndReturn(run func(messageID string) bool) *RpcControlTracking_WasIHaveRPCSent_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/score_option_builder.go b/network/p2p/mock/score_option_builder.go index e37c7de9210..f9f75cce158 100644 --- a/network/p2p/mock/score_option_builder.go +++ b/network/p2p/mock/score_option_builder.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/libp2p/go-libp2p-pubsub" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - pubsub "github.com/libp2p/go-libp2p-pubsub" ) +// NewScoreOptionBuilder creates a new instance of ScoreOptionBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScoreOptionBuilder(t interface { + mock.TestingT + Cleanup(func()) +}) *ScoreOptionBuilder { + mock := &ScoreOptionBuilder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ScoreOptionBuilder is an autogenerated mock type for the ScoreOptionBuilder type type ScoreOptionBuilder struct { mock.Mock } -// BuildFlowPubSubScoreOption provides a mock function with no fields -func (_m *ScoreOptionBuilder) BuildFlowPubSubScoreOption() (*pubsub.PeerScoreParams, *pubsub.PeerScoreThresholds) { - ret := _m.Called() +type ScoreOptionBuilder_Expecter struct { + mock *mock.Mock +} + +func (_m *ScoreOptionBuilder) EXPECT() *ScoreOptionBuilder_Expecter { + return &ScoreOptionBuilder_Expecter{mock: &_m.Mock} +} + +// BuildFlowPubSubScoreOption provides a mock function for the type ScoreOptionBuilder +func (_mock *ScoreOptionBuilder) BuildFlowPubSubScoreOption() (*pubsub.PeerScoreParams, *pubsub.PeerScoreThresholds) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for BuildFlowPubSubScoreOption") @@ -24,103 +47,234 @@ func (_m *ScoreOptionBuilder) BuildFlowPubSubScoreOption() (*pubsub.PeerScorePar var r0 *pubsub.PeerScoreParams var r1 *pubsub.PeerScoreThresholds - if rf, ok := ret.Get(0).(func() (*pubsub.PeerScoreParams, *pubsub.PeerScoreThresholds)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*pubsub.PeerScoreParams, *pubsub.PeerScoreThresholds)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *pubsub.PeerScoreParams); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *pubsub.PeerScoreParams); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*pubsub.PeerScoreParams) } } - - if rf, ok := ret.Get(1).(func() *pubsub.PeerScoreThresholds); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() *pubsub.PeerScoreThresholds); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*pubsub.PeerScoreThresholds) } } - return r0, r1 } -// Done provides a mock function with no fields -func (_m *ScoreOptionBuilder) Done() <-chan struct{} { - ret := _m.Called() +// ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BuildFlowPubSubScoreOption' +type ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call struct { + *mock.Call +} + +// BuildFlowPubSubScoreOption is a helper method to define mock.On call +func (_e *ScoreOptionBuilder_Expecter) BuildFlowPubSubScoreOption() *ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call { + return &ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call{Call: _e.mock.On("BuildFlowPubSubScoreOption")} +} + +func (_c *ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call) Run(run func()) *ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call) Return(peerScoreParams *pubsub.PeerScoreParams, peerScoreThresholds *pubsub.PeerScoreThresholds) *ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call { + _c.Call.Return(peerScoreParams, peerScoreThresholds) + return _c +} + +func (_c *ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call) RunAndReturn(run func() (*pubsub.PeerScoreParams, *pubsub.PeerScoreThresholds)) *ScoreOptionBuilder_BuildFlowPubSubScoreOption_Call { + _c.Call.Return(run) + return _c +} + +// Done provides a mock function for the type ScoreOptionBuilder +func (_mock *ScoreOptionBuilder) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *ScoreOptionBuilder) Ready() <-chan struct{} { - ret := _m.Called() +// ScoreOptionBuilder_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type ScoreOptionBuilder_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *ScoreOptionBuilder_Expecter) Done() *ScoreOptionBuilder_Done_Call { + return &ScoreOptionBuilder_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *ScoreOptionBuilder_Done_Call) Run(run func()) *ScoreOptionBuilder_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScoreOptionBuilder_Done_Call) Return(valCh <-chan struct{}) *ScoreOptionBuilder_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ScoreOptionBuilder_Done_Call) RunAndReturn(run func() <-chan struct{}) *ScoreOptionBuilder_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type ScoreOptionBuilder +func (_mock *ScoreOptionBuilder) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *ScoreOptionBuilder) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// ScoreOptionBuilder_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type ScoreOptionBuilder_Ready_Call struct { + *mock.Call +} + +// Ready is a helper method to define mock.On call +func (_e *ScoreOptionBuilder_Expecter) Ready() *ScoreOptionBuilder_Ready_Call { + return &ScoreOptionBuilder_Ready_Call{Call: _e.mock.On("Ready")} +} + +func (_c *ScoreOptionBuilder_Ready_Call) Run(run func()) *ScoreOptionBuilder_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c } -// TopicScoreParams provides a mock function with given fields: _a0 -func (_m *ScoreOptionBuilder) TopicScoreParams(_a0 *pubsub.Topic) *pubsub.TopicScoreParams { - ret := _m.Called(_a0) +func (_c *ScoreOptionBuilder_Ready_Call) Return(valCh <-chan struct{}) *ScoreOptionBuilder_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *ScoreOptionBuilder_Ready_Call) RunAndReturn(run func() <-chan struct{}) *ScoreOptionBuilder_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type ScoreOptionBuilder +func (_mock *ScoreOptionBuilder) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// ScoreOptionBuilder_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type ScoreOptionBuilder_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *ScoreOptionBuilder_Expecter) Start(signalerContext interface{}) *ScoreOptionBuilder_Start_Call { + return &ScoreOptionBuilder_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *ScoreOptionBuilder_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *ScoreOptionBuilder_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScoreOptionBuilder_Start_Call) Return() *ScoreOptionBuilder_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *ScoreOptionBuilder_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *ScoreOptionBuilder_Start_Call { + _c.Run(run) + return _c +} + +// TopicScoreParams provides a mock function for the type ScoreOptionBuilder +func (_mock *ScoreOptionBuilder) TopicScoreParams(topic *pubsub.Topic) *pubsub.TopicScoreParams { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for TopicScoreParams") } var r0 *pubsub.TopicScoreParams - if rf, ok := ret.Get(0).(func(*pubsub.Topic) *pubsub.TopicScoreParams); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(*pubsub.Topic) *pubsub.TopicScoreParams); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*pubsub.TopicScoreParams) } } - return r0 } -// NewScoreOptionBuilder creates a new instance of ScoreOptionBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewScoreOptionBuilder(t interface { - mock.TestingT - Cleanup(func()) -}) *ScoreOptionBuilder { - mock := &ScoreOptionBuilder{} - mock.Mock.Test(t) +// ScoreOptionBuilder_TopicScoreParams_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TopicScoreParams' +type ScoreOptionBuilder_TopicScoreParams_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TopicScoreParams is a helper method to define mock.On call +// - topic *pubsub.Topic +func (_e *ScoreOptionBuilder_Expecter) TopicScoreParams(topic interface{}) *ScoreOptionBuilder_TopicScoreParams_Call { + return &ScoreOptionBuilder_TopicScoreParams_Call{Call: _e.mock.On("TopicScoreParams", topic)} +} - return mock +func (_c *ScoreOptionBuilder_TopicScoreParams_Call) Run(run func(topic *pubsub.Topic)) *ScoreOptionBuilder_TopicScoreParams_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *pubsub.Topic + if args[0] != nil { + arg0 = args[0].(*pubsub.Topic) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScoreOptionBuilder_TopicScoreParams_Call) Return(topicScoreParams *pubsub.TopicScoreParams) *ScoreOptionBuilder_TopicScoreParams_Call { + _c.Call.Return(topicScoreParams) + return _c +} + +func (_c *ScoreOptionBuilder_TopicScoreParams_Call) RunAndReturn(run func(topic *pubsub.Topic) *pubsub.TopicScoreParams) *ScoreOptionBuilder_TopicScoreParams_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/stream_factory.go b/network/p2p/mock/stream_factory.go index 2d98bb6e7f3..bfd65c2a685 100644 --- a/network/p2p/mock/stream_factory.go +++ b/network/p2p/mock/stream_factory.go @@ -1,26 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - network "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewStreamFactory creates a new instance of StreamFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStreamFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *StreamFactory { + mock := &StreamFactory{} + mock.Mock.Test(t) - protocol "github.com/libp2p/go-libp2p/core/protocol" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // StreamFactory is an autogenerated mock type for the StreamFactory type type StreamFactory struct { mock.Mock } -// NewStream provides a mock function with given fields: _a0, _a1, _a2 -func (_m *StreamFactory) NewStream(_a0 context.Context, _a1 peer.ID, _a2 protocol.ID) (network.Stream, error) { - ret := _m.Called(_a0, _a1, _a2) +type StreamFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *StreamFactory) EXPECT() *StreamFactory_Expecter { + return &StreamFactory_Expecter{mock: &_m.Mock} +} + +// NewStream provides a mock function for the type StreamFactory +func (_mock *StreamFactory) NewStream(context1 context.Context, iD peer.ID, iD1 protocol.ID) (network.Stream, error) { + ret := _mock.Called(context1, iD, iD1) if len(ret) == 0 { panic("no return value specified for NewStream") @@ -28,41 +50,112 @@ func (_m *StreamFactory) NewStream(_a0 context.Context, _a1 peer.ID, _a2 protoco var r0 network.Stream var r1 error - if rf, ok := ret.Get(0).(func(context.Context, peer.ID, protocol.ID) (network.Stream, error)); ok { - return rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID, protocol.ID) (network.Stream, error)); ok { + return returnFunc(context1, iD, iD1) } - if rf, ok := ret.Get(0).(func(context.Context, peer.ID, protocol.ID) network.Stream); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID, protocol.ID) network.Stream); ok { + r0 = returnFunc(context1, iD, iD1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.Stream) } } - - if rf, ok := ret.Get(1).(func(context.Context, peer.ID, protocol.ID) error); ok { - r1 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(1).(func(context.Context, peer.ID, protocol.ID) error); ok { + r1 = returnFunc(context1, iD, iD1) } else { r1 = ret.Error(1) } - return r0, r1 } -// SetStreamHandler provides a mock function with given fields: _a0, _a1 -func (_m *StreamFactory) SetStreamHandler(_a0 protocol.ID, _a1 network.StreamHandler) { - _m.Called(_a0, _a1) +// StreamFactory_NewStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewStream' +type StreamFactory_NewStream_Call struct { + *mock.Call } -// NewStreamFactory creates a new instance of StreamFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStreamFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *StreamFactory { - mock := &StreamFactory{} - mock.Mock.Test(t) +// NewStream is a helper method to define mock.On call +// - context1 context.Context +// - iD peer.ID +// - iD1 protocol.ID +func (_e *StreamFactory_Expecter) NewStream(context1 interface{}, iD interface{}, iD1 interface{}) *StreamFactory_NewStream_Call { + return &StreamFactory_NewStream_Call{Call: _e.mock.On("NewStream", context1, iD, iD1)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *StreamFactory_NewStream_Call) Run(run func(context1 context.Context, iD peer.ID, iD1 protocol.ID)) *StreamFactory_NewStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + var arg2 protocol.ID + if args[2] != nil { + arg2 = args[2].(protocol.ID) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} - return mock +func (_c *StreamFactory_NewStream_Call) Return(stream network.Stream, err error) *StreamFactory_NewStream_Call { + _c.Call.Return(stream, err) + return _c +} + +func (_c *StreamFactory_NewStream_Call) RunAndReturn(run func(context1 context.Context, iD peer.ID, iD1 protocol.ID) (network.Stream, error)) *StreamFactory_NewStream_Call { + _c.Call.Return(run) + return _c +} + +// SetStreamHandler provides a mock function for the type StreamFactory +func (_mock *StreamFactory) SetStreamHandler(iD protocol.ID, streamHandler network.StreamHandler) { + _mock.Called(iD, streamHandler) + return +} + +// StreamFactory_SetStreamHandler_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetStreamHandler' +type StreamFactory_SetStreamHandler_Call struct { + *mock.Call +} + +// SetStreamHandler is a helper method to define mock.On call +// - iD protocol.ID +// - streamHandler network.StreamHandler +func (_e *StreamFactory_Expecter) SetStreamHandler(iD interface{}, streamHandler interface{}) *StreamFactory_SetStreamHandler_Call { + return &StreamFactory_SetStreamHandler_Call{Call: _e.mock.On("SetStreamHandler", iD, streamHandler)} +} + +func (_c *StreamFactory_SetStreamHandler_Call) Run(run func(iD protocol.ID, streamHandler network.StreamHandler)) *StreamFactory_SetStreamHandler_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocol.ID + if args[0] != nil { + arg0 = args[0].(protocol.ID) + } + var arg1 network.StreamHandler + if args[1] != nil { + arg1 = args[1].(network.StreamHandler) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *StreamFactory_SetStreamHandler_Call) Return() *StreamFactory_SetStreamHandler_Call { + _c.Call.Return() + return _c +} + +func (_c *StreamFactory_SetStreamHandler_Call) RunAndReturn(run func(iD protocol.ID, streamHandler network.StreamHandler)) *StreamFactory_SetStreamHandler_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/subscription.go b/network/p2p/mock/subscription.go index 3eeeec294ac..23dd35e8ca4 100644 --- a/network/p2p/mock/subscription.go +++ b/network/p2p/mock/subscription.go @@ -1,28 +1,79 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" + "github.com/libp2p/go-libp2p-pubsub" mock "github.com/stretchr/testify/mock" - - pubsub "github.com/libp2p/go-libp2p-pubsub" ) +// NewSubscription creates a new instance of Subscription. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscription(t interface { + mock.TestingT + Cleanup(func()) +}) *Subscription { + mock := &Subscription{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Subscription is an autogenerated mock type for the Subscription type type Subscription struct { mock.Mock } -// Cancel provides a mock function with no fields -func (_m *Subscription) Cancel() { - _m.Called() +type Subscription_Expecter struct { + mock *mock.Mock } -// Next provides a mock function with given fields: _a0 -func (_m *Subscription) Next(_a0 context.Context) (*pubsub.Message, error) { - ret := _m.Called(_a0) +func (_m *Subscription) EXPECT() *Subscription_Expecter { + return &Subscription_Expecter{mock: &_m.Mock} +} + +// Cancel provides a mock function for the type Subscription +func (_mock *Subscription) Cancel() { + _mock.Called() + return +} + +// Subscription_Cancel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Cancel' +type Subscription_Cancel_Call struct { + *mock.Call +} + +// Cancel is a helper method to define mock.On call +func (_e *Subscription_Expecter) Cancel() *Subscription_Cancel_Call { + return &Subscription_Cancel_Call{Call: _e.mock.On("Cancel")} +} + +func (_c *Subscription_Cancel_Call) Run(run func()) *Subscription_Cancel_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Subscription_Cancel_Call) Return() *Subscription_Cancel_Call { + _c.Call.Return() + return _c +} + +func (_c *Subscription_Cancel_Call) RunAndReturn(run func()) *Subscription_Cancel_Call { + _c.Run(run) + return _c +} + +// Next provides a mock function for the type Subscription +func (_mock *Subscription) Next(context1 context.Context) (*pubsub.Message, error) { + ret := _mock.Called(context1) if len(ret) == 0 { panic("no return value specified for Next") @@ -30,54 +81,98 @@ func (_m *Subscription) Next(_a0 context.Context) (*pubsub.Message, error) { var r0 *pubsub.Message var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*pubsub.Message, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) (*pubsub.Message, error)); ok { + return returnFunc(context1) } - if rf, ok := ret.Get(0).(func(context.Context) *pubsub.Message); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(context.Context) *pubsub.Message); ok { + r0 = returnFunc(context1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*pubsub.Message) } } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = returnFunc(context1) } else { r1 = ret.Error(1) } - return r0, r1 } -// Topic provides a mock function with no fields -func (_m *Subscription) Topic() string { - ret := _m.Called() +// Subscription_Next_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Next' +type Subscription_Next_Call struct { + *mock.Call +} + +// Next is a helper method to define mock.On call +// - context1 context.Context +func (_e *Subscription_Expecter) Next(context1 interface{}) *Subscription_Next_Call { + return &Subscription_Next_Call{Call: _e.mock.On("Next", context1)} +} + +func (_c *Subscription_Next_Call) Run(run func(context1 context.Context)) *Subscription_Next_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Subscription_Next_Call) Return(message *pubsub.Message, err error) *Subscription_Next_Call { + _c.Call.Return(message, err) + return _c +} + +func (_c *Subscription_Next_Call) RunAndReturn(run func(context1 context.Context) (*pubsub.Message, error)) *Subscription_Next_Call { + _c.Call.Return(run) + return _c +} + +// Topic provides a mock function for the type Subscription +func (_mock *Subscription) Topic() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Topic") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// NewSubscription creates a new instance of Subscription. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSubscription(t interface { - mock.TestingT - Cleanup(func()) -}) *Subscription { - mock := &Subscription{} - mock.Mock.Test(t) +// Subscription_Topic_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Topic' +type Subscription_Topic_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Topic is a helper method to define mock.On call +func (_e *Subscription_Expecter) Topic() *Subscription_Topic_Call { + return &Subscription_Topic_Call{Call: _e.mock.On("Topic")} +} - return mock +func (_c *Subscription_Topic_Call) Run(run func()) *Subscription_Topic_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Subscription_Topic_Call) Return(s string) *Subscription_Topic_Call { + _c.Call.Return(s) + return _c +} + +func (_c *Subscription_Topic_Call) RunAndReturn(run func() string) *Subscription_Topic_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/subscription_filter.go b/network/p2p/mock/subscription_filter.go index 6a4a467c98d..4d905d72747 100644 --- a/network/p2p/mock/subscription_filter.go +++ b/network/p2p/mock/subscription_filter.go @@ -1,41 +1,96 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/libp2p/go-libp2p-pubsub/pb" + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewSubscriptionFilter creates a new instance of SubscriptionFilter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscriptionFilter(t interface { + mock.TestingT + Cleanup(func()) +}) *SubscriptionFilter { + mock := &SubscriptionFilter{} + mock.Mock.Test(t) - pubsub_pb "github.com/libp2p/go-libp2p-pubsub/pb" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // SubscriptionFilter is an autogenerated mock type for the SubscriptionFilter type type SubscriptionFilter struct { mock.Mock } -// CanSubscribe provides a mock function with given fields: _a0 -func (_m *SubscriptionFilter) CanSubscribe(_a0 string) bool { - ret := _m.Called(_a0) +type SubscriptionFilter_Expecter struct { + mock *mock.Mock +} + +func (_m *SubscriptionFilter) EXPECT() *SubscriptionFilter_Expecter { + return &SubscriptionFilter_Expecter{mock: &_m.Mock} +} + +// CanSubscribe provides a mock function for the type SubscriptionFilter +func (_mock *SubscriptionFilter) CanSubscribe(s string) bool { + ret := _mock.Called(s) if len(ret) == 0 { panic("no return value specified for CanSubscribe") } var r0 bool - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(string) bool); ok { + r0 = returnFunc(s) } else { r0 = ret.Get(0).(bool) } - return r0 } -// FilterIncomingSubscriptions provides a mock function with given fields: _a0, _a1 -func (_m *SubscriptionFilter) FilterIncomingSubscriptions(_a0 peer.ID, _a1 []*pubsub_pb.RPC_SubOpts) ([]*pubsub_pb.RPC_SubOpts, error) { - ret := _m.Called(_a0, _a1) +// SubscriptionFilter_CanSubscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CanSubscribe' +type SubscriptionFilter_CanSubscribe_Call struct { + *mock.Call +} + +// CanSubscribe is a helper method to define mock.On call +// - s string +func (_e *SubscriptionFilter_Expecter) CanSubscribe(s interface{}) *SubscriptionFilter_CanSubscribe_Call { + return &SubscriptionFilter_CanSubscribe_Call{Call: _e.mock.On("CanSubscribe", s)} +} + +func (_c *SubscriptionFilter_CanSubscribe_Call) Run(run func(s string)) *SubscriptionFilter_CanSubscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SubscriptionFilter_CanSubscribe_Call) Return(b bool) *SubscriptionFilter_CanSubscribe_Call { + _c.Call.Return(b) + return _c +} + +func (_c *SubscriptionFilter_CanSubscribe_Call) RunAndReturn(run func(s string) bool) *SubscriptionFilter_CanSubscribe_Call { + _c.Call.Return(run) + return _c +} + +// FilterIncomingSubscriptions provides a mock function for the type SubscriptionFilter +func (_mock *SubscriptionFilter) FilterIncomingSubscriptions(iD peer.ID, rPC_SubOptss []*pubsub_pb.RPC_SubOpts) ([]*pubsub_pb.RPC_SubOpts, error) { + ret := _mock.Called(iD, rPC_SubOptss) if len(ret) == 0 { panic("no return value specified for FilterIncomingSubscriptions") @@ -43,36 +98,60 @@ func (_m *SubscriptionFilter) FilterIncomingSubscriptions(_a0 peer.ID, _a1 []*pu var r0 []*pubsub_pb.RPC_SubOpts var r1 error - if rf, ok := ret.Get(0).(func(peer.ID, []*pubsub_pb.RPC_SubOpts) ([]*pubsub_pb.RPC_SubOpts, error)); ok { - return rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(peer.ID, []*pubsub_pb.RPC_SubOpts) ([]*pubsub_pb.RPC_SubOpts, error)); ok { + return returnFunc(iD, rPC_SubOptss) } - if rf, ok := ret.Get(0).(func(peer.ID, []*pubsub_pb.RPC_SubOpts) []*pubsub_pb.RPC_SubOpts); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(peer.ID, []*pubsub_pb.RPC_SubOpts) []*pubsub_pb.RPC_SubOpts); ok { + r0 = returnFunc(iD, rPC_SubOptss) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*pubsub_pb.RPC_SubOpts) } } - - if rf, ok := ret.Get(1).(func(peer.ID, []*pubsub_pb.RPC_SubOpts) error); ok { - r1 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(1).(func(peer.ID, []*pubsub_pb.RPC_SubOpts) error); ok { + r1 = returnFunc(iD, rPC_SubOptss) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSubscriptionFilter creates a new instance of SubscriptionFilter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSubscriptionFilter(t interface { - mock.TestingT - Cleanup(func()) -}) *SubscriptionFilter { - mock := &SubscriptionFilter{} - mock.Mock.Test(t) +// SubscriptionFilter_FilterIncomingSubscriptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FilterIncomingSubscriptions' +type SubscriptionFilter_FilterIncomingSubscriptions_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// FilterIncomingSubscriptions is a helper method to define mock.On call +// - iD peer.ID +// - rPC_SubOptss []*pubsub_pb.RPC_SubOpts +func (_e *SubscriptionFilter_Expecter) FilterIncomingSubscriptions(iD interface{}, rPC_SubOptss interface{}) *SubscriptionFilter_FilterIncomingSubscriptions_Call { + return &SubscriptionFilter_FilterIncomingSubscriptions_Call{Call: _e.mock.On("FilterIncomingSubscriptions", iD, rPC_SubOptss)} +} - return mock +func (_c *SubscriptionFilter_FilterIncomingSubscriptions_Call) Run(run func(iD peer.ID, rPC_SubOptss []*pubsub_pb.RPC_SubOpts)) *SubscriptionFilter_FilterIncomingSubscriptions_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 []*pubsub_pb.RPC_SubOpts + if args[1] != nil { + arg1 = args[1].([]*pubsub_pb.RPC_SubOpts) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SubscriptionFilter_FilterIncomingSubscriptions_Call) Return(rPC_SubOptss1 []*pubsub_pb.RPC_SubOpts, err error) *SubscriptionFilter_FilterIncomingSubscriptions_Call { + _c.Call.Return(rPC_SubOptss1, err) + return _c +} + +func (_c *SubscriptionFilter_FilterIncomingSubscriptions_Call) RunAndReturn(run func(iD peer.ID, rPC_SubOptss []*pubsub_pb.RPC_SubOpts) ([]*pubsub_pb.RPC_SubOpts, error)) *SubscriptionFilter_FilterIncomingSubscriptions_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/subscription_provider.go b/network/p2p/mock/subscription_provider.go index f1d20e23a0e..14ce34508a5 100644 --- a/network/p2p/mock/subscription_provider.go +++ b/network/p2p/mock/subscription_provider.go @@ -1,94 +1,223 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewSubscriptionProvider creates a new instance of SubscriptionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscriptionProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *SubscriptionProvider { + mock := &SubscriptionProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SubscriptionProvider is an autogenerated mock type for the SubscriptionProvider type type SubscriptionProvider struct { mock.Mock } -// Done provides a mock function with no fields -func (_m *SubscriptionProvider) Done() <-chan struct{} { - ret := _m.Called() +type SubscriptionProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *SubscriptionProvider) EXPECT() *SubscriptionProvider_Expecter { + return &SubscriptionProvider_Expecter{mock: &_m.Mock} +} + +// Done provides a mock function for the type SubscriptionProvider +func (_mock *SubscriptionProvider) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// GetSubscribedTopics provides a mock function with given fields: pid -func (_m *SubscriptionProvider) GetSubscribedTopics(pid peer.ID) []string { - ret := _m.Called(pid) +// SubscriptionProvider_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type SubscriptionProvider_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *SubscriptionProvider_Expecter) Done() *SubscriptionProvider_Done_Call { + return &SubscriptionProvider_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *SubscriptionProvider_Done_Call) Run(run func()) *SubscriptionProvider_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SubscriptionProvider_Done_Call) Return(valCh <-chan struct{}) *SubscriptionProvider_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *SubscriptionProvider_Done_Call) RunAndReturn(run func() <-chan struct{}) *SubscriptionProvider_Done_Call { + _c.Call.Return(run) + return _c +} + +// GetSubscribedTopics provides a mock function for the type SubscriptionProvider +func (_mock *SubscriptionProvider) GetSubscribedTopics(pid peer.ID) []string { + ret := _mock.Called(pid) if len(ret) == 0 { panic("no return value specified for GetSubscribedTopics") } var r0 []string - if rf, ok := ret.Get(0).(func(peer.ID) []string); ok { - r0 = rf(pid) + if returnFunc, ok := ret.Get(0).(func(peer.ID) []string); ok { + r0 = returnFunc(pid) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]string) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *SubscriptionProvider) Ready() <-chan struct{} { - ret := _m.Called() +// SubscriptionProvider_GetSubscribedTopics_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSubscribedTopics' +type SubscriptionProvider_GetSubscribedTopics_Call struct { + *mock.Call +} + +// GetSubscribedTopics is a helper method to define mock.On call +// - pid peer.ID +func (_e *SubscriptionProvider_Expecter) GetSubscribedTopics(pid interface{}) *SubscriptionProvider_GetSubscribedTopics_Call { + return &SubscriptionProvider_GetSubscribedTopics_Call{Call: _e.mock.On("GetSubscribedTopics", pid)} +} + +func (_c *SubscriptionProvider_GetSubscribedTopics_Call) Run(run func(pid peer.ID)) *SubscriptionProvider_GetSubscribedTopics_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SubscriptionProvider_GetSubscribedTopics_Call) Return(strings []string) *SubscriptionProvider_GetSubscribedTopics_Call { + _c.Call.Return(strings) + return _c +} + +func (_c *SubscriptionProvider_GetSubscribedTopics_Call) RunAndReturn(run func(pid peer.ID) []string) *SubscriptionProvider_GetSubscribedTopics_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type SubscriptionProvider +func (_mock *SubscriptionProvider) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *SubscriptionProvider) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// SubscriptionProvider_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type SubscriptionProvider_Ready_Call struct { + *mock.Call } -// NewSubscriptionProvider creates a new instance of SubscriptionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSubscriptionProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *SubscriptionProvider { - mock := &SubscriptionProvider{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *SubscriptionProvider_Expecter) Ready() *SubscriptionProvider_Ready_Call { + return &SubscriptionProvider_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *SubscriptionProvider_Ready_Call) Run(run func()) *SubscriptionProvider_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *SubscriptionProvider_Ready_Call) Return(valCh <-chan struct{}) *SubscriptionProvider_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *SubscriptionProvider_Ready_Call) RunAndReturn(run func() <-chan struct{}) *SubscriptionProvider_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type SubscriptionProvider +func (_mock *SubscriptionProvider) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// SubscriptionProvider_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type SubscriptionProvider_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *SubscriptionProvider_Expecter) Start(signalerContext interface{}) *SubscriptionProvider_Start_Call { + return &SubscriptionProvider_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *SubscriptionProvider_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *SubscriptionProvider_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SubscriptionProvider_Start_Call) Return() *SubscriptionProvider_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *SubscriptionProvider_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *SubscriptionProvider_Start_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/subscription_validator.go b/network/p2p/mock/subscription_validator.go index 5de8728e573..a02c95bdcd3 100644 --- a/network/p2p/mock/subscription_validator.go +++ b/network/p2p/mock/subscription_validator.go @@ -1,94 +1,228 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - irrecoverable "github.com/onflow/flow-go/module/irrecoverable" - + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/module/irrecoverable" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewSubscriptionValidator creates a new instance of SubscriptionValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscriptionValidator(t interface { + mock.TestingT + Cleanup(func()) +}) *SubscriptionValidator { + mock := &SubscriptionValidator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SubscriptionValidator is an autogenerated mock type for the SubscriptionValidator type type SubscriptionValidator struct { mock.Mock } -// CheckSubscribedToAllowedTopics provides a mock function with given fields: pid, role -func (_m *SubscriptionValidator) CheckSubscribedToAllowedTopics(pid peer.ID, role flow.Role) error { - ret := _m.Called(pid, role) +type SubscriptionValidator_Expecter struct { + mock *mock.Mock +} + +func (_m *SubscriptionValidator) EXPECT() *SubscriptionValidator_Expecter { + return &SubscriptionValidator_Expecter{mock: &_m.Mock} +} + +// CheckSubscribedToAllowedTopics provides a mock function for the type SubscriptionValidator +func (_mock *SubscriptionValidator) CheckSubscribedToAllowedTopics(pid peer.ID, role flow.Role) error { + ret := _mock.Called(pid, role) if len(ret) == 0 { panic("no return value specified for CheckSubscribedToAllowedTopics") } var r0 error - if rf, ok := ret.Get(0).(func(peer.ID, flow.Role) error); ok { - r0 = rf(pid, role) + if returnFunc, ok := ret.Get(0).(func(peer.ID, flow.Role) error); ok { + r0 = returnFunc(pid, role) } else { r0 = ret.Error(0) } - return r0 } -// Done provides a mock function with no fields -func (_m *SubscriptionValidator) Done() <-chan struct{} { - ret := _m.Called() +// SubscriptionValidator_CheckSubscribedToAllowedTopics_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckSubscribedToAllowedTopics' +type SubscriptionValidator_CheckSubscribedToAllowedTopics_Call struct { + *mock.Call +} + +// CheckSubscribedToAllowedTopics is a helper method to define mock.On call +// - pid peer.ID +// - role flow.Role +func (_e *SubscriptionValidator_Expecter) CheckSubscribedToAllowedTopics(pid interface{}, role interface{}) *SubscriptionValidator_CheckSubscribedToAllowedTopics_Call { + return &SubscriptionValidator_CheckSubscribedToAllowedTopics_Call{Call: _e.mock.On("CheckSubscribedToAllowedTopics", pid, role)} +} + +func (_c *SubscriptionValidator_CheckSubscribedToAllowedTopics_Call) Run(run func(pid peer.ID, role flow.Role)) *SubscriptionValidator_CheckSubscribedToAllowedTopics_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 flow.Role + if args[1] != nil { + arg1 = args[1].(flow.Role) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *SubscriptionValidator_CheckSubscribedToAllowedTopics_Call) Return(err error) *SubscriptionValidator_CheckSubscribedToAllowedTopics_Call { + _c.Call.Return(err) + return _c +} + +func (_c *SubscriptionValidator_CheckSubscribedToAllowedTopics_Call) RunAndReturn(run func(pid peer.ID, role flow.Role) error) *SubscriptionValidator_CheckSubscribedToAllowedTopics_Call { + _c.Call.Return(run) + return _c +} + +// Done provides a mock function for the type SubscriptionValidator +func (_mock *SubscriptionValidator) Done() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Done") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Ready provides a mock function with no fields -func (_m *SubscriptionValidator) Ready() <-chan struct{} { - ret := _m.Called() +// SubscriptionValidator_Done_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Done' +type SubscriptionValidator_Done_Call struct { + *mock.Call +} + +// Done is a helper method to define mock.On call +func (_e *SubscriptionValidator_Expecter) Done() *SubscriptionValidator_Done_Call { + return &SubscriptionValidator_Done_Call{Call: _e.mock.On("Done")} +} + +func (_c *SubscriptionValidator_Done_Call) Run(run func()) *SubscriptionValidator_Done_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SubscriptionValidator_Done_Call) Return(valCh <-chan struct{}) *SubscriptionValidator_Done_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *SubscriptionValidator_Done_Call) RunAndReturn(run func() <-chan struct{}) *SubscriptionValidator_Done_Call { + _c.Call.Return(run) + return _c +} + +// Ready provides a mock function for the type SubscriptionValidator +func (_mock *SubscriptionValidator) Ready() <-chan struct{} { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Ready") } var r0 <-chan struct{} - if rf, ok := ret.Get(0).(func() <-chan struct{}); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() <-chan struct{}); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(<-chan struct{}) } } - return r0 } -// Start provides a mock function with given fields: _a0 -func (_m *SubscriptionValidator) Start(_a0 irrecoverable.SignalerContext) { - _m.Called(_a0) +// SubscriptionValidator_Ready_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ready' +type SubscriptionValidator_Ready_Call struct { + *mock.Call } -// NewSubscriptionValidator creates a new instance of SubscriptionValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSubscriptionValidator(t interface { - mock.TestingT - Cleanup(func()) -}) *SubscriptionValidator { - mock := &SubscriptionValidator{} - mock.Mock.Test(t) +// Ready is a helper method to define mock.On call +func (_e *SubscriptionValidator_Expecter) Ready() *SubscriptionValidator_Ready_Call { + return &SubscriptionValidator_Ready_Call{Call: _e.mock.On("Ready")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *SubscriptionValidator_Ready_Call) Run(run func()) *SubscriptionValidator_Ready_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *SubscriptionValidator_Ready_Call) Return(valCh <-chan struct{}) *SubscriptionValidator_Ready_Call { + _c.Call.Return(valCh) + return _c +} + +func (_c *SubscriptionValidator_Ready_Call) RunAndReturn(run func() <-chan struct{}) *SubscriptionValidator_Ready_Call { + _c.Call.Return(run) + return _c +} + +// Start provides a mock function for the type SubscriptionValidator +func (_mock *SubscriptionValidator) Start(signalerContext irrecoverable.SignalerContext) { + _mock.Called(signalerContext) + return +} + +// SubscriptionValidator_Start_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Start' +type SubscriptionValidator_Start_Call struct { + *mock.Call +} + +// Start is a helper method to define mock.On call +// - signalerContext irrecoverable.SignalerContext +func (_e *SubscriptionValidator_Expecter) Start(signalerContext interface{}) *SubscriptionValidator_Start_Call { + return &SubscriptionValidator_Start_Call{Call: _e.mock.On("Start", signalerContext)} +} + +func (_c *SubscriptionValidator_Start_Call) Run(run func(signalerContext irrecoverable.SignalerContext)) *SubscriptionValidator_Start_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 irrecoverable.SignalerContext + if args[0] != nil { + arg0 = args[0].(irrecoverable.SignalerContext) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SubscriptionValidator_Start_Call) Return() *SubscriptionValidator_Start_Call { + _c.Call.Return() + return _c +} + +func (_c *SubscriptionValidator_Start_Call) RunAndReturn(run func(signalerContext irrecoverable.SignalerContext)) *SubscriptionValidator_Start_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/subscriptions.go b/network/p2p/mock/subscriptions.go index 6e409ebb967..693da88df17 100644 --- a/network/p2p/mock/subscriptions.go +++ b/network/p2p/mock/subscriptions.go @@ -1,52 +1,129 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - channels "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/channels" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" - - p2p "github.com/onflow/flow-go/network/p2p" ) +// NewSubscriptions creates a new instance of Subscriptions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscriptions(t interface { + mock.TestingT + Cleanup(func()) +}) *Subscriptions { + mock := &Subscriptions{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Subscriptions is an autogenerated mock type for the Subscriptions type type Subscriptions struct { mock.Mock } -// HasSubscription provides a mock function with given fields: topic -func (_m *Subscriptions) HasSubscription(topic channels.Topic) bool { - ret := _m.Called(topic) +type Subscriptions_Expecter struct { + mock *mock.Mock +} + +func (_m *Subscriptions) EXPECT() *Subscriptions_Expecter { + return &Subscriptions_Expecter{mock: &_m.Mock} +} + +// HasSubscription provides a mock function for the type Subscriptions +func (_mock *Subscriptions) HasSubscription(topic channels.Topic) bool { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for HasSubscription") } var r0 bool - if rf, ok := ret.Get(0).(func(channels.Topic) bool); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(channels.Topic) bool); ok { + r0 = returnFunc(topic) } else { r0 = ret.Get(0).(bool) } - return r0 } -// SetUnicastManager provides a mock function with given fields: uniMgr -func (_m *Subscriptions) SetUnicastManager(uniMgr p2p.UnicastManager) { - _m.Called(uniMgr) +// Subscriptions_HasSubscription_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasSubscription' +type Subscriptions_HasSubscription_Call struct { + *mock.Call } -// NewSubscriptions creates a new instance of Subscriptions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSubscriptions(t interface { - mock.TestingT - Cleanup(func()) -}) *Subscriptions { - mock := &Subscriptions{} - mock.Mock.Test(t) +// HasSubscription is a helper method to define mock.On call +// - topic channels.Topic +func (_e *Subscriptions_Expecter) HasSubscription(topic interface{}) *Subscriptions_HasSubscription_Call { + return &Subscriptions_HasSubscription_Call{Call: _e.mock.On("HasSubscription", topic)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *Subscriptions_HasSubscription_Call) Run(run func(topic channels.Topic)) *Subscriptions_HasSubscription_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 channels.Topic + if args[0] != nil { + arg0 = args[0].(channels.Topic) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *Subscriptions_HasSubscription_Call) Return(b bool) *Subscriptions_HasSubscription_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Subscriptions_HasSubscription_Call) RunAndReturn(run func(topic channels.Topic) bool) *Subscriptions_HasSubscription_Call { + _c.Call.Return(run) + return _c +} + +// SetUnicastManager provides a mock function for the type Subscriptions +func (_mock *Subscriptions) SetUnicastManager(uniMgr p2p.UnicastManager) { + _mock.Called(uniMgr) + return +} + +// Subscriptions_SetUnicastManager_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetUnicastManager' +type Subscriptions_SetUnicastManager_Call struct { + *mock.Call +} + +// SetUnicastManager is a helper method to define mock.On call +// - uniMgr p2p.UnicastManager +func (_e *Subscriptions_Expecter) SetUnicastManager(uniMgr interface{}) *Subscriptions_SetUnicastManager_Call { + return &Subscriptions_SetUnicastManager_Call{Call: _e.mock.On("SetUnicastManager", uniMgr)} +} + +func (_c *Subscriptions_SetUnicastManager_Call) Run(run func(uniMgr p2p.UnicastManager)) *Subscriptions_SetUnicastManager_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.UnicastManager + if args[0] != nil { + arg0 = args[0].(p2p.UnicastManager) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Subscriptions_SetUnicastManager_Call) Return() *Subscriptions_SetUnicastManager_Call { + _c.Call.Return() + return _c +} + +func (_c *Subscriptions_SetUnicastManager_Call) RunAndReturn(run func(uniMgr p2p.UnicastManager)) *Subscriptions_SetUnicastManager_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/topic.go b/network/p2p/mock/topic.go index 5b0c3e11d31..cccd894fe0b 100644 --- a/network/p2p/mock/topic.go +++ b/network/p2p/mock/topic.go @@ -1,76 +1,191 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - p2p "github.com/onflow/flow-go/network/p2p" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" ) +// NewTopic creates a new instance of Topic. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTopic(t interface { + mock.TestingT + Cleanup(func()) +}) *Topic { + mock := &Topic{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Topic is an autogenerated mock type for the Topic type type Topic struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *Topic) Close() error { - ret := _m.Called() +type Topic_Expecter struct { + mock *mock.Mock +} + +func (_m *Topic) EXPECT() *Topic_Expecter { + return &Topic_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type Topic +func (_mock *Topic) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Publish provides a mock function with given fields: _a0, _a1 -func (_m *Topic) Publish(_a0 context.Context, _a1 []byte) error { - ret := _m.Called(_a0, _a1) +// Topic_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type Topic_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *Topic_Expecter) Close() *Topic_Close_Call { + return &Topic_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *Topic_Close_Call) Run(run func()) *Topic_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Topic_Close_Call) Return(err error) *Topic_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Topic_Close_Call) RunAndReturn(run func() error) *Topic_Close_Call { + _c.Call.Return(run) + return _c +} + +// Publish provides a mock function for the type Topic +func (_mock *Topic) Publish(context1 context.Context, bytes []byte) error { + ret := _mock.Called(context1, bytes) if len(ret) == 0 { panic("no return value specified for Publish") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, []byte) error); ok { - r0 = rf(_a0, _a1) + if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) error); ok { + r0 = returnFunc(context1, bytes) } else { r0 = ret.Error(0) } - return r0 } -// String provides a mock function with no fields -func (_m *Topic) String() string { - ret := _m.Called() +// Topic_Publish_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Publish' +type Topic_Publish_Call struct { + *mock.Call +} + +// Publish is a helper method to define mock.On call +// - context1 context.Context +// - bytes []byte +func (_e *Topic_Expecter) Publish(context1 interface{}, bytes interface{}) *Topic_Publish_Call { + return &Topic_Publish_Call{Call: _e.mock.On("Publish", context1, bytes)} +} + +func (_c *Topic_Publish_Call) Run(run func(context1 context.Context, bytes []byte)) *Topic_Publish_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Topic_Publish_Call) Return(err error) *Topic_Publish_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Topic_Publish_Call) RunAndReturn(run func(context1 context.Context, bytes []byte) error) *Topic_Publish_Call { + _c.Call.Return(run) + return _c +} + +// String provides a mock function for the type Topic +func (_mock *Topic) String() string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for String") } var r0 string - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() string); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(string) } - return r0 } -// Subscribe provides a mock function with no fields -func (_m *Topic) Subscribe() (p2p.Subscription, error) { - ret := _m.Called() +// Topic_String_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'String' +type Topic_String_Call struct { + *mock.Call +} + +// String is a helper method to define mock.On call +func (_e *Topic_Expecter) String() *Topic_String_Call { + return &Topic_String_Call{Call: _e.mock.On("String")} +} + +func (_c *Topic_String_Call) Run(run func()) *Topic_String_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Topic_String_Call) Return(s string) *Topic_String_Call { + _c.Call.Return(s) + return _c +} + +func (_c *Topic_String_Call) RunAndReturn(run func() string) *Topic_String_Call { + _c.Call.Return(run) + return _c +} + +// Subscribe provides a mock function for the type Topic +func (_mock *Topic) Subscribe() (p2p.Subscription, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Subscribe") @@ -78,36 +193,47 @@ func (_m *Topic) Subscribe() (p2p.Subscription, error) { var r0 p2p.Subscription var r1 error - if rf, ok := ret.Get(0).(func() (p2p.Subscription, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (p2p.Subscription, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() p2p.Subscription); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() p2p.Subscription); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(p2p.Subscription) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTopic creates a new instance of Topic. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTopic(t interface { - mock.TestingT - Cleanup(func()) -}) *Topic { - mock := &Topic{} - mock.Mock.Test(t) +// Topic_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' +type Topic_Subscribe_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Subscribe is a helper method to define mock.On call +func (_e *Topic_Expecter) Subscribe() *Topic_Subscribe_Call { + return &Topic_Subscribe_Call{Call: _e.mock.On("Subscribe")} +} - return mock +func (_c *Topic_Subscribe_Call) Run(run func()) *Topic_Subscribe_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Topic_Subscribe_Call) Return(subscription p2p.Subscription, err error) *Topic_Subscribe_Call { + _c.Call.Return(subscription, err) + return _c +} + +func (_c *Topic_Subscribe_Call) RunAndReturn(run func() (p2p.Subscription, error)) *Topic_Subscribe_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/topic_provider.go b/network/p2p/mock/topic_provider.go index 062fa689ae1..604228d4a5b 100644 --- a/network/p2p/mock/topic_provider.go +++ b/network/p2p/mock/topic_provider.go @@ -1,68 +1,136 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( + "github.com/libp2p/go-libp2p/core/peer" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) +// NewTopicProvider creates a new instance of TopicProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTopicProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *TopicProvider { + mock := &TopicProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TopicProvider is an autogenerated mock type for the TopicProvider type type TopicProvider struct { mock.Mock } -// GetTopics provides a mock function with no fields -func (_m *TopicProvider) GetTopics() []string { - ret := _m.Called() +type TopicProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *TopicProvider) EXPECT() *TopicProvider_Expecter { + return &TopicProvider_Expecter{mock: &_m.Mock} +} + +// GetTopics provides a mock function for the type TopicProvider +func (_mock *TopicProvider) GetTopics() []string { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetTopics") } var r0 []string - if rf, ok := ret.Get(0).(func() []string); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []string); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]string) } } - return r0 } -// ListPeers provides a mock function with given fields: topic -func (_m *TopicProvider) ListPeers(topic string) []peer.ID { - ret := _m.Called(topic) +// TopicProvider_GetTopics_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTopics' +type TopicProvider_GetTopics_Call struct { + *mock.Call +} + +// GetTopics is a helper method to define mock.On call +func (_e *TopicProvider_Expecter) GetTopics() *TopicProvider_GetTopics_Call { + return &TopicProvider_GetTopics_Call{Call: _e.mock.On("GetTopics")} +} + +func (_c *TopicProvider_GetTopics_Call) Run(run func()) *TopicProvider_GetTopics_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TopicProvider_GetTopics_Call) Return(strings []string) *TopicProvider_GetTopics_Call { + _c.Call.Return(strings) + return _c +} + +func (_c *TopicProvider_GetTopics_Call) RunAndReturn(run func() []string) *TopicProvider_GetTopics_Call { + _c.Call.Return(run) + return _c +} + +// ListPeers provides a mock function for the type TopicProvider +func (_mock *TopicProvider) ListPeers(topic string) []peer.ID { + ret := _mock.Called(topic) if len(ret) == 0 { panic("no return value specified for ListPeers") } var r0 []peer.ID - if rf, ok := ret.Get(0).(func(string) []peer.ID); ok { - r0 = rf(topic) + if returnFunc, ok := ret.Get(0).(func(string) []peer.ID); ok { + r0 = returnFunc(topic) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]peer.ID) } } - return r0 } -// NewTopicProvider creates a new instance of TopicProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTopicProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *TopicProvider { - mock := &TopicProvider{} - mock.Mock.Test(t) +// TopicProvider_ListPeers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPeers' +type TopicProvider_ListPeers_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ListPeers is a helper method to define mock.On call +// - topic string +func (_e *TopicProvider_Expecter) ListPeers(topic interface{}) *TopicProvider_ListPeers_Call { + return &TopicProvider_ListPeers_Call{Call: _e.mock.On("ListPeers", topic)} +} - return mock +func (_c *TopicProvider_ListPeers_Call) Run(run func(topic string)) *TopicProvider_ListPeers_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TopicProvider_ListPeers_Call) Return(iDs []peer.ID) *TopicProvider_ListPeers_Call { + _c.Call.Return(iDs) + return _c +} + +func (_c *TopicProvider_ListPeers_Call) RunAndReturn(run func(topic string) []peer.ID) *TopicProvider_ListPeers_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/unicast_management.go b/network/p2p/mock/unicast_management.go index 8935c9e0584..923e4f5e55c 100644 --- a/network/p2p/mock/unicast_management.go +++ b/network/p2p/mock/unicast_management.go @@ -1,69 +1,167 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - network "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network/p2p/unicast/protocols" mock "github.com/stretchr/testify/mock" +) - peer "github.com/libp2p/go-libp2p/core/peer" +// NewUnicastManagement creates a new instance of UnicastManagement. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewUnicastManagement(t interface { + mock.TestingT + Cleanup(func()) +}) *UnicastManagement { + mock := &UnicastManagement{} + mock.Mock.Test(t) - protocols "github.com/onflow/flow-go/network/p2p/unicast/protocols" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // UnicastManagement is an autogenerated mock type for the UnicastManagement type type UnicastManagement struct { mock.Mock } -// OpenAndWriteOnStream provides a mock function with given fields: ctx, peerID, protectionTag, writingLogic -func (_m *UnicastManagement) OpenAndWriteOnStream(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(network.Stream) error) error { - ret := _m.Called(ctx, peerID, protectionTag, writingLogic) +type UnicastManagement_Expecter struct { + mock *mock.Mock +} + +func (_m *UnicastManagement) EXPECT() *UnicastManagement_Expecter { + return &UnicastManagement_Expecter{mock: &_m.Mock} +} + +// OpenAndWriteOnStream provides a mock function for the type UnicastManagement +func (_mock *UnicastManagement) OpenAndWriteOnStream(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(stream network.Stream) error) error { + ret := _mock.Called(ctx, peerID, protectionTag, writingLogic) if len(ret) == 0 { panic("no return value specified for OpenAndWriteOnStream") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, peer.ID, string, func(network.Stream) error) error); ok { - r0 = rf(ctx, peerID, protectionTag, writingLogic) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID, string, func(stream network.Stream) error) error); ok { + r0 = returnFunc(ctx, peerID, protectionTag, writingLogic) } else { r0 = ret.Error(0) } - return r0 } -// WithDefaultUnicastProtocol provides a mock function with given fields: defaultHandler, preferred -func (_m *UnicastManagement) WithDefaultUnicastProtocol(defaultHandler network.StreamHandler, preferred []protocols.ProtocolName) error { - ret := _m.Called(defaultHandler, preferred) +// UnicastManagement_OpenAndWriteOnStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OpenAndWriteOnStream' +type UnicastManagement_OpenAndWriteOnStream_Call struct { + *mock.Call +} + +// OpenAndWriteOnStream is a helper method to define mock.On call +// - ctx context.Context +// - peerID peer.ID +// - protectionTag string +// - writingLogic func(stream network.Stream) error +func (_e *UnicastManagement_Expecter) OpenAndWriteOnStream(ctx interface{}, peerID interface{}, protectionTag interface{}, writingLogic interface{}) *UnicastManagement_OpenAndWriteOnStream_Call { + return &UnicastManagement_OpenAndWriteOnStream_Call{Call: _e.mock.On("OpenAndWriteOnStream", ctx, peerID, protectionTag, writingLogic)} +} + +func (_c *UnicastManagement_OpenAndWriteOnStream_Call) Run(run func(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(stream network.Stream) error)) *UnicastManagement_OpenAndWriteOnStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 func(stream network.Stream) error + if args[3] != nil { + arg3 = args[3].(func(stream network.Stream) error) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *UnicastManagement_OpenAndWriteOnStream_Call) Return(err error) *UnicastManagement_OpenAndWriteOnStream_Call { + _c.Call.Return(err) + return _c +} + +func (_c *UnicastManagement_OpenAndWriteOnStream_Call) RunAndReturn(run func(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(stream network.Stream) error) error) *UnicastManagement_OpenAndWriteOnStream_Call { + _c.Call.Return(run) + return _c +} + +// WithDefaultUnicastProtocol provides a mock function for the type UnicastManagement +func (_mock *UnicastManagement) WithDefaultUnicastProtocol(defaultHandler network.StreamHandler, preferred []protocols.ProtocolName) error { + ret := _mock.Called(defaultHandler, preferred) if len(ret) == 0 { panic("no return value specified for WithDefaultUnicastProtocol") } var r0 error - if rf, ok := ret.Get(0).(func(network.StreamHandler, []protocols.ProtocolName) error); ok { - r0 = rf(defaultHandler, preferred) + if returnFunc, ok := ret.Get(0).(func(network.StreamHandler, []protocols.ProtocolName) error); ok { + r0 = returnFunc(defaultHandler, preferred) } else { r0 = ret.Error(0) } - return r0 } -// NewUnicastManagement creates a new instance of UnicastManagement. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewUnicastManagement(t interface { - mock.TestingT - Cleanup(func()) -}) *UnicastManagement { - mock := &UnicastManagement{} - mock.Mock.Test(t) +// UnicastManagement_WithDefaultUnicastProtocol_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithDefaultUnicastProtocol' +type UnicastManagement_WithDefaultUnicastProtocol_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WithDefaultUnicastProtocol is a helper method to define mock.On call +// - defaultHandler network.StreamHandler +// - preferred []protocols.ProtocolName +func (_e *UnicastManagement_Expecter) WithDefaultUnicastProtocol(defaultHandler interface{}, preferred interface{}) *UnicastManagement_WithDefaultUnicastProtocol_Call { + return &UnicastManagement_WithDefaultUnicastProtocol_Call{Call: _e.mock.On("WithDefaultUnicastProtocol", defaultHandler, preferred)} +} - return mock +func (_c *UnicastManagement_WithDefaultUnicastProtocol_Call) Run(run func(defaultHandler network.StreamHandler, preferred []protocols.ProtocolName)) *UnicastManagement_WithDefaultUnicastProtocol_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.StreamHandler + if args[0] != nil { + arg0 = args[0].(network.StreamHandler) + } + var arg1 []protocols.ProtocolName + if args[1] != nil { + arg1 = args[1].([]protocols.ProtocolName) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManagement_WithDefaultUnicastProtocol_Call) Return(err error) *UnicastManagement_WithDefaultUnicastProtocol_Call { + _c.Call.Return(err) + return _c +} + +func (_c *UnicastManagement_WithDefaultUnicastProtocol_Call) RunAndReturn(run func(defaultHandler network.StreamHandler, preferred []protocols.ProtocolName) error) *UnicastManagement_WithDefaultUnicastProtocol_Call { + _c.Call.Return(run) + return _c } diff --git a/network/p2p/mock/unicast_manager.go b/network/p2p/mock/unicast_manager.go index 4ae43d3b500..9aff0458b53 100644 --- a/network/p2p/mock/unicast_manager.go +++ b/network/p2p/mock/unicast_manager.go @@ -1,26 +1,48 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - network "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network/p2p/unicast/protocols" mock "github.com/stretchr/testify/mock" +) + +// NewUnicastManager creates a new instance of UnicastManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewUnicastManager(t interface { + mock.TestingT + Cleanup(func()) +}) *UnicastManager { + mock := &UnicastManager{} + mock.Mock.Test(t) - peer "github.com/libp2p/go-libp2p/core/peer" + t.Cleanup(func() { mock.AssertExpectations(t) }) - protocols "github.com/onflow/flow-go/network/p2p/unicast/protocols" -) + return mock +} // UnicastManager is an autogenerated mock type for the UnicastManager type type UnicastManager struct { mock.Mock } -// CreateStream provides a mock function with given fields: ctx, peerID -func (_m *UnicastManager) CreateStream(ctx context.Context, peerID peer.ID) (network.Stream, error) { - ret := _m.Called(ctx, peerID) +type UnicastManager_Expecter struct { + mock *mock.Mock +} + +func (_m *UnicastManager) EXPECT() *UnicastManager_Expecter { + return &UnicastManager_Expecter{mock: &_m.Mock} +} + +// CreateStream provides a mock function for the type UnicastManager +func (_mock *UnicastManager) CreateStream(ctx context.Context, peerID peer.ID) (network.Stream, error) { + ret := _mock.Called(ctx, peerID) if len(ret) == 0 { panic("no return value specified for CreateStream") @@ -28,59 +50,151 @@ func (_m *UnicastManager) CreateStream(ctx context.Context, peerID peer.ID) (net var r0 network.Stream var r1 error - if rf, ok := ret.Get(0).(func(context.Context, peer.ID) (network.Stream, error)); ok { - return rf(ctx, peerID) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID) (network.Stream, error)); ok { + return returnFunc(ctx, peerID) } - if rf, ok := ret.Get(0).(func(context.Context, peer.ID) network.Stream); ok { - r0 = rf(ctx, peerID) + if returnFunc, ok := ret.Get(0).(func(context.Context, peer.ID) network.Stream); ok { + r0 = returnFunc(ctx, peerID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(network.Stream) } } - - if rf, ok := ret.Get(1).(func(context.Context, peer.ID) error); ok { - r1 = rf(ctx, peerID) + if returnFunc, ok := ret.Get(1).(func(context.Context, peer.ID) error); ok { + r1 = returnFunc(ctx, peerID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Register provides a mock function with given fields: unicast -func (_m *UnicastManager) Register(unicast protocols.ProtocolName) error { - ret := _m.Called(unicast) +// UnicastManager_CreateStream_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateStream' +type UnicastManager_CreateStream_Call struct { + *mock.Call +} + +// CreateStream is a helper method to define mock.On call +// - ctx context.Context +// - peerID peer.ID +func (_e *UnicastManager_Expecter) CreateStream(ctx interface{}, peerID interface{}) *UnicastManager_CreateStream_Call { + return &UnicastManager_CreateStream_Call{Call: _e.mock.On("CreateStream", ctx, peerID)} +} + +func (_c *UnicastManager_CreateStream_Call) Run(run func(ctx context.Context, peerID peer.ID)) *UnicastManager_CreateStream_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 peer.ID + if args[1] != nil { + arg1 = args[1].(peer.ID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *UnicastManager_CreateStream_Call) Return(stream network.Stream, err error) *UnicastManager_CreateStream_Call { + _c.Call.Return(stream, err) + return _c +} + +func (_c *UnicastManager_CreateStream_Call) RunAndReturn(run func(ctx context.Context, peerID peer.ID) (network.Stream, error)) *UnicastManager_CreateStream_Call { + _c.Call.Return(run) + return _c +} + +// Register provides a mock function for the type UnicastManager +func (_mock *UnicastManager) Register(unicast protocols.ProtocolName) error { + ret := _mock.Called(unicast) if len(ret) == 0 { panic("no return value specified for Register") } var r0 error - if rf, ok := ret.Get(0).(func(protocols.ProtocolName) error); ok { - r0 = rf(unicast) + if returnFunc, ok := ret.Get(0).(func(protocols.ProtocolName) error); ok { + r0 = returnFunc(unicast) } else { r0 = ret.Error(0) } - return r0 } -// SetDefaultHandler provides a mock function with given fields: defaultHandler -func (_m *UnicastManager) SetDefaultHandler(defaultHandler network.StreamHandler) { - _m.Called(defaultHandler) +// UnicastManager_Register_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Register' +type UnicastManager_Register_Call struct { + *mock.Call } -// NewUnicastManager creates a new instance of UnicastManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewUnicastManager(t interface { - mock.TestingT - Cleanup(func()) -}) *UnicastManager { - mock := &UnicastManager{} - mock.Mock.Test(t) +// Register is a helper method to define mock.On call +// - unicast protocols.ProtocolName +func (_e *UnicastManager_Expecter) Register(unicast interface{}) *UnicastManager_Register_Call { + return &UnicastManager_Register_Call{Call: _e.mock.On("Register", unicast)} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *UnicastManager_Register_Call) Run(run func(unicast protocols.ProtocolName)) *UnicastManager_Register_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 protocols.ProtocolName + if args[0] != nil { + arg0 = args[0].(protocols.ProtocolName) + } + run( + arg0, + ) + }) + return _c +} - return mock +func (_c *UnicastManager_Register_Call) Return(err error) *UnicastManager_Register_Call { + _c.Call.Return(err) + return _c +} + +func (_c *UnicastManager_Register_Call) RunAndReturn(run func(unicast protocols.ProtocolName) error) *UnicastManager_Register_Call { + _c.Call.Return(run) + return _c +} + +// SetDefaultHandler provides a mock function for the type UnicastManager +func (_mock *UnicastManager) SetDefaultHandler(defaultHandler network.StreamHandler) { + _mock.Called(defaultHandler) + return +} + +// UnicastManager_SetDefaultHandler_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetDefaultHandler' +type UnicastManager_SetDefaultHandler_Call struct { + *mock.Call +} + +// SetDefaultHandler is a helper method to define mock.On call +// - defaultHandler network.StreamHandler +func (_e *UnicastManager_Expecter) SetDefaultHandler(defaultHandler interface{}) *UnicastManager_SetDefaultHandler_Call { + return &UnicastManager_SetDefaultHandler_Call{Call: _e.mock.On("SetDefaultHandler", defaultHandler)} +} + +func (_c *UnicastManager_SetDefaultHandler_Call) Run(run func(defaultHandler network.StreamHandler)) *UnicastManager_SetDefaultHandler_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 network.StreamHandler + if args[0] != nil { + arg0 = args[0].(network.StreamHandler) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *UnicastManager_SetDefaultHandler_Call) Return() *UnicastManager_SetDefaultHandler_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastManager_SetDefaultHandler_Call) RunAndReturn(run func(defaultHandler network.StreamHandler)) *UnicastManager_SetDefaultHandler_Call { + _c.Run(run) + return _c } diff --git a/network/p2p/mock/unicast_rate_limiter_distributor.go b/network/p2p/mock/unicast_rate_limiter_distributor.go index 88a587b06aa..9a28fa69b42 100644 --- a/network/p2p/mock/unicast_rate_limiter_distributor.go +++ b/network/p2p/mock/unicast_rate_limiter_distributor.go @@ -1,29 +1,15 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - p2p "github.com/onflow/flow-go/network/p2p" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/onflow/flow-go/network/p2p" mock "github.com/stretchr/testify/mock" - - peer "github.com/libp2p/go-libp2p/core/peer" ) -// UnicastRateLimiterDistributor is an autogenerated mock type for the UnicastRateLimiterDistributor type -type UnicastRateLimiterDistributor struct { - mock.Mock -} - -// AddConsumer provides a mock function with given fields: consumer -func (_m *UnicastRateLimiterDistributor) AddConsumer(consumer p2p.RateLimiterConsumer) { - _m.Called(consumer) -} - -// OnRateLimitedPeer provides a mock function with given fields: pid, role, msgType, topic, reason -func (_m *UnicastRateLimiterDistributor) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { - _m.Called(pid, role, msgType, topic, reason) -} - // NewUnicastRateLimiterDistributor creates a new instance of UnicastRateLimiterDistributor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewUnicastRateLimiterDistributor(t interface { @@ -37,3 +23,120 @@ func NewUnicastRateLimiterDistributor(t interface { return mock } + +// UnicastRateLimiterDistributor is an autogenerated mock type for the UnicastRateLimiterDistributor type +type UnicastRateLimiterDistributor struct { + mock.Mock +} + +type UnicastRateLimiterDistributor_Expecter struct { + mock *mock.Mock +} + +func (_m *UnicastRateLimiterDistributor) EXPECT() *UnicastRateLimiterDistributor_Expecter { + return &UnicastRateLimiterDistributor_Expecter{mock: &_m.Mock} +} + +// AddConsumer provides a mock function for the type UnicastRateLimiterDistributor +func (_mock *UnicastRateLimiterDistributor) AddConsumer(consumer p2p.RateLimiterConsumer) { + _mock.Called(consumer) + return +} + +// UnicastRateLimiterDistributor_AddConsumer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddConsumer' +type UnicastRateLimiterDistributor_AddConsumer_Call struct { + *mock.Call +} + +// AddConsumer is a helper method to define mock.On call +// - consumer p2p.RateLimiterConsumer +func (_e *UnicastRateLimiterDistributor_Expecter) AddConsumer(consumer interface{}) *UnicastRateLimiterDistributor_AddConsumer_Call { + return &UnicastRateLimiterDistributor_AddConsumer_Call{Call: _e.mock.On("AddConsumer", consumer)} +} + +func (_c *UnicastRateLimiterDistributor_AddConsumer_Call) Run(run func(consumer p2p.RateLimiterConsumer)) *UnicastRateLimiterDistributor_AddConsumer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 p2p.RateLimiterConsumer + if args[0] != nil { + arg0 = args[0].(p2p.RateLimiterConsumer) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *UnicastRateLimiterDistributor_AddConsumer_Call) Return() *UnicastRateLimiterDistributor_AddConsumer_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastRateLimiterDistributor_AddConsumer_Call) RunAndReturn(run func(consumer p2p.RateLimiterConsumer)) *UnicastRateLimiterDistributor_AddConsumer_Call { + _c.Run(run) + return _c +} + +// OnRateLimitedPeer provides a mock function for the type UnicastRateLimiterDistributor +func (_mock *UnicastRateLimiterDistributor) OnRateLimitedPeer(pid peer.ID, role string, msgType string, topic string, reason string) { + _mock.Called(pid, role, msgType, topic, reason) + return +} + +// UnicastRateLimiterDistributor_OnRateLimitedPeer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnRateLimitedPeer' +type UnicastRateLimiterDistributor_OnRateLimitedPeer_Call struct { + *mock.Call +} + +// OnRateLimitedPeer is a helper method to define mock.On call +// - pid peer.ID +// - role string +// - msgType string +// - topic string +// - reason string +func (_e *UnicastRateLimiterDistributor_Expecter) OnRateLimitedPeer(pid interface{}, role interface{}, msgType interface{}, topic interface{}, reason interface{}) *UnicastRateLimiterDistributor_OnRateLimitedPeer_Call { + return &UnicastRateLimiterDistributor_OnRateLimitedPeer_Call{Call: _e.mock.On("OnRateLimitedPeer", pid, role, msgType, topic, reason)} +} + +func (_c *UnicastRateLimiterDistributor_OnRateLimitedPeer_Call) Run(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *UnicastRateLimiterDistributor_OnRateLimitedPeer_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 peer.ID + if args[0] != nil { + arg0 = args[0].(peer.ID) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + var arg3 string + if args[3] != nil { + arg3 = args[3].(string) + } + var arg4 string + if args[4] != nil { + arg4 = args[4].(string) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *UnicastRateLimiterDistributor_OnRateLimitedPeer_Call) Return() *UnicastRateLimiterDistributor_OnRateLimitedPeer_Call { + _c.Call.Return() + return _c +} + +func (_c *UnicastRateLimiterDistributor_OnRateLimitedPeer_Call) RunAndReturn(run func(pid peer.ID, role string, msgType string, topic string, reason string)) *UnicastRateLimiterDistributor_OnRateLimitedPeer_Call { + _c.Run(run) + return _c +} diff --git a/network/p2p/node/internal/protocolPeerCache.go b/network/p2p/node/internal/protocolPeerCache.go index 81af4a06538..bc72e44072a 100644 --- a/network/p2p/node/internal/protocolPeerCache.go +++ b/network/p2p/node/internal/protocolPeerCache.go @@ -36,7 +36,7 @@ func NewProtocolPeerCache(logger zerolog.Logger, h host.Host, protocols []protoc } sub, err := h.EventBus(). - Subscribe([]interface{}{new(event.EvtPeerIdentificationCompleted), new(event.EvtPeerProtocolsUpdated)}) + Subscribe([]any{new(event.EvtPeerIdentificationCompleted), new(event.EvtPeerProtocolsUpdated)}) if err != nil { return nil, fmt.Errorf("could not subscribe to peer protocol update events: %w", err) } diff --git a/network/p2p/node/libp2pNode.go b/network/p2p/node/libp2pNode.go index 05069106f86..b507ff656c7 100644 --- a/network/p2p/node/libp2pNode.go +++ b/network/p2p/node/libp2pNode.go @@ -289,7 +289,7 @@ func (n *Node) createStream(ctx context.Context, peerID peer.ID) (libp2pnet.Stre return nil, flownet.NewPeerUnreachableError(fmt.Errorf("could not create stream peer_id: %s: %w", peerID, err)) } - lg.Info(). + lg.Debug(). Str("networking_protocol_id", string(stream.Protocol())). Msg("stream successfully created to remote peer") return stream, nil diff --git a/network/p2p/scoring/internal/subscriptionCache.go b/network/p2p/scoring/internal/subscriptionCache.go index 94f64a8594f..37f9ea798ff 100644 --- a/network/p2p/scoring/internal/subscriptionCache.go +++ b/network/p2p/scoring/internal/subscriptionCache.go @@ -2,6 +2,7 @@ package internal import ( "fmt" + "slices" "github.com/libp2p/go-libp2p/core/peer" "github.com/rs/zerolog" @@ -121,11 +122,9 @@ func (s *SubscriptionRecordCache) AddWithInitTopicForPeer(pid peer.ID, topic str record.Topics = make([]string, 0) } // check if the topic already exists; if it does, we do not need to update the record. - for _, t := range record.Topics { - if t == topic { - // topic already exists - return record - } + if slices.Contains(record.Topics, topic) { + // topic already exists + return record } record.LastUpdatedCycle = currentCycle record.Topics = append(record.Topics, topic) diff --git a/network/p2p/scoring/subscription_provider.go b/network/p2p/scoring/subscription_provider.go index 2bfd43bb870..98649d48cbe 100644 --- a/network/p2p/scoring/subscription_provider.go +++ b/network/p2p/scoring/subscription_provider.go @@ -7,7 +7,6 @@ import ( "github.com/go-playground/validator/v10" "github.com/libp2p/go-libp2p/core/peer" "github.com/rs/zerolog" - "go.uber.org/atomic" "github.com/onflow/flow-go/module" "github.com/onflow/flow-go/module/component" @@ -34,8 +33,6 @@ type SubscriptionProvider struct { // idProvider translates the peer ids to flow ids. idProvider module.IdentityProvider - // allTopics is a list of all topics in the pubsub network that this node is subscribed to. - allTopicsUpdate atomic.Bool // whether a goroutine is already updating the list of topics allTopicsUpdateInterval time.Duration // the interval for updating the list of topics in the pubsub network that this node has subscribed to. } @@ -99,22 +96,14 @@ func (s *SubscriptionProvider) updateTopicsLoop(ctx irrecoverable.SignalerContex } } -// updateTopics returns all the topics in the pubsub network that this node (peer) has subscribed to. -// Note that this method always returns the cached version of the subscribed topics while querying the -// pubsub network for the list of topics in a goroutine. Hence, the first call to this method always returns an empty -// list. -// Args: -// - ctx: the context of the caller. -// Returns: -// - error on failure to update the list of topics. The returned error is irrecoverable and indicates an exception. +// updateTopics queries the pubsub network for all topics this node subscribes to and updates the cache +// with the current peer subscriptions for each topic. +// +// IMPORTANT: This method is designed to be called only from the single-goroutine ticker loop in updateTopicsLoop. +// No synchronization is needed because the ticker guarantees sequential execution. +// +// No errors are expected during normal operation. func (s *SubscriptionProvider) updateTopics() error { - if updateInProgress := s.allTopicsUpdate.CompareAndSwap(false, true); updateInProgress { - // another goroutine is already updating the list of topics - s.logger.Trace().Msg("skipping topic update; another update is already in progress") - return nil - } - - // start of critical section; protected by updateInProgress atomic flag allTopics := s.topicProviderOracle().GetTopics() s.logger.Trace().Msgf("all topics updated: %v", allTopics) @@ -145,9 +134,6 @@ func (s *SubscriptionProvider) updateTopics() error { Msg("updated topics for peer") } } - - // remove the update flag; end of critical section - s.allTopicsUpdate.Store(false) return nil } diff --git a/network/p2p/test/topic_validator_test.go b/network/p2p/test/topic_validator_test.go index ac200851eb1..6715c20fb04 100644 --- a/network/p2p/test/topic_validator_test.go +++ b/network/p2p/test/topic_validator_test.go @@ -351,7 +351,7 @@ func TestAuthorizedSenderValidator_Unauthorized(t *testing.T) { Err: message.ErrUnauthorizedRole, } violationsConsumer := mocknetwork.NewViolationsConsumer(t) - violationsConsumer.On("OnUnAuthorizedSenderError", violation).Once().Return(nil) + violationsConsumer.On("OnUnauthorizedSenderError", violation).Once().Return(nil) getIdentity := func(pid peer.ID) (*flow.Identity, bool) { fid, err := translatorFixture.GetFlowID(pid) if err != nil { diff --git a/network/p2p/tracer/gossipSubMeshTracer.go b/network/p2p/tracer/gossipSubMeshTracer.go index a25f4e717d6..c36c5d041bf 100644 --- a/network/p2p/tracer/gossipSubMeshTracer.go +++ b/network/p2p/tracer/gossipSubMeshTracer.go @@ -279,6 +279,15 @@ func (t *GossipSubMeshTracer) Leave(topic string) { Str("topic", topic). Msg("local peer left topic") } + + // Clean up topic mesh tracking for cluster topics. + // Note: Metric cardinality is bounded by normalizing cluster topics to their prefix + // (e.g., "consensus-cluster", "sync-cluster") when recording metrics. + if channels.IsClusterChannel(channels.Channel(topic)) { + t.topicMeshMu.Lock() + delete(t.topicMeshMap, topic) + t.topicMeshMu.Unlock() + } } // ValidateMessage is called by GossipSub as a callback when a message is received by the local node and entered the validation phase. diff --git a/network/proxy/conduit.go b/network/proxy/conduit.go index 377087dc005..ac4f8bb530b 100644 --- a/network/proxy/conduit.go +++ b/network/proxy/conduit.go @@ -14,14 +14,14 @@ type ProxyConduit struct { var _ network.Conduit = (*ProxyConduit)(nil) -func (c *ProxyConduit) Publish(event interface{}, targetIDs ...flow.Identifier) error { +func (c *ProxyConduit) Publish(event any, targetIDs ...flow.Identifier) error { return c.Conduit.Publish(event, c.targetNodeID) } -func (c *ProxyConduit) Unicast(event interface{}, targetID flow.Identifier) error { +func (c *ProxyConduit) Unicast(event any, targetID flow.Identifier) error { return c.Conduit.Unicast(event, c.targetNodeID) } -func (c *ProxyConduit) Multicast(event interface{}, num uint, targetIDs ...flow.Identifier) error { +func (c *ProxyConduit) Multicast(event any, num uint, targetIDs ...flow.Identifier) error { return c.Conduit.Multicast(event, 1, c.targetNodeID) } diff --git a/network/queue.go b/network/queue.go index 0d2b6241529..e26f647a3bb 100644 --- a/network/queue.go +++ b/network/queue.go @@ -3,10 +3,10 @@ package network // MessageQueue is the interface of the inbound message queue type MessageQueue interface { // Insert inserts the message in queue - Insert(message interface{}) error + Insert(message any) error // Remove removes the message from the queue in priority order. If no message is found, this call blocks. // If two messages have the same priority, items are de-queued in insertion order - Remove() interface{} + Remove() any // Len gives the current length of the queue Len() int } diff --git a/network/queue/eventPriority.go b/network/queue/eventPriority.go index ad64278aa87..c40ae5b1a03 100644 --- a/network/queue/eventPriority.go +++ b/network/queue/eventPriority.go @@ -18,7 +18,7 @@ const ( // QMessage is the message that is enqueued for each incoming message type QMessage struct { - Payload interface{} // the decoded message + Payload any // the decoded message Size int // the size of the message in bytes Target channels.Channel // the target channel to lookup the engine SenderID flow.Identifier // senderID for logging @@ -26,7 +26,7 @@ type QMessage struct { // GetEventPriority returns the priority of the flow event message. // It is an average of the priority by message type and priority by message size -func GetEventPriority(message interface{}) (Priority, error) { +func GetEventPriority(message any) (Priority, error) { qm, ok := message.(QMessage) if !ok { return 0, fmt.Errorf("invalid message format: %T", message) @@ -37,7 +37,7 @@ func GetEventPriority(message interface{}) (Priority, error) { } // getPriorityByType maps a message type to its priority -func getPriorityByType(message interface{}) Priority { +func getPriorityByType(message any) Priority { switch message.(type) { // consensus case *messages.Proposal: diff --git a/network/queue/messageQueue.go b/network/queue/messageQueue.go index 9fffdbf0556..1caccef65c1 100644 --- a/network/queue/messageQueue.go +++ b/network/queue/messageQueue.go @@ -3,6 +3,7 @@ package queue import ( "container/heap" "context" + "errors" "fmt" "sync" "time" @@ -10,25 +11,38 @@ import ( "github.com/onflow/flow-go/module" ) +// ErrQueueFull is returned when attempting to insert a message into a full queue. +var ErrQueueFull = errors.New("message queue is full") + type Priority int const LowPriority = Priority(1) const MediumPriority = Priority(5) const HighPriority = Priority(10) +// DefaultMaxSize is the default maximum number of messages that can be queued. +// This limit prevents unbounded memory growth from message flooding attacks. +const DefaultMaxSize = 100_000 + // MessagePriorityFunc - the callback function to derive priority of a message -type MessagePriorityFunc func(message interface{}) (Priority, error) +type MessagePriorityFunc func(message any) (Priority, error) -// MessageQueue is the heap based priority queue implementation of the MessageQueue implementation +// MessageQueue is the heap based priority queue implementation of the MessageQueue implementation. +// It enforces a maximum size limit to prevent unbounded memory growth from message flooding attacks. type MessageQueue struct { pq *priorityQueue cond *sync.Cond priorityFunc MessagePriorityFunc ctx context.Context metrics module.NetworkInboundQueueMetrics + maxSize int } -func (mq *MessageQueue) Insert(message interface{}) error { +// Insert adds a message to the queue. +// +// Expected error returns during normal operation: +// - [ErrQueueFull]: when the queue has reached its maximum capacity +func (mq *MessageQueue) Insert(message any) error { if err := mq.ctx.Err(); err != nil { return err @@ -50,6 +64,12 @@ func (mq *MessageQueue) Insert(message interface{}) error { // lock the underlying mutex mq.cond.L.Lock() + // check if queue is at capacity + if mq.pq.Len() >= mq.maxSize { + mq.cond.L.Unlock() + return fmt.Errorf("queue at capacity (%d messages): %w", mq.maxSize, ErrQueueFull) + } + // push message to the underlying priority queue heap.Push(mq.pq, item) @@ -65,7 +85,7 @@ func (mq *MessageQueue) Insert(message interface{}) error { return nil } -func (mq *MessageQueue) Remove() interface{} { +func (mq *MessageQueue) Remove() any { mq.cond.L.Lock() defer mq.cond.L.Unlock() for mq.pq.Len() == 0 { @@ -92,7 +112,12 @@ func (mq *MessageQueue) Len() int { return mq.pq.Len() } -func NewMessageQueue(ctx context.Context, priorityFunc MessagePriorityFunc, metrics module.NetworkInboundQueueMetrics) *MessageQueue { +// NewMessageQueue creates a new bounded message queue with the specified maximum size. +// If maxSize is 0 or negative, DefaultMaxSize is used. +func NewMessageQueue(ctx context.Context, priorityFunc MessagePriorityFunc, metrics module.NetworkInboundQueueMetrics, maxSize int) *MessageQueue { + if maxSize <= 0 { + maxSize = DefaultMaxSize + } var items = make([]*item, 0) pq := priorityQueue(items) mq := &MessageQueue{ @@ -100,6 +125,7 @@ func NewMessageQueue(ctx context.Context, priorityFunc MessagePriorityFunc, metr priorityFunc: priorityFunc, ctx: ctx, metrics: metrics, + maxSize: maxSize, } m := sync.Mutex{} mq.cond = sync.NewCond(&m) diff --git a/network/queue/messageQueue_test.go b/network/queue/messageQueue_test.go index 5fd7cf86839..4e316749780 100644 --- a/network/queue/messageQueue_test.go +++ b/network/queue/messageQueue_test.go @@ -38,7 +38,7 @@ func TestConcurrentQueueAccess(t *testing.T) { messages := createMessages(messageCnt, randomPriority) - var priorityFunc queue.MessagePriorityFunc = func(message interface{}) (queue.Priority, error) { + var priorityFunc queue.MessagePriorityFunc = func(message any) (queue.Priority, error) { return messages[message.(string)], nil } @@ -49,7 +49,7 @@ func TestConcurrentQueueAccess(t *testing.T) { close(msgChan) ctx, cancel := context.WithCancel(context.Background()) - mq := queue.NewMessageQueue(ctx, priorityFunc, metrics.NewNoopCollector()) + mq := queue.NewMessageQueue(ctx, priorityFunc, metrics.NewNoopCollector(), 0) writeWg := sync.WaitGroup{} write := func() { @@ -71,13 +71,13 @@ func TestConcurrentQueueAccess(t *testing.T) { } // kick off writers - for i := 0; i < writerCnt; i++ { + for range writerCnt { writeWg.Add(1) go write() } // kick off readers - for i := 0; i < readerCnt; i++ { + for range readerCnt { go read() } @@ -96,7 +96,7 @@ func TestConcurrentQueueAccess(t *testing.T) { // TestQueueShutdown tests that Remove unblocks when the context is shutdown func TestQueueShutdown(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) - mq := queue.NewMessageQueue(ctx, fixedPriority, metrics.NewNoopCollector()) + mq := queue.NewMessageQueue(ctx, fixedPriority, metrics.NewNoopCollector(), 0) ch := make(chan struct{}) go func() { @@ -118,7 +118,7 @@ func TestQueueShutdown(t *testing.T) { func testQueue(t *testing.T, messages map[string]queue.Priority) { // create the priority function - var priorityFunc queue.MessagePriorityFunc = func(message interface{}) (queue.Priority, error) { + var priorityFunc queue.MessagePriorityFunc = func(message any) (queue.Priority, error) { return messages[message.(string)], nil } @@ -131,7 +131,7 @@ func testQueue(t *testing.T, messages map[string]queue.Priority) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() // create the queue - mq := queue.NewMessageQueue(ctx, priorityFunc, metrics.NewNoopCollector()) + mq := queue.NewMessageQueue(ctx, priorityFunc, metrics.NewNoopCollector(), 0) // insert all elements in the queue for msg, p := range messages { @@ -167,7 +167,7 @@ func BenchmarkPush(b *testing.B) { b.StopTimer() ctx, cancel := context.WithCancel(context.Background()) defer cancel() - var mq = queue.NewMessageQueue(ctx, randomPriority, metrics.NewNoopCollector()) + var mq = queue.NewMessageQueue(ctx, randomPriority, metrics.NewNoopCollector(), 0) for i := 0; i < b.N; i++ { err := mq.Insert("test") if err != nil { @@ -187,7 +187,7 @@ func BenchmarkPop(b *testing.B) { b.StopTimer() ctx, cancel := context.WithCancel(context.Background()) defer cancel() - var mq = queue.NewMessageQueue(ctx, randomPriority, metrics.NewNoopCollector()) + var mq = queue.NewMessageQueue(ctx, randomPriority, metrics.NewNoopCollector(), 0) for i := 0; i < b.N; i++ { err := mq.Insert("test") if err != nil { @@ -205,7 +205,7 @@ func createMessages(messageCnt int, priorityFunc queue.MessagePriorityFunc) map[ // create a map of messages -> priority messages := make(map[string]queue.Priority, messageCnt) - for i := 0; i < messageCnt; i++ { + for i := range messageCnt { // choose a random priority p, _ := priorityFunc(nil) // create a message @@ -216,12 +216,45 @@ func createMessages(messageCnt int, priorityFunc queue.MessagePriorityFunc) map[ return messages } -func randomPriority(_ interface{}) (queue.Priority, error) { +func randomPriority(_ any) (queue.Priority, error) { p := rand.Intn(int(queue.HighPriority-queue.LowPriority+1)) + int(queue.LowPriority) return queue.Priority(p), nil } -func fixedPriority(_ interface{}) (queue.Priority, error) { +// TestQueueFull tests that inserting into a full queue returns ErrQueueFull +func TestQueueFull(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + maxSize := 10 + mq := queue.NewMessageQueue(ctx, fixedPriority, metrics.NewNoopCollector(), maxSize) + + // fill the queue to capacity + for i := 0; i < maxSize; i++ { + err := mq.Insert("message") + assert.NoError(t, err) + } + + assert.Equal(t, maxSize, mq.Len()) + + // next insert should fail with ErrQueueFull + err := mq.Insert("overflow") + assert.Error(t, err) + assert.ErrorIs(t, err, queue.ErrQueueFull) + + // queue length should still be at maxSize + assert.Equal(t, maxSize, mq.Len()) + + // removing one element should allow inserting again + _ = mq.Remove() + assert.Equal(t, maxSize-1, mq.Len()) + + err = mq.Insert("new message") + assert.NoError(t, err) + assert.Equal(t, maxSize, mq.Len()) +} + +func fixedPriority(_ any) (queue.Priority, error) { return queue.MediumPriority, nil } diff --git a/network/queue/priorityQueue.go b/network/queue/priorityQueue.go index 5aa1e2919be..300662aa947 100644 --- a/network/queue/priorityQueue.go +++ b/network/queue/priorityQueue.go @@ -3,7 +3,7 @@ package queue import "time" type item struct { - message interface{} + message any priority int // The priority of the item in the queue. // The index is needed by update and is maintained by the heap.Interface methods. index int // The index of the item in the heap. @@ -34,7 +34,7 @@ func (pq priorityQueue) Swap(i, j int) { pq[j].index = j } -func (pq *priorityQueue) Push(x interface{}) { +func (pq *priorityQueue) Push(x any) { n := len(*pq) item, ok := x.(*item) if !ok { @@ -44,7 +44,7 @@ func (pq *priorityQueue) Push(x interface{}) { *pq = append(*pq, item) } -func (pq *priorityQueue) Pop() interface{} { +func (pq *priorityQueue) Pop() any { old := *pq n := len(old) item := old[n-1] diff --git a/network/queue/queueWorker.go b/network/queue/queueWorker.go index 68daf6ef665..bb6f6ee9051 100644 --- a/network/queue/queueWorker.go +++ b/network/queue/queueWorker.go @@ -10,7 +10,7 @@ const DefaultNumWorkers = 50 // worker de-queues an item from the queue if available and calls the callback function endlessly // if no item is available, it blocks -func worker(ctx context.Context, queue network.MessageQueue, callback func(interface{})) { +func worker(ctx context.Context, queue network.MessageQueue, callback func(any)) { for { // blocking call item := queue.Remove() @@ -24,8 +24,8 @@ func worker(ctx context.Context, queue network.MessageQueue, callback func(inter } // CreateQueueWorkers creates queue workers to read from the queue -func CreateQueueWorkers(ctx context.Context, numWorks uint64, queue network.MessageQueue, callback func(interface{})) { - for i := uint64(0); i < numWorks; i++ { +func CreateQueueWorkers(ctx context.Context, numWorks uint64, queue network.MessageQueue, callback func(any)) { + for range numWorks { go worker(ctx, queue, callback) } } diff --git a/network/queue/queueWorker_test.go b/network/queue/queueWorker_test.go index 2bd1a46ac0e..2043cdc14f9 100644 --- a/network/queue/queueWorker_test.go +++ b/network/queue/queueWorker_test.go @@ -35,19 +35,19 @@ func testWorkers(t *testing.T, maxPriority int, messageCnt int, workerCnt int) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() // the priority function just returns the message as the priority itself (message = priority) - var q network.MessageQueue = queue.NewMessageQueue(ctx, func(m interface{}) (queue.Priority, error) { + var q network.MessageQueue = queue.NewMessageQueue(ctx, func(m any) (queue.Priority, error) { i, ok := m.(int) assert.True(t, ok) return queue.Priority(i), nil }, - metrics.NewNoopCollector()) + metrics.NewNoopCollector(), 0) var l sync.Mutex // protect comparisons with expectedPriority messagesPerPriority := messageCnt / maxPriority // messages per priority expectedPriority := maxPriority - 1 // when dequeing, the priority can be the current highest priority or one less var callbackCnt int64 //count the number of times the callback gets called // callback checks if message is of expected priority - callback := func(data interface{}) { + callback := func(data any) { actual := data.(int) l.Lock() assert.LessOrEqual(t, expectedPriority, actual) @@ -62,7 +62,7 @@ func testWorkers(t *testing.T, maxPriority int, messageCnt int, workerCnt int) { // each message is an int which is also its priority // messages are inserted in increasing order of priority // e.g. 1,2,3...10,1,2,3,..10,....messagecnt - for i := 0; i < messageCnt; i++ { + for i := range messageCnt { priority := (i % maxPriority) + 1 err := q.Insert(priority) assert.NoError(t, err) diff --git a/network/relay/relayer.go b/network/relay/relayer.go index 682c026b3c4..73f76677a31 100644 --- a/network/relay/relayer.go +++ b/network/relay/relayer.go @@ -20,7 +20,7 @@ type Relayer struct { // ignored. If a usecase arises, we should implement a mechanism to forward these messages to a handler. type noopProcessor struct{} -func (n *noopProcessor) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { +func (n *noopProcessor) Process(channel channels.Channel, originID flow.Identifier, event any) error { return nil } @@ -40,7 +40,7 @@ func NewRelayer(destinationNetwork network.EngineRegistry, channel channels.Chan } -func (r *Relayer) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error { +func (r *Relayer) Process(channel channels.Channel, originID flow.Identifier, event any) error { g := new(errgroup.Group) g.Go(func() error { diff --git a/network/slashing/consumer.go b/network/slashing/consumer.go index 3ba8d656c21..295526c5145 100644 --- a/network/slashing/consumer.go +++ b/network/slashing/consumer.go @@ -92,8 +92,8 @@ func (c *Consumer) reportMisbehavior(misbehavior network.Misbehavior, violation c.misbehaviorReportConsumer.ReportMisbehaviorOnChannel(violation.Channel, report) } -// OnUnAuthorizedSenderError logs an error for unauthorized sender error and reports a misbehavior to alsp misbehavior report manager. -func (c *Consumer) OnUnAuthorizedSenderError(violation *network.Violation) { +// OnUnauthorizedSenderError logs an error for unauthorized sender error and reports a misbehavior to alsp misbehavior report manager. +func (c *Consumer) OnUnauthorizedSenderError(violation *network.Violation) { c.logOffense(alsp.UnAuthorizedSender, violation) c.reportMisbehavior(alsp.UnAuthorizedSender, violation) } diff --git a/network/stub/hash.go b/network/stub/hash.go index 4730e4b096d..dd119bafa76 100644 --- a/network/stub/hash.go +++ b/network/stub/hash.go @@ -12,7 +12,7 @@ import ( ) // eventKey generates a unique fingerprint for the tuple of (sender, event, type of event, channel) -func eventKey(from flow.Identifier, channel channels.Channel, event interface{}) (string, error) { +func eventKey(from flow.Identifier, channel channels.Channel, event any) (string, error) { marshaler := json.NewMarshaler() tag, err := marshaler.Marshal([]byte(fmt.Sprintf("testthenetwork %s %T", channel, event))) diff --git a/network/stub/hub.go b/network/stub/hub.go index 91a50940545..5ba0e6a4fc5 100644 --- a/network/stub/hub.go +++ b/network/stub/hub.go @@ -47,7 +47,7 @@ func (h *Hub) DeliverAllEventually(t *testing.T, condition func() bool) { h.DeliverAllEventuallyUntil(t, condition, time.Second*10, time.Millisecond*500) } -// DeliverAllEventuallyUntil attempts attempts on delivery of all the buffered messages in the Network instances +// DeliverAllEventuallyUntil attempts on delivery of all the buffered messages in the Network instances // attached to this instance of Hub. Once the delivery is done, it evaluates and returns the // condition function. It fails if delivery of all buffered messages in the Network instances // attached to this Hub is not getting done within `waitFor` time interval. diff --git a/network/stub/network.go b/network/stub/network.go index 65468296e14..0e3249ebf08 100644 --- a/network/stub/network.go +++ b/network/stub/network.go @@ -118,7 +118,7 @@ func (n *Network) UnRegisterChannel(channel channels.Channel) error { // submit is called when the attached Engine to the channel is sending an event to an // Engine attached to the same channel on another node or nodes. -func (n *Network) submit(channel channels.Channel, event interface{}, targetIDs ...flow.Identifier) error { +func (n *Network) submit(channel channels.Channel, event any, targetIDs ...flow.Identifier) error { e, ok := event.(messages.UntrustedMessage) if !ok { return fmt.Errorf("invalid message type: expected messages.UntrustedMessage, got %T", event) @@ -137,7 +137,7 @@ func (n *Network) submit(channel channels.Channel, event interface{}, targetIDs // UnicastOnChannel is called when the attached Engine to the channel is sending an event to a single target // Engine attached to the same channel on another node. -func (n *Network) UnicastOnChannel(channel channels.Channel, event interface{}, targetID flow.Identifier) error { +func (n *Network) UnicastOnChannel(channel channels.Channel, event any, targetID flow.Identifier) error { msg, ok := event.(messages.UntrustedMessage) if !ok { return fmt.Errorf("invalid message type: expected messages.UntrustedMessage, got %T", event) @@ -156,7 +156,7 @@ func (n *Network) UnicastOnChannel(channel channels.Channel, event interface{}, // publish is called when the attached Engine is sending an event to a group of Engines attached to the // same channel on other nodes based on selector. // In this test helper implementation, publish uses submit method under the hood. -func (n *Network) PublishOnChannel(channel channels.Channel, event interface{}, targetIDs ...flow.Identifier) error { +func (n *Network) PublishOnChannel(channel channels.Channel, event any, targetIDs ...flow.Identifier) error { if len(targetIDs) == 0 { return fmt.Errorf("publish found empty target ID list for the message") @@ -168,7 +168,7 @@ func (n *Network) PublishOnChannel(channel channels.Channel, event interface{}, // multicast is called when an engine attached to the channel is sending an event to a number of randomly chosen // Engines attached to the same channel on other nodes. The targeted nodes are selected based on the selector. // In this test helper implementation, multicast uses submit method under the hood. -func (n *Network) MulticastOnChannel(channel channels.Channel, event interface{}, num uint, targetIDs ...flow.Identifier) error { +func (n *Network) MulticastOnChannel(channel channels.Channel, event any, num uint, targetIDs ...flow.Identifier) error { var err error targetIDs, err = flow.Sample(num, targetIDs...) if err != nil { diff --git a/network/test/cohort1/network_test.go b/network/test/cohort1/network_test.go index 7934c3fa203..70b926c362e 100644 --- a/network/test/cohort1/network_test.go +++ b/network/test/cohort1/network_test.go @@ -816,20 +816,44 @@ func (suite *NetworkTestSuite) TestMaxMessageSize_Unicast() { // TestLargeMessageSize_SendDirect asserts that a ChunkDataResponse is treated as a large message and can be unicasted // successfully even though it's size is greater than the default message size. +// The message is sent from an Execution Node (EN) to a Verification Node (VN). func (suite *NetworkTestSuite) TestLargeMessageSize_SendDirect() { - sourceIndex := 0 - targetIndex := suite.size - 1 - targetId := suite.ids[targetIndex].NodeID + sourceIndex := 0 // EN // creates a network payload with a size greater than the default max size using a known large message type targetSize := uint64(underlay.DefaultMaxUnicastMsgSize) + 1000 event := unittest.ChunkDataResponseMsgFixture(unittest.IdentifierFixture(), unittest.WithApproximateSize(targetSize)) - // expect one message to be received by the target + // create a VN node as target + vnIds, vnLibP2PNodes := testutils.LibP2PNodeForNetworkFixture(suite.T(), suite.sporkId, 1, p2ptest.WithRole(flow.RoleVerification)) + vnId := vnIds[0] + + // update identity providers to include the VN + allIds := flow.IdentityList(append(suite.ids, vnId)) + suite.providers[sourceIndex].SetIdentities(allIds) + + vnIdProvider := unittest.NewUpdatableIDProvider(allIds) + vnNetCfg := testutils.NetworkConfigFixture(suite.T(), *vnId, vnIdProvider, suite.sporkId, vnLibP2PNodes[0]) + vnNet, err := underlay.NewNetwork(vnNetCfg) + require.NoError(suite.T(), err) + + ctx, cancel := context.WithCancel(suite.mwCtx) + irrecoverableCtx := irrecoverable.NewMockSignalerContext(suite.T(), ctx) + + testutils.StartNodesAndNetworks(irrecoverableCtx, suite.T(), vnLibP2PNodes, []network.EngineRegistry{vnNet}) + defer testutils.StopComponents(suite.T(), vnLibP2PNodes, 1*time.Second) + defer testutils.StopComponents(suite.T(), []network.EngineRegistry{vnNet}, 1*time.Second) + // cancel is deferred last so it runs first (LIFO), signaling components to stop before waiting + defer cancel() + + // connect EN and VN so they can communicate + p2ptest.LetNodesDiscoverEachOther(suite.T(), ctx, []p2p.LibP2PNode{suite.libP2PNodes[sourceIndex], vnLibP2PNodes[0]}, flow.IdentityList{suite.ids[sourceIndex], vnId}) + suite.networks[sourceIndex].UpdateNodeAddresses() + + // expect one message to be received by the VN ch := make(chan struct{}) - // mocks a target engine on the last node of the test suit that will receive the message on the test channel. targetEngine := &mocknetwork.MessageProcessor{} - _, err := suite.networks[targetIndex].Register(channels.ProvideChunks, targetEngine) + _, err = vnNet.Register(channels.ProvideChunks, targetEngine) require.NoError(suite.T(), err) targetEngine.On("Process", mockery.Anything, mockery.Anything, mockery.Anything). Run(func(args mockery.Arguments) { @@ -837,11 +861,11 @@ func (suite *NetworkTestSuite) TestLargeMessageSize_SendDirect() { msgChannel, ok := args[0].(channels.Channel) require.True(suite.T(), ok) - require.Equal(suite.T(), channels.ProvideChunks, msgChannel) // channel + require.Equal(suite.T(), channels.ProvideChunks, msgChannel) msgOriginID, ok := args[1].(flow.Identifier) require.True(suite.T(), ok) - require.Equal(suite.T(), suite.ids[sourceIndex].NodeID, msgOriginID) // sender id + require.Equal(suite.T(), suite.ids[sourceIndex].NodeID, msgOriginID) msgPayload, ok := args[2].(*flow.ChunkDataResponse) require.True(suite.T(), ok) @@ -849,16 +873,16 @@ func (suite *NetworkTestSuite) TestLargeMessageSize_SendDirect() { internal, err := event.ToInternal() require.NoError(suite.T(), err) - require.Equal(suite.T(), internal, msgPayload) // payload + require.Equal(suite.T(), internal, msgPayload) }).Return(nil).Once() - // sends a direct message from source node to the target node + // sends a direct message from EN to VN con0, err := suite.networks[sourceIndex].Register(channels.ProvideChunks, &mocknetwork.MessageProcessor{}) require.NoError(suite.T(), err) - require.NoError(suite.T(), con0.Unicast(event, targetId)) + require.NoError(suite.T(), con0.Unicast(event, vnId.NodeID)) - // check message reception on target - unittest.RequireCloseBefore(suite.T(), ch, 5*time.Second, "source node failed to send large message to target") + // check message reception on VN + unittest.RequireCloseBefore(suite.T(), ch, 5*time.Second, "EN failed to send large message to VN") } // TestMaxMessageSize_Publish evaluates that invoking Publish method of the network on a message diff --git a/network/test/cohort2/unicast_authorization_test.go b/network/test/cohort2/unicast_authorization_test.go index c3f55e54738..b961a1766e7 100644 --- a/network/test/cohort2/unicast_authorization_test.go +++ b/network/test/cohort2/unicast_authorization_test.go @@ -24,6 +24,7 @@ import ( mocknetwork "github.com/onflow/flow-go/network/mock" "github.com/onflow/flow-go/network/p2p" p2plogging "github.com/onflow/flow-go/network/p2p/logging" + p2ptest "github.com/onflow/flow-go/network/p2p/test" "github.com/onflow/flow-go/network/underlay" "github.com/onflow/flow-go/network/validator" "github.com/onflow/flow-go/utils/unittest" @@ -128,16 +129,12 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_UnstakedPeer() expectedSenderPeerID, err := unittest.PeerIDFromFlowID(u.senderID) require.NoError(u.T(), err) - var nilID *flow.Identity expectedViolation := &network.Violation{ - Identity: nilID, // because the peer will be unverified this identity will be nil PeerID: p2plogging.PeerId(expectedSenderPeerID), - MsgType: "", // message will not be decoded before OnSenderEjectedError is logged, we won't log message type - Channel: channels.TestNetworkChannel, // message will not be decoded before OnSenderEjectedError is logged, we won't log peer ID Protocol: message.ProtocolTypeUnicast, Err: validator.ErrIdentityUnverified, } - slashingViolationsConsumer.On("OnUnAuthorizedSenderError", expectedViolation).Return(nil).Once().Run(func(args mockery.Arguments) { + slashingViolationsConsumer.On("OnUnauthorizedSenderError", expectedViolation).Return(nil).Once().Run(func(args mockery.Arguments) { close(u.waitCh) }) @@ -183,8 +180,8 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_EjectedPeer() { Identity: u.senderID, // we expect this method to be called with the ejected identity OriginID: u.senderID.NodeID, PeerID: p2plogging.PeerId(expectedSenderPeerID), - MsgType: "", // message will not be decoded before OnSenderEjectedError is logged, we won't log message type - Channel: channels.TestNetworkChannel, // message will not be decoded before OnSenderEjectedError is logged, we won't log peer ID + MsgType: "", // message will not be decoded before OnSenderEjectedError is logged, we won't log message type + Channel: "", // ejection is checked before the channel is known Protocol: message.ProtocolTypeUnicast, Err: validator.ErrSenderEjected, } @@ -229,7 +226,7 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_UnauthorizedPee Err: message.ErrUnauthorizedMessageOnChannel, } - slashingViolationsConsumer.On("OnUnAuthorizedSenderError", expectedViolation). + slashingViolationsConsumer.On("OnUnauthorizedSenderError", expectedViolation). Return(nil).Once().Run(func(args mockery.Arguments) { close(u.waitCh) }) @@ -332,7 +329,7 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_WrongMsgCode() Err: message.ErrUnauthorizedMessageOnChannel, } - slashingViolationsConsumer.On("OnUnAuthorizedSenderError", expectedViolation). + slashingViolationsConsumer.On("OnUnauthorizedSenderError", expectedViolation). Return(nil).Once().Run(func(args mockery.Arguments) { close(u.waitCh) }) @@ -463,7 +460,11 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_ReceiverHasNoSu err = senderCon.Unicast(&libp2pmessage.TestMessage{ Text: string("hello"), }, u.receiverID.NodeID) - require.NoError(u.T(), err) + if err != nil { + // It can happen that the receiver resets before the sender closes, + // in which case the error will be "stream reset" + require.ErrorContains(u.T(), err, "stream reset", "expected stream-related error when receiver has no subscription") + } // wait for slashing violations consumer mock to invoke run func and close ch if expected method call happens unittest.RequireCloseBefore(u.T(), u.waitCh, u.channelCloseDuration, "could close ch on time") @@ -506,6 +507,89 @@ func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_ReceiverHasSubs unittest.RequireCloseBefore(u.T(), u.waitCh, u.channelCloseDuration, "could close ch on time") } +// setupNetworksWithRoles will setup the sender and receiver networks with the given roles and slashing violations consumer. +func (u *UnicastAuthorizationTestSuite) setupNetworksWithRoles( + senderRole flow.Role, + receiverRole flow.Role, + slashingViolationsConsumer network.ViolationsConsumer, +) { + u.sporkId = unittest.IdentifierFixture() + idProvider := unittest.NewUpdatableIDProvider(flow.IdentityList{}) + + senderNode, senderIdentity := p2ptest.NodeFixture(u.T(), u.sporkId, u.T().Name(), idProvider, + p2ptest.WithRole(senderRole), + p2ptest.WithUnicastHandlerFunc(nil)) + receiverNode, receiverIdentity := p2ptest.NodeFixture(u.T(), u.sporkId, u.T().Name(), idProvider, + p2ptest.WithRole(receiverRole), + p2ptest.WithUnicastHandlerFunc(nil)) + + ids := flow.IdentityList{&senderIdentity, &receiverIdentity} + idProvider.SetIdentities(ids) + + u.codec = newOverridableMessageEncoder(unittest.NetworkCodec()) + nets, providers := testutils.NetworksFixture( + u.T(), + u.sporkId, + ids, + []p2p.LibP2PNode{senderNode, receiverNode}, + underlay.WithCodec(u.codec), + underlay.WithSlashingViolationConsumerFactory(func(_ network.ConduitAdapter) network.ViolationsConsumer { + return slashingViolationsConsumer + }), + underlay.WithUnicastStreamAuthorizer(message.IsAuthorizedUnicastSenderRole)) + require.Len(u.T(), ids, 2) + require.Len(u.T(), providers, 2) + require.Len(u.T(), nets, 2) + + u.senderNetwork = nets[0] + u.receiverNetwork = nets[1] + u.senderID = ids[0] + u.receiverID = ids[1] + u.providers = providers + u.libP2PNodes = []p2p.LibP2PNode{senderNode, receiverNode} +} + +// TestUnicastAuthorization_UnauthorizedSenderRole tests that unicast streams from an unauthorized +// sender role are rejected before reading any message data. An LN sender to an SN receiver is +// not an authorized pair per the unicast role authorization matrix. +func (u *UnicastAuthorizationTestSuite) TestUnicastAuthorization_UnauthorizedSenderRole() { + slashingViolationsConsumer := mocknetwork.NewViolationsConsumer(u.T()) + u.setupNetworksWithRoles(flow.RoleCollection, flow.RoleConsensus, slashingViolationsConsumer) + + expectedSenderPeerID, err := unittest.PeerIDFromFlowID(u.senderID) + require.NoError(u.T(), err) + + expectedViolation := &network.Violation{ + Identity: u.senderID, + PeerID: p2plogging.PeerId(expectedSenderPeerID), + Protocol: message.ProtocolTypeUnicast, + Err: underlay.ErrUnauthorizedUnicastSender, + } + + slashingViolationsConsumer.On("OnUnauthorizedUnicastOnChannel", expectedViolation). + Return(nil).Once().Run(func(args mockery.Arguments) { + close(u.waitCh) + }) + + u.startNetworksAndLibp2pNodes() + + // both sides register on the test channel so the sender can create a conduit + _, err = u.receiverNetwork.Register(channels.TestNetworkChannel, &mocknetwork.MessageProcessor{}) + require.NoError(u.T(), err) + + senderCon, err := u.senderNetwork.Register(channels.TestNetworkChannel, &mocknetwork.MessageProcessor{}) + require.NoError(u.T(), err) + + // send message via unicast from LN to SN — should be rejected at stream pre-authorization + err = senderCon.Unicast(&libp2pmessage.TestMessage{ + Text: "hello", + }, u.receiverID.NodeID) + require.NoError(u.T(), err) + + // wait for slashing violations consumer to be invoked + unittest.RequireCloseBefore(u.T(), u.waitCh, u.channelCloseDuration, "could close ch on time") +} + // overridableMessageEncoder is a codec that allows to override the encoder for a specific type only for sake of testing. // We specifically use this to override the encoder for the TestMessage type to encode it with an invalid message code. type overridableMessageEncoder struct { diff --git a/network/underlay/network.go b/network/underlay/network.go index ba4bfd82331..785855d7489 100644 --- a/network/underlay/network.go +++ b/network/underlay/network.go @@ -72,6 +72,10 @@ var ( // the network receives a message via unicast but does not have a corresponding subscription for // the channel in that message. ErrUnicastMsgWithoutSub = errors.New("networking layer does not have subscription for the channel ID indicated in the unicast message received") + + // ErrUnauthorizedUnicastSender is reported via the slashing violations consumer when a peer + // opens a unicast stream but its role is not authorized to send unicast messages to this node's role. + ErrUnauthorizedUnicastSender = errors.New("sender role not authorized to send unicast messages to receiver role") ) // Network serves as the comprehensive networking layer that integrates three interfaces within Flow; Underlay, EngineRegistry, and ConduitAdapter. @@ -113,6 +117,8 @@ type Network struct { validators []network.MessageValidator authorizedSenderValidator *validator.AuthorizedSenderValidator preferredUnicasts []protocols.ProtocolName + unicastStreamAuthorizer func(sender, receiver flow.Role) bool + messageQueueSize int } var _ network.EngineRegistry = &Network{} @@ -162,6 +168,13 @@ type NetworkConfig struct { Libp2pNode p2p.LibP2PNode BitSwapMetrics module.BitswapMetrics SlashingViolationConsumerFactory func(network.ConduitAdapter) network.ViolationsConsumer + // UnicastStreamAuthorizer determines whether a sender role is permitted to open a unicast + // stream to a receiver role, before any message data is read from the stream. If nil, + // defaults to message.IsAuthorizedUnicastSenderRole. + UnicastStreamAuthorizer func(sender, receiver flow.Role) bool + // MessageQueueSize is the maximum number of messages that can be buffered in the inbound message queue. + // If set to 0, queue.DefaultMaxSize will be used. + MessageQueueSize int } // Validate validates the configuration, and sets default values for any missing fields. @@ -169,6 +182,9 @@ func (cfg *NetworkConfig) Validate() { if cfg.UnicastMessageTimeout <= 0 { cfg.UnicastMessageTimeout = DefaultUnicastTimeout } + if cfg.UnicastStreamAuthorizer == nil { + cfg.UnicastStreamAuthorizer = message.IsAuthorizedUnicastSenderRole + } } // NetworkConfigOption is a function that can be used to override network config parmeters. @@ -200,6 +216,16 @@ func WithSlashingViolationConsumerFactory(factory func(adapter network.ConduitAd } } +// WithUnicastStreamAuthorizer overrides the default unicast stream authorizer function. +// The authorizer determines whether a sender role is permitted to open a unicast stream +// to a receiver role, before any message data is read from the stream. +// Defaults to [message.IsAuthorizedUnicastSenderRole] when nil. +func WithUnicastStreamAuthorizer(authorizer func(sender, receiver flow.Role) bool) NetworkConfigOption { + return func(params *NetworkConfig) { + params.UnicastStreamAuthorizer = authorizer + } +} + // NetworkOption is a function that can be used to override network attributes. // It is mostly used for testing purposes. // Note: do not override network attributes in production unless you know what you are doing. @@ -282,6 +308,8 @@ func NewNetwork(param *NetworkConfig, opts ...NetworkOption) (*Network, error) { libP2PNode: param.Libp2pNode, unicastRateLimiters: ratelimit.NoopRateLimiters(), validators: DefaultValidators(param.Logger.With().Str("component", "network-validators").Logger(), param.Me.NodeID()), + unicastStreamAuthorizer: param.UnicastStreamAuthorizer, + messageQueueSize: param.MessageQueueSize, } n.subscriptionManager = subscription.NewChannelSubscriptionManager(n) @@ -432,7 +460,7 @@ func (n *Network) processRegisterBlobServiceRequests(parent irrecoverable.Signal // createInboundMessageQueue creates the queue that will be used to process incoming messages. func (n *Network) createInboundMessageQueue(ctx irrecoverable.SignalerContext, ready component.ReadyFunc) { - n.queue = queue.NewMessageQueue(ctx, queue.GetEventPriority, n.metrics) + n.queue = queue.NewMessageQueue(ctx, queue.GetEventPriority, n.metrics, n.messageQueueSize) queue.CreateQueueWorkers(ctx, queue.DefaultNumWorkers, n.queue, n.queueSubmitFunc) ready() @@ -596,7 +624,7 @@ func (n *Network) processNetworkMessage(msg network.IncomingMessageScope) error // UnicastOnChannel sends the message in a reliable way to the given recipient. // It uses 1-1 direct messaging over the underlying network to deliver the message. // It returns an error if unicasting fails. -func (n *Network) UnicastOnChannel(channel channels.Channel, payload interface{}, targetID flow.Identifier) error { +func (n *Network) UnicastOnChannel(channel channels.Channel, payload any, targetID flow.Identifier) error { if targetID == n.me.NodeID() { n.logger.Debug().Msg("network skips self unicasting") return nil @@ -672,7 +700,7 @@ func (n *Network) UnicastOnChannel(channel channels.Channel, payload interface{} // In this context, unreliable means that the message is published over a libp2p pub-sub // channel and can be read by any node subscribed to that channel. // The selector could be used to optimize or restrict delivery. -func (n *Network) PublishOnChannel(channel channels.Channel, message interface{}, targetIDs ...flow.Identifier) error { +func (n *Network) PublishOnChannel(channel channels.Channel, message any, targetIDs ...flow.Identifier) error { filteredIDs := flow.IdentifierList(targetIDs).Filter(n.removeSelfFilter()) if len(filteredIDs) == 0 { @@ -690,7 +718,7 @@ func (n *Network) PublishOnChannel(channel channels.Channel, message interface{} // MulticastOnChannel unreliably sends the specified event over the channel to randomly selected 'num' number of recipients // selected from the specified targetIDs. -func (n *Network) MulticastOnChannel(channel channels.Channel, message interface{}, num uint, targetIDs ...flow.Identifier) error { +func (n *Network) MulticastOnChannel(channel channels.Channel, message any, num uint, targetIDs ...flow.Identifier) error { selectedIDs, err := flow.IdentifierList(targetIDs).Filter(n.removeSelfFilter()).Sample(num) if err != nil { return fmt.Errorf("sampling failed: %w", err) @@ -718,7 +746,7 @@ func (n *Network) removeSelfFilter() flow.IdentifierFilter { } // sendOnChannel sends the message on channel to targets. -func (n *Network) sendOnChannel(channel channels.Channel, msg interface{}, targetIDs []flow.Identifier) error { +func (n *Network) sendOnChannel(channel channels.Channel, msg any, targetIDs []flow.Identifier) error { n.logger.Debug(). Interface("message", msg). Str("channel", channel.String()). @@ -750,7 +778,7 @@ func (n *Network) sendOnChannel(channel channels.Channel, msg interface{}, targe // queueSubmitFunc submits the message to the engine synchronously. It is the callback for the queue worker // when it gets a message from the queue -func (n *Network) queueSubmitFunc(message interface{}) { +func (n *Network) queueSubmitFunc(message any) { qm := message.(queue.QMessage) logger := n.logger.With(). @@ -806,12 +834,16 @@ func DefaultValidators(log zerolog.Logger, flowID flow.Identifier) []network.Mes } } -// isProtocolParticipant returns a PeerFilter that returns true if a peer is a staked (i.e., authorized) node. +// isProtocolParticipant returns a PeerFilter that allows if a peer is a staked (i.e., authorized) node. func (n *Network) isProtocolParticipant() p2p.PeerFilter { return func(p peer.ID) error { - if _, ok := n.Identity(p); !ok { + id, ok := n.Identity(p) + if !ok { return fmt.Errorf("failed to get identity of unknown peer with peer id %s", p2plogging.PeerId(p)) } + if id.IsEjected() { + return fmt.Errorf("peer with peer id %s is ejected", p2plogging.PeerId(p)) + } return nil } } @@ -949,12 +981,47 @@ func (n *Network) handleIncomingStream(s libp2pnet.Stream) { return } - // TODO: We need to allow per-topic timeouts and message size limits. - // This allows us to configure higher limits for topics on which we expect - // to receive large messages (e.g. Chunk Data Packs), and use the normal - // limits for other topics. In order to enable this, we will need to register - // a separate stream handler for each topic. - ctx, cancel := context.WithTimeout(n.ctx, LargeMsgUnicastTimeout) + // Resolve remote peer identity to determine the max message size and timeout for this stream. + // + // Only chunk data packs require the larger message size limit. Currently, the message + // type cannot be determined until the message is fully received and parsed from the + // payload, so we use the sender and receiver roles as a proxy. Since chunk data packs + // are only sent by execution nodes to verification nodes, and since execution nodes + // are permissioned and will be for the foreseeable future, we allow the higher limit + // for all unicast streams from execution nodes to verification nodes. All other node + // combinations use the default (lower) limit. + remoteIdentity, ok := n.getAuthorizedIdentity(log, remotePeer) + if !ok { + return + } + + // Before reading anything from the stream, check if the sender's role is allowed to send unicast + // messages to the receiver's role. This avoids spending resources processing messages that will + // fail validation later. + if !n.unicastStreamAuthorizer(remoteIdentity.Role, n.me.Role()) { + log.Warn(). + Str("remote_peer", remotePeer.String()). + Str("remote_role", remoteIdentity.Role.String()). + Str("local_role", n.me.Role().String()). + Bool(logging.KeySuspicious, true). + Msg("rejecting unicast stream from unauthorized sender role") + n.slashingViolationsConsumer.OnUnauthorizedUnicastOnChannel(&network.Violation{ + Identity: remoteIdentity, + PeerID: p2plogging.PeerId(remotePeer), + Protocol: message.ProtocolTypeUnicast, + Err: ErrUnauthorizedUnicastSender, + }) + return + } + + maxMsgSize := DefaultMaxUnicastMsgSize + unicastTimeout := DefaultUnicastTimeout + if n.me.Role() == flow.RoleVerification && remoteIdentity.Role == flow.RoleExecution { + maxMsgSize = LargeMsgMaxUnicastMsgSize + unicastTimeout = LargeMsgUnicastTimeout + } + + ctx, cancel := context.WithTimeout(n.ctx, unicastTimeout) defer cancel() deadline, _ := ctx.Deadline() @@ -966,7 +1033,7 @@ func (n *Network) handleIncomingStream(s libp2pnet.Stream) { } // create the reader - r := ggio.NewDelimitedReader(s, LargeMsgMaxUnicastMsgSize) + r := ggio.NewDelimitedReader(s, maxMsgSize) for { if ctx.Err() != nil { return @@ -1038,16 +1105,47 @@ func (n *Network) handleIncomingStream(s libp2pnet.Stream) { return } - n.wg.Add(1) - go func() { - defer n.wg.Done() + n.wg.Go(func() { n.processUnicastStreamMessage(remotePeer, &msg) - }() + }) } success = true } +// getAuthorizedIdentity resolves the identity of a remote peer and returns it if it is authorized. +// If the peer is not authorized (unknown or ejected), it returns false and logs a violation. +func (n *Network) getAuthorizedIdentity(log zerolog.Logger, remotePeer peer.ID) (*flow.Identity, bool) { + remoteIdentity, ok := n.Identity(remotePeer) + if !ok { + log.Error(). + Str("remote_peer", remotePeer.String()). + Bool(logging.KeySuspicious, true). + Msg("failed to resolve identity of remote peer") + n.slashingViolationsConsumer.OnUnauthorizedSenderError(&network.Violation{ + PeerID: p2plogging.PeerId(remotePeer), + Protocol: message.ProtocolTypeUnicast, + Err: validator.ErrIdentityUnverified, + }) + return nil, false + } + if remoteIdentity.IsEjected() { + log.Error(). + Str("remote_peer", remotePeer.String()). + Bool(logging.KeySuspicious, true). + Msg("remote peer is ejected") + n.slashingViolationsConsumer.OnSenderEjectedError(&network.Violation{ + OriginID: remoteIdentity.NodeID, + Identity: remoteIdentity, + PeerID: p2plogging.PeerId(remotePeer), + Protocol: message.ProtocolTypeUnicast, + Err: validator.ErrSenderEjected, + }) + return nil, false + } + return remoteIdentity, true +} + // Subscribe subscribes the network to a channel. // No errors are expected during normal operation. func (n *Network) Subscribe(channel channels.Channel) error { @@ -1076,13 +1174,11 @@ func (n *Network) Subscribe(channel channels.Channel) error { // create a new readSubscription with the context of the network rs := internal.NewReadSubscription(s, n.processPubSubMessages, n.logger) - n.wg.Add(1) // kick off the receive loop to continuously receive messages - go func() { - defer n.wg.Done() + n.wg.Go(func() { rs.ReceiveLoop(n.ctx) - }() + }) // update peers to add some nodes interested in the same topic as direct peers n.libP2PNode.RequestPeerUpdate() @@ -1237,6 +1333,11 @@ func (n *Network) processMessage(scope network.IncomingMessageScope) { // if validation passed, send the message to the overlay err := n.Receive(scope) if err != nil { + if errors.Is(err, queue.ErrQueueFull) { + // queue full is expected during message floods + logger.Warn().Msg("message dropped: queue full") + return + } n.logger.Error().Err(err).Msg("could not deliver payload") } } diff --git a/network/underlay/network_test.go b/network/underlay/network_test.go new file mode 100644 index 00000000000..c4a80fa39d3 --- /dev/null +++ b/network/underlay/network_test.go @@ -0,0 +1,147 @@ +package underlay + +import ( + "testing" + + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/flow" + modulemock "github.com/onflow/flow-go/module/mock" + "github.com/onflow/flow-go/network" + "github.com/onflow/flow-go/network/message" + mockmsg "github.com/onflow/flow-go/network/mock" + p2plogging "github.com/onflow/flow-go/network/p2p/logging" + "github.com/onflow/flow-go/network/validator" + "github.com/onflow/flow-go/utils/unittest" +) + +func TestIsProtocolParticipant_UnknownPeer(t *testing.T) { + idProvider := modulemock.NewIdentityProvider(t) + remotePeerID := unittest.PeerIdFixture(t) + + idProvider.On("ByPeerID", remotePeerID).Return(nil, false).Once() + + net := &Network{ + identityProvider: idProvider, + } + + filter := net.isProtocolParticipant() + err := filter(remotePeerID) + require.Error(t, err) + assert.Contains(t, err.Error(), "unknown") +} + +func TestIsProtocolParticipant_EjectedPeer(t *testing.T) { + idProvider := modulemock.NewIdentityProvider(t) + remotePeerID := unittest.PeerIdFixture(t) + + ejectedIdentity := unittest.IdentityFixture( + unittest.WithRole(flow.RoleExecution), + unittest.WithParticipationStatus(flow.EpochParticipationStatusEjected), + ) + idProvider.On("ByPeerID", remotePeerID).Return(ejectedIdentity, true).Once() + + net := &Network{ + identityProvider: idProvider, + } + + filter := net.isProtocolParticipant() + err := filter(remotePeerID) + require.Error(t, err) + assert.Contains(t, err.Error(), "ejected") +} + +func TestIsProtocolParticipant_ActivePeer(t *testing.T) { + idProvider := modulemock.NewIdentityProvider(t) + remotePeerID := unittest.PeerIdFixture(t) + + activeIdentity := unittest.IdentityFixture( + unittest.WithRole(flow.RoleConsensus), + unittest.WithParticipationStatus(flow.EpochParticipationStatusActive), + ) + idProvider.On("ByPeerID", remotePeerID).Return(activeIdentity, true).Once() + + net := &Network{ + identityProvider: idProvider, + } + + filter := net.isProtocolParticipant() + err := filter(remotePeerID) + require.NoError(t, err) +} + +func TestGetAuthorizedIdentity_UnknownPeer(t *testing.T) { + idProvider := modulemock.NewIdentityProvider(t) + violationsConsumer := mockmsg.NewViolationsConsumer(t) + remotePeerID := unittest.PeerIdFixture(t) + + idProvider.On("ByPeerID", remotePeerID).Return(nil, false).Once() + violationsConsumer.On("OnUnauthorizedSenderError", &network.Violation{ + PeerID: p2plogging.PeerId(remotePeerID), + Protocol: message.ProtocolTypeUnicast, + Err: validator.ErrIdentityUnverified, + }).Once() + + net := &Network{ + identityProvider: idProvider, + slashingViolationsConsumer: violationsConsumer, + } + + log := zerolog.Nop() + identity, ok := net.getAuthorizedIdentity(log, remotePeerID) + require.False(t, ok) + require.Nil(t, identity) +} + +func TestGetAuthorizedIdentity_EjectedPeer(t *testing.T) { + idProvider := modulemock.NewIdentityProvider(t) + violationsConsumer := mockmsg.NewViolationsConsumer(t) + remotePeerID := unittest.PeerIdFixture(t) + + ejectedIdentity := unittest.IdentityFixture( + unittest.WithRole(flow.RoleExecution), + unittest.WithParticipationStatus(flow.EpochParticipationStatusEjected), + ) + idProvider.On("ByPeerID", remotePeerID).Return(ejectedIdentity, true).Once() + violationsConsumer.On("OnSenderEjectedError", &network.Violation{ + OriginID: ejectedIdentity.NodeID, + Identity: ejectedIdentity, + PeerID: p2plogging.PeerId(remotePeerID), + Protocol: message.ProtocolTypeUnicast, + Err: validator.ErrSenderEjected, + }).Once() + + net := &Network{ + identityProvider: idProvider, + slashingViolationsConsumer: violationsConsumer, + } + + log := zerolog.Nop() + identity, ok := net.getAuthorizedIdentity(log, remotePeerID) + require.False(t, ok) + require.Nil(t, identity) +} + +func TestGetAuthorizedIdentity_ActivePeer(t *testing.T) { + idProvider := modulemock.NewIdentityProvider(t) + violationsConsumer := mockmsg.NewViolationsConsumer(t) + remotePeerID := unittest.PeerIdFixture(t) + + activeIdentity := unittest.IdentityFixture( + unittest.WithRole(flow.RoleConsensus), + unittest.WithParticipationStatus(flow.EpochParticipationStatusActive), + ) + idProvider.On("ByPeerID", remotePeerID).Return(activeIdentity, true).Once() + + net := &Network{ + identityProvider: idProvider, + slashingViolationsConsumer: violationsConsumer, + } + + log := zerolog.Nop() + identity, ok := net.getAuthorizedIdentity(log, remotePeerID) + require.True(t, ok) + require.Equal(t, activeIdentity, identity) +} diff --git a/network/underlay/noop.go b/network/underlay/noop.go index 8273ded7026..f8ed89e29ab 100644 --- a/network/underlay/noop.go +++ b/network/underlay/noop.go @@ -16,15 +16,15 @@ var _ network.Conduit = (*NoopConduit)(nil) func (n *NoopConduit) ReportMisbehavior(network.MisbehaviorReport) {} -func (n *NoopConduit) Publish(event interface{}, targetIDs ...flow.Identifier) error { +func (n *NoopConduit) Publish(event any, targetIDs ...flow.Identifier) error { return nil } -func (n *NoopConduit) Unicast(event interface{}, targetID flow.Identifier) error { +func (n *NoopConduit) Unicast(event any, targetID flow.Identifier) error { return nil } -func (n *NoopConduit) Multicast(event interface{}, num uint, targetIDs ...flow.Identifier) error { +func (n *NoopConduit) Multicast(event any, num uint, targetIDs ...flow.Identifier) error { return nil } diff --git a/network/validator/authorized_sender_validator.go b/network/validator/authorized_sender_validator.go index d4300e06e03..e640b76b367 100644 --- a/network/validator/authorized_sender_validator.go +++ b/network/validator/authorized_sender_validator.go @@ -63,7 +63,7 @@ func (av *AuthorizedSenderValidator) Validate(from peer.ID, payload []byte, chan identity, ok := av.getIdentity(from) if !ok { violation := &network.Violation{PeerID: p2plogging.PeerId(from), Channel: channel, Protocol: protocol, Err: ErrIdentityUnverified} - av.slashingViolationsConsumer.OnUnAuthorizedSenderError(violation) + av.slashingViolationsConsumer.OnUnauthorizedSenderError(violation) return "", ErrIdentityUnverified } @@ -84,7 +84,7 @@ func (av *AuthorizedSenderValidator) Validate(from peer.ID, payload []byte, chan return msgType, err case errors.Is(err, message.ErrUnauthorizedMessageOnChannel) || errors.Is(err, message.ErrUnauthorizedRole): violation := &network.Violation{OriginID: identity.NodeID, Identity: identity, PeerID: p2plogging.PeerId(from), MsgType: msgType, Channel: channel, Protocol: protocol, Err: err} - av.slashingViolationsConsumer.OnUnAuthorizedSenderError(violation) + av.slashingViolationsConsumer.OnUnauthorizedSenderError(violation) return msgType, err case errors.Is(err, ErrSenderEjected): violation := &network.Violation{OriginID: identity.NodeID, Identity: identity, PeerID: p2plogging.PeerId(from), MsgType: msgType, Channel: channel, Protocol: protocol, Err: err} diff --git a/network/violations_consumer.go b/network/violations_consumer.go index 6c3de412c77..a5810ad552e 100644 --- a/network/violations_consumer.go +++ b/network/violations_consumer.go @@ -10,8 +10,8 @@ import ( // misbehavior report manager. Any errors encountered while reporting the misbehavior are considered irrecoverable and // will result in a fatal level log. type ViolationsConsumer interface { - // OnUnAuthorizedSenderError logs an error for unauthorized sender error. - OnUnAuthorizedSenderError(violation *Violation) + // OnUnauthorizedSenderError logs an error for unauthorized sender error. + OnUnauthorizedSenderError(violation *Violation) // OnUnknownMsgTypeError logs an error for unknown message type error. OnUnknownMsgTypeError(violation *Violation) diff --git a/revive.toml b/revive.toml deleted file mode 100644 index 923706943d5..00000000000 --- a/revive.toml +++ /dev/null @@ -1,30 +0,0 @@ -ignoreGeneratedHeader = false -severity = "error" -confidence = 0.8 -errorCode = 1 -warningCode = 0 - -[rule.blank-imports] -[rule.context-as-argument] -[rule.context-keys-type] -[rule.dot-imports] -[rule.error-return] -[rule.error-strings] -[rule.error-naming] -[rule.if-return] -[rule.var-naming] -[rule.var-declaration] -[rule.package-comments] -[rule.range] -[rule.receiver-naming] -[rule.time-naming] -[rule.unexported-return] -[rule.indent-error-flow] -[rule.errorf] -[rule.empty-block] -[rule.superfluous-else] -[rule.unreachable-code] -[rule.redefines-builtin-id] - -# This will be activated at a later date. -# [rule.unused-parameter] diff --git a/scripts/find-unused-mocks.sh b/scripts/find-unused-mocks.sh new file mode 100755 index 00000000000..be73ccfeca7 --- /dev/null +++ b/scripts/find-unused-mocks.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Parse flags +VERBOSE=false +while getopts "v" opt; do + case $opt in + v) VERBOSE=true ;; + *) echo "Usage: $0 [-v] [root_dir]" >&2; exit 1 ;; + esac +done +shift $((OPTIND - 1)) + +# Root of the repo to search +ROOT="${1:-.}" + +# Go module import prefix +MODULE_PREFIX="github.com/onflow/flow-go" + +# Mockery header we are looking for +MOCKERY_HEADER='^// Code generated by mockery; DO NOT EDIT\.' + +# Temporary storage for package paths +packages=() + +# Step 1: Find all mockery-generated files +while IFS= read -r -d '' file; do + # Remove leading ./ if present + relative_path="${file#./}" + + # Get directory containing the file + package_dir="${relative_path%/*}" + + # Build full Go import path + package_path="${MODULE_PREFIX}/${package_dir}" + + packages+=("$package_path") +done < <( + grep -rlZ "$MOCKERY_HEADER" "$ROOT" +) + +# Step 2: Deduplicate packages +IFS=$'\n' read -r -d '' -a unique_packages < <(printf '%s\n' "${packages[@]}" | sort -u && printf '\0') || true + +# 3) Find unused (not referenced in *.go files) +unused_packages=() +used_packages=() +for pkg in "${unique_packages[@]}"; do + if ! grep -R --include="*.go" -Fq -- "$pkg" "$ROOT"; then + unused_packages+=("$pkg") + else + used_packages+=("$pkg") + fi +done + +# 4) Output used packages if verbose +if $VERBOSE && ((${#used_packages[@]} > 0)); then + printf 'Used mock packages:\n' + printf ' %s\n' "${used_packages[@]}" +fi + +# 5) Output unused packages, then fail if any exist +if ((${#unused_packages[@]} > 0)); then + printf 'Generated mock packages are unused. Please exclude them from `.mockery.yaml` and remove them: %s\n' "${unused_packages[@]}" + exit 1 +fi + +exit 0 diff --git a/state/cluster/invalid/snapshot.go b/state/cluster/invalid/snapshot.go index 02ccb6503ae..4affa2b5fcf 100644 --- a/state/cluster/invalid/snapshot.go +++ b/state/cluster/invalid/snapshot.go @@ -30,7 +30,7 @@ func NewSnapshot(err error) *Snapshot { var _ cluster.Snapshot = (*Snapshot)(nil) // NewSnapshotf is NewSnapshot with ergonomic error formatting. -func NewSnapshotf(msg string, args ...interface{}) *Snapshot { +func NewSnapshotf(msg string, args ...any) *Snapshot { return NewSnapshot(fmt.Errorf(msg, args...)) } diff --git a/state/cluster/mock/mutable_state.go b/state/cluster/mock/mutable_state.go index e0994a444b5..b92cd5f6ea8 100644 --- a/state/cluster/mock/mutable_state.go +++ b/state/cluster/mock/mutable_state.go @@ -1,109 +1,235 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - cluster "github.com/onflow/flow-go/state/cluster" - + cluster0 "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/cluster" mock "github.com/stretchr/testify/mock" - - modelcluster "github.com/onflow/flow-go/model/cluster" ) +// NewMutableState creates a new instance of MutableState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMutableState(t interface { + mock.TestingT + Cleanup(func()) +}) *MutableState { + mock := &MutableState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MutableState is an autogenerated mock type for the MutableState type type MutableState struct { mock.Mock } -// AtBlockID provides a mock function with given fields: blockID -func (_m *MutableState) AtBlockID(blockID flow.Identifier) cluster.Snapshot { - ret := _m.Called(blockID) +type MutableState_Expecter struct { + mock *mock.Mock +} + +func (_m *MutableState) EXPECT() *MutableState_Expecter { + return &MutableState_Expecter{mock: &_m.Mock} +} + +// AtBlockID provides a mock function for the type MutableState +func (_mock *MutableState) AtBlockID(blockID flow.Identifier) cluster.Snapshot { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for AtBlockID") } var r0 cluster.Snapshot - if rf, ok := ret.Get(0).(func(flow.Identifier) cluster.Snapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) cluster.Snapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cluster.Snapshot) } } - return r0 } -// Extend provides a mock function with given fields: proposal -func (_m *MutableState) Extend(proposal *modelcluster.Proposal) error { - ret := _m.Called(proposal) +// MutableState_AtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtBlockID' +type MutableState_AtBlockID_Call struct { + *mock.Call +} + +// AtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *MutableState_Expecter) AtBlockID(blockID interface{}) *MutableState_AtBlockID_Call { + return &MutableState_AtBlockID_Call{Call: _e.mock.On("AtBlockID", blockID)} +} + +func (_c *MutableState_AtBlockID_Call) Run(run func(blockID flow.Identifier)) *MutableState_AtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MutableState_AtBlockID_Call) Return(snapshot cluster.Snapshot) *MutableState_AtBlockID_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *MutableState_AtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) cluster.Snapshot) *MutableState_AtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Extend provides a mock function for the type MutableState +func (_mock *MutableState) Extend(proposal *cluster0.Proposal) error { + ret := _mock.Called(proposal) if len(ret) == 0 { panic("no return value specified for Extend") } var r0 error - if rf, ok := ret.Get(0).(func(*modelcluster.Proposal) error); ok { - r0 = rf(proposal) + if returnFunc, ok := ret.Get(0).(func(*cluster0.Proposal) error); ok { + r0 = returnFunc(proposal) } else { r0 = ret.Error(0) } - return r0 } -// Final provides a mock function with no fields -func (_m *MutableState) Final() cluster.Snapshot { - ret := _m.Called() +// MutableState_Extend_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Extend' +type MutableState_Extend_Call struct { + *mock.Call +} + +// Extend is a helper method to define mock.On call +// - proposal *cluster0.Proposal +func (_e *MutableState_Expecter) Extend(proposal interface{}) *MutableState_Extend_Call { + return &MutableState_Extend_Call{Call: _e.mock.On("Extend", proposal)} +} + +func (_c *MutableState_Extend_Call) Run(run func(proposal *cluster0.Proposal)) *MutableState_Extend_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *cluster0.Proposal + if args[0] != nil { + arg0 = args[0].(*cluster0.Proposal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MutableState_Extend_Call) Return(err error) *MutableState_Extend_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MutableState_Extend_Call) RunAndReturn(run func(proposal *cluster0.Proposal) error) *MutableState_Extend_Call { + _c.Call.Return(run) + return _c +} + +// Final provides a mock function for the type MutableState +func (_mock *MutableState) Final() cluster.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Final") } var r0 cluster.Snapshot - if rf, ok := ret.Get(0).(func() cluster.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() cluster.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cluster.Snapshot) } } - return r0 } -// Params provides a mock function with no fields -func (_m *MutableState) Params() cluster.Params { - ret := _m.Called() +// MutableState_Final_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Final' +type MutableState_Final_Call struct { + *mock.Call +} + +// Final is a helper method to define mock.On call +func (_e *MutableState_Expecter) Final() *MutableState_Final_Call { + return &MutableState_Final_Call{Call: _e.mock.On("Final")} +} + +func (_c *MutableState_Final_Call) Run(run func()) *MutableState_Final_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableState_Final_Call) Return(snapshot cluster.Snapshot) *MutableState_Final_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *MutableState_Final_Call) RunAndReturn(run func() cluster.Snapshot) *MutableState_Final_Call { + _c.Call.Return(run) + return _c +} + +// Params provides a mock function for the type MutableState +func (_mock *MutableState) Params() cluster.Params { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Params") } var r0 cluster.Params - if rf, ok := ret.Get(0).(func() cluster.Params); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() cluster.Params); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cluster.Params) } } - return r0 } -// NewMutableState creates a new instance of MutableState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMutableState(t interface { - mock.TestingT - Cleanup(func()) -}) *MutableState { - mock := &MutableState{} - mock.Mock.Test(t) +// MutableState_Params_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Params' +type MutableState_Params_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Params is a helper method to define mock.On call +func (_e *MutableState_Expecter) Params() *MutableState_Params_Call { + return &MutableState_Params_Call{Call: _e.mock.On("Params")} +} - return mock +func (_c *MutableState_Params_Call) Run(run func()) *MutableState_Params_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableState_Params_Call) Return(params cluster.Params) *MutableState_Params_Call { + _c.Call.Return(params) + return _c +} + +func (_c *MutableState_Params_Call) RunAndReturn(run func() cluster.Params) *MutableState_Params_Call { + _c.Call.Return(run) + return _c } diff --git a/state/cluster/mock/params.go b/state/cluster/mock/params.go index 94be4347973..a264df184ba 100644 --- a/state/cluster/mock/params.go +++ b/state/cluster/mock/params.go @@ -1,45 +1,81 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewParams creates a new instance of Params. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewParams(t interface { + mock.TestingT + Cleanup(func()) +}) *Params { + mock := &Params{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Params is an autogenerated mock type for the Params type type Params struct { mock.Mock } -// ChainID provides a mock function with no fields -func (_m *Params) ChainID() flow.ChainID { - ret := _m.Called() +type Params_Expecter struct { + mock *mock.Mock +} + +func (_m *Params) EXPECT() *Params_Expecter { + return &Params_Expecter{mock: &_m.Mock} +} + +// ChainID provides a mock function for the type Params +func (_mock *Params) ChainID() flow.ChainID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ChainID") } var r0 flow.ChainID - if rf, ok := ret.Get(0).(func() flow.ChainID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ChainID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(flow.ChainID) } - return r0 } -// NewParams creates a new instance of Params. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewParams(t interface { - mock.TestingT - Cleanup(func()) -}) *Params { - mock := &Params{} - mock.Mock.Test(t) +// Params_ChainID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChainID' +type Params_ChainID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ChainID is a helper method to define mock.On call +func (_e *Params_Expecter) ChainID() *Params_ChainID_Call { + return &Params_ChainID_Call{Call: _e.mock.On("ChainID")} +} - return mock +func (_c *Params_ChainID_Call) Run(run func()) *Params_ChainID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_ChainID_Call) Return(chainID flow.ChainID) *Params_ChainID_Call { + _c.Call.Return(chainID) + return _c +} + +func (_c *Params_ChainID_Call) RunAndReturn(run func() flow.ChainID) *Params_ChainID_Call { + _c.Call.Return(run) + return _c } diff --git a/state/cluster/mock/snapshot.go b/state/cluster/mock/snapshot.go index 08938de8e26..086b2939535 100644 --- a/state/cluster/mock/snapshot.go +++ b/state/cluster/mock/snapshot.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSnapshot creates a new instance of Snapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSnapshot(t interface { + mock.TestingT + Cleanup(func()) +}) *Snapshot { + mock := &Snapshot{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Snapshot is an autogenerated mock type for the Snapshot type type Snapshot struct { mock.Mock } -// Collection provides a mock function with no fields -func (_m *Snapshot) Collection() (*flow.Collection, error) { - ret := _m.Called() +type Snapshot_Expecter struct { + mock *mock.Mock +} + +func (_m *Snapshot) EXPECT() *Snapshot_Expecter { + return &Snapshot_Expecter{mock: &_m.Mock} +} + +// Collection provides a mock function for the type Snapshot +func (_mock *Snapshot) Collection() (*flow.Collection, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Collection") @@ -22,29 +46,54 @@ func (_m *Snapshot) Collection() (*flow.Collection, error) { var r0 *flow.Collection var r1 error - if rf, ok := ret.Get(0).(func() (*flow.Collection, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.Collection, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.Collection); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Collection); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Collection) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Head provides a mock function with no fields -func (_m *Snapshot) Head() (*flow.Header, error) { - ret := _m.Called() +// Snapshot_Collection_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Collection' +type Snapshot_Collection_Call struct { + *mock.Call +} + +// Collection is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Collection() *Snapshot_Collection_Call { + return &Snapshot_Collection_Call{Call: _e.mock.On("Collection")} +} + +func (_c *Snapshot_Collection_Call) Run(run func()) *Snapshot_Collection_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Collection_Call) Return(collection *flow.Collection, err error) *Snapshot_Collection_Call { + _c.Call.Return(collection, err) + return _c +} + +func (_c *Snapshot_Collection_Call) RunAndReturn(run func() (*flow.Collection, error)) *Snapshot_Collection_Call { + _c.Call.Return(run) + return _c +} + +// Head provides a mock function for the type Snapshot +func (_mock *Snapshot) Head() (*flow.Header, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Head") @@ -52,29 +101,54 @@ func (_m *Snapshot) Head() (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func() (*flow.Header, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.Header, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Pending provides a mock function with no fields -func (_m *Snapshot) Pending() ([]flow.Identifier, error) { - ret := _m.Called() +// Snapshot_Head_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Head' +type Snapshot_Head_Call struct { + *mock.Call +} + +// Head is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Head() *Snapshot_Head_Call { + return &Snapshot_Head_Call{Call: _e.mock.On("Head")} +} + +func (_c *Snapshot_Head_Call) Run(run func()) *Snapshot_Head_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Head_Call) Return(header *flow.Header, err error) *Snapshot_Head_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Snapshot_Head_Call) RunAndReturn(run func() (*flow.Header, error)) *Snapshot_Head_Call { + _c.Call.Return(run) + return _c +} + +// Pending provides a mock function for the type Snapshot +func (_mock *Snapshot) Pending() ([]flow.Identifier, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Pending") @@ -82,36 +156,47 @@ func (_m *Snapshot) Pending() ([]flow.Identifier, error) { var r0 []flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func() ([]flow.Identifier, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]flow.Identifier, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Identifier) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSnapshot creates a new instance of Snapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSnapshot(t interface { - mock.TestingT - Cleanup(func()) -}) *Snapshot { - mock := &Snapshot{} - mock.Mock.Test(t) +// Snapshot_Pending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Pending' +type Snapshot_Pending_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Pending is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Pending() *Snapshot_Pending_Call { + return &Snapshot_Pending_Call{Call: _e.mock.On("Pending")} +} - return mock +func (_c *Snapshot_Pending_Call) Run(run func()) *Snapshot_Pending_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Pending_Call) Return(identifiers []flow.Identifier, err error) *Snapshot_Pending_Call { + _c.Call.Return(identifiers, err) + return _c +} + +func (_c *Snapshot_Pending_Call) RunAndReturn(run func() ([]flow.Identifier, error)) *Snapshot_Pending_Call { + _c.Call.Return(run) + return _c } diff --git a/state/cluster/mock/state.go b/state/cluster/mock/state.go index 3f0a103d16c..adae47a11d4 100644 --- a/state/cluster/mock/state.go +++ b/state/cluster/mock/state.go @@ -1,89 +1,183 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - cluster "github.com/onflow/flow-go/state/cluster" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/cluster" mock "github.com/stretchr/testify/mock" ) +// NewState creates a new instance of State. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewState(t interface { + mock.TestingT + Cleanup(func()) +}) *State { + mock := &State{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // State is an autogenerated mock type for the State type type State struct { mock.Mock } -// AtBlockID provides a mock function with given fields: blockID -func (_m *State) AtBlockID(blockID flow.Identifier) cluster.Snapshot { - ret := _m.Called(blockID) +type State_Expecter struct { + mock *mock.Mock +} + +func (_m *State) EXPECT() *State_Expecter { + return &State_Expecter{mock: &_m.Mock} +} + +// AtBlockID provides a mock function for the type State +func (_mock *State) AtBlockID(blockID flow.Identifier) cluster.Snapshot { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for AtBlockID") } var r0 cluster.Snapshot - if rf, ok := ret.Get(0).(func(flow.Identifier) cluster.Snapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) cluster.Snapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cluster.Snapshot) } } - return r0 } -// Final provides a mock function with no fields -func (_m *State) Final() cluster.Snapshot { - ret := _m.Called() +// State_AtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtBlockID' +type State_AtBlockID_Call struct { + *mock.Call +} + +// AtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *State_Expecter) AtBlockID(blockID interface{}) *State_AtBlockID_Call { + return &State_AtBlockID_Call{Call: _e.mock.On("AtBlockID", blockID)} +} + +func (_c *State_AtBlockID_Call) Run(run func(blockID flow.Identifier)) *State_AtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *State_AtBlockID_Call) Return(snapshot cluster.Snapshot) *State_AtBlockID_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *State_AtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) cluster.Snapshot) *State_AtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// Final provides a mock function for the type State +func (_mock *State) Final() cluster.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Final") } var r0 cluster.Snapshot - if rf, ok := ret.Get(0).(func() cluster.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() cluster.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cluster.Snapshot) } } - return r0 } -// Params provides a mock function with no fields -func (_m *State) Params() cluster.Params { - ret := _m.Called() +// State_Final_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Final' +type State_Final_Call struct { + *mock.Call +} + +// Final is a helper method to define mock.On call +func (_e *State_Expecter) Final() *State_Final_Call { + return &State_Final_Call{Call: _e.mock.On("Final")} +} + +func (_c *State_Final_Call) Run(run func()) *State_Final_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *State_Final_Call) Return(snapshot cluster.Snapshot) *State_Final_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *State_Final_Call) RunAndReturn(run func() cluster.Snapshot) *State_Final_Call { + _c.Call.Return(run) + return _c +} + +// Params provides a mock function for the type State +func (_mock *State) Params() cluster.Params { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Params") } var r0 cluster.Params - if rf, ok := ret.Get(0).(func() cluster.Params); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() cluster.Params); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(cluster.Params) } } - return r0 } -// NewState creates a new instance of State. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewState(t interface { - mock.TestingT - Cleanup(func()) -}) *State { - mock := &State{} - mock.Mock.Test(t) +// State_Params_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Params' +type State_Params_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Params is a helper method to define mock.On call +func (_e *State_Expecter) Params() *State_Params_Call { + return &State_Params_Call{Call: _e.mock.On("Params")} +} - return mock +func (_c *State_Params_Call) Run(run func()) *State_Params_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *State_Params_Call) Return(params cluster.Params) *State_Params_Call { + _c.Call.Return(params) + return _c +} + +func (_c *State_Params_Call) RunAndReturn(run func() cluster.Params) *State_Params_Call { + _c.Call.Return(run) + return _c } diff --git a/state/errors.go b/state/errors.go index 495aed5a4fe..e47a77c23b9 100644 --- a/state/errors.go +++ b/state/errors.go @@ -19,7 +19,7 @@ type InvalidExtensionError struct { error } -func NewInvalidExtensionErrorf(msg string, args ...interface{}) error { +func NewInvalidExtensionErrorf(msg string, args ...any) error { return InvalidExtensionError{ error: fmt.Errorf(msg, args...), } @@ -42,7 +42,7 @@ type OutdatedExtensionError struct { error } -func NewOutdatedExtensionErrorf(msg string, args ...interface{}) error { +func NewOutdatedExtensionErrorf(msg string, args ...any) error { return OutdatedExtensionError{ error: fmt.Errorf(msg, args...), } @@ -65,7 +65,7 @@ type UnverifiableExtensionError struct { error } -func NewUnverifiableExtensionError(msg string, args ...interface{}) error { +func NewUnverifiableExtensionError(msg string, args ...any) error { return UnverifiableExtensionError{ error: fmt.Errorf(msg, args...), } diff --git a/state/protocol/badger/mutator_test.go b/state/protocol/badger/mutator_test.go index 47055894268..eb9c7a2df07 100644 --- a/state/protocol/badger/mutator_test.go +++ b/state/protocol/badger/mutator_test.go @@ -19,7 +19,6 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/model/flow/filter" "github.com/onflow/flow-go/module" - "github.com/onflow/flow-go/module/metrics" mmetrics "github.com/onflow/flow-go/module/metrics" mockmodule "github.com/onflow/flow-go/module/mock" "github.com/onflow/flow-go/module/signature" @@ -86,7 +85,7 @@ func TestBootstrapValid(t *testing.T) { func TestExtendValid(t *testing.T) { unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() db := pebbleimpl.ToDB(pdb) log := zerolog.Nop() @@ -257,7 +256,7 @@ func TestSealedIndex(t *testing.T) { err = state.Finalize(context.Background(), b4.ID()) require.NoError(t, err) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() seals := store.NewSeals(metrics, db) // can only find seal for G @@ -2799,7 +2798,7 @@ func TestEpochTargetDuration(t *testing.T) { func TestExtendInvalidSealsInBlock(t *testing.T) { unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() db := pebbleimpl.ToDB(pdb) @@ -3463,7 +3462,7 @@ func TestCacheAtomicity(t *testing.T) { func TestHeaderInvalidTimestamp(t *testing.T) { unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() db := pebbleimpl.ToDB(pdb) diff --git a/state/protocol/badger/state_test.go b/state/protocol/badger/state_test.go index cc9c024d3e6..83c05b1e40c 100644 --- a/state/protocol/badger/state_test.go +++ b/state/protocol/badger/state_test.go @@ -17,7 +17,6 @@ import ( bprotocol "github.com/onflow/flow-go/state/protocol/badger" "github.com/onflow/flow-go/state/protocol/inmem" "github.com/onflow/flow-go/state/protocol/util" - protoutil "github.com/onflow/flow-go/state/protocol/util" "github.com/onflow/flow-go/storage" "github.com/onflow/flow-go/storage/operation/pebbleimpl" "github.com/onflow/flow-go/storage/store" @@ -34,7 +33,7 @@ func TestBootstrapAndOpen(t *testing.T) { block.ParentID = unittest.IdentifierFixture() }) - protoutil.RunWithBootstrapState(t, rootSnapshot, func(db storage.DB, _ *bprotocol.State) { + util.RunWithBootstrapState(t, rootSnapshot, func(db storage.DB, _ *bprotocol.State) { lockManager := storage.NewTestingLockManager() // expect the final view metric to be set to current epoch's final view epoch, err := rootSnapshot.Epochs().Current() @@ -111,7 +110,7 @@ func TestBootstrapAndOpen_EpochCommitted(t *testing.T) { } }) - protoutil.RunWithBootstrapState(t, committedPhaseSnapshot, func(db storage.DB, _ *bprotocol.State) { + util.RunWithBootstrapState(t, committedPhaseSnapshot, func(db storage.DB, _ *bprotocol.State) { lockManager := storage.NewTestingLockManager() complianceMetrics := new(mock.ComplianceMetrics) @@ -879,7 +878,7 @@ func bootstrap(t *testing.T, rootSnapshot protocol.Snapshot, f func(*bprotocol.S // from non-root states. func snapshotAfter(t *testing.T, rootSnapshot protocol.Snapshot, f func(*bprotocol.FollowerState, protocol.MutableProtocolState) protocol.Snapshot) protocol.Snapshot { var after protocol.Snapshot - protoutil.RunWithFullProtocolStateAndMutator(t, rootSnapshot, func(_ storage.DB, state *bprotocol.ParticipantState, mutableState protocol.MutableProtocolState) { + util.RunWithFullProtocolStateAndMutator(t, rootSnapshot, func(_ storage.DB, state *bprotocol.ParticipantState, mutableState protocol.MutableProtocolState) { snap := f(state.FollowerState, mutableState) var err error after, err = inmem.FromSnapshot(snap) diff --git a/state/protocol/errors.go b/state/protocol/errors.go index 2ed04bb43ae..3e0dc3a183a 100644 --- a/state/protocol/errors.go +++ b/state/protocol/errors.go @@ -93,7 +93,7 @@ func IsInvalidBlockTimestampError(err error) bool { return errors.As(err, &errInvalidTimestampError) } -func NewInvalidBlockTimestamp(msg string, args ...interface{}) error { +func NewInvalidBlockTimestamp(msg string, args ...any) error { return InvalidBlockTimestampError{ error: fmt.Errorf(msg, args...), } @@ -116,7 +116,7 @@ func IsInvalidServiceEventError(err error) bool { // NewInvalidServiceEventErrorf returns an invalid service event error. Since all invalid // service events indicate an invalid extension, the service event error is wrapped in // the invalid extension error at construction. -func NewInvalidServiceEventErrorf(msg string, args ...interface{}) error { +func NewInvalidServiceEventErrorf(msg string, args ...any) error { return state.NewInvalidExtensionErrorf( "cannot extend state with invalid service event: %w", InvalidServiceEventError{ @@ -131,7 +131,7 @@ type UnfinalizedSealingSegmentError struct { error } -func NewUnfinalizedSealingSegmentErrorf(msg string, args ...interface{}) error { +func NewUnfinalizedSealingSegmentErrorf(msg string, args ...any) error { return UnfinalizedSealingSegmentError{ error: fmt.Errorf(msg, args...), } diff --git a/state/protocol/events/mock/heights.go b/state/protocol/events/mock/heights.go index 97412124350..1c73eaca3c8 100644 --- a/state/protocol/events/mock/heights.go +++ b/state/protocol/events/mock/heights.go @@ -1,18 +1,12 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" - -// Heights is an autogenerated mock type for the Heights type -type Heights struct { - mock.Mock -} - -// OnHeight provides a mock function with given fields: height, callback -func (_m *Heights) OnHeight(height uint64, callback func()) { - _m.Called(height, callback) -} +import ( + mock "github.com/stretchr/testify/mock" +) // NewHeights creates a new instance of Heights. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. @@ -27,3 +21,62 @@ func NewHeights(t interface { return mock } + +// Heights is an autogenerated mock type for the Heights type +type Heights struct { + mock.Mock +} + +type Heights_Expecter struct { + mock *mock.Mock +} + +func (_m *Heights) EXPECT() *Heights_Expecter { + return &Heights_Expecter{mock: &_m.Mock} +} + +// OnHeight provides a mock function for the type Heights +func (_mock *Heights) OnHeight(height uint64, callback func()) { + _mock.Called(height, callback) + return +} + +// Heights_OnHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnHeight' +type Heights_OnHeight_Call struct { + *mock.Call +} + +// OnHeight is a helper method to define mock.On call +// - height uint64 +// - callback func() +func (_e *Heights_Expecter) OnHeight(height interface{}, callback interface{}) *Heights_OnHeight_Call { + return &Heights_OnHeight_Call{Call: _e.mock.On("OnHeight", height, callback)} +} + +func (_c *Heights_OnHeight_Call) Run(run func(height uint64, callback func())) *Heights_OnHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 func() + if args[1] != nil { + arg1 = args[1].(func()) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Heights_OnHeight_Call) Return() *Heights_OnHeight_Call { + _c.Call.Return() + return _c +} + +func (_c *Heights_OnHeight_Call) RunAndReturn(run func(height uint64, callback func())) *Heights_OnHeight_Call { + _c.Run(run) + return _c +} diff --git a/state/protocol/events/mock/views.go b/state/protocol/events/mock/views.go index 78850a425e0..3689e459516 100644 --- a/state/protocol/events/mock/views.go +++ b/state/protocol/events/mock/views.go @@ -1,22 +1,14 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - events "github.com/onflow/flow-go/state/protocol/events" + "github.com/onflow/flow-go/state/protocol/events" mock "github.com/stretchr/testify/mock" ) -// Views is an autogenerated mock type for the Views type -type Views struct { - mock.Mock -} - -// OnView provides a mock function with given fields: view, callback -func (_m *Views) OnView(view uint64, callback events.OnViewCallback) { - _m.Called(view, callback) -} - // NewViews creates a new instance of Views. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewViews(t interface { @@ -30,3 +22,62 @@ func NewViews(t interface { return mock } + +// Views is an autogenerated mock type for the Views type +type Views struct { + mock.Mock +} + +type Views_Expecter struct { + mock *mock.Mock +} + +func (_m *Views) EXPECT() *Views_Expecter { + return &Views_Expecter{mock: &_m.Mock} +} + +// OnView provides a mock function for the type Views +func (_mock *Views) OnView(view uint64, callback events.OnViewCallback) { + _mock.Called(view, callback) + return +} + +// Views_OnView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnView' +type Views_OnView_Call struct { + *mock.Call +} + +// OnView is a helper method to define mock.On call +// - view uint64 +// - callback events.OnViewCallback +func (_e *Views_Expecter) OnView(view interface{}, callback interface{}) *Views_OnView_Call { + return &Views_OnView_Call{Call: _e.mock.On("OnView", view, callback)} +} + +func (_c *Views_OnView_Call) Run(run func(view uint64, callback events.OnViewCallback)) *Views_OnView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 events.OnViewCallback + if args[1] != nil { + arg1 = args[1].(events.OnViewCallback) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Views_OnView_Call) Return() *Views_OnView_Call { + _c.Call.Return() + return _c +} + +func (_c *Views_OnView_Call) RunAndReturn(run func(view uint64, callback events.OnViewCallback)) *Views_OnView_Call { + _c.Run(run) + return _c +} diff --git a/state/protocol/invalid/snapshot.go b/state/protocol/invalid/snapshot.go index 814b5a388aa..34873a5faf5 100644 --- a/state/protocol/invalid/snapshot.go +++ b/state/protocol/invalid/snapshot.go @@ -30,7 +30,7 @@ func NewSnapshot(err error) *Snapshot { var _ protocol.Snapshot = (*Snapshot)(nil) // NewSnapshotf is NewSnapshot with ergonomic error formatting. -func NewSnapshotf(msg string, args ...interface{}) *Snapshot { +func NewSnapshotf(msg string, args ...any) *Snapshot { return NewSnapshot(fmt.Errorf(msg, args...)) } diff --git a/state/protocol/mock/block_timer.go b/state/protocol/mock/block_timer.go index 16499090427..a3ef6aa46c7 100644 --- a/state/protocol/mock/block_timer.go +++ b/state/protocol/mock/block_timer.go @@ -1,60 +1,144 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewBlockTimer creates a new instance of BlockTimer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockTimer(t interface { + mock.TestingT + Cleanup(func()) +}) *BlockTimer { + mock := &BlockTimer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // BlockTimer is an autogenerated mock type for the BlockTimer type type BlockTimer struct { mock.Mock } -// Build provides a mock function with given fields: parentTimestamp -func (_m *BlockTimer) Build(parentTimestamp uint64) uint64 { - ret := _m.Called(parentTimestamp) +type BlockTimer_Expecter struct { + mock *mock.Mock +} + +func (_m *BlockTimer) EXPECT() *BlockTimer_Expecter { + return &BlockTimer_Expecter{mock: &_m.Mock} +} + +// Build provides a mock function for the type BlockTimer +func (_mock *BlockTimer) Build(parentTimestamp uint64) uint64 { + ret := _mock.Called(parentTimestamp) if len(ret) == 0 { panic("no return value specified for Build") } var r0 uint64 - if rf, ok := ret.Get(0).(func(uint64) uint64); ok { - r0 = rf(parentTimestamp) + if returnFunc, ok := ret.Get(0).(func(uint64) uint64); ok { + r0 = returnFunc(parentTimestamp) } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Validate provides a mock function with given fields: parentTimestamp, currentTimestamp -func (_m *BlockTimer) Validate(parentTimestamp uint64, currentTimestamp uint64) error { - ret := _m.Called(parentTimestamp, currentTimestamp) +// BlockTimer_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build' +type BlockTimer_Build_Call struct { + *mock.Call +} + +// Build is a helper method to define mock.On call +// - parentTimestamp uint64 +func (_e *BlockTimer_Expecter) Build(parentTimestamp interface{}) *BlockTimer_Build_Call { + return &BlockTimer_Build_Call{Call: _e.mock.On("Build", parentTimestamp)} +} + +func (_c *BlockTimer_Build_Call) Run(run func(parentTimestamp uint64)) *BlockTimer_Build_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BlockTimer_Build_Call) Return(v uint64) *BlockTimer_Build_Call { + _c.Call.Return(v) + return _c +} + +func (_c *BlockTimer_Build_Call) RunAndReturn(run func(parentTimestamp uint64) uint64) *BlockTimer_Build_Call { + _c.Call.Return(run) + return _c +} + +// Validate provides a mock function for the type BlockTimer +func (_mock *BlockTimer) Validate(parentTimestamp uint64, currentTimestamp uint64) error { + ret := _mock.Called(parentTimestamp, currentTimestamp) if len(ret) == 0 { panic("no return value specified for Validate") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, uint64) error); ok { - r0 = rf(parentTimestamp, currentTimestamp) + if returnFunc, ok := ret.Get(0).(func(uint64, uint64) error); ok { + r0 = returnFunc(parentTimestamp, currentTimestamp) } else { r0 = ret.Error(0) } - return r0 } -// NewBlockTimer creates a new instance of BlockTimer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlockTimer(t interface { - mock.TestingT - Cleanup(func()) -}) *BlockTimer { - mock := &BlockTimer{} - mock.Mock.Test(t) +// BlockTimer_Validate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Validate' +type BlockTimer_Validate_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Validate is a helper method to define mock.On call +// - parentTimestamp uint64 +// - currentTimestamp uint64 +func (_e *BlockTimer_Expecter) Validate(parentTimestamp interface{}, currentTimestamp interface{}) *BlockTimer_Validate_Call { + return &BlockTimer_Validate_Call{Call: _e.mock.On("Validate", parentTimestamp, currentTimestamp)} +} - return mock +func (_c *BlockTimer_Validate_Call) Run(run func(parentTimestamp uint64, currentTimestamp uint64)) *BlockTimer_Validate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *BlockTimer_Validate_Call) Return(err error) *BlockTimer_Validate_Call { + _c.Call.Return(err) + return _c +} + +func (_c *BlockTimer_Validate_Call) RunAndReturn(run func(parentTimestamp uint64, currentTimestamp uint64) error) *BlockTimer_Validate_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/cluster.go b/state/protocol/mock/cluster.go index 46a12811ebf..790aa9beafc 100644 --- a/state/protocol/mock/cluster.go +++ b/state/protocol/mock/cluster.go @@ -1,143 +1,308 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cluster "github.com/onflow/flow-go/model/cluster" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewCluster creates a new instance of Cluster. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCluster(t interface { + mock.TestingT + Cleanup(func()) +}) *Cluster { + mock := &Cluster{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Cluster is an autogenerated mock type for the Cluster type type Cluster struct { mock.Mock } -// ChainID provides a mock function with no fields -func (_m *Cluster) ChainID() flow.ChainID { - ret := _m.Called() +type Cluster_Expecter struct { + mock *mock.Mock +} + +func (_m *Cluster) EXPECT() *Cluster_Expecter { + return &Cluster_Expecter{mock: &_m.Mock} +} + +// ChainID provides a mock function for the type Cluster +func (_mock *Cluster) ChainID() flow.ChainID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ChainID") } var r0 flow.ChainID - if rf, ok := ret.Get(0).(func() flow.ChainID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ChainID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(flow.ChainID) } - return r0 } -// EpochCounter provides a mock function with no fields -func (_m *Cluster) EpochCounter() uint64 { - ret := _m.Called() +// Cluster_ChainID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChainID' +type Cluster_ChainID_Call struct { + *mock.Call +} + +// ChainID is a helper method to define mock.On call +func (_e *Cluster_Expecter) ChainID() *Cluster_ChainID_Call { + return &Cluster_ChainID_Call{Call: _e.mock.On("ChainID")} +} + +func (_c *Cluster_ChainID_Call) Run(run func()) *Cluster_ChainID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Cluster_ChainID_Call) Return(chainID flow.ChainID) *Cluster_ChainID_Call { + _c.Call.Return(chainID) + return _c +} + +func (_c *Cluster_ChainID_Call) RunAndReturn(run func() flow.ChainID) *Cluster_ChainID_Call { + _c.Call.Return(run) + return _c +} + +// EpochCounter provides a mock function for the type Cluster +func (_mock *Cluster) EpochCounter() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochCounter") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Index provides a mock function with no fields -func (_m *Cluster) Index() uint { - ret := _m.Called() +// Cluster_EpochCounter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochCounter' +type Cluster_EpochCounter_Call struct { + *mock.Call +} + +// EpochCounter is a helper method to define mock.On call +func (_e *Cluster_Expecter) EpochCounter() *Cluster_EpochCounter_Call { + return &Cluster_EpochCounter_Call{Call: _e.mock.On("EpochCounter")} +} + +func (_c *Cluster_EpochCounter_Call) Run(run func()) *Cluster_EpochCounter_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Cluster_EpochCounter_Call) Return(v uint64) *Cluster_EpochCounter_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Cluster_EpochCounter_Call) RunAndReturn(run func() uint64) *Cluster_EpochCounter_Call { + _c.Call.Return(run) + return _c +} + +// Index provides a mock function for the type Cluster +func (_mock *Cluster) Index() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Index") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// Members provides a mock function with no fields -func (_m *Cluster) Members() flow.IdentitySkeletonList { - ret := _m.Called() +// Cluster_Index_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Index' +type Cluster_Index_Call struct { + *mock.Call +} + +// Index is a helper method to define mock.On call +func (_e *Cluster_Expecter) Index() *Cluster_Index_Call { + return &Cluster_Index_Call{Call: _e.mock.On("Index")} +} + +func (_c *Cluster_Index_Call) Run(run func()) *Cluster_Index_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Cluster_Index_Call) Return(v uint) *Cluster_Index_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Cluster_Index_Call) RunAndReturn(run func() uint) *Cluster_Index_Call { + _c.Call.Return(run) + return _c +} + +// Members provides a mock function for the type Cluster +func (_mock *Cluster) Members() flow.IdentitySkeletonList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Members") } var r0 flow.IdentitySkeletonList - if rf, ok := ret.Get(0).(func() flow.IdentitySkeletonList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentitySkeletonList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentitySkeletonList) } } - return r0 } -// RootBlock provides a mock function with no fields -func (_m *Cluster) RootBlock() *cluster.Block { - ret := _m.Called() +// Cluster_Members_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Members' +type Cluster_Members_Call struct { + *mock.Call +} + +// Members is a helper method to define mock.On call +func (_e *Cluster_Expecter) Members() *Cluster_Members_Call { + return &Cluster_Members_Call{Call: _e.mock.On("Members")} +} + +func (_c *Cluster_Members_Call) Run(run func()) *Cluster_Members_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Cluster_Members_Call) Return(v flow.IdentitySkeletonList) *Cluster_Members_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Cluster_Members_Call) RunAndReturn(run func() flow.IdentitySkeletonList) *Cluster_Members_Call { + _c.Call.Return(run) + return _c +} + +// RootBlock provides a mock function for the type Cluster +func (_mock *Cluster) RootBlock() *cluster.Block { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RootBlock") } var r0 *cluster.Block - if rf, ok := ret.Get(0).(func() *cluster.Block); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *cluster.Block); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*cluster.Block) } } - return r0 } -// RootQC provides a mock function with no fields -func (_m *Cluster) RootQC() *flow.QuorumCertificate { - ret := _m.Called() +// Cluster_RootBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RootBlock' +type Cluster_RootBlock_Call struct { + *mock.Call +} + +// RootBlock is a helper method to define mock.On call +func (_e *Cluster_Expecter) RootBlock() *Cluster_RootBlock_Call { + return &Cluster_RootBlock_Call{Call: _e.mock.On("RootBlock")} +} + +func (_c *Cluster_RootBlock_Call) Run(run func()) *Cluster_RootBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Cluster_RootBlock_Call) Return(v *cluster.Block) *Cluster_RootBlock_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Cluster_RootBlock_Call) RunAndReturn(run func() *cluster.Block) *Cluster_RootBlock_Call { + _c.Call.Return(run) + return _c +} + +// RootQC provides a mock function for the type Cluster +func (_mock *Cluster) RootQC() *flow.QuorumCertificate { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RootQC") } var r0 *flow.QuorumCertificate - if rf, ok := ret.Get(0).(func() *flow.QuorumCertificate); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.QuorumCertificate); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.QuorumCertificate) } } - return r0 } -// NewCluster creates a new instance of Cluster. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCluster(t interface { - mock.TestingT - Cleanup(func()) -}) *Cluster { - mock := &Cluster{} - mock.Mock.Test(t) +// Cluster_RootQC_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RootQC' +type Cluster_RootQC_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RootQC is a helper method to define mock.On call +func (_e *Cluster_Expecter) RootQC() *Cluster_RootQC_Call { + return &Cluster_RootQC_Call{Call: _e.mock.On("RootQC")} +} - return mock +func (_c *Cluster_RootQC_Call) Run(run func()) *Cluster_RootQC_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Cluster_RootQC_Call) Return(quorumCertificate *flow.QuorumCertificate) *Cluster_RootQC_Call { + _c.Call.Return(quorumCertificate) + return _c +} + +func (_c *Cluster_RootQC_Call) RunAndReturn(run func() *flow.QuorumCertificate) *Cluster_RootQC_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/committed_epoch.go b/state/protocol/mock/committed_epoch.go index 271bbaf94ee..4fc30fc4b40 100644 --- a/state/protocol/mock/committed_epoch.go +++ b/state/protocol/mock/committed_epoch.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewCommittedEpoch creates a new instance of CommittedEpoch. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCommittedEpoch(t interface { + mock.TestingT + Cleanup(func()) +}) *CommittedEpoch { + mock := &CommittedEpoch{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CommittedEpoch is an autogenerated mock type for the CommittedEpoch type type CommittedEpoch struct { mock.Mock } -// Cluster provides a mock function with given fields: index -func (_m *CommittedEpoch) Cluster(index uint) (protocol.Cluster, error) { - ret := _m.Called(index) +type CommittedEpoch_Expecter struct { + mock *mock.Mock +} + +func (_m *CommittedEpoch) EXPECT() *CommittedEpoch_Expecter { + return &CommittedEpoch_Expecter{mock: &_m.Mock} +} + +// Cluster provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) Cluster(index uint) (protocol.Cluster, error) { + ret := _mock.Called(index) if len(ret) == 0 { panic("no return value specified for Cluster") @@ -24,29 +47,61 @@ func (_m *CommittedEpoch) Cluster(index uint) (protocol.Cluster, error) { var r0 protocol.Cluster var r1 error - if rf, ok := ret.Get(0).(func(uint) (protocol.Cluster, error)); ok { - return rf(index) + if returnFunc, ok := ret.Get(0).(func(uint) (protocol.Cluster, error)); ok { + return returnFunc(index) } - if rf, ok := ret.Get(0).(func(uint) protocol.Cluster); ok { - r0 = rf(index) + if returnFunc, ok := ret.Get(0).(func(uint) protocol.Cluster); ok { + r0 = returnFunc(index) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Cluster) } } - - if rf, ok := ret.Get(1).(func(uint) error); ok { - r1 = rf(index) + if returnFunc, ok := ret.Get(1).(func(uint) error); ok { + r1 = returnFunc(index) } else { r1 = ret.Error(1) } - return r0, r1 } -// ClusterByChainID provides a mock function with given fields: chainID -func (_m *CommittedEpoch) ClusterByChainID(chainID flow.ChainID) (protocol.Cluster, error) { - ret := _m.Called(chainID) +// CommittedEpoch_Cluster_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Cluster' +type CommittedEpoch_Cluster_Call struct { + *mock.Call +} + +// Cluster is a helper method to define mock.On call +// - index uint +func (_e *CommittedEpoch_Expecter) Cluster(index interface{}) *CommittedEpoch_Cluster_Call { + return &CommittedEpoch_Cluster_Call{Call: _e.mock.On("Cluster", index)} +} + +func (_c *CommittedEpoch_Cluster_Call) Run(run func(index uint)) *CommittedEpoch_Cluster_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CommittedEpoch_Cluster_Call) Return(cluster protocol.Cluster, err error) *CommittedEpoch_Cluster_Call { + _c.Call.Return(cluster, err) + return _c +} + +func (_c *CommittedEpoch_Cluster_Call) RunAndReturn(run func(index uint) (protocol.Cluster, error)) *CommittedEpoch_Cluster_Call { + _c.Call.Return(run) + return _c +} + +// ClusterByChainID provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) ClusterByChainID(chainID flow.ChainID) (protocol.Cluster, error) { + ret := _mock.Called(chainID) if len(ret) == 0 { panic("no return value specified for ClusterByChainID") @@ -54,29 +109,61 @@ func (_m *CommittedEpoch) ClusterByChainID(chainID flow.ChainID) (protocol.Clust var r0 protocol.Cluster var r1 error - if rf, ok := ret.Get(0).(func(flow.ChainID) (protocol.Cluster, error)); ok { - return rf(chainID) + if returnFunc, ok := ret.Get(0).(func(flow.ChainID) (protocol.Cluster, error)); ok { + return returnFunc(chainID) } - if rf, ok := ret.Get(0).(func(flow.ChainID) protocol.Cluster); ok { - r0 = rf(chainID) + if returnFunc, ok := ret.Get(0).(func(flow.ChainID) protocol.Cluster); ok { + r0 = returnFunc(chainID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Cluster) } } - - if rf, ok := ret.Get(1).(func(flow.ChainID) error); ok { - r1 = rf(chainID) + if returnFunc, ok := ret.Get(1).(func(flow.ChainID) error); ok { + r1 = returnFunc(chainID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Clustering provides a mock function with no fields -func (_m *CommittedEpoch) Clustering() (flow.ClusterList, error) { - ret := _m.Called() +// CommittedEpoch_ClusterByChainID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClusterByChainID' +type CommittedEpoch_ClusterByChainID_Call struct { + *mock.Call +} + +// ClusterByChainID is a helper method to define mock.On call +// - chainID flow.ChainID +func (_e *CommittedEpoch_Expecter) ClusterByChainID(chainID interface{}) *CommittedEpoch_ClusterByChainID_Call { + return &CommittedEpoch_ClusterByChainID_Call{Call: _e.mock.On("ClusterByChainID", chainID)} +} + +func (_c *CommittedEpoch_ClusterByChainID_Call) Run(run func(chainID flow.ChainID)) *CommittedEpoch_ClusterByChainID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ChainID + if args[0] != nil { + arg0 = args[0].(flow.ChainID) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CommittedEpoch_ClusterByChainID_Call) Return(cluster protocol.Cluster, err error) *CommittedEpoch_ClusterByChainID_Call { + _c.Call.Return(cluster, err) + return _c +} + +func (_c *CommittedEpoch_ClusterByChainID_Call) RunAndReturn(run func(chainID flow.ChainID) (protocol.Cluster, error)) *CommittedEpoch_ClusterByChainID_Call { + _c.Call.Return(run) + return _c +} + +// Clustering provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) Clustering() (flow.ClusterList, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Clustering") @@ -84,47 +171,98 @@ func (_m *CommittedEpoch) Clustering() (flow.ClusterList, error) { var r0 flow.ClusterList var r1 error - if rf, ok := ret.Get(0).(func() (flow.ClusterList, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.ClusterList, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.ClusterList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ClusterList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.ClusterList) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Counter provides a mock function with no fields -func (_m *CommittedEpoch) Counter() uint64 { - ret := _m.Called() +// CommittedEpoch_Clustering_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clustering' +type CommittedEpoch_Clustering_Call struct { + *mock.Call +} + +// Clustering is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) Clustering() *CommittedEpoch_Clustering_Call { + return &CommittedEpoch_Clustering_Call{Call: _e.mock.On("Clustering")} +} + +func (_c *CommittedEpoch_Clustering_Call) Run(run func()) *CommittedEpoch_Clustering_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_Clustering_Call) Return(clusterList flow.ClusterList, err error) *CommittedEpoch_Clustering_Call { + _c.Call.Return(clusterList, err) + return _c +} + +func (_c *CommittedEpoch_Clustering_Call) RunAndReturn(run func() (flow.ClusterList, error)) *CommittedEpoch_Clustering_Call { + _c.Call.Return(run) + return _c +} + +// Counter provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) Counter() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Counter") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// DKG provides a mock function with no fields -func (_m *CommittedEpoch) DKG() (protocol.DKG, error) { - ret := _m.Called() +// CommittedEpoch_Counter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Counter' +type CommittedEpoch_Counter_Call struct { + *mock.Call +} + +// Counter is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) Counter() *CommittedEpoch_Counter_Call { + return &CommittedEpoch_Counter_Call{Call: _e.mock.On("Counter")} +} + +func (_c *CommittedEpoch_Counter_Call) Run(run func()) *CommittedEpoch_Counter_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_Counter_Call) Return(v uint64) *CommittedEpoch_Counter_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_Counter_Call) RunAndReturn(run func() uint64) *CommittedEpoch_Counter_Call { + _c.Call.Return(run) + return _c +} + +// DKG provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) DKG() (protocol.DKG, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for DKG") @@ -132,83 +270,186 @@ func (_m *CommittedEpoch) DKG() (protocol.DKG, error) { var r0 protocol.DKG var r1 error - if rf, ok := ret.Get(0).(func() (protocol.DKG, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.DKG, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.DKG); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.DKG); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.DKG) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// DKGPhase1FinalView provides a mock function with no fields -func (_m *CommittedEpoch) DKGPhase1FinalView() uint64 { - ret := _m.Called() +// CommittedEpoch_DKG_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DKG' +type CommittedEpoch_DKG_Call struct { + *mock.Call +} + +// DKG is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) DKG() *CommittedEpoch_DKG_Call { + return &CommittedEpoch_DKG_Call{Call: _e.mock.On("DKG")} +} + +func (_c *CommittedEpoch_DKG_Call) Run(run func()) *CommittedEpoch_DKG_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_DKG_Call) Return(dKG protocol.DKG, err error) *CommittedEpoch_DKG_Call { + _c.Call.Return(dKG, err) + return _c +} + +func (_c *CommittedEpoch_DKG_Call) RunAndReturn(run func() (protocol.DKG, error)) *CommittedEpoch_DKG_Call { + _c.Call.Return(run) + return _c +} + +// DKGPhase1FinalView provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) DKGPhase1FinalView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for DKGPhase1FinalView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// DKGPhase2FinalView provides a mock function with no fields -func (_m *CommittedEpoch) DKGPhase2FinalView() uint64 { - ret := _m.Called() +// CommittedEpoch_DKGPhase1FinalView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DKGPhase1FinalView' +type CommittedEpoch_DKGPhase1FinalView_Call struct { + *mock.Call +} + +// DKGPhase1FinalView is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) DKGPhase1FinalView() *CommittedEpoch_DKGPhase1FinalView_Call { + return &CommittedEpoch_DKGPhase1FinalView_Call{Call: _e.mock.On("DKGPhase1FinalView")} +} + +func (_c *CommittedEpoch_DKGPhase1FinalView_Call) Run(run func()) *CommittedEpoch_DKGPhase1FinalView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_DKGPhase1FinalView_Call) Return(v uint64) *CommittedEpoch_DKGPhase1FinalView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_DKGPhase1FinalView_Call) RunAndReturn(run func() uint64) *CommittedEpoch_DKGPhase1FinalView_Call { + _c.Call.Return(run) + return _c +} + +// DKGPhase2FinalView provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) DKGPhase2FinalView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for DKGPhase2FinalView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// DKGPhase3FinalView provides a mock function with no fields -func (_m *CommittedEpoch) DKGPhase3FinalView() uint64 { - ret := _m.Called() +// CommittedEpoch_DKGPhase2FinalView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DKGPhase2FinalView' +type CommittedEpoch_DKGPhase2FinalView_Call struct { + *mock.Call +} + +// DKGPhase2FinalView is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) DKGPhase2FinalView() *CommittedEpoch_DKGPhase2FinalView_Call { + return &CommittedEpoch_DKGPhase2FinalView_Call{Call: _e.mock.On("DKGPhase2FinalView")} +} + +func (_c *CommittedEpoch_DKGPhase2FinalView_Call) Run(run func()) *CommittedEpoch_DKGPhase2FinalView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_DKGPhase2FinalView_Call) Return(v uint64) *CommittedEpoch_DKGPhase2FinalView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_DKGPhase2FinalView_Call) RunAndReturn(run func() uint64) *CommittedEpoch_DKGPhase2FinalView_Call { + _c.Call.Return(run) + return _c +} + +// DKGPhase3FinalView provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) DKGPhase3FinalView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for DKGPhase3FinalView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// FinalHeight provides a mock function with no fields -func (_m *CommittedEpoch) FinalHeight() (uint64, error) { - ret := _m.Called() +// CommittedEpoch_DKGPhase3FinalView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DKGPhase3FinalView' +type CommittedEpoch_DKGPhase3FinalView_Call struct { + *mock.Call +} + +// DKGPhase3FinalView is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) DKGPhase3FinalView() *CommittedEpoch_DKGPhase3FinalView_Call { + return &CommittedEpoch_DKGPhase3FinalView_Call{Call: _e.mock.On("DKGPhase3FinalView")} +} + +func (_c *CommittedEpoch_DKGPhase3FinalView_Call) Run(run func()) *CommittedEpoch_DKGPhase3FinalView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_DKGPhase3FinalView_Call) Return(v uint64) *CommittedEpoch_DKGPhase3FinalView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_DKGPhase3FinalView_Call) RunAndReturn(run func() uint64) *CommittedEpoch_DKGPhase3FinalView_Call { + _c.Call.Return(run) + return _c +} + +// FinalHeight provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) FinalHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalHeight") @@ -216,45 +457,96 @@ func (_m *CommittedEpoch) FinalHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// FinalView provides a mock function with no fields -func (_m *CommittedEpoch) FinalView() uint64 { - ret := _m.Called() +// CommittedEpoch_FinalHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalHeight' +type CommittedEpoch_FinalHeight_Call struct { + *mock.Call +} + +// FinalHeight is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) FinalHeight() *CommittedEpoch_FinalHeight_Call { + return &CommittedEpoch_FinalHeight_Call{Call: _e.mock.On("FinalHeight")} +} + +func (_c *CommittedEpoch_FinalHeight_Call) Run(run func()) *CommittedEpoch_FinalHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_FinalHeight_Call) Return(v uint64, err error) *CommittedEpoch_FinalHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *CommittedEpoch_FinalHeight_Call) RunAndReturn(run func() (uint64, error)) *CommittedEpoch_FinalHeight_Call { + _c.Call.Return(run) + return _c +} + +// FinalView provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) FinalView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// FirstHeight provides a mock function with no fields -func (_m *CommittedEpoch) FirstHeight() (uint64, error) { - ret := _m.Called() +// CommittedEpoch_FinalView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalView' +type CommittedEpoch_FinalView_Call struct { + *mock.Call +} + +// FinalView is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) FinalView() *CommittedEpoch_FinalView_Call { + return &CommittedEpoch_FinalView_Call{Call: _e.mock.On("FinalView")} +} + +func (_c *CommittedEpoch_FinalView_Call) Run(run func()) *CommittedEpoch_FinalView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_FinalView_Call) Return(v uint64) *CommittedEpoch_FinalView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_FinalView_Call) RunAndReturn(run func() uint64) *CommittedEpoch_FinalView_Call { + _c.Call.Return(run) + return _c +} + +// FirstHeight provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) FirstHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FirstHeight") @@ -262,128 +554,269 @@ func (_m *CommittedEpoch) FirstHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// FirstView provides a mock function with no fields -func (_m *CommittedEpoch) FirstView() uint64 { - ret := _m.Called() +// CommittedEpoch_FirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstHeight' +type CommittedEpoch_FirstHeight_Call struct { + *mock.Call +} + +// FirstHeight is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) FirstHeight() *CommittedEpoch_FirstHeight_Call { + return &CommittedEpoch_FirstHeight_Call{Call: _e.mock.On("FirstHeight")} +} + +func (_c *CommittedEpoch_FirstHeight_Call) Run(run func()) *CommittedEpoch_FirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_FirstHeight_Call) Return(v uint64, err error) *CommittedEpoch_FirstHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *CommittedEpoch_FirstHeight_Call) RunAndReturn(run func() (uint64, error)) *CommittedEpoch_FirstHeight_Call { + _c.Call.Return(run) + return _c +} + +// FirstView provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) FirstView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FirstView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// InitialIdentities provides a mock function with no fields -func (_m *CommittedEpoch) InitialIdentities() flow.IdentitySkeletonList { - ret := _m.Called() +// CommittedEpoch_FirstView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstView' +type CommittedEpoch_FirstView_Call struct { + *mock.Call +} + +// FirstView is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) FirstView() *CommittedEpoch_FirstView_Call { + return &CommittedEpoch_FirstView_Call{Call: _e.mock.On("FirstView")} +} + +func (_c *CommittedEpoch_FirstView_Call) Run(run func()) *CommittedEpoch_FirstView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_FirstView_Call) Return(v uint64) *CommittedEpoch_FirstView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_FirstView_Call) RunAndReturn(run func() uint64) *CommittedEpoch_FirstView_Call { + _c.Call.Return(run) + return _c +} + +// InitialIdentities provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) InitialIdentities() flow.IdentitySkeletonList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for InitialIdentities") } var r0 flow.IdentitySkeletonList - if rf, ok := ret.Get(0).(func() flow.IdentitySkeletonList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentitySkeletonList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentitySkeletonList) } } - return r0 } -// RandomSource provides a mock function with no fields -func (_m *CommittedEpoch) RandomSource() []byte { - ret := _m.Called() +// CommittedEpoch_InitialIdentities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InitialIdentities' +type CommittedEpoch_InitialIdentities_Call struct { + *mock.Call +} + +// InitialIdentities is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) InitialIdentities() *CommittedEpoch_InitialIdentities_Call { + return &CommittedEpoch_InitialIdentities_Call{Call: _e.mock.On("InitialIdentities")} +} + +func (_c *CommittedEpoch_InitialIdentities_Call) Run(run func()) *CommittedEpoch_InitialIdentities_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_InitialIdentities_Call) Return(v flow.IdentitySkeletonList) *CommittedEpoch_InitialIdentities_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_InitialIdentities_Call) RunAndReturn(run func() flow.IdentitySkeletonList) *CommittedEpoch_InitialIdentities_Call { + _c.Call.Return(run) + return _c +} + +// RandomSource provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) RandomSource() []byte { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RandomSource") } var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - return r0 } -// TargetDuration provides a mock function with no fields -func (_m *CommittedEpoch) TargetDuration() uint64 { - ret := _m.Called() +// CommittedEpoch_RandomSource_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RandomSource' +type CommittedEpoch_RandomSource_Call struct { + *mock.Call +} + +// RandomSource is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) RandomSource() *CommittedEpoch_RandomSource_Call { + return &CommittedEpoch_RandomSource_Call{Call: _e.mock.On("RandomSource")} +} + +func (_c *CommittedEpoch_RandomSource_Call) Run(run func()) *CommittedEpoch_RandomSource_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_RandomSource_Call) Return(bytes []byte) *CommittedEpoch_RandomSource_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *CommittedEpoch_RandomSource_Call) RunAndReturn(run func() []byte) *CommittedEpoch_RandomSource_Call { + _c.Call.Return(run) + return _c +} + +// TargetDuration provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) TargetDuration() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TargetDuration") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// TargetEndTime provides a mock function with no fields -func (_m *CommittedEpoch) TargetEndTime() uint64 { - ret := _m.Called() +// CommittedEpoch_TargetDuration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TargetDuration' +type CommittedEpoch_TargetDuration_Call struct { + *mock.Call +} + +// TargetDuration is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) TargetDuration() *CommittedEpoch_TargetDuration_Call { + return &CommittedEpoch_TargetDuration_Call{Call: _e.mock.On("TargetDuration")} +} + +func (_c *CommittedEpoch_TargetDuration_Call) Run(run func()) *CommittedEpoch_TargetDuration_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_TargetDuration_Call) Return(v uint64) *CommittedEpoch_TargetDuration_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_TargetDuration_Call) RunAndReturn(run func() uint64) *CommittedEpoch_TargetDuration_Call { + _c.Call.Return(run) + return _c +} + +// TargetEndTime provides a mock function for the type CommittedEpoch +func (_mock *CommittedEpoch) TargetEndTime() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TargetEndTime") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewCommittedEpoch creates a new instance of CommittedEpoch. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCommittedEpoch(t interface { - mock.TestingT - Cleanup(func()) -}) *CommittedEpoch { - mock := &CommittedEpoch{} - mock.Mock.Test(t) +// CommittedEpoch_TargetEndTime_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TargetEndTime' +type CommittedEpoch_TargetEndTime_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TargetEndTime is a helper method to define mock.On call +func (_e *CommittedEpoch_Expecter) TargetEndTime() *CommittedEpoch_TargetEndTime_Call { + return &CommittedEpoch_TargetEndTime_Call{Call: _e.mock.On("TargetEndTime")} +} - return mock +func (_c *CommittedEpoch_TargetEndTime_Call) Run(run func()) *CommittedEpoch_TargetEndTime_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *CommittedEpoch_TargetEndTime_Call) Return(v uint64) *CommittedEpoch_TargetEndTime_Call { + _c.Call.Return(v) + return _c +} + +func (_c *CommittedEpoch_TargetEndTime_Call) RunAndReturn(run func() uint64) *CommittedEpoch_TargetEndTime_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/consumer.go b/state/protocol/mock/consumer.go index 003bacda598..aa3c8578ddb 100644 --- a/state/protocol/mock/consumer.go +++ b/state/protocol/mock/consumer.go @@ -1,67 +1,405 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewConsumer creates a new instance of Consumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *Consumer { + mock := &Consumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Consumer is an autogenerated mock type for the Consumer type type Consumer struct { mock.Mock } -// BlockFinalized provides a mock function with given fields: block -func (_m *Consumer) BlockFinalized(block *flow.Header) { - _m.Called(block) +type Consumer_Expecter struct { + mock *mock.Mock } -// BlockProcessable provides a mock function with given fields: block, certifyingQC -func (_m *Consumer) BlockProcessable(block *flow.Header, certifyingQC *flow.QuorumCertificate) { - _m.Called(block, certifyingQC) +func (_m *Consumer) EXPECT() *Consumer_Expecter { + return &Consumer_Expecter{mock: &_m.Mock} } -// EpochCommittedPhaseStarted provides a mock function with given fields: currentEpochCounter, first -func (_m *Consumer) EpochCommittedPhaseStarted(currentEpochCounter uint64, first *flow.Header) { - _m.Called(currentEpochCounter, first) +// BlockFinalized provides a mock function for the type Consumer +func (_mock *Consumer) BlockFinalized(block *flow.Header) { + _mock.Called(block) + return } -// EpochExtended provides a mock function with given fields: epochCounter, header, extension -func (_m *Consumer) EpochExtended(epochCounter uint64, header *flow.Header, extension flow.EpochExtension) { - _m.Called(epochCounter, header, extension) +// Consumer_BlockFinalized_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockFinalized' +type Consumer_BlockFinalized_Call struct { + *mock.Call } -// EpochFallbackModeExited provides a mock function with given fields: epochCounter, header -func (_m *Consumer) EpochFallbackModeExited(epochCounter uint64, header *flow.Header) { - _m.Called(epochCounter, header) +// BlockFinalized is a helper method to define mock.On call +// - block *flow.Header +func (_e *Consumer_Expecter) BlockFinalized(block interface{}) *Consumer_BlockFinalized_Call { + return &Consumer_BlockFinalized_Call{Call: _e.mock.On("BlockFinalized", block)} } -// EpochFallbackModeTriggered provides a mock function with given fields: epochCounter, header -func (_m *Consumer) EpochFallbackModeTriggered(epochCounter uint64, header *flow.Header) { - _m.Called(epochCounter, header) +func (_c *Consumer_BlockFinalized_Call) Run(run func(block *flow.Header)) *Consumer_BlockFinalized_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + run( + arg0, + ) + }) + return _c } -// EpochSetupPhaseStarted provides a mock function with given fields: currentEpochCounter, first -func (_m *Consumer) EpochSetupPhaseStarted(currentEpochCounter uint64, first *flow.Header) { - _m.Called(currentEpochCounter, first) +func (_c *Consumer_BlockFinalized_Call) Return() *Consumer_BlockFinalized_Call { + _c.Call.Return() + return _c } -// EpochTransition provides a mock function with given fields: newEpochCounter, first -func (_m *Consumer) EpochTransition(newEpochCounter uint64, first *flow.Header) { - _m.Called(newEpochCounter, first) +func (_c *Consumer_BlockFinalized_Call) RunAndReturn(run func(block *flow.Header)) *Consumer_BlockFinalized_Call { + _c.Run(run) + return _c } -// NewConsumer creates a new instance of Consumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *Consumer { - mock := &Consumer{} - mock.Mock.Test(t) +// BlockProcessable provides a mock function for the type Consumer +func (_mock *Consumer) BlockProcessable(block *flow.Header, certifyingQC *flow.QuorumCertificate) { + _mock.Called(block, certifyingQC) + return +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Consumer_BlockProcessable_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockProcessable' +type Consumer_BlockProcessable_Call struct { + *mock.Call +} - return mock +// BlockProcessable is a helper method to define mock.On call +// - block *flow.Header +// - certifyingQC *flow.QuorumCertificate +func (_e *Consumer_Expecter) BlockProcessable(block interface{}, certifyingQC interface{}) *Consumer_BlockProcessable_Call { + return &Consumer_BlockProcessable_Call{Call: _e.mock.On("BlockProcessable", block, certifyingQC)} +} + +func (_c *Consumer_BlockProcessable_Call) Run(run func(block *flow.Header, certifyingQC *flow.QuorumCertificate)) *Consumer_BlockProcessable_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Header + if args[0] != nil { + arg0 = args[0].(*flow.Header) + } + var arg1 *flow.QuorumCertificate + if args[1] != nil { + arg1 = args[1].(*flow.QuorumCertificate) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_BlockProcessable_Call) Return() *Consumer_BlockProcessable_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_BlockProcessable_Call) RunAndReturn(run func(block *flow.Header, certifyingQC *flow.QuorumCertificate)) *Consumer_BlockProcessable_Call { + _c.Run(run) + return _c +} + +// EpochCommittedPhaseStarted provides a mock function for the type Consumer +func (_mock *Consumer) EpochCommittedPhaseStarted(currentEpochCounter uint64, first *flow.Header) { + _mock.Called(currentEpochCounter, first) + return +} + +// Consumer_EpochCommittedPhaseStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochCommittedPhaseStarted' +type Consumer_EpochCommittedPhaseStarted_Call struct { + *mock.Call +} + +// EpochCommittedPhaseStarted is a helper method to define mock.On call +// - currentEpochCounter uint64 +// - first *flow.Header +func (_e *Consumer_Expecter) EpochCommittedPhaseStarted(currentEpochCounter interface{}, first interface{}) *Consumer_EpochCommittedPhaseStarted_Call { + return &Consumer_EpochCommittedPhaseStarted_Call{Call: _e.mock.On("EpochCommittedPhaseStarted", currentEpochCounter, first)} +} + +func (_c *Consumer_EpochCommittedPhaseStarted_Call) Run(run func(currentEpochCounter uint64, first *flow.Header)) *Consumer_EpochCommittedPhaseStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_EpochCommittedPhaseStarted_Call) Return() *Consumer_EpochCommittedPhaseStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_EpochCommittedPhaseStarted_Call) RunAndReturn(run func(currentEpochCounter uint64, first *flow.Header)) *Consumer_EpochCommittedPhaseStarted_Call { + _c.Run(run) + return _c +} + +// EpochExtended provides a mock function for the type Consumer +func (_mock *Consumer) EpochExtended(epochCounter uint64, header *flow.Header, extension flow.EpochExtension) { + _mock.Called(epochCounter, header, extension) + return +} + +// Consumer_EpochExtended_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochExtended' +type Consumer_EpochExtended_Call struct { + *mock.Call +} + +// EpochExtended is a helper method to define mock.On call +// - epochCounter uint64 +// - header *flow.Header +// - extension flow.EpochExtension +func (_e *Consumer_Expecter) EpochExtended(epochCounter interface{}, header interface{}, extension interface{}) *Consumer_EpochExtended_Call { + return &Consumer_EpochExtended_Call{Call: _e.mock.On("EpochExtended", epochCounter, header, extension)} +} + +func (_c *Consumer_EpochExtended_Call) Run(run func(epochCounter uint64, header *flow.Header, extension flow.EpochExtension)) *Consumer_EpochExtended_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + var arg2 flow.EpochExtension + if args[2] != nil { + arg2 = args[2].(flow.EpochExtension) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Consumer_EpochExtended_Call) Return() *Consumer_EpochExtended_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_EpochExtended_Call) RunAndReturn(run func(epochCounter uint64, header *flow.Header, extension flow.EpochExtension)) *Consumer_EpochExtended_Call { + _c.Run(run) + return _c +} + +// EpochFallbackModeExited provides a mock function for the type Consumer +func (_mock *Consumer) EpochFallbackModeExited(epochCounter uint64, header *flow.Header) { + _mock.Called(epochCounter, header) + return +} + +// Consumer_EpochFallbackModeExited_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochFallbackModeExited' +type Consumer_EpochFallbackModeExited_Call struct { + *mock.Call +} + +// EpochFallbackModeExited is a helper method to define mock.On call +// - epochCounter uint64 +// - header *flow.Header +func (_e *Consumer_Expecter) EpochFallbackModeExited(epochCounter interface{}, header interface{}) *Consumer_EpochFallbackModeExited_Call { + return &Consumer_EpochFallbackModeExited_Call{Call: _e.mock.On("EpochFallbackModeExited", epochCounter, header)} +} + +func (_c *Consumer_EpochFallbackModeExited_Call) Run(run func(epochCounter uint64, header *flow.Header)) *Consumer_EpochFallbackModeExited_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_EpochFallbackModeExited_Call) Return() *Consumer_EpochFallbackModeExited_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_EpochFallbackModeExited_Call) RunAndReturn(run func(epochCounter uint64, header *flow.Header)) *Consumer_EpochFallbackModeExited_Call { + _c.Run(run) + return _c +} + +// EpochFallbackModeTriggered provides a mock function for the type Consumer +func (_mock *Consumer) EpochFallbackModeTriggered(epochCounter uint64, header *flow.Header) { + _mock.Called(epochCounter, header) + return +} + +// Consumer_EpochFallbackModeTriggered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochFallbackModeTriggered' +type Consumer_EpochFallbackModeTriggered_Call struct { + *mock.Call +} + +// EpochFallbackModeTriggered is a helper method to define mock.On call +// - epochCounter uint64 +// - header *flow.Header +func (_e *Consumer_Expecter) EpochFallbackModeTriggered(epochCounter interface{}, header interface{}) *Consumer_EpochFallbackModeTriggered_Call { + return &Consumer_EpochFallbackModeTriggered_Call{Call: _e.mock.On("EpochFallbackModeTriggered", epochCounter, header)} +} + +func (_c *Consumer_EpochFallbackModeTriggered_Call) Run(run func(epochCounter uint64, header *flow.Header)) *Consumer_EpochFallbackModeTriggered_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_EpochFallbackModeTriggered_Call) Return() *Consumer_EpochFallbackModeTriggered_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_EpochFallbackModeTriggered_Call) RunAndReturn(run func(epochCounter uint64, header *flow.Header)) *Consumer_EpochFallbackModeTriggered_Call { + _c.Run(run) + return _c +} + +// EpochSetupPhaseStarted provides a mock function for the type Consumer +func (_mock *Consumer) EpochSetupPhaseStarted(currentEpochCounter uint64, first *flow.Header) { + _mock.Called(currentEpochCounter, first) + return +} + +// Consumer_EpochSetupPhaseStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochSetupPhaseStarted' +type Consumer_EpochSetupPhaseStarted_Call struct { + *mock.Call +} + +// EpochSetupPhaseStarted is a helper method to define mock.On call +// - currentEpochCounter uint64 +// - first *flow.Header +func (_e *Consumer_Expecter) EpochSetupPhaseStarted(currentEpochCounter interface{}, first interface{}) *Consumer_EpochSetupPhaseStarted_Call { + return &Consumer_EpochSetupPhaseStarted_Call{Call: _e.mock.On("EpochSetupPhaseStarted", currentEpochCounter, first)} +} + +func (_c *Consumer_EpochSetupPhaseStarted_Call) Run(run func(currentEpochCounter uint64, first *flow.Header)) *Consumer_EpochSetupPhaseStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_EpochSetupPhaseStarted_Call) Return() *Consumer_EpochSetupPhaseStarted_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_EpochSetupPhaseStarted_Call) RunAndReturn(run func(currentEpochCounter uint64, first *flow.Header)) *Consumer_EpochSetupPhaseStarted_Call { + _c.Run(run) + return _c +} + +// EpochTransition provides a mock function for the type Consumer +func (_mock *Consumer) EpochTransition(newEpochCounter uint64, first *flow.Header) { + _mock.Called(newEpochCounter, first) + return +} + +// Consumer_EpochTransition_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochTransition' +type Consumer_EpochTransition_Call struct { + *mock.Call +} + +// EpochTransition is a helper method to define mock.On call +// - newEpochCounter uint64 +// - first *flow.Header +func (_e *Consumer_Expecter) EpochTransition(newEpochCounter interface{}, first interface{}) *Consumer_EpochTransition_Call { + return &Consumer_EpochTransition_Call{Call: _e.mock.On("EpochTransition", newEpochCounter, first)} +} + +func (_c *Consumer_EpochTransition_Call) Run(run func(newEpochCounter uint64, first *flow.Header)) *Consumer_EpochTransition_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.Header + if args[1] != nil { + arg1 = args[1].(*flow.Header) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Consumer_EpochTransition_Call) Return() *Consumer_EpochTransition_Call { + _c.Call.Return() + return _c +} + +func (_c *Consumer_EpochTransition_Call) RunAndReturn(run func(newEpochCounter uint64, first *flow.Header)) *Consumer_EpochTransition_Call { + _c.Run(run) + return _c } diff --git a/state/protocol/mock/dkg.go b/state/protocol/mock/dkg.go index 4de7eac9ce1..0a801974f86 100644 --- a/state/protocol/mock/dkg.go +++ b/state/protocol/mock/dkg.go @@ -1,42 +1,91 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewDKG creates a new instance of DKG. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKG(t interface { + mock.TestingT + Cleanup(func()) +}) *DKG { + mock := &DKG{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKG is an autogenerated mock type for the DKG type type DKG struct { mock.Mock } -// GroupKey provides a mock function with no fields -func (_m *DKG) GroupKey() crypto.PublicKey { - ret := _m.Called() +type DKG_Expecter struct { + mock *mock.Mock +} + +func (_m *DKG) EXPECT() *DKG_Expecter { + return &DKG_Expecter{mock: &_m.Mock} +} + +// GroupKey provides a mock function for the type DKG +func (_mock *DKG) GroupKey() crypto.PublicKey { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GroupKey") } var r0 crypto.PublicKey - if rf, ok := ret.Get(0).(func() crypto.PublicKey); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() crypto.PublicKey); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PublicKey) } } - return r0 } -// Index provides a mock function with given fields: nodeID -func (_m *DKG) Index(nodeID flow.Identifier) (uint, error) { - ret := _m.Called(nodeID) +// DKG_GroupKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GroupKey' +type DKG_GroupKey_Call struct { + *mock.Call +} + +// GroupKey is a helper method to define mock.On call +func (_e *DKG_Expecter) GroupKey() *DKG_GroupKey_Call { + return &DKG_GroupKey_Call{Call: _e.mock.On("GroupKey")} +} + +func (_c *DKG_GroupKey_Call) Run(run func()) *DKG_GroupKey_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKG_GroupKey_Call) Return(publicKey crypto.PublicKey) *DKG_GroupKey_Call { + _c.Call.Return(publicKey) + return _c +} + +func (_c *DKG_GroupKey_Call) RunAndReturn(run func() crypto.PublicKey) *DKG_GroupKey_Call { + _c.Call.Return(run) + return _c +} + +// Index provides a mock function for the type DKG +func (_mock *DKG) Index(nodeID flow.Identifier) (uint, error) { + ret := _mock.Called(nodeID) if len(ret) == 0 { panic("no return value specified for Index") @@ -44,27 +93,59 @@ func (_m *DKG) Index(nodeID flow.Identifier) (uint, error) { var r0 uint var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (uint, error)); ok { - return rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (uint, error)); ok { + return returnFunc(nodeID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) uint); ok { - r0 = rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) uint); ok { + r0 = returnFunc(nodeID) } else { r0 = ret.Get(0).(uint) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(nodeID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(nodeID) } else { r1 = ret.Error(1) } - return r0, r1 } -// KeyShare provides a mock function with given fields: nodeID -func (_m *DKG) KeyShare(nodeID flow.Identifier) (crypto.PublicKey, error) { - ret := _m.Called(nodeID) +// DKG_Index_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Index' +type DKG_Index_Call struct { + *mock.Call +} + +// Index is a helper method to define mock.On call +// - nodeID flow.Identifier +func (_e *DKG_Expecter) Index(nodeID interface{}) *DKG_Index_Call { + return &DKG_Index_Call{Call: _e.mock.On("Index", nodeID)} +} + +func (_c *DKG_Index_Call) Run(run func(nodeID flow.Identifier)) *DKG_Index_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKG_Index_Call) Return(v uint, err error) *DKG_Index_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *DKG_Index_Call) RunAndReturn(run func(nodeID flow.Identifier) (uint, error)) *DKG_Index_Call { + _c.Call.Return(run) + return _c +} + +// KeyShare provides a mock function for the type DKG +func (_mock *DKG) KeyShare(nodeID flow.Identifier) (crypto.PublicKey, error) { + ret := _mock.Called(nodeID) if len(ret) == 0 { panic("no return value specified for KeyShare") @@ -72,49 +153,107 @@ func (_m *DKG) KeyShare(nodeID flow.Identifier) (crypto.PublicKey, error) { var r0 crypto.PublicKey var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (crypto.PublicKey, error)); ok { - return rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (crypto.PublicKey, error)); ok { + return returnFunc(nodeID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) crypto.PublicKey); ok { - r0 = rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) crypto.PublicKey); ok { + r0 = returnFunc(nodeID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PublicKey) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(nodeID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(nodeID) } else { r1 = ret.Error(1) } - return r0, r1 } -// KeyShares provides a mock function with no fields -func (_m *DKG) KeyShares() []crypto.PublicKey { - ret := _m.Called() +// DKG_KeyShare_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'KeyShare' +type DKG_KeyShare_Call struct { + *mock.Call +} + +// KeyShare is a helper method to define mock.On call +// - nodeID flow.Identifier +func (_e *DKG_Expecter) KeyShare(nodeID interface{}) *DKG_KeyShare_Call { + return &DKG_KeyShare_Call{Call: _e.mock.On("KeyShare", nodeID)} +} + +func (_c *DKG_KeyShare_Call) Run(run func(nodeID flow.Identifier)) *DKG_KeyShare_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKG_KeyShare_Call) Return(publicKey crypto.PublicKey, err error) *DKG_KeyShare_Call { + _c.Call.Return(publicKey, err) + return _c +} + +func (_c *DKG_KeyShare_Call) RunAndReturn(run func(nodeID flow.Identifier) (crypto.PublicKey, error)) *DKG_KeyShare_Call { + _c.Call.Return(run) + return _c +} + +// KeyShares provides a mock function for the type DKG +func (_mock *DKG) KeyShares() []crypto.PublicKey { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for KeyShares") } var r0 []crypto.PublicKey - if rf, ok := ret.Get(0).(func() []crypto.PublicKey); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []crypto.PublicKey); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]crypto.PublicKey) } } - return r0 } -// NodeID provides a mock function with given fields: index -func (_m *DKG) NodeID(index uint) (flow.Identifier, error) { - ret := _m.Called(index) +// DKG_KeyShares_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'KeyShares' +type DKG_KeyShares_Call struct { + *mock.Call +} + +// KeyShares is a helper method to define mock.On call +func (_e *DKG_Expecter) KeyShares() *DKG_KeyShares_Call { + return &DKG_KeyShares_Call{Call: _e.mock.On("KeyShares")} +} + +func (_c *DKG_KeyShares_Call) Run(run func()) *DKG_KeyShares_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKG_KeyShares_Call) Return(publicKeys []crypto.PublicKey) *DKG_KeyShares_Call { + _c.Call.Return(publicKeys) + return _c +} + +func (_c *DKG_KeyShares_Call) RunAndReturn(run func() []crypto.PublicKey) *DKG_KeyShares_Call { + _c.Call.Return(run) + return _c +} + +// NodeID provides a mock function for the type DKG +func (_mock *DKG) NodeID(index uint) (flow.Identifier, error) { + ret := _mock.Called(index) if len(ret) == 0 { panic("no return value specified for NodeID") @@ -122,54 +261,98 @@ func (_m *DKG) NodeID(index uint) (flow.Identifier, error) { var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint) (flow.Identifier, error)); ok { - return rf(index) + if returnFunc, ok := ret.Get(0).(func(uint) (flow.Identifier, error)); ok { + return returnFunc(index) } - if rf, ok := ret.Get(0).(func(uint) flow.Identifier); ok { - r0 = rf(index) + if returnFunc, ok := ret.Get(0).(func(uint) flow.Identifier); ok { + r0 = returnFunc(index) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint) error); ok { - r1 = rf(index) + if returnFunc, ok := ret.Get(1).(func(uint) error); ok { + r1 = returnFunc(index) } else { r1 = ret.Error(1) } - return r0, r1 } -// Size provides a mock function with no fields -func (_m *DKG) Size() uint { - ret := _m.Called() +// DKG_NodeID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NodeID' +type DKG_NodeID_Call struct { + *mock.Call +} + +// NodeID is a helper method to define mock.On call +// - index uint +func (_e *DKG_Expecter) NodeID(index interface{}) *DKG_NodeID_Call { + return &DKG_NodeID_Call{Call: _e.mock.On("NodeID", index)} +} + +func (_c *DKG_NodeID_Call) Run(run func(index uint)) *DKG_NodeID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint + if args[0] != nil { + arg0 = args[0].(uint) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKG_NodeID_Call) Return(identifier flow.Identifier, err error) *DKG_NodeID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *DKG_NodeID_Call) RunAndReturn(run func(index uint) (flow.Identifier, error)) *DKG_NodeID_Call { + _c.Call.Return(run) + return _c +} + +// Size provides a mock function for the type DKG +func (_mock *DKG) Size() uint { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Size") } var r0 uint - if rf, ok := ret.Get(0).(func() uint); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint) } - return r0 } -// NewDKG creates a new instance of DKG. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKG(t interface { - mock.TestingT - Cleanup(func()) -}) *DKG { - mock := &DKG{} - mock.Mock.Test(t) +// DKG_Size_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Size' +type DKG_Size_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Size is a helper method to define mock.On call +func (_e *DKG_Expecter) Size() *DKG_Size_Call { + return &DKG_Size_Call{Call: _e.mock.On("Size")} +} - return mock +func (_c *DKG_Size_Call) Run(run func()) *DKG_Size_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DKG_Size_Call) Return(v uint) *DKG_Size_Call { + _c.Call.Return(v) + return _c +} + +func (_c *DKG_Size_Call) RunAndReturn(run func() uint) *DKG_Size_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/epoch_protocol_state.go b/state/protocol/mock/epoch_protocol_state.go index 2c045716118..7270479263e 100644 --- a/state/protocol/mock/epoch_protocol_state.go +++ b/state/protocol/mock/epoch_protocol_state.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewEpochProtocolState creates a new instance of EpochProtocolState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochProtocolState(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochProtocolState { + mock := &EpochProtocolState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EpochProtocolState is an autogenerated mock type for the EpochProtocolState type type EpochProtocolState struct { mock.Mock } -// Clustering provides a mock function with no fields -func (_m *EpochProtocolState) Clustering() (flow.ClusterList, error) { - ret := _m.Called() +type EpochProtocolState_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochProtocolState) EXPECT() *EpochProtocolState_Expecter { + return &EpochProtocolState_Expecter{mock: &_m.Mock} +} + +// Clustering provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) Clustering() (flow.ClusterList, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Clustering") @@ -24,29 +47,54 @@ func (_m *EpochProtocolState) Clustering() (flow.ClusterList, error) { var r0 flow.ClusterList var r1 error - if rf, ok := ret.Get(0).(func() (flow.ClusterList, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.ClusterList, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.ClusterList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ClusterList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.ClusterList) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// DKG provides a mock function with no fields -func (_m *EpochProtocolState) DKG() (protocol.DKG, error) { - ret := _m.Called() +// EpochProtocolState_Clustering_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clustering' +type EpochProtocolState_Clustering_Call struct { + *mock.Call +} + +// Clustering is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) Clustering() *EpochProtocolState_Clustering_Call { + return &EpochProtocolState_Clustering_Call{Call: _e.mock.On("Clustering")} +} + +func (_c *EpochProtocolState_Clustering_Call) Run(run func()) *EpochProtocolState_Clustering_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_Clustering_Call) Return(clusterList flow.ClusterList, err error) *EpochProtocolState_Clustering_Call { + _c.Call.Return(clusterList, err) + return _c +} + +func (_c *EpochProtocolState_Clustering_Call) RunAndReturn(run func() (flow.ClusterList, error)) *EpochProtocolState_Clustering_Call { + _c.Call.Return(run) + return _c +} + +// DKG provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) DKG() (protocol.DKG, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for DKG") @@ -54,228 +102,499 @@ func (_m *EpochProtocolState) DKG() (protocol.DKG, error) { var r0 protocol.DKG var r1 error - if rf, ok := ret.Get(0).(func() (protocol.DKG, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.DKG, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.DKG); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.DKG); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.DKG) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Entry provides a mock function with no fields -func (_m *EpochProtocolState) Entry() *flow.RichEpochStateEntry { - ret := _m.Called() +// EpochProtocolState_DKG_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DKG' +type EpochProtocolState_DKG_Call struct { + *mock.Call +} + +// DKG is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) DKG() *EpochProtocolState_DKG_Call { + return &EpochProtocolState_DKG_Call{Call: _e.mock.On("DKG")} +} + +func (_c *EpochProtocolState_DKG_Call) Run(run func()) *EpochProtocolState_DKG_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_DKG_Call) Return(dKG protocol.DKG, err error) *EpochProtocolState_DKG_Call { + _c.Call.Return(dKG, err) + return _c +} + +func (_c *EpochProtocolState_DKG_Call) RunAndReturn(run func() (protocol.DKG, error)) *EpochProtocolState_DKG_Call { + _c.Call.Return(run) + return _c +} + +// Entry provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) Entry() *flow.RichEpochStateEntry { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Entry") } var r0 *flow.RichEpochStateEntry - if rf, ok := ret.Get(0).(func() *flow.RichEpochStateEntry); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.RichEpochStateEntry); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.RichEpochStateEntry) } } - return r0 } -// Epoch provides a mock function with no fields -func (_m *EpochProtocolState) Epoch() uint64 { - ret := _m.Called() +// EpochProtocolState_Entry_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Entry' +type EpochProtocolState_Entry_Call struct { + *mock.Call +} + +// Entry is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) Entry() *EpochProtocolState_Entry_Call { + return &EpochProtocolState_Entry_Call{Call: _e.mock.On("Entry")} +} + +func (_c *EpochProtocolState_Entry_Call) Run(run func()) *EpochProtocolState_Entry_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_Entry_Call) Return(richEpochStateEntry *flow.RichEpochStateEntry) *EpochProtocolState_Entry_Call { + _c.Call.Return(richEpochStateEntry) + return _c +} + +func (_c *EpochProtocolState_Entry_Call) RunAndReturn(run func() *flow.RichEpochStateEntry) *EpochProtocolState_Entry_Call { + _c.Call.Return(run) + return _c +} + +// Epoch provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) Epoch() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Epoch") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// EpochCommit provides a mock function with no fields -func (_m *EpochProtocolState) EpochCommit() *flow.EpochCommit { - ret := _m.Called() +// EpochProtocolState_Epoch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Epoch' +type EpochProtocolState_Epoch_Call struct { + *mock.Call +} + +// Epoch is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) Epoch() *EpochProtocolState_Epoch_Call { + return &EpochProtocolState_Epoch_Call{Call: _e.mock.On("Epoch")} +} + +func (_c *EpochProtocolState_Epoch_Call) Run(run func()) *EpochProtocolState_Epoch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_Epoch_Call) Return(v uint64) *EpochProtocolState_Epoch_Call { + _c.Call.Return(v) + return _c +} + +func (_c *EpochProtocolState_Epoch_Call) RunAndReturn(run func() uint64) *EpochProtocolState_Epoch_Call { + _c.Call.Return(run) + return _c +} + +// EpochCommit provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) EpochCommit() *flow.EpochCommit { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochCommit") } var r0 *flow.EpochCommit - if rf, ok := ret.Get(0).(func() *flow.EpochCommit); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.EpochCommit); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.EpochCommit) } } - return r0 } -// EpochExtensions provides a mock function with no fields -func (_m *EpochProtocolState) EpochExtensions() []flow.EpochExtension { - ret := _m.Called() +// EpochProtocolState_EpochCommit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochCommit' +type EpochProtocolState_EpochCommit_Call struct { + *mock.Call +} + +// EpochCommit is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) EpochCommit() *EpochProtocolState_EpochCommit_Call { + return &EpochProtocolState_EpochCommit_Call{Call: _e.mock.On("EpochCommit")} +} + +func (_c *EpochProtocolState_EpochCommit_Call) Run(run func()) *EpochProtocolState_EpochCommit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_EpochCommit_Call) Return(epochCommit *flow.EpochCommit) *EpochProtocolState_EpochCommit_Call { + _c.Call.Return(epochCommit) + return _c +} + +func (_c *EpochProtocolState_EpochCommit_Call) RunAndReturn(run func() *flow.EpochCommit) *EpochProtocolState_EpochCommit_Call { + _c.Call.Return(run) + return _c +} + +// EpochExtensions provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) EpochExtensions() []flow.EpochExtension { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochExtensions") } var r0 []flow.EpochExtension - if rf, ok := ret.Get(0).(func() []flow.EpochExtension); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []flow.EpochExtension); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.EpochExtension) } } - return r0 } -// EpochFallbackTriggered provides a mock function with no fields -func (_m *EpochProtocolState) EpochFallbackTriggered() bool { - ret := _m.Called() +// EpochProtocolState_EpochExtensions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochExtensions' +type EpochProtocolState_EpochExtensions_Call struct { + *mock.Call +} + +// EpochExtensions is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) EpochExtensions() *EpochProtocolState_EpochExtensions_Call { + return &EpochProtocolState_EpochExtensions_Call{Call: _e.mock.On("EpochExtensions")} +} + +func (_c *EpochProtocolState_EpochExtensions_Call) Run(run func()) *EpochProtocolState_EpochExtensions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_EpochExtensions_Call) Return(epochExtensions []flow.EpochExtension) *EpochProtocolState_EpochExtensions_Call { + _c.Call.Return(epochExtensions) + return _c +} + +func (_c *EpochProtocolState_EpochExtensions_Call) RunAndReturn(run func() []flow.EpochExtension) *EpochProtocolState_EpochExtensions_Call { + _c.Call.Return(run) + return _c +} + +// EpochFallbackTriggered provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) EpochFallbackTriggered() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochFallbackTriggered") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// EpochPhase provides a mock function with no fields -func (_m *EpochProtocolState) EpochPhase() flow.EpochPhase { - ret := _m.Called() +// EpochProtocolState_EpochFallbackTriggered_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochFallbackTriggered' +type EpochProtocolState_EpochFallbackTriggered_Call struct { + *mock.Call +} + +// EpochFallbackTriggered is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) EpochFallbackTriggered() *EpochProtocolState_EpochFallbackTriggered_Call { + return &EpochProtocolState_EpochFallbackTriggered_Call{Call: _e.mock.On("EpochFallbackTriggered")} +} + +func (_c *EpochProtocolState_EpochFallbackTriggered_Call) Run(run func()) *EpochProtocolState_EpochFallbackTriggered_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_EpochFallbackTriggered_Call) Return(b bool) *EpochProtocolState_EpochFallbackTriggered_Call { + _c.Call.Return(b) + return _c +} + +func (_c *EpochProtocolState_EpochFallbackTriggered_Call) RunAndReturn(run func() bool) *EpochProtocolState_EpochFallbackTriggered_Call { + _c.Call.Return(run) + return _c +} + +// EpochPhase provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) EpochPhase() flow.EpochPhase { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochPhase") } var r0 flow.EpochPhase - if rf, ok := ret.Get(0).(func() flow.EpochPhase); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.EpochPhase); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(flow.EpochPhase) } - return r0 } -// EpochSetup provides a mock function with no fields -func (_m *EpochProtocolState) EpochSetup() *flow.EpochSetup { - ret := _m.Called() +// EpochProtocolState_EpochPhase_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochPhase' +type EpochProtocolState_EpochPhase_Call struct { + *mock.Call +} + +// EpochPhase is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) EpochPhase() *EpochProtocolState_EpochPhase_Call { + return &EpochProtocolState_EpochPhase_Call{Call: _e.mock.On("EpochPhase")} +} + +func (_c *EpochProtocolState_EpochPhase_Call) Run(run func()) *EpochProtocolState_EpochPhase_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_EpochPhase_Call) Return(epochPhase flow.EpochPhase) *EpochProtocolState_EpochPhase_Call { + _c.Call.Return(epochPhase) + return _c +} + +func (_c *EpochProtocolState_EpochPhase_Call) RunAndReturn(run func() flow.EpochPhase) *EpochProtocolState_EpochPhase_Call { + _c.Call.Return(run) + return _c +} + +// EpochSetup provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) EpochSetup() *flow.EpochSetup { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochSetup") } var r0 *flow.EpochSetup - if rf, ok := ret.Get(0).(func() *flow.EpochSetup); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.EpochSetup); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.EpochSetup) } } - return r0 } -// GlobalParams provides a mock function with no fields -func (_m *EpochProtocolState) GlobalParams() protocol.GlobalParams { - ret := _m.Called() +// EpochProtocolState_EpochSetup_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochSetup' +type EpochProtocolState_EpochSetup_Call struct { + *mock.Call +} + +// EpochSetup is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) EpochSetup() *EpochProtocolState_EpochSetup_Call { + return &EpochProtocolState_EpochSetup_Call{Call: _e.mock.On("EpochSetup")} +} + +func (_c *EpochProtocolState_EpochSetup_Call) Run(run func()) *EpochProtocolState_EpochSetup_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_EpochSetup_Call) Return(epochSetup *flow.EpochSetup) *EpochProtocolState_EpochSetup_Call { + _c.Call.Return(epochSetup) + return _c +} + +func (_c *EpochProtocolState_EpochSetup_Call) RunAndReturn(run func() *flow.EpochSetup) *EpochProtocolState_EpochSetup_Call { + _c.Call.Return(run) + return _c +} + +// GlobalParams provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) GlobalParams() protocol.GlobalParams { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GlobalParams") } var r0 protocol.GlobalParams - if rf, ok := ret.Get(0).(func() protocol.GlobalParams); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.GlobalParams); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.GlobalParams) } } - return r0 } -// Identities provides a mock function with no fields -func (_m *EpochProtocolState) Identities() flow.IdentityList { - ret := _m.Called() +// EpochProtocolState_GlobalParams_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GlobalParams' +type EpochProtocolState_GlobalParams_Call struct { + *mock.Call +} + +// GlobalParams is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) GlobalParams() *EpochProtocolState_GlobalParams_Call { + return &EpochProtocolState_GlobalParams_Call{Call: _e.mock.On("GlobalParams")} +} + +func (_c *EpochProtocolState_GlobalParams_Call) Run(run func()) *EpochProtocolState_GlobalParams_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_GlobalParams_Call) Return(globalParams protocol.GlobalParams) *EpochProtocolState_GlobalParams_Call { + _c.Call.Return(globalParams) + return _c +} + +func (_c *EpochProtocolState_GlobalParams_Call) RunAndReturn(run func() protocol.GlobalParams) *EpochProtocolState_GlobalParams_Call { + _c.Call.Return(run) + return _c +} + +// Identities provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) Identities() flow.IdentityList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Identities") } var r0 flow.IdentityList - if rf, ok := ret.Get(0).(func() flow.IdentityList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentityList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentityList) } } - return r0 } -// PreviousEpochExists provides a mock function with no fields -func (_m *EpochProtocolState) PreviousEpochExists() bool { - ret := _m.Called() +// EpochProtocolState_Identities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Identities' +type EpochProtocolState_Identities_Call struct { + *mock.Call +} + +// Identities is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) Identities() *EpochProtocolState_Identities_Call { + return &EpochProtocolState_Identities_Call{Call: _e.mock.On("Identities")} +} + +func (_c *EpochProtocolState_Identities_Call) Run(run func()) *EpochProtocolState_Identities_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_Identities_Call) Return(v flow.IdentityList) *EpochProtocolState_Identities_Call { + _c.Call.Return(v) + return _c +} + +func (_c *EpochProtocolState_Identities_Call) RunAndReturn(run func() flow.IdentityList) *EpochProtocolState_Identities_Call { + _c.Call.Return(run) + return _c +} + +// PreviousEpochExists provides a mock function for the type EpochProtocolState +func (_mock *EpochProtocolState) PreviousEpochExists() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for PreviousEpochExists") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewEpochProtocolState creates a new instance of EpochProtocolState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochProtocolState(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochProtocolState { - mock := &EpochProtocolState{} - mock.Mock.Test(t) +// EpochProtocolState_PreviousEpochExists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PreviousEpochExists' +type EpochProtocolState_PreviousEpochExists_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// PreviousEpochExists is a helper method to define mock.On call +func (_e *EpochProtocolState_Expecter) PreviousEpochExists() *EpochProtocolState_PreviousEpochExists_Call { + return &EpochProtocolState_PreviousEpochExists_Call{Call: _e.mock.On("PreviousEpochExists")} +} - return mock +func (_c *EpochProtocolState_PreviousEpochExists_Call) Run(run func()) *EpochProtocolState_PreviousEpochExists_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochProtocolState_PreviousEpochExists_Call) Return(b bool) *EpochProtocolState_PreviousEpochExists_Call { + _c.Call.Return(b) + return _c +} + +func (_c *EpochProtocolState_PreviousEpochExists_Call) RunAndReturn(run func() bool) *EpochProtocolState_PreviousEpochExists_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/epoch_query.go b/state/protocol/mock/epoch_query.go index e59fdc415aa..20c0536c8aa 100644 --- a/state/protocol/mock/epoch_query.go +++ b/state/protocol/mock/epoch_query.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - protocol "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" ) +// NewEpochQuery creates a new instance of EpochQuery. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochQuery(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochQuery { + mock := &EpochQuery{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EpochQuery is an autogenerated mock type for the EpochQuery type type EpochQuery struct { mock.Mock } -// Current provides a mock function with no fields -func (_m *EpochQuery) Current() (protocol.CommittedEpoch, error) { - ret := _m.Called() +type EpochQuery_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochQuery) EXPECT() *EpochQuery_Expecter { + return &EpochQuery_Expecter{mock: &_m.Mock} +} + +// Current provides a mock function for the type EpochQuery +func (_mock *EpochQuery) Current() (protocol.CommittedEpoch, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Current") @@ -22,29 +46,54 @@ func (_m *EpochQuery) Current() (protocol.CommittedEpoch, error) { var r0 protocol.CommittedEpoch var r1 error - if rf, ok := ret.Get(0).(func() (protocol.CommittedEpoch, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.CommittedEpoch, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.CommittedEpoch); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.CommittedEpoch); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.CommittedEpoch) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NextCommitted provides a mock function with no fields -func (_m *EpochQuery) NextCommitted() (protocol.CommittedEpoch, error) { - ret := _m.Called() +// EpochQuery_Current_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Current' +type EpochQuery_Current_Call struct { + *mock.Call +} + +// Current is a helper method to define mock.On call +func (_e *EpochQuery_Expecter) Current() *EpochQuery_Current_Call { + return &EpochQuery_Current_Call{Call: _e.mock.On("Current")} +} + +func (_c *EpochQuery_Current_Call) Run(run func()) *EpochQuery_Current_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochQuery_Current_Call) Return(committedEpoch protocol.CommittedEpoch, err error) *EpochQuery_Current_Call { + _c.Call.Return(committedEpoch, err) + return _c +} + +func (_c *EpochQuery_Current_Call) RunAndReturn(run func() (protocol.CommittedEpoch, error)) *EpochQuery_Current_Call { + _c.Call.Return(run) + return _c +} + +// NextCommitted provides a mock function for the type EpochQuery +func (_mock *EpochQuery) NextCommitted() (protocol.CommittedEpoch, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NextCommitted") @@ -52,29 +101,54 @@ func (_m *EpochQuery) NextCommitted() (protocol.CommittedEpoch, error) { var r0 protocol.CommittedEpoch var r1 error - if rf, ok := ret.Get(0).(func() (protocol.CommittedEpoch, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.CommittedEpoch, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.CommittedEpoch); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.CommittedEpoch); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.CommittedEpoch) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NextUnsafe provides a mock function with no fields -func (_m *EpochQuery) NextUnsafe() (protocol.TentativeEpoch, error) { - ret := _m.Called() +// EpochQuery_NextCommitted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NextCommitted' +type EpochQuery_NextCommitted_Call struct { + *mock.Call +} + +// NextCommitted is a helper method to define mock.On call +func (_e *EpochQuery_Expecter) NextCommitted() *EpochQuery_NextCommitted_Call { + return &EpochQuery_NextCommitted_Call{Call: _e.mock.On("NextCommitted")} +} + +func (_c *EpochQuery_NextCommitted_Call) Run(run func()) *EpochQuery_NextCommitted_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochQuery_NextCommitted_Call) Return(committedEpoch protocol.CommittedEpoch, err error) *EpochQuery_NextCommitted_Call { + _c.Call.Return(committedEpoch, err) + return _c +} + +func (_c *EpochQuery_NextCommitted_Call) RunAndReturn(run func() (protocol.CommittedEpoch, error)) *EpochQuery_NextCommitted_Call { + _c.Call.Return(run) + return _c +} + +// NextUnsafe provides a mock function for the type EpochQuery +func (_mock *EpochQuery) NextUnsafe() (protocol.TentativeEpoch, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NextUnsafe") @@ -82,29 +156,54 @@ func (_m *EpochQuery) NextUnsafe() (protocol.TentativeEpoch, error) { var r0 protocol.TentativeEpoch var r1 error - if rf, ok := ret.Get(0).(func() (protocol.TentativeEpoch, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.TentativeEpoch, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.TentativeEpoch); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.TentativeEpoch); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.TentativeEpoch) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Previous provides a mock function with no fields -func (_m *EpochQuery) Previous() (protocol.CommittedEpoch, error) { - ret := _m.Called() +// EpochQuery_NextUnsafe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NextUnsafe' +type EpochQuery_NextUnsafe_Call struct { + *mock.Call +} + +// NextUnsafe is a helper method to define mock.On call +func (_e *EpochQuery_Expecter) NextUnsafe() *EpochQuery_NextUnsafe_Call { + return &EpochQuery_NextUnsafe_Call{Call: _e.mock.On("NextUnsafe")} +} + +func (_c *EpochQuery_NextUnsafe_Call) Run(run func()) *EpochQuery_NextUnsafe_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochQuery_NextUnsafe_Call) Return(tentativeEpoch protocol.TentativeEpoch, err error) *EpochQuery_NextUnsafe_Call { + _c.Call.Return(tentativeEpoch, err) + return _c +} + +func (_c *EpochQuery_NextUnsafe_Call) RunAndReturn(run func() (protocol.TentativeEpoch, error)) *EpochQuery_NextUnsafe_Call { + _c.Call.Return(run) + return _c +} + +// Previous provides a mock function for the type EpochQuery +func (_mock *EpochQuery) Previous() (protocol.CommittedEpoch, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Previous") @@ -112,36 +211,47 @@ func (_m *EpochQuery) Previous() (protocol.CommittedEpoch, error) { var r0 protocol.CommittedEpoch var r1 error - if rf, ok := ret.Get(0).(func() (protocol.CommittedEpoch, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.CommittedEpoch, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.CommittedEpoch); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.CommittedEpoch); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.CommittedEpoch) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEpochQuery creates a new instance of EpochQuery. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochQuery(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochQuery { - mock := &EpochQuery{} - mock.Mock.Test(t) +// EpochQuery_Previous_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Previous' +type EpochQuery_Previous_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Previous is a helper method to define mock.On call +func (_e *EpochQuery_Expecter) Previous() *EpochQuery_Previous_Call { + return &EpochQuery_Previous_Call{Call: _e.mock.On("Previous")} +} - return mock +func (_c *EpochQuery_Previous_Call) Run(run func()) *EpochQuery_Previous_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *EpochQuery_Previous_Call) Return(committedEpoch protocol.CommittedEpoch, err error) *EpochQuery_Previous_Call { + _c.Call.Return(committedEpoch, err) + return _c +} + +func (_c *EpochQuery_Previous_Call) RunAndReturn(run func() (protocol.CommittedEpoch, error)) *EpochQuery_Previous_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/follower_state.go b/state/protocol/mock/follower_state.go index 4aa2c6b868a..bf9be2874f5 100644 --- a/state/protocol/mock/follower_state.go +++ b/state/protocol/mock/follower_state.go @@ -1,167 +1,398 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewFollowerState creates a new instance of FollowerState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFollowerState(t interface { + mock.TestingT + Cleanup(func()) +}) *FollowerState { + mock := &FollowerState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // FollowerState is an autogenerated mock type for the FollowerState type type FollowerState struct { mock.Mock } -// AtBlockID provides a mock function with given fields: blockID -func (_m *FollowerState) AtBlockID(blockID flow.Identifier) protocol.Snapshot { - ret := _m.Called(blockID) +type FollowerState_Expecter struct { + mock *mock.Mock +} + +func (_m *FollowerState) EXPECT() *FollowerState_Expecter { + return &FollowerState_Expecter{mock: &_m.Mock} +} + +// AtBlockID provides a mock function for the type FollowerState +func (_mock *FollowerState) AtBlockID(blockID flow.Identifier) protocol.Snapshot { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for AtBlockID") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.Snapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.Snapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// AtHeight provides a mock function with given fields: height -func (_m *FollowerState) AtHeight(height uint64) protocol.Snapshot { - ret := _m.Called(height) +// FollowerState_AtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtBlockID' +type FollowerState_AtBlockID_Call struct { + *mock.Call +} + +// AtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *FollowerState_Expecter) AtBlockID(blockID interface{}) *FollowerState_AtBlockID_Call { + return &FollowerState_AtBlockID_Call{Call: _e.mock.On("AtBlockID", blockID)} +} + +func (_c *FollowerState_AtBlockID_Call) Run(run func(blockID flow.Identifier)) *FollowerState_AtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FollowerState_AtBlockID_Call) Return(snapshot protocol.Snapshot) *FollowerState_AtBlockID_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *FollowerState_AtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) protocol.Snapshot) *FollowerState_AtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// AtHeight provides a mock function for the type FollowerState +func (_mock *FollowerState) AtHeight(height uint64) protocol.Snapshot { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for AtHeight") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func(uint64) protocol.Snapshot); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) protocol.Snapshot); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// ExtendCertified provides a mock function with given fields: ctx, certified -func (_m *FollowerState) ExtendCertified(ctx context.Context, certified *flow.CertifiedBlock) error { - ret := _m.Called(ctx, certified) +// FollowerState_AtHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtHeight' +type FollowerState_AtHeight_Call struct { + *mock.Call +} + +// AtHeight is a helper method to define mock.On call +// - height uint64 +func (_e *FollowerState_Expecter) AtHeight(height interface{}) *FollowerState_AtHeight_Call { + return &FollowerState_AtHeight_Call{Call: _e.mock.On("AtHeight", height)} +} + +func (_c *FollowerState_AtHeight_Call) Run(run func(height uint64)) *FollowerState_AtHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *FollowerState_AtHeight_Call) Return(snapshot protocol.Snapshot) *FollowerState_AtHeight_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *FollowerState_AtHeight_Call) RunAndReturn(run func(height uint64) protocol.Snapshot) *FollowerState_AtHeight_Call { + _c.Call.Return(run) + return _c +} + +// ExtendCertified provides a mock function for the type FollowerState +func (_mock *FollowerState) ExtendCertified(ctx context.Context, certified *flow.CertifiedBlock) error { + ret := _mock.Called(ctx, certified) if len(ret) == 0 { panic("no return value specified for ExtendCertified") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.CertifiedBlock) error); ok { - r0 = rf(ctx, certified) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.CertifiedBlock) error); ok { + r0 = returnFunc(ctx, certified) } else { r0 = ret.Error(0) } - return r0 } -// Final provides a mock function with no fields -func (_m *FollowerState) Final() protocol.Snapshot { - ret := _m.Called() +// FollowerState_ExtendCertified_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExtendCertified' +type FollowerState_ExtendCertified_Call struct { + *mock.Call +} + +// ExtendCertified is a helper method to define mock.On call +// - ctx context.Context +// - certified *flow.CertifiedBlock +func (_e *FollowerState_Expecter) ExtendCertified(ctx interface{}, certified interface{}) *FollowerState_ExtendCertified_Call { + return &FollowerState_ExtendCertified_Call{Call: _e.mock.On("ExtendCertified", ctx, certified)} +} + +func (_c *FollowerState_ExtendCertified_Call) Run(run func(ctx context.Context, certified *flow.CertifiedBlock)) *FollowerState_ExtendCertified_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.CertifiedBlock + if args[1] != nil { + arg1 = args[1].(*flow.CertifiedBlock) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *FollowerState_ExtendCertified_Call) Return(err error) *FollowerState_ExtendCertified_Call { + _c.Call.Return(err) + return _c +} + +func (_c *FollowerState_ExtendCertified_Call) RunAndReturn(run func(ctx context.Context, certified *flow.CertifiedBlock) error) *FollowerState_ExtendCertified_Call { + _c.Call.Return(run) + return _c +} + +// Final provides a mock function for the type FollowerState +func (_mock *FollowerState) Final() protocol.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Final") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func() protocol.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// Finalize provides a mock function with given fields: ctx, blockID -func (_m *FollowerState) Finalize(ctx context.Context, blockID flow.Identifier) error { - ret := _m.Called(ctx, blockID) +// FollowerState_Final_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Final' +type FollowerState_Final_Call struct { + *mock.Call +} + +// Final is a helper method to define mock.On call +func (_e *FollowerState_Expecter) Final() *FollowerState_Final_Call { + return &FollowerState_Final_Call{Call: _e.mock.On("Final")} +} + +func (_c *FollowerState_Final_Call) Run(run func()) *FollowerState_Final_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FollowerState_Final_Call) Return(snapshot protocol.Snapshot) *FollowerState_Final_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *FollowerState_Final_Call) RunAndReturn(run func() protocol.Snapshot) *FollowerState_Final_Call { + _c.Call.Return(run) + return _c +} + +// Finalize provides a mock function for the type FollowerState +func (_mock *FollowerState) Finalize(ctx context.Context, blockID flow.Identifier) error { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for Finalize") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) error); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) error); ok { + r0 = returnFunc(ctx, blockID) } else { r0 = ret.Error(0) } - return r0 } -// Params provides a mock function with no fields -func (_m *FollowerState) Params() protocol.Params { - ret := _m.Called() +// FollowerState_Finalize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Finalize' +type FollowerState_Finalize_Call struct { + *mock.Call +} + +// Finalize is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *FollowerState_Expecter) Finalize(ctx interface{}, blockID interface{}) *FollowerState_Finalize_Call { + return &FollowerState_Finalize_Call{Call: _e.mock.On("Finalize", ctx, blockID)} +} + +func (_c *FollowerState_Finalize_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *FollowerState_Finalize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *FollowerState_Finalize_Call) Return(err error) *FollowerState_Finalize_Call { + _c.Call.Return(err) + return _c +} + +func (_c *FollowerState_Finalize_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) error) *FollowerState_Finalize_Call { + _c.Call.Return(run) + return _c +} + +// Params provides a mock function for the type FollowerState +func (_mock *FollowerState) Params() protocol.Params { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Params") } var r0 protocol.Params - if rf, ok := ret.Get(0).(func() protocol.Params); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Params); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Params) } } - return r0 } -// Sealed provides a mock function with no fields -func (_m *FollowerState) Sealed() protocol.Snapshot { - ret := _m.Called() +// FollowerState_Params_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Params' +type FollowerState_Params_Call struct { + *mock.Call +} + +// Params is a helper method to define mock.On call +func (_e *FollowerState_Expecter) Params() *FollowerState_Params_Call { + return &FollowerState_Params_Call{Call: _e.mock.On("Params")} +} + +func (_c *FollowerState_Params_Call) Run(run func()) *FollowerState_Params_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FollowerState_Params_Call) Return(params protocol.Params) *FollowerState_Params_Call { + _c.Call.Return(params) + return _c +} + +func (_c *FollowerState_Params_Call) RunAndReturn(run func() protocol.Params) *FollowerState_Params_Call { + _c.Call.Return(run) + return _c +} + +// Sealed provides a mock function for the type FollowerState +func (_mock *FollowerState) Sealed() protocol.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Sealed") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func() protocol.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// NewFollowerState creates a new instance of FollowerState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewFollowerState(t interface { - mock.TestingT - Cleanup(func()) -}) *FollowerState { - mock := &FollowerState{} - mock.Mock.Test(t) +// FollowerState_Sealed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sealed' +type FollowerState_Sealed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Sealed is a helper method to define mock.On call +func (_e *FollowerState_Expecter) Sealed() *FollowerState_Sealed_Call { + return &FollowerState_Sealed_Call{Call: _e.mock.On("Sealed")} +} - return mock +func (_c *FollowerState_Sealed_Call) Run(run func()) *FollowerState_Sealed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FollowerState_Sealed_Call) Return(snapshot protocol.Snapshot) *FollowerState_Sealed_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *FollowerState_Sealed_Call) RunAndReturn(run func() protocol.Snapshot) *FollowerState_Sealed_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/global_params.go b/state/protocol/mock/global_params.go index 216946d5111..07ff766fdbe 100644 --- a/state/protocol/mock/global_params.go +++ b/state/protocol/mock/global_params.go @@ -1,101 +1,215 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewGlobalParams creates a new instance of GlobalParams. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGlobalParams(t interface { + mock.TestingT + Cleanup(func()) +}) *GlobalParams { + mock := &GlobalParams{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // GlobalParams is an autogenerated mock type for the GlobalParams type type GlobalParams struct { mock.Mock } -// ChainID provides a mock function with no fields -func (_m *GlobalParams) ChainID() flow.ChainID { - ret := _m.Called() +type GlobalParams_Expecter struct { + mock *mock.Mock +} + +func (_m *GlobalParams) EXPECT() *GlobalParams_Expecter { + return &GlobalParams_Expecter{mock: &_m.Mock} +} + +// ChainID provides a mock function for the type GlobalParams +func (_mock *GlobalParams) ChainID() flow.ChainID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ChainID") } var r0 flow.ChainID - if rf, ok := ret.Get(0).(func() flow.ChainID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ChainID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(flow.ChainID) } - return r0 } -// SporkID provides a mock function with no fields -func (_m *GlobalParams) SporkID() flow.Identifier { - ret := _m.Called() +// GlobalParams_ChainID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChainID' +type GlobalParams_ChainID_Call struct { + *mock.Call +} + +// ChainID is a helper method to define mock.On call +func (_e *GlobalParams_Expecter) ChainID() *GlobalParams_ChainID_Call { + return &GlobalParams_ChainID_Call{Call: _e.mock.On("ChainID")} +} + +func (_c *GlobalParams_ChainID_Call) Run(run func()) *GlobalParams_ChainID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GlobalParams_ChainID_Call) Return(chainID flow.ChainID) *GlobalParams_ChainID_Call { + _c.Call.Return(chainID) + return _c +} + +func (_c *GlobalParams_ChainID_Call) RunAndReturn(run func() flow.ChainID) *GlobalParams_ChainID_Call { + _c.Call.Return(run) + return _c +} + +// SporkID provides a mock function for the type GlobalParams +func (_mock *GlobalParams) SporkID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// SporkRootBlockHeight provides a mock function with no fields -func (_m *GlobalParams) SporkRootBlockHeight() uint64 { - ret := _m.Called() +// GlobalParams_SporkID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkID' +type GlobalParams_SporkID_Call struct { + *mock.Call +} + +// SporkID is a helper method to define mock.On call +func (_e *GlobalParams_Expecter) SporkID() *GlobalParams_SporkID_Call { + return &GlobalParams_SporkID_Call{Call: _e.mock.On("SporkID")} +} + +func (_c *GlobalParams_SporkID_Call) Run(run func()) *GlobalParams_SporkID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GlobalParams_SporkID_Call) Return(identifier flow.Identifier) *GlobalParams_SporkID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *GlobalParams_SporkID_Call) RunAndReturn(run func() flow.Identifier) *GlobalParams_SporkID_Call { + _c.Call.Return(run) + return _c +} + +// SporkRootBlockHeight provides a mock function for the type GlobalParams +func (_mock *GlobalParams) SporkRootBlockHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkRootBlockHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// SporkRootBlockView provides a mock function with no fields -func (_m *GlobalParams) SporkRootBlockView() uint64 { - ret := _m.Called() +// GlobalParams_SporkRootBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkRootBlockHeight' +type GlobalParams_SporkRootBlockHeight_Call struct { + *mock.Call +} + +// SporkRootBlockHeight is a helper method to define mock.On call +func (_e *GlobalParams_Expecter) SporkRootBlockHeight() *GlobalParams_SporkRootBlockHeight_Call { + return &GlobalParams_SporkRootBlockHeight_Call{Call: _e.mock.On("SporkRootBlockHeight")} +} + +func (_c *GlobalParams_SporkRootBlockHeight_Call) Run(run func()) *GlobalParams_SporkRootBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GlobalParams_SporkRootBlockHeight_Call) Return(v uint64) *GlobalParams_SporkRootBlockHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *GlobalParams_SporkRootBlockHeight_Call) RunAndReturn(run func() uint64) *GlobalParams_SporkRootBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// SporkRootBlockView provides a mock function for the type GlobalParams +func (_mock *GlobalParams) SporkRootBlockView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkRootBlockView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewGlobalParams creates a new instance of GlobalParams. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGlobalParams(t interface { - mock.TestingT - Cleanup(func()) -}) *GlobalParams { - mock := &GlobalParams{} - mock.Mock.Test(t) +// GlobalParams_SporkRootBlockView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkRootBlockView' +type GlobalParams_SporkRootBlockView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SporkRootBlockView is a helper method to define mock.On call +func (_e *GlobalParams_Expecter) SporkRootBlockView() *GlobalParams_SporkRootBlockView_Call { + return &GlobalParams_SporkRootBlockView_Call{Call: _e.mock.On("SporkRootBlockView")} +} - return mock +func (_c *GlobalParams_SporkRootBlockView_Call) Run(run func()) *GlobalParams_SporkRootBlockView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *GlobalParams_SporkRootBlockView_Call) Return(v uint64) *GlobalParams_SporkRootBlockView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *GlobalParams_SporkRootBlockView_Call) RunAndReturn(run func() uint64) *GlobalParams_SporkRootBlockView_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/instance_params.go b/state/protocol/mock/instance_params.go index 32fb69dbd5d..66cc7fc865f 100644 --- a/state/protocol/mock/instance_params.go +++ b/state/protocol/mock/instance_params.go @@ -1,107 +1,221 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewInstanceParams creates a new instance of InstanceParams. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewInstanceParams(t interface { + mock.TestingT + Cleanup(func()) +}) *InstanceParams { + mock := &InstanceParams{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // InstanceParams is an autogenerated mock type for the InstanceParams type type InstanceParams struct { mock.Mock } -// FinalizedRoot provides a mock function with no fields -func (_m *InstanceParams) FinalizedRoot() *flow.Header { - ret := _m.Called() +type InstanceParams_Expecter struct { + mock *mock.Mock +} + +func (_m *InstanceParams) EXPECT() *InstanceParams_Expecter { + return &InstanceParams_Expecter{mock: &_m.Mock} +} + +// FinalizedRoot provides a mock function for the type InstanceParams +func (_mock *InstanceParams) FinalizedRoot() *flow.Header { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalizedRoot") } var r0 *flow.Header - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - return r0 } -// Seal provides a mock function with no fields -func (_m *InstanceParams) Seal() *flow.Seal { - ret := _m.Called() +// InstanceParams_FinalizedRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedRoot' +type InstanceParams_FinalizedRoot_Call struct { + *mock.Call +} + +// FinalizedRoot is a helper method to define mock.On call +func (_e *InstanceParams_Expecter) FinalizedRoot() *InstanceParams_FinalizedRoot_Call { + return &InstanceParams_FinalizedRoot_Call{Call: _e.mock.On("FinalizedRoot")} +} + +func (_c *InstanceParams_FinalizedRoot_Call) Run(run func()) *InstanceParams_FinalizedRoot_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *InstanceParams_FinalizedRoot_Call) Return(header *flow.Header) *InstanceParams_FinalizedRoot_Call { + _c.Call.Return(header) + return _c +} + +func (_c *InstanceParams_FinalizedRoot_Call) RunAndReturn(run func() *flow.Header) *InstanceParams_FinalizedRoot_Call { + _c.Call.Return(run) + return _c +} + +// Seal provides a mock function for the type InstanceParams +func (_mock *InstanceParams) Seal() *flow.Seal { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Seal") } var r0 *flow.Seal - if rf, ok := ret.Get(0).(func() *flow.Seal); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Seal); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Seal) } } - return r0 } -// SealedRoot provides a mock function with no fields -func (_m *InstanceParams) SealedRoot() *flow.Header { - ret := _m.Called() +// InstanceParams_Seal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Seal' +type InstanceParams_Seal_Call struct { + *mock.Call +} + +// Seal is a helper method to define mock.On call +func (_e *InstanceParams_Expecter) Seal() *InstanceParams_Seal_Call { + return &InstanceParams_Seal_Call{Call: _e.mock.On("Seal")} +} + +func (_c *InstanceParams_Seal_Call) Run(run func()) *InstanceParams_Seal_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *InstanceParams_Seal_Call) Return(seal *flow.Seal) *InstanceParams_Seal_Call { + _c.Call.Return(seal) + return _c +} + +func (_c *InstanceParams_Seal_Call) RunAndReturn(run func() *flow.Seal) *InstanceParams_Seal_Call { + _c.Call.Return(run) + return _c +} + +// SealedRoot provides a mock function for the type InstanceParams +func (_mock *InstanceParams) SealedRoot() *flow.Header { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SealedRoot") } var r0 *flow.Header - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - return r0 } -// SporkRootBlock provides a mock function with no fields -func (_m *InstanceParams) SporkRootBlock() *flow.Block { - ret := _m.Called() +// InstanceParams_SealedRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SealedRoot' +type InstanceParams_SealedRoot_Call struct { + *mock.Call +} + +// SealedRoot is a helper method to define mock.On call +func (_e *InstanceParams_Expecter) SealedRoot() *InstanceParams_SealedRoot_Call { + return &InstanceParams_SealedRoot_Call{Call: _e.mock.On("SealedRoot")} +} + +func (_c *InstanceParams_SealedRoot_Call) Run(run func()) *InstanceParams_SealedRoot_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *InstanceParams_SealedRoot_Call) Return(header *flow.Header) *InstanceParams_SealedRoot_Call { + _c.Call.Return(header) + return _c +} + +func (_c *InstanceParams_SealedRoot_Call) RunAndReturn(run func() *flow.Header) *InstanceParams_SealedRoot_Call { + _c.Call.Return(run) + return _c +} + +// SporkRootBlock provides a mock function for the type InstanceParams +func (_mock *InstanceParams) SporkRootBlock() *flow.Block { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkRootBlock") } var r0 *flow.Block - if rf, ok := ret.Get(0).(func() *flow.Block); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Block); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - return r0 } -// NewInstanceParams creates a new instance of InstanceParams. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewInstanceParams(t interface { - mock.TestingT - Cleanup(func()) -}) *InstanceParams { - mock := &InstanceParams{} - mock.Mock.Test(t) +// InstanceParams_SporkRootBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkRootBlock' +type InstanceParams_SporkRootBlock_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SporkRootBlock is a helper method to define mock.On call +func (_e *InstanceParams_Expecter) SporkRootBlock() *InstanceParams_SporkRootBlock_Call { + return &InstanceParams_SporkRootBlock_Call{Call: _e.mock.On("SporkRootBlock")} +} - return mock +func (_c *InstanceParams_SporkRootBlock_Call) Run(run func()) *InstanceParams_SporkRootBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *InstanceParams_SporkRootBlock_Call) Return(v *flow.Block) *InstanceParams_SporkRootBlock_Call { + _c.Call.Return(v) + return _c +} + +func (_c *InstanceParams_SporkRootBlock_Call) RunAndReturn(run func() *flow.Block) *InstanceParams_SporkRootBlock_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/kv_store_reader.go b/state/protocol/mock/kv_store_reader.go index 906583507f1..5a1838f5605 100644 --- a/state/protocol/mock/kv_store_reader.go +++ b/state/protocol/mock/kv_store_reader.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewKVStoreReader creates a new instance of KVStoreReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewKVStoreReader(t interface { + mock.TestingT + Cleanup(func()) +}) *KVStoreReader { + mock := &KVStoreReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // KVStoreReader is an autogenerated mock type for the KVStoreReader type type KVStoreReader struct { mock.Mock } -// GetCadenceComponentVersion provides a mock function with no fields -func (_m *KVStoreReader) GetCadenceComponentVersion() (protocol.MagnitudeVersion, error) { - ret := _m.Called() +type KVStoreReader_Expecter struct { + mock *mock.Mock +} + +func (_m *KVStoreReader) EXPECT() *KVStoreReader_Expecter { + return &KVStoreReader_Expecter{mock: &_m.Mock} +} + +// GetCadenceComponentVersion provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetCadenceComponentVersion() (protocol.MagnitudeVersion, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetCadenceComponentVersion") @@ -24,85 +47,188 @@ func (_m *KVStoreReader) GetCadenceComponentVersion() (protocol.MagnitudeVersion var r0 protocol.MagnitudeVersion var r1 error - if rf, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.MagnitudeVersion) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCadenceComponentVersionUpgrade provides a mock function with no fields -func (_m *KVStoreReader) GetCadenceComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { - ret := _m.Called() +// KVStoreReader_GetCadenceComponentVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCadenceComponentVersion' +type KVStoreReader_GetCadenceComponentVersion_Call struct { + *mock.Call +} + +// GetCadenceComponentVersion is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetCadenceComponentVersion() *KVStoreReader_GetCadenceComponentVersion_Call { + return &KVStoreReader_GetCadenceComponentVersion_Call{Call: _e.mock.On("GetCadenceComponentVersion")} +} + +func (_c *KVStoreReader_GetCadenceComponentVersion_Call) Run(run func()) *KVStoreReader_GetCadenceComponentVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetCadenceComponentVersion_Call) Return(magnitudeVersion protocol.MagnitudeVersion, err error) *KVStoreReader_GetCadenceComponentVersion_Call { + _c.Call.Return(magnitudeVersion, err) + return _c +} + +func (_c *KVStoreReader_GetCadenceComponentVersion_Call) RunAndReturn(run func() (protocol.MagnitudeVersion, error)) *KVStoreReader_GetCadenceComponentVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetCadenceComponentVersionUpgrade provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetCadenceComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetCadenceComponentVersionUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.MagnitudeVersion] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.MagnitudeVersion]) } } - return r0 } -// GetEpochExtensionViewCount provides a mock function with no fields -func (_m *KVStoreReader) GetEpochExtensionViewCount() uint64 { - ret := _m.Called() +// KVStoreReader_GetCadenceComponentVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCadenceComponentVersionUpgrade' +type KVStoreReader_GetCadenceComponentVersionUpgrade_Call struct { + *mock.Call +} + +// GetCadenceComponentVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetCadenceComponentVersionUpgrade() *KVStoreReader_GetCadenceComponentVersionUpgrade_Call { + return &KVStoreReader_GetCadenceComponentVersionUpgrade_Call{Call: _e.mock.On("GetCadenceComponentVersionUpgrade")} +} + +func (_c *KVStoreReader_GetCadenceComponentVersionUpgrade_Call) Run(run func()) *KVStoreReader_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetCadenceComponentVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreReader_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreReader_GetCadenceComponentVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreReader_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetEpochExtensionViewCount provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetEpochExtensionViewCount() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetEpochExtensionViewCount") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetEpochStateID provides a mock function with no fields -func (_m *KVStoreReader) GetEpochStateID() flow.Identifier { - ret := _m.Called() +// KVStoreReader_GetEpochExtensionViewCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEpochExtensionViewCount' +type KVStoreReader_GetEpochExtensionViewCount_Call struct { + *mock.Call +} + +// GetEpochExtensionViewCount is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetEpochExtensionViewCount() *KVStoreReader_GetEpochExtensionViewCount_Call { + return &KVStoreReader_GetEpochExtensionViewCount_Call{Call: _e.mock.On("GetEpochExtensionViewCount")} +} + +func (_c *KVStoreReader_GetEpochExtensionViewCount_Call) Run(run func()) *KVStoreReader_GetEpochExtensionViewCount_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetEpochExtensionViewCount_Call) Return(v uint64) *KVStoreReader_GetEpochExtensionViewCount_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreReader_GetEpochExtensionViewCount_Call) RunAndReturn(run func() uint64) *KVStoreReader_GetEpochExtensionViewCount_Call { + _c.Call.Return(run) + return _c +} + +// GetEpochStateID provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetEpochStateID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetEpochStateID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// GetExecutionComponentVersion provides a mock function with no fields -func (_m *KVStoreReader) GetExecutionComponentVersion() (protocol.MagnitudeVersion, error) { - ret := _m.Called() +// KVStoreReader_GetEpochStateID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEpochStateID' +type KVStoreReader_GetEpochStateID_Call struct { + *mock.Call +} + +// GetEpochStateID is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetEpochStateID() *KVStoreReader_GetEpochStateID_Call { + return &KVStoreReader_GetEpochStateID_Call{Call: _e.mock.On("GetEpochStateID")} +} + +func (_c *KVStoreReader_GetEpochStateID_Call) Run(run func()) *KVStoreReader_GetEpochStateID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetEpochStateID_Call) Return(identifier flow.Identifier) *KVStoreReader_GetEpochStateID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *KVStoreReader_GetEpochStateID_Call) RunAndReturn(run func() flow.Identifier) *KVStoreReader_GetEpochStateID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionComponentVersion provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetExecutionComponentVersion() (protocol.MagnitudeVersion, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionComponentVersion") @@ -110,47 +236,98 @@ func (_m *KVStoreReader) GetExecutionComponentVersion() (protocol.MagnitudeVersi var r0 protocol.MagnitudeVersion var r1 error - if rf, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.MagnitudeVersion) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionComponentVersionUpgrade provides a mock function with no fields -func (_m *KVStoreReader) GetExecutionComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { - ret := _m.Called() +// KVStoreReader_GetExecutionComponentVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionComponentVersion' +type KVStoreReader_GetExecutionComponentVersion_Call struct { + *mock.Call +} + +// GetExecutionComponentVersion is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetExecutionComponentVersion() *KVStoreReader_GetExecutionComponentVersion_Call { + return &KVStoreReader_GetExecutionComponentVersion_Call{Call: _e.mock.On("GetExecutionComponentVersion")} +} + +func (_c *KVStoreReader_GetExecutionComponentVersion_Call) Run(run func()) *KVStoreReader_GetExecutionComponentVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetExecutionComponentVersion_Call) Return(magnitudeVersion protocol.MagnitudeVersion, err error) *KVStoreReader_GetExecutionComponentVersion_Call { + _c.Call.Return(magnitudeVersion, err) + return _c +} + +func (_c *KVStoreReader_GetExecutionComponentVersion_Call) RunAndReturn(run func() (protocol.MagnitudeVersion, error)) *KVStoreReader_GetExecutionComponentVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionComponentVersionUpgrade provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetExecutionComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionComponentVersionUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.MagnitudeVersion] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.MagnitudeVersion]) } } - return r0 } -// GetExecutionMeteringParameters provides a mock function with no fields -func (_m *KVStoreReader) GetExecutionMeteringParameters() (protocol.ExecutionMeteringParameters, error) { - ret := _m.Called() +// KVStoreReader_GetExecutionComponentVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionComponentVersionUpgrade' +type KVStoreReader_GetExecutionComponentVersionUpgrade_Call struct { + *mock.Call +} + +// GetExecutionComponentVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetExecutionComponentVersionUpgrade() *KVStoreReader_GetExecutionComponentVersionUpgrade_Call { + return &KVStoreReader_GetExecutionComponentVersionUpgrade_Call{Call: _e.mock.On("GetExecutionComponentVersionUpgrade")} +} + +func (_c *KVStoreReader_GetExecutionComponentVersionUpgrade_Call) Run(run func()) *KVStoreReader_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetExecutionComponentVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreReader_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreReader_GetExecutionComponentVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreReader_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionMeteringParameters provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetExecutionMeteringParameters() (protocol.ExecutionMeteringParameters, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionMeteringParameters") @@ -158,123 +335,278 @@ func (_m *KVStoreReader) GetExecutionMeteringParameters() (protocol.ExecutionMet var r0 protocol.ExecutionMeteringParameters var r1 error - if rf, ok := ret.Get(0).(func() (protocol.ExecutionMeteringParameters, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.ExecutionMeteringParameters, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.ExecutionMeteringParameters); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.ExecutionMeteringParameters); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.ExecutionMeteringParameters) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionMeteringParametersUpgrade provides a mock function with no fields -func (_m *KVStoreReader) GetExecutionMeteringParametersUpgrade() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] { - ret := _m.Called() +// KVStoreReader_GetExecutionMeteringParameters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionMeteringParameters' +type KVStoreReader_GetExecutionMeteringParameters_Call struct { + *mock.Call +} + +// GetExecutionMeteringParameters is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetExecutionMeteringParameters() *KVStoreReader_GetExecutionMeteringParameters_Call { + return &KVStoreReader_GetExecutionMeteringParameters_Call{Call: _e.mock.On("GetExecutionMeteringParameters")} +} + +func (_c *KVStoreReader_GetExecutionMeteringParameters_Call) Run(run func()) *KVStoreReader_GetExecutionMeteringParameters_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetExecutionMeteringParameters_Call) Return(executionMeteringParameters protocol.ExecutionMeteringParameters, err error) *KVStoreReader_GetExecutionMeteringParameters_Call { + _c.Call.Return(executionMeteringParameters, err) + return _c +} + +func (_c *KVStoreReader_GetExecutionMeteringParameters_Call) RunAndReturn(run func() (protocol.ExecutionMeteringParameters, error)) *KVStoreReader_GetExecutionMeteringParameters_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionMeteringParametersUpgrade provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetExecutionMeteringParametersUpgrade() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionMeteringParametersUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) } } - return r0 } -// GetFinalizationSafetyThreshold provides a mock function with no fields -func (_m *KVStoreReader) GetFinalizationSafetyThreshold() uint64 { - ret := _m.Called() +// KVStoreReader_GetExecutionMeteringParametersUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionMeteringParametersUpgrade' +type KVStoreReader_GetExecutionMeteringParametersUpgrade_Call struct { + *mock.Call +} + +// GetExecutionMeteringParametersUpgrade is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetExecutionMeteringParametersUpgrade() *KVStoreReader_GetExecutionMeteringParametersUpgrade_Call { + return &KVStoreReader_GetExecutionMeteringParametersUpgrade_Call{Call: _e.mock.On("GetExecutionMeteringParametersUpgrade")} +} + +func (_c *KVStoreReader_GetExecutionMeteringParametersUpgrade_Call) Run(run func()) *KVStoreReader_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetExecutionMeteringParametersUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) *KVStoreReader_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreReader_GetExecutionMeteringParametersUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) *KVStoreReader_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetFinalizationSafetyThreshold provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetFinalizationSafetyThreshold() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetFinalizationSafetyThreshold") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetProtocolStateVersion provides a mock function with no fields -func (_m *KVStoreReader) GetProtocolStateVersion() uint64 { - ret := _m.Called() +// KVStoreReader_GetFinalizationSafetyThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFinalizationSafetyThreshold' +type KVStoreReader_GetFinalizationSafetyThreshold_Call struct { + *mock.Call +} + +// GetFinalizationSafetyThreshold is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetFinalizationSafetyThreshold() *KVStoreReader_GetFinalizationSafetyThreshold_Call { + return &KVStoreReader_GetFinalizationSafetyThreshold_Call{Call: _e.mock.On("GetFinalizationSafetyThreshold")} +} + +func (_c *KVStoreReader_GetFinalizationSafetyThreshold_Call) Run(run func()) *KVStoreReader_GetFinalizationSafetyThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetFinalizationSafetyThreshold_Call) Return(v uint64) *KVStoreReader_GetFinalizationSafetyThreshold_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreReader_GetFinalizationSafetyThreshold_Call) RunAndReturn(run func() uint64) *KVStoreReader_GetFinalizationSafetyThreshold_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateVersion provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetProtocolStateVersion() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetProtocolStateVersion") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetVersionUpgrade provides a mock function with no fields -func (_m *KVStoreReader) GetVersionUpgrade() *protocol.ViewBasedActivator[uint64] { - ret := _m.Called() +// KVStoreReader_GetProtocolStateVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateVersion' +type KVStoreReader_GetProtocolStateVersion_Call struct { + *mock.Call +} + +// GetProtocolStateVersion is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetProtocolStateVersion() *KVStoreReader_GetProtocolStateVersion_Call { + return &KVStoreReader_GetProtocolStateVersion_Call{Call: _e.mock.On("GetProtocolStateVersion")} +} + +func (_c *KVStoreReader_GetProtocolStateVersion_Call) Run(run func()) *KVStoreReader_GetProtocolStateVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetProtocolStateVersion_Call) Return(v uint64) *KVStoreReader_GetProtocolStateVersion_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreReader_GetProtocolStateVersion_Call) RunAndReturn(run func() uint64) *KVStoreReader_GetProtocolStateVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetVersionUpgrade provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) GetVersionUpgrade() *protocol.ViewBasedActivator[uint64] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetVersionUpgrade") } var r0 *protocol.ViewBasedActivator[uint64] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[uint64]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[uint64]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[uint64]) } } - return r0 } -// ID provides a mock function with no fields -func (_m *KVStoreReader) ID() flow.Identifier { - ret := _m.Called() +// KVStoreReader_GetVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVersionUpgrade' +type KVStoreReader_GetVersionUpgrade_Call struct { + *mock.Call +} + +// GetVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) GetVersionUpgrade() *KVStoreReader_GetVersionUpgrade_Call { + return &KVStoreReader_GetVersionUpgrade_Call{Call: _e.mock.On("GetVersionUpgrade")} +} + +func (_c *KVStoreReader_GetVersionUpgrade_Call) Run(run func()) *KVStoreReader_GetVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_GetVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[uint64]) *KVStoreReader_GetVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreReader_GetVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[uint64]) *KVStoreReader_GetVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// ID provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) ID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// VersionedEncode provides a mock function with no fields -func (_m *KVStoreReader) VersionedEncode() (uint64, []byte, error) { - ret := _m.Called() +// KVStoreReader_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type KVStoreReader_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) ID() *KVStoreReader_ID_Call { + return &KVStoreReader_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *KVStoreReader_ID_Call) Run(run func()) *KVStoreReader_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_ID_Call) Return(identifier flow.Identifier) *KVStoreReader_ID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *KVStoreReader_ID_Call) RunAndReturn(run func() flow.Identifier) *KVStoreReader_ID_Call { + _c.Call.Return(run) + return _c +} + +// VersionedEncode provides a mock function for the type KVStoreReader +func (_mock *KVStoreReader) VersionedEncode() (uint64, []byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for VersionedEncode") @@ -283,42 +615,52 @@ func (_m *KVStoreReader) VersionedEncode() (uint64, []byte, error) { var r0 uint64 var r1 []byte var r2 error - if rf, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() []byte); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() []byte); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]byte) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewKVStoreReader creates a new instance of KVStoreReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewKVStoreReader(t interface { - mock.TestingT - Cleanup(func()) -}) *KVStoreReader { - mock := &KVStoreReader{} - mock.Mock.Test(t) +// KVStoreReader_VersionedEncode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VersionedEncode' +type KVStoreReader_VersionedEncode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VersionedEncode is a helper method to define mock.On call +func (_e *KVStoreReader_Expecter) VersionedEncode() *KVStoreReader_VersionedEncode_Call { + return &KVStoreReader_VersionedEncode_Call{Call: _e.mock.On("VersionedEncode")} +} - return mock +func (_c *KVStoreReader_VersionedEncode_Call) Run(run func()) *KVStoreReader_VersionedEncode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreReader_VersionedEncode_Call) Return(v uint64, bytes []byte, err error) *KVStoreReader_VersionedEncode_Call { + _c.Call.Return(v, bytes, err) + return _c +} + +func (_c *KVStoreReader_VersionedEncode_Call) RunAndReturn(run func() (uint64, []byte, error)) *KVStoreReader_VersionedEncode_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/mutable_protocol_state.go b/state/protocol/mock/mutable_protocol_state.go index b8e4423a7cd..bf0b7b1a2bb 100644 --- a/state/protocol/mock/mutable_protocol_state.go +++ b/state/protocol/mock/mutable_protocol_state.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - deferred "github.com/onflow/flow-go/storage/deferred" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage/deferred" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewMutableProtocolState creates a new instance of MutableProtocolState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMutableProtocolState(t interface { + mock.TestingT + Cleanup(func()) +}) *MutableProtocolState { + mock := &MutableProtocolState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MutableProtocolState is an autogenerated mock type for the MutableProtocolState type type MutableProtocolState struct { mock.Mock } -// EpochStateAtBlockID provides a mock function with given fields: blockID -func (_m *MutableProtocolState) EpochStateAtBlockID(blockID flow.Identifier) (protocol.EpochProtocolState, error) { - ret := _m.Called(blockID) +type MutableProtocolState_Expecter struct { + mock *mock.Mock +} + +func (_m *MutableProtocolState) EXPECT() *MutableProtocolState_Expecter { + return &MutableProtocolState_Expecter{mock: &_m.Mock} +} + +// EpochStateAtBlockID provides a mock function for the type MutableProtocolState +func (_mock *MutableProtocolState) EpochStateAtBlockID(blockID flow.Identifier) (protocol.EpochProtocolState, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for EpochStateAtBlockID") @@ -26,29 +48,61 @@ func (_m *MutableProtocolState) EpochStateAtBlockID(blockID flow.Identifier) (pr var r0 protocol.EpochProtocolState var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (protocol.EpochProtocolState, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (protocol.EpochProtocolState, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.EpochProtocolState); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.EpochProtocolState); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.EpochProtocolState) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// EvolveState provides a mock function with given fields: deferredDBOps, parentBlockID, candidateView, candidateSeals -func (_m *MutableProtocolState) EvolveState(deferredDBOps *deferred.DeferredBlockPersist, parentBlockID flow.Identifier, candidateView uint64, candidateSeals []*flow.Seal) (flow.Identifier, error) { - ret := _m.Called(deferredDBOps, parentBlockID, candidateView, candidateSeals) +// MutableProtocolState_EpochStateAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochStateAtBlockID' +type MutableProtocolState_EpochStateAtBlockID_Call struct { + *mock.Call +} + +// EpochStateAtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *MutableProtocolState_Expecter) EpochStateAtBlockID(blockID interface{}) *MutableProtocolState_EpochStateAtBlockID_Call { + return &MutableProtocolState_EpochStateAtBlockID_Call{Call: _e.mock.On("EpochStateAtBlockID", blockID)} +} + +func (_c *MutableProtocolState_EpochStateAtBlockID_Call) Run(run func(blockID flow.Identifier)) *MutableProtocolState_EpochStateAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MutableProtocolState_EpochStateAtBlockID_Call) Return(epochProtocolState protocol.EpochProtocolState, err error) *MutableProtocolState_EpochStateAtBlockID_Call { + _c.Call.Return(epochProtocolState, err) + return _c +} + +func (_c *MutableProtocolState_EpochStateAtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (protocol.EpochProtocolState, error)) *MutableProtocolState_EpochStateAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// EvolveState provides a mock function for the type MutableProtocolState +func (_mock *MutableProtocolState) EvolveState(deferredDBOps *deferred.DeferredBlockPersist, parentBlockID flow.Identifier, candidateView uint64, candidateSeals []*flow.Seal) (flow.Identifier, error) { + ret := _mock.Called(deferredDBOps, parentBlockID, candidateView, candidateSeals) if len(ret) == 0 { panic("no return value specified for EvolveState") @@ -56,49 +110,125 @@ func (_m *MutableProtocolState) EvolveState(deferredDBOps *deferred.DeferredBloc var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(*deferred.DeferredBlockPersist, flow.Identifier, uint64, []*flow.Seal) (flow.Identifier, error)); ok { - return rf(deferredDBOps, parentBlockID, candidateView, candidateSeals) + if returnFunc, ok := ret.Get(0).(func(*deferred.DeferredBlockPersist, flow.Identifier, uint64, []*flow.Seal) (flow.Identifier, error)); ok { + return returnFunc(deferredDBOps, parentBlockID, candidateView, candidateSeals) } - if rf, ok := ret.Get(0).(func(*deferred.DeferredBlockPersist, flow.Identifier, uint64, []*flow.Seal) flow.Identifier); ok { - r0 = rf(deferredDBOps, parentBlockID, candidateView, candidateSeals) + if returnFunc, ok := ret.Get(0).(func(*deferred.DeferredBlockPersist, flow.Identifier, uint64, []*flow.Seal) flow.Identifier); ok { + r0 = returnFunc(deferredDBOps, parentBlockID, candidateView, candidateSeals) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(*deferred.DeferredBlockPersist, flow.Identifier, uint64, []*flow.Seal) error); ok { - r1 = rf(deferredDBOps, parentBlockID, candidateView, candidateSeals) + if returnFunc, ok := ret.Get(1).(func(*deferred.DeferredBlockPersist, flow.Identifier, uint64, []*flow.Seal) error); ok { + r1 = returnFunc(deferredDBOps, parentBlockID, candidateView, candidateSeals) } else { r1 = ret.Error(1) } - return r0, r1 } -// GlobalParams provides a mock function with no fields -func (_m *MutableProtocolState) GlobalParams() protocol.GlobalParams { - ret := _m.Called() +// MutableProtocolState_EvolveState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EvolveState' +type MutableProtocolState_EvolveState_Call struct { + *mock.Call +} + +// EvolveState is a helper method to define mock.On call +// - deferredDBOps *deferred.DeferredBlockPersist +// - parentBlockID flow.Identifier +// - candidateView uint64 +// - candidateSeals []*flow.Seal +func (_e *MutableProtocolState_Expecter) EvolveState(deferredDBOps interface{}, parentBlockID interface{}, candidateView interface{}, candidateSeals interface{}) *MutableProtocolState_EvolveState_Call { + return &MutableProtocolState_EvolveState_Call{Call: _e.mock.On("EvolveState", deferredDBOps, parentBlockID, candidateView, candidateSeals)} +} + +func (_c *MutableProtocolState_EvolveState_Call) Run(run func(deferredDBOps *deferred.DeferredBlockPersist, parentBlockID flow.Identifier, candidateView uint64, candidateSeals []*flow.Seal)) *MutableProtocolState_EvolveState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *deferred.DeferredBlockPersist + if args[0] != nil { + arg0 = args[0].(*deferred.DeferredBlockPersist) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []*flow.Seal + if args[3] != nil { + arg3 = args[3].([]*flow.Seal) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *MutableProtocolState_EvolveState_Call) Return(stateID flow.Identifier, err error) *MutableProtocolState_EvolveState_Call { + _c.Call.Return(stateID, err) + return _c +} + +func (_c *MutableProtocolState_EvolveState_Call) RunAndReturn(run func(deferredDBOps *deferred.DeferredBlockPersist, parentBlockID flow.Identifier, candidateView uint64, candidateSeals []*flow.Seal) (flow.Identifier, error)) *MutableProtocolState_EvolveState_Call { + _c.Call.Return(run) + return _c +} + +// GlobalParams provides a mock function for the type MutableProtocolState +func (_mock *MutableProtocolState) GlobalParams() protocol.GlobalParams { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GlobalParams") } var r0 protocol.GlobalParams - if rf, ok := ret.Get(0).(func() protocol.GlobalParams); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.GlobalParams); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.GlobalParams) } } - return r0 } -// KVStoreAtBlockID provides a mock function with given fields: blockID -func (_m *MutableProtocolState) KVStoreAtBlockID(blockID flow.Identifier) (protocol.KVStoreReader, error) { - ret := _m.Called(blockID) +// MutableProtocolState_GlobalParams_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GlobalParams' +type MutableProtocolState_GlobalParams_Call struct { + *mock.Call +} + +// GlobalParams is a helper method to define mock.On call +func (_e *MutableProtocolState_Expecter) GlobalParams() *MutableProtocolState_GlobalParams_Call { + return &MutableProtocolState_GlobalParams_Call{Call: _e.mock.On("GlobalParams")} +} + +func (_c *MutableProtocolState_GlobalParams_Call) Run(run func()) *MutableProtocolState_GlobalParams_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MutableProtocolState_GlobalParams_Call) Return(globalParams protocol.GlobalParams) *MutableProtocolState_GlobalParams_Call { + _c.Call.Return(globalParams) + return _c +} + +func (_c *MutableProtocolState_GlobalParams_Call) RunAndReturn(run func() protocol.GlobalParams) *MutableProtocolState_GlobalParams_Call { + _c.Call.Return(run) + return _c +} + +// KVStoreAtBlockID provides a mock function for the type MutableProtocolState +func (_mock *MutableProtocolState) KVStoreAtBlockID(blockID flow.Identifier) (protocol.KVStoreReader, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for KVStoreAtBlockID") @@ -106,36 +236,54 @@ func (_m *MutableProtocolState) KVStoreAtBlockID(blockID flow.Identifier) (proto var r0 protocol.KVStoreReader var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (protocol.KVStoreReader, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (protocol.KVStoreReader, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.KVStoreReader); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.KVStoreReader); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.KVStoreReader) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewMutableProtocolState creates a new instance of MutableProtocolState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMutableProtocolState(t interface { - mock.TestingT - Cleanup(func()) -}) *MutableProtocolState { - mock := &MutableProtocolState{} - mock.Mock.Test(t) +// MutableProtocolState_KVStoreAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'KVStoreAtBlockID' +type MutableProtocolState_KVStoreAtBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// KVStoreAtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *MutableProtocolState_Expecter) KVStoreAtBlockID(blockID interface{}) *MutableProtocolState_KVStoreAtBlockID_Call { + return &MutableProtocolState_KVStoreAtBlockID_Call{Call: _e.mock.On("KVStoreAtBlockID", blockID)} +} - return mock +func (_c *MutableProtocolState_KVStoreAtBlockID_Call) Run(run func(blockID flow.Identifier)) *MutableProtocolState_KVStoreAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MutableProtocolState_KVStoreAtBlockID_Call) Return(kVStoreReader protocol.KVStoreReader, err error) *MutableProtocolState_KVStoreAtBlockID_Call { + _c.Call.Return(kVStoreReader, err) + return _c +} + +func (_c *MutableProtocolState_KVStoreAtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (protocol.KVStoreReader, error)) *MutableProtocolState_KVStoreAtBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/params.go b/state/protocol/mock/params.go index 8e007746636..d566479eb39 100644 --- a/state/protocol/mock/params.go +++ b/state/protocol/mock/params.go @@ -1,181 +1,399 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewParams creates a new instance of Params. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewParams(t interface { + mock.TestingT + Cleanup(func()) +}) *Params { + mock := &Params{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Params is an autogenerated mock type for the Params type type Params struct { mock.Mock } -// ChainID provides a mock function with no fields -func (_m *Params) ChainID() flow.ChainID { - ret := _m.Called() +type Params_Expecter struct { + mock *mock.Mock +} + +func (_m *Params) EXPECT() *Params_Expecter { + return &Params_Expecter{mock: &_m.Mock} +} + +// ChainID provides a mock function for the type Params +func (_mock *Params) ChainID() flow.ChainID { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ChainID") } var r0 flow.ChainID - if rf, ok := ret.Get(0).(func() flow.ChainID); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ChainID); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(flow.ChainID) } - return r0 } -// FinalizedRoot provides a mock function with no fields -func (_m *Params) FinalizedRoot() *flow.Header { - ret := _m.Called() +// Params_ChainID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ChainID' +type Params_ChainID_Call struct { + *mock.Call +} + +// ChainID is a helper method to define mock.On call +func (_e *Params_Expecter) ChainID() *Params_ChainID_Call { + return &Params_ChainID_Call{Call: _e.mock.On("ChainID")} +} + +func (_c *Params_ChainID_Call) Run(run func()) *Params_ChainID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_ChainID_Call) Return(chainID flow.ChainID) *Params_ChainID_Call { + _c.Call.Return(chainID) + return _c +} + +func (_c *Params_ChainID_Call) RunAndReturn(run func() flow.ChainID) *Params_ChainID_Call { + _c.Call.Return(run) + return _c +} + +// FinalizedRoot provides a mock function for the type Params +func (_mock *Params) FinalizedRoot() *flow.Header { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FinalizedRoot") } var r0 *flow.Header - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - return r0 } -// Seal provides a mock function with no fields -func (_m *Params) Seal() *flow.Seal { - ret := _m.Called() +// Params_FinalizedRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedRoot' +type Params_FinalizedRoot_Call struct { + *mock.Call +} + +// FinalizedRoot is a helper method to define mock.On call +func (_e *Params_Expecter) FinalizedRoot() *Params_FinalizedRoot_Call { + return &Params_FinalizedRoot_Call{Call: _e.mock.On("FinalizedRoot")} +} + +func (_c *Params_FinalizedRoot_Call) Run(run func()) *Params_FinalizedRoot_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_FinalizedRoot_Call) Return(header *flow.Header) *Params_FinalizedRoot_Call { + _c.Call.Return(header) + return _c +} + +func (_c *Params_FinalizedRoot_Call) RunAndReturn(run func() *flow.Header) *Params_FinalizedRoot_Call { + _c.Call.Return(run) + return _c +} + +// Seal provides a mock function for the type Params +func (_mock *Params) Seal() *flow.Seal { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Seal") } var r0 *flow.Seal - if rf, ok := ret.Get(0).(func() *flow.Seal); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Seal); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Seal) } } - return r0 } -// SealedRoot provides a mock function with no fields -func (_m *Params) SealedRoot() *flow.Header { - ret := _m.Called() +// Params_Seal_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Seal' +type Params_Seal_Call struct { + *mock.Call +} + +// Seal is a helper method to define mock.On call +func (_e *Params_Expecter) Seal() *Params_Seal_Call { + return &Params_Seal_Call{Call: _e.mock.On("Seal")} +} + +func (_c *Params_Seal_Call) Run(run func()) *Params_Seal_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_Seal_Call) Return(seal *flow.Seal) *Params_Seal_Call { + _c.Call.Return(seal) + return _c +} + +func (_c *Params_Seal_Call) RunAndReturn(run func() *flow.Seal) *Params_Seal_Call { + _c.Call.Return(run) + return _c +} + +// SealedRoot provides a mock function for the type Params +func (_mock *Params) SealedRoot() *flow.Header { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SealedRoot") } var r0 *flow.Header - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - return r0 } -// SporkID provides a mock function with no fields -func (_m *Params) SporkID() flow.Identifier { - ret := _m.Called() +// Params_SealedRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SealedRoot' +type Params_SealedRoot_Call struct { + *mock.Call +} + +// SealedRoot is a helper method to define mock.On call +func (_e *Params_Expecter) SealedRoot() *Params_SealedRoot_Call { + return &Params_SealedRoot_Call{Call: _e.mock.On("SealedRoot")} +} + +func (_c *Params_SealedRoot_Call) Run(run func()) *Params_SealedRoot_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_SealedRoot_Call) Return(header *flow.Header) *Params_SealedRoot_Call { + _c.Call.Return(header) + return _c +} + +func (_c *Params_SealedRoot_Call) RunAndReturn(run func() *flow.Header) *Params_SealedRoot_Call { + _c.Call.Return(run) + return _c +} + +// SporkID provides a mock function for the type Params +func (_mock *Params) SporkID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// SporkRootBlock provides a mock function with no fields -func (_m *Params) SporkRootBlock() *flow.Block { - ret := _m.Called() +// Params_SporkID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkID' +type Params_SporkID_Call struct { + *mock.Call +} + +// SporkID is a helper method to define mock.On call +func (_e *Params_Expecter) SporkID() *Params_SporkID_Call { + return &Params_SporkID_Call{Call: _e.mock.On("SporkID")} +} + +func (_c *Params_SporkID_Call) Run(run func()) *Params_SporkID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_SporkID_Call) Return(identifier flow.Identifier) *Params_SporkID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *Params_SporkID_Call) RunAndReturn(run func() flow.Identifier) *Params_SporkID_Call { + _c.Call.Return(run) + return _c +} + +// SporkRootBlock provides a mock function for the type Params +func (_mock *Params) SporkRootBlock() *flow.Block { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkRootBlock") } var r0 *flow.Block - if rf, ok := ret.Get(0).(func() *flow.Block); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Block); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - return r0 } -// SporkRootBlockHeight provides a mock function with no fields -func (_m *Params) SporkRootBlockHeight() uint64 { - ret := _m.Called() +// Params_SporkRootBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkRootBlock' +type Params_SporkRootBlock_Call struct { + *mock.Call +} + +// SporkRootBlock is a helper method to define mock.On call +func (_e *Params_Expecter) SporkRootBlock() *Params_SporkRootBlock_Call { + return &Params_SporkRootBlock_Call{Call: _e.mock.On("SporkRootBlock")} +} + +func (_c *Params_SporkRootBlock_Call) Run(run func()) *Params_SporkRootBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_SporkRootBlock_Call) Return(v *flow.Block) *Params_SporkRootBlock_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Params_SporkRootBlock_Call) RunAndReturn(run func() *flow.Block) *Params_SporkRootBlock_Call { + _c.Call.Return(run) + return _c +} + +// SporkRootBlockHeight provides a mock function for the type Params +func (_mock *Params) SporkRootBlockHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkRootBlockHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// SporkRootBlockView provides a mock function with no fields -func (_m *Params) SporkRootBlockView() uint64 { - ret := _m.Called() +// Params_SporkRootBlockHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkRootBlockHeight' +type Params_SporkRootBlockHeight_Call struct { + *mock.Call +} + +// SporkRootBlockHeight is a helper method to define mock.On call +func (_e *Params_Expecter) SporkRootBlockHeight() *Params_SporkRootBlockHeight_Call { + return &Params_SporkRootBlockHeight_Call{Call: _e.mock.On("SporkRootBlockHeight")} +} + +func (_c *Params_SporkRootBlockHeight_Call) Run(run func()) *Params_SporkRootBlockHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_SporkRootBlockHeight_Call) Return(v uint64) *Params_SporkRootBlockHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Params_SporkRootBlockHeight_Call) RunAndReturn(run func() uint64) *Params_SporkRootBlockHeight_Call { + _c.Call.Return(run) + return _c +} + +// SporkRootBlockView provides a mock function for the type Params +func (_mock *Params) SporkRootBlockView() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SporkRootBlockView") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewParams creates a new instance of Params. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewParams(t interface { - mock.TestingT - Cleanup(func()) -}) *Params { - mock := &Params{} - mock.Mock.Test(t) +// Params_SporkRootBlockView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SporkRootBlockView' +type Params_SporkRootBlockView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SporkRootBlockView is a helper method to define mock.On call +func (_e *Params_Expecter) SporkRootBlockView() *Params_SporkRootBlockView_Call { + return &Params_SporkRootBlockView_Call{Call: _e.mock.On("SporkRootBlockView")} +} - return mock +func (_c *Params_SporkRootBlockView_Call) Run(run func()) *Params_SporkRootBlockView_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Params_SporkRootBlockView_Call) Return(v uint64) *Params_SporkRootBlockView_Call { + _c.Call.Return(v) + return _c +} + +func (_c *Params_SporkRootBlockView_Call) RunAndReturn(run func() uint64) *Params_SporkRootBlockView_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/participant_state.go b/state/protocol/mock/participant_state.go index e885439723b..bd198ae2423 100644 --- a/state/protocol/mock/participant_state.go +++ b/state/protocol/mock/participant_state.go @@ -1,185 +1,455 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - context "context" + "context" - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewParticipantState creates a new instance of ParticipantState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewParticipantState(t interface { + mock.TestingT + Cleanup(func()) +}) *ParticipantState { + mock := &ParticipantState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ParticipantState is an autogenerated mock type for the ParticipantState type type ParticipantState struct { mock.Mock } -// AtBlockID provides a mock function with given fields: blockID -func (_m *ParticipantState) AtBlockID(blockID flow.Identifier) protocol.Snapshot { - ret := _m.Called(blockID) +type ParticipantState_Expecter struct { + mock *mock.Mock +} + +func (_m *ParticipantState) EXPECT() *ParticipantState_Expecter { + return &ParticipantState_Expecter{mock: &_m.Mock} +} + +// AtBlockID provides a mock function for the type ParticipantState +func (_mock *ParticipantState) AtBlockID(blockID flow.Identifier) protocol.Snapshot { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for AtBlockID") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.Snapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.Snapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// AtHeight provides a mock function with given fields: height -func (_m *ParticipantState) AtHeight(height uint64) protocol.Snapshot { - ret := _m.Called(height) +// ParticipantState_AtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtBlockID' +type ParticipantState_AtBlockID_Call struct { + *mock.Call +} + +// AtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ParticipantState_Expecter) AtBlockID(blockID interface{}) *ParticipantState_AtBlockID_Call { + return &ParticipantState_AtBlockID_Call{Call: _e.mock.On("AtBlockID", blockID)} +} + +func (_c *ParticipantState_AtBlockID_Call) Run(run func(blockID flow.Identifier)) *ParticipantState_AtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ParticipantState_AtBlockID_Call) Return(snapshot protocol.Snapshot) *ParticipantState_AtBlockID_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *ParticipantState_AtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) protocol.Snapshot) *ParticipantState_AtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// AtHeight provides a mock function for the type ParticipantState +func (_mock *ParticipantState) AtHeight(height uint64) protocol.Snapshot { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for AtHeight") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func(uint64) protocol.Snapshot); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) protocol.Snapshot); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// Extend provides a mock function with given fields: ctx, candidate -func (_m *ParticipantState) Extend(ctx context.Context, candidate *flow.Proposal) error { - ret := _m.Called(ctx, candidate) +// ParticipantState_AtHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtHeight' +type ParticipantState_AtHeight_Call struct { + *mock.Call +} + +// AtHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ParticipantState_Expecter) AtHeight(height interface{}) *ParticipantState_AtHeight_Call { + return &ParticipantState_AtHeight_Call{Call: _e.mock.On("AtHeight", height)} +} + +func (_c *ParticipantState_AtHeight_Call) Run(run func(height uint64)) *ParticipantState_AtHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ParticipantState_AtHeight_Call) Return(snapshot protocol.Snapshot) *ParticipantState_AtHeight_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *ParticipantState_AtHeight_Call) RunAndReturn(run func(height uint64) protocol.Snapshot) *ParticipantState_AtHeight_Call { + _c.Call.Return(run) + return _c +} + +// Extend provides a mock function for the type ParticipantState +func (_mock *ParticipantState) Extend(ctx context.Context, candidate *flow.Proposal) error { + ret := _mock.Called(ctx, candidate) if len(ret) == 0 { panic("no return value specified for Extend") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.Proposal) error); ok { - r0 = rf(ctx, candidate) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.Proposal) error); ok { + r0 = returnFunc(ctx, candidate) } else { r0 = ret.Error(0) } - return r0 } -// ExtendCertified provides a mock function with given fields: ctx, certified -func (_m *ParticipantState) ExtendCertified(ctx context.Context, certified *flow.CertifiedBlock) error { - ret := _m.Called(ctx, certified) +// ParticipantState_Extend_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Extend' +type ParticipantState_Extend_Call struct { + *mock.Call +} + +// Extend is a helper method to define mock.On call +// - ctx context.Context +// - candidate *flow.Proposal +func (_e *ParticipantState_Expecter) Extend(ctx interface{}, candidate interface{}) *ParticipantState_Extend_Call { + return &ParticipantState_Extend_Call{Call: _e.mock.On("Extend", ctx, candidate)} +} + +func (_c *ParticipantState_Extend_Call) Run(run func(ctx context.Context, candidate *flow.Proposal)) *ParticipantState_Extend_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.Proposal + if args[1] != nil { + arg1 = args[1].(*flow.Proposal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantState_Extend_Call) Return(err error) *ParticipantState_Extend_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ParticipantState_Extend_Call) RunAndReturn(run func(ctx context.Context, candidate *flow.Proposal) error) *ParticipantState_Extend_Call { + _c.Call.Return(run) + return _c +} + +// ExtendCertified provides a mock function for the type ParticipantState +func (_mock *ParticipantState) ExtendCertified(ctx context.Context, certified *flow.CertifiedBlock) error { + ret := _mock.Called(ctx, certified) if len(ret) == 0 { panic("no return value specified for ExtendCertified") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *flow.CertifiedBlock) error); ok { - r0 = rf(ctx, certified) + if returnFunc, ok := ret.Get(0).(func(context.Context, *flow.CertifiedBlock) error); ok { + r0 = returnFunc(ctx, certified) } else { r0 = ret.Error(0) } - return r0 } -// Final provides a mock function with no fields -func (_m *ParticipantState) Final() protocol.Snapshot { - ret := _m.Called() +// ParticipantState_ExtendCertified_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExtendCertified' +type ParticipantState_ExtendCertified_Call struct { + *mock.Call +} + +// ExtendCertified is a helper method to define mock.On call +// - ctx context.Context +// - certified *flow.CertifiedBlock +func (_e *ParticipantState_Expecter) ExtendCertified(ctx interface{}, certified interface{}) *ParticipantState_ExtendCertified_Call { + return &ParticipantState_ExtendCertified_Call{Call: _e.mock.On("ExtendCertified", ctx, certified)} +} + +func (_c *ParticipantState_ExtendCertified_Call) Run(run func(ctx context.Context, certified *flow.CertifiedBlock)) *ParticipantState_ExtendCertified_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *flow.CertifiedBlock + if args[1] != nil { + arg1 = args[1].(*flow.CertifiedBlock) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantState_ExtendCertified_Call) Return(err error) *ParticipantState_ExtendCertified_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ParticipantState_ExtendCertified_Call) RunAndReturn(run func(ctx context.Context, certified *flow.CertifiedBlock) error) *ParticipantState_ExtendCertified_Call { + _c.Call.Return(run) + return _c +} + +// Final provides a mock function for the type ParticipantState +func (_mock *ParticipantState) Final() protocol.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Final") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func() protocol.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// Finalize provides a mock function with given fields: ctx, blockID -func (_m *ParticipantState) Finalize(ctx context.Context, blockID flow.Identifier) error { - ret := _m.Called(ctx, blockID) +// ParticipantState_Final_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Final' +type ParticipantState_Final_Call struct { + *mock.Call +} + +// Final is a helper method to define mock.On call +func (_e *ParticipantState_Expecter) Final() *ParticipantState_Final_Call { + return &ParticipantState_Final_Call{Call: _e.mock.On("Final")} +} + +func (_c *ParticipantState_Final_Call) Run(run func()) *ParticipantState_Final_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ParticipantState_Final_Call) Return(snapshot protocol.Snapshot) *ParticipantState_Final_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *ParticipantState_Final_Call) RunAndReturn(run func() protocol.Snapshot) *ParticipantState_Final_Call { + _c.Call.Return(run) + return _c +} + +// Finalize provides a mock function for the type ParticipantState +func (_mock *ParticipantState) Finalize(ctx context.Context, blockID flow.Identifier) error { + ret := _mock.Called(ctx, blockID) if len(ret) == 0 { panic("no return value specified for Finalize") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, flow.Identifier) error); ok { - r0 = rf(ctx, blockID) + if returnFunc, ok := ret.Get(0).(func(context.Context, flow.Identifier) error); ok { + r0 = returnFunc(ctx, blockID) } else { r0 = ret.Error(0) } - return r0 } -// Params provides a mock function with no fields -func (_m *ParticipantState) Params() protocol.Params { - ret := _m.Called() +// ParticipantState_Finalize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Finalize' +type ParticipantState_Finalize_Call struct { + *mock.Call +} + +// Finalize is a helper method to define mock.On call +// - ctx context.Context +// - blockID flow.Identifier +func (_e *ParticipantState_Expecter) Finalize(ctx interface{}, blockID interface{}) *ParticipantState_Finalize_Call { + return &ParticipantState_Finalize_Call{Call: _e.mock.On("Finalize", ctx, blockID)} +} + +func (_c *ParticipantState_Finalize_Call) Run(run func(ctx context.Context, blockID flow.Identifier)) *ParticipantState_Finalize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ParticipantState_Finalize_Call) Return(err error) *ParticipantState_Finalize_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ParticipantState_Finalize_Call) RunAndReturn(run func(ctx context.Context, blockID flow.Identifier) error) *ParticipantState_Finalize_Call { + _c.Call.Return(run) + return _c +} + +// Params provides a mock function for the type ParticipantState +func (_mock *ParticipantState) Params() protocol.Params { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Params") } var r0 protocol.Params - if rf, ok := ret.Get(0).(func() protocol.Params); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Params); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Params) } } - return r0 } -// Sealed provides a mock function with no fields -func (_m *ParticipantState) Sealed() protocol.Snapshot { - ret := _m.Called() +// ParticipantState_Params_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Params' +type ParticipantState_Params_Call struct { + *mock.Call +} + +// Params is a helper method to define mock.On call +func (_e *ParticipantState_Expecter) Params() *ParticipantState_Params_Call { + return &ParticipantState_Params_Call{Call: _e.mock.On("Params")} +} + +func (_c *ParticipantState_Params_Call) Run(run func()) *ParticipantState_Params_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ParticipantState_Params_Call) Return(params protocol.Params) *ParticipantState_Params_Call { + _c.Call.Return(params) + return _c +} + +func (_c *ParticipantState_Params_Call) RunAndReturn(run func() protocol.Params) *ParticipantState_Params_Call { + _c.Call.Return(run) + return _c +} + +// Sealed provides a mock function for the type ParticipantState +func (_mock *ParticipantState) Sealed() protocol.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Sealed") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func() protocol.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// NewParticipantState creates a new instance of ParticipantState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewParticipantState(t interface { - mock.TestingT - Cleanup(func()) -}) *ParticipantState { - mock := &ParticipantState{} - mock.Mock.Test(t) +// ParticipantState_Sealed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sealed' +type ParticipantState_Sealed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Sealed is a helper method to define mock.On call +func (_e *ParticipantState_Expecter) Sealed() *ParticipantState_Sealed_Call { + return &ParticipantState_Sealed_Call{Call: _e.mock.On("Sealed")} +} - return mock +func (_c *ParticipantState_Sealed_Call) Run(run func()) *ParticipantState_Sealed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ParticipantState_Sealed_Call) Return(snapshot protocol.Snapshot) *ParticipantState_Sealed_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *ParticipantState_Sealed_Call) RunAndReturn(run func() protocol.Snapshot) *ParticipantState_Sealed_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/protocol_state.go b/state/protocol/mock/protocol_state.go index a7c96a112d2..9c471e20fdd 100644 --- a/state/protocol/mock/protocol_state.go +++ b/state/protocol/mock/protocol_state.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewProtocolState creates a new instance of ProtocolState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProtocolState(t interface { + mock.TestingT + Cleanup(func()) +}) *ProtocolState { + mock := &ProtocolState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ProtocolState is an autogenerated mock type for the ProtocolState type type ProtocolState struct { mock.Mock } -// EpochStateAtBlockID provides a mock function with given fields: blockID -func (_m *ProtocolState) EpochStateAtBlockID(blockID flow.Identifier) (protocol.EpochProtocolState, error) { - ret := _m.Called(blockID) +type ProtocolState_Expecter struct { + mock *mock.Mock +} + +func (_m *ProtocolState) EXPECT() *ProtocolState_Expecter { + return &ProtocolState_Expecter{mock: &_m.Mock} +} + +// EpochStateAtBlockID provides a mock function for the type ProtocolState +func (_mock *ProtocolState) EpochStateAtBlockID(blockID flow.Identifier) (protocol.EpochProtocolState, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for EpochStateAtBlockID") @@ -24,49 +47,107 @@ func (_m *ProtocolState) EpochStateAtBlockID(blockID flow.Identifier) (protocol. var r0 protocol.EpochProtocolState var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (protocol.EpochProtocolState, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (protocol.EpochProtocolState, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.EpochProtocolState); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.EpochProtocolState); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.EpochProtocolState) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GlobalParams provides a mock function with no fields -func (_m *ProtocolState) GlobalParams() protocol.GlobalParams { - ret := _m.Called() +// ProtocolState_EpochStateAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochStateAtBlockID' +type ProtocolState_EpochStateAtBlockID_Call struct { + *mock.Call +} + +// EpochStateAtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ProtocolState_Expecter) EpochStateAtBlockID(blockID interface{}) *ProtocolState_EpochStateAtBlockID_Call { + return &ProtocolState_EpochStateAtBlockID_Call{Call: _e.mock.On("EpochStateAtBlockID", blockID)} +} + +func (_c *ProtocolState_EpochStateAtBlockID_Call) Run(run func(blockID flow.Identifier)) *ProtocolState_EpochStateAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProtocolState_EpochStateAtBlockID_Call) Return(epochProtocolState protocol.EpochProtocolState, err error) *ProtocolState_EpochStateAtBlockID_Call { + _c.Call.Return(epochProtocolState, err) + return _c +} + +func (_c *ProtocolState_EpochStateAtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (protocol.EpochProtocolState, error)) *ProtocolState_EpochStateAtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// GlobalParams provides a mock function for the type ProtocolState +func (_mock *ProtocolState) GlobalParams() protocol.GlobalParams { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GlobalParams") } var r0 protocol.GlobalParams - if rf, ok := ret.Get(0).(func() protocol.GlobalParams); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.GlobalParams); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.GlobalParams) } } - return r0 } -// KVStoreAtBlockID provides a mock function with given fields: blockID -func (_m *ProtocolState) KVStoreAtBlockID(blockID flow.Identifier) (protocol.KVStoreReader, error) { - ret := _m.Called(blockID) +// ProtocolState_GlobalParams_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GlobalParams' +type ProtocolState_GlobalParams_Call struct { + *mock.Call +} + +// GlobalParams is a helper method to define mock.On call +func (_e *ProtocolState_Expecter) GlobalParams() *ProtocolState_GlobalParams_Call { + return &ProtocolState_GlobalParams_Call{Call: _e.mock.On("GlobalParams")} +} + +func (_c *ProtocolState_GlobalParams_Call) Run(run func()) *ProtocolState_GlobalParams_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ProtocolState_GlobalParams_Call) Return(globalParams protocol.GlobalParams) *ProtocolState_GlobalParams_Call { + _c.Call.Return(globalParams) + return _c +} + +func (_c *ProtocolState_GlobalParams_Call) RunAndReturn(run func() protocol.GlobalParams) *ProtocolState_GlobalParams_Call { + _c.Call.Return(run) + return _c +} + +// KVStoreAtBlockID provides a mock function for the type ProtocolState +func (_mock *ProtocolState) KVStoreAtBlockID(blockID flow.Identifier) (protocol.KVStoreReader, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for KVStoreAtBlockID") @@ -74,36 +155,54 @@ func (_m *ProtocolState) KVStoreAtBlockID(blockID flow.Identifier) (protocol.KVS var r0 protocol.KVStoreReader var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (protocol.KVStoreReader, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (protocol.KVStoreReader, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.KVStoreReader); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.KVStoreReader); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.KVStoreReader) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewProtocolState creates a new instance of ProtocolState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProtocolState(t interface { - mock.TestingT - Cleanup(func()) -}) *ProtocolState { - mock := &ProtocolState{} - mock.Mock.Test(t) +// ProtocolState_KVStoreAtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'KVStoreAtBlockID' +type ProtocolState_KVStoreAtBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// KVStoreAtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ProtocolState_Expecter) KVStoreAtBlockID(blockID interface{}) *ProtocolState_KVStoreAtBlockID_Call { + return &ProtocolState_KVStoreAtBlockID_Call{Call: _e.mock.On("KVStoreAtBlockID", blockID)} +} - return mock +func (_c *ProtocolState_KVStoreAtBlockID_Call) Run(run func(blockID flow.Identifier)) *ProtocolState_KVStoreAtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProtocolState_KVStoreAtBlockID_Call) Return(kVStoreReader protocol.KVStoreReader, err error) *ProtocolState_KVStoreAtBlockID_Call { + _c.Call.Return(kVStoreReader, err) + return _c +} + +func (_c *ProtocolState_KVStoreAtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (protocol.KVStoreReader, error)) *ProtocolState_KVStoreAtBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/snapshot.go b/state/protocol/mock/snapshot.go index bda1dcc90a9..ab7970a0ce9 100644 --- a/state/protocol/mock/snapshot.go +++ b/state/protocol/mock/snapshot.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewSnapshot creates a new instance of Snapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSnapshot(t interface { + mock.TestingT + Cleanup(func()) +}) *Snapshot { + mock := &Snapshot{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Snapshot is an autogenerated mock type for the Snapshot type type Snapshot struct { mock.Mock } -// Commit provides a mock function with no fields -func (_m *Snapshot) Commit() (flow.StateCommitment, error) { - ret := _m.Called() +type Snapshot_Expecter struct { + mock *mock.Mock +} + +func (_m *Snapshot) EXPECT() *Snapshot_Expecter { + return &Snapshot_Expecter{mock: &_m.Mock} +} + +// Commit provides a mock function for the type Snapshot +func (_mock *Snapshot) Commit() (flow.StateCommitment, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Commit") @@ -24,29 +47,54 @@ func (_m *Snapshot) Commit() (flow.StateCommitment, error) { var r0 flow.StateCommitment var r1 error - if rf, ok := ret.Get(0).(func() (flow.StateCommitment, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.StateCommitment, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.StateCommitment); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.StateCommitment); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Descendants provides a mock function with no fields -func (_m *Snapshot) Descendants() ([]flow.Identifier, error) { - ret := _m.Called() +// Snapshot_Commit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Commit' +type Snapshot_Commit_Call struct { + *mock.Call +} + +// Commit is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Commit() *Snapshot_Commit_Call { + return &Snapshot_Commit_Call{Call: _e.mock.On("Commit")} +} + +func (_c *Snapshot_Commit_Call) Run(run func()) *Snapshot_Commit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Commit_Call) Return(stateCommitment flow.StateCommitment, err error) *Snapshot_Commit_Call { + _c.Call.Return(stateCommitment, err) + return _c +} + +func (_c *Snapshot_Commit_Call) RunAndReturn(run func() (flow.StateCommitment, error)) *Snapshot_Commit_Call { + _c.Call.Return(run) + return _c +} + +// Descendants provides a mock function for the type Snapshot +func (_mock *Snapshot) Descendants() ([]flow.Identifier, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Descendants") @@ -54,29 +102,54 @@ func (_m *Snapshot) Descendants() ([]flow.Identifier, error) { var r0 []flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func() ([]flow.Identifier, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]flow.Identifier, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Identifier) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// EpochPhase provides a mock function with no fields -func (_m *Snapshot) EpochPhase() (flow.EpochPhase, error) { - ret := _m.Called() +// Snapshot_Descendants_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Descendants' +type Snapshot_Descendants_Call struct { + *mock.Call +} + +// Descendants is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Descendants() *Snapshot_Descendants_Call { + return &Snapshot_Descendants_Call{Call: _e.mock.On("Descendants")} +} + +func (_c *Snapshot_Descendants_Call) Run(run func()) *Snapshot_Descendants_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Descendants_Call) Return(identifiers []flow.Identifier, err error) *Snapshot_Descendants_Call { + _c.Call.Return(identifiers, err) + return _c +} + +func (_c *Snapshot_Descendants_Call) RunAndReturn(run func() ([]flow.Identifier, error)) *Snapshot_Descendants_Call { + _c.Call.Return(run) + return _c +} + +// EpochPhase provides a mock function for the type Snapshot +func (_mock *Snapshot) EpochPhase() (flow.EpochPhase, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochPhase") @@ -84,27 +157,52 @@ func (_m *Snapshot) EpochPhase() (flow.EpochPhase, error) { var r0 flow.EpochPhase var r1 error - if rf, ok := ret.Get(0).(func() (flow.EpochPhase, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.EpochPhase, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.EpochPhase); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.EpochPhase); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(flow.EpochPhase) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// EpochProtocolState provides a mock function with no fields -func (_m *Snapshot) EpochProtocolState() (protocol.EpochProtocolState, error) { - ret := _m.Called() +// Snapshot_EpochPhase_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochPhase' +type Snapshot_EpochPhase_Call struct { + *mock.Call +} + +// EpochPhase is a helper method to define mock.On call +func (_e *Snapshot_Expecter) EpochPhase() *Snapshot_EpochPhase_Call { + return &Snapshot_EpochPhase_Call{Call: _e.mock.On("EpochPhase")} +} + +func (_c *Snapshot_EpochPhase_Call) Run(run func()) *Snapshot_EpochPhase_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_EpochPhase_Call) Return(epochPhase flow.EpochPhase, err error) *Snapshot_EpochPhase_Call { + _c.Call.Return(epochPhase, err) + return _c +} + +func (_c *Snapshot_EpochPhase_Call) RunAndReturn(run func() (flow.EpochPhase, error)) *Snapshot_EpochPhase_Call { + _c.Call.Return(run) + return _c +} + +// EpochProtocolState provides a mock function for the type Snapshot +func (_mock *Snapshot) EpochProtocolState() (protocol.EpochProtocolState, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EpochProtocolState") @@ -112,49 +210,100 @@ func (_m *Snapshot) EpochProtocolState() (protocol.EpochProtocolState, error) { var r0 protocol.EpochProtocolState var r1 error - if rf, ok := ret.Get(0).(func() (protocol.EpochProtocolState, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.EpochProtocolState, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.EpochProtocolState); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.EpochProtocolState); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.EpochProtocolState) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Epochs provides a mock function with no fields -func (_m *Snapshot) Epochs() protocol.EpochQuery { - ret := _m.Called() +// Snapshot_EpochProtocolState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EpochProtocolState' +type Snapshot_EpochProtocolState_Call struct { + *mock.Call +} + +// EpochProtocolState is a helper method to define mock.On call +func (_e *Snapshot_Expecter) EpochProtocolState() *Snapshot_EpochProtocolState_Call { + return &Snapshot_EpochProtocolState_Call{Call: _e.mock.On("EpochProtocolState")} +} + +func (_c *Snapshot_EpochProtocolState_Call) Run(run func()) *Snapshot_EpochProtocolState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_EpochProtocolState_Call) Return(epochProtocolState protocol.EpochProtocolState, err error) *Snapshot_EpochProtocolState_Call { + _c.Call.Return(epochProtocolState, err) + return _c +} + +func (_c *Snapshot_EpochProtocolState_Call) RunAndReturn(run func() (protocol.EpochProtocolState, error)) *Snapshot_EpochProtocolState_Call { + _c.Call.Return(run) + return _c +} + +// Epochs provides a mock function for the type Snapshot +func (_mock *Snapshot) Epochs() protocol.EpochQuery { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Epochs") } var r0 protocol.EpochQuery - if rf, ok := ret.Get(0).(func() protocol.EpochQuery); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.EpochQuery); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.EpochQuery) } } - return r0 } -// Head provides a mock function with no fields -func (_m *Snapshot) Head() (*flow.Header, error) { - ret := _m.Called() +// Snapshot_Epochs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Epochs' +type Snapshot_Epochs_Call struct { + *mock.Call +} + +// Epochs is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Epochs() *Snapshot_Epochs_Call { + return &Snapshot_Epochs_Call{Call: _e.mock.On("Epochs")} +} + +func (_c *Snapshot_Epochs_Call) Run(run func()) *Snapshot_Epochs_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Epochs_Call) Return(epochQuery protocol.EpochQuery) *Snapshot_Epochs_Call { + _c.Call.Return(epochQuery) + return _c +} + +func (_c *Snapshot_Epochs_Call) RunAndReturn(run func() protocol.EpochQuery) *Snapshot_Epochs_Call { + _c.Call.Return(run) + return _c +} + +// Head provides a mock function for the type Snapshot +func (_mock *Snapshot) Head() (*flow.Header, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Head") @@ -162,29 +311,54 @@ func (_m *Snapshot) Head() (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func() (*flow.Header, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.Header, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.Header); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.Header); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Identities provides a mock function with given fields: selector -func (_m *Snapshot) Identities(selector flow.IdentityFilter[flow.Identity]) (flow.IdentityList, error) { - ret := _m.Called(selector) +// Snapshot_Head_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Head' +type Snapshot_Head_Call struct { + *mock.Call +} + +// Head is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Head() *Snapshot_Head_Call { + return &Snapshot_Head_Call{Call: _e.mock.On("Head")} +} + +func (_c *Snapshot_Head_Call) Run(run func()) *Snapshot_Head_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Head_Call) Return(header *flow.Header, err error) *Snapshot_Head_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Snapshot_Head_Call) RunAndReturn(run func() (*flow.Header, error)) *Snapshot_Head_Call { + _c.Call.Return(run) + return _c +} + +// Identities provides a mock function for the type Snapshot +func (_mock *Snapshot) Identities(selector flow.IdentityFilter[flow.Identity]) (flow.IdentityList, error) { + ret := _mock.Called(selector) if len(ret) == 0 { panic("no return value specified for Identities") @@ -192,29 +366,61 @@ func (_m *Snapshot) Identities(selector flow.IdentityFilter[flow.Identity]) (flo var r0 flow.IdentityList var r1 error - if rf, ok := ret.Get(0).(func(flow.IdentityFilter[flow.Identity]) (flow.IdentityList, error)); ok { - return rf(selector) + if returnFunc, ok := ret.Get(0).(func(flow.IdentityFilter[flow.Identity]) (flow.IdentityList, error)); ok { + return returnFunc(selector) } - if rf, ok := ret.Get(0).(func(flow.IdentityFilter[flow.Identity]) flow.IdentityList); ok { - r0 = rf(selector) + if returnFunc, ok := ret.Get(0).(func(flow.IdentityFilter[flow.Identity]) flow.IdentityList); ok { + r0 = returnFunc(selector) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentityList) } } - - if rf, ok := ret.Get(1).(func(flow.IdentityFilter[flow.Identity]) error); ok { - r1 = rf(selector) + if returnFunc, ok := ret.Get(1).(func(flow.IdentityFilter[flow.Identity]) error); ok { + r1 = returnFunc(selector) } else { r1 = ret.Error(1) } - return r0, r1 } -// Identity provides a mock function with given fields: nodeID -func (_m *Snapshot) Identity(nodeID flow.Identifier) (*flow.Identity, error) { - ret := _m.Called(nodeID) +// Snapshot_Identities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Identities' +type Snapshot_Identities_Call struct { + *mock.Call +} + +// Identities is a helper method to define mock.On call +// - selector flow.IdentityFilter[flow.Identity] +func (_e *Snapshot_Expecter) Identities(selector interface{}) *Snapshot_Identities_Call { + return &Snapshot_Identities_Call{Call: _e.mock.On("Identities", selector)} +} + +func (_c *Snapshot_Identities_Call) Run(run func(selector flow.IdentityFilter[flow.Identity])) *Snapshot_Identities_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.IdentityFilter[flow.Identity] + if args[0] != nil { + arg0 = args[0].(flow.IdentityFilter[flow.Identity]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Snapshot_Identities_Call) Return(v flow.IdentityList, err error) *Snapshot_Identities_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Snapshot_Identities_Call) RunAndReturn(run func(selector flow.IdentityFilter[flow.Identity]) (flow.IdentityList, error)) *Snapshot_Identities_Call { + _c.Call.Return(run) + return _c +} + +// Identity provides a mock function for the type Snapshot +func (_mock *Snapshot) Identity(nodeID flow.Identifier) (*flow.Identity, error) { + ret := _mock.Called(nodeID) if len(ret) == 0 { panic("no return value specified for Identity") @@ -222,49 +428,107 @@ func (_m *Snapshot) Identity(nodeID flow.Identifier) (*flow.Identity, error) { var r0 *flow.Identity var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Identity, error)); ok { - return rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Identity, error)); ok { + return returnFunc(nodeID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Identity); ok { - r0 = rf(nodeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Identity); ok { + r0 = returnFunc(nodeID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Identity) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(nodeID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(nodeID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Params provides a mock function with no fields -func (_m *Snapshot) Params() protocol.GlobalParams { - ret := _m.Called() +// Snapshot_Identity_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Identity' +type Snapshot_Identity_Call struct { + *mock.Call +} + +// Identity is a helper method to define mock.On call +// - nodeID flow.Identifier +func (_e *Snapshot_Expecter) Identity(nodeID interface{}) *Snapshot_Identity_Call { + return &Snapshot_Identity_Call{Call: _e.mock.On("Identity", nodeID)} +} + +func (_c *Snapshot_Identity_Call) Run(run func(nodeID flow.Identifier)) *Snapshot_Identity_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Snapshot_Identity_Call) Return(identity *flow.Identity, err error) *Snapshot_Identity_Call { + _c.Call.Return(identity, err) + return _c +} + +func (_c *Snapshot_Identity_Call) RunAndReturn(run func(nodeID flow.Identifier) (*flow.Identity, error)) *Snapshot_Identity_Call { + _c.Call.Return(run) + return _c +} + +// Params provides a mock function for the type Snapshot +func (_mock *Snapshot) Params() protocol.GlobalParams { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Params") } var r0 protocol.GlobalParams - if rf, ok := ret.Get(0).(func() protocol.GlobalParams); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.GlobalParams); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.GlobalParams) } } - return r0 } -// ProtocolState provides a mock function with no fields -func (_m *Snapshot) ProtocolState() (protocol.KVStoreReader, error) { - ret := _m.Called() +// Snapshot_Params_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Params' +type Snapshot_Params_Call struct { + *mock.Call +} + +// Params is a helper method to define mock.On call +func (_e *Snapshot_Expecter) Params() *Snapshot_Params_Call { + return &Snapshot_Params_Call{Call: _e.mock.On("Params")} +} + +func (_c *Snapshot_Params_Call) Run(run func()) *Snapshot_Params_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_Params_Call) Return(globalParams protocol.GlobalParams) *Snapshot_Params_Call { + _c.Call.Return(globalParams) + return _c +} + +func (_c *Snapshot_Params_Call) RunAndReturn(run func() protocol.GlobalParams) *Snapshot_Params_Call { + _c.Call.Return(run) + return _c +} + +// ProtocolState provides a mock function for the type Snapshot +func (_mock *Snapshot) ProtocolState() (protocol.KVStoreReader, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ProtocolState") @@ -272,29 +536,54 @@ func (_m *Snapshot) ProtocolState() (protocol.KVStoreReader, error) { var r0 protocol.KVStoreReader var r1 error - if rf, ok := ret.Get(0).(func() (protocol.KVStoreReader, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.KVStoreReader, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.KVStoreReader); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.KVStoreReader); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.KVStoreReader) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// QuorumCertificate provides a mock function with no fields -func (_m *Snapshot) QuorumCertificate() (*flow.QuorumCertificate, error) { - ret := _m.Called() +// Snapshot_ProtocolState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProtocolState' +type Snapshot_ProtocolState_Call struct { + *mock.Call +} + +// ProtocolState is a helper method to define mock.On call +func (_e *Snapshot_Expecter) ProtocolState() *Snapshot_ProtocolState_Call { + return &Snapshot_ProtocolState_Call{Call: _e.mock.On("ProtocolState")} +} + +func (_c *Snapshot_ProtocolState_Call) Run(run func()) *Snapshot_ProtocolState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_ProtocolState_Call) Return(kVStoreReader protocol.KVStoreReader, err error) *Snapshot_ProtocolState_Call { + _c.Call.Return(kVStoreReader, err) + return _c +} + +func (_c *Snapshot_ProtocolState_Call) RunAndReturn(run func() (protocol.KVStoreReader, error)) *Snapshot_ProtocolState_Call { + _c.Call.Return(run) + return _c +} + +// QuorumCertificate provides a mock function for the type Snapshot +func (_mock *Snapshot) QuorumCertificate() (*flow.QuorumCertificate, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for QuorumCertificate") @@ -302,29 +591,54 @@ func (_m *Snapshot) QuorumCertificate() (*flow.QuorumCertificate, error) { var r0 *flow.QuorumCertificate var r1 error - if rf, ok := ret.Get(0).(func() (*flow.QuorumCertificate, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.QuorumCertificate, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.QuorumCertificate); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.QuorumCertificate); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.QuorumCertificate) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// RandomSource provides a mock function with no fields -func (_m *Snapshot) RandomSource() ([]byte, error) { - ret := _m.Called() +// Snapshot_QuorumCertificate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QuorumCertificate' +type Snapshot_QuorumCertificate_Call struct { + *mock.Call +} + +// QuorumCertificate is a helper method to define mock.On call +func (_e *Snapshot_Expecter) QuorumCertificate() *Snapshot_QuorumCertificate_Call { + return &Snapshot_QuorumCertificate_Call{Call: _e.mock.On("QuorumCertificate")} +} + +func (_c *Snapshot_QuorumCertificate_Call) Run(run func()) *Snapshot_QuorumCertificate_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_QuorumCertificate_Call) Return(quorumCertificate *flow.QuorumCertificate, err error) *Snapshot_QuorumCertificate_Call { + _c.Call.Return(quorumCertificate, err) + return _c +} + +func (_c *Snapshot_QuorumCertificate_Call) RunAndReturn(run func() (*flow.QuorumCertificate, error)) *Snapshot_QuorumCertificate_Call { + _c.Call.Return(run) + return _c +} + +// RandomSource provides a mock function for the type Snapshot +func (_mock *Snapshot) RandomSource() ([]byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RandomSource") @@ -332,29 +646,54 @@ func (_m *Snapshot) RandomSource() ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func() ([]byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// SealedResult provides a mock function with no fields -func (_m *Snapshot) SealedResult() (*flow.ExecutionResult, *flow.Seal, error) { - ret := _m.Called() +// Snapshot_RandomSource_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RandomSource' +type Snapshot_RandomSource_Call struct { + *mock.Call +} + +// RandomSource is a helper method to define mock.On call +func (_e *Snapshot_Expecter) RandomSource() *Snapshot_RandomSource_Call { + return &Snapshot_RandomSource_Call{Call: _e.mock.On("RandomSource")} +} + +func (_c *Snapshot_RandomSource_Call) Run(run func()) *Snapshot_RandomSource_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_RandomSource_Call) Return(bytes []byte, err error) *Snapshot_RandomSource_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Snapshot_RandomSource_Call) RunAndReturn(run func() ([]byte, error)) *Snapshot_RandomSource_Call { + _c.Call.Return(run) + return _c +} + +// SealedResult provides a mock function for the type Snapshot +func (_mock *Snapshot) SealedResult() (*flow.ExecutionResult, *flow.Seal, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SealedResult") @@ -363,37 +702,61 @@ func (_m *Snapshot) SealedResult() (*flow.ExecutionResult, *flow.Seal, error) { var r0 *flow.ExecutionResult var r1 *flow.Seal var r2 error - if rf, ok := ret.Get(0).(func() (*flow.ExecutionResult, *flow.Seal, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.ExecutionResult, *flow.Seal, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.ExecutionResult); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.ExecutionResult); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func() *flow.Seal); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() *flow.Seal); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*flow.Seal) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SealingSegment provides a mock function with no fields -func (_m *Snapshot) SealingSegment() (*flow.SealingSegment, error) { - ret := _m.Called() +// Snapshot_SealedResult_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SealedResult' +type Snapshot_SealedResult_Call struct { + *mock.Call +} + +// SealedResult is a helper method to define mock.On call +func (_e *Snapshot_Expecter) SealedResult() *Snapshot_SealedResult_Call { + return &Snapshot_SealedResult_Call{Call: _e.mock.On("SealedResult")} +} + +func (_c *Snapshot_SealedResult_Call) Run(run func()) *Snapshot_SealedResult_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_SealedResult_Call) Return(executionResult *flow.ExecutionResult, seal *flow.Seal, err error) *Snapshot_SealedResult_Call { + _c.Call.Return(executionResult, seal, err) + return _c +} + +func (_c *Snapshot_SealedResult_Call) RunAndReturn(run func() (*flow.ExecutionResult, *flow.Seal, error)) *Snapshot_SealedResult_Call { + _c.Call.Return(run) + return _c +} + +// SealingSegment provides a mock function for the type Snapshot +func (_mock *Snapshot) SealingSegment() (*flow.SealingSegment, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for SealingSegment") @@ -401,29 +764,54 @@ func (_m *Snapshot) SealingSegment() (*flow.SealingSegment, error) { var r0 *flow.SealingSegment var r1 error - if rf, ok := ret.Get(0).(func() (*flow.SealingSegment, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.SealingSegment, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.SealingSegment); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.SealingSegment); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.SealingSegment) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// VersionBeacon provides a mock function with no fields -func (_m *Snapshot) VersionBeacon() (*flow.SealedVersionBeacon, error) { - ret := _m.Called() +// Snapshot_SealingSegment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SealingSegment' +type Snapshot_SealingSegment_Call struct { + *mock.Call +} + +// SealingSegment is a helper method to define mock.On call +func (_e *Snapshot_Expecter) SealingSegment() *Snapshot_SealingSegment_Call { + return &Snapshot_SealingSegment_Call{Call: _e.mock.On("SealingSegment")} +} + +func (_c *Snapshot_SealingSegment_Call) Run(run func()) *Snapshot_SealingSegment_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_SealingSegment_Call) Return(sealingSegment *flow.SealingSegment, err error) *Snapshot_SealingSegment_Call { + _c.Call.Return(sealingSegment, err) + return _c +} + +func (_c *Snapshot_SealingSegment_Call) RunAndReturn(run func() (*flow.SealingSegment, error)) *Snapshot_SealingSegment_Call { + _c.Call.Return(run) + return _c +} + +// VersionBeacon provides a mock function for the type Snapshot +func (_mock *Snapshot) VersionBeacon() (*flow.SealedVersionBeacon, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for VersionBeacon") @@ -431,36 +819,47 @@ func (_m *Snapshot) VersionBeacon() (*flow.SealedVersionBeacon, error) { var r0 *flow.SealedVersionBeacon var r1 error - if rf, ok := ret.Get(0).(func() (*flow.SealedVersionBeacon, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.SealedVersionBeacon, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.SealedVersionBeacon); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.SealedVersionBeacon); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.SealedVersionBeacon) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSnapshot creates a new instance of Snapshot. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSnapshot(t interface { - mock.TestingT - Cleanup(func()) -}) *Snapshot { - mock := &Snapshot{} - mock.Mock.Test(t) +// Snapshot_VersionBeacon_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VersionBeacon' +type Snapshot_VersionBeacon_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VersionBeacon is a helper method to define mock.On call +func (_e *Snapshot_Expecter) VersionBeacon() *Snapshot_VersionBeacon_Call { + return &Snapshot_VersionBeacon_Call{Call: _e.mock.On("VersionBeacon")} +} - return mock +func (_c *Snapshot_VersionBeacon_Call) Run(run func()) *Snapshot_VersionBeacon_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Snapshot_VersionBeacon_Call) Return(sealedVersionBeacon *flow.SealedVersionBeacon, err error) *Snapshot_VersionBeacon_Call { + _c.Call.Return(sealedVersionBeacon, err) + return _c +} + +func (_c *Snapshot_VersionBeacon_Call) RunAndReturn(run func() (*flow.SealedVersionBeacon, error)) *Snapshot_VersionBeacon_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/snapshot_execution_subset.go b/state/protocol/mock/snapshot_execution_subset.go index 70890194cc7..8335da4aa19 100644 --- a/state/protocol/mock/snapshot_execution_subset.go +++ b/state/protocol/mock/snapshot_execution_subset.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSnapshotExecutionSubset creates a new instance of SnapshotExecutionSubset. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSnapshotExecutionSubset(t interface { + mock.TestingT + Cleanup(func()) +}) *SnapshotExecutionSubset { + mock := &SnapshotExecutionSubset{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SnapshotExecutionSubset is an autogenerated mock type for the SnapshotExecutionSubset type type SnapshotExecutionSubset struct { mock.Mock } -// RandomSource provides a mock function with no fields -func (_m *SnapshotExecutionSubset) RandomSource() ([]byte, error) { - ret := _m.Called() +type SnapshotExecutionSubset_Expecter struct { + mock *mock.Mock +} + +func (_m *SnapshotExecutionSubset) EXPECT() *SnapshotExecutionSubset_Expecter { + return &SnapshotExecutionSubset_Expecter{mock: &_m.Mock} +} + +// RandomSource provides a mock function for the type SnapshotExecutionSubset +func (_mock *SnapshotExecutionSubset) RandomSource() ([]byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for RandomSource") @@ -22,29 +46,54 @@ func (_m *SnapshotExecutionSubset) RandomSource() ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func() ([]byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// VersionBeacon provides a mock function with no fields -func (_m *SnapshotExecutionSubset) VersionBeacon() (*flow.SealedVersionBeacon, error) { - ret := _m.Called() +// SnapshotExecutionSubset_RandomSource_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RandomSource' +type SnapshotExecutionSubset_RandomSource_Call struct { + *mock.Call +} + +// RandomSource is a helper method to define mock.On call +func (_e *SnapshotExecutionSubset_Expecter) RandomSource() *SnapshotExecutionSubset_RandomSource_Call { + return &SnapshotExecutionSubset_RandomSource_Call{Call: _e.mock.On("RandomSource")} +} + +func (_c *SnapshotExecutionSubset_RandomSource_Call) Run(run func()) *SnapshotExecutionSubset_RandomSource_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SnapshotExecutionSubset_RandomSource_Call) Return(bytes []byte, err error) *SnapshotExecutionSubset_RandomSource_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *SnapshotExecutionSubset_RandomSource_Call) RunAndReturn(run func() ([]byte, error)) *SnapshotExecutionSubset_RandomSource_Call { + _c.Call.Return(run) + return _c +} + +// VersionBeacon provides a mock function for the type SnapshotExecutionSubset +func (_mock *SnapshotExecutionSubset) VersionBeacon() (*flow.SealedVersionBeacon, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for VersionBeacon") @@ -52,36 +101,47 @@ func (_m *SnapshotExecutionSubset) VersionBeacon() (*flow.SealedVersionBeacon, e var r0 *flow.SealedVersionBeacon var r1 error - if rf, ok := ret.Get(0).(func() (*flow.SealedVersionBeacon, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.SealedVersionBeacon, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.SealedVersionBeacon); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.SealedVersionBeacon); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.SealedVersionBeacon) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSnapshotExecutionSubset creates a new instance of SnapshotExecutionSubset. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSnapshotExecutionSubset(t interface { - mock.TestingT - Cleanup(func()) -}) *SnapshotExecutionSubset { - mock := &SnapshotExecutionSubset{} - mock.Mock.Test(t) +// SnapshotExecutionSubset_VersionBeacon_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VersionBeacon' +type SnapshotExecutionSubset_VersionBeacon_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VersionBeacon is a helper method to define mock.On call +func (_e *SnapshotExecutionSubset_Expecter) VersionBeacon() *SnapshotExecutionSubset_VersionBeacon_Call { + return &SnapshotExecutionSubset_VersionBeacon_Call{Call: _e.mock.On("VersionBeacon")} +} - return mock +func (_c *SnapshotExecutionSubset_VersionBeacon_Call) Run(run func()) *SnapshotExecutionSubset_VersionBeacon_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *SnapshotExecutionSubset_VersionBeacon_Call) Return(sealedVersionBeacon *flow.SealedVersionBeacon, err error) *SnapshotExecutionSubset_VersionBeacon_Call { + _c.Call.Return(sealedVersionBeacon, err) + return _c +} + +func (_c *SnapshotExecutionSubset_VersionBeacon_Call) RunAndReturn(run func() (*flow.SealedVersionBeacon, error)) *SnapshotExecutionSubset_VersionBeacon_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/snapshot_execution_subset_provider.go b/state/protocol/mock/snapshot_execution_subset_provider.go index 3b62ea57611..c88c7f5a8d6 100644 --- a/state/protocol/mock/snapshot_execution_subset_provider.go +++ b/state/protocol/mock/snapshot_execution_subset_provider.go @@ -1,49 +1,91 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewSnapshotExecutionSubsetProvider creates a new instance of SnapshotExecutionSubsetProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSnapshotExecutionSubsetProvider(t interface { + mock.TestingT + Cleanup(func()) +}) *SnapshotExecutionSubsetProvider { + mock := &SnapshotExecutionSubsetProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SnapshotExecutionSubsetProvider is an autogenerated mock type for the SnapshotExecutionSubsetProvider type type SnapshotExecutionSubsetProvider struct { mock.Mock } -// AtBlockID provides a mock function with given fields: blockID -func (_m *SnapshotExecutionSubsetProvider) AtBlockID(blockID flow.Identifier) protocol.SnapshotExecutionSubset { - ret := _m.Called(blockID) +type SnapshotExecutionSubsetProvider_Expecter struct { + mock *mock.Mock +} + +func (_m *SnapshotExecutionSubsetProvider) EXPECT() *SnapshotExecutionSubsetProvider_Expecter { + return &SnapshotExecutionSubsetProvider_Expecter{mock: &_m.Mock} +} + +// AtBlockID provides a mock function for the type SnapshotExecutionSubsetProvider +func (_mock *SnapshotExecutionSubsetProvider) AtBlockID(blockID flow.Identifier) protocol.SnapshotExecutionSubset { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for AtBlockID") } var r0 protocol.SnapshotExecutionSubset - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.SnapshotExecutionSubset); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.SnapshotExecutionSubset); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.SnapshotExecutionSubset) } } - return r0 } -// NewSnapshotExecutionSubsetProvider creates a new instance of SnapshotExecutionSubsetProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSnapshotExecutionSubsetProvider(t interface { - mock.TestingT - Cleanup(func()) -}) *SnapshotExecutionSubsetProvider { - mock := &SnapshotExecutionSubsetProvider{} - mock.Mock.Test(t) +// SnapshotExecutionSubsetProvider_AtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtBlockID' +type SnapshotExecutionSubsetProvider_AtBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// AtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *SnapshotExecutionSubsetProvider_Expecter) AtBlockID(blockID interface{}) *SnapshotExecutionSubsetProvider_AtBlockID_Call { + return &SnapshotExecutionSubsetProvider_AtBlockID_Call{Call: _e.mock.On("AtBlockID", blockID)} +} - return mock +func (_c *SnapshotExecutionSubsetProvider_AtBlockID_Call) Run(run func(blockID flow.Identifier)) *SnapshotExecutionSubsetProvider_AtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SnapshotExecutionSubsetProvider_AtBlockID_Call) Return(snapshotExecutionSubset protocol.SnapshotExecutionSubset) *SnapshotExecutionSubsetProvider_AtBlockID_Call { + _c.Call.Return(snapshotExecutionSubset) + return _c +} + +func (_c *SnapshotExecutionSubsetProvider_AtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) protocol.SnapshotExecutionSubset) *SnapshotExecutionSubsetProvider_AtBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/state.go b/state/protocol/mock/state.go index ee85272bd91..234be8b6fcc 100644 --- a/state/protocol/mock/state.go +++ b/state/protocol/mock/state.go @@ -1,129 +1,282 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewState creates a new instance of State. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewState(t interface { + mock.TestingT + Cleanup(func()) +}) *State { + mock := &State{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // State is an autogenerated mock type for the State type type State struct { mock.Mock } -// AtBlockID provides a mock function with given fields: blockID -func (_m *State) AtBlockID(blockID flow.Identifier) protocol.Snapshot { - ret := _m.Called(blockID) +type State_Expecter struct { + mock *mock.Mock +} + +func (_m *State) EXPECT() *State_Expecter { + return &State_Expecter{mock: &_m.Mock} +} + +// AtBlockID provides a mock function for the type State +func (_mock *State) AtBlockID(blockID flow.Identifier) protocol.Snapshot { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for AtBlockID") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol.Snapshot); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol.Snapshot); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// AtHeight provides a mock function with given fields: height -func (_m *State) AtHeight(height uint64) protocol.Snapshot { - ret := _m.Called(height) +// State_AtBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtBlockID' +type State_AtBlockID_Call struct { + *mock.Call +} + +// AtBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *State_Expecter) AtBlockID(blockID interface{}) *State_AtBlockID_Call { + return &State_AtBlockID_Call{Call: _e.mock.On("AtBlockID", blockID)} +} + +func (_c *State_AtBlockID_Call) Run(run func(blockID flow.Identifier)) *State_AtBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *State_AtBlockID_Call) Return(snapshot protocol.Snapshot) *State_AtBlockID_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *State_AtBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) protocol.Snapshot) *State_AtBlockID_Call { + _c.Call.Return(run) + return _c +} + +// AtHeight provides a mock function for the type State +func (_mock *State) AtHeight(height uint64) protocol.Snapshot { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for AtHeight") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func(uint64) protocol.Snapshot); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) protocol.Snapshot); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// Final provides a mock function with no fields -func (_m *State) Final() protocol.Snapshot { - ret := _m.Called() +// State_AtHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtHeight' +type State_AtHeight_Call struct { + *mock.Call +} + +// AtHeight is a helper method to define mock.On call +// - height uint64 +func (_e *State_Expecter) AtHeight(height interface{}) *State_AtHeight_Call { + return &State_AtHeight_Call{Call: _e.mock.On("AtHeight", height)} +} + +func (_c *State_AtHeight_Call) Run(run func(height uint64)) *State_AtHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *State_AtHeight_Call) Return(snapshot protocol.Snapshot) *State_AtHeight_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *State_AtHeight_Call) RunAndReturn(run func(height uint64) protocol.Snapshot) *State_AtHeight_Call { + _c.Call.Return(run) + return _c +} + +// Final provides a mock function for the type State +func (_mock *State) Final() protocol.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Final") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func() protocol.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// Params provides a mock function with no fields -func (_m *State) Params() protocol.Params { - ret := _m.Called() +// State_Final_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Final' +type State_Final_Call struct { + *mock.Call +} + +// Final is a helper method to define mock.On call +func (_e *State_Expecter) Final() *State_Final_Call { + return &State_Final_Call{Call: _e.mock.On("Final")} +} + +func (_c *State_Final_Call) Run(run func()) *State_Final_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *State_Final_Call) Return(snapshot protocol.Snapshot) *State_Final_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *State_Final_Call) RunAndReturn(run func() protocol.Snapshot) *State_Final_Call { + _c.Call.Return(run) + return _c +} + +// Params provides a mock function for the type State +func (_mock *State) Params() protocol.Params { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Params") } var r0 protocol.Params - if rf, ok := ret.Get(0).(func() protocol.Params); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Params); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Params) } } - return r0 } -// Sealed provides a mock function with no fields -func (_m *State) Sealed() protocol.Snapshot { - ret := _m.Called() +// State_Params_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Params' +type State_Params_Call struct { + *mock.Call +} + +// Params is a helper method to define mock.On call +func (_e *State_Expecter) Params() *State_Params_Call { + return &State_Params_Call{Call: _e.mock.On("Params")} +} + +func (_c *State_Params_Call) Run(run func()) *State_Params_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *State_Params_Call) Return(params protocol.Params) *State_Params_Call { + _c.Call.Return(params) + return _c +} + +func (_c *State_Params_Call) RunAndReturn(run func() protocol.Params) *State_Params_Call { + _c.Call.Return(run) + return _c +} + +// Sealed provides a mock function for the type State +func (_mock *State) Sealed() protocol.Snapshot { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Sealed") } var r0 protocol.Snapshot - if rf, ok := ret.Get(0).(func() protocol.Snapshot); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.Snapshot); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.Snapshot) } } - return r0 } -// NewState creates a new instance of State. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewState(t interface { - mock.TestingT - Cleanup(func()) -}) *State { - mock := &State{} - mock.Mock.Test(t) +// State_Sealed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sealed' +type State_Sealed_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Sealed is a helper method to define mock.On call +func (_e *State_Expecter) Sealed() *State_Sealed_Call { + return &State_Sealed_Call{Call: _e.mock.On("Sealed")} +} - return mock +func (_c *State_Sealed_Call) Run(run func()) *State_Sealed_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *State_Sealed_Call) Return(snapshot protocol.Snapshot) *State_Sealed_Call { + _c.Call.Return(snapshot) + return _c +} + +func (_c *State_Sealed_Call) RunAndReturn(run func() protocol.Snapshot) *State_Sealed_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/tentative_epoch.go b/state/protocol/mock/tentative_epoch.go index b291d94df7f..4de938655b7 100644 --- a/state/protocol/mock/tentative_epoch.go +++ b/state/protocol/mock/tentative_epoch.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTentativeEpoch creates a new instance of TentativeEpoch. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTentativeEpoch(t interface { + mock.TestingT + Cleanup(func()) +}) *TentativeEpoch { + mock := &TentativeEpoch{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TentativeEpoch is an autogenerated mock type for the TentativeEpoch type type TentativeEpoch struct { mock.Mock } -// Clustering provides a mock function with no fields -func (_m *TentativeEpoch) Clustering() (flow.ClusterList, error) { - ret := _m.Called() +type TentativeEpoch_Expecter struct { + mock *mock.Mock +} + +func (_m *TentativeEpoch) EXPECT() *TentativeEpoch_Expecter { + return &TentativeEpoch_Expecter{mock: &_m.Mock} +} + +// Clustering provides a mock function for the type TentativeEpoch +func (_mock *TentativeEpoch) Clustering() (flow.ClusterList, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Clustering") @@ -22,74 +46,137 @@ func (_m *TentativeEpoch) Clustering() (flow.ClusterList, error) { var r0 flow.ClusterList var r1 error - if rf, ok := ret.Get(0).(func() (flow.ClusterList, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.ClusterList, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.ClusterList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.ClusterList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.ClusterList) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// Counter provides a mock function with no fields -func (_m *TentativeEpoch) Counter() uint64 { - ret := _m.Called() +// TentativeEpoch_Clustering_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Clustering' +type TentativeEpoch_Clustering_Call struct { + *mock.Call +} + +// Clustering is a helper method to define mock.On call +func (_e *TentativeEpoch_Expecter) Clustering() *TentativeEpoch_Clustering_Call { + return &TentativeEpoch_Clustering_Call{Call: _e.mock.On("Clustering")} +} + +func (_c *TentativeEpoch_Clustering_Call) Run(run func()) *TentativeEpoch_Clustering_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TentativeEpoch_Clustering_Call) Return(clusterList flow.ClusterList, err error) *TentativeEpoch_Clustering_Call { + _c.Call.Return(clusterList, err) + return _c +} + +func (_c *TentativeEpoch_Clustering_Call) RunAndReturn(run func() (flow.ClusterList, error)) *TentativeEpoch_Clustering_Call { + _c.Call.Return(run) + return _c +} + +// Counter provides a mock function for the type TentativeEpoch +func (_mock *TentativeEpoch) Counter() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Counter") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// InitialIdentities provides a mock function with no fields -func (_m *TentativeEpoch) InitialIdentities() flow.IdentitySkeletonList { - ret := _m.Called() +// TentativeEpoch_Counter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Counter' +type TentativeEpoch_Counter_Call struct { + *mock.Call +} + +// Counter is a helper method to define mock.On call +func (_e *TentativeEpoch_Expecter) Counter() *TentativeEpoch_Counter_Call { + return &TentativeEpoch_Counter_Call{Call: _e.mock.On("Counter")} +} + +func (_c *TentativeEpoch_Counter_Call) Run(run func()) *TentativeEpoch_Counter_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TentativeEpoch_Counter_Call) Return(v uint64) *TentativeEpoch_Counter_Call { + _c.Call.Return(v) + return _c +} + +func (_c *TentativeEpoch_Counter_Call) RunAndReturn(run func() uint64) *TentativeEpoch_Counter_Call { + _c.Call.Return(run) + return _c +} + +// InitialIdentities provides a mock function for the type TentativeEpoch +func (_mock *TentativeEpoch) InitialIdentities() flow.IdentitySkeletonList { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for InitialIdentities") } var r0 flow.IdentitySkeletonList - if rf, ok := ret.Get(0).(func() flow.IdentitySkeletonList); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.IdentitySkeletonList); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.IdentitySkeletonList) } } - return r0 } -// NewTentativeEpoch creates a new instance of TentativeEpoch. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTentativeEpoch(t interface { - mock.TestingT - Cleanup(func()) -}) *TentativeEpoch { - mock := &TentativeEpoch{} - mock.Mock.Test(t) +// TentativeEpoch_InitialIdentities_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InitialIdentities' +type TentativeEpoch_InitialIdentities_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// InitialIdentities is a helper method to define mock.On call +func (_e *TentativeEpoch_Expecter) InitialIdentities() *TentativeEpoch_InitialIdentities_Call { + return &TentativeEpoch_InitialIdentities_Call{Call: _e.mock.On("InitialIdentities")} +} - return mock +func (_c *TentativeEpoch_InitialIdentities_Call) Run(run func()) *TentativeEpoch_InitialIdentities_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *TentativeEpoch_InitialIdentities_Call) Return(v flow.IdentitySkeletonList) *TentativeEpoch_InitialIdentities_Call { + _c.Call.Return(v) + return _c +} + +func (_c *TentativeEpoch_InitialIdentities_Call) RunAndReturn(run func() flow.IdentitySkeletonList) *TentativeEpoch_InitialIdentities_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/mock/versioned_encodable.go b/state/protocol/mock/versioned_encodable.go index 04ef23e4705..c5d4d39126d 100644 --- a/state/protocol/mock/versioned_encodable.go +++ b/state/protocol/mock/versioned_encodable.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewVersionedEncodable creates a new instance of VersionedEncodable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVersionedEncodable(t interface { + mock.TestingT + Cleanup(func()) +}) *VersionedEncodable { + mock := &VersionedEncodable{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // VersionedEncodable is an autogenerated mock type for the VersionedEncodable type type VersionedEncodable struct { mock.Mock } -// VersionedEncode provides a mock function with no fields -func (_m *VersionedEncodable) VersionedEncode() (uint64, []byte, error) { - ret := _m.Called() +type VersionedEncodable_Expecter struct { + mock *mock.Mock +} + +func (_m *VersionedEncodable) EXPECT() *VersionedEncodable_Expecter { + return &VersionedEncodable_Expecter{mock: &_m.Mock} +} + +// VersionedEncode provides a mock function for the type VersionedEncodable +func (_mock *VersionedEncodable) VersionedEncode() (uint64, []byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for VersionedEncode") @@ -20,42 +46,52 @@ func (_m *VersionedEncodable) VersionedEncode() (uint64, []byte, error) { var r0 uint64 var r1 []byte var r2 error - if rf, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() []byte); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() []byte); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]byte) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewVersionedEncodable creates a new instance of VersionedEncodable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVersionedEncodable(t interface { - mock.TestingT - Cleanup(func()) -}) *VersionedEncodable { - mock := &VersionedEncodable{} - mock.Mock.Test(t) +// VersionedEncodable_VersionedEncode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VersionedEncode' +type VersionedEncodable_VersionedEncode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VersionedEncode is a helper method to define mock.On call +func (_e *VersionedEncodable_Expecter) VersionedEncode() *VersionedEncodable_VersionedEncode_Call { + return &VersionedEncodable_VersionedEncode_Call{Call: _e.mock.On("VersionedEncode")} +} - return mock +func (_c *VersionedEncodable_VersionedEncode_Call) Run(run func()) *VersionedEncodable_VersionedEncode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *VersionedEncodable_VersionedEncode_Call) Return(v uint64, bytes []byte, err error) *VersionedEncodable_VersionedEncode_Call { + _c.Call.Return(v, bytes, err) + return _c +} + +func (_c *VersionedEncodable_VersionedEncode_Call) RunAndReturn(run func() (uint64, []byte, error)) *VersionedEncodable_VersionedEncode_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/epochs/mock/state_machine.go b/state/protocol/protocol_state/epochs/mock/state_machine.go index acc155da2de..285c248c713 100644 --- a/state/protocol/protocol_state/epochs/mock/state_machine.go +++ b/state/protocol/protocol_state/epochs/mock/state_machine.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewStateMachine creates a new instance of StateMachine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStateMachine(t interface { + mock.TestingT + Cleanup(func()) +}) *StateMachine { + mock := &StateMachine{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // StateMachine is an autogenerated mock type for the StateMachine type type StateMachine struct { mock.Mock } -// Build provides a mock function with no fields -func (_m *StateMachine) Build() (*flow.EpochStateEntry, flow.Identifier, bool) { - ret := _m.Called() +type StateMachine_Expecter struct { + mock *mock.Mock +} + +func (_m *StateMachine) EXPECT() *StateMachine_Expecter { + return &StateMachine_Expecter{mock: &_m.Mock} +} + +// Build provides a mock function for the type StateMachine +func (_mock *StateMachine) Build() (*flow.EpochStateEntry, flow.Identifier, bool) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Build") @@ -23,75 +47,158 @@ func (_m *StateMachine) Build() (*flow.EpochStateEntry, flow.Identifier, bool) { var r0 *flow.EpochStateEntry var r1 flow.Identifier var r2 bool - if rf, ok := ret.Get(0).(func() (*flow.EpochStateEntry, flow.Identifier, bool)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*flow.EpochStateEntry, flow.Identifier, bool)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *flow.EpochStateEntry); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.EpochStateEntry); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.EpochStateEntry) } } - - if rf, ok := ret.Get(1).(func() flow.Identifier); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() flow.Identifier); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).(flow.Identifier) } } - - if rf, ok := ret.Get(2).(func() bool); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() bool); ok { + r2 = returnFunc() } else { r2 = ret.Get(2).(bool) } - return r0, r1, r2 } -// EjectIdentity provides a mock function with given fields: ejectionEvent -func (_m *StateMachine) EjectIdentity(ejectionEvent *flow.EjectNode) bool { - ret := _m.Called(ejectionEvent) +// StateMachine_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build' +type StateMachine_Build_Call struct { + *mock.Call +} + +// Build is a helper method to define mock.On call +func (_e *StateMachine_Expecter) Build() *StateMachine_Build_Call { + return &StateMachine_Build_Call{Call: _e.mock.On("Build")} +} + +func (_c *StateMachine_Build_Call) Run(run func()) *StateMachine_Build_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *StateMachine_Build_Call) Return(updatedState *flow.EpochStateEntry, stateID flow.Identifier, hasChanges bool) *StateMachine_Build_Call { + _c.Call.Return(updatedState, stateID, hasChanges) + return _c +} + +func (_c *StateMachine_Build_Call) RunAndReturn(run func() (*flow.EpochStateEntry, flow.Identifier, bool)) *StateMachine_Build_Call { + _c.Call.Return(run) + return _c +} + +// EjectIdentity provides a mock function for the type StateMachine +func (_mock *StateMachine) EjectIdentity(ejectionEvent *flow.EjectNode) bool { + ret := _mock.Called(ejectionEvent) if len(ret) == 0 { panic("no return value specified for EjectIdentity") } var r0 bool - if rf, ok := ret.Get(0).(func(*flow.EjectNode) bool); ok { - r0 = rf(ejectionEvent) + if returnFunc, ok := ret.Get(0).(func(*flow.EjectNode) bool); ok { + r0 = returnFunc(ejectionEvent) } else { r0 = ret.Get(0).(bool) } - return r0 } -// ParentState provides a mock function with no fields -func (_m *StateMachine) ParentState() *flow.RichEpochStateEntry { - ret := _m.Called() +// StateMachine_EjectIdentity_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EjectIdentity' +type StateMachine_EjectIdentity_Call struct { + *mock.Call +} + +// EjectIdentity is a helper method to define mock.On call +// - ejectionEvent *flow.EjectNode +func (_e *StateMachine_Expecter) EjectIdentity(ejectionEvent interface{}) *StateMachine_EjectIdentity_Call { + return &StateMachine_EjectIdentity_Call{Call: _e.mock.On("EjectIdentity", ejectionEvent)} +} + +func (_c *StateMachine_EjectIdentity_Call) Run(run func(ejectionEvent *flow.EjectNode)) *StateMachine_EjectIdentity_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.EjectNode + if args[0] != nil { + arg0 = args[0].(*flow.EjectNode) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StateMachine_EjectIdentity_Call) Return(b bool) *StateMachine_EjectIdentity_Call { + _c.Call.Return(b) + return _c +} + +func (_c *StateMachine_EjectIdentity_Call) RunAndReturn(run func(ejectionEvent *flow.EjectNode) bool) *StateMachine_EjectIdentity_Call { + _c.Call.Return(run) + return _c +} + +// ParentState provides a mock function for the type StateMachine +func (_mock *StateMachine) ParentState() *flow.RichEpochStateEntry { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ParentState") } var r0 *flow.RichEpochStateEntry - if rf, ok := ret.Get(0).(func() *flow.RichEpochStateEntry); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *flow.RichEpochStateEntry); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.RichEpochStateEntry) } } - return r0 } -// ProcessEpochCommit provides a mock function with given fields: epochCommit -func (_m *StateMachine) ProcessEpochCommit(epochCommit *flow.EpochCommit) (bool, error) { - ret := _m.Called(epochCommit) +// StateMachine_ParentState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ParentState' +type StateMachine_ParentState_Call struct { + *mock.Call +} + +// ParentState is a helper method to define mock.On call +func (_e *StateMachine_Expecter) ParentState() *StateMachine_ParentState_Call { + return &StateMachine_ParentState_Call{Call: _e.mock.On("ParentState")} +} + +func (_c *StateMachine_ParentState_Call) Run(run func()) *StateMachine_ParentState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *StateMachine_ParentState_Call) Return(richEpochStateEntry *flow.RichEpochStateEntry) *StateMachine_ParentState_Call { + _c.Call.Return(richEpochStateEntry) + return _c +} + +func (_c *StateMachine_ParentState_Call) RunAndReturn(run func() *flow.RichEpochStateEntry) *StateMachine_ParentState_Call { + _c.Call.Return(run) + return _c +} + +// ProcessEpochCommit provides a mock function for the type StateMachine +func (_mock *StateMachine) ProcessEpochCommit(epochCommit *flow.EpochCommit) (bool, error) { + ret := _mock.Called(epochCommit) if len(ret) == 0 { panic("no return value specified for ProcessEpochCommit") @@ -99,27 +206,59 @@ func (_m *StateMachine) ProcessEpochCommit(epochCommit *flow.EpochCommit) (bool, var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*flow.EpochCommit) (bool, error)); ok { - return rf(epochCommit) + if returnFunc, ok := ret.Get(0).(func(*flow.EpochCommit) (bool, error)); ok { + return returnFunc(epochCommit) } - if rf, ok := ret.Get(0).(func(*flow.EpochCommit) bool); ok { - r0 = rf(epochCommit) + if returnFunc, ok := ret.Get(0).(func(*flow.EpochCommit) bool); ok { + r0 = returnFunc(epochCommit) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*flow.EpochCommit) error); ok { - r1 = rf(epochCommit) + if returnFunc, ok := ret.Get(1).(func(*flow.EpochCommit) error); ok { + r1 = returnFunc(epochCommit) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProcessEpochRecover provides a mock function with given fields: epochRecover -func (_m *StateMachine) ProcessEpochRecover(epochRecover *flow.EpochRecover) (bool, error) { - ret := _m.Called(epochRecover) +// StateMachine_ProcessEpochCommit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessEpochCommit' +type StateMachine_ProcessEpochCommit_Call struct { + *mock.Call +} + +// ProcessEpochCommit is a helper method to define mock.On call +// - epochCommit *flow.EpochCommit +func (_e *StateMachine_Expecter) ProcessEpochCommit(epochCommit interface{}) *StateMachine_ProcessEpochCommit_Call { + return &StateMachine_ProcessEpochCommit_Call{Call: _e.mock.On("ProcessEpochCommit", epochCommit)} +} + +func (_c *StateMachine_ProcessEpochCommit_Call) Run(run func(epochCommit *flow.EpochCommit)) *StateMachine_ProcessEpochCommit_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.EpochCommit + if args[0] != nil { + arg0 = args[0].(*flow.EpochCommit) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StateMachine_ProcessEpochCommit_Call) Return(b bool, err error) *StateMachine_ProcessEpochCommit_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *StateMachine_ProcessEpochCommit_Call) RunAndReturn(run func(epochCommit *flow.EpochCommit) (bool, error)) *StateMachine_ProcessEpochCommit_Call { + _c.Call.Return(run) + return _c +} + +// ProcessEpochRecover provides a mock function for the type StateMachine +func (_mock *StateMachine) ProcessEpochRecover(epochRecover *flow.EpochRecover) (bool, error) { + ret := _mock.Called(epochRecover) if len(ret) == 0 { panic("no return value specified for ProcessEpochRecover") @@ -127,27 +266,59 @@ func (_m *StateMachine) ProcessEpochRecover(epochRecover *flow.EpochRecover) (bo var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*flow.EpochRecover) (bool, error)); ok { - return rf(epochRecover) + if returnFunc, ok := ret.Get(0).(func(*flow.EpochRecover) (bool, error)); ok { + return returnFunc(epochRecover) } - if rf, ok := ret.Get(0).(func(*flow.EpochRecover) bool); ok { - r0 = rf(epochRecover) + if returnFunc, ok := ret.Get(0).(func(*flow.EpochRecover) bool); ok { + r0 = returnFunc(epochRecover) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*flow.EpochRecover) error); ok { - r1 = rf(epochRecover) + if returnFunc, ok := ret.Get(1).(func(*flow.EpochRecover) error); ok { + r1 = returnFunc(epochRecover) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProcessEpochSetup provides a mock function with given fields: epochSetup -func (_m *StateMachine) ProcessEpochSetup(epochSetup *flow.EpochSetup) (bool, error) { - ret := _m.Called(epochSetup) +// StateMachine_ProcessEpochRecover_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessEpochRecover' +type StateMachine_ProcessEpochRecover_Call struct { + *mock.Call +} + +// ProcessEpochRecover is a helper method to define mock.On call +// - epochRecover *flow.EpochRecover +func (_e *StateMachine_Expecter) ProcessEpochRecover(epochRecover interface{}) *StateMachine_ProcessEpochRecover_Call { + return &StateMachine_ProcessEpochRecover_Call{Call: _e.mock.On("ProcessEpochRecover", epochRecover)} +} + +func (_c *StateMachine_ProcessEpochRecover_Call) Run(run func(epochRecover *flow.EpochRecover)) *StateMachine_ProcessEpochRecover_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.EpochRecover + if args[0] != nil { + arg0 = args[0].(*flow.EpochRecover) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StateMachine_ProcessEpochRecover_Call) Return(b bool, err error) *StateMachine_ProcessEpochRecover_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *StateMachine_ProcessEpochRecover_Call) RunAndReturn(run func(epochRecover *flow.EpochRecover) (bool, error)) *StateMachine_ProcessEpochRecover_Call { + _c.Call.Return(run) + return _c +} + +// ProcessEpochSetup provides a mock function for the type StateMachine +func (_mock *StateMachine) ProcessEpochSetup(epochSetup *flow.EpochSetup) (bool, error) { + ret := _mock.Called(epochSetup) if len(ret) == 0 { panic("no return value specified for ProcessEpochSetup") @@ -155,70 +326,140 @@ func (_m *StateMachine) ProcessEpochSetup(epochSetup *flow.EpochSetup) (bool, er var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*flow.EpochSetup) (bool, error)); ok { - return rf(epochSetup) + if returnFunc, ok := ret.Get(0).(func(*flow.EpochSetup) (bool, error)); ok { + return returnFunc(epochSetup) } - if rf, ok := ret.Get(0).(func(*flow.EpochSetup) bool); ok { - r0 = rf(epochSetup) + if returnFunc, ok := ret.Get(0).(func(*flow.EpochSetup) bool); ok { + r0 = returnFunc(epochSetup) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*flow.EpochSetup) error); ok { - r1 = rf(epochSetup) + if returnFunc, ok := ret.Get(1).(func(*flow.EpochSetup) error); ok { + r1 = returnFunc(epochSetup) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransitionToNextEpoch provides a mock function with no fields -func (_m *StateMachine) TransitionToNextEpoch() error { - ret := _m.Called() +// StateMachine_ProcessEpochSetup_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessEpochSetup' +type StateMachine_ProcessEpochSetup_Call struct { + *mock.Call +} + +// ProcessEpochSetup is a helper method to define mock.On call +// - epochSetup *flow.EpochSetup +func (_e *StateMachine_Expecter) ProcessEpochSetup(epochSetup interface{}) *StateMachine_ProcessEpochSetup_Call { + return &StateMachine_ProcessEpochSetup_Call{Call: _e.mock.On("ProcessEpochSetup", epochSetup)} +} + +func (_c *StateMachine_ProcessEpochSetup_Call) Run(run func(epochSetup *flow.EpochSetup)) *StateMachine_ProcessEpochSetup_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.EpochSetup + if args[0] != nil { + arg0 = args[0].(*flow.EpochSetup) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StateMachine_ProcessEpochSetup_Call) Return(b bool, err error) *StateMachine_ProcessEpochSetup_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *StateMachine_ProcessEpochSetup_Call) RunAndReturn(run func(epochSetup *flow.EpochSetup) (bool, error)) *StateMachine_ProcessEpochSetup_Call { + _c.Call.Return(run) + return _c +} + +// TransitionToNextEpoch provides a mock function for the type StateMachine +func (_mock *StateMachine) TransitionToNextEpoch() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for TransitionToNextEpoch") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// View provides a mock function with no fields -func (_m *StateMachine) View() uint64 { - ret := _m.Called() +// StateMachine_TransitionToNextEpoch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransitionToNextEpoch' +type StateMachine_TransitionToNextEpoch_Call struct { + *mock.Call +} + +// TransitionToNextEpoch is a helper method to define mock.On call +func (_e *StateMachine_Expecter) TransitionToNextEpoch() *StateMachine_TransitionToNextEpoch_Call { + return &StateMachine_TransitionToNextEpoch_Call{Call: _e.mock.On("TransitionToNextEpoch")} +} + +func (_c *StateMachine_TransitionToNextEpoch_Call) Run(run func()) *StateMachine_TransitionToNextEpoch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *StateMachine_TransitionToNextEpoch_Call) Return(err error) *StateMachine_TransitionToNextEpoch_Call { + _c.Call.Return(err) + return _c +} + +func (_c *StateMachine_TransitionToNextEpoch_Call) RunAndReturn(run func() error) *StateMachine_TransitionToNextEpoch_Call { + _c.Call.Return(run) + return _c +} + +// View provides a mock function for the type StateMachine +func (_mock *StateMachine) View() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for View") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewStateMachine creates a new instance of StateMachine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStateMachine(t interface { - mock.TestingT - Cleanup(func()) -}) *StateMachine { - mock := &StateMachine{} - mock.Mock.Test(t) +// StateMachine_View_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'View' +type StateMachine_View_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// View is a helper method to define mock.On call +func (_e *StateMachine_Expecter) View() *StateMachine_View_Call { + return &StateMachine_View_Call{Call: _e.mock.On("View")} +} - return mock +func (_c *StateMachine_View_Call) Run(run func()) *StateMachine_View_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *StateMachine_View_Call) Return(v uint64) *StateMachine_View_Call { + _c.Call.Return(v) + return _c +} + +func (_c *StateMachine_View_Call) RunAndReturn(run func() uint64) *StateMachine_View_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/epochs/mock/state_machine_factory_method.go b/state/protocol/protocol_state/epochs/mock/state_machine_factory_method.go deleted file mode 100644 index 838fae65393..00000000000 --- a/state/protocol/protocol_state/epochs/mock/state_machine_factory_method.go +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - flow "github.com/onflow/flow-go/model/flow" - epochs "github.com/onflow/flow-go/state/protocol/protocol_state/epochs" - - mock "github.com/stretchr/testify/mock" -) - -// StateMachineFactoryMethod is an autogenerated mock type for the StateMachineFactoryMethod type -type StateMachineFactoryMethod struct { - mock.Mock -} - -// Execute provides a mock function with given fields: candidateView, parentState -func (_m *StateMachineFactoryMethod) Execute(candidateView uint64, parentState *flow.RichEpochStateEntry) (epochs.StateMachine, error) { - ret := _m.Called(candidateView, parentState) - - if len(ret) == 0 { - panic("no return value specified for Execute") - } - - var r0 epochs.StateMachine - var r1 error - if rf, ok := ret.Get(0).(func(uint64, *flow.RichEpochStateEntry) (epochs.StateMachine, error)); ok { - return rf(candidateView, parentState) - } - if rf, ok := ret.Get(0).(func(uint64, *flow.RichEpochStateEntry) epochs.StateMachine); ok { - r0 = rf(candidateView, parentState) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(epochs.StateMachine) - } - } - - if rf, ok := ret.Get(1).(func(uint64, *flow.RichEpochStateEntry) error); ok { - r1 = rf(candidateView, parentState) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// NewStateMachineFactoryMethod creates a new instance of StateMachineFactoryMethod. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStateMachineFactoryMethod(t interface { - mock.TestingT - Cleanup(func()) -}) *StateMachineFactoryMethod { - mock := &StateMachineFactoryMethod{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/state/protocol/protocol_state/epochs/mock_interfaces/mock/state_machine_factory_method.go b/state/protocol/protocol_state/epochs/mock_interfaces/mock/state_machine_factory_method.go new file mode 100644 index 00000000000..2f781ba0d25 --- /dev/null +++ b/state/protocol/protocol_state/epochs/mock_interfaces/mock/state_machine_factory_method.go @@ -0,0 +1,106 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol/protocol_state/epochs" + mock "github.com/stretchr/testify/mock" +) + +// NewStateMachineFactoryMethod creates a new instance of StateMachineFactoryMethod. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStateMachineFactoryMethod(t interface { + mock.TestingT + Cleanup(func()) +}) *StateMachineFactoryMethod { + mock := &StateMachineFactoryMethod{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// StateMachineFactoryMethod is an autogenerated mock type for the StateMachineFactoryMethod type +type StateMachineFactoryMethod struct { + mock.Mock +} + +type StateMachineFactoryMethod_Expecter struct { + mock *mock.Mock +} + +func (_m *StateMachineFactoryMethod) EXPECT() *StateMachineFactoryMethod_Expecter { + return &StateMachineFactoryMethod_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function for the type StateMachineFactoryMethod +func (_mock *StateMachineFactoryMethod) Execute(candidateView uint64, parentState *flow.RichEpochStateEntry) (epochs.StateMachine, error) { + ret := _mock.Called(candidateView, parentState) + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 epochs.StateMachine + var r1 error + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.RichEpochStateEntry) (epochs.StateMachine, error)); ok { + return returnFunc(candidateView, parentState) + } + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.RichEpochStateEntry) epochs.StateMachine); ok { + r0 = returnFunc(candidateView, parentState) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(epochs.StateMachine) + } + } + if returnFunc, ok := ret.Get(1).(func(uint64, *flow.RichEpochStateEntry) error); ok { + r1 = returnFunc(candidateView, parentState) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// StateMachineFactoryMethod_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type StateMachineFactoryMethod_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +// - candidateView uint64 +// - parentState *flow.RichEpochStateEntry +func (_e *StateMachineFactoryMethod_Expecter) Execute(candidateView interface{}, parentState interface{}) *StateMachineFactoryMethod_Execute_Call { + return &StateMachineFactoryMethod_Execute_Call{Call: _e.mock.On("Execute", candidateView, parentState)} +} + +func (_c *StateMachineFactoryMethod_Execute_Call) Run(run func(candidateView uint64, parentState *flow.RichEpochStateEntry)) *StateMachineFactoryMethod_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.RichEpochStateEntry + if args[1] != nil { + arg1 = args[1].(*flow.RichEpochStateEntry) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *StateMachineFactoryMethod_Execute_Call) Return(stateMachine epochs.StateMachine, err error) *StateMachineFactoryMethod_Execute_Call { + _c.Call.Return(stateMachine, err) + return _c +} + +func (_c *StateMachineFactoryMethod_Execute_Call) RunAndReturn(run func(candidateView uint64, parentState *flow.RichEpochStateEntry) (epochs.StateMachine, error)) *StateMachineFactoryMethod_Execute_Call { + _c.Call.Return(run) + return _c +} diff --git a/state/protocol/protocol_state/epochs/mock_interfaces/state_machine_factory_method.go b/state/protocol/protocol_state/epochs/mock_interfaces/state_machine_factory_method.go index 3635134277a..40ff922ee3c 100644 --- a/state/protocol/protocol_state/epochs/mock_interfaces/state_machine_factory_method.go +++ b/state/protocol/protocol_state/epochs/mock_interfaces/state_machine_factory_method.go @@ -1,4 +1,4 @@ -package mockinterfaces +package mock_interfaces import ( "github.com/onflow/flow-go/model/flow" diff --git a/state/protocol/protocol_state/epochs/statemachine_test.go b/state/protocol/protocol_state/epochs/statemachine_test.go index 4b5d837d7ef..3f85c37f70d 100644 --- a/state/protocol/protocol_state/epochs/statemachine_test.go +++ b/state/protocol/protocol_state/epochs/statemachine_test.go @@ -16,7 +16,9 @@ import ( protocolmock "github.com/onflow/flow-go/state/protocol/mock" "github.com/onflow/flow-go/state/protocol/protocol_state/epochs" "github.com/onflow/flow-go/state/protocol/protocol_state/epochs/mock" + mock_interfaces "github.com/onflow/flow-go/state/protocol/protocol_state/epochs/mock_interfaces/mock" protocol_statemock "github.com/onflow/flow-go/state/protocol/protocol_state/mock" + protocol_mock_interfaces "github.com/onflow/flow-go/state/protocol/protocol_state/mock_interfaces/mock" "github.com/onflow/flow-go/storage" storagemock "github.com/onflow/flow-go/storage/mock" "github.com/onflow/flow-go/utils/unittest" @@ -39,8 +41,8 @@ type EpochStateMachineSuite struct { parentEpochState *flow.RichEpochStateEntry mutator *protocol_statemock.KVStoreMutator happyPathStateMachine *mock.StateMachine - happyPathStateMachineFactory *mock.StateMachineFactoryMethod - fallbackPathStateMachineFactory *mock.StateMachineFactoryMethod + happyPathStateMachineFactory *mock_interfaces.StateMachineFactoryMethod + fallbackPathStateMachineFactory *mock_interfaces.StateMachineFactoryMethod candidate *flow.Header lockManager lockctx.Manager @@ -57,8 +59,8 @@ func (s *EpochStateMachineSuite) SetupTest() { s.mutator = protocol_statemock.NewKVStoreMutator(s.T()) s.candidate = unittest.BlockHeaderFixture(unittest.HeaderWithView(s.parentEpochState.CurrentEpochSetup.FirstView + 1)) s.happyPathStateMachine = mock.NewStateMachine(s.T()) - s.happyPathStateMachineFactory = mock.NewStateMachineFactoryMethod(s.T()) - s.fallbackPathStateMachineFactory = mock.NewStateMachineFactoryMethod(s.T()) + s.happyPathStateMachineFactory = mock_interfaces.NewStateMachineFactoryMethod(s.T()) + s.fallbackPathStateMachineFactory = mock_interfaces.NewStateMachineFactoryMethod(s.T()) s.lockManager = storage.NewTestingLockManager() s.epochStateDB.On("ByBlockID", mocks.Anything).Return(func(_ flow.Identifier) *flow.RichEpochStateEntry { @@ -176,12 +178,12 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { s.Run("EpochStaking phase", func() { // Since we are before the epoch commitment deadline, we should instantiate a happy-path state machine s.Run("before commitment deadline", func() { - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) // expect to be called happyPathStateMachineFactory.On("Execute", s.candidate.View, s.parentEpochState). Return(s.happyPathStateMachine, nil).Once() // don't expect to be called - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) candidate := unittest.BlockHeaderFixture(unittest.HeaderWithView(s.parentEpochState.CurrentEpochSetup.FirstView + 1)) stateMachine, err := epochs.NewEpochStateMachine( @@ -202,9 +204,9 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { // phase, we should use the epoch fallback state machine. s.Run("past commitment deadline", func() { // don't expect to be called - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) // expect to be called - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) candidate := unittest.BlockHeaderFixture(unittest.HeaderWithView(s.parentEpochState.CurrentEpochSetup.FinalView - 1)) fallbackPathStateMachineFactory.On("Execute", candidate.View, s.parentEpochState). @@ -232,9 +234,9 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { // Since we are before the epoch commitment deadline, we should instantiate a happy-path state machine s.Run("before commitment deadline", func() { - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) // don't expect to be called - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) candidate := unittest.BlockHeaderFixture(unittest.HeaderWithView(s.parentEpochState.CurrentEpochSetup.FirstView + 1)) // expect to be called @@ -258,8 +260,8 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { // phase, we should use the epoch fallback state machine. s.Run("past commitment deadline", func() { // don't expect to be called - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) candidate := unittest.BlockHeaderFixture(unittest.HeaderWithView(s.parentEpochState.CurrentEpochSetup.FinalView - 1)) // expect to be called @@ -285,12 +287,12 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { s.parentEpochState = unittest.EpochStateFixture(unittest.WithNextEpochProtocolState()) // Since we are before the epoch commitment deadline, we should instantiate a happy-path state machine s.Run("before commitment deadline", func() { - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) // expect to be called happyPathStateMachineFactory.On("Execute", s.candidate.View, s.parentEpochState). Return(s.happyPathStateMachine, nil).Once() // don't expect to be called - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) candidate := unittest.BlockHeaderFixture(unittest.HeaderWithView(s.parentEpochState.CurrentEpochSetup.FirstView + 1)) stateMachine, err := epochs.NewEpochStateMachine( @@ -310,9 +312,9 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { // Despite being past the epoch commitment deadline, since we are in the EpochCommitted phase // already, we should proceed with the happy-path state machine s.Run("past commitment deadline", func() { - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) // don't expect to be called - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) candidate := unittest.BlockHeaderFixture(unittest.HeaderWithView(s.parentEpochState.CurrentEpochSetup.FinalView - 1)) // expect to be called @@ -339,9 +341,9 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { s.Run("state machine constructor returns error", func() { s.Run("happy-path", func() { exception := irrecoverable.NewExceptionf("exception") - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) happyPathStateMachineFactory.On("Execute", s.candidate.View, s.parentEpochState).Return(nil, exception).Once() - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) stateMachine, err := epochs.NewEpochStateMachine( s.candidate.View, @@ -360,8 +362,8 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { s.Run("epoch-fallback", func() { s.parentEpochState.EpochFallbackTriggered = true // ensure we use epoch-fallback state machine exception := irrecoverable.NewExceptionf("exception") - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) fallbackPathStateMachineFactory.On("Execute", s.candidate.View, s.parentEpochState).Return(nil, exception).Once() stateMachine, err := epochs.NewEpochStateMachine( @@ -386,9 +388,9 @@ func (s *EpochStateMachineSuite) TestEpochStateMachine_Constructor() { // fallback state machine. Errors other than `InvalidServiceEventError` should be bubbled up as exceptions. func (s *EpochStateMachineSuite) TestEvolveState_InvalidEpochSetup() { s.Run("invalid-epoch-setup", func() { - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) happyPathStateMachineFactory.On("Execute", s.candidate.View, s.parentEpochState).Return(s.happyPathStateMachine, nil).Once() - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) stateMachine, err := epochs.NewEpochStateMachine( s.candidate.View, s.candidate.ParentID, @@ -433,9 +435,9 @@ func (s *EpochStateMachineSuite) TestEvolveState_InvalidEpochSetup() { // fallback state machine. Errors other than `InvalidServiceEventError` should be bubbled up as exceptions. func (s *EpochStateMachineSuite) TestEvolveState_InvalidEpochCommit() { s.Run("invalid-epoch-commit", func() { - happyPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + happyPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) happyPathStateMachineFactory.On("Execute", s.candidate.View, s.parentEpochState).Return(s.happyPathStateMachine, nil).Once() - fallbackPathStateMachineFactory := mock.NewStateMachineFactoryMethod(s.T()) + fallbackPathStateMachineFactory := mock_interfaces.NewStateMachineFactoryMethod(s.T()) stateMachine, err := epochs.NewEpochStateMachine( s.candidate.View, s.candidate.ParentID, @@ -522,8 +524,8 @@ func (s *EpochStateMachineSuite) TestEvolveStateTransitionToNextEpoch_WithInvali s.candidate.View = s.parentEpochState.NextEpochSetup.FirstView happyPathTelemetry := protocol_statemock.NewStateMachineTelemetryConsumer(s.T()) fallbackPathTelemetry := protocol_statemock.NewStateMachineTelemetryConsumer(s.T()) - happyPathTelemetryFactory := protocol_statemock.NewStateMachineEventsTelemetryFactory(s.T()) - fallbackTelemetryFactory := protocol_statemock.NewStateMachineEventsTelemetryFactory(s.T()) + happyPathTelemetryFactory := protocol_mock_interfaces.NewStateMachineEventsTelemetryFactory(s.T()) + fallbackTelemetryFactory := protocol_mock_interfaces.NewStateMachineEventsTelemetryFactory(s.T()) happyPathTelemetryFactory.On("Execute", s.candidate.View).Return(happyPathTelemetry).Once() fallbackTelemetryFactory.On("Execute", s.candidate.View).Return(fallbackPathTelemetry).Once() stateMachine, err := epochs.NewEpochStateMachineFactory( diff --git a/state/protocol/protocol_state/mock/key_value_store_state_machine.go b/state/protocol/protocol_state/mock/key_value_store_state_machine.go index f3bed6f0689..57c8a5fa1b9 100644 --- a/state/protocol/protocol_state/mock/key_value_store_state_machine.go +++ b/state/protocol/protocol_state/mock/key_value_store_state_machine.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - deferred "github.com/onflow/flow-go/storage/deferred" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/storage/deferred" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewKeyValueStoreStateMachine creates a new instance of KeyValueStoreStateMachine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewKeyValueStoreStateMachine(t interface { + mock.TestingT + Cleanup(func()) +}) *KeyValueStoreStateMachine { + mock := &KeyValueStoreStateMachine{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // KeyValueStoreStateMachine is an autogenerated mock type for the KeyValueStoreStateMachine type -type KeyValueStoreStateMachine[P any] struct { +type KeyValueStoreStateMachine struct { mock.Mock } -// Build provides a mock function with no fields -func (_m *KeyValueStoreStateMachine[P]) Build() (*deferred.DeferredBlockPersist, error) { - ret := _m.Called() +type KeyValueStoreStateMachine_Expecter struct { + mock *mock.Mock +} + +func (_m *KeyValueStoreStateMachine) EXPECT() *KeyValueStoreStateMachine_Expecter { + return &KeyValueStoreStateMachine_Expecter{mock: &_m.Mock} +} + +// Build provides a mock function for the type KeyValueStoreStateMachine +func (_mock *KeyValueStoreStateMachine) Build() (*deferred.DeferredBlockPersist, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Build") @@ -26,92 +48,188 @@ func (_m *KeyValueStoreStateMachine[P]) Build() (*deferred.DeferredBlockPersist, var r0 *deferred.DeferredBlockPersist var r1 error - if rf, ok := ret.Get(0).(func() (*deferred.DeferredBlockPersist, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*deferred.DeferredBlockPersist, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *deferred.DeferredBlockPersist); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *deferred.DeferredBlockPersist); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*deferred.DeferredBlockPersist) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// EvolveState provides a mock function with given fields: sealedServiceEvents -func (_m *KeyValueStoreStateMachine[P]) EvolveState(sealedServiceEvents []flow.ServiceEvent) error { - ret := _m.Called(sealedServiceEvents) +// KeyValueStoreStateMachine_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build' +type KeyValueStoreStateMachine_Build_Call struct { + *mock.Call +} + +// Build is a helper method to define mock.On call +func (_e *KeyValueStoreStateMachine_Expecter) Build() *KeyValueStoreStateMachine_Build_Call { + return &KeyValueStoreStateMachine_Build_Call{Call: _e.mock.On("Build")} +} + +func (_c *KeyValueStoreStateMachine_Build_Call) Run(run func()) *KeyValueStoreStateMachine_Build_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KeyValueStoreStateMachine_Build_Call) Return(deferredBlockPersist *deferred.DeferredBlockPersist, err error) *KeyValueStoreStateMachine_Build_Call { + _c.Call.Return(deferredBlockPersist, err) + return _c +} + +func (_c *KeyValueStoreStateMachine_Build_Call) RunAndReturn(run func() (*deferred.DeferredBlockPersist, error)) *KeyValueStoreStateMachine_Build_Call { + _c.Call.Return(run) + return _c +} + +// EvolveState provides a mock function for the type KeyValueStoreStateMachine +func (_mock *KeyValueStoreStateMachine) EvolveState(sealedServiceEvents []flow.ServiceEvent) error { + ret := _mock.Called(sealedServiceEvents) if len(ret) == 0 { panic("no return value specified for EvolveState") } var r0 error - if rf, ok := ret.Get(0).(func([]flow.ServiceEvent) error); ok { - r0 = rf(sealedServiceEvents) + if returnFunc, ok := ret.Get(0).(func([]flow.ServiceEvent) error); ok { + r0 = returnFunc(sealedServiceEvents) } else { r0 = ret.Error(0) } - return r0 } -// ParentState provides a mock function with no fields -func (_m *KeyValueStoreStateMachine[P]) ParentState() protocol.KVStoreReader { - ret := _m.Called() +// KeyValueStoreStateMachine_EvolveState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EvolveState' +type KeyValueStoreStateMachine_EvolveState_Call struct { + *mock.Call +} + +// EvolveState is a helper method to define mock.On call +// - sealedServiceEvents []flow.ServiceEvent +func (_e *KeyValueStoreStateMachine_Expecter) EvolveState(sealedServiceEvents interface{}) *KeyValueStoreStateMachine_EvolveState_Call { + return &KeyValueStoreStateMachine_EvolveState_Call{Call: _e.mock.On("EvolveState", sealedServiceEvents)} +} + +func (_c *KeyValueStoreStateMachine_EvolveState_Call) Run(run func(sealedServiceEvents []flow.ServiceEvent)) *KeyValueStoreStateMachine_EvolveState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.ServiceEvent + if args[0] != nil { + arg0 = args[0].([]flow.ServiceEvent) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *KeyValueStoreStateMachine_EvolveState_Call) Return(err error) *KeyValueStoreStateMachine_EvolveState_Call { + _c.Call.Return(err) + return _c +} + +func (_c *KeyValueStoreStateMachine_EvolveState_Call) RunAndReturn(run func(sealedServiceEvents []flow.ServiceEvent) error) *KeyValueStoreStateMachine_EvolveState_Call { + _c.Call.Return(run) + return _c +} + +// ParentState provides a mock function for the type KeyValueStoreStateMachine +func (_mock *KeyValueStoreStateMachine) ParentState() protocol.KVStoreReader { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ParentState") } var r0 protocol.KVStoreReader - if rf, ok := ret.Get(0).(func() protocol.KVStoreReader); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.KVStoreReader); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol.KVStoreReader) } } - return r0 } -// View provides a mock function with no fields -func (_m *KeyValueStoreStateMachine[P]) View() uint64 { - ret := _m.Called() +// KeyValueStoreStateMachine_ParentState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ParentState' +type KeyValueStoreStateMachine_ParentState_Call struct { + *mock.Call +} + +// ParentState is a helper method to define mock.On call +func (_e *KeyValueStoreStateMachine_Expecter) ParentState() *KeyValueStoreStateMachine_ParentState_Call { + return &KeyValueStoreStateMachine_ParentState_Call{Call: _e.mock.On("ParentState")} +} + +func (_c *KeyValueStoreStateMachine_ParentState_Call) Run(run func()) *KeyValueStoreStateMachine_ParentState_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KeyValueStoreStateMachine_ParentState_Call) Return(kVStoreReader protocol.KVStoreReader) *KeyValueStoreStateMachine_ParentState_Call { + _c.Call.Return(kVStoreReader) + return _c +} + +func (_c *KeyValueStoreStateMachine_ParentState_Call) RunAndReturn(run func() protocol.KVStoreReader) *KeyValueStoreStateMachine_ParentState_Call { + _c.Call.Return(run) + return _c +} + +// View provides a mock function for the type KeyValueStoreStateMachine +func (_mock *KeyValueStoreStateMachine) View() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for View") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewKeyValueStoreStateMachine creates a new instance of KeyValueStoreStateMachine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewKeyValueStoreStateMachine[P any](t interface { - mock.TestingT - Cleanup(func()) -}) *KeyValueStoreStateMachine[P] { - mock := &KeyValueStoreStateMachine[P]{} - mock.Mock.Test(t) +// KeyValueStoreStateMachine_View_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'View' +type KeyValueStoreStateMachine_View_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// View is a helper method to define mock.On call +func (_e *KeyValueStoreStateMachine_Expecter) View() *KeyValueStoreStateMachine_View_Call { + return &KeyValueStoreStateMachine_View_Call{Call: _e.mock.On("View")} +} - return mock +func (_c *KeyValueStoreStateMachine_View_Call) Run(run func()) *KeyValueStoreStateMachine_View_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KeyValueStoreStateMachine_View_Call) Return(v uint64) *KeyValueStoreStateMachine_View_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KeyValueStoreStateMachine_View_Call) RunAndReturn(run func() uint64) *KeyValueStoreStateMachine_View_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/mock/key_value_store_state_machine_factory.go b/state/protocol/protocol_state/mock/key_value_store_state_machine_factory.go index 29e874b7355..fc1f1491900 100644 --- a/state/protocol/protocol_state/mock/key_value_store_state_machine_factory.go +++ b/state/protocol/protocol_state/mock/key_value_store_state_machine_factory.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/state/protocol/protocol_state" mock "github.com/stretchr/testify/mock" +) - protocol "github.com/onflow/flow-go/state/protocol" +// NewKeyValueStoreStateMachineFactory creates a new instance of KeyValueStoreStateMachineFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewKeyValueStoreStateMachineFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *KeyValueStoreStateMachineFactory { + mock := &KeyValueStoreStateMachineFactory{} + mock.Mock.Test(t) - protocol_state "github.com/onflow/flow-go/state/protocol/protocol_state" -) + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // KeyValueStoreStateMachineFactory is an autogenerated mock type for the KeyValueStoreStateMachineFactory type type KeyValueStoreStateMachineFactory struct { mock.Mock } -// Create provides a mock function with given fields: candidateView, parentID, parentState, mutator -func (_m *KeyValueStoreStateMachineFactory) Create(candidateView uint64, parentID flow.Identifier, parentState protocol.KVStoreReader, mutator protocol_state.KVStoreMutator) (protocol_state.KeyValueStoreStateMachine, error) { - ret := _m.Called(candidateView, parentID, parentState, mutator) +type KeyValueStoreStateMachineFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *KeyValueStoreStateMachineFactory) EXPECT() *KeyValueStoreStateMachineFactory_Expecter { + return &KeyValueStoreStateMachineFactory_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type KeyValueStoreStateMachineFactory +func (_mock *KeyValueStoreStateMachineFactory) Create(candidateView uint64, parentID flow.Identifier, parentState protocol.KVStoreReader, mutator protocol_state.KVStoreMutator) (protocol_state.KeyValueStoreStateMachine, error) { + ret := _mock.Called(candidateView, parentID, parentState, mutator) if len(ret) == 0 { panic("no return value specified for Create") @@ -26,36 +48,72 @@ func (_m *KeyValueStoreStateMachineFactory) Create(candidateView uint64, parentI var r0 protocol_state.KeyValueStoreStateMachine var r1 error - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier, protocol.KVStoreReader, protocol_state.KVStoreMutator) (protocol_state.KeyValueStoreStateMachine, error)); ok { - return rf(candidateView, parentID, parentState, mutator) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier, protocol.KVStoreReader, protocol_state.KVStoreMutator) (protocol_state.KeyValueStoreStateMachine, error)); ok { + return returnFunc(candidateView, parentID, parentState, mutator) } - if rf, ok := ret.Get(0).(func(uint64, flow.Identifier, protocol.KVStoreReader, protocol_state.KVStoreMutator) protocol_state.KeyValueStoreStateMachine); ok { - r0 = rf(candidateView, parentID, parentState, mutator) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.Identifier, protocol.KVStoreReader, protocol_state.KVStoreMutator) protocol_state.KeyValueStoreStateMachine); ok { + r0 = returnFunc(candidateView, parentID, parentState, mutator) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol_state.KeyValueStoreStateMachine) } } - - if rf, ok := ret.Get(1).(func(uint64, flow.Identifier, protocol.KVStoreReader, protocol_state.KVStoreMutator) error); ok { - r1 = rf(candidateView, parentID, parentState, mutator) + if returnFunc, ok := ret.Get(1).(func(uint64, flow.Identifier, protocol.KVStoreReader, protocol_state.KVStoreMutator) error); ok { + r1 = returnFunc(candidateView, parentID, parentState, mutator) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewKeyValueStoreStateMachineFactory creates a new instance of KeyValueStoreStateMachineFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewKeyValueStoreStateMachineFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *KeyValueStoreStateMachineFactory { - mock := &KeyValueStoreStateMachineFactory{} - mock.Mock.Test(t) +// KeyValueStoreStateMachineFactory_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type KeyValueStoreStateMachineFactory_Create_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Create is a helper method to define mock.On call +// - candidateView uint64 +// - parentID flow.Identifier +// - parentState protocol.KVStoreReader +// - mutator protocol_state.KVStoreMutator +func (_e *KeyValueStoreStateMachineFactory_Expecter) Create(candidateView interface{}, parentID interface{}, parentState interface{}, mutator interface{}) *KeyValueStoreStateMachineFactory_Create_Call { + return &KeyValueStoreStateMachineFactory_Create_Call{Call: _e.mock.On("Create", candidateView, parentID, parentState, mutator)} +} - return mock +func (_c *KeyValueStoreStateMachineFactory_Create_Call) Run(run func(candidateView uint64, parentID flow.Identifier, parentState protocol.KVStoreReader, mutator protocol_state.KVStoreMutator)) *KeyValueStoreStateMachineFactory_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 protocol.KVStoreReader + if args[2] != nil { + arg2 = args[2].(protocol.KVStoreReader) + } + var arg3 protocol_state.KVStoreMutator + if args[3] != nil { + arg3 = args[3].(protocol_state.KVStoreMutator) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *KeyValueStoreStateMachineFactory_Create_Call) Return(v protocol_state.KeyValueStoreStateMachine, err error) *KeyValueStoreStateMachineFactory_Create_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *KeyValueStoreStateMachineFactory_Create_Call) RunAndReturn(run func(candidateView uint64, parentID flow.Identifier, parentState protocol.KVStoreReader, mutator protocol_state.KVStoreMutator) (protocol_state.KeyValueStoreStateMachine, error)) *KeyValueStoreStateMachineFactory_Create_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/mock/kv_store_api.go b/state/protocol/protocol_state/mock/kv_store_api.go index 214482e93ba..2f529563ed8 100644 --- a/state/protocol/protocol_state/mock/kv_store_api.go +++ b/state/protocol/protocol_state/mock/kv_store_api.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/state/protocol/protocol_state" mock "github.com/stretchr/testify/mock" +) + +// NewKVStoreAPI creates a new instance of KVStoreAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewKVStoreAPI(t interface { + mock.TestingT + Cleanup(func()) +}) *KVStoreAPI { + mock := &KVStoreAPI{} + mock.Mock.Test(t) - protocol "github.com/onflow/flow-go/state/protocol" + t.Cleanup(func() { mock.AssertExpectations(t) }) - protocol_state "github.com/onflow/flow-go/state/protocol/protocol_state" -) + return mock +} // KVStoreAPI is an autogenerated mock type for the KVStoreAPI type type KVStoreAPI struct { mock.Mock } -// GetCadenceComponentVersion provides a mock function with no fields -func (_m *KVStoreAPI) GetCadenceComponentVersion() (protocol.MagnitudeVersion, error) { - ret := _m.Called() +type KVStoreAPI_Expecter struct { + mock *mock.Mock +} + +func (_m *KVStoreAPI) EXPECT() *KVStoreAPI_Expecter { + return &KVStoreAPI_Expecter{mock: &_m.Mock} +} + +// GetCadenceComponentVersion provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetCadenceComponentVersion() (protocol.MagnitudeVersion, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetCadenceComponentVersion") @@ -26,85 +48,188 @@ func (_m *KVStoreAPI) GetCadenceComponentVersion() (protocol.MagnitudeVersion, e var r0 protocol.MagnitudeVersion var r1 error - if rf, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.MagnitudeVersion) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCadenceComponentVersionUpgrade provides a mock function with no fields -func (_m *KVStoreAPI) GetCadenceComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { - ret := _m.Called() +// KVStoreAPI_GetCadenceComponentVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCadenceComponentVersion' +type KVStoreAPI_GetCadenceComponentVersion_Call struct { + *mock.Call +} + +// GetCadenceComponentVersion is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetCadenceComponentVersion() *KVStoreAPI_GetCadenceComponentVersion_Call { + return &KVStoreAPI_GetCadenceComponentVersion_Call{Call: _e.mock.On("GetCadenceComponentVersion")} +} + +func (_c *KVStoreAPI_GetCadenceComponentVersion_Call) Run(run func()) *KVStoreAPI_GetCadenceComponentVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetCadenceComponentVersion_Call) Return(magnitudeVersion protocol.MagnitudeVersion, err error) *KVStoreAPI_GetCadenceComponentVersion_Call { + _c.Call.Return(magnitudeVersion, err) + return _c +} + +func (_c *KVStoreAPI_GetCadenceComponentVersion_Call) RunAndReturn(run func() (protocol.MagnitudeVersion, error)) *KVStoreAPI_GetCadenceComponentVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetCadenceComponentVersionUpgrade provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetCadenceComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetCadenceComponentVersionUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.MagnitudeVersion] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.MagnitudeVersion]) } } - return r0 } -// GetEpochExtensionViewCount provides a mock function with no fields -func (_m *KVStoreAPI) GetEpochExtensionViewCount() uint64 { - ret := _m.Called() +// KVStoreAPI_GetCadenceComponentVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCadenceComponentVersionUpgrade' +type KVStoreAPI_GetCadenceComponentVersionUpgrade_Call struct { + *mock.Call +} + +// GetCadenceComponentVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetCadenceComponentVersionUpgrade() *KVStoreAPI_GetCadenceComponentVersionUpgrade_Call { + return &KVStoreAPI_GetCadenceComponentVersionUpgrade_Call{Call: _e.mock.On("GetCadenceComponentVersionUpgrade")} +} + +func (_c *KVStoreAPI_GetCadenceComponentVersionUpgrade_Call) Run(run func()) *KVStoreAPI_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetCadenceComponentVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreAPI_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreAPI_GetCadenceComponentVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreAPI_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetEpochExtensionViewCount provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetEpochExtensionViewCount() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetEpochExtensionViewCount") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetEpochStateID provides a mock function with no fields -func (_m *KVStoreAPI) GetEpochStateID() flow.Identifier { - ret := _m.Called() +// KVStoreAPI_GetEpochExtensionViewCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEpochExtensionViewCount' +type KVStoreAPI_GetEpochExtensionViewCount_Call struct { + *mock.Call +} + +// GetEpochExtensionViewCount is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetEpochExtensionViewCount() *KVStoreAPI_GetEpochExtensionViewCount_Call { + return &KVStoreAPI_GetEpochExtensionViewCount_Call{Call: _e.mock.On("GetEpochExtensionViewCount")} +} + +func (_c *KVStoreAPI_GetEpochExtensionViewCount_Call) Run(run func()) *KVStoreAPI_GetEpochExtensionViewCount_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetEpochExtensionViewCount_Call) Return(v uint64) *KVStoreAPI_GetEpochExtensionViewCount_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreAPI_GetEpochExtensionViewCount_Call) RunAndReturn(run func() uint64) *KVStoreAPI_GetEpochExtensionViewCount_Call { + _c.Call.Return(run) + return _c +} + +// GetEpochStateID provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetEpochStateID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetEpochStateID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// GetExecutionComponentVersion provides a mock function with no fields -func (_m *KVStoreAPI) GetExecutionComponentVersion() (protocol.MagnitudeVersion, error) { - ret := _m.Called() +// KVStoreAPI_GetEpochStateID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEpochStateID' +type KVStoreAPI_GetEpochStateID_Call struct { + *mock.Call +} + +// GetEpochStateID is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetEpochStateID() *KVStoreAPI_GetEpochStateID_Call { + return &KVStoreAPI_GetEpochStateID_Call{Call: _e.mock.On("GetEpochStateID")} +} + +func (_c *KVStoreAPI_GetEpochStateID_Call) Run(run func()) *KVStoreAPI_GetEpochStateID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetEpochStateID_Call) Return(identifier flow.Identifier) *KVStoreAPI_GetEpochStateID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *KVStoreAPI_GetEpochStateID_Call) RunAndReturn(run func() flow.Identifier) *KVStoreAPI_GetEpochStateID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionComponentVersion provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetExecutionComponentVersion() (protocol.MagnitudeVersion, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionComponentVersion") @@ -112,47 +237,98 @@ func (_m *KVStoreAPI) GetExecutionComponentVersion() (protocol.MagnitudeVersion, var r0 protocol.MagnitudeVersion var r1 error - if rf, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.MagnitudeVersion) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionComponentVersionUpgrade provides a mock function with no fields -func (_m *KVStoreAPI) GetExecutionComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { - ret := _m.Called() +// KVStoreAPI_GetExecutionComponentVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionComponentVersion' +type KVStoreAPI_GetExecutionComponentVersion_Call struct { + *mock.Call +} + +// GetExecutionComponentVersion is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetExecutionComponentVersion() *KVStoreAPI_GetExecutionComponentVersion_Call { + return &KVStoreAPI_GetExecutionComponentVersion_Call{Call: _e.mock.On("GetExecutionComponentVersion")} +} + +func (_c *KVStoreAPI_GetExecutionComponentVersion_Call) Run(run func()) *KVStoreAPI_GetExecutionComponentVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetExecutionComponentVersion_Call) Return(magnitudeVersion protocol.MagnitudeVersion, err error) *KVStoreAPI_GetExecutionComponentVersion_Call { + _c.Call.Return(magnitudeVersion, err) + return _c +} + +func (_c *KVStoreAPI_GetExecutionComponentVersion_Call) RunAndReturn(run func() (protocol.MagnitudeVersion, error)) *KVStoreAPI_GetExecutionComponentVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionComponentVersionUpgrade provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetExecutionComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionComponentVersionUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.MagnitudeVersion] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.MagnitudeVersion]) } } - return r0 } -// GetExecutionMeteringParameters provides a mock function with no fields -func (_m *KVStoreAPI) GetExecutionMeteringParameters() (protocol.ExecutionMeteringParameters, error) { - ret := _m.Called() +// KVStoreAPI_GetExecutionComponentVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionComponentVersionUpgrade' +type KVStoreAPI_GetExecutionComponentVersionUpgrade_Call struct { + *mock.Call +} + +// GetExecutionComponentVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetExecutionComponentVersionUpgrade() *KVStoreAPI_GetExecutionComponentVersionUpgrade_Call { + return &KVStoreAPI_GetExecutionComponentVersionUpgrade_Call{Call: _e.mock.On("GetExecutionComponentVersionUpgrade")} +} + +func (_c *KVStoreAPI_GetExecutionComponentVersionUpgrade_Call) Run(run func()) *KVStoreAPI_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetExecutionComponentVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreAPI_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreAPI_GetExecutionComponentVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreAPI_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionMeteringParameters provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetExecutionMeteringParameters() (protocol.ExecutionMeteringParameters, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionMeteringParameters") @@ -160,123 +336,278 @@ func (_m *KVStoreAPI) GetExecutionMeteringParameters() (protocol.ExecutionMeteri var r0 protocol.ExecutionMeteringParameters var r1 error - if rf, ok := ret.Get(0).(func() (protocol.ExecutionMeteringParameters, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.ExecutionMeteringParameters, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.ExecutionMeteringParameters); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.ExecutionMeteringParameters); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.ExecutionMeteringParameters) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionMeteringParametersUpgrade provides a mock function with no fields -func (_m *KVStoreAPI) GetExecutionMeteringParametersUpgrade() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] { - ret := _m.Called() +// KVStoreAPI_GetExecutionMeteringParameters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionMeteringParameters' +type KVStoreAPI_GetExecutionMeteringParameters_Call struct { + *mock.Call +} + +// GetExecutionMeteringParameters is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetExecutionMeteringParameters() *KVStoreAPI_GetExecutionMeteringParameters_Call { + return &KVStoreAPI_GetExecutionMeteringParameters_Call{Call: _e.mock.On("GetExecutionMeteringParameters")} +} + +func (_c *KVStoreAPI_GetExecutionMeteringParameters_Call) Run(run func()) *KVStoreAPI_GetExecutionMeteringParameters_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetExecutionMeteringParameters_Call) Return(executionMeteringParameters protocol.ExecutionMeteringParameters, err error) *KVStoreAPI_GetExecutionMeteringParameters_Call { + _c.Call.Return(executionMeteringParameters, err) + return _c +} + +func (_c *KVStoreAPI_GetExecutionMeteringParameters_Call) RunAndReturn(run func() (protocol.ExecutionMeteringParameters, error)) *KVStoreAPI_GetExecutionMeteringParameters_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionMeteringParametersUpgrade provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetExecutionMeteringParametersUpgrade() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionMeteringParametersUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) } } - return r0 } -// GetFinalizationSafetyThreshold provides a mock function with no fields -func (_m *KVStoreAPI) GetFinalizationSafetyThreshold() uint64 { - ret := _m.Called() +// KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionMeteringParametersUpgrade' +type KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call struct { + *mock.Call +} + +// GetExecutionMeteringParametersUpgrade is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetExecutionMeteringParametersUpgrade() *KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call { + return &KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call{Call: _e.mock.On("GetExecutionMeteringParametersUpgrade")} +} + +func (_c *KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call) Run(run func()) *KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) *KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) *KVStoreAPI_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetFinalizationSafetyThreshold provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetFinalizationSafetyThreshold() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetFinalizationSafetyThreshold") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetProtocolStateVersion provides a mock function with no fields -func (_m *KVStoreAPI) GetProtocolStateVersion() uint64 { - ret := _m.Called() +// KVStoreAPI_GetFinalizationSafetyThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFinalizationSafetyThreshold' +type KVStoreAPI_GetFinalizationSafetyThreshold_Call struct { + *mock.Call +} + +// GetFinalizationSafetyThreshold is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetFinalizationSafetyThreshold() *KVStoreAPI_GetFinalizationSafetyThreshold_Call { + return &KVStoreAPI_GetFinalizationSafetyThreshold_Call{Call: _e.mock.On("GetFinalizationSafetyThreshold")} +} + +func (_c *KVStoreAPI_GetFinalizationSafetyThreshold_Call) Run(run func()) *KVStoreAPI_GetFinalizationSafetyThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetFinalizationSafetyThreshold_Call) Return(v uint64) *KVStoreAPI_GetFinalizationSafetyThreshold_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreAPI_GetFinalizationSafetyThreshold_Call) RunAndReturn(run func() uint64) *KVStoreAPI_GetFinalizationSafetyThreshold_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateVersion provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetProtocolStateVersion() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetProtocolStateVersion") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetVersionUpgrade provides a mock function with no fields -func (_m *KVStoreAPI) GetVersionUpgrade() *protocol.ViewBasedActivator[uint64] { - ret := _m.Called() +// KVStoreAPI_GetProtocolStateVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateVersion' +type KVStoreAPI_GetProtocolStateVersion_Call struct { + *mock.Call +} + +// GetProtocolStateVersion is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetProtocolStateVersion() *KVStoreAPI_GetProtocolStateVersion_Call { + return &KVStoreAPI_GetProtocolStateVersion_Call{Call: _e.mock.On("GetProtocolStateVersion")} +} + +func (_c *KVStoreAPI_GetProtocolStateVersion_Call) Run(run func()) *KVStoreAPI_GetProtocolStateVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetProtocolStateVersion_Call) Return(v uint64) *KVStoreAPI_GetProtocolStateVersion_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreAPI_GetProtocolStateVersion_Call) RunAndReturn(run func() uint64) *KVStoreAPI_GetProtocolStateVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetVersionUpgrade provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) GetVersionUpgrade() *protocol.ViewBasedActivator[uint64] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetVersionUpgrade") } var r0 *protocol.ViewBasedActivator[uint64] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[uint64]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[uint64]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[uint64]) } } - return r0 } -// ID provides a mock function with no fields -func (_m *KVStoreAPI) ID() flow.Identifier { - ret := _m.Called() +// KVStoreAPI_GetVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVersionUpgrade' +type KVStoreAPI_GetVersionUpgrade_Call struct { + *mock.Call +} + +// GetVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) GetVersionUpgrade() *KVStoreAPI_GetVersionUpgrade_Call { + return &KVStoreAPI_GetVersionUpgrade_Call{Call: _e.mock.On("GetVersionUpgrade")} +} + +func (_c *KVStoreAPI_GetVersionUpgrade_Call) Run(run func()) *KVStoreAPI_GetVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_GetVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[uint64]) *KVStoreAPI_GetVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreAPI_GetVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[uint64]) *KVStoreAPI_GetVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// ID provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) ID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// Replicate provides a mock function with given fields: protocolVersion -func (_m *KVStoreAPI) Replicate(protocolVersion uint64) (protocol_state.KVStoreMutator, error) { - ret := _m.Called(protocolVersion) +// KVStoreAPI_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type KVStoreAPI_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) ID() *KVStoreAPI_ID_Call { + return &KVStoreAPI_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *KVStoreAPI_ID_Call) Run(run func()) *KVStoreAPI_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_ID_Call) Return(identifier flow.Identifier) *KVStoreAPI_ID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *KVStoreAPI_ID_Call) RunAndReturn(run func() flow.Identifier) *KVStoreAPI_ID_Call { + _c.Call.Return(run) + return _c +} + +// Replicate provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) Replicate(protocolVersion uint64) (protocol_state.KVStoreMutator, error) { + ret := _mock.Called(protocolVersion) if len(ret) == 0 { panic("no return value specified for Replicate") @@ -284,29 +615,61 @@ func (_m *KVStoreAPI) Replicate(protocolVersion uint64) (protocol_state.KVStoreM var r0 protocol_state.KVStoreMutator var r1 error - if rf, ok := ret.Get(0).(func(uint64) (protocol_state.KVStoreMutator, error)); ok { - return rf(protocolVersion) + if returnFunc, ok := ret.Get(0).(func(uint64) (protocol_state.KVStoreMutator, error)); ok { + return returnFunc(protocolVersion) } - if rf, ok := ret.Get(0).(func(uint64) protocol_state.KVStoreMutator); ok { - r0 = rf(protocolVersion) + if returnFunc, ok := ret.Get(0).(func(uint64) protocol_state.KVStoreMutator); ok { + r0 = returnFunc(protocolVersion) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol_state.KVStoreMutator) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(protocolVersion) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(protocolVersion) } else { r1 = ret.Error(1) } - return r0, r1 } -// VersionedEncode provides a mock function with no fields -func (_m *KVStoreAPI) VersionedEncode() (uint64, []byte, error) { - ret := _m.Called() +// KVStoreAPI_Replicate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Replicate' +type KVStoreAPI_Replicate_Call struct { + *mock.Call +} + +// Replicate is a helper method to define mock.On call +// - protocolVersion uint64 +func (_e *KVStoreAPI_Expecter) Replicate(protocolVersion interface{}) *KVStoreAPI_Replicate_Call { + return &KVStoreAPI_Replicate_Call{Call: _e.mock.On("Replicate", protocolVersion)} +} + +func (_c *KVStoreAPI_Replicate_Call) Run(run func(protocolVersion uint64)) *KVStoreAPI_Replicate_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *KVStoreAPI_Replicate_Call) Return(kVStoreMutator protocol_state.KVStoreMutator, err error) *KVStoreAPI_Replicate_Call { + _c.Call.Return(kVStoreMutator, err) + return _c +} + +func (_c *KVStoreAPI_Replicate_Call) RunAndReturn(run func(protocolVersion uint64) (protocol_state.KVStoreMutator, error)) *KVStoreAPI_Replicate_Call { + _c.Call.Return(run) + return _c +} + +// VersionedEncode provides a mock function for the type KVStoreAPI +func (_mock *KVStoreAPI) VersionedEncode() (uint64, []byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for VersionedEncode") @@ -315,42 +678,52 @@ func (_m *KVStoreAPI) VersionedEncode() (uint64, []byte, error) { var r0 uint64 var r1 []byte var r2 error - if rf, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() []byte); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() []byte); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]byte) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewKVStoreAPI creates a new instance of KVStoreAPI. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewKVStoreAPI(t interface { - mock.TestingT - Cleanup(func()) -}) *KVStoreAPI { - mock := &KVStoreAPI{} - mock.Mock.Test(t) +// KVStoreAPI_VersionedEncode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VersionedEncode' +type KVStoreAPI_VersionedEncode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VersionedEncode is a helper method to define mock.On call +func (_e *KVStoreAPI_Expecter) VersionedEncode() *KVStoreAPI_VersionedEncode_Call { + return &KVStoreAPI_VersionedEncode_Call{Call: _e.mock.On("VersionedEncode")} +} - return mock +func (_c *KVStoreAPI_VersionedEncode_Call) Run(run func()) *KVStoreAPI_VersionedEncode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreAPI_VersionedEncode_Call) Return(v uint64, bytes []byte, err error) *KVStoreAPI_VersionedEncode_Call { + _c.Call.Return(v, bytes, err) + return _c +} + +func (_c *KVStoreAPI_VersionedEncode_Call) RunAndReturn(run func() (uint64, []byte, error)) *KVStoreAPI_VersionedEncode_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/mock/kv_store_mutator.go b/state/protocol/protocol_state/mock/kv_store_mutator.go index 82226218dfb..1bb72c64bc3 100644 --- a/state/protocol/protocol_state/mock/kv_store_mutator.go +++ b/state/protocol/protocol_state/mock/kv_store_mutator.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" mock "github.com/stretchr/testify/mock" - - protocol "github.com/onflow/flow-go/state/protocol" ) +// NewKVStoreMutator creates a new instance of KVStoreMutator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewKVStoreMutator(t interface { + mock.TestingT + Cleanup(func()) +}) *KVStoreMutator { + mock := &KVStoreMutator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // KVStoreMutator is an autogenerated mock type for the KVStoreMutator type type KVStoreMutator struct { mock.Mock } -// GetCadenceComponentVersion provides a mock function with no fields -func (_m *KVStoreMutator) GetCadenceComponentVersion() (protocol.MagnitudeVersion, error) { - ret := _m.Called() +type KVStoreMutator_Expecter struct { + mock *mock.Mock +} + +func (_m *KVStoreMutator) EXPECT() *KVStoreMutator_Expecter { + return &KVStoreMutator_Expecter{mock: &_m.Mock} +} + +// GetCadenceComponentVersion provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetCadenceComponentVersion() (protocol.MagnitudeVersion, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetCadenceComponentVersion") @@ -24,85 +47,188 @@ func (_m *KVStoreMutator) GetCadenceComponentVersion() (protocol.MagnitudeVersio var r0 protocol.MagnitudeVersion var r1 error - if rf, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.MagnitudeVersion) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetCadenceComponentVersionUpgrade provides a mock function with no fields -func (_m *KVStoreMutator) GetCadenceComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { - ret := _m.Called() +// KVStoreMutator_GetCadenceComponentVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCadenceComponentVersion' +type KVStoreMutator_GetCadenceComponentVersion_Call struct { + *mock.Call +} + +// GetCadenceComponentVersion is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetCadenceComponentVersion() *KVStoreMutator_GetCadenceComponentVersion_Call { + return &KVStoreMutator_GetCadenceComponentVersion_Call{Call: _e.mock.On("GetCadenceComponentVersion")} +} + +func (_c *KVStoreMutator_GetCadenceComponentVersion_Call) Run(run func()) *KVStoreMutator_GetCadenceComponentVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetCadenceComponentVersion_Call) Return(magnitudeVersion protocol.MagnitudeVersion, err error) *KVStoreMutator_GetCadenceComponentVersion_Call { + _c.Call.Return(magnitudeVersion, err) + return _c +} + +func (_c *KVStoreMutator_GetCadenceComponentVersion_Call) RunAndReturn(run func() (protocol.MagnitudeVersion, error)) *KVStoreMutator_GetCadenceComponentVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetCadenceComponentVersionUpgrade provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetCadenceComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetCadenceComponentVersionUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.MagnitudeVersion] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.MagnitudeVersion]) } } - return r0 } -// GetEpochExtensionViewCount provides a mock function with no fields -func (_m *KVStoreMutator) GetEpochExtensionViewCount() uint64 { - ret := _m.Called() +// KVStoreMutator_GetCadenceComponentVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCadenceComponentVersionUpgrade' +type KVStoreMutator_GetCadenceComponentVersionUpgrade_Call struct { + *mock.Call +} + +// GetCadenceComponentVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetCadenceComponentVersionUpgrade() *KVStoreMutator_GetCadenceComponentVersionUpgrade_Call { + return &KVStoreMutator_GetCadenceComponentVersionUpgrade_Call{Call: _e.mock.On("GetCadenceComponentVersionUpgrade")} +} + +func (_c *KVStoreMutator_GetCadenceComponentVersionUpgrade_Call) Run(run func()) *KVStoreMutator_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetCadenceComponentVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreMutator_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreMutator_GetCadenceComponentVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreMutator_GetCadenceComponentVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetEpochExtensionViewCount provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetEpochExtensionViewCount() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetEpochExtensionViewCount") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetEpochStateID provides a mock function with no fields -func (_m *KVStoreMutator) GetEpochStateID() flow.Identifier { - ret := _m.Called() +// KVStoreMutator_GetEpochExtensionViewCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEpochExtensionViewCount' +type KVStoreMutator_GetEpochExtensionViewCount_Call struct { + *mock.Call +} + +// GetEpochExtensionViewCount is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetEpochExtensionViewCount() *KVStoreMutator_GetEpochExtensionViewCount_Call { + return &KVStoreMutator_GetEpochExtensionViewCount_Call{Call: _e.mock.On("GetEpochExtensionViewCount")} +} + +func (_c *KVStoreMutator_GetEpochExtensionViewCount_Call) Run(run func()) *KVStoreMutator_GetEpochExtensionViewCount_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetEpochExtensionViewCount_Call) Return(v uint64) *KVStoreMutator_GetEpochExtensionViewCount_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreMutator_GetEpochExtensionViewCount_Call) RunAndReturn(run func() uint64) *KVStoreMutator_GetEpochExtensionViewCount_Call { + _c.Call.Return(run) + return _c +} + +// GetEpochStateID provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetEpochStateID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetEpochStateID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// GetExecutionComponentVersion provides a mock function with no fields -func (_m *KVStoreMutator) GetExecutionComponentVersion() (protocol.MagnitudeVersion, error) { - ret := _m.Called() +// KVStoreMutator_GetEpochStateID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetEpochStateID' +type KVStoreMutator_GetEpochStateID_Call struct { + *mock.Call +} + +// GetEpochStateID is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetEpochStateID() *KVStoreMutator_GetEpochStateID_Call { + return &KVStoreMutator_GetEpochStateID_Call{Call: _e.mock.On("GetEpochStateID")} +} + +func (_c *KVStoreMutator_GetEpochStateID_Call) Run(run func()) *KVStoreMutator_GetEpochStateID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetEpochStateID_Call) Return(identifier flow.Identifier) *KVStoreMutator_GetEpochStateID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *KVStoreMutator_GetEpochStateID_Call) RunAndReturn(run func() flow.Identifier) *KVStoreMutator_GetEpochStateID_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionComponentVersion provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetExecutionComponentVersion() (protocol.MagnitudeVersion, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionComponentVersion") @@ -110,47 +236,98 @@ func (_m *KVStoreMutator) GetExecutionComponentVersion() (protocol.MagnitudeVers var r0 protocol.MagnitudeVersion var r1 error - if rf, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.MagnitudeVersion, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.MagnitudeVersion); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.MagnitudeVersion) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionComponentVersionUpgrade provides a mock function with no fields -func (_m *KVStoreMutator) GetExecutionComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { - ret := _m.Called() +// KVStoreMutator_GetExecutionComponentVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionComponentVersion' +type KVStoreMutator_GetExecutionComponentVersion_Call struct { + *mock.Call +} + +// GetExecutionComponentVersion is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetExecutionComponentVersion() *KVStoreMutator_GetExecutionComponentVersion_Call { + return &KVStoreMutator_GetExecutionComponentVersion_Call{Call: _e.mock.On("GetExecutionComponentVersion")} +} + +func (_c *KVStoreMutator_GetExecutionComponentVersion_Call) Run(run func()) *KVStoreMutator_GetExecutionComponentVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetExecutionComponentVersion_Call) Return(magnitudeVersion protocol.MagnitudeVersion, err error) *KVStoreMutator_GetExecutionComponentVersion_Call { + _c.Call.Return(magnitudeVersion, err) + return _c +} + +func (_c *KVStoreMutator_GetExecutionComponentVersion_Call) RunAndReturn(run func() (protocol.MagnitudeVersion, error)) *KVStoreMutator_GetExecutionComponentVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionComponentVersionUpgrade provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetExecutionComponentVersionUpgrade() *protocol.ViewBasedActivator[protocol.MagnitudeVersion] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionComponentVersionUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.MagnitudeVersion] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.MagnitudeVersion]) } } - return r0 } -// GetExecutionMeteringParameters provides a mock function with no fields -func (_m *KVStoreMutator) GetExecutionMeteringParameters() (protocol.ExecutionMeteringParameters, error) { - ret := _m.Called() +// KVStoreMutator_GetExecutionComponentVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionComponentVersionUpgrade' +type KVStoreMutator_GetExecutionComponentVersionUpgrade_Call struct { + *mock.Call +} + +// GetExecutionComponentVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetExecutionComponentVersionUpgrade() *KVStoreMutator_GetExecutionComponentVersionUpgrade_Call { + return &KVStoreMutator_GetExecutionComponentVersionUpgrade_Call{Call: _e.mock.On("GetExecutionComponentVersionUpgrade")} +} + +func (_c *KVStoreMutator_GetExecutionComponentVersionUpgrade_Call) Run(run func()) *KVStoreMutator_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetExecutionComponentVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreMutator_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreMutator_GetExecutionComponentVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.MagnitudeVersion]) *KVStoreMutator_GetExecutionComponentVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionMeteringParameters provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetExecutionMeteringParameters() (protocol.ExecutionMeteringParameters, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionMeteringParameters") @@ -158,151 +335,409 @@ func (_m *KVStoreMutator) GetExecutionMeteringParameters() (protocol.ExecutionMe var r0 protocol.ExecutionMeteringParameters var r1 error - if rf, ok := ret.Get(0).(func() (protocol.ExecutionMeteringParameters, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (protocol.ExecutionMeteringParameters, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() protocol.ExecutionMeteringParameters); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() protocol.ExecutionMeteringParameters); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(protocol.ExecutionMeteringParameters) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// GetExecutionMeteringParametersUpgrade provides a mock function with no fields -func (_m *KVStoreMutator) GetExecutionMeteringParametersUpgrade() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] { - ret := _m.Called() +// KVStoreMutator_GetExecutionMeteringParameters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionMeteringParameters' +type KVStoreMutator_GetExecutionMeteringParameters_Call struct { + *mock.Call +} + +// GetExecutionMeteringParameters is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetExecutionMeteringParameters() *KVStoreMutator_GetExecutionMeteringParameters_Call { + return &KVStoreMutator_GetExecutionMeteringParameters_Call{Call: _e.mock.On("GetExecutionMeteringParameters")} +} + +func (_c *KVStoreMutator_GetExecutionMeteringParameters_Call) Run(run func()) *KVStoreMutator_GetExecutionMeteringParameters_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetExecutionMeteringParameters_Call) Return(executionMeteringParameters protocol.ExecutionMeteringParameters, err error) *KVStoreMutator_GetExecutionMeteringParameters_Call { + _c.Call.Return(executionMeteringParameters, err) + return _c +} + +func (_c *KVStoreMutator_GetExecutionMeteringParameters_Call) RunAndReturn(run func() (protocol.ExecutionMeteringParameters, error)) *KVStoreMutator_GetExecutionMeteringParameters_Call { + _c.Call.Return(run) + return _c +} + +// GetExecutionMeteringParametersUpgrade provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetExecutionMeteringParametersUpgrade() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetExecutionMeteringParametersUpgrade") } var r0 *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) } } - return r0 } -// GetFinalizationSafetyThreshold provides a mock function with no fields -func (_m *KVStoreMutator) GetFinalizationSafetyThreshold() uint64 { - ret := _m.Called() +// KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetExecutionMeteringParametersUpgrade' +type KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call struct { + *mock.Call +} + +// GetExecutionMeteringParametersUpgrade is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetExecutionMeteringParametersUpgrade() *KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call { + return &KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call{Call: _e.mock.On("GetExecutionMeteringParametersUpgrade")} +} + +func (_c *KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call) Run(run func()) *KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) *KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[protocol.ExecutionMeteringParameters]) *KVStoreMutator_GetExecutionMeteringParametersUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// GetFinalizationSafetyThreshold provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetFinalizationSafetyThreshold() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetFinalizationSafetyThreshold") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetProtocolStateVersion provides a mock function with no fields -func (_m *KVStoreMutator) GetProtocolStateVersion() uint64 { - ret := _m.Called() +// KVStoreMutator_GetFinalizationSafetyThreshold_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFinalizationSafetyThreshold' +type KVStoreMutator_GetFinalizationSafetyThreshold_Call struct { + *mock.Call +} + +// GetFinalizationSafetyThreshold is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetFinalizationSafetyThreshold() *KVStoreMutator_GetFinalizationSafetyThreshold_Call { + return &KVStoreMutator_GetFinalizationSafetyThreshold_Call{Call: _e.mock.On("GetFinalizationSafetyThreshold")} +} + +func (_c *KVStoreMutator_GetFinalizationSafetyThreshold_Call) Run(run func()) *KVStoreMutator_GetFinalizationSafetyThreshold_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetFinalizationSafetyThreshold_Call) Return(v uint64) *KVStoreMutator_GetFinalizationSafetyThreshold_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreMutator_GetFinalizationSafetyThreshold_Call) RunAndReturn(run func() uint64) *KVStoreMutator_GetFinalizationSafetyThreshold_Call { + _c.Call.Return(run) + return _c +} + +// GetProtocolStateVersion provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetProtocolStateVersion() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetProtocolStateVersion") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// GetVersionUpgrade provides a mock function with no fields -func (_m *KVStoreMutator) GetVersionUpgrade() *protocol.ViewBasedActivator[uint64] { - ret := _m.Called() +// KVStoreMutator_GetProtocolStateVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProtocolStateVersion' +type KVStoreMutator_GetProtocolStateVersion_Call struct { + *mock.Call +} + +// GetProtocolStateVersion is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetProtocolStateVersion() *KVStoreMutator_GetProtocolStateVersion_Call { + return &KVStoreMutator_GetProtocolStateVersion_Call{Call: _e.mock.On("GetProtocolStateVersion")} +} + +func (_c *KVStoreMutator_GetProtocolStateVersion_Call) Run(run func()) *KVStoreMutator_GetProtocolStateVersion_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetProtocolStateVersion_Call) Return(v uint64) *KVStoreMutator_GetProtocolStateVersion_Call { + _c.Call.Return(v) + return _c +} + +func (_c *KVStoreMutator_GetProtocolStateVersion_Call) RunAndReturn(run func() uint64) *KVStoreMutator_GetProtocolStateVersion_Call { + _c.Call.Return(run) + return _c +} + +// GetVersionUpgrade provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) GetVersionUpgrade() *protocol.ViewBasedActivator[uint64] { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetVersionUpgrade") } var r0 *protocol.ViewBasedActivator[uint64] - if rf, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[uint64]); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *protocol.ViewBasedActivator[uint64]); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*protocol.ViewBasedActivator[uint64]) } } - return r0 } -// ID provides a mock function with no fields -func (_m *KVStoreMutator) ID() flow.Identifier { - ret := _m.Called() +// KVStoreMutator_GetVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVersionUpgrade' +type KVStoreMutator_GetVersionUpgrade_Call struct { + *mock.Call +} + +// GetVersionUpgrade is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) GetVersionUpgrade() *KVStoreMutator_GetVersionUpgrade_Call { + return &KVStoreMutator_GetVersionUpgrade_Call{Call: _e.mock.On("GetVersionUpgrade")} +} + +func (_c *KVStoreMutator_GetVersionUpgrade_Call) Run(run func()) *KVStoreMutator_GetVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_GetVersionUpgrade_Call) Return(viewBasedActivator *protocol.ViewBasedActivator[uint64]) *KVStoreMutator_GetVersionUpgrade_Call { + _c.Call.Return(viewBasedActivator) + return _c +} + +func (_c *KVStoreMutator_GetVersionUpgrade_Call) RunAndReturn(run func() *protocol.ViewBasedActivator[uint64]) *KVStoreMutator_GetVersionUpgrade_Call { + _c.Call.Return(run) + return _c +} + +// ID provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) ID() flow.Identifier { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ID") } var r0 flow.Identifier - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - return r0 } -// SetEpochExtensionViewCount provides a mock function with given fields: viewCount -func (_m *KVStoreMutator) SetEpochExtensionViewCount(viewCount uint64) error { - ret := _m.Called(viewCount) +// KVStoreMutator_ID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ID' +type KVStoreMutator_ID_Call struct { + *mock.Call +} + +// ID is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) ID() *KVStoreMutator_ID_Call { + return &KVStoreMutator_ID_Call{Call: _e.mock.On("ID")} +} + +func (_c *KVStoreMutator_ID_Call) Run(run func()) *KVStoreMutator_ID_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_ID_Call) Return(identifier flow.Identifier) *KVStoreMutator_ID_Call { + _c.Call.Return(identifier) + return _c +} + +func (_c *KVStoreMutator_ID_Call) RunAndReturn(run func() flow.Identifier) *KVStoreMutator_ID_Call { + _c.Call.Return(run) + return _c +} + +// SetEpochExtensionViewCount provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) SetEpochExtensionViewCount(viewCount uint64) error { + ret := _mock.Called(viewCount) if len(ret) == 0 { panic("no return value specified for SetEpochExtensionViewCount") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(viewCount) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(viewCount) } else { r0 = ret.Error(0) } - return r0 } -// SetEpochStateID provides a mock function with given fields: stateID -func (_m *KVStoreMutator) SetEpochStateID(stateID flow.Identifier) { - _m.Called(stateID) +// KVStoreMutator_SetEpochExtensionViewCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetEpochExtensionViewCount' +type KVStoreMutator_SetEpochExtensionViewCount_Call struct { + *mock.Call } -// SetVersionUpgrade provides a mock function with given fields: version -func (_m *KVStoreMutator) SetVersionUpgrade(version *protocol.ViewBasedActivator[uint64]) { - _m.Called(version) +// SetEpochExtensionViewCount is a helper method to define mock.On call +// - viewCount uint64 +func (_e *KVStoreMutator_Expecter) SetEpochExtensionViewCount(viewCount interface{}) *KVStoreMutator_SetEpochExtensionViewCount_Call { + return &KVStoreMutator_SetEpochExtensionViewCount_Call{Call: _e.mock.On("SetEpochExtensionViewCount", viewCount)} } -// VersionedEncode provides a mock function with no fields -func (_m *KVStoreMutator) VersionedEncode() (uint64, []byte, error) { - ret := _m.Called() +func (_c *KVStoreMutator_SetEpochExtensionViewCount_Call) Run(run func(viewCount uint64)) *KVStoreMutator_SetEpochExtensionViewCount_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *KVStoreMutator_SetEpochExtensionViewCount_Call) Return(err error) *KVStoreMutator_SetEpochExtensionViewCount_Call { + _c.Call.Return(err) + return _c +} + +func (_c *KVStoreMutator_SetEpochExtensionViewCount_Call) RunAndReturn(run func(viewCount uint64) error) *KVStoreMutator_SetEpochExtensionViewCount_Call { + _c.Call.Return(run) + return _c +} + +// SetEpochStateID provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) SetEpochStateID(stateID flow.Identifier) { + _mock.Called(stateID) + return +} + +// KVStoreMutator_SetEpochStateID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetEpochStateID' +type KVStoreMutator_SetEpochStateID_Call struct { + *mock.Call +} + +// SetEpochStateID is a helper method to define mock.On call +// - stateID flow.Identifier +func (_e *KVStoreMutator_Expecter) SetEpochStateID(stateID interface{}) *KVStoreMutator_SetEpochStateID_Call { + return &KVStoreMutator_SetEpochStateID_Call{Call: _e.mock.On("SetEpochStateID", stateID)} +} + +func (_c *KVStoreMutator_SetEpochStateID_Call) Run(run func(stateID flow.Identifier)) *KVStoreMutator_SetEpochStateID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *KVStoreMutator_SetEpochStateID_Call) Return() *KVStoreMutator_SetEpochStateID_Call { + _c.Call.Return() + return _c +} + +func (_c *KVStoreMutator_SetEpochStateID_Call) RunAndReturn(run func(stateID flow.Identifier)) *KVStoreMutator_SetEpochStateID_Call { + _c.Run(run) + return _c +} + +// SetVersionUpgrade provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) SetVersionUpgrade(version *protocol.ViewBasedActivator[uint64]) { + _mock.Called(version) + return +} + +// KVStoreMutator_SetVersionUpgrade_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetVersionUpgrade' +type KVStoreMutator_SetVersionUpgrade_Call struct { + *mock.Call +} + +// SetVersionUpgrade is a helper method to define mock.On call +// - version *protocol.ViewBasedActivator[uint64] +func (_e *KVStoreMutator_Expecter) SetVersionUpgrade(version interface{}) *KVStoreMutator_SetVersionUpgrade_Call { + return &KVStoreMutator_SetVersionUpgrade_Call{Call: _e.mock.On("SetVersionUpgrade", version)} +} + +func (_c *KVStoreMutator_SetVersionUpgrade_Call) Run(run func(version *protocol.ViewBasedActivator[uint64])) *KVStoreMutator_SetVersionUpgrade_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *protocol.ViewBasedActivator[uint64] + if args[0] != nil { + arg0 = args[0].(*protocol.ViewBasedActivator[uint64]) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *KVStoreMutator_SetVersionUpgrade_Call) Return() *KVStoreMutator_SetVersionUpgrade_Call { + _c.Call.Return() + return _c +} + +func (_c *KVStoreMutator_SetVersionUpgrade_Call) RunAndReturn(run func(version *protocol.ViewBasedActivator[uint64])) *KVStoreMutator_SetVersionUpgrade_Call { + _c.Run(run) + return _c +} + +// VersionedEncode provides a mock function for the type KVStoreMutator +func (_mock *KVStoreMutator) VersionedEncode() (uint64, []byte, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for VersionedEncode") @@ -311,42 +746,52 @@ func (_m *KVStoreMutator) VersionedEncode() (uint64, []byte, error) { var r0 uint64 var r1 []byte var r2 error - if rf, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, []byte, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() []byte); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() []byte); ok { + r1 = returnFunc() } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]byte) } } - - if rf, ok := ret.Get(2).(func() error); ok { - r2 = rf() + if returnFunc, ok := ret.Get(2).(func() error); ok { + r2 = returnFunc() } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewKVStoreMutator creates a new instance of KVStoreMutator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewKVStoreMutator(t interface { - mock.TestingT - Cleanup(func()) -}) *KVStoreMutator { - mock := &KVStoreMutator{} - mock.Mock.Test(t) +// KVStoreMutator_VersionedEncode_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VersionedEncode' +type KVStoreMutator_VersionedEncode_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VersionedEncode is a helper method to define mock.On call +func (_e *KVStoreMutator_Expecter) VersionedEncode() *KVStoreMutator_VersionedEncode_Call { + return &KVStoreMutator_VersionedEncode_Call{Call: _e.mock.On("VersionedEncode")} +} - return mock +func (_c *KVStoreMutator_VersionedEncode_Call) Run(run func()) *KVStoreMutator_VersionedEncode_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *KVStoreMutator_VersionedEncode_Call) Return(v uint64, bytes []byte, err error) *KVStoreMutator_VersionedEncode_Call { + _c.Call.Return(v, bytes, err) + return _c +} + +func (_c *KVStoreMutator_VersionedEncode_Call) RunAndReturn(run func() (uint64, []byte, error)) *KVStoreMutator_VersionedEncode_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/mock/orthogonal_store_state_machine.go b/state/protocol/protocol_state/mock/orthogonal_store_state_machine.go index 171d2e55bce..4b2c17c2ce6 100644 --- a/state/protocol/protocol_state/mock/orthogonal_store_state_machine.go +++ b/state/protocol/protocol_state/mock/orthogonal_store_state_machine.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" - deferred "github.com/onflow/flow-go/storage/deferred" - + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage/deferred" mock "github.com/stretchr/testify/mock" ) +// NewOrthogonalStoreStateMachine creates a new instance of OrthogonalStoreStateMachine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewOrthogonalStoreStateMachine[P any](t interface { + mock.TestingT + Cleanup(func()) +}) *OrthogonalStoreStateMachine[P] { + mock := &OrthogonalStoreStateMachine[P]{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // OrthogonalStoreStateMachine is an autogenerated mock type for the OrthogonalStoreStateMachine type type OrthogonalStoreStateMachine[P any] struct { mock.Mock } -// Build provides a mock function with no fields -func (_m *OrthogonalStoreStateMachine[P]) Build() (*deferred.DeferredBlockPersist, error) { - ret := _m.Called() +type OrthogonalStoreStateMachine_Expecter[P any] struct { + mock *mock.Mock +} + +func (_m *OrthogonalStoreStateMachine[P]) EXPECT() *OrthogonalStoreStateMachine_Expecter[P] { + return &OrthogonalStoreStateMachine_Expecter[P]{mock: &_m.Mock} +} + +// Build provides a mock function for the type OrthogonalStoreStateMachine +func (_mock *OrthogonalStoreStateMachine[P]) Build() (*deferred.DeferredBlockPersist, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Build") @@ -24,92 +47,188 @@ func (_m *OrthogonalStoreStateMachine[P]) Build() (*deferred.DeferredBlockPersis var r0 *deferred.DeferredBlockPersist var r1 error - if rf, ok := ret.Get(0).(func() (*deferred.DeferredBlockPersist, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (*deferred.DeferredBlockPersist, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() *deferred.DeferredBlockPersist); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *deferred.DeferredBlockPersist); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*deferred.DeferredBlockPersist) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// EvolveState provides a mock function with given fields: sealedServiceEvents -func (_m *OrthogonalStoreStateMachine[P]) EvolveState(sealedServiceEvents []flow.ServiceEvent) error { - ret := _m.Called(sealedServiceEvents) +// OrthogonalStoreStateMachine_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build' +type OrthogonalStoreStateMachine_Build_Call[P any] struct { + *mock.Call +} + +// Build is a helper method to define mock.On call +func (_e *OrthogonalStoreStateMachine_Expecter[P]) Build() *OrthogonalStoreStateMachine_Build_Call[P] { + return &OrthogonalStoreStateMachine_Build_Call[P]{Call: _e.mock.On("Build")} +} + +func (_c *OrthogonalStoreStateMachine_Build_Call[P]) Run(run func()) *OrthogonalStoreStateMachine_Build_Call[P] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OrthogonalStoreStateMachine_Build_Call[P]) Return(deferredBlockPersist *deferred.DeferredBlockPersist, err error) *OrthogonalStoreStateMachine_Build_Call[P] { + _c.Call.Return(deferredBlockPersist, err) + return _c +} + +func (_c *OrthogonalStoreStateMachine_Build_Call[P]) RunAndReturn(run func() (*deferred.DeferredBlockPersist, error)) *OrthogonalStoreStateMachine_Build_Call[P] { + _c.Call.Return(run) + return _c +} + +// EvolveState provides a mock function for the type OrthogonalStoreStateMachine +func (_mock *OrthogonalStoreStateMachine[P]) EvolveState(sealedServiceEvents []flow.ServiceEvent) error { + ret := _mock.Called(sealedServiceEvents) if len(ret) == 0 { panic("no return value specified for EvolveState") } var r0 error - if rf, ok := ret.Get(0).(func([]flow.ServiceEvent) error); ok { - r0 = rf(sealedServiceEvents) + if returnFunc, ok := ret.Get(0).(func([]flow.ServiceEvent) error); ok { + r0 = returnFunc(sealedServiceEvents) } else { r0 = ret.Error(0) } - return r0 } -// ParentState provides a mock function with no fields -func (_m *OrthogonalStoreStateMachine[P]) ParentState() P { - ret := _m.Called() +// OrthogonalStoreStateMachine_EvolveState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EvolveState' +type OrthogonalStoreStateMachine_EvolveState_Call[P any] struct { + *mock.Call +} + +// EvolveState is a helper method to define mock.On call +// - sealedServiceEvents []flow.ServiceEvent +func (_e *OrthogonalStoreStateMachine_Expecter[P]) EvolveState(sealedServiceEvents interface{}) *OrthogonalStoreStateMachine_EvolveState_Call[P] { + return &OrthogonalStoreStateMachine_EvolveState_Call[P]{Call: _e.mock.On("EvolveState", sealedServiceEvents)} +} + +func (_c *OrthogonalStoreStateMachine_EvolveState_Call[P]) Run(run func(sealedServiceEvents []flow.ServiceEvent)) *OrthogonalStoreStateMachine_EvolveState_Call[P] { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.ServiceEvent + if args[0] != nil { + arg0 = args[0].([]flow.ServiceEvent) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *OrthogonalStoreStateMachine_EvolveState_Call[P]) Return(err error) *OrthogonalStoreStateMachine_EvolveState_Call[P] { + _c.Call.Return(err) + return _c +} + +func (_c *OrthogonalStoreStateMachine_EvolveState_Call[P]) RunAndReturn(run func(sealedServiceEvents []flow.ServiceEvent) error) *OrthogonalStoreStateMachine_EvolveState_Call[P] { + _c.Call.Return(run) + return _c +} + +// ParentState provides a mock function for the type OrthogonalStoreStateMachine +func (_mock *OrthogonalStoreStateMachine[P]) ParentState() P { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ParentState") } var r0 P - if rf, ok := ret.Get(0).(func() P); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() P); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(P) } } - return r0 } -// View provides a mock function with no fields -func (_m *OrthogonalStoreStateMachine[P]) View() uint64 { - ret := _m.Called() +// OrthogonalStoreStateMachine_ParentState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ParentState' +type OrthogonalStoreStateMachine_ParentState_Call[P any] struct { + *mock.Call +} + +// ParentState is a helper method to define mock.On call +func (_e *OrthogonalStoreStateMachine_Expecter[P]) ParentState() *OrthogonalStoreStateMachine_ParentState_Call[P] { + return &OrthogonalStoreStateMachine_ParentState_Call[P]{Call: _e.mock.On("ParentState")} +} + +func (_c *OrthogonalStoreStateMachine_ParentState_Call[P]) Run(run func()) *OrthogonalStoreStateMachine_ParentState_Call[P] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OrthogonalStoreStateMachine_ParentState_Call[P]) Return(v P) *OrthogonalStoreStateMachine_ParentState_Call[P] { + _c.Call.Return(v) + return _c +} + +func (_c *OrthogonalStoreStateMachine_ParentState_Call[P]) RunAndReturn(run func() P) *OrthogonalStoreStateMachine_ParentState_Call[P] { + _c.Call.Return(run) + return _c +} + +// View provides a mock function for the type OrthogonalStoreStateMachine +func (_mock *OrthogonalStoreStateMachine[P]) View() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for View") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewOrthogonalStoreStateMachine creates a new instance of OrthogonalStoreStateMachine. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewOrthogonalStoreStateMachine[P any](t interface { - mock.TestingT - Cleanup(func()) -}) *OrthogonalStoreStateMachine[P] { - mock := &OrthogonalStoreStateMachine[P]{} - mock.Mock.Test(t) +// OrthogonalStoreStateMachine_View_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'View' +type OrthogonalStoreStateMachine_View_Call[P any] struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// View is a helper method to define mock.On call +func (_e *OrthogonalStoreStateMachine_Expecter[P]) View() *OrthogonalStoreStateMachine_View_Call[P] { + return &OrthogonalStoreStateMachine_View_Call[P]{Call: _e.mock.On("View")} +} - return mock +func (_c *OrthogonalStoreStateMachine_View_Call[P]) Run(run func()) *OrthogonalStoreStateMachine_View_Call[P] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *OrthogonalStoreStateMachine_View_Call[P]) Return(v uint64) *OrthogonalStoreStateMachine_View_Call[P] { + _c.Call.Return(v) + return _c +} + +func (_c *OrthogonalStoreStateMachine_View_Call[P]) RunAndReturn(run func() uint64) *OrthogonalStoreStateMachine_View_Call[P] { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/mock/protocol_kv_store.go b/state/protocol/protocol_state/mock/protocol_kv_store.go index 165100b9107..fe8b0f00829 100644 --- a/state/protocol/protocol_state/mock/protocol_kv_store.go +++ b/state/protocol/protocol_state/mock/protocol_kv_store.go @@ -1,64 +1,180 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/state/protocol" + "github.com/onflow/flow-go/state/protocol/protocol_state" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" +) - protocol "github.com/onflow/flow-go/state/protocol" +// NewProtocolKVStore creates a new instance of ProtocolKVStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProtocolKVStore(t interface { + mock.TestingT + Cleanup(func()) +}) *ProtocolKVStore { + mock := &ProtocolKVStore{} + mock.Mock.Test(t) - protocol_state "github.com/onflow/flow-go/state/protocol/protocol_state" + t.Cleanup(func() { mock.AssertExpectations(t) }) - storage "github.com/onflow/flow-go/storage" -) + return mock +} // ProtocolKVStore is an autogenerated mock type for the ProtocolKVStore type type ProtocolKVStore struct { mock.Mock } -// BatchIndex provides a mock function with given fields: lctx, rw, blockID, stateID -func (_m *ProtocolKVStore) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier) error { - ret := _m.Called(lctx, rw, blockID, stateID) +type ProtocolKVStore_Expecter struct { + mock *mock.Mock +} + +func (_m *ProtocolKVStore) EXPECT() *ProtocolKVStore_Expecter { + return &ProtocolKVStore_Expecter{mock: &_m.Mock} +} + +// BatchIndex provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier) error { + ret := _mock.Called(lctx, rw, blockID, stateID) if len(ret) == 0 { panic("no return value specified for BatchIndex") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { - r0 = rf(lctx, rw, blockID, stateID) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, blockID, stateID) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: rw, stateID, kvStore -func (_m *ProtocolKVStore) BatchStore(rw storage.ReaderBatchWriter, stateID flow.Identifier, kvStore protocol.KVStoreReader) error { - ret := _m.Called(rw, stateID, kvStore) +// ProtocolKVStore_BatchIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchIndex' +type ProtocolKVStore_BatchIndex_Call struct { + *mock.Call +} + +// BatchIndex is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - stateID flow.Identifier +func (_e *ProtocolKVStore_Expecter) BatchIndex(lctx interface{}, rw interface{}, blockID interface{}, stateID interface{}) *ProtocolKVStore_BatchIndex_Call { + return &ProtocolKVStore_BatchIndex_Call{Call: _e.mock.On("BatchIndex", lctx, rw, blockID, stateID)} +} + +func (_c *ProtocolKVStore_BatchIndex_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier)) *ProtocolKVStore_BatchIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_BatchIndex_Call) Return(err error) *ProtocolKVStore_BatchIndex_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ProtocolKVStore_BatchIndex_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier) error) *ProtocolKVStore_BatchIndex_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) BatchStore(rw storage.ReaderBatchWriter, stateID flow.Identifier, kvStore protocol.KVStoreReader) error { + ret := _mock.Called(rw, stateID, kvStore) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(storage.ReaderBatchWriter, flow.Identifier, protocol.KVStoreReader) error); ok { - r0 = rf(rw, stateID, kvStore) + if returnFunc, ok := ret.Get(0).(func(storage.ReaderBatchWriter, flow.Identifier, protocol.KVStoreReader) error); ok { + r0 = returnFunc(rw, stateID, kvStore) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *ProtocolKVStore) ByBlockID(blockID flow.Identifier) (protocol_state.KVStoreAPI, error) { - ret := _m.Called(blockID) +// ProtocolKVStore_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type ProtocolKVStore_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - rw storage.ReaderBatchWriter +// - stateID flow.Identifier +// - kvStore protocol.KVStoreReader +func (_e *ProtocolKVStore_Expecter) BatchStore(rw interface{}, stateID interface{}, kvStore interface{}) *ProtocolKVStore_BatchStore_Call { + return &ProtocolKVStore_BatchStore_Call{Call: _e.mock.On("BatchStore", rw, stateID, kvStore)} +} + +func (_c *ProtocolKVStore_BatchStore_Call) Run(run func(rw storage.ReaderBatchWriter, stateID flow.Identifier, kvStore protocol.KVStoreReader)) *ProtocolKVStore_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 storage.ReaderBatchWriter + if args[0] != nil { + arg0 = args[0].(storage.ReaderBatchWriter) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 protocol.KVStoreReader + if args[2] != nil { + arg2 = args[2].(protocol.KVStoreReader) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_BatchStore_Call) Return(err error) *ProtocolKVStore_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ProtocolKVStore_BatchStore_Call) RunAndReturn(run func(rw storage.ReaderBatchWriter, stateID flow.Identifier, kvStore protocol.KVStoreReader) error) *ProtocolKVStore_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) ByBlockID(blockID flow.Identifier) (protocol_state.KVStoreAPI, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -66,29 +182,61 @@ func (_m *ProtocolKVStore) ByBlockID(blockID flow.Identifier) (protocol_state.KV var r0 protocol_state.KVStoreAPI var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (protocol_state.KVStoreAPI, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (protocol_state.KVStoreAPI, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol_state.KVStoreAPI); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol_state.KVStoreAPI); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol_state.KVStoreAPI) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: id -func (_m *ProtocolKVStore) ByID(id flow.Identifier) (protocol_state.KVStoreAPI, error) { - ret := _m.Called(id) +// ProtocolKVStore_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ProtocolKVStore_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ProtocolKVStore_Expecter) ByBlockID(blockID interface{}) *ProtocolKVStore_ByBlockID_Call { + return &ProtocolKVStore_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *ProtocolKVStore_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *ProtocolKVStore_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_ByBlockID_Call) Return(kVStoreAPI protocol_state.KVStoreAPI, err error) *ProtocolKVStore_ByBlockID_Call { + _c.Call.Return(kVStoreAPI, err) + return _c +} + +func (_c *ProtocolKVStore_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (protocol_state.KVStoreAPI, error)) *ProtocolKVStore_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) ByID(id flow.Identifier) (protocol_state.KVStoreAPI, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByID") @@ -96,36 +244,54 @@ func (_m *ProtocolKVStore) ByID(id flow.Identifier) (protocol_state.KVStoreAPI, var r0 protocol_state.KVStoreAPI var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (protocol_state.KVStoreAPI, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (protocol_state.KVStoreAPI, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) protocol_state.KVStoreAPI); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) protocol_state.KVStoreAPI); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(protocol_state.KVStoreAPI) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewProtocolKVStore creates a new instance of ProtocolKVStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProtocolKVStore(t interface { - mock.TestingT - Cleanup(func()) -}) *ProtocolKVStore { - mock := &ProtocolKVStore{} - mock.Mock.Test(t) +// ProtocolKVStore_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ProtocolKVStore_ByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *ProtocolKVStore_Expecter) ByID(id interface{}) *ProtocolKVStore_ByID_Call { + return &ProtocolKVStore_ByID_Call{Call: _e.mock.On("ByID", id)} +} - return mock +func (_c *ProtocolKVStore_ByID_Call) Run(run func(id flow.Identifier)) *ProtocolKVStore_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_ByID_Call) Return(kVStoreAPI protocol_state.KVStoreAPI, err error) *ProtocolKVStore_ByID_Call { + _c.Call.Return(kVStoreAPI, err) + return _c +} + +func (_c *ProtocolKVStore_ByID_Call) RunAndReturn(run func(id flow.Identifier) (protocol_state.KVStoreAPI, error)) *ProtocolKVStore_ByID_Call { + _c.Call.Return(run) + return _c } diff --git a/state/protocol/protocol_state/mock/state_machine_events_telemetry_factory.go b/state/protocol/protocol_state/mock/state_machine_events_telemetry_factory.go deleted file mode 100644 index 315450d6f5d..00000000000 --- a/state/protocol/protocol_state/mock/state_machine_events_telemetry_factory.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mock - -import ( - mock "github.com/stretchr/testify/mock" - - protocol_state "github.com/onflow/flow-go/state/protocol/protocol_state" -) - -// StateMachineEventsTelemetryFactory is an autogenerated mock type for the StateMachineEventsTelemetryFactory type -type StateMachineEventsTelemetryFactory struct { - mock.Mock -} - -// Execute provides a mock function with given fields: candidateView -func (_m *StateMachineEventsTelemetryFactory) Execute(candidateView uint64) protocol_state.StateMachineTelemetryConsumer { - ret := _m.Called(candidateView) - - if len(ret) == 0 { - panic("no return value specified for Execute") - } - - var r0 protocol_state.StateMachineTelemetryConsumer - if rf, ok := ret.Get(0).(func(uint64) protocol_state.StateMachineTelemetryConsumer); ok { - r0 = rf(candidateView) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(protocol_state.StateMachineTelemetryConsumer) - } - } - - return r0 -} - -// NewStateMachineEventsTelemetryFactory creates a new instance of StateMachineEventsTelemetryFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStateMachineEventsTelemetryFactory(t interface { - mock.TestingT - Cleanup(func()) -}) *StateMachineEventsTelemetryFactory { - mock := &StateMachineEventsTelemetryFactory{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/state/protocol/protocol_state/mock/state_machine_telemetry_consumer.go b/state/protocol/protocol_state/mock/state_machine_telemetry_consumer.go index 79a59c3c643..d0995e1bf89 100644 --- a/state/protocol/protocol_state/mock/state_machine_telemetry_consumer.go +++ b/state/protocol/protocol_state/mock/state_machine_telemetry_consumer.go @@ -1,42 +1,163 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewStateMachineTelemetryConsumer creates a new instance of StateMachineTelemetryConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStateMachineTelemetryConsumer(t interface { + mock.TestingT + Cleanup(func()) +}) *StateMachineTelemetryConsumer { + mock := &StateMachineTelemetryConsumer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // StateMachineTelemetryConsumer is an autogenerated mock type for the StateMachineTelemetryConsumer type type StateMachineTelemetryConsumer struct { mock.Mock } -// OnInvalidServiceEvent provides a mock function with given fields: event, err -func (_m *StateMachineTelemetryConsumer) OnInvalidServiceEvent(event flow.ServiceEvent, err error) { - _m.Called(event, err) +type StateMachineTelemetryConsumer_Expecter struct { + mock *mock.Mock } -// OnServiceEventProcessed provides a mock function with given fields: event -func (_m *StateMachineTelemetryConsumer) OnServiceEventProcessed(event flow.ServiceEvent) { - _m.Called(event) +func (_m *StateMachineTelemetryConsumer) EXPECT() *StateMachineTelemetryConsumer_Expecter { + return &StateMachineTelemetryConsumer_Expecter{mock: &_m.Mock} } -// OnServiceEventReceived provides a mock function with given fields: event -func (_m *StateMachineTelemetryConsumer) OnServiceEventReceived(event flow.ServiceEvent) { - _m.Called(event) +// OnInvalidServiceEvent provides a mock function for the type StateMachineTelemetryConsumer +func (_mock *StateMachineTelemetryConsumer) OnInvalidServiceEvent(event flow.ServiceEvent, err error) { + _mock.Called(event, err) + return } -// NewStateMachineTelemetryConsumer creates a new instance of StateMachineTelemetryConsumer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStateMachineTelemetryConsumer(t interface { - mock.TestingT - Cleanup(func()) -}) *StateMachineTelemetryConsumer { - mock := &StateMachineTelemetryConsumer{} - mock.Mock.Test(t) +// StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnInvalidServiceEvent' +type StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// OnInvalidServiceEvent is a helper method to define mock.On call +// - event flow.ServiceEvent +// - err error +func (_e *StateMachineTelemetryConsumer_Expecter) OnInvalidServiceEvent(event interface{}, err interface{}) *StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call { + return &StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call{Call: _e.mock.On("OnInvalidServiceEvent", event, err)} +} - return mock +func (_c *StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call) Run(run func(event flow.ServiceEvent, err error)) *StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ServiceEvent + if args[0] != nil { + arg0 = args[0].(flow.ServiceEvent) + } + var arg1 error + if args[1] != nil { + arg1 = args[1].(error) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call) Return() *StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call { + _c.Call.Return() + return _c +} + +func (_c *StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call) RunAndReturn(run func(event flow.ServiceEvent, err error)) *StateMachineTelemetryConsumer_OnInvalidServiceEvent_Call { + _c.Run(run) + return _c +} + +// OnServiceEventProcessed provides a mock function for the type StateMachineTelemetryConsumer +func (_mock *StateMachineTelemetryConsumer) OnServiceEventProcessed(event flow.ServiceEvent) { + _mock.Called(event) + return +} + +// StateMachineTelemetryConsumer_OnServiceEventProcessed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnServiceEventProcessed' +type StateMachineTelemetryConsumer_OnServiceEventProcessed_Call struct { + *mock.Call +} + +// OnServiceEventProcessed is a helper method to define mock.On call +// - event flow.ServiceEvent +func (_e *StateMachineTelemetryConsumer_Expecter) OnServiceEventProcessed(event interface{}) *StateMachineTelemetryConsumer_OnServiceEventProcessed_Call { + return &StateMachineTelemetryConsumer_OnServiceEventProcessed_Call{Call: _e.mock.On("OnServiceEventProcessed", event)} +} + +func (_c *StateMachineTelemetryConsumer_OnServiceEventProcessed_Call) Run(run func(event flow.ServiceEvent)) *StateMachineTelemetryConsumer_OnServiceEventProcessed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ServiceEvent + if args[0] != nil { + arg0 = args[0].(flow.ServiceEvent) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StateMachineTelemetryConsumer_OnServiceEventProcessed_Call) Return() *StateMachineTelemetryConsumer_OnServiceEventProcessed_Call { + _c.Call.Return() + return _c +} + +func (_c *StateMachineTelemetryConsumer_OnServiceEventProcessed_Call) RunAndReturn(run func(event flow.ServiceEvent)) *StateMachineTelemetryConsumer_OnServiceEventProcessed_Call { + _c.Run(run) + return _c +} + +// OnServiceEventReceived provides a mock function for the type StateMachineTelemetryConsumer +func (_mock *StateMachineTelemetryConsumer) OnServiceEventReceived(event flow.ServiceEvent) { + _mock.Called(event) + return +} + +// StateMachineTelemetryConsumer_OnServiceEventReceived_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnServiceEventReceived' +type StateMachineTelemetryConsumer_OnServiceEventReceived_Call struct { + *mock.Call +} + +// OnServiceEventReceived is a helper method to define mock.On call +// - event flow.ServiceEvent +func (_e *StateMachineTelemetryConsumer_Expecter) OnServiceEventReceived(event interface{}) *StateMachineTelemetryConsumer_OnServiceEventReceived_Call { + return &StateMachineTelemetryConsumer_OnServiceEventReceived_Call{Call: _e.mock.On("OnServiceEventReceived", event)} +} + +func (_c *StateMachineTelemetryConsumer_OnServiceEventReceived_Call) Run(run func(event flow.ServiceEvent)) *StateMachineTelemetryConsumer_OnServiceEventReceived_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.ServiceEvent + if args[0] != nil { + arg0 = args[0].(flow.ServiceEvent) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StateMachineTelemetryConsumer_OnServiceEventReceived_Call) Return() *StateMachineTelemetryConsumer_OnServiceEventReceived_Call { + _c.Call.Return() + return _c +} + +func (_c *StateMachineTelemetryConsumer_OnServiceEventReceived_Call) RunAndReturn(run func(event flow.ServiceEvent)) *StateMachineTelemetryConsumer_OnServiceEventReceived_Call { + _c.Run(run) + return _c } diff --git a/state/protocol/protocol_state/mock_interfaces/mock/state_machine_events_telemetry_factory.go b/state/protocol/protocol_state/mock_interfaces/mock/state_machine_events_telemetry_factory.go new file mode 100644 index 00000000000..3b8fdc81638 --- /dev/null +++ b/state/protocol/protocol_state/mock_interfaces/mock/state_machine_events_telemetry_factory.go @@ -0,0 +1,90 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/state/protocol/protocol_state" + mock "github.com/stretchr/testify/mock" +) + +// NewStateMachineEventsTelemetryFactory creates a new instance of StateMachineEventsTelemetryFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStateMachineEventsTelemetryFactory(t interface { + mock.TestingT + Cleanup(func()) +}) *StateMachineEventsTelemetryFactory { + mock := &StateMachineEventsTelemetryFactory{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// StateMachineEventsTelemetryFactory is an autogenerated mock type for the StateMachineEventsTelemetryFactory type +type StateMachineEventsTelemetryFactory struct { + mock.Mock +} + +type StateMachineEventsTelemetryFactory_Expecter struct { + mock *mock.Mock +} + +func (_m *StateMachineEventsTelemetryFactory) EXPECT() *StateMachineEventsTelemetryFactory_Expecter { + return &StateMachineEventsTelemetryFactory_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function for the type StateMachineEventsTelemetryFactory +func (_mock *StateMachineEventsTelemetryFactory) Execute(candidateView uint64) protocol_state.StateMachineTelemetryConsumer { + ret := _mock.Called(candidateView) + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 protocol_state.StateMachineTelemetryConsumer + if returnFunc, ok := ret.Get(0).(func(uint64) protocol_state.StateMachineTelemetryConsumer); ok { + r0 = returnFunc(candidateView) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(protocol_state.StateMachineTelemetryConsumer) + } + } + return r0 +} + +// StateMachineEventsTelemetryFactory_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type StateMachineEventsTelemetryFactory_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +// - candidateView uint64 +func (_e *StateMachineEventsTelemetryFactory_Expecter) Execute(candidateView interface{}) *StateMachineEventsTelemetryFactory_Execute_Call { + return &StateMachineEventsTelemetryFactory_Execute_Call{Call: _e.mock.On("Execute", candidateView)} +} + +func (_c *StateMachineEventsTelemetryFactory_Execute_Call) Run(run func(candidateView uint64)) *StateMachineEventsTelemetryFactory_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StateMachineEventsTelemetryFactory_Execute_Call) Return(stateMachineTelemetryConsumer protocol_state.StateMachineTelemetryConsumer) *StateMachineEventsTelemetryFactory_Execute_Call { + _c.Call.Return(stateMachineTelemetryConsumer) + return _c +} + +func (_c *StateMachineEventsTelemetryFactory_Execute_Call) RunAndReturn(run func(candidateView uint64) protocol_state.StateMachineTelemetryConsumer) *StateMachineEventsTelemetryFactory_Execute_Call { + _c.Call.Return(run) + return _c +} diff --git a/state/protocol/util/testing.go b/state/protocol/util/testing.go index 220fb2d41bb..cc0ba5f0a79 100644 --- a/state/protocol/util/testing.go +++ b/state/protocol/util/testing.go @@ -10,7 +10,6 @@ import ( "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/module" - "github.com/onflow/flow-go/module/metrics" mmetrics "github.com/onflow/flow-go/module/metrics" modulemock "github.com/onflow/flow-go/module/mock" "github.com/onflow/flow-go/module/trace" @@ -70,7 +69,7 @@ func RunWithBootstrapState(t testing.TB, rootSnapshot protocol.Snapshot, f func( unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() db := pebbleimpl.ToDB(pdb) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() all := store.InitAll(metrics, db) state, err := pbadger.Bootstrap( metrics, @@ -97,7 +96,7 @@ func RunWithFullProtocolState(t testing.TB, rootSnapshot protocol.Snapshot, f fu unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() db := pebbleimpl.ToDB(pdb) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() consumer := events.NewNoop() @@ -187,7 +186,7 @@ func RunWithFullProtocolStateAndValidator(t testing.TB, rootSnapshot protocol.Sn unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() db := pebbleimpl.ToDB(pdb) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() consumer := events.NewNoop() @@ -231,7 +230,7 @@ func RunWithFollowerProtocolState(t testing.TB, rootSnapshot protocol.Snapshot, unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() db := pebbleimpl.ToDB(pdb) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() consumer := events.NewNoop() @@ -272,7 +271,7 @@ func RunWithFullProtocolStateAndConsumer(t testing.TB, rootSnapshot protocol.Sna unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() db := pebbleimpl.ToDB(pdb) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() all := store.InitAll(metrics, db) @@ -369,7 +368,7 @@ func RunWithFollowerProtocolStateAndHeaders(t testing.TB, rootSnapshot protocol. unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() db := pebbleimpl.ToDB(pdb) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() consumer := events.NewNoop() @@ -410,7 +409,7 @@ func RunWithFullProtocolStateAndMutator(t testing.TB, rootSnapshot protocol.Snap unittest.RunWithPebbleDB(t, func(pdb *pebble.DB) { lockManager := storage.NewTestingLockManager() db := pebbleimpl.ToDB(pdb) - metrics := metrics.NewNoopCollector() + metrics := mmetrics.NewNoopCollector() tracer := trace.NewNoopTracer() log := zerolog.Nop() consumer := events.NewNoop() diff --git a/storage/account_transactions.go b/storage/account_transactions.go new file mode 100644 index 00000000000..fe34ee5b690 --- /dev/null +++ b/storage/account_transactions.go @@ -0,0 +1,92 @@ +package storage + +import ( + "github.com/jordanschalm/lockctx" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// AccountTransactionIterator is an iterator over account transactions ordered by descending +// block height, then ascending transaction index within each block. +type AccountTransactionIterator = IndexIterator[accessmodel.AccountTransaction, accessmodel.AccountTransactionCursor] + +// AccountTransactionsReader provides read access to the account transaction index. +// +// All methods are safe for concurrent access. +type AccountTransactionsReader interface { + // ByAddress returns an iterator over transactions for the given account, ordered + // in descending block height (newest first), with ascending transaction index within + // each block. Returns an exhausted iterator and no error if the account has no transactions. + // + // `cursor` is a pointer to an [accessmodel.AccountTransactionCursor]: + // - nil means start from the latest indexed height + // - non-nil means start at the cursor position (inclusive) + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped] if the index has not been initialized + // - [ErrHeightNotIndexed] if the cursor height extends beyond indexed heights + ByAddress( + account flow.Address, + cursor *accessmodel.AccountTransactionCursor, + ) (AccountTransactionIterator, error) +} + +// AccountTransactionsRangeReader provides access to the range of available indexed heights. +// +// All methods are safe for concurrent access. +type AccountTransactionsRangeReader interface { + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + FirstIndexedHeight() uint64 + + // LatestIndexedHeight returns the latest block height that has been indexed. + LatestIndexedHeight() uint64 +} + +// AccountTransactionsWriter provides write access to the account transaction index. +// +// NOT CONCURRENCY SAFE. +type AccountTransactionsWriter interface { + // Store indexes all account-transaction associations for a block. + // Must be called sequentially with consecutive heights (latestHeight + 1). + // The caller must hold the [storage.LockIndexAccountTransactions] lock until the batch is committed. + // + // Expected error returns during normal operations: + // - [storage.ErrAlreadyExists] if the block height is already indexed + Store(lctx lockctx.Proof, rw ReaderBatchWriter, blockHeight uint64, txData []accessmodel.AccountTransaction) error +} + +// AccountTransactions provides both read and write access to the account transaction index. +type AccountTransactions interface { + AccountTransactionsReader + AccountTransactionsRangeReader + AccountTransactionsWriter +} + +// AccountTransactionsBootstrapper is a wrapper around the [AccountTransactions] database that performs +// just-in-time initialization of the index when the initial block is provided. +// +// Account transactions are indexed from execution data which may not be available for the root block +// during bootstrapping. This module acts as a proxy for the underlying [AccountTransactions] and +// encapsulates the complexity of initializing the index when the initial block is eventually provided. +type AccountTransactionsBootstrapper interface { + AccountTransactionsReader + AccountTransactionsWriter + + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped]: if the index has not been initialized + FirstIndexedHeight() (uint64, error) + + // LatestIndexedHeight returns the latest block height that has been indexed. + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped]: if the index has not been initialized + LatestIndexedHeight() (uint64, error) + + // UninitializedFirstHeight returns the height the index will accept as the first height, and a boolean + // indicating if the index is initialized. + // If the index is not initialized, the first call to Store must include data for this height. + UninitializedFirstHeight() (uint64, bool) +} diff --git a/storage/account_transfers.go b/storage/account_transfers.go new file mode 100644 index 00000000000..22c84289b27 --- /dev/null +++ b/storage/account_transfers.go @@ -0,0 +1,182 @@ +package storage + +import ( + "github.com/jordanschalm/lockctx" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// FungibleTokenTransferIterator is an iterator over fungible token transfers ordered by +// descending block height, then ascending transaction and event index within each block. +type FungibleTokenTransferIterator = IndexIterator[accessmodel.FungibleTokenTransfer, accessmodel.TransferCursor] + +// FungibleTokenTransfersReader provides read access to the fungible token transfer index. +// +// All methods are safe for concurrent access. +type FungibleTokenTransfersReader interface { + // ByAddress returns an iterator over fungible token transfers involving the given account, + // ordered in descending block height (newest first), with ascending transaction and event + // index within each block. This includes transfers where the account is either the sender + // or recipient. Returns an exhausted iterator and no error if the account has no transfers. + // + // `cursor` is a pointer to an [accessmodel.TransferCursor]: + // - nil means start from the latest indexed height + // - non-nil means start at the cursor position (inclusive) + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped] if the index has not been initialized + // - [ErrHeightNotIndexed] if the cursor height extends beyond indexed heights + ByAddress( + account flow.Address, + cursor *accessmodel.TransferCursor, + ) (FungibleTokenTransferIterator, error) +} + +// FungibleTokenTransfersRangeReader provides access to the range of available indexed heights. +// +// All methods are safe for concurrent access. +type FungibleTokenTransfersRangeReader interface { + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + FirstIndexedHeight() uint64 + + // LatestIndexedHeight returns the latest block height that has been indexed. + LatestIndexedHeight() uint64 +} + +// FungibleTokenTransfersWriter provides write access to the fungible token transfer index. +// +// NOT CONCURRENCY SAFE. +type FungibleTokenTransfersWriter interface { + // Store indexes all fungible token transfers for a block. + // Each transfer is indexed under both the source and recipient addresses. + // Must be called sequentially with consecutive heights (latestHeight + 1). + // The caller must hold the [LockIndexFungibleTokenTransfers] lock until the batch is committed. + // + // Expected error returns during normal operations: + // - [ErrAlreadyExists] if the block height is already indexed + Store(lctx lockctx.Proof, rw ReaderBatchWriter, blockHeight uint64, transfers []accessmodel.FungibleTokenTransfer) error +} + +// FungibleTokenTransfers provides both read and write access to the fungible token transfer index. +type FungibleTokenTransfers interface { + FungibleTokenTransfersReader + FungibleTokenTransfersRangeReader + FungibleTokenTransfersWriter +} + +// FungibleTokenTransfersBootstrapper is a wrapper around the [FungibleTokenTransfers] database that +// performs just-in-time initialization of the index when the initial block is provided. +// +// Fungible token transfers are indexed from execution data which may not be available for the root +// block during bootstrapping. This module acts as a proxy for the underlying [FungibleTokenTransfers] +// and encapsulates the complexity of initializing the index when the initial block is eventually +// provided. +type FungibleTokenTransfersBootstrapper interface { + FungibleTokenTransfersReader + FungibleTokenTransfersWriter + + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped]: if the index has not been initialized + FirstIndexedHeight() (uint64, error) + + // LatestIndexedHeight returns the latest block height that has been indexed. + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped]: if the index has not been initialized + LatestIndexedHeight() (uint64, error) + + // UninitializedFirstHeight returns the height the index will accept as the first height, and a boolean + // indicating if the index is initialized. + // If the index is not initialized, the first call to `Store` must include data for this height. + UninitializedFirstHeight() (uint64, bool) +} + +// NonFungibleTokenTransferIterator is an iterator over non-fungible token transfers ordered by +// descending block height, then ascending transaction and event index within each block. +type NonFungibleTokenTransferIterator = IndexIterator[accessmodel.NonFungibleTokenTransfer, accessmodel.TransferCursor] + +// NonFungibleTokenTransfersReader provides read access to the non-fungible token transfer index. +// +// All methods are safe for concurrent access. +type NonFungibleTokenTransfersReader interface { + // ByAddress returns an iterator over non-fungible token transfers involving the given account, + // ordered in descending block height (newest first), with ascending transaction and event + // index within each block. This includes transfers where the account is either the sender + // or recipient. Returns an exhausted iterator and no error if the account has no transfers. + // + // `cursor` is a pointer to an [accessmodel.TransferCursor]: + // - nil means start from the latest indexed height + // - non-nil means start at the cursor position (inclusive) + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped] if the index has not been initialized + // - [ErrHeightNotIndexed] if the cursor height extends beyond indexed heights + ByAddress( + account flow.Address, + cursor *accessmodel.TransferCursor, + ) (NonFungibleTokenTransferIterator, error) +} + +// NonFungibleTokenTransfersRangeReader provides access to the range of available indexed heights. +// +// All methods are safe for concurrent access. +type NonFungibleTokenTransfersRangeReader interface { + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + FirstIndexedHeight() uint64 + + // LatestIndexedHeight returns the latest block height that has been indexed. + LatestIndexedHeight() uint64 +} + +// NonFungibleTokenTransfersWriter provides write access to the non-fungible token transfer index. +// +// NOT CONCURRENCY SAFE. +type NonFungibleTokenTransfersWriter interface { + // Store indexes all non-fungible token transfers for a block. + // Each transfer is indexed under both the source and recipient addresses. + // Must be called sequentially with consecutive heights (latestHeight + 1). + // The caller must hold the [LockIndexNonFungibleTokenTransfers] lock until the batch is committed. + // + // Expected error returns during normal operations: + // - [ErrAlreadyExists] if the block height is already indexed + Store(lctx lockctx.Proof, rw ReaderBatchWriter, blockHeight uint64, transfers []accessmodel.NonFungibleTokenTransfer) error +} + +// NonFungibleTokenTransfers provides both read and write access to the non-fungible token transfer index. +type NonFungibleTokenTransfers interface { + NonFungibleTokenTransfersReader + NonFungibleTokenTransfersRangeReader + NonFungibleTokenTransfersWriter +} + +// NonFungibleTokenTransfersBootstrapper is a wrapper around the [NonFungibleTokenTransfers] database that +// performs just-in-time initialization of the index when the initial block is provided. +// +// Non-fungible token transfers are indexed from execution data which may not be available for the root +// block during bootstrapping. This module acts as a proxy for the underlying [NonFungibleTokenTransfers] +// and encapsulates the complexity of initializing the index when the initial block is eventually +// provided. +type NonFungibleTokenTransfersBootstrapper interface { + NonFungibleTokenTransfersReader + NonFungibleTokenTransfersWriter + + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped]: if the index has not been initialized + FirstIndexedHeight() (uint64, error) + + // LatestIndexedHeight returns the latest block height that has been indexed. + // + // Expected error returns during normal operations: + // - [ErrNotBootstrapped]: if the index has not been initialized + LatestIndexedHeight() (uint64, error) + + // UninitializedFirstHeight returns the height the index will accept as the first height, and a boolean + // indicating if the index is initialized. + // If the index is not initialized, the first call to `Store` must include data for this height. + UninitializedFirstHeight() (uint64, bool) +} diff --git a/storage/blocks.go b/storage/blocks.go index 7fd8212bca3..dcd82dec013 100644 --- a/storage/blocks.go +++ b/storage/blocks.go @@ -92,6 +92,20 @@ type Blocks interface { // to decode an existing database value ByCollectionID(collID flow.Identifier) (*flow.Block, error) + // BlockIDByCollectionID returns the block ID for the finalized block which includes the guarantee for the given collection + // (the collection guarantee such that `CollectionGuarantee.CollectionID == collID`). + // NOTE: This method is only available for collections included in finalized blocks. + // While consensus nodes verify that collections are not repeated within the same fork, + // each different fork can contain a recent collection once. Therefore, we must wait for + // finality. + // CAUTION: this method is not backed by a cache and therefore comparatively slow! + // + // Error returns: + // - storage.ErrNotFound if no FINALIZED block exists containing the expected collection guarantee + // - generic error in case of unexpected failure from the database layer, or failure + // to decode an existing database value + BlockIDByCollectionID(collID flow.Identifier) (flow.Identifier, error) + // BatchIndexBlockContainingCollectionGuarantees produces mappings from the IDs of [flow.CollectionGuarantee]s to the block ID containing these guarantees. // The caller must acquire [storage.LockIndexBlockByPayloadGuarantees] and hold it until the database write has been committed. // diff --git a/storage/contract_deployments.go b/storage/contract_deployments.go new file mode 100644 index 00000000000..bc2a21a63fc --- /dev/null +++ b/storage/contract_deployments.go @@ -0,0 +1,124 @@ +package storage + +import ( + "github.com/jordanschalm/lockctx" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// ContractDeploymentIterator iterates over contract deployments with a [accessmodel.ContractDeploymentsCursor]. +type ContractDeploymentIterator = IndexIterator[accessmodel.ContractDeployment, accessmodel.ContractDeploymentsCursor] + +// ContractDeploymentsIndexReader provides read access to the contract deployments index. +// +// All methods are safe for concurrent access. +type ContractDeploymentsIndexReader interface { + // ByContract returns the most recent deployment for the given contract. + // + // Expected error returns during normal operation: + // - [ErrNotFound]: if no deployment for the given contract exists + // - [ErrNotBootstrapped]: if the index has not been initialized + ByContract(account flow.Address, name string) (accessmodel.ContractDeployment, error) + + // DeploymentsByContract returns an iterator over all recorded deployments for the given + // contract, ordered from most recent to oldest (descending block height). + // + // cursor is a pointer to an [accessmodel.ContractDeploymentsCursor]: + // - nil means start from the most recent deployment + // - non-nil means start at the cursor position (inclusive) + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + DeploymentsByContract( + account flow.Address, + name string, + cursor *accessmodel.ContractDeploymentsCursor, + ) (ContractDeploymentIterator, error) + + // ByAddress returns an iterator over the latest deployment for each contract deployed + // by the given address, ordered by contract identifier (ascending). + // + // cursor is a pointer to an [accessmodel.ContractDeploymentsCursor]: + // - nil means start from the first contract (by identifier) + // - non-nil resumes from cursor.Address and cursor.ContractName (inclusive); other cursor fields are ignored + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + ByAddress( + account flow.Address, + cursor *accessmodel.ContractDeploymentsCursor, + ) (ContractDeploymentIterator, error) + + // All returns an iterator over the latest deployment for each indexed contract, + // ordered by contract identifier (ascending). + // + // cursor is a pointer to an [accessmodel.ContractDeploymentsCursor]: + // - nil means start from the first contract (by identifier) + // - non-nil resumes from cursor.Address and cursor.ContractName (inclusive); other cursor fields are ignored + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + All(cursor *accessmodel.ContractDeploymentsCursor) (ContractDeploymentIterator, error) +} + +// ContractDeploymentsIndexRangeReader provides access to the range of indexed heights. +// +// All methods are safe for concurrent access. +type ContractDeploymentsIndexRangeReader interface { + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + FirstIndexedHeight() uint64 + + // LatestIndexedHeight returns the latest block height that has been indexed. + LatestIndexedHeight() uint64 +} + +// ContractDeploymentsIndexWriter provides write access to the contract deployments index. +// +// NOT CONCURRENTLY SAFE. +type ContractDeploymentsIndexWriter interface { + // Store indexes all contract deployments from the given block and advances the latest indexed + // height to blockHeight. Must be called with consecutive heights. + // The caller must hold the [LockIndexContractDeployments] lock until the batch is committed. + // + // Expected error returns during normal operation: + // - [ErrAlreadyExists]: if blockHeight has already been indexed + Store( + lctx lockctx.Proof, + rw ReaderBatchWriter, + blockHeight uint64, + deployments []accessmodel.ContractDeployment, + ) error +} + +// ContractDeploymentsIndex provides full read and write access to the contract deployments index. +type ContractDeploymentsIndex interface { + ContractDeploymentsIndexReader + ContractDeploymentsIndexRangeReader + ContractDeploymentsIndexWriter +} + +// ContractDeploymentsIndexBootstrapper wraps [ContractDeploymentsIndex] and performs +// just-in-time initialization of the index when the initial block is provided. +// +// All read and write methods proxy to the underlying index once initialized. +type ContractDeploymentsIndexBootstrapper interface { + ContractDeploymentsIndexReader + ContractDeploymentsIndexWriter + + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + FirstIndexedHeight() (uint64, error) + + // LatestIndexedHeight returns the latest block height that has been indexed. + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + LatestIndexedHeight() (uint64, error) + + // UninitializedFirstHeight returns the height the index will accept as the first height, + // and a boolean indicating whether the index is already initialized. + UninitializedFirstHeight() (uint64, bool) +} diff --git a/storage/errors.go b/storage/errors.go index b3d81d9709c..840f50a6bd2 100644 --- a/storage/errors.go +++ b/storage/errors.go @@ -31,6 +31,13 @@ var ( // ErrNotBootstrapped is returned when the database has not been bootstrapped. ErrNotBootstrapped = errors.New("pebble database not bootstrapped") + + // ErrInvalidQuery is returned when parameters passed to a read query are invalid (e.g., startHeight > endHeight). + ErrInvalidQuery = errors.New("invalid query") + + // ErrInvalidStatusTransition is returned when a status update is not valid for the + // current state (e.g. executing an already-cancelled scheduled transaction). + ErrInvalidStatusTransition = errors.New("invalid scheduled transaction status transition") ) // InvalidDKGStateTransitionError is a sentinel error that is returned in case an invalid state transition is attempted. diff --git a/storage/index_iterator.go b/storage/index_iterator.go new file mode 100644 index 00000000000..1bee387e5b1 --- /dev/null +++ b/storage/index_iterator.go @@ -0,0 +1,29 @@ +package storage + +import "iter" + +// IndexFilter is a function that filters data entries to include in query responses. +// It takes a single entry and returns true if the entry should be included in the response. +type IndexFilter[T any] func(T) bool + +// IndexIterator is an iterator over index entries. +// This is intended to be used with the `indexes` package to allow clients to collect filtered results. +type IndexIterator[T any, C any] iter.Seq2[IteratorEntry[T, C], error] + +// ReconstructFunc is a function that reconstructs an output value T based on the key and value from storage. +type ReconstructFunc[T any, C any] func(C, []byte) (*T, error) + +// DecodeKeyFunc is a function that decodes a storage key into a cursor C. +type DecodeKeyFunc[C any] func([]byte) (C, error) + +// IteratorEntry is a single entry returned by an index iterator. +// It provides access to the cursor and value for the entry. +type IteratorEntry[T any, C any] interface { + // Cursor returns the cursor for the entry, which includes all data included in the storage key. + Cursor() C + + // Value returns the fully reconstructed value for the entry. + // + // Any error indicates the value cannot be reconstructed from the storage value. + Value() (T, error) +} diff --git a/storage/indexes/account_ft_transfers.go b/storage/indexes/account_ft_transfers.go new file mode 100644 index 00000000000..ef97552c2b6 --- /dev/null +++ b/storage/indexes/account_ft_transfers.go @@ -0,0 +1,346 @@ +package indexes + +import ( + "encoding/binary" + "fmt" + "math/big" + + "github.com/jordanschalm/lockctx" + "github.com/vmihailenco/msgpack/v4" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" +) + +// FungibleTokenTransfers implements [storage.FungibleTokenTransfers] using Pebble. +// It provides an index mapping accounts to their fungible token transfers, ordered by block height +// in descending order (newest first). +// +// Each transfer is indexed under both the source and recipient addresses. +// +// Key format: [prefix][address][~block_height][tx_index][event_index] +// - prefix: 1 byte (codeFungibleTokenTransfers) +// - address: 8 bytes ([flow.Address]) +// - ~block_height: 8 bytes (one's complement for descending sort) +// - tx_index: 4 bytes (uint32, big-endian) +// - event_index: 4 bytes (uint32, big-endian) +// +// Heights are stored as one's complement to ensure descending order search. This optimizes for the +// most common use case of iterating over the most recent transfers, and makes it easy to answer the +// question "give me the most recent N transfers for this account that meet these criteria". +// +// Value format: [storedFungibleTokenTransfer] +// +// All read methods are safe for concurrent access. Write methods (Store) +// must be called sequentially with consecutive heights. +type FungibleTokenTransfers struct { + *IndexState +} + +// storedFungibleTokenTransfer is the internal value stored in the database for each FT transfer entry. +// Amount is stored as []byte via [big.Int.Bytes] for msgpack compatibility. +type storedFungibleTokenTransfer struct { + TransactionID flow.Identifier + EventIndices []uint32 // Index of the event within the transaction + SourceAddress flow.Address + RecipientAddress flow.Address + TokenType string + + // Amount is the token amount transferred. + // Stored as []byte (big.Int) instead of uint64 to allow storing both UFix64 and EVM UInt256 values. + Amount []byte +} + +const ( + // ftTransferKeyLen is the total length of a fungible token transfer index key + // 1 (prefix) + 8 (address) + 8 (height) + 4 (txIndex) + 4 (eventIndex) = 25 + ftTransferKeyLen = 1 + flow.AddressLength + heightLen + txIndexLen + eventIndexLen + + // ftTransferPrefixLen is the length of the prefix used for iteration (prefix + address) + ftTransferPrefixLen = 1 + flow.AddressLength + + // ftTransferPrefixWithHeightLen includes the height for range queries + ftTransferPrefixWithHeightLen = ftTransferPrefixLen + heightLen +) + +var _ storage.FungibleTokenTransfers = (*FungibleTokenTransfers)(nil) + +// NewFungibleTokenTransfers creates a new FungibleTokenTransfers backed by the given database. +// +// If the index has not been initialized, construction will fail with [storage.ErrNotBootstrapped]. +// The caller should retry with [BootstrapFungibleTokenTransfers] passing the required initialization data. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func NewFungibleTokenTransfers(db storage.DB) (*FungibleTokenTransfers, error) { + state, err := NewIndexState( + db, + storage.LockIndexFungibleTokenTransfers, + keyAccountFTTransferFirstHeightKey, + keyAccountFTTransferLatestHeightKey, + ) + if err != nil { + return nil, fmt.Errorf("could not create index state: %w", err) + } + return &FungibleTokenTransfers{IndexState: state}, nil +} + +// BootstrapFungibleTokenTransfers initializes the fungible token transfer index with data from the first block, +// and returns a new [FungibleTokenTransfers] instance. +// The caller must hold the [storage.LockIndexFungibleTokenTransfers] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrAlreadyExists] if data is found while initializing +func BootstrapFungibleTokenTransfers( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + db storage.DB, + initialStartHeight uint64, + transfers []access.FungibleTokenTransfer, +) (*FungibleTokenTransfers, error) { + state, err := BootstrapIndexState( + lctx, + rw, + db, + storage.LockIndexFungibleTokenTransfers, + keyAccountFTTransferFirstHeightKey, + keyAccountFTTransferLatestHeightKey, + initialStartHeight, + ) + if err != nil { + return nil, fmt.Errorf("could not bootstrap fungible token transfers: %w", err) + } + + if err := storeAllFTTransfers(rw, initialStartHeight, transfers); err != nil { + return nil, fmt.Errorf("could not store fungible token transfers: %w", err) + } + + return &FungibleTokenTransfers{IndexState: state}, nil +} + +// ByAddress returns an iterator over fungible token transfers involving the given account, +// ordered in descending block height (newest first), with ascending transaction and event +// index within each block. Returns an exhausted iterator and no error if the account has +// no transfers. +// +// `cursor` is a pointer to an [access.TransferCursor]: +// - nil means start from the latest indexed height +// - non-nil means start at the cursor position (inclusive) +// +// Expected error returns during normal operations: +// - [storage.ErrHeightNotIndexed] if the cursor height extends beyond indexed heights +func (idx *FungibleTokenTransfers) ByAddress( + account flow.Address, + cursor *access.TransferCursor, +) (storage.IndexIterator[access.FungibleTokenTransfer, access.TransferCursor], error) { + startKey, endKey, err := idx.rangeKeys(account, cursor) + if err != nil { + return nil, fmt.Errorf("could not determine range keys: %w", err) + } + + iter, err := idx.db.Reader().NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator: %w", err) + } + + return iterator.Build(iter, decodeFTTransferKey, reconstructFTTransfer), nil +} + +// rangeKeys computes the start and end keys for iterating over transfers of an account, based on +// the provided cursor. +// +// Any error indicates the cursor is invalid +func (idx *FungibleTokenTransfers) rangeKeys(account flow.Address, cursor *access.TransferCursor) (startKey, endKey []byte, err error) { + latestHeight := idx.latestHeight.Load() + if cursor == nil { + // keys include the one's complement of the height, so iteration is in descending order of height. + startKey = makeFTTransferKeyPrefix(account, latestHeight) + endKey = makeFTTransferKeyPrefix(account, idx.firstHeight) + return startKey, endKey, nil + } + + if err := validateCursorHeight(cursor.BlockHeight, idx.firstHeight, latestHeight); err != nil { + return nil, nil, err + } + + // since the cursor may point to a transaction within idx.firstHeight, we need to use the last + // possible key for the prefix. + startKey = makeFTTransferKey(account, cursor.BlockHeight, cursor.TransactionIndex, cursor.EventIndex) + endKey = makeFTTransferKeyPrefix(account, idx.firstHeight) + endKey = storage.PrefixInclusiveEnd(endKey, startKey) + + return startKey, endKey, nil +} + +// Store indexes all fungible token transfers for a block. +// Each transfer is indexed under both the source and recipient addresses. +// Must be called sequentially with consecutive heights (latestHeight + 1). +// The caller must hold the [storage.LockIndexFungibleTokenTransfers] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (idx *FungibleTokenTransfers) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error { + if err := idx.PrepareStore(lctx, rw, blockHeight); err != nil { + return fmt.Errorf("could not prepare store for block %d: %w", blockHeight, err) + } + + return storeAllFTTransfers(rw, blockHeight, transfers) +} + +// storeAllFTTransfers writes all fungible token transfer entries for a block. +// Each transfer produces two entries: one keyed by source address and one keyed by recipient address. +// The caller must hold the [storage.LockIndexFungibleTokenTransfers] lock until the batch is committed. +// +// No error returns are expected during normal operation. +func storeAllFTTransfers(rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error { + writer := rw.Writer() + + for _, entry := range transfers { + if err := validateFTTransfer(blockHeight, entry); err != nil { + return fmt.Errorf("invalid fungible token transfer: %w", err) + } + + value := makeFTTransferValue(entry) + eventIndex := ftEventIndex(entry) + + // Index under source address + sourceKey := makeFTTransferKey(entry.SourceAddress, entry.BlockHeight, entry.TransactionIndex, eventIndex) + if err := operation.UpsertByKey(writer, sourceKey, value); err != nil { + return fmt.Errorf("could not set key for source %s, tx %s: %w", entry.SourceAddress, entry.TransactionID, err) + } + + // Index under recipient address (if different from source, this creates a second entry; + // if same, this is an idempotent overwrite with the same value) + recipientKey := makeFTTransferKey(entry.RecipientAddress, entry.BlockHeight, entry.TransactionIndex, eventIndex) + if err := operation.UpsertByKey(writer, recipientKey, value); err != nil { + return fmt.Errorf("could not set key for recipient %s, tx %s: %w", entry.RecipientAddress, entry.TransactionID, err) + } + } + + return nil +} + +func ftEventIndex(entry access.FungibleTokenTransfer) uint32 { + // use the last event index. this is either the deposit event or the last withdrawal event + // if the vault was destroyed. + return entry.EventIndices[len(entry.EventIndices)-1] +} + +// reconstructFTTransfer decodes a stored value into an [access.FungibleTokenTransfer]. +// +// Any error indicates the value is not valid. +func reconstructFTTransfer(cursor access.TransferCursor, value []byte) (*access.FungibleTokenTransfer, error) { + var stored storedFungibleTokenTransfer + if err := msgpack.Unmarshal(value, &stored); err != nil { + return nil, fmt.Errorf("could not decode value: %w", err) + } + return &access.FungibleTokenTransfer{ + TransactionID: stored.TransactionID, + BlockHeight: cursor.BlockHeight, + TransactionIndex: cursor.TransactionIndex, + EventIndices: stored.EventIndices, + SourceAddress: stored.SourceAddress, + RecipientAddress: stored.RecipientAddress, + TokenType: stored.TokenType, + Amount: new(big.Int).SetBytes(stored.Amount), + }, nil +} + +// makeFTTransferValue builds the stored value for a fungible token transfer index entry. +func makeFTTransferValue(entry access.FungibleTokenTransfer) storedFungibleTokenTransfer { + var amountBytes []byte + if entry.Amount != nil { + amountBytes = entry.Amount.Bytes() + } + return storedFungibleTokenTransfer{ + TransactionID: entry.TransactionID, + EventIndices: entry.EventIndices, + SourceAddress: entry.SourceAddress, + RecipientAddress: entry.RecipientAddress, + TokenType: entry.TokenType, + Amount: amountBytes, + } +} + +// makeFTTransferKey creates a full key for a fungible token transfer index entry. +// Key format: [prefix][address][~block_height][tx_index][event_index] +func makeFTTransferKey(address flow.Address, height uint64, txIndex uint32, eventIndex uint32) []byte { + key := make([]byte, ftTransferKeyLen) + + key[0] = codeAccountFungibleTokenTransfers + copy(key[1:1+flow.AddressLength], address[:]) + + // One's complement of height for descending order + binary.BigEndian.PutUint64(key[1+flow.AddressLength:], ^height) + binary.BigEndian.PutUint32(key[1+flow.AddressLength+8:], txIndex) + binary.BigEndian.PutUint32(key[1+flow.AddressLength+8+4:], eventIndex) + + return key +} + +// makeFTTransferKeyPrefix creates a prefix key for iteration, up to and including the height. +// Key format: [prefix][address][~block_height] +func makeFTTransferKeyPrefix(address flow.Address, height uint64) []byte { + prefix := make([]byte, ftTransferPrefixWithHeightLen) + + prefix[0] = codeAccountFungibleTokenTransfers + copy(prefix[1:1+flow.AddressLength], address[:]) + + binary.BigEndian.PutUint64(prefix[1+flow.AddressLength:], ^height) + + return prefix +} + +// decodeFTTransferKey decodes a fungible token transfer key into its components. +// +// Any error indicates the key is not valid. +func decodeFTTransferKey(key []byte) (access.TransferCursor, error) { + if len(key) != ftTransferKeyLen { + return access.TransferCursor{}, fmt.Errorf("invalid key length: expected %d, got %d", + ftTransferKeyLen, len(key)) + } + + if key[0] != codeAccountFungibleTokenTransfers { + return access.TransferCursor{}, fmt.Errorf("invalid prefix: expected %d, got %d", + codeAccountFungibleTokenTransfers, key[0]) + } + + offset := 1 + + address := flow.BytesToAddress(key[offset : offset+flow.AddressLength]) + offset += flow.AddressLength + + height := ^binary.BigEndian.Uint64(key[offset:]) + offset += 8 + + txIndex := binary.BigEndian.Uint32(key[offset:]) + offset += 4 + + eventIndex := binary.BigEndian.Uint32(key[offset:]) + + return access.TransferCursor{ + Address: address, + BlockHeight: height, + TransactionIndex: txIndex, + EventIndex: eventIndex, + }, nil +} + +// validateFTTransfer validates the fungible token transfer is valid. +// +// Any error indicates the transfer is invalid. +func validateFTTransfer(blockHeight uint64, transfer access.FungibleTokenTransfer) error { + if transfer.BlockHeight != blockHeight { + return fmt.Errorf("block height mismatch: expected %d, got %d", blockHeight, transfer.BlockHeight) + } + if len(transfer.EventIndices) == 0 { + return fmt.Errorf("transfer must have at least one event index (tx=%s)", transfer.TransactionID) + } + if transfer.Amount == nil { + return fmt.Errorf("transfer amount is nil (tx=%s)", transfer.TransactionID) + } + return nil +} diff --git a/storage/indexes/account_ft_transfers_bootstrapper.go b/storage/indexes/account_ft_transfers_bootstrapper.go new file mode 100644 index 00000000000..6a72dea68f0 --- /dev/null +++ b/storage/indexes/account_ft_transfers_bootstrapper.go @@ -0,0 +1,133 @@ +package indexes + +import ( + "errors" + "fmt" + + "github.com/jordanschalm/lockctx" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// FungibleTokenTransfersBootstrapper wraps a [FungibleTokenTransfers] and performs just-in-time +// initialization of the index when the initial block is provided. +// +// Fungible token transfers are indexed from execution data which may not be available for the root +// block during bootstrapping. This module acts as a proxy for the underlying [FungibleTokenTransfers] +// and encapsulates the complexity of initializing the index when the initial block is eventually +// provided. +type FungibleTokenTransfersBootstrapper struct { + db storage.DB + initialStartHeight uint64 + + store *atomic.Pointer[FungibleTokenTransfers] +} + +var _ storage.FungibleTokenTransfersBootstrapper = (*FungibleTokenTransfersBootstrapper)(nil) + +// NewFungibleTokenTransfersBootstrapper creates a new [FungibleTokenTransfersBootstrapper]. +// If the index is already initialized (from a previous run), the underlying store is loaded immediately. +// Otherwise, the store remains nil until the first call to [Store] with the initial start height. +// +// No error returns are expected during normal operation. +func NewFungibleTokenTransfersBootstrapper(db storage.DB, initialStartHeight uint64) (*FungibleTokenTransfersBootstrapper, error) { + store, err := NewFungibleTokenTransfers(db) + if err != nil { + if !errors.Is(err, storage.ErrNotBootstrapped) { + return nil, fmt.Errorf("could not create fungible token transfers: %w", err) + } + store = nil + } + + return &FungibleTokenTransfersBootstrapper{ + db: db, + initialStartHeight: initialStartHeight, + store: atomic.NewPointer(store), + }, nil +} + +// FirstIndexedHeight returns the first (oldest) block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *FungibleTokenTransfersBootstrapper) FirstIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.FirstIndexedHeight(), nil +} + +// LatestIndexedHeight returns the latest block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *FungibleTokenTransfersBootstrapper) LatestIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.LatestIndexedHeight(), nil +} + +// UninitializedFirstHeight returns the height the index will accept as the first height, and a boolean +// indicating if the index is initialized. +// If the index is not initialized, the first call to `Store` must include data for this height. +func (b *FungibleTokenTransfersBootstrapper) UninitializedFirstHeight() (uint64, bool) { + store := b.store.Load() + if store == nil { + return b.initialStartHeight, false + } + return store.FirstIndexedHeight(), true +} + +// ByAddress returns an iterator over fungible token transfers involving the given account. +// See [FungibleTokenTransfers.ByAddress] for full documentation. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrHeightNotIndexed] if the cursor height extends beyond indexed heights +func (b *FungibleTokenTransfersBootstrapper) ByAddress( + account flow.Address, + cursor *access.TransferCursor, +) (storage.FungibleTokenTransferIterator, error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.ByAddress(account, cursor) +} + +// Store indexes all fungible token transfers for a block. +// Must be called sequentially with consecutive heights (latestHeight + 1). +// The caller must hold the [storage.LockIndexFungibleTokenTransfers] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized and the provided block height +// is not the initial start height +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (b *FungibleTokenTransfersBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error { + // if the index is already initialized, store the data directly + if store := b.store.Load(); store != nil { + return store.Store(lctx, rw, blockHeight, transfers) + } + + // otherwise bootstrap the index + if blockHeight != b.initialStartHeight { + return fmt.Errorf("expected first indexed height %d, got %d: %w", b.initialStartHeight, blockHeight, storage.ErrNotBootstrapped) + } + + store, err := BootstrapFungibleTokenTransfers(lctx, rw, b.db, b.initialStartHeight, transfers) + if err != nil { + return fmt.Errorf("could not initialize fungible token transfers storage: %w", err) + } + + if !b.store.CompareAndSwap(nil, store) { + return fmt.Errorf("fungible token transfers initialized during bootstrap") + } + + return nil +} diff --git a/storage/indexes/account_ft_transfers_bootstrapper_test.go b/storage/indexes/account_ft_transfers_bootstrapper_test.go new file mode 100644 index 00000000000..cfb1dcf524b --- /dev/null +++ b/storage/indexes/account_ft_transfers_bootstrapper_test.go @@ -0,0 +1,373 @@ +package indexes + +import ( + "errors" + "math/big" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +func TestFTBootstrapper_Constructor(t *testing.T) { + t.Parallel() + + t.Run("uninitialized DB returns ErrNotBootstrapped from height methods", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 10) + require.NoError(t, err) + + _, err = store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + _, err = store.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("already-bootstrapped DB is immediately usable", func(t *testing.T) { + RunWithBootstrappedFTTransferIndex(t, 5, nil, func(db storage.DB, _ storage.LockManager, _ *FungibleTokenTransfers) { + store, err := NewFungibleTokenTransfersBootstrapper(db, 5) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(5), first) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(5), latest) + }) + }) +} + +func TestFTBootstrapper_PreBootstrapState(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 42) + require.NoError(t, err) + + t.Run("FirstIndexedHeight returns ErrNotBootstrapped", func(t *testing.T) { + height, err := store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + }) + + t.Run("LatestIndexedHeight returns ErrNotBootstrapped", func(t *testing.T) { + height, err := store.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + }) + + t.Run("ByAddress returns ErrNotBootstrapped", func(t *testing.T) { + _, err := store.ByAddress(unittest.RandomAddressFixture(), nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + + t.Run("UninitializedFirstHeight returns initialStartHeight and false", func(t *testing.T) { + height, initialized := store.UninitializedFirstHeight() + assert.Equal(t, uint64(42), height) + assert.False(t, initialized) + }) + }) +} + +func TestFTBootstrapper_StoreTriggersBootstrap(t *testing.T) { + t.Parallel() + + t.Run("Store at initialStartHeight bootstraps the index", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = storeFTBootstrapperTransfers(t, store, storageDB, 10, nil) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(10), first) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(10), latest) + + height, initialized := store.UninitializedFirstHeight() + assert.Equal(t, uint64(10), height) + assert.True(t, initialized) + }) + }) + + t.Run("Store at wrong height returns ErrNotBootstrapped", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = storeFTBootstrapperTransfers(t, store, storageDB, 11, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeFTBootstrapperTransfers(t, store, storageDB, 9, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) +} + +func TestFTBootstrapper_BootstrapWithData(t *testing.T) { + t.Parallel() + + t.Run("bootstrap with transfer data persists and is queryable", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + firstHeight := uint64(5) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, firstHeight) + require.NoError(t, err) + + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + transfers := []access.FungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: firstHeight, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.0x1654653399040a61.FlowToken", + Amount: big.NewInt(1000), + }, + } + + err = storeFTBootstrapperTransfers(t, store, storageDB, firstHeight, transfers) + require.NoError(t, err) + + results := allFTTransfers(t, store, source) + require.Len(t, results, 1) + assert.Equal(t, txID, results[0].TransactionID) + assert.Equal(t, uint64(5), results[0].BlockHeight) + assert.Equal(t, uint32(0), results[0].TransactionIndex) + assert.Equal(t, source, results[0].SourceAddress) + assert.Equal(t, recipient, results[0].RecipientAddress) + assert.Equal(t, "A.0x1654653399040a61.FlowToken", results[0].TokenType) + assert.Equal(t, 0, big.NewInt(1000).Cmp(results[0].Amount)) + }) + }) + + t.Run("subsequent stores work after bootstrap", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 1) + require.NoError(t, err) + + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + err = storeFTBootstrapperTransfers(t, store, storageDB, 1, []access.FungibleTokenTransfer{ + { + TransactionID: txID1, + BlockHeight: 1, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.0x1654653399040a61.FlowToken", + Amount: big.NewInt(100), + }, + }) + require.NoError(t, err) + + err = storeFTBootstrapperTransfers(t, store, storageDB, 2, []access.FungibleTokenTransfer{ + { + TransactionID: txID2, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.0x1654653399040a61.FlowToken", + Amount: big.NewInt(200), + }, + }) + require.NoError(t, err) + + transfers := allFTTransfers(t, store, source) + require.Len(t, transfers, 2) + + // Descending order: height 2 first, then height 1 + assert.Equal(t, txID2, transfers[0].TransactionID) + assert.Equal(t, uint64(2), transfers[0].BlockHeight) + + assert.Equal(t, txID1, transfers[1].TransactionID) + assert.Equal(t, uint64(1), transfers[1].BlockHeight) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(2), latest) + }) + }) +} + +func TestFTBootstrapper_StoreAtSameHeight(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 5) + require.NoError(t, err) + + // Bootstrap at height 5 + err = storeFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.NoError(t, err) + + // Store at height 5 again returns ErrAlreadyExists + err = storeFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestFTBootstrapper_StoreBelowLatest(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 5) + require.NoError(t, err) + + // Bootstrap at height 5 + err = storeFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.NoError(t, err) + + // Store at height 6 + err = storeFTBootstrapperTransfers(t, store, storageDB, 6, nil) + require.NoError(t, err) + + // Store at height 4 (below latest=6) + err = storeFTBootstrapperTransfers(t, store, storageDB, 4, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestFTBootstrapper_NonConsecutiveStoreAfterBootstrap(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewFungibleTokenTransfersBootstrapper(storageDB, 5) + require.NoError(t, err) + + // Bootstrap at height 5 + err = storeFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.NoError(t, err) + + // Attempt to store at height 7, skipping height 6 + err = storeFTBootstrapperTransfers(t, store, storageDB, 7, nil) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrAlreadyExists)) + assert.False(t, errors.Is(err, storage.ErrNotBootstrapped)) + }) +} + +func TestFTBootstrapper_DoubleBootstrapProtection(t *testing.T) { + t.Parallel() + + lockManager := storage.NewTestingLockManager() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + err := unittest.WithLock(t, lockManager, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapFungibleTokenTransfers(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.NoError(t, err) + + // Attempting to bootstrap again should fail + err = unittest.WithLock(t, lockManager, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapFungibleTokenTransfers(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestFTBootstrapper_PersistenceAcrossRestart(t *testing.T) { + t.Parallel() + + unittest.RunWithTempDir(t, func(dir string) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + func() { + db := openPebbleDB(t, dir) + defer db.Close() + + store, err := NewFungibleTokenTransfersBootstrapper(db, 100) + require.NoError(t, err) + + _, err = store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeFTBootstrapperTransfers(t, store, db, 100, []access.FungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 100, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.0x1654653399040a61.FlowToken", + Amount: big.NewInt(500), + }, + }) + require.NoError(t, err) + }() + + db := openPebbleDB(t, dir) + defer db.Close() + + store, err := NewFungibleTokenTransfersBootstrapper(db, 100) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(100), first) + + transfers := allFTTransfers(t, store, source) + require.Len(t, transfers, 1) + assert.Equal(t, txID, transfers[0].TransactionID) + }) +} + +func storeFTBootstrapperTransfers( + tb testing.TB, + store storage.FungibleTokenTransfersBootstrapper, + db storage.DB, + height uint64, + transfers []access.FungibleTokenTransfer, +) error { + tb.Helper() + lockManager := storage.NewTestingLockManager() + return unittest.WithLock(tb, lockManager, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return store.Store(lctx, rw, height, transfers) + }) + }) +} diff --git a/storage/indexes/account_ft_transfers_test.go b/storage/indexes/account_ft_transfers_test.go new file mode 100644 index 00000000000..3bf20b85369 --- /dev/null +++ b/storage/indexes/account_ft_transfers_test.go @@ -0,0 +1,934 @@ +package indexes + +import ( + "errors" + "math" + "math/big" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// allFTTransfers is a test helper that queries all transfers for the given account using +// ByAddress with no cursor, and collects all results. +func allFTTransfers(tb testing.TB, idx storage.FungibleTokenTransfersReader, account flow.Address) []access.FungibleTokenTransfer { + tb.Helper() + iter, err := idx.ByAddress(account, nil) + require.NoError(tb, err) + var transfers []access.FungibleTokenTransfer + for item := range iter { + t, err := item.Value() + require.NoError(tb, err) + transfers = append(transfers, t) + } + return transfers +} + +// RunWithBootstrappedFTTransferIndex creates a new Pebble database and bootstraps it +// for fungible token transfer indexing at the given start height. The callback receives a shared +// lock manager that should be passed to storeFTTransfers for consistent lock usage. +func RunWithBootstrappedFTTransferIndex(tb testing.TB, startHeight uint64, transfers []access.FungibleTokenTransfer, f func(db storage.DB, lockManager storage.LockManager, idx *FungibleTokenTransfers)) { + unittest.RunWithPebbleDB(tb, func(db *pebble.DB) { + lockManager := storage.NewTestingLockManager() + var idx *FungibleTokenTransfers + storageDB := pebbleimpl.ToDB(db) + err := unittest.WithLock(tb, lockManager, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + var bootstrapErr error + idx, bootstrapErr = BootstrapFungibleTokenTransfers(lctx, rw, storageDB, startHeight, transfers) + return bootstrapErr + }) + }) + require.NoError(tb, err) + f(storageDB, lockManager, idx) + }) +} + +// storeFTTransfers stores fungible token transfers at the given height using the provided index +// and lock manager. +func storeFTTransfers(tb testing.TB, lockManager storage.LockManager, idx *FungibleTokenTransfers, height uint64, transfers []access.FungibleTokenTransfer) error { + return unittest.WithLock(tb, lockManager, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return idx.db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, height, transfers) + }) + }) +} + +// makeTestTransfer is a helper to build an access.FungibleTokenTransfer for testing. +func makeTestTransfer( + source flow.Address, + recipient flow.Address, + blockHeight uint64, + txIndex uint32, + eventIndex uint32, + tokenType string, + amount *big.Int, +) access.FungibleTokenTransfer { + return access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: blockHeight, + TransactionIndex: txIndex, + EventIndices: []uint32{eventIndex}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: tokenType, + Amount: amount, + } +} + +func TestFTTransfers_Initialize(t *testing.T) { + t.Parallel() + + t.Run("uninitialized database returns ErrNotBootstrapped", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + _, err := NewFungibleTokenTransfers(storageDB) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("corrupted DB with firstHeight but no latestHeight returns exception", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + // Write only the firstHeight key, simulating a corrupted state + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.UpsertByKey(rw.Writer(), keyAccountFTTransferFirstHeightKey, uint64(10)) + }) + require.NoError(t, err) + + _, err = NewFungibleTokenTransfers(storageDB) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrNotBootstrapped), + "should not return ErrNotBootstrapped for corrupted state") + }) + }) + + t.Run("bootstrap initializes the index", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, _ storage.LockManager, idx *FungibleTokenTransfers) { + assert.Equal(t, uint64(1), idx.FirstIndexedHeight()) + assert.Equal(t, uint64(1), idx.LatestIndexedHeight()) + }) + }) + + t.Run("bootstrap with initial data stores and retrieves transfers", func(t *testing.T) { + t.Parallel() + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + amount := big.NewInt(42) + + initialData := []access.FungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 5, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.0x1654653399040a61.FlowToken", + Amount: amount, + }, + } + + RunWithBootstrappedFTTransferIndex(t, 5, initialData, func(_ storage.DB, _ storage.LockManager, idx *FungibleTokenTransfers) { + assert.Equal(t, uint64(5), idx.FirstIndexedHeight()) + assert.Equal(t, uint64(5), idx.LatestIndexedHeight()) + + // Query by source + transfers := allFTTransfers(t, idx, source) + require.Len(t, transfers, 1) + assert.Equal(t, initialData[0].TransactionID, transfers[0].TransactionID) + assert.Equal(t, initialData[0].BlockHeight, transfers[0].BlockHeight) + assert.Equal(t, initialData[0].TransactionIndex, transfers[0].TransactionIndex) + assert.Equal(t, initialData[0].EventIndices[0], transfers[0].EventIndices[0]) + assert.Equal(t, source, transfers[0].SourceAddress) + assert.Equal(t, recipient, transfers[0].RecipientAddress) + assert.Equal(t, initialData[0].TokenType, transfers[0].TokenType) + assert.Equal(t, 0, amount.Cmp(transfers[0].Amount)) + + // Query by recipient + recipientTransfers := allFTTransfers(t, idx, recipient) + require.Len(t, recipientTransfers, 1) + assert.Equal(t, initialData[0].TransactionID, recipientTransfers[0].TransactionID) + }) + }) + + t.Run("bootstrap at height 0", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 0, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + assert.Equal(t, uint64(0), idx.FirstIndexedHeight()) + assert.Equal(t, uint64(0), idx.LatestIndexedHeight()) + + // Store at height 1 (consecutive after 0) + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + transfer := makeTestTransfer(source, recipient, 1, 0, 0, "A.FlowToken", big.NewInt(100)) + + err := storeFTTransfers(t, lm, idx, 1, []access.FungibleTokenTransfer{transfer}) + require.NoError(t, err) + assert.Equal(t, uint64(1), idx.LatestIndexedHeight()) + + transfers := allFTTransfers(t, idx, source) + require.Len(t, transfers, 1) + assert.Equal(t, transfer.TransactionID, transfers[0].TransactionID) + }) + }) +} + +func TestFTTransfers_StoreAndQuery(t *testing.T) { + t.Parallel() + + t.Run("store single block with single transfer", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + amount := big.NewInt(500) + transfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.FlowToken", + Amount: amount, + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer}) + require.NoError(t, err) + + transfers := allFTTransfers(t, idx, source) + require.Len(t, transfers, 1) + assert.Equal(t, transfer.TransactionID, transfers[0].TransactionID) + assert.Equal(t, uint64(2), transfers[0].BlockHeight) + assert.Equal(t, uint32(0), transfers[0].TransactionIndex) + assert.Equal(t, uint32(0), transfers[0].EventIndices[0]) + assert.Equal(t, source, transfers[0].SourceAddress) + assert.Equal(t, recipient, transfers[0].RecipientAddress) + assert.Equal(t, "A.FlowToken", transfers[0].TokenType) + assert.Equal(t, 0, amount.Cmp(transfers[0].Amount)) + }) + }) + + t.Run("store single block with multiple transfers for different accounts", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + charlie := unittest.RandomAddressFixture() + + transfers := []access.FungibleTokenTransfer{ + makeTestTransfer(alice, bob, 2, 0, 0, "A.FlowToken", big.NewInt(100)), + makeTestTransfer(bob, charlie, 2, 1, 0, "A.FlowToken", big.NewInt(50)), + } + + err := storeFTTransfers(t, lm, idx, 2, transfers) + require.NoError(t, err) + + // Alice: 1 transfer (as source) + aliceTransfers := allFTTransfers(t, idx, alice) + assert.Len(t, aliceTransfers, 1) + + // Bob: 2 transfers (as recipient of first, source of second) + bobTransfers := allFTTransfers(t, idx, bob) + assert.Len(t, bobTransfers, 2) + + // Charlie: 1 transfer (as recipient) + charlieTransfers := allFTTransfers(t, idx, charlie) + assert.Len(t, charlieTransfers, 1) + }) + }) + + t.Run("store multiple blocks with transfers, query by address", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + alice := unittest.RandomAddressFixture() + bob := unittest.RandomAddressFixture() + + // Block 2: Alice sends to Bob + transfer1 := makeTestTransfer(alice, bob, 2, 0, 0, "A.FlowToken", big.NewInt(100)) + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer1}) + require.NoError(t, err) + + // Block 3: Bob sends to Alice + transfer2 := makeTestTransfer(bob, alice, 3, 0, 0, "A.FlowToken", big.NewInt(50)) + err = storeFTTransfers(t, lm, idx, 3, []access.FungibleTokenTransfer{transfer2}) + require.NoError(t, err) + + // Alice should see both transfers (source in block 2, recipient in block 3) + aliceTransfers := allFTTransfers(t, idx, alice) + require.Len(t, aliceTransfers, 2) + + // Bob should see both transfers (recipient in block 2, source in block 3) + bobTransfers := allFTTransfers(t, idx, bob) + assert.Len(t, bobTransfers, 2) + }) + }) + + t.Run("dual indexing: transfer indexed under both source and recipient", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + transfer := access.FungibleTokenTransfer{ + TransactionID: txID, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.FlowToken", + Amount: big.NewInt(999), + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer}) + require.NoError(t, err) + + // Query by source address + sourceTransfers := allFTTransfers(t, idx, source) + require.Len(t, sourceTransfers, 1) + assert.Equal(t, txID, sourceTransfers[0].TransactionID) + + // Query by recipient address + recipientTransfers := allFTTransfers(t, idx, recipient) + require.Len(t, recipientTransfers, 1) + assert.Equal(t, txID, recipientTransfers[0].TransactionID) + + // Both should contain the same transfer data + assert.Equal(t, sourceTransfers[0].SourceAddress, recipientTransfers[0].SourceAddress) + assert.Equal(t, sourceTransfers[0].RecipientAddress, recipientTransfers[0].RecipientAddress) + assert.Equal(t, sourceTransfers[0].TokenType, recipientTransfers[0].TokenType) + }) + }) + + t.Run("query returns results in descending order (newest first)", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + other := unittest.RandomAddressFixture() + + // Index 10 blocks, each with a transfer involving account + for height := uint64(2); height <= 11; height++ { + transfer := makeTestTransfer(account, other, height, 0, 0, "A.FlowToken", big.NewInt(int64(height))) + err := storeFTTransfers(t, lm, idx, height, []access.FungibleTokenTransfer{transfer}) + require.NoError(t, err) + } + + transfers := allFTTransfers(t, idx, account) + require.Len(t, transfers, 10) + + // Verify descending order by height + for i := 0; i < len(transfers)-1; i++ { + assert.Greater(t, transfers[i].BlockHeight, transfers[i+1].BlockHeight, + "results should be in descending order by height") + } + }) + }) + + t.Run("multiple transfers at same height ordered by txIndex then eventIndex", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + other := unittest.RandomAddressFixture() + + transfers := []access.FungibleTokenTransfer{ + makeTestTransfer(account, other, 2, 0, 0, "A.FlowToken", big.NewInt(10)), + makeTestTransfer(account, other, 2, 0, 1, "A.FlowToken", big.NewInt(20)), + makeTestTransfer(account, other, 2, 1, 0, "A.FlowToken", big.NewInt(30)), + makeTestTransfer(account, other, 2, 1, 2, "A.FlowToken", big.NewInt(40)), + makeTestTransfer(account, other, 2, 2, 0, "A.FlowToken", big.NewInt(50)), + } + + err := storeFTTransfers(t, lm, idx, 2, transfers) + require.NoError(t, err) + + results := allFTTransfers(t, idx, account) + require.Len(t, results, 5) + + // Within same height, should be ordered by txIndex ascending, then eventIndex ascending + assert.Equal(t, uint32(0), results[0].TransactionIndex) + assert.Equal(t, uint32(0), results[0].EventIndices[0]) + + assert.Equal(t, uint32(0), results[1].TransactionIndex) + assert.Equal(t, uint32(1), results[1].EventIndices[0]) + + assert.Equal(t, uint32(1), results[2].TransactionIndex) + assert.Equal(t, uint32(0), results[2].EventIndices[0]) + + assert.Equal(t, uint32(1), results[3].TransactionIndex) + assert.Equal(t, uint32(2), results[3].EventIndices[0]) + + assert.Equal(t, uint32(2), results[4].TransactionIndex) + assert.Equal(t, uint32(0), results[4].EventIndices[0]) + }) + }) +} + +func TestFTTransfers_HeightValidation(t *testing.T) { + t.Parallel() + + t.Run("store at latestHeight returns ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + // Index height 2 + err := storeFTTransfers(t, lm, idx, 2, nil) + require.NoError(t, err) + + // Re-store at height 2 should return ErrAlreadyExists + err = storeFTTransfers(t, lm, idx, 2, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("store below latestHeight returns ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + err := storeFTTransfers(t, lm, idx, 2, nil) + require.NoError(t, err) + err = storeFTTransfers(t, lm, idx, 3, nil) + require.NoError(t, err) + + // Try to store height 1 (below latest=3) + err = storeFTTransfers(t, lm, idx, 1, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("store non-consecutive height fails", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + // Try to index height 5 when latest is 1 + err := storeFTTransfers(t, lm, idx, 5, nil) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrAlreadyExists), + "non-consecutive height should not return ErrAlreadyExists") + }) + }) + + t.Run("block height mismatch in entry fails", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + + // Entry claims height 5 but we're indexing height 2 + badTransfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 5, // mismatch + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.FlowToken", + Amount: big.NewInt(100), + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{badTransfer}) + require.Error(t, err) + assert.Contains(t, err.Error(), "block height mismatch") + }) + }) + + t.Run("store with nil EventIndices fails", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + transfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: nil, // invalid: must have at least one event index + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + TokenType: "A.FlowToken", + Amount: big.NewInt(100), + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer}) + require.Error(t, err) + assert.Contains(t, err.Error(), "at least one event index") + }) + }) + + t.Run("store with empty EventIndices fails", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + transfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{}, // invalid: must have at least one event index + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + TokenType: "A.FlowToken", + Amount: big.NewInt(100), + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer}) + require.Error(t, err) + assert.Contains(t, err.Error(), "at least one event index") + }) + }) + +} + +func TestFTTransfers_RangeQueries(t *testing.T) { + t.Parallel() + + t.Run("cursor height greater than latestIndexedHeight returns ErrHeightNotIndexed", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 5, nil, func(_ storage.DB, _ storage.LockManager, idx *FungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + cursor := &access.TransferCursor{BlockHeight: 100} + _, err := idx.ByAddress(account, cursor) + require.ErrorIs(t, err, storage.ErrHeightNotIndexed) + }) + }) + + t.Run("cursor height less than firstIndexedHeight returns ErrHeightNotIndexed", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 5, nil, func(_ storage.DB, _ storage.LockManager, idx *FungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + cursor := &access.TransferCursor{BlockHeight: 1} + _, err := idx.ByAddress(account, cursor) + require.ErrorIs(t, err, storage.ErrHeightNotIndexed) + }) + }) + + t.Run("nil cursor queries all data from latest height", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + + // Index heights 2 and 3 + transfer2 := makeTestTransfer(source, recipient, 2, 0, 0, "A.FlowToken", big.NewInt(100)) + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer2}) + require.NoError(t, err) + transfer3 := makeTestTransfer(source, recipient, 3, 0, 0, "A.FlowToken", big.NewInt(200)) + err = storeFTTransfers(t, lm, idx, 3, []access.FungibleTokenTransfer{transfer3}) + require.NoError(t, err) + + // nil cursor returns all data + transfers := allFTTransfers(t, idx, source) + assert.Len(t, transfers, 2) + }) + }) + + t.Run("empty results for address with no transfers", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + // Index a block so we have indexed heights + err := storeFTTransfers(t, lm, idx, 2, nil) + require.NoError(t, err) + + noTransfersAccount := unittest.RandomAddressFixture() + transfers := allFTTransfers(t, idx, noTransfersAccount) + assert.Empty(t, transfers) + }) + }) +} + +func TestFTTransfers_KeyEncoding(t *testing.T) { + t.Parallel() + + t.Run("roundtrip: encode then decode returns original values", func(t *testing.T) { + t.Parallel() + address := unittest.RandomAddressFixture() + height := uint64(12345) + txIndex := uint32(42) + eventIndex := uint32(7) + + key := makeFTTransferKey(address, height, txIndex, eventIndex) + + cursor, err := decodeFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, height, cursor.BlockHeight) + assert.Equal(t, txIndex, cursor.TransactionIndex) + assert.Equal(t, eventIndex, cursor.EventIndex) + }) + + t.Run("boundary values: height 0, txIndex 0, eventIndex 0", func(t *testing.T) { + t.Parallel() + address := unittest.RandomAddressFixture() + + key := makeFTTransferKey(address, 0, 0, 0) + cursor, err := decodeFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, uint64(0), cursor.BlockHeight) + assert.Equal(t, uint32(0), cursor.TransactionIndex) + assert.Equal(t, uint32(0), cursor.EventIndex) + }) + + t.Run("boundary values: max height, max txIndex, max eventIndex", func(t *testing.T) { + t.Parallel() + address := unittest.RandomAddressFixture() + + key := makeFTTransferKey(address, math.MaxUint64, math.MaxUint32, math.MaxUint32) + cursor, err := decodeFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, uint64(math.MaxUint64), cursor.BlockHeight) + assert.Equal(t, uint32(math.MaxUint32), cursor.TransactionIndex) + assert.Equal(t, uint32(math.MaxUint32), cursor.EventIndex) + }) + + t.Run("boundary values: zero address", func(t *testing.T) { + t.Parallel() + address := flow.Address{} + height := uint64(12345) + txIndex := uint32(42) + eventIndex := uint32(7) + + key := makeFTTransferKey(address, height, txIndex, eventIndex) + cursor, err := decodeFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, height, cursor.BlockHeight) + assert.Equal(t, txIndex, cursor.TransactionIndex) + assert.Equal(t, eventIndex, cursor.EventIndex) + }) + + t.Run("ones complement ensures descending order", func(t *testing.T) { + t.Parallel() + address := unittest.RandomAddressFixture() + + // Higher heights should produce lexicographically smaller keys (descending order) + keyLow := makeFTTransferKey(address, 100, 0, 0) + keyHigh := makeFTTransferKey(address, 200, 0, 0) + + // In byte comparison, the key for height 200 should sort before height 100 + // because ^200 < ^100 (ones complement inverts the order) + assert.True(t, string(keyHigh) < string(keyLow), + "key for higher height should sort lexicographically before key for lower height") + }) +} + +func TestFTTransfers_KeyDecoding_Errors(t *testing.T) { + t.Parallel() + + t.Run("key too short", func(t *testing.T) { + t.Parallel() + _, err := decodeFTTransferKey(make([]byte, 10)) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid key length") + }) + + t.Run("key too long", func(t *testing.T) { + t.Parallel() + _, err := decodeFTTransferKey(make([]byte, 30)) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid key length") + }) + + t.Run("invalid prefix", func(t *testing.T) { + t.Parallel() + key := make([]byte, ftTransferKeyLen) + key[0] = 0xFF // wrong prefix + _, err := decodeFTTransferKey(key) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid prefix") + }) +} + +func TestFTTransfers_LockRequirement(t *testing.T) { + t.Parallel() + + t.Run("Store without lock returns error", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + lctx := lm.NewContext() + defer lctx.Release() + + // Call without acquiring the required lock + err := db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, 2, nil) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) + + t.Run("initializeFTTransfers without lock returns error", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + lctx := lm.NewContext() + defer lctx.Release() + + // Call without acquiring the required lock + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapFungibleTokenTransfers(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) +} + +func TestFTTransfers_UncommittedBatch(t *testing.T) { + t.Parallel() + + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + require.Equal(t, uint64(1), idx.LatestIndexedHeight()) + + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + transfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.FlowToken", + Amount: big.NewInt(100), + } + + // Create a batch manually and store data without committing. + // Store registers an OnCommitSucceed callback to update latestHeight, + // which should only fire when the batch is committed. + batch := db.NewBatch() + err := unittest.WithLock(t, lm, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return idx.Store(lctx, batch, 2, []access.FungibleTokenTransfer{transfer}) + }) + require.NoError(t, err) + + // Close the batch without committing - discards pending writes + require.NoError(t, batch.Close()) + + // latestHeight must still be 1 since the batch was never committed + assert.Equal(t, uint64(1), idx.LatestIndexedHeight(), + "latestHeight should not update when the batch is not committed") + }) +} + +func TestFTTransfers_BootstrapHeightMismatch(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + + // Entry claims height 99 but we're bootstrapping at height 5 + err := unittest.WithLock(t, lm, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapFungibleTokenTransfers(lctx, rw, storageDB, 5, []access.FungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 99, // mismatch with bootstrap height 5 + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.FlowToken", + Amount: big.NewInt(100), + }, + }) + return bootstrapErr + }) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "block height mismatch") + }) +} + +func TestFTTransfers_BootstrapEmptyEventIndices(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + err := unittest.WithLock(t, lm, storage.LockIndexFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapFungibleTokenTransfers(lctx, rw, storageDB, 5, []access.FungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 5, + TransactionIndex: 0, + EventIndices: nil, // invalid: must have at least one event index + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + TokenType: "A.FlowToken", + Amount: big.NewInt(100), + }, + }) + return bootstrapErr + }) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "at least one event index") + }) +} + +func TestFTTransfers_SelfTransfer(t *testing.T) { + t.Parallel() + + // When source == recipient, the two UpsertByKey calls write the same key. + // The second is an idempotent overwrite. The address should still see exactly one entry. + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + transfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: account, + RecipientAddress: account, // same as source + TokenType: "A.FlowToken", + Amount: big.NewInt(42), + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer}) + require.NoError(t, err) + + transfers := allFTTransfers(t, idx, account) + assert.Len(t, transfers, 1, "self-transfer should produce exactly one entry per address") + assert.Equal(t, transfer.TransactionID, transfers[0].TransactionID) + }) +} + +func TestFTTransfers_LargeAmount(t *testing.T) { + t.Parallel() + + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + + // Use a very large amount (bigger than uint64) + largeAmount := new(big.Int) + largeAmount.SetString("999999999999999999999999999999999999999999", 10) + + transfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.FlowToken", + Amount: largeAmount, + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer}) + require.NoError(t, err) + + transfers := allFTTransfers(t, idx, source) + require.Len(t, transfers, 1) + assert.Equal(t, 0, largeAmount.Cmp(transfers[0].Amount), + "large amount should roundtrip correctly") + }) +} + +func TestFTTransfers_NilAmount(t *testing.T) { + t.Parallel() + + RunWithBootstrappedFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + + transfer := access.FungibleTokenTransfer{ + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + TokenType: "A.FlowToken", + Amount: nil, + } + + err := storeFTTransfers(t, lm, idx, 2, []access.FungibleTokenTransfer{transfer}) + require.Error(t, err) + assert.Contains(t, err.Error(), "transfer amount is nil") + }) +} + +// TestFTTransfers_PaginationCoversAllEntries verifies that paginating through all transfers +// for an account using CollectResults visits every entry exactly once. This specifically +// exercises the PrefixInclusiveEnd logic: when a cursor lands at firstHeight, the iterator +// range must still include all remaining entries at that height. +func TestFTTransfers_PaginationCoversAllEntries(t *testing.T) { + t.Parallel() + + const firstHeight = uint64(5) + const pageSize = uint32(3) + + account := unittest.RandomAddressFixture() + other := unittest.RandomAddressFixture() + + // Bootstrap with 3 transfers at firstHeight so that all 3 are stored at the + // first indexed height. When the page boundary later falls exactly at firstHeight, + // PrefixInclusiveEnd must pad the end key so the iterator covers all entries there. + initialTransfers := []access.FungibleTokenTransfer{ + makeTestTransfer(account, other, firstHeight, 0, 0, "A.FlowToken", big.NewInt(1)), + makeTestTransfer(account, other, firstHeight, 1, 0, "A.FlowToken", big.NewInt(2)), + makeTestTransfer(account, other, firstHeight, 2, 0, "A.FlowToken", big.NewInt(3)), + } + + RunWithBootstrappedFTTransferIndex(t, firstHeight, initialTransfers, func(_ storage.DB, lm storage.LockManager, idx *FungibleTokenTransfers) { + // 3 more transfers at height 6 (one above firstHeight) + err := storeFTTransfers(t, lm, idx, 6, []access.FungibleTokenTransfer{ + makeTestTransfer(account, other, 6, 0, 0, "A.FlowToken", big.NewInt(4)), + makeTestTransfer(account, other, 6, 1, 0, "A.FlowToken", big.NewInt(5)), + makeTestTransfer(account, other, 6, 2, 0, "A.FlowToken", big.NewInt(6)), + }) + require.NoError(t, err) + + // Paginate using CollectResults until cursor is nil. + // Page 1 (cursor=nil) collects height-6 entries and returns a cursor pointing + // to firstHeight. Page 2 must still return all 3 entries at firstHeight. + var allCollected []access.FungibleTokenTransfer + var cursor *access.TransferCursor + for { + ftIter, err := idx.ByAddress(account, cursor) + require.NoError(t, err) + + page, nextCursor, err := iterator.CollectResults(ftIter, pageSize, nil) + require.NoError(t, err) + + allCollected = append(allCollected, page...) + cursor = nextCursor + if cursor == nil { + break + } + } + + // All 6 transfers must be visited exactly once. + require.Len(t, allCollected, 6) + + // First 3 results are from height 6 (newest first), next 3 from firstHeight. + for i := 0; i < 3; i++ { + assert.Equal(t, uint64(6), allCollected[i].BlockHeight) + assert.Equal(t, uint32(i), allCollected[i].TransactionIndex) + } + for i := 0; i < 3; i++ { + assert.Equal(t, firstHeight, allCollected[3+i].BlockHeight) + assert.Equal(t, uint32(i), allCollected[3+i].TransactionIndex) + } + }) +} diff --git a/storage/indexes/account_nft_transfers.go b/storage/indexes/account_nft_transfers.go new file mode 100644 index 00000000000..4db86fdb61d --- /dev/null +++ b/storage/indexes/account_nft_transfers.go @@ -0,0 +1,333 @@ +package indexes + +import ( + "encoding/binary" + "fmt" + + "github.com/jordanschalm/lockctx" + "github.com/vmihailenco/msgpack/v4" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" +) + +// NonFungibleTokenTransfers implements [storage.NonFungibleTokenTransfers] using Pebble. +// It provides an index mapping accounts to their non-fungible token transfers, ordered by block height +// in descending order (newest first). +// +// Each transfer is indexed under both the source and recipient addresses. +// +// Key format: [prefix][address][~block_height][tx_index][event_index] +// - prefix: 1 byte (codeNonFungibleTokenTransfers) +// - address: 8 bytes ([flow.Address]) +// - ~block_height: 8 bytes (one's complement for descending sort) +// - tx_index: 4 bytes (uint32, big-endian) +// - event_index: 4 bytes (uint32, big-endian) +// +// Heights are stored as one's complement to ensure descending order search. This optimizes for the +// most common use case of iterating over the most recent transfers, and makes it easy to answer the +// question "give me the most recent N transfers for this account that meet these criteria". +// +// Value format: [storedNonFungibleTokenTransfer] +// +// All read methods are safe for concurrent access. Write methods (Store) +// must be called sequentially with consecutive heights. +type NonFungibleTokenTransfers struct { + *IndexState +} + +// storedNonFungibleTokenTransfer is the internal value stored in the database for each NFT transfer entry. +type storedNonFungibleTokenTransfer struct { + TransactionID flow.Identifier + EventIndices []uint32 + SourceAddress flow.Address + RecipientAddress flow.Address + TokenType string + ID uint64 +} + +const ( + // nftTransferKeyLen is the total length of a non-fungible token transfer index key + // 1 (prefix) + 8 (address) + 8 (height) + 4 (txIndex) + 4 (eventIndex) = 25 + nftTransferKeyLen = 1 + flow.AddressLength + heightLen + txIndexLen + eventIndexLen + + // nftTransferPrefixLen is the length of the prefix used for iteration (prefix + address) + nftTransferPrefixLen = 1 + flow.AddressLength + + // nftTransferPrefixWithHeightLen includes the height for range queries + nftTransferPrefixWithHeightLen = nftTransferPrefixLen + heightLen +) + +var _ storage.NonFungibleTokenTransfers = (*NonFungibleTokenTransfers)(nil) + +// NewNonFungibleTokenTransfers creates a new NonFungibleTokenTransfers backed by the given database. +// +// If the index has not been initialized, construction will fail with [storage.ErrNotBootstrapped]. +// The caller should retry with [BootstrapNonFungibleTokenTransfers] passing the required initialization data. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func NewNonFungibleTokenTransfers(db storage.DB) (*NonFungibleTokenTransfers, error) { + state, err := NewIndexState( + db, + storage.LockIndexNonFungibleTokenTransfers, + keyAccountNFTTransferFirstHeightKey, + keyAccountNFTTransferLatestHeightKey, + ) + if err != nil { + return nil, fmt.Errorf("could not create index state: %w", err) + } + return &NonFungibleTokenTransfers{IndexState: state}, nil +} + +// BootstrapNonFungibleTokenTransfers initializes the non-fungible token transfer index with data from the +// first block, and returns a new [NonFungibleTokenTransfers] instance. +// The caller must hold the [storage.LockIndexNonFungibleTokenTransfers] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrAlreadyExists] if data is found while initializing +func BootstrapNonFungibleTokenTransfers( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + db storage.DB, + initialStartHeight uint64, + transfers []access.NonFungibleTokenTransfer, +) (*NonFungibleTokenTransfers, error) { + state, err := BootstrapIndexState( + lctx, + rw, + db, + storage.LockIndexNonFungibleTokenTransfers, + keyAccountNFTTransferFirstHeightKey, + keyAccountNFTTransferLatestHeightKey, + initialStartHeight, + ) + if err != nil { + return nil, fmt.Errorf("could not bootstrap non-fungible token transfers: %w", err) + } + + if err := storeAllNFTTransfers(rw, initialStartHeight, transfers); err != nil { + return nil, fmt.Errorf("could not store non-fungible token transfers: %w", err) + } + + return &NonFungibleTokenTransfers{IndexState: state}, nil +} + +// ByAddress returns an iterator over non-fungible token transfers involving the given account, +// ordered in descending block height (newest first), with ascending transaction and event +// index within each block. Returns an exhausted iterator and no error if the account has +// no transfers. +// +// `cursor` is a pointer to an [access.TransferCursor]: +// - nil means start from the latest indexed height +// - non-nil means start at the cursor position (inclusive) +// +// Expected error returns during normal operations: +// - [storage.ErrHeightNotIndexed] if the cursor height is outside of the indexed range +func (idx *NonFungibleTokenTransfers) ByAddress( + account flow.Address, + cursor *access.TransferCursor, +) (storage.IndexIterator[access.NonFungibleTokenTransfer, access.TransferCursor], error) { + startKey, endKey, err := idx.rangeKeys(account, cursor) + if err != nil { + return nil, fmt.Errorf("could not determine range keys: %w", err) + } + + iter, err := idx.db.Reader().NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator: %w", err) + } + + return iterator.Build(iter, decodeNFTTransferKey, reconstructNFTTransfer), nil +} + +// rangeKeys computes the start and end keys for iterating over transfers of an account, based on +// the provided cursor. +// +// Any error indicates the cursor is invalid +func (idx *NonFungibleTokenTransfers) rangeKeys(account flow.Address, cursor *access.TransferCursor) (startKey, endKey []byte, err error) { + latestHeight := idx.latestHeight.Load() + if cursor == nil { + // keys include the one's complement of the height, so iteration is in descending order of height. + startKey = makeNFTTransferKeyPrefix(account, latestHeight) + endKey = makeNFTTransferKeyPrefix(account, idx.firstHeight) + return startKey, endKey, nil + } + + if err := validateCursorHeight(cursor.BlockHeight, idx.firstHeight, latestHeight); err != nil { + return nil, nil, err + } + + // since the cursor may point to a transaction within idx.firstHeight, we need to use the last + // possible key for the prefix. + startKey = makeNFTTransferKey(account, cursor.BlockHeight, cursor.TransactionIndex, cursor.EventIndex) + endKey = makeNFTTransferKeyPrefix(account, idx.firstHeight) + endKey = storage.PrefixInclusiveEnd(endKey, startKey) + + return startKey, endKey, nil +} + +// Store indexes all non-fungible token transfers for a block. +// Each transfer is indexed under both the source and recipient addresses. +// Must be called sequentially with consecutive heights (latestHeight + 1). +// The caller must hold the [storage.LockIndexNonFungibleTokenTransfers] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (idx *NonFungibleTokenTransfers) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error { + if err := idx.PrepareStore(lctx, rw, blockHeight); err != nil { + return fmt.Errorf("could not prepare store for block %d: %w", blockHeight, err) + } + + return storeAllNFTTransfers(rw, blockHeight, transfers) +} + +// storeAllNFTTransfers writes all non-fungible token transfer entries for a block. +// Each transfer produces two entries: one keyed by source address and one keyed by recipient address. +// The caller must hold the [storage.LockIndexNonFungibleTokenTransfers] lock until the batch is committed. +// +// No error returns are expected during normal operation. +func storeAllNFTTransfers(rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error { + writer := rw.Writer() + + for _, entry := range transfers { + if err := validateNFTTransfer(blockHeight, entry); err != nil { + return fmt.Errorf("invalid non-fungible token transfer: %w", err) + } + + value := makeNFTTransferValue(entry) + + eventIndex := nftTransferEventIndex(entry) + + // Index under source address + sourceKey := makeNFTTransferKey(entry.SourceAddress, entry.BlockHeight, entry.TransactionIndex, eventIndex) + if err := operation.UpsertByKey(writer, sourceKey, value); err != nil { + return fmt.Errorf("could not set key for source %s, tx %s: %w", entry.SourceAddress, entry.TransactionID, err) + } + + // Index under recipient address + recipientKey := makeNFTTransferKey(entry.RecipientAddress, entry.BlockHeight, entry.TransactionIndex, eventIndex) + if err := operation.UpsertByKey(writer, recipientKey, value); err != nil { + return fmt.Errorf("could not set key for recipient %s, tx %s: %w", entry.RecipientAddress, entry.TransactionID, err) + } + } + + return nil +} + +func nftTransferEventIndex(entry access.NonFungibleTokenTransfer) uint32 { + // use the last event index. this is either the deposit event or the last withdrawal event + // if the vault was destroyed. + return entry.EventIndices[len(entry.EventIndices)-1] +} + +// reconstructNFTTransfer decodes a stored value into an [access.NonFungibleTokenTransfer]. +// +// Any error indicates the value is not valid. +func reconstructNFTTransfer(cursor access.TransferCursor, value []byte) (*access.NonFungibleTokenTransfer, error) { + var stored storedNonFungibleTokenTransfer + if err := msgpack.Unmarshal(value, &stored); err != nil { + return nil, fmt.Errorf("could not decode value: %w", err) + } + return &access.NonFungibleTokenTransfer{ + TransactionID: stored.TransactionID, + BlockHeight: cursor.BlockHeight, + TransactionIndex: cursor.TransactionIndex, + EventIndices: stored.EventIndices, + SourceAddress: stored.SourceAddress, + RecipientAddress: stored.RecipientAddress, + TokenType: stored.TokenType, + ID: stored.ID, + }, nil +} + +// makeNFTTransferValue builds the stored value for a non-fungible token transfer index entry. +func makeNFTTransferValue(entry access.NonFungibleTokenTransfer) storedNonFungibleTokenTransfer { + return storedNonFungibleTokenTransfer{ + TransactionID: entry.TransactionID, + EventIndices: entry.EventIndices, + SourceAddress: entry.SourceAddress, + RecipientAddress: entry.RecipientAddress, + TokenType: entry.TokenType, + ID: entry.ID, + } +} + +// makeNFTTransferKey creates a full key for a non-fungible token transfer index entry. +// Key format: [prefix][address][~block_height][tx_index][event_index] +func makeNFTTransferKey(address flow.Address, height uint64, txIndex uint32, eventIndex uint32) []byte { + key := make([]byte, nftTransferKeyLen) + + key[0] = codeAccountNonFungibleTokenTransfers + copy(key[1:1+flow.AddressLength], address[:]) + + binary.BigEndian.PutUint64(key[1+flow.AddressLength:], ^height) + binary.BigEndian.PutUint32(key[1+flow.AddressLength+8:], txIndex) + binary.BigEndian.PutUint32(key[1+flow.AddressLength+8+4:], eventIndex) + + return key +} + +// makeNFTTransferKeyPrefix creates a prefix key for iteration, up to and including the height. +// Key format: [prefix][address][~block_height] +func makeNFTTransferKeyPrefix(address flow.Address, height uint64) []byte { + prefix := make([]byte, nftTransferPrefixWithHeightLen) + + prefix[0] = codeAccountNonFungibleTokenTransfers + copy(prefix[1:1+flow.AddressLength], address[:]) + + binary.BigEndian.PutUint64(prefix[1+flow.AddressLength:], ^height) + + return prefix +} + +// decodeNFTTransferKey decodes a non-fungible token transfer key into its components. +// +// Any error indicates the key is not valid. +func decodeNFTTransferKey(key []byte) (access.TransferCursor, error) { + if len(key) != nftTransferKeyLen { + return access.TransferCursor{}, fmt.Errorf("invalid key length: expected %d, got %d", + nftTransferKeyLen, len(key)) + } + + if key[0] != codeAccountNonFungibleTokenTransfers { + return access.TransferCursor{}, fmt.Errorf("invalid prefix: expected %d, got %d", + codeAccountNonFungibleTokenTransfers, key[0]) + } + + offset := 1 + + address := flow.BytesToAddress(key[offset : offset+flow.AddressLength]) + offset += flow.AddressLength + + height := ^binary.BigEndian.Uint64(key[offset:]) + offset += 8 + + txIndex := binary.BigEndian.Uint32(key[offset:]) + offset += 4 + + eventIndex := binary.BigEndian.Uint32(key[offset:]) + + return access.TransferCursor{ + Address: address, + BlockHeight: height, + TransactionIndex: txIndex, + EventIndex: eventIndex, + }, nil +} + +// validateNFTTransfer validates the non-fungible token transfer is valid. +// +// Any error indicates the transfer is invalid. +func validateNFTTransfer(blockHeight uint64, transfer access.NonFungibleTokenTransfer) error { + if transfer.BlockHeight != blockHeight { + return fmt.Errorf("block height mismatch: expected %d, got %d", blockHeight, transfer.BlockHeight) + } + if len(transfer.EventIndices) == 0 { + return fmt.Errorf("transfer must have at least one event index (tx=%s)", transfer.TransactionID) + } + return nil +} diff --git a/storage/indexes/account_nft_transfers_bootstrapper.go b/storage/indexes/account_nft_transfers_bootstrapper.go new file mode 100644 index 00000000000..692cd02259d --- /dev/null +++ b/storage/indexes/account_nft_transfers_bootstrapper.go @@ -0,0 +1,133 @@ +package indexes + +import ( + "errors" + "fmt" + + "github.com/jordanschalm/lockctx" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// NonFungibleTokenTransfersBootstrapper wraps a [NonFungibleTokenTransfers] and performs just-in-time +// initialization of the index when the initial block is provided. +// +// Non-fungible token transfers are indexed from execution data which may not be available for the root +// block during bootstrapping. This module acts as a proxy for the underlying [NonFungibleTokenTransfers] +// and encapsulates the complexity of initializing the index when the initial block is eventually +// provided. +type NonFungibleTokenTransfersBootstrapper struct { + db storage.DB + initialStartHeight uint64 + + store *atomic.Pointer[NonFungibleTokenTransfers] +} + +var _ storage.NonFungibleTokenTransfersBootstrapper = (*NonFungibleTokenTransfersBootstrapper)(nil) + +// NewNonFungibleTokenTransfersBootstrapper creates a new [NonFungibleTokenTransfersBootstrapper]. +// If the index is already initialized (from a previous run), the underlying store is loaded immediately. +// Otherwise, the store remains nil until the first call to [Store] with the initial start height. +// +// No error returns are expected during normal operation. +func NewNonFungibleTokenTransfersBootstrapper(db storage.DB, initialStartHeight uint64) (*NonFungibleTokenTransfersBootstrapper, error) { + store, err := NewNonFungibleTokenTransfers(db) + if err != nil { + if !errors.Is(err, storage.ErrNotBootstrapped) { + return nil, fmt.Errorf("could not create non-fungible token transfers: %w", err) + } + store = nil + } + + return &NonFungibleTokenTransfersBootstrapper{ + db: db, + initialStartHeight: initialStartHeight, + store: atomic.NewPointer(store), + }, nil +} + +// FirstIndexedHeight returns the first (oldest) block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *NonFungibleTokenTransfersBootstrapper) FirstIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.FirstIndexedHeight(), nil +} + +// LatestIndexedHeight returns the latest block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *NonFungibleTokenTransfersBootstrapper) LatestIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.LatestIndexedHeight(), nil +} + +// UninitializedFirstHeight returns the height the index will accept as the first height, and a boolean +// indicating if the index is initialized. +// If the index is not initialized, the first call to `Store` must include data for this height. +func (b *NonFungibleTokenTransfersBootstrapper) UninitializedFirstHeight() (uint64, bool) { + store := b.store.Load() + if store == nil { + return b.initialStartHeight, false + } + return store.FirstIndexedHeight(), true +} + +// ByAddress returns an iterator over non-fungible token transfers involving the given account. +// See [NonFungibleTokenTransfers.ByAddress] for full documentation. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrHeightNotIndexed] if the cursor height extends beyond indexed heights +func (b *NonFungibleTokenTransfersBootstrapper) ByAddress( + account flow.Address, + cursor *access.TransferCursor, +) (storage.NonFungibleTokenTransferIterator, error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.ByAddress(account, cursor) +} + +// Store indexes all non-fungible token transfers for a block. +// Must be called sequentially with consecutive heights (latestHeight + 1). +// The caller must hold the [storage.LockIndexNonFungibleTokenTransfers] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized and the provided block height +// is not the initial start height +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (b *NonFungibleTokenTransfersBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error { + // if the index is already initialized, store the data directly + if store := b.store.Load(); store != nil { + return store.Store(lctx, rw, blockHeight, transfers) + } + + // otherwise bootstrap the index + if blockHeight != b.initialStartHeight { + return fmt.Errorf("expected first indexed height %d, got %d: %w", b.initialStartHeight, blockHeight, storage.ErrNotBootstrapped) + } + + store, err := BootstrapNonFungibleTokenTransfers(lctx, rw, b.db, b.initialStartHeight, transfers) + if err != nil { + return fmt.Errorf("could not initialize non-fungible token transfers storage: %w", err) + } + + if !b.store.CompareAndSwap(nil, store) { + return fmt.Errorf("non-fungible token transfers initialized during bootstrap") + } + + return nil +} diff --git a/storage/indexes/account_nft_transfers_bootstrapper_test.go b/storage/indexes/account_nft_transfers_bootstrapper_test.go new file mode 100644 index 00000000000..ba90d5e7776 --- /dev/null +++ b/storage/indexes/account_nft_transfers_bootstrapper_test.go @@ -0,0 +1,391 @@ +package indexes + +import ( + "errors" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +func TestNFTBootstrapper_Constructor(t *testing.T) { + t.Parallel() + + t.Run("uninitialized DB returns ErrNotBootstrapped from height methods", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 10) + require.NoError(t, err) + + _, err = store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + _, err = store.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("already-bootstrapped DB is immediately usable", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 5, nil, func(db storage.DB, _ storage.LockManager, _ *NonFungibleTokenTransfers) { + store, err := NewNonFungibleTokenTransfersBootstrapper(db, 5) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(5), first) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(5), latest) + }) + }) +} + +func TestNFTBootstrapper_PreBootstrapState(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 42) + require.NoError(t, err) + + t.Run("FirstIndexedHeight returns ErrNotBootstrapped", func(t *testing.T) { + height, err := store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + }) + + t.Run("LatestIndexedHeight returns ErrNotBootstrapped", func(t *testing.T) { + height, err := store.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + }) + + t.Run("ByAddress returns ErrNotBootstrapped", func(t *testing.T) { + _, err := store.ByAddress(unittest.RandomAddressFixture(), nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + + t.Run("UninitializedFirstHeight returns initialStartHeight and false", func(t *testing.T) { + height, initialized := store.UninitializedFirstHeight() + assert.Equal(t, uint64(42), height) + assert.False(t, initialized) + }) + }) +} + +func TestNFTBootstrapper_StoreTriggersBootstrap(t *testing.T) { + t.Parallel() + + t.Run("Store at initialStartHeight bootstraps the index", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = storeNFTBootstrapperTransfers(t, store, storageDB, 10, nil) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(10), first) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(10), latest) + + height, initialized := store.UninitializedFirstHeight() + assert.Equal(t, uint64(10), height) + assert.True(t, initialized) + }) + }) + + t.Run("Store at wrong height returns ErrNotBootstrapped", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = storeNFTBootstrapperTransfers(t, store, storageDB, 11, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeNFTBootstrapperTransfers(t, store, storageDB, 9, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) +} + +func TestNFTBootstrapper_BootstrapWithData(t *testing.T) { + t.Parallel() + + t.Run("bootstrap with transfer data persists and is queryable", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + firstHeight := uint64(5) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, firstHeight) + require.NoError(t, err) + + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + transfers := []access.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: firstHeight, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 42, + }, + } + + err = storeNFTBootstrapperTransfers(t, store, storageDB, firstHeight, transfers) + require.NoError(t, err) + + iter, err := store.ByAddress(source, nil) + require.NoError(t, err) + var sourceTransfers []access.NonFungibleTokenTransfer + for item := range iter { + tr, iterErr := item.Value() + require.NoError(t, iterErr) + sourceTransfers = append(sourceTransfers, tr) + } + require.Len(t, sourceTransfers, 1) + assert.Equal(t, txID, sourceTransfers[0].TransactionID) + assert.Equal(t, uint64(5), sourceTransfers[0].BlockHeight) + assert.Equal(t, uint32(0), sourceTransfers[0].TransactionIndex) + assert.Equal(t, source, sourceTransfers[0].SourceAddress) + assert.Equal(t, recipient, sourceTransfers[0].RecipientAddress) + assert.Equal(t, uint64(42), sourceTransfers[0].ID) + }) + }) + + t.Run("subsequent stores work after bootstrap", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 1) + require.NoError(t, err) + + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + err = storeNFTBootstrapperTransfers(t, store, storageDB, 1, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID1, + BlockHeight: 1, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 1, + }, + }) + require.NoError(t, err) + + err = storeNFTBootstrapperTransfers(t, store, storageDB, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID2, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 2, + }, + }) + require.NoError(t, err) + + iter, err := store.ByAddress(source, nil) + require.NoError(t, err) + var transfers []access.NonFungibleTokenTransfer + for item := range iter { + tr, iterErr := item.Value() + require.NoError(t, iterErr) + transfers = append(transfers, tr) + } + require.Len(t, transfers, 2) + + // Descending order: height 2 first, then height 1 + assert.Equal(t, txID2, transfers[0].TransactionID) + assert.Equal(t, uint64(2), transfers[0].BlockHeight) + assert.Equal(t, uint64(2), transfers[0].ID) + + assert.Equal(t, txID1, transfers[1].TransactionID) + assert.Equal(t, uint64(1), transfers[1].BlockHeight) + assert.Equal(t, uint64(1), transfers[1].ID) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(2), latest) + }) + }) +} + +func TestNFTBootstrapper_StoreAtSameHeight(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 5) + require.NoError(t, err) + + // Bootstrap at height 5 + err = storeNFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.NoError(t, err) + + // Store at height 5 again returns ErrAlreadyExists + err = storeNFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestNFTBootstrapper_StoreBelowLatest(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 5) + require.NoError(t, err) + + // Bootstrap at height 5 + err = storeNFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.NoError(t, err) + + // Store at height 6 + err = storeNFTBootstrapperTransfers(t, store, storageDB, 6, nil) + require.NoError(t, err) + + // Store at height 4 (below latest=6) + err = storeNFTBootstrapperTransfers(t, store, storageDB, 4, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestNFTBootstrapper_NonConsecutiveStoreAfterBootstrap(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewNonFungibleTokenTransfersBootstrapper(storageDB, 5) + require.NoError(t, err) + + // Bootstrap at height 5 + err = storeNFTBootstrapperTransfers(t, store, storageDB, 5, nil) + require.NoError(t, err) + + // Attempt to store at height 7, skipping height 6 + err = storeNFTBootstrapperTransfers(t, store, storageDB, 7, nil) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrAlreadyExists)) + assert.False(t, errors.Is(err, storage.ErrNotBootstrapped)) + }) +} + +func TestNFTBootstrapper_DoubleBootstrapProtection(t *testing.T) { + t.Parallel() + + lockManager := storage.NewTestingLockManager() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + err := unittest.WithLock(t, lockManager, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapNonFungibleTokenTransfers(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.NoError(t, err) + + // Attempting to bootstrap again should fail + err = unittest.WithLock(t, lockManager, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapNonFungibleTokenTransfers(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestNFTBootstrapper_PersistenceAcrossRestart(t *testing.T) { + t.Parallel() + + unittest.RunWithTempDir(t, func(dir string) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + func() { + db := openPebbleDB(t, dir) + defer db.Close() + + store, err := NewNonFungibleTokenTransfersBootstrapper(db, 100) + require.NoError(t, err) + + _, err = store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeNFTBootstrapperTransfers(t, store, db, 100, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 100, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 77, + }, + }) + require.NoError(t, err) + }() + + db := openPebbleDB(t, dir) + defer db.Close() + + store, err := NewNonFungibleTokenTransfersBootstrapper(db, 100) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(100), first) + + iter, err := store.ByAddress(source, nil) + require.NoError(t, err) + var transfers []access.NonFungibleTokenTransfer + for item := range iter { + tr, iterErr := item.Value() + require.NoError(t, iterErr) + transfers = append(transfers, tr) + } + require.Len(t, transfers, 1) + assert.Equal(t, txID, transfers[0].TransactionID) + assert.Equal(t, uint64(77), transfers[0].ID) + }) +} + +func storeNFTBootstrapperTransfers( + tb testing.TB, + store storage.NonFungibleTokenTransfersBootstrapper, + db storage.DB, + height uint64, + transfers []access.NonFungibleTokenTransfer, +) error { + tb.Helper() + lockManager := storage.NewTestingLockManager() + return unittest.WithLock(tb, lockManager, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return store.Store(lctx, rw, height, transfers) + }) + }) +} diff --git a/storage/indexes/account_nft_transfers_test.go b/storage/indexes/account_nft_transfers_test.go new file mode 100644 index 00000000000..d31e2e9f7f6 --- /dev/null +++ b/storage/indexes/account_nft_transfers_test.go @@ -0,0 +1,789 @@ +package indexes + +import ( + "errors" + "math" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// queryAllNFTTransfers is a test helper that queries all transfers for the given account +// using a nil cursor. +func queryAllNFTTransfers(t *testing.T, idx *NonFungibleTokenTransfers, account flow.Address) []access.NonFungibleTokenTransfer { + t.Helper() + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + var transfers []access.NonFungibleTokenTransfer + for item := range iter { + tr, err := item.Value() + require.NoError(t, err) + transfers = append(transfers, tr) + } + return transfers +} + +func TestNFTTransfers_Initialize(t *testing.T) { + t.Parallel() + + t.Run("uninitialized database returns ErrNotBootstrapped", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + _, err := NewNonFungibleTokenTransfers(storageDB) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("corrupted DB with firstHeight but no latestHeight returns exception", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + // Write only the firstHeight key, simulating a corrupted state + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.UpsertByKey(rw.Writer(), keyAccountNFTTransferFirstHeightKey, uint64(10)) + }) + require.NoError(t, err) + + _, err = NewNonFungibleTokenTransfers(storageDB) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrNotBootstrapped), + "should not return ErrNotBootstrapped for corrupted state") + }) + }) + + t.Run("bootstrap initializes the index", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, _ storage.LockManager, idx *NonFungibleTokenTransfers) { + first := idx.FirstIndexedHeight() + assert.Equal(t, uint64(1), first) + + latest := idx.LatestIndexedHeight() + assert.Equal(t, uint64(1), latest) + }) + }) + + t.Run("bootstrap with initial data", func(t *testing.T) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + initialData := []access.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 1, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 42, + }, + } + RunWithBootstrappedNFTTransferIndex(t, 1, initialData, func(_ storage.DB, _ storage.LockManager, idx *NonFungibleTokenTransfers) { + first := idx.FirstIndexedHeight() + assert.Equal(t, uint64(1), first) + + latest := idx.LatestIndexedHeight() + assert.Equal(t, uint64(1), latest) + + // Query by source + sourceTransfers := queryAllNFTTransfers(t, idx, source) + require.Len(t, sourceTransfers, 1) + assert.Equal(t, txID, sourceTransfers[0].TransactionID) + assert.Equal(t, uint64(1), sourceTransfers[0].BlockHeight) + assert.Equal(t, uint32(0), sourceTransfers[0].TransactionIndex) + assert.Equal(t, uint32(0), sourceTransfers[0].EventIndices[0]) + assert.Equal(t, source, sourceTransfers[0].SourceAddress) + assert.Equal(t, recipient, sourceTransfers[0].RecipientAddress) + assert.Equal(t, uint64(42), sourceTransfers[0].ID) + + // Query by recipient + recipientTransfers := queryAllNFTTransfers(t, idx, recipient) + require.Len(t, recipientTransfers, 1) + assert.Equal(t, txID, recipientTransfers[0].TransactionID) + }) + }) + + t.Run("bootstrap at height 0", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 0, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + assert.Equal(t, uint64(0), idx.FirstIndexedHeight()) + assert.Equal(t, uint64(0), idx.LatestIndexedHeight()) + + // Store at height 1 (consecutive after 0) + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + err := storeNFTTransfers(t, lm, idx, 1, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 1, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 1, + }, + }) + require.NoError(t, err) + + assert.Equal(t, uint64(1), idx.LatestIndexedHeight()) + + results := queryAllNFTTransfers(t, idx, source) + require.Len(t, results, 1) + assert.Equal(t, txID, results[0].TransactionID) + }) + }) +} + +func TestNFTTransfers_StoreAndQuery(t *testing.T) { + t.Parallel() + + t.Run("single block with single transfer", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + transfers := []access.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 100, + }, + } + + err := storeNFTTransfers(t, lm, idx, 2, transfers) + require.NoError(t, err) + + results := queryAllNFTTransfers(t, idx, source) + require.Len(t, results, 1) + assert.Equal(t, txID, results[0].TransactionID) + assert.Equal(t, uint64(2), results[0].BlockHeight) + assert.Equal(t, uint32(0), results[0].TransactionIndex) + assert.Equal(t, uint32(0), results[0].EventIndices[0]) + assert.Equal(t, source, results[0].SourceAddress) + assert.Equal(t, recipient, results[0].RecipientAddress) + assert.Equal(t, uint64(100), results[0].ID) + }) + }) + + t.Run("multiple accounts", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + account1 := unittest.RandomAddressFixture() + account2 := unittest.RandomAddressFixture() + account3 := unittest.RandomAddressFixture() + require.NotEqual(t, account1, account2) + require.NotEqual(t, account2, account3) + + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + // Block 2: account1 -> account2 + err := storeNFTTransfers(t, lm, idx, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID1, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: account1, + RecipientAddress: account2, + ID: 1, + }, + }) + require.NoError(t, err) + + // Block 3: account2 -> account3 + err = storeNFTTransfers(t, lm, idx, 3, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID2, + BlockHeight: 3, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: account2, + RecipientAddress: account3, + ID: 2, + }, + }) + require.NoError(t, err) + + // account1: 1 transfer (source in block 2) + results := queryAllNFTTransfers(t, idx, account1) + require.Len(t, results, 1) + assert.Equal(t, txID1, results[0].TransactionID) + + // account2: 2 transfers (recipient in block 2, source in block 3) + results = queryAllNFTTransfers(t, idx, account2) + require.Len(t, results, 2) + + // account3: 1 transfer (recipient in block 3) + results = queryAllNFTTransfers(t, idx, account3) + require.Len(t, results, 1) + assert.Equal(t, txID2, results[0].TransactionID) + }) + }) + + t.Run("dual indexing source and recipient", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + source := unittest.RandomAddressFixture() + recipient := unittest.RandomAddressFixture() + require.NotEqual(t, source, recipient) + txID := unittest.IdentifierFixture() + + err := storeNFTTransfers(t, lm, idx, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: source, + RecipientAddress: recipient, + ID: 7, + }, + }) + require.NoError(t, err) + + // Both source and recipient should see the transfer + sourceResults := queryAllNFTTransfers(t, idx, source) + require.Len(t, sourceResults, 1) + assert.Equal(t, txID, sourceResults[0].TransactionID) + + recipientResults := queryAllNFTTransfers(t, idx, recipient) + require.Len(t, recipientResults, 1) + assert.Equal(t, txID, recipientResults[0].TransactionID) + }) + }) + + t.Run("descending order", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + + // Index 10 blocks + for height := uint64(2); height <= 11; height++ { + err := storeNFTTransfers(t, lm, idx, height, []access.NonFungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: height, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: account, + RecipientAddress: unittest.RandomAddressFixture(), + ID: height, + }, + }) + require.NoError(t, err) + } + + results := queryAllNFTTransfers(t, idx, account) + require.Len(t, results, 10) + + // Verify descending order + for i := 0; i < len(results)-1; i++ { + assert.Greater(t, results[i].BlockHeight, results[i+1].BlockHeight, + "results should be in descending order by height") + } + }) + }) + + t.Run("multiple transfers at same height", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + txID0 := unittest.IdentifierFixture() + txID1 := unittest.IdentifierFixture() + + err := storeNFTTransfers(t, lm, idx, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID0, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: account, + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + { + TransactionID: txID1, + BlockHeight: 2, + TransactionIndex: 1, + EventIndices: []uint32{0}, + SourceAddress: account, + RecipientAddress: unittest.RandomAddressFixture(), + ID: 2, + }, + }) + require.NoError(t, err) + + results := queryAllNFTTransfers(t, idx, account) + require.Len(t, results, 2) + + // Same height, ascending txIndex + assert.Equal(t, uint64(2), results[0].BlockHeight) + assert.Equal(t, uint64(2), results[1].BlockHeight) + assert.Less(t, results[0].TransactionIndex, results[1].TransactionIndex) + }) + }) +} + +func TestNFTTransfers_HeightValidation(t *testing.T) { + t.Parallel() + + t.Run("repeated store at latest height returns ErrAlreadyExists", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + // Index height 2 + err := storeNFTTransfers(t, lm, idx, 2, nil) + require.NoError(t, err) + + // Re-indexing height 2 should return ErrAlreadyExists + err = storeNFTTransfers(t, lm, idx, 2, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("store below latest returns ErrAlreadyExists", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + err := storeNFTTransfers(t, lm, idx, 2, nil) + require.NoError(t, err) + err = storeNFTTransfers(t, lm, idx, 3, nil) + require.NoError(t, err) + + // Try to store height 1 (below latest=3) + err = storeNFTTransfers(t, lm, idx, 1, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("store non-consecutive height fails", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + // Try to index height 5 when latest is 1 + err := storeNFTTransfers(t, lm, idx, 5, nil) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrAlreadyExists), + "non-consecutive height should not return ErrAlreadyExists") + }) + }) + + t.Run("block height mismatch in entry fails", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + // Entry claims height 5 but we're indexing height 2 + err := storeNFTTransfers(t, lm, idx, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 5, // mismatch + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "block height mismatch") + }) + }) + + t.Run("store with nil EventIndices fails", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + err := storeNFTTransfers(t, lm, idx, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: nil, // invalid: must have at least one event index + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "at least one event index") + }) + }) + + t.Run("store with empty EventIndices fails", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + err := storeNFTTransfers(t, lm, idx, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{}, // invalid: must have at least one event index + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "at least one event index") + }) + }) +} + +func TestNFTTransfers_RangeQueries(t *testing.T) { + t.Parallel() + + t.Run("cursor height greater than latest returns ErrHeightNotIndexed", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 5, nil, func(_ storage.DB, _ storage.LockManager, idx *NonFungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + cursor := &access.TransferCursor{BlockHeight: 100} + _, err := idx.ByAddress(account, cursor) + require.ErrorIs(t, err, storage.ErrHeightNotIndexed) + }) + }) + + t.Run("cursor height before first returns ErrHeightNotIndexed", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 5, nil, func(_ storage.DB, _ storage.LockManager, idx *NonFungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + cursor := &access.TransferCursor{BlockHeight: 1} + _, err := idx.ByAddress(account, cursor) + require.ErrorIs(t, err, storage.ErrHeightNotIndexed) + }) + }) + + t.Run("nil cursor queries from latest", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + err := storeNFTTransfers(t, lm, idx, 2, []access.NonFungibleTokenTransfer{ + { + TransactionID: txID, + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: account, + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + }) + require.NoError(t, err) + + // nil cursor should query from latest + results := queryAllNFTTransfers(t, idx, account) + require.Len(t, results, 1) + assert.Equal(t, txID, results[0].TransactionID) + }) + }) + + t.Run("empty results for account with no transfers", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + account := unittest.RandomAddressFixture() + + // Index some data so we have indexed heights + err := storeNFTTransfers(t, lm, idx, 2, nil) + require.NoError(t, err) + + results := queryAllNFTTransfers(t, idx, account) + assert.Empty(t, results) + }) + }) +} + +func TestNFTTransfers_KeyEncoding(t *testing.T) { + t.Parallel() + + t.Run("key encoding and decoding roundtrip", func(t *testing.T) { + address := unittest.RandomAddressFixture() + height := uint64(12345) + txIndex := uint32(42) + eventIndex := uint32(7) + + key := makeNFTTransferKey(address, height, txIndex, eventIndex) + + cursor, err := decodeNFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, height, cursor.BlockHeight) + assert.Equal(t, txIndex, cursor.TransactionIndex) + assert.Equal(t, eventIndex, cursor.EventIndex) + }) + + t.Run("boundary values: height 0, txIndex 0, eventIndex 0", func(t *testing.T) { + address := unittest.RandomAddressFixture() + key := makeNFTTransferKey(address, 0, 0, 0) + cursor, err := decodeNFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, uint64(0), cursor.BlockHeight) + assert.Equal(t, uint32(0), cursor.TransactionIndex) + assert.Equal(t, uint32(0), cursor.EventIndex) + }) + + t.Run("boundary values: max height, max txIndex, max eventIndex", func(t *testing.T) { + address := unittest.RandomAddressFixture() + key := makeNFTTransferKey(address, math.MaxUint64, math.MaxUint32, math.MaxUint32) + cursor, err := decodeNFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, uint64(math.MaxUint64), cursor.BlockHeight) + assert.Equal(t, uint32(math.MaxUint32), cursor.TransactionIndex) + assert.Equal(t, uint32(math.MaxUint32), cursor.EventIndex) + }) + + t.Run("boundary values: zero address", func(t *testing.T) { + address := flow.Address{} + key := makeNFTTransferKey(address, 12345, 42, 7) + cursor, err := decodeNFTTransferKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, uint64(12345), cursor.BlockHeight) + assert.Equal(t, uint32(42), cursor.TransactionIndex) + assert.Equal(t, uint32(7), cursor.EventIndex) + }) +} + +func TestNFTTransfers_KeyDecoding_Errors(t *testing.T) { + t.Parallel() + + t.Run("key too short", func(t *testing.T) { + _, err := decodeNFTTransferKey(make([]byte, 10)) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid key length") + }) + + t.Run("key too long", func(t *testing.T) { + _, err := decodeNFTTransferKey(make([]byte, 30)) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid key length") + }) + + t.Run("invalid prefix", func(t *testing.T) { + key := make([]byte, nftTransferKeyLen) + key[0] = 0xFF // wrong prefix + _, err := decodeNFTTransferKey(key) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid prefix") + }) +} + +func TestNFTTransfers_LockRequirement(t *testing.T) { + t.Parallel() + + t.Run("Store without lock returns error", func(t *testing.T) { + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + lctx := lm.NewContext() + defer lctx.Release() + + // Call without acquiring the required lock + err := db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, 2, nil) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) + + t.Run("initializeNFTTransfers without lock returns error", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + lctx := lm.NewContext() + defer lctx.Release() + + // Call without acquiring the required lock + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapNonFungibleTokenTransfers(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) +} + +func TestNFTTransfers_UncommittedBatch(t *testing.T) { + t.Parallel() + + RunWithBootstrappedNFTTransferIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + require.Equal(t, uint64(1), idx.LatestIndexedHeight()) + + transfers := []access.NonFungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 2, + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + } + + // Create a batch manually and store data without committing. + batch := db.NewBatch() + err := unittest.WithLock(t, lm, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return idx.Store(lctx, batch, 2, transfers) + }) + require.NoError(t, err) + + // Close the batch without committing - discards pending writes + require.NoError(t, batch.Close()) + + // latestHeight must still be 1 since the batch was never committed + assert.Equal(t, uint64(1), idx.LatestIndexedHeight(), + "latestHeight should not update when the batch is not committed") + }) +} + +func TestNFTTransfers_BootstrapHeightMismatch(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + // Entry claims height 99 but we're bootstrapping at height 5 + err := unittest.WithLock(t, lm, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapNonFungibleTokenTransfers(lctx, rw, storageDB, 5, []access.NonFungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 99, // mismatch with bootstrap height 5 + TransactionIndex: 0, + EventIndices: []uint32{0}, + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + }) + return bootstrapErr + }) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "block height mismatch") + }) +} + +func TestNFTTransfers_BootstrapEmptyEventIndices(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + err := unittest.WithLock(t, lm, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapNonFungibleTokenTransfers(lctx, rw, storageDB, 5, []access.NonFungibleTokenTransfer{ + { + TransactionID: unittest.IdentifierFixture(), + BlockHeight: 5, + TransactionIndex: 0, + EventIndices: nil, // invalid: must have at least one event index + SourceAddress: unittest.RandomAddressFixture(), + RecipientAddress: unittest.RandomAddressFixture(), + ID: 1, + }, + }) + return bootstrapErr + }) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "at least one event index") + }) +} + +// RunWithBootstrappedNFTTransferIndex creates a new Pebble database and bootstraps it +// for NFT transfer indexing at the given start height. The callback receives a shared +// lock manager that should be passed to storeNFTTransfers for consistent lock usage. +func RunWithBootstrappedNFTTransferIndex(tb testing.TB, startHeight uint64, transfers []access.NonFungibleTokenTransfer, f func(db storage.DB, lockManager storage.LockManager, idx *NonFungibleTokenTransfers)) { + unittest.RunWithPebbleDB(tb, func(db *pebble.DB) { + lockManager := storage.NewTestingLockManager() + + var idx *NonFungibleTokenTransfers + storageDB := pebbleimpl.ToDB(db) + err := unittest.WithLock(tb, lockManager, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + var bootstrapErr error + idx, bootstrapErr = BootstrapNonFungibleTokenTransfers(lctx, rw, storageDB, startHeight, transfers) + return bootstrapErr + }) + }) + require.NoError(tb, err) + + f(storageDB, lockManager, idx) + }) +} + +func storeNFTTransfers(tb testing.TB, lockManager storage.LockManager, idx *NonFungibleTokenTransfers, height uint64, transfers []access.NonFungibleTokenTransfer) error { + return unittest.WithLock(tb, lockManager, storage.LockIndexNonFungibleTokenTransfers, func(lctx lockctx.Context) error { + return idx.db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, height, transfers) + }) + }) +} + +// TestNFTTransfers_PaginationCoversAllEntries verifies that paginating through all transfers +// for an account using CollectResults visits every entry exactly once. This specifically +// exercises the PrefixInclusiveEnd logic: when a cursor lands at firstHeight, the iterator +// range must still include all remaining entries at that height. +func TestNFTTransfers_PaginationCoversAllEntries(t *testing.T) { + t.Parallel() + + const firstHeight = uint64(5) + const pageSize = uint32(3) + + account := unittest.RandomAddressFixture() + other := unittest.RandomAddressFixture() + + // Bootstrap with 3 transfers at firstHeight so that all 3 are stored at the + // first indexed height. When the page boundary later falls exactly at firstHeight, + // PrefixInclusiveEnd must pad the end key so the iterator covers all entries there. + initialTransfers := []access.NonFungibleTokenTransfer{ + {TransactionID: unittest.IdentifierFixture(), BlockHeight: firstHeight, TransactionIndex: 0, EventIndices: []uint32{0}, SourceAddress: account, RecipientAddress: other, ID: 1}, + {TransactionID: unittest.IdentifierFixture(), BlockHeight: firstHeight, TransactionIndex: 1, EventIndices: []uint32{0}, SourceAddress: account, RecipientAddress: other, ID: 2}, + {TransactionID: unittest.IdentifierFixture(), BlockHeight: firstHeight, TransactionIndex: 2, EventIndices: []uint32{0}, SourceAddress: account, RecipientAddress: other, ID: 3}, + } + + RunWithBootstrappedNFTTransferIndex(t, firstHeight, initialTransfers, func(_ storage.DB, lm storage.LockManager, idx *NonFungibleTokenTransfers) { + // 3 more transfers at height 6 (one above firstHeight) + err := storeNFTTransfers(t, lm, idx, 6, []access.NonFungibleTokenTransfer{ + {TransactionID: unittest.IdentifierFixture(), BlockHeight: 6, TransactionIndex: 0, EventIndices: []uint32{0}, SourceAddress: account, RecipientAddress: other, ID: 4}, + {TransactionID: unittest.IdentifierFixture(), BlockHeight: 6, TransactionIndex: 1, EventIndices: []uint32{0}, SourceAddress: account, RecipientAddress: other, ID: 5}, + {TransactionID: unittest.IdentifierFixture(), BlockHeight: 6, TransactionIndex: 2, EventIndices: []uint32{0}, SourceAddress: account, RecipientAddress: other, ID: 6}, + }) + require.NoError(t, err) + + // Paginate using CollectResults until cursor is nil. + // Page 1 (cursor=nil) collects height-6 entries and returns a cursor pointing + // to firstHeight. Page 2 must still return all 3 entries at firstHeight. + var allCollected []access.NonFungibleTokenTransfer + var cursor *access.TransferCursor + for { + nftIter, err := idx.ByAddress(account, cursor) + require.NoError(t, err) + + page, nextCursor, err := iterator.CollectResults(nftIter, pageSize, nil) + require.NoError(t, err) + + allCollected = append(allCollected, page...) + cursor = nextCursor + if cursor == nil { + break + } + } + + // All 6 transfers must be visited exactly once. + require.Len(t, allCollected, 6) + + // First 3 results are from height 6 (newest first), next 3 from firstHeight. + for i := 0; i < 3; i++ { + assert.Equal(t, uint64(6), allCollected[i].BlockHeight) + assert.Equal(t, uint32(i), allCollected[i].TransactionIndex) + } + for i := 0; i < 3; i++ { + assert.Equal(t, firstHeight, allCollected[3+i].BlockHeight) + assert.Equal(t, uint32(i), allCollected[3+i].TransactionIndex) + } + }) +} diff --git a/storage/indexes/account_transactions.go b/storage/indexes/account_transactions.go new file mode 100644 index 00000000000..e2ace1f8f23 --- /dev/null +++ b/storage/indexes/account_transactions.go @@ -0,0 +1,307 @@ +package indexes + +import ( + "encoding/binary" + "fmt" + "slices" + + "github.com/jordanschalm/lockctx" + "github.com/vmihailenco/msgpack/v4" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" +) + +// AccountTransactions implements storage.AccountTransactions using Pebble. +// It provides an index mapping accounts to their transactions, ordered by block height +// in descending order (newest first). +// +// Key format: [prefix][address][~block_height][tx_index] +// - prefix: 1 byte (codeAccountTransactions) +// - address: 8 bytes (flow.Address) +// - ~block_height: 8 bytes (one's complement for descending sort) +// - tx_index: 4 bytes (uint32, big-endian) +// +// Heights are stored as one's complement to ensure descending order search. This optimizes for the +// most common use case of iterating over the most recent transactions, and makes it easy to answer the +// question "give me the most recent N transactions for this account that meet these criteria". +// +// Value format: storedAccountTransaction +// - tx_id: 32 bytes (flow.Identifier) +// - roles: variable length ([]access.TransactionRole) +// +// All read methods are safe for concurrent access. Write methods (Store) +// must be called sequentially with consecutive heights. +type AccountTransactions struct { + *IndexState +} + +type storedAccountTransaction struct { + TransactionID flow.Identifier + Roles []access.TransactionRole +} + +const ( + // accountTxKeyLen is the total length of an account transaction index key + // 1 (prefix) + 8 (address) + 8 (height) + 4 (txIndex) = 21 + accountTxKeyLen = 1 + flow.AddressLength + heightLen + txIndexLen + + // accountTxPrefixLen is the length of the prefix used for iteration (prefix + address) + accountTxPrefixLen = 1 + flow.AddressLength + + // accountTxPrefixWithHeightLen includes the height for range queries + accountTxPrefixWithHeightLen = accountTxPrefixLen + heightLen +) + +var _ storage.AccountTransactions = (*AccountTransactions)(nil) + +// NewAccountTransactions creates a new AccountTransactions backed by the given database. +// +// If the index has not been initialized, constuction will fail with [storage.ErrNotBootstrapped]. +// The caller should retry with `BootstrapAccountTransactions` passing the required initialization data. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func NewAccountTransactions(db storage.DB) (*AccountTransactions, error) { + state, err := NewIndexState( + db, + storage.LockIndexAccountTransactions, + keyAccountTransactionFirstHeightKey, + keyAccountTransactionLatestHeightKey, + ) + if err != nil { + return nil, fmt.Errorf("could not create index state: %w", err) + } + return &AccountTransactions{IndexState: state}, nil +} + +// BootstrapAccountTransactions initializes the account transactions index with data from the first block, +// and returns a new [AccountTransactions] instance. +// The caller must hold the [storage.LockIndexAccountTransactions] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrAlreadyExists] if any data is found while initializing +func BootstrapAccountTransactions( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + db storage.DB, + initialStartHeight uint64, + txData []access.AccountTransaction, +) (*AccountTransactions, error) { + state, err := BootstrapIndexState( + lctx, + rw, + db, + storage.LockIndexAccountTransactions, + keyAccountTransactionFirstHeightKey, + keyAccountTransactionLatestHeightKey, + initialStartHeight) + if err != nil { + return nil, fmt.Errorf("could not bootstrap account transactions: %w", err) + } + + if err := storeAllAccountTransactions(rw, initialStartHeight, txData); err != nil { + return nil, fmt.Errorf("could not store account transactions: %w", err) + } + + return &AccountTransactions{IndexState: state}, nil +} + +// ByAddress returns an iterator over transactions for the given account, ordered in descending +// block height (newest first), with ascending transaction index within each block. +// Returns an exhausted iterator and no error if the account has no transactions. +// +// `cursor` is a pointer to an [access.AccountTransactionCursor]: +// - nil means start from the latest indexed height +// - non-nil means start at the cursor position (inclusive) +// +// Expected error returns during normal operations: +// - [storage.ErrHeightNotIndexed] if the cursor height extends beyond indexed heights +func (idx *AccountTransactions) ByAddress( + account flow.Address, + cursor *access.AccountTransactionCursor, +) (storage.IndexIterator[access.AccountTransaction, access.AccountTransactionCursor], error) { + startKey, endKey, err := idx.rangeKeys(account, cursor) + if err != nil { + return nil, fmt.Errorf("could not determine range keys: %w", err) + } + + iter, err := idx.db.Reader().NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator: %w", err) + } + + return iterator.Build(iter, decodeAccountTxKey, reconstructAccountTransaction), nil +} + +// rangeKeys computes the start and end keys for iterating over transactions of an account, based on +// the provided cursor. +// +// Any error indicates the cursor is invalid +func (idx *AccountTransactions) rangeKeys(account flow.Address, cursor *access.AccountTransactionCursor) (startKey, endKey []byte, err error) { + latestHeight := idx.latestHeight.Load() + if cursor == nil { + // keys include the one's complement of the height, so iteration is in descending order of height. + startKey = makeAccountTxKeyPrefix(account, latestHeight) + endKey = makeAccountTxKeyPrefix(account, idx.firstHeight) + return startKey, endKey, nil + } + + if err := validateCursorHeight(cursor.BlockHeight, idx.firstHeight, latestHeight); err != nil { + return nil, nil, err + } + + // since the cursor may point to a transaction within idx.firstHeight, we need to use the last + // possible key for the prefix. + startKey = makeAccountTxKey(account, cursor.BlockHeight, cursor.TransactionIndex) + endKey = makeAccountTxKeyPrefix(account, idx.firstHeight) + endKey = storage.PrefixInclusiveEnd(endKey, startKey) + + return startKey, endKey, nil +} + +// Store indexes all account-transaction associations for a block. +// Must be called sequentially with consecutive heights (latestHeight + 1). +// The caller must hold the [storage.LockIndexAccountTransactions] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (idx *AccountTransactions) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error { + if err := idx.PrepareStore(lctx, rw, blockHeight); err != nil { + return fmt.Errorf("could not prepare store for block %d: %w", blockHeight, err) + } + + return storeAllAccountTransactions(rw, blockHeight, txData) +} + +// storeAllAccountTransactions stores all account transactions for a given block height. +// The caller must hold the [storage.LockIndexAccountTransactions] lock until the batch is committed. +// +// No error returns are expected during normal operation. +func storeAllAccountTransactions(rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error { + writer := rw.Writer() + for _, entry := range txData { + if entry.BlockHeight != blockHeight { + return fmt.Errorf("block height mismatch: expected %d, got %d", blockHeight, entry.BlockHeight) + } + + key := makeAccountTxKey(entry.Address, entry.BlockHeight, entry.TransactionIndex) + + exists, err := operation.KeyExists(rw.GlobalReader(), key) + if err != nil { + return fmt.Errorf("could not check if key exists: %w", err) + } + if exists { + // since the block height was already checked to be exactly the next expected height, there + // should not be any data in the db for this height. if there is, the db is in an inconsistent + // state. + return fmt.Errorf("account transaction %s at height %d already indexed", entry.Address, entry.BlockHeight) + } + + value := makeAccountTxValue(entry) + if err := operation.UpsertByKey(writer, key, value); err != nil { + return fmt.Errorf("could not set key for account %s, tx %s: %w", entry.Address, entry.TransactionID, err) + } + } + + return nil +} + +func reconstructAccountTransaction(key access.AccountTransactionCursor, value []byte) (*access.AccountTransaction, error) { + var stored storedAccountTransaction + if err := msgpack.Unmarshal(value, &stored); err != nil { + return nil, fmt.Errorf("could not decode value: %w", err) + } + return &access.AccountTransaction{ + Address: key.Address, + BlockHeight: key.BlockHeight, + TransactionID: stored.TransactionID, + TransactionIndex: key.TransactionIndex, + Roles: stored.Roles, + }, nil +} + +// makeAccountTxValue builds the value for an account transaction index entry. +func makeAccountTxValue(entry access.AccountTransaction) storedAccountTransaction { + // enforce that stored roles are sorted in ascending order + slices.Sort(entry.Roles) + + // deduplicate roles + entry.Roles = slices.Compact(entry.Roles) + + return storedAccountTransaction{ + TransactionID: entry.TransactionID, + Roles: entry.Roles, + } +} + +// makeAccountTxKey creates a full key for an account transaction index entry. +// Key format: [prefix][address][~block_height][tx_index] +func makeAccountTxKey(address flow.Address, height uint64, txIndex uint32) []byte { + key := make([]byte, accountTxKeyLen) + + key[0] = codeAccountTransactions + copy(key[1:1+flow.AddressLength], address[:]) + + // One's complement of height for descending order + onesComplement := ^height + binary.BigEndian.PutUint64(key[1+flow.AddressLength:], onesComplement) + + binary.BigEndian.PutUint32(key[1+flow.AddressLength+8:], txIndex) + + return key +} + +// makeAccountTxKeyPrefix creates a prefix key for iteration, up to and including the height. +// This is used to set iterator bounds for height range queries. +// Key format: [prefix][address][~block_height] +func makeAccountTxKeyPrefix(address flow.Address, height uint64) []byte { + prefix := make([]byte, accountTxPrefixWithHeightLen) + + prefix[0] = codeAccountTransactions + copy(prefix[1:1+flow.AddressLength], address[:]) + + // One's complement of height for descending order + onesComplement := ^height + binary.BigEndian.PutUint64(prefix[1+flow.AddressLength:], onesComplement) + + return prefix +} + +// decodeAccountTxKey decodes a key and value into an AccountTransaction. +// +// Any error indicates the key is not valid. +func decodeAccountTxKey(key []byte) (access.AccountTransactionCursor, error) { + if len(key) != accountTxKeyLen { + return access.AccountTransactionCursor{}, fmt.Errorf("invalid key length: expected %d, got %d", + accountTxKeyLen, len(key)) + } + + if key[0] != codeAccountTransactions { + return access.AccountTransactionCursor{}, fmt.Errorf("invalid prefix: expected %d, got %d", + codeAccountTransactions, key[0]) + } + + // Skip prefix + offset := 1 + + address := flow.BytesToAddress(key[offset : offset+flow.AddressLength]) + offset += flow.AddressLength + + // Decode height (one's complement) + onesComplement := binary.BigEndian.Uint64(key[offset:]) + height := ^onesComplement + offset += 8 + + // Decode transaction index + txIndex := binary.BigEndian.Uint32(key[offset:]) + + return access.AccountTransactionCursor{ + Address: address, + BlockHeight: height, + TransactionIndex: txIndex, + }, nil +} diff --git a/storage/indexes/account_transactions_bootstrapper.go b/storage/indexes/account_transactions_bootstrapper.go new file mode 100644 index 00000000000..5ab0100df8d --- /dev/null +++ b/storage/indexes/account_transactions_bootstrapper.go @@ -0,0 +1,134 @@ +package indexes + +import ( + "errors" + "fmt" + + "github.com/jordanschalm/lockctx" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// AccountTransactionsBootstrapper wraps an [AccountTransactions] and performs just-in-time initialization +// of the index when the initial block is provided. +// +// Account transactions are indexed from execution data which may not be available for the root block +// during bootstrapping. This module acts as a proxy for the underlying [AccountTransactions] and +// encapsulates the complexity of initializing the index when the initial block is eventually provided. +type AccountTransactionsBootstrapper struct { + db storage.DB + initialStartHeight uint64 + + store *atomic.Pointer[AccountTransactions] +} + +var _ storage.AccountTransactionsBootstrapper = (*AccountTransactionsBootstrapper)(nil) + +// NewAccountTransactionsBootstrapper creates a new account transactions bootstrapper. +// +// No error returns are expected during normal operation. +func NewAccountTransactionsBootstrapper(db storage.DB, initialStartHeight uint64) (*AccountTransactionsBootstrapper, error) { + store, err := NewAccountTransactions(db) + if err != nil { + if !errors.Is(err, storage.ErrNotBootstrapped) { + return nil, fmt.Errorf("could not create account transactions: %w", err) + } + // make sure it's nil + store = nil + } + + return &AccountTransactionsBootstrapper{ + db: db, + initialStartHeight: initialStartHeight, + store: atomic.NewPointer(store), + }, nil +} + +// FirstIndexedHeight returns the first (oldest) block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *AccountTransactionsBootstrapper) FirstIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.FirstIndexedHeight(), nil +} + +// LatestIndexedHeight returns the latest block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *AccountTransactionsBootstrapper) LatestIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.LatestIndexedHeight(), nil +} + +// UninitializedFirstHeight returns the height the index will accept as the first height, and a boolean +// indicating if the index is initialized. +// If the index is not initialized, the first call to `Store` must include data for this height. +func (b *AccountTransactionsBootstrapper) UninitializedFirstHeight() (uint64, bool) { + store := b.store.Load() + if store == nil { + return b.initialStartHeight, false + } + return store.FirstIndexedHeight(), true +} + +// ByAddress returns an iterator over transactions for the given account. +// See [AccountTransactions.ByAddress] for full documentation. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrHeightNotIndexed] if the cursor height extends beyond indexed heights +func (b *AccountTransactionsBootstrapper) ByAddress( + account flow.Address, + cursor *access.AccountTransactionCursor, +) (storage.IndexIterator[access.AccountTransaction, access.AccountTransactionCursor], error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.ByAddress(account, cursor) +} + +// Store indexes all account-transaction associations for a block. +// Must be called sequentially with consecutive heights (latestHeight + 1). +// The caller must hold the [storage.LockIndexAccountTransactions] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized and the provided block height is not the initial start height +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (b *AccountTransactionsBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error { + // if the index is already initialized, store the data directly + if store := b.store.Load(); store != nil { + return store.Store(lctx, rw, blockHeight, txData) + } + + // otherwise bootstrap the index. this will store the data during initialization + if blockHeight != b.initialStartHeight { + return fmt.Errorf("expected first indexed height %d, got %d: %w", b.initialStartHeight, blockHeight, storage.ErrNotBootstrapped) + } + + store, err := BootstrapAccountTransactions(lctx, rw, b.db, b.initialStartHeight, txData) + if err != nil { + return fmt.Errorf("could not initialize account transactions storage: %w", err) + } + + if !b.store.CompareAndSwap(nil, store) { + // this should never happen. if it does, there is a bug. this indicates another goroutine + // successfully initialized `store` since we checked the value above. since the bootstrap + // operation is protected by the lock and it performs sanity checks to ensure the table + // is actually empty, the bootstrap operation should fail if there was concurrent access. + return fmt.Errorf("account transactions initialized during bootstrap") + } + + return nil +} diff --git a/storage/indexes/account_transactions_bootstrapper_test.go b/storage/indexes/account_transactions_bootstrapper_test.go new file mode 100644 index 00000000000..951e1d932b0 --- /dev/null +++ b/storage/indexes/account_transactions_bootstrapper_test.go @@ -0,0 +1,323 @@ +package indexes + +import ( + "errors" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +func TestBootstrapper_Constructor(t *testing.T) { + t.Parallel() + + t.Run("uninitialized DB returns ErrNotBootstrapped", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewAccountTransactionsBootstrapper(storageDB, 10) + require.NoError(t, err) + + // Inner store should be nil, so height methods return ErrNotBootstrapped + _, err = store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("already-bootstrapped DB is immediately usable", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 5, nil, func(db storage.DB, _ storage.LockManager, _ *AccountTransactions) { + store, err := NewAccountTransactionsBootstrapper(db, 5) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(5), first) + }) + }) +} + +func TestBootstrapper_PreBootstrapState(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewAccountTransactionsBootstrapper(storageDB, 42) + require.NoError(t, err) + + t.Run("FirstIndexedHeight returns zero with ErrNotBootstrapped", func(t *testing.T) { + height, err := store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + }) + + t.Run("LatestIndexedHeight returns zero with ErrNotBootstrapped", func(t *testing.T) { + height, err := store.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + }) + + t.Run("UninitializedFirstHeight returns initialStartHeight and false", func(t *testing.T) { + height, initialized := store.UninitializedFirstHeight() + assert.Equal(t, uint64(42), height) + assert.False(t, initialized) + }) + + t.Run("ByAddress returns ErrNotBootstrapped", func(t *testing.T) { + _, err := store.ByAddress(unittest.RandomAddressFixture(), nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) +} + +func TestBootstrapper_StoreTriggersBootstrap(t *testing.T) { + t.Parallel() + + t.Run("Store at initialStartHeight bootstraps the index", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewAccountTransactionsBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = storeBootstrapperTx(t, store, storageDB, 10, nil) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(10), first) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(10), latest) + + height, initialized := store.UninitializedFirstHeight() + assert.Equal(t, uint64(10), height) + assert.True(t, initialized) + }) + }) + + t.Run("Store at wrong height returns ErrNotBootstrapped", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewAccountTransactionsBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = storeBootstrapperTx(t, store, storageDB, 11, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeBootstrapperTx(t, store, storageDB, 9, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) +} + +func TestBootstrapper_BootstrapWithData(t *testing.T) { + t.Parallel() + + t.Run("bootstrap with transaction data persists and is queryable", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + firstHeight := uint64(5) + store, err := NewAccountTransactionsBootstrapper(storageDB, firstHeight) + require.NoError(t, err) + + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + txData := []access.AccountTransaction{ + { + Address: account, + BlockHeight: firstHeight, + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + } + + err = storeBootstrapperTx(t, store, storageDB, firstHeight, txData) + require.NoError(t, err) + + iter, err := store.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 1) + assert.Equal(t, txID, txs[0].TransactionID) + assert.Equal(t, uint64(5), txs[0].BlockHeight) + assert.Equal(t, uint32(0), txs[0].TransactionIndex) + assert.Equal(t, []access.TransactionRole{access.TransactionRoleAuthorizer}, txs[0].Roles) + }) + }) + + t.Run("subsequent stores work after bootstrap", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewAccountTransactionsBootstrapper(storageDB, 1) + require.NoError(t, err) + + account := unittest.RandomAddressFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + err = storeBootstrapperTx(t, store, storageDB, 1, []access.AccountTransaction{ + { + Address: account, + BlockHeight: 1, + TransactionID: txID1, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + require.NoError(t, err) + + err = storeBootstrapperTx(t, store, storageDB, 2, []access.AccountTransaction{ + { + Address: account, + BlockHeight: 2, + TransactionID: txID2, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleInteracted}, + }, + }) + require.NoError(t, err) + + iter, err := store.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 2) + + // Descending order: height 2 first, then height 1 + assert.Equal(t, txID2, txs[0].TransactionID) + assert.Equal(t, uint64(2), txs[0].BlockHeight) + assert.Equal(t, []access.TransactionRole{access.TransactionRoleInteracted}, txs[0].Roles) + + assert.Equal(t, txID1, txs[1].TransactionID) + assert.Equal(t, uint64(1), txs[1].BlockHeight) + assert.Equal(t, []access.TransactionRole{access.TransactionRoleAuthorizer}, txs[1].Roles) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(2), latest) + }) + }) +} + +func TestBootstrapper_NonConsecutiveStoreAfterBootstrap(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := NewAccountTransactionsBootstrapper(storageDB, 5) + require.NoError(t, err) + + // Bootstrap at height 5 + err = storeBootstrapperTx(t, store, storageDB, 5, nil) + require.NoError(t, err) + + // Attempt to store at height 7, skipping height 6 + err = storeBootstrapperTx(t, store, storageDB, 7, nil) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrAlreadyExists)) + assert.False(t, errors.Is(err, storage.ErrNotBootstrapped)) + }) +} + +func TestBootstrapper_PersistenceAcrossRestart(t *testing.T) { + t.Parallel() + + unittest.RunWithTempDir(t, func(dir string) { + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + func() { + db := openPebbleDB(t, dir) + defer db.Close() + + store, err := NewAccountTransactionsBootstrapper(db, 100) + require.NoError(t, err) + + _, err = store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeBootstrapperTx(t, store, db, 100, []access.AccountTransaction{ + { + Address: account, + BlockHeight: 100, + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + require.NoError(t, err) + }() + + db := openPebbleDB(t, dir) + defer db.Close() + + store, err := NewAccountTransactionsBootstrapper(db, 100) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(100), first) + + iter, err := store.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 1) + assert.Equal(t, txID, txs[0].TransactionID) + }) +} + +func TestBootstrapper_DoubleBootstrapProtection(t *testing.T) { + t.Parallel() + + lockManager := storage.NewTestingLockManager() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + err := unittest.WithLock(t, lockManager, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapAccountTransactions(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.NoError(t, err) + + // Attempting to bootstrap again via initialize should fail + err = unittest.WithLock(t, lockManager, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapAccountTransactions(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func storeBootstrapperTx( + tb testing.TB, + store storage.AccountTransactionsBootstrapper, + db storage.DB, + height uint64, + txData []access.AccountTransaction, +) error { + tb.Helper() + lockManager := storage.NewTestingLockManager() + return unittest.WithLock(tb, lockManager, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return store.Store(lctx, rw, height, txData) + }) + }) +} + +func openPebbleDB(tb testing.TB, dir string) storage.DB { + tb.Helper() + pdb, err := pebble.Open(dir, &pebble.Options{}) + require.NoError(tb, err) + return pebbleimpl.ToDB(pdb) +} diff --git a/storage/indexes/account_transactions_test.go b/storage/indexes/account_transactions_test.go new file mode 100644 index 00000000000..253fbf92c2a --- /dev/null +++ b/storage/indexes/account_transactions_test.go @@ -0,0 +1,940 @@ +package indexes + +import ( + "errors" + "math" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// collectAll drains an iterator into a slice. +func collectAll(tb testing.TB, iter storage.AccountTransactionIterator) []access.AccountTransaction { + tb.Helper() + var txs []access.AccountTransaction + for item := range iter { + tx, err := item.Value() + require.NoError(tb, err) + txs = append(txs, tx) + } + return txs +} + +func TestAccountTransactions_Initialize(t *testing.T) { + t.Parallel() + + t.Run("uninitialized database returns ErrNotBootstrapped", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + _, err := NewAccountTransactions(storageDB) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("corrupted DB with firstHeight but no latestHeight returns exception", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + // Write only the firstHeight key, simulating a corrupted state + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.UpsertByKey(rw.Writer(), keyAccountTransactionFirstHeightKey, uint64(10)) + }) + require.NoError(t, err) + + _, err = NewAccountTransactions(storageDB) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrNotBootstrapped), + "should not return ErrNotBootstrapped for corrupted state") + }) + }) + + t.Run("bootstrap initializes the index", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, _ storage.LockManager, idx *AccountTransactions) { + first := idx.FirstIndexedHeight() + assert.Equal(t, uint64(1), first) + + latest := idx.LatestIndexedHeight() + assert.Equal(t, uint64(1), latest) + }) + }) + + t.Run("bootstrap with initial data", func(t *testing.T) { + initialData := []access.AccountTransaction{ + { + Address: unittest.RandomAddressFixture(), + BlockHeight: 1, + TransactionID: unittest.IdentifierFixture(), + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + } + RunWithBootstrappedAccountTxIndex(t, 1, initialData, func(_ storage.DB, _ storage.LockManager, idx *AccountTransactions) { + first := idx.FirstIndexedHeight() + assert.Equal(t, uint64(1), first) + + latest := idx.LatestIndexedHeight() + assert.Equal(t, uint64(1), latest) + + iter, err := idx.ByAddress(initialData[0].Address, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 1) + assert.Equal(t, initialData[0].BlockHeight, txs[0].BlockHeight) + assert.Equal(t, initialData[0].TransactionID, txs[0].TransactionID) + assert.Equal(t, initialData[0].TransactionIndex, txs[0].TransactionIndex) + assert.Equal(t, initialData[0].Roles, txs[0].Roles) + }) + }) + + t.Run("bootstrap at height 0", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 0, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + assert.Equal(t, uint64(0), idx.FirstIndexedHeight()) + assert.Equal(t, uint64(0), idx.LatestIndexedHeight()) + + // Store at height 1 (consecutive after 0) + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + err := storeAccountTransactions(t, lm, idx, 1, []access.AccountTransaction{ + { + Address: account, + BlockHeight: 1, + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + require.NoError(t, err) + + assert.Equal(t, uint64(1), idx.LatestIndexedHeight()) + + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 1) + assert.Equal(t, txID, txs[0].TransactionID) + }) + }) +} + +func TestAccountTransactions_IndexAndQuery(t *testing.T) { + t.Parallel() + + t.Run("index single block with single transaction", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account1 := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + txData := []access.AccountTransaction{ + { + Address: account1, + BlockHeight: 2, + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + } + + err := storeAccountTransactions(t, lm, idx, 2, txData) + require.NoError(t, err) + + iter, err := idx.ByAddress(account1, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 1) + assert.Equal(t, txID, txs[0].TransactionID) + assert.Equal(t, uint64(2), txs[0].BlockHeight) + assert.Equal(t, uint32(0), txs[0].TransactionIndex) + assert.Equal(t, []access.TransactionRole{access.TransactionRoleAuthorizer}, txs[0].Roles) + }) + }) + + t.Run("index multiple blocks with multiple transactions", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account1 := unittest.RandomAddressFixture() + account2 := unittest.RandomAddressFixture() + require.NotEqual(t, account1, account2, "accounts should be different") + + // Block 2: one tx involving account1 + txID1 := unittest.IdentifierFixture() + err := storeAccountTransactions(t, lm, idx, 2, []access.AccountTransaction{ + { + Address: account1, + BlockHeight: 2, + TransactionID: txID1, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + require.NoError(t, err) + + // Block 3: two txs, one involving both accounts + txID2 := unittest.IdentifierFixture() + txID3 := unittest.IdentifierFixture() + err = storeAccountTransactions(t, lm, idx, 3, []access.AccountTransaction{ + { + Address: account1, + BlockHeight: 3, + TransactionID: txID2, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleInteracted}, + }, + { + Address: account2, + BlockHeight: 3, + TransactionID: txID2, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + { + Address: account2, + BlockHeight: 3, + TransactionID: txID3, + TransactionIndex: 1, + Roles: []access.TransactionRole{access.TransactionRoleInteracted}, + }, + }) + require.NoError(t, err) + + // Query account1 (should have 2 txs) + iter, err := idx.ByAddress(account1, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 2) + + // Results should be in descending order (newest first) + assert.Equal(t, txID2, txs[0].TransactionID) + assert.Equal(t, uint64(3), txs[0].BlockHeight) + assert.Equal(t, []access.TransactionRole{access.TransactionRoleInteracted}, txs[0].Roles) + + assert.Equal(t, txID1, txs[1].TransactionID) + assert.Equal(t, uint64(2), txs[1].BlockHeight) + assert.Equal(t, []access.TransactionRole{access.TransactionRoleAuthorizer}, txs[1].Roles) + + // Query account2 (should have 2 txs, both in block 3) + iter, err = idx.ByAddress(account2, nil) + require.NoError(t, err) + txs = collectAll(t, iter) + require.Len(t, txs, 2) + + // Both in block 3, ordered by txIndex ascending + assert.Equal(t, uint64(3), txs[0].BlockHeight) + assert.Equal(t, uint64(3), txs[1].BlockHeight) + assert.Less(t, txs[0].TransactionIndex, txs[1].TransactionIndex) + }) + }) +} + +func TestAccountTransactions_CursorPositioning(t *testing.T) { + t.Parallel() + + t.Run("cursor positions iterator at correct entry", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + + // Index 5 blocks (heights 2-6), each with 1 tx + for height := uint64(2); height <= 6; height++ { + txID := unittest.IdentifierFixture() + err := storeAccountTransactions(t, lm, idx, height, []access.AccountTransaction{ + { + Address: account, + BlockHeight: height, + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + require.NoError(t, err) + } + + // No cursor: starts from latest (height 6) + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 5) + assert.Equal(t, uint64(6), txs[0].BlockHeight) + assert.Equal(t, uint64(2), txs[4].BlockHeight) + + // Cursor at height 4, txIndex 0: starts from that entry inclusive + cursor := &access.AccountTransactionCursor{BlockHeight: 4, TransactionIndex: 0} + iter, err = idx.ByAddress(account, cursor) + require.NoError(t, err) + txs = collectAll(t, iter) + require.Len(t, txs, 3) // heights 4, 3, 2 + assert.Equal(t, uint64(4), txs[0].BlockHeight) + assert.Equal(t, uint64(3), txs[1].BlockHeight) + assert.Equal(t, uint64(2), txs[2].BlockHeight) + }) + }) + + t.Run("cursor within same block positions by transaction index", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + txID3 := unittest.IdentifierFixture() + err := storeAccountTransactions(t, lm, idx, 2, []access.AccountTransaction{ + {Address: account, BlockHeight: 2, TransactionID: txID1, TransactionIndex: 0, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + {Address: account, BlockHeight: 2, TransactionID: txID2, TransactionIndex: 1, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + {Address: account, BlockHeight: 2, TransactionID: txID3, TransactionIndex: 2, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + }) + require.NoError(t, err) + + // Cursor at txIndex 1: starts from txIndex 1 inclusive + cursor := &access.AccountTransactionCursor{BlockHeight: 2, TransactionIndex: 1} + iter, err := idx.ByAddress(account, cursor) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 2) + assert.Equal(t, uint32(1), txs[0].TransactionIndex) + assert.Equal(t, uint32(2), txs[1].TransactionIndex) + }) + }) +} + +func TestAccountTransactions_DescendingOrder(t *testing.T) { + t.Parallel() + + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + + // Index 10 blocks + for height := uint64(2); height <= 11; height++ { + err := storeAccountTransactions(t, lm, idx, height, []access.AccountTransaction{ + { + Address: account, + BlockHeight: height, + TransactionID: unittest.IdentifierFixture(), + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + require.NoError(t, err) + } + + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 10) + + // Verify descending order + for i := 0; i < len(txs)-1; i++ { + assert.Greater(t, txs[i].BlockHeight, txs[i+1].BlockHeight, + "results should be in descending order by height") + } + }) +} + +func TestAccountTransactions_MultiTxSameHeightOrdering(t *testing.T) { + t.Parallel() + + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + + txID0 := unittest.IdentifierFixture() + txID1 := unittest.IdentifierFixture() + txID2 := unittest.IdentifierFixture() + + // Store 3 txs for the same account at the same height with different txIndex values + err := storeAccountTransactions(t, lm, idx, 2, []access.AccountTransaction{ + { + Address: account, + BlockHeight: 2, + TransactionID: txID0, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + { + Address: account, + BlockHeight: 2, + TransactionID: txID1, + TransactionIndex: 1, + Roles: []access.TransactionRole{access.TransactionRolePayer}, + }, + { + Address: account, + BlockHeight: 2, + TransactionID: txID2, + TransactionIndex: 2, + Roles: []access.TransactionRole{access.TransactionRoleInteracted}, + }, + }) + require.NoError(t, err) + + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 3) + + // All at same height, should be ordered by ascending txIndex + assert.Equal(t, txID0, txs[0].TransactionID) + assert.Equal(t, uint32(0), txs[0].TransactionIndex) + assert.Equal(t, txID1, txs[1].TransactionID) + assert.Equal(t, uint32(1), txs[1].TransactionIndex) + assert.Equal(t, txID2, txs[2].TransactionID) + assert.Equal(t, uint32(2), txs[2].TransactionIndex) + }) +} + +func TestAccountTransactions_ErrorCases(t *testing.T) { + t.Parallel() + + t.Run("cursor before first indexed height returns error", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 5, nil, func(_ storage.DB, _ storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + + cursor := &access.AccountTransactionCursor{BlockHeight: 3, TransactionIndex: 0} + _, err := idx.ByAddress(account, cursor) + require.ErrorIs(t, err, storage.ErrHeightNotIndexed) + }) + }) + + t.Run("cursor after latest indexed height returns error", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 5, nil, func(_ storage.DB, _ storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + + cursor := &access.AccountTransactionCursor{BlockHeight: 100, TransactionIndex: 0} + _, err := idx.ByAddress(account, cursor) + require.ErrorIs(t, err, storage.ErrHeightNotIndexed) + }) + }) + + t.Run("nil cursor returns empty iterator for account with no transactions", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 5, nil, func(_ storage.DB, _ storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + assert.Empty(t, txs) + }) + }) + + t.Run("store non-consecutive height fails", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + // Try to index height 5 when latest is 1 + err := storeAccountTransactions(t, lm, idx, 5, nil) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrAlreadyExists), + "non-consecutive height should not return ErrAlreadyExists") + }) + }) + + t.Run("store below latest returns ErrAlreadyExists", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + err := storeAccountTransactions(t, lm, idx, 2, nil) + require.NoError(t, err) + err = storeAccountTransactions(t, lm, idx, 3, nil) + require.NoError(t, err) + + // Try to store height 1 (below latest=3) + err = storeAccountTransactions(t, lm, idx, 1, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("duplicate key in committed DB returns corruption error", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + txData := []access.AccountTransaction{ + { + Address: account, + BlockHeight: 2, + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + } + + // Store txData at height 2 + err := storeAccountTransactions(t, lm, idx, 2, txData) + require.NoError(t, err) + + // Simulate a partial write scenario: roll back the latest height marker + // in the DB from 2 to 1, as if the tx keys were committed but the + // height marker update was lost (e.g. crash between writes). + // Note: this should not be possible given the storage logic. + err = db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.UpsertByKey(rw.Writer(), keyAccountTransactionLatestHeightKey, uint64(1)) + }) + require.NoError(t, err) + + // Now Store at height 2 detects (via in-memory height) that height 2 is already indexed. + err = storeAccountTransactions(t, lm, idx, 2, txData) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("block height mismatch in entry fails", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + // Entry claims height 5 but we're indexing height 2 + err := storeAccountTransactions(t, lm, idx, 2, []access.AccountTransaction{ + { + Address: account, + BlockHeight: 5, // mismatch + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "block height mismatch") + }) + }) + + t.Run("repeated store at latest height returns ErrAlreadyExists", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + // Index height 2 + err := storeAccountTransactions(t, lm, idx, 2, nil) + require.NoError(t, err) + + // Re-indexing height 2 should return ErrAlreadyExists + err = storeAccountTransactions(t, lm, idx, 2, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) +} + +func TestAccountTransactions_KeyEncoding(t *testing.T) { + t.Parallel() + + t.Run("key encoding and decoding roundtrip", func(t *testing.T) { + address := unittest.RandomAddressFixture() + height := uint64(12345) + txIndex := uint32(42) + + key := makeAccountTxKey(address, height, txIndex) + + cursor, err := decodeAccountTxKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, height, cursor.BlockHeight) + assert.Equal(t, txIndex, cursor.TransactionIndex) + }) + + t.Run("makeAccountTxValue sorts roles", func(t *testing.T) { + txID := unittest.IdentifierFixture() + entry := access.AccountTransaction{ + TransactionID: txID, + // Roles deliberately out of order + Roles: []access.TransactionRole{ + access.TransactionRoleInteracted, // 3 + access.TransactionRoleAuthorizer, // 0 + access.TransactionRolePayer, // 1 + }, + } + + stored := makeAccountTxValue(entry) + assert.Equal(t, txID, stored.TransactionID) + assert.Equal(t, []access.TransactionRole{ + access.TransactionRoleAuthorizer, // 0 + access.TransactionRolePayer, // 1 + access.TransactionRoleInteracted, // 3 + }, stored.Roles) + }) + + t.Run("boundary values: height 0, txIndex 0", func(t *testing.T) { + address := unittest.RandomAddressFixture() + height := uint64(0) + txIndex := uint32(0) + + key := makeAccountTxKey(address, height, txIndex) + cursor, err := decodeAccountTxKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, height, cursor.BlockHeight) + assert.Equal(t, txIndex, cursor.TransactionIndex) + }) + + t.Run("boundary values: max height, max txIndex", func(t *testing.T) { + address := unittest.RandomAddressFixture() + height := uint64(math.MaxUint64) + txIndex := uint32(math.MaxUint32) + + key := makeAccountTxKey(address, height, txIndex) + cursor, err := decodeAccountTxKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, uint64(math.MaxUint64), cursor.BlockHeight) + assert.Equal(t, uint32(math.MaxUint32), cursor.TransactionIndex) + }) + + t.Run("boundary values: zero address", func(t *testing.T) { + address := flow.Address{} + height := uint64(12345) + txIndex := uint32(42) + + key := makeAccountTxKey(address, height, txIndex) + cursor, err := decodeAccountTxKey(key) + require.NoError(t, err) + assert.Equal(t, address, cursor.Address) + assert.Equal(t, height, cursor.BlockHeight) + assert.Equal(t, txIndex, cursor.TransactionIndex) + }) +} + +func TestAccountTransactions_KeyDecoding_Errors(t *testing.T) { + t.Parallel() + + t.Run("key too short", func(t *testing.T) { + _, err := decodeAccountTxKey(make([]byte, 10)) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid key length") + }) + + t.Run("key too long", func(t *testing.T) { + _, err := decodeAccountTxKey(make([]byte, 25)) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid key length") + }) + + t.Run("invalid prefix", func(t *testing.T) { + key := make([]byte, accountTxKeyLen) + key[0] = 0xFF // wrong prefix + _, err := decodeAccountTxKey(key) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid prefix") + }) +} + +func TestAccountTransactions_EmptyResults(t *testing.T) { + t.Parallel() + + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + // Query for account that has no transactions + account := unittest.RandomAddressFixture() + + // First index some data so we have indexed heights + err := storeAccountTransactions(t, lm, idx, 2, nil) + require.NoError(t, err) + + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + assert.Empty(t, txs) + }) +} + +func TestAccountTransactions_RolesRoundTrip(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + roles []access.TransactionRole + expectedRoles []access.TransactionRole // expected after sorting and deduplication + }{ + { + name: "single role - authorizer", + roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + expectedRoles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + { + name: "single role - payer", + roles: []access.TransactionRole{access.TransactionRolePayer}, + expectedRoles: []access.TransactionRole{access.TransactionRolePayer}, + }, + { + name: "single role - proposer", + roles: []access.TransactionRole{access.TransactionRoleProposer}, + expectedRoles: []access.TransactionRole{access.TransactionRoleProposer}, + }, + { + name: "single role - interaction", + roles: []access.TransactionRole{access.TransactionRoleInteracted}, + expectedRoles: []access.TransactionRole{access.TransactionRoleInteracted}, + }, + { + name: "multiple roles - payer and authorizer", + roles: []access.TransactionRole{ + access.TransactionRoleAuthorizer, + access.TransactionRolePayer, + }, + expectedRoles: []access.TransactionRole{ + access.TransactionRoleAuthorizer, + access.TransactionRolePayer, + }, + }, + { + name: "all roles", + roles: []access.TransactionRole{ + access.TransactionRoleAuthorizer, + access.TransactionRolePayer, + access.TransactionRoleProposer, + access.TransactionRoleInteracted, + }, + expectedRoles: []access.TransactionRole{ + access.TransactionRoleAuthorizer, + access.TransactionRolePayer, + access.TransactionRoleProposer, + access.TransactionRoleInteracted, + }, + }, + { + name: "unsorted roles are stored sorted", + roles: []access.TransactionRole{ + access.TransactionRoleInteracted, + access.TransactionRoleAuthorizer, + access.TransactionRolePayer, + }, + expectedRoles: []access.TransactionRole{ + access.TransactionRoleAuthorizer, + access.TransactionRolePayer, + access.TransactionRoleInteracted, + }, + }, + { + name: "duplicate roles are deduplicated", + roles: []access.TransactionRole{ + access.TransactionRoleInteracted, + access.TransactionRoleInteracted, + access.TransactionRoleInteracted, + }, + expectedRoles: []access.TransactionRole{ + access.TransactionRoleInteracted, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + // Copy the input roles to detect mutation + inputRoles := make([]access.TransactionRole, len(tt.roles)) + copy(inputRoles, tt.roles) + + txData := []access.AccountTransaction{ + { + Address: account, + BlockHeight: 2, + TransactionID: txID, + TransactionIndex: 0, + Roles: inputRoles, + }, + } + + err := storeAccountTransactions(t, lm, idx, 2, txData) + require.NoError(t, err) + + iter, err := idx.ByAddress(account, nil) + require.NoError(t, err) + txs := collectAll(t, iter) + require.Len(t, txs, 1) + assert.Equal(t, txID, txs[0].TransactionID) + assert.Equal(t, tt.expectedRoles, txs[0].Roles) + }) + }) + } +} + +func TestAccountTransactions_LockRequirement(t *testing.T) { + t.Parallel() + + t.Run("Store without lock returns error", func(t *testing.T) { + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *AccountTransactions) { + lctx := lm.NewContext() + defer lctx.Release() + + // Call without acquiring the required lock + err := db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, 2, nil) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) + + t.Run("initialize without lock returns error", func(t *testing.T) { + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + lctx := lm.NewContext() + defer lctx.Release() + + // Call without acquiring the required lock + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapAccountTransactions(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) +} + +func TestAccountTransactions_BootstrapHeightMismatch(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + + // Entry claims height 99 but we're bootstrapping at height 5 + err := unittest.WithLock(t, lm, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapAccountTransactions(lctx, rw, storageDB, 5, []access.AccountTransaction{ + { + Address: account, + BlockHeight: 99, // mismatch with bootstrap height 5 + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + }) + return bootstrapErr + }) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "block height mismatch") + }) +} + +func storeAccountTransactions(tb testing.TB, lockManager storage.LockManager, idx *AccountTransactions, height uint64, txData []access.AccountTransaction) error { + return unittest.WithLock(tb, lockManager, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return idx.db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, height, txData) + }) + }) +} + +// RunWithBootstrappedAccountTxIndex creates a new Pebble database and bootstraps it +// for account transaction indexing at the given start height. The callback receives a shared +// lock manager that should be passed to storeAccountTransactions for consistent lock usage. +func RunWithBootstrappedAccountTxIndex(tb testing.TB, startHeight uint64, txData []access.AccountTransaction, f func(db storage.DB, lockManager storage.LockManager, idx *AccountTransactions)) { + unittest.RunWithPebbleDB(tb, func(db *pebble.DB) { + lockManager := storage.NewTestingLockManager() + + var accountTx *AccountTransactions + storageDB := pebbleimpl.ToDB(db) + err := unittest.WithLock(tb, lockManager, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + var bootstrapErr error + accountTx, bootstrapErr = BootstrapAccountTransactions(lctx, rw, storageDB, startHeight, txData) + return bootstrapErr + }) + }) + require.NoError(tb, err) + + f(storageDB, lockManager, accountTx) + }) +} + +// TestAccountTransactions_PaginationCoversAllEntries verifies that paginating through all +// transactions for an account using CollectResults visits every entry exactly once. This +// specifically exercises the PrefixInclusiveEnd logic: when a cursor lands at firstHeight, +// the iterator range must still include all remaining entries at that height. +func TestAccountTransactions_PaginationCoversAllEntries(t *testing.T) { + t.Parallel() + + const firstHeight = uint64(5) + const pageSize = uint32(3) + + account := unittest.RandomAddressFixture() + + // Bootstrap with 3 transactions at firstHeight so that all 3 are stored at the + // first indexed height. When the page boundary later falls exactly at firstHeight, + // PrefixInclusiveEnd must pad the end key so the iterator covers all entries there. + initialTxs := []access.AccountTransaction{ + {Address: account, BlockHeight: firstHeight, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 0, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + {Address: account, BlockHeight: firstHeight, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 1, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + {Address: account, BlockHeight: firstHeight, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 2, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + } + + RunWithBootstrappedAccountTxIndex(t, firstHeight, initialTxs, func(_ storage.DB, lm storage.LockManager, idx *AccountTransactions) { + // 3 more transactions at height 6 (one above firstHeight) + err := storeAccountTransactions(t, lm, idx, 6, []access.AccountTransaction{ + {Address: account, BlockHeight: 6, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 0, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + {Address: account, BlockHeight: 6, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 1, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + {Address: account, BlockHeight: 6, TransactionID: unittest.IdentifierFixture(), TransactionIndex: 2, Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}}, + }) + require.NoError(t, err) + + // Paginate using CollectResults until cursor is nil. + // Page 1 (cursor=nil) collects height-6 entries and returns a cursor pointing + // to firstHeight. Page 2 must still return all 3 entries at firstHeight. + var allCollected []access.AccountTransaction + var cursor *access.AccountTransactionCursor + for { + txIter, err := idx.ByAddress(account, cursor) + require.NoError(t, err) + + page, nextCursor, err := iterator.CollectResults(txIter, pageSize, nil) + require.NoError(t, err) + + allCollected = append(allCollected, page...) + cursor = nextCursor + if cursor == nil { + break + } + } + + // All 6 transactions must be visited exactly once. + require.Len(t, allCollected, 6) + + // First 3 results are from height 6 (newest first), next 3 from firstHeight. + for i := 0; i < 3; i++ { + assert.Equal(t, uint64(6), allCollected[i].BlockHeight) + assert.Equal(t, uint32(i), allCollected[i].TransactionIndex) + } + for i := 0; i < 3; i++ { + assert.Equal(t, firstHeight, allCollected[3+i].BlockHeight) + assert.Equal(t, uint32(i), allCollected[3+i].TransactionIndex) + } + }) +} + +func TestAccountTransactions_UncommittedBatch(t *testing.T) { + t.Parallel() + + RunWithBootstrappedAccountTxIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *AccountTransactions) { + require.Equal(t, uint64(1), idx.LatestIndexedHeight()) + + account := unittest.RandomAddressFixture() + txID := unittest.IdentifierFixture() + txData := []access.AccountTransaction{ + { + Address: account, + BlockHeight: 2, + TransactionID: txID, + TransactionIndex: 0, + Roles: []access.TransactionRole{access.TransactionRoleAuthorizer}, + }, + } + + // Create a batch manually and store data without committing. + // Store registers an OnCommitSucceed callback to update latestHeight, + // which should only fire when the batch is committed. + batch := db.NewBatch() + err := unittest.WithLock(t, lm, storage.LockIndexAccountTransactions, func(lctx lockctx.Context) error { + return idx.Store(lctx, batch, 2, txData) + }) + require.NoError(t, err) + + // Close the batch without committing - discards pending writes + require.NoError(t, batch.Close()) + + // latestHeight must still be 1 since the batch was never committed + assert.Equal(t, uint64(1), idx.LatestIndexedHeight(), + "latestHeight should not update when the batch is not committed") + }) +} diff --git a/storage/indexes/contracts.go b/storage/indexes/contracts.go new file mode 100644 index 00000000000..6a2671785cf --- /dev/null +++ b/storage/indexes/contracts.go @@ -0,0 +1,478 @@ +package indexes + +import ( + "encoding/binary" + "fmt" + "strings" + + "github.com/jordanschalm/lockctx" + "github.com/vmihailenco/msgpack/v4" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" +) + +const ( + // contractDeploymentKeyOverhead is the number of bytes in a contract deployment key that are not + // part of the contract name. The format is: + // + // [code(1)][address bytes(8)][contract name][~height(8)][txIndex(4)][eventIndex(4)] + // + // so the overhead is code(1) + address(8) + ~height(8) + txIndex(4) + eventIndex(4) = 25 bytes. + contractDeploymentKeyOverhead = 1 + flow.AddressLength + heightLen + txIndexLen + eventIndexLen + + // minValidKeyLen is the minimum length of a valid contract deployment key. + // This is contractDeploymentKeyOverhead, plus a 1 character contract name. + minValidKeyLen = contractDeploymentKeyOverhead + 1 +) + +// storedContractDeployment holds the fields of a [access.ContractDeployment] that are not +// derivable from the primary key. Fields derivable from the key (ContractName, Address, Height, +// TxIndex, EventIndex) are not stored here. +type storedContractDeployment struct { + TransactionID flow.Identifier + Code []byte + CodeHash []byte + IsPlaceholder bool + IsDeleted bool +} + +// ContractDeploymentsIndex implements [storage.ContractDeploymentsIndex]. +// +// Primary index key format: +// +// [codeContractDeployment][address bytes(8)][contract name][~height(8)][txIndex(4)][eventIndex(4)] +// +// The one's complement of height (~height) ensures that the most recent deployment (highest +// height) has the smallest byte value, so it appears first during ascending key iteration. +// +// [All] and [ByAddress] use [BuildPrefixIterator] over the primary index with the prefix +// [codeContractDeployment][address bytes(8)][contract name], which yields exactly one entry +// (the most recent deployment) per contract without a separate secondary index. +// +// All read methods are safe for concurrent access. Write methods must be called sequentially. +type ContractDeploymentsIndex struct { + *IndexState +} + +var _ storage.ContractDeploymentsIndex = (*ContractDeploymentsIndex)(nil) + +// NewContractDeploymentsIndex creates a new index backed by db. +// +// Expected error returns during normal operation: +// - [storage.ErrNotBootstrapped]: if the index has not been initialized +func NewContractDeploymentsIndex(db storage.DB) (*ContractDeploymentsIndex, error) { + state, err := NewIndexState( + db, + storage.LockIndexContractDeployments, + keyContractDeploymentFirstHeightKey, + keyContractDeploymentLatestHeightKey, + ) + if err != nil { + return nil, fmt.Errorf("could not create index state: %w", err) + } + return &ContractDeploymentsIndex{IndexState: state}, nil +} + +// BootstrapContractDeployments initializes the index with the given start height and initial +// contract deployments, and returns a new [ContractDeploymentsIndex]. +// The caller must hold the [storage.LockIndexContractDeployments] lock until the batch is committed. +// +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists]: if any bounds key already exists +func BootstrapContractDeployments( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + db storage.DB, + initialStartHeight uint64, + deployments []access.ContractDeployment, +) (*ContractDeploymentsIndex, error) { + state, err := BootstrapIndexState( + lctx, + rw, + db, + storage.LockIndexContractDeployments, + keyContractDeploymentFirstHeightKey, + keyContractDeploymentLatestHeightKey, + initialStartHeight, + ) + if err != nil { + return nil, fmt.Errorf("could not bootstrap contract deployments: %w", err) + } + + if err := storeAllContractDeployments(rw, deployments); err != nil { + return nil, fmt.Errorf("could not store initial contract deployments: %w", err) + } + + return &ContractDeploymentsIndex{IndexState: state}, nil +} + +// ByContract returns the most recent deployment for the given contract. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if no deployment for the given contract exists +func (idx *ContractDeploymentsIndex) ByContract(account flow.Address, name string) (access.ContractDeployment, error) { + // pass a nil cursor to indicate search should start from the latest deployment + iter, err := idx.DeploymentsByContract(account, name, nil) + if err != nil { + return access.ContractDeployment{}, fmt.Errorf("could not get deployments for %s.%s: %w", account.Hex(), name, err) + } + + // iterate over deployments for the contract, and return the first one (most recent) + for item, err := range iter { + if err != nil { + return access.ContractDeployment{}, fmt.Errorf("could not iterate contract deployments for %s.%s: %w", account.Hex(), name, err) + } + return item.Value() + } + + // no deployments were found + return access.ContractDeployment{}, storage.ErrNotFound +} + +// DeploymentsByContract returns an iterator over all recorded deployments for the given +// contract, ordered from most recent to oldest (descending block height). +// +// cursor is a pointer to an [access.ContractDeploymentsCursor]: +// - nil means start from the most recent deployment +// - non-nil means start at the cursor position (inclusive) +// +// Returns an exhausted iterator (zero items) and no error if no deployments exist for the given contract. +// +// No error returns are expected during normal operation. +func (idx *ContractDeploymentsIndex) DeploymentsByContract( + account flow.Address, + name string, + cursor *access.ContractDeploymentsCursor, +) (storage.ContractDeploymentIterator, error) { + startKey, endKey, err := idx.rangeKeysByContract(account, name, cursor) + if err != nil { + return nil, fmt.Errorf("could not determine range keys: %w", err) + } + + reader := idx.db.Reader() + storageIter, err := reader.NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator for contract %s.%s: %w", account.Hex(), name, err) + } + + return iterator.Build(storageIter, decodeDeploymentCursor, reconstructContractDeployment), nil +} + +// All returns an iterator over the latest deployment for each indexed contract, +// ordered by contract identifier (ascending). +// +// cursor is a pointer to an [access.ContractDeploymentsCursor]: +// - nil means start from the first contract (by identifier) +// - non-nil resumes from (cursor.Address, cursor.ContractName) (inclusive); other cursor fields are ignored +// +// Returns an exhausted iterator (zero items) and no error if no contracts exist. +// +// No error returns are expected during normal operation. +func (idx *ContractDeploymentsIndex) All( + cursor *access.ContractDeploymentsCursor, +) (storage.ContractDeploymentIterator, error) { + startKey, endKey, err := idx.rangeKeysAll(cursor) + if err != nil { + return nil, fmt.Errorf("could not determine range keys: %w", err) + } + + reader := idx.db.Reader() + storageIter, err := reader.NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator for all contracts: %w", err) + } + + // this prefix iterator will return the first entry for each prefix returned by contractDeploymentKeyPrefix + return iterator.BuildPrefixIterator( + storageIter, + decodeDeploymentCursor, + reconstructContractDeployment, + contractDeploymentKeyPrefix, + ), nil +} + +// ByAddress returns an iterator over the latest deployment for each contract deployed by the +// given address, ordered by contract identifier (ascending). +// +// cursor is a pointer to an [access.ContractDeploymentsCursor]: +// - nil means start from the first contract at the address (by identifier) +// - non-nil resumes from (cursor.Address, cursor.ContractName) (inclusive); other cursor fields are ignored +// +// Returns an exhausted iterator (zero items) and no error if no deployments exist for the given address. +// +// No error returns are expected during normal operation. +func (idx *ContractDeploymentsIndex) ByAddress( + account flow.Address, + cursor *access.ContractDeploymentsCursor, +) (storage.ContractDeploymentIterator, error) { + startKey, endKey, err := idx.rangeKeysByAddress(account, cursor) + if err != nil { + return nil, fmt.Errorf("could not determine range keys: %w", err) + } + + reader := idx.db.Reader() + storageIter, err := reader.NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator for address %s: %w", account.Hex(), err) + } + + // this prefix iterator will return the first entry for each prefix returned by contractDeploymentKeyPrefix + return iterator.BuildPrefixIterator( + storageIter, + decodeDeploymentCursor, + reconstructContractDeployment, + contractDeploymentKeyPrefix, + ), nil +} + +// rangeKeysByContract computes the start and end keys for iterating over deployments of a specific +// contract, based on the provided cursor. +// +// Any error indicates the cursor is invalid. +func (idx *ContractDeploymentsIndex) rangeKeysByContract(account flow.Address, name string, cursor *access.ContractDeploymentsCursor) (startKey, endKey []byte, err error) { + prefix := makeContractDeploymentContractPrefix(account, name) + + latestHeight := idx.latestHeight.Load() + if cursor == nil { + // by default, iterate over all deployments for the contract + return prefix, prefix, nil + } + + if err := validateCursorHeight(cursor.BlockHeight, idx.firstHeight, latestHeight); err != nil { + return nil, nil, err + } + + startKey = makeContractDeploymentKey(account, name, cursor.BlockHeight, cursor.TransactionIndex, cursor.EventIndex) + endKey = storage.PrefixInclusiveEnd(prefix, startKey) + + return startKey, endKey, nil +} + +// rangeKeysAll computes the start and end keys for iterating over all contracts, based on the provided cursor. +// +// Any error indicates the cursor is invalid. +func (idx *ContractDeploymentsIndex) rangeKeysAll(cursor *access.ContractDeploymentsCursor) (startKey, endKey []byte, err error) { + prefix := []byte{codeContractDeployment} + + if cursor == nil || cursor.ContractName == "" { + // by default, iterate over all contracts + return prefix, prefix, nil + } + + startKey = makeContractDeploymentContractPrefix(cursor.Address, cursor.ContractName) + endKey = storage.PrefixInclusiveEnd(prefix, startKey) + + return startKey, endKey, nil +} + +// rangeKeysByAddress computes the start and end keys for iterating over contracts by address, based on +// the provided cursor. +// +// Any error indicates the cursor is invalid. +func (idx *ContractDeploymentsIndex) rangeKeysByAddress(account flow.Address, cursor *access.ContractDeploymentsCursor) (startKey, endKey []byte, err error) { + prefix := makeContractDeploymentAddressPrefix(account) + + if cursor == nil || cursor.ContractName == "" { + // by default, iterate over all contracts for the address + return prefix, prefix, nil + } + + startKey = makeContractDeploymentContractPrefix(cursor.Address, cursor.ContractName) + endKey = storage.PrefixInclusiveEnd(prefix, startKey) + + return startKey, endKey, nil +} + +// Store indexes all contract deployments from the given block and advances the latest indexed +// height to blockHeight. Must be called with consecutive block heights. +// The caller must hold the [storage.LockIndexContractDeployments] lock until the batch is committed. +// +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists]: if blockHeight has already been indexed +func (idx *ContractDeploymentsIndex) Store( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + blockHeight uint64, + deployments []access.ContractDeployment, +) error { + if err := idx.PrepareStore(lctx, rw, blockHeight); err != nil { + return fmt.Errorf("could not prepare store for block %d: %w", blockHeight, err) + } + + return storeAllContractDeployments(rw, deployments) +} + +// storeAllContractDeployments writes all contract deployment entries to the batch. +// For each deployment it writes a primary index entry at +// [codeContractDeployment][address bytes][contract name][~height][txIndex][eventIndex]. +// +// The caller must hold the [storage.LockIndexContractDeployments] lock until the batch is committed. +// +// No error returns are expected during normal operation. +func storeAllContractDeployments(rw storage.ReaderBatchWriter, deployments []access.ContractDeployment) error { + writer := rw.Writer() + for _, d := range deployments { + if d.ContractName == "" || strings.Contains(d.ContractName, ".") { + return fmt.Errorf("deployment for %s has invalid contract name: %q", d.Address.Hex(), d.ContractName) + } + + primaryKey := makeContractDeploymentKey(d.Address, d.ContractName, d.BlockHeight, d.TransactionIndex, d.EventIndex) + exists, err := operation.KeyExists(rw.GlobalReader(), primaryKey) + if err != nil { + return fmt.Errorf("could not check key for deployment %s.%s: %w", d.Address.Hex(), d.ContractName, err) + } + if exists { + return fmt.Errorf("deployment A.%s.%s at height %d already exists: %w", d.Address.Hex(), d.ContractName, d.BlockHeight, storage.ErrAlreadyExists) + } + primaryVal := storedContractDeployment{ + TransactionID: d.TransactionID, + Code: d.Code, + CodeHash: d.CodeHash, + IsPlaceholder: d.IsPlaceholder, + IsDeleted: d.IsDeleted, + } + if err := operation.UpsertByKey(writer, primaryKey, primaryVal); err != nil { + return fmt.Errorf("could not store primary deployment entry for A.%s.%s: %w", d.Address.Hex(), d.ContractName, err) + } + } + return nil +} + +// makeContractDeploymentKey creates a primary key for the given address, contract name, height, +// txIndex, and eventIndex. +// +// Key format: [codeContractDeployment][address bytes(8)][contract name][~height(8)][txIndex(4)][eventIndex(4)] +func makeContractDeploymentKey(addr flow.Address, name string, height uint64, txIndex, eventIndex uint32) []byte { + nameBytes := []byte(name) + key := make([]byte, contractDeploymentKeyOverhead+len(nameBytes)) + offset := 0 + + key[offset] = codeContractDeployment + offset++ + + copy(key[offset:], addr[:]) + offset += flow.AddressLength + + copy(key[offset:], nameBytes) + offset += len(nameBytes) + + binary.BigEndian.PutUint64(key[offset:], ^height) // one's complement for descending height order + offset += heightLen + + binary.BigEndian.PutUint32(key[offset:], txIndex) + offset += txIndexLen + + binary.BigEndian.PutUint32(key[offset:], eventIndex) + + return key +} + +// makeContractDeploymentContractPrefix returns the prefix used to iterate over all deployments +// of a specific contract: +// +// [codeContractDeployment][address bytes(8)][contract name bytes] +func makeContractDeploymentContractPrefix(addr flow.Address, name string) []byte { + nameBytes := []byte(name) + prefix := make([]byte, 1+flow.AddressLength+len(nameBytes)) + prefix[0] = codeContractDeployment + copy(prefix[1:], addr[:]) + copy(prefix[1+flow.AddressLength:], nameBytes) + return prefix +} + +// makeContractDeploymentAddressPrefix returns the prefix used to iterate over all contracts +// deployed by a specific address: +// +// [codeContractDeployment][address bytes(8)] +// +// This prefix matches all contracts owned by the given address, since the address occupies a +// fixed 8-byte slot at the start of every primary key. +func makeContractDeploymentAddressPrefix(addr flow.Address) []byte { + prefix := make([]byte, 1+flow.AddressLength) + prefix[0] = codeContractDeployment + copy(prefix[1:], addr[:]) + return prefix +} + +// contractDeploymentKeyPrefix returns the contract-specific portion of a primary key: +// +// [codeContractDeployment][address bytes(8)][contract name bytes] +// +// It strips the fixed 16-byte suffix ([~height(8)][txIndex(4)][eventIndex(4)]) from the key. +// Used as the keyPrefix argument to [iterator.BuildPrefixIterator] so that all deployments of +// the same contract are grouped together and only the first (most recent) is yielded. +func contractDeploymentKeyPrefix(key []byte) ([]byte, error) { + if len(key) < minValidKeyLen { + return nil, fmt.Errorf("key too short: expected at least %d bytes, got %d", minValidKeyLen, len(key)) + } + if key[0] != codeContractDeployment { + return nil, fmt.Errorf("invalid key prefix: expected %d, got %d", codeContractDeployment, key[0]) + } + return key[:len(key)-heightLen-txIndexLen-eventIndexLen], nil +} + +// decodeDeploymentCursor decodes a primary key into an [access.ContractDeploymentsCursor]. +// +// Any error indicates a malformed key. +func decodeDeploymentCursor(key []byte) (access.ContractDeploymentsCursor, error) { + if len(key) < minValidKeyLen { + return access.ContractDeploymentsCursor{}, fmt.Errorf("key too short: %d bytes", len(key)) + } + if key[0] != codeContractDeployment { + return access.ContractDeploymentsCursor{}, fmt.Errorf("invalid prefix: expected %d, got %d", codeContractDeployment, key[0]) + } + offset := 1 + + var addr flow.Address + copy(addr[:], key[offset:offset+flow.AddressLength]) + offset += flow.AddressLength + + // The fixed-size suffix is ~height(8) + txIndex(4) + eventIndex(4) = 16 bytes. + // Everything between the address and the suffix is the contract name. + nameEnd := len(key) - heightLen - txIndexLen - eventIndexLen + contractName := string(key[offset:nameEnd]) + offset = nameEnd + + height := ^binary.BigEndian.Uint64(key[offset:]) + offset += heightLen + + txIndex := binary.BigEndian.Uint32(key[offset:]) + offset += txIndexLen + + eventIndex := binary.BigEndian.Uint32(key[offset:]) + + return access.ContractDeploymentsCursor{ + Address: addr, + ContractName: contractName, + BlockHeight: height, + TransactionIndex: txIndex, + EventIndex: eventIndex, + }, nil +} + +// reconstructContractDeployment builds a full [access.ContractDeployment] from a decoded +// [access.ContractDeploymentsCursor] and the primary index value bytes. +// +// Any error indicates a malformed value. +func reconstructContractDeployment(cursor access.ContractDeploymentsCursor, val []byte) (*access.ContractDeployment, error) { + var stored storedContractDeployment + if err := msgpack.Unmarshal(val, &stored); err != nil { + return nil, fmt.Errorf("could not unmarshal contract deployment: %w", err) + } + return &access.ContractDeployment{ + ContractName: cursor.ContractName, + Address: cursor.Address, + BlockHeight: cursor.BlockHeight, + TransactionID: stored.TransactionID, + TransactionIndex: cursor.TransactionIndex, + EventIndex: cursor.EventIndex, + Code: stored.Code, + CodeHash: stored.CodeHash, + IsPlaceholder: stored.IsPlaceholder, + IsDeleted: stored.IsDeleted, + }, nil +} diff --git a/storage/indexes/contracts_bootstrapper.go b/storage/indexes/contracts_bootstrapper.go new file mode 100644 index 00000000000..31a66fd6e04 --- /dev/null +++ b/storage/indexes/contracts_bootstrapper.go @@ -0,0 +1,185 @@ +package indexes + +import ( + "errors" + "fmt" + + "github.com/jordanschalm/lockctx" + "go.uber.org/atomic" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// ContractDeploymentsBootstrapper wraps a [ContractDeploymentsIndex] and performs +// just-in-time initialization of the index when the initial block is provided. +// +// Contract deployments may not be available for the root block during bootstrapping. +// This struct acts as a proxy for the underlying [ContractDeploymentsIndex] and +// encapsulates the complexity of initializing the index when the initial block is eventually provided. +type ContractDeploymentsBootstrapper struct { + db storage.DB + initialStartHeight uint64 + + store *atomic.Pointer[ContractDeploymentsIndex] +} + +var _ storage.ContractDeploymentsIndexBootstrapper = (*ContractDeploymentsBootstrapper)(nil) + +// NewContractDeploymentsBootstrapper creates a new contract deployments bootstrapper. +// +// No error returns are expected during normal operation. +func NewContractDeploymentsBootstrapper(db storage.DB, initialStartHeight uint64) (*ContractDeploymentsBootstrapper, error) { + store, err := NewContractDeploymentsIndex(db) + if err != nil { + if !errors.Is(err, storage.ErrNotBootstrapped) { + return nil, fmt.Errorf("could not create contract deployments index: %w", err) + } + // not yet bootstrapped — start with a nil store + store = nil + } + + return &ContractDeploymentsBootstrapper{ + db: db, + initialStartHeight: initialStartHeight, + store: atomic.NewPointer(store), + }, nil +} + +// FirstIndexedHeight returns the first (oldest) block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ContractDeploymentsBootstrapper) FirstIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.FirstIndexedHeight(), nil +} + +// LatestIndexedHeight returns the latest block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ContractDeploymentsBootstrapper) LatestIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.LatestIndexedHeight(), nil +} + +// UninitializedFirstHeight returns the height the index will accept as the first height, and a +// boolean indicating if the index is initialized. +// If the index is not initialized, the first call to Store must include data for this height. +func (b *ContractDeploymentsBootstrapper) UninitializedFirstHeight() (uint64, bool) { + store := b.store.Load() + if store == nil { + return b.initialStartHeight, false + } + return store.FirstIndexedHeight(), true +} + +// ByContract returns the most recent deployment for the given contract. +// See [ContractDeploymentsIndex.ByContract]. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrNotFound] if no deployment for the given contract exists +func (b *ContractDeploymentsBootstrapper) ByContract(account flow.Address, name string) (accessmodel.ContractDeployment, error) { + store := b.store.Load() + if store == nil { + return accessmodel.ContractDeployment{}, storage.ErrNotBootstrapped + } + return store.ByContract(account, name) +} + +// DeploymentsByContract returns an iterator over all recorded deployments for the given contract, +// ordered from most recent to oldest. See [ContractDeploymentsIndex.DeploymentsByContract]. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ContractDeploymentsBootstrapper) DeploymentsByContract( + account flow.Address, + name string, + cursor *accessmodel.ContractDeploymentsCursor, +) (storage.ContractDeploymentIterator, error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.DeploymentsByContract(account, name, cursor) +} + +// ByAddress returns an iterator over the latest deployment for each contract deployed by the +// given address. See [ContractDeploymentsIndex.ByAddress]. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ContractDeploymentsBootstrapper) ByAddress( + account flow.Address, + cursor *accessmodel.ContractDeploymentsCursor, +) (storage.ContractDeploymentIterator, error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.ByAddress(account, cursor) +} + +// All returns an iterator over the latest deployment for each indexed contract. +// See [ContractDeploymentsIndex.All]. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ContractDeploymentsBootstrapper) All( + cursor *accessmodel.ContractDeploymentsCursor, +) (storage.ContractDeploymentIterator, error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.All(cursor) +} + +// Store indexes all contract deployments from the given block and advances the latest indexed +// height to blockHeight. Must be called with consecutive heights. +// The caller must hold the [storage.LockIndexContractDeployments] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized and the provided block +// height is not the initial start height +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (b *ContractDeploymentsBootstrapper) Store( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + blockHeight uint64, + deployments []accessmodel.ContractDeployment, +) error { + // if the index is already initialized, store the data directly + if store := b.store.Load(); store != nil { + return store.Store(lctx, rw, blockHeight, deployments) + } + + // otherwise bootstrap the index + if blockHeight != b.initialStartHeight { + return fmt.Errorf("expected first indexed height %d, got %d: %w", b.initialStartHeight, blockHeight, storage.ErrNotBootstrapped) + } + + store, err := BootstrapContractDeployments(lctx, rw, b.db, b.initialStartHeight, deployments) + if err != nil { + return fmt.Errorf("could not initialize contract deployments storage: %w", err) + } + + if !b.store.CompareAndSwap(nil, store) { + // this should never happen. if it does, there is a bug. this indicates another goroutine + // successfully initialized `store` since we checked the value above. since the bootstrap + // operation is protected by the lock and it performs sanity checks to ensure the table + // is actually empty, the bootstrap operation should fail if there was concurrent access. + return fmt.Errorf("contract deployments index initialized during bootstrap") + } + + return nil +} diff --git a/storage/indexes/contracts_bootstrapper_test.go b/storage/indexes/contracts_bootstrapper_test.go new file mode 100644 index 00000000000..efed20a17ad --- /dev/null +++ b/storage/indexes/contracts_bootstrapper_test.go @@ -0,0 +1,232 @@ +package indexes + +import ( + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +func TestContractDeploymentsBootstrapper_Constructor(t *testing.T) { + t.Parallel() + + t.Run("nil store when not bootstrapped", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + b, err := NewContractDeploymentsBootstrapper(storageDB, 5) + require.NoError(t, err) + // Store is nil: read operations return ErrNotBootstrapped + _, err = b.ByContract(flow.HexToAddress("1234567890abcdef"), "Foo") + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("loads existing bootstrapped index", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 7, nil, func(db storage.DB, _ storage.LockManager, _ *ContractDeploymentsIndex) { + b, err := NewContractDeploymentsBootstrapper(db, 7) + require.NoError(t, err) + + first, err := b.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(7), first) + + latest, err := b.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(7), latest) + }) + }) +} + +func TestContractDeploymentsBootstrapper_BeforeBootstrap(t *testing.T) { + t.Parallel() + + // A bootstrapper created from an empty DB: all read methods return ErrNotBootstrapped. + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + b, err := NewContractDeploymentsBootstrapper(storageDB, 5) + require.NoError(t, err) + + t.Run("FirstIndexedHeight returns ErrNotBootstrapped", func(t *testing.T) { + _, err := b.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + + t.Run("LatestIndexedHeight returns ErrNotBootstrapped", func(t *testing.T) { + _, err := b.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + + t.Run("ByContract returns ErrNotBootstrapped", func(t *testing.T) { + _, err := b.ByContract(flow.HexToAddress("1234567890abcdef"), "Foo") + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + + t.Run("DeploymentsByContract returns ErrNotBootstrapped", func(t *testing.T) { + _, err := b.DeploymentsByContract(flow.HexToAddress("1234567890abcdef"), "Foo", nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + + t.Run("ByAddress returns ErrNotBootstrapped", func(t *testing.T) { + _, err := b.ByAddress(unittest.RandomAddressFixture(), nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + + t.Run("All returns ErrNotBootstrapped", func(t *testing.T) { + _, err := b.All(nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) +} + +func TestContractDeploymentsBootstrapper_UninitializedFirstHeight(t *testing.T) { + t.Parallel() + + t.Run("returns (initialStartHeight, false) before bootstrap", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + b, err := NewContractDeploymentsBootstrapper(storageDB, 42) + require.NoError(t, err) + + h, initialized := b.UninitializedFirstHeight() + assert.Equal(t, uint64(42), h) + assert.False(t, initialized) + }) + }) + + t.Run("returns (firstHeight, true) after bootstrap", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + b, err := NewContractDeploymentsBootstrapper(storageDB, 10) + require.NoError(t, err) + + // Bootstrap by calling Store at the initial height. + err = unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return b.Store(lctx, rw, 10, nil) + }) + }) + require.NoError(t, err) + + h, initialized := b.UninitializedFirstHeight() + assert.Equal(t, uint64(10), h) + assert.True(t, initialized) + }) + }) +} + +func TestContractDeploymentsBootstrapper_Store(t *testing.T) { + t.Parallel() + + t.Run("store at wrong height before bootstrap returns ErrNotBootstrapped", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + b, err := NewContractDeploymentsBootstrapper(storageDB, 10) + require.NoError(t, err) + + // Store at height 5 when initialStartHeight is 10 + err = unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return b.Store(lctx, rw, 5, nil) + }) + }) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("store at correct height bootstraps index", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + b, err := NewContractDeploymentsBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return b.Store(lctx, rw, 10, nil) + }) + }) + require.NoError(t, err) + + // After bootstrapping, read operations should succeed. + first, err := b.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(10), first) + }) + }) + + t.Run("subsequent heights work normally after bootstrap", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + b, err := NewContractDeploymentsBootstrapper(storageDB, 10) + require.NoError(t, err) + + // Bootstrap at height 10 + err = unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return b.Store(lctx, rw, 10, nil) + }) + }) + require.NoError(t, err) + + // Store at height 11 should work + d := makeDeployment(flow.HexToAddress("1234567890abcdef"), "MyContract", 11, 0, 0) + err = unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return b.Store(lctx, rw, 11, []access.ContractDeployment{d}) + }) + }) + require.NoError(t, err) + + // Verify the deployment is queryable + result, err := b.ByContract(d.Address, d.ContractName) + require.NoError(t, err) + assertDeployment(t, d, result) + }) + }) + + t.Run("store with initial deployments at bootstrap height", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + b, err := NewContractDeploymentsBootstrapper(storageDB, 5) + require.NoError(t, err) + + d := makeDeployment(flow.HexToAddress("1234567890abcdef"), "MyContract", 5, 0, 0) + + err = unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return b.Store(lctx, rw, 5, []access.ContractDeployment{d}) + }) + }) + require.NoError(t, err) + + result, err := b.ByContract(d.Address, d.ContractName) + require.NoError(t, err) + assertDeployment(t, d, result) + }) + }) +} diff --git a/storage/indexes/contracts_test.go b/storage/indexes/contracts_test.go new file mode 100644 index 00000000000..b880ac297e7 --- /dev/null +++ b/storage/indexes/contracts_test.go @@ -0,0 +1,900 @@ +package indexes + +import ( + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// RunWithBootstrappedContractDeploymentsIndex creates a fresh Pebble database and bootstraps +// it for contract deployment indexing at the given start height with the given initial +// deployments. The callback receives the shared storage DB, lock manager, and the index. +func RunWithBootstrappedContractDeploymentsIndex( + tb testing.TB, + startHeight uint64, + deployments []access.ContractDeployment, + f func(db storage.DB, lockManager storage.LockManager, idx *ContractDeploymentsIndex), +) { + unittest.RunWithPebbleDB(tb, func(db *pebble.DB) { + lockManager := storage.NewTestingLockManager() + var idx *ContractDeploymentsIndex + storageDB := pebbleimpl.ToDB(db) + err := unittest.WithLock(tb, lockManager, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + var bootstrapErr error + idx, bootstrapErr = BootstrapContractDeployments(lctx, rw, storageDB, startHeight, deployments) + return bootstrapErr + }) + }) + require.NoError(tb, err) + f(storageDB, lockManager, idx) + }) +} + +// storeContractDeployments stores a block of contract deployments at the given height using the +// provided index and lock manager. +func storeContractDeployments( + tb testing.TB, + lm storage.LockManager, + idx *ContractDeploymentsIndex, + height uint64, + deployments []access.ContractDeployment, +) error { + return unittest.WithLock(tb, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return idx.db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, height, deployments) + }) + }) +} + +// collectContractDeployments is a test helper that creates a DeploymentsByContract iterator +// and collects results via CollectResults. +func collectContractDeployments( + tb testing.TB, + idx *ContractDeploymentsIndex, + addr flow.Address, + name string, + limit uint32, + cursor *access.ContractDeploymentsCursor, + filter storage.IndexFilter[*access.ContractDeployment], +) ([]access.ContractDeployment, *access.ContractDeploymentsCursor) { + tb.Helper() + iter, err := idx.DeploymentsByContract(addr, name, cursor) + require.NoError(tb, err) + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter) + require.NoError(tb, err) + return collected, nextCursor +} + +// collectAllContracts is a test helper that creates an All iterator and collects results +// via CollectResults. +func collectAllContracts( + tb testing.TB, + idx *ContractDeploymentsIndex, + limit uint32, + cursor *access.ContractDeploymentsCursor, + filter storage.IndexFilter[*access.ContractDeployment], +) ([]access.ContractDeployment, *access.ContractDeploymentsCursor) { + tb.Helper() + iter, err := idx.All(cursor) + require.NoError(tb, err) + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter) + require.NoError(tb, err) + return collected, nextCursor +} + +// collectContractsByAddress is a test helper that creates a ByAddress iterator and collects +// results via CollectResults. +func collectContractsByAddress( + tb testing.TB, + idx *ContractDeploymentsIndex, + addr flow.Address, + limit uint32, + cursor *access.ContractDeploymentsCursor, + filter storage.IndexFilter[*access.ContractDeployment], +) ([]access.ContractDeployment, *access.ContractDeploymentsCursor) { + tb.Helper() + iter, err := idx.ByAddress(addr, cursor) + require.NoError(tb, err) + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter) + require.NoError(tb, err) + return collected, nextCursor +} + +// assertDeployment asserts that actual matches all fields of expected. +func assertDeployment(tb testing.TB, expected, actual access.ContractDeployment) { + tb.Helper() + assert.Equal(tb, expected.Address, actual.Address) + assert.Equal(tb, expected.ContractName, actual.ContractName) + assert.Equal(tb, expected.BlockHeight, actual.BlockHeight) + assert.Equal(tb, expected.TransactionID, actual.TransactionID) + assert.Equal(tb, expected.TransactionIndex, actual.TransactionIndex) + assert.Equal(tb, expected.EventIndex, actual.EventIndex) + assert.Equal(tb, expected.Code, actual.Code) + assert.Equal(tb, expected.CodeHash, actual.CodeHash) + assert.Equal(tb, expected.IsDeleted, actual.IsDeleted) + assert.Equal(tb, expected.IsPlaceholder, actual.IsPlaceholder) +} + +// makeDeployment builds a minimal access.ContractDeployment for use in tests. +func makeDeployment(addr flow.Address, name string, height uint64, txIndex, eventIndex uint32) access.ContractDeployment { + fakeHash := unittest.IdentifierFixture() + return access.ContractDeployment{ + ContractName: name, + Address: addr, + BlockHeight: height, + TransactionID: unittest.IdentifierFixture(), + TransactionIndex: txIndex, + EventIndex: eventIndex, + Code: []byte("access(all) contract MyContract {}"), + CodeHash: fakeHash[:], + } +} + +// ---------------------------------------------------------------------------- +// NewContractDeploymentsIndex +// ---------------------------------------------------------------------------- + +func TestContractDeployments_NewIndex(t *testing.T) { + t.Parallel() + + t.Run("uninitialized database returns ErrNotBootstrapped", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + _, err := NewContractDeploymentsIndex(storageDB) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) + }) + + t.Run("corrupted DB with only first height key returns exception", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + // Write only the firstHeight key, simulating a corrupted state. + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.UpsertByKey(rw.Writer(), keyContractDeploymentFirstHeightKey, uint64(10)) + }) + require.NoError(t, err) + + _, err = NewContractDeploymentsIndex(storageDB) + require.Error(t, err) + assert.NotErrorIs(t, err, storage.ErrNotBootstrapped, "corrupted state should not return ErrNotBootstrapped") + }) + }) + + t.Run("already bootstrapped loads correctly", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 5, nil, func(db storage.DB, _ storage.LockManager, _ *ContractDeploymentsIndex) { + // Open the index again from the same DB — should succeed. + idx2, err := NewContractDeploymentsIndex(db) + require.NoError(t, err) + assert.Equal(t, uint64(5), idx2.FirstIndexedHeight()) + assert.Equal(t, uint64(5), idx2.LatestIndexedHeight()) + }) + }) +} + +// ---------------------------------------------------------------------------- +// BootstrapContractDeployments +// ---------------------------------------------------------------------------- + +func TestContractDeployments_Bootstrap(t *testing.T) { + t.Parallel() + + t.Run("bootstrap initializes height markers", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 10, nil, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + assert.Equal(t, uint64(10), idx.FirstIndexedHeight()) + assert.Equal(t, uint64(10), idx.LatestIndexedHeight()) + }) + }) + + t.Run("bootstrap at height 0", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 0, nil, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + assert.Equal(t, uint64(0), idx.FirstIndexedHeight()) + assert.Equal(t, uint64(0), idx.LatestIndexedHeight()) + }) + }) + + t.Run("bootstrap with initial deployments stores them", func(t *testing.T) { + t.Parallel() + d := makeDeployment(unittest.RandomAddressFixture(), "MyContract", 5, 0, 0) + RunWithBootstrappedContractDeploymentsIndex(t, 5, []access.ContractDeployment{d}, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + result, err := idx.ByContract(d.Address, d.ContractName) + require.NoError(t, err) + assertDeployment(t, d, result) + }) + }) + + t.Run("empty contract name returns error during bootstrap", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + deployment := access.ContractDeployment{ + Address: unittest.RandomAddressFixture(), + ContractName: "", + BlockHeight: 1, + } + + err := unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, err := BootstrapContractDeployments(lctx, rw, storageDB, 1, []access.ContractDeployment{deployment}) + return err + }) + }) + require.Error(t, err) + }) + }) + + t.Run("contract name containing dot returns error during bootstrap", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + deployment := access.ContractDeployment{ + Address: unittest.RandomAddressFixture(), + ContractName: "My.Contract", + BlockHeight: 1, + } + + err := unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, err := BootstrapContractDeployments(lctx, rw, storageDB, 1, []access.ContractDeployment{deployment}) + return err + }) + }) + require.Error(t, err) + }) + }) + + t.Run("double-bootstrap returns ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, _ *ContractDeploymentsIndex) { + err := unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapContractDeployments(lctx, rw, db, 1, nil) + return bootstrapErr + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) +} + +// ---------------------------------------------------------------------------- +// ByContract +// ---------------------------------------------------------------------------- + +func TestContractDeployments_ByContract(t *testing.T) { + t.Parallel() + + t.Run("not found returns ErrNotFound", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + _, err := idx.ByContract(unittest.RandomAddressFixture(), "NoSuchContract") + require.ErrorIs(t, err, storage.ErrNotFound) + }) + }) + + t.Run("returns most recent deployment when multiple exist", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + d1 := makeDeployment(addr, "MyContract", 2, 0, 0) + d2 := makeDeployment(addr, "MyContract", 3, 0, 0) + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d1})) + require.NoError(t, storeContractDeployments(t, lm, idx, 3, []access.ContractDeployment{d2})) + + result, err := idx.ByContract(d2.Address, d2.ContractName) + require.NoError(t, err) + // Most recent is height 3 + assert.Equal(t, uint64(3), result.BlockHeight) + }) + }) + + t.Run("returns single deployment correctly", func(t *testing.T) { + t.Parallel() + d := makeDeployment(unittest.RandomAddressFixture(), "MyContract", 2, 1, 2) + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d})) + + result, err := idx.ByContract(d.Address, d.ContractName) + require.NoError(t, err) + assertDeployment(t, d, result) + }) + }) +} + +// ---------------------------------------------------------------------------- +// DeploymentsByContractID +// ---------------------------------------------------------------------------- + +func TestContractDeployments_DeploymentsByContractID(t *testing.T) { + t.Parallel() + + t.Run("no deployments for contract returns empty results", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + collected, nextCursor := collectContractDeployments(t, idx, unittest.RandomAddressFixture(), "NoSuchContract", 10, nil, nil) + assert.Empty(t, collected) + assert.Nil(t, nextCursor) + }) + }) + + t.Run("first page returns deployments in descending order", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + d1 := makeDeployment(addr, "MyContract", 2, 1, 4) + d2 := makeDeployment(addr, "MyContract", 3, 2, 5) + d3 := makeDeployment(addr, "MyContract", 4, 3, 6) + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d1})) + require.NoError(t, storeContractDeployments(t, lm, idx, 3, []access.ContractDeployment{d2})) + require.NoError(t, storeContractDeployments(t, lm, idx, 4, []access.ContractDeployment{d3})) + + collected, nextCursor := collectContractDeployments(t, idx, addr, "MyContract", 10, nil, nil) + require.Len(t, collected, 3) + // Descending order: height 4, 3, 2 + assertDeployment(t, d3, collected[0]) + assertDeployment(t, d2, collected[1]) + assertDeployment(t, d1, collected[2]) + assert.Nil(t, nextCursor) + }) + }) + + t.Run("has-more sets NextCursor pointing to first item of next page", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + name := "MyContract" + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + // Store 3 deployments at heights 2, 3, 4 + for h := uint64(2); h <= 4; h++ { + d := makeDeployment(addr, name, h, 0, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, h, []access.ContractDeployment{d})) + } + + // Request page of 2 when 3 exist: returns [h=4, h=3], cursor points to h=2 (next page). + collected, nextCursor := collectContractDeployments(t, idx, addr, name, 2, nil, nil) + require.Len(t, collected, 2) + require.NotNil(t, nextCursor) + assert.Equal(t, uint64(2), nextCursor.BlockHeight) + }) + }) + + t.Run("with cursor resumes from cursor position (inclusive)", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + name := "MyContract" + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + // Store 4 deployments at heights 2-5 + for h := uint64(2); h <= 5; h++ { + d := makeDeployment(addr, name, h, 0, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, h, []access.ContractDeployment{d})) + } + + // First page: limit=2, no cursor → [h=5, h=4], cursor → h=3 + collected1, nextCursor := collectContractDeployments(t, idx, addr, name, 2, nil, nil) + require.Len(t, collected1, 2) + require.NotNil(t, nextCursor) + + require.Equal(t, uint64(3), nextCursor.BlockHeight) + require.Equal(t, uint32(0), nextCursor.TransactionIndex) + require.Equal(t, uint32(0), nextCursor.EventIndex) + + // Second page: resume from cursor → [h=3, h=2] + collected2, _ := collectContractDeployments(t, idx, addr, name, 2, nextCursor, nil) + require.Len(t, collected2, 2) + + // Heights across both pages must be distinct and descending + allHeights := []uint64{ + collected1[0].BlockHeight, + collected1[1].BlockHeight, + collected2[0].BlockHeight, + collected2[1].BlockHeight, + } + assert.Equal(t, []uint64{5, 4, 3, 2}, allHeights) + }) + }) +} + +// ---------------------------------------------------------------------------- +// All +// ---------------------------------------------------------------------------- + +func TestContractDeployments_All(t *testing.T) { + t.Parallel() + + t.Run("empty index returns empty results", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + collected, nextCursor := collectAllContracts(t, idx, 10, nil, nil) + assert.Empty(t, collected) + assert.Nil(t, nextCursor) + }) + }) + + t.Run("returns latest per contract in ascending address/contract name order", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + dA1 := makeDeployment(addr, "AContract", 2, 0, 0) + dA2 := makeDeployment(addr, "AContract", 3, 0, 0) // later update + dB := makeDeployment(addr, "BContract", 2, 1, 0) + dC := makeDeployment(addr, "CContract", 2, 2, 0) + + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{dA1, dB, dC})) + require.NoError(t, storeContractDeployments(t, lm, idx, 3, []access.ContractDeployment{dA2})) + + collected, _ := collectAllContracts(t, idx, 10, nil, nil) + require.Len(t, collected, 3) + + // Ascending contractID order; contractA shows the most recent deployment (dA2) + assertDeployment(t, dA2, collected[0]) + assertDeployment(t, dB, collected[1]) + assertDeployment(t, dC, collected[2]) + }) + }) + + t.Run("has-more sets NextCursor pointing to first item of next page", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + dA := makeDeployment(addr, "AContract", 2, 0, 0) + dB := makeDeployment(addr, "BContract", 2, 1, 0) + dC := makeDeployment(addr, "CContract", 2, 2, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{dA, dB, dC})) + + // limit=2, 3 exist: returns [A, B], cursor → C (first of next page) + collected, nextCursor := collectAllContracts(t, idx, 2, nil, nil) + require.Len(t, collected, 2) + require.NotNil(t, nextCursor) + assert.Equal(t, dC.Address, nextCursor.Address) + assert.Equal(t, dC.ContractName, nextCursor.ContractName) + }) + }) + + t.Run("with cursor resumes from cursor position (inclusive)", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + dA := makeDeployment(addr, "AContract", 2, 0, 0) + dB := makeDeployment(addr, "BContract", 2, 1, 0) + dC := makeDeployment(addr, "CContract", 2, 2, 0) + dD := makeDeployment(addr, "DContract", 2, 3, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{dA, dB, dC, dD})) + + // First page: [A, B], cursor → C + collected1, nextCursor := collectAllContracts(t, idx, 2, nil, nil) + require.Len(t, collected1, 2) + require.NotNil(t, nextCursor) + + // Second page: resume from cursor → [C, D] + collected2, _ := collectAllContracts(t, idx, 2, nextCursor, nil) + require.Len(t, collected2, 2) + + names := []string{ + collected1[0].ContractName, + collected1[1].ContractName, + collected2[0].ContractName, + collected2[1].ContractName, + } + assert.Equal(t, []string{"AContract", "BContract", "CContract", "DContract"}, names) + }) + }) + + t.Run("filter applied to results", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + dA := makeDeployment(addr, "AContract", 2, 0, 0) + dB := makeDeployment(addr, "BContract", 2, 1, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{dA, dB})) + + // Filter that only accepts AContract + filter := func(d *access.ContractDeployment) bool { + return d.Address == dA.Address && d.ContractName == dA.ContractName + } + + collected, _ := collectAllContracts(t, idx, 10, nil, filter) + require.Len(t, collected, 1) + assertDeployment(t, dA, collected[0]) + }) + }) +} + +// ---------------------------------------------------------------------------- +// ByAddress +// ---------------------------------------------------------------------------- + +func TestContractDeployments_ByAddress(t *testing.T) { + t.Parallel() + + t.Run("returns only contracts for that address", func(t *testing.T) { + t.Parallel() + addr1 := unittest.RandomAddressFixture() + addr2 := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + dA := makeDeployment(addr1, "ContractA", 2, 0, 0) + dB := makeDeployment(addr1, "ContractB", 2, 1, 0) + dC := makeDeployment(addr2, "ContractC", 2, 2, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{dA, dB, dC})) + + // Query addr1 - should get ContractA and ContractB only + collected1, _ := collectContractsByAddress(t, idx, addr1, 10, nil, nil) + require.Len(t, collected1, 2) + for _, d := range collected1 { + assert.Equal(t, addr1, d.Address, "deployment %s should belong to addr1", d.ContractName) + } + + // Query addr2 - should get ContractC only + collected2, _ := collectContractsByAddress(t, idx, addr2, 10, nil, nil) + require.Len(t, collected2, 1) + assertDeployment(t, dC, collected2[0]) + }) + }) + + t.Run("returns empty when address has no contracts", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + addr := unittest.RandomAddressFixture() + collected, nextCursor := collectContractsByAddress(t, idx, addr, 10, nil, nil) + assert.Empty(t, collected) + assert.Nil(t, nextCursor) + }) + }) + + t.Run("has-more sets NextCursor pointing to first item of next page", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + dA := makeDeployment(addr, "ContractA", 2, 0, 0) + dB := makeDeployment(addr, "ContractB", 2, 1, 0) + dC := makeDeployment(addr, "ContractC", 2, 2, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{dA, dB, dC})) + + // limit=2, 3 exist: returns [A, B], cursor → C (first of next page) + collected, nextCursor := collectContractsByAddress(t, idx, addr, 2, nil, nil) + require.Len(t, collected, 2) + require.NotNil(t, nextCursor) + assert.Equal(t, dC.Address, nextCursor.Address) + assert.Equal(t, dC.ContractName, nextCursor.ContractName) + }) + }) + + t.Run("with cursor resumes from cursor position (inclusive)", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + dA := makeDeployment(addr, "ContractA", 2, 0, 0) + dB := makeDeployment(addr, "ContractB", 2, 1, 0) + dC := makeDeployment(addr, "ContractC", 2, 2, 0) + dD := makeDeployment(addr, "ContractD", 2, 3, 0) + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{dA, dB, dC, dD})) + + // First page: [A, B], cursor → C + collected1, nextCursor := collectContractsByAddress(t, idx, addr, 2, nil, nil) + require.Len(t, collected1, 2) + require.NotNil(t, nextCursor) + + // Second page: resume from cursor → [C, D] + collected2, _ := collectContractsByAddress(t, idx, addr, 2, nextCursor, nil) + require.Len(t, collected2, 2) + + names := []string{ + collected1[0].ContractName, + collected1[1].ContractName, + collected2[0].ContractName, + collected2[1].ContractName, + } + assert.Equal(t, []string{"ContractA", "ContractB", "ContractC", "ContractD"}, names) + }) + }) +} + +// ---------------------------------------------------------------------------- +// Store +// ---------------------------------------------------------------------------- + +func TestContractDeployments_Store(t *testing.T) { + t.Parallel() + + t.Run("stores consecutive heights successfully", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + d2 := makeDeployment(addr, "MyContract", 2, 0, 0) + d3 := makeDeployment(addr, "MyContract", 3, 0, 0) + + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d2})) + assert.Equal(t, uint64(2), idx.LatestIndexedHeight()) + + require.NoError(t, storeContractDeployments(t, lm, idx, 3, []access.ContractDeployment{d3})) + assert.Equal(t, uint64(3), idx.LatestIndexedHeight()) + }) + }) + + t.Run("duplicate height returns ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, nil)) + + err := storeContractDeployments(t, lm, idx, 2, nil) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("non-consecutive height returns error", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + err := storeContractDeployments(t, lm, idx, 5, nil) + require.Error(t, err) + assert.NotErrorIs(t, err, storage.ErrAlreadyExists, + "non-consecutive height should not return ErrAlreadyExists") + }) + }) + + t.Run("empty contract name in batch returns error", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + bad := access.ContractDeployment{ + Address: unittest.RandomAddressFixture(), + ContractName: "", + BlockHeight: 2, + } + err := storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{bad}) + require.Error(t, err) + }) + }) + + t.Run("contract name containing dot in batch returns error", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + bad := access.ContractDeployment{ + Address: unittest.RandomAddressFixture(), + ContractName: "My.Contract", + BlockHeight: 2, + } + err := storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{bad}) + require.Error(t, err) + }) + }) + + t.Run("store without lock returns error", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + lctx := lm.NewContext() + defer lctx.Release() + + // lctx does not hold the required lock + err := db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, 2, nil) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) + + t.Run("uncommitted batch does not advance latestHeight", func(t *testing.T) { + t.Parallel() + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(db storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.Equal(t, uint64(1), idx.LatestIndexedHeight()) + + batch := db.NewBatch() + err := unittest.WithLock(t, lm, storage.LockIndexContractDeployments, func(lctx lockctx.Context) error { + return idx.Store(lctx, batch, 2, nil) + }) + require.NoError(t, err) + + // Close without committing + require.NoError(t, batch.Close()) + + assert.Equal(t, uint64(1), idx.LatestIndexedHeight(), + "latestHeight must not advance when batch is not committed") + }) + }) +} + +// ---------------------------------------------------------------------------- +// IsDeleted +// ---------------------------------------------------------------------------- + +func TestContractDeployments_IsDeleted(t *testing.T) { + t.Parallel() + + addr := unittest.RandomAddressFixture() + name := "MyContract" + + t.Run("IsDeleted=true is persisted and returned by ByContract", func(t *testing.T) { + t.Parallel() + d := makeDeployment(addr, name, 2, 0, 0) + d.IsDeleted = true + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d})) + + result, err := idx.ByContract(d.Address, d.ContractName) + require.NoError(t, err) + assertDeployment(t, d, result) + }) + }) + + t.Run("IsDeleted=false is persisted and returned by ByContract", func(t *testing.T) { + t.Parallel() + d := makeDeployment(addr, name, 2, 0, 0) + d.IsDeleted = false + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d})) + + result, err := idx.ByContract(d.Address, d.ContractName) + require.NoError(t, err) + assertDeployment(t, d, result) + }) + }) + + t.Run("ByContract returns deleted deployment as most recent", func(t *testing.T) { + t.Parallel() + d1 := makeDeployment(addr, name, 2, 0, 0) // initial deploy + d2 := makeDeployment(addr, name, 3, 0, 0) // deletion + d2.IsDeleted = true + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d1})) + require.NoError(t, storeContractDeployments(t, lm, idx, 3, []access.ContractDeployment{d2})) + + result, err := idx.ByContract(d2.Address, d2.ContractName) + require.NoError(t, err) + assertDeployment(t, d2, result) + }) + }) + + t.Run("IsDeleted is preserved across deploy-delete-redeploy sequence", func(t *testing.T) { + t.Parallel() + d1 := makeDeployment(addr, name, 2, 0, 0) // initial deploy + d2 := makeDeployment(addr, name, 3, 0, 0) // deletion + d2.IsDeleted = true + d3 := makeDeployment(addr, name, 4, 0, 0) // redeploy + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d1})) + require.NoError(t, storeContractDeployments(t, lm, idx, 3, []access.ContractDeployment{d2})) + require.NoError(t, storeContractDeployments(t, lm, idx, 4, []access.ContractDeployment{d3})) + + // Most recent is the redeploy at h=4, not deleted + result, err := idx.ByContract(d3.Address, d3.ContractName) + require.NoError(t, err) + assertDeployment(t, d3, result) + + // Full history shows the deletion at h=3 + collected, _ := collectContractDeployments(t, idx, addr, name, 10, nil, nil) + require.Len(t, collected, 3) + assertDeployment(t, d3, collected[0]) // h=4 + assertDeployment(t, d2, collected[1]) // h=3 (deleted) + assertDeployment(t, d1, collected[2]) // h=2 + }) + }) + + t.Run("IsDeleted=true persisted in bootstrap deployments", func(t *testing.T) { + t.Parallel() + d := makeDeployment(addr, name, 5, 0, 0) + d.IsDeleted = true + + RunWithBootstrappedContractDeploymentsIndex(t, 5, []access.ContractDeployment{d}, func(_ storage.DB, _ storage.LockManager, idx *ContractDeploymentsIndex) { + result, err := idx.ByContract(d.Address, d.ContractName) + require.NoError(t, err) + assertDeployment(t, d, result) + }) + }) + + t.Run("All returns deleted deployments (filtering is at backend layer)", func(t *testing.T) { + t.Parallel() + d := makeDeployment(addr, name, 2, 0, 0) + d.IsDeleted = true + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d})) + + collected, _ := collectAllContracts(t, idx, 10, nil, nil) + require.Len(t, collected, 1) + assertDeployment(t, d, collected[0]) + }) + }) + + t.Run("ByAddress returns deleted deployments (filtering is at backend layer)", func(t *testing.T) { + t.Parallel() + d := makeDeployment(addr, name, 2, 0, 0) + d.IsDeleted = true + + RunWithBootstrappedContractDeploymentsIndex(t, 1, nil, func(_ storage.DB, lm storage.LockManager, idx *ContractDeploymentsIndex) { + require.NoError(t, storeContractDeployments(t, lm, idx, 2, []access.ContractDeployment{d})) + + collected, _ := collectContractsByAddress(t, idx, d.Address, 10, nil, nil) + require.Len(t, collected, 1) + assertDeployment(t, d, collected[0]) + }) + }) +} + +// ---------------------------------------------------------------------------- +// Key codec +// ---------------------------------------------------------------------------- + +func TestContractDeployments_KeyCodec(t *testing.T) { + t.Parallel() + + t.Run("roundtrip: makeContractDeploymentKey then decodeDeploymentCursor", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + name := "MyContract" + height := uint64(12345) + txIndex := uint32(42) + eventIndex := uint32(7) + + key := makeContractDeploymentKey(addr, name, height, txIndex, eventIndex) + cursor, err := decodeDeploymentCursor(key) + require.NoError(t, err) + assert.Equal(t, addr, cursor.Address) + assert.Equal(t, name, cursor.ContractName) + assert.Equal(t, height, cursor.BlockHeight) + assert.Equal(t, txIndex, cursor.TransactionIndex) + assert.Equal(t, eventIndex, cursor.EventIndex) + }) + + t.Run("ones complement ensures descending height order", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + name := "MyContract" + + keyLow := makeContractDeploymentKey(addr, name, 100, 0, 0) + keyHigh := makeContractDeploymentKey(addr, name, 200, 0, 0) + + // Higher height => smaller key (descending iteration) + assert.True(t, string(keyHigh) < string(keyLow), + "key for higher height should sort before key for lower height") + }) + + t.Run("malformed key too short returns error", func(t *testing.T) { + t.Parallel() + _, err := decodeDeploymentCursor(make([]byte, 5)) + require.Error(t, err) + }) + + t.Run("malformed key with wrong prefix byte returns error", func(t *testing.T) { + t.Parallel() + addr := unittest.RandomAddressFixture() + key := makeContractDeploymentKey(addr, "MyContract", 1, 0, 0) + key[0] = 0xFF + _, err := decodeDeploymentCursor(key) + require.Error(t, err) + }) +} diff --git a/storage/indexes/helpers.go b/storage/indexes/helpers.go new file mode 100644 index 00000000000..2375ef4aa00 --- /dev/null +++ b/storage/indexes/helpers.go @@ -0,0 +1,43 @@ +package indexes + +import ( + "fmt" + + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation" +) + +const ( + heightLen = 8 // length of uint64 in bytes + txIndexLen = 4 // length of uint32 in bytes + eventIndexLen = 4 // length of uint32 in bytes +) + +// validateCursorHeight validates the block height for the cursor is within the valid range (firstHeight, latestHeight) +// +// Expected error returns during normal operations: +// - [storage.ErrHeightNotIndexed] if the block height is outside of the indexed range +func validateCursorHeight(blockHeight uint64, firstHeight uint64, latestHeight uint64) error { + if blockHeight > latestHeight { + return fmt.Errorf("cursor height %d is greater than latest indexed height %d: %w", + blockHeight, latestHeight, storage.ErrHeightNotIndexed) + } + + if blockHeight < firstHeight { + return fmt.Errorf("cursor height %d is before first indexed height %d: %w", + blockHeight, firstHeight, storage.ErrHeightNotIndexed) + } + return nil +} + +// readHeight reads a height value from the database. +// +// Expected error returns during normal operations: +// - [storage.ErrNotFound] if the height is not found +func readHeight(reader storage.Reader, key []byte) (uint64, error) { + var height uint64 + if err := operation.RetrieveByKey(reader, key, &height); err != nil { + return 0, err + } + return height, nil +} diff --git a/storage/indexes/iterator/collector.go b/storage/indexes/iterator/collector.go new file mode 100644 index 00000000000..5345774093d --- /dev/null +++ b/storage/indexes/iterator/collector.go @@ -0,0 +1,45 @@ +package iterator + +import ( + "fmt" + + "github.com/onflow/flow-go/storage" +) + +// CollectResults iterates over the storage iterator and collects results that match the filter. +// It returns when it reaches the limit or the iterator is exhausted. +// Returns the results matching the filter and the next cursor. +// A nil filter accepts all entries. +// +// No error returns are expected during normal operation. +func CollectResults[T any, C any](iter storage.IndexIterator[T, C], limit uint32, filter storage.IndexFilter[*T]) ([]T, *C, error) { + if limit == 0 { + return nil, nil, nil // no results to collect + } + + var collected []T + for item, err := range iter { + if err != nil { + return nil, nil, fmt.Errorf("could not get item: %w", err) + } + + // stop once we've collected `limit` results + // go one extra iteration to check if there are more results and build the next cursor + // if there is no extra item, then the cursor will be nil + if uint32(len(collected)) >= limit { + nextItem := item + nextCursor := nextItem.Cursor() + return collected, &nextCursor, nil + } + + tx, err := item.Value() + if err != nil { + return nil, nil, fmt.Errorf("could not get transaction: %w", err) + } + if filter != nil && !filter(&tx) { + continue + } + collected = append(collected, tx) + } + return collected, nil, nil +} diff --git a/storage/indexes/iterator/collector_test.go b/storage/indexes/iterator/collector_test.go new file mode 100644 index 00000000000..e3eda69729f --- /dev/null +++ b/storage/indexes/iterator/collector_test.go @@ -0,0 +1,146 @@ +package iterator_test + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" +) + +// testEntry is a simple IteratorEntry implementation for testing. +type testEntry struct { + value string + cursor int +} + +func (e testEntry) Cursor() int { return e.cursor } +func (e testEntry) Value() (string, error) { return e.value, nil } + +// errEntry is an IteratorEntry whose Value always returns an error. +type errEntry struct{ err error } + +func (e errEntry) Cursor() int { return 0 } +func (e errEntry) Value() (string, error) { return "", e.err } + +func newIter(entries ...storage.IteratorEntry[string, int]) storage.IndexIterator[string, int] { + return func(yield func(storage.IteratorEntry[string, int], error) bool) { + for _, e := range entries { + if !yield(e, nil) { + return + } + } + } +} + +func newErrIter(err error) storage.IndexIterator[string, int] { + return func(yield func(storage.IteratorEntry[string, int], error) bool) { + yield(nil, err) + } +} + +func TestCollectResults(t *testing.T) { + t.Parallel() + + t.Run("limit zero returns immediately with no results", func(t *testing.T) { + iter := newIter(testEntry{value: "a", cursor: 1}) + + results, cursor, err := iterator.CollectResults(iter, 0, nil) + require.NoError(t, err) + assert.Nil(t, results) + assert.Nil(t, cursor) + }) + + t.Run("fewer results than limit returns all with nil cursor", func(t *testing.T) { + iter := newIter( + testEntry{value: "a", cursor: 1}, + testEntry{value: "b", cursor: 2}, + ) + + results, cursor, err := iterator.CollectResults(iter, 10, nil) + require.NoError(t, err) + assert.Equal(t, []string{"a", "b"}, results) + assert.Nil(t, cursor) + }) + + t.Run("exactly limit results returns all with nil cursor", func(t *testing.T) { + iter := newIter( + testEntry{value: "a", cursor: 1}, + testEntry{value: "b", cursor: 2}, + ) + + results, cursor, err := iterator.CollectResults(iter, 2, nil) + require.NoError(t, err) + assert.Equal(t, []string{"a", "b"}, results) + assert.Nil(t, cursor) + }) + + t.Run("more results than limit returns limit results and next cursor", func(t *testing.T) { + iter := newIter( + testEntry{value: "a", cursor: 1}, + testEntry{value: "b", cursor: 2}, + testEntry{value: "c", cursor: 3}, + ) + + results, nextCursor, err := iterator.CollectResults(iter, 2, nil) + require.NoError(t, err) + require.Equal(t, []string{"a", "b"}, results) + require.NotNil(t, nextCursor) + assert.Equal(t, 3, *nextCursor) + }) + + t.Run("nil filter passes all items", func(t *testing.T) { + iter := newIter( + testEntry{value: "a", cursor: 1}, + testEntry{value: "b", cursor: 2}, + ) + + results, _, err := iterator.CollectResults(iter, 10, nil) + require.NoError(t, err) + assert.Equal(t, []string{"a", "b"}, results) + }) + + t.Run("filter rejects non-matching items", func(t *testing.T) { + iter := newIter( + testEntry{value: "keep", cursor: 1}, + testEntry{value: "skip", cursor: 2}, + testEntry{value: "keep", cursor: 3}, + ) + filter := func(v *string) bool { return *v == "keep" } + + results, cursor, err := iterator.CollectResults(iter, 10, filter) + require.NoError(t, err) + assert.Equal(t, []string{"keep", "keep"}, results) + assert.Nil(t, cursor) + }) + + t.Run("error from iterator yield propagates", func(t *testing.T) { + iterErr := errors.New("iterator error") + iter := newErrIter(iterErr) + + _, _, err := iterator.CollectResults(iter, 10, nil) + require.Error(t, err) + assert.ErrorIs(t, err, iterErr) + }) + + t.Run("error from Value propagates", func(t *testing.T) { + valErr := errors.New("value error") + iter := newIter(errEntry{err: valErr}) + + _, _, err := iterator.CollectResults(iter, 10, nil) + require.Error(t, err) + assert.ErrorIs(t, err, valErr) + }) + + t.Run("empty iterator returns nil results and nil cursor", func(t *testing.T) { + iter := newIter() + + results, cursor, err := iterator.CollectResults(iter, 10, nil) + require.NoError(t, err) + assert.Nil(t, results) + assert.Nil(t, cursor) + }) +} diff --git a/storage/indexes/iterator/entry.go b/storage/indexes/iterator/entry.go new file mode 100644 index 00000000000..d9e15525b87 --- /dev/null +++ b/storage/indexes/iterator/entry.go @@ -0,0 +1,31 @@ +package iterator + +// Entry is a single stored entry returned by an index iterator. +type Entry[T any, C any] struct { + cursor C + getValue func(C) (*T, error) +} + +func NewEntry[T any, C any](cursor C, getValue func(C) (*T, error)) Entry[T, C] { + return Entry[T, C]{ + cursor: cursor, + getValue: getValue, + } +} + +// Cursor returns the cursor for the entry, which includes all data included in the storage key. +func (i Entry[T, C]) Cursor() C { + return i.cursor +} + +// Value returns the fully reconstructed value for the entry. +// +// Any error indicates the value cannot be reconstructed from the storage value. +func (i Entry[T, C]) Value() (T, error) { + v, err := i.getValue(i.cursor) + if err != nil { + var zero T + return zero, err + } + return *v, nil +} diff --git a/storage/indexes/iterator/iterator.go b/storage/indexes/iterator/iterator.go new file mode 100644 index 00000000000..5cdd9a52342 --- /dev/null +++ b/storage/indexes/iterator/iterator.go @@ -0,0 +1,121 @@ +package iterator + +import ( + "bytes" + + "github.com/onflow/flow-go/storage" +) + +// Build creates a new index iterator from a storage iterator. +// The returned iterator is a iter.Seq and can be used directly in for loops: +// +// for entry, err := range Build(iter, decodeKey, reconstruct) { +// if err != nil { +// return err +// } +// value, err := entry.Value() +// if err != nil { +// return err +// } +// // use value +// } +func Build[T any, C any](iter storage.Iterator, decodeKey storage.DecodeKeyFunc[C], reconstruct storage.ReconstructFunc[T, C]) storage.IndexIterator[T, C] { + return func(yield func(storage.IteratorEntry[T, C], error) bool) { + defer iter.Close() + for iter.First(); iter.Valid(); iter.Next() { + storageItem := iter.IterItem() + key := storageItem.KeyCopy(nil) + + cursor, err := decodeKey(key) + if err != nil { + if !yield(nil, err) { + return + } + // in practice, the caller is most likely going to break from the loop if there's an error + // continue here since that is the intuitive behavior. + continue + } + + getValue := func(decodedKey C) (*T, error) { + var result *T + err := storageItem.Value(func(val []byte) error { + var err error + result, err = reconstruct(decodedKey, val) + return err + }) + return result, err + } + + entry := NewEntry(cursor, getValue) + if !yield(entry, nil) { + return + } + } + } +} + +// BuildPrefixIterator creates a new index iterator from a storage iterator, yielding only the +// first entry per group. Two consecutive keys belong to the same group when keyPrefix +// returns equal byte slices for both. Since the iterator is assumed to be ordered with +// groups contiguous and the desired entry first within each group, this yields exactly +// one entry per group. +func BuildPrefixIterator[T any, C any]( + iter storage.Iterator, + decodeKey storage.DecodeKeyFunc[C], + reconstruct storage.ReconstructFunc[T, C], + keyPrefix func(key []byte) ([]byte, error), // must not modify the input slice. returned slice will also not be modifed +) storage.IndexIterator[T, C] { + return func(yield func(storage.IteratorEntry[T, C], error) bool) { + defer iter.Close() + var lastPrefix []byte + for iter.First(); iter.Valid(); iter.Next() { + storageItem := iter.IterItem() + key := storageItem.Key() + + prefix, err := keyPrefix(key) + if err != nil { + if !yield(nil, err) { + return + } + // in practice, the caller is most likely going to break from the loop if there's an error + // continue here since that is the intuitive behavior. + continue + } + + if bytes.Equal(prefix, lastPrefix) { + continue + } + + // make a copy since iter will reuse the same memory for the next key + lastPrefix = append(lastPrefix[:0], prefix...) + + keyCopy := make([]byte, len(key)) + copy(keyCopy, key) + + cursor, err := decodeKey(keyCopy) + if err != nil { + if !yield(nil, err) { + return + } + // in practice, the caller is most likely going to break from the loop if there's an error + // continue here since that is the intuitive behavior. + continue + } + + getValue := func(decodedKey C) (*T, error) { + var result *T + err := storageItem.Value(func(val []byte) error { + var err error + result, err = reconstruct(decodedKey, val) + return err + }) + return result, err + } + + entry := NewEntry(cursor, getValue) + if !yield(entry, nil) { + return + } + } + } +} diff --git a/storage/indexes/iterator/iterator_test.go b/storage/indexes/iterator/iterator_test.go new file mode 100644 index 00000000000..275c5cc2438 --- /dev/null +++ b/storage/indexes/iterator/iterator_test.go @@ -0,0 +1,281 @@ +package iterator_test + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" +) + +// memItem implements [storage.IterItem] for testing. +type memItem struct { + key []byte + val []byte +} + +func (m *memItem) Key() []byte { return m.key } +func (m *memItem) KeyCopy(dst []byte) []byte { return append(dst[:0], m.key...) } +func (m *memItem) Value(fn func([]byte) error) error { return fn(m.val) } + +// memIterator implements [storage.Iterator] backed by an in-memory slice. +type memIterator struct { + items []*memItem + idx int +} + +func newMemIterator(items ...*memItem) *memIterator { + return &memIterator{items: items, idx: -1} +} + +func (m *memIterator) First() bool { + m.idx = 0 + return m.Valid() +} + +func (m *memIterator) Valid() bool { return m.idx >= 0 && m.idx < len(m.items) } + +func (m *memIterator) Next() { m.idx++ } + +func (m *memIterator) IterItem() storage.IterItem { + if !m.Valid() { + return nil + } + return m.items[m.idx] +} + +func (m *memIterator) Close() error { return nil } + +// decodeStringKey interprets the key as a string cursor. +func decodeStringKey(key []byte) (string, error) { + return string(key), nil +} + +// reconstructString builds a string value from cursor and raw bytes. +func reconstructString(_ string, val []byte) (*string, error) { + s := string(val) + return &s, nil +} + +func TestBuild(t *testing.T) { + t.Parallel() + + t.Run("iterates all entries", func(t *testing.T) { + iter := newMemIterator( + &memItem{key: []byte("k1"), val: []byte("v1")}, + &memItem{key: []byte("k2"), val: []byte("v2")}, + &memItem{key: []byte("k3"), val: []byte("v3")}, + ) + + var results []string + for entry, err := range iterator.Build(iter, decodeStringKey, reconstructString) { + require.NoError(t, err) + val, err := entry.Value() + require.NoError(t, err) + results = append(results, val) + } + assert.Equal(t, []string{"v1", "v2", "v3"}, results) + }) + + t.Run("empty iterator yields nothing", func(t *testing.T) { + iter := newMemIterator() + + var count int + for _, err := range iterator.Build(iter, decodeStringKey, reconstructString) { + require.NoError(t, err) + count++ + } + assert.Zero(t, count) + }) + + t.Run("decodeKey error is yielded", func(t *testing.T) { + decodeErr := errors.New("decode error") + failDecode := func([]byte) (string, error) { return "", decodeErr } + + iter := newMemIterator( + &memItem{key: []byte("k1"), val: []byte("v1")}, + ) + + for _, err := range iterator.Build(iter, failDecode, reconstructString) { + require.ErrorIs(t, err, decodeErr) + break + } + }) + + t.Run("reconstruct error is surfaced via Value", func(t *testing.T) { + reconstructErr := errors.New("reconstruct error") + failReconstruct := func(string, []byte) (*string, error) { return nil, reconstructErr } + + iter := newMemIterator( + &memItem{key: []byte("k1"), val: []byte("v1")}, + ) + + for entry, err := range iterator.Build(iter, decodeStringKey, failReconstruct) { + require.NoError(t, err) + _, err = entry.Value() + require.ErrorIs(t, err, reconstructErr) + break + } + }) +} + +func TestBuildPrefixIterator(t *testing.T) { + t.Parallel() + + // keyPrefix returns the first 2 bytes as the group prefix. + keyPrefix := func(key []byte) ([]byte, error) { + if len(key) < 2 { + return nil, fmt.Errorf("key too short: %d", len(key)) + } + return key[:2], nil + } + + t.Run("deduplicates consecutive entries with same prefix", func(t *testing.T) { + // Keys share prefix "aa" — only first should be yielded + iter := newMemIterator( + &memItem{key: []byte("aa1"), val: []byte("first")}, + &memItem{key: []byte("aa2"), val: []byte("second")}, + &memItem{key: []byte("aa3"), val: []byte("third")}, + ) + + var results []string + for entry, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, reconstructString, keyPrefix) { + require.NoError(t, err) + val, err := entry.Value() + require.NoError(t, err) + results = append(results, val) + } + assert.Equal(t, []string{"first"}, results) + }) + + t.Run("yields one entry per distinct prefix group", func(t *testing.T) { + iter := newMemIterator( + &memItem{key: []byte("aa1"), val: []byte("a-first")}, + &memItem{key: []byte("aa2"), val: []byte("a-second")}, + &memItem{key: []byte("bb1"), val: []byte("b-first")}, + &memItem{key: []byte("bb2"), val: []byte("b-second")}, + &memItem{key: []byte("cc1"), val: []byte("c-first")}, + ) + + var results []string + for entry, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, reconstructString, keyPrefix) { + require.NoError(t, err) + val, err := entry.Value() + require.NoError(t, err) + results = append(results, val) + } + assert.Equal(t, []string{"a-first", "b-first", "c-first"}, results) + }) + + t.Run("empty iterator yields nothing", func(t *testing.T) { + iter := newMemIterator() + + var count int + for _, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, reconstructString, keyPrefix) { + require.NoError(t, err) + count++ + } + assert.Zero(t, count) + }) + + t.Run("single entry is yielded", func(t *testing.T) { + iter := newMemIterator( + &memItem{key: []byte("aa1"), val: []byte("only")}, + ) + + var results []string + for entry, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, reconstructString, keyPrefix) { + require.NoError(t, err) + val, err := entry.Value() + require.NoError(t, err) + results = append(results, val) + } + assert.Equal(t, []string{"only"}, results) + }) + + t.Run("keyPrefix error is yielded", func(t *testing.T) { + // key with only 1 byte triggers the "key too short" error + iter := newMemIterator( + &memItem{key: []byte("x"), val: []byte("val")}, + ) + + for _, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, reconstructString, keyPrefix) { + require.Error(t, err) + assert.Contains(t, err.Error(), "key too short") + break + } + }) + + t.Run("keyPrefix error on second entry still yields first", func(t *testing.T) { + iter := newMemIterator( + &memItem{key: []byte("aa1"), val: []byte("good")}, + &memItem{key: []byte("x"), val: []byte("bad")}, // triggers keyPrefix error + ) + + var results []string + var gotErr error + for entry, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, reconstructString, keyPrefix) { + if err != nil { + gotErr = err + break + } + val, err := entry.Value() + require.NoError(t, err) + results = append(results, val) + } + assert.Equal(t, []string{"good"}, results) + require.Error(t, gotErr) + }) + + t.Run("decodeKey error is yielded", func(t *testing.T) { + decodeErr := errors.New("decode error") + failDecode := func([]byte) (string, error) { return "", decodeErr } + + iter := newMemIterator( + &memItem{key: []byte("aa1"), val: []byte("v1")}, + ) + + for _, err := range iterator.BuildPrefixIterator(iter, failDecode, reconstructString, keyPrefix) { + require.ErrorIs(t, err, decodeErr) + break + } + }) + + t.Run("reconstruct error is surfaced via Value", func(t *testing.T) { + reconstructErr := errors.New("reconstruct error") + failReconstruct := func(string, []byte) (*string, error) { return nil, reconstructErr } + + iter := newMemIterator( + &memItem{key: []byte("aa1"), val: []byte("v1")}, + ) + + for entry, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, failReconstruct, keyPrefix) { + require.NoError(t, err) + _, err = entry.Value() + require.ErrorIs(t, err, reconstructErr) + break + } + }) + + t.Run("early break stops iteration", func(t *testing.T) { + iter := newMemIterator( + &memItem{key: []byte("aa1"), val: []byte("first")}, + &memItem{key: []byte("bb1"), val: []byte("second")}, + &memItem{key: []byte("cc1"), val: []byte("third")}, + ) + + var results []string + for entry, err := range iterator.BuildPrefixIterator(iter, decodeStringKey, reconstructString, keyPrefix) { + require.NoError(t, err) + val, err := entry.Value() + require.NoError(t, err) + results = append(results, val) + break // stop after first + } + assert.Equal(t, []string{"first"}, results) + }) +} diff --git a/storage/indexes/prefix.go b/storage/indexes/prefix.go new file mode 100644 index 00000000000..45d1f0d3a64 --- /dev/null +++ b/storage/indexes/prefix.go @@ -0,0 +1,47 @@ +package indexes + +const ( + // codeIndexProcessedHeightLowerBound is the prefix for indexer's lower bound of processed heights + // the second byte is the indexer's prefix code. + // Example: prefix [8][10] means this entry is the lowest processed height for the type with code 10. + codeIndexProcessedHeightLowerBound byte = 8 + // codeIndexProcessedHeightUpperBound is the prefix for indexer's upper bound of processed heights + // the second byte is the indexer's prefix code. + // Example: prefix [9][10] means this entry is the highest processed height for the type with code 10. + codeIndexProcessedHeightUpperBound byte = 9 + + // Account indexes + codeAccountTransactions byte = 10 // Account transactions index + codeAccountFungibleTokenTransfers byte = 11 // Account fungible token transfers index + codeAccountNonFungibleTokenTransfers byte = 12 // Account non-fungible token transfers index + codeScheduledTransaction byte = 13 // Scheduled transaction index + codeScheduledTransactionByAddress byte = 14 // Scheduled transaction by address + codeContractDeployment byte = 15 // Contract deployment index (full history) + + // reserved as extension byte for future use + _ byte = 255 +) + +// Indexer Processed Heights Keys +// these are the currently supported indexers' upper and lower bound height keys +var ( + // Upper and lower bound keys for account transactions + keyAccountTransactionLatestHeightKey = []byte{codeIndexProcessedHeightUpperBound, codeAccountTransactions} + keyAccountTransactionFirstHeightKey = []byte{codeIndexProcessedHeightLowerBound, codeAccountTransactions} + + // Upper and lower bound keys for account fungible token transfers + keyAccountFTTransferLatestHeightKey = []byte{codeIndexProcessedHeightUpperBound, codeAccountFungibleTokenTransfers} + keyAccountFTTransferFirstHeightKey = []byte{codeIndexProcessedHeightLowerBound, codeAccountFungibleTokenTransfers} + + // Upper and lower bound keys for account non-fungible token transfers + keyAccountNFTTransferLatestHeightKey = []byte{codeIndexProcessedHeightUpperBound, codeAccountNonFungibleTokenTransfers} + keyAccountNFTTransferFirstHeightKey = []byte{codeIndexProcessedHeightLowerBound, codeAccountNonFungibleTokenTransfers} + + // Upper and lower bound keys for scheduled transactions + keyScheduledTxLatestHeightKey = []byte{codeIndexProcessedHeightUpperBound, codeScheduledTransaction} + keyScheduledTxFirstHeightKey = []byte{codeIndexProcessedHeightLowerBound, codeScheduledTransaction} + + // Upper and lower bound keys for contract deployments + keyContractDeploymentLatestHeightKey = []byte{codeIndexProcessedHeightUpperBound, codeContractDeployment} + keyContractDeploymentFirstHeightKey = []byte{codeIndexProcessedHeightLowerBound, codeContractDeployment} +) diff --git a/storage/indexes/scheduled_transactions.go b/storage/indexes/scheduled_transactions.go new file mode 100644 index 00000000000..e6ac06f3ca4 --- /dev/null +++ b/storage/indexes/scheduled_transactions.go @@ -0,0 +1,418 @@ +package indexes + +import ( + "encoding/binary" + "fmt" + "math" + + "github.com/jordanschalm/lockctx" + "github.com/vmihailenco/msgpack/v4" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation" + "github.com/onflow/flow-go/utils/visited" +) + +const ( + // idLen is the length of the uint64 ID in bytes + idLen = 8 + // scheduledTxPrimaryKeyLen is [code(1)][~id(8)] = 9 bytes + scheduledTxPrimaryKeyLen = 1 + idLen + // scheduledTxByAddrKeyLen is [code(1)][address(8)][~id(8)] = 17 bytes + scheduledTxByAddrKeyLen = 1 + flow.AddressLength + idLen +) + +// ScheduledTransactionsIndex implements [storage.ScheduledTransactionsIndex] using Pebble. +// +// Primary key format: [codeScheduledTransaction][~id] → ScheduledTransaction value +// By-address key format: [codeScheduledTransactionByAddress][addr][~id] → nil (key-only) +// +// One's complement of id (~id) gives descending iteration order in ascending byte space. +// +// All read methods are safe for concurrent access. Write methods must be called sequentially. +type ScheduledTransactionsIndex struct { + *IndexState +} + +var _ storage.ScheduledTransactionsIndex = (*ScheduledTransactionsIndex)(nil) + +// NewScheduledTransactionsIndex creates a new index backed by db. +// +// Expected error returns during normal operation: +// - [storage.ErrNotBootstrapped]: if the index has not been initialized +func NewScheduledTransactionsIndex(db storage.DB) (*ScheduledTransactionsIndex, error) { + state, err := NewIndexState( + db, + storage.LockIndexScheduledTransactionsIndex, + keyScheduledTxFirstHeightKey, + keyScheduledTxLatestHeightKey, + ) + if err != nil { + return nil, fmt.Errorf("could not create index state: %w", err) + } + return &ScheduledTransactionsIndex{IndexState: state}, nil +} + +// BootstrapScheduledTransactions initializes the index with the given start height and initial +// scheduled transactions, and returns a new [ScheduledTransactionsIndex]. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until the batch +// is committed. +// +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists]: if any bounds key already exists +func BootstrapScheduledTransactions( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + db storage.DB, + initialStartHeight uint64, + scheduledTxs []access.ScheduledTransaction, +) (*ScheduledTransactionsIndex, error) { + state, err := BootstrapIndexState( + lctx, + rw, + db, + storage.LockIndexScheduledTransactionsIndex, + keyScheduledTxFirstHeightKey, + keyScheduledTxLatestHeightKey, + initialStartHeight, + ) + if err != nil { + return nil, fmt.Errorf("could not bootstrap scheduled transactions: %w", err) + } + + if err := storeAllScheduledTransactions(rw, scheduledTxs); err != nil { + return nil, fmt.Errorf("could not store scheduled transactions: %w", err) + } + + return &ScheduledTransactionsIndex{IndexState: state}, nil +} + +// ByID returns the scheduled transaction with the given ID. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if no scheduled transaction with the given ID exists +func (idx *ScheduledTransactionsIndex) ByID(id uint64) (access.ScheduledTransaction, error) { + var tx access.ScheduledTransaction + if err := operation.RetrieveByKey(idx.db.Reader(), makeScheduledTxPrimaryKey(id), &tx); err != nil { + return access.ScheduledTransaction{}, fmt.Errorf("could not retrieve scheduled transaction %d: %w", id, err) + } + return tx, nil +} + +// All returns an iterator over all scheduled transactions in descending ID order. +// Returns an exhausted iterator and no error if no transactions exist. +// +// `cursor` is a pointer to an [access.ScheduledTransactionCursor]: +// - nil means start from the highest indexed ID +// - non-nil means start at the cursor ID (inclusive) +// +// No error returns are expected during normal operation. +func (idx *ScheduledTransactionsIndex) All( + cursor *access.ScheduledTransactionCursor, +) (storage.ScheduledTransactionIterator, error) { + startKey, endKey := idx.rangeKeysAll(cursor) + + reader := idx.db.Reader() + iter, err := reader.NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator: %w", err) + } + + return iterator.Build(iter, decodeScheduledTxCursor, reconstructScheduledTx), nil +} + +// ByAddress returns an iterator over scheduled transactions for the given account in +// descending ID order. Returns an exhausted iterator and no error if the account has no +// transactions. +// +// `cursor` is a pointer to an [access.ScheduledTransactionCursor]: +// - nil means start from the highest indexed ID +// - non-nil means start at the cursor ID (inclusive) +// +// No error returns are expected during normal operation. +func (idx *ScheduledTransactionsIndex) ByAddress( + account flow.Address, + cursor *access.ScheduledTransactionCursor, +) (storage.ScheduledTransactionIterator, error) { + startKey, endKey := idx.rangeKeysAddress(account, cursor) + + reader := idx.db.Reader() + iter, err := reader.NewIter(startKey, endKey, storage.DefaultIteratorOptions()) + if err != nil { + return nil, fmt.Errorf("could not create iterator: %w", err) + } + + // The by-address index is key-only (nil values). The getValue closure performs + // a secondary lookup into the primary index using the decoded cursor's ID. + getValue := func(cur access.ScheduledTransactionCursor, _ []byte) (*access.ScheduledTransaction, error) { + var tx access.ScheduledTransaction + if err := operation.RetrieveByKey(reader, makeScheduledTxPrimaryKey(cur.ID), &tx); err != nil { + return nil, err + } + return &tx, nil + } + + return iterator.Build(iter, decodeScheduledTxByAddrCursor, getValue), nil +} + +// rangeKeysAll computes the start and end keys for iterating over all scheduled transactions based +// on the provided cursor. +func (idx *ScheduledTransactionsIndex) rangeKeysAll(cursor *access.ScheduledTransactionCursor) (startKey, endKey []byte) { + if cursor == nil { + // keys include the one's complement of the ID, so iteration is in descending order of ids. + startKey = makeScheduledTxPrimaryKey(math.MaxUint64) + endKey = makeScheduledTxPrimaryKey(0) + return startKey, endKey + } + + startKey = makeScheduledTxPrimaryKey(cursor.ID) + endKey = makeScheduledTxPrimaryKey(0) + return startKey, endKey +} + +// rangeKeysAddress computes the start and end keys for iterating over scheduled transactions of an +// account, based on the provided cursor. +func (idx *ScheduledTransactionsIndex) rangeKeysAddress(address flow.Address, cursor *access.ScheduledTransactionCursor) (startKey, endKey []byte) { + if cursor == nil { + // keys include the one's complement of the ID, so iteration is in descending order of ids. + startKey := makeScheduledTxByAddrKey(address, math.MaxUint64) + endKey := makeScheduledTxByAddrKey(address, 0) + return startKey, endKey + } + + startKey = makeScheduledTxByAddrKey(address, cursor.ID) + endKey = makeScheduledTxByAddrKey(address, 0) + return startKey, endKey +} + +// Store indexes new scheduled transactions from the block and advances the latest indexed height. +// Must be called with consecutive block heights. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until committed. +// +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists]: if blockHeight is already indexed +func (idx *ScheduledTransactionsIndex) Store( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + blockHeight uint64, + scheduledTxs []access.ScheduledTransaction, +) error { + if err := idx.PrepareStore(lctx, rw, blockHeight); err != nil { + return fmt.Errorf("could not prepare store for block %d: %w", blockHeight, err) + } + + return storeAllScheduledTransactions(rw, scheduledTxs) +} + +// storeAllScheduledTransactions writes all scheduled transaction entries to the batch. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until the batch +// is committed. +// +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists]: if any scheduled transaction ID already exists +func storeAllScheduledTransactions(rw storage.ReaderBatchWriter, scheduledTxs []access.ScheduledTransaction) error { + writer := rw.Writer() + seen := visited.New[uint64]() + for _, tx := range scheduledTxs { + if seen.Visit(tx.ID) { + return fmt.Errorf("scheduled transaction %d appears more than once in batch: %w", tx.ID, storage.ErrAlreadyExists) + } + + primaryKey := makeScheduledTxPrimaryKey(tx.ID) + + exists, err := operation.KeyExists(rw.GlobalReader(), primaryKey) + if err != nil { + return fmt.Errorf("could not check key for tx %d: %w", tx.ID, err) + } + if exists { + return fmt.Errorf("scheduled transaction %d already exists: %w", tx.ID, storage.ErrAlreadyExists) + } + + if err := operation.UpsertByKey(writer, primaryKey, tx); err != nil { + return fmt.Errorf("could not store tx %d: %w", tx.ID, err) + } + if err := operation.UpsertByKey(writer, makeScheduledTxByAddrKey(tx.TransactionHandlerOwner, tx.ID), nil); err != nil { + return fmt.Errorf("could not store by-address key for tx %d: %w", tx.ID, err) + } + } + return nil +} + +// Executed updates the transaction's status to Executed and records the ID of the +// transaction that emitted the Executed event. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until committed. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if no entry with the given ID exists +// - [storage.ErrInvalidStatusTransition]: if the transaction is already Cancelled, Executed, or Failed +func (idx *ScheduledTransactionsIndex) Executed( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + scheduledTxID uint64, + transactionID flow.Identifier, +) error { + if !lctx.HoldsLock(storage.LockIndexScheduledTransactionsIndex) { + return fmt.Errorf("missing required lock: %s", storage.LockIndexScheduledTransactionsIndex) + } + + key := makeScheduledTxPrimaryKey(scheduledTxID) + var tx access.ScheduledTransaction + if err := operation.RetrieveByKey(rw.GlobalReader(), key, &tx); err != nil { + return fmt.Errorf("could not retrieve scheduled transaction %d: %w", scheduledTxID, err) + } + if tx.Status != access.ScheduledTxStatusScheduled { + return fmt.Errorf("tx %d already in terminal state %s: %w", scheduledTxID, tx.Status, storage.ErrInvalidStatusTransition) + } + + tx.Status = access.ScheduledTxStatusExecuted + tx.ExecutedTransactionID = transactionID + + if err := operation.UpsertByKey(rw.Writer(), key, tx); err != nil { + return fmt.Errorf("could not update scheduled transaction %d: %w", scheduledTxID, err) + } + return nil +} + +// Cancelled updates the transaction's status to Cancelled and records fee amounts +// and the ID of the transaction that emitted the Canceled event. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until committed. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if no entry with the given ID exists +// - [storage.ErrInvalidStatusTransition]: if the transaction is already Executed, Cancelled, or Failed +func (idx *ScheduledTransactionsIndex) Cancelled( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + scheduledTxID uint64, + feesReturned uint64, + feesDeducted uint64, + transactionID flow.Identifier, +) error { + if !lctx.HoldsLock(storage.LockIndexScheduledTransactionsIndex) { + return fmt.Errorf("missing required lock: %s", storage.LockIndexScheduledTransactionsIndex) + } + + key := makeScheduledTxPrimaryKey(scheduledTxID) + var tx access.ScheduledTransaction + if err := operation.RetrieveByKey(rw.GlobalReader(), key, &tx); err != nil { + return fmt.Errorf("could not retrieve scheduled transaction %d: %w", scheduledTxID, err) + } + if tx.Status != access.ScheduledTxStatusScheduled { + return fmt.Errorf("tx %d already in terminal state %s: %w", scheduledTxID, tx.Status, storage.ErrInvalidStatusTransition) + } + + tx.Status = access.ScheduledTxStatusCancelled + tx.FeesReturned = feesReturned + tx.FeesDeducted = feesDeducted + tx.CancelledTransactionID = transactionID + + if err := operation.UpsertByKey(rw.Writer(), key, tx); err != nil { + return fmt.Errorf("could not update scheduled transaction %d: %w", scheduledTxID, err) + } + return nil +} + +// Failed updates the transaction's status to Failed and records the ID of the executor +// transaction that attempted (and failed) to execute the scheduled transaction. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until committed. +// +// Expected error returns during normal operation: +// - [storage.ErrNotFound]: if no entry with the given ID exists +// - [storage.ErrInvalidStatusTransition]: if the transaction is already Executed, Cancelled, or Failed +func (idx *ScheduledTransactionsIndex) Failed( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + scheduledTxID uint64, + transactionID flow.Identifier, +) error { + if !lctx.HoldsLock(storage.LockIndexScheduledTransactionsIndex) { + return fmt.Errorf("missing required lock: %s", storage.LockIndexScheduledTransactionsIndex) + } + + key := makeScheduledTxPrimaryKey(scheduledTxID) + + var tx access.ScheduledTransaction + if err := operation.RetrieveByKey(rw.GlobalReader(), key, &tx); err != nil { + return fmt.Errorf("could not retrieve scheduled transaction %d: %w", scheduledTxID, err) + } + if tx.Status != access.ScheduledTxStatusScheduled { + return fmt.Errorf("tx %d already in terminal state %s: %w", scheduledTxID, tx.Status, storage.ErrInvalidStatusTransition) + } + + tx.Status = access.ScheduledTxStatusFailed + tx.ExecutedTransactionID = transactionID + + if err := operation.UpsertByKey(rw.Writer(), key, tx); err != nil { + return fmt.Errorf("could not update scheduled transaction %d: %w", scheduledTxID, err) + } + return nil +} + +// reconstructScheduledTx decodes a msgpack-encoded value into a [access.ScheduledTransaction]. +// +// Any error indicates a malformed value. +func reconstructScheduledTx(_ access.ScheduledTransactionCursor, value []byte) (*access.ScheduledTransaction, error) { + var tx access.ScheduledTransaction + if err := msgpack.Unmarshal(value, &tx); err != nil { + return nil, err + } + return &tx, nil +} + +// makeScheduledTxPrimaryKey creates a primary key [code][~id]. +// One's complement ensures higher IDs sort first during forward iteration. +func makeScheduledTxPrimaryKey(id uint64) []byte { + key := make([]byte, scheduledTxPrimaryKeyLen) + key[0] = codeScheduledTransaction + binary.BigEndian.PutUint64(key[1:], ^id) + return key +} + +// makeScheduledTxByAddrKey creates a by-address key [code][address][~id]. +func makeScheduledTxByAddrKey(addr flow.Address, id uint64) []byte { + key := make([]byte, scheduledTxByAddrKeyLen) + key[0] = codeScheduledTransactionByAddress + copy(key[1:1+flow.AddressLength], addr[:]) + binary.BigEndian.PutUint64(key[1+flow.AddressLength:], ^id) + return key +} + +// decodeScheduledTxCursor decodes a primary key and returns the ID. +// +// Any error indicates a malformed key. +func decodeScheduledTxCursor(key []byte) (access.ScheduledTransactionCursor, error) { + if len(key) != scheduledTxPrimaryKeyLen { + return access.ScheduledTransactionCursor{}, fmt.Errorf("invalid primary key length: expected %d, got %d", scheduledTxPrimaryKeyLen, len(key)) + } + if key[0] != codeScheduledTransaction { + return access.ScheduledTransactionCursor{}, fmt.Errorf("invalid prefix: expected %d, got %d", codeScheduledTransaction, key[0]) + } + return access.ScheduledTransactionCursor{ + ID: ^binary.BigEndian.Uint64(key[1:]), + }, nil +} + +// decodeScheduledTxByAddrCursor decodes a by-address key and returns the cursor ID. +// +// Any error indicates a malformed key. +func decodeScheduledTxByAddrCursor(key []byte) (access.ScheduledTransactionCursor, error) { + if len(key) != scheduledTxByAddrKeyLen { + return access.ScheduledTransactionCursor{}, fmt.Errorf( + "invalid by-address key length: expected %d, got %d", scheduledTxByAddrKeyLen, len(key)) + } + if key[0] != codeScheduledTransactionByAddress { + return access.ScheduledTransactionCursor{}, fmt.Errorf( + "invalid prefix: expected %d, got %d", codeScheduledTransactionByAddress, key[0]) + } + + // skip prefix and address + offset := 1 + flow.AddressLength + id := ^binary.BigEndian.Uint64(key[offset:]) + + return access.ScheduledTransactionCursor{ + ID: id, + }, nil +} diff --git a/storage/indexes/scheduled_transactions_bootstrapper.go b/storage/indexes/scheduled_transactions_bootstrapper.go new file mode 100644 index 00000000000..032675b00fb --- /dev/null +++ b/storage/indexes/scheduled_transactions_bootstrapper.go @@ -0,0 +1,234 @@ +package indexes + +import ( + "errors" + "fmt" + + "github.com/jordanschalm/lockctx" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" +) + +// ScheduledTransactionsBootstrapper wraps a [ScheduledTransactionsIndex] and performs +// just-in-time initialization of the index when the initial block is provided. +// +// Scheduled transactions may not be available for the root block during bootstrapping. +// This struct acts as a proxy for the underlying [ScheduledTransactionsIndex] and +// encapsulates the complexity of initializing the index when the initial block is eventually provided. +type ScheduledTransactionsBootstrapper struct { + db storage.DB + initialStartHeight uint64 + + store *atomic.Pointer[ScheduledTransactionsIndex] +} + +var _ storage.ScheduledTransactionsIndexBootstrapper = (*ScheduledTransactionsBootstrapper)(nil) + +// NewScheduledTransactionsBootstrapper creates a new scheduled transactions bootstrapper. +// +// No error returns are expected during normal operation. +func NewScheduledTransactionsBootstrapper(db storage.DB, initialStartHeight uint64) (*ScheduledTransactionsBootstrapper, error) { + store, err := NewScheduledTransactionsIndex(db) + if err != nil { + if !errors.Is(err, storage.ErrNotBootstrapped) { + return nil, fmt.Errorf("could not create scheduled transactions index: %w", err) + } + // make sure it's nil + store = nil + } + + return &ScheduledTransactionsBootstrapper{ + db: db, + initialStartHeight: initialStartHeight, + store: atomic.NewPointer(store), + }, nil +} + +// FirstIndexedHeight returns the first (oldest) block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ScheduledTransactionsBootstrapper) FirstIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.FirstIndexedHeight(), nil +} + +// LatestIndexedHeight returns the latest block height that has been indexed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ScheduledTransactionsBootstrapper) LatestIndexedHeight() (uint64, error) { + store := b.store.Load() + if store == nil { + return 0, storage.ErrNotBootstrapped + } + return store.LatestIndexedHeight(), nil +} + +// UninitializedFirstHeight returns the height the index will accept as the first height, and a boolean +// indicating if the index is initialized. +// If the index is not initialized, the first call to `Store` must include data for this height. +func (b *ScheduledTransactionsBootstrapper) UninitializedFirstHeight() (uint64, bool) { + store := b.store.Load() + if store == nil { + return b.initialStartHeight, false + } + return store.FirstIndexedHeight(), true +} + +// ByID returns the scheduled transaction with the given scheduler-assigned ID. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrNotFound] if no scheduled transaction with the given ID exists +func (b *ScheduledTransactionsBootstrapper) ByID(id uint64) (access.ScheduledTransaction, error) { + store := b.store.Load() + if store == nil { + return access.ScheduledTransaction{}, storage.ErrNotBootstrapped + } + return store.ByID(id) +} + +// ByAddress returns an iterator over scheduled transactions for the given account. +// See [ScheduledTransactionsIndex.ByAddress] for full documentation. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ScheduledTransactionsBootstrapper) ByAddress( + account flow.Address, + cursor *access.ScheduledTransactionCursor, +) (storage.ScheduledTransactionIterator, error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.ByAddress(account, cursor) +} + +// All returns an iterator over all scheduled transactions. +// See [ScheduledTransactionsIndex.All] for full documentation. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +func (b *ScheduledTransactionsBootstrapper) All( + cursor *access.ScheduledTransactionCursor, +) (storage.ScheduledTransactionIterator, error) { + store := b.store.Load() + if store == nil { + return nil, storage.ErrNotBootstrapped + } + return store.All(cursor) +} + +// Store indexes all new scheduled transactions from the given block. +// Must be called sequentially with consecutive heights (latestHeight + 1). +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until the batch is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized and the provided block height +// is not the initial start height +// - [storage.ErrAlreadyExists] if the block height is already indexed +func (b *ScheduledTransactionsBootstrapper) Store( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + blockHeight uint64, + scheduledTxs []access.ScheduledTransaction, +) error { + // if the index is already initialized, store the data directly + if store := b.store.Load(); store != nil { + return store.Store(lctx, rw, blockHeight, scheduledTxs) + } + + // otherwise bootstrap the index. this will store the data during initialization + if blockHeight != b.initialStartHeight { + return fmt.Errorf("expected first indexed height %d, got %d: %w", b.initialStartHeight, blockHeight, storage.ErrNotBootstrapped) + } + + store, err := BootstrapScheduledTransactions(lctx, rw, b.db, b.initialStartHeight, scheduledTxs) + if err != nil { + return fmt.Errorf("could not initialize scheduled transactions storage: %w", err) + } + + if !b.store.CompareAndSwap(nil, store) { + // this should never happen. if it does, there is a bug. this indicates another goroutine + // successfully initialized `store` since we checked the value above. since the bootstrap + // operation is protected by the lock and it performs sanity checks to ensure the table + // is actually empty, the bootstrap operation should fail if there was concurrent access. + return fmt.Errorf("scheduled transactions initialized during bootstrap") + } + + return nil +} + +// Executed updates the scheduled transaction's status to Executed and records the ID of the transaction +// that emitted the Executed event. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until the batch +// is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrNotFound] if no scheduled transaction with the given ID exists +// - [storage.ErrInvalidStatusTransition] if the transaction is already Executed, Cancelled, or Failed +func (b *ScheduledTransactionsBootstrapper) Executed( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + scheduledTxID uint64, + transactionID flow.Identifier, +) error { + store := b.store.Load() + if store == nil { + return storage.ErrNotBootstrapped + } + return store.Executed(lctx, rw, scheduledTxID, transactionID) +} + +// Cancelled updates the scheduled transaction's status to Cancelled and records the +// fee amounts and the ID of the transaction that emitted the Canceled event. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until the batch +// is committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrNotFound] if no scheduled transaction with the given ID exists +// - [storage.ErrInvalidStatusTransition] if the transaction is already Executed, Cancelled, or Failed +func (b *ScheduledTransactionsBootstrapper) Cancelled( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + scheduledTxID uint64, + feesReturned uint64, + feesDeducted uint64, + transactionID flow.Identifier, +) error { + store := b.store.Load() + if store == nil { + return storage.ErrNotBootstrapped + } + return store.Cancelled(lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID) +} + +// Failed updates the transaction's status to Failed and records the ID of the transaction +// that emitted the Failed event. +// The caller must hold the [storage.LockIndexScheduledTransactionsIndex] lock until committed. +// +// Expected error returns during normal operations: +// - [storage.ErrNotBootstrapped] if the index has not been initialized +// - [storage.ErrNotFound] if no scheduled transaction with the given ID exists +// - [storage.ErrInvalidStatusTransition] if the transaction is already Executed, Cancelled, or Failed +func (b *ScheduledTransactionsBootstrapper) Failed( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + scheduledTxID uint64, + transactionID flow.Identifier, +) error { + store := b.store.Load() + if store == nil { + return storage.ErrNotBootstrapped + } + return store.Failed(lctx, rw, scheduledTxID, transactionID) +} diff --git a/storage/indexes/scheduled_transactions_bootstrapper_test.go b/storage/indexes/scheduled_transactions_bootstrapper_test.go new file mode 100644 index 00000000000..f1563172c2b --- /dev/null +++ b/storage/indexes/scheduled_transactions_bootstrapper_test.go @@ -0,0 +1,287 @@ +package indexes_test + +import ( + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// storeBootstrapperScheduledTx is a helper that calls Store on the bootstrapper under the required lock. +func storeBootstrapperScheduledTx( + tb testing.TB, + store storage.ScheduledTransactionsIndexBootstrapper, + db storage.DB, + height uint64, + txs []access.ScheduledTransaction, +) error { + tb.Helper() + lockManager := storage.NewTestingLockManager() + return unittest.WithLock(tb, lockManager, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return store.Store(lctx, rw, height, txs) + }) + }) +} + +// openPebbleScheduledTxDB opens a pebble DB at dir for use in persistence tests. +func openPebbleScheduledTxDB(tb testing.TB, dir string) storage.DB { + tb.Helper() + pdb, err := pebble.Open(dir, &pebble.Options{}) + require.NoError(tb, err) + return pebbleimpl.ToDB(pdb) +} + +// collectBootstrapperAll collects results from the bootstrapper All method. +func collectBootstrapperAll(tb testing.TB, store storage.ScheduledTransactionsIndexBootstrapper, limit uint32, cursor *access.ScheduledTransactionCursor) ([]access.ScheduledTransaction, *access.ScheduledTransactionCursor) { + tb.Helper() + iter, err := store.All(cursor) + require.NoError(tb, err) + collected, nextCursor, err := iterator.CollectResults(iter, limit, nil) + require.NoError(tb, err) + return collected, nextCursor +} + +// collectBootstrapperByAddress collects results from the bootstrapper ByAddress method. +func collectBootstrapperByAddress(tb testing.TB, store storage.ScheduledTransactionsIndexBootstrapper, addr access.ScheduledTransaction, limit uint32, cursor *access.ScheduledTransactionCursor) ([]access.ScheduledTransaction, *access.ScheduledTransactionCursor) { + tb.Helper() + iter, err := store.ByAddress(addr.TransactionHandlerOwner, cursor) + require.NoError(tb, err) + collected, nextCursor, err := iterator.CollectResults(iter, limit, nil) + require.NoError(tb, err) + return collected, nextCursor +} + +func TestScheduledTransactionsBootstrapper_Uninitialized_Reads(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := indexes.NewScheduledTransactionsBootstrapper(storageDB, 10) + require.NoError(t, err) + + _, err = store.ByID(1) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + _, err = store.ByAddress(unittest.RandomAddressFixture(), nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + _, err = store.All(nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) +} + +func TestScheduledTransactionsBootstrapper_FirstStore_WrongHeight(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := indexes.NewScheduledTransactionsBootstrapper(storageDB, 10) + require.NoError(t, err) + + err = storeBootstrapperScheduledTx(t, store, storageDB, 11, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeBootstrapperScheduledTx(t, store, storageDB, 9, nil) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + }) +} + +func TestScheduledTransactionsBootstrapper_FirstStore_BootstrapsAndSucceeds(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := indexes.NewScheduledTransactionsBootstrapper(storageDB, 10) + require.NoError(t, err) + + addr := unittest.RandomAddressFixture() + txs := []access.ScheduledTransaction{makeScheduledTx(1, addr)} + + err = storeBootstrapperScheduledTx(t, store, storageDB, 10, txs) + require.NoError(t, err) + + // reads should work after bootstrap + got, err := store.ByID(1) + require.NoError(t, err) + assert.Equal(t, uint64(1), got.ID) + + byAddr, _ := collectBootstrapperByAddress(t, store, txs[0], 10, nil) + require.Len(t, byAddr, 1) + assert.Equal(t, uint64(1), byAddr[0].ID) + + all, _ := collectBootstrapperAll(t, store, 10, nil) + require.Len(t, all, 1) + }) +} + +func TestScheduledTransactionsBootstrapper_SecondStore_Succeeds(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := indexes.NewScheduledTransactionsBootstrapper(storageDB, 5) + require.NoError(t, err) + + addr := unittest.RandomAddressFixture() + tx1 := makeScheduledTx(1, addr) + tx2 := makeScheduledTx(2, addr) + + err = storeBootstrapperScheduledTx(t, store, storageDB, 5, []access.ScheduledTransaction{tx1}) + require.NoError(t, err) + + err = storeBootstrapperScheduledTx(t, store, storageDB, 6, []access.ScheduledTransaction{tx2}) + require.NoError(t, err) + + byAddr, _ := collectBootstrapperByAddress(t, store, tx1, 10, nil) + require.Len(t, byAddr, 2) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(6), latest) + }) +} + +func TestScheduledTransactionsBootstrapper_UninitializedFirstHeight(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := indexes.NewScheduledTransactionsBootstrapper(storageDB, 42) + require.NoError(t, err) + + height, initialized := store.UninitializedFirstHeight() + assert.Equal(t, uint64(42), height) + assert.False(t, initialized) + + err = storeBootstrapperScheduledTx(t, store, storageDB, 42, nil) + require.NoError(t, err) + + height, initialized = store.UninitializedFirstHeight() + assert.Equal(t, uint64(42), height) + assert.True(t, initialized) + }) +} + +func TestScheduledTransactionsBootstrapper_HeightMethods_Uninitialized(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := indexes.NewScheduledTransactionsBootstrapper(storageDB, 42) + require.NoError(t, err) + + height, err := store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + + height, err = store.LatestIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + assert.Equal(t, uint64(0), height) + }) +} + +func TestScheduledTransactionsBootstrapper_HeightMethods_Initialized(t *testing.T) { + t.Parallel() + + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + store, err := indexes.NewScheduledTransactionsBootstrapper(storageDB, 7) + require.NoError(t, err) + + err = storeBootstrapperScheduledTx(t, store, storageDB, 7, nil) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(7), first) + + latest, err := store.LatestIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(7), latest) + }) +} + +func TestScheduledTransactionsBootstrapper_AlreadyBootstrapped(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 5, func(db storage.DB, _ storage.LockManager, _ *indexes.ScheduledTransactionsIndex) { + store, err := indexes.NewScheduledTransactionsBootstrapper(db, 5) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(5), first) + }) +} + +func TestScheduledTransactionsBootstrapper_DoubleBootstrapProtection(t *testing.T) { + t.Parallel() + + lockManager := storage.NewTestingLockManager() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + err := unittest.WithLock(t, lockManager, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := indexes.BootstrapScheduledTransactions(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.NoError(t, err) + + err = unittest.WithLock(t, lockManager, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := indexes.BootstrapScheduledTransactions(lctx, rw, storageDB, 1, nil) + return bootstrapErr + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestScheduledTransactionsBootstrapper_PersistenceAcrossRestart(t *testing.T) { + t.Parallel() + + unittest.RunWithTempDir(t, func(dir string) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(99, addr) + + func() { + db := openPebbleScheduledTxDB(t, dir) + defer db.Close() + + store, err := indexes.NewScheduledTransactionsBootstrapper(db, 100) + require.NoError(t, err) + + _, err = store.FirstIndexedHeight() + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + + err = storeBootstrapperScheduledTx(t, store, db, 100, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + }() + + db := openPebbleScheduledTxDB(t, dir) + defer db.Close() + + store, err := indexes.NewScheduledTransactionsBootstrapper(db, 100) + require.NoError(t, err) + + first, err := store.FirstIndexedHeight() + require.NoError(t, err) + assert.Equal(t, uint64(100), first) + + got, err := store.ByID(99) + require.NoError(t, err) + assert.Equal(t, uint64(99), got.ID) + }) +} diff --git a/storage/indexes/scheduled_transactions_test.go b/storage/indexes/scheduled_transactions_test.go new file mode 100644 index 00000000000..45babdae7ee --- /dev/null +++ b/storage/indexes/scheduled_transactions_test.go @@ -0,0 +1,390 @@ +package indexes_test + +import ( + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/indexes" + "github.com/onflow/flow-go/storage/indexes/iterator" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// RunWithBootstrappedScheduledTxIndex creates a Pebble DB and bootstraps the scheduled +// transactions index at the given start height. The callback receives the DB, lock manager, +// and the bootstrapped index. +func RunWithBootstrappedScheduledTxIndex( + tb testing.TB, + startHeight uint64, + f func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex), +) { + unittest.RunWithPebbleDB(tb, func(db *pebble.DB) { + lm := storage.NewTestingLockManager() + storageDB := pebbleimpl.ToDB(db) + + var idx *indexes.ScheduledTransactionsIndex + err := unittest.WithLock(tb, lm, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + var bootstrapErr error + idx, bootstrapErr = indexes.BootstrapScheduledTransactions(lctx, rw, storageDB, startHeight, nil) + return bootstrapErr + }) + }) + require.NoError(tb, err) + + f(storageDB, lm, idx) + }) +} + +// storeScheduledTxs is a helper that stores transactions under the required lock. +func storeScheduledTxs( + tb testing.TB, + lm storage.LockManager, + idx *indexes.ScheduledTransactionsIndex, + db storage.DB, + blockHeight uint64, + txs []access.ScheduledTransaction, +) error { + return unittest.WithLock(tb, lm, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Store(lctx, rw, blockHeight, txs) + }) + }) +} + +// executeTx is a helper that calls Executed under the required lock. +func executeTx( + tb testing.TB, + lm storage.LockManager, + idx *indexes.ScheduledTransactionsIndex, + db storage.DB, + id uint64, + transactionID flow.Identifier, +) error { + return unittest.WithLock(tb, lm, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Executed(lctx, rw, id, transactionID) + }) + }) +} + +// cancelTx is a helper that calls Cancelled under the required lock. +func cancelTx( + tb testing.TB, + lm storage.LockManager, + idx *indexes.ScheduledTransactionsIndex, + db storage.DB, + id uint64, + feesReturned uint64, + feesDeducted uint64, + transactionID flow.Identifier, +) error { + return unittest.WithLock(tb, lm, storage.LockIndexScheduledTransactionsIndex, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return idx.Cancelled(lctx, rw, id, feesReturned, feesDeducted, transactionID) + }) + }) +} + +// collectAll is a test helper that collects all results from the index using CollectResults. +func collectAll(tb testing.TB, idx *indexes.ScheduledTransactionsIndex, limit uint32, cursor *access.ScheduledTransactionCursor, filter storage.IndexFilter[*access.ScheduledTransaction]) ([]access.ScheduledTransaction, *access.ScheduledTransactionCursor) { + tb.Helper() + iter, err := idx.All(cursor) + require.NoError(tb, err) + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter) + require.NoError(tb, err) + return collected, nextCursor +} + +// collectByAddress is a test helper that collects results for an address using CollectResults. +func collectByAddress(tb testing.TB, idx *indexes.ScheduledTransactionsIndex, addr flow.Address, limit uint32, cursor *access.ScheduledTransactionCursor, filter storage.IndexFilter[*access.ScheduledTransaction]) ([]access.ScheduledTransaction, *access.ScheduledTransactionCursor) { + tb.Helper() + iter, err := idx.ByAddress(addr, cursor) + require.NoError(tb, err) + collected, nextCursor, err := iterator.CollectResults(iter, limit, filter) + require.NoError(tb, err) + return collected, nextCursor +} + +// makeScheduledTx builds a minimal ScheduledTransaction with the given ID and address. +func makeScheduledTx(id uint64, addr flow.Address) access.ScheduledTransaction { + return access.ScheduledTransaction{ + ID: id, + Priority: 1, + Timestamp: 1000, + Fees: 500, + TransactionHandlerOwner: addr, + TransactionHandlerTypeIdentifier: "A.0000000000000001.Contract", + TransactionHandlerUUID: 42, + TransactionHandlerPublicPath: "handler", + Status: access.ScheduledTxStatusScheduled, + } +} + +func TestScheduledTransactionsIndex_StoreAndByID(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(100, addr) + + err := storeScheduledTxs(t, lm, idx, db, 2, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + + got, err := idx.ByID(100) + require.NoError(t, err) + assert.Equal(t, tx.ID, got.ID) + assert.Equal(t, tx.Priority, got.Priority) + assert.Equal(t, tx.Timestamp, got.Timestamp) + assert.Equal(t, tx.Fees, got.Fees) + assert.Equal(t, tx.TransactionHandlerOwner, got.TransactionHandlerOwner) + assert.Equal(t, tx.TransactionHandlerTypeIdentifier, got.TransactionHandlerTypeIdentifier) + assert.Equal(t, tx.TransactionHandlerUUID, got.TransactionHandlerUUID) + assert.Equal(t, tx.TransactionHandlerPublicPath, got.TransactionHandlerPublicPath) + assert.Equal(t, access.ScheduledTxStatusScheduled, got.Status) + }) +} + +func TestScheduledTransactionsIndex_StoreDuplicate(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(200, addr) + + err := storeScheduledTxs(t, lm, idx, db, 2, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + + // Storing the same tx ID again always returns ErrAlreadyExists. + err = storeScheduledTxs(t, lm, idx, db, 3, []access.ScheduledTransaction{tx}) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) +} + +func TestScheduledTransactionsIndex_Executed_Happy(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(400, addr) + executedTxID := unittest.IdentifierFixture() + + err := storeScheduledTxs(t, lm, idx, db, 2, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + + err = executeTx(t, lm, idx, db, 400, executedTxID) + require.NoError(t, err) + + got, err := idx.ByID(400) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusExecuted, got.Status) + assert.Equal(t, executedTxID, got.ExecutedTransactionID) + }) +} + +func TestScheduledTransactionsIndex_Executed_NotFound(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + err := executeTx(t, lm, idx, db, 9999, unittest.IdentifierFixture()) + require.ErrorIs(t, err, storage.ErrNotFound) + }) +} + +func TestScheduledTransactionsIndex_Executed_AlreadyTerminal(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(500, addr) + + err := storeScheduledTxs(t, lm, idx, db, 2, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + + err = executeTx(t, lm, idx, db, 500, unittest.IdentifierFixture()) + require.NoError(t, err) + + // Second call should fail. + err = executeTx(t, lm, idx, db, 500, unittest.IdentifierFixture()) + require.ErrorIs(t, err, storage.ErrInvalidStatusTransition) + }) +} + +func TestScheduledTransactionsIndex_Cancelled_Happy(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(600, addr) + cancelledTxID := unittest.IdentifierFixture() + + err := storeScheduledTxs(t, lm, idx, db, 2, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + + err = cancelTx(t, lm, idx, db, 600, 50, 10, cancelledTxID) + require.NoError(t, err) + + got, err := idx.ByID(600) + require.NoError(t, err) + assert.Equal(t, access.ScheduledTxStatusCancelled, got.Status) + assert.Equal(t, uint64(50), got.FeesReturned) + assert.Equal(t, uint64(10), got.FeesDeducted) + assert.Equal(t, cancelledTxID, got.CancelledTransactionID) + }) +} + +func TestScheduledTransactionsIndex_Cancelled_AlreadyTerminal(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(700, addr) + + err := storeScheduledTxs(t, lm, idx, db, 2, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + + err = cancelTx(t, lm, idx, db, 700, 10, 5, unittest.IdentifierFixture()) + require.NoError(t, err) + + // Second cancellation should fail. + err = cancelTx(t, lm, idx, db, 700, 10, 5, unittest.IdentifierFixture()) + require.ErrorIs(t, err, storage.ErrInvalidStatusTransition) + }) +} + +func TestScheduledTransactionsIndex_ExecutedThenCancelled(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + tx := makeScheduledTx(800, addr) + + err := storeScheduledTxs(t, lm, idx, db, 2, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + + err = executeTx(t, lm, idx, db, 800, unittest.IdentifierFixture()) + require.NoError(t, err) + + // Cancelling an executed tx should fail. + err = cancelTx(t, lm, idx, db, 800, 10, 5, unittest.IdentifierFixture()) + require.ErrorIs(t, err, storage.ErrInvalidStatusTransition) + }) +} + +func TestScheduledTransactionsIndex_All_Pagination(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + + // Store txs with IDs 1-5, one per block height. + for i := uint64(1); i <= 5; i++ { + tx := makeScheduledTx(i, addr) + err := storeScheduledTxs(t, lm, idx, db, i+1, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + } + + // Page 1: limit=2, expect IDs 5, 4 (highest first). + page1, cursor1 := collectAll(t, idx, 2, nil, nil) + require.Len(t, page1, 2) + require.NotNil(t, cursor1) + assert.Equal(t, uint64(5), page1[0].ID) + assert.Equal(t, uint64(4), page1[1].ID) + + // Page 2: use cursor, expect IDs 3, 2. + page2, cursor2 := collectAll(t, idx, 2, cursor1, nil) + require.Len(t, page2, 2) + require.NotNil(t, cursor2) + assert.Equal(t, uint64(3), page2[0].ID) + assert.Equal(t, uint64(2), page2[1].ID) + + // Page 3: expect only ID 1, no next cursor. + page3, cursor3 := collectAll(t, idx, 2, cursor2, nil) + require.Len(t, page3, 1) + assert.Nil(t, cursor3) + assert.Equal(t, uint64(1), page3[0].ID) + }) +} + +func TestScheduledTransactionsIndex_ByAddress_Pagination(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr1 := unittest.RandomAddressFixture() + addr2 := unittest.RandomAddressFixture() + + // Store 3 txs for addr1 (IDs 1, 2, 3) and 2 txs for addr2 (IDs 4, 5). + blockHeight := uint64(2) + for _, tx := range []access.ScheduledTransaction{ + makeScheduledTx(1, addr1), + makeScheduledTx(2, addr1), + makeScheduledTx(3, addr1), + } { + err := storeScheduledTxs(t, lm, idx, db, blockHeight, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + blockHeight++ + } + for _, tx := range []access.ScheduledTransaction{ + makeScheduledTx(4, addr2), + makeScheduledTx(5, addr2), + } { + err := storeScheduledTxs(t, lm, idx, db, blockHeight, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + blockHeight++ + } + + // First page for addr1: limit=2, expect IDs 3, 2 (highest first). + page1, cursor1 := collectByAddress(t, idx, addr1, 2, nil, nil) + require.Len(t, page1, 2) + require.NotNil(t, cursor1) + assert.Equal(t, uint64(3), page1[0].ID) + assert.Equal(t, uint64(2), page1[1].ID) + + // Second page for addr1: expect ID 1, no next cursor. + page2, cursor2 := collectByAddress(t, idx, addr1, 2, cursor1, nil) + require.Len(t, page2, 1) + assert.Nil(t, cursor2) + assert.Equal(t, uint64(1), page2[0].ID) + + // addr2 is unaffected: limit=10, expect IDs 5, 4. + pageAddr2, _ := collectByAddress(t, idx, addr2, 10, nil, nil) + require.Len(t, pageAddr2, 2) + assert.Equal(t, uint64(5), pageAddr2[0].ID) + assert.Equal(t, uint64(4), pageAddr2[1].ID) + }) +} + +func TestScheduledTransactionsIndex_All_Filter(t *testing.T) { + t.Parallel() + + RunWithBootstrappedScheduledTxIndex(t, 1, func(db storage.DB, lm storage.LockManager, idx *indexes.ScheduledTransactionsIndex) { + addr := unittest.RandomAddressFixture() + + // Store 3 txs: IDs 1, 2, 3. + for i := uint64(1); i <= 3; i++ { + tx := makeScheduledTx(i, addr) + err := storeScheduledTxs(t, lm, idx, db, i+1, []access.ScheduledTransaction{tx}) + require.NoError(t, err) + } + + // Execute tx with ID=2. + err := executeTx(t, lm, idx, db, 2, unittest.IdentifierFixture()) + require.NoError(t, err) + + // Filter to only Executed txs — should return exactly tx with ID=2. + executedOnly := func(tx *access.ScheduledTransaction) bool { + return tx.Status == access.ScheduledTxStatusExecuted + } + collected, _ := collectAll(t, idx, 10, nil, executedOnly) + require.Len(t, collected, 1) + assert.Equal(t, uint64(2), collected[0].ID) + assert.Equal(t, access.ScheduledTxStatusExecuted, collected[0].Status) + }) +} diff --git a/storage/indexes/state.go b/storage/indexes/state.go new file mode 100644 index 00000000000..bf5e3e15684 --- /dev/null +++ b/storage/indexes/state.go @@ -0,0 +1,151 @@ +package indexes + +import ( + "errors" + "fmt" + + "github.com/jordanschalm/lockctx" + "go.uber.org/atomic" + + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation" +) + +// IndexState manages height tracking for a block-height-indexed store. +// Concrete index types embed *IndexState to inherit height management. +// +// All read methods are safe for concurrent access. Write methods (PrepareStore) must be called +// sequentially, and the caller must hold the required lock until the batch is committed. +type IndexState struct { + db storage.DB + firstHeight uint64 + latestHeight *atomic.Uint64 + requiredLock string + lowerBoundKey []byte + upperBoundKey []byte +} + +// New reads the first and latest heights from the DB and returns a new IndexState. +// +// Expected error returns during normal operation: +// - [storage.ErrNotBootstrapped]: if the index has not been initialized +func NewIndexState(db storage.DB, requiredLock string, lowerBoundKey, upperBoundKey []byte) (*IndexState, error) { + firstHeight, err := readHeight(db.Reader(), lowerBoundKey) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + return nil, storage.ErrNotBootstrapped + } + return nil, fmt.Errorf("could not get first height: %w", err) + } + + latestHeight, err := readHeight(db.Reader(), upperBoundKey) + if err != nil { + return nil, fmt.Errorf("could not get latest height: %w", err) + } + + return &IndexState{ + db: db, + firstHeight: firstHeight, + latestHeight: atomic.NewUint64(latestHeight), + requiredLock: requiredLock, + lowerBoundKey: lowerBoundKey, + upperBoundKey: upperBoundKey, + }, nil +} + +// Bootstrap writes the bounds keys at initialStartHeight to the batch and returns a new IndexState. +// The caller is responsible for writing initial items to the same batch before committing. +// +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists]: if either bounds key already exists +func BootstrapIndexState( + lctx lockctx.Proof, + rw storage.ReaderBatchWriter, + db storage.DB, + requiredLock string, + lowerBoundKey, upperBoundKey []byte, + initialStartHeight uint64, +) (*IndexState, error) { + if !lctx.HoldsLock(requiredLock) { + return nil, fmt.Errorf("missing required lock: %s", requiredLock) + } + + for _, key := range [][]byte{lowerBoundKey, upperBoundKey} { + exists, err := operation.KeyExists(rw.GlobalReader(), key) + if err != nil { + return nil, fmt.Errorf("could not check bounds key: %w", err) + } + if exists { + return nil, fmt.Errorf("bounds key already exists: %w", storage.ErrAlreadyExists) + } + } + + writer := rw.Writer() + if err := operation.UpsertByKey(writer, lowerBoundKey, initialStartHeight); err != nil { + return nil, fmt.Errorf("could not set first height: %w", err) + } + if err := operation.UpsertByKey(writer, upperBoundKey, initialStartHeight); err != nil { + return nil, fmt.Errorf("could not set latest height: %w", err) + } + + // the caller is responsible for writing initial data to the batch before committing + + return &IndexState{ + db: db, + firstHeight: initialStartHeight, + latestHeight: atomic.NewUint64(initialStartHeight), + requiredLock: requiredLock, + lowerBoundKey: lowerBoundKey, + upperBoundKey: upperBoundKey, + }, nil +} + +// FirstIndexedHeight returns the first (oldest) indexed height. +func (s *IndexState) FirstIndexedHeight() uint64 { + return s.firstHeight +} + +// LatestIndexedHeight returns the latest indexed height. +func (s *IndexState) LatestIndexedHeight() uint64 { + return s.latestHeight.Load() +} + +// PrepareStore validates that blockHeight is the next consecutive height, verifies the required +// lock is held, writes the upper bound key update to the batch, and registers an OnCommitSucceed +// callback to advance the in-memory latestHeight. +// +// Expected error returns during normal operation: +// - [storage.ErrAlreadyExists]: if blockHeight is already indexed +func (s *IndexState) PrepareStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64) error { + if !lctx.HoldsLock(s.requiredLock) { + return fmt.Errorf("missing required lock: %s", s.requiredLock) + } + + // make sure the block height is the next consecutive height + expected := s.latestHeight.Load() + 1 + if blockHeight < expected { + return storage.ErrAlreadyExists + } + if blockHeight > expected { + return fmt.Errorf("must index consecutive heights: expected %d, got %d", expected, blockHeight) + } + + // sanity check that the stored height is in sync with the in-memory height + storedLatestHeight, err := readHeight(rw.GlobalReader(), s.upperBoundKey) + if err != nil { + return fmt.Errorf("could not get latest indexed height: %w", err) + } + if blockHeight != storedLatestHeight+1 { + return fmt.Errorf("must index consecutive heights: expected %d, got %d", storedLatestHeight+1, blockHeight) + } + + if err := operation.UpsertByKey(rw.Writer(), s.upperBoundKey, blockHeight); err != nil { + return fmt.Errorf("could not update latest height: %w", err) + } + + storage.OnCommitSucceed(rw, func() { + s.latestHeight.Store(blockHeight) + }) + + return nil +} diff --git a/storage/indexes/state_test.go b/storage/indexes/state_test.go new file mode 100644 index 00000000000..970f0c8486d --- /dev/null +++ b/storage/indexes/state_test.go @@ -0,0 +1,340 @@ +package indexes + +import ( + "errors" + "testing" + + "github.com/cockroachdb/pebble/v2" + "github.com/jordanschalm/lockctx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage/operation" + "github.com/onflow/flow-go/storage/operation/pebbleimpl" + "github.com/onflow/flow-go/utils/unittest" +) + +// testIndexStateLock reuses a registered lock name for IndexState unit tests. +// The test keys below use a unique prefix (0xFD) that does not collide with any +// concrete index type, so tests can share the same DB without interference. +const testIndexStateLock = storage.LockIndexAccountTransactions + +var ( + testIndexStateLowerKey = []byte{0xFD, 0x01} + testIndexStateUpperKey = []byte{0xFD, 0x02} +) + +// bootstrapTestIndexState bootstraps an IndexState in a committed batch and returns it. +func bootstrapTestIndexState(tb testing.TB, db storage.DB, lm storage.LockManager, height uint64) *IndexState { + tb.Helper() + var state *IndexState + err := unittest.WithLock(tb, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + var bootstrapErr error + state, bootstrapErr = BootstrapIndexState(lctx, rw, db, testIndexStateLock, testIndexStateLowerKey, testIndexStateUpperKey, height) + return bootstrapErr + }) + }) + require.NoError(tb, err) + return state +} + +func TestNewIndexState(t *testing.T) { + t.Parallel() + + t.Run("uninitialized DB returns ErrNotBootstrapped", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + index, err := NewIndexState(storageDB, testIndexStateLock, testIndexStateLowerKey, testIndexStateUpperKey) + require.ErrorIs(t, err, storage.ErrNotBootstrapped) + require.Nil(t, index) + }) + }) + + t.Run("lower bound key present but upper bound missing returns exception", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + + // Write only the lower bound, simulating partial / corrupted state. + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.UpsertByKey(rw.Writer(), testIndexStateLowerKey, uint64(5)) + }) + require.NoError(t, err) + + index, err := NewIndexState(storageDB, testIndexStateLock, testIndexStateLowerKey, testIndexStateUpperKey) + require.Nil(t, index) + assert.False(t, errors.Is(err, storage.ErrNotBootstrapped), "partial state should not return ErrNotBootstrapped") + require.Error(t, err) + }) + }) + + t.Run("fully bootstrapped DB returns correct heights", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + bootstrapTestIndexState(t, storageDB, lm, 42) + + state, err := NewIndexState(storageDB, testIndexStateLock, testIndexStateLowerKey, testIndexStateUpperKey) + require.NoError(t, err) + assert.Equal(t, uint64(42), state.FirstIndexedHeight()) + assert.Equal(t, uint64(42), state.LatestIndexedHeight()) + }) + }) + + t.Run("bootstrapped at height 0 returns correct heights", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + bootstrapTestIndexState(t, storageDB, lm, 0) + + state, err := NewIndexState(storageDB, testIndexStateLock, testIndexStateLowerKey, testIndexStateUpperKey) + require.NoError(t, err) + assert.Equal(t, uint64(0), state.FirstIndexedHeight()) + assert.Equal(t, uint64(0), state.LatestIndexedHeight()) + }) + }) +} + +func TestBootstrapIndexState(t *testing.T) { + t.Parallel() + + t.Run("without lock returns error", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + lctx := lm.NewContext() + defer lctx.Release() + + // lctx does not hold testIndexStateLock + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + _, bootstrapErr := BootstrapIndexState(lctx, rw, storageDB, testIndexStateLock, testIndexStateLowerKey, testIndexStateUpperKey, 1) + return bootstrapErr + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) + + t.Run("clean DB bootstraps successfully", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + state := bootstrapTestIndexState(t, storageDB, lm, 10) + assert.Equal(t, uint64(10), state.FirstIndexedHeight()) + assert.Equal(t, uint64(10), state.LatestIndexedHeight()) + }) + }) + + t.Run("second bootstrap returns ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + bootstrapTestIndexState(t, storageDB, lm, 1) + + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + index, bootstrapErr := BootstrapIndexState(lctx, rw, storageDB, testIndexStateLock, testIndexStateLowerKey, testIndexStateUpperKey, 1) + require.Nil(t, index) + return bootstrapErr + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("bootstrap at height 0", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + + state := bootstrapTestIndexState(t, storageDB, lm, 0) + assert.Equal(t, uint64(0), state.FirstIndexedHeight()) + assert.Equal(t, uint64(0), state.LatestIndexedHeight()) + }) + }) +} + +func TestIndexState_PrepareStore(t *testing.T) { + t.Parallel() + + t.Run("without lock returns error", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 1) + + // lctx does not hold testIndexStateLock + lctx := lm.NewContext() + defer lctx.Release() + + err := storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, 2) + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required lock") + }) + }) + + t.Run("consecutive height succeeds and advances latest height", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 1) + + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, 2) + }) + }) + require.NoError(t, err) + assert.Equal(t, uint64(2), state.LatestIndexedHeight()) + }) + }) + + t.Run("re-store at latest height returns ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 1) + + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, 1) + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("store below latest height returns ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 5) + + // advance to 6 + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, 6) + }) + }) + require.NoError(t, err) + + // try to store at 4 (below latest=6) + err = unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, 4) + }) + }) + require.ErrorIs(t, err, storage.ErrAlreadyExists) + }) + }) + + t.Run("non-consecutive height returns error, not ErrAlreadyExists", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 1) + + // gap: latest=1, expected=2, got=5 + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, 5) + }) + }) + require.Error(t, err) + assert.False(t, errors.Is(err, storage.ErrAlreadyExists), + "non-consecutive height should not return ErrAlreadyExists") + }) + }) + + t.Run("in-memory height not updated when batch is not committed", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 1) + + require.Equal(t, uint64(1), state.LatestIndexedHeight()) + + batch := state.db.NewBatch() + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return state.PrepareStore(lctx, batch, 2) + }) + require.NoError(t, err) + + // Close the batch without committing — discards the write. + require.NoError(t, batch.Close()) + + assert.Equal(t, uint64(1), state.LatestIndexedHeight(), + "latestHeight must not update when batch is not committed") + }) + }) +} + +func TestIndexState_Accessors(t *testing.T) { + t.Parallel() + + t.Run("FirstIndexedHeight returns bootstrap height", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 77) + assert.Equal(t, uint64(77), state.FirstIndexedHeight()) + }) + }) + + t.Run("FirstIndexedHeight does not change after PrepareStore", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 10) + + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, 11) + }) + }) + require.NoError(t, err) + + assert.Equal(t, uint64(10), state.FirstIndexedHeight(), + "FirstIndexedHeight must not change after PrepareStore") + }) + }) + + t.Run("LatestIndexedHeight advances with each committed PrepareStore", func(t *testing.T) { + t.Parallel() + unittest.RunWithPebbleDB(t, func(db *pebble.DB) { + storageDB := pebbleimpl.ToDB(db) + lm := storage.NewTestingLockManager() + state := bootstrapTestIndexState(t, storageDB, lm, 1) + + for height := uint64(2); height <= 5; height++ { + err := unittest.WithLock(t, lm, testIndexStateLock, func(lctx lockctx.Context) error { + return storageDB.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return state.PrepareStore(lctx, rw, height) + }) + }) + require.NoError(t, err) + assert.Equal(t, height, state.LatestIndexedHeight()) + } + }) + }) +} diff --git a/storage/inmemory/registers_reader.go b/storage/inmemory/registers_reader.go index 2445f0df4f3..c800082ec53 100644 --- a/storage/inmemory/registers_reader.go +++ b/storage/inmemory/registers_reader.go @@ -1,6 +1,8 @@ package inmemory import ( + "fmt" + "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow-go/storage" ) @@ -52,3 +54,9 @@ func (r *RegistersReader) LatestHeight() uint64 { func (r *RegistersReader) FirstHeight() uint64 { return r.blockHeight } + +func (r *RegistersReader) ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] { + return func(yield func(storage.IteratorEntry[flow.RegisterValue, flow.RegisterID], error) bool) { + yield(nil, fmt.Errorf("not implemented")) + } +} diff --git a/storage/locks.go b/storage/locks.go index 1981438b13b..d2cbee190f3 100644 --- a/storage/locks.go +++ b/storage/locks.go @@ -50,6 +50,15 @@ const ( LockInsertLivenessData = "lock_insert_liveness_data" // LockIndexScheduledTransaction protects the indexing of scheduled transactions. LockIndexScheduledTransaction = "lock_index_scheduled_transaction" + + LockIndexAccountTransactions = "lock_index_account_transactions" + LockIndexFungibleTokenTransfers = "lock_index_fungible_token_transfers" + LockIndexNonFungibleTokenTransfers = "lock_index_non_fungible_token_transfers" + // LockIndexScheduledTransactionsIndex protects the extended scheduled transactions index. + // This is distinct from LockIndexScheduledTransaction which protects a different lookup. + LockIndexScheduledTransactionsIndex = "lock_index_scheduled_transactions_index" + // LockIndexContractDeployments protects the extended contract deployments index. + LockIndexContractDeployments = "lock_index_contract_deployments" ) // Locks returns a list of all named locks used by the storage layer. @@ -76,6 +85,11 @@ func Locks() []string { LockInsertSafetyData, LockInsertLivenessData, LockIndexScheduledTransaction, + LockIndexAccountTransactions, + LockIndexFungibleTokenTransfers, + LockIndexNonFungibleTokenTransfers, + LockIndexScheduledTransactionsIndex, + LockIndexContractDeployments, } } @@ -129,6 +143,14 @@ var LockGroupProtocolStateBootstrap = []string{ LockInsertLivenessData, } +var LockGroupAccessExtendedIndexers = []string{ + LockIndexAccountTransactions, + LockIndexFungibleTokenTransfers, + LockIndexNonFungibleTokenTransfers, + LockIndexScheduledTransactionsIndex, + LockIndexContractDeployments, +} + // addLocks adds a chain of locks to the builder in the order they appear in the locks slice. // This creates a directed acyclic graph where each lock can be acquired after the previous one. func addLocks(builder lockctx.DAGPolicyBuilder, locks []string) { @@ -161,6 +183,7 @@ func makeLockPolicy() lockctx.Policy { addLocks(builder, LockGroupExecutionSaveExecutionResult) addLocks(builder, LockGroupCollectionBootstrapClusterState) addLocks(builder, LockGroupProtocolStateBootstrap) + addLocks(builder, LockGroupAccessExtendedIndexers) return builder.Build() } diff --git a/storage/merkle/errors.go b/storage/merkle/errors.go index 183d06a876d..bc926265ecc 100644 --- a/storage/merkle/errors.go +++ b/storage/merkle/errors.go @@ -14,7 +14,7 @@ type MalformedProofError struct { } // NewMalformedProofErrorf constructs a new MalformedProofError -func NewMalformedProofErrorf(msg string, args ...interface{}) *MalformedProofError { +func NewMalformedProofErrorf(msg string, args ...any) *MalformedProofError { return &MalformedProofError{err: fmt.Errorf(msg, args...)} } @@ -42,7 +42,7 @@ type InvalidProofError struct { } // newInvalidProofErrorf constructs a new InvalidProofError -func newInvalidProofErrorf(msg string, args ...interface{}) *InvalidProofError { +func newInvalidProofErrorf(msg string, args ...any) *InvalidProofError { return &InvalidProofError{err: fmt.Errorf(msg, args...)} } diff --git a/storage/merkle/proof_test.go b/storage/merkle/proof_test.go index 826b61b6ed8..4a10b4ae825 100644 --- a/storage/merkle/proof_test.go +++ b/storage/merkle/proof_test.go @@ -151,7 +151,7 @@ func TestProofsWithRandomKeys(t *testing.T) { // generate the desired number of keys and map a value to each key keys := make([][]byte, 0, numberOfInsertions) vals := make(map[string][]byte) - for i := 0; i < numberOfInsertions; i++ { + for range numberOfInsertions { key, val := randomKeyValuePair(32, 128) keys = append(keys, key) vals[string(key)] = val diff --git a/storage/merkle/tree.go b/storage/merkle/tree.go index f50c7f5686a..3913788d1cc 100644 --- a/storage/merkle/tree.go +++ b/storage/merkle/tree.go @@ -192,7 +192,7 @@ PutLoop: remainCount := n.count - commonCount - 1 if remainCount > 0 { remainPath := bitutils.MakeBitVector(remainCount) - for i := 0; i < remainCount; i++ { + for i := range remainCount { bitutils.WriteBit(remainPath, i, bitutils.ReadBit(n.path, i+commonCount+1)) } remainNode := &short{count: remainCount, path: remainPath} @@ -224,7 +224,7 @@ PutLoop: // otherwise, insert a short node with the remainder of the path finalCount := totalCount - index finalPath := bitutils.MakeBitVector(finalCount) - for i := 0; i < finalCount; i++ { + for i := range finalCount { bitutils.WriteBit(finalPath, i, bitutils.ReadBit(key, index+i)) } finalNode := &short{count: finalCount, path: []byte(finalPath)} diff --git a/storage/merkle/tree_test.go b/storage/merkle/tree_test.go index 8d0a601c6c0..f7d8d10ccbe 100644 --- a/storage/merkle/tree_test.go +++ b/storage/merkle/tree_test.go @@ -245,7 +245,7 @@ func TestTreeSingle(t *testing.T) { assert.NoError(t, err) // for the pre-defined number of times... - for i := 0; i < TreeTestLength; i++ { + for range TreeTestLength { // insert a random key with a random value and make sure it didn't // exist yet; collisions are unlikely enough to never happen key, val := randomKeyValuePair(keyLength, 128) @@ -283,7 +283,7 @@ func TestTreeBatch(t *testing.T) { // insert a batch of random key-value pairs keys := make([][]byte, 0, TreeTestLength) vals := make([][]byte, 0, TreeTestLength) - for i := 0; i < TreeTestLength; i++ { + for range TreeTestLength { key, val := randomKeyValuePair(keyLength, 128) keys = append(keys, key) vals = append(vals, val) @@ -331,7 +331,7 @@ func TestRandomOrder(t *testing.T) { // generate the desired number of keys and map a value to each key keys := make([][]byte, 0, TreeTestLength) vals := make(map[string][]byte) - for i := 0; i < TreeTestLength; i++ { + for range TreeTestLength { key, val := randomKeyValuePair(32, 128) keys = append(keys, key) vals[string(key)] = val @@ -392,7 +392,7 @@ func createTree(n int) *Tree { if err != nil { panic(err.Error()) } - for i := 0; i < n; i++ { + for range n { key, val := randomKeyValuePair(32, 128) _, _ = t.Put(key, val) } diff --git a/storage/mock/account_transactions.go b/storage/mock/account_transactions.go new file mode 100644 index 00000000000..aac226e5baf --- /dev/null +++ b/storage/mock/account_transactions.go @@ -0,0 +1,265 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewAccountTransactions creates a new instance of AccountTransactions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountTransactions(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountTransactions { + mock := &AccountTransactions{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// AccountTransactions is an autogenerated mock type for the AccountTransactions type +type AccountTransactions struct { + mock.Mock +} + +type AccountTransactions_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountTransactions) EXPECT() *AccountTransactions_Expecter { + return &AccountTransactions_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type AccountTransactions +func (_mock *AccountTransactions) ByAddress(account flow.Address, cursor *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.AccountTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.AccountTransactionCursor) storage.AccountTransactionIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.AccountTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.AccountTransactionCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccountTransactions_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type AccountTransactions_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.AccountTransactionCursor +func (_e *AccountTransactions_Expecter) ByAddress(account interface{}, cursor interface{}) *AccountTransactions_ByAddress_Call { + return &AccountTransactions_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *AccountTransactions_ByAddress_Call) Run(run func(account flow.Address, cursor *access.AccountTransactionCursor)) *AccountTransactions_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.AccountTransactionCursor + if args[1] != nil { + arg1 = args[1].(*access.AccountTransactionCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountTransactions_ByAddress_Call) Return(v storage.AccountTransactionIterator, err error) *AccountTransactions_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountTransactions_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error)) *AccountTransactions_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type AccountTransactions +func (_mock *AccountTransactions) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// AccountTransactions_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type AccountTransactions_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *AccountTransactions_Expecter) FirstIndexedHeight() *AccountTransactions_FirstIndexedHeight_Call { + return &AccountTransactions_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *AccountTransactions_FirstIndexedHeight_Call) Run(run func()) *AccountTransactions_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccountTransactions_FirstIndexedHeight_Call) Return(v uint64) *AccountTransactions_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *AccountTransactions_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *AccountTransactions_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type AccountTransactions +func (_mock *AccountTransactions) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// AccountTransactions_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type AccountTransactions_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *AccountTransactions_Expecter) LatestIndexedHeight() *AccountTransactions_LatestIndexedHeight_Call { + return &AccountTransactions_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *AccountTransactions_LatestIndexedHeight_Call) Run(run func()) *AccountTransactions_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccountTransactions_LatestIndexedHeight_Call) Return(v uint64) *AccountTransactions_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *AccountTransactions_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *AccountTransactions_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type AccountTransactions +func (_mock *AccountTransactions) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error { + ret := _mock.Called(lctx, rw, blockHeight, txData) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.AccountTransaction) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, txData) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// AccountTransactions_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type AccountTransactions_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - txData []access.AccountTransaction +func (_e *AccountTransactions_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, txData interface{}) *AccountTransactions_Store_Call { + return &AccountTransactions_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, txData)} +} + +func (_c *AccountTransactions_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction)) *AccountTransactions_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.AccountTransaction + if args[3] != nil { + arg3 = args[3].([]access.AccountTransaction) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *AccountTransactions_Store_Call) Return(err error) *AccountTransactions_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccountTransactions_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error) *AccountTransactions_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/account_transactions_bootstrapper.go b/storage/mock/account_transactions_bootstrapper.go new file mode 100644 index 00000000000..2876ccc41d0 --- /dev/null +++ b/storage/mock/account_transactions_bootstrapper.go @@ -0,0 +1,336 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewAccountTransactionsBootstrapper creates a new instance of AccountTransactionsBootstrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountTransactionsBootstrapper(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountTransactionsBootstrapper { + mock := &AccountTransactionsBootstrapper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// AccountTransactionsBootstrapper is an autogenerated mock type for the AccountTransactionsBootstrapper type +type AccountTransactionsBootstrapper struct { + mock.Mock +} + +type AccountTransactionsBootstrapper_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountTransactionsBootstrapper) EXPECT() *AccountTransactionsBootstrapper_Expecter { + return &AccountTransactionsBootstrapper_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type AccountTransactionsBootstrapper +func (_mock *AccountTransactionsBootstrapper) ByAddress(account flow.Address, cursor *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.AccountTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.AccountTransactionCursor) storage.AccountTransactionIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.AccountTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.AccountTransactionCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccountTransactionsBootstrapper_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type AccountTransactionsBootstrapper_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.AccountTransactionCursor +func (_e *AccountTransactionsBootstrapper_Expecter) ByAddress(account interface{}, cursor interface{}) *AccountTransactionsBootstrapper_ByAddress_Call { + return &AccountTransactionsBootstrapper_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *AccountTransactionsBootstrapper_ByAddress_Call) Run(run func(account flow.Address, cursor *access.AccountTransactionCursor)) *AccountTransactionsBootstrapper_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.AccountTransactionCursor + if args[1] != nil { + arg1 = args[1].(*access.AccountTransactionCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountTransactionsBootstrapper_ByAddress_Call) Return(v storage.AccountTransactionIterator, err error) *AccountTransactionsBootstrapper_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountTransactionsBootstrapper_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error)) *AccountTransactionsBootstrapper_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type AccountTransactionsBootstrapper +func (_mock *AccountTransactionsBootstrapper) FirstIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccountTransactionsBootstrapper_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type AccountTransactionsBootstrapper_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *AccountTransactionsBootstrapper_Expecter) FirstIndexedHeight() *AccountTransactionsBootstrapper_FirstIndexedHeight_Call { + return &AccountTransactionsBootstrapper_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *AccountTransactionsBootstrapper_FirstIndexedHeight_Call) Run(run func()) *AccountTransactionsBootstrapper_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccountTransactionsBootstrapper_FirstIndexedHeight_Call) Return(v uint64, err error) *AccountTransactionsBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountTransactionsBootstrapper_FirstIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *AccountTransactionsBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type AccountTransactionsBootstrapper +func (_mock *AccountTransactionsBootstrapper) LatestIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccountTransactionsBootstrapper_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type AccountTransactionsBootstrapper_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *AccountTransactionsBootstrapper_Expecter) LatestIndexedHeight() *AccountTransactionsBootstrapper_LatestIndexedHeight_Call { + return &AccountTransactionsBootstrapper_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *AccountTransactionsBootstrapper_LatestIndexedHeight_Call) Run(run func()) *AccountTransactionsBootstrapper_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccountTransactionsBootstrapper_LatestIndexedHeight_Call) Return(v uint64, err error) *AccountTransactionsBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountTransactionsBootstrapper_LatestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *AccountTransactionsBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type AccountTransactionsBootstrapper +func (_mock *AccountTransactionsBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error { + ret := _mock.Called(lctx, rw, blockHeight, txData) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.AccountTransaction) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, txData) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// AccountTransactionsBootstrapper_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type AccountTransactionsBootstrapper_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - txData []access.AccountTransaction +func (_e *AccountTransactionsBootstrapper_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, txData interface{}) *AccountTransactionsBootstrapper_Store_Call { + return &AccountTransactionsBootstrapper_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, txData)} +} + +func (_c *AccountTransactionsBootstrapper_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction)) *AccountTransactionsBootstrapper_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.AccountTransaction + if args[3] != nil { + arg3 = args[3].([]access.AccountTransaction) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *AccountTransactionsBootstrapper_Store_Call) Return(err error) *AccountTransactionsBootstrapper_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccountTransactionsBootstrapper_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error) *AccountTransactionsBootstrapper_Store_Call { + _c.Call.Return(run) + return _c +} + +// UninitializedFirstHeight provides a mock function for the type AccountTransactionsBootstrapper +func (_mock *AccountTransactionsBootstrapper) UninitializedFirstHeight() (uint64, bool) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for UninitializedFirstHeight") + } + + var r0 uint64 + var r1 bool + if returnFunc, ok := ret.Get(0).(func() (uint64, bool)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() + } else { + r1 = ret.Get(1).(bool) + } + return r0, r1 +} + +// AccountTransactionsBootstrapper_UninitializedFirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UninitializedFirstHeight' +type AccountTransactionsBootstrapper_UninitializedFirstHeight_Call struct { + *mock.Call +} + +// UninitializedFirstHeight is a helper method to define mock.On call +func (_e *AccountTransactionsBootstrapper_Expecter) UninitializedFirstHeight() *AccountTransactionsBootstrapper_UninitializedFirstHeight_Call { + return &AccountTransactionsBootstrapper_UninitializedFirstHeight_Call{Call: _e.mock.On("UninitializedFirstHeight")} +} + +func (_c *AccountTransactionsBootstrapper_UninitializedFirstHeight_Call) Run(run func()) *AccountTransactionsBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccountTransactionsBootstrapper_UninitializedFirstHeight_Call) Return(v uint64, b bool) *AccountTransactionsBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *AccountTransactionsBootstrapper_UninitializedFirstHeight_Call) RunAndReturn(run func() (uint64, bool)) *AccountTransactionsBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/account_transactions_range_reader.go b/storage/mock/account_transactions_range_reader.go new file mode 100644 index 00000000000..f3cb7a86e1d --- /dev/null +++ b/storage/mock/account_transactions_range_reader.go @@ -0,0 +1,124 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewAccountTransactionsRangeReader creates a new instance of AccountTransactionsRangeReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountTransactionsRangeReader(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountTransactionsRangeReader { + mock := &AccountTransactionsRangeReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// AccountTransactionsRangeReader is an autogenerated mock type for the AccountTransactionsRangeReader type +type AccountTransactionsRangeReader struct { + mock.Mock +} + +type AccountTransactionsRangeReader_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountTransactionsRangeReader) EXPECT() *AccountTransactionsRangeReader_Expecter { + return &AccountTransactionsRangeReader_Expecter{mock: &_m.Mock} +} + +// FirstIndexedHeight provides a mock function for the type AccountTransactionsRangeReader +func (_mock *AccountTransactionsRangeReader) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// AccountTransactionsRangeReader_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type AccountTransactionsRangeReader_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *AccountTransactionsRangeReader_Expecter) FirstIndexedHeight() *AccountTransactionsRangeReader_FirstIndexedHeight_Call { + return &AccountTransactionsRangeReader_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *AccountTransactionsRangeReader_FirstIndexedHeight_Call) Run(run func()) *AccountTransactionsRangeReader_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccountTransactionsRangeReader_FirstIndexedHeight_Call) Return(v uint64) *AccountTransactionsRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *AccountTransactionsRangeReader_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *AccountTransactionsRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type AccountTransactionsRangeReader +func (_mock *AccountTransactionsRangeReader) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// AccountTransactionsRangeReader_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type AccountTransactionsRangeReader_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *AccountTransactionsRangeReader_Expecter) LatestIndexedHeight() *AccountTransactionsRangeReader_LatestIndexedHeight_Call { + return &AccountTransactionsRangeReader_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *AccountTransactionsRangeReader_LatestIndexedHeight_Call) Run(run func()) *AccountTransactionsRangeReader_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *AccountTransactionsRangeReader_LatestIndexedHeight_Call) Return(v uint64) *AccountTransactionsRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *AccountTransactionsRangeReader_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *AccountTransactionsRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/account_transactions_reader.go b/storage/mock/account_transactions_reader.go new file mode 100644 index 00000000000..e1c2d835798 --- /dev/null +++ b/storage/mock/account_transactions_reader.go @@ -0,0 +1,107 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewAccountTransactionsReader creates a new instance of AccountTransactionsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountTransactionsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountTransactionsReader { + mock := &AccountTransactionsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// AccountTransactionsReader is an autogenerated mock type for the AccountTransactionsReader type +type AccountTransactionsReader struct { + mock.Mock +} + +type AccountTransactionsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountTransactionsReader) EXPECT() *AccountTransactionsReader_Expecter { + return &AccountTransactionsReader_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type AccountTransactionsReader +func (_mock *AccountTransactionsReader) ByAddress(account flow.Address, cursor *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.AccountTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.AccountTransactionCursor) storage.AccountTransactionIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.AccountTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.AccountTransactionCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// AccountTransactionsReader_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type AccountTransactionsReader_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.AccountTransactionCursor +func (_e *AccountTransactionsReader_Expecter) ByAddress(account interface{}, cursor interface{}) *AccountTransactionsReader_ByAddress_Call { + return &AccountTransactionsReader_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *AccountTransactionsReader_ByAddress_Call) Run(run func(account flow.Address, cursor *access.AccountTransactionCursor)) *AccountTransactionsReader_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.AccountTransactionCursor + if args[1] != nil { + arg1 = args[1].(*access.AccountTransactionCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *AccountTransactionsReader_ByAddress_Call) Return(v storage.AccountTransactionIterator, err error) *AccountTransactionsReader_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *AccountTransactionsReader_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.AccountTransactionCursor) (storage.AccountTransactionIterator, error)) *AccountTransactionsReader_ByAddress_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/account_transactions_writer.go b/storage/mock/account_transactions_writer.go new file mode 100644 index 00000000000..fe3fd017b9c --- /dev/null +++ b/storage/mock/account_transactions_writer.go @@ -0,0 +1,108 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewAccountTransactionsWriter creates a new instance of AccountTransactionsWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccountTransactionsWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *AccountTransactionsWriter { + mock := &AccountTransactionsWriter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// AccountTransactionsWriter is an autogenerated mock type for the AccountTransactionsWriter type +type AccountTransactionsWriter struct { + mock.Mock +} + +type AccountTransactionsWriter_Expecter struct { + mock *mock.Mock +} + +func (_m *AccountTransactionsWriter) EXPECT() *AccountTransactionsWriter_Expecter { + return &AccountTransactionsWriter_Expecter{mock: &_m.Mock} +} + +// Store provides a mock function for the type AccountTransactionsWriter +func (_mock *AccountTransactionsWriter) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error { + ret := _mock.Called(lctx, rw, blockHeight, txData) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.AccountTransaction) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, txData) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// AccountTransactionsWriter_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type AccountTransactionsWriter_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - txData []access.AccountTransaction +func (_e *AccountTransactionsWriter_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, txData interface{}) *AccountTransactionsWriter_Store_Call { + return &AccountTransactionsWriter_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, txData)} +} + +func (_c *AccountTransactionsWriter_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction)) *AccountTransactionsWriter_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.AccountTransaction + if args[3] != nil { + arg3 = args[3].([]access.AccountTransaction) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *AccountTransactionsWriter_Store_Call) Return(err error) *AccountTransactionsWriter_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *AccountTransactionsWriter_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, txData []access.AccountTransaction) error) *AccountTransactionsWriter_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/batch.go b/storage/mock/batch.go index 682bd456095..b25c8a7345f 100644 --- a/storage/mock/batch.go +++ b/storage/mock/batch.go @@ -1,81 +1,218 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewBatch creates a new instance of Batch. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBatch(t interface { + mock.TestingT + Cleanup(func()) +}) *Batch { + mock := &Batch{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Batch is an autogenerated mock type for the Batch type type Batch struct { mock.Mock } -// AddCallback provides a mock function with given fields: _a0 -func (_m *Batch) AddCallback(_a0 func(error)) { - _m.Called(_a0) +type Batch_Expecter struct { + mock *mock.Mock +} + +func (_m *Batch) EXPECT() *Batch_Expecter { + return &Batch_Expecter{mock: &_m.Mock} +} + +// AddCallback provides a mock function for the type Batch +func (_mock *Batch) AddCallback(fn func(error)) { + _mock.Called(fn) + return +} + +// Batch_AddCallback_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddCallback' +type Batch_AddCallback_Call struct { + *mock.Call +} + +// AddCallback is a helper method to define mock.On call +// - fn func(error) +func (_e *Batch_Expecter) AddCallback(fn interface{}) *Batch_AddCallback_Call { + return &Batch_AddCallback_Call{Call: _e.mock.On("AddCallback", fn)} +} + +func (_c *Batch_AddCallback_Call) Run(run func(fn func(error))) *Batch_AddCallback_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(error) + if args[0] != nil { + arg0 = args[0].(func(error)) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Batch_AddCallback_Call) Return() *Batch_AddCallback_Call { + _c.Call.Return() + return _c +} + +func (_c *Batch_AddCallback_Call) RunAndReturn(run func(fn func(error))) *Batch_AddCallback_Call { + _c.Run(run) + return _c } -// Close provides a mock function with no fields -func (_m *Batch) Close() error { - ret := _m.Called() +// Close provides a mock function for the type Batch +func (_mock *Batch) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// Commit provides a mock function with no fields -func (_m *Batch) Commit() error { - ret := _m.Called() +// Batch_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type Batch_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *Batch_Expecter) Close() *Batch_Close_Call { + return &Batch_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *Batch_Close_Call) Run(run func()) *Batch_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Batch_Close_Call) Return(err error) *Batch_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Batch_Close_Call) RunAndReturn(run func() error) *Batch_Close_Call { + _c.Call.Return(run) + return _c +} + +// Commit provides a mock function for the type Batch +func (_mock *Batch) Commit() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Commit") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// GlobalReader provides a mock function with no fields -func (_m *Batch) GlobalReader() storage.Reader { - ret := _m.Called() +// Batch_Commit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Commit' +type Batch_Commit_Call struct { + *mock.Call +} + +// Commit is a helper method to define mock.On call +func (_e *Batch_Expecter) Commit() *Batch_Commit_Call { + return &Batch_Commit_Call{Call: _e.mock.On("Commit")} +} + +func (_c *Batch_Commit_Call) Run(run func()) *Batch_Commit_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Batch_Commit_Call) Return(err error) *Batch_Commit_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Batch_Commit_Call) RunAndReturn(run func() error) *Batch_Commit_Call { + _c.Call.Return(run) + return _c +} + +// GlobalReader provides a mock function for the type Batch +func (_mock *Batch) GlobalReader() storage.Reader { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GlobalReader") } var r0 storage.Reader - if rf, ok := ret.Get(0).(func() storage.Reader); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.Reader); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Reader) } } - return r0 } -// ScopedValue provides a mock function with given fields: key -func (_m *Batch) ScopedValue(key string) (any, bool) { - ret := _m.Called(key) +// Batch_GlobalReader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GlobalReader' +type Batch_GlobalReader_Call struct { + *mock.Call +} + +// GlobalReader is a helper method to define mock.On call +func (_e *Batch_Expecter) GlobalReader() *Batch_GlobalReader_Call { + return &Batch_GlobalReader_Call{Call: _e.mock.On("GlobalReader")} +} + +func (_c *Batch_GlobalReader_Call) Run(run func()) *Batch_GlobalReader_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Batch_GlobalReader_Call) Return(reader storage.Reader) *Batch_GlobalReader_Call { + _c.Call.Return(reader) + return _c +} + +func (_c *Batch_GlobalReader_Call) RunAndReturn(run func() storage.Reader) *Batch_GlobalReader_Call { + _c.Call.Return(run) + return _c +} + +// ScopedValue provides a mock function for the type Batch +func (_mock *Batch) ScopedValue(key string) (any, bool) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for ScopedValue") @@ -83,61 +220,146 @@ func (_m *Batch) ScopedValue(key string) (any, bool) { var r0 any var r1 bool - if rf, ok := ret.Get(0).(func(string) (any, bool)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func(string) (any, bool)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func(string) any); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(string) any); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(any) } } - - if rf, ok := ret.Get(1).(func(string) bool); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func(string) bool); ok { + r1 = returnFunc(key) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// SetScopedValue provides a mock function with given fields: key, value -func (_m *Batch) SetScopedValue(key string, value any) { - _m.Called(key, value) +// Batch_ScopedValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScopedValue' +type Batch_ScopedValue_Call struct { + *mock.Call +} + +// ScopedValue is a helper method to define mock.On call +// - key string +func (_e *Batch_Expecter) ScopedValue(key interface{}) *Batch_ScopedValue_Call { + return &Batch_ScopedValue_Call{Call: _e.mock.On("ScopedValue", key)} +} + +func (_c *Batch_ScopedValue_Call) Run(run func(key string)) *Batch_ScopedValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Batch_ScopedValue_Call) Return(v any, b bool) *Batch_ScopedValue_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *Batch_ScopedValue_Call) RunAndReturn(run func(key string) (any, bool)) *Batch_ScopedValue_Call { + _c.Call.Return(run) + return _c +} + +// SetScopedValue provides a mock function for the type Batch +func (_mock *Batch) SetScopedValue(key string, value any) { + _mock.Called(key, value) + return +} + +// Batch_SetScopedValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetScopedValue' +type Batch_SetScopedValue_Call struct { + *mock.Call +} + +// SetScopedValue is a helper method to define mock.On call +// - key string +// - value any +func (_e *Batch_Expecter) SetScopedValue(key interface{}, value interface{}) *Batch_SetScopedValue_Call { + return &Batch_SetScopedValue_Call{Call: _e.mock.On("SetScopedValue", key, value)} } -// Writer provides a mock function with no fields -func (_m *Batch) Writer() storage.Writer { - ret := _m.Called() +func (_c *Batch_SetScopedValue_Call) Run(run func(key string, value any)) *Batch_SetScopedValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 any + if args[1] != nil { + arg1 = args[1].(any) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Batch_SetScopedValue_Call) Return() *Batch_SetScopedValue_Call { + _c.Call.Return() + return _c +} + +func (_c *Batch_SetScopedValue_Call) RunAndReturn(run func(key string, value any)) *Batch_SetScopedValue_Call { + _c.Run(run) + return _c +} + +// Writer provides a mock function for the type Batch +func (_mock *Batch) Writer() storage.Writer { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Writer") } var r0 storage.Writer - if rf, ok := ret.Get(0).(func() storage.Writer); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.Writer); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Writer) } } - return r0 } -// NewBatch creates a new instance of Batch. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBatch(t interface { - mock.TestingT - Cleanup(func()) -}) *Batch { - mock := &Batch{} - mock.Mock.Test(t) +// Batch_Writer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Writer' +type Batch_Writer_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Writer is a helper method to define mock.On call +func (_e *Batch_Expecter) Writer() *Batch_Writer_Call { + return &Batch_Writer_Call{Call: _e.mock.On("Writer")} +} - return mock +func (_c *Batch_Writer_Call) Run(run func()) *Batch_Writer_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Batch_Writer_Call) Return(writer storage.Writer) *Batch_Writer_Call { + _c.Call.Return(writer) + return _c +} + +func (_c *Batch_Writer_Call) RunAndReturn(run func() storage.Writer) *Batch_Writer_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/batch_storage.go b/storage/mock/batch_storage.go index 778593db273..88b7bf6b93e 100644 --- a/storage/mock/batch_storage.go +++ b/storage/mock/batch_storage.go @@ -1,70 +1,167 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - badger "github.com/dgraph-io/badger/v2" + "github.com/dgraph-io/badger/v2" mock "github.com/stretchr/testify/mock" ) +// NewBatchStorage creates a new instance of BatchStorage. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBatchStorage(t interface { + mock.TestingT + Cleanup(func()) +}) *BatchStorage { + mock := &BatchStorage{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // BatchStorage is an autogenerated mock type for the BatchStorage type type BatchStorage struct { mock.Mock } -// Flush provides a mock function with no fields -func (_m *BatchStorage) Flush() error { - ret := _m.Called() +type BatchStorage_Expecter struct { + mock *mock.Mock +} + +func (_m *BatchStorage) EXPECT() *BatchStorage_Expecter { + return &BatchStorage_Expecter{mock: &_m.Mock} +} + +// Flush provides a mock function for the type BatchStorage +func (_mock *BatchStorage) Flush() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Flush") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// GetWriter provides a mock function with no fields -func (_m *BatchStorage) GetWriter() *badger.WriteBatch { - ret := _m.Called() +// BatchStorage_Flush_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Flush' +type BatchStorage_Flush_Call struct { + *mock.Call +} + +// Flush is a helper method to define mock.On call +func (_e *BatchStorage_Expecter) Flush() *BatchStorage_Flush_Call { + return &BatchStorage_Flush_Call{Call: _e.mock.On("Flush")} +} + +func (_c *BatchStorage_Flush_Call) Run(run func()) *BatchStorage_Flush_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *BatchStorage_Flush_Call) Return(err error) *BatchStorage_Flush_Call { + _c.Call.Return(err) + return _c +} + +func (_c *BatchStorage_Flush_Call) RunAndReturn(run func() error) *BatchStorage_Flush_Call { + _c.Call.Return(run) + return _c +} + +// GetWriter provides a mock function for the type BatchStorage +func (_mock *BatchStorage) GetWriter() *badger.WriteBatch { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GetWriter") } var r0 *badger.WriteBatch - if rf, ok := ret.Get(0).(func() *badger.WriteBatch); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() *badger.WriteBatch); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*badger.WriteBatch) } } - return r0 } -// OnSucceed provides a mock function with given fields: callback -func (_m *BatchStorage) OnSucceed(callback func()) { - _m.Called(callback) +// BatchStorage_GetWriter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetWriter' +type BatchStorage_GetWriter_Call struct { + *mock.Call } -// NewBatchStorage creates a new instance of BatchStorage. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBatchStorage(t interface { - mock.TestingT - Cleanup(func()) -}) *BatchStorage { - mock := &BatchStorage{} - mock.Mock.Test(t) +// GetWriter is a helper method to define mock.On call +func (_e *BatchStorage_Expecter) GetWriter() *BatchStorage_GetWriter_Call { + return &BatchStorage_GetWriter_Call{Call: _e.mock.On("GetWriter")} +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +func (_c *BatchStorage_GetWriter_Call) Run(run func()) *BatchStorage_GetWriter_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} - return mock +func (_c *BatchStorage_GetWriter_Call) Return(writeBatch *badger.WriteBatch) *BatchStorage_GetWriter_Call { + _c.Call.Return(writeBatch) + return _c +} + +func (_c *BatchStorage_GetWriter_Call) RunAndReturn(run func() *badger.WriteBatch) *BatchStorage_GetWriter_Call { + _c.Call.Return(run) + return _c +} + +// OnSucceed provides a mock function for the type BatchStorage +func (_mock *BatchStorage) OnSucceed(callback func()) { + _mock.Called(callback) + return +} + +// BatchStorage_OnSucceed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OnSucceed' +type BatchStorage_OnSucceed_Call struct { + *mock.Call +} + +// OnSucceed is a helper method to define mock.On call +// - callback func() +func (_e *BatchStorage_Expecter) OnSucceed(callback interface{}) *BatchStorage_OnSucceed_Call { + return &BatchStorage_OnSucceed_Call{Call: _e.mock.On("OnSucceed", callback)} +} + +func (_c *BatchStorage_OnSucceed_Call) Run(run func(callback func())) *BatchStorage_OnSucceed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func() + if args[0] != nil { + arg0 = args[0].(func()) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *BatchStorage_OnSucceed_Call) Return() *BatchStorage_OnSucceed_Call { + _c.Call.Return() + return _c +} + +func (_c *BatchStorage_OnSucceed_Call) RunAndReturn(run func(callback func())) *BatchStorage_OnSucceed_Call { + _c.Run(run) + return _c } diff --git a/storage/mock/blocks.go b/storage/mock/blocks.go index 9beee2b80d7..946fc547ae9 100644 --- a/storage/mock/blocks.go +++ b/storage/mock/blocks.go @@ -1,60 +1,240 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewBlocks creates a new instance of Blocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlocks(t interface { + mock.TestingT + Cleanup(func()) +}) *Blocks { + mock := &Blocks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Blocks is an autogenerated mock type for the Blocks type type Blocks struct { mock.Mock } -// BatchIndexBlockContainingCollectionGuarantees provides a mock function with given fields: lctx, rw, blockID, guaranteeIDs -func (_m *Blocks) BatchIndexBlockContainingCollectionGuarantees(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, guaranteeIDs []flow.Identifier) error { - ret := _m.Called(lctx, rw, blockID, guaranteeIDs) +type Blocks_Expecter struct { + mock *mock.Mock +} + +func (_m *Blocks) EXPECT() *Blocks_Expecter { + return &Blocks_Expecter{mock: &_m.Mock} +} + +// BatchIndexBlockContainingCollectionGuarantees provides a mock function for the type Blocks +func (_mock *Blocks) BatchIndexBlockContainingCollectionGuarantees(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, guaranteeIDs []flow.Identifier) error { + ret := _mock.Called(lctx, rw, blockID, guaranteeIDs) if len(ret) == 0 { panic("no return value specified for BatchIndexBlockContainingCollectionGuarantees") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.Identifier) error); ok { - r0 = rf(lctx, rw, blockID, guaranteeIDs) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, blockID, guaranteeIDs) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: lctx, rw, proposal -func (_m *Blocks) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, proposal *flow.Proposal) error { - ret := _m.Called(lctx, rw, proposal) +// Blocks_BatchIndexBlockContainingCollectionGuarantees_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchIndexBlockContainingCollectionGuarantees' +type Blocks_BatchIndexBlockContainingCollectionGuarantees_Call struct { + *mock.Call +} + +// BatchIndexBlockContainingCollectionGuarantees is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - guaranteeIDs []flow.Identifier +func (_e *Blocks_Expecter) BatchIndexBlockContainingCollectionGuarantees(lctx interface{}, rw interface{}, blockID interface{}, guaranteeIDs interface{}) *Blocks_BatchIndexBlockContainingCollectionGuarantees_Call { + return &Blocks_BatchIndexBlockContainingCollectionGuarantees_Call{Call: _e.mock.On("BatchIndexBlockContainingCollectionGuarantees", lctx, rw, blockID, guaranteeIDs)} +} + +func (_c *Blocks_BatchIndexBlockContainingCollectionGuarantees_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, guaranteeIDs []flow.Identifier)) *Blocks_BatchIndexBlockContainingCollectionGuarantees_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 []flow.Identifier + if args[3] != nil { + arg3 = args[3].([]flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Blocks_BatchIndexBlockContainingCollectionGuarantees_Call) Return(err error) *Blocks_BatchIndexBlockContainingCollectionGuarantees_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Blocks_BatchIndexBlockContainingCollectionGuarantees_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, guaranteeIDs []flow.Identifier) error) *Blocks_BatchIndexBlockContainingCollectionGuarantees_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type Blocks +func (_mock *Blocks) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, proposal *flow.Proposal) error { + ret := _mock.Called(lctx, rw, proposal) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, *flow.Proposal) error); ok { - r0 = rf(lctx, rw, proposal) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, *flow.Proposal) error); ok { + r0 = returnFunc(lctx, rw, proposal) } else { r0 = ret.Error(0) } - return r0 } -// ByCollectionID provides a mock function with given fields: collID -func (_m *Blocks) ByCollectionID(collID flow.Identifier) (*flow.Block, error) { - ret := _m.Called(collID) +// Blocks_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type Blocks_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - proposal *flow.Proposal +func (_e *Blocks_Expecter) BatchStore(lctx interface{}, rw interface{}, proposal interface{}) *Blocks_BatchStore_Call { + return &Blocks_BatchStore_Call{Call: _e.mock.On("BatchStore", lctx, rw, proposal)} +} + +func (_c *Blocks_BatchStore_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, proposal *flow.Proposal)) *Blocks_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 *flow.Proposal + if args[2] != nil { + arg2 = args[2].(*flow.Proposal) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Blocks_BatchStore_Call) Return(err error) *Blocks_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Blocks_BatchStore_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, proposal *flow.Proposal) error) *Blocks_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// BlockIDByCollectionID provides a mock function for the type Blocks +func (_mock *Blocks) BlockIDByCollectionID(collID flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(collID) + + if len(ret) == 0 { + panic("no return value specified for BlockIDByCollectionID") + } + + var r0 flow.Identifier + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(collID) + } + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(collID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(flow.Identifier) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(collID) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// Blocks_BlockIDByCollectionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockIDByCollectionID' +type Blocks_BlockIDByCollectionID_Call struct { + *mock.Call +} + +// BlockIDByCollectionID is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *Blocks_Expecter) BlockIDByCollectionID(collID interface{}) *Blocks_BlockIDByCollectionID_Call { + return &Blocks_BlockIDByCollectionID_Call{Call: _e.mock.On("BlockIDByCollectionID", collID)} +} + +func (_c *Blocks_BlockIDByCollectionID_Call) Run(run func(collID flow.Identifier)) *Blocks_BlockIDByCollectionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_BlockIDByCollectionID_Call) Return(identifier flow.Identifier, err error) *Blocks_BlockIDByCollectionID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *Blocks_BlockIDByCollectionID_Call) RunAndReturn(run func(collID flow.Identifier) (flow.Identifier, error)) *Blocks_BlockIDByCollectionID_Call { + _c.Call.Return(run) + return _c +} + +// ByCollectionID provides a mock function for the type Blocks +func (_mock *Blocks) ByCollectionID(collID flow.Identifier) (*flow.Block, error) { + ret := _mock.Called(collID) if len(ret) == 0 { panic("no return value specified for ByCollectionID") @@ -62,29 +242,61 @@ func (_m *Blocks) ByCollectionID(collID flow.Identifier) (*flow.Block, error) { var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Block, error)); ok { - return rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Block, error)); ok { + return returnFunc(collID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Block); ok { - r0 = rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Block); ok { + r0 = returnFunc(collID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(collID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(collID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByHeight provides a mock function with given fields: height -func (_m *Blocks) ByHeight(height uint64) (*flow.Block, error) { - ret := _m.Called(height) +// Blocks_ByCollectionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByCollectionID' +type Blocks_ByCollectionID_Call struct { + *mock.Call +} + +// ByCollectionID is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *Blocks_Expecter) ByCollectionID(collID interface{}) *Blocks_ByCollectionID_Call { + return &Blocks_ByCollectionID_Call{Call: _e.mock.On("ByCollectionID", collID)} +} + +func (_c *Blocks_ByCollectionID_Call) Run(run func(collID flow.Identifier)) *Blocks_ByCollectionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_ByCollectionID_Call) Return(v *flow.Block, err error) *Blocks_ByCollectionID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Blocks_ByCollectionID_Call) RunAndReturn(run func(collID flow.Identifier) (*flow.Block, error)) *Blocks_ByCollectionID_Call { + _c.Call.Return(run) + return _c +} + +// ByHeight provides a mock function for the type Blocks +func (_mock *Blocks) ByHeight(height uint64) (*flow.Block, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for ByHeight") @@ -92,29 +304,61 @@ func (_m *Blocks) ByHeight(height uint64) (*flow.Block, error) { var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*flow.Block, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) (*flow.Block, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) *flow.Block); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) *flow.Block); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: blockID -func (_m *Blocks) ByID(blockID flow.Identifier) (*flow.Block, error) { - ret := _m.Called(blockID) +// Blocks_ByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByHeight' +type Blocks_ByHeight_Call struct { + *mock.Call +} + +// ByHeight is a helper method to define mock.On call +// - height uint64 +func (_e *Blocks_Expecter) ByHeight(height interface{}) *Blocks_ByHeight_Call { + return &Blocks_ByHeight_Call{Call: _e.mock.On("ByHeight", height)} +} + +func (_c *Blocks_ByHeight_Call) Run(run func(height uint64)) *Blocks_ByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_ByHeight_Call) Return(v *flow.Block, err error) *Blocks_ByHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Blocks_ByHeight_Call) RunAndReturn(run func(height uint64) (*flow.Block, error)) *Blocks_ByHeight_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type Blocks +func (_mock *Blocks) ByID(blockID flow.Identifier) (*flow.Block, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -122,29 +366,61 @@ func (_m *Blocks) ByID(blockID flow.Identifier) (*flow.Block, error) { var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Block, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Block, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Block); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Block); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByView provides a mock function with given fields: view -func (_m *Blocks) ByView(view uint64) (*flow.Block, error) { - ret := _m.Called(view) +// Blocks_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type Blocks_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Blocks_Expecter) ByID(blockID interface{}) *Blocks_ByID_Call { + return &Blocks_ByID_Call{Call: _e.mock.On("ByID", blockID)} +} + +func (_c *Blocks_ByID_Call) Run(run func(blockID flow.Identifier)) *Blocks_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_ByID_Call) Return(v *flow.Block, err error) *Blocks_ByID_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Blocks_ByID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.Block, error)) *Blocks_ByID_Call { + _c.Call.Return(run) + return _c +} + +// ByView provides a mock function for the type Blocks +func (_mock *Blocks) ByView(view uint64) (*flow.Block, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for ByView") @@ -152,29 +428,61 @@ func (_m *Blocks) ByView(view uint64) (*flow.Block, error) { var r0 *flow.Block var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*flow.Block, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (*flow.Block, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) *flow.Block); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) *flow.Block); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Block) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProposalByHeight provides a mock function with given fields: height -func (_m *Blocks) ProposalByHeight(height uint64) (*flow.Proposal, error) { - ret := _m.Called(height) +// Blocks_ByView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByView' +type Blocks_ByView_Call struct { + *mock.Call +} + +// ByView is a helper method to define mock.On call +// - view uint64 +func (_e *Blocks_Expecter) ByView(view interface{}) *Blocks_ByView_Call { + return &Blocks_ByView_Call{Call: _e.mock.On("ByView", view)} +} + +func (_c *Blocks_ByView_Call) Run(run func(view uint64)) *Blocks_ByView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_ByView_Call) Return(v *flow.Block, err error) *Blocks_ByView_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *Blocks_ByView_Call) RunAndReturn(run func(view uint64) (*flow.Block, error)) *Blocks_ByView_Call { + _c.Call.Return(run) + return _c +} + +// ProposalByHeight provides a mock function for the type Blocks +func (_mock *Blocks) ProposalByHeight(height uint64) (*flow.Proposal, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for ProposalByHeight") @@ -182,29 +490,61 @@ func (_m *Blocks) ProposalByHeight(height uint64) (*flow.Proposal, error) { var r0 *flow.Proposal var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*flow.Proposal, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) (*flow.Proposal, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) *flow.Proposal); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) *flow.Proposal); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Proposal) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProposalByID provides a mock function with given fields: blockID -func (_m *Blocks) ProposalByID(blockID flow.Identifier) (*flow.Proposal, error) { - ret := _m.Called(blockID) +// Blocks_ProposalByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProposalByHeight' +type Blocks_ProposalByHeight_Call struct { + *mock.Call +} + +// ProposalByHeight is a helper method to define mock.On call +// - height uint64 +func (_e *Blocks_Expecter) ProposalByHeight(height interface{}) *Blocks_ProposalByHeight_Call { + return &Blocks_ProposalByHeight_Call{Call: _e.mock.On("ProposalByHeight", height)} +} + +func (_c *Blocks_ProposalByHeight_Call) Run(run func(height uint64)) *Blocks_ProposalByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_ProposalByHeight_Call) Return(proposal *flow.Proposal, err error) *Blocks_ProposalByHeight_Call { + _c.Call.Return(proposal, err) + return _c +} + +func (_c *Blocks_ProposalByHeight_Call) RunAndReturn(run func(height uint64) (*flow.Proposal, error)) *Blocks_ProposalByHeight_Call { + _c.Call.Return(run) + return _c +} + +// ProposalByID provides a mock function for the type Blocks +func (_mock *Blocks) ProposalByID(blockID flow.Identifier) (*flow.Proposal, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ProposalByID") @@ -212,29 +552,61 @@ func (_m *Blocks) ProposalByID(blockID flow.Identifier) (*flow.Proposal, error) var r0 *flow.Proposal var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Proposal, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Proposal, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Proposal); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Proposal); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Proposal) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProposalByView provides a mock function with given fields: view -func (_m *Blocks) ProposalByView(view uint64) (*flow.Proposal, error) { - ret := _m.Called(view) +// Blocks_ProposalByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProposalByID' +type Blocks_ProposalByID_Call struct { + *mock.Call +} + +// ProposalByID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Blocks_Expecter) ProposalByID(blockID interface{}) *Blocks_ProposalByID_Call { + return &Blocks_ProposalByID_Call{Call: _e.mock.On("ProposalByID", blockID)} +} + +func (_c *Blocks_ProposalByID_Call) Run(run func(blockID flow.Identifier)) *Blocks_ProposalByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_ProposalByID_Call) Return(proposal *flow.Proposal, err error) *Blocks_ProposalByID_Call { + _c.Call.Return(proposal, err) + return _c +} + +func (_c *Blocks_ProposalByID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.Proposal, error)) *Blocks_ProposalByID_Call { + _c.Call.Return(run) + return _c +} + +// ProposalByView provides a mock function for the type Blocks +func (_mock *Blocks) ProposalByView(view uint64) (*flow.Proposal, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for ProposalByView") @@ -242,36 +614,54 @@ func (_m *Blocks) ProposalByView(view uint64) (*flow.Proposal, error) { var r0 *flow.Proposal var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*flow.Proposal, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (*flow.Proposal, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) *flow.Proposal); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) *flow.Proposal); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Proposal) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewBlocks creates a new instance of Blocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBlocks(t interface { - mock.TestingT - Cleanup(func()) -}) *Blocks { - mock := &Blocks{} - mock.Mock.Test(t) +// Blocks_ProposalByView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProposalByView' +type Blocks_ProposalByView_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ProposalByView is a helper method to define mock.On call +// - view uint64 +func (_e *Blocks_Expecter) ProposalByView(view interface{}) *Blocks_ProposalByView_Call { + return &Blocks_ProposalByView_Call{Call: _e.mock.On("ProposalByView", view)} +} - return mock +func (_c *Blocks_ProposalByView_Call) Run(run func(view uint64)) *Blocks_ProposalByView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Blocks_ProposalByView_Call) Return(proposal *flow.Proposal, err error) *Blocks_ProposalByView_Call { + _c.Call.Return(proposal, err) + return _c +} + +func (_c *Blocks_ProposalByView_Call) RunAndReturn(run func(view uint64) (*flow.Proposal, error)) *Blocks_ProposalByView_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/chunk_data_packs.go b/storage/mock/chunk_data_packs.go index 6faa2c09cd4..b681f1b5168 100644 --- a/storage/mock/chunk_data_packs.go +++ b/storage/mock/chunk_data_packs.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewChunkDataPacks creates a new instance of ChunkDataPacks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChunkDataPacks(t interface { + mock.TestingT + Cleanup(func()) +}) *ChunkDataPacks { + mock := &ChunkDataPacks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ChunkDataPacks is an autogenerated mock type for the ChunkDataPacks type type ChunkDataPacks struct { mock.Mock } -// BatchRemove provides a mock function with given fields: chunkIDs, rw -func (_m *ChunkDataPacks) BatchRemove(chunkIDs []flow.Identifier, rw storage.ReaderBatchWriter) ([]flow.Identifier, error) { - ret := _m.Called(chunkIDs, rw) +type ChunkDataPacks_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunkDataPacks) EXPECT() *ChunkDataPacks_Expecter { + return &ChunkDataPacks_Expecter{mock: &_m.Mock} +} + +// BatchRemove provides a mock function for the type ChunkDataPacks +func (_mock *ChunkDataPacks) BatchRemove(chunkIDs []flow.Identifier, rw storage.ReaderBatchWriter) ([]flow.Identifier, error) { + ret := _mock.Called(chunkIDs, rw) if len(ret) == 0 { panic("no return value specified for BatchRemove") @@ -26,47 +48,124 @@ func (_m *ChunkDataPacks) BatchRemove(chunkIDs []flow.Identifier, rw storage.Rea var r0 []flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) ([]flow.Identifier, error)); ok { - return rf(chunkIDs, rw) + if returnFunc, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) ([]flow.Identifier, error)); ok { + return returnFunc(chunkIDs, rw) } - if rf, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) []flow.Identifier); ok { - r0 = rf(chunkIDs, rw) + if returnFunc, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) []flow.Identifier); ok { + r0 = returnFunc(chunkIDs, rw) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Identifier) } } - - if rf, ok := ret.Get(1).(func([]flow.Identifier, storage.ReaderBatchWriter) error); ok { - r1 = rf(chunkIDs, rw) + if returnFunc, ok := ret.Get(1).(func([]flow.Identifier, storage.ReaderBatchWriter) error); ok { + r1 = returnFunc(chunkIDs, rw) } else { r1 = ret.Error(1) } - return r0, r1 } -// BatchRemoveChunkDataPacksOnly provides a mock function with given fields: chunkIDs, chunkDataPackBatch -func (_m *ChunkDataPacks) BatchRemoveChunkDataPacksOnly(chunkIDs []flow.Identifier, chunkDataPackBatch storage.ReaderBatchWriter) error { - ret := _m.Called(chunkIDs, chunkDataPackBatch) +// ChunkDataPacks_BatchRemove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemove' +type ChunkDataPacks_BatchRemove_Call struct { + *mock.Call +} + +// BatchRemove is a helper method to define mock.On call +// - chunkIDs []flow.Identifier +// - rw storage.ReaderBatchWriter +func (_e *ChunkDataPacks_Expecter) BatchRemove(chunkIDs interface{}, rw interface{}) *ChunkDataPacks_BatchRemove_Call { + return &ChunkDataPacks_BatchRemove_Call{Call: _e.mock.On("BatchRemove", chunkIDs, rw)} +} + +func (_c *ChunkDataPacks_BatchRemove_Call) Run(run func(chunkIDs []flow.Identifier, rw storage.ReaderBatchWriter)) *ChunkDataPacks_BatchRemove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.Identifier + if args[0] != nil { + arg0 = args[0].([]flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkDataPacks_BatchRemove_Call) Return(chunkDataPackIDs []flow.Identifier, err error) *ChunkDataPacks_BatchRemove_Call { + _c.Call.Return(chunkDataPackIDs, err) + return _c +} + +func (_c *ChunkDataPacks_BatchRemove_Call) RunAndReturn(run func(chunkIDs []flow.Identifier, rw storage.ReaderBatchWriter) ([]flow.Identifier, error)) *ChunkDataPacks_BatchRemove_Call { + _c.Call.Return(run) + return _c +} + +// BatchRemoveChunkDataPacksOnly provides a mock function for the type ChunkDataPacks +func (_mock *ChunkDataPacks) BatchRemoveChunkDataPacksOnly(chunkIDs []flow.Identifier, chunkDataPackBatch storage.ReaderBatchWriter) error { + ret := _mock.Called(chunkIDs, chunkDataPackBatch) if len(ret) == 0 { panic("no return value specified for BatchRemoveChunkDataPacksOnly") } var r0 error - if rf, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(chunkIDs, chunkDataPackBatch) + if returnFunc, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(chunkIDs, chunkDataPackBatch) } else { r0 = ret.Error(0) } - return r0 } -// ByChunkID provides a mock function with given fields: chunkID -func (_m *ChunkDataPacks) ByChunkID(chunkID flow.Identifier) (*flow.ChunkDataPack, error) { - ret := _m.Called(chunkID) +// ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemoveChunkDataPacksOnly' +type ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call struct { + *mock.Call +} + +// BatchRemoveChunkDataPacksOnly is a helper method to define mock.On call +// - chunkIDs []flow.Identifier +// - chunkDataPackBatch storage.ReaderBatchWriter +func (_e *ChunkDataPacks_Expecter) BatchRemoveChunkDataPacksOnly(chunkIDs interface{}, chunkDataPackBatch interface{}) *ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call { + return &ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call{Call: _e.mock.On("BatchRemoveChunkDataPacksOnly", chunkIDs, chunkDataPackBatch)} +} + +func (_c *ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call) Run(run func(chunkIDs []flow.Identifier, chunkDataPackBatch storage.ReaderBatchWriter)) *ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.Identifier + if args[0] != nil { + arg0 = args[0].([]flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call) Return(err error) *ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call) RunAndReturn(run func(chunkIDs []flow.Identifier, chunkDataPackBatch storage.ReaderBatchWriter) error) *ChunkDataPacks_BatchRemoveChunkDataPacksOnly_Call { + _c.Call.Return(run) + return _c +} + +// ByChunkID provides a mock function for the type ChunkDataPacks +func (_mock *ChunkDataPacks) ByChunkID(chunkID flow.Identifier) (*flow.ChunkDataPack, error) { + ret := _mock.Called(chunkID) if len(ret) == 0 { panic("no return value specified for ByChunkID") @@ -74,66 +173,116 @@ func (_m *ChunkDataPacks) ByChunkID(chunkID flow.Identifier) (*flow.ChunkDataPac var r0 *flow.ChunkDataPack var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ChunkDataPack, error)); ok { - return rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ChunkDataPack, error)); ok { + return returnFunc(chunkID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ChunkDataPack); ok { - r0 = rf(chunkID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ChunkDataPack); ok { + r0 = returnFunc(chunkID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ChunkDataPack) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(chunkID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(chunkID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Store provides a mock function with given fields: cs -func (_m *ChunkDataPacks) Store(cs []*flow.ChunkDataPack) (func(lockctx.Proof, storage.ReaderBatchWriter) error, error) { - ret := _m.Called(cs) +// ChunkDataPacks_ByChunkID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByChunkID' +type ChunkDataPacks_ByChunkID_Call struct { + *mock.Call +} + +// ByChunkID is a helper method to define mock.On call +// - chunkID flow.Identifier +func (_e *ChunkDataPacks_Expecter) ByChunkID(chunkID interface{}) *ChunkDataPacks_ByChunkID_Call { + return &ChunkDataPacks_ByChunkID_Call{Call: _e.mock.On("ByChunkID", chunkID)} +} + +func (_c *ChunkDataPacks_ByChunkID_Call) Run(run func(chunkID flow.Identifier)) *ChunkDataPacks_ByChunkID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkDataPacks_ByChunkID_Call) Return(chunkDataPack *flow.ChunkDataPack, err error) *ChunkDataPacks_ByChunkID_Call { + _c.Call.Return(chunkDataPack, err) + return _c +} + +func (_c *ChunkDataPacks_ByChunkID_Call) RunAndReturn(run func(chunkID flow.Identifier) (*flow.ChunkDataPack, error)) *ChunkDataPacks_ByChunkID_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type ChunkDataPacks +func (_mock *ChunkDataPacks) Store(cs []*flow.ChunkDataPack) (func(lctx lockctx.Proof, protocolDBBatch storage.ReaderBatchWriter) error, error) { + ret := _mock.Called(cs) if len(ret) == 0 { panic("no return value specified for Store") } - var r0 func(lockctx.Proof, storage.ReaderBatchWriter) error + var r0 func(lctx lockctx.Proof, protocolDBBatch storage.ReaderBatchWriter) error var r1 error - if rf, ok := ret.Get(0).(func([]*flow.ChunkDataPack) (func(lockctx.Proof, storage.ReaderBatchWriter) error, error)); ok { - return rf(cs) + if returnFunc, ok := ret.Get(0).(func([]*flow.ChunkDataPack) (func(lctx lockctx.Proof, protocolDBBatch storage.ReaderBatchWriter) error, error)); ok { + return returnFunc(cs) } - if rf, ok := ret.Get(0).(func([]*flow.ChunkDataPack) func(lockctx.Proof, storage.ReaderBatchWriter) error); ok { - r0 = rf(cs) + if returnFunc, ok := ret.Get(0).(func([]*flow.ChunkDataPack) func(lctx lockctx.Proof, protocolDBBatch storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(cs) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter) error) + r0 = ret.Get(0).(func(lctx lockctx.Proof, protocolDBBatch storage.ReaderBatchWriter) error) } } - - if rf, ok := ret.Get(1).(func([]*flow.ChunkDataPack) error); ok { - r1 = rf(cs) + if returnFunc, ok := ret.Get(1).(func([]*flow.ChunkDataPack) error); ok { + r1 = returnFunc(cs) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewChunkDataPacks creates a new instance of ChunkDataPacks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChunkDataPacks(t interface { - mock.TestingT - Cleanup(func()) -}) *ChunkDataPacks { - mock := &ChunkDataPacks{} - mock.Mock.Test(t) +// ChunkDataPacks_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ChunkDataPacks_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - cs []*flow.ChunkDataPack +func (_e *ChunkDataPacks_Expecter) Store(cs interface{}) *ChunkDataPacks_Store_Call { + return &ChunkDataPacks_Store_Call{Call: _e.mock.On("Store", cs)} +} - return mock +func (_c *ChunkDataPacks_Store_Call) Run(run func(cs []*flow.ChunkDataPack)) *ChunkDataPacks_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []*flow.ChunkDataPack + if args[0] != nil { + arg0 = args[0].([]*flow.ChunkDataPack) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunkDataPacks_Store_Call) Return(fn func(lctx lockctx.Proof, protocolDBBatch storage.ReaderBatchWriter) error, err error) *ChunkDataPacks_Store_Call { + _c.Call.Return(fn, err) + return _c +} + +func (_c *ChunkDataPacks_Store_Call) RunAndReturn(run func(cs []*flow.ChunkDataPack) (func(lctx lockctx.Proof, protocolDBBatch storage.ReaderBatchWriter) error, error)) *ChunkDataPacks_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/chunks_queue.go b/storage/mock/chunks_queue.go index d181f271266..ebd718a52e0 100644 --- a/storage/mock/chunks_queue.go +++ b/storage/mock/chunks_queue.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - chunks "github.com/onflow/flow-go/model/chunks" + "github.com/onflow/flow-go/model/chunks" mock "github.com/stretchr/testify/mock" ) +// NewChunksQueue creates a new instance of ChunksQueue. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewChunksQueue(t interface { + mock.TestingT + Cleanup(func()) +}) *ChunksQueue { + mock := &ChunksQueue{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ChunksQueue is an autogenerated mock type for the ChunksQueue type type ChunksQueue struct { mock.Mock } -// AtIndex provides a mock function with given fields: index -func (_m *ChunksQueue) AtIndex(index uint64) (*chunks.Locator, error) { - ret := _m.Called(index) +type ChunksQueue_Expecter struct { + mock *mock.Mock +} + +func (_m *ChunksQueue) EXPECT() *ChunksQueue_Expecter { + return &ChunksQueue_Expecter{mock: &_m.Mock} +} + +// AtIndex provides a mock function for the type ChunksQueue +func (_mock *ChunksQueue) AtIndex(index uint64) (*chunks.Locator, error) { + ret := _mock.Called(index) if len(ret) == 0 { panic("no return value specified for AtIndex") @@ -22,29 +46,61 @@ func (_m *ChunksQueue) AtIndex(index uint64) (*chunks.Locator, error) { var r0 *chunks.Locator var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*chunks.Locator, error)); ok { - return rf(index) + if returnFunc, ok := ret.Get(0).(func(uint64) (*chunks.Locator, error)); ok { + return returnFunc(index) } - if rf, ok := ret.Get(0).(func(uint64) *chunks.Locator); ok { - r0 = rf(index) + if returnFunc, ok := ret.Get(0).(func(uint64) *chunks.Locator); ok { + r0 = returnFunc(index) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*chunks.Locator) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(index) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(index) } else { r1 = ret.Error(1) } - return r0, r1 } -// LatestIndex provides a mock function with no fields -func (_m *ChunksQueue) LatestIndex() (uint64, error) { - ret := _m.Called() +// ChunksQueue_AtIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AtIndex' +type ChunksQueue_AtIndex_Call struct { + *mock.Call +} + +// AtIndex is a helper method to define mock.On call +// - index uint64 +func (_e *ChunksQueue_Expecter) AtIndex(index interface{}) *ChunksQueue_AtIndex_Call { + return &ChunksQueue_AtIndex_Call{Call: _e.mock.On("AtIndex", index)} +} + +func (_c *ChunksQueue_AtIndex_Call) Run(run func(index uint64)) *ChunksQueue_AtIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunksQueue_AtIndex_Call) Return(locator *chunks.Locator, err error) *ChunksQueue_AtIndex_Call { + _c.Call.Return(locator, err) + return _c +} + +func (_c *ChunksQueue_AtIndex_Call) RunAndReturn(run func(index uint64) (*chunks.Locator, error)) *ChunksQueue_AtIndex_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndex provides a mock function for the type ChunksQueue +func (_mock *ChunksQueue) LatestIndex() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LatestIndex") @@ -52,27 +108,52 @@ func (_m *ChunksQueue) LatestIndex() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// StoreChunkLocator provides a mock function with given fields: locator -func (_m *ChunksQueue) StoreChunkLocator(locator *chunks.Locator) (bool, error) { - ret := _m.Called(locator) +// ChunksQueue_LatestIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndex' +type ChunksQueue_LatestIndex_Call struct { + *mock.Call +} + +// LatestIndex is a helper method to define mock.On call +func (_e *ChunksQueue_Expecter) LatestIndex() *ChunksQueue_LatestIndex_Call { + return &ChunksQueue_LatestIndex_Call{Call: _e.mock.On("LatestIndex")} +} + +func (_c *ChunksQueue_LatestIndex_Call) Run(run func()) *ChunksQueue_LatestIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ChunksQueue_LatestIndex_Call) Return(v uint64, err error) *ChunksQueue_LatestIndex_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ChunksQueue_LatestIndex_Call) RunAndReturn(run func() (uint64, error)) *ChunksQueue_LatestIndex_Call { + _c.Call.Return(run) + return _c +} + +// StoreChunkLocator provides a mock function for the type ChunksQueue +func (_mock *ChunksQueue) StoreChunkLocator(locator *chunks.Locator) (bool, error) { + ret := _mock.Called(locator) if len(ret) == 0 { panic("no return value specified for StoreChunkLocator") @@ -80,34 +161,52 @@ func (_m *ChunksQueue) StoreChunkLocator(locator *chunks.Locator) (bool, error) var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(*chunks.Locator) (bool, error)); ok { - return rf(locator) + if returnFunc, ok := ret.Get(0).(func(*chunks.Locator) (bool, error)); ok { + return returnFunc(locator) } - if rf, ok := ret.Get(0).(func(*chunks.Locator) bool); ok { - r0 = rf(locator) + if returnFunc, ok := ret.Get(0).(func(*chunks.Locator) bool); ok { + r0 = returnFunc(locator) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(*chunks.Locator) error); ok { - r1 = rf(locator) + if returnFunc, ok := ret.Get(1).(func(*chunks.Locator) error); ok { + r1 = returnFunc(locator) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewChunksQueue creates a new instance of ChunksQueue. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewChunksQueue(t interface { - mock.TestingT - Cleanup(func()) -}) *ChunksQueue { - mock := &ChunksQueue{} - mock.Mock.Test(t) +// ChunksQueue_StoreChunkLocator_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StoreChunkLocator' +type ChunksQueue_StoreChunkLocator_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StoreChunkLocator is a helper method to define mock.On call +// - locator *chunks.Locator +func (_e *ChunksQueue_Expecter) StoreChunkLocator(locator interface{}) *ChunksQueue_StoreChunkLocator_Call { + return &ChunksQueue_StoreChunkLocator_Call{Call: _e.mock.On("StoreChunkLocator", locator)} +} - return mock +func (_c *ChunksQueue_StoreChunkLocator_Call) Run(run func(locator *chunks.Locator)) *ChunksQueue_StoreChunkLocator_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *chunks.Locator + if args[0] != nil { + arg0 = args[0].(*chunks.Locator) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ChunksQueue_StoreChunkLocator_Call) Return(b bool, err error) *ChunksQueue_StoreChunkLocator_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ChunksQueue_StoreChunkLocator_Call) RunAndReturn(run func(locator *chunks.Locator) (bool, error)) *ChunksQueue_StoreChunkLocator_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/cluster_blocks.go b/storage/mock/cluster_blocks.go index 12ef80c78a3..0dd2a0c083f 100644 --- a/storage/mock/cluster_blocks.go +++ b/storage/mock/cluster_blocks.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cluster "github.com/onflow/flow-go/model/cluster" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewClusterBlocks creates a new instance of ClusterBlocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewClusterBlocks(t interface { + mock.TestingT + Cleanup(func()) +}) *ClusterBlocks { + mock := &ClusterBlocks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ClusterBlocks is an autogenerated mock type for the ClusterBlocks type type ClusterBlocks struct { mock.Mock } -// ProposalByHeight provides a mock function with given fields: height -func (_m *ClusterBlocks) ProposalByHeight(height uint64) (*cluster.Proposal, error) { - ret := _m.Called(height) +type ClusterBlocks_Expecter struct { + mock *mock.Mock +} + +func (_m *ClusterBlocks) EXPECT() *ClusterBlocks_Expecter { + return &ClusterBlocks_Expecter{mock: &_m.Mock} +} + +// ProposalByHeight provides a mock function for the type ClusterBlocks +func (_mock *ClusterBlocks) ProposalByHeight(height uint64) (*cluster.Proposal, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for ProposalByHeight") @@ -24,29 +47,61 @@ func (_m *ClusterBlocks) ProposalByHeight(height uint64) (*cluster.Proposal, err var r0 *cluster.Proposal var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*cluster.Proposal, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) (*cluster.Proposal, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) *cluster.Proposal); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) *cluster.Proposal); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*cluster.Proposal) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProposalByID provides a mock function with given fields: blockID -func (_m *ClusterBlocks) ProposalByID(blockID flow.Identifier) (*cluster.Proposal, error) { - ret := _m.Called(blockID) +// ClusterBlocks_ProposalByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProposalByHeight' +type ClusterBlocks_ProposalByHeight_Call struct { + *mock.Call +} + +// ProposalByHeight is a helper method to define mock.On call +// - height uint64 +func (_e *ClusterBlocks_Expecter) ProposalByHeight(height interface{}) *ClusterBlocks_ProposalByHeight_Call { + return &ClusterBlocks_ProposalByHeight_Call{Call: _e.mock.On("ProposalByHeight", height)} +} + +func (_c *ClusterBlocks_ProposalByHeight_Call) Run(run func(height uint64)) *ClusterBlocks_ProposalByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ClusterBlocks_ProposalByHeight_Call) Return(proposal *cluster.Proposal, err error) *ClusterBlocks_ProposalByHeight_Call { + _c.Call.Return(proposal, err) + return _c +} + +func (_c *ClusterBlocks_ProposalByHeight_Call) RunAndReturn(run func(height uint64) (*cluster.Proposal, error)) *ClusterBlocks_ProposalByHeight_Call { + _c.Call.Return(run) + return _c +} + +// ProposalByID provides a mock function for the type ClusterBlocks +func (_mock *ClusterBlocks) ProposalByID(blockID flow.Identifier) (*cluster.Proposal, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ProposalByID") @@ -54,36 +109,54 @@ func (_m *ClusterBlocks) ProposalByID(blockID flow.Identifier) (*cluster.Proposa var r0 *cluster.Proposal var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*cluster.Proposal, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*cluster.Proposal, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *cluster.Proposal); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *cluster.Proposal); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*cluster.Proposal) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewClusterBlocks creates a new instance of ClusterBlocks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClusterBlocks(t interface { - mock.TestingT - Cleanup(func()) -}) *ClusterBlocks { - mock := &ClusterBlocks{} - mock.Mock.Test(t) +// ClusterBlocks_ProposalByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProposalByID' +type ClusterBlocks_ProposalByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ProposalByID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ClusterBlocks_Expecter) ProposalByID(blockID interface{}) *ClusterBlocks_ProposalByID_Call { + return &ClusterBlocks_ProposalByID_Call{Call: _e.mock.On("ProposalByID", blockID)} +} - return mock +func (_c *ClusterBlocks_ProposalByID_Call) Run(run func(blockID flow.Identifier)) *ClusterBlocks_ProposalByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ClusterBlocks_ProposalByID_Call) Return(proposal *cluster.Proposal, err error) *ClusterBlocks_ProposalByID_Call { + _c.Call.Return(proposal, err) + return _c +} + +func (_c *ClusterBlocks_ProposalByID_Call) RunAndReturn(run func(blockID flow.Identifier) (*cluster.Proposal, error)) *ClusterBlocks_ProposalByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/cluster_payloads.go b/storage/mock/cluster_payloads.go index d8db251339d..ea4e30ed158 100644 --- a/storage/mock/cluster_payloads.go +++ b/storage/mock/cluster_payloads.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - cluster "github.com/onflow/flow-go/model/cluster" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/flow-go/model/cluster" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewClusterPayloads creates a new instance of ClusterPayloads. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewClusterPayloads(t interface { + mock.TestingT + Cleanup(func()) +}) *ClusterPayloads { + mock := &ClusterPayloads{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ClusterPayloads is an autogenerated mock type for the ClusterPayloads type type ClusterPayloads struct { mock.Mock } -// ByBlockID provides a mock function with given fields: blockID -func (_m *ClusterPayloads) ByBlockID(blockID flow.Identifier) (*cluster.Payload, error) { - ret := _m.Called(blockID) +type ClusterPayloads_Expecter struct { + mock *mock.Mock +} + +func (_m *ClusterPayloads) EXPECT() *ClusterPayloads_Expecter { + return &ClusterPayloads_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type ClusterPayloads +func (_mock *ClusterPayloads) ByBlockID(blockID flow.Identifier) (*cluster.Payload, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -24,36 +47,54 @@ func (_m *ClusterPayloads) ByBlockID(blockID flow.Identifier) (*cluster.Payload, var r0 *cluster.Payload var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*cluster.Payload, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*cluster.Payload, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *cluster.Payload); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *cluster.Payload); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*cluster.Payload) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewClusterPayloads creates a new instance of ClusterPayloads. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClusterPayloads(t interface { - mock.TestingT - Cleanup(func()) -}) *ClusterPayloads { - mock := &ClusterPayloads{} - mock.Mock.Test(t) +// ClusterPayloads_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ClusterPayloads_ByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ClusterPayloads_Expecter) ByBlockID(blockID interface{}) *ClusterPayloads_ByBlockID_Call { + return &ClusterPayloads_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} - return mock +func (_c *ClusterPayloads_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *ClusterPayloads_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ClusterPayloads_ByBlockID_Call) Return(payload *cluster.Payload, err error) *ClusterPayloads_ByBlockID_Call { + _c.Call.Return(payload, err) + return _c +} + +func (_c *ClusterPayloads_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*cluster.Payload, error)) *ClusterPayloads_ByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/collections.go b/storage/mock/collections.go index 592ba5fba26..d606b250a1e 100644 --- a/storage/mock/collections.go +++ b/storage/mock/collections.go @@ -1,24 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewCollections creates a new instance of Collections. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCollections(t interface { + mock.TestingT + Cleanup(func()) +}) *Collections { + mock := &Collections{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Collections is an autogenerated mock type for the Collections type type Collections struct { mock.Mock } -// BatchStoreAndIndexByTransaction provides a mock function with given fields: lctx, collection, batch -func (_m *Collections) BatchStoreAndIndexByTransaction(lctx lockctx.Proof, collection *flow.Collection, batch storage.ReaderBatchWriter) (*flow.LightCollection, error) { - ret := _m.Called(lctx, collection, batch) +type Collections_Expecter struct { + mock *mock.Mock +} + +func (_m *Collections) EXPECT() *Collections_Expecter { + return &Collections_Expecter{mock: &_m.Mock} +} + +// BatchStoreAndIndexByTransaction provides a mock function for the type Collections +func (_mock *Collections) BatchStoreAndIndexByTransaction(lctx lockctx.Proof, collection *flow.Collection, batch storage.ReaderBatchWriter) (*flow.LightCollection, error) { + ret := _mock.Called(lctx, collection, batch) if len(ret) == 0 { panic("no return value specified for BatchStoreAndIndexByTransaction") @@ -26,29 +48,73 @@ func (_m *Collections) BatchStoreAndIndexByTransaction(lctx lockctx.Proof, colle var r0 *flow.LightCollection var r1 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection, storage.ReaderBatchWriter) (*flow.LightCollection, error)); ok { - return rf(lctx, collection, batch) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection, storage.ReaderBatchWriter) (*flow.LightCollection, error)); ok { + return returnFunc(lctx, collection, batch) } - if rf, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection, storage.ReaderBatchWriter) *flow.LightCollection); ok { - r0 = rf(lctx, collection, batch) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection, storage.ReaderBatchWriter) *flow.LightCollection); ok { + r0 = returnFunc(lctx, collection, batch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightCollection) } } - - if rf, ok := ret.Get(1).(func(lockctx.Proof, *flow.Collection, storage.ReaderBatchWriter) error); ok { - r1 = rf(lctx, collection, batch) + if returnFunc, ok := ret.Get(1).(func(lockctx.Proof, *flow.Collection, storage.ReaderBatchWriter) error); ok { + r1 = returnFunc(lctx, collection, batch) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: collID -func (_m *Collections) ByID(collID flow.Identifier) (*flow.Collection, error) { - ret := _m.Called(collID) +// Collections_BatchStoreAndIndexByTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStoreAndIndexByTransaction' +type Collections_BatchStoreAndIndexByTransaction_Call struct { + *mock.Call +} + +// BatchStoreAndIndexByTransaction is a helper method to define mock.On call +// - lctx lockctx.Proof +// - collection *flow.Collection +// - batch storage.ReaderBatchWriter +func (_e *Collections_Expecter) BatchStoreAndIndexByTransaction(lctx interface{}, collection interface{}, batch interface{}) *Collections_BatchStoreAndIndexByTransaction_Call { + return &Collections_BatchStoreAndIndexByTransaction_Call{Call: _e.mock.On("BatchStoreAndIndexByTransaction", lctx, collection, batch)} +} + +func (_c *Collections_BatchStoreAndIndexByTransaction_Call) Run(run func(lctx lockctx.Proof, collection *flow.Collection, batch storage.ReaderBatchWriter)) *Collections_BatchStoreAndIndexByTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 *flow.Collection + if args[1] != nil { + arg1 = args[1].(*flow.Collection) + } + var arg2 storage.ReaderBatchWriter + if args[2] != nil { + arg2 = args[2].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Collections_BatchStoreAndIndexByTransaction_Call) Return(lightCollection *flow.LightCollection, err error) *Collections_BatchStoreAndIndexByTransaction_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *Collections_BatchStoreAndIndexByTransaction_Call) RunAndReturn(run func(lctx lockctx.Proof, collection *flow.Collection, batch storage.ReaderBatchWriter) (*flow.LightCollection, error)) *Collections_BatchStoreAndIndexByTransaction_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type Collections +func (_mock *Collections) ByID(collID flow.Identifier) (*flow.Collection, error) { + ret := _mock.Called(collID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -56,29 +122,61 @@ func (_m *Collections) ByID(collID flow.Identifier) (*flow.Collection, error) { var r0 *flow.Collection var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Collection, error)); ok { - return rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Collection, error)); ok { + return returnFunc(collID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Collection); ok { - r0 = rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Collection); ok { + r0 = returnFunc(collID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Collection) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(collID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(collID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LightByID provides a mock function with given fields: collID -func (_m *Collections) LightByID(collID flow.Identifier) (*flow.LightCollection, error) { - ret := _m.Called(collID) +// Collections_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type Collections_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *Collections_Expecter) ByID(collID interface{}) *Collections_ByID_Call { + return &Collections_ByID_Call{Call: _e.mock.On("ByID", collID)} +} + +func (_c *Collections_ByID_Call) Run(run func(collID flow.Identifier)) *Collections_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Collections_ByID_Call) Return(collection *flow.Collection, err error) *Collections_ByID_Call { + _c.Call.Return(collection, err) + return _c +} + +func (_c *Collections_ByID_Call) RunAndReturn(run func(collID flow.Identifier) (*flow.Collection, error)) *Collections_ByID_Call { + _c.Call.Return(run) + return _c +} + +// LightByID provides a mock function for the type Collections +func (_mock *Collections) LightByID(collID flow.Identifier) (*flow.LightCollection, error) { + ret := _mock.Called(collID) if len(ret) == 0 { panic("no return value specified for LightByID") @@ -86,29 +184,61 @@ func (_m *Collections) LightByID(collID flow.Identifier) (*flow.LightCollection, var r0 *flow.LightCollection var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { - return rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { + return returnFunc(collID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { - r0 = rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { + r0 = returnFunc(collID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightCollection) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(collID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(collID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LightByTransactionID provides a mock function with given fields: txID -func (_m *Collections) LightByTransactionID(txID flow.Identifier) (*flow.LightCollection, error) { - ret := _m.Called(txID) +// Collections_LightByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LightByID' +type Collections_LightByID_Call struct { + *mock.Call +} + +// LightByID is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *Collections_Expecter) LightByID(collID interface{}) *Collections_LightByID_Call { + return &Collections_LightByID_Call{Call: _e.mock.On("LightByID", collID)} +} + +func (_c *Collections_LightByID_Call) Run(run func(collID flow.Identifier)) *Collections_LightByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Collections_LightByID_Call) Return(lightCollection *flow.LightCollection, err error) *Collections_LightByID_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *Collections_LightByID_Call) RunAndReturn(run func(collID flow.Identifier) (*flow.LightCollection, error)) *Collections_LightByID_Call { + _c.Call.Return(run) + return _c +} + +// LightByTransactionID provides a mock function for the type Collections +func (_mock *Collections) LightByTransactionID(txID flow.Identifier) (*flow.LightCollection, error) { + ret := _mock.Called(txID) if len(ret) == 0 { panic("no return value specified for LightByTransactionID") @@ -116,47 +246,112 @@ func (_m *Collections) LightByTransactionID(txID flow.Identifier) (*flow.LightCo var r0 *flow.LightCollection var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { - return rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { + return returnFunc(txID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { - r0 = rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { + r0 = returnFunc(txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightCollection) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(txID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Remove provides a mock function with given fields: collID -func (_m *Collections) Remove(collID flow.Identifier) error { - ret := _m.Called(collID) +// Collections_LightByTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LightByTransactionID' +type Collections_LightByTransactionID_Call struct { + *mock.Call +} + +// LightByTransactionID is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *Collections_Expecter) LightByTransactionID(txID interface{}) *Collections_LightByTransactionID_Call { + return &Collections_LightByTransactionID_Call{Call: _e.mock.On("LightByTransactionID", txID)} +} + +func (_c *Collections_LightByTransactionID_Call) Run(run func(txID flow.Identifier)) *Collections_LightByTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Collections_LightByTransactionID_Call) Return(lightCollection *flow.LightCollection, err error) *Collections_LightByTransactionID_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *Collections_LightByTransactionID_Call) RunAndReturn(run func(txID flow.Identifier) (*flow.LightCollection, error)) *Collections_LightByTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type Collections +func (_mock *Collections) Remove(collID flow.Identifier) error { + ret := _mock.Called(collID) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier) error); ok { - r0 = rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) error); ok { + r0 = returnFunc(collID) } else { r0 = ret.Error(0) } - return r0 } -// Store provides a mock function with given fields: collection -func (_m *Collections) Store(collection *flow.Collection) (*flow.LightCollection, error) { - ret := _m.Called(collection) +// Collections_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type Collections_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *Collections_Expecter) Remove(collID interface{}) *Collections_Remove_Call { + return &Collections_Remove_Call{Call: _e.mock.On("Remove", collID)} +} + +func (_c *Collections_Remove_Call) Run(run func(collID flow.Identifier)) *Collections_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Collections_Remove_Call) Return(err error) *Collections_Remove_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Collections_Remove_Call) RunAndReturn(run func(collID flow.Identifier) error) *Collections_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type Collections +func (_mock *Collections) Store(collection *flow.Collection) (*flow.LightCollection, error) { + ret := _mock.Called(collection) if len(ret) == 0 { panic("no return value specified for Store") @@ -164,29 +359,61 @@ func (_m *Collections) Store(collection *flow.Collection) (*flow.LightCollection var r0 *flow.LightCollection var r1 error - if rf, ok := ret.Get(0).(func(*flow.Collection) (*flow.LightCollection, error)); ok { - return rf(collection) + if returnFunc, ok := ret.Get(0).(func(*flow.Collection) (*flow.LightCollection, error)); ok { + return returnFunc(collection) } - if rf, ok := ret.Get(0).(func(*flow.Collection) *flow.LightCollection); ok { - r0 = rf(collection) + if returnFunc, ok := ret.Get(0).(func(*flow.Collection) *flow.LightCollection); ok { + r0 = returnFunc(collection) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightCollection) } } - - if rf, ok := ret.Get(1).(func(*flow.Collection) error); ok { - r1 = rf(collection) + if returnFunc, ok := ret.Get(1).(func(*flow.Collection) error); ok { + r1 = returnFunc(collection) } else { r1 = ret.Error(1) } - return r0, r1 } -// StoreAndIndexByTransaction provides a mock function with given fields: lctx, collection -func (_m *Collections) StoreAndIndexByTransaction(lctx lockctx.Proof, collection *flow.Collection) (*flow.LightCollection, error) { - ret := _m.Called(lctx, collection) +// Collections_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type Collections_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - collection *flow.Collection +func (_e *Collections_Expecter) Store(collection interface{}) *Collections_Store_Call { + return &Collections_Store_Call{Call: _e.mock.On("Store", collection)} +} + +func (_c *Collections_Store_Call) Run(run func(collection *flow.Collection)) *Collections_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Collection + if args[0] != nil { + arg0 = args[0].(*flow.Collection) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Collections_Store_Call) Return(lightCollection *flow.LightCollection, err error) *Collections_Store_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *Collections_Store_Call) RunAndReturn(run func(collection *flow.Collection) (*flow.LightCollection, error)) *Collections_Store_Call { + _c.Call.Return(run) + return _c +} + +// StoreAndIndexByTransaction provides a mock function for the type Collections +func (_mock *Collections) StoreAndIndexByTransaction(lctx lockctx.Proof, collection *flow.Collection) (*flow.LightCollection, error) { + ret := _mock.Called(lctx, collection) if len(ret) == 0 { panic("no return value specified for StoreAndIndexByTransaction") @@ -194,36 +421,60 @@ func (_m *Collections) StoreAndIndexByTransaction(lctx lockctx.Proof, collection var r0 *flow.LightCollection var r1 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection) (*flow.LightCollection, error)); ok { - return rf(lctx, collection) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection) (*flow.LightCollection, error)); ok { + return returnFunc(lctx, collection) } - if rf, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection) *flow.LightCollection); ok { - r0 = rf(lctx, collection) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, *flow.Collection) *flow.LightCollection); ok { + r0 = returnFunc(lctx, collection) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightCollection) } } - - if rf, ok := ret.Get(1).(func(lockctx.Proof, *flow.Collection) error); ok { - r1 = rf(lctx, collection) + if returnFunc, ok := ret.Get(1).(func(lockctx.Proof, *flow.Collection) error); ok { + r1 = returnFunc(lctx, collection) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewCollections creates a new instance of Collections. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCollections(t interface { - mock.TestingT - Cleanup(func()) -}) *Collections { - mock := &Collections{} - mock.Mock.Test(t) +// Collections_StoreAndIndexByTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StoreAndIndexByTransaction' +type Collections_StoreAndIndexByTransaction_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StoreAndIndexByTransaction is a helper method to define mock.On call +// - lctx lockctx.Proof +// - collection *flow.Collection +func (_e *Collections_Expecter) StoreAndIndexByTransaction(lctx interface{}, collection interface{}) *Collections_StoreAndIndexByTransaction_Call { + return &Collections_StoreAndIndexByTransaction_Call{Call: _e.mock.On("StoreAndIndexByTransaction", lctx, collection)} +} - return mock +func (_c *Collections_StoreAndIndexByTransaction_Call) Run(run func(lctx lockctx.Proof, collection *flow.Collection)) *Collections_StoreAndIndexByTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 *flow.Collection + if args[1] != nil { + arg1 = args[1].(*flow.Collection) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Collections_StoreAndIndexByTransaction_Call) Return(lightCollection *flow.LightCollection, err error) *Collections_StoreAndIndexByTransaction_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *Collections_StoreAndIndexByTransaction_Call) RunAndReturn(run func(lctx lockctx.Proof, collection *flow.Collection) (*flow.LightCollection, error)) *Collections_StoreAndIndexByTransaction_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/collections_reader.go b/storage/mock/collections_reader.go index 3a8e071d6bc..d463ac183bf 100644 --- a/storage/mock/collections_reader.go +++ b/storage/mock/collections_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewCollectionsReader creates a new instance of CollectionsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCollectionsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *CollectionsReader { + mock := &CollectionsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CollectionsReader is an autogenerated mock type for the CollectionsReader type type CollectionsReader struct { mock.Mock } -// ByID provides a mock function with given fields: collID -func (_m *CollectionsReader) ByID(collID flow.Identifier) (*flow.Collection, error) { - ret := _m.Called(collID) +type CollectionsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *CollectionsReader) EXPECT() *CollectionsReader_Expecter { + return &CollectionsReader_Expecter{mock: &_m.Mock} +} + +// ByID provides a mock function for the type CollectionsReader +func (_mock *CollectionsReader) ByID(collID flow.Identifier) (*flow.Collection, error) { + ret := _mock.Called(collID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -22,29 +46,61 @@ func (_m *CollectionsReader) ByID(collID flow.Identifier) (*flow.Collection, err var r0 *flow.Collection var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Collection, error)); ok { - return rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Collection, error)); ok { + return returnFunc(collID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Collection); ok { - r0 = rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Collection); ok { + r0 = returnFunc(collID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Collection) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(collID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(collID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LightByID provides a mock function with given fields: collID -func (_m *CollectionsReader) LightByID(collID flow.Identifier) (*flow.LightCollection, error) { - ret := _m.Called(collID) +// CollectionsReader_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type CollectionsReader_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *CollectionsReader_Expecter) ByID(collID interface{}) *CollectionsReader_ByID_Call { + return &CollectionsReader_ByID_Call{Call: _e.mock.On("ByID", collID)} +} + +func (_c *CollectionsReader_ByID_Call) Run(run func(collID flow.Identifier)) *CollectionsReader_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionsReader_ByID_Call) Return(collection *flow.Collection, err error) *CollectionsReader_ByID_Call { + _c.Call.Return(collection, err) + return _c +} + +func (_c *CollectionsReader_ByID_Call) RunAndReturn(run func(collID flow.Identifier) (*flow.Collection, error)) *CollectionsReader_ByID_Call { + _c.Call.Return(run) + return _c +} + +// LightByID provides a mock function for the type CollectionsReader +func (_mock *CollectionsReader) LightByID(collID flow.Identifier) (*flow.LightCollection, error) { + ret := _mock.Called(collID) if len(ret) == 0 { panic("no return value specified for LightByID") @@ -52,29 +108,61 @@ func (_m *CollectionsReader) LightByID(collID flow.Identifier) (*flow.LightColle var r0 *flow.LightCollection var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { - return rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { + return returnFunc(collID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { - r0 = rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { + r0 = returnFunc(collID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightCollection) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(collID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(collID) } else { r1 = ret.Error(1) } - return r0, r1 } -// LightByTransactionID provides a mock function with given fields: txID -func (_m *CollectionsReader) LightByTransactionID(txID flow.Identifier) (*flow.LightCollection, error) { - ret := _m.Called(txID) +// CollectionsReader_LightByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LightByID' +type CollectionsReader_LightByID_Call struct { + *mock.Call +} + +// LightByID is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *CollectionsReader_Expecter) LightByID(collID interface{}) *CollectionsReader_LightByID_Call { + return &CollectionsReader_LightByID_Call{Call: _e.mock.On("LightByID", collID)} +} + +func (_c *CollectionsReader_LightByID_Call) Run(run func(collID flow.Identifier)) *CollectionsReader_LightByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionsReader_LightByID_Call) Return(lightCollection *flow.LightCollection, err error) *CollectionsReader_LightByID_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *CollectionsReader_LightByID_Call) RunAndReturn(run func(collID flow.Identifier) (*flow.LightCollection, error)) *CollectionsReader_LightByID_Call { + _c.Call.Return(run) + return _c +} + +// LightByTransactionID provides a mock function for the type CollectionsReader +func (_mock *CollectionsReader) LightByTransactionID(txID flow.Identifier) (*flow.LightCollection, error) { + ret := _mock.Called(txID) if len(ret) == 0 { panic("no return value specified for LightByTransactionID") @@ -82,36 +170,54 @@ func (_m *CollectionsReader) LightByTransactionID(txID flow.Identifier) (*flow.L var r0 *flow.LightCollection var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { - return rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.LightCollection, error)); ok { + return returnFunc(txID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { - r0 = rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.LightCollection); ok { + r0 = returnFunc(txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightCollection) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(txID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewCollectionsReader creates a new instance of CollectionsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCollectionsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *CollectionsReader { - mock := &CollectionsReader{} - mock.Mock.Test(t) +// CollectionsReader_LightByTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LightByTransactionID' +type CollectionsReader_LightByTransactionID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// LightByTransactionID is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *CollectionsReader_Expecter) LightByTransactionID(txID interface{}) *CollectionsReader_LightByTransactionID_Call { + return &CollectionsReader_LightByTransactionID_Call{Call: _e.mock.On("LightByTransactionID", txID)} +} - return mock +func (_c *CollectionsReader_LightByTransactionID_Call) Run(run func(txID flow.Identifier)) *CollectionsReader_LightByTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CollectionsReader_LightByTransactionID_Call) Return(lightCollection *flow.LightCollection, err error) *CollectionsReader_LightByTransactionID_Call { + _c.Call.Return(lightCollection, err) + return _c +} + +func (_c *CollectionsReader_LightByTransactionID_Call) RunAndReturn(run func(txID flow.Identifier) (*flow.LightCollection, error)) *CollectionsReader_LightByTransactionID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/commits.go b/storage/mock/commits.go index 5d86ac4803b..3aaa849acdc 100644 --- a/storage/mock/commits.go +++ b/storage/mock/commits.go @@ -1,60 +1,172 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewCommits creates a new instance of Commits. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCommits(t interface { + mock.TestingT + Cleanup(func()) +}) *Commits { + mock := &Commits{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Commits is an autogenerated mock type for the Commits type type Commits struct { mock.Mock } -// BatchRemoveByBlockID provides a mock function with given fields: blockID, batch -func (_m *Commits) BatchRemoveByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { - ret := _m.Called(blockID, batch) +type Commits_Expecter struct { + mock *mock.Mock +} + +func (_m *Commits) EXPECT() *Commits_Expecter { + return &Commits_Expecter{mock: &_m.Mock} +} + +// BatchRemoveByBlockID provides a mock function for the type Commits +func (_mock *Commits) BatchRemoveByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(blockID, batch) if len(ret) == 0 { panic("no return value specified for BatchRemoveByBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(blockID, batch) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(blockID, batch) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: lctx, blockID, commit, batch -func (_m *Commits) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, commit flow.StateCommitment, batch storage.ReaderBatchWriter) error { - ret := _m.Called(lctx, blockID, commit, batch) +// Commits_BatchRemoveByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemoveByBlockID' +type Commits_BatchRemoveByBlockID_Call struct { + *mock.Call +} + +// BatchRemoveByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +// - batch storage.ReaderBatchWriter +func (_e *Commits_Expecter) BatchRemoveByBlockID(blockID interface{}, batch interface{}) *Commits_BatchRemoveByBlockID_Call { + return &Commits_BatchRemoveByBlockID_Call{Call: _e.mock.On("BatchRemoveByBlockID", blockID, batch)} +} + +func (_c *Commits_BatchRemoveByBlockID_Call) Run(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter)) *Commits_BatchRemoveByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Commits_BatchRemoveByBlockID_Call) Return(err error) *Commits_BatchRemoveByBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Commits_BatchRemoveByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter) error) *Commits_BatchRemoveByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type Commits +func (_mock *Commits) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, commit flow.StateCommitment, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(lctx, blockID, commit, batch) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, flow.StateCommitment, storage.ReaderBatchWriter) error); ok { - r0 = rf(lctx, blockID, commit, batch) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, flow.StateCommitment, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(lctx, blockID, commit, batch) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *Commits) ByBlockID(blockID flow.Identifier) (flow.StateCommitment, error) { - ret := _m.Called(blockID) +// Commits_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type Commits_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - lctx lockctx.Proof +// - blockID flow.Identifier +// - commit flow.StateCommitment +// - batch storage.ReaderBatchWriter +func (_e *Commits_Expecter) BatchStore(lctx interface{}, blockID interface{}, commit interface{}, batch interface{}) *Commits_BatchStore_Call { + return &Commits_BatchStore_Call{Call: _e.mock.On("BatchStore", lctx, blockID, commit, batch)} +} + +func (_c *Commits_BatchStore_Call) Run(run func(lctx lockctx.Proof, blockID flow.Identifier, commit flow.StateCommitment, batch storage.ReaderBatchWriter)) *Commits_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.StateCommitment + if args[2] != nil { + arg2 = args[2].(flow.StateCommitment) + } + var arg3 storage.ReaderBatchWriter + if args[3] != nil { + arg3 = args[3].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Commits_BatchStore_Call) Return(err error) *Commits_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Commits_BatchStore_Call) RunAndReturn(run func(lctx lockctx.Proof, blockID flow.Identifier, commit flow.StateCommitment, batch storage.ReaderBatchWriter) error) *Commits_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type Commits +func (_mock *Commits) ByBlockID(blockID flow.Identifier) (flow.StateCommitment, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -62,36 +174,54 @@ func (_m *Commits) ByBlockID(blockID flow.Identifier) (flow.StateCommitment, err var r0 flow.StateCommitment var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewCommits creates a new instance of Commits. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCommits(t interface { - mock.TestingT - Cleanup(func()) -}) *Commits { - mock := &Commits{} - mock.Mock.Test(t) +// Commits_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type Commits_ByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Commits_Expecter) ByBlockID(blockID interface{}) *Commits_ByBlockID_Call { + return &Commits_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} - return mock +func (_c *Commits_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *Commits_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Commits_ByBlockID_Call) Return(stateCommitment flow.StateCommitment, err error) *Commits_ByBlockID_Call { + _c.Call.Return(stateCommitment, err) + return _c +} + +func (_c *Commits_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.StateCommitment, error)) *Commits_ByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/commits_reader.go b/storage/mock/commits_reader.go index 4e46f3d959b..25f2cd60be6 100644 --- a/storage/mock/commits_reader.go +++ b/storage/mock/commits_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewCommitsReader creates a new instance of CommitsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCommitsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *CommitsReader { + mock := &CommitsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // CommitsReader is an autogenerated mock type for the CommitsReader type type CommitsReader struct { mock.Mock } -// ByBlockID provides a mock function with given fields: blockID -func (_m *CommitsReader) ByBlockID(blockID flow.Identifier) (flow.StateCommitment, error) { - ret := _m.Called(blockID) +type CommitsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *CommitsReader) EXPECT() *CommitsReader_Expecter { + return &CommitsReader_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type CommitsReader +func (_mock *CommitsReader) ByBlockID(blockID flow.Identifier) (flow.StateCommitment, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,36 +46,54 @@ func (_m *CommitsReader) ByBlockID(blockID flow.Identifier) (flow.StateCommitmen var r0 flow.StateCommitment var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.StateCommitment, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.StateCommitment); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewCommitsReader creates a new instance of CommitsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewCommitsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *CommitsReader { - mock := &CommitsReader{} - mock.Mock.Test(t) +// CommitsReader_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type CommitsReader_ByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *CommitsReader_Expecter) ByBlockID(blockID interface{}) *CommitsReader_ByBlockID_Call { + return &CommitsReader_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} - return mock +func (_c *CommitsReader_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *CommitsReader_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *CommitsReader_ByBlockID_Call) Return(stateCommitment flow.StateCommitment, err error) *CommitsReader_ByBlockID_Call { + _c.Call.Return(stateCommitment, err) + return _c +} + +func (_c *CommitsReader_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.StateCommitment, error)) *CommitsReader_ByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/computation_result_upload_status.go b/storage/mock/computation_result_upload_status.go index 3bd31ddb438..6ab55b2182a 100644 --- a/storage/mock/computation_result_upload_status.go +++ b/storage/mock/computation_result_upload_status.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewComputationResultUploadStatus creates a new instance of ComputationResultUploadStatus. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewComputationResultUploadStatus(t interface { + mock.TestingT + Cleanup(func()) +}) *ComputationResultUploadStatus { + mock := &ComputationResultUploadStatus{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ComputationResultUploadStatus is an autogenerated mock type for the ComputationResultUploadStatus type type ComputationResultUploadStatus struct { mock.Mock } -// ByID provides a mock function with given fields: blockID -func (_m *ComputationResultUploadStatus) ByID(blockID flow.Identifier) (bool, error) { - ret := _m.Called(blockID) +type ComputationResultUploadStatus_Expecter struct { + mock *mock.Mock +} + +func (_m *ComputationResultUploadStatus) EXPECT() *ComputationResultUploadStatus_Expecter { + return &ComputationResultUploadStatus_Expecter{mock: &_m.Mock} +} + +// ByID provides a mock function for the type ComputationResultUploadStatus +func (_mock *ComputationResultUploadStatus) ByID(blockID flow.Identifier) (bool, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -22,27 +46,59 @@ func (_m *ComputationResultUploadStatus) ByID(blockID flow.Identifier) (bool, er var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetIDsByUploadStatus provides a mock function with given fields: targetUploadStatus -func (_m *ComputationResultUploadStatus) GetIDsByUploadStatus(targetUploadStatus bool) ([]flow.Identifier, error) { - ret := _m.Called(targetUploadStatus) +// ComputationResultUploadStatus_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ComputationResultUploadStatus_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ComputationResultUploadStatus_Expecter) ByID(blockID interface{}) *ComputationResultUploadStatus_ByID_Call { + return &ComputationResultUploadStatus_ByID_Call{Call: _e.mock.On("ByID", blockID)} +} + +func (_c *ComputationResultUploadStatus_ByID_Call) Run(run func(blockID flow.Identifier)) *ComputationResultUploadStatus_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComputationResultUploadStatus_ByID_Call) Return(b bool, err error) *ComputationResultUploadStatus_ByID_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *ComputationResultUploadStatus_ByID_Call) RunAndReturn(run func(blockID flow.Identifier) (bool, error)) *ComputationResultUploadStatus_ByID_Call { + _c.Call.Return(run) + return _c +} + +// GetIDsByUploadStatus provides a mock function for the type ComputationResultUploadStatus +func (_mock *ComputationResultUploadStatus) GetIDsByUploadStatus(targetUploadStatus bool) ([]flow.Identifier, error) { + ret := _mock.Called(targetUploadStatus) if len(ret) == 0 { panic("no return value specified for GetIDsByUploadStatus") @@ -50,72 +106,162 @@ func (_m *ComputationResultUploadStatus) GetIDsByUploadStatus(targetUploadStatus var r0 []flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(bool) ([]flow.Identifier, error)); ok { - return rf(targetUploadStatus) + if returnFunc, ok := ret.Get(0).(func(bool) ([]flow.Identifier, error)); ok { + return returnFunc(targetUploadStatus) } - if rf, ok := ret.Get(0).(func(bool) []flow.Identifier); ok { - r0 = rf(targetUploadStatus) + if returnFunc, ok := ret.Get(0).(func(bool) []flow.Identifier); ok { + r0 = returnFunc(targetUploadStatus) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(bool) error); ok { - r1 = rf(targetUploadStatus) + if returnFunc, ok := ret.Get(1).(func(bool) error); ok { + r1 = returnFunc(targetUploadStatus) } else { r1 = ret.Error(1) } - return r0, r1 } -// Remove provides a mock function with given fields: blockID -func (_m *ComputationResultUploadStatus) Remove(blockID flow.Identifier) error { - ret := _m.Called(blockID) +// ComputationResultUploadStatus_GetIDsByUploadStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetIDsByUploadStatus' +type ComputationResultUploadStatus_GetIDsByUploadStatus_Call struct { + *mock.Call +} + +// GetIDsByUploadStatus is a helper method to define mock.On call +// - targetUploadStatus bool +func (_e *ComputationResultUploadStatus_Expecter) GetIDsByUploadStatus(targetUploadStatus interface{}) *ComputationResultUploadStatus_GetIDsByUploadStatus_Call { + return &ComputationResultUploadStatus_GetIDsByUploadStatus_Call{Call: _e.mock.On("GetIDsByUploadStatus", targetUploadStatus)} +} + +func (_c *ComputationResultUploadStatus_GetIDsByUploadStatus_Call) Run(run func(targetUploadStatus bool)) *ComputationResultUploadStatus_GetIDsByUploadStatus_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 bool + if args[0] != nil { + arg0 = args[0].(bool) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComputationResultUploadStatus_GetIDsByUploadStatus_Call) Return(identifiers []flow.Identifier, err error) *ComputationResultUploadStatus_GetIDsByUploadStatus_Call { + _c.Call.Return(identifiers, err) + return _c +} + +func (_c *ComputationResultUploadStatus_GetIDsByUploadStatus_Call) RunAndReturn(run func(targetUploadStatus bool) ([]flow.Identifier, error)) *ComputationResultUploadStatus_GetIDsByUploadStatus_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type ComputationResultUploadStatus +func (_mock *ComputationResultUploadStatus) Remove(blockID flow.Identifier) error { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier) error); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) error); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Error(0) } - return r0 } -// Upsert provides a mock function with given fields: blockID, wasUploadCompleted -func (_m *ComputationResultUploadStatus) Upsert(blockID flow.Identifier, wasUploadCompleted bool) error { - ret := _m.Called(blockID, wasUploadCompleted) +// ComputationResultUploadStatus_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type ComputationResultUploadStatus_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ComputationResultUploadStatus_Expecter) Remove(blockID interface{}) *ComputationResultUploadStatus_Remove_Call { + return &ComputationResultUploadStatus_Remove_Call{Call: _e.mock.On("Remove", blockID)} +} + +func (_c *ComputationResultUploadStatus_Remove_Call) Run(run func(blockID flow.Identifier)) *ComputationResultUploadStatus_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ComputationResultUploadStatus_Remove_Call) Return(err error) *ComputationResultUploadStatus_Remove_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ComputationResultUploadStatus_Remove_Call) RunAndReturn(run func(blockID flow.Identifier) error) *ComputationResultUploadStatus_Remove_Call { + _c.Call.Return(run) + return _c +} + +// Upsert provides a mock function for the type ComputationResultUploadStatus +func (_mock *ComputationResultUploadStatus) Upsert(blockID flow.Identifier, wasUploadCompleted bool) error { + ret := _mock.Called(blockID, wasUploadCompleted) if len(ret) == 0 { panic("no return value specified for Upsert") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, bool) error); ok { - r0 = rf(blockID, wasUploadCompleted) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, bool) error); ok { + r0 = returnFunc(blockID, wasUploadCompleted) } else { r0 = ret.Error(0) } - return r0 } -// NewComputationResultUploadStatus creates a new instance of ComputationResultUploadStatus. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewComputationResultUploadStatus(t interface { - mock.TestingT - Cleanup(func()) -}) *ComputationResultUploadStatus { - mock := &ComputationResultUploadStatus{} - mock.Mock.Test(t) +// ComputationResultUploadStatus_Upsert_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Upsert' +type ComputationResultUploadStatus_Upsert_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Upsert is a helper method to define mock.On call +// - blockID flow.Identifier +// - wasUploadCompleted bool +func (_e *ComputationResultUploadStatus_Expecter) Upsert(blockID interface{}, wasUploadCompleted interface{}) *ComputationResultUploadStatus_Upsert_Call { + return &ComputationResultUploadStatus_Upsert_Call{Call: _e.mock.On("Upsert", blockID, wasUploadCompleted)} +} - return mock +func (_c *ComputationResultUploadStatus_Upsert_Call) Run(run func(blockID flow.Identifier, wasUploadCompleted bool)) *ComputationResultUploadStatus_Upsert_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 bool + if args[1] != nil { + arg1 = args[1].(bool) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ComputationResultUploadStatus_Upsert_Call) Return(err error) *ComputationResultUploadStatus_Upsert_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ComputationResultUploadStatus_Upsert_Call) RunAndReturn(run func(blockID flow.Identifier, wasUploadCompleted bool) error) *ComputationResultUploadStatus_Upsert_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/consumer_progress.go b/storage/mock/consumer_progress.go index baa6a85888b..899a39cac32 100644 --- a/storage/mock/consumer_progress.go +++ b/storage/mock/consumer_progress.go @@ -1,38 +1,101 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewConsumerProgress creates a new instance of ConsumerProgress. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConsumerProgress(t interface { + mock.TestingT + Cleanup(func()) +}) *ConsumerProgress { + mock := &ConsumerProgress{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ConsumerProgress is an autogenerated mock type for the ConsumerProgress type type ConsumerProgress struct { mock.Mock } -// BatchSetProcessedIndex provides a mock function with given fields: processed, batch -func (_m *ConsumerProgress) BatchSetProcessedIndex(processed uint64, batch storage.ReaderBatchWriter) error { - ret := _m.Called(processed, batch) +type ConsumerProgress_Expecter struct { + mock *mock.Mock +} + +func (_m *ConsumerProgress) EXPECT() *ConsumerProgress_Expecter { + return &ConsumerProgress_Expecter{mock: &_m.Mock} +} + +// BatchSetProcessedIndex provides a mock function for the type ConsumerProgress +func (_mock *ConsumerProgress) BatchSetProcessedIndex(processed uint64, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(processed, batch) if len(ret) == 0 { panic("no return value specified for BatchSetProcessedIndex") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, storage.ReaderBatchWriter) error); ok { - r0 = rf(processed, batch) + if returnFunc, ok := ret.Get(0).(func(uint64, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(processed, batch) } else { r0 = ret.Error(0) } - return r0 } -// ProcessedIndex provides a mock function with no fields -func (_m *ConsumerProgress) ProcessedIndex() (uint64, error) { - ret := _m.Called() +// ConsumerProgress_BatchSetProcessedIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchSetProcessedIndex' +type ConsumerProgress_BatchSetProcessedIndex_Call struct { + *mock.Call +} + +// BatchSetProcessedIndex is a helper method to define mock.On call +// - processed uint64 +// - batch storage.ReaderBatchWriter +func (_e *ConsumerProgress_Expecter) BatchSetProcessedIndex(processed interface{}, batch interface{}) *ConsumerProgress_BatchSetProcessedIndex_Call { + return &ConsumerProgress_BatchSetProcessedIndex_Call{Call: _e.mock.On("BatchSetProcessedIndex", processed, batch)} +} + +func (_c *ConsumerProgress_BatchSetProcessedIndex_Call) Run(run func(processed uint64, batch storage.ReaderBatchWriter)) *ConsumerProgress_BatchSetProcessedIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ConsumerProgress_BatchSetProcessedIndex_Call) Return(err error) *ConsumerProgress_BatchSetProcessedIndex_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConsumerProgress_BatchSetProcessedIndex_Call) RunAndReturn(run func(processed uint64, batch storage.ReaderBatchWriter) error) *ConsumerProgress_BatchSetProcessedIndex_Call { + _c.Call.Return(run) + return _c +} + +// ProcessedIndex provides a mock function for the type ConsumerProgress +func (_mock *ConsumerProgress) ProcessedIndex() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for ProcessedIndex") @@ -40,52 +103,96 @@ func (_m *ConsumerProgress) ProcessedIndex() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// SetProcessedIndex provides a mock function with given fields: processed -func (_m *ConsumerProgress) SetProcessedIndex(processed uint64) error { - ret := _m.Called(processed) +// ConsumerProgress_ProcessedIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessedIndex' +type ConsumerProgress_ProcessedIndex_Call struct { + *mock.Call +} + +// ProcessedIndex is a helper method to define mock.On call +func (_e *ConsumerProgress_Expecter) ProcessedIndex() *ConsumerProgress_ProcessedIndex_Call { + return &ConsumerProgress_ProcessedIndex_Call{Call: _e.mock.On("ProcessedIndex")} +} + +func (_c *ConsumerProgress_ProcessedIndex_Call) Run(run func()) *ConsumerProgress_ProcessedIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ConsumerProgress_ProcessedIndex_Call) Return(v uint64, err error) *ConsumerProgress_ProcessedIndex_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ConsumerProgress_ProcessedIndex_Call) RunAndReturn(run func() (uint64, error)) *ConsumerProgress_ProcessedIndex_Call { + _c.Call.Return(run) + return _c +} + +// SetProcessedIndex provides a mock function for the type ConsumerProgress +func (_mock *ConsumerProgress) SetProcessedIndex(processed uint64) error { + ret := _mock.Called(processed) if len(ret) == 0 { panic("no return value specified for SetProcessedIndex") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(processed) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(processed) } else { r0 = ret.Error(0) } - return r0 } -// NewConsumerProgress creates a new instance of ConsumerProgress. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConsumerProgress(t interface { - mock.TestingT - Cleanup(func()) -}) *ConsumerProgress { - mock := &ConsumerProgress{} - mock.Mock.Test(t) +// ConsumerProgress_SetProcessedIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetProcessedIndex' +type ConsumerProgress_SetProcessedIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SetProcessedIndex is a helper method to define mock.On call +// - processed uint64 +func (_e *ConsumerProgress_Expecter) SetProcessedIndex(processed interface{}) *ConsumerProgress_SetProcessedIndex_Call { + return &ConsumerProgress_SetProcessedIndex_Call{Call: _e.mock.On("SetProcessedIndex", processed)} +} - return mock +func (_c *ConsumerProgress_SetProcessedIndex_Call) Run(run func(processed uint64)) *ConsumerProgress_SetProcessedIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsumerProgress_SetProcessedIndex_Call) Return(err error) *ConsumerProgress_SetProcessedIndex_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ConsumerProgress_SetProcessedIndex_Call) RunAndReturn(run func(processed uint64) error) *ConsumerProgress_SetProcessedIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/consumer_progress_initializer.go b/storage/mock/consumer_progress_initializer.go index c10c5fa778d..852bb1e9738 100644 --- a/storage/mock/consumer_progress_initializer.go +++ b/storage/mock/consumer_progress_initializer.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewConsumerProgressInitializer creates a new instance of ConsumerProgressInitializer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewConsumerProgressInitializer(t interface { + mock.TestingT + Cleanup(func()) +}) *ConsumerProgressInitializer { + mock := &ConsumerProgressInitializer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ConsumerProgressInitializer is an autogenerated mock type for the ConsumerProgressInitializer type type ConsumerProgressInitializer struct { mock.Mock } -// Initialize provides a mock function with given fields: defaultIndex -func (_m *ConsumerProgressInitializer) Initialize(defaultIndex uint64) (storage.ConsumerProgress, error) { - ret := _m.Called(defaultIndex) +type ConsumerProgressInitializer_Expecter struct { + mock *mock.Mock +} + +func (_m *ConsumerProgressInitializer) EXPECT() *ConsumerProgressInitializer_Expecter { + return &ConsumerProgressInitializer_Expecter{mock: &_m.Mock} +} + +// Initialize provides a mock function for the type ConsumerProgressInitializer +func (_mock *ConsumerProgressInitializer) Initialize(defaultIndex uint64) (storage.ConsumerProgress, error) { + ret := _mock.Called(defaultIndex) if len(ret) == 0 { panic("no return value specified for Initialize") @@ -22,36 +46,54 @@ func (_m *ConsumerProgressInitializer) Initialize(defaultIndex uint64) (storage. var r0 storage.ConsumerProgress var r1 error - if rf, ok := ret.Get(0).(func(uint64) (storage.ConsumerProgress, error)); ok { - return rf(defaultIndex) + if returnFunc, ok := ret.Get(0).(func(uint64) (storage.ConsumerProgress, error)); ok { + return returnFunc(defaultIndex) } - if rf, ok := ret.Get(0).(func(uint64) storage.ConsumerProgress); ok { - r0 = rf(defaultIndex) + if returnFunc, ok := ret.Get(0).(func(uint64) storage.ConsumerProgress); ok { + r0 = returnFunc(defaultIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.ConsumerProgress) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(defaultIndex) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(defaultIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewConsumerProgressInitializer creates a new instance of ConsumerProgressInitializer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewConsumerProgressInitializer(t interface { - mock.TestingT - Cleanup(func()) -}) *ConsumerProgressInitializer { - mock := &ConsumerProgressInitializer{} - mock.Mock.Test(t) +// ConsumerProgressInitializer_Initialize_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Initialize' +type ConsumerProgressInitializer_Initialize_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Initialize is a helper method to define mock.On call +// - defaultIndex uint64 +func (_e *ConsumerProgressInitializer_Expecter) Initialize(defaultIndex interface{}) *ConsumerProgressInitializer_Initialize_Call { + return &ConsumerProgressInitializer_Initialize_Call{Call: _e.mock.On("Initialize", defaultIndex)} +} - return mock +func (_c *ConsumerProgressInitializer_Initialize_Call) Run(run func(defaultIndex uint64)) *ConsumerProgressInitializer_Initialize_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ConsumerProgressInitializer_Initialize_Call) Return(consumerProgress storage.ConsumerProgress, err error) *ConsumerProgressInitializer_Initialize_Call { + _c.Call.Return(consumerProgress, err) + return _c +} + +func (_c *ConsumerProgressInitializer_Initialize_Call) RunAndReturn(run func(defaultIndex uint64) (storage.ConsumerProgress, error)) *ConsumerProgressInitializer_Initialize_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/contract_deployments_index.go b/storage/mock/contract_deployments_index.go new file mode 100644 index 00000000000..51770c37cf4 --- /dev/null +++ b/storage/mock/contract_deployments_index.go @@ -0,0 +1,467 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewContractDeploymentsIndex creates a new instance of ContractDeploymentsIndex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractDeploymentsIndex(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractDeploymentsIndex { + mock := &ContractDeploymentsIndex{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ContractDeploymentsIndex is an autogenerated mock type for the ContractDeploymentsIndex type +type ContractDeploymentsIndex struct { + mock.Mock +} + +type ContractDeploymentsIndex_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractDeploymentsIndex) EXPECT() *ContractDeploymentsIndex_Expecter { + return &ContractDeploymentsIndex_Expecter{mock: &_m.Mock} +} + +// All provides a mock function for the type ContractDeploymentsIndex +func (_mock *ContractDeploymentsIndex) All(cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(cursor) + + if len(ret) == 0 { + panic("no return value specified for All") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(*access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(cursor) + } + if returnFunc, ok := ret.Get(0).(func(*access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(*access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndex_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ContractDeploymentsIndex_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndex_Expecter) All(cursor interface{}) *ContractDeploymentsIndex_All_Call { + return &ContractDeploymentsIndex_All_Call{Call: _e.mock.On("All", cursor)} +} + +func (_c *ContractDeploymentsIndex_All_Call) Run(run func(cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndex_All_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.ContractDeploymentsCursor + if args[0] != nil { + arg0 = args[0].(*access.ContractDeploymentsCursor) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndex_All_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndex_All_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndex_All_Call) RunAndReturn(run func(cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndex_All_Call { + _c.Call.Return(run) + return _c +} + +// ByAddress provides a mock function for the type ContractDeploymentsIndex +func (_mock *ContractDeploymentsIndex) ByAddress(account flow.Address, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndex_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type ContractDeploymentsIndex_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndex_Expecter) ByAddress(account interface{}, cursor interface{}) *ContractDeploymentsIndex_ByAddress_Call { + return &ContractDeploymentsIndex_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *ContractDeploymentsIndex_ByAddress_Call) Run(run func(account flow.Address, cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndex_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.ContractDeploymentsCursor + if args[1] != nil { + arg1 = args[1].(*access.ContractDeploymentsCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndex_ByAddress_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndex_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndex_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndex_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// ByContract provides a mock function for the type ContractDeploymentsIndex +func (_mock *ContractDeploymentsIndex) ByContract(account flow.Address, name string) (access.ContractDeployment, error) { + ret := _mock.Called(account, name) + + if len(ret) == 0 { + panic("no return value specified for ByContract") + } + + var r0 access.ContractDeployment + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, string) (access.ContractDeployment, error)); ok { + return returnFunc(account, name) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, string) access.ContractDeployment); ok { + r0 = returnFunc(account, name) + } else { + r0 = ret.Get(0).(access.ContractDeployment) + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, string) error); ok { + r1 = returnFunc(account, name) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndex_ByContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByContract' +type ContractDeploymentsIndex_ByContract_Call struct { + *mock.Call +} + +// ByContract is a helper method to define mock.On call +// - account flow.Address +// - name string +func (_e *ContractDeploymentsIndex_Expecter) ByContract(account interface{}, name interface{}) *ContractDeploymentsIndex_ByContract_Call { + return &ContractDeploymentsIndex_ByContract_Call{Call: _e.mock.On("ByContract", account, name)} +} + +func (_c *ContractDeploymentsIndex_ByContract_Call) Run(run func(account flow.Address, name string)) *ContractDeploymentsIndex_ByContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndex_ByContract_Call) Return(contractDeployment access.ContractDeployment, err error) *ContractDeploymentsIndex_ByContract_Call { + _c.Call.Return(contractDeployment, err) + return _c +} + +func (_c *ContractDeploymentsIndex_ByContract_Call) RunAndReturn(run func(account flow.Address, name string) (access.ContractDeployment, error)) *ContractDeploymentsIndex_ByContract_Call { + _c.Call.Return(run) + return _c +} + +// DeploymentsByContract provides a mock function for the type ContractDeploymentsIndex +func (_mock *ContractDeploymentsIndex) DeploymentsByContract(account flow.Address, name string, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(account, name, cursor) + + if len(ret) == 0 { + panic("no return value specified for DeploymentsByContract") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, string, *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(account, name, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, string, *access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(account, name, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, string, *access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(account, name, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndex_DeploymentsByContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeploymentsByContract' +type ContractDeploymentsIndex_DeploymentsByContract_Call struct { + *mock.Call +} + +// DeploymentsByContract is a helper method to define mock.On call +// - account flow.Address +// - name string +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndex_Expecter) DeploymentsByContract(account interface{}, name interface{}, cursor interface{}) *ContractDeploymentsIndex_DeploymentsByContract_Call { + return &ContractDeploymentsIndex_DeploymentsByContract_Call{Call: _e.mock.On("DeploymentsByContract", account, name, cursor)} +} + +func (_c *ContractDeploymentsIndex_DeploymentsByContract_Call) Run(run func(account flow.Address, name string, cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndex_DeploymentsByContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 *access.ContractDeploymentsCursor + if args[2] != nil { + arg2 = args[2].(*access.ContractDeploymentsCursor) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndex_DeploymentsByContract_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndex_DeploymentsByContract_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndex_DeploymentsByContract_Call) RunAndReturn(run func(account flow.Address, name string, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndex_DeploymentsByContract_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type ContractDeploymentsIndex +func (_mock *ContractDeploymentsIndex) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ContractDeploymentsIndex_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type ContractDeploymentsIndex_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *ContractDeploymentsIndex_Expecter) FirstIndexedHeight() *ContractDeploymentsIndex_FirstIndexedHeight_Call { + return &ContractDeploymentsIndex_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *ContractDeploymentsIndex_FirstIndexedHeight_Call) Run(run func()) *ContractDeploymentsIndex_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractDeploymentsIndex_FirstIndexedHeight_Call) Return(v uint64) *ContractDeploymentsIndex_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ContractDeploymentsIndex_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *ContractDeploymentsIndex_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type ContractDeploymentsIndex +func (_mock *ContractDeploymentsIndex) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ContractDeploymentsIndex_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type ContractDeploymentsIndex_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *ContractDeploymentsIndex_Expecter) LatestIndexedHeight() *ContractDeploymentsIndex_LatestIndexedHeight_Call { + return &ContractDeploymentsIndex_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *ContractDeploymentsIndex_LatestIndexedHeight_Call) Run(run func()) *ContractDeploymentsIndex_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractDeploymentsIndex_LatestIndexedHeight_Call) Return(v uint64) *ContractDeploymentsIndex_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ContractDeploymentsIndex_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *ContractDeploymentsIndex_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type ContractDeploymentsIndex +func (_mock *ContractDeploymentsIndex) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment) error { + ret := _mock.Called(lctx, rw, blockHeight, deployments) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.ContractDeployment) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, deployments) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ContractDeploymentsIndex_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ContractDeploymentsIndex_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - deployments []access.ContractDeployment +func (_e *ContractDeploymentsIndex_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, deployments interface{}) *ContractDeploymentsIndex_Store_Call { + return &ContractDeploymentsIndex_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, deployments)} +} + +func (_c *ContractDeploymentsIndex_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment)) *ContractDeploymentsIndex_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.ContractDeployment + if args[3] != nil { + arg3 = args[3].([]access.ContractDeployment) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndex_Store_Call) Return(err error) *ContractDeploymentsIndex_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ContractDeploymentsIndex_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment) error) *ContractDeploymentsIndex_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/contract_deployments_index_bootstrapper.go b/storage/mock/contract_deployments_index_bootstrapper.go new file mode 100644 index 00000000000..a1b275a92a2 --- /dev/null +++ b/storage/mock/contract_deployments_index_bootstrapper.go @@ -0,0 +1,538 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewContractDeploymentsIndexBootstrapper creates a new instance of ContractDeploymentsIndexBootstrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractDeploymentsIndexBootstrapper(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractDeploymentsIndexBootstrapper { + mock := &ContractDeploymentsIndexBootstrapper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ContractDeploymentsIndexBootstrapper is an autogenerated mock type for the ContractDeploymentsIndexBootstrapper type +type ContractDeploymentsIndexBootstrapper struct { + mock.Mock +} + +type ContractDeploymentsIndexBootstrapper_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractDeploymentsIndexBootstrapper) EXPECT() *ContractDeploymentsIndexBootstrapper_Expecter { + return &ContractDeploymentsIndexBootstrapper_Expecter{mock: &_m.Mock} +} + +// All provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) All(cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(cursor) + + if len(ret) == 0 { + panic("no return value specified for All") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(*access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(cursor) + } + if returnFunc, ok := ret.Get(0).(func(*access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(*access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexBootstrapper_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ContractDeploymentsIndexBootstrapper_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) All(cursor interface{}) *ContractDeploymentsIndexBootstrapper_All_Call { + return &ContractDeploymentsIndexBootstrapper_All_Call{Call: _e.mock.On("All", cursor)} +} + +func (_c *ContractDeploymentsIndexBootstrapper_All_Call) Run(run func(cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndexBootstrapper_All_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.ContractDeploymentsCursor + if args[0] != nil { + arg0 = args[0].(*access.ContractDeploymentsCursor) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_All_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndexBootstrapper_All_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_All_Call) RunAndReturn(run func(cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndexBootstrapper_All_Call { + _c.Call.Return(run) + return _c +} + +// ByAddress provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) ByAddress(account flow.Address, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexBootstrapper_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type ContractDeploymentsIndexBootstrapper_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) ByAddress(account interface{}, cursor interface{}) *ContractDeploymentsIndexBootstrapper_ByAddress_Call { + return &ContractDeploymentsIndexBootstrapper_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *ContractDeploymentsIndexBootstrapper_ByAddress_Call) Run(run func(account flow.Address, cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndexBootstrapper_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.ContractDeploymentsCursor + if args[1] != nil { + arg1 = args[1].(*access.ContractDeploymentsCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_ByAddress_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndexBootstrapper_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndexBootstrapper_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// ByContract provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) ByContract(account flow.Address, name string) (access.ContractDeployment, error) { + ret := _mock.Called(account, name) + + if len(ret) == 0 { + panic("no return value specified for ByContract") + } + + var r0 access.ContractDeployment + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, string) (access.ContractDeployment, error)); ok { + return returnFunc(account, name) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, string) access.ContractDeployment); ok { + r0 = returnFunc(account, name) + } else { + r0 = ret.Get(0).(access.ContractDeployment) + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, string) error); ok { + r1 = returnFunc(account, name) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexBootstrapper_ByContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByContract' +type ContractDeploymentsIndexBootstrapper_ByContract_Call struct { + *mock.Call +} + +// ByContract is a helper method to define mock.On call +// - account flow.Address +// - name string +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) ByContract(account interface{}, name interface{}) *ContractDeploymentsIndexBootstrapper_ByContract_Call { + return &ContractDeploymentsIndexBootstrapper_ByContract_Call{Call: _e.mock.On("ByContract", account, name)} +} + +func (_c *ContractDeploymentsIndexBootstrapper_ByContract_Call) Run(run func(account flow.Address, name string)) *ContractDeploymentsIndexBootstrapper_ByContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_ByContract_Call) Return(contractDeployment access.ContractDeployment, err error) *ContractDeploymentsIndexBootstrapper_ByContract_Call { + _c.Call.Return(contractDeployment, err) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_ByContract_Call) RunAndReturn(run func(account flow.Address, name string) (access.ContractDeployment, error)) *ContractDeploymentsIndexBootstrapper_ByContract_Call { + _c.Call.Return(run) + return _c +} + +// DeploymentsByContract provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) DeploymentsByContract(account flow.Address, name string, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(account, name, cursor) + + if len(ret) == 0 { + panic("no return value specified for DeploymentsByContract") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, string, *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(account, name, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, string, *access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(account, name, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, string, *access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(account, name, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeploymentsByContract' +type ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call struct { + *mock.Call +} + +// DeploymentsByContract is a helper method to define mock.On call +// - account flow.Address +// - name string +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) DeploymentsByContract(account interface{}, name interface{}, cursor interface{}) *ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call { + return &ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call{Call: _e.mock.On("DeploymentsByContract", account, name, cursor)} +} + +func (_c *ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call) Run(run func(account flow.Address, name string, cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 *access.ContractDeploymentsCursor + if args[2] != nil { + arg2 = args[2].(*access.ContractDeploymentsCursor) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call) RunAndReturn(run func(account flow.Address, name string, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndexBootstrapper_DeploymentsByContract_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) FirstIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) FirstIndexedHeight() *ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call { + return &ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call) Run(run func()) *ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call) Return(v uint64, err error) *ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *ContractDeploymentsIndexBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) LatestIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) LatestIndexedHeight() *ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call { + return &ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call) Run(run func()) *ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call) Return(v uint64, err error) *ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *ContractDeploymentsIndexBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment) error { + ret := _mock.Called(lctx, rw, blockHeight, deployments) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.ContractDeployment) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, deployments) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ContractDeploymentsIndexBootstrapper_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ContractDeploymentsIndexBootstrapper_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - deployments []access.ContractDeployment +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, deployments interface{}) *ContractDeploymentsIndexBootstrapper_Store_Call { + return &ContractDeploymentsIndexBootstrapper_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, deployments)} +} + +func (_c *ContractDeploymentsIndexBootstrapper_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment)) *ContractDeploymentsIndexBootstrapper_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.ContractDeployment + if args[3] != nil { + arg3 = args[3].([]access.ContractDeployment) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_Store_Call) Return(err error) *ContractDeploymentsIndexBootstrapper_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment) error) *ContractDeploymentsIndexBootstrapper_Store_Call { + _c.Call.Return(run) + return _c +} + +// UninitializedFirstHeight provides a mock function for the type ContractDeploymentsIndexBootstrapper +func (_mock *ContractDeploymentsIndexBootstrapper) UninitializedFirstHeight() (uint64, bool) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for UninitializedFirstHeight") + } + + var r0 uint64 + var r1 bool + if returnFunc, ok := ret.Get(0).(func() (uint64, bool)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() + } else { + r1 = ret.Get(1).(bool) + } + return r0, r1 +} + +// ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UninitializedFirstHeight' +type ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call struct { + *mock.Call +} + +// UninitializedFirstHeight is a helper method to define mock.On call +func (_e *ContractDeploymentsIndexBootstrapper_Expecter) UninitializedFirstHeight() *ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call { + return &ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call{Call: _e.mock.On("UninitializedFirstHeight")} +} + +func (_c *ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call) Run(run func()) *ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call) Return(v uint64, b bool) *ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call) RunAndReturn(run func() (uint64, bool)) *ContractDeploymentsIndexBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/contract_deployments_index_range_reader.go b/storage/mock/contract_deployments_index_range_reader.go new file mode 100644 index 00000000000..a14323eca4e --- /dev/null +++ b/storage/mock/contract_deployments_index_range_reader.go @@ -0,0 +1,124 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewContractDeploymentsIndexRangeReader creates a new instance of ContractDeploymentsIndexRangeReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractDeploymentsIndexRangeReader(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractDeploymentsIndexRangeReader { + mock := &ContractDeploymentsIndexRangeReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ContractDeploymentsIndexRangeReader is an autogenerated mock type for the ContractDeploymentsIndexRangeReader type +type ContractDeploymentsIndexRangeReader struct { + mock.Mock +} + +type ContractDeploymentsIndexRangeReader_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractDeploymentsIndexRangeReader) EXPECT() *ContractDeploymentsIndexRangeReader_Expecter { + return &ContractDeploymentsIndexRangeReader_Expecter{mock: &_m.Mock} +} + +// FirstIndexedHeight provides a mock function for the type ContractDeploymentsIndexRangeReader +func (_mock *ContractDeploymentsIndexRangeReader) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *ContractDeploymentsIndexRangeReader_Expecter) FirstIndexedHeight() *ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call { + return &ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call) Run(run func()) *ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call) Return(v uint64) *ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *ContractDeploymentsIndexRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type ContractDeploymentsIndexRangeReader +func (_mock *ContractDeploymentsIndexRangeReader) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *ContractDeploymentsIndexRangeReader_Expecter) LatestIndexedHeight() *ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call { + return &ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call) Run(run func()) *ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call) Return(v uint64) *ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *ContractDeploymentsIndexRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/contract_deployments_index_reader.go b/storage/mock/contract_deployments_index_reader.go new file mode 100644 index 00000000000..b4fc35cceb2 --- /dev/null +++ b/storage/mock/contract_deployments_index_reader.go @@ -0,0 +1,309 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewContractDeploymentsIndexReader creates a new instance of ContractDeploymentsIndexReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractDeploymentsIndexReader(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractDeploymentsIndexReader { + mock := &ContractDeploymentsIndexReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ContractDeploymentsIndexReader is an autogenerated mock type for the ContractDeploymentsIndexReader type +type ContractDeploymentsIndexReader struct { + mock.Mock +} + +type ContractDeploymentsIndexReader_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractDeploymentsIndexReader) EXPECT() *ContractDeploymentsIndexReader_Expecter { + return &ContractDeploymentsIndexReader_Expecter{mock: &_m.Mock} +} + +// All provides a mock function for the type ContractDeploymentsIndexReader +func (_mock *ContractDeploymentsIndexReader) All(cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(cursor) + + if len(ret) == 0 { + panic("no return value specified for All") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(*access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(cursor) + } + if returnFunc, ok := ret.Get(0).(func(*access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(*access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexReader_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ContractDeploymentsIndexReader_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndexReader_Expecter) All(cursor interface{}) *ContractDeploymentsIndexReader_All_Call { + return &ContractDeploymentsIndexReader_All_Call{Call: _e.mock.On("All", cursor)} +} + +func (_c *ContractDeploymentsIndexReader_All_Call) Run(run func(cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndexReader_All_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.ContractDeploymentsCursor + if args[0] != nil { + arg0 = args[0].(*access.ContractDeploymentsCursor) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexReader_All_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndexReader_All_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexReader_All_Call) RunAndReturn(run func(cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndexReader_All_Call { + _c.Call.Return(run) + return _c +} + +// ByAddress provides a mock function for the type ContractDeploymentsIndexReader +func (_mock *ContractDeploymentsIndexReader) ByAddress(account flow.Address, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexReader_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type ContractDeploymentsIndexReader_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndexReader_Expecter) ByAddress(account interface{}, cursor interface{}) *ContractDeploymentsIndexReader_ByAddress_Call { + return &ContractDeploymentsIndexReader_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *ContractDeploymentsIndexReader_ByAddress_Call) Run(run func(account flow.Address, cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndexReader_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.ContractDeploymentsCursor + if args[1] != nil { + arg1 = args[1].(*access.ContractDeploymentsCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexReader_ByAddress_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndexReader_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexReader_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndexReader_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// ByContract provides a mock function for the type ContractDeploymentsIndexReader +func (_mock *ContractDeploymentsIndexReader) ByContract(account flow.Address, name string) (access.ContractDeployment, error) { + ret := _mock.Called(account, name) + + if len(ret) == 0 { + panic("no return value specified for ByContract") + } + + var r0 access.ContractDeployment + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, string) (access.ContractDeployment, error)); ok { + return returnFunc(account, name) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, string) access.ContractDeployment); ok { + r0 = returnFunc(account, name) + } else { + r0 = ret.Get(0).(access.ContractDeployment) + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, string) error); ok { + r1 = returnFunc(account, name) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexReader_ByContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByContract' +type ContractDeploymentsIndexReader_ByContract_Call struct { + *mock.Call +} + +// ByContract is a helper method to define mock.On call +// - account flow.Address +// - name string +func (_e *ContractDeploymentsIndexReader_Expecter) ByContract(account interface{}, name interface{}) *ContractDeploymentsIndexReader_ByContract_Call { + return &ContractDeploymentsIndexReader_ByContract_Call{Call: _e.mock.On("ByContract", account, name)} +} + +func (_c *ContractDeploymentsIndexReader_ByContract_Call) Run(run func(account flow.Address, name string)) *ContractDeploymentsIndexReader_ByContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexReader_ByContract_Call) Return(contractDeployment access.ContractDeployment, err error) *ContractDeploymentsIndexReader_ByContract_Call { + _c.Call.Return(contractDeployment, err) + return _c +} + +func (_c *ContractDeploymentsIndexReader_ByContract_Call) RunAndReturn(run func(account flow.Address, name string) (access.ContractDeployment, error)) *ContractDeploymentsIndexReader_ByContract_Call { + _c.Call.Return(run) + return _c +} + +// DeploymentsByContract provides a mock function for the type ContractDeploymentsIndexReader +func (_mock *ContractDeploymentsIndexReader) DeploymentsByContract(account flow.Address, name string, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error) { + ret := _mock.Called(account, name, cursor) + + if len(ret) == 0 { + panic("no return value specified for DeploymentsByContract") + } + + var r0 storage.ContractDeploymentIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, string, *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)); ok { + return returnFunc(account, name, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, string, *access.ContractDeploymentsCursor) storage.ContractDeploymentIterator); ok { + r0 = returnFunc(account, name, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ContractDeploymentIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, string, *access.ContractDeploymentsCursor) error); ok { + r1 = returnFunc(account, name, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ContractDeploymentsIndexReader_DeploymentsByContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeploymentsByContract' +type ContractDeploymentsIndexReader_DeploymentsByContract_Call struct { + *mock.Call +} + +// DeploymentsByContract is a helper method to define mock.On call +// - account flow.Address +// - name string +// - cursor *access.ContractDeploymentsCursor +func (_e *ContractDeploymentsIndexReader_Expecter) DeploymentsByContract(account interface{}, name interface{}, cursor interface{}) *ContractDeploymentsIndexReader_DeploymentsByContract_Call { + return &ContractDeploymentsIndexReader_DeploymentsByContract_Call{Call: _e.mock.On("DeploymentsByContract", account, name, cursor)} +} + +func (_c *ContractDeploymentsIndexReader_DeploymentsByContract_Call) Run(run func(account flow.Address, name string, cursor *access.ContractDeploymentsCursor)) *ContractDeploymentsIndexReader_DeploymentsByContract_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 *access.ContractDeploymentsCursor + if args[2] != nil { + arg2 = args[2].(*access.ContractDeploymentsCursor) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexReader_DeploymentsByContract_Call) Return(v storage.ContractDeploymentIterator, err error) *ContractDeploymentsIndexReader_DeploymentsByContract_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ContractDeploymentsIndexReader_DeploymentsByContract_Call) RunAndReturn(run func(account flow.Address, name string, cursor *access.ContractDeploymentsCursor) (storage.ContractDeploymentIterator, error)) *ContractDeploymentsIndexReader_DeploymentsByContract_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/contract_deployments_index_writer.go b/storage/mock/contract_deployments_index_writer.go new file mode 100644 index 00000000000..b2346c5e493 --- /dev/null +++ b/storage/mock/contract_deployments_index_writer.go @@ -0,0 +1,108 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewContractDeploymentsIndexWriter creates a new instance of ContractDeploymentsIndexWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewContractDeploymentsIndexWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *ContractDeploymentsIndexWriter { + mock := &ContractDeploymentsIndexWriter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ContractDeploymentsIndexWriter is an autogenerated mock type for the ContractDeploymentsIndexWriter type +type ContractDeploymentsIndexWriter struct { + mock.Mock +} + +type ContractDeploymentsIndexWriter_Expecter struct { + mock *mock.Mock +} + +func (_m *ContractDeploymentsIndexWriter) EXPECT() *ContractDeploymentsIndexWriter_Expecter { + return &ContractDeploymentsIndexWriter_Expecter{mock: &_m.Mock} +} + +// Store provides a mock function for the type ContractDeploymentsIndexWriter +func (_mock *ContractDeploymentsIndexWriter) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment) error { + ret := _mock.Called(lctx, rw, blockHeight, deployments) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.ContractDeployment) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, deployments) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ContractDeploymentsIndexWriter_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ContractDeploymentsIndexWriter_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - deployments []access.ContractDeployment +func (_e *ContractDeploymentsIndexWriter_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, deployments interface{}) *ContractDeploymentsIndexWriter_Store_Call { + return &ContractDeploymentsIndexWriter_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, deployments)} +} + +func (_c *ContractDeploymentsIndexWriter_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment)) *ContractDeploymentsIndexWriter_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.ContractDeployment + if args[3] != nil { + arg3 = args[3].([]access.ContractDeployment) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ContractDeploymentsIndexWriter_Store_Call) Return(err error) *ContractDeploymentsIndexWriter_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ContractDeploymentsIndexWriter_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, deployments []access.ContractDeployment) error) *ContractDeploymentsIndexWriter_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/db.go b/storage/mock/db.go index 28f8b82b536..0f318d571c2 100644 --- a/storage/mock/db.go +++ b/storage/mock/db.go @@ -1,103 +1,224 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewDB creates a new instance of DB. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDB(t interface { + mock.TestingT + Cleanup(func()) +}) *DB { + mock := &DB{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DB is an autogenerated mock type for the DB type type DB struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *DB) Close() error { - ret := _m.Called() +type DB_Expecter struct { + mock *mock.Mock +} + +func (_m *DB) EXPECT() *DB_Expecter { + return &DB_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type DB +func (_mock *DB) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// NewBatch provides a mock function with no fields -func (_m *DB) NewBatch() storage.Batch { - ret := _m.Called() +// DB_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type DB_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *DB_Expecter) Close() *DB_Close_Call { + return &DB_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *DB_Close_Call) Run(run func()) *DB_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DB_Close_Call) Return(err error) *DB_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DB_Close_Call) RunAndReturn(run func() error) *DB_Close_Call { + _c.Call.Return(run) + return _c +} + +// NewBatch provides a mock function for the type DB +func (_mock *DB) NewBatch() storage.Batch { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NewBatch") } var r0 storage.Batch - if rf, ok := ret.Get(0).(func() storage.Batch); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.Batch); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Batch) } } - return r0 } -// Reader provides a mock function with no fields -func (_m *DB) Reader() storage.Reader { - ret := _m.Called() +// DB_NewBatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewBatch' +type DB_NewBatch_Call struct { + *mock.Call +} + +// NewBatch is a helper method to define mock.On call +func (_e *DB_Expecter) NewBatch() *DB_NewBatch_Call { + return &DB_NewBatch_Call{Call: _e.mock.On("NewBatch")} +} + +func (_c *DB_NewBatch_Call) Run(run func()) *DB_NewBatch_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DB_NewBatch_Call) Return(batch storage.Batch) *DB_NewBatch_Call { + _c.Call.Return(batch) + return _c +} + +func (_c *DB_NewBatch_Call) RunAndReturn(run func() storage.Batch) *DB_NewBatch_Call { + _c.Call.Return(run) + return _c +} + +// Reader provides a mock function for the type DB +func (_mock *DB) Reader() storage.Reader { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Reader") } var r0 storage.Reader - if rf, ok := ret.Get(0).(func() storage.Reader); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.Reader); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Reader) } } - return r0 } -// WithReaderBatchWriter provides a mock function with given fields: _a0 -func (_m *DB) WithReaderBatchWriter(_a0 func(storage.ReaderBatchWriter) error) error { - ret := _m.Called(_a0) +// DB_Reader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reader' +type DB_Reader_Call struct { + *mock.Call +} + +// Reader is a helper method to define mock.On call +func (_e *DB_Expecter) Reader() *DB_Reader_Call { + return &DB_Reader_Call{Call: _e.mock.On("Reader")} +} + +func (_c *DB_Reader_Call) Run(run func()) *DB_Reader_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *DB_Reader_Call) Return(reader storage.Reader) *DB_Reader_Call { + _c.Call.Return(reader) + return _c +} + +func (_c *DB_Reader_Call) RunAndReturn(run func() storage.Reader) *DB_Reader_Call { + _c.Call.Return(run) + return _c +} + +// WithReaderBatchWriter provides a mock function for the type DB +func (_mock *DB) WithReaderBatchWriter(fn func(storage.ReaderBatchWriter) error) error { + ret := _mock.Called(fn) if len(ret) == 0 { panic("no return value specified for WithReaderBatchWriter") } var r0 error - if rf, ok := ret.Get(0).(func(func(storage.ReaderBatchWriter) error) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(func(storage.ReaderBatchWriter) error) error); ok { + r0 = returnFunc(fn) } else { r0 = ret.Error(0) } - return r0 } -// NewDB creates a new instance of DB. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDB(t interface { - mock.TestingT - Cleanup(func()) -}) *DB { - mock := &DB{} - mock.Mock.Test(t) +// DB_WithReaderBatchWriter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithReaderBatchWriter' +type DB_WithReaderBatchWriter_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// WithReaderBatchWriter is a helper method to define mock.On call +// - fn func(storage.ReaderBatchWriter) error +func (_e *DB_Expecter) WithReaderBatchWriter(fn interface{}) *DB_WithReaderBatchWriter_Call { + return &DB_WithReaderBatchWriter_Call{Call: _e.mock.On("WithReaderBatchWriter", fn)} +} - return mock +func (_c *DB_WithReaderBatchWriter_Call) Run(run func(fn func(storage.ReaderBatchWriter) error)) *DB_WithReaderBatchWriter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(storage.ReaderBatchWriter) error + if args[0] != nil { + arg0 = args[0].(func(storage.ReaderBatchWriter) error) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DB_WithReaderBatchWriter_Call) Return(err error) *DB_WithReaderBatchWriter_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DB_WithReaderBatchWriter_Call) RunAndReturn(run func(fn func(storage.ReaderBatchWriter) error) error) *DB_WithReaderBatchWriter_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/dkg_state.go b/storage/mock/dkg_state.go index 52c07058ea2..d5207c89c43 100644 --- a/storage/mock/dkg_state.go +++ b/storage/mock/dkg_state.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewDKGState creates a new instance of DKGState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGState(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGState { + mock := &DKGState{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKGState is an autogenerated mock type for the DKGState type type DKGState struct { mock.Mock } -// CommitMyBeaconPrivateKey provides a mock function with given fields: epochCounter, commit -func (_m *DKGState) CommitMyBeaconPrivateKey(epochCounter uint64, commit *flow.EpochCommit) error { - ret := _m.Called(epochCounter, commit) +type DKGState_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGState) EXPECT() *DKGState_Expecter { + return &DKGState_Expecter{mock: &_m.Mock} +} + +// CommitMyBeaconPrivateKey provides a mock function for the type DKGState +func (_mock *DKGState) CommitMyBeaconPrivateKey(epochCounter uint64, commit *flow.EpochCommit) error { + ret := _mock.Called(epochCounter, commit) if len(ret) == 0 { panic("no return value specified for CommitMyBeaconPrivateKey") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, *flow.EpochCommit) error); ok { - r0 = rf(epochCounter, commit) + if returnFunc, ok := ret.Get(0).(func(uint64, *flow.EpochCommit) error); ok { + r0 = returnFunc(epochCounter, commit) } else { r0 = ret.Error(0) } - return r0 } -// GetDKGState provides a mock function with given fields: epochCounter -func (_m *DKGState) GetDKGState(epochCounter uint64) (flow.DKGState, error) { - ret := _m.Called(epochCounter) +// DKGState_CommitMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CommitMyBeaconPrivateKey' +type DKGState_CommitMyBeaconPrivateKey_Call struct { + *mock.Call +} + +// CommitMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +// - commit *flow.EpochCommit +func (_e *DKGState_Expecter) CommitMyBeaconPrivateKey(epochCounter interface{}, commit interface{}) *DKGState_CommitMyBeaconPrivateKey_Call { + return &DKGState_CommitMyBeaconPrivateKey_Call{Call: _e.mock.On("CommitMyBeaconPrivateKey", epochCounter, commit)} +} + +func (_c *DKGState_CommitMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64, commit *flow.EpochCommit)) *DKGState_CommitMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 *flow.EpochCommit + if args[1] != nil { + arg1 = args[1].(*flow.EpochCommit) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGState_CommitMyBeaconPrivateKey_Call) Return(err error) *DKGState_CommitMyBeaconPrivateKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_CommitMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64, commit *flow.EpochCommit) error) *DKGState_CommitMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// GetDKGState provides a mock function for the type DKGState +func (_mock *DKGState) GetDKGState(epochCounter uint64) (flow.DKGState, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for GetDKGState") @@ -42,45 +104,116 @@ func (_m *DKGState) GetDKGState(epochCounter uint64) (flow.DKGState, error) { var r0 flow.DKGState var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.DKGState, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.DKGState, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) flow.DKGState); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.DKGState); ok { + r0 = returnFunc(epochCounter) } else { r0 = ret.Get(0).(flow.DKGState) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// InsertMyBeaconPrivateKey provides a mock function with given fields: epochCounter, key -func (_m *DKGState) InsertMyBeaconPrivateKey(epochCounter uint64, key crypto.PrivateKey) error { - ret := _m.Called(epochCounter, key) +// DKGState_GetDKGState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetDKGState' +type DKGState_GetDKGState_Call struct { + *mock.Call +} + +// GetDKGState is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGState_Expecter) GetDKGState(epochCounter interface{}) *DKGState_GetDKGState_Call { + return &DKGState_GetDKGState_Call{Call: _e.mock.On("GetDKGState", epochCounter)} +} + +func (_c *DKGState_GetDKGState_Call) Run(run func(epochCounter uint64)) *DKGState_GetDKGState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGState_GetDKGState_Call) Return(dKGState flow.DKGState, err error) *DKGState_GetDKGState_Call { + _c.Call.Return(dKGState, err) + return _c +} + +func (_c *DKGState_GetDKGState_Call) RunAndReturn(run func(epochCounter uint64) (flow.DKGState, error)) *DKGState_GetDKGState_Call { + _c.Call.Return(run) + return _c +} + +// InsertMyBeaconPrivateKey provides a mock function for the type DKGState +func (_mock *DKGState) InsertMyBeaconPrivateKey(epochCounter uint64, key crypto.PrivateKey) error { + ret := _mock.Called(epochCounter, key) if len(ret) == 0 { panic("no return value specified for InsertMyBeaconPrivateKey") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, crypto.PrivateKey) error); ok { - r0 = rf(epochCounter, key) + if returnFunc, ok := ret.Get(0).(func(uint64, crypto.PrivateKey) error); ok { + r0 = returnFunc(epochCounter, key) } else { r0 = ret.Error(0) } - return r0 } -// IsDKGStarted provides a mock function with given fields: epochCounter -func (_m *DKGState) IsDKGStarted(epochCounter uint64) (bool, error) { - ret := _m.Called(epochCounter) +// DKGState_InsertMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InsertMyBeaconPrivateKey' +type DKGState_InsertMyBeaconPrivateKey_Call struct { + *mock.Call +} + +// InsertMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +// - key crypto.PrivateKey +func (_e *DKGState_Expecter) InsertMyBeaconPrivateKey(epochCounter interface{}, key interface{}) *DKGState_InsertMyBeaconPrivateKey_Call { + return &DKGState_InsertMyBeaconPrivateKey_Call{Call: _e.mock.On("InsertMyBeaconPrivateKey", epochCounter, key)} +} + +func (_c *DKGState_InsertMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64, key crypto.PrivateKey)) *DKGState_InsertMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 crypto.PrivateKey + if args[1] != nil { + arg1 = args[1].(crypto.PrivateKey) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGState_InsertMyBeaconPrivateKey_Call) Return(err error) *DKGState_InsertMyBeaconPrivateKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_InsertMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64, key crypto.PrivateKey) error) *DKGState_InsertMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// IsDKGStarted provides a mock function for the type DKGState +func (_mock *DKGState) IsDKGStarted(epochCounter uint64) (bool, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for IsDKGStarted") @@ -88,27 +221,59 @@ func (_m *DKGState) IsDKGStarted(epochCounter uint64) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64) (bool, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (bool, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) bool); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) bool); ok { + r0 = returnFunc(epochCounter) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// RetrieveMyBeaconPrivateKey provides a mock function with given fields: epochCounter -func (_m *DKGState) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { - ret := _m.Called(epochCounter) +// DKGState_IsDKGStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsDKGStarted' +type DKGState_IsDKGStarted_Call struct { + *mock.Call +} + +// IsDKGStarted is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGState_Expecter) IsDKGStarted(epochCounter interface{}) *DKGState_IsDKGStarted_Call { + return &DKGState_IsDKGStarted_Call{Call: _e.mock.On("IsDKGStarted", epochCounter)} +} + +func (_c *DKGState_IsDKGStarted_Call) Run(run func(epochCounter uint64)) *DKGState_IsDKGStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGState_IsDKGStarted_Call) Return(b bool, err error) *DKGState_IsDKGStarted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *DKGState_IsDKGStarted_Call) RunAndReturn(run func(epochCounter uint64) (bool, error)) *DKGState_IsDKGStarted_Call { + _c.Call.Return(run) + return _c +} + +// RetrieveMyBeaconPrivateKey provides a mock function for the type DKGState +func (_mock *DKGState) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for RetrieveMyBeaconPrivateKey") @@ -117,53 +282,123 @@ func (_m *DKGState) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.Priv var r0 crypto.PrivateKey var r1 bool var r2 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(epochCounter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(epochCounter) + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(epochCounter) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// SetDKGState provides a mock function with given fields: epochCounter, newState -func (_m *DKGState) SetDKGState(epochCounter uint64, newState flow.DKGState) error { - ret := _m.Called(epochCounter, newState) +// DKGState_RetrieveMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RetrieveMyBeaconPrivateKey' +type DKGState_RetrieveMyBeaconPrivateKey_Call struct { + *mock.Call +} + +// RetrieveMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGState_Expecter) RetrieveMyBeaconPrivateKey(epochCounter interface{}) *DKGState_RetrieveMyBeaconPrivateKey_Call { + return &DKGState_RetrieveMyBeaconPrivateKey_Call{Call: _e.mock.On("RetrieveMyBeaconPrivateKey", epochCounter)} +} + +func (_c *DKGState_RetrieveMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64)) *DKGState_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGState_RetrieveMyBeaconPrivateKey_Call) Return(key crypto.PrivateKey, safe bool, err error) *DKGState_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(key, safe, err) + return _c +} + +func (_c *DKGState_RetrieveMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64) (crypto.PrivateKey, bool, error)) *DKGState_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// SetDKGState provides a mock function for the type DKGState +func (_mock *DKGState) SetDKGState(epochCounter uint64, newState flow.DKGState) error { + ret := _mock.Called(epochCounter, newState) if len(ret) == 0 { panic("no return value specified for SetDKGState") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, flow.DKGState) error); ok { - r0 = rf(epochCounter, newState) + if returnFunc, ok := ret.Get(0).(func(uint64, flow.DKGState) error); ok { + r0 = returnFunc(epochCounter, newState) } else { r0 = ret.Error(0) } - return r0 } -// UnsafeRetrieveMyBeaconPrivateKey provides a mock function with given fields: epochCounter -func (_m *DKGState) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, error) { - ret := _m.Called(epochCounter) +// DKGState_SetDKGState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetDKGState' +type DKGState_SetDKGState_Call struct { + *mock.Call +} + +// SetDKGState is a helper method to define mock.On call +// - epochCounter uint64 +// - newState flow.DKGState +func (_e *DKGState_Expecter) SetDKGState(epochCounter interface{}, newState interface{}) *DKGState_SetDKGState_Call { + return &DKGState_SetDKGState_Call{Call: _e.mock.On("SetDKGState", epochCounter, newState)} +} + +func (_c *DKGState_SetDKGState_Call) Run(run func(epochCounter uint64, newState flow.DKGState)) *DKGState_SetDKGState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 flow.DKGState + if args[1] != nil { + arg1 = args[1].(flow.DKGState) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *DKGState_SetDKGState_Call) Return(err error) *DKGState_SetDKGState_Call { + _c.Call.Return(err) + return _c +} + +func (_c *DKGState_SetDKGState_Call) RunAndReturn(run func(epochCounter uint64, newState flow.DKGState) error) *DKGState_SetDKGState_Call { + _c.Call.Return(run) + return _c +} + +// UnsafeRetrieveMyBeaconPrivateKey provides a mock function for the type DKGState +func (_mock *DKGState) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for UnsafeRetrieveMyBeaconPrivateKey") @@ -171,36 +406,54 @@ func (_m *DKGState) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) (crypt var r0 crypto.PrivateKey var r1 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(epochCounter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewDKGState creates a new instance of DKGState. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGState(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGState { - mock := &DKGState{} - mock.Mock.Test(t) +// DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnsafeRetrieveMyBeaconPrivateKey' +type DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UnsafeRetrieveMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGState_Expecter) UnsafeRetrieveMyBeaconPrivateKey(epochCounter interface{}) *DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call { + return &DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call{Call: _e.mock.On("UnsafeRetrieveMyBeaconPrivateKey", epochCounter)} +} - return mock +func (_c *DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64)) *DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call) Return(privateKey crypto.PrivateKey, err error) *DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(privateKey, err) + return _c +} + +func (_c *DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64) (crypto.PrivateKey, error)) *DKGState_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/dkg_state_reader.go b/storage/mock/dkg_state_reader.go index 622b50470d0..a171939df3c 100644 --- a/storage/mock/dkg_state_reader.go +++ b/storage/mock/dkg_state_reader.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewDKGStateReader creates a new instance of DKGStateReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewDKGStateReader(t interface { + mock.TestingT + Cleanup(func()) +}) *DKGStateReader { + mock := &DKGStateReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // DKGStateReader is an autogenerated mock type for the DKGStateReader type type DKGStateReader struct { mock.Mock } -// GetDKGState provides a mock function with given fields: epochCounter -func (_m *DKGStateReader) GetDKGState(epochCounter uint64) (flow.DKGState, error) { - ret := _m.Called(epochCounter) +type DKGStateReader_Expecter struct { + mock *mock.Mock +} + +func (_m *DKGStateReader) EXPECT() *DKGStateReader_Expecter { + return &DKGStateReader_Expecter{mock: &_m.Mock} +} + +// GetDKGState provides a mock function for the type DKGStateReader +func (_mock *DKGStateReader) GetDKGState(epochCounter uint64) (flow.DKGState, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for GetDKGState") @@ -24,27 +47,59 @@ func (_m *DKGStateReader) GetDKGState(epochCounter uint64) (flow.DKGState, error var r0 flow.DKGState var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.DKGState, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.DKGState, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) flow.DKGState); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.DKGState); ok { + r0 = returnFunc(epochCounter) } else { r0 = ret.Get(0).(flow.DKGState) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// IsDKGStarted provides a mock function with given fields: epochCounter -func (_m *DKGStateReader) IsDKGStarted(epochCounter uint64) (bool, error) { - ret := _m.Called(epochCounter) +// DKGStateReader_GetDKGState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetDKGState' +type DKGStateReader_GetDKGState_Call struct { + *mock.Call +} + +// GetDKGState is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGStateReader_Expecter) GetDKGState(epochCounter interface{}) *DKGStateReader_GetDKGState_Call { + return &DKGStateReader_GetDKGState_Call{Call: _e.mock.On("GetDKGState", epochCounter)} +} + +func (_c *DKGStateReader_GetDKGState_Call) Run(run func(epochCounter uint64)) *DKGStateReader_GetDKGState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGStateReader_GetDKGState_Call) Return(dKGState flow.DKGState, err error) *DKGStateReader_GetDKGState_Call { + _c.Call.Return(dKGState, err) + return _c +} + +func (_c *DKGStateReader_GetDKGState_Call) RunAndReturn(run func(epochCounter uint64) (flow.DKGState, error)) *DKGStateReader_GetDKGState_Call { + _c.Call.Return(run) + return _c +} + +// IsDKGStarted provides a mock function for the type DKGStateReader +func (_mock *DKGStateReader) IsDKGStarted(epochCounter uint64) (bool, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for IsDKGStarted") @@ -52,27 +107,59 @@ func (_m *DKGStateReader) IsDKGStarted(epochCounter uint64) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64) (bool, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (bool, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) bool); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) bool); ok { + r0 = returnFunc(epochCounter) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// RetrieveMyBeaconPrivateKey provides a mock function with given fields: epochCounter -func (_m *DKGStateReader) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { - ret := _m.Called(epochCounter) +// DKGStateReader_IsDKGStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsDKGStarted' +type DKGStateReader_IsDKGStarted_Call struct { + *mock.Call +} + +// IsDKGStarted is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGStateReader_Expecter) IsDKGStarted(epochCounter interface{}) *DKGStateReader_IsDKGStarted_Call { + return &DKGStateReader_IsDKGStarted_Call{Call: _e.mock.On("IsDKGStarted", epochCounter)} +} + +func (_c *DKGStateReader_IsDKGStarted_Call) Run(run func(epochCounter uint64)) *DKGStateReader_IsDKGStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGStateReader_IsDKGStarted_Call) Return(b bool, err error) *DKGStateReader_IsDKGStarted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *DKGStateReader_IsDKGStarted_Call) RunAndReturn(run func(epochCounter uint64) (bool, error)) *DKGStateReader_IsDKGStarted_Call { + _c.Call.Return(run) + return _c +} + +// RetrieveMyBeaconPrivateKey provides a mock function for the type DKGStateReader +func (_mock *DKGStateReader) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for RetrieveMyBeaconPrivateKey") @@ -81,35 +168,66 @@ func (_m *DKGStateReader) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypt var r0 crypto.PrivateKey var r1 bool var r2 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(epochCounter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(epochCounter) + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(epochCounter) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// UnsafeRetrieveMyBeaconPrivateKey provides a mock function with given fields: epochCounter -func (_m *DKGStateReader) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, error) { - ret := _m.Called(epochCounter) +// DKGStateReader_RetrieveMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RetrieveMyBeaconPrivateKey' +type DKGStateReader_RetrieveMyBeaconPrivateKey_Call struct { + *mock.Call +} + +// RetrieveMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGStateReader_Expecter) RetrieveMyBeaconPrivateKey(epochCounter interface{}) *DKGStateReader_RetrieveMyBeaconPrivateKey_Call { + return &DKGStateReader_RetrieveMyBeaconPrivateKey_Call{Call: _e.mock.On("RetrieveMyBeaconPrivateKey", epochCounter)} +} + +func (_c *DKGStateReader_RetrieveMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64)) *DKGStateReader_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGStateReader_RetrieveMyBeaconPrivateKey_Call) Return(key crypto.PrivateKey, safe bool, err error) *DKGStateReader_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(key, safe, err) + return _c +} + +func (_c *DKGStateReader_RetrieveMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64) (crypto.PrivateKey, bool, error)) *DKGStateReader_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// UnsafeRetrieveMyBeaconPrivateKey provides a mock function for the type DKGStateReader +func (_mock *DKGStateReader) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for UnsafeRetrieveMyBeaconPrivateKey") @@ -117,36 +235,54 @@ func (_m *DKGStateReader) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) var r0 crypto.PrivateKey var r1 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(epochCounter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewDKGStateReader creates a new instance of DKGStateReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewDKGStateReader(t interface { - mock.TestingT - Cleanup(func()) -}) *DKGStateReader { - mock := &DKGStateReader{} - mock.Mock.Test(t) +// DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnsafeRetrieveMyBeaconPrivateKey' +type DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UnsafeRetrieveMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *DKGStateReader_Expecter) UnsafeRetrieveMyBeaconPrivateKey(epochCounter interface{}) *DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call { + return &DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call{Call: _e.mock.On("UnsafeRetrieveMyBeaconPrivateKey", epochCounter)} +} - return mock +func (_c *DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64)) *DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call) Return(privateKey crypto.PrivateKey, err error) *DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(privateKey, err) + return _c +} + +func (_c *DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64) (crypto.PrivateKey, error)) *DKGStateReader_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/epoch_commits.go b/storage/mock/epoch_commits.go index 369b93f1e11..9c3462e1a61 100644 --- a/storage/mock/epoch_commits.go +++ b/storage/mock/epoch_commits.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewEpochCommits creates a new instance of EpochCommits. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochCommits(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochCommits { + mock := &EpochCommits{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EpochCommits is an autogenerated mock type for the EpochCommits type type EpochCommits struct { mock.Mock } -// BatchStore provides a mock function with given fields: rw, commit -func (_m *EpochCommits) BatchStore(rw storage.ReaderBatchWriter, commit *flow.EpochCommit) error { - ret := _m.Called(rw, commit) +type EpochCommits_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochCommits) EXPECT() *EpochCommits_Expecter { + return &EpochCommits_Expecter{mock: &_m.Mock} +} + +// BatchStore provides a mock function for the type EpochCommits +func (_mock *EpochCommits) BatchStore(rw storage.ReaderBatchWriter, commit *flow.EpochCommit) error { + ret := _mock.Called(rw, commit) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(storage.ReaderBatchWriter, *flow.EpochCommit) error); ok { - r0 = rf(rw, commit) + if returnFunc, ok := ret.Get(0).(func(storage.ReaderBatchWriter, *flow.EpochCommit) error); ok { + r0 = returnFunc(rw, commit) } else { r0 = ret.Error(0) } - return r0 } -// ByID provides a mock function with given fields: _a0 -func (_m *EpochCommits) ByID(_a0 flow.Identifier) (*flow.EpochCommit, error) { - ret := _m.Called(_a0) +// EpochCommits_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type EpochCommits_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - rw storage.ReaderBatchWriter +// - commit *flow.EpochCommit +func (_e *EpochCommits_Expecter) BatchStore(rw interface{}, commit interface{}) *EpochCommits_BatchStore_Call { + return &EpochCommits_BatchStore_Call{Call: _e.mock.On("BatchStore", rw, commit)} +} + +func (_c *EpochCommits_BatchStore_Call) Run(run func(rw storage.ReaderBatchWriter, commit *flow.EpochCommit)) *EpochCommits_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 storage.ReaderBatchWriter + if args[0] != nil { + arg0 = args[0].(storage.ReaderBatchWriter) + } + var arg1 *flow.EpochCommit + if args[1] != nil { + arg1 = args[1].(*flow.EpochCommit) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EpochCommits_BatchStore_Call) Return(err error) *EpochCommits_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EpochCommits_BatchStore_Call) RunAndReturn(run func(rw storage.ReaderBatchWriter, commit *flow.EpochCommit) error) *EpochCommits_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type EpochCommits +func (_mock *EpochCommits) ByID(identifier flow.Identifier) (*flow.EpochCommit, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for ByID") @@ -42,36 +104,54 @@ func (_m *EpochCommits) ByID(_a0 flow.Identifier) (*flow.EpochCommit, error) { var r0 *flow.EpochCommit var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.EpochCommit, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.EpochCommit, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.EpochCommit); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.EpochCommit); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.EpochCommit) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEpochCommits creates a new instance of EpochCommits. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochCommits(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochCommits { - mock := &EpochCommits{} - mock.Mock.Test(t) +// EpochCommits_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type EpochCommits_ByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *EpochCommits_Expecter) ByID(identifier interface{}) *EpochCommits_ByID_Call { + return &EpochCommits_ByID_Call{Call: _e.mock.On("ByID", identifier)} +} - return mock +func (_c *EpochCommits_ByID_Call) Run(run func(identifier flow.Identifier)) *EpochCommits_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochCommits_ByID_Call) Return(epochCommit *flow.EpochCommit, err error) *EpochCommits_ByID_Call { + _c.Call.Return(epochCommit, err) + return _c +} + +func (_c *EpochCommits_ByID_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.EpochCommit, error)) *EpochCommits_ByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/epoch_protocol_state_entries.go b/storage/mock/epoch_protocol_state_entries.go index 9a29646b158..2197f52a7ff 100644 --- a/storage/mock/epoch_protocol_state_entries.go +++ b/storage/mock/epoch_protocol_state_entries.go @@ -1,60 +1,178 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewEpochProtocolStateEntries creates a new instance of EpochProtocolStateEntries. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochProtocolStateEntries(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochProtocolStateEntries { + mock := &EpochProtocolStateEntries{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EpochProtocolStateEntries is an autogenerated mock type for the EpochProtocolStateEntries type type EpochProtocolStateEntries struct { mock.Mock } -// BatchIndex provides a mock function with given fields: lctx, rw, blockID, epochProtocolStateID -func (_m *EpochProtocolStateEntries) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, epochProtocolStateID flow.Identifier) error { - ret := _m.Called(lctx, rw, blockID, epochProtocolStateID) +type EpochProtocolStateEntries_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochProtocolStateEntries) EXPECT() *EpochProtocolStateEntries_Expecter { + return &EpochProtocolStateEntries_Expecter{mock: &_m.Mock} +} + +// BatchIndex provides a mock function for the type EpochProtocolStateEntries +func (_mock *EpochProtocolStateEntries) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, epochProtocolStateID flow.Identifier) error { + ret := _mock.Called(lctx, rw, blockID, epochProtocolStateID) if len(ret) == 0 { panic("no return value specified for BatchIndex") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { - r0 = rf(lctx, rw, blockID, epochProtocolStateID) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, blockID, epochProtocolStateID) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: w, epochProtocolStateID, epochProtocolStateEntry -func (_m *EpochProtocolStateEntries) BatchStore(w storage.Writer, epochProtocolStateID flow.Identifier, epochProtocolStateEntry *flow.MinEpochStateEntry) error { - ret := _m.Called(w, epochProtocolStateID, epochProtocolStateEntry) +// EpochProtocolStateEntries_BatchIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchIndex' +type EpochProtocolStateEntries_BatchIndex_Call struct { + *mock.Call +} + +// BatchIndex is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - epochProtocolStateID flow.Identifier +func (_e *EpochProtocolStateEntries_Expecter) BatchIndex(lctx interface{}, rw interface{}, blockID interface{}, epochProtocolStateID interface{}) *EpochProtocolStateEntries_BatchIndex_Call { + return &EpochProtocolStateEntries_BatchIndex_Call{Call: _e.mock.On("BatchIndex", lctx, rw, blockID, epochProtocolStateID)} +} + +func (_c *EpochProtocolStateEntries_BatchIndex_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, epochProtocolStateID flow.Identifier)) *EpochProtocolStateEntries_BatchIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *EpochProtocolStateEntries_BatchIndex_Call) Return(err error) *EpochProtocolStateEntries_BatchIndex_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EpochProtocolStateEntries_BatchIndex_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, epochProtocolStateID flow.Identifier) error) *EpochProtocolStateEntries_BatchIndex_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type EpochProtocolStateEntries +func (_mock *EpochProtocolStateEntries) BatchStore(w storage.Writer, epochProtocolStateID flow.Identifier, epochProtocolStateEntry *flow.MinEpochStateEntry) error { + ret := _mock.Called(w, epochProtocolStateID, epochProtocolStateEntry) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(storage.Writer, flow.Identifier, *flow.MinEpochStateEntry) error); ok { - r0 = rf(w, epochProtocolStateID, epochProtocolStateEntry) + if returnFunc, ok := ret.Get(0).(func(storage.Writer, flow.Identifier, *flow.MinEpochStateEntry) error); ok { + r0 = returnFunc(w, epochProtocolStateID, epochProtocolStateEntry) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *EpochProtocolStateEntries) ByBlockID(blockID flow.Identifier) (*flow.RichEpochStateEntry, error) { - ret := _m.Called(blockID) +// EpochProtocolStateEntries_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type EpochProtocolStateEntries_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - w storage.Writer +// - epochProtocolStateID flow.Identifier +// - epochProtocolStateEntry *flow.MinEpochStateEntry +func (_e *EpochProtocolStateEntries_Expecter) BatchStore(w interface{}, epochProtocolStateID interface{}, epochProtocolStateEntry interface{}) *EpochProtocolStateEntries_BatchStore_Call { + return &EpochProtocolStateEntries_BatchStore_Call{Call: _e.mock.On("BatchStore", w, epochProtocolStateID, epochProtocolStateEntry)} +} + +func (_c *EpochProtocolStateEntries_BatchStore_Call) Run(run func(w storage.Writer, epochProtocolStateID flow.Identifier, epochProtocolStateEntry *flow.MinEpochStateEntry)) *EpochProtocolStateEntries_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 storage.Writer + if args[0] != nil { + arg0 = args[0].(storage.Writer) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 *flow.MinEpochStateEntry + if args[2] != nil { + arg2 = args[2].(*flow.MinEpochStateEntry) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *EpochProtocolStateEntries_BatchStore_Call) Return(err error) *EpochProtocolStateEntries_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EpochProtocolStateEntries_BatchStore_Call) RunAndReturn(run func(w storage.Writer, epochProtocolStateID flow.Identifier, epochProtocolStateEntry *flow.MinEpochStateEntry) error) *EpochProtocolStateEntries_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type EpochProtocolStateEntries +func (_mock *EpochProtocolStateEntries) ByBlockID(blockID flow.Identifier) (*flow.RichEpochStateEntry, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -62,29 +180,61 @@ func (_m *EpochProtocolStateEntries) ByBlockID(blockID flow.Identifier) (*flow.R var r0 *flow.RichEpochStateEntry var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.RichEpochStateEntry, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.RichEpochStateEntry, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.RichEpochStateEntry); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.RichEpochStateEntry); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.RichEpochStateEntry) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: id -func (_m *EpochProtocolStateEntries) ByID(id flow.Identifier) (*flow.RichEpochStateEntry, error) { - ret := _m.Called(id) +// EpochProtocolStateEntries_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type EpochProtocolStateEntries_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *EpochProtocolStateEntries_Expecter) ByBlockID(blockID interface{}) *EpochProtocolStateEntries_ByBlockID_Call { + return &EpochProtocolStateEntries_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *EpochProtocolStateEntries_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *EpochProtocolStateEntries_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochProtocolStateEntries_ByBlockID_Call) Return(richEpochStateEntry *flow.RichEpochStateEntry, err error) *EpochProtocolStateEntries_ByBlockID_Call { + _c.Call.Return(richEpochStateEntry, err) + return _c +} + +func (_c *EpochProtocolStateEntries_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.RichEpochStateEntry, error)) *EpochProtocolStateEntries_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type EpochProtocolStateEntries +func (_mock *EpochProtocolStateEntries) ByID(id flow.Identifier) (*flow.RichEpochStateEntry, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByID") @@ -92,36 +242,54 @@ func (_m *EpochProtocolStateEntries) ByID(id flow.Identifier) (*flow.RichEpochSt var r0 *flow.RichEpochStateEntry var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.RichEpochStateEntry, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.RichEpochStateEntry, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.RichEpochStateEntry); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.RichEpochStateEntry); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.RichEpochStateEntry) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEpochProtocolStateEntries creates a new instance of EpochProtocolStateEntries. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochProtocolStateEntries(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochProtocolStateEntries { - mock := &EpochProtocolStateEntries{} - mock.Mock.Test(t) +// EpochProtocolStateEntries_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type EpochProtocolStateEntries_ByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *EpochProtocolStateEntries_Expecter) ByID(id interface{}) *EpochProtocolStateEntries_ByID_Call { + return &EpochProtocolStateEntries_ByID_Call{Call: _e.mock.On("ByID", id)} +} - return mock +func (_c *EpochProtocolStateEntries_ByID_Call) Run(run func(id flow.Identifier)) *EpochProtocolStateEntries_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochProtocolStateEntries_ByID_Call) Return(richEpochStateEntry *flow.RichEpochStateEntry, err error) *EpochProtocolStateEntries_ByID_Call { + _c.Call.Return(richEpochStateEntry, err) + return _c +} + +func (_c *EpochProtocolStateEntries_ByID_Call) RunAndReturn(run func(id flow.Identifier) (*flow.RichEpochStateEntry, error)) *EpochProtocolStateEntries_ByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/epoch_recovery_my_beacon_key.go b/storage/mock/epoch_recovery_my_beacon_key.go index 8fb2c5066ac..7a6e0ef78d6 100644 --- a/storage/mock/epoch_recovery_my_beacon_key.go +++ b/storage/mock/epoch_recovery_my_beacon_key.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/onflow/crypto" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewEpochRecoveryMyBeaconKey creates a new instance of EpochRecoveryMyBeaconKey. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochRecoveryMyBeaconKey(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochRecoveryMyBeaconKey { + mock := &EpochRecoveryMyBeaconKey{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EpochRecoveryMyBeaconKey is an autogenerated mock type for the EpochRecoveryMyBeaconKey type type EpochRecoveryMyBeaconKey struct { mock.Mock } -// GetDKGState provides a mock function with given fields: epochCounter -func (_m *EpochRecoveryMyBeaconKey) GetDKGState(epochCounter uint64) (flow.DKGState, error) { - ret := _m.Called(epochCounter) +type EpochRecoveryMyBeaconKey_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochRecoveryMyBeaconKey) EXPECT() *EpochRecoveryMyBeaconKey_Expecter { + return &EpochRecoveryMyBeaconKey_Expecter{mock: &_m.Mock} +} + +// GetDKGState provides a mock function for the type EpochRecoveryMyBeaconKey +func (_mock *EpochRecoveryMyBeaconKey) GetDKGState(epochCounter uint64) (flow.DKGState, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for GetDKGState") @@ -24,27 +47,59 @@ func (_m *EpochRecoveryMyBeaconKey) GetDKGState(epochCounter uint64) (flow.DKGSt var r0 flow.DKGState var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.DKGState, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.DKGState, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) flow.DKGState); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.DKGState); ok { + r0 = returnFunc(epochCounter) } else { r0 = ret.Get(0).(flow.DKGState) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// IsDKGStarted provides a mock function with given fields: epochCounter -func (_m *EpochRecoveryMyBeaconKey) IsDKGStarted(epochCounter uint64) (bool, error) { - ret := _m.Called(epochCounter) +// EpochRecoveryMyBeaconKey_GetDKGState_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetDKGState' +type EpochRecoveryMyBeaconKey_GetDKGState_Call struct { + *mock.Call +} + +// GetDKGState is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *EpochRecoveryMyBeaconKey_Expecter) GetDKGState(epochCounter interface{}) *EpochRecoveryMyBeaconKey_GetDKGState_Call { + return &EpochRecoveryMyBeaconKey_GetDKGState_Call{Call: _e.mock.On("GetDKGState", epochCounter)} +} + +func (_c *EpochRecoveryMyBeaconKey_GetDKGState_Call) Run(run func(epochCounter uint64)) *EpochRecoveryMyBeaconKey_GetDKGState_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_GetDKGState_Call) Return(dKGState flow.DKGState, err error) *EpochRecoveryMyBeaconKey_GetDKGState_Call { + _c.Call.Return(dKGState, err) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_GetDKGState_Call) RunAndReturn(run func(epochCounter uint64) (flow.DKGState, error)) *EpochRecoveryMyBeaconKey_GetDKGState_Call { + _c.Call.Return(run) + return _c +} + +// IsDKGStarted provides a mock function for the type EpochRecoveryMyBeaconKey +func (_mock *EpochRecoveryMyBeaconKey) IsDKGStarted(epochCounter uint64) (bool, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for IsDKGStarted") @@ -52,27 +107,59 @@ func (_m *EpochRecoveryMyBeaconKey) IsDKGStarted(epochCounter uint64) (bool, err var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(uint64) (bool, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (bool, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) bool); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) bool); ok { + r0 = returnFunc(epochCounter) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// RetrieveMyBeaconPrivateKey provides a mock function with given fields: epochCounter -func (_m *EpochRecoveryMyBeaconKey) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { - ret := _m.Called(epochCounter) +// EpochRecoveryMyBeaconKey_IsDKGStarted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsDKGStarted' +type EpochRecoveryMyBeaconKey_IsDKGStarted_Call struct { + *mock.Call +} + +// IsDKGStarted is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *EpochRecoveryMyBeaconKey_Expecter) IsDKGStarted(epochCounter interface{}) *EpochRecoveryMyBeaconKey_IsDKGStarted_Call { + return &EpochRecoveryMyBeaconKey_IsDKGStarted_Call{Call: _e.mock.On("IsDKGStarted", epochCounter)} +} + +func (_c *EpochRecoveryMyBeaconKey_IsDKGStarted_Call) Run(run func(epochCounter uint64)) *EpochRecoveryMyBeaconKey_IsDKGStarted_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_IsDKGStarted_Call) Return(b bool, err error) *EpochRecoveryMyBeaconKey_IsDKGStarted_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_IsDKGStarted_Call) RunAndReturn(run func(epochCounter uint64) (bool, error)) *EpochRecoveryMyBeaconKey_IsDKGStarted_Call { + _c.Call.Return(run) + return _c +} + +// RetrieveMyBeaconPrivateKey provides a mock function for the type EpochRecoveryMyBeaconKey +func (_mock *EpochRecoveryMyBeaconKey) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for RetrieveMyBeaconPrivateKey") @@ -81,35 +168,66 @@ func (_m *EpochRecoveryMyBeaconKey) RetrieveMyBeaconPrivateKey(epochCounter uint var r0 crypto.PrivateKey var r1 bool var r2 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(epochCounter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(epochCounter) + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(epochCounter) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// UnsafeRetrieveMyBeaconPrivateKey provides a mock function with given fields: epochCounter -func (_m *EpochRecoveryMyBeaconKey) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, error) { - ret := _m.Called(epochCounter) +// EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RetrieveMyBeaconPrivateKey' +type EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call struct { + *mock.Call +} + +// RetrieveMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *EpochRecoveryMyBeaconKey_Expecter) RetrieveMyBeaconPrivateKey(epochCounter interface{}) *EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call { + return &EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call{Call: _e.mock.On("RetrieveMyBeaconPrivateKey", epochCounter)} +} + +func (_c *EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64)) *EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call) Return(key crypto.PrivateKey, safe bool, err error) *EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(key, safe, err) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64) (crypto.PrivateKey, bool, error)) *EpochRecoveryMyBeaconKey_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// UnsafeRetrieveMyBeaconPrivateKey provides a mock function for the type EpochRecoveryMyBeaconKey +func (_mock *EpochRecoveryMyBeaconKey) UnsafeRetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for UnsafeRetrieveMyBeaconPrivateKey") @@ -117,54 +235,117 @@ func (_m *EpochRecoveryMyBeaconKey) UnsafeRetrieveMyBeaconPrivateKey(epochCounte var r0 crypto.PrivateKey var r1 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(epochCounter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Error(1) } - return r0, r1 } -// UpsertMyBeaconPrivateKey provides a mock function with given fields: epochCounter, key, commit -func (_m *EpochRecoveryMyBeaconKey) UpsertMyBeaconPrivateKey(epochCounter uint64, key crypto.PrivateKey, commit *flow.EpochCommit) error { - ret := _m.Called(epochCounter, key, commit) +// EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UnsafeRetrieveMyBeaconPrivateKey' +type EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call struct { + *mock.Call +} + +// UnsafeRetrieveMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *EpochRecoveryMyBeaconKey_Expecter) UnsafeRetrieveMyBeaconPrivateKey(epochCounter interface{}) *EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call { + return &EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call{Call: _e.mock.On("UnsafeRetrieveMyBeaconPrivateKey", epochCounter)} +} + +func (_c *EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64)) *EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call) Return(privateKey crypto.PrivateKey, err error) *EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(privateKey, err) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64) (crypto.PrivateKey, error)) *EpochRecoveryMyBeaconKey_UnsafeRetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c +} + +// UpsertMyBeaconPrivateKey provides a mock function for the type EpochRecoveryMyBeaconKey +func (_mock *EpochRecoveryMyBeaconKey) UpsertMyBeaconPrivateKey(epochCounter uint64, key crypto.PrivateKey, commit *flow.EpochCommit) error { + ret := _mock.Called(epochCounter, key, commit) if len(ret) == 0 { panic("no return value specified for UpsertMyBeaconPrivateKey") } var r0 error - if rf, ok := ret.Get(0).(func(uint64, crypto.PrivateKey, *flow.EpochCommit) error); ok { - r0 = rf(epochCounter, key, commit) + if returnFunc, ok := ret.Get(0).(func(uint64, crypto.PrivateKey, *flow.EpochCommit) error); ok { + r0 = returnFunc(epochCounter, key, commit) } else { r0 = ret.Error(0) } - return r0 } -// NewEpochRecoveryMyBeaconKey creates a new instance of EpochRecoveryMyBeaconKey. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochRecoveryMyBeaconKey(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochRecoveryMyBeaconKey { - mock := &EpochRecoveryMyBeaconKey{} - mock.Mock.Test(t) +// EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpsertMyBeaconPrivateKey' +type EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UpsertMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +// - key crypto.PrivateKey +// - commit *flow.EpochCommit +func (_e *EpochRecoveryMyBeaconKey_Expecter) UpsertMyBeaconPrivateKey(epochCounter interface{}, key interface{}, commit interface{}) *EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call { + return &EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call{Call: _e.mock.On("UpsertMyBeaconPrivateKey", epochCounter, key, commit)} +} - return mock +func (_c *EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64, key crypto.PrivateKey, commit *flow.EpochCommit)) *EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + var arg1 crypto.PrivateKey + if args[1] != nil { + arg1 = args[1].(crypto.PrivateKey) + } + var arg2 *flow.EpochCommit + if args[2] != nil { + arg2 = args[2].(*flow.EpochCommit) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call) Return(err error) *EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64, key crypto.PrivateKey, commit *flow.EpochCommit) error) *EpochRecoveryMyBeaconKey_UpsertMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/epoch_setups.go b/storage/mock/epoch_setups.go index a0aece572c3..20757ff9e9c 100644 --- a/storage/mock/epoch_setups.go +++ b/storage/mock/epoch_setups.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewEpochSetups creates a new instance of EpochSetups. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEpochSetups(t interface { + mock.TestingT + Cleanup(func()) +}) *EpochSetups { + mock := &EpochSetups{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EpochSetups is an autogenerated mock type for the EpochSetups type type EpochSetups struct { mock.Mock } -// BatchStore provides a mock function with given fields: rw, setup -func (_m *EpochSetups) BatchStore(rw storage.ReaderBatchWriter, setup *flow.EpochSetup) error { - ret := _m.Called(rw, setup) +type EpochSetups_Expecter struct { + mock *mock.Mock +} + +func (_m *EpochSetups) EXPECT() *EpochSetups_Expecter { + return &EpochSetups_Expecter{mock: &_m.Mock} +} + +// BatchStore provides a mock function for the type EpochSetups +func (_mock *EpochSetups) BatchStore(rw storage.ReaderBatchWriter, setup *flow.EpochSetup) error { + ret := _mock.Called(rw, setup) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(storage.ReaderBatchWriter, *flow.EpochSetup) error); ok { - r0 = rf(rw, setup) + if returnFunc, ok := ret.Get(0).(func(storage.ReaderBatchWriter, *flow.EpochSetup) error); ok { + r0 = returnFunc(rw, setup) } else { r0 = ret.Error(0) } - return r0 } -// ByID provides a mock function with given fields: _a0 -func (_m *EpochSetups) ByID(_a0 flow.Identifier) (*flow.EpochSetup, error) { - ret := _m.Called(_a0) +// EpochSetups_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type EpochSetups_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - rw storage.ReaderBatchWriter +// - setup *flow.EpochSetup +func (_e *EpochSetups_Expecter) BatchStore(rw interface{}, setup interface{}) *EpochSetups_BatchStore_Call { + return &EpochSetups_BatchStore_Call{Call: _e.mock.On("BatchStore", rw, setup)} +} + +func (_c *EpochSetups_BatchStore_Call) Run(run func(rw storage.ReaderBatchWriter, setup *flow.EpochSetup)) *EpochSetups_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 storage.ReaderBatchWriter + if args[0] != nil { + arg0 = args[0].(storage.ReaderBatchWriter) + } + var arg1 *flow.EpochSetup + if args[1] != nil { + arg1 = args[1].(*flow.EpochSetup) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EpochSetups_BatchStore_Call) Return(err error) *EpochSetups_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *EpochSetups_BatchStore_Call) RunAndReturn(run func(rw storage.ReaderBatchWriter, setup *flow.EpochSetup) error) *EpochSetups_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type EpochSetups +func (_mock *EpochSetups) ByID(identifier flow.Identifier) (*flow.EpochSetup, error) { + ret := _mock.Called(identifier) if len(ret) == 0 { panic("no return value specified for ByID") @@ -42,36 +104,54 @@ func (_m *EpochSetups) ByID(_a0 flow.Identifier) (*flow.EpochSetup, error) { var r0 *flow.EpochSetup var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.EpochSetup, error)); ok { - return rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.EpochSetup, error)); ok { + return returnFunc(identifier) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.EpochSetup); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.EpochSetup); ok { + r0 = returnFunc(identifier) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.EpochSetup) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(_a0) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(identifier) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEpochSetups creates a new instance of EpochSetups. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEpochSetups(t interface { - mock.TestingT - Cleanup(func()) -}) *EpochSetups { - mock := &EpochSetups{} - mock.Mock.Test(t) +// EpochSetups_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type EpochSetups_ByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByID is a helper method to define mock.On call +// - identifier flow.Identifier +func (_e *EpochSetups_Expecter) ByID(identifier interface{}) *EpochSetups_ByID_Call { + return &EpochSetups_ByID_Call{Call: _e.mock.On("ByID", identifier)} +} - return mock +func (_c *EpochSetups_ByID_Call) Run(run func(identifier flow.Identifier)) *EpochSetups_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EpochSetups_ByID_Call) Return(epochSetup *flow.EpochSetup, err error) *EpochSetups_ByID_Call { + _c.Call.Return(epochSetup, err) + return _c +} + +func (_c *EpochSetups_ByID_Call) RunAndReturn(run func(identifier flow.Identifier) (*flow.EpochSetup, error)) *EpochSetups_ByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/events.go b/storage/mock/events.go index ea90103c5d3..316f3cbda9b 100644 --- a/storage/mock/events.go +++ b/storage/mock/events.go @@ -1,60 +1,172 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewEvents creates a new instance of Events. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEvents(t interface { + mock.TestingT + Cleanup(func()) +}) *Events { + mock := &Events{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Events is an autogenerated mock type for the Events type type Events struct { mock.Mock } -// BatchRemoveByBlockID provides a mock function with given fields: blockID, batch -func (_m *Events) BatchRemoveByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { - ret := _m.Called(blockID, batch) +type Events_Expecter struct { + mock *mock.Mock +} + +func (_m *Events) EXPECT() *Events_Expecter { + return &Events_Expecter{mock: &_m.Mock} +} + +// BatchRemoveByBlockID provides a mock function for the type Events +func (_mock *Events) BatchRemoveByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(blockID, batch) if len(ret) == 0 { panic("no return value specified for BatchRemoveByBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(blockID, batch) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(blockID, batch) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: lctx, blockID, events, batch -func (_m *Events) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, events []flow.EventsList, batch storage.ReaderBatchWriter) error { - ret := _m.Called(lctx, blockID, events, batch) +// Events_BatchRemoveByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemoveByBlockID' +type Events_BatchRemoveByBlockID_Call struct { + *mock.Call +} + +// BatchRemoveByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +// - batch storage.ReaderBatchWriter +func (_e *Events_Expecter) BatchRemoveByBlockID(blockID interface{}, batch interface{}) *Events_BatchRemoveByBlockID_Call { + return &Events_BatchRemoveByBlockID_Call{Call: _e.mock.On("BatchRemoveByBlockID", blockID, batch)} +} + +func (_c *Events_BatchRemoveByBlockID_Call) Run(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter)) *Events_BatchRemoveByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Events_BatchRemoveByBlockID_Call) Return(err error) *Events_BatchRemoveByBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Events_BatchRemoveByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter) error) *Events_BatchRemoveByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type Events +func (_mock *Events) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, events []flow.EventsList, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(lctx, blockID, events, batch) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, []flow.EventsList, storage.ReaderBatchWriter) error); ok { - r0 = rf(lctx, blockID, events, batch) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, []flow.EventsList, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(lctx, blockID, events, batch) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *Events) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { - ret := _m.Called(blockID) +// Events_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type Events_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - lctx lockctx.Proof +// - blockID flow.Identifier +// - events []flow.EventsList +// - batch storage.ReaderBatchWriter +func (_e *Events_Expecter) BatchStore(lctx interface{}, blockID interface{}, events interface{}, batch interface{}) *Events_BatchStore_Call { + return &Events_BatchStore_Call{Call: _e.mock.On("BatchStore", lctx, blockID, events, batch)} +} + +func (_c *Events_BatchStore_Call) Run(run func(lctx lockctx.Proof, blockID flow.Identifier, events []flow.EventsList, batch storage.ReaderBatchWriter)) *Events_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 []flow.EventsList + if args[2] != nil { + arg2 = args[2].([]flow.EventsList) + } + var arg3 storage.ReaderBatchWriter + if args[3] != nil { + arg3 = args[3].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *Events_BatchStore_Call) Return(err error) *Events_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Events_BatchStore_Call) RunAndReturn(run func(lctx lockctx.Proof, blockID flow.Identifier, events []flow.EventsList, batch storage.ReaderBatchWriter) error) *Events_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type Events +func (_mock *Events) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -62,29 +174,61 @@ func (_m *Events) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Event, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Event, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.Event); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.Event); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDEventType provides a mock function with given fields: blockID, eventType -func (_m *Events) ByBlockIDEventType(blockID flow.Identifier, eventType flow.EventType) ([]flow.Event, error) { - ret := _m.Called(blockID, eventType) +// Events_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type Events_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Events_Expecter) ByBlockID(blockID interface{}) *Events_ByBlockID_Call { + return &Events_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *Events_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *Events_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Events_ByBlockID_Call) Return(events []flow.Event, err error) *Events_ByBlockID_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *Events_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) ([]flow.Event, error)) *Events_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDEventType provides a mock function for the type Events +func (_mock *Events) ByBlockIDEventType(blockID flow.Identifier, eventType flow.EventType) ([]flow.Event, error) { + ret := _mock.Called(blockID, eventType) if len(ret) == 0 { panic("no return value specified for ByBlockIDEventType") @@ -92,29 +236,67 @@ func (_m *Events) ByBlockIDEventType(blockID flow.Identifier, eventType flow.Eve var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) ([]flow.Event, error)); ok { - return rf(blockID, eventType) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) ([]flow.Event, error)); ok { + return returnFunc(blockID, eventType) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) []flow.Event); ok { - r0 = rf(blockID, eventType) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) []flow.Event); ok { + r0 = returnFunc(blockID, eventType) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.EventType) error); ok { - r1 = rf(blockID, eventType) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.EventType) error); ok { + r1 = returnFunc(blockID, eventType) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *Events) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) ([]flow.Event, error) { - ret := _m.Called(blockID, transactionID) +// Events_ByBlockIDEventType_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDEventType' +type Events_ByBlockIDEventType_Call struct { + *mock.Call +} + +// ByBlockIDEventType is a helper method to define mock.On call +// - blockID flow.Identifier +// - eventType flow.EventType +func (_e *Events_Expecter) ByBlockIDEventType(blockID interface{}, eventType interface{}) *Events_ByBlockIDEventType_Call { + return &Events_ByBlockIDEventType_Call{Call: _e.mock.On("ByBlockIDEventType", blockID, eventType)} +} + +func (_c *Events_ByBlockIDEventType_Call) Run(run func(blockID flow.Identifier, eventType flow.EventType)) *Events_ByBlockIDEventType_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.EventType + if args[1] != nil { + arg1 = args[1].(flow.EventType) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Events_ByBlockIDEventType_Call) Return(events []flow.Event, err error) *Events_ByBlockIDEventType_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *Events_ByBlockIDEventType_Call) RunAndReturn(run func(blockID flow.Identifier, eventType flow.EventType) ([]flow.Event, error)) *Events_ByBlockIDEventType_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type Events +func (_mock *Events) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) ([]flow.Event, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -122,29 +304,67 @@ func (_m *Events) ByBlockIDTransactionID(blockID flow.Identifier, transactionID var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) ([]flow.Event, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) ([]flow.Event, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) []flow.Event); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) []flow.Event); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *Events) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) ([]flow.Event, error) { - ret := _m.Called(blockID, txIndex) +// Events_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type Events_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *Events_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *Events_ByBlockIDTransactionID_Call { + return &Events_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *Events_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *Events_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Events_ByBlockIDTransactionID_Call) Return(events []flow.Event, err error) *Events_ByBlockIDTransactionID_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *Events_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) ([]flow.Event, error)) *Events_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type Events +func (_mock *Events) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) ([]flow.Event, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -152,36 +372,60 @@ func (_m *Events) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uin var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) ([]flow.Event, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) ([]flow.Event, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) []flow.Event); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) []flow.Event); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEvents creates a new instance of Events. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEvents(t interface { - mock.TestingT - Cleanup(func()) -}) *Events { - mock := &Events{} - mock.Mock.Test(t) +// Events_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type Events_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *Events_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *Events_ByBlockIDTransactionIndex_Call { + return &Events_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} - return mock +func (_c *Events_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *Events_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Events_ByBlockIDTransactionIndex_Call) Return(events []flow.Event, err error) *Events_ByBlockIDTransactionIndex_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *Events_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) ([]flow.Event, error)) *Events_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/events_reader.go b/storage/mock/events_reader.go index 31459d361ae..71e15d0c360 100644 --- a/storage/mock/events_reader.go +++ b/storage/mock/events_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewEventsReader creates a new instance of EventsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEventsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *EventsReader { + mock := &EventsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // EventsReader is an autogenerated mock type for the EventsReader type type EventsReader struct { mock.Mock } -// ByBlockID provides a mock function with given fields: blockID -func (_m *EventsReader) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { - ret := _m.Called(blockID) +type EventsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *EventsReader) EXPECT() *EventsReader_Expecter { + return &EventsReader_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type EventsReader +func (_mock *EventsReader) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,29 +46,61 @@ func (_m *EventsReader) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Event, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Event, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.Event); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.Event); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDEventType provides a mock function with given fields: blockID, eventType -func (_m *EventsReader) ByBlockIDEventType(blockID flow.Identifier, eventType flow.EventType) ([]flow.Event, error) { - ret := _m.Called(blockID, eventType) +// EventsReader_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type EventsReader_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *EventsReader_Expecter) ByBlockID(blockID interface{}) *EventsReader_ByBlockID_Call { + return &EventsReader_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *EventsReader_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *EventsReader_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *EventsReader_ByBlockID_Call) Return(events []flow.Event, err error) *EventsReader_ByBlockID_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *EventsReader_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) ([]flow.Event, error)) *EventsReader_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDEventType provides a mock function for the type EventsReader +func (_mock *EventsReader) ByBlockIDEventType(blockID flow.Identifier, eventType flow.EventType) ([]flow.Event, error) { + ret := _mock.Called(blockID, eventType) if len(ret) == 0 { panic("no return value specified for ByBlockIDEventType") @@ -52,29 +108,67 @@ func (_m *EventsReader) ByBlockIDEventType(blockID flow.Identifier, eventType fl var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) ([]flow.Event, error)); ok { - return rf(blockID, eventType) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) ([]flow.Event, error)); ok { + return returnFunc(blockID, eventType) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) []flow.Event); ok { - r0 = rf(blockID, eventType) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.EventType) []flow.Event); ok { + r0 = returnFunc(blockID, eventType) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.EventType) error); ok { - r1 = rf(blockID, eventType) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.EventType) error); ok { + r1 = returnFunc(blockID, eventType) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *EventsReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) ([]flow.Event, error) { - ret := _m.Called(blockID, transactionID) +// EventsReader_ByBlockIDEventType_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDEventType' +type EventsReader_ByBlockIDEventType_Call struct { + *mock.Call +} + +// ByBlockIDEventType is a helper method to define mock.On call +// - blockID flow.Identifier +// - eventType flow.EventType +func (_e *EventsReader_Expecter) ByBlockIDEventType(blockID interface{}, eventType interface{}) *EventsReader_ByBlockIDEventType_Call { + return &EventsReader_ByBlockIDEventType_Call{Call: _e.mock.On("ByBlockIDEventType", blockID, eventType)} +} + +func (_c *EventsReader_ByBlockIDEventType_Call) Run(run func(blockID flow.Identifier, eventType flow.EventType)) *EventsReader_ByBlockIDEventType_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.EventType + if args[1] != nil { + arg1 = args[1].(flow.EventType) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EventsReader_ByBlockIDEventType_Call) Return(events []flow.Event, err error) *EventsReader_ByBlockIDEventType_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *EventsReader_ByBlockIDEventType_Call) RunAndReturn(run func(blockID flow.Identifier, eventType flow.EventType) ([]flow.Event, error)) *EventsReader_ByBlockIDEventType_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type EventsReader +func (_mock *EventsReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) ([]flow.Event, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -82,29 +176,67 @@ func (_m *EventsReader) ByBlockIDTransactionID(blockID flow.Identifier, transact var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) ([]flow.Event, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) ([]flow.Event, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) []flow.Event); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) []flow.Event); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *EventsReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) ([]flow.Event, error) { - ret := _m.Called(blockID, txIndex) +// EventsReader_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type EventsReader_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *EventsReader_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *EventsReader_ByBlockIDTransactionID_Call { + return &EventsReader_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *EventsReader_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *EventsReader_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EventsReader_ByBlockIDTransactionID_Call) Return(events []flow.Event, err error) *EventsReader_ByBlockIDTransactionID_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *EventsReader_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) ([]flow.Event, error)) *EventsReader_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type EventsReader +func (_mock *EventsReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) ([]flow.Event, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -112,36 +244,60 @@ func (_m *EventsReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txInd var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) ([]flow.Event, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) ([]flow.Event, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) []flow.Event); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) []flow.Event); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewEventsReader creates a new instance of EventsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEventsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *EventsReader { - mock := &EventsReader{} - mock.Mock.Test(t) +// EventsReader_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type EventsReader_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *EventsReader_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *EventsReader_ByBlockIDTransactionIndex_Call { + return &EventsReader_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} - return mock +func (_c *EventsReader_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *EventsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *EventsReader_ByBlockIDTransactionIndex_Call) Return(events []flow.Event, err error) *EventsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *EventsReader_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) ([]flow.Event, error)) *EventsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/execution_fork_evidence.go b/storage/mock/execution_fork_evidence.go index f523fdbc98a..59aef05879e 100644 --- a/storage/mock/execution_fork_evidence.go +++ b/storage/mock/execution_fork_evidence.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewExecutionForkEvidence creates a new instance of ExecutionForkEvidence. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionForkEvidence(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionForkEvidence { + mock := &ExecutionForkEvidence{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionForkEvidence is an autogenerated mock type for the ExecutionForkEvidence type type ExecutionForkEvidence struct { mock.Mock } -// Retrieve provides a mock function with no fields -func (_m *ExecutionForkEvidence) Retrieve() ([]*flow.IncorporatedResultSeal, error) { - ret := _m.Called() +type ExecutionForkEvidence_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionForkEvidence) EXPECT() *ExecutionForkEvidence_Expecter { + return &ExecutionForkEvidence_Expecter{mock: &_m.Mock} +} + +// Retrieve provides a mock function for the type ExecutionForkEvidence +func (_mock *ExecutionForkEvidence) Retrieve() ([]*flow.IncorporatedResultSeal, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Retrieve") @@ -24,54 +47,104 @@ func (_m *ExecutionForkEvidence) Retrieve() ([]*flow.IncorporatedResultSeal, err var r0 []*flow.IncorporatedResultSeal var r1 error - if rf, ok := ret.Get(0).(func() ([]*flow.IncorporatedResultSeal, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() ([]*flow.IncorporatedResultSeal, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() []*flow.IncorporatedResultSeal); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []*flow.IncorporatedResultSeal); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.IncorporatedResultSeal) } } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// StoreIfNotExists provides a mock function with given fields: lctx, conflictingSeals -func (_m *ExecutionForkEvidence) StoreIfNotExists(lctx lockctx.Proof, conflictingSeals []*flow.IncorporatedResultSeal) error { - ret := _m.Called(lctx, conflictingSeals) +// ExecutionForkEvidence_Retrieve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Retrieve' +type ExecutionForkEvidence_Retrieve_Call struct { + *mock.Call +} + +// Retrieve is a helper method to define mock.On call +func (_e *ExecutionForkEvidence_Expecter) Retrieve() *ExecutionForkEvidence_Retrieve_Call { + return &ExecutionForkEvidence_Retrieve_Call{Call: _e.mock.On("Retrieve")} +} + +func (_c *ExecutionForkEvidence_Retrieve_Call) Run(run func()) *ExecutionForkEvidence_Retrieve_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ExecutionForkEvidence_Retrieve_Call) Return(incorporatedResultSeals []*flow.IncorporatedResultSeal, err error) *ExecutionForkEvidence_Retrieve_Call { + _c.Call.Return(incorporatedResultSeals, err) + return _c +} + +func (_c *ExecutionForkEvidence_Retrieve_Call) RunAndReturn(run func() ([]*flow.IncorporatedResultSeal, error)) *ExecutionForkEvidence_Retrieve_Call { + _c.Call.Return(run) + return _c +} + +// StoreIfNotExists provides a mock function for the type ExecutionForkEvidence +func (_mock *ExecutionForkEvidence) StoreIfNotExists(lctx lockctx.Proof, conflictingSeals []*flow.IncorporatedResultSeal) error { + ret := _mock.Called(lctx, conflictingSeals) if len(ret) == 0 { panic("no return value specified for StoreIfNotExists") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, []*flow.IncorporatedResultSeal) error); ok { - r0 = rf(lctx, conflictingSeals) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, []*flow.IncorporatedResultSeal) error); ok { + r0 = returnFunc(lctx, conflictingSeals) } else { r0 = ret.Error(0) } - return r0 } -// NewExecutionForkEvidence creates a new instance of ExecutionForkEvidence. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionForkEvidence(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionForkEvidence { - mock := &ExecutionForkEvidence{} - mock.Mock.Test(t) +// ExecutionForkEvidence_StoreIfNotExists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StoreIfNotExists' +type ExecutionForkEvidence_StoreIfNotExists_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StoreIfNotExists is a helper method to define mock.On call +// - lctx lockctx.Proof +// - conflictingSeals []*flow.IncorporatedResultSeal +func (_e *ExecutionForkEvidence_Expecter) StoreIfNotExists(lctx interface{}, conflictingSeals interface{}) *ExecutionForkEvidence_StoreIfNotExists_Call { + return &ExecutionForkEvidence_StoreIfNotExists_Call{Call: _e.mock.On("StoreIfNotExists", lctx, conflictingSeals)} +} - return mock +func (_c *ExecutionForkEvidence_StoreIfNotExists_Call) Run(run func(lctx lockctx.Proof, conflictingSeals []*flow.IncorporatedResultSeal)) *ExecutionForkEvidence_StoreIfNotExists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 []*flow.IncorporatedResultSeal + if args[1] != nil { + arg1 = args[1].([]*flow.IncorporatedResultSeal) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionForkEvidence_StoreIfNotExists_Call) Return(err error) *ExecutionForkEvidence_StoreIfNotExists_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionForkEvidence_StoreIfNotExists_Call) RunAndReturn(run func(lctx lockctx.Proof, conflictingSeals []*flow.IncorporatedResultSeal) error) *ExecutionForkEvidence_StoreIfNotExists_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/execution_receipts.go b/storage/mock/execution_receipts.go index a8c4931a0cf..668826f7ad5 100644 --- a/storage/mock/execution_receipts.go +++ b/storage/mock/execution_receipts.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewExecutionReceipts creates a new instance of ExecutionReceipts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionReceipts(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionReceipts { + mock := &ExecutionReceipts{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionReceipts is an autogenerated mock type for the ExecutionReceipts type type ExecutionReceipts struct { mock.Mock } -// BatchStore provides a mock function with given fields: receipt, batch -func (_m *ExecutionReceipts) BatchStore(receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter) error { - ret := _m.Called(receipt, batch) +type ExecutionReceipts_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionReceipts) EXPECT() *ExecutionReceipts_Expecter { + return &ExecutionReceipts_Expecter{mock: &_m.Mock} +} + +// BatchStore provides a mock function for the type ExecutionReceipts +func (_mock *ExecutionReceipts) BatchStore(receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(receipt, batch) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt, storage.ReaderBatchWriter) error); ok { - r0 = rf(receipt, batch) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(receipt, batch) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *ExecutionReceipts) ByBlockID(blockID flow.Identifier) (flow.ExecutionReceiptList, error) { - ret := _m.Called(blockID) +// ExecutionReceipts_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type ExecutionReceipts_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - receipt *flow.ExecutionReceipt +// - batch storage.ReaderBatchWriter +func (_e *ExecutionReceipts_Expecter) BatchStore(receipt interface{}, batch interface{}) *ExecutionReceipts_BatchStore_Call { + return &ExecutionReceipts_BatchStore_Call{Call: _e.mock.On("BatchStore", receipt, batch)} +} + +func (_c *ExecutionReceipts_BatchStore_Call) Run(run func(receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter)) *ExecutionReceipts_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionReceipts_BatchStore_Call) Return(err error) *ExecutionReceipts_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionReceipts_BatchStore_Call) RunAndReturn(run func(receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter) error) *ExecutionReceipts_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type ExecutionReceipts +func (_mock *ExecutionReceipts) ByBlockID(blockID flow.Identifier) (flow.ExecutionReceiptList, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -42,29 +104,61 @@ func (_m *ExecutionReceipts) ByBlockID(blockID flow.Identifier) (flow.ExecutionR var r0 flow.ExecutionReceiptList var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.ExecutionReceiptList, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.ExecutionReceiptList, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.ExecutionReceiptList); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.ExecutionReceiptList); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.ExecutionReceiptList) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: receiptID -func (_m *ExecutionReceipts) ByID(receiptID flow.Identifier) (*flow.ExecutionReceipt, error) { - ret := _m.Called(receiptID) +// ExecutionReceipts_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ExecutionReceipts_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionReceipts_Expecter) ByBlockID(blockID interface{}) *ExecutionReceipts_ByBlockID_Call { + return &ExecutionReceipts_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *ExecutionReceipts_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *ExecutionReceipts_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionReceipts_ByBlockID_Call) Return(executionReceiptList flow.ExecutionReceiptList, err error) *ExecutionReceipts_ByBlockID_Call { + _c.Call.Return(executionReceiptList, err) + return _c +} + +func (_c *ExecutionReceipts_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.ExecutionReceiptList, error)) *ExecutionReceipts_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ExecutionReceipts +func (_mock *ExecutionReceipts) ByID(receiptID flow.Identifier) (*flow.ExecutionReceipt, error) { + ret := _mock.Called(receiptID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -72,54 +166,105 @@ func (_m *ExecutionReceipts) ByID(receiptID flow.Identifier) (*flow.ExecutionRec var r0 *flow.ExecutionReceipt var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionReceipt, error)); ok { - return rf(receiptID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionReceipt, error)); ok { + return returnFunc(receiptID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionReceipt); ok { - r0 = rf(receiptID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionReceipt); ok { + r0 = returnFunc(receiptID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionReceipt) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(receiptID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(receiptID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Store provides a mock function with given fields: receipt -func (_m *ExecutionReceipts) Store(receipt *flow.ExecutionReceipt) error { - ret := _m.Called(receipt) +// ExecutionReceipts_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ExecutionReceipts_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - receiptID flow.Identifier +func (_e *ExecutionReceipts_Expecter) ByID(receiptID interface{}) *ExecutionReceipts_ByID_Call { + return &ExecutionReceipts_ByID_Call{Call: _e.mock.On("ByID", receiptID)} +} + +func (_c *ExecutionReceipts_ByID_Call) Run(run func(receiptID flow.Identifier)) *ExecutionReceipts_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionReceipts_ByID_Call) Return(executionReceipt *flow.ExecutionReceipt, err error) *ExecutionReceipts_ByID_Call { + _c.Call.Return(executionReceipt, err) + return _c +} + +func (_c *ExecutionReceipts_ByID_Call) RunAndReturn(run func(receiptID flow.Identifier) (*flow.ExecutionReceipt, error)) *ExecutionReceipts_ByID_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type ExecutionReceipts +func (_mock *ExecutionReceipts) Store(receipt *flow.ExecutionReceipt) error { + ret := _mock.Called(receipt) if len(ret) == 0 { panic("no return value specified for Store") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionReceipt) error); ok { - r0 = rf(receipt) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionReceipt) error); ok { + r0 = returnFunc(receipt) } else { r0 = ret.Error(0) } - return r0 } -// NewExecutionReceipts creates a new instance of ExecutionReceipts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionReceipts(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionReceipts { - mock := &ExecutionReceipts{} - mock.Mock.Test(t) +// ExecutionReceipts_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ExecutionReceipts_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - receipt *flow.ExecutionReceipt +func (_e *ExecutionReceipts_Expecter) Store(receipt interface{}) *ExecutionReceipts_Store_Call { + return &ExecutionReceipts_Store_Call{Call: _e.mock.On("Store", receipt)} +} - return mock +func (_c *ExecutionReceipts_Store_Call) Run(run func(receipt *flow.ExecutionReceipt)) *ExecutionReceipts_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionReceipt + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionReceipt) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionReceipts_Store_Call) Return(err error) *ExecutionReceipts_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionReceipts_Store_Call) RunAndReturn(run func(receipt *flow.ExecutionReceipt) error) *ExecutionReceipts_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/execution_results.go b/storage/mock/execution_results.go index 868351f817f..44f9f6a67bc 100644 --- a/storage/mock/execution_results.go +++ b/storage/mock/execution_results.go @@ -1,78 +1,229 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewExecutionResults creates a new instance of ExecutionResults. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionResults(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionResults { + mock := &ExecutionResults{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionResults is an autogenerated mock type for the ExecutionResults type type ExecutionResults struct { mock.Mock } -// BatchIndex provides a mock function with given fields: lctx, rw, blockID, resultID -func (_m *ExecutionResults) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, resultID flow.Identifier) error { - ret := _m.Called(lctx, rw, blockID, resultID) +type ExecutionResults_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionResults) EXPECT() *ExecutionResults_Expecter { + return &ExecutionResults_Expecter{mock: &_m.Mock} +} + +// BatchIndex provides a mock function for the type ExecutionResults +func (_mock *ExecutionResults) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, resultID flow.Identifier) error { + ret := _mock.Called(lctx, rw, blockID, resultID) if len(ret) == 0 { panic("no return value specified for BatchIndex") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { - r0 = rf(lctx, rw, blockID, resultID) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, blockID, resultID) } else { r0 = ret.Error(0) } - return r0 } -// BatchRemoveIndexByBlockID provides a mock function with given fields: blockID, batch -func (_m *ExecutionResults) BatchRemoveIndexByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { - ret := _m.Called(blockID, batch) +// ExecutionResults_BatchIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchIndex' +type ExecutionResults_BatchIndex_Call struct { + *mock.Call +} + +// BatchIndex is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - resultID flow.Identifier +func (_e *ExecutionResults_Expecter) BatchIndex(lctx interface{}, rw interface{}, blockID interface{}, resultID interface{}) *ExecutionResults_BatchIndex_Call { + return &ExecutionResults_BatchIndex_Call{Call: _e.mock.On("BatchIndex", lctx, rw, blockID, resultID)} +} + +func (_c *ExecutionResults_BatchIndex_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, resultID flow.Identifier)) *ExecutionResults_BatchIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ExecutionResults_BatchIndex_Call) Return(err error) *ExecutionResults_BatchIndex_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionResults_BatchIndex_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, resultID flow.Identifier) error) *ExecutionResults_BatchIndex_Call { + _c.Call.Return(run) + return _c +} + +// BatchRemoveIndexByBlockID provides a mock function for the type ExecutionResults +func (_mock *ExecutionResults) BatchRemoveIndexByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(blockID, batch) if len(ret) == 0 { panic("no return value specified for BatchRemoveIndexByBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(blockID, batch) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(blockID, batch) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: result, batch -func (_m *ExecutionResults) BatchStore(result *flow.ExecutionResult, batch storage.ReaderBatchWriter) error { - ret := _m.Called(result, batch) +// ExecutionResults_BatchRemoveIndexByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemoveIndexByBlockID' +type ExecutionResults_BatchRemoveIndexByBlockID_Call struct { + *mock.Call +} + +// BatchRemoveIndexByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +// - batch storage.ReaderBatchWriter +func (_e *ExecutionResults_Expecter) BatchRemoveIndexByBlockID(blockID interface{}, batch interface{}) *ExecutionResults_BatchRemoveIndexByBlockID_Call { + return &ExecutionResults_BatchRemoveIndexByBlockID_Call{Call: _e.mock.On("BatchRemoveIndexByBlockID", blockID, batch)} +} + +func (_c *ExecutionResults_BatchRemoveIndexByBlockID_Call) Run(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter)) *ExecutionResults_BatchRemoveIndexByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionResults_BatchRemoveIndexByBlockID_Call) Return(err error) *ExecutionResults_BatchRemoveIndexByBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionResults_BatchRemoveIndexByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter) error) *ExecutionResults_BatchRemoveIndexByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type ExecutionResults +func (_mock *ExecutionResults) BatchStore(result *flow.ExecutionResult, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(result, batch) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.ExecutionResult, storage.ReaderBatchWriter) error); ok { - r0 = rf(result, batch) + if returnFunc, ok := ret.Get(0).(func(*flow.ExecutionResult, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(result, batch) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *ExecutionResults) ByBlockID(blockID flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(blockID) +// ExecutionResults_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type ExecutionResults_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - result *flow.ExecutionResult +// - batch storage.ReaderBatchWriter +func (_e *ExecutionResults_Expecter) BatchStore(result interface{}, batch interface{}) *ExecutionResults_BatchStore_Call { + return &ExecutionResults_BatchStore_Call{Call: _e.mock.On("BatchStore", result, batch)} +} + +func (_c *ExecutionResults_BatchStore_Call) Run(run func(result *flow.ExecutionResult, batch storage.ReaderBatchWriter)) *ExecutionResults_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ExecutionResult + if args[0] != nil { + arg0 = args[0].(*flow.ExecutionResult) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ExecutionResults_BatchStore_Call) Return(err error) *ExecutionResults_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ExecutionResults_BatchStore_Call) RunAndReturn(run func(result *flow.ExecutionResult, batch storage.ReaderBatchWriter) error) *ExecutionResults_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type ExecutionResults +func (_mock *ExecutionResults) ByBlockID(blockID flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -80,29 +231,61 @@ func (_m *ExecutionResults) ByBlockID(blockID flow.Identifier) (*flow.ExecutionR var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: resultID -func (_m *ExecutionResults) ByID(resultID flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(resultID) +// ExecutionResults_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ExecutionResults_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionResults_Expecter) ByBlockID(blockID interface{}) *ExecutionResults_ByBlockID_Call { + return &ExecutionResults_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *ExecutionResults_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *ExecutionResults_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionResults_ByBlockID_Call) Return(executionResult *flow.ExecutionResult, err error) *ExecutionResults_ByBlockID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *ExecutionResults_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.ExecutionResult, error)) *ExecutionResults_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ExecutionResults +func (_mock *ExecutionResults) ByID(resultID flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(resultID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -110,29 +293,61 @@ func (_m *ExecutionResults) ByID(resultID flow.Identifier) (*flow.ExecutionResul var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(resultID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(resultID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(resultID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(resultID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(resultID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(resultID) } else { r1 = ret.Error(1) } - return r0, r1 } -// IDByBlockID provides a mock function with given fields: blockID -func (_m *ExecutionResults) IDByBlockID(blockID flow.Identifier) (flow.Identifier, error) { - ret := _m.Called(blockID) +// ExecutionResults_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ExecutionResults_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - resultID flow.Identifier +func (_e *ExecutionResults_Expecter) ByID(resultID interface{}) *ExecutionResults_ByID_Call { + return &ExecutionResults_ByID_Call{Call: _e.mock.On("ByID", resultID)} +} + +func (_c *ExecutionResults_ByID_Call) Run(run func(resultID flow.Identifier)) *ExecutionResults_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionResults_ByID_Call) Return(executionResult *flow.ExecutionResult, err error) *ExecutionResults_ByID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *ExecutionResults_ByID_Call) RunAndReturn(run func(resultID flow.Identifier) (*flow.ExecutionResult, error)) *ExecutionResults_ByID_Call { + _c.Call.Return(run) + return _c +} + +// IDByBlockID provides a mock function for the type ExecutionResults +func (_mock *ExecutionResults) IDByBlockID(blockID flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for IDByBlockID") @@ -140,36 +355,54 @@ func (_m *ExecutionResults) IDByBlockID(blockID flow.Identifier) (flow.Identifie var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionResults creates a new instance of ExecutionResults. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionResults(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionResults { - mock := &ExecutionResults{} - mock.Mock.Test(t) +// ExecutionResults_IDByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IDByBlockID' +type ExecutionResults_IDByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// IDByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionResults_Expecter) IDByBlockID(blockID interface{}) *ExecutionResults_IDByBlockID_Call { + return &ExecutionResults_IDByBlockID_Call{Call: _e.mock.On("IDByBlockID", blockID)} +} - return mock +func (_c *ExecutionResults_IDByBlockID_Call) Run(run func(blockID flow.Identifier)) *ExecutionResults_IDByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionResults_IDByBlockID_Call) Return(identifier flow.Identifier, err error) *ExecutionResults_IDByBlockID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ExecutionResults_IDByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.Identifier, error)) *ExecutionResults_IDByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/execution_results_reader.go b/storage/mock/execution_results_reader.go index 244624758e9..ab8875180d1 100644 --- a/storage/mock/execution_results_reader.go +++ b/storage/mock/execution_results_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewExecutionResultsReader creates a new instance of ExecutionResultsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewExecutionResultsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *ExecutionResultsReader { + mock := &ExecutionResultsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ExecutionResultsReader is an autogenerated mock type for the ExecutionResultsReader type type ExecutionResultsReader struct { mock.Mock } -// ByBlockID provides a mock function with given fields: blockID -func (_m *ExecutionResultsReader) ByBlockID(blockID flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(blockID) +type ExecutionResultsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *ExecutionResultsReader) EXPECT() *ExecutionResultsReader_Expecter { + return &ExecutionResultsReader_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type ExecutionResultsReader +func (_mock *ExecutionResultsReader) ByBlockID(blockID flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,29 +46,61 @@ func (_m *ExecutionResultsReader) ByBlockID(blockID flow.Identifier) (*flow.Exec var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: resultID -func (_m *ExecutionResultsReader) ByID(resultID flow.Identifier) (*flow.ExecutionResult, error) { - ret := _m.Called(resultID) +// ExecutionResultsReader_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ExecutionResultsReader_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionResultsReader_Expecter) ByBlockID(blockID interface{}) *ExecutionResultsReader_ByBlockID_Call { + return &ExecutionResultsReader_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *ExecutionResultsReader_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *ExecutionResultsReader_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionResultsReader_ByBlockID_Call) Return(executionResult *flow.ExecutionResult, err error) *ExecutionResultsReader_ByBlockID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *ExecutionResultsReader_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.ExecutionResult, error)) *ExecutionResultsReader_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ExecutionResultsReader +func (_mock *ExecutionResultsReader) ByID(resultID flow.Identifier) (*flow.ExecutionResult, error) { + ret := _mock.Called(resultID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -52,29 +108,61 @@ func (_m *ExecutionResultsReader) ByID(resultID flow.Identifier) (*flow.Executio var r0 *flow.ExecutionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { - return rf(resultID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionResult, error)); ok { + return returnFunc(resultID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { - r0 = rf(resultID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionResult); ok { + r0 = returnFunc(resultID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(resultID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(resultID) } else { r1 = ret.Error(1) } - return r0, r1 } -// IDByBlockID provides a mock function with given fields: blockID -func (_m *ExecutionResultsReader) IDByBlockID(blockID flow.Identifier) (flow.Identifier, error) { - ret := _m.Called(blockID) +// ExecutionResultsReader_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ExecutionResultsReader_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - resultID flow.Identifier +func (_e *ExecutionResultsReader_Expecter) ByID(resultID interface{}) *ExecutionResultsReader_ByID_Call { + return &ExecutionResultsReader_ByID_Call{Call: _e.mock.On("ByID", resultID)} +} + +func (_c *ExecutionResultsReader_ByID_Call) Run(run func(resultID flow.Identifier)) *ExecutionResultsReader_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionResultsReader_ByID_Call) Return(executionResult *flow.ExecutionResult, err error) *ExecutionResultsReader_ByID_Call { + _c.Call.Return(executionResult, err) + return _c +} + +func (_c *ExecutionResultsReader_ByID_Call) RunAndReturn(run func(resultID flow.Identifier) (*flow.ExecutionResult, error)) *ExecutionResultsReader_ByID_Call { + _c.Call.Return(run) + return _c +} + +// IDByBlockID provides a mock function for the type ExecutionResultsReader +func (_mock *ExecutionResultsReader) IDByBlockID(blockID flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for IDByBlockID") @@ -82,36 +170,54 @@ func (_m *ExecutionResultsReader) IDByBlockID(blockID flow.Identifier) (flow.Ide var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewExecutionResultsReader creates a new instance of ExecutionResultsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewExecutionResultsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *ExecutionResultsReader { - mock := &ExecutionResultsReader{} - mock.Mock.Test(t) +// ExecutionResultsReader_IDByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IDByBlockID' +type ExecutionResultsReader_IDByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// IDByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ExecutionResultsReader_Expecter) IDByBlockID(blockID interface{}) *ExecutionResultsReader_IDByBlockID_Call { + return &ExecutionResultsReader_IDByBlockID_Call{Call: _e.mock.On("IDByBlockID", blockID)} +} - return mock +func (_c *ExecutionResultsReader_IDByBlockID_Call) Run(run func(blockID flow.Identifier)) *ExecutionResultsReader_IDByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ExecutionResultsReader_IDByBlockID_Call) Return(identifier flow.Identifier, err error) *ExecutionResultsReader_IDByBlockID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ExecutionResultsReader_IDByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (flow.Identifier, error)) *ExecutionResultsReader_IDByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/fungible_token_transfers.go b/storage/mock/fungible_token_transfers.go new file mode 100644 index 00000000000..6b0dc22a5c5 --- /dev/null +++ b/storage/mock/fungible_token_transfers.go @@ -0,0 +1,265 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewFungibleTokenTransfers creates a new instance of FungibleTokenTransfers. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFungibleTokenTransfers(t interface { + mock.TestingT + Cleanup(func()) +}) *FungibleTokenTransfers { + mock := &FungibleTokenTransfers{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// FungibleTokenTransfers is an autogenerated mock type for the FungibleTokenTransfers type +type FungibleTokenTransfers struct { + mock.Mock +} + +type FungibleTokenTransfers_Expecter struct { + mock *mock.Mock +} + +func (_m *FungibleTokenTransfers) EXPECT() *FungibleTokenTransfers_Expecter { + return &FungibleTokenTransfers_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type FungibleTokenTransfers +func (_mock *FungibleTokenTransfers) ByAddress(account flow.Address, cursor *access.TransferCursor) (storage.FungibleTokenTransferIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.FungibleTokenTransferIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) (storage.FungibleTokenTransferIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) storage.FungibleTokenTransferIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.FungibleTokenTransferIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.TransferCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// FungibleTokenTransfers_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type FungibleTokenTransfers_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.TransferCursor +func (_e *FungibleTokenTransfers_Expecter) ByAddress(account interface{}, cursor interface{}) *FungibleTokenTransfers_ByAddress_Call { + return &FungibleTokenTransfers_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *FungibleTokenTransfers_ByAddress_Call) Run(run func(account flow.Address, cursor *access.TransferCursor)) *FungibleTokenTransfers_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.TransferCursor + if args[1] != nil { + arg1 = args[1].(*access.TransferCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *FungibleTokenTransfers_ByAddress_Call) Return(v storage.FungibleTokenTransferIterator, err error) *FungibleTokenTransfers_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *FungibleTokenTransfers_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.TransferCursor) (storage.FungibleTokenTransferIterator, error)) *FungibleTokenTransfers_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type FungibleTokenTransfers +func (_mock *FungibleTokenTransfers) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// FungibleTokenTransfers_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type FungibleTokenTransfers_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *FungibleTokenTransfers_Expecter) FirstIndexedHeight() *FungibleTokenTransfers_FirstIndexedHeight_Call { + return &FungibleTokenTransfers_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *FungibleTokenTransfers_FirstIndexedHeight_Call) Run(run func()) *FungibleTokenTransfers_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FungibleTokenTransfers_FirstIndexedHeight_Call) Return(v uint64) *FungibleTokenTransfers_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *FungibleTokenTransfers_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *FungibleTokenTransfers_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type FungibleTokenTransfers +func (_mock *FungibleTokenTransfers) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// FungibleTokenTransfers_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type FungibleTokenTransfers_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *FungibleTokenTransfers_Expecter) LatestIndexedHeight() *FungibleTokenTransfers_LatestIndexedHeight_Call { + return &FungibleTokenTransfers_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *FungibleTokenTransfers_LatestIndexedHeight_Call) Run(run func()) *FungibleTokenTransfers_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FungibleTokenTransfers_LatestIndexedHeight_Call) Return(v uint64) *FungibleTokenTransfers_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *FungibleTokenTransfers_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *FungibleTokenTransfers_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type FungibleTokenTransfers +func (_mock *FungibleTokenTransfers) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error { + ret := _mock.Called(lctx, rw, blockHeight, transfers) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.FungibleTokenTransfer) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, transfers) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// FungibleTokenTransfers_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type FungibleTokenTransfers_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - transfers []access.FungibleTokenTransfer +func (_e *FungibleTokenTransfers_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, transfers interface{}) *FungibleTokenTransfers_Store_Call { + return &FungibleTokenTransfers_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, transfers)} +} + +func (_c *FungibleTokenTransfers_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer)) *FungibleTokenTransfers_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.FungibleTokenTransfer + if args[3] != nil { + arg3 = args[3].([]access.FungibleTokenTransfer) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *FungibleTokenTransfers_Store_Call) Return(err error) *FungibleTokenTransfers_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *FungibleTokenTransfers_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error) *FungibleTokenTransfers_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/fungible_token_transfers_bootstrapper.go b/storage/mock/fungible_token_transfers_bootstrapper.go new file mode 100644 index 00000000000..40b7125d087 --- /dev/null +++ b/storage/mock/fungible_token_transfers_bootstrapper.go @@ -0,0 +1,336 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewFungibleTokenTransfersBootstrapper creates a new instance of FungibleTokenTransfersBootstrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFungibleTokenTransfersBootstrapper(t interface { + mock.TestingT + Cleanup(func()) +}) *FungibleTokenTransfersBootstrapper { + mock := &FungibleTokenTransfersBootstrapper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// FungibleTokenTransfersBootstrapper is an autogenerated mock type for the FungibleTokenTransfersBootstrapper type +type FungibleTokenTransfersBootstrapper struct { + mock.Mock +} + +type FungibleTokenTransfersBootstrapper_Expecter struct { + mock *mock.Mock +} + +func (_m *FungibleTokenTransfersBootstrapper) EXPECT() *FungibleTokenTransfersBootstrapper_Expecter { + return &FungibleTokenTransfersBootstrapper_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type FungibleTokenTransfersBootstrapper +func (_mock *FungibleTokenTransfersBootstrapper) ByAddress(account flow.Address, cursor *access.TransferCursor) (storage.FungibleTokenTransferIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.FungibleTokenTransferIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) (storage.FungibleTokenTransferIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) storage.FungibleTokenTransferIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.FungibleTokenTransferIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.TransferCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// FungibleTokenTransfersBootstrapper_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type FungibleTokenTransfersBootstrapper_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.TransferCursor +func (_e *FungibleTokenTransfersBootstrapper_Expecter) ByAddress(account interface{}, cursor interface{}) *FungibleTokenTransfersBootstrapper_ByAddress_Call { + return &FungibleTokenTransfersBootstrapper_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *FungibleTokenTransfersBootstrapper_ByAddress_Call) Run(run func(account flow.Address, cursor *access.TransferCursor)) *FungibleTokenTransfersBootstrapper_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.TransferCursor + if args[1] != nil { + arg1 = args[1].(*access.TransferCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_ByAddress_Call) Return(v storage.FungibleTokenTransferIterator, err error) *FungibleTokenTransfersBootstrapper_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.TransferCursor) (storage.FungibleTokenTransferIterator, error)) *FungibleTokenTransfersBootstrapper_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type FungibleTokenTransfersBootstrapper +func (_mock *FungibleTokenTransfersBootstrapper) FirstIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *FungibleTokenTransfersBootstrapper_Expecter) FirstIndexedHeight() *FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + return &FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call) Run(run func()) *FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call) Return(v uint64, err error) *FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *FungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type FungibleTokenTransfersBootstrapper +func (_mock *FungibleTokenTransfersBootstrapper) LatestIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *FungibleTokenTransfersBootstrapper_Expecter) LatestIndexedHeight() *FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + return &FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call) Run(run func()) *FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call) Return(v uint64, err error) *FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *FungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type FungibleTokenTransfersBootstrapper +func (_mock *FungibleTokenTransfersBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error { + ret := _mock.Called(lctx, rw, blockHeight, transfers) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.FungibleTokenTransfer) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, transfers) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// FungibleTokenTransfersBootstrapper_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type FungibleTokenTransfersBootstrapper_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - transfers []access.FungibleTokenTransfer +func (_e *FungibleTokenTransfersBootstrapper_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, transfers interface{}) *FungibleTokenTransfersBootstrapper_Store_Call { + return &FungibleTokenTransfersBootstrapper_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, transfers)} +} + +func (_c *FungibleTokenTransfersBootstrapper_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer)) *FungibleTokenTransfersBootstrapper_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.FungibleTokenTransfer + if args[3] != nil { + arg3 = args[3].([]access.FungibleTokenTransfer) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_Store_Call) Return(err error) *FungibleTokenTransfersBootstrapper_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error) *FungibleTokenTransfersBootstrapper_Store_Call { + _c.Call.Return(run) + return _c +} + +// UninitializedFirstHeight provides a mock function for the type FungibleTokenTransfersBootstrapper +func (_mock *FungibleTokenTransfersBootstrapper) UninitializedFirstHeight() (uint64, bool) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for UninitializedFirstHeight") + } + + var r0 uint64 + var r1 bool + if returnFunc, ok := ret.Get(0).(func() (uint64, bool)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() + } else { + r1 = ret.Get(1).(bool) + } + return r0, r1 +} + +// FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UninitializedFirstHeight' +type FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call struct { + *mock.Call +} + +// UninitializedFirstHeight is a helper method to define mock.On call +func (_e *FungibleTokenTransfersBootstrapper_Expecter) UninitializedFirstHeight() *FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + return &FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call{Call: _e.mock.On("UninitializedFirstHeight")} +} + +func (_c *FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call) Run(run func()) *FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call) Return(v uint64, b bool) *FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call) RunAndReturn(run func() (uint64, bool)) *FungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/fungible_token_transfers_range_reader.go b/storage/mock/fungible_token_transfers_range_reader.go new file mode 100644 index 00000000000..73d9fcddad7 --- /dev/null +++ b/storage/mock/fungible_token_transfers_range_reader.go @@ -0,0 +1,124 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewFungibleTokenTransfersRangeReader creates a new instance of FungibleTokenTransfersRangeReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFungibleTokenTransfersRangeReader(t interface { + mock.TestingT + Cleanup(func()) +}) *FungibleTokenTransfersRangeReader { + mock := &FungibleTokenTransfersRangeReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// FungibleTokenTransfersRangeReader is an autogenerated mock type for the FungibleTokenTransfersRangeReader type +type FungibleTokenTransfersRangeReader struct { + mock.Mock +} + +type FungibleTokenTransfersRangeReader_Expecter struct { + mock *mock.Mock +} + +func (_m *FungibleTokenTransfersRangeReader) EXPECT() *FungibleTokenTransfersRangeReader_Expecter { + return &FungibleTokenTransfersRangeReader_Expecter{mock: &_m.Mock} +} + +// FirstIndexedHeight provides a mock function for the type FungibleTokenTransfersRangeReader +func (_mock *FungibleTokenTransfersRangeReader) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *FungibleTokenTransfersRangeReader_Expecter) FirstIndexedHeight() *FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + return &FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call) Run(run func()) *FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call) Return(v uint64) *FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *FungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type FungibleTokenTransfersRangeReader +func (_mock *FungibleTokenTransfersRangeReader) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *FungibleTokenTransfersRangeReader_Expecter) LatestIndexedHeight() *FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + return &FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call) Run(run func()) *FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call) Return(v uint64) *FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *FungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/fungible_token_transfers_reader.go b/storage/mock/fungible_token_transfers_reader.go new file mode 100644 index 00000000000..0bd6f1f4c13 --- /dev/null +++ b/storage/mock/fungible_token_transfers_reader.go @@ -0,0 +1,107 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewFungibleTokenTransfersReader creates a new instance of FungibleTokenTransfersReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFungibleTokenTransfersReader(t interface { + mock.TestingT + Cleanup(func()) +}) *FungibleTokenTransfersReader { + mock := &FungibleTokenTransfersReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// FungibleTokenTransfersReader is an autogenerated mock type for the FungibleTokenTransfersReader type +type FungibleTokenTransfersReader struct { + mock.Mock +} + +type FungibleTokenTransfersReader_Expecter struct { + mock *mock.Mock +} + +func (_m *FungibleTokenTransfersReader) EXPECT() *FungibleTokenTransfersReader_Expecter { + return &FungibleTokenTransfersReader_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type FungibleTokenTransfersReader +func (_mock *FungibleTokenTransfersReader) ByAddress(account flow.Address, cursor *access.TransferCursor) (storage.FungibleTokenTransferIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.FungibleTokenTransferIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) (storage.FungibleTokenTransferIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) storage.FungibleTokenTransferIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.FungibleTokenTransferIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.TransferCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// FungibleTokenTransfersReader_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type FungibleTokenTransfersReader_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.TransferCursor +func (_e *FungibleTokenTransfersReader_Expecter) ByAddress(account interface{}, cursor interface{}) *FungibleTokenTransfersReader_ByAddress_Call { + return &FungibleTokenTransfersReader_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *FungibleTokenTransfersReader_ByAddress_Call) Run(run func(account flow.Address, cursor *access.TransferCursor)) *FungibleTokenTransfersReader_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.TransferCursor + if args[1] != nil { + arg1 = args[1].(*access.TransferCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *FungibleTokenTransfersReader_ByAddress_Call) Return(v storage.FungibleTokenTransferIterator, err error) *FungibleTokenTransfersReader_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *FungibleTokenTransfersReader_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.TransferCursor) (storage.FungibleTokenTransferIterator, error)) *FungibleTokenTransfersReader_ByAddress_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/fungible_token_transfers_writer.go b/storage/mock/fungible_token_transfers_writer.go new file mode 100644 index 00000000000..59923aeefa4 --- /dev/null +++ b/storage/mock/fungible_token_transfers_writer.go @@ -0,0 +1,108 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewFungibleTokenTransfersWriter creates a new instance of FungibleTokenTransfersWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFungibleTokenTransfersWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *FungibleTokenTransfersWriter { + mock := &FungibleTokenTransfersWriter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// FungibleTokenTransfersWriter is an autogenerated mock type for the FungibleTokenTransfersWriter type +type FungibleTokenTransfersWriter struct { + mock.Mock +} + +type FungibleTokenTransfersWriter_Expecter struct { + mock *mock.Mock +} + +func (_m *FungibleTokenTransfersWriter) EXPECT() *FungibleTokenTransfersWriter_Expecter { + return &FungibleTokenTransfersWriter_Expecter{mock: &_m.Mock} +} + +// Store provides a mock function for the type FungibleTokenTransfersWriter +func (_mock *FungibleTokenTransfersWriter) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error { + ret := _mock.Called(lctx, rw, blockHeight, transfers) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.FungibleTokenTransfer) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, transfers) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// FungibleTokenTransfersWriter_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type FungibleTokenTransfersWriter_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - transfers []access.FungibleTokenTransfer +func (_e *FungibleTokenTransfersWriter_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, transfers interface{}) *FungibleTokenTransfersWriter_Store_Call { + return &FungibleTokenTransfersWriter_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, transfers)} +} + +func (_c *FungibleTokenTransfersWriter_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer)) *FungibleTokenTransfersWriter_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.FungibleTokenTransfer + if args[3] != nil { + arg3 = args[3].([]access.FungibleTokenTransfer) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *FungibleTokenTransfersWriter_Store_Call) Return(err error) *FungibleTokenTransfersWriter_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *FungibleTokenTransfersWriter_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.FungibleTokenTransfer) error) *FungibleTokenTransfersWriter_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/guarantees.go b/storage/mock/guarantees.go index 93c59eae208..3b1a7d9ddcf 100644 --- a/storage/mock/guarantees.go +++ b/storage/mock/guarantees.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewGuarantees creates a new instance of Guarantees. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewGuarantees(t interface { + mock.TestingT + Cleanup(func()) +}) *Guarantees { + mock := &Guarantees{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Guarantees is an autogenerated mock type for the Guarantees type type Guarantees struct { mock.Mock } -// ByCollectionID provides a mock function with given fields: collID -func (_m *Guarantees) ByCollectionID(collID flow.Identifier) (*flow.CollectionGuarantee, error) { - ret := _m.Called(collID) +type Guarantees_Expecter struct { + mock *mock.Mock +} + +func (_m *Guarantees) EXPECT() *Guarantees_Expecter { + return &Guarantees_Expecter{mock: &_m.Mock} +} + +// ByCollectionID provides a mock function for the type Guarantees +func (_mock *Guarantees) ByCollectionID(collID flow.Identifier) (*flow.CollectionGuarantee, error) { + ret := _mock.Called(collID) if len(ret) == 0 { panic("no return value specified for ByCollectionID") @@ -22,29 +46,61 @@ func (_m *Guarantees) ByCollectionID(collID flow.Identifier) (*flow.CollectionGu var r0 *flow.CollectionGuarantee var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.CollectionGuarantee, error)); ok { - return rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.CollectionGuarantee, error)); ok { + return returnFunc(collID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.CollectionGuarantee); ok { - r0 = rf(collID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.CollectionGuarantee); ok { + r0 = returnFunc(collID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.CollectionGuarantee) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(collID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(collID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: guaranteeID -func (_m *Guarantees) ByID(guaranteeID flow.Identifier) (*flow.CollectionGuarantee, error) { - ret := _m.Called(guaranteeID) +// Guarantees_ByCollectionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByCollectionID' +type Guarantees_ByCollectionID_Call struct { + *mock.Call +} + +// ByCollectionID is a helper method to define mock.On call +// - collID flow.Identifier +func (_e *Guarantees_Expecter) ByCollectionID(collID interface{}) *Guarantees_ByCollectionID_Call { + return &Guarantees_ByCollectionID_Call{Call: _e.mock.On("ByCollectionID", collID)} +} + +func (_c *Guarantees_ByCollectionID_Call) Run(run func(collID flow.Identifier)) *Guarantees_ByCollectionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Guarantees_ByCollectionID_Call) Return(collectionGuarantee *flow.CollectionGuarantee, err error) *Guarantees_ByCollectionID_Call { + _c.Call.Return(collectionGuarantee, err) + return _c +} + +func (_c *Guarantees_ByCollectionID_Call) RunAndReturn(run func(collID flow.Identifier) (*flow.CollectionGuarantee, error)) *Guarantees_ByCollectionID_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type Guarantees +func (_mock *Guarantees) ByID(guaranteeID flow.Identifier) (*flow.CollectionGuarantee, error) { + ret := _mock.Called(guaranteeID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -52,36 +108,54 @@ func (_m *Guarantees) ByID(guaranteeID flow.Identifier) (*flow.CollectionGuarant var r0 *flow.CollectionGuarantee var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.CollectionGuarantee, error)); ok { - return rf(guaranteeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.CollectionGuarantee, error)); ok { + return returnFunc(guaranteeID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.CollectionGuarantee); ok { - r0 = rf(guaranteeID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.CollectionGuarantee); ok { + r0 = returnFunc(guaranteeID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.CollectionGuarantee) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(guaranteeID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(guaranteeID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewGuarantees creates a new instance of Guarantees. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewGuarantees(t interface { - mock.TestingT - Cleanup(func()) -}) *Guarantees { - mock := &Guarantees{} - mock.Mock.Test(t) +// Guarantees_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type Guarantees_ByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByID is a helper method to define mock.On call +// - guaranteeID flow.Identifier +func (_e *Guarantees_Expecter) ByID(guaranteeID interface{}) *Guarantees_ByID_Call { + return &Guarantees_ByID_Call{Call: _e.mock.On("ByID", guaranteeID)} +} - return mock +func (_c *Guarantees_ByID_Call) Run(run func(guaranteeID flow.Identifier)) *Guarantees_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Guarantees_ByID_Call) Return(collectionGuarantee *flow.CollectionGuarantee, err error) *Guarantees_ByID_Call { + _c.Call.Return(collectionGuarantee, err) + return _c +} + +func (_c *Guarantees_ByID_Call) RunAndReturn(run func(guaranteeID flow.Identifier) (*flow.CollectionGuarantee, error)) *Guarantees_ByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/headers.go b/storage/mock/headers.go index f179da8186e..bc87afef241 100644 --- a/storage/mock/headers.go +++ b/storage/mock/headers.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewHeaders creates a new instance of Headers. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewHeaders(t interface { + mock.TestingT + Cleanup(func()) +}) *Headers { + mock := &Headers{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Headers is an autogenerated mock type for the Headers type type Headers struct { mock.Mock } -// BlockIDByHeight provides a mock function with given fields: height -func (_m *Headers) BlockIDByHeight(height uint64) (flow.Identifier, error) { - ret := _m.Called(height) +type Headers_Expecter struct { + mock *mock.Mock +} + +func (_m *Headers) EXPECT() *Headers_Expecter { + return &Headers_Expecter{mock: &_m.Mock} +} + +// BlockIDByHeight provides a mock function for the type Headers +func (_mock *Headers) BlockIDByHeight(height uint64) (flow.Identifier, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for BlockIDByHeight") @@ -22,29 +46,61 @@ func (_m *Headers) BlockIDByHeight(height uint64) (flow.Identifier, error) { var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *Headers) ByBlockID(blockID flow.Identifier) (*flow.Header, error) { - ret := _m.Called(blockID) +// Headers_BlockIDByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockIDByHeight' +type Headers_BlockIDByHeight_Call struct { + *mock.Call +} + +// BlockIDByHeight is a helper method to define mock.On call +// - height uint64 +func (_e *Headers_Expecter) BlockIDByHeight(height interface{}) *Headers_BlockIDByHeight_Call { + return &Headers_BlockIDByHeight_Call{Call: _e.mock.On("BlockIDByHeight", height)} +} + +func (_c *Headers_BlockIDByHeight_Call) Run(run func(height uint64)) *Headers_BlockIDByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Headers_BlockIDByHeight_Call) Return(identifier flow.Identifier, err error) *Headers_BlockIDByHeight_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *Headers_BlockIDByHeight_Call) RunAndReturn(run func(height uint64) (flow.Identifier, error)) *Headers_BlockIDByHeight_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type Headers +func (_mock *Headers) ByBlockID(blockID flow.Identifier) (*flow.Header, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -52,29 +108,61 @@ func (_m *Headers) ByBlockID(blockID flow.Identifier) (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Header, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Header, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Header); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Header); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByHeight provides a mock function with given fields: height -func (_m *Headers) ByHeight(height uint64) (*flow.Header, error) { - ret := _m.Called(height) +// Headers_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type Headers_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Headers_Expecter) ByBlockID(blockID interface{}) *Headers_ByBlockID_Call { + return &Headers_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *Headers_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *Headers_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Headers_ByBlockID_Call) Return(header *flow.Header, err error) *Headers_ByBlockID_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Headers_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.Header, error)) *Headers_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByHeight provides a mock function for the type Headers +func (_mock *Headers) ByHeight(height uint64) (*flow.Header, error) { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for ByHeight") @@ -82,29 +170,61 @@ func (_m *Headers) ByHeight(height uint64) (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*flow.Header, error)); ok { - return rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) (*flow.Header, error)); ok { + return returnFunc(height) } - if rf, ok := ret.Get(0).(func(uint64) *flow.Header); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) *flow.Header); ok { + r0 = returnFunc(height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(height) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(height) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByParentID provides a mock function with given fields: parentID -func (_m *Headers) ByParentID(parentID flow.Identifier) ([]*flow.Header, error) { - ret := _m.Called(parentID) +// Headers_ByHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByHeight' +type Headers_ByHeight_Call struct { + *mock.Call +} + +// ByHeight is a helper method to define mock.On call +// - height uint64 +func (_e *Headers_Expecter) ByHeight(height interface{}) *Headers_ByHeight_Call { + return &Headers_ByHeight_Call{Call: _e.mock.On("ByHeight", height)} +} + +func (_c *Headers_ByHeight_Call) Run(run func(height uint64)) *Headers_ByHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Headers_ByHeight_Call) Return(header *flow.Header, err error) *Headers_ByHeight_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Headers_ByHeight_Call) RunAndReturn(run func(height uint64) (*flow.Header, error)) *Headers_ByHeight_Call { + _c.Call.Return(run) + return _c +} + +// ByParentID provides a mock function for the type Headers +func (_mock *Headers) ByParentID(parentID flow.Identifier) ([]*flow.Header, error) { + ret := _mock.Called(parentID) if len(ret) == 0 { panic("no return value specified for ByParentID") @@ -112,29 +232,61 @@ func (_m *Headers) ByParentID(parentID flow.Identifier) ([]*flow.Header, error) var r0 []*flow.Header var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]*flow.Header, error)); ok { - return rf(parentID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]*flow.Header, error)); ok { + return returnFunc(parentID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []*flow.Header); ok { - r0 = rf(parentID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []*flow.Header); ok { + r0 = returnFunc(parentID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*flow.Header) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(parentID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(parentID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByView provides a mock function with given fields: view -func (_m *Headers) ByView(view uint64) (*flow.Header, error) { - ret := _m.Called(view) +// Headers_ByParentID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByParentID' +type Headers_ByParentID_Call struct { + *mock.Call +} + +// ByParentID is a helper method to define mock.On call +// - parentID flow.Identifier +func (_e *Headers_Expecter) ByParentID(parentID interface{}) *Headers_ByParentID_Call { + return &Headers_ByParentID_Call{Call: _e.mock.On("ByParentID", parentID)} +} + +func (_c *Headers_ByParentID_Call) Run(run func(parentID flow.Identifier)) *Headers_ByParentID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Headers_ByParentID_Call) Return(headers []*flow.Header, err error) *Headers_ByParentID_Call { + _c.Call.Return(headers, err) + return _c +} + +func (_c *Headers_ByParentID_Call) RunAndReturn(run func(parentID flow.Identifier) ([]*flow.Header, error)) *Headers_ByParentID_Call { + _c.Call.Return(run) + return _c +} + +// ByView provides a mock function for the type Headers +func (_mock *Headers) ByView(view uint64) (*flow.Header, error) { + ret := _mock.Called(view) if len(ret) == 0 { panic("no return value specified for ByView") @@ -142,29 +294,61 @@ func (_m *Headers) ByView(view uint64) (*flow.Header, error) { var r0 *flow.Header var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*flow.Header, error)); ok { - return rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) (*flow.Header, error)); ok { + return returnFunc(view) } - if rf, ok := ret.Get(0).(func(uint64) *flow.Header); ok { - r0 = rf(view) + if returnFunc, ok := ret.Get(0).(func(uint64) *flow.Header); ok { + r0 = returnFunc(view) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Header) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(view) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(view) } else { r1 = ret.Error(1) } - return r0, r1 } -// Exists provides a mock function with given fields: blockID -func (_m *Headers) Exists(blockID flow.Identifier) (bool, error) { - ret := _m.Called(blockID) +// Headers_ByView_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByView' +type Headers_ByView_Call struct { + *mock.Call +} + +// ByView is a helper method to define mock.On call +// - view uint64 +func (_e *Headers_Expecter) ByView(view interface{}) *Headers_ByView_Call { + return &Headers_ByView_Call{Call: _e.mock.On("ByView", view)} +} + +func (_c *Headers_ByView_Call) Run(run func(view uint64)) *Headers_ByView_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Headers_ByView_Call) Return(header *flow.Header, err error) *Headers_ByView_Call { + _c.Call.Return(header, err) + return _c +} + +func (_c *Headers_ByView_Call) RunAndReturn(run func(view uint64) (*flow.Header, error)) *Headers_ByView_Call { + _c.Call.Return(run) + return _c +} + +// Exists provides a mock function for the type Headers +func (_mock *Headers) Exists(blockID flow.Identifier) (bool, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for Exists") @@ -172,27 +356,59 @@ func (_m *Headers) Exists(blockID flow.Identifier) (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ProposalByBlockID provides a mock function with given fields: blockID -func (_m *Headers) ProposalByBlockID(blockID flow.Identifier) (*flow.ProposalHeader, error) { - ret := _m.Called(blockID) +// Headers_Exists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Exists' +type Headers_Exists_Call struct { + *mock.Call +} + +// Exists is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Headers_Expecter) Exists(blockID interface{}) *Headers_Exists_Call { + return &Headers_Exists_Call{Call: _e.mock.On("Exists", blockID)} +} + +func (_c *Headers_Exists_Call) Run(run func(blockID flow.Identifier)) *Headers_Exists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Headers_Exists_Call) Return(b bool, err error) *Headers_Exists_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *Headers_Exists_Call) RunAndReturn(run func(blockID flow.Identifier) (bool, error)) *Headers_Exists_Call { + _c.Call.Return(run) + return _c +} + +// ProposalByBlockID provides a mock function for the type Headers +func (_mock *Headers) ProposalByBlockID(blockID flow.Identifier) (*flow.ProposalHeader, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ProposalByBlockID") @@ -200,36 +416,54 @@ func (_m *Headers) ProposalByBlockID(blockID flow.Identifier) (*flow.ProposalHea var r0 *flow.ProposalHeader var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ProposalHeader, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ProposalHeader, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ProposalHeader); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ProposalHeader); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ProposalHeader) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewHeaders creates a new instance of Headers. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewHeaders(t interface { - mock.TestingT - Cleanup(func()) -}) *Headers { - mock := &Headers{} - mock.Mock.Test(t) +// Headers_ProposalByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProposalByBlockID' +type Headers_ProposalByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ProposalByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Headers_Expecter) ProposalByBlockID(blockID interface{}) *Headers_ProposalByBlockID_Call { + return &Headers_ProposalByBlockID_Call{Call: _e.mock.On("ProposalByBlockID", blockID)} +} - return mock +func (_c *Headers_ProposalByBlockID_Call) Run(run func(blockID flow.Identifier)) *Headers_ProposalByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Headers_ProposalByBlockID_Call) Return(proposalHeader *flow.ProposalHeader, err error) *Headers_ProposalByBlockID_Call { + _c.Call.Return(proposalHeader, err) + return _c +} + +func (_c *Headers_ProposalByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.ProposalHeader, error)) *Headers_ProposalByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/height_index.go b/storage/mock/height_index.go index 0b25bf331dc..16f15f50f88 100644 --- a/storage/mock/height_index.go +++ b/storage/mock/height_index.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewHeightIndex creates a new instance of HeightIndex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewHeightIndex(t interface { + mock.TestingT + Cleanup(func()) +}) *HeightIndex { + mock := &HeightIndex{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // HeightIndex is an autogenerated mock type for the HeightIndex type type HeightIndex struct { mock.Mock } -// FirstHeight provides a mock function with no fields -func (_m *HeightIndex) FirstHeight() (uint64, error) { - ret := _m.Called() +type HeightIndex_Expecter struct { + mock *mock.Mock +} + +func (_m *HeightIndex) EXPECT() *HeightIndex_Expecter { + return &HeightIndex_Expecter{mock: &_m.Mock} +} + +// FirstHeight provides a mock function for the type HeightIndex +func (_mock *HeightIndex) FirstHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FirstHeight") @@ -19,27 +45,52 @@ func (_m *HeightIndex) FirstHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// LatestHeight provides a mock function with no fields -func (_m *HeightIndex) LatestHeight() (uint64, error) { - ret := _m.Called() +// HeightIndex_FirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstHeight' +type HeightIndex_FirstHeight_Call struct { + *mock.Call +} + +// FirstHeight is a helper method to define mock.On call +func (_e *HeightIndex_Expecter) FirstHeight() *HeightIndex_FirstHeight_Call { + return &HeightIndex_FirstHeight_Call{Call: _e.mock.On("FirstHeight")} +} + +func (_c *HeightIndex_FirstHeight_Call) Run(run func()) *HeightIndex_FirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HeightIndex_FirstHeight_Call) Return(v uint64, err error) *HeightIndex_FirstHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *HeightIndex_FirstHeight_Call) RunAndReturn(run func() (uint64, error)) *HeightIndex_FirstHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestHeight provides a mock function for the type HeightIndex +func (_mock *HeightIndex) LatestHeight() (uint64, error) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LatestHeight") @@ -47,52 +98,96 @@ func (_m *HeightIndex) LatestHeight() (uint64, error) { var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func() (uint64, error)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() } else { r1 = ret.Error(1) } - return r0, r1 } -// SetLatestHeight provides a mock function with given fields: height -func (_m *HeightIndex) SetLatestHeight(height uint64) error { - ret := _m.Called(height) +// HeightIndex_LatestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestHeight' +type HeightIndex_LatestHeight_Call struct { + *mock.Call +} + +// LatestHeight is a helper method to define mock.On call +func (_e *HeightIndex_Expecter) LatestHeight() *HeightIndex_LatestHeight_Call { + return &HeightIndex_LatestHeight_Call{Call: _e.mock.On("LatestHeight")} +} + +func (_c *HeightIndex_LatestHeight_Call) Run(run func()) *HeightIndex_LatestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *HeightIndex_LatestHeight_Call) Return(v uint64, err error) *HeightIndex_LatestHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *HeightIndex_LatestHeight_Call) RunAndReturn(run func() (uint64, error)) *HeightIndex_LatestHeight_Call { + _c.Call.Return(run) + return _c +} + +// SetLatestHeight provides a mock function for the type HeightIndex +func (_mock *HeightIndex) SetLatestHeight(height uint64) error { + ret := _mock.Called(height) if len(ret) == 0 { panic("no return value specified for SetLatestHeight") } var r0 error - if rf, ok := ret.Get(0).(func(uint64) error); ok { - r0 = rf(height) + if returnFunc, ok := ret.Get(0).(func(uint64) error); ok { + r0 = returnFunc(height) } else { r0 = ret.Error(0) } - return r0 } -// NewHeightIndex creates a new instance of HeightIndex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewHeightIndex(t interface { - mock.TestingT - Cleanup(func()) -}) *HeightIndex { - mock := &HeightIndex{} - mock.Mock.Test(t) +// HeightIndex_SetLatestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetLatestHeight' +type HeightIndex_SetLatestHeight_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SetLatestHeight is a helper method to define mock.On call +// - height uint64 +func (_e *HeightIndex_Expecter) SetLatestHeight(height interface{}) *HeightIndex_SetLatestHeight_Call { + return &HeightIndex_SetLatestHeight_Call{Call: _e.mock.On("SetLatestHeight", height)} +} - return mock +func (_c *HeightIndex_SetLatestHeight_Call) Run(run func(height uint64)) *HeightIndex_SetLatestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *HeightIndex_SetLatestHeight_Call) Return(err error) *HeightIndex_SetLatestHeight_Call { + _c.Call.Return(err) + return _c +} + +func (_c *HeightIndex_SetLatestHeight_Call) RunAndReturn(run func(height uint64) error) *HeightIndex_SetLatestHeight_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/index.go b/storage/mock/index.go index 382c0f8f434..37112178e18 100644 --- a/storage/mock/index.go +++ b/storage/mock/index.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewIndex creates a new instance of Index. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIndex(t interface { + mock.TestingT + Cleanup(func()) +}) *Index { + mock := &Index{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Index is an autogenerated mock type for the Index type type Index struct { mock.Mock } -// ByBlockID provides a mock function with given fields: blockID -func (_m *Index) ByBlockID(blockID flow.Identifier) (*flow.Index, error) { - ret := _m.Called(blockID) +type Index_Expecter struct { + mock *mock.Mock +} + +func (_m *Index) EXPECT() *Index_Expecter { + return &Index_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type Index +func (_mock *Index) ByBlockID(blockID flow.Identifier) (*flow.Index, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,36 +46,54 @@ func (_m *Index) ByBlockID(blockID flow.Identifier) (*flow.Index, error) { var r0 *flow.Index var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Index, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Index, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Index); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Index); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Index) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewIndex creates a new instance of Index. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIndex(t interface { - mock.TestingT - Cleanup(func()) -}) *Index { - mock := &Index{} - mock.Mock.Test(t) +// Index_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type Index_ByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Index_Expecter) ByBlockID(blockID interface{}) *Index_ByBlockID_Call { + return &Index_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} - return mock +func (_c *Index_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *Index_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Index_ByBlockID_Call) Return(index *flow.Index, err error) *Index_ByBlockID_Call { + _c.Call.Return(index, err) + return _c +} + +func (_c *Index_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.Index, error)) *Index_ByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/iter_item.go b/storage/mock/iter_item.go index 6a2e8220d76..120f9a03b4b 100644 --- a/storage/mock/iter_item.go +++ b/storage/mock/iter_item.go @@ -1,82 +1,186 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewIterItem creates a new instance of IterItem. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIterItem(t interface { + mock.TestingT + Cleanup(func()) +}) *IterItem { + mock := &IterItem{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // IterItem is an autogenerated mock type for the IterItem type type IterItem struct { mock.Mock } -// Key provides a mock function with no fields -func (_m *IterItem) Key() []byte { - ret := _m.Called() +type IterItem_Expecter struct { + mock *mock.Mock +} + +func (_m *IterItem) EXPECT() *IterItem_Expecter { + return &IterItem_Expecter{mock: &_m.Mock} +} + +// Key provides a mock function for the type IterItem +func (_mock *IterItem) Key() []byte { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Key") } var r0 []byte - if rf, ok := ret.Get(0).(func() []byte); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() []byte); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - return r0 } -// KeyCopy provides a mock function with given fields: dst -func (_m *IterItem) KeyCopy(dst []byte) []byte { - ret := _m.Called(dst) +// IterItem_Key_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Key' +type IterItem_Key_Call struct { + *mock.Call +} + +// Key is a helper method to define mock.On call +func (_e *IterItem_Expecter) Key() *IterItem_Key_Call { + return &IterItem_Key_Call{Call: _e.mock.On("Key")} +} + +func (_c *IterItem_Key_Call) Run(run func()) *IterItem_Key_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IterItem_Key_Call) Return(bytes []byte) *IterItem_Key_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *IterItem_Key_Call) RunAndReturn(run func() []byte) *IterItem_Key_Call { + _c.Call.Return(run) + return _c +} + +// KeyCopy provides a mock function for the type IterItem +func (_mock *IterItem) KeyCopy(dst []byte) []byte { + ret := _mock.Called(dst) if len(ret) == 0 { panic("no return value specified for KeyCopy") } var r0 []byte - if rf, ok := ret.Get(0).(func([]byte) []byte); ok { - r0 = rf(dst) + if returnFunc, ok := ret.Get(0).(func([]byte) []byte); ok { + r0 = returnFunc(dst) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - return r0 } -// Value provides a mock function with given fields: _a0 -func (_m *IterItem) Value(_a0 func([]byte) error) error { - ret := _m.Called(_a0) +// IterItem_KeyCopy_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'KeyCopy' +type IterItem_KeyCopy_Call struct { + *mock.Call +} + +// KeyCopy is a helper method to define mock.On call +// - dst []byte +func (_e *IterItem_Expecter) KeyCopy(dst interface{}) *IterItem_KeyCopy_Call { + return &IterItem_KeyCopy_Call{Call: _e.mock.On("KeyCopy", dst)} +} + +func (_c *IterItem_KeyCopy_Call) Run(run func(dst []byte)) *IterItem_KeyCopy_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IterItem_KeyCopy_Call) Return(bytes []byte) *IterItem_KeyCopy_Call { + _c.Call.Return(bytes) + return _c +} + +func (_c *IterItem_KeyCopy_Call) RunAndReturn(run func(dst []byte) []byte) *IterItem_KeyCopy_Call { + _c.Call.Return(run) + return _c +} + +// Value provides a mock function for the type IterItem +func (_mock *IterItem) Value(fn func(val []byte) error) error { + ret := _mock.Called(fn) if len(ret) == 0 { panic("no return value specified for Value") } var r0 error - if rf, ok := ret.Get(0).(func(func([]byte) error) error); ok { - r0 = rf(_a0) + if returnFunc, ok := ret.Get(0).(func(func(val []byte) error) error); ok { + r0 = returnFunc(fn) } else { r0 = ret.Error(0) } - return r0 } -// NewIterItem creates a new instance of IterItem. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIterItem(t interface { - mock.TestingT - Cleanup(func()) -}) *IterItem { - mock := &IterItem{} - mock.Mock.Test(t) +// IterItem_Value_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Value' +type IterItem_Value_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Value is a helper method to define mock.On call +// - fn func(val []byte) error +func (_e *IterItem_Expecter) Value(fn interface{}) *IterItem_Value_Call { + return &IterItem_Value_Call{Call: _e.mock.On("Value", fn)} +} - return mock +func (_c *IterItem_Value_Call) Run(run func(fn func(val []byte) error)) *IterItem_Value_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(val []byte) error + if args[0] != nil { + arg0 = args[0].(func(val []byte) error) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *IterItem_Value_Call) Return(err error) *IterItem_Value_Call { + _c.Call.Return(err) + return _c +} + +func (_c *IterItem_Value_Call) RunAndReturn(run func(fn func(val []byte) error) error) *IterItem_Value_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/iterator.go b/storage/mock/iterator.go index 5a27dc28063..6d0c39e0400 100644 --- a/storage/mock/iterator.go +++ b/storage/mock/iterator.go @@ -1,106 +1,248 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewIterator creates a new instance of Iterator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIterator(t interface { + mock.TestingT + Cleanup(func()) +}) *Iterator { + mock := &Iterator{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Iterator is an autogenerated mock type for the Iterator type type Iterator struct { mock.Mock } -// Close provides a mock function with no fields -func (_m *Iterator) Close() error { - ret := _m.Called() +type Iterator_Expecter struct { + mock *mock.Mock +} + +func (_m *Iterator) EXPECT() *Iterator_Expecter { + return &Iterator_Expecter{mock: &_m.Mock} +} + +// Close provides a mock function for the type Iterator +func (_mock *Iterator) Close() error { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Close") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() error); ok { + r0 = returnFunc() } else { r0 = ret.Error(0) } - return r0 } -// First provides a mock function with no fields -func (_m *Iterator) First() bool { - ret := _m.Called() +// Iterator_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close' +type Iterator_Close_Call struct { + *mock.Call +} + +// Close is a helper method to define mock.On call +func (_e *Iterator_Expecter) Close() *Iterator_Close_Call { + return &Iterator_Close_Call{Call: _e.mock.On("Close")} +} + +func (_c *Iterator_Close_Call) Run(run func()) *Iterator_Close_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Iterator_Close_Call) Return(err error) *Iterator_Close_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Iterator_Close_Call) RunAndReturn(run func() error) *Iterator_Close_Call { + _c.Call.Return(run) + return _c +} + +// First provides a mock function for the type Iterator +func (_mock *Iterator) First() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for First") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// IterItem provides a mock function with no fields -func (_m *Iterator) IterItem() storage.IterItem { - ret := _m.Called() +// Iterator_First_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'First' +type Iterator_First_Call struct { + *mock.Call +} + +// First is a helper method to define mock.On call +func (_e *Iterator_Expecter) First() *Iterator_First_Call { + return &Iterator_First_Call{Call: _e.mock.On("First")} +} + +func (_c *Iterator_First_Call) Run(run func()) *Iterator_First_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Iterator_First_Call) Return(b bool) *Iterator_First_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Iterator_First_Call) RunAndReturn(run func() bool) *Iterator_First_Call { + _c.Call.Return(run) + return _c +} + +// IterItem provides a mock function for the type Iterator +func (_mock *Iterator) IterItem() storage.IterItem { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for IterItem") } var r0 storage.IterItem - if rf, ok := ret.Get(0).(func() storage.IterItem); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.IterItem); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.IterItem) } } - return r0 } -// Next provides a mock function with no fields -func (_m *Iterator) Next() { - _m.Called() +// Iterator_IterItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IterItem' +type Iterator_IterItem_Call struct { + *mock.Call +} + +// IterItem is a helper method to define mock.On call +func (_e *Iterator_Expecter) IterItem() *Iterator_IterItem_Call { + return &Iterator_IterItem_Call{Call: _e.mock.On("IterItem")} +} + +func (_c *Iterator_IterItem_Call) Run(run func()) *Iterator_IterItem_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Iterator_IterItem_Call) Return(iterItem storage.IterItem) *Iterator_IterItem_Call { + _c.Call.Return(iterItem) + return _c +} + +func (_c *Iterator_IterItem_Call) RunAndReturn(run func() storage.IterItem) *Iterator_IterItem_Call { + _c.Call.Return(run) + return _c } -// Valid provides a mock function with no fields -func (_m *Iterator) Valid() bool { - ret := _m.Called() +// Next provides a mock function for the type Iterator +func (_mock *Iterator) Next() { + _mock.Called() + return +} + +// Iterator_Next_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Next' +type Iterator_Next_Call struct { + *mock.Call +} + +// Next is a helper method to define mock.On call +func (_e *Iterator_Expecter) Next() *Iterator_Next_Call { + return &Iterator_Next_Call{Call: _e.mock.On("Next")} +} + +func (_c *Iterator_Next_Call) Run(run func()) *Iterator_Next_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Iterator_Next_Call) Return() *Iterator_Next_Call { + _c.Call.Return() + return _c +} + +func (_c *Iterator_Next_Call) RunAndReturn(run func()) *Iterator_Next_Call { + _c.Run(run) + return _c +} + +// Valid provides a mock function for the type Iterator +func (_mock *Iterator) Valid() bool { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Valid") } var r0 bool - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() bool); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(bool) } - return r0 } -// NewIterator creates a new instance of Iterator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewIterator(t interface { - mock.TestingT - Cleanup(func()) -}) *Iterator { - mock := &Iterator{} - mock.Mock.Test(t) +// Iterator_Valid_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Valid' +type Iterator_Valid_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Valid is a helper method to define mock.On call +func (_e *Iterator_Expecter) Valid() *Iterator_Valid_Call { + return &Iterator_Valid_Call{Call: _e.mock.On("Valid")} +} - return mock +func (_c *Iterator_Valid_Call) Run(run func()) *Iterator_Valid_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Iterator_Valid_Call) Return(b bool) *Iterator_Valid_Call { + _c.Call.Return(b) + return _c +} + +func (_c *Iterator_Valid_Call) RunAndReturn(run func() bool) *Iterator_Valid_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/iterator_entry.go b/storage/mock/iterator_entry.go new file mode 100644 index 00000000000..d2c24448299 --- /dev/null +++ b/storage/mock/iterator_entry.go @@ -0,0 +1,137 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewIteratorEntry creates a new instance of IteratorEntry. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIteratorEntry[T any, C any](t interface { + mock.TestingT + Cleanup(func()) +}) *IteratorEntry[T, C] { + mock := &IteratorEntry[T, C]{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// IteratorEntry is an autogenerated mock type for the IteratorEntry type +type IteratorEntry[T any, C any] struct { + mock.Mock +} + +type IteratorEntry_Expecter[T any, C any] struct { + mock *mock.Mock +} + +func (_m *IteratorEntry[T, C]) EXPECT() *IteratorEntry_Expecter[T, C] { + return &IteratorEntry_Expecter[T, C]{mock: &_m.Mock} +} + +// Cursor provides a mock function for the type IteratorEntry +func (_mock *IteratorEntry[T, C]) Cursor() C { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Cursor") + } + + var r0 C + if returnFunc, ok := ret.Get(0).(func() C); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(C) + } + } + return r0 +} + +// IteratorEntry_Cursor_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Cursor' +type IteratorEntry_Cursor_Call[T any, C any] struct { + *mock.Call +} + +// Cursor is a helper method to define mock.On call +func (_e *IteratorEntry_Expecter[T, C]) Cursor() *IteratorEntry_Cursor_Call[T, C] { + return &IteratorEntry_Cursor_Call[T, C]{Call: _e.mock.On("Cursor")} +} + +func (_c *IteratorEntry_Cursor_Call[T, C]) Run(run func()) *IteratorEntry_Cursor_Call[T, C] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IteratorEntry_Cursor_Call[T, C]) Return(v C) *IteratorEntry_Cursor_Call[T, C] { + _c.Call.Return(v) + return _c +} + +func (_c *IteratorEntry_Cursor_Call[T, C]) RunAndReturn(run func() C) *IteratorEntry_Cursor_Call[T, C] { + _c.Call.Return(run) + return _c +} + +// Value provides a mock function for the type IteratorEntry +func (_mock *IteratorEntry[T, C]) Value() (T, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for Value") + } + + var r0 T + var r1 error + if returnFunc, ok := ret.Get(0).(func() (T, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() T); ok { + r0 = returnFunc() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(T) + } + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// IteratorEntry_Value_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Value' +type IteratorEntry_Value_Call[T any, C any] struct { + *mock.Call +} + +// Value is a helper method to define mock.On call +func (_e *IteratorEntry_Expecter[T, C]) Value() *IteratorEntry_Value_Call[T, C] { + return &IteratorEntry_Value_Call[T, C]{Call: _e.mock.On("Value")} +} + +func (_c *IteratorEntry_Value_Call[T, C]) Run(run func()) *IteratorEntry_Value_Call[T, C] { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *IteratorEntry_Value_Call[T, C]) Return(v T, err error) *IteratorEntry_Value_Call[T, C] { + _c.Call.Return(v, err) + return _c +} + +func (_c *IteratorEntry_Value_Call[T, C]) RunAndReturn(run func() (T, error)) *IteratorEntry_Value_Call[T, C] { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/latest_persisted_sealed_result.go b/storage/mock/latest_persisted_sealed_result.go index 6481b95e3e3..159ac82eec0 100644 --- a/storage/mock/latest_persisted_sealed_result.go +++ b/storage/mock/latest_persisted_sealed_result.go @@ -1,40 +1,108 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewLatestPersistedSealedResult creates a new instance of LatestPersistedSealedResult. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLatestPersistedSealedResult(t interface { + mock.TestingT + Cleanup(func()) +}) *LatestPersistedSealedResult { + mock := &LatestPersistedSealedResult{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LatestPersistedSealedResult is an autogenerated mock type for the LatestPersistedSealedResult type type LatestPersistedSealedResult struct { mock.Mock } -// BatchSet provides a mock function with given fields: resultID, height, batch -func (_m *LatestPersistedSealedResult) BatchSet(resultID flow.Identifier, height uint64, batch storage.ReaderBatchWriter) error { - ret := _m.Called(resultID, height, batch) +type LatestPersistedSealedResult_Expecter struct { + mock *mock.Mock +} + +func (_m *LatestPersistedSealedResult) EXPECT() *LatestPersistedSealedResult_Expecter { + return &LatestPersistedSealedResult_Expecter{mock: &_m.Mock} +} + +// BatchSet provides a mock function for the type LatestPersistedSealedResult +func (_mock *LatestPersistedSealedResult) BatchSet(resultID flow.Identifier, height uint64, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(resultID, height, batch) if len(ret) == 0 { panic("no return value specified for BatchSet") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint64, storage.ReaderBatchWriter) error); ok { - r0 = rf(resultID, height, batch) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint64, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(resultID, height, batch) } else { r0 = ret.Error(0) } - return r0 } -// Latest provides a mock function with no fields -func (_m *LatestPersistedSealedResult) Latest() (flow.Identifier, uint64) { - ret := _m.Called() +// LatestPersistedSealedResult_BatchSet_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchSet' +type LatestPersistedSealedResult_BatchSet_Call struct { + *mock.Call +} + +// BatchSet is a helper method to define mock.On call +// - resultID flow.Identifier +// - height uint64 +// - batch storage.ReaderBatchWriter +func (_e *LatestPersistedSealedResult_Expecter) BatchSet(resultID interface{}, height interface{}, batch interface{}) *LatestPersistedSealedResult_BatchSet_Call { + return &LatestPersistedSealedResult_BatchSet_Call{Call: _e.mock.On("BatchSet", resultID, height, batch)} +} + +func (_c *LatestPersistedSealedResult_BatchSet_Call) Run(run func(resultID flow.Identifier, height uint64, batch storage.ReaderBatchWriter)) *LatestPersistedSealedResult_BatchSet_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 storage.ReaderBatchWriter + if args[2] != nil { + arg2 = args[2].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *LatestPersistedSealedResult_BatchSet_Call) Return(err error) *LatestPersistedSealedResult_BatchSet_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LatestPersistedSealedResult_BatchSet_Call) RunAndReturn(run func(resultID flow.Identifier, height uint64, batch storage.ReaderBatchWriter) error) *LatestPersistedSealedResult_BatchSet_Call { + _c.Call.Return(run) + return _c +} + +// Latest provides a mock function for the type LatestPersistedSealedResult +func (_mock *LatestPersistedSealedResult) Latest() (flow.Identifier, uint64) { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Latest") @@ -42,36 +110,47 @@ func (_m *LatestPersistedSealedResult) Latest() (flow.Identifier, uint64) { var r0 flow.Identifier var r1 uint64 - if rf, ok := ret.Get(0).(func() (flow.Identifier, uint64)); ok { - return rf() + if returnFunc, ok := ret.Get(0).(func() (flow.Identifier, uint64)); ok { + return returnFunc() } - if rf, ok := ret.Get(0).(func() flow.Identifier); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.Identifier); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func() uint64); ok { - r1 = rf() + if returnFunc, ok := ret.Get(1).(func() uint64); ok { + r1 = returnFunc() } else { r1 = ret.Get(1).(uint64) } - return r0, r1 } -// NewLatestPersistedSealedResult creates a new instance of LatestPersistedSealedResult. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLatestPersistedSealedResult(t interface { - mock.TestingT - Cleanup(func()) -}) *LatestPersistedSealedResult { - mock := &LatestPersistedSealedResult{} - mock.Mock.Test(t) +// LatestPersistedSealedResult_Latest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Latest' +type LatestPersistedSealedResult_Latest_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Latest is a helper method to define mock.On call +func (_e *LatestPersistedSealedResult_Expecter) Latest() *LatestPersistedSealedResult_Latest_Call { + return &LatestPersistedSealedResult_Latest_Call{Call: _e.mock.On("Latest")} +} - return mock +func (_c *LatestPersistedSealedResult_Latest_Call) Run(run func()) *LatestPersistedSealedResult_Latest_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LatestPersistedSealedResult_Latest_Call) Return(identifier flow.Identifier, v uint64) *LatestPersistedSealedResult_Latest_Call { + _c.Call.Return(identifier, v) + return _c +} + +func (_c *LatestPersistedSealedResult_Latest_Call) RunAndReturn(run func() (flow.Identifier, uint64)) *LatestPersistedSealedResult_Latest_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/ledger.go b/storage/mock/ledger.go index 5ca49f03591..d8676bebb12 100644 --- a/storage/mock/ledger.go +++ b/storage/mock/ledger.go @@ -1,40 +1,90 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewLedger creates a new instance of Ledger. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLedger(t interface { + mock.TestingT + Cleanup(func()) +}) *Ledger { + mock := &Ledger{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Ledger is an autogenerated mock type for the Ledger type type Ledger struct { mock.Mock } -// EmptyStateCommitment provides a mock function with no fields -func (_m *Ledger) EmptyStateCommitment() flow.StateCommitment { - ret := _m.Called() +type Ledger_Expecter struct { + mock *mock.Mock +} + +func (_m *Ledger) EXPECT() *Ledger_Expecter { + return &Ledger_Expecter{mock: &_m.Mock} +} + +// EmptyStateCommitment provides a mock function for the type Ledger +func (_mock *Ledger) EmptyStateCommitment() flow.StateCommitment { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for EmptyStateCommitment") } var r0 flow.StateCommitment - if rf, ok := ret.Get(0).(func() flow.StateCommitment); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() flow.StateCommitment); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - return r0 } -// GetRegisters provides a mock function with given fields: registerIDs, stateCommitment -func (_m *Ledger) GetRegisters(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment) ([]flow.RegisterValue, error) { - ret := _m.Called(registerIDs, stateCommitment) +// Ledger_EmptyStateCommitment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EmptyStateCommitment' +type Ledger_EmptyStateCommitment_Call struct { + *mock.Call +} + +// EmptyStateCommitment is a helper method to define mock.On call +func (_e *Ledger_Expecter) EmptyStateCommitment() *Ledger_EmptyStateCommitment_Call { + return &Ledger_EmptyStateCommitment_Call{Call: _e.mock.On("EmptyStateCommitment")} +} + +func (_c *Ledger_EmptyStateCommitment_Call) Run(run func()) *Ledger_EmptyStateCommitment_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Ledger_EmptyStateCommitment_Call) Return(stateCommitment flow.StateCommitment) *Ledger_EmptyStateCommitment_Call { + _c.Call.Return(stateCommitment) + return _c +} + +func (_c *Ledger_EmptyStateCommitment_Call) RunAndReturn(run func() flow.StateCommitment) *Ledger_EmptyStateCommitment_Call { + _c.Call.Return(run) + return _c +} + +// GetRegisters provides a mock function for the type Ledger +func (_mock *Ledger) GetRegisters(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment) ([]flow.RegisterValue, error) { + ret := _mock.Called(registerIDs, stateCommitment) if len(ret) == 0 { panic("no return value specified for GetRegisters") @@ -42,29 +92,67 @@ func (_m *Ledger) GetRegisters(registerIDs []flow.RegisterID, stateCommitment fl var r0 []flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) ([]flow.RegisterValue, error)); ok { - return rf(registerIDs, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) ([]flow.RegisterValue, error)); ok { + return returnFunc(registerIDs, stateCommitment) } - if rf, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) []flow.RegisterValue); ok { - r0 = rf(registerIDs, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) []flow.RegisterValue); ok { + r0 = returnFunc(registerIDs, stateCommitment) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func([]flow.RegisterID, flow.StateCommitment) error); ok { - r1 = rf(registerIDs, stateCommitment) + if returnFunc, ok := ret.Get(1).(func([]flow.RegisterID, flow.StateCommitment) error); ok { + r1 = returnFunc(registerIDs, stateCommitment) } else { r1 = ret.Error(1) } - return r0, r1 } -// GetRegistersWithProof provides a mock function with given fields: registerIDs, stateCommitment -func (_m *Ledger) GetRegistersWithProof(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment) ([]flow.RegisterValue, []flow.StorageProof, error) { - ret := _m.Called(registerIDs, stateCommitment) +// Ledger_GetRegisters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegisters' +type Ledger_GetRegisters_Call struct { + *mock.Call +} + +// GetRegisters is a helper method to define mock.On call +// - registerIDs []flow.RegisterID +// - stateCommitment flow.StateCommitment +func (_e *Ledger_Expecter) GetRegisters(registerIDs interface{}, stateCommitment interface{}) *Ledger_GetRegisters_Call { + return &Ledger_GetRegisters_Call{Call: _e.mock.On("GetRegisters", registerIDs, stateCommitment)} +} + +func (_c *Ledger_GetRegisters_Call) Run(run func(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment)) *Ledger_GetRegisters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.RegisterID + if args[0] != nil { + arg0 = args[0].([]flow.RegisterID) + } + var arg1 flow.StateCommitment + if args[1] != nil { + arg1 = args[1].(flow.StateCommitment) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Ledger_GetRegisters_Call) Return(values []flow.RegisterValue, err error) *Ledger_GetRegisters_Call { + _c.Call.Return(values, err) + return _c +} + +func (_c *Ledger_GetRegisters_Call) RunAndReturn(run func(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment) ([]flow.RegisterValue, error)) *Ledger_GetRegisters_Call { + _c.Call.Return(run) + return _c +} + +// GetRegistersWithProof provides a mock function for the type Ledger +func (_mock *Ledger) GetRegistersWithProof(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment) ([]flow.RegisterValue, []flow.StorageProof, error) { + ret := _mock.Called(registerIDs, stateCommitment) if len(ret) == 0 { panic("no return value specified for GetRegistersWithProof") @@ -73,37 +161,74 @@ func (_m *Ledger) GetRegistersWithProof(registerIDs []flow.RegisterID, stateComm var r0 []flow.RegisterValue var r1 []flow.StorageProof var r2 error - if rf, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) ([]flow.RegisterValue, []flow.StorageProof, error)); ok { - return rf(registerIDs, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) ([]flow.RegisterValue, []flow.StorageProof, error)); ok { + return returnFunc(registerIDs, stateCommitment) } - if rf, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) []flow.RegisterValue); ok { - r0 = rf(registerIDs, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment) []flow.RegisterValue); ok { + r0 = returnFunc(registerIDs, stateCommitment) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func([]flow.RegisterID, flow.StateCommitment) []flow.StorageProof); ok { - r1 = rf(registerIDs, stateCommitment) + if returnFunc, ok := ret.Get(1).(func([]flow.RegisterID, flow.StateCommitment) []flow.StorageProof); ok { + r1 = returnFunc(registerIDs, stateCommitment) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]flow.StorageProof) } } - - if rf, ok := ret.Get(2).(func([]flow.RegisterID, flow.StateCommitment) error); ok { - r2 = rf(registerIDs, stateCommitment) + if returnFunc, ok := ret.Get(2).(func([]flow.RegisterID, flow.StateCommitment) error); ok { + r2 = returnFunc(registerIDs, stateCommitment) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// UpdateRegisters provides a mock function with given fields: registerIDs, values, stateCommitment -func (_m *Ledger) UpdateRegisters(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment) (flow.StateCommitment, error) { - ret := _m.Called(registerIDs, values, stateCommitment) +// Ledger_GetRegistersWithProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRegistersWithProof' +type Ledger_GetRegistersWithProof_Call struct { + *mock.Call +} + +// GetRegistersWithProof is a helper method to define mock.On call +// - registerIDs []flow.RegisterID +// - stateCommitment flow.StateCommitment +func (_e *Ledger_Expecter) GetRegistersWithProof(registerIDs interface{}, stateCommitment interface{}) *Ledger_GetRegistersWithProof_Call { + return &Ledger_GetRegistersWithProof_Call{Call: _e.mock.On("GetRegistersWithProof", registerIDs, stateCommitment)} +} + +func (_c *Ledger_GetRegistersWithProof_Call) Run(run func(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment)) *Ledger_GetRegistersWithProof_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.RegisterID + if args[0] != nil { + arg0 = args[0].([]flow.RegisterID) + } + var arg1 flow.StateCommitment + if args[1] != nil { + arg1 = args[1].(flow.StateCommitment) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Ledger_GetRegistersWithProof_Call) Return(values []flow.RegisterValue, proofs []flow.StorageProof, err error) *Ledger_GetRegistersWithProof_Call { + _c.Call.Return(values, proofs, err) + return _c +} + +func (_c *Ledger_GetRegistersWithProof_Call) RunAndReturn(run func(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment) ([]flow.RegisterValue, []flow.StorageProof, error)) *Ledger_GetRegistersWithProof_Call { + _c.Call.Return(run) + return _c +} + +// UpdateRegisters provides a mock function for the type Ledger +func (_mock *Ledger) UpdateRegisters(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment) (flow.StateCommitment, error) { + ret := _mock.Called(registerIDs, values, stateCommitment) if len(ret) == 0 { panic("no return value specified for UpdateRegisters") @@ -111,29 +236,73 @@ func (_m *Ledger) UpdateRegisters(registerIDs []flow.RegisterID, values []flow.R var r0 flow.StateCommitment var r1 error - if rf, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) (flow.StateCommitment, error)); ok { - return rf(registerIDs, values, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) (flow.StateCommitment, error)); ok { + return returnFunc(registerIDs, values, stateCommitment) } - if rf, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) flow.StateCommitment); ok { - r0 = rf(registerIDs, values, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) flow.StateCommitment); ok { + r0 = returnFunc(registerIDs, values, stateCommitment) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) error); ok { - r1 = rf(registerIDs, values, stateCommitment) + if returnFunc, ok := ret.Get(1).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) error); ok { + r1 = returnFunc(registerIDs, values, stateCommitment) } else { r1 = ret.Error(1) } - return r0, r1 } -// UpdateRegistersWithProof provides a mock function with given fields: registerIDs, values, stateCommitment -func (_m *Ledger) UpdateRegistersWithProof(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment) (flow.StateCommitment, []flow.StorageProof, error) { - ret := _m.Called(registerIDs, values, stateCommitment) +// Ledger_UpdateRegisters_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateRegisters' +type Ledger_UpdateRegisters_Call struct { + *mock.Call +} + +// UpdateRegisters is a helper method to define mock.On call +// - registerIDs []flow.RegisterID +// - values []flow.RegisterValue +// - stateCommitment flow.StateCommitment +func (_e *Ledger_Expecter) UpdateRegisters(registerIDs interface{}, values interface{}, stateCommitment interface{}) *Ledger_UpdateRegisters_Call { + return &Ledger_UpdateRegisters_Call{Call: _e.mock.On("UpdateRegisters", registerIDs, values, stateCommitment)} +} + +func (_c *Ledger_UpdateRegisters_Call) Run(run func(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment)) *Ledger_UpdateRegisters_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.RegisterID + if args[0] != nil { + arg0 = args[0].([]flow.RegisterID) + } + var arg1 []flow.RegisterValue + if args[1] != nil { + arg1 = args[1].([]flow.RegisterValue) + } + var arg2 flow.StateCommitment + if args[2] != nil { + arg2 = args[2].(flow.StateCommitment) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Ledger_UpdateRegisters_Call) Return(newStateCommitment flow.StateCommitment, err error) *Ledger_UpdateRegisters_Call { + _c.Call.Return(newStateCommitment, err) + return _c +} + +func (_c *Ledger_UpdateRegisters_Call) RunAndReturn(run func(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment) (flow.StateCommitment, error)) *Ledger_UpdateRegisters_Call { + _c.Call.Return(run) + return _c +} + +// UpdateRegistersWithProof provides a mock function for the type Ledger +func (_mock *Ledger) UpdateRegistersWithProof(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment) (flow.StateCommitment, []flow.StorageProof, error) { + ret := _mock.Called(registerIDs, values, stateCommitment) if len(ret) == 0 { panic("no return value specified for UpdateRegistersWithProof") @@ -142,44 +311,73 @@ func (_m *Ledger) UpdateRegistersWithProof(registerIDs []flow.RegisterID, values var r0 flow.StateCommitment var r1 []flow.StorageProof var r2 error - if rf, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) (flow.StateCommitment, []flow.StorageProof, error)); ok { - return rf(registerIDs, values, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) (flow.StateCommitment, []flow.StorageProof, error)); ok { + return returnFunc(registerIDs, values, stateCommitment) } - if rf, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) flow.StateCommitment); ok { - r0 = rf(registerIDs, values, stateCommitment) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) flow.StateCommitment); ok { + r0 = returnFunc(registerIDs, values, stateCommitment) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.StateCommitment) } } - - if rf, ok := ret.Get(1).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) []flow.StorageProof); ok { - r1 = rf(registerIDs, values, stateCommitment) + if returnFunc, ok := ret.Get(1).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) []flow.StorageProof); ok { + r1 = returnFunc(registerIDs, values, stateCommitment) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]flow.StorageProof) } } - - if rf, ok := ret.Get(2).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) error); ok { - r2 = rf(registerIDs, values, stateCommitment) + if returnFunc, ok := ret.Get(2).(func([]flow.RegisterID, []flow.RegisterValue, flow.StateCommitment) error); ok { + r2 = returnFunc(registerIDs, values, stateCommitment) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewLedger creates a new instance of Ledger. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLedger(t interface { - mock.TestingT - Cleanup(func()) -}) *Ledger { - mock := &Ledger{} - mock.Mock.Test(t) +// Ledger_UpdateRegistersWithProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateRegistersWithProof' +type Ledger_UpdateRegistersWithProof_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// UpdateRegistersWithProof is a helper method to define mock.On call +// - registerIDs []flow.RegisterID +// - values []flow.RegisterValue +// - stateCommitment flow.StateCommitment +func (_e *Ledger_Expecter) UpdateRegistersWithProof(registerIDs interface{}, values interface{}, stateCommitment interface{}) *Ledger_UpdateRegistersWithProof_Call { + return &Ledger_UpdateRegistersWithProof_Call{Call: _e.mock.On("UpdateRegistersWithProof", registerIDs, values, stateCommitment)} +} - return mock +func (_c *Ledger_UpdateRegistersWithProof_Call) Run(run func(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment)) *Ledger_UpdateRegistersWithProof_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.RegisterID + if args[0] != nil { + arg0 = args[0].([]flow.RegisterID) + } + var arg1 []flow.RegisterValue + if args[1] != nil { + arg1 = args[1].([]flow.RegisterValue) + } + var arg2 flow.StateCommitment + if args[2] != nil { + arg2 = args[2].(flow.StateCommitment) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Ledger_UpdateRegistersWithProof_Call) Return(newStateCommitment flow.StateCommitment, proofs []flow.StorageProof, err error) *Ledger_UpdateRegistersWithProof_Call { + _c.Call.Return(newStateCommitment, proofs, err) + return _c +} + +func (_c *Ledger_UpdateRegistersWithProof_Call) RunAndReturn(run func(registerIDs []flow.RegisterID, values []flow.RegisterValue, stateCommitment flow.StateCommitment) (flow.StateCommitment, []flow.StorageProof, error)) *Ledger_UpdateRegistersWithProof_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/ledger_verifier.go b/storage/mock/ledger_verifier.go index c92d8efb92a..8bc2dd4302b 100644 --- a/storage/mock/ledger_verifier.go +++ b/storage/mock/ledger_verifier.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewLedgerVerifier creates a new instance of LedgerVerifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLedgerVerifier(t interface { + mock.TestingT + Cleanup(func()) +}) *LedgerVerifier { + mock := &LedgerVerifier{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LedgerVerifier is an autogenerated mock type for the LedgerVerifier type type LedgerVerifier struct { mock.Mock } -// VerifyRegistersProof provides a mock function with given fields: registerIDs, stateCommitment, values, proof -func (_m *LedgerVerifier) VerifyRegistersProof(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment, values []flow.RegisterValue, proof []flow.StorageProof) (bool, error) { - ret := _m.Called(registerIDs, stateCommitment, values, proof) +type LedgerVerifier_Expecter struct { + mock *mock.Mock +} + +func (_m *LedgerVerifier) EXPECT() *LedgerVerifier_Expecter { + return &LedgerVerifier_Expecter{mock: &_m.Mock} +} + +// VerifyRegistersProof provides a mock function for the type LedgerVerifier +func (_mock *LedgerVerifier) VerifyRegistersProof(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment, values []flow.RegisterValue, proof []flow.StorageProof) (bool, error) { + ret := _mock.Called(registerIDs, stateCommitment, values, proof) if len(ret) == 0 { panic("no return value specified for VerifyRegistersProof") @@ -22,34 +46,70 @@ func (_m *LedgerVerifier) VerifyRegistersProof(registerIDs []flow.RegisterID, st var r0 bool var r1 error - if rf, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment, []flow.RegisterValue, []flow.StorageProof) (bool, error)); ok { - return rf(registerIDs, stateCommitment, values, proof) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment, []flow.RegisterValue, []flow.StorageProof) (bool, error)); ok { + return returnFunc(registerIDs, stateCommitment, values, proof) } - if rf, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment, []flow.RegisterValue, []flow.StorageProof) bool); ok { - r0 = rf(registerIDs, stateCommitment, values, proof) + if returnFunc, ok := ret.Get(0).(func([]flow.RegisterID, flow.StateCommitment, []flow.RegisterValue, []flow.StorageProof) bool); ok { + r0 = returnFunc(registerIDs, stateCommitment, values, proof) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func([]flow.RegisterID, flow.StateCommitment, []flow.RegisterValue, []flow.StorageProof) error); ok { - r1 = rf(registerIDs, stateCommitment, values, proof) + if returnFunc, ok := ret.Get(1).(func([]flow.RegisterID, flow.StateCommitment, []flow.RegisterValue, []flow.StorageProof) error); ok { + r1 = returnFunc(registerIDs, stateCommitment, values, proof) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewLedgerVerifier creates a new instance of LedgerVerifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLedgerVerifier(t interface { - mock.TestingT - Cleanup(func()) -}) *LedgerVerifier { - mock := &LedgerVerifier{} - mock.Mock.Test(t) +// LedgerVerifier_VerifyRegistersProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyRegistersProof' +type LedgerVerifier_VerifyRegistersProof_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// VerifyRegistersProof is a helper method to define mock.On call +// - registerIDs []flow.RegisterID +// - stateCommitment flow.StateCommitment +// - values []flow.RegisterValue +// - proof []flow.StorageProof +func (_e *LedgerVerifier_Expecter) VerifyRegistersProof(registerIDs interface{}, stateCommitment interface{}, values interface{}, proof interface{}) *LedgerVerifier_VerifyRegistersProof_Call { + return &LedgerVerifier_VerifyRegistersProof_Call{Call: _e.mock.On("VerifyRegistersProof", registerIDs, stateCommitment, values, proof)} +} - return mock +func (_c *LedgerVerifier_VerifyRegistersProof_Call) Run(run func(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment, values []flow.RegisterValue, proof []flow.StorageProof)) *LedgerVerifier_VerifyRegistersProof_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.RegisterID + if args[0] != nil { + arg0 = args[0].([]flow.RegisterID) + } + var arg1 flow.StateCommitment + if args[1] != nil { + arg1 = args[1].(flow.StateCommitment) + } + var arg2 []flow.RegisterValue + if args[2] != nil { + arg2 = args[2].([]flow.RegisterValue) + } + var arg3 []flow.StorageProof + if args[3] != nil { + arg3 = args[3].([]flow.StorageProof) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *LedgerVerifier_VerifyRegistersProof_Call) Return(verified bool, err error) *LedgerVerifier_VerifyRegistersProof_Call { + _c.Call.Return(verified, err) + return _c +} + +func (_c *LedgerVerifier_VerifyRegistersProof_Call) RunAndReturn(run func(registerIDs []flow.RegisterID, stateCommitment flow.StateCommitment, values []flow.RegisterValue, proof []flow.StorageProof) (bool, error)) *LedgerVerifier_VerifyRegistersProof_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/light_transaction_results.go b/storage/mock/light_transaction_results.go index 03f5f3326b3..ed10c884fe6 100644 --- a/storage/mock/light_transaction_results.go +++ b/storage/mock/light_transaction_results.go @@ -1,42 +1,115 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewLightTransactionResults creates a new instance of LightTransactionResults. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLightTransactionResults(t interface { + mock.TestingT + Cleanup(func()) +}) *LightTransactionResults { + mock := &LightTransactionResults{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LightTransactionResults is an autogenerated mock type for the LightTransactionResults type type LightTransactionResults struct { mock.Mock } -// BatchStore provides a mock function with given fields: lctx, rw, blockID, transactionResults -func (_m *LightTransactionResults) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.LightTransactionResult) error { - ret := _m.Called(lctx, rw, blockID, transactionResults) +type LightTransactionResults_Expecter struct { + mock *mock.Mock +} + +func (_m *LightTransactionResults) EXPECT() *LightTransactionResults_Expecter { + return &LightTransactionResults_Expecter{mock: &_m.Mock} +} + +// BatchStore provides a mock function for the type LightTransactionResults +func (_mock *LightTransactionResults) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.LightTransactionResult) error { + ret := _mock.Called(lctx, rw, blockID, transactionResults) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.LightTransactionResult) error); ok { - r0 = rf(lctx, rw, blockID, transactionResults) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.LightTransactionResult) error); ok { + r0 = returnFunc(lctx, rw, blockID, transactionResults) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: id -func (_m *LightTransactionResults) ByBlockID(id flow.Identifier) ([]flow.LightTransactionResult, error) { - ret := _m.Called(id) +// LightTransactionResults_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type LightTransactionResults_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - transactionResults []flow.LightTransactionResult +func (_e *LightTransactionResults_Expecter) BatchStore(lctx interface{}, rw interface{}, blockID interface{}, transactionResults interface{}) *LightTransactionResults_BatchStore_Call { + return &LightTransactionResults_BatchStore_Call{Call: _e.mock.On("BatchStore", lctx, rw, blockID, transactionResults)} +} + +func (_c *LightTransactionResults_BatchStore_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.LightTransactionResult)) *LightTransactionResults_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 []flow.LightTransactionResult + if args[3] != nil { + arg3 = args[3].([]flow.LightTransactionResult) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *LightTransactionResults_BatchStore_Call) Return(err error) *LightTransactionResults_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *LightTransactionResults_BatchStore_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.LightTransactionResult) error) *LightTransactionResults_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type LightTransactionResults +func (_mock *LightTransactionResults) ByBlockID(id flow.Identifier) ([]flow.LightTransactionResult, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -44,29 +117,61 @@ func (_m *LightTransactionResults) ByBlockID(id flow.Identifier) ([]flow.LightTr var r0 []flow.LightTransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.LightTransactionResult, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.LightTransactionResult, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.LightTransactionResult); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.LightTransactionResult); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.LightTransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *LightTransactionResults) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.LightTransactionResult, error) { - ret := _m.Called(blockID, transactionID) +// LightTransactionResults_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type LightTransactionResults_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LightTransactionResults_Expecter) ByBlockID(id interface{}) *LightTransactionResults_ByBlockID_Call { + return &LightTransactionResults_ByBlockID_Call{Call: _e.mock.On("ByBlockID", id)} +} + +func (_c *LightTransactionResults_ByBlockID_Call) Run(run func(id flow.Identifier)) *LightTransactionResults_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LightTransactionResults_ByBlockID_Call) Return(lightTransactionResults []flow.LightTransactionResult, err error) *LightTransactionResults_ByBlockID_Call { + _c.Call.Return(lightTransactionResults, err) + return _c +} + +func (_c *LightTransactionResults_ByBlockID_Call) RunAndReturn(run func(id flow.Identifier) ([]flow.LightTransactionResult, error)) *LightTransactionResults_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type LightTransactionResults +func (_mock *LightTransactionResults) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.LightTransactionResult, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -74,29 +179,67 @@ func (_m *LightTransactionResults) ByBlockIDTransactionID(blockID flow.Identifie var r0 *flow.LightTransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.LightTransactionResult, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.LightTransactionResult, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.LightTransactionResult); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.LightTransactionResult); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightTransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *LightTransactionResults) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.LightTransactionResult, error) { - ret := _m.Called(blockID, txIndex) +// LightTransactionResults_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type LightTransactionResults_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *LightTransactionResults_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *LightTransactionResults_ByBlockIDTransactionID_Call { + return &LightTransactionResults_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *LightTransactionResults_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *LightTransactionResults_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LightTransactionResults_ByBlockIDTransactionID_Call) Return(lightTransactionResult *flow.LightTransactionResult, err error) *LightTransactionResults_ByBlockIDTransactionID_Call { + _c.Call.Return(lightTransactionResult, err) + return _c +} + +func (_c *LightTransactionResults_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) (*flow.LightTransactionResult, error)) *LightTransactionResults_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type LightTransactionResults +func (_mock *LightTransactionResults) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.LightTransactionResult, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -104,36 +247,60 @@ func (_m *LightTransactionResults) ByBlockIDTransactionIndex(blockID flow.Identi var r0 *flow.LightTransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.LightTransactionResult, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.LightTransactionResult, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.LightTransactionResult); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.LightTransactionResult); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightTransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewLightTransactionResults creates a new instance of LightTransactionResults. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLightTransactionResults(t interface { - mock.TestingT - Cleanup(func()) -}) *LightTransactionResults { - mock := &LightTransactionResults{} - mock.Mock.Test(t) +// LightTransactionResults_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type LightTransactionResults_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *LightTransactionResults_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *LightTransactionResults_ByBlockIDTransactionIndex_Call { + return &LightTransactionResults_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} - return mock +func (_c *LightTransactionResults_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *LightTransactionResults_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LightTransactionResults_ByBlockIDTransactionIndex_Call) Return(lightTransactionResult *flow.LightTransactionResult, err error) *LightTransactionResults_ByBlockIDTransactionIndex_Call { + _c.Call.Return(lightTransactionResult, err) + return _c +} + +func (_c *LightTransactionResults_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) (*flow.LightTransactionResult, error)) *LightTransactionResults_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/light_transaction_results_reader.go b/storage/mock/light_transaction_results_reader.go index a93151f12d2..65976faeff9 100644 --- a/storage/mock/light_transaction_results_reader.go +++ b/storage/mock/light_transaction_results_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewLightTransactionResultsReader creates a new instance of LightTransactionResultsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLightTransactionResultsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *LightTransactionResultsReader { + mock := &LightTransactionResultsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LightTransactionResultsReader is an autogenerated mock type for the LightTransactionResultsReader type type LightTransactionResultsReader struct { mock.Mock } -// ByBlockID provides a mock function with given fields: id -func (_m *LightTransactionResultsReader) ByBlockID(id flow.Identifier) ([]flow.LightTransactionResult, error) { - ret := _m.Called(id) +type LightTransactionResultsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *LightTransactionResultsReader) EXPECT() *LightTransactionResultsReader_Expecter { + return &LightTransactionResultsReader_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type LightTransactionResultsReader +func (_mock *LightTransactionResultsReader) ByBlockID(id flow.Identifier) ([]flow.LightTransactionResult, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,29 +46,61 @@ func (_m *LightTransactionResultsReader) ByBlockID(id flow.Identifier) ([]flow.L var r0 []flow.LightTransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.LightTransactionResult, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.LightTransactionResult, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.LightTransactionResult); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.LightTransactionResult); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.LightTransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *LightTransactionResultsReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.LightTransactionResult, error) { - ret := _m.Called(blockID, transactionID) +// LightTransactionResultsReader_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type LightTransactionResultsReader_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *LightTransactionResultsReader_Expecter) ByBlockID(id interface{}) *LightTransactionResultsReader_ByBlockID_Call { + return &LightTransactionResultsReader_ByBlockID_Call{Call: _e.mock.On("ByBlockID", id)} +} + +func (_c *LightTransactionResultsReader_ByBlockID_Call) Run(run func(id flow.Identifier)) *LightTransactionResultsReader_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *LightTransactionResultsReader_ByBlockID_Call) Return(lightTransactionResults []flow.LightTransactionResult, err error) *LightTransactionResultsReader_ByBlockID_Call { + _c.Call.Return(lightTransactionResults, err) + return _c +} + +func (_c *LightTransactionResultsReader_ByBlockID_Call) RunAndReturn(run func(id flow.Identifier) ([]flow.LightTransactionResult, error)) *LightTransactionResultsReader_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type LightTransactionResultsReader +func (_mock *LightTransactionResultsReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.LightTransactionResult, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -52,29 +108,67 @@ func (_m *LightTransactionResultsReader) ByBlockIDTransactionID(blockID flow.Ide var r0 *flow.LightTransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.LightTransactionResult, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.LightTransactionResult, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.LightTransactionResult); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.LightTransactionResult); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightTransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *LightTransactionResultsReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.LightTransactionResult, error) { - ret := _m.Called(blockID, txIndex) +// LightTransactionResultsReader_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type LightTransactionResultsReader_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *LightTransactionResultsReader_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *LightTransactionResultsReader_ByBlockIDTransactionID_Call { + return &LightTransactionResultsReader_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *LightTransactionResultsReader_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *LightTransactionResultsReader_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LightTransactionResultsReader_ByBlockIDTransactionID_Call) Return(lightTransactionResult *flow.LightTransactionResult, err error) *LightTransactionResultsReader_ByBlockIDTransactionID_Call { + _c.Call.Return(lightTransactionResult, err) + return _c +} + +func (_c *LightTransactionResultsReader_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) (*flow.LightTransactionResult, error)) *LightTransactionResultsReader_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type LightTransactionResultsReader +func (_mock *LightTransactionResultsReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.LightTransactionResult, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -82,36 +176,60 @@ func (_m *LightTransactionResultsReader) ByBlockIDTransactionIndex(blockID flow. var r0 *flow.LightTransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.LightTransactionResult, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.LightTransactionResult, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.LightTransactionResult); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.LightTransactionResult); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.LightTransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewLightTransactionResultsReader creates a new instance of LightTransactionResultsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLightTransactionResultsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *LightTransactionResultsReader { - mock := &LightTransactionResultsReader{} - mock.Mock.Test(t) +// LightTransactionResultsReader_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type LightTransactionResultsReader_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *LightTransactionResultsReader_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *LightTransactionResultsReader_ByBlockIDTransactionIndex_Call { + return &LightTransactionResultsReader_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} - return mock +func (_c *LightTransactionResultsReader_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *LightTransactionResultsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *LightTransactionResultsReader_ByBlockIDTransactionIndex_Call) Return(lightTransactionResult *flow.LightTransactionResult, err error) *LightTransactionResultsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(lightTransactionResult, err) + return _c +} + +func (_c *LightTransactionResultsReader_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) (*flow.LightTransactionResult, error)) *LightTransactionResultsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/lock_manager.go b/storage/mock/lock_manager.go index e1ea9a1c2e9..9008d8015dc 100644 --- a/storage/mock/lock_manager.go +++ b/storage/mock/lock_manager.go @@ -1,47 +1,83 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" + "github.com/jordanschalm/lockctx" mock "github.com/stretchr/testify/mock" ) +// NewLockManager creates a new instance of LockManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewLockManager(t interface { + mock.TestingT + Cleanup(func()) +}) *LockManager { + mock := &LockManager{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // LockManager is an autogenerated mock type for the LockManager type type LockManager struct { mock.Mock } -// NewContext provides a mock function with no fields -func (_m *LockManager) NewContext() lockctx.Context { - ret := _m.Called() +type LockManager_Expecter struct { + mock *mock.Mock +} + +func (_m *LockManager) EXPECT() *LockManager_Expecter { + return &LockManager_Expecter{mock: &_m.Mock} +} + +// NewContext provides a mock function for the type LockManager +func (_mock *LockManager) NewContext() lockctx.Context { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NewContext") } var r0 lockctx.Context - if rf, ok := ret.Get(0).(func() lockctx.Context); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() lockctx.Context); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(lockctx.Context) } } - return r0 } -// NewLockManager creates a new instance of LockManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLockManager(t interface { - mock.TestingT - Cleanup(func()) -}) *LockManager { - mock := &LockManager{} - mock.Mock.Test(t) +// LockManager_NewContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewContext' +type LockManager_NewContext_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NewContext is a helper method to define mock.On call +func (_e *LockManager_Expecter) NewContext() *LockManager_NewContext_Call { + return &LockManager_NewContext_Call{Call: _e.mock.On("NewContext")} +} - return mock +func (_c *LockManager_NewContext_Call) Run(run func()) *LockManager_NewContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *LockManager_NewContext_Call) Return(context lockctx.Context) *LockManager_NewContext_Call { + _c.Call.Return(context) + return _c +} + +func (_c *LockManager_NewContext_Call) RunAndReturn(run func() lockctx.Context) *LockManager_NewContext_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/my_execution_receipts.go b/storage/mock/my_execution_receipts.go index 00fa6a07707..a0770e1b7aa 100644 --- a/storage/mock/my_execution_receipts.go +++ b/storage/mock/my_execution_receipts.go @@ -1,60 +1,166 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewMyExecutionReceipts creates a new instance of MyExecutionReceipts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMyExecutionReceipts(t interface { + mock.TestingT + Cleanup(func()) +}) *MyExecutionReceipts { + mock := &MyExecutionReceipts{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // MyExecutionReceipts is an autogenerated mock type for the MyExecutionReceipts type type MyExecutionReceipts struct { mock.Mock } -// BatchRemoveIndexByBlockID provides a mock function with given fields: blockID, batch -func (_m *MyExecutionReceipts) BatchRemoveIndexByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { - ret := _m.Called(blockID, batch) +type MyExecutionReceipts_Expecter struct { + mock *mock.Mock +} + +func (_m *MyExecutionReceipts) EXPECT() *MyExecutionReceipts_Expecter { + return &MyExecutionReceipts_Expecter{mock: &_m.Mock} +} + +// BatchRemoveIndexByBlockID provides a mock function for the type MyExecutionReceipts +func (_mock *MyExecutionReceipts) BatchRemoveIndexByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(blockID, batch) if len(ret) == 0 { panic("no return value specified for BatchRemoveIndexByBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(blockID, batch) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(blockID, batch) } else { r0 = ret.Error(0) } - return r0 } -// BatchStoreMyReceipt provides a mock function with given fields: lctx, receipt, batch -func (_m *MyExecutionReceipts) BatchStoreMyReceipt(lctx lockctx.Proof, receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter) error { - ret := _m.Called(lctx, receipt, batch) +// MyExecutionReceipts_BatchRemoveIndexByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemoveIndexByBlockID' +type MyExecutionReceipts_BatchRemoveIndexByBlockID_Call struct { + *mock.Call +} + +// BatchRemoveIndexByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +// - batch storage.ReaderBatchWriter +func (_e *MyExecutionReceipts_Expecter) BatchRemoveIndexByBlockID(blockID interface{}, batch interface{}) *MyExecutionReceipts_BatchRemoveIndexByBlockID_Call { + return &MyExecutionReceipts_BatchRemoveIndexByBlockID_Call{Call: _e.mock.On("BatchRemoveIndexByBlockID", blockID, batch)} +} + +func (_c *MyExecutionReceipts_BatchRemoveIndexByBlockID_Call) Run(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter)) *MyExecutionReceipts_BatchRemoveIndexByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *MyExecutionReceipts_BatchRemoveIndexByBlockID_Call) Return(err error) *MyExecutionReceipts_BatchRemoveIndexByBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MyExecutionReceipts_BatchRemoveIndexByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter) error) *MyExecutionReceipts_BatchRemoveIndexByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// BatchStoreMyReceipt provides a mock function for the type MyExecutionReceipts +func (_mock *MyExecutionReceipts) BatchStoreMyReceipt(lctx lockctx.Proof, receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(lctx, receipt, batch) if len(ret) == 0 { panic("no return value specified for BatchStoreMyReceipt") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, *flow.ExecutionReceipt, storage.ReaderBatchWriter) error); ok { - r0 = rf(lctx, receipt, batch) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, *flow.ExecutionReceipt, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(lctx, receipt, batch) } else { r0 = ret.Error(0) } - return r0 } -// MyReceipt provides a mock function with given fields: blockID -func (_m *MyExecutionReceipts) MyReceipt(blockID flow.Identifier) (*flow.ExecutionReceipt, error) { - ret := _m.Called(blockID) +// MyExecutionReceipts_BatchStoreMyReceipt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStoreMyReceipt' +type MyExecutionReceipts_BatchStoreMyReceipt_Call struct { + *mock.Call +} + +// BatchStoreMyReceipt is a helper method to define mock.On call +// - lctx lockctx.Proof +// - receipt *flow.ExecutionReceipt +// - batch storage.ReaderBatchWriter +func (_e *MyExecutionReceipts_Expecter) BatchStoreMyReceipt(lctx interface{}, receipt interface{}, batch interface{}) *MyExecutionReceipts_BatchStoreMyReceipt_Call { + return &MyExecutionReceipts_BatchStoreMyReceipt_Call{Call: _e.mock.On("BatchStoreMyReceipt", lctx, receipt, batch)} +} + +func (_c *MyExecutionReceipts_BatchStoreMyReceipt_Call) Run(run func(lctx lockctx.Proof, receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter)) *MyExecutionReceipts_BatchStoreMyReceipt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 *flow.ExecutionReceipt + if args[1] != nil { + arg1 = args[1].(*flow.ExecutionReceipt) + } + var arg2 storage.ReaderBatchWriter + if args[2] != nil { + arg2 = args[2].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *MyExecutionReceipts_BatchStoreMyReceipt_Call) Return(err error) *MyExecutionReceipts_BatchStoreMyReceipt_Call { + _c.Call.Return(err) + return _c +} + +func (_c *MyExecutionReceipts_BatchStoreMyReceipt_Call) RunAndReturn(run func(lctx lockctx.Proof, receipt *flow.ExecutionReceipt, batch storage.ReaderBatchWriter) error) *MyExecutionReceipts_BatchStoreMyReceipt_Call { + _c.Call.Return(run) + return _c +} + +// MyReceipt provides a mock function for the type MyExecutionReceipts +func (_mock *MyExecutionReceipts) MyReceipt(blockID flow.Identifier) (*flow.ExecutionReceipt, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for MyReceipt") @@ -62,36 +168,54 @@ func (_m *MyExecutionReceipts) MyReceipt(blockID flow.Identifier) (*flow.Executi var r0 *flow.ExecutionReceipt var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionReceipt, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ExecutionReceipt, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionReceipt); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ExecutionReceipt); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ExecutionReceipt) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewMyExecutionReceipts creates a new instance of MyExecutionReceipts. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewMyExecutionReceipts(t interface { - mock.TestingT - Cleanup(func()) -}) *MyExecutionReceipts { - mock := &MyExecutionReceipts{} - mock.Mock.Test(t) +// MyExecutionReceipts_MyReceipt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MyReceipt' +type MyExecutionReceipts_MyReceipt_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// MyReceipt is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *MyExecutionReceipts_Expecter) MyReceipt(blockID interface{}) *MyExecutionReceipts_MyReceipt_Call { + return &MyExecutionReceipts_MyReceipt_Call{Call: _e.mock.On("MyReceipt", blockID)} +} - return mock +func (_c *MyExecutionReceipts_MyReceipt_Call) Run(run func(blockID flow.Identifier)) *MyExecutionReceipts_MyReceipt_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *MyExecutionReceipts_MyReceipt_Call) Return(executionReceipt *flow.ExecutionReceipt, err error) *MyExecutionReceipts_MyReceipt_Call { + _c.Call.Return(executionReceipt, err) + return _c +} + +func (_c *MyExecutionReceipts_MyReceipt_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.ExecutionReceipt, error)) *MyExecutionReceipts_MyReceipt_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/node_disallow_list.go b/storage/mock/node_disallow_list.go index 47b2c7ff04e..bf5e897a4c0 100644 --- a/storage/mock/node_disallow_list.go +++ b/storage/mock/node_disallow_list.go @@ -1,63 +1,139 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewNodeDisallowList creates a new instance of NodeDisallowList. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNodeDisallowList(t interface { + mock.TestingT + Cleanup(func()) +}) *NodeDisallowList { + mock := &NodeDisallowList{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // NodeDisallowList is an autogenerated mock type for the NodeDisallowList type type NodeDisallowList struct { mock.Mock } -// Retrieve provides a mock function with given fields: disallowList -func (_m *NodeDisallowList) Retrieve(disallowList *map[flow.Identifier]struct{}) error { - ret := _m.Called(disallowList) +type NodeDisallowList_Expecter struct { + mock *mock.Mock +} + +func (_m *NodeDisallowList) EXPECT() *NodeDisallowList_Expecter { + return &NodeDisallowList_Expecter{mock: &_m.Mock} +} + +// Retrieve provides a mock function for the type NodeDisallowList +func (_mock *NodeDisallowList) Retrieve(disallowList *map[flow.Identifier]struct{}) error { + ret := _mock.Called(disallowList) if len(ret) == 0 { panic("no return value specified for Retrieve") } var r0 error - if rf, ok := ret.Get(0).(func(*map[flow.Identifier]struct{}) error); ok { - r0 = rf(disallowList) + if returnFunc, ok := ret.Get(0).(func(*map[flow.Identifier]struct{}) error); ok { + r0 = returnFunc(disallowList) } else { r0 = ret.Error(0) } - return r0 } -// Store provides a mock function with given fields: disallowList -func (_m *NodeDisallowList) Store(disallowList map[flow.Identifier]struct{}) error { - ret := _m.Called(disallowList) +// NodeDisallowList_Retrieve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Retrieve' +type NodeDisallowList_Retrieve_Call struct { + *mock.Call +} + +// Retrieve is a helper method to define mock.On call +// - disallowList *map[flow.Identifier]struct{} +func (_e *NodeDisallowList_Expecter) Retrieve(disallowList interface{}) *NodeDisallowList_Retrieve_Call { + return &NodeDisallowList_Retrieve_Call{Call: _e.mock.On("Retrieve", disallowList)} +} + +func (_c *NodeDisallowList_Retrieve_Call) Run(run func(disallowList *map[flow.Identifier]struct{})) *NodeDisallowList_Retrieve_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *map[flow.Identifier]struct{} + if args[0] != nil { + arg0 = args[0].(*map[flow.Identifier]struct{}) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeDisallowList_Retrieve_Call) Return(err error) *NodeDisallowList_Retrieve_Call { + _c.Call.Return(err) + return _c +} + +func (_c *NodeDisallowList_Retrieve_Call) RunAndReturn(run func(disallowList *map[flow.Identifier]struct{}) error) *NodeDisallowList_Retrieve_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type NodeDisallowList +func (_mock *NodeDisallowList) Store(disallowList map[flow.Identifier]struct{}) error { + ret := _mock.Called(disallowList) if len(ret) == 0 { panic("no return value specified for Store") } var r0 error - if rf, ok := ret.Get(0).(func(map[flow.Identifier]struct{}) error); ok { - r0 = rf(disallowList) + if returnFunc, ok := ret.Get(0).(func(map[flow.Identifier]struct{}) error); ok { + r0 = returnFunc(disallowList) } else { r0 = ret.Error(0) } - return r0 } -// NewNodeDisallowList creates a new instance of NodeDisallowList. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewNodeDisallowList(t interface { - mock.TestingT - Cleanup(func()) -}) *NodeDisallowList { - mock := &NodeDisallowList{} - mock.Mock.Test(t) +// NodeDisallowList_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type NodeDisallowList_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - disallowList map[flow.Identifier]struct{} +func (_e *NodeDisallowList_Expecter) Store(disallowList interface{}) *NodeDisallowList_Store_Call { + return &NodeDisallowList_Store_Call{Call: _e.mock.On("Store", disallowList)} +} - return mock +func (_c *NodeDisallowList_Store_Call) Run(run func(disallowList map[flow.Identifier]struct{})) *NodeDisallowList_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 map[flow.Identifier]struct{} + if args[0] != nil { + arg0 = args[0].(map[flow.Identifier]struct{}) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *NodeDisallowList_Store_Call) Return(err error) *NodeDisallowList_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *NodeDisallowList_Store_Call) RunAndReturn(run func(disallowList map[flow.Identifier]struct{}) error) *NodeDisallowList_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/non_fungible_token_transfers.go b/storage/mock/non_fungible_token_transfers.go new file mode 100644 index 00000000000..f0af48ace3b --- /dev/null +++ b/storage/mock/non_fungible_token_transfers.go @@ -0,0 +1,265 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewNonFungibleTokenTransfers creates a new instance of NonFungibleTokenTransfers. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNonFungibleTokenTransfers(t interface { + mock.TestingT + Cleanup(func()) +}) *NonFungibleTokenTransfers { + mock := &NonFungibleTokenTransfers{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// NonFungibleTokenTransfers is an autogenerated mock type for the NonFungibleTokenTransfers type +type NonFungibleTokenTransfers struct { + mock.Mock +} + +type NonFungibleTokenTransfers_Expecter struct { + mock *mock.Mock +} + +func (_m *NonFungibleTokenTransfers) EXPECT() *NonFungibleTokenTransfers_Expecter { + return &NonFungibleTokenTransfers_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type NonFungibleTokenTransfers +func (_mock *NonFungibleTokenTransfers) ByAddress(account flow.Address, cursor *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.NonFungibleTokenTransferIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) storage.NonFungibleTokenTransferIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.NonFungibleTokenTransferIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.TransferCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// NonFungibleTokenTransfers_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type NonFungibleTokenTransfers_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.TransferCursor +func (_e *NonFungibleTokenTransfers_Expecter) ByAddress(account interface{}, cursor interface{}) *NonFungibleTokenTransfers_ByAddress_Call { + return &NonFungibleTokenTransfers_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *NonFungibleTokenTransfers_ByAddress_Call) Run(run func(account flow.Address, cursor *access.TransferCursor)) *NonFungibleTokenTransfers_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.TransferCursor + if args[1] != nil { + arg1 = args[1].(*access.TransferCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NonFungibleTokenTransfers_ByAddress_Call) Return(v storage.NonFungibleTokenTransferIterator, err error) *NonFungibleTokenTransfers_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *NonFungibleTokenTransfers_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error)) *NonFungibleTokenTransfers_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type NonFungibleTokenTransfers +func (_mock *NonFungibleTokenTransfers) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// NonFungibleTokenTransfers_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type NonFungibleTokenTransfers_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *NonFungibleTokenTransfers_Expecter) FirstIndexedHeight() *NonFungibleTokenTransfers_FirstIndexedHeight_Call { + return &NonFungibleTokenTransfers_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *NonFungibleTokenTransfers_FirstIndexedHeight_Call) Run(run func()) *NonFungibleTokenTransfers_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NonFungibleTokenTransfers_FirstIndexedHeight_Call) Return(v uint64) *NonFungibleTokenTransfers_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *NonFungibleTokenTransfers_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *NonFungibleTokenTransfers_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type NonFungibleTokenTransfers +func (_mock *NonFungibleTokenTransfers) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// NonFungibleTokenTransfers_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type NonFungibleTokenTransfers_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *NonFungibleTokenTransfers_Expecter) LatestIndexedHeight() *NonFungibleTokenTransfers_LatestIndexedHeight_Call { + return &NonFungibleTokenTransfers_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *NonFungibleTokenTransfers_LatestIndexedHeight_Call) Run(run func()) *NonFungibleTokenTransfers_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NonFungibleTokenTransfers_LatestIndexedHeight_Call) Return(v uint64) *NonFungibleTokenTransfers_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *NonFungibleTokenTransfers_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *NonFungibleTokenTransfers_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type NonFungibleTokenTransfers +func (_mock *NonFungibleTokenTransfers) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error { + ret := _mock.Called(lctx, rw, blockHeight, transfers) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.NonFungibleTokenTransfer) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, transfers) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// NonFungibleTokenTransfers_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type NonFungibleTokenTransfers_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - transfers []access.NonFungibleTokenTransfer +func (_e *NonFungibleTokenTransfers_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, transfers interface{}) *NonFungibleTokenTransfers_Store_Call { + return &NonFungibleTokenTransfers_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, transfers)} +} + +func (_c *NonFungibleTokenTransfers_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer)) *NonFungibleTokenTransfers_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.NonFungibleTokenTransfer + if args[3] != nil { + arg3 = args[3].([]access.NonFungibleTokenTransfer) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NonFungibleTokenTransfers_Store_Call) Return(err error) *NonFungibleTokenTransfers_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *NonFungibleTokenTransfers_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error) *NonFungibleTokenTransfers_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/non_fungible_token_transfers_bootstrapper.go b/storage/mock/non_fungible_token_transfers_bootstrapper.go new file mode 100644 index 00000000000..ce0b74af0f3 --- /dev/null +++ b/storage/mock/non_fungible_token_transfers_bootstrapper.go @@ -0,0 +1,336 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewNonFungibleTokenTransfersBootstrapper creates a new instance of NonFungibleTokenTransfersBootstrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNonFungibleTokenTransfersBootstrapper(t interface { + mock.TestingT + Cleanup(func()) +}) *NonFungibleTokenTransfersBootstrapper { + mock := &NonFungibleTokenTransfersBootstrapper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// NonFungibleTokenTransfersBootstrapper is an autogenerated mock type for the NonFungibleTokenTransfersBootstrapper type +type NonFungibleTokenTransfersBootstrapper struct { + mock.Mock +} + +type NonFungibleTokenTransfersBootstrapper_Expecter struct { + mock *mock.Mock +} + +func (_m *NonFungibleTokenTransfersBootstrapper) EXPECT() *NonFungibleTokenTransfersBootstrapper_Expecter { + return &NonFungibleTokenTransfersBootstrapper_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type NonFungibleTokenTransfersBootstrapper +func (_mock *NonFungibleTokenTransfersBootstrapper) ByAddress(account flow.Address, cursor *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.NonFungibleTokenTransferIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) storage.NonFungibleTokenTransferIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.NonFungibleTokenTransferIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.TransferCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// NonFungibleTokenTransfersBootstrapper_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type NonFungibleTokenTransfersBootstrapper_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.TransferCursor +func (_e *NonFungibleTokenTransfersBootstrapper_Expecter) ByAddress(account interface{}, cursor interface{}) *NonFungibleTokenTransfersBootstrapper_ByAddress_Call { + return &NonFungibleTokenTransfersBootstrapper_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *NonFungibleTokenTransfersBootstrapper_ByAddress_Call) Run(run func(account flow.Address, cursor *access.TransferCursor)) *NonFungibleTokenTransfersBootstrapper_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.TransferCursor + if args[1] != nil { + arg1 = args[1].(*access.TransferCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_ByAddress_Call) Return(v storage.NonFungibleTokenTransferIterator, err error) *NonFungibleTokenTransfersBootstrapper_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error)) *NonFungibleTokenTransfersBootstrapper_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type NonFungibleTokenTransfersBootstrapper +func (_mock *NonFungibleTokenTransfersBootstrapper) FirstIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *NonFungibleTokenTransfersBootstrapper_Expecter) FirstIndexedHeight() *NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + return &NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call) Run(run func()) *NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call) Return(v uint64, err error) *NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *NonFungibleTokenTransfersBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type NonFungibleTokenTransfersBootstrapper +func (_mock *NonFungibleTokenTransfersBootstrapper) LatestIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *NonFungibleTokenTransfersBootstrapper_Expecter) LatestIndexedHeight() *NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + return &NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call) Run(run func()) *NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call) Return(v uint64, err error) *NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *NonFungibleTokenTransfersBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type NonFungibleTokenTransfersBootstrapper +func (_mock *NonFungibleTokenTransfersBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error { + ret := _mock.Called(lctx, rw, blockHeight, transfers) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.NonFungibleTokenTransfer) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, transfers) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// NonFungibleTokenTransfersBootstrapper_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type NonFungibleTokenTransfersBootstrapper_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - transfers []access.NonFungibleTokenTransfer +func (_e *NonFungibleTokenTransfersBootstrapper_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, transfers interface{}) *NonFungibleTokenTransfersBootstrapper_Store_Call { + return &NonFungibleTokenTransfersBootstrapper_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, transfers)} +} + +func (_c *NonFungibleTokenTransfersBootstrapper_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer)) *NonFungibleTokenTransfersBootstrapper_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.NonFungibleTokenTransfer + if args[3] != nil { + arg3 = args[3].([]access.NonFungibleTokenTransfer) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_Store_Call) Return(err error) *NonFungibleTokenTransfersBootstrapper_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error) *NonFungibleTokenTransfersBootstrapper_Store_Call { + _c.Call.Return(run) + return _c +} + +// UninitializedFirstHeight provides a mock function for the type NonFungibleTokenTransfersBootstrapper +func (_mock *NonFungibleTokenTransfersBootstrapper) UninitializedFirstHeight() (uint64, bool) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for UninitializedFirstHeight") + } + + var r0 uint64 + var r1 bool + if returnFunc, ok := ret.Get(0).(func() (uint64, bool)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() + } else { + r1 = ret.Get(1).(bool) + } + return r0, r1 +} + +// NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UninitializedFirstHeight' +type NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call struct { + *mock.Call +} + +// UninitializedFirstHeight is a helper method to define mock.On call +func (_e *NonFungibleTokenTransfersBootstrapper_Expecter) UninitializedFirstHeight() *NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + return &NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call{Call: _e.mock.On("UninitializedFirstHeight")} +} + +func (_c *NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call) Run(run func()) *NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call) Return(v uint64, b bool) *NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call) RunAndReturn(run func() (uint64, bool)) *NonFungibleTokenTransfersBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/non_fungible_token_transfers_range_reader.go b/storage/mock/non_fungible_token_transfers_range_reader.go new file mode 100644 index 00000000000..4d3329e4edd --- /dev/null +++ b/storage/mock/non_fungible_token_transfers_range_reader.go @@ -0,0 +1,124 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewNonFungibleTokenTransfersRangeReader creates a new instance of NonFungibleTokenTransfersRangeReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNonFungibleTokenTransfersRangeReader(t interface { + mock.TestingT + Cleanup(func()) +}) *NonFungibleTokenTransfersRangeReader { + mock := &NonFungibleTokenTransfersRangeReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// NonFungibleTokenTransfersRangeReader is an autogenerated mock type for the NonFungibleTokenTransfersRangeReader type +type NonFungibleTokenTransfersRangeReader struct { + mock.Mock +} + +type NonFungibleTokenTransfersRangeReader_Expecter struct { + mock *mock.Mock +} + +func (_m *NonFungibleTokenTransfersRangeReader) EXPECT() *NonFungibleTokenTransfersRangeReader_Expecter { + return &NonFungibleTokenTransfersRangeReader_Expecter{mock: &_m.Mock} +} + +// FirstIndexedHeight provides a mock function for the type NonFungibleTokenTransfersRangeReader +func (_mock *NonFungibleTokenTransfersRangeReader) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *NonFungibleTokenTransfersRangeReader_Expecter) FirstIndexedHeight() *NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + return &NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call) Run(run func()) *NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call) Return(v uint64) *NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *NonFungibleTokenTransfersRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type NonFungibleTokenTransfersRangeReader +func (_mock *NonFungibleTokenTransfersRangeReader) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *NonFungibleTokenTransfersRangeReader_Expecter) LatestIndexedHeight() *NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + return &NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call) Run(run func()) *NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call) Return(v uint64) *NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *NonFungibleTokenTransfersRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/non_fungible_token_transfers_reader.go b/storage/mock/non_fungible_token_transfers_reader.go new file mode 100644 index 00000000000..e781b3742e8 --- /dev/null +++ b/storage/mock/non_fungible_token_transfers_reader.go @@ -0,0 +1,107 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewNonFungibleTokenTransfersReader creates a new instance of NonFungibleTokenTransfersReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNonFungibleTokenTransfersReader(t interface { + mock.TestingT + Cleanup(func()) +}) *NonFungibleTokenTransfersReader { + mock := &NonFungibleTokenTransfersReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// NonFungibleTokenTransfersReader is an autogenerated mock type for the NonFungibleTokenTransfersReader type +type NonFungibleTokenTransfersReader struct { + mock.Mock +} + +type NonFungibleTokenTransfersReader_Expecter struct { + mock *mock.Mock +} + +func (_m *NonFungibleTokenTransfersReader) EXPECT() *NonFungibleTokenTransfersReader_Expecter { + return &NonFungibleTokenTransfersReader_Expecter{mock: &_m.Mock} +} + +// ByAddress provides a mock function for the type NonFungibleTokenTransfersReader +func (_mock *NonFungibleTokenTransfersReader) ByAddress(account flow.Address, cursor *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.NonFungibleTokenTransferIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.TransferCursor) storage.NonFungibleTokenTransferIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.NonFungibleTokenTransferIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.TransferCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// NonFungibleTokenTransfersReader_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type NonFungibleTokenTransfersReader_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.TransferCursor +func (_e *NonFungibleTokenTransfersReader_Expecter) ByAddress(account interface{}, cursor interface{}) *NonFungibleTokenTransfersReader_ByAddress_Call { + return &NonFungibleTokenTransfersReader_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *NonFungibleTokenTransfersReader_ByAddress_Call) Run(run func(account flow.Address, cursor *access.TransferCursor)) *NonFungibleTokenTransfersReader_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.TransferCursor + if args[1] != nil { + arg1 = args[1].(*access.TransferCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *NonFungibleTokenTransfersReader_ByAddress_Call) Return(v storage.NonFungibleTokenTransferIterator, err error) *NonFungibleTokenTransfersReader_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *NonFungibleTokenTransfersReader_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.TransferCursor) (storage.NonFungibleTokenTransferIterator, error)) *NonFungibleTokenTransfersReader_ByAddress_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/non_fungible_token_transfers_writer.go b/storage/mock/non_fungible_token_transfers_writer.go new file mode 100644 index 00000000000..988e07064e1 --- /dev/null +++ b/storage/mock/non_fungible_token_transfers_writer.go @@ -0,0 +1,108 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewNonFungibleTokenTransfersWriter creates a new instance of NonFungibleTokenTransfersWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNonFungibleTokenTransfersWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *NonFungibleTokenTransfersWriter { + mock := &NonFungibleTokenTransfersWriter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// NonFungibleTokenTransfersWriter is an autogenerated mock type for the NonFungibleTokenTransfersWriter type +type NonFungibleTokenTransfersWriter struct { + mock.Mock +} + +type NonFungibleTokenTransfersWriter_Expecter struct { + mock *mock.Mock +} + +func (_m *NonFungibleTokenTransfersWriter) EXPECT() *NonFungibleTokenTransfersWriter_Expecter { + return &NonFungibleTokenTransfersWriter_Expecter{mock: &_m.Mock} +} + +// Store provides a mock function for the type NonFungibleTokenTransfersWriter +func (_mock *NonFungibleTokenTransfersWriter) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error { + ret := _mock.Called(lctx, rw, blockHeight, transfers) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.NonFungibleTokenTransfer) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, transfers) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// NonFungibleTokenTransfersWriter_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type NonFungibleTokenTransfersWriter_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - transfers []access.NonFungibleTokenTransfer +func (_e *NonFungibleTokenTransfersWriter_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, transfers interface{}) *NonFungibleTokenTransfersWriter_Store_Call { + return &NonFungibleTokenTransfersWriter_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, transfers)} +} + +func (_c *NonFungibleTokenTransfersWriter_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer)) *NonFungibleTokenTransfersWriter_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.NonFungibleTokenTransfer + if args[3] != nil { + arg3 = args[3].([]access.NonFungibleTokenTransfer) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *NonFungibleTokenTransfersWriter_Store_Call) Return(err error) *NonFungibleTokenTransfersWriter_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *NonFungibleTokenTransfersWriter_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, transfers []access.NonFungibleTokenTransfer) error) *NonFungibleTokenTransfersWriter_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/payloads.go b/storage/mock/payloads.go index 9dd42c8cf79..e2d6a160788 100644 --- a/storage/mock/payloads.go +++ b/storage/mock/payloads.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewPayloads creates a new instance of Payloads. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPayloads(t interface { + mock.TestingT + Cleanup(func()) +}) *Payloads { + mock := &Payloads{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Payloads is an autogenerated mock type for the Payloads type type Payloads struct { mock.Mock } -// ByBlockID provides a mock function with given fields: blockID -func (_m *Payloads) ByBlockID(blockID flow.Identifier) (*flow.Payload, error) { - ret := _m.Called(blockID) +type Payloads_Expecter struct { + mock *mock.Mock +} + +func (_m *Payloads) EXPECT() *Payloads_Expecter { + return &Payloads_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type Payloads +func (_mock *Payloads) ByBlockID(blockID flow.Identifier) (*flow.Payload, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,36 +46,54 @@ func (_m *Payloads) ByBlockID(blockID flow.Identifier) (*flow.Payload, error) { var r0 *flow.Payload var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Payload, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Payload, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Payload); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Payload); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Payload) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewPayloads creates a new instance of Payloads. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewPayloads(t interface { - mock.TestingT - Cleanup(func()) -}) *Payloads { - mock := &Payloads{} - mock.Mock.Test(t) +// Payloads_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type Payloads_ByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Payloads_Expecter) ByBlockID(blockID interface{}) *Payloads_ByBlockID_Call { + return &Payloads_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} - return mock +func (_c *Payloads_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *Payloads_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Payloads_ByBlockID_Call) Return(payload *flow.Payload, err error) *Payloads_ByBlockID_Call { + _c.Call.Return(payload, err) + return _c +} + +func (_c *Payloads_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.Payload, error)) *Payloads_ByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/protocol_kv_store.go b/storage/mock/protocol_kv_store.go index 130bbf0be0a..92abc19be67 100644 --- a/storage/mock/protocol_kv_store.go +++ b/storage/mock/protocol_kv_store.go @@ -1,60 +1,178 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewProtocolKVStore creates a new instance of ProtocolKVStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewProtocolKVStore(t interface { + mock.TestingT + Cleanup(func()) +}) *ProtocolKVStore { + mock := &ProtocolKVStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ProtocolKVStore is an autogenerated mock type for the ProtocolKVStore type type ProtocolKVStore struct { mock.Mock } -// BatchIndex provides a mock function with given fields: lctx, rw, blockID, stateID -func (_m *ProtocolKVStore) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier) error { - ret := _m.Called(lctx, rw, blockID, stateID) +type ProtocolKVStore_Expecter struct { + mock *mock.Mock +} + +func (_m *ProtocolKVStore) EXPECT() *ProtocolKVStore_Expecter { + return &ProtocolKVStore_Expecter{mock: &_m.Mock} +} + +// BatchIndex provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) BatchIndex(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier) error { + ret := _mock.Called(lctx, rw, blockID, stateID) if len(ret) == 0 { panic("no return value specified for BatchIndex") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { - r0 = rf(lctx, rw, blockID, stateID) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, blockID, stateID) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: rw, stateID, data -func (_m *ProtocolKVStore) BatchStore(rw storage.ReaderBatchWriter, stateID flow.Identifier, data *flow.PSKeyValueStoreData) error { - ret := _m.Called(rw, stateID, data) +// ProtocolKVStore_BatchIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchIndex' +type ProtocolKVStore_BatchIndex_Call struct { + *mock.Call +} + +// BatchIndex is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - stateID flow.Identifier +func (_e *ProtocolKVStore_Expecter) BatchIndex(lctx interface{}, rw interface{}, blockID interface{}, stateID interface{}) *ProtocolKVStore_BatchIndex_Call { + return &ProtocolKVStore_BatchIndex_Call{Call: _e.mock.On("BatchIndex", lctx, rw, blockID, stateID)} +} + +func (_c *ProtocolKVStore_BatchIndex_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier)) *ProtocolKVStore_BatchIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_BatchIndex_Call) Return(err error) *ProtocolKVStore_BatchIndex_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ProtocolKVStore_BatchIndex_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, stateID flow.Identifier) error) *ProtocolKVStore_BatchIndex_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) BatchStore(rw storage.ReaderBatchWriter, stateID flow.Identifier, data *flow.PSKeyValueStoreData) error { + ret := _mock.Called(rw, stateID, data) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(storage.ReaderBatchWriter, flow.Identifier, *flow.PSKeyValueStoreData) error); ok { - r0 = rf(rw, stateID, data) + if returnFunc, ok := ret.Get(0).(func(storage.ReaderBatchWriter, flow.Identifier, *flow.PSKeyValueStoreData) error); ok { + r0 = returnFunc(rw, stateID, data) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *ProtocolKVStore) ByBlockID(blockID flow.Identifier) (*flow.PSKeyValueStoreData, error) { - ret := _m.Called(blockID) +// ProtocolKVStore_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type ProtocolKVStore_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - rw storage.ReaderBatchWriter +// - stateID flow.Identifier +// - data *flow.PSKeyValueStoreData +func (_e *ProtocolKVStore_Expecter) BatchStore(rw interface{}, stateID interface{}, data interface{}) *ProtocolKVStore_BatchStore_Call { + return &ProtocolKVStore_BatchStore_Call{Call: _e.mock.On("BatchStore", rw, stateID, data)} +} + +func (_c *ProtocolKVStore_BatchStore_Call) Run(run func(rw storage.ReaderBatchWriter, stateID flow.Identifier, data *flow.PSKeyValueStoreData)) *ProtocolKVStore_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 storage.ReaderBatchWriter + if args[0] != nil { + arg0 = args[0].(storage.ReaderBatchWriter) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 *flow.PSKeyValueStoreData + if args[2] != nil { + arg2 = args[2].(*flow.PSKeyValueStoreData) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_BatchStore_Call) Return(err error) *ProtocolKVStore_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ProtocolKVStore_BatchStore_Call) RunAndReturn(run func(rw storage.ReaderBatchWriter, stateID flow.Identifier, data *flow.PSKeyValueStoreData) error) *ProtocolKVStore_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) ByBlockID(blockID flow.Identifier) (*flow.PSKeyValueStoreData, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -62,29 +180,61 @@ func (_m *ProtocolKVStore) ByBlockID(blockID flow.Identifier) (*flow.PSKeyValueS var r0 *flow.PSKeyValueStoreData var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.PSKeyValueStoreData, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.PSKeyValueStoreData, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.PSKeyValueStoreData); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.PSKeyValueStoreData); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.PSKeyValueStoreData) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: id -func (_m *ProtocolKVStore) ByID(id flow.Identifier) (*flow.PSKeyValueStoreData, error) { - ret := _m.Called(id) +// ProtocolKVStore_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ProtocolKVStore_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ProtocolKVStore_Expecter) ByBlockID(blockID interface{}) *ProtocolKVStore_ByBlockID_Call { + return &ProtocolKVStore_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} + +func (_c *ProtocolKVStore_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *ProtocolKVStore_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_ByBlockID_Call) Return(pSKeyValueStoreData *flow.PSKeyValueStoreData, err error) *ProtocolKVStore_ByBlockID_Call { + _c.Call.Return(pSKeyValueStoreData, err) + return _c +} + +func (_c *ProtocolKVStore_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.PSKeyValueStoreData, error)) *ProtocolKVStore_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ProtocolKVStore +func (_mock *ProtocolKVStore) ByID(id flow.Identifier) (*flow.PSKeyValueStoreData, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByID") @@ -92,36 +242,54 @@ func (_m *ProtocolKVStore) ByID(id flow.Identifier) (*flow.PSKeyValueStoreData, var r0 *flow.PSKeyValueStoreData var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.PSKeyValueStoreData, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.PSKeyValueStoreData, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.PSKeyValueStoreData); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.PSKeyValueStoreData); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.PSKeyValueStoreData) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewProtocolKVStore creates a new instance of ProtocolKVStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProtocolKVStore(t interface { - mock.TestingT - Cleanup(func()) -}) *ProtocolKVStore { - mock := &ProtocolKVStore{} - mock.Mock.Test(t) +// ProtocolKVStore_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ProtocolKVStore_ByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *ProtocolKVStore_Expecter) ByID(id interface{}) *ProtocolKVStore_ByID_Call { + return &ProtocolKVStore_ByID_Call{Call: _e.mock.On("ByID", id)} +} - return mock +func (_c *ProtocolKVStore_ByID_Call) Run(run func(id flow.Identifier)) *ProtocolKVStore_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ProtocolKVStore_ByID_Call) Return(pSKeyValueStoreData *flow.PSKeyValueStoreData, err error) *ProtocolKVStore_ByID_Call { + _c.Call.Return(pSKeyValueStoreData, err) + return _c +} + +func (_c *ProtocolKVStore_ByID_Call) RunAndReturn(run func(id flow.Identifier) (*flow.PSKeyValueStoreData, error)) *ProtocolKVStore_ByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/quorum_certificates.go b/storage/mock/quorum_certificates.go index b4bd5177b2e..22c18bdf766 100644 --- a/storage/mock/quorum_certificates.go +++ b/storage/mock/quorum_certificates.go @@ -1,42 +1,109 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewQuorumCertificates creates a new instance of QuorumCertificates. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewQuorumCertificates(t interface { + mock.TestingT + Cleanup(func()) +}) *QuorumCertificates { + mock := &QuorumCertificates{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // QuorumCertificates is an autogenerated mock type for the QuorumCertificates type type QuorumCertificates struct { mock.Mock } -// BatchStore provides a mock function with given fields: _a0, _a1, _a2 -func (_m *QuorumCertificates) BatchStore(_a0 lockctx.Proof, _a1 storage.ReaderBatchWriter, _a2 *flow.QuorumCertificate) error { - ret := _m.Called(_a0, _a1, _a2) +type QuorumCertificates_Expecter struct { + mock *mock.Mock +} + +func (_m *QuorumCertificates) EXPECT() *QuorumCertificates_Expecter { + return &QuorumCertificates_Expecter{mock: &_m.Mock} +} + +// BatchStore provides a mock function for the type QuorumCertificates +func (_mock *QuorumCertificates) BatchStore(proof lockctx.Proof, readerBatchWriter storage.ReaderBatchWriter, quorumCertificate *flow.QuorumCertificate) error { + ret := _mock.Called(proof, readerBatchWriter, quorumCertificate) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, *flow.QuorumCertificate) error); ok { - r0 = rf(_a0, _a1, _a2) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, *flow.QuorumCertificate) error); ok { + r0 = returnFunc(proof, readerBatchWriter, quorumCertificate) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *QuorumCertificates) ByBlockID(blockID flow.Identifier) (*flow.QuorumCertificate, error) { - ret := _m.Called(blockID) +// QuorumCertificates_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type QuorumCertificates_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - proof lockctx.Proof +// - readerBatchWriter storage.ReaderBatchWriter +// - quorumCertificate *flow.QuorumCertificate +func (_e *QuorumCertificates_Expecter) BatchStore(proof interface{}, readerBatchWriter interface{}, quorumCertificate interface{}) *QuorumCertificates_BatchStore_Call { + return &QuorumCertificates_BatchStore_Call{Call: _e.mock.On("BatchStore", proof, readerBatchWriter, quorumCertificate)} +} + +func (_c *QuorumCertificates_BatchStore_Call) Run(run func(proof lockctx.Proof, readerBatchWriter storage.ReaderBatchWriter, quorumCertificate *flow.QuorumCertificate)) *QuorumCertificates_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 *flow.QuorumCertificate + if args[2] != nil { + arg2 = args[2].(*flow.QuorumCertificate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *QuorumCertificates_BatchStore_Call) Return(err error) *QuorumCertificates_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *QuorumCertificates_BatchStore_Call) RunAndReturn(run func(proof lockctx.Proof, readerBatchWriter storage.ReaderBatchWriter, quorumCertificate *flow.QuorumCertificate) error) *QuorumCertificates_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type QuorumCertificates +func (_mock *QuorumCertificates) ByBlockID(blockID flow.Identifier) (*flow.QuorumCertificate, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -44,36 +111,54 @@ func (_m *QuorumCertificates) ByBlockID(blockID flow.Identifier) (*flow.QuorumCe var r0 *flow.QuorumCertificate var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.QuorumCertificate, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.QuorumCertificate, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.QuorumCertificate); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.QuorumCertificate); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.QuorumCertificate) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewQuorumCertificates creates a new instance of QuorumCertificates. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewQuorumCertificates(t interface { - mock.TestingT - Cleanup(func()) -}) *QuorumCertificates { - mock := &QuorumCertificates{} - mock.Mock.Test(t) +// QuorumCertificates_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type QuorumCertificates_ByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *QuorumCertificates_Expecter) ByBlockID(blockID interface{}) *QuorumCertificates_ByBlockID_Call { + return &QuorumCertificates_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} - return mock +func (_c *QuorumCertificates_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *QuorumCertificates_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *QuorumCertificates_ByBlockID_Call) Return(quorumCertificate *flow.QuorumCertificate, err error) *QuorumCertificates_ByBlockID_Call { + _c.Call.Return(quorumCertificate, err) + return _c +} + +func (_c *QuorumCertificates_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.QuorumCertificate, error)) *QuorumCertificates_ByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/reader.go b/storage/mock/reader.go index b3fab6abdb8..58790b90c03 100644 --- a/storage/mock/reader.go +++ b/storage/mock/reader.go @@ -1,22 +1,46 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - io "io" + "io" - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewReader creates a new instance of Reader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReader(t interface { + mock.TestingT + Cleanup(func()) +}) *Reader { + mock := &Reader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Reader is an autogenerated mock type for the Reader type type Reader struct { mock.Mock } -// Get provides a mock function with given fields: key -func (_m *Reader) Get(key []byte) ([]byte, io.Closer, error) { - ret := _m.Called(key) +type Reader_Expecter struct { + mock *mock.Mock +} + +func (_m *Reader) EXPECT() *Reader_Expecter { + return &Reader_Expecter{mock: &_m.Mock} +} + +// Get provides a mock function for the type Reader +func (_mock *Reader) Get(key []byte) ([]byte, io.Closer, error) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Get") @@ -25,37 +49,68 @@ func (_m *Reader) Get(key []byte) ([]byte, io.Closer, error) { var r0 []byte var r1 io.Closer var r2 error - if rf, ok := ret.Get(0).(func([]byte) ([]byte, io.Closer, error)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func([]byte) ([]byte, io.Closer, error)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func([]byte) []byte); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func([]byte) []byte); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func([]byte) io.Closer); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func([]byte) io.Closer); ok { + r1 = returnFunc(key) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(io.Closer) } } - - if rf, ok := ret.Get(2).(func([]byte) error); ok { - r2 = rf(key) + if returnFunc, ok := ret.Get(2).(func([]byte) error); ok { + r2 = returnFunc(key) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewIter provides a mock function with given fields: startPrefix, endPrefix, ops -func (_m *Reader) NewIter(startPrefix []byte, endPrefix []byte, ops storage.IteratorOption) (storage.Iterator, error) { - ret := _m.Called(startPrefix, endPrefix, ops) +// Reader_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type Reader_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - key []byte +func (_e *Reader_Expecter) Get(key interface{}) *Reader_Get_Call { + return &Reader_Get_Call{Call: _e.mock.On("Get", key)} +} + +func (_c *Reader_Get_Call) Run(run func(key []byte)) *Reader_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Reader_Get_Call) Return(value []byte, closer io.Closer, err error) *Reader_Get_Call { + _c.Call.Return(value, closer, err) + return _c +} + +func (_c *Reader_Get_Call) RunAndReturn(run func(key []byte) ([]byte, io.Closer, error)) *Reader_Get_Call { + _c.Call.Return(run) + return _c +} + +// NewIter provides a mock function for the type Reader +func (_mock *Reader) NewIter(startPrefix []byte, endPrefix []byte, ops storage.IteratorOption) (storage.Iterator, error) { + ret := _mock.Called(startPrefix, endPrefix, ops) if len(ret) == 0 { panic("no return value specified for NewIter") @@ -63,56 +118,112 @@ func (_m *Reader) NewIter(startPrefix []byte, endPrefix []byte, ops storage.Iter var r0 storage.Iterator var r1 error - if rf, ok := ret.Get(0).(func([]byte, []byte, storage.IteratorOption) (storage.Iterator, error)); ok { - return rf(startPrefix, endPrefix, ops) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte, storage.IteratorOption) (storage.Iterator, error)); ok { + return returnFunc(startPrefix, endPrefix, ops) } - if rf, ok := ret.Get(0).(func([]byte, []byte, storage.IteratorOption) storage.Iterator); ok { - r0 = rf(startPrefix, endPrefix, ops) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte, storage.IteratorOption) storage.Iterator); ok { + r0 = returnFunc(startPrefix, endPrefix, ops) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Iterator) } } - - if rf, ok := ret.Get(1).(func([]byte, []byte, storage.IteratorOption) error); ok { - r1 = rf(startPrefix, endPrefix, ops) + if returnFunc, ok := ret.Get(1).(func([]byte, []byte, storage.IteratorOption) error); ok { + r1 = returnFunc(startPrefix, endPrefix, ops) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSeeker provides a mock function with no fields -func (_m *Reader) NewSeeker() storage.Seeker { - ret := _m.Called() +// Reader_NewIter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewIter' +type Reader_NewIter_Call struct { + *mock.Call +} + +// NewIter is a helper method to define mock.On call +// - startPrefix []byte +// - endPrefix []byte +// - ops storage.IteratorOption +func (_e *Reader_Expecter) NewIter(startPrefix interface{}, endPrefix interface{}, ops interface{}) *Reader_NewIter_Call { + return &Reader_NewIter_Call{Call: _e.mock.On("NewIter", startPrefix, endPrefix, ops)} +} + +func (_c *Reader_NewIter_Call) Run(run func(startPrefix []byte, endPrefix []byte, ops storage.IteratorOption)) *Reader_NewIter_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 storage.IteratorOption + if args[2] != nil { + arg2 = args[2].(storage.IteratorOption) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Reader_NewIter_Call) Return(iterator storage.Iterator, err error) *Reader_NewIter_Call { + _c.Call.Return(iterator, err) + return _c +} + +func (_c *Reader_NewIter_Call) RunAndReturn(run func(startPrefix []byte, endPrefix []byte, ops storage.IteratorOption) (storage.Iterator, error)) *Reader_NewIter_Call { + _c.Call.Return(run) + return _c +} + +// NewSeeker provides a mock function for the type Reader +func (_mock *Reader) NewSeeker() storage.Seeker { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for NewSeeker") } var r0 storage.Seeker - if rf, ok := ret.Get(0).(func() storage.Seeker); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.Seeker); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Seeker) } } - return r0 } -// NewReader creates a new instance of Reader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReader(t interface { - mock.TestingT - Cleanup(func()) -}) *Reader { - mock := &Reader{} - mock.Mock.Test(t) +// Reader_NewSeeker_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewSeeker' +type Reader_NewSeeker_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// NewSeeker is a helper method to define mock.On call +func (_e *Reader_Expecter) NewSeeker() *Reader_NewSeeker_Call { + return &Reader_NewSeeker_Call{Call: _e.mock.On("NewSeeker")} +} - return mock +func (_c *Reader_NewSeeker_Call) Run(run func()) *Reader_NewSeeker_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *Reader_NewSeeker_Call) Return(seeker storage.Seeker) *Reader_NewSeeker_Call { + _c.Call.Return(seeker) + return _c +} + +func (_c *Reader_NewSeeker_Call) RunAndReturn(run func() storage.Seeker) *Reader_NewSeeker_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/reader_batch_writer.go b/storage/mock/reader_batch_writer.go index 7141a9a9893..fcd8ed75e9e 100644 --- a/storage/mock/reader_batch_writer.go +++ b/storage/mock/reader_batch_writer.go @@ -1,45 +1,130 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewReaderBatchWriter creates a new instance of ReaderBatchWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewReaderBatchWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *ReaderBatchWriter { + mock := &ReaderBatchWriter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ReaderBatchWriter is an autogenerated mock type for the ReaderBatchWriter type type ReaderBatchWriter struct { mock.Mock } -// AddCallback provides a mock function with given fields: _a0 -func (_m *ReaderBatchWriter) AddCallback(_a0 func(error)) { - _m.Called(_a0) +type ReaderBatchWriter_Expecter struct { + mock *mock.Mock +} + +func (_m *ReaderBatchWriter) EXPECT() *ReaderBatchWriter_Expecter { + return &ReaderBatchWriter_Expecter{mock: &_m.Mock} } -// GlobalReader provides a mock function with no fields -func (_m *ReaderBatchWriter) GlobalReader() storage.Reader { - ret := _m.Called() +// AddCallback provides a mock function for the type ReaderBatchWriter +func (_mock *ReaderBatchWriter) AddCallback(fn func(error)) { + _mock.Called(fn) + return +} + +// ReaderBatchWriter_AddCallback_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddCallback' +type ReaderBatchWriter_AddCallback_Call struct { + *mock.Call +} + +// AddCallback is a helper method to define mock.On call +// - fn func(error) +func (_e *ReaderBatchWriter_Expecter) AddCallback(fn interface{}) *ReaderBatchWriter_AddCallback_Call { + return &ReaderBatchWriter_AddCallback_Call{Call: _e.mock.On("AddCallback", fn)} +} + +func (_c *ReaderBatchWriter_AddCallback_Call) Run(run func(fn func(error))) *ReaderBatchWriter_AddCallback_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 func(error) + if args[0] != nil { + arg0 = args[0].(func(error)) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ReaderBatchWriter_AddCallback_Call) Return() *ReaderBatchWriter_AddCallback_Call { + _c.Call.Return() + return _c +} + +func (_c *ReaderBatchWriter_AddCallback_Call) RunAndReturn(run func(fn func(error))) *ReaderBatchWriter_AddCallback_Call { + _c.Run(run) + return _c +} + +// GlobalReader provides a mock function for the type ReaderBatchWriter +func (_mock *ReaderBatchWriter) GlobalReader() storage.Reader { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for GlobalReader") } var r0 storage.Reader - if rf, ok := ret.Get(0).(func() storage.Reader); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.Reader); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Reader) } } - return r0 } -// ScopedValue provides a mock function with given fields: key -func (_m *ReaderBatchWriter) ScopedValue(key string) (any, bool) { - ret := _m.Called(key) +// ReaderBatchWriter_GlobalReader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GlobalReader' +type ReaderBatchWriter_GlobalReader_Call struct { + *mock.Call +} + +// GlobalReader is a helper method to define mock.On call +func (_e *ReaderBatchWriter_Expecter) GlobalReader() *ReaderBatchWriter_GlobalReader_Call { + return &ReaderBatchWriter_GlobalReader_Call{Call: _e.mock.On("GlobalReader")} +} + +func (_c *ReaderBatchWriter_GlobalReader_Call) Run(run func()) *ReaderBatchWriter_GlobalReader_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReaderBatchWriter_GlobalReader_Call) Return(reader storage.Reader) *ReaderBatchWriter_GlobalReader_Call { + _c.Call.Return(reader) + return _c +} + +func (_c *ReaderBatchWriter_GlobalReader_Call) RunAndReturn(run func() storage.Reader) *ReaderBatchWriter_GlobalReader_Call { + _c.Call.Return(run) + return _c +} + +// ScopedValue provides a mock function for the type ReaderBatchWriter +func (_mock *ReaderBatchWriter) ScopedValue(key string) (any, bool) { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for ScopedValue") @@ -47,61 +132,146 @@ func (_m *ReaderBatchWriter) ScopedValue(key string) (any, bool) { var r0 any var r1 bool - if rf, ok := ret.Get(0).(func(string) (any, bool)); ok { - return rf(key) + if returnFunc, ok := ret.Get(0).(func(string) (any, bool)); ok { + return returnFunc(key) } - if rf, ok := ret.Get(0).(func(string) any); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func(string) any); ok { + r0 = returnFunc(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(any) } } - - if rf, ok := ret.Get(1).(func(string) bool); ok { - r1 = rf(key) + if returnFunc, ok := ret.Get(1).(func(string) bool); ok { + r1 = returnFunc(key) } else { r1 = ret.Get(1).(bool) } - return r0, r1 } -// SetScopedValue provides a mock function with given fields: key, value -func (_m *ReaderBatchWriter) SetScopedValue(key string, value any) { - _m.Called(key, value) +// ReaderBatchWriter_ScopedValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ScopedValue' +type ReaderBatchWriter_ScopedValue_Call struct { + *mock.Call +} + +// ScopedValue is a helper method to define mock.On call +// - key string +func (_e *ReaderBatchWriter_Expecter) ScopedValue(key interface{}) *ReaderBatchWriter_ScopedValue_Call { + return &ReaderBatchWriter_ScopedValue_Call{Call: _e.mock.On("ScopedValue", key)} +} + +func (_c *ReaderBatchWriter_ScopedValue_Call) Run(run func(key string)) *ReaderBatchWriter_ScopedValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + run( + arg0, + ) + }) + return _c } -// Writer provides a mock function with no fields -func (_m *ReaderBatchWriter) Writer() storage.Writer { - ret := _m.Called() +func (_c *ReaderBatchWriter_ScopedValue_Call) Return(v any, b bool) *ReaderBatchWriter_ScopedValue_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *ReaderBatchWriter_ScopedValue_Call) RunAndReturn(run func(key string) (any, bool)) *ReaderBatchWriter_ScopedValue_Call { + _c.Call.Return(run) + return _c +} + +// SetScopedValue provides a mock function for the type ReaderBatchWriter +func (_mock *ReaderBatchWriter) SetScopedValue(key string, value any) { + _mock.Called(key, value) + return +} + +// ReaderBatchWriter_SetScopedValue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetScopedValue' +type ReaderBatchWriter_SetScopedValue_Call struct { + *mock.Call +} + +// SetScopedValue is a helper method to define mock.On call +// - key string +// - value any +func (_e *ReaderBatchWriter_Expecter) SetScopedValue(key interface{}, value interface{}) *ReaderBatchWriter_SetScopedValue_Call { + return &ReaderBatchWriter_SetScopedValue_Call{Call: _e.mock.On("SetScopedValue", key, value)} +} + +func (_c *ReaderBatchWriter_SetScopedValue_Call) Run(run func(key string, value any)) *ReaderBatchWriter_SetScopedValue_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 any + if args[1] != nil { + arg1 = args[1].(any) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ReaderBatchWriter_SetScopedValue_Call) Return() *ReaderBatchWriter_SetScopedValue_Call { + _c.Call.Return() + return _c +} + +func (_c *ReaderBatchWriter_SetScopedValue_Call) RunAndReturn(run func(key string, value any)) *ReaderBatchWriter_SetScopedValue_Call { + _c.Run(run) + return _c +} + +// Writer provides a mock function for the type ReaderBatchWriter +func (_mock *ReaderBatchWriter) Writer() storage.Writer { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for Writer") } var r0 storage.Writer - if rf, ok := ret.Get(0).(func() storage.Writer); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() storage.Writer); ok { + r0 = returnFunc() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(storage.Writer) } } - return r0 } -// NewReaderBatchWriter creates a new instance of ReaderBatchWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReaderBatchWriter(t interface { - mock.TestingT - Cleanup(func()) -}) *ReaderBatchWriter { - mock := &ReaderBatchWriter{} - mock.Mock.Test(t) +// ReaderBatchWriter_Writer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Writer' +type ReaderBatchWriter_Writer_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Writer is a helper method to define mock.On call +func (_e *ReaderBatchWriter_Expecter) Writer() *ReaderBatchWriter_Writer_Call { + return &ReaderBatchWriter_Writer_Call{Call: _e.mock.On("Writer")} +} - return mock +func (_c *ReaderBatchWriter_Writer_Call) Run(run func()) *ReaderBatchWriter_Writer_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ReaderBatchWriter_Writer_Call) Return(writer storage.Writer) *ReaderBatchWriter_Writer_Call { + _c.Call.Return(writer) + return _c +} + +func (_c *ReaderBatchWriter_Writer_Call) RunAndReturn(run func() storage.Writer) *ReaderBatchWriter_Writer_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/register_index.go b/storage/mock/register_index.go index 83be7904666..67f20bb5232 100644 --- a/storage/mock/register_index.go +++ b/storage/mock/register_index.go @@ -1,38 +1,154 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewRegisterIndex creates a new instance of RegisterIndex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRegisterIndex(t interface { + mock.TestingT + Cleanup(func()) +}) *RegisterIndex { + mock := &RegisterIndex{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RegisterIndex is an autogenerated mock type for the RegisterIndex type type RegisterIndex struct { mock.Mock } -// FirstHeight provides a mock function with no fields -func (_m *RegisterIndex) FirstHeight() uint64 { - ret := _m.Called() +type RegisterIndex_Expecter struct { + mock *mock.Mock +} + +func (_m *RegisterIndex) EXPECT() *RegisterIndex_Expecter { + return &RegisterIndex_Expecter{mock: &_m.Mock} +} + +// ByKeyPrefix provides a mock function for the type RegisterIndex +func (_mock *RegisterIndex) ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] { + ret := _mock.Called(keyPrefix, height, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByKeyPrefix") + } + + var r0 storage.IndexIterator[flow.RegisterValue, flow.RegisterID] + if returnFunc, ok := ret.Get(0).(func(string, uint64, *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]); ok { + r0 = returnFunc(keyPrefix, height, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) + } + } + return r0 +} + +// RegisterIndex_ByKeyPrefix_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByKeyPrefix' +type RegisterIndex_ByKeyPrefix_Call struct { + *mock.Call +} + +// ByKeyPrefix is a helper method to define mock.On call +// - keyPrefix string +// - height uint64 +// - cursor *flow.RegisterID +func (_e *RegisterIndex_Expecter) ByKeyPrefix(keyPrefix interface{}, height interface{}, cursor interface{}) *RegisterIndex_ByKeyPrefix_Call { + return &RegisterIndex_ByKeyPrefix_Call{Call: _e.mock.On("ByKeyPrefix", keyPrefix, height, cursor)} +} + +func (_c *RegisterIndex_ByKeyPrefix_Call) Run(run func(keyPrefix string, height uint64, cursor *flow.RegisterID)) *RegisterIndex_ByKeyPrefix_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.RegisterID + if args[2] != nil { + arg2 = args[2].(*flow.RegisterID) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *RegisterIndex_ByKeyPrefix_Call) Return(indexIterator storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *RegisterIndex_ByKeyPrefix_Call { + _c.Call.Return(indexIterator) + return _c +} + +func (_c *RegisterIndex_ByKeyPrefix_Call) RunAndReturn(run func(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *RegisterIndex_ByKeyPrefix_Call { + _c.Call.Return(run) + return _c +} + +// FirstHeight provides a mock function for the type RegisterIndex +func (_mock *RegisterIndex) FirstHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FirstHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Get provides a mock function with given fields: ID, height -func (_m *RegisterIndex) Get(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { - ret := _m.Called(ID, height) +// RegisterIndex_FirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstHeight' +type RegisterIndex_FirstHeight_Call struct { + *mock.Call +} + +// FirstHeight is a helper method to define mock.On call +func (_e *RegisterIndex_Expecter) FirstHeight() *RegisterIndex_FirstHeight_Call { + return &RegisterIndex_FirstHeight_Call{Call: _e.mock.On("FirstHeight")} +} + +func (_c *RegisterIndex_FirstHeight_Call) Run(run func()) *RegisterIndex_FirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterIndex_FirstHeight_Call) Return(v uint64) *RegisterIndex_FirstHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *RegisterIndex_FirstHeight_Call) RunAndReturn(run func() uint64) *RegisterIndex_FirstHeight_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type RegisterIndex +func (_mock *RegisterIndex) Get(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { + ret := _mock.Called(ID, height) if len(ret) == 0 { panic("no return value specified for Get") @@ -40,72 +156,161 @@ func (_m *RegisterIndex) Get(ID flow.RegisterID, height uint64) (flow.RegisterVa var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { - return rf(ID, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { + return returnFunc(ID, height) } - if rf, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { - r0 = rf(ID, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { + r0 = returnFunc(ID, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { - r1 = rf(ID, height) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { + r1 = returnFunc(ID, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// LatestHeight provides a mock function with no fields -func (_m *RegisterIndex) LatestHeight() uint64 { - ret := _m.Called() +// RegisterIndex_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type RegisterIndex_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - ID flow.RegisterID +// - height uint64 +func (_e *RegisterIndex_Expecter) Get(ID interface{}, height interface{}) *RegisterIndex_Get_Call { + return &RegisterIndex_Get_Call{Call: _e.mock.On("Get", ID, height)} +} + +func (_c *RegisterIndex_Get_Call) Run(run func(ID flow.RegisterID, height uint64)) *RegisterIndex_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RegisterIndex_Get_Call) Return(v flow.RegisterValue, err error) *RegisterIndex_Get_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *RegisterIndex_Get_Call) RunAndReturn(run func(ID flow.RegisterID, height uint64) (flow.RegisterValue, error)) *RegisterIndex_Get_Call { + _c.Call.Return(run) + return _c +} + +// LatestHeight provides a mock function for the type RegisterIndex +func (_mock *RegisterIndex) LatestHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LatestHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Store provides a mock function with given fields: entries, height -func (_m *RegisterIndex) Store(entries flow.RegisterEntries, height uint64) error { - ret := _m.Called(entries, height) +// RegisterIndex_LatestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestHeight' +type RegisterIndex_LatestHeight_Call struct { + *mock.Call +} + +// LatestHeight is a helper method to define mock.On call +func (_e *RegisterIndex_Expecter) LatestHeight() *RegisterIndex_LatestHeight_Call { + return &RegisterIndex_LatestHeight_Call{Call: _e.mock.On("LatestHeight")} +} + +func (_c *RegisterIndex_LatestHeight_Call) Run(run func()) *RegisterIndex_LatestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterIndex_LatestHeight_Call) Return(v uint64) *RegisterIndex_LatestHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *RegisterIndex_LatestHeight_Call) RunAndReturn(run func() uint64) *RegisterIndex_LatestHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type RegisterIndex +func (_mock *RegisterIndex) Store(entries flow.RegisterEntries, height uint64) error { + ret := _mock.Called(entries, height) if len(ret) == 0 { panic("no return value specified for Store") } var r0 error - if rf, ok := ret.Get(0).(func(flow.RegisterEntries, uint64) error); ok { - r0 = rf(entries, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterEntries, uint64) error); ok { + r0 = returnFunc(entries, height) } else { r0 = ret.Error(0) } - return r0 } -// NewRegisterIndex creates a new instance of RegisterIndex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRegisterIndex(t interface { - mock.TestingT - Cleanup(func()) -}) *RegisterIndex { - mock := &RegisterIndex{} - mock.Mock.Test(t) +// RegisterIndex_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type RegisterIndex_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - entries flow.RegisterEntries +// - height uint64 +func (_e *RegisterIndex_Expecter) Store(entries interface{}, height interface{}) *RegisterIndex_Store_Call { + return &RegisterIndex_Store_Call{Call: _e.mock.On("Store", entries, height)} +} - return mock +func (_c *RegisterIndex_Store_Call) Run(run func(entries flow.RegisterEntries, height uint64)) *RegisterIndex_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterEntries + if args[0] != nil { + arg0 = args[0].(flow.RegisterEntries) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RegisterIndex_Store_Call) Return(err error) *RegisterIndex_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *RegisterIndex_Store_Call) RunAndReturn(run func(entries flow.RegisterEntries, height uint64) error) *RegisterIndex_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/register_index_reader.go b/storage/mock/register_index_reader.go index 8a056bd5943..d762e35e267 100644 --- a/storage/mock/register_index_reader.go +++ b/storage/mock/register_index_reader.go @@ -1,38 +1,154 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewRegisterIndexReader creates a new instance of RegisterIndexReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRegisterIndexReader(t interface { + mock.TestingT + Cleanup(func()) +}) *RegisterIndexReader { + mock := &RegisterIndexReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // RegisterIndexReader is an autogenerated mock type for the RegisterIndexReader type type RegisterIndexReader struct { mock.Mock } -// FirstHeight provides a mock function with no fields -func (_m *RegisterIndexReader) FirstHeight() uint64 { - ret := _m.Called() +type RegisterIndexReader_Expecter struct { + mock *mock.Mock +} + +func (_m *RegisterIndexReader) EXPECT() *RegisterIndexReader_Expecter { + return &RegisterIndexReader_Expecter{mock: &_m.Mock} +} + +// ByKeyPrefix provides a mock function for the type RegisterIndexReader +func (_mock *RegisterIndexReader) ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] { + ret := _mock.Called(keyPrefix, height, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByKeyPrefix") + } + + var r0 storage.IndexIterator[flow.RegisterValue, flow.RegisterID] + if returnFunc, ok := ret.Get(0).(func(string, uint64, *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]); ok { + r0 = returnFunc(keyPrefix, height, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) + } + } + return r0 +} + +// RegisterIndexReader_ByKeyPrefix_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByKeyPrefix' +type RegisterIndexReader_ByKeyPrefix_Call struct { + *mock.Call +} + +// ByKeyPrefix is a helper method to define mock.On call +// - keyPrefix string +// - height uint64 +// - cursor *flow.RegisterID +func (_e *RegisterIndexReader_Expecter) ByKeyPrefix(keyPrefix interface{}, height interface{}, cursor interface{}) *RegisterIndexReader_ByKeyPrefix_Call { + return &RegisterIndexReader_ByKeyPrefix_Call{Call: _e.mock.On("ByKeyPrefix", keyPrefix, height, cursor)} +} + +func (_c *RegisterIndexReader_ByKeyPrefix_Call) Run(run func(keyPrefix string, height uint64, cursor *flow.RegisterID)) *RegisterIndexReader_ByKeyPrefix_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + var arg2 *flow.RegisterID + if args[2] != nil { + arg2 = args[2].(*flow.RegisterID) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *RegisterIndexReader_ByKeyPrefix_Call) Return(indexIterator storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *RegisterIndexReader_ByKeyPrefix_Call { + _c.Call.Return(indexIterator) + return _c +} + +func (_c *RegisterIndexReader_ByKeyPrefix_Call) RunAndReturn(run func(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) *RegisterIndexReader_ByKeyPrefix_Call { + _c.Call.Return(run) + return _c +} + +// FirstHeight provides a mock function for the type RegisterIndexReader +func (_mock *RegisterIndexReader) FirstHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for FirstHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// Get provides a mock function with given fields: ID, height -func (_m *RegisterIndexReader) Get(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { - ret := _m.Called(ID, height) +// RegisterIndexReader_FirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstHeight' +type RegisterIndexReader_FirstHeight_Call struct { + *mock.Call +} + +// FirstHeight is a helper method to define mock.On call +func (_e *RegisterIndexReader_Expecter) FirstHeight() *RegisterIndexReader_FirstHeight_Call { + return &RegisterIndexReader_FirstHeight_Call{Call: _e.mock.On("FirstHeight")} +} + +func (_c *RegisterIndexReader_FirstHeight_Call) Run(run func()) *RegisterIndexReader_FirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterIndexReader_FirstHeight_Call) Return(v uint64) *RegisterIndexReader_FirstHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *RegisterIndexReader_FirstHeight_Call) RunAndReturn(run func() uint64) *RegisterIndexReader_FirstHeight_Call { + _c.Call.Return(run) + return _c +} + +// Get provides a mock function for the type RegisterIndexReader +func (_mock *RegisterIndexReader) Get(ID flow.RegisterID, height uint64) (flow.RegisterValue, error) { + ret := _mock.Called(ID, height) if len(ret) == 0 { panic("no return value specified for Get") @@ -40,54 +156,104 @@ func (_m *RegisterIndexReader) Get(ID flow.RegisterID, height uint64) (flow.Regi var r0 flow.RegisterValue var r1 error - if rf, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { - return rf(ID, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) (flow.RegisterValue, error)); ok { + return returnFunc(ID, height) } - if rf, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { - r0 = rf(ID, height) + if returnFunc, ok := ret.Get(0).(func(flow.RegisterID, uint64) flow.RegisterValue); ok { + r0 = returnFunc(ID, height) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.RegisterValue) } } - - if rf, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { - r1 = rf(ID, height) + if returnFunc, ok := ret.Get(1).(func(flow.RegisterID, uint64) error); ok { + r1 = returnFunc(ID, height) } else { r1 = ret.Error(1) } - return r0, r1 } -// LatestHeight provides a mock function with no fields -func (_m *RegisterIndexReader) LatestHeight() uint64 { - ret := _m.Called() +// RegisterIndexReader_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' +type RegisterIndexReader_Get_Call struct { + *mock.Call +} + +// Get is a helper method to define mock.On call +// - ID flow.RegisterID +// - height uint64 +func (_e *RegisterIndexReader_Expecter) Get(ID interface{}, height interface{}) *RegisterIndexReader_Get_Call { + return &RegisterIndexReader_Get_Call{Call: _e.mock.On("Get", ID, height)} +} + +func (_c *RegisterIndexReader_Get_Call) Run(run func(ID flow.RegisterID, height uint64)) *RegisterIndexReader_Get_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.RegisterID + if args[0] != nil { + arg0 = args[0].(flow.RegisterID) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *RegisterIndexReader_Get_Call) Return(v flow.RegisterValue, err error) *RegisterIndexReader_Get_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *RegisterIndexReader_Get_Call) RunAndReturn(run func(ID flow.RegisterID, height uint64) (flow.RegisterValue, error)) *RegisterIndexReader_Get_Call { + _c.Call.Return(run) + return _c +} + +// LatestHeight provides a mock function for the type RegisterIndexReader +func (_mock *RegisterIndexReader) LatestHeight() uint64 { + ret := _mock.Called() if len(ret) == 0 { panic("no return value specified for LatestHeight") } var r0 uint64 - if rf, ok := ret.Get(0).(func() uint64); ok { - r0 = rf() + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() } else { r0 = ret.Get(0).(uint64) } - return r0 } -// NewRegisterIndexReader creates a new instance of RegisterIndexReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewRegisterIndexReader(t interface { - mock.TestingT - Cleanup(func()) -}) *RegisterIndexReader { - mock := &RegisterIndexReader{} - mock.Mock.Test(t) +// RegisterIndexReader_LatestHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestHeight' +type RegisterIndexReader_LatestHeight_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// LatestHeight is a helper method to define mock.On call +func (_e *RegisterIndexReader_Expecter) LatestHeight() *RegisterIndexReader_LatestHeight_Call { + return &RegisterIndexReader_LatestHeight_Call{Call: _e.mock.On("LatestHeight")} +} - return mock +func (_c *RegisterIndexReader_LatestHeight_Call) Run(run func()) *RegisterIndexReader_LatestHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *RegisterIndexReader_LatestHeight_Call) Return(v uint64) *RegisterIndexReader_LatestHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *RegisterIndexReader_LatestHeight_Call) RunAndReturn(run func() uint64) *RegisterIndexReader_LatestHeight_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/result_approvals.go b/storage/mock/result_approvals.go index a050d410707..197cfa239cd 100644 --- a/storage/mock/result_approvals.go +++ b/storage/mock/result_approvals.go @@ -1,22 +1,45 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewResultApprovals creates a new instance of ResultApprovals. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewResultApprovals(t interface { + mock.TestingT + Cleanup(func()) +}) *ResultApprovals { + mock := &ResultApprovals{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ResultApprovals is an autogenerated mock type for the ResultApprovals type type ResultApprovals struct { mock.Mock } -// ByChunk provides a mock function with given fields: resultID, chunkIndex -func (_m *ResultApprovals) ByChunk(resultID flow.Identifier, chunkIndex uint64) (*flow.ResultApproval, error) { - ret := _m.Called(resultID, chunkIndex) +type ResultApprovals_Expecter struct { + mock *mock.Mock +} + +func (_m *ResultApprovals) EXPECT() *ResultApprovals_Expecter { + return &ResultApprovals_Expecter{mock: &_m.Mock} +} + +// ByChunk provides a mock function for the type ResultApprovals +func (_mock *ResultApprovals) ByChunk(resultID flow.Identifier, chunkIndex uint64) (*flow.ResultApproval, error) { + ret := _mock.Called(resultID, chunkIndex) if len(ret) == 0 { panic("no return value specified for ByChunk") @@ -24,29 +47,67 @@ func (_m *ResultApprovals) ByChunk(resultID flow.Identifier, chunkIndex uint64) var r0 *flow.ResultApproval var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint64) (*flow.ResultApproval, error)); ok { - return rf(resultID, chunkIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint64) (*flow.ResultApproval, error)); ok { + return returnFunc(resultID, chunkIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint64) *flow.ResultApproval); ok { - r0 = rf(resultID, chunkIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint64) *flow.ResultApproval); ok { + r0 = returnFunc(resultID, chunkIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ResultApproval) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint64) error); ok { - r1 = rf(resultID, chunkIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint64) error); ok { + r1 = returnFunc(resultID, chunkIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByID provides a mock function with given fields: approvalID -func (_m *ResultApprovals) ByID(approvalID flow.Identifier) (*flow.ResultApproval, error) { - ret := _m.Called(approvalID) +// ResultApprovals_ByChunk_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByChunk' +type ResultApprovals_ByChunk_Call struct { + *mock.Call +} + +// ByChunk is a helper method to define mock.On call +// - resultID flow.Identifier +// - chunkIndex uint64 +func (_e *ResultApprovals_Expecter) ByChunk(resultID interface{}, chunkIndex interface{}) *ResultApprovals_ByChunk_Call { + return &ResultApprovals_ByChunk_Call{Call: _e.mock.On("ByChunk", resultID, chunkIndex)} +} + +func (_c *ResultApprovals_ByChunk_Call) Run(run func(resultID flow.Identifier, chunkIndex uint64)) *ResultApprovals_ByChunk_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint64 + if args[1] != nil { + arg1 = args[1].(uint64) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ResultApprovals_ByChunk_Call) Return(resultApproval *flow.ResultApproval, err error) *ResultApprovals_ByChunk_Call { + _c.Call.Return(resultApproval, err) + return _c +} + +func (_c *ResultApprovals_ByChunk_Call) RunAndReturn(run func(resultID flow.Identifier, chunkIndex uint64) (*flow.ResultApproval, error)) *ResultApprovals_ByChunk_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ResultApprovals +func (_mock *ResultApprovals) ByID(approvalID flow.Identifier) (*flow.ResultApproval, error) { + ret := _mock.Called(approvalID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -54,56 +115,107 @@ func (_m *ResultApprovals) ByID(approvalID flow.Identifier) (*flow.ResultApprova var r0 *flow.ResultApproval var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.ResultApproval, error)); ok { - return rf(approvalID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.ResultApproval, error)); ok { + return returnFunc(approvalID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.ResultApproval); ok { - r0 = rf(approvalID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.ResultApproval); ok { + r0 = returnFunc(approvalID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.ResultApproval) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(approvalID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(approvalID) } else { r1 = ret.Error(1) } - return r0, r1 } -// StoreMyApproval provides a mock function with given fields: approval -func (_m *ResultApprovals) StoreMyApproval(approval *flow.ResultApproval) func(lockctx.Proof) error { - ret := _m.Called(approval) +// ResultApprovals_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ResultApprovals_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - approvalID flow.Identifier +func (_e *ResultApprovals_Expecter) ByID(approvalID interface{}) *ResultApprovals_ByID_Call { + return &ResultApprovals_ByID_Call{Call: _e.mock.On("ByID", approvalID)} +} + +func (_c *ResultApprovals_ByID_Call) Run(run func(approvalID flow.Identifier)) *ResultApprovals_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ResultApprovals_ByID_Call) Return(resultApproval *flow.ResultApproval, err error) *ResultApprovals_ByID_Call { + _c.Call.Return(resultApproval, err) + return _c +} + +func (_c *ResultApprovals_ByID_Call) RunAndReturn(run func(approvalID flow.Identifier) (*flow.ResultApproval, error)) *ResultApprovals_ByID_Call { + _c.Call.Return(run) + return _c +} + +// StoreMyApproval provides a mock function for the type ResultApprovals +func (_mock *ResultApprovals) StoreMyApproval(approval *flow.ResultApproval) func(lctx lockctx.Proof) error { + ret := _mock.Called(approval) if len(ret) == 0 { panic("no return value specified for StoreMyApproval") } - var r0 func(lockctx.Proof) error - if rf, ok := ret.Get(0).(func(*flow.ResultApproval) func(lockctx.Proof) error); ok { - r0 = rf(approval) + var r0 func(lctx lockctx.Proof) error + if returnFunc, ok := ret.Get(0).(func(*flow.ResultApproval) func(lctx lockctx.Proof) error); ok { + r0 = returnFunc(approval) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(func(lockctx.Proof) error) + r0 = ret.Get(0).(func(lctx lockctx.Proof) error) } } - return r0 } -// NewResultApprovals creates a new instance of ResultApprovals. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewResultApprovals(t interface { - mock.TestingT - Cleanup(func()) -}) *ResultApprovals { - mock := &ResultApprovals{} - mock.Mock.Test(t) +// ResultApprovals_StoreMyApproval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StoreMyApproval' +type ResultApprovals_StoreMyApproval_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StoreMyApproval is a helper method to define mock.On call +// - approval *flow.ResultApproval +func (_e *ResultApprovals_Expecter) StoreMyApproval(approval interface{}) *ResultApprovals_StoreMyApproval_Call { + return &ResultApprovals_StoreMyApproval_Call{Call: _e.mock.On("StoreMyApproval", approval)} +} - return mock +func (_c *ResultApprovals_StoreMyApproval_Call) Run(run func(approval *flow.ResultApproval)) *ResultApprovals_StoreMyApproval_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.ResultApproval + if args[0] != nil { + arg0 = args[0].(*flow.ResultApproval) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ResultApprovals_StoreMyApproval_Call) Return(fn func(lctx lockctx.Proof) error) *ResultApprovals_StoreMyApproval_Call { + _c.Call.Return(fn) + return _c +} + +func (_c *ResultApprovals_StoreMyApproval_Call) RunAndReturn(run func(approval *flow.ResultApproval) func(lctx lockctx.Proof) error) *ResultApprovals_StoreMyApproval_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/safe_beacon_keys.go b/storage/mock/safe_beacon_keys.go index 9e0afae0cb7..edba9ac4a68 100644 --- a/storage/mock/safe_beacon_keys.go +++ b/storage/mock/safe_beacon_keys.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - crypto "github.com/onflow/crypto" + "github.com/onflow/crypto" mock "github.com/stretchr/testify/mock" ) +// NewSafeBeaconKeys creates a new instance of SafeBeaconKeys. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSafeBeaconKeys(t interface { + mock.TestingT + Cleanup(func()) +}) *SafeBeaconKeys { + mock := &SafeBeaconKeys{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // SafeBeaconKeys is an autogenerated mock type for the SafeBeaconKeys type type SafeBeaconKeys struct { mock.Mock } -// RetrieveMyBeaconPrivateKey provides a mock function with given fields: epochCounter -func (_m *SafeBeaconKeys) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { - ret := _m.Called(epochCounter) +type SafeBeaconKeys_Expecter struct { + mock *mock.Mock +} + +func (_m *SafeBeaconKeys) EXPECT() *SafeBeaconKeys_Expecter { + return &SafeBeaconKeys_Expecter{mock: &_m.Mock} +} + +// RetrieveMyBeaconPrivateKey provides a mock function for the type SafeBeaconKeys +func (_mock *SafeBeaconKeys) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypto.PrivateKey, bool, error) { + ret := _mock.Called(epochCounter) if len(ret) == 0 { panic("no return value specified for RetrieveMyBeaconPrivateKey") @@ -23,42 +47,59 @@ func (_m *SafeBeaconKeys) RetrieveMyBeaconPrivateKey(epochCounter uint64) (crypt var r0 crypto.PrivateKey var r1 bool var r2 error - if rf, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { - return rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) (crypto.PrivateKey, bool, error)); ok { + return returnFunc(epochCounter) } - if rf, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { - r0 = rf(epochCounter) + if returnFunc, ok := ret.Get(0).(func(uint64) crypto.PrivateKey); ok { + r0 = returnFunc(epochCounter) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(crypto.PrivateKey) } } - - if rf, ok := ret.Get(1).(func(uint64) bool); ok { - r1 = rf(epochCounter) + if returnFunc, ok := ret.Get(1).(func(uint64) bool); ok { + r1 = returnFunc(epochCounter) } else { r1 = ret.Get(1).(bool) } - - if rf, ok := ret.Get(2).(func(uint64) error); ok { - r2 = rf(epochCounter) + if returnFunc, ok := ret.Get(2).(func(uint64) error); ok { + r2 = returnFunc(epochCounter) } else { r2 = ret.Error(2) } - return r0, r1, r2 } -// NewSafeBeaconKeys creates a new instance of SafeBeaconKeys. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSafeBeaconKeys(t interface { - mock.TestingT - Cleanup(func()) -}) *SafeBeaconKeys { - mock := &SafeBeaconKeys{} - mock.Mock.Test(t) +// SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RetrieveMyBeaconPrivateKey' +type SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// RetrieveMyBeaconPrivateKey is a helper method to define mock.On call +// - epochCounter uint64 +func (_e *SafeBeaconKeys_Expecter) RetrieveMyBeaconPrivateKey(epochCounter interface{}) *SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call { + return &SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call{Call: _e.mock.On("RetrieveMyBeaconPrivateKey", epochCounter)} +} - return mock +func (_c *SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call) Run(run func(epochCounter uint64)) *SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call) Return(key crypto.PrivateKey, safe bool, err error) *SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(key, safe, err) + return _c +} + +func (_c *SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call) RunAndReturn(run func(epochCounter uint64) (crypto.PrivateKey, bool, error)) *SafeBeaconKeys_RetrieveMyBeaconPrivateKey_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/scheduled_transactions.go b/storage/mock/scheduled_transactions.go index 15845811ff2..b256576343c 100644 --- a/storage/mock/scheduled_transactions.go +++ b/storage/mock/scheduled_transactions.go @@ -1,42 +1,121 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewScheduledTransactions creates a new instance of ScheduledTransactions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScheduledTransactions(t interface { + mock.TestingT + Cleanup(func()) +}) *ScheduledTransactions { + mock := &ScheduledTransactions{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ScheduledTransactions is an autogenerated mock type for the ScheduledTransactions type type ScheduledTransactions struct { mock.Mock } -// BatchIndex provides a mock function with given fields: lctx, blockID, txID, scheduledTxID, batch -func (_m *ScheduledTransactions) BatchIndex(lctx lockctx.Proof, blockID flow.Identifier, txID flow.Identifier, scheduledTxID uint64, batch storage.ReaderBatchWriter) error { - ret := _m.Called(lctx, blockID, txID, scheduledTxID, batch) +type ScheduledTransactions_Expecter struct { + mock *mock.Mock +} + +func (_m *ScheduledTransactions) EXPECT() *ScheduledTransactions_Expecter { + return &ScheduledTransactions_Expecter{mock: &_m.Mock} +} + +// BatchIndex provides a mock function for the type ScheduledTransactions +func (_mock *ScheduledTransactions) BatchIndex(lctx lockctx.Proof, blockID flow.Identifier, txID flow.Identifier, scheduledTxID uint64, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(lctx, blockID, txID, scheduledTxID, batch) if len(ret) == 0 { panic("no return value specified for BatchIndex") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, flow.Identifier, uint64, storage.ReaderBatchWriter) error); ok { - r0 = rf(lctx, blockID, txID, scheduledTxID, batch) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, flow.Identifier, uint64, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(lctx, blockID, txID, scheduledTxID, batch) } else { r0 = ret.Error(0) } - return r0 } -// BlockIDByTransactionID provides a mock function with given fields: txID -func (_m *ScheduledTransactions) BlockIDByTransactionID(txID flow.Identifier) (flow.Identifier, error) { - ret := _m.Called(txID) +// ScheduledTransactions_BatchIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchIndex' +type ScheduledTransactions_BatchIndex_Call struct { + *mock.Call +} + +// BatchIndex is a helper method to define mock.On call +// - lctx lockctx.Proof +// - blockID flow.Identifier +// - txID flow.Identifier +// - scheduledTxID uint64 +// - batch storage.ReaderBatchWriter +func (_e *ScheduledTransactions_Expecter) BatchIndex(lctx interface{}, blockID interface{}, txID interface{}, scheduledTxID interface{}, batch interface{}) *ScheduledTransactions_BatchIndex_Call { + return &ScheduledTransactions_BatchIndex_Call{Call: _e.mock.On("BatchIndex", lctx, blockID, txID, scheduledTxID, batch)} +} + +func (_c *ScheduledTransactions_BatchIndex_Call) Run(run func(lctx lockctx.Proof, blockID flow.Identifier, txID flow.Identifier, scheduledTxID uint64, batch storage.ReaderBatchWriter)) *ScheduledTransactions_BatchIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + var arg4 storage.ReaderBatchWriter + if args[4] != nil { + arg4 = args[4].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + ) + }) + return _c +} + +func (_c *ScheduledTransactions_BatchIndex_Call) Return(err error) *ScheduledTransactions_BatchIndex_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactions_BatchIndex_Call) RunAndReturn(run func(lctx lockctx.Proof, blockID flow.Identifier, txID flow.Identifier, scheduledTxID uint64, batch storage.ReaderBatchWriter) error) *ScheduledTransactions_BatchIndex_Call { + _c.Call.Return(run) + return _c +} + +// BlockIDByTransactionID provides a mock function for the type ScheduledTransactions +func (_mock *ScheduledTransactions) BlockIDByTransactionID(txID flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(txID) if len(ret) == 0 { panic("no return value specified for BlockIDByTransactionID") @@ -44,29 +123,61 @@ func (_m *ScheduledTransactions) BlockIDByTransactionID(txID flow.Identifier) (f var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { - return rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(txID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { - r0 = rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(txID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionIDByID provides a mock function with given fields: scheduledTxID -func (_m *ScheduledTransactions) TransactionIDByID(scheduledTxID uint64) (flow.Identifier, error) { - ret := _m.Called(scheduledTxID) +// ScheduledTransactions_BlockIDByTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockIDByTransactionID' +type ScheduledTransactions_BlockIDByTransactionID_Call struct { + *mock.Call +} + +// BlockIDByTransactionID is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *ScheduledTransactions_Expecter) BlockIDByTransactionID(txID interface{}) *ScheduledTransactions_BlockIDByTransactionID_Call { + return &ScheduledTransactions_BlockIDByTransactionID_Call{Call: _e.mock.On("BlockIDByTransactionID", txID)} +} + +func (_c *ScheduledTransactions_BlockIDByTransactionID_Call) Run(run func(txID flow.Identifier)) *ScheduledTransactions_BlockIDByTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactions_BlockIDByTransactionID_Call) Return(identifier flow.Identifier, err error) *ScheduledTransactions_BlockIDByTransactionID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ScheduledTransactions_BlockIDByTransactionID_Call) RunAndReturn(run func(txID flow.Identifier) (flow.Identifier, error)) *ScheduledTransactions_BlockIDByTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// TransactionIDByID provides a mock function for the type ScheduledTransactions +func (_mock *ScheduledTransactions) TransactionIDByID(scheduledTxID uint64) (flow.Identifier, error) { + ret := _mock.Called(scheduledTxID) if len(ret) == 0 { panic("no return value specified for TransactionIDByID") @@ -74,36 +185,54 @@ func (_m *ScheduledTransactions) TransactionIDByID(scheduledTxID uint64) (flow.I var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { - return rf(scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { + return returnFunc(scheduledTxID) } - if rf, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { - r0 = rf(scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { + r0 = returnFunc(scheduledTxID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(scheduledTxID) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(scheduledTxID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewScheduledTransactions creates a new instance of ScheduledTransactions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewScheduledTransactions(t interface { - mock.TestingT - Cleanup(func()) -}) *ScheduledTransactions { - mock := &ScheduledTransactions{} - mock.Mock.Test(t) +// ScheduledTransactions_TransactionIDByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionIDByID' +type ScheduledTransactions_TransactionIDByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TransactionIDByID is a helper method to define mock.On call +// - scheduledTxID uint64 +func (_e *ScheduledTransactions_Expecter) TransactionIDByID(scheduledTxID interface{}) *ScheduledTransactions_TransactionIDByID_Call { + return &ScheduledTransactions_TransactionIDByID_Call{Call: _e.mock.On("TransactionIDByID", scheduledTxID)} +} - return mock +func (_c *ScheduledTransactions_TransactionIDByID_Call) Run(run func(scheduledTxID uint64)) *ScheduledTransactions_TransactionIDByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactions_TransactionIDByID_Call) Return(identifier flow.Identifier, err error) *ScheduledTransactions_TransactionIDByID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ScheduledTransactions_TransactionIDByID_Call) RunAndReturn(run func(scheduledTxID uint64) (flow.Identifier, error)) *ScheduledTransactions_TransactionIDByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/scheduled_transactions_index.go b/storage/mock/scheduled_transactions_index.go new file mode 100644 index 00000000000..7a41be8ed9d --- /dev/null +++ b/storage/mock/scheduled_transactions_index.go @@ -0,0 +1,606 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewScheduledTransactionsIndex creates a new instance of ScheduledTransactionsIndex. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScheduledTransactionsIndex(t interface { + mock.TestingT + Cleanup(func()) +}) *ScheduledTransactionsIndex { + mock := &ScheduledTransactionsIndex{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ScheduledTransactionsIndex is an autogenerated mock type for the ScheduledTransactionsIndex type +type ScheduledTransactionsIndex struct { + mock.Mock +} + +type ScheduledTransactionsIndex_Expecter struct { + mock *mock.Mock +} + +func (_m *ScheduledTransactionsIndex) EXPECT() *ScheduledTransactionsIndex_Expecter { + return &ScheduledTransactionsIndex_Expecter{mock: &_m.Mock} +} + +// All provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) All(cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error) { + ret := _mock.Called(cursor) + + if len(ret) == 0 { + panic("no return value specified for All") + } + + var r0 storage.ScheduledTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(*access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)); ok { + return returnFunc(cursor) + } + if returnFunc, ok := ret.Get(0).(func(*access.ScheduledTransactionCursor) storage.ScheduledTransactionIterator); ok { + r0 = returnFunc(cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ScheduledTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(*access.ScheduledTransactionCursor) error); ok { + r1 = returnFunc(cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndex_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ScheduledTransactionsIndex_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +// - cursor *access.ScheduledTransactionCursor +func (_e *ScheduledTransactionsIndex_Expecter) All(cursor interface{}) *ScheduledTransactionsIndex_All_Call { + return &ScheduledTransactionsIndex_All_Call{Call: _e.mock.On("All", cursor)} +} + +func (_c *ScheduledTransactionsIndex_All_Call) Run(run func(cursor *access.ScheduledTransactionCursor)) *ScheduledTransactionsIndex_All_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.ScheduledTransactionCursor + if args[0] != nil { + arg0 = args[0].(*access.ScheduledTransactionCursor) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_All_Call) Return(v storage.ScheduledTransactionIterator, err error) *ScheduledTransactionsIndex_All_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndex_All_Call) RunAndReturn(run func(cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)) *ScheduledTransactionsIndex_All_Call { + _c.Call.Return(run) + return _c +} + +// ByAddress provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) ByAddress(account flow.Address, cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.ScheduledTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ScheduledTransactionCursor) storage.ScheduledTransactionIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ScheduledTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.ScheduledTransactionCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndex_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type ScheduledTransactionsIndex_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.ScheduledTransactionCursor +func (_e *ScheduledTransactionsIndex_Expecter) ByAddress(account interface{}, cursor interface{}) *ScheduledTransactionsIndex_ByAddress_Call { + return &ScheduledTransactionsIndex_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *ScheduledTransactionsIndex_ByAddress_Call) Run(run func(account flow.Address, cursor *access.ScheduledTransactionCursor)) *ScheduledTransactionsIndex_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.ScheduledTransactionCursor + if args[1] != nil { + arg1 = args[1].(*access.ScheduledTransactionCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_ByAddress_Call) Return(v storage.ScheduledTransactionIterator, err error) *ScheduledTransactionsIndex_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndex_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)) *ScheduledTransactionsIndex_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) ByID(id uint64) (access.ScheduledTransaction, error) { + ret := _mock.Called(id) + + if len(ret) == 0 { + panic("no return value specified for ByID") + } + + var r0 access.ScheduledTransaction + var r1 error + if returnFunc, ok := ret.Get(0).(func(uint64) (access.ScheduledTransaction, error)); ok { + return returnFunc(id) + } + if returnFunc, ok := ret.Get(0).(func(uint64) access.ScheduledTransaction); ok { + r0 = returnFunc(id) + } else { + r0 = ret.Get(0).(access.ScheduledTransaction) + } + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(id) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndex_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ScheduledTransactionsIndex_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - id uint64 +func (_e *ScheduledTransactionsIndex_Expecter) ByID(id interface{}) *ScheduledTransactionsIndex_ByID_Call { + return &ScheduledTransactionsIndex_ByID_Call{Call: _e.mock.On("ByID", id)} +} + +func (_c *ScheduledTransactionsIndex_ByID_Call) Run(run func(id uint64)) *ScheduledTransactionsIndex_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_ByID_Call) Return(scheduledTransaction access.ScheduledTransaction, err error) *ScheduledTransactionsIndex_ByID_Call { + _c.Call.Return(scheduledTransaction, err) + return _c +} + +func (_c *ScheduledTransactionsIndex_ByID_Call) RunAndReturn(run func(id uint64) (access.ScheduledTransaction, error)) *ScheduledTransactionsIndex_ByID_Call { + _c.Call.Return(run) + return _c +} + +// Cancelled provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) Cancelled(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Cancelled") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, uint64, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndex_Cancelled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Cancelled' +type ScheduledTransactionsIndex_Cancelled_Call struct { + *mock.Call +} + +// Cancelled is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - feesReturned uint64 +// - feesDeducted uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndex_Expecter) Cancelled(lctx interface{}, rw interface{}, scheduledTxID interface{}, feesReturned interface{}, feesDeducted interface{}, transactionID interface{}) *ScheduledTransactionsIndex_Cancelled_Call { + return &ScheduledTransactionsIndex_Cancelled_Call{Call: _e.mock.On("Cancelled", lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID)} +} + +func (_c *ScheduledTransactionsIndex_Cancelled_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndex_Cancelled_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + var arg4 uint64 + if args[4] != nil { + arg4 = args[4].(uint64) + } + var arg5 flow.Identifier + if args[5] != nil { + arg5 = args[5].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_Cancelled_Call) Return(err error) *ScheduledTransactionsIndex_Cancelled_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndex_Cancelled_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndex_Cancelled_Call { + _c.Call.Return(run) + return _c +} + +// Executed provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) Executed(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Executed") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndex_Executed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Executed' +type ScheduledTransactionsIndex_Executed_Call struct { + *mock.Call +} + +// Executed is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndex_Expecter) Executed(lctx interface{}, rw interface{}, scheduledTxID interface{}, transactionID interface{}) *ScheduledTransactionsIndex_Executed_Call { + return &ScheduledTransactionsIndex_Executed_Call{Call: _e.mock.On("Executed", lctx, rw, scheduledTxID, transactionID)} +} + +func (_c *ScheduledTransactionsIndex_Executed_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndex_Executed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_Executed_Call) Return(err error) *ScheduledTransactionsIndex_Executed_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndex_Executed_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndex_Executed_Call { + _c.Call.Return(run) + return _c +} + +// Failed provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) Failed(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Failed") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndex_Failed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Failed' +type ScheduledTransactionsIndex_Failed_Call struct { + *mock.Call +} + +// Failed is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndex_Expecter) Failed(lctx interface{}, rw interface{}, scheduledTxID interface{}, transactionID interface{}) *ScheduledTransactionsIndex_Failed_Call { + return &ScheduledTransactionsIndex_Failed_Call{Call: _e.mock.On("Failed", lctx, rw, scheduledTxID, transactionID)} +} + +func (_c *ScheduledTransactionsIndex_Failed_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndex_Failed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_Failed_Call) Return(err error) *ScheduledTransactionsIndex_Failed_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndex_Failed_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndex_Failed_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ScheduledTransactionsIndex_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type ScheduledTransactionsIndex_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *ScheduledTransactionsIndex_Expecter) FirstIndexedHeight() *ScheduledTransactionsIndex_FirstIndexedHeight_Call { + return &ScheduledTransactionsIndex_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *ScheduledTransactionsIndex_FirstIndexedHeight_Call) Run(run func()) *ScheduledTransactionsIndex_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_FirstIndexedHeight_Call) Return(v uint64) *ScheduledTransactionsIndex_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ScheduledTransactionsIndex_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *ScheduledTransactionsIndex_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ScheduledTransactionsIndex_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type ScheduledTransactionsIndex_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *ScheduledTransactionsIndex_Expecter) LatestIndexedHeight() *ScheduledTransactionsIndex_LatestIndexedHeight_Call { + return &ScheduledTransactionsIndex_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *ScheduledTransactionsIndex_LatestIndexedHeight_Call) Run(run func()) *ScheduledTransactionsIndex_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_LatestIndexedHeight_Call) Return(v uint64) *ScheduledTransactionsIndex_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ScheduledTransactionsIndex_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *ScheduledTransactionsIndex_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type ScheduledTransactionsIndex +func (_mock *ScheduledTransactionsIndex) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction) error { + ret := _mock.Called(lctx, rw, blockHeight, scheduledTxs) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.ScheduledTransaction) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, scheduledTxs) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndex_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ScheduledTransactionsIndex_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - scheduledTxs []access.ScheduledTransaction +func (_e *ScheduledTransactionsIndex_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, scheduledTxs interface{}) *ScheduledTransactionsIndex_Store_Call { + return &ScheduledTransactionsIndex_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, scheduledTxs)} +} + +func (_c *ScheduledTransactionsIndex_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction)) *ScheduledTransactionsIndex_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.ScheduledTransaction + if args[3] != nil { + arg3 = args[3].([]access.ScheduledTransaction) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndex_Store_Call) Return(err error) *ScheduledTransactionsIndex_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndex_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction) error) *ScheduledTransactionsIndex_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/scheduled_transactions_index_bootstrapper.go b/storage/mock/scheduled_transactions_index_bootstrapper.go new file mode 100644 index 00000000000..ab2766569a0 --- /dev/null +++ b/storage/mock/scheduled_transactions_index_bootstrapper.go @@ -0,0 +1,677 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewScheduledTransactionsIndexBootstrapper creates a new instance of ScheduledTransactionsIndexBootstrapper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScheduledTransactionsIndexBootstrapper(t interface { + mock.TestingT + Cleanup(func()) +}) *ScheduledTransactionsIndexBootstrapper { + mock := &ScheduledTransactionsIndexBootstrapper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ScheduledTransactionsIndexBootstrapper is an autogenerated mock type for the ScheduledTransactionsIndexBootstrapper type +type ScheduledTransactionsIndexBootstrapper struct { + mock.Mock +} + +type ScheduledTransactionsIndexBootstrapper_Expecter struct { + mock *mock.Mock +} + +func (_m *ScheduledTransactionsIndexBootstrapper) EXPECT() *ScheduledTransactionsIndexBootstrapper_Expecter { + return &ScheduledTransactionsIndexBootstrapper_Expecter{mock: &_m.Mock} +} + +// All provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) All(cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error) { + ret := _mock.Called(cursor) + + if len(ret) == 0 { + panic("no return value specified for All") + } + + var r0 storage.ScheduledTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(*access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)); ok { + return returnFunc(cursor) + } + if returnFunc, ok := ret.Get(0).(func(*access.ScheduledTransactionCursor) storage.ScheduledTransactionIterator); ok { + r0 = returnFunc(cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ScheduledTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(*access.ScheduledTransactionCursor) error); ok { + r1 = returnFunc(cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexBootstrapper_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ScheduledTransactionsIndexBootstrapper_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +// - cursor *access.ScheduledTransactionCursor +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) All(cursor interface{}) *ScheduledTransactionsIndexBootstrapper_All_Call { + return &ScheduledTransactionsIndexBootstrapper_All_Call{Call: _e.mock.On("All", cursor)} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_All_Call) Run(run func(cursor *access.ScheduledTransactionCursor)) *ScheduledTransactionsIndexBootstrapper_All_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.ScheduledTransactionCursor + if args[0] != nil { + arg0 = args[0].(*access.ScheduledTransactionCursor) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_All_Call) Return(v storage.ScheduledTransactionIterator, err error) *ScheduledTransactionsIndexBootstrapper_All_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_All_Call) RunAndReturn(run func(cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)) *ScheduledTransactionsIndexBootstrapper_All_Call { + _c.Call.Return(run) + return _c +} + +// ByAddress provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) ByAddress(account flow.Address, cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.ScheduledTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ScheduledTransactionCursor) storage.ScheduledTransactionIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ScheduledTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.ScheduledTransactionCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexBootstrapper_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type ScheduledTransactionsIndexBootstrapper_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.ScheduledTransactionCursor +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) ByAddress(account interface{}, cursor interface{}) *ScheduledTransactionsIndexBootstrapper_ByAddress_Call { + return &ScheduledTransactionsIndexBootstrapper_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_ByAddress_Call) Run(run func(account flow.Address, cursor *access.ScheduledTransactionCursor)) *ScheduledTransactionsIndexBootstrapper_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.ScheduledTransactionCursor + if args[1] != nil { + arg1 = args[1].(*access.ScheduledTransactionCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_ByAddress_Call) Return(v storage.ScheduledTransactionIterator, err error) *ScheduledTransactionsIndexBootstrapper_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)) *ScheduledTransactionsIndexBootstrapper_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) ByID(id uint64) (access.ScheduledTransaction, error) { + ret := _mock.Called(id) + + if len(ret) == 0 { + panic("no return value specified for ByID") + } + + var r0 access.ScheduledTransaction + var r1 error + if returnFunc, ok := ret.Get(0).(func(uint64) (access.ScheduledTransaction, error)); ok { + return returnFunc(id) + } + if returnFunc, ok := ret.Get(0).(func(uint64) access.ScheduledTransaction); ok { + r0 = returnFunc(id) + } else { + r0 = ret.Get(0).(access.ScheduledTransaction) + } + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(id) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexBootstrapper_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ScheduledTransactionsIndexBootstrapper_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - id uint64 +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) ByID(id interface{}) *ScheduledTransactionsIndexBootstrapper_ByID_Call { + return &ScheduledTransactionsIndexBootstrapper_ByID_Call{Call: _e.mock.On("ByID", id)} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_ByID_Call) Run(run func(id uint64)) *ScheduledTransactionsIndexBootstrapper_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_ByID_Call) Return(scheduledTransaction access.ScheduledTransaction, err error) *ScheduledTransactionsIndexBootstrapper_ByID_Call { + _c.Call.Return(scheduledTransaction, err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_ByID_Call) RunAndReturn(run func(id uint64) (access.ScheduledTransaction, error)) *ScheduledTransactionsIndexBootstrapper_ByID_Call { + _c.Call.Return(run) + return _c +} + +// Cancelled provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) Cancelled(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Cancelled") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, uint64, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexBootstrapper_Cancelled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Cancelled' +type ScheduledTransactionsIndexBootstrapper_Cancelled_Call struct { + *mock.Call +} + +// Cancelled is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - feesReturned uint64 +// - feesDeducted uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) Cancelled(lctx interface{}, rw interface{}, scheduledTxID interface{}, feesReturned interface{}, feesDeducted interface{}, transactionID interface{}) *ScheduledTransactionsIndexBootstrapper_Cancelled_Call { + return &ScheduledTransactionsIndexBootstrapper_Cancelled_Call{Call: _e.mock.On("Cancelled", lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID)} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Cancelled_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndexBootstrapper_Cancelled_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + var arg4 uint64 + if args[4] != nil { + arg4 = args[4].(uint64) + } + var arg5 flow.Identifier + if args[5] != nil { + arg5 = args[5].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Cancelled_Call) Return(err error) *ScheduledTransactionsIndexBootstrapper_Cancelled_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Cancelled_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndexBootstrapper_Cancelled_Call { + _c.Call.Return(run) + return _c +} + +// Executed provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) Executed(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Executed") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexBootstrapper_Executed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Executed' +type ScheduledTransactionsIndexBootstrapper_Executed_Call struct { + *mock.Call +} + +// Executed is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) Executed(lctx interface{}, rw interface{}, scheduledTxID interface{}, transactionID interface{}) *ScheduledTransactionsIndexBootstrapper_Executed_Call { + return &ScheduledTransactionsIndexBootstrapper_Executed_Call{Call: _e.mock.On("Executed", lctx, rw, scheduledTxID, transactionID)} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Executed_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndexBootstrapper_Executed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Executed_Call) Return(err error) *ScheduledTransactionsIndexBootstrapper_Executed_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Executed_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndexBootstrapper_Executed_Call { + _c.Call.Return(run) + return _c +} + +// Failed provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) Failed(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Failed") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexBootstrapper_Failed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Failed' +type ScheduledTransactionsIndexBootstrapper_Failed_Call struct { + *mock.Call +} + +// Failed is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) Failed(lctx interface{}, rw interface{}, scheduledTxID interface{}, transactionID interface{}) *ScheduledTransactionsIndexBootstrapper_Failed_Call { + return &ScheduledTransactionsIndexBootstrapper_Failed_Call{Call: _e.mock.On("Failed", lctx, rw, scheduledTxID, transactionID)} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Failed_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndexBootstrapper_Failed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Failed_Call) Return(err error) *ScheduledTransactionsIndexBootstrapper_Failed_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Failed_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndexBootstrapper_Failed_Call { + _c.Call.Return(run) + return _c +} + +// FirstIndexedHeight provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) FirstIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) FirstIndexedHeight() *ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call { + return &ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call) Run(run func()) *ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call) Return(v uint64, err error) *ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *ScheduledTransactionsIndexBootstrapper_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) LatestIndexedHeight() (uint64, error) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + var r1 error + if returnFunc, ok := ret.Get(0).(func() (uint64, error)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() error); ok { + r1 = returnFunc() + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) LatestIndexedHeight() *ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call { + return &ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call) Run(run func()) *ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call) Return(v uint64, err error) *ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call) RunAndReturn(run func() (uint64, error)) *ScheduledTransactionsIndexBootstrapper_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction) error { + ret := _mock.Called(lctx, rw, blockHeight, scheduledTxs) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.ScheduledTransaction) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, scheduledTxs) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexBootstrapper_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ScheduledTransactionsIndexBootstrapper_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - scheduledTxs []access.ScheduledTransaction +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, scheduledTxs interface{}) *ScheduledTransactionsIndexBootstrapper_Store_Call { + return &ScheduledTransactionsIndexBootstrapper_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, scheduledTxs)} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction)) *ScheduledTransactionsIndexBootstrapper_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.ScheduledTransaction + if args[3] != nil { + arg3 = args[3].([]access.ScheduledTransaction) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Store_Call) Return(err error) *ScheduledTransactionsIndexBootstrapper_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction) error) *ScheduledTransactionsIndexBootstrapper_Store_Call { + _c.Call.Return(run) + return _c +} + +// UninitializedFirstHeight provides a mock function for the type ScheduledTransactionsIndexBootstrapper +func (_mock *ScheduledTransactionsIndexBootstrapper) UninitializedFirstHeight() (uint64, bool) { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for UninitializedFirstHeight") + } + + var r0 uint64 + var r1 bool + if returnFunc, ok := ret.Get(0).(func() (uint64, bool)); ok { + return returnFunc() + } + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + if returnFunc, ok := ret.Get(1).(func() bool); ok { + r1 = returnFunc() + } else { + r1 = ret.Get(1).(bool) + } + return r0, r1 +} + +// ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UninitializedFirstHeight' +type ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call struct { + *mock.Call +} + +// UninitializedFirstHeight is a helper method to define mock.On call +func (_e *ScheduledTransactionsIndexBootstrapper_Expecter) UninitializedFirstHeight() *ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call { + return &ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call{Call: _e.mock.On("UninitializedFirstHeight")} +} + +func (_c *ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call) Run(run func()) *ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call) Return(v uint64, b bool) *ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(v, b) + return _c +} + +func (_c *ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call) RunAndReturn(run func() (uint64, bool)) *ScheduledTransactionsIndexBootstrapper_UninitializedFirstHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/scheduled_transactions_index_range_reader.go b/storage/mock/scheduled_transactions_index_range_reader.go new file mode 100644 index 00000000000..537354fe8fb --- /dev/null +++ b/storage/mock/scheduled_transactions_index_range_reader.go @@ -0,0 +1,124 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewScheduledTransactionsIndexRangeReader creates a new instance of ScheduledTransactionsIndexRangeReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScheduledTransactionsIndexRangeReader(t interface { + mock.TestingT + Cleanup(func()) +}) *ScheduledTransactionsIndexRangeReader { + mock := &ScheduledTransactionsIndexRangeReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ScheduledTransactionsIndexRangeReader is an autogenerated mock type for the ScheduledTransactionsIndexRangeReader type +type ScheduledTransactionsIndexRangeReader struct { + mock.Mock +} + +type ScheduledTransactionsIndexRangeReader_Expecter struct { + mock *mock.Mock +} + +func (_m *ScheduledTransactionsIndexRangeReader) EXPECT() *ScheduledTransactionsIndexRangeReader_Expecter { + return &ScheduledTransactionsIndexRangeReader_Expecter{mock: &_m.Mock} +} + +// FirstIndexedHeight provides a mock function for the type ScheduledTransactionsIndexRangeReader +func (_mock *ScheduledTransactionsIndexRangeReader) FirstIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for FirstIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FirstIndexedHeight' +type ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call struct { + *mock.Call +} + +// FirstIndexedHeight is a helper method to define mock.On call +func (_e *ScheduledTransactionsIndexRangeReader_Expecter) FirstIndexedHeight() *ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call { + return &ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call{Call: _e.mock.On("FirstIndexedHeight")} +} + +func (_c *ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call) Run(run func()) *ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call) Return(v uint64) *ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call) RunAndReturn(run func() uint64) *ScheduledTransactionsIndexRangeReader_FirstIndexedHeight_Call { + _c.Call.Return(run) + return _c +} + +// LatestIndexedHeight provides a mock function for the type ScheduledTransactionsIndexRangeReader +func (_mock *ScheduledTransactionsIndexRangeReader) LatestIndexedHeight() uint64 { + ret := _mock.Called() + + if len(ret) == 0 { + panic("no return value specified for LatestIndexedHeight") + } + + var r0 uint64 + if returnFunc, ok := ret.Get(0).(func() uint64); ok { + r0 = returnFunc() + } else { + r0 = ret.Get(0).(uint64) + } + return r0 +} + +// ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestIndexedHeight' +type ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call struct { + *mock.Call +} + +// LatestIndexedHeight is a helper method to define mock.On call +func (_e *ScheduledTransactionsIndexRangeReader_Expecter) LatestIndexedHeight() *ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call { + return &ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call{Call: _e.mock.On("LatestIndexedHeight")} +} + +func (_c *ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call) Run(run func()) *ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call) Return(v uint64) *ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(v) + return _c +} + +func (_c *ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call) RunAndReturn(run func() uint64) *ScheduledTransactionsIndexRangeReader_LatestIndexedHeight_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/scheduled_transactions_index_reader.go b/storage/mock/scheduled_transactions_index_reader.go new file mode 100644 index 00000000000..a204d1fb572 --- /dev/null +++ b/storage/mock/scheduled_transactions_index_reader.go @@ -0,0 +1,229 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewScheduledTransactionsIndexReader creates a new instance of ScheduledTransactionsIndexReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScheduledTransactionsIndexReader(t interface { + mock.TestingT + Cleanup(func()) +}) *ScheduledTransactionsIndexReader { + mock := &ScheduledTransactionsIndexReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ScheduledTransactionsIndexReader is an autogenerated mock type for the ScheduledTransactionsIndexReader type +type ScheduledTransactionsIndexReader struct { + mock.Mock +} + +type ScheduledTransactionsIndexReader_Expecter struct { + mock *mock.Mock +} + +func (_m *ScheduledTransactionsIndexReader) EXPECT() *ScheduledTransactionsIndexReader_Expecter { + return &ScheduledTransactionsIndexReader_Expecter{mock: &_m.Mock} +} + +// All provides a mock function for the type ScheduledTransactionsIndexReader +func (_mock *ScheduledTransactionsIndexReader) All(cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error) { + ret := _mock.Called(cursor) + + if len(ret) == 0 { + panic("no return value specified for All") + } + + var r0 storage.ScheduledTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(*access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)); ok { + return returnFunc(cursor) + } + if returnFunc, ok := ret.Get(0).(func(*access.ScheduledTransactionCursor) storage.ScheduledTransactionIterator); ok { + r0 = returnFunc(cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ScheduledTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(*access.ScheduledTransactionCursor) error); ok { + r1 = returnFunc(cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexReader_All_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'All' +type ScheduledTransactionsIndexReader_All_Call struct { + *mock.Call +} + +// All is a helper method to define mock.On call +// - cursor *access.ScheduledTransactionCursor +func (_e *ScheduledTransactionsIndexReader_Expecter) All(cursor interface{}) *ScheduledTransactionsIndexReader_All_Call { + return &ScheduledTransactionsIndexReader_All_Call{Call: _e.mock.On("All", cursor)} +} + +func (_c *ScheduledTransactionsIndexReader_All_Call) Run(run func(cursor *access.ScheduledTransactionCursor)) *ScheduledTransactionsIndexReader_All_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *access.ScheduledTransactionCursor + if args[0] != nil { + arg0 = args[0].(*access.ScheduledTransactionCursor) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexReader_All_Call) Return(v storage.ScheduledTransactionIterator, err error) *ScheduledTransactionsIndexReader_All_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndexReader_All_Call) RunAndReturn(run func(cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)) *ScheduledTransactionsIndexReader_All_Call { + _c.Call.Return(run) + return _c +} + +// ByAddress provides a mock function for the type ScheduledTransactionsIndexReader +func (_mock *ScheduledTransactionsIndexReader) ByAddress(account flow.Address, cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error) { + ret := _mock.Called(account, cursor) + + if len(ret) == 0 { + panic("no return value specified for ByAddress") + } + + var r0 storage.ScheduledTransactionIterator + var r1 error + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)); ok { + return returnFunc(account, cursor) + } + if returnFunc, ok := ret.Get(0).(func(flow.Address, *access.ScheduledTransactionCursor) storage.ScheduledTransactionIterator); ok { + r0 = returnFunc(account, cursor) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(storage.ScheduledTransactionIterator) + } + } + if returnFunc, ok := ret.Get(1).(func(flow.Address, *access.ScheduledTransactionCursor) error); ok { + r1 = returnFunc(account, cursor) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexReader_ByAddress_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByAddress' +type ScheduledTransactionsIndexReader_ByAddress_Call struct { + *mock.Call +} + +// ByAddress is a helper method to define mock.On call +// - account flow.Address +// - cursor *access.ScheduledTransactionCursor +func (_e *ScheduledTransactionsIndexReader_Expecter) ByAddress(account interface{}, cursor interface{}) *ScheduledTransactionsIndexReader_ByAddress_Call { + return &ScheduledTransactionsIndexReader_ByAddress_Call{Call: _e.mock.On("ByAddress", account, cursor)} +} + +func (_c *ScheduledTransactionsIndexReader_ByAddress_Call) Run(run func(account flow.Address, cursor *access.ScheduledTransactionCursor)) *ScheduledTransactionsIndexReader_ByAddress_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Address + if args[0] != nil { + arg0 = args[0].(flow.Address) + } + var arg1 *access.ScheduledTransactionCursor + if args[1] != nil { + arg1 = args[1].(*access.ScheduledTransactionCursor) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexReader_ByAddress_Call) Return(v storage.ScheduledTransactionIterator, err error) *ScheduledTransactionsIndexReader_ByAddress_Call { + _c.Call.Return(v, err) + return _c +} + +func (_c *ScheduledTransactionsIndexReader_ByAddress_Call) RunAndReturn(run func(account flow.Address, cursor *access.ScheduledTransactionCursor) (storage.ScheduledTransactionIterator, error)) *ScheduledTransactionsIndexReader_ByAddress_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type ScheduledTransactionsIndexReader +func (_mock *ScheduledTransactionsIndexReader) ByID(id uint64) (access.ScheduledTransaction, error) { + ret := _mock.Called(id) + + if len(ret) == 0 { + panic("no return value specified for ByID") + } + + var r0 access.ScheduledTransaction + var r1 error + if returnFunc, ok := ret.Get(0).(func(uint64) (access.ScheduledTransaction, error)); ok { + return returnFunc(id) + } + if returnFunc, ok := ret.Get(0).(func(uint64) access.ScheduledTransaction); ok { + r0 = returnFunc(id) + } else { + r0 = ret.Get(0).(access.ScheduledTransaction) + } + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(id) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// ScheduledTransactionsIndexReader_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type ScheduledTransactionsIndexReader_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - id uint64 +func (_e *ScheduledTransactionsIndexReader_Expecter) ByID(id interface{}) *ScheduledTransactionsIndexReader_ByID_Call { + return &ScheduledTransactionsIndexReader_ByID_Call{Call: _e.mock.On("ByID", id)} +} + +func (_c *ScheduledTransactionsIndexReader_ByID_Call) Run(run func(id uint64)) *ScheduledTransactionsIndexReader_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexReader_ByID_Call) Return(scheduledTransaction access.ScheduledTransaction, err error) *ScheduledTransactionsIndexReader_ByID_Call { + _c.Call.Return(scheduledTransaction, err) + return _c +} + +func (_c *ScheduledTransactionsIndexReader_ByID_Call) RunAndReturn(run func(id uint64) (access.ScheduledTransaction, error)) *ScheduledTransactionsIndexReader_ByID_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/scheduled_transactions_index_writer.go b/storage/mock/scheduled_transactions_index_writer.go new file mode 100644 index 00000000000..d734543d200 --- /dev/null +++ b/storage/mock/scheduled_transactions_index_writer.go @@ -0,0 +1,328 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mock + +import ( + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" + mock "github.com/stretchr/testify/mock" +) + +// NewScheduledTransactionsIndexWriter creates a new instance of ScheduledTransactionsIndexWriter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScheduledTransactionsIndexWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *ScheduledTransactionsIndexWriter { + mock := &ScheduledTransactionsIndexWriter{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + +// ScheduledTransactionsIndexWriter is an autogenerated mock type for the ScheduledTransactionsIndexWriter type +type ScheduledTransactionsIndexWriter struct { + mock.Mock +} + +type ScheduledTransactionsIndexWriter_Expecter struct { + mock *mock.Mock +} + +func (_m *ScheduledTransactionsIndexWriter) EXPECT() *ScheduledTransactionsIndexWriter_Expecter { + return &ScheduledTransactionsIndexWriter_Expecter{mock: &_m.Mock} +} + +// Cancelled provides a mock function for the type ScheduledTransactionsIndexWriter +func (_mock *ScheduledTransactionsIndexWriter) Cancelled(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Cancelled") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, uint64, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexWriter_Cancelled_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Cancelled' +type ScheduledTransactionsIndexWriter_Cancelled_Call struct { + *mock.Call +} + +// Cancelled is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - feesReturned uint64 +// - feesDeducted uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndexWriter_Expecter) Cancelled(lctx interface{}, rw interface{}, scheduledTxID interface{}, feesReturned interface{}, feesDeducted interface{}, transactionID interface{}) *ScheduledTransactionsIndexWriter_Cancelled_Call { + return &ScheduledTransactionsIndexWriter_Cancelled_Call{Call: _e.mock.On("Cancelled", lctx, rw, scheduledTxID, feesReturned, feesDeducted, transactionID)} +} + +func (_c *ScheduledTransactionsIndexWriter_Cancelled_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndexWriter_Cancelled_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 uint64 + if args[3] != nil { + arg3 = args[3].(uint64) + } + var arg4 uint64 + if args[4] != nil { + arg4 = args[4].(uint64) + } + var arg5 flow.Identifier + if args[5] != nil { + arg5 = args[5].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Cancelled_Call) Return(err error) *ScheduledTransactionsIndexWriter_Cancelled_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Cancelled_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, feesReturned uint64, feesDeducted uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndexWriter_Cancelled_Call { + _c.Call.Return(run) + return _c +} + +// Executed provides a mock function for the type ScheduledTransactionsIndexWriter +func (_mock *ScheduledTransactionsIndexWriter) Executed(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Executed") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexWriter_Executed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Executed' +type ScheduledTransactionsIndexWriter_Executed_Call struct { + *mock.Call +} + +// Executed is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndexWriter_Expecter) Executed(lctx interface{}, rw interface{}, scheduledTxID interface{}, transactionID interface{}) *ScheduledTransactionsIndexWriter_Executed_Call { + return &ScheduledTransactionsIndexWriter_Executed_Call{Call: _e.mock.On("Executed", lctx, rw, scheduledTxID, transactionID)} +} + +func (_c *ScheduledTransactionsIndexWriter_Executed_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndexWriter_Executed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Executed_Call) Return(err error) *ScheduledTransactionsIndexWriter_Executed_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Executed_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndexWriter_Executed_Call { + _c.Call.Return(run) + return _c +} + +// Failed provides a mock function for the type ScheduledTransactionsIndexWriter +func (_mock *ScheduledTransactionsIndexWriter) Failed(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error { + ret := _mock.Called(lctx, rw, scheduledTxID, transactionID) + + if len(ret) == 0 { + panic("no return value specified for Failed") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, flow.Identifier) error); ok { + r0 = returnFunc(lctx, rw, scheduledTxID, transactionID) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexWriter_Failed_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Failed' +type ScheduledTransactionsIndexWriter_Failed_Call struct { + *mock.Call +} + +// Failed is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - scheduledTxID uint64 +// - transactionID flow.Identifier +func (_e *ScheduledTransactionsIndexWriter_Expecter) Failed(lctx interface{}, rw interface{}, scheduledTxID interface{}, transactionID interface{}) *ScheduledTransactionsIndexWriter_Failed_Call { + return &ScheduledTransactionsIndexWriter_Failed_Call{Call: _e.mock.On("Failed", lctx, rw, scheduledTxID, transactionID)} +} + +func (_c *ScheduledTransactionsIndexWriter_Failed_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier)) *ScheduledTransactionsIndexWriter_Failed_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 flow.Identifier + if args[3] != nil { + arg3 = args[3].(flow.Identifier) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Failed_Call) Return(err error) *ScheduledTransactionsIndexWriter_Failed_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Failed_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, scheduledTxID uint64, transactionID flow.Identifier) error) *ScheduledTransactionsIndexWriter_Failed_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type ScheduledTransactionsIndexWriter +func (_mock *ScheduledTransactionsIndexWriter) Store(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction) error { + ret := _mock.Called(lctx, rw, blockHeight, scheduledTxs) + + if len(ret) == 0 { + panic("no return value specified for Store") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, uint64, []access.ScheduledTransaction) error); ok { + r0 = returnFunc(lctx, rw, blockHeight, scheduledTxs) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// ScheduledTransactionsIndexWriter_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type ScheduledTransactionsIndexWriter_Store_Call struct { + *mock.Call +} + +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockHeight uint64 +// - scheduledTxs []access.ScheduledTransaction +func (_e *ScheduledTransactionsIndexWriter_Expecter) Store(lctx interface{}, rw interface{}, blockHeight interface{}, scheduledTxs interface{}) *ScheduledTransactionsIndexWriter_Store_Call { + return &ScheduledTransactionsIndexWriter_Store_Call{Call: _e.mock.On("Store", lctx, rw, blockHeight, scheduledTxs)} +} + +func (_c *ScheduledTransactionsIndexWriter_Store_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction)) *ScheduledTransactionsIndexWriter_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 uint64 + if args[2] != nil { + arg2 = args[2].(uint64) + } + var arg3 []access.ScheduledTransaction + if args[3] != nil { + arg3 = args[3].([]access.ScheduledTransaction) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Store_Call) Return(err error) *ScheduledTransactionsIndexWriter_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ScheduledTransactionsIndexWriter_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockHeight uint64, scheduledTxs []access.ScheduledTransaction) error) *ScheduledTransactionsIndexWriter_Store_Call { + _c.Call.Return(run) + return _c +} diff --git a/storage/mock/scheduled_transactions_reader.go b/storage/mock/scheduled_transactions_reader.go index 48caeb999eb..da4a59d12c0 100644 --- a/storage/mock/scheduled_transactions_reader.go +++ b/storage/mock/scheduled_transactions_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewScheduledTransactionsReader creates a new instance of ScheduledTransactionsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewScheduledTransactionsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *ScheduledTransactionsReader { + mock := &ScheduledTransactionsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ScheduledTransactionsReader is an autogenerated mock type for the ScheduledTransactionsReader type type ScheduledTransactionsReader struct { mock.Mock } -// BlockIDByTransactionID provides a mock function with given fields: txID -func (_m *ScheduledTransactionsReader) BlockIDByTransactionID(txID flow.Identifier) (flow.Identifier, error) { - ret := _m.Called(txID) +type ScheduledTransactionsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *ScheduledTransactionsReader) EXPECT() *ScheduledTransactionsReader_Expecter { + return &ScheduledTransactionsReader_Expecter{mock: &_m.Mock} +} + +// BlockIDByTransactionID provides a mock function for the type ScheduledTransactionsReader +func (_mock *ScheduledTransactionsReader) BlockIDByTransactionID(txID flow.Identifier) (flow.Identifier, error) { + ret := _mock.Called(txID) if len(ret) == 0 { panic("no return value specified for BlockIDByTransactionID") @@ -22,29 +46,61 @@ func (_m *ScheduledTransactionsReader) BlockIDByTransactionID(txID flow.Identifi var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { - return rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (flow.Identifier, error)); ok { + return returnFunc(txID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { - r0 = rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) flow.Identifier); ok { + r0 = returnFunc(txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(txID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// TransactionIDByID provides a mock function with given fields: scheduledTxID -func (_m *ScheduledTransactionsReader) TransactionIDByID(scheduledTxID uint64) (flow.Identifier, error) { - ret := _m.Called(scheduledTxID) +// ScheduledTransactionsReader_BlockIDByTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockIDByTransactionID' +type ScheduledTransactionsReader_BlockIDByTransactionID_Call struct { + *mock.Call +} + +// BlockIDByTransactionID is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *ScheduledTransactionsReader_Expecter) BlockIDByTransactionID(txID interface{}) *ScheduledTransactionsReader_BlockIDByTransactionID_Call { + return &ScheduledTransactionsReader_BlockIDByTransactionID_Call{Call: _e.mock.On("BlockIDByTransactionID", txID)} +} + +func (_c *ScheduledTransactionsReader_BlockIDByTransactionID_Call) Run(run func(txID flow.Identifier)) *ScheduledTransactionsReader_BlockIDByTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsReader_BlockIDByTransactionID_Call) Return(identifier flow.Identifier, err error) *ScheduledTransactionsReader_BlockIDByTransactionID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ScheduledTransactionsReader_BlockIDByTransactionID_Call) RunAndReturn(run func(txID flow.Identifier) (flow.Identifier, error)) *ScheduledTransactionsReader_BlockIDByTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// TransactionIDByID provides a mock function for the type ScheduledTransactionsReader +func (_mock *ScheduledTransactionsReader) TransactionIDByID(scheduledTxID uint64) (flow.Identifier, error) { + ret := _mock.Called(scheduledTxID) if len(ret) == 0 { panic("no return value specified for TransactionIDByID") @@ -52,36 +108,54 @@ func (_m *ScheduledTransactionsReader) TransactionIDByID(scheduledTxID uint64) ( var r0 flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { - return rf(scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(uint64) (flow.Identifier, error)); ok { + return returnFunc(scheduledTxID) } - if rf, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { - r0 = rf(scheduledTxID) + if returnFunc, ok := ret.Get(0).(func(uint64) flow.Identifier); ok { + r0 = returnFunc(scheduledTxID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(flow.Identifier) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(scheduledTxID) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(scheduledTxID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewScheduledTransactionsReader creates a new instance of ScheduledTransactionsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewScheduledTransactionsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *ScheduledTransactionsReader { - mock := &ScheduledTransactionsReader{} - mock.Mock.Test(t) +// ScheduledTransactionsReader_TransactionIDByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionIDByID' +type ScheduledTransactionsReader_TransactionIDByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// TransactionIDByID is a helper method to define mock.On call +// - scheduledTxID uint64 +func (_e *ScheduledTransactionsReader_Expecter) TransactionIDByID(scheduledTxID interface{}) *ScheduledTransactionsReader_TransactionIDByID_Call { + return &ScheduledTransactionsReader_TransactionIDByID_Call{Call: _e.mock.On("TransactionIDByID", scheduledTxID)} +} - return mock +func (_c *ScheduledTransactionsReader_TransactionIDByID_Call) Run(run func(scheduledTxID uint64)) *ScheduledTransactionsReader_TransactionIDByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ScheduledTransactionsReader_TransactionIDByID_Call) Return(identifier flow.Identifier, err error) *ScheduledTransactionsReader_TransactionIDByID_Call { + _c.Call.Return(identifier, err) + return _c +} + +func (_c *ScheduledTransactionsReader_TransactionIDByID_Call) RunAndReturn(run func(scheduledTxID uint64) (flow.Identifier, error)) *ScheduledTransactionsReader_TransactionIDByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/seals.go b/storage/mock/seals.go index 7968bb2996c..69218ea3e64 100644 --- a/storage/mock/seals.go +++ b/storage/mock/seals.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewSeals creates a new instance of Seals. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSeals(t interface { + mock.TestingT + Cleanup(func()) +}) *Seals { + mock := &Seals{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Seals is an autogenerated mock type for the Seals type type Seals struct { mock.Mock } -// ByID provides a mock function with given fields: sealID -func (_m *Seals) ByID(sealID flow.Identifier) (*flow.Seal, error) { - ret := _m.Called(sealID) +type Seals_Expecter struct { + mock *mock.Mock +} + +func (_m *Seals) EXPECT() *Seals_Expecter { + return &Seals_Expecter{mock: &_m.Mock} +} + +// ByID provides a mock function for the type Seals +func (_mock *Seals) ByID(sealID flow.Identifier) (*flow.Seal, error) { + ret := _mock.Called(sealID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -22,29 +46,61 @@ func (_m *Seals) ByID(sealID flow.Identifier) (*flow.Seal, error) { var r0 *flow.Seal var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Seal, error)); ok { - return rf(sealID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Seal, error)); ok { + return returnFunc(sealID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Seal); ok { - r0 = rf(sealID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Seal); ok { + r0 = returnFunc(sealID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Seal) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(sealID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(sealID) } else { r1 = ret.Error(1) } - return r0, r1 } -// FinalizedSealForBlock provides a mock function with given fields: blockID -func (_m *Seals) FinalizedSealForBlock(blockID flow.Identifier) (*flow.Seal, error) { - ret := _m.Called(blockID) +// Seals_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type Seals_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - sealID flow.Identifier +func (_e *Seals_Expecter) ByID(sealID interface{}) *Seals_ByID_Call { + return &Seals_ByID_Call{Call: _e.mock.On("ByID", sealID)} +} + +func (_c *Seals_ByID_Call) Run(run func(sealID flow.Identifier)) *Seals_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Seals_ByID_Call) Return(seal *flow.Seal, err error) *Seals_ByID_Call { + _c.Call.Return(seal, err) + return _c +} + +func (_c *Seals_ByID_Call) RunAndReturn(run func(sealID flow.Identifier) (*flow.Seal, error)) *Seals_ByID_Call { + _c.Call.Return(run) + return _c +} + +// FinalizedSealForBlock provides a mock function for the type Seals +func (_mock *Seals) FinalizedSealForBlock(blockID flow.Identifier) (*flow.Seal, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for FinalizedSealForBlock") @@ -52,29 +108,61 @@ func (_m *Seals) FinalizedSealForBlock(blockID flow.Identifier) (*flow.Seal, err var r0 *flow.Seal var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Seal, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Seal, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Seal); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Seal); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Seal) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// HighestInFork provides a mock function with given fields: blockID -func (_m *Seals) HighestInFork(blockID flow.Identifier) (*flow.Seal, error) { - ret := _m.Called(blockID) +// Seals_FinalizedSealForBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FinalizedSealForBlock' +type Seals_FinalizedSealForBlock_Call struct { + *mock.Call +} + +// FinalizedSealForBlock is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Seals_Expecter) FinalizedSealForBlock(blockID interface{}) *Seals_FinalizedSealForBlock_Call { + return &Seals_FinalizedSealForBlock_Call{Call: _e.mock.On("FinalizedSealForBlock", blockID)} +} + +func (_c *Seals_FinalizedSealForBlock_Call) Run(run func(blockID flow.Identifier)) *Seals_FinalizedSealForBlock_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Seals_FinalizedSealForBlock_Call) Return(seal *flow.Seal, err error) *Seals_FinalizedSealForBlock_Call { + _c.Call.Return(seal, err) + return _c +} + +func (_c *Seals_FinalizedSealForBlock_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.Seal, error)) *Seals_FinalizedSealForBlock_Call { + _c.Call.Return(run) + return _c +} + +// HighestInFork provides a mock function for the type Seals +func (_mock *Seals) HighestInFork(blockID flow.Identifier) (*flow.Seal, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for HighestInFork") @@ -82,54 +170,105 @@ func (_m *Seals) HighestInFork(blockID flow.Identifier) (*flow.Seal, error) { var r0 *flow.Seal var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.Seal, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.Seal, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.Seal); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.Seal); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.Seal) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Store provides a mock function with given fields: seal -func (_m *Seals) Store(seal *flow.Seal) error { - ret := _m.Called(seal) +// Seals_HighestInFork_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HighestInFork' +type Seals_HighestInFork_Call struct { + *mock.Call +} + +// HighestInFork is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *Seals_Expecter) HighestInFork(blockID interface{}) *Seals_HighestInFork_Call { + return &Seals_HighestInFork_Call{Call: _e.mock.On("HighestInFork", blockID)} +} + +func (_c *Seals_HighestInFork_Call) Run(run func(blockID flow.Identifier)) *Seals_HighestInFork_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Seals_HighestInFork_Call) Return(seal *flow.Seal, err error) *Seals_HighestInFork_Call { + _c.Call.Return(seal, err) + return _c +} + +func (_c *Seals_HighestInFork_Call) RunAndReturn(run func(blockID flow.Identifier) (*flow.Seal, error)) *Seals_HighestInFork_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type Seals +func (_mock *Seals) Store(seal *flow.Seal) error { + ret := _mock.Called(seal) if len(ret) == 0 { panic("no return value specified for Store") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.Seal) error); ok { - r0 = rf(seal) + if returnFunc, ok := ret.Get(0).(func(*flow.Seal) error); ok { + r0 = returnFunc(seal) } else { r0 = ret.Error(0) } - return r0 } -// NewSeals creates a new instance of Seals. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSeals(t interface { - mock.TestingT - Cleanup(func()) -}) *Seals { - mock := &Seals{} - mock.Mock.Test(t) +// Seals_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type Seals_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - seal *flow.Seal +func (_e *Seals_Expecter) Store(seal interface{}) *Seals_Store_Call { + return &Seals_Store_Call{Call: _e.mock.On("Store", seal)} +} - return mock +func (_c *Seals_Store_Call) Run(run func(seal *flow.Seal)) *Seals_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.Seal + if args[0] != nil { + arg0 = args[0].(*flow.Seal) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Seals_Store_Call) Return(err error) *Seals_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Seals_Store_Call) RunAndReturn(run func(seal *flow.Seal) error) *Seals_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/seeker.go b/storage/mock/seeker.go index 837dd401cb0..c9add0a632f 100644 --- a/storage/mock/seeker.go +++ b/storage/mock/seeker.go @@ -1,17 +1,43 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewSeeker creates a new instance of Seeker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSeeker(t interface { + mock.TestingT + Cleanup(func()) +}) *Seeker { + mock := &Seeker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Seeker is an autogenerated mock type for the Seeker type type Seeker struct { mock.Mock } -// SeekLE provides a mock function with given fields: startPrefix, key -func (_m *Seeker) SeekLE(startPrefix []byte, key []byte) ([]byte, error) { - ret := _m.Called(startPrefix, key) +type Seeker_Expecter struct { + mock *mock.Mock +} + +func (_m *Seeker) EXPECT() *Seeker_Expecter { + return &Seeker_Expecter{mock: &_m.Mock} +} + +// SeekLE provides a mock function for the type Seeker +func (_mock *Seeker) SeekLE(startPrefix []byte, key []byte) ([]byte, error) { + ret := _mock.Called(startPrefix, key) if len(ret) == 0 { panic("no return value specified for SeekLE") @@ -19,36 +45,60 @@ func (_m *Seeker) SeekLE(startPrefix []byte, key []byte) ([]byte, error) { var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func([]byte, []byte) ([]byte, error)); ok { - return rf(startPrefix, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) ([]byte, error)); ok { + return returnFunc(startPrefix, key) } - if rf, ok := ret.Get(0).(func([]byte, []byte) []byte); ok { - r0 = rf(startPrefix, key) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) []byte); ok { + r0 = returnFunc(startPrefix, key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) } } - - if rf, ok := ret.Get(1).(func([]byte, []byte) error); ok { - r1 = rf(startPrefix, key) + if returnFunc, ok := ret.Get(1).(func([]byte, []byte) error); ok { + r1 = returnFunc(startPrefix, key) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewSeeker creates a new instance of Seeker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewSeeker(t interface { - mock.TestingT - Cleanup(func()) -}) *Seeker { - mock := &Seeker{} - mock.Mock.Test(t) +// Seeker_SeekLE_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SeekLE' +type Seeker_SeekLE_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// SeekLE is a helper method to define mock.On call +// - startPrefix []byte +// - key []byte +func (_e *Seeker_Expecter) SeekLE(startPrefix interface{}, key interface{}) *Seeker_SeekLE_Call { + return &Seeker_SeekLE_Call{Call: _e.mock.On("SeekLE", startPrefix, key)} +} - return mock +func (_c *Seeker_SeekLE_Call) Run(run func(startPrefix []byte, key []byte)) *Seeker_SeekLE_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Seeker_SeekLE_Call) Return(bytes []byte, err error) *Seeker_SeekLE_Call { + _c.Call.Return(bytes, err) + return _c +} + +func (_c *Seeker_SeekLE_Call) RunAndReturn(run func(startPrefix []byte, key []byte) ([]byte, error)) *Seeker_SeekLE_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/service_events.go b/storage/mock/service_events.go index a7c47994f77..7dbece3cf94 100644 --- a/storage/mock/service_events.go +++ b/storage/mock/service_events.go @@ -1,60 +1,172 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewServiceEvents creates a new instance of ServiceEvents. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewServiceEvents(t interface { + mock.TestingT + Cleanup(func()) +}) *ServiceEvents { + mock := &ServiceEvents{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // ServiceEvents is an autogenerated mock type for the ServiceEvents type type ServiceEvents struct { mock.Mock } -// BatchRemoveByBlockID provides a mock function with given fields: blockID, batch -func (_m *ServiceEvents) BatchRemoveByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { - ret := _m.Called(blockID, batch) +type ServiceEvents_Expecter struct { + mock *mock.Mock +} + +func (_m *ServiceEvents) EXPECT() *ServiceEvents_Expecter { + return &ServiceEvents_Expecter{mock: &_m.Mock} +} + +// BatchRemoveByBlockID provides a mock function for the type ServiceEvents +func (_mock *ServiceEvents) BatchRemoveByBlockID(blockID flow.Identifier, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(blockID, batch) if len(ret) == 0 { panic("no return value specified for BatchRemoveByBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(blockID, batch) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(blockID, batch) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: lctx, blockID, events, batch -func (_m *ServiceEvents) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, events []flow.Event, batch storage.ReaderBatchWriter) error { - ret := _m.Called(lctx, blockID, events, batch) +// ServiceEvents_BatchRemoveByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemoveByBlockID' +type ServiceEvents_BatchRemoveByBlockID_Call struct { + *mock.Call +} + +// BatchRemoveByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +// - batch storage.ReaderBatchWriter +func (_e *ServiceEvents_Expecter) BatchRemoveByBlockID(blockID interface{}, batch interface{}) *ServiceEvents_BatchRemoveByBlockID_Call { + return &ServiceEvents_BatchRemoveByBlockID_Call{Call: _e.mock.On("BatchRemoveByBlockID", blockID, batch)} +} + +func (_c *ServiceEvents_BatchRemoveByBlockID_Call) Run(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter)) *ServiceEvents_BatchRemoveByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *ServiceEvents_BatchRemoveByBlockID_Call) Return(err error) *ServiceEvents_BatchRemoveByBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ServiceEvents_BatchRemoveByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier, batch storage.ReaderBatchWriter) error) *ServiceEvents_BatchRemoveByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type ServiceEvents +func (_mock *ServiceEvents) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, events []flow.Event, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(lctx, blockID, events, batch) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, []flow.Event, storage.ReaderBatchWriter) error); ok { - r0 = rf(lctx, blockID, events, batch) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, []flow.Event, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(lctx, blockID, events, batch) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: blockID -func (_m *ServiceEvents) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { - ret := _m.Called(blockID) +// ServiceEvents_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type ServiceEvents_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - lctx lockctx.Proof +// - blockID flow.Identifier +// - events []flow.Event +// - batch storage.ReaderBatchWriter +func (_e *ServiceEvents_Expecter) BatchStore(lctx interface{}, blockID interface{}, events interface{}, batch interface{}) *ServiceEvents_BatchStore_Call { + return &ServiceEvents_BatchStore_Call{Call: _e.mock.On("BatchStore", lctx, blockID, events, batch)} +} + +func (_c *ServiceEvents_BatchStore_Call) Run(run func(lctx lockctx.Proof, blockID flow.Identifier, events []flow.Event, batch storage.ReaderBatchWriter)) *ServiceEvents_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 []flow.Event + if args[2] != nil { + arg2 = args[2].([]flow.Event) + } + var arg3 storage.ReaderBatchWriter + if args[3] != nil { + arg3 = args[3].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *ServiceEvents_BatchStore_Call) Return(err error) *ServiceEvents_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *ServiceEvents_BatchStore_Call) RunAndReturn(run func(lctx lockctx.Proof, blockID flow.Identifier, events []flow.Event, batch storage.ReaderBatchWriter) error) *ServiceEvents_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type ServiceEvents +func (_mock *ServiceEvents) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -62,36 +174,54 @@ func (_m *ServiceEvents) ByBlockID(blockID flow.Identifier) ([]flow.Event, error var r0 []flow.Event var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Event, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.Event, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.Event); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.Event); ok { + r0 = returnFunc(blockID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Event) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewServiceEvents creates a new instance of ServiceEvents. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewServiceEvents(t interface { - mock.TestingT - Cleanup(func()) -}) *ServiceEvents { - mock := &ServiceEvents{} - mock.Mock.Test(t) +// ServiceEvents_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type ServiceEvents_ByBlockID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockID is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *ServiceEvents_Expecter) ByBlockID(blockID interface{}) *ServiceEvents_ByBlockID_Call { + return &ServiceEvents_ByBlockID_Call{Call: _e.mock.On("ByBlockID", blockID)} +} - return mock +func (_c *ServiceEvents_ByBlockID_Call) Run(run func(blockID flow.Identifier)) *ServiceEvents_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *ServiceEvents_ByBlockID_Call) Return(events []flow.Event, err error) *ServiceEvents_ByBlockID_Call { + _c.Call.Return(events, err) + return _c +} + +func (_c *ServiceEvents_ByBlockID_Call) RunAndReturn(run func(blockID flow.Identifier) ([]flow.Event, error)) *ServiceEvents_ByBlockID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/stored_chunk_data_packs.go b/storage/mock/stored_chunk_data_packs.go index a88c298e91a..c4dbc7211a9 100644 --- a/storage/mock/stored_chunk_data_packs.go +++ b/storage/mock/stored_chunk_data_packs.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewStoredChunkDataPacks creates a new instance of StoredChunkDataPacks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStoredChunkDataPacks(t interface { + mock.TestingT + Cleanup(func()) +}) *StoredChunkDataPacks { + mock := &StoredChunkDataPacks{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // StoredChunkDataPacks is an autogenerated mock type for the StoredChunkDataPacks type type StoredChunkDataPacks struct { mock.Mock } -// BatchRemove provides a mock function with given fields: chunkDataPackIDs, rw -func (_m *StoredChunkDataPacks) BatchRemove(chunkDataPackIDs []flow.Identifier, rw storage.ReaderBatchWriter) error { - ret := _m.Called(chunkDataPackIDs, rw) +type StoredChunkDataPacks_Expecter struct { + mock *mock.Mock +} + +func (_m *StoredChunkDataPacks) EXPECT() *StoredChunkDataPacks_Expecter { + return &StoredChunkDataPacks_Expecter{mock: &_m.Mock} +} + +// BatchRemove provides a mock function for the type StoredChunkDataPacks +func (_mock *StoredChunkDataPacks) BatchRemove(chunkDataPackIDs []flow.Identifier, rw storage.ReaderBatchWriter) error { + ret := _mock.Called(chunkDataPackIDs, rw) if len(ret) == 0 { panic("no return value specified for BatchRemove") } var r0 error - if rf, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(chunkDataPackIDs, rw) + if returnFunc, ok := ret.Get(0).(func([]flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(chunkDataPackIDs, rw) } else { r0 = ret.Error(0) } - return r0 } -// ByID provides a mock function with given fields: id -func (_m *StoredChunkDataPacks) ByID(id flow.Identifier) (*storage.StoredChunkDataPack, error) { - ret := _m.Called(id) +// StoredChunkDataPacks_BatchRemove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemove' +type StoredChunkDataPacks_BatchRemove_Call struct { + *mock.Call +} + +// BatchRemove is a helper method to define mock.On call +// - chunkDataPackIDs []flow.Identifier +// - rw storage.ReaderBatchWriter +func (_e *StoredChunkDataPacks_Expecter) BatchRemove(chunkDataPackIDs interface{}, rw interface{}) *StoredChunkDataPacks_BatchRemove_Call { + return &StoredChunkDataPacks_BatchRemove_Call{Call: _e.mock.On("BatchRemove", chunkDataPackIDs, rw)} +} + +func (_c *StoredChunkDataPacks_BatchRemove_Call) Run(run func(chunkDataPackIDs []flow.Identifier, rw storage.ReaderBatchWriter)) *StoredChunkDataPacks_BatchRemove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.Identifier + if args[0] != nil { + arg0 = args[0].([]flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *StoredChunkDataPacks_BatchRemove_Call) Return(err error) *StoredChunkDataPacks_BatchRemove_Call { + _c.Call.Return(err) + return _c +} + +func (_c *StoredChunkDataPacks_BatchRemove_Call) RunAndReturn(run func(chunkDataPackIDs []flow.Identifier, rw storage.ReaderBatchWriter) error) *StoredChunkDataPacks_BatchRemove_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type StoredChunkDataPacks +func (_mock *StoredChunkDataPacks) ByID(id flow.Identifier) (*storage.StoredChunkDataPack, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByID") @@ -42,47 +104,112 @@ func (_m *StoredChunkDataPacks) ByID(id flow.Identifier) (*storage.StoredChunkDa var r0 *storage.StoredChunkDataPack var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*storage.StoredChunkDataPack, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*storage.StoredChunkDataPack, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *storage.StoredChunkDataPack); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *storage.StoredChunkDataPack); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*storage.StoredChunkDataPack) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// Remove provides a mock function with given fields: chunkDataPackIDs -func (_m *StoredChunkDataPacks) Remove(chunkDataPackIDs []flow.Identifier) error { - ret := _m.Called(chunkDataPackIDs) +// StoredChunkDataPacks_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type StoredChunkDataPacks_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *StoredChunkDataPacks_Expecter) ByID(id interface{}) *StoredChunkDataPacks_ByID_Call { + return &StoredChunkDataPacks_ByID_Call{Call: _e.mock.On("ByID", id)} +} + +func (_c *StoredChunkDataPacks_ByID_Call) Run(run func(id flow.Identifier)) *StoredChunkDataPacks_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StoredChunkDataPacks_ByID_Call) Return(storedChunkDataPack *storage.StoredChunkDataPack, err error) *StoredChunkDataPacks_ByID_Call { + _c.Call.Return(storedChunkDataPack, err) + return _c +} + +func (_c *StoredChunkDataPacks_ByID_Call) RunAndReturn(run func(id flow.Identifier) (*storage.StoredChunkDataPack, error)) *StoredChunkDataPacks_ByID_Call { + _c.Call.Return(run) + return _c +} + +// Remove provides a mock function for the type StoredChunkDataPacks +func (_mock *StoredChunkDataPacks) Remove(chunkDataPackIDs []flow.Identifier) error { + ret := _mock.Called(chunkDataPackIDs) if len(ret) == 0 { panic("no return value specified for Remove") } var r0 error - if rf, ok := ret.Get(0).(func([]flow.Identifier) error); ok { - r0 = rf(chunkDataPackIDs) + if returnFunc, ok := ret.Get(0).(func([]flow.Identifier) error); ok { + r0 = returnFunc(chunkDataPackIDs) } else { r0 = ret.Error(0) } - return r0 } -// StoreChunkDataPacks provides a mock function with given fields: cs -func (_m *StoredChunkDataPacks) StoreChunkDataPacks(cs []*storage.StoredChunkDataPack) ([]flow.Identifier, error) { - ret := _m.Called(cs) +// StoredChunkDataPacks_Remove_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Remove' +type StoredChunkDataPacks_Remove_Call struct { + *mock.Call +} + +// Remove is a helper method to define mock.On call +// - chunkDataPackIDs []flow.Identifier +func (_e *StoredChunkDataPacks_Expecter) Remove(chunkDataPackIDs interface{}) *StoredChunkDataPacks_Remove_Call { + return &StoredChunkDataPacks_Remove_Call{Call: _e.mock.On("Remove", chunkDataPackIDs)} +} + +func (_c *StoredChunkDataPacks_Remove_Call) Run(run func(chunkDataPackIDs []flow.Identifier)) *StoredChunkDataPacks_Remove_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []flow.Identifier + if args[0] != nil { + arg0 = args[0].([]flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StoredChunkDataPacks_Remove_Call) Return(err error) *StoredChunkDataPacks_Remove_Call { + _c.Call.Return(err) + return _c +} + +func (_c *StoredChunkDataPacks_Remove_Call) RunAndReturn(run func(chunkDataPackIDs []flow.Identifier) error) *StoredChunkDataPacks_Remove_Call { + _c.Call.Return(run) + return _c +} + +// StoreChunkDataPacks provides a mock function for the type StoredChunkDataPacks +func (_mock *StoredChunkDataPacks) StoreChunkDataPacks(cs []*storage.StoredChunkDataPack) ([]flow.Identifier, error) { + ret := _mock.Called(cs) if len(ret) == 0 { panic("no return value specified for StoreChunkDataPacks") @@ -90,36 +217,54 @@ func (_m *StoredChunkDataPacks) StoreChunkDataPacks(cs []*storage.StoredChunkDat var r0 []flow.Identifier var r1 error - if rf, ok := ret.Get(0).(func([]*storage.StoredChunkDataPack) ([]flow.Identifier, error)); ok { - return rf(cs) + if returnFunc, ok := ret.Get(0).(func([]*storage.StoredChunkDataPack) ([]flow.Identifier, error)); ok { + return returnFunc(cs) } - if rf, ok := ret.Get(0).(func([]*storage.StoredChunkDataPack) []flow.Identifier); ok { - r0 = rf(cs) + if returnFunc, ok := ret.Get(0).(func([]*storage.StoredChunkDataPack) []flow.Identifier); ok { + r0 = returnFunc(cs) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.Identifier) } } - - if rf, ok := ret.Get(1).(func([]*storage.StoredChunkDataPack) error); ok { - r1 = rf(cs) + if returnFunc, ok := ret.Get(1).(func([]*storage.StoredChunkDataPack) error); ok { + r1 = returnFunc(cs) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewStoredChunkDataPacks creates a new instance of StoredChunkDataPacks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewStoredChunkDataPacks(t interface { - mock.TestingT - Cleanup(func()) -}) *StoredChunkDataPacks { - mock := &StoredChunkDataPacks{} - mock.Mock.Test(t) +// StoredChunkDataPacks_StoreChunkDataPacks_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'StoreChunkDataPacks' +type StoredChunkDataPacks_StoreChunkDataPacks_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// StoreChunkDataPacks is a helper method to define mock.On call +// - cs []*storage.StoredChunkDataPack +func (_e *StoredChunkDataPacks_Expecter) StoreChunkDataPacks(cs interface{}) *StoredChunkDataPacks_StoreChunkDataPacks_Call { + return &StoredChunkDataPacks_StoreChunkDataPacks_Call{Call: _e.mock.On("StoreChunkDataPacks", cs)} +} - return mock +func (_c *StoredChunkDataPacks_StoreChunkDataPacks_Call) Run(run func(cs []*storage.StoredChunkDataPack)) *StoredChunkDataPacks_StoreChunkDataPacks_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []*storage.StoredChunkDataPack + if args[0] != nil { + arg0 = args[0].([]*storage.StoredChunkDataPack) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *StoredChunkDataPacks_StoreChunkDataPacks_Call) Return(identifiers []flow.Identifier, err error) *StoredChunkDataPacks_StoreChunkDataPacks_Call { + _c.Call.Return(identifiers, err) + return _c +} + +func (_c *StoredChunkDataPacks_StoreChunkDataPacks_Call) RunAndReturn(run func(cs []*storage.StoredChunkDataPack) ([]flow.Identifier, error)) *StoredChunkDataPacks_StoreChunkDataPacks_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/transaction.go b/storage/mock/transaction.go index ea5a27c0c96..2f1c0ee506d 100644 --- a/storage/mock/transaction.go +++ b/storage/mock/transaction.go @@ -1,42 +1,93 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock -import mock "github.com/stretchr/testify/mock" +import ( + mock "github.com/stretchr/testify/mock" +) + +// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransaction(t interface { + mock.TestingT + Cleanup(func()) +}) *Transaction { + mock := &Transaction{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} // Transaction is an autogenerated mock type for the Transaction type type Transaction struct { mock.Mock } -// Set provides a mock function with given fields: key, val -func (_m *Transaction) Set(key []byte, val []byte) error { - ret := _m.Called(key, val) +type Transaction_Expecter struct { + mock *mock.Mock +} + +func (_m *Transaction) EXPECT() *Transaction_Expecter { + return &Transaction_Expecter{mock: &_m.Mock} +} + +// Set provides a mock function for the type Transaction +func (_mock *Transaction) Set(key []byte, val []byte) error { + ret := _mock.Called(key, val) if len(ret) == 0 { panic("no return value specified for Set") } var r0 error - if rf, ok := ret.Get(0).(func([]byte, []byte) error); ok { - r0 = rf(key, val) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) error); ok { + r0 = returnFunc(key, val) } else { r0 = ret.Error(0) } - return r0 } -// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransaction(t interface { - mock.TestingT - Cleanup(func()) -}) *Transaction { - mock := &Transaction{} - mock.Mock.Test(t) +// Transaction_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set' +type Transaction_Set_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Set is a helper method to define mock.On call +// - key []byte +// - val []byte +func (_e *Transaction_Expecter) Set(key interface{}, val interface{}) *Transaction_Set_Call { + return &Transaction_Set_Call{Call: _e.mock.On("Set", key, val)} +} - return mock +func (_c *Transaction_Set_Call) Run(run func(key []byte, val []byte)) *Transaction_Set_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Transaction_Set_Call) Return(err error) *Transaction_Set_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Transaction_Set_Call) RunAndReturn(run func(key []byte, val []byte) error) *Transaction_Set_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/transaction_result_error_messages.go b/storage/mock/transaction_result_error_messages.go index 16a940510ef..f9189e91439 100644 --- a/storage/mock/transaction_result_error_messages.go +++ b/storage/mock/transaction_result_error_messages.go @@ -1,42 +1,115 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewTransactionResultErrorMessages creates a new instance of TransactionResultErrorMessages. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionResultErrorMessages(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionResultErrorMessages { + mock := &TransactionResultErrorMessages{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionResultErrorMessages is an autogenerated mock type for the TransactionResultErrorMessages type type TransactionResultErrorMessages struct { mock.Mock } -// BatchStore provides a mock function with given fields: lctx, rw, blockID, transactionResultErrorMessages -func (_m *TransactionResultErrorMessages) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage) error { - ret := _m.Called(lctx, rw, blockID, transactionResultErrorMessages) +type TransactionResultErrorMessages_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionResultErrorMessages) EXPECT() *TransactionResultErrorMessages_Expecter { + return &TransactionResultErrorMessages_Expecter{mock: &_m.Mock} +} + +// BatchStore provides a mock function for the type TransactionResultErrorMessages +func (_mock *TransactionResultErrorMessages) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage) error { + ret := _mock.Called(lctx, rw, blockID, transactionResultErrorMessages) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.TransactionResultErrorMessage) error); ok { - r0 = rf(lctx, rw, blockID, transactionResultErrorMessages) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.TransactionResultErrorMessage) error); ok { + r0 = returnFunc(lctx, rw, blockID, transactionResultErrorMessages) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: id -func (_m *TransactionResultErrorMessages) ByBlockID(id flow.Identifier) ([]flow.TransactionResultErrorMessage, error) { - ret := _m.Called(id) +// TransactionResultErrorMessages_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type TransactionResultErrorMessages_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - transactionResultErrorMessages []flow.TransactionResultErrorMessage +func (_e *TransactionResultErrorMessages_Expecter) BatchStore(lctx interface{}, rw interface{}, blockID interface{}, transactionResultErrorMessages interface{}) *TransactionResultErrorMessages_BatchStore_Call { + return &TransactionResultErrorMessages_BatchStore_Call{Call: _e.mock.On("BatchStore", lctx, rw, blockID, transactionResultErrorMessages)} +} + +func (_c *TransactionResultErrorMessages_BatchStore_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage)) *TransactionResultErrorMessages_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 []flow.TransactionResultErrorMessage + if args[3] != nil { + arg3 = args[3].([]flow.TransactionResultErrorMessage) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessages_BatchStore_Call) Return(err error) *TransactionResultErrorMessages_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *TransactionResultErrorMessages_BatchStore_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage) error) *TransactionResultErrorMessages_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type TransactionResultErrorMessages +func (_mock *TransactionResultErrorMessages) ByBlockID(id flow.Identifier) ([]flow.TransactionResultErrorMessage, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -44,29 +117,61 @@ func (_m *TransactionResultErrorMessages) ByBlockID(id flow.Identifier) ([]flow. var r0 []flow.TransactionResultErrorMessage var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResultErrorMessage, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResultErrorMessage, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResultErrorMessage); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResultErrorMessage); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.TransactionResultErrorMessage) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *TransactionResultErrorMessages) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResultErrorMessage, error) { - ret := _m.Called(blockID, transactionID) +// TransactionResultErrorMessages_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type TransactionResultErrorMessages_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *TransactionResultErrorMessages_Expecter) ByBlockID(id interface{}) *TransactionResultErrorMessages_ByBlockID_Call { + return &TransactionResultErrorMessages_ByBlockID_Call{Call: _e.mock.On("ByBlockID", id)} +} + +func (_c *TransactionResultErrorMessages_ByBlockID_Call) Run(run func(id flow.Identifier)) *TransactionResultErrorMessages_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessages_ByBlockID_Call) Return(transactionResultErrorMessages []flow.TransactionResultErrorMessage, err error) *TransactionResultErrorMessages_ByBlockID_Call { + _c.Call.Return(transactionResultErrorMessages, err) + return _c +} + +func (_c *TransactionResultErrorMessages_ByBlockID_Call) RunAndReturn(run func(id flow.Identifier) ([]flow.TransactionResultErrorMessage, error)) *TransactionResultErrorMessages_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type TransactionResultErrorMessages +func (_mock *TransactionResultErrorMessages) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResultErrorMessage, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -74,29 +179,67 @@ func (_m *TransactionResultErrorMessages) ByBlockIDTransactionID(blockID flow.Id var r0 *flow.TransactionResultErrorMessage var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResultErrorMessage, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResultErrorMessage, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResultErrorMessage); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResultErrorMessage); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResultErrorMessage) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *TransactionResultErrorMessages) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResultErrorMessage, error) { - ret := _m.Called(blockID, txIndex) +// TransactionResultErrorMessages_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type TransactionResultErrorMessages_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *TransactionResultErrorMessages_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *TransactionResultErrorMessages_ByBlockIDTransactionID_Call { + return &TransactionResultErrorMessages_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *TransactionResultErrorMessages_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *TransactionResultErrorMessages_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessages_ByBlockIDTransactionID_Call) Return(transactionResultErrorMessage *flow.TransactionResultErrorMessage, err error) *TransactionResultErrorMessages_ByBlockIDTransactionID_Call { + _c.Call.Return(transactionResultErrorMessage, err) + return _c +} + +func (_c *TransactionResultErrorMessages_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResultErrorMessage, error)) *TransactionResultErrorMessages_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type TransactionResultErrorMessages +func (_mock *TransactionResultErrorMessages) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResultErrorMessage, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -104,29 +247,67 @@ func (_m *TransactionResultErrorMessages) ByBlockIDTransactionIndex(blockID flow var r0 *flow.TransactionResultErrorMessage var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResultErrorMessage, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResultErrorMessage, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResultErrorMessage); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResultErrorMessage); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResultErrorMessage) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// Exists provides a mock function with given fields: blockID -func (_m *TransactionResultErrorMessages) Exists(blockID flow.Identifier) (bool, error) { - ret := _m.Called(blockID) +// TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} + +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *TransactionResultErrorMessages_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call { + return &TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} + +func (_c *TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call) Return(transactionResultErrorMessage *flow.TransactionResultErrorMessage, err error) *TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call { + _c.Call.Return(transactionResultErrorMessage, err) + return _c +} + +func (_c *TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResultErrorMessage, error)) *TransactionResultErrorMessages_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c +} + +// Exists provides a mock function for the type TransactionResultErrorMessages +func (_mock *TransactionResultErrorMessages) Exists(blockID flow.Identifier) (bool, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for Exists") @@ -134,52 +315,115 @@ func (_m *TransactionResultErrorMessages) Exists(blockID flow.Identifier) (bool, var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Store provides a mock function with given fields: lctx, blockID, transactionResultErrorMessages -func (_m *TransactionResultErrorMessages) Store(lctx lockctx.Proof, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage) error { - ret := _m.Called(lctx, blockID, transactionResultErrorMessages) +// TransactionResultErrorMessages_Exists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Exists' +type TransactionResultErrorMessages_Exists_Call struct { + *mock.Call +} + +// Exists is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *TransactionResultErrorMessages_Expecter) Exists(blockID interface{}) *TransactionResultErrorMessages_Exists_Call { + return &TransactionResultErrorMessages_Exists_Call{Call: _e.mock.On("Exists", blockID)} +} + +func (_c *TransactionResultErrorMessages_Exists_Call) Run(run func(blockID flow.Identifier)) *TransactionResultErrorMessages_Exists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessages_Exists_Call) Return(b bool, err error) *TransactionResultErrorMessages_Exists_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *TransactionResultErrorMessages_Exists_Call) RunAndReturn(run func(blockID flow.Identifier) (bool, error)) *TransactionResultErrorMessages_Exists_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type TransactionResultErrorMessages +func (_mock *TransactionResultErrorMessages) Store(lctx lockctx.Proof, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage) error { + ret := _mock.Called(lctx, blockID, transactionResultErrorMessages) if len(ret) == 0 { panic("no return value specified for Store") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, []flow.TransactionResultErrorMessage) error); ok { - r0 = rf(lctx, blockID, transactionResultErrorMessages) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, flow.Identifier, []flow.TransactionResultErrorMessage) error); ok { + r0 = returnFunc(lctx, blockID, transactionResultErrorMessages) } else { r0 = ret.Error(0) } - return r0 } -// NewTransactionResultErrorMessages creates a new instance of TransactionResultErrorMessages. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionResultErrorMessages(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionResultErrorMessages { - mock := &TransactionResultErrorMessages{} - mock.Mock.Test(t) +// TransactionResultErrorMessages_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type TransactionResultErrorMessages_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - lctx lockctx.Proof +// - blockID flow.Identifier +// - transactionResultErrorMessages []flow.TransactionResultErrorMessage +func (_e *TransactionResultErrorMessages_Expecter) Store(lctx interface{}, blockID interface{}, transactionResultErrorMessages interface{}) *TransactionResultErrorMessages_Store_Call { + return &TransactionResultErrorMessages_Store_Call{Call: _e.mock.On("Store", lctx, blockID, transactionResultErrorMessages)} +} - return mock +func (_c *TransactionResultErrorMessages_Store_Call) Run(run func(lctx lockctx.Proof, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage)) *TransactionResultErrorMessages_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + var arg2 []flow.TransactionResultErrorMessage + if args[2] != nil { + arg2 = args[2].([]flow.TransactionResultErrorMessage) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessages_Store_Call) Return(err error) *TransactionResultErrorMessages_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *TransactionResultErrorMessages_Store_Call) RunAndReturn(run func(lctx lockctx.Proof, blockID flow.Identifier, transactionResultErrorMessages []flow.TransactionResultErrorMessage) error) *TransactionResultErrorMessages_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/transaction_result_error_messages_reader.go b/storage/mock/transaction_result_error_messages_reader.go index c4005009fb2..5e86963e679 100644 --- a/storage/mock/transaction_result_error_messages_reader.go +++ b/storage/mock/transaction_result_error_messages_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTransactionResultErrorMessagesReader creates a new instance of TransactionResultErrorMessagesReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionResultErrorMessagesReader(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionResultErrorMessagesReader { + mock := &TransactionResultErrorMessagesReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionResultErrorMessagesReader is an autogenerated mock type for the TransactionResultErrorMessagesReader type type TransactionResultErrorMessagesReader struct { mock.Mock } -// ByBlockID provides a mock function with given fields: id -func (_m *TransactionResultErrorMessagesReader) ByBlockID(id flow.Identifier) ([]flow.TransactionResultErrorMessage, error) { - ret := _m.Called(id) +type TransactionResultErrorMessagesReader_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionResultErrorMessagesReader) EXPECT() *TransactionResultErrorMessagesReader_Expecter { + return &TransactionResultErrorMessagesReader_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type TransactionResultErrorMessagesReader +func (_mock *TransactionResultErrorMessagesReader) ByBlockID(id flow.Identifier) ([]flow.TransactionResultErrorMessage, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,29 +46,61 @@ func (_m *TransactionResultErrorMessagesReader) ByBlockID(id flow.Identifier) ([ var r0 []flow.TransactionResultErrorMessage var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResultErrorMessage, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResultErrorMessage, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResultErrorMessage); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResultErrorMessage); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.TransactionResultErrorMessage) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *TransactionResultErrorMessagesReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResultErrorMessage, error) { - ret := _m.Called(blockID, transactionID) +// TransactionResultErrorMessagesReader_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type TransactionResultErrorMessagesReader_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *TransactionResultErrorMessagesReader_Expecter) ByBlockID(id interface{}) *TransactionResultErrorMessagesReader_ByBlockID_Call { + return &TransactionResultErrorMessagesReader_ByBlockID_Call{Call: _e.mock.On("ByBlockID", id)} +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockID_Call) Run(run func(id flow.Identifier)) *TransactionResultErrorMessagesReader_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockID_Call) Return(transactionResultErrorMessages []flow.TransactionResultErrorMessage, err error) *TransactionResultErrorMessagesReader_ByBlockID_Call { + _c.Call.Return(transactionResultErrorMessages, err) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockID_Call) RunAndReturn(run func(id flow.Identifier) ([]flow.TransactionResultErrorMessage, error)) *TransactionResultErrorMessagesReader_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type TransactionResultErrorMessagesReader +func (_mock *TransactionResultErrorMessagesReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResultErrorMessage, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -52,29 +108,67 @@ func (_m *TransactionResultErrorMessagesReader) ByBlockIDTransactionID(blockID f var r0 *flow.TransactionResultErrorMessage var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResultErrorMessage, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResultErrorMessage, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResultErrorMessage); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResultErrorMessage); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResultErrorMessage) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *TransactionResultErrorMessagesReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResultErrorMessage, error) { - ret := _m.Called(blockID, txIndex) +// TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *TransactionResultErrorMessagesReader_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call { + return &TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call) Return(transactionResultErrorMessage *flow.TransactionResultErrorMessage, err error) *TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call { + _c.Call.Return(transactionResultErrorMessage, err) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResultErrorMessage, error)) *TransactionResultErrorMessagesReader_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type TransactionResultErrorMessagesReader +func (_mock *TransactionResultErrorMessagesReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResultErrorMessage, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -82,29 +176,67 @@ func (_m *TransactionResultErrorMessagesReader) ByBlockIDTransactionIndex(blockI var r0 *flow.TransactionResultErrorMessage var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResultErrorMessage, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResultErrorMessage, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResultErrorMessage); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResultErrorMessage); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResultErrorMessage) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// Exists provides a mock function with given fields: blockID -func (_m *TransactionResultErrorMessagesReader) Exists(blockID flow.Identifier) (bool, error) { - ret := _m.Called(blockID) +// TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} + +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *TransactionResultErrorMessagesReader_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call { + return &TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call) Return(transactionResultErrorMessage *flow.TransactionResultErrorMessage, err error) *TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(transactionResultErrorMessage, err) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResultErrorMessage, error)) *TransactionResultErrorMessagesReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c +} + +// Exists provides a mock function for the type TransactionResultErrorMessagesReader +func (_mock *TransactionResultErrorMessagesReader) Exists(blockID flow.Identifier) (bool, error) { + ret := _mock.Called(blockID) if len(ret) == 0 { panic("no return value specified for Exists") @@ -112,34 +244,52 @@ func (_m *TransactionResultErrorMessagesReader) Exists(blockID flow.Identifier) var r0 bool var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { - return rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (bool, error)); ok { + return returnFunc(blockID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) bool); ok { - r0 = rf(blockID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) bool); ok { + r0 = returnFunc(blockID) } else { r0 = ret.Get(0).(bool) } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(blockID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(blockID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTransactionResultErrorMessagesReader creates a new instance of TransactionResultErrorMessagesReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionResultErrorMessagesReader(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionResultErrorMessagesReader { - mock := &TransactionResultErrorMessagesReader{} - mock.Mock.Test(t) +// TransactionResultErrorMessagesReader_Exists_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Exists' +type TransactionResultErrorMessagesReader_Exists_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Exists is a helper method to define mock.On call +// - blockID flow.Identifier +func (_e *TransactionResultErrorMessagesReader_Expecter) Exists(blockID interface{}) *TransactionResultErrorMessagesReader_Exists_Call { + return &TransactionResultErrorMessagesReader_Exists_Call{Call: _e.mock.On("Exists", blockID)} +} - return mock +func (_c *TransactionResultErrorMessagesReader_Exists_Call) Run(run func(blockID flow.Identifier)) *TransactionResultErrorMessagesReader_Exists_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_Exists_Call) Return(b bool, err error) *TransactionResultErrorMessagesReader_Exists_Call { + _c.Call.Return(b, err) + return _c +} + +func (_c *TransactionResultErrorMessagesReader_Exists_Call) RunAndReturn(run func(blockID flow.Identifier) (bool, error)) *TransactionResultErrorMessagesReader_Exists_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/transaction_results.go b/storage/mock/transaction_results.go index c35cc476460..033ff2aa283 100644 --- a/storage/mock/transaction_results.go +++ b/storage/mock/transaction_results.go @@ -1,60 +1,172 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - lockctx "github.com/jordanschalm/lockctx" - flow "github.com/onflow/flow-go/model/flow" - + "github.com/jordanschalm/lockctx" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewTransactionResults creates a new instance of TransactionResults. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionResults(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionResults { + mock := &TransactionResults{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionResults is an autogenerated mock type for the TransactionResults type type TransactionResults struct { mock.Mock } -// BatchRemoveByBlockID provides a mock function with given fields: id, batch -func (_m *TransactionResults) BatchRemoveByBlockID(id flow.Identifier, batch storage.ReaderBatchWriter) error { - ret := _m.Called(id, batch) +type TransactionResults_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionResults) EXPECT() *TransactionResults_Expecter { + return &TransactionResults_Expecter{mock: &_m.Mock} +} + +// BatchRemoveByBlockID provides a mock function for the type TransactionResults +func (_mock *TransactionResults) BatchRemoveByBlockID(id flow.Identifier, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(id, batch) if len(ret) == 0 { panic("no return value specified for BatchRemoveByBlockID") } var r0 error - if rf, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { - r0 = rf(id, batch) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(id, batch) } else { r0 = ret.Error(0) } - return r0 } -// BatchStore provides a mock function with given fields: lctx, rw, blockID, transactionResults -func (_m *TransactionResults) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.TransactionResult) error { - ret := _m.Called(lctx, rw, blockID, transactionResults) +// TransactionResults_BatchRemoveByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchRemoveByBlockID' +type TransactionResults_BatchRemoveByBlockID_Call struct { + *mock.Call +} + +// BatchRemoveByBlockID is a helper method to define mock.On call +// - id flow.Identifier +// - batch storage.ReaderBatchWriter +func (_e *TransactionResults_Expecter) BatchRemoveByBlockID(id interface{}, batch interface{}) *TransactionResults_BatchRemoveByBlockID_Call { + return &TransactionResults_BatchRemoveByBlockID_Call{Call: _e.mock.On("BatchRemoveByBlockID", id, batch)} +} + +func (_c *TransactionResults_BatchRemoveByBlockID_Call) Run(run func(id flow.Identifier, batch storage.ReaderBatchWriter)) *TransactionResults_BatchRemoveByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResults_BatchRemoveByBlockID_Call) Return(err error) *TransactionResults_BatchRemoveByBlockID_Call { + _c.Call.Return(err) + return _c +} + +func (_c *TransactionResults_BatchRemoveByBlockID_Call) RunAndReturn(run func(id flow.Identifier, batch storage.ReaderBatchWriter) error) *TransactionResults_BatchRemoveByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// BatchStore provides a mock function for the type TransactionResults +func (_mock *TransactionResults) BatchStore(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.TransactionResult) error { + ret := _mock.Called(lctx, rw, blockID, transactionResults) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.TransactionResult) error); ok { - r0 = rf(lctx, rw, blockID, transactionResults) + if returnFunc, ok := ret.Get(0).(func(lockctx.Proof, storage.ReaderBatchWriter, flow.Identifier, []flow.TransactionResult) error); ok { + r0 = returnFunc(lctx, rw, blockID, transactionResults) } else { r0 = ret.Error(0) } - return r0 } -// ByBlockID provides a mock function with given fields: id -func (_m *TransactionResults) ByBlockID(id flow.Identifier) ([]flow.TransactionResult, error) { - ret := _m.Called(id) +// TransactionResults_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type TransactionResults_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - lctx lockctx.Proof +// - rw storage.ReaderBatchWriter +// - blockID flow.Identifier +// - transactionResults []flow.TransactionResult +func (_e *TransactionResults_Expecter) BatchStore(lctx interface{}, rw interface{}, blockID interface{}, transactionResults interface{}) *TransactionResults_BatchStore_Call { + return &TransactionResults_BatchStore_Call{Call: _e.mock.On("BatchStore", lctx, rw, blockID, transactionResults)} +} + +func (_c *TransactionResults_BatchStore_Call) Run(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.TransactionResult)) *TransactionResults_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 lockctx.Proof + if args[0] != nil { + arg0 = args[0].(lockctx.Proof) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + var arg2 flow.Identifier + if args[2] != nil { + arg2 = args[2].(flow.Identifier) + } + var arg3 []flow.TransactionResult + if args[3] != nil { + arg3 = args[3].([]flow.TransactionResult) + } + run( + arg0, + arg1, + arg2, + arg3, + ) + }) + return _c +} + +func (_c *TransactionResults_BatchStore_Call) Return(err error) *TransactionResults_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *TransactionResults_BatchStore_Call) RunAndReturn(run func(lctx lockctx.Proof, rw storage.ReaderBatchWriter, blockID flow.Identifier, transactionResults []flow.TransactionResult) error) *TransactionResults_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockID provides a mock function for the type TransactionResults +func (_mock *TransactionResults) ByBlockID(id flow.Identifier) ([]flow.TransactionResult, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -62,29 +174,61 @@ func (_m *TransactionResults) ByBlockID(id flow.Identifier) ([]flow.TransactionR var r0 []flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResult, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResult, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResult); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResult); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *TransactionResults) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResult, error) { - ret := _m.Called(blockID, transactionID) +// TransactionResults_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type TransactionResults_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *TransactionResults_Expecter) ByBlockID(id interface{}) *TransactionResults_ByBlockID_Call { + return &TransactionResults_ByBlockID_Call{Call: _e.mock.On("ByBlockID", id)} +} + +func (_c *TransactionResults_ByBlockID_Call) Run(run func(id flow.Identifier)) *TransactionResults_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionResults_ByBlockID_Call) Return(transactionResults []flow.TransactionResult, err error) *TransactionResults_ByBlockID_Call { + _c.Call.Return(transactionResults, err) + return _c +} + +func (_c *TransactionResults_ByBlockID_Call) RunAndReturn(run func(id flow.Identifier) ([]flow.TransactionResult, error)) *TransactionResults_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type TransactionResults +func (_mock *TransactionResults) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResult, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -92,29 +236,67 @@ func (_m *TransactionResults) ByBlockIDTransactionID(blockID flow.Identifier, tr var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResult, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResult, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResult); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResult); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *TransactionResults) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResult, error) { - ret := _m.Called(blockID, txIndex) +// TransactionResults_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type TransactionResults_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *TransactionResults_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *TransactionResults_ByBlockIDTransactionID_Call { + return &TransactionResults_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *TransactionResults_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *TransactionResults_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResults_ByBlockIDTransactionID_Call) Return(transactionResult *flow.TransactionResult, err error) *TransactionResults_ByBlockIDTransactionID_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionResults_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResult, error)) *TransactionResults_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type TransactionResults +func (_mock *TransactionResults) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResult, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -122,36 +304,60 @@ func (_m *TransactionResults) ByBlockIDTransactionIndex(blockID flow.Identifier, var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResult, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResult, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResult); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResult); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTransactionResults creates a new instance of TransactionResults. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionResults(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionResults { - mock := &TransactionResults{} - mock.Mock.Test(t) +// TransactionResults_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type TransactionResults_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *TransactionResults_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *TransactionResults_ByBlockIDTransactionIndex_Call { + return &TransactionResults_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} - return mock +func (_c *TransactionResults_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *TransactionResults_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResults_ByBlockIDTransactionIndex_Call) Return(transactionResult *flow.TransactionResult, err error) *TransactionResults_ByBlockIDTransactionIndex_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionResults_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResult, error)) *TransactionResults_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/transaction_results_reader.go b/storage/mock/transaction_results_reader.go index 52f2b0f1ae1..d285d9a7376 100644 --- a/storage/mock/transaction_results_reader.go +++ b/storage/mock/transaction_results_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTransactionResultsReader creates a new instance of TransactionResultsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionResultsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionResultsReader { + mock := &TransactionResultsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionResultsReader is an autogenerated mock type for the TransactionResultsReader type type TransactionResultsReader struct { mock.Mock } -// ByBlockID provides a mock function with given fields: id -func (_m *TransactionResultsReader) ByBlockID(id flow.Identifier) ([]flow.TransactionResult, error) { - ret := _m.Called(id) +type TransactionResultsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionResultsReader) EXPECT() *TransactionResultsReader_Expecter { + return &TransactionResultsReader_Expecter{mock: &_m.Mock} +} + +// ByBlockID provides a mock function for the type TransactionResultsReader +func (_mock *TransactionResultsReader) ByBlockID(id flow.Identifier) ([]flow.TransactionResult, error) { + ret := _mock.Called(id) if len(ret) == 0 { panic("no return value specified for ByBlockID") @@ -22,29 +46,61 @@ func (_m *TransactionResultsReader) ByBlockID(id flow.Identifier) ([]flow.Transa var r0 []flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResult, error)); ok { - return rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) ([]flow.TransactionResult, error)); ok { + return returnFunc(id) } - if rf, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResult); ok { - r0 = rf(id) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) []flow.TransactionResult); ok { + r0 = returnFunc(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(id) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(id) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionID provides a mock function with given fields: blockID, transactionID -func (_m *TransactionResultsReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResult, error) { - ret := _m.Called(blockID, transactionID) +// TransactionResultsReader_ByBlockID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockID' +type TransactionResultsReader_ByBlockID_Call struct { + *mock.Call +} + +// ByBlockID is a helper method to define mock.On call +// - id flow.Identifier +func (_e *TransactionResultsReader_Expecter) ByBlockID(id interface{}) *TransactionResultsReader_ByBlockID_Call { + return &TransactionResultsReader_ByBlockID_Call{Call: _e.mock.On("ByBlockID", id)} +} + +func (_c *TransactionResultsReader_ByBlockID_Call) Run(run func(id flow.Identifier)) *TransactionResultsReader_ByBlockID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionResultsReader_ByBlockID_Call) Return(transactionResults []flow.TransactionResult, err error) *TransactionResultsReader_ByBlockID_Call { + _c.Call.Return(transactionResults, err) + return _c +} + +func (_c *TransactionResultsReader_ByBlockID_Call) RunAndReturn(run func(id flow.Identifier) ([]flow.TransactionResult, error)) *TransactionResultsReader_ByBlockID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionID provides a mock function for the type TransactionResultsReader +func (_mock *TransactionResultsReader) ByBlockIDTransactionID(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResult, error) { + ret := _mock.Called(blockID, transactionID) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionID") @@ -52,29 +108,67 @@ func (_m *TransactionResultsReader) ByBlockIDTransactionID(blockID flow.Identifi var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResult, error)); ok { - return rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) (*flow.TransactionResult, error)); ok { + return returnFunc(blockID, transactionID) } - if rf, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResult); ok { - r0 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, flow.Identifier) *flow.TransactionResult); ok { + r0 = returnFunc(blockID, transactionID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { - r1 = rf(blockID, transactionID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, flow.Identifier) error); ok { + r1 = returnFunc(blockID, transactionID) } else { r1 = ret.Error(1) } - return r0, r1 } -// ByBlockIDTransactionIndex provides a mock function with given fields: blockID, txIndex -func (_m *TransactionResultsReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResult, error) { - ret := _m.Called(blockID, txIndex) +// TransactionResultsReader_ByBlockIDTransactionID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionID' +type TransactionResultsReader_ByBlockIDTransactionID_Call struct { + *mock.Call +} + +// ByBlockIDTransactionID is a helper method to define mock.On call +// - blockID flow.Identifier +// - transactionID flow.Identifier +func (_e *TransactionResultsReader_Expecter) ByBlockIDTransactionID(blockID interface{}, transactionID interface{}) *TransactionResultsReader_ByBlockIDTransactionID_Call { + return &TransactionResultsReader_ByBlockIDTransactionID_Call{Call: _e.mock.On("ByBlockIDTransactionID", blockID, transactionID)} +} + +func (_c *TransactionResultsReader_ByBlockIDTransactionID_Call) Run(run func(blockID flow.Identifier, transactionID flow.Identifier)) *TransactionResultsReader_ByBlockIDTransactionID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 flow.Identifier + if args[1] != nil { + arg1 = args[1].(flow.Identifier) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResultsReader_ByBlockIDTransactionID_Call) Return(transactionResult *flow.TransactionResult, err error) *TransactionResultsReader_ByBlockIDTransactionID_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionResultsReader_ByBlockIDTransactionID_Call) RunAndReturn(run func(blockID flow.Identifier, transactionID flow.Identifier) (*flow.TransactionResult, error)) *TransactionResultsReader_ByBlockIDTransactionID_Call { + _c.Call.Return(run) + return _c +} + +// ByBlockIDTransactionIndex provides a mock function for the type TransactionResultsReader +func (_mock *TransactionResultsReader) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResult, error) { + ret := _mock.Called(blockID, txIndex) if len(ret) == 0 { panic("no return value specified for ByBlockIDTransactionIndex") @@ -82,36 +176,60 @@ func (_m *TransactionResultsReader) ByBlockIDTransactionIndex(blockID flow.Ident var r0 *flow.TransactionResult var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResult, error)); ok { - return rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) (*flow.TransactionResult, error)); ok { + return returnFunc(blockID, txIndex) } - if rf, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResult); ok { - r0 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier, uint32) *flow.TransactionResult); ok { + r0 = returnFunc(blockID, txIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionResult) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { - r1 = rf(blockID, txIndex) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier, uint32) error); ok { + r1 = returnFunc(blockID, txIndex) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTransactionResultsReader creates a new instance of TransactionResultsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionResultsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionResultsReader { - mock := &TransactionResultsReader{} - mock.Mock.Test(t) +// TransactionResultsReader_ByBlockIDTransactionIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByBlockIDTransactionIndex' +type TransactionResultsReader_ByBlockIDTransactionIndex_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByBlockIDTransactionIndex is a helper method to define mock.On call +// - blockID flow.Identifier +// - txIndex uint32 +func (_e *TransactionResultsReader_Expecter) ByBlockIDTransactionIndex(blockID interface{}, txIndex interface{}) *TransactionResultsReader_ByBlockIDTransactionIndex_Call { + return &TransactionResultsReader_ByBlockIDTransactionIndex_Call{Call: _e.mock.On("ByBlockIDTransactionIndex", blockID, txIndex)} +} - return mock +func (_c *TransactionResultsReader_ByBlockIDTransactionIndex_Call) Run(run func(blockID flow.Identifier, txIndex uint32)) *TransactionResultsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + var arg1 uint32 + if args[1] != nil { + arg1 = args[1].(uint32) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *TransactionResultsReader_ByBlockIDTransactionIndex_Call) Return(transactionResult *flow.TransactionResult, err error) *TransactionResultsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(transactionResult, err) + return _c +} + +func (_c *TransactionResultsReader_ByBlockIDTransactionIndex_Call) RunAndReturn(run func(blockID flow.Identifier, txIndex uint32) (*flow.TransactionResult, error)) *TransactionResultsReader_ByBlockIDTransactionIndex_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/transactions.go b/storage/mock/transactions.go index c45143dcc6f..8d4fb979c0c 100644 --- a/storage/mock/transactions.go +++ b/storage/mock/transactions.go @@ -1,40 +1,102 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" - - storage "github.com/onflow/flow-go/storage" ) +// NewTransactions creates a new instance of Transactions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactions(t interface { + mock.TestingT + Cleanup(func()) +}) *Transactions { + mock := &Transactions{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Transactions is an autogenerated mock type for the Transactions type type Transactions struct { mock.Mock } -// BatchStore provides a mock function with given fields: tx, batch -func (_m *Transactions) BatchStore(tx *flow.TransactionBody, batch storage.ReaderBatchWriter) error { - ret := _m.Called(tx, batch) +type Transactions_Expecter struct { + mock *mock.Mock +} + +func (_m *Transactions) EXPECT() *Transactions_Expecter { + return &Transactions_Expecter{mock: &_m.Mock} +} + +// BatchStore provides a mock function for the type Transactions +func (_mock *Transactions) BatchStore(tx *flow.TransactionBody, batch storage.ReaderBatchWriter) error { + ret := _mock.Called(tx, batch) if len(ret) == 0 { panic("no return value specified for BatchStore") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.TransactionBody, storage.ReaderBatchWriter) error); ok { - r0 = rf(tx, batch) + if returnFunc, ok := ret.Get(0).(func(*flow.TransactionBody, storage.ReaderBatchWriter) error); ok { + r0 = returnFunc(tx, batch) } else { r0 = ret.Error(0) } - return r0 } -// ByID provides a mock function with given fields: txID -func (_m *Transactions) ByID(txID flow.Identifier) (*flow.TransactionBody, error) { - ret := _m.Called(txID) +// Transactions_BatchStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchStore' +type Transactions_BatchStore_Call struct { + *mock.Call +} + +// BatchStore is a helper method to define mock.On call +// - tx *flow.TransactionBody +// - batch storage.ReaderBatchWriter +func (_e *Transactions_Expecter) BatchStore(tx interface{}, batch interface{}) *Transactions_BatchStore_Call { + return &Transactions_BatchStore_Call{Call: _e.mock.On("BatchStore", tx, batch)} +} + +func (_c *Transactions_BatchStore_Call) Run(run func(tx *flow.TransactionBody, batch storage.ReaderBatchWriter)) *Transactions_BatchStore_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TransactionBody + if args[0] != nil { + arg0 = args[0].(*flow.TransactionBody) + } + var arg1 storage.ReaderBatchWriter + if args[1] != nil { + arg1 = args[1].(storage.ReaderBatchWriter) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Transactions_BatchStore_Call) Return(err error) *Transactions_BatchStore_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Transactions_BatchStore_Call) RunAndReturn(run func(tx *flow.TransactionBody, batch storage.ReaderBatchWriter) error) *Transactions_BatchStore_Call { + _c.Call.Return(run) + return _c +} + +// ByID provides a mock function for the type Transactions +func (_mock *Transactions) ByID(txID flow.Identifier) (*flow.TransactionBody, error) { + ret := _mock.Called(txID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -42,54 +104,105 @@ func (_m *Transactions) ByID(txID flow.Identifier) (*flow.TransactionBody, error var r0 *flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionBody, error)); ok { - return rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionBody, error)); ok { + return returnFunc(txID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionBody); ok { - r0 = rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionBody); ok { + r0 = returnFunc(txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(txID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// Store provides a mock function with given fields: tx -func (_m *Transactions) Store(tx *flow.TransactionBody) error { - ret := _m.Called(tx) +// Transactions_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type Transactions_ByID_Call struct { + *mock.Call +} + +// ByID is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *Transactions_Expecter) ByID(txID interface{}) *Transactions_ByID_Call { + return &Transactions_ByID_Call{Call: _e.mock.On("ByID", txID)} +} + +func (_c *Transactions_ByID_Call) Run(run func(txID flow.Identifier)) *Transactions_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Transactions_ByID_Call) Return(transactionBody *flow.TransactionBody, err error) *Transactions_ByID_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *Transactions_ByID_Call) RunAndReturn(run func(txID flow.Identifier) (*flow.TransactionBody, error)) *Transactions_ByID_Call { + _c.Call.Return(run) + return _c +} + +// Store provides a mock function for the type Transactions +func (_mock *Transactions) Store(tx *flow.TransactionBody) error { + ret := _mock.Called(tx) if len(ret) == 0 { panic("no return value specified for Store") } var r0 error - if rf, ok := ret.Get(0).(func(*flow.TransactionBody) error); ok { - r0 = rf(tx) + if returnFunc, ok := ret.Get(0).(func(*flow.TransactionBody) error); ok { + r0 = returnFunc(tx) } else { r0 = ret.Error(0) } - return r0 } -// NewTransactions creates a new instance of Transactions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactions(t interface { - mock.TestingT - Cleanup(func()) -}) *Transactions { - mock := &Transactions{} - mock.Mock.Test(t) +// Transactions_Store_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Store' +type Transactions_Store_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Store is a helper method to define mock.On call +// - tx *flow.TransactionBody +func (_e *Transactions_Expecter) Store(tx interface{}) *Transactions_Store_Call { + return &Transactions_Store_Call{Call: _e.mock.On("Store", tx)} +} - return mock +func (_c *Transactions_Store_Call) Run(run func(tx *flow.TransactionBody)) *Transactions_Store_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 *flow.TransactionBody + if args[0] != nil { + arg0 = args[0].(*flow.TransactionBody) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Transactions_Store_Call) Return(err error) *Transactions_Store_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Transactions_Store_Call) RunAndReturn(run func(tx *flow.TransactionBody) error) *Transactions_Store_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/transactions_reader.go b/storage/mock/transactions_reader.go index d14c0ef05e3..fe2ddc89c5c 100644 --- a/storage/mock/transactions_reader.go +++ b/storage/mock/transactions_reader.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewTransactionsReader creates a new instance of TransactionsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionsReader(t interface { + mock.TestingT + Cleanup(func()) +}) *TransactionsReader { + mock := &TransactionsReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // TransactionsReader is an autogenerated mock type for the TransactionsReader type type TransactionsReader struct { mock.Mock } -// ByID provides a mock function with given fields: txID -func (_m *TransactionsReader) ByID(txID flow.Identifier) (*flow.TransactionBody, error) { - ret := _m.Called(txID) +type TransactionsReader_Expecter struct { + mock *mock.Mock +} + +func (_m *TransactionsReader) EXPECT() *TransactionsReader_Expecter { + return &TransactionsReader_Expecter{mock: &_m.Mock} +} + +// ByID provides a mock function for the type TransactionsReader +func (_mock *TransactionsReader) ByID(txID flow.Identifier) (*flow.TransactionBody, error) { + ret := _mock.Called(txID) if len(ret) == 0 { panic("no return value specified for ByID") @@ -22,36 +46,54 @@ func (_m *TransactionsReader) ByID(txID flow.Identifier) (*flow.TransactionBody, var r0 *flow.TransactionBody var r1 error - if rf, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionBody, error)); ok { - return rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) (*flow.TransactionBody, error)); ok { + return returnFunc(txID) } - if rf, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionBody); ok { - r0 = rf(txID) + if returnFunc, ok := ret.Get(0).(func(flow.Identifier) *flow.TransactionBody); ok { + r0 = returnFunc(txID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.TransactionBody) } } - - if rf, ok := ret.Get(1).(func(flow.Identifier) error); ok { - r1 = rf(txID) + if returnFunc, ok := ret.Get(1).(func(flow.Identifier) error); ok { + r1 = returnFunc(txID) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewTransactionsReader creates a new instance of TransactionsReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewTransactionsReader(t interface { - mock.TestingT - Cleanup(func()) -}) *TransactionsReader { - mock := &TransactionsReader{} - mock.Mock.Test(t) +// TransactionsReader_ByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ByID' +type TransactionsReader_ByID_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// ByID is a helper method to define mock.On call +// - txID flow.Identifier +func (_e *TransactionsReader_Expecter) ByID(txID interface{}) *TransactionsReader_ByID_Call { + return &TransactionsReader_ByID_Call{Call: _e.mock.On("ByID", txID)} +} - return mock +func (_c *TransactionsReader_ByID_Call) Run(run func(txID flow.Identifier)) *TransactionsReader_ByID_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 flow.Identifier + if args[0] != nil { + arg0 = args[0].(flow.Identifier) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *TransactionsReader_ByID_Call) Return(transactionBody *flow.TransactionBody, err error) *TransactionsReader_ByID_Call { + _c.Call.Return(transactionBody, err) + return _c +} + +func (_c *TransactionsReader_ByID_Call) RunAndReturn(run func(txID flow.Identifier) (*flow.TransactionBody, error)) *TransactionsReader_ByID_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/version_beacons.go b/storage/mock/version_beacons.go index 7219f130a6c..0935f2d234e 100644 --- a/storage/mock/version_beacons.go +++ b/storage/mock/version_beacons.go @@ -1,20 +1,44 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - flow "github.com/onflow/flow-go/model/flow" + "github.com/onflow/flow-go/model/flow" mock "github.com/stretchr/testify/mock" ) +// NewVersionBeacons creates a new instance of VersionBeacons. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVersionBeacons(t interface { + mock.TestingT + Cleanup(func()) +}) *VersionBeacons { + mock := &VersionBeacons{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // VersionBeacons is an autogenerated mock type for the VersionBeacons type type VersionBeacons struct { mock.Mock } -// Highest provides a mock function with given fields: belowOrEqualTo -func (_m *VersionBeacons) Highest(belowOrEqualTo uint64) (*flow.SealedVersionBeacon, error) { - ret := _m.Called(belowOrEqualTo) +type VersionBeacons_Expecter struct { + mock *mock.Mock +} + +func (_m *VersionBeacons) EXPECT() *VersionBeacons_Expecter { + return &VersionBeacons_Expecter{mock: &_m.Mock} +} + +// Highest provides a mock function for the type VersionBeacons +func (_mock *VersionBeacons) Highest(belowOrEqualTo uint64) (*flow.SealedVersionBeacon, error) { + ret := _mock.Called(belowOrEqualTo) if len(ret) == 0 { panic("no return value specified for Highest") @@ -22,36 +46,54 @@ func (_m *VersionBeacons) Highest(belowOrEqualTo uint64) (*flow.SealedVersionBea var r0 *flow.SealedVersionBeacon var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*flow.SealedVersionBeacon, error)); ok { - return rf(belowOrEqualTo) + if returnFunc, ok := ret.Get(0).(func(uint64) (*flow.SealedVersionBeacon, error)); ok { + return returnFunc(belowOrEqualTo) } - if rf, ok := ret.Get(0).(func(uint64) *flow.SealedVersionBeacon); ok { - r0 = rf(belowOrEqualTo) + if returnFunc, ok := ret.Get(0).(func(uint64) *flow.SealedVersionBeacon); ok { + r0 = returnFunc(belowOrEqualTo) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*flow.SealedVersionBeacon) } } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(belowOrEqualTo) + if returnFunc, ok := ret.Get(1).(func(uint64) error); ok { + r1 = returnFunc(belowOrEqualTo) } else { r1 = ret.Error(1) } - return r0, r1 } -// NewVersionBeacons creates a new instance of VersionBeacons. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewVersionBeacons(t interface { - mock.TestingT - Cleanup(func()) -}) *VersionBeacons { - mock := &VersionBeacons{} - mock.Mock.Test(t) +// VersionBeacons_Highest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Highest' +type VersionBeacons_Highest_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Highest is a helper method to define mock.On call +// - belowOrEqualTo uint64 +func (_e *VersionBeacons_Expecter) Highest(belowOrEqualTo interface{}) *VersionBeacons_Highest_Call { + return &VersionBeacons_Highest_Call{Call: _e.mock.On("Highest", belowOrEqualTo)} +} - return mock +func (_c *VersionBeacons_Highest_Call) Run(run func(belowOrEqualTo uint64)) *VersionBeacons_Highest_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 uint64 + if args[0] != nil { + arg0 = args[0].(uint64) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *VersionBeacons_Highest_Call) Return(sealedVersionBeacon *flow.SealedVersionBeacon, err error) *VersionBeacons_Highest_Call { + _c.Call.Return(sealedVersionBeacon, err) + return _c +} + +func (_c *VersionBeacons_Highest_Call) RunAndReturn(run func(belowOrEqualTo uint64) (*flow.SealedVersionBeacon, error)) *VersionBeacons_Highest_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/mock/writer.go b/storage/mock/writer.go index 55cf24ad9e8..6bc864f157d 100644 --- a/storage/mock/writer.go +++ b/storage/mock/writer.go @@ -1,81 +1,208 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify package mock import ( - storage "github.com/onflow/flow-go/storage" + "github.com/onflow/flow-go/storage" mock "github.com/stretchr/testify/mock" ) +// NewWriter creates a new instance of Writer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewWriter(t interface { + mock.TestingT + Cleanup(func()) +}) *Writer { + mock := &Writer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} + // Writer is an autogenerated mock type for the Writer type type Writer struct { mock.Mock } -// Delete provides a mock function with given fields: key -func (_m *Writer) Delete(key []byte) error { - ret := _m.Called(key) +type Writer_Expecter struct { + mock *mock.Mock +} + +func (_m *Writer) EXPECT() *Writer_Expecter { + return &Writer_Expecter{mock: &_m.Mock} +} + +// Delete provides a mock function for the type Writer +func (_mock *Writer) Delete(key []byte) error { + ret := _mock.Called(key) if len(ret) == 0 { panic("no return value specified for Delete") } var r0 error - if rf, ok := ret.Get(0).(func([]byte) error); ok { - r0 = rf(key) + if returnFunc, ok := ret.Get(0).(func([]byte) error); ok { + r0 = returnFunc(key) } else { r0 = ret.Error(0) } - return r0 } -// DeleteByRange provides a mock function with given fields: globalReader, startPrefix, endPrefix -func (_m *Writer) DeleteByRange(globalReader storage.Reader, startPrefix []byte, endPrefix []byte) error { - ret := _m.Called(globalReader, startPrefix, endPrefix) +// Writer_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete' +type Writer_Delete_Call struct { + *mock.Call +} + +// Delete is a helper method to define mock.On call +// - key []byte +func (_e *Writer_Expecter) Delete(key interface{}) *Writer_Delete_Call { + return &Writer_Delete_Call{Call: _e.mock.On("Delete", key)} +} + +func (_c *Writer_Delete_Call) Run(run func(key []byte)) *Writer_Delete_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + run( + arg0, + ) + }) + return _c +} + +func (_c *Writer_Delete_Call) Return(err error) *Writer_Delete_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Writer_Delete_Call) RunAndReturn(run func(key []byte) error) *Writer_Delete_Call { + _c.Call.Return(run) + return _c +} + +// DeleteByRange provides a mock function for the type Writer +func (_mock *Writer) DeleteByRange(globalReader storage.Reader, startPrefix []byte, endPrefix []byte) error { + ret := _mock.Called(globalReader, startPrefix, endPrefix) if len(ret) == 0 { panic("no return value specified for DeleteByRange") } var r0 error - if rf, ok := ret.Get(0).(func(storage.Reader, []byte, []byte) error); ok { - r0 = rf(globalReader, startPrefix, endPrefix) + if returnFunc, ok := ret.Get(0).(func(storage.Reader, []byte, []byte) error); ok { + r0 = returnFunc(globalReader, startPrefix, endPrefix) } else { r0 = ret.Error(0) } - return r0 } -// Set provides a mock function with given fields: k, v -func (_m *Writer) Set(k []byte, v []byte) error { - ret := _m.Called(k, v) +// Writer_DeleteByRange_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteByRange' +type Writer_DeleteByRange_Call struct { + *mock.Call +} + +// DeleteByRange is a helper method to define mock.On call +// - globalReader storage.Reader +// - startPrefix []byte +// - endPrefix []byte +func (_e *Writer_Expecter) DeleteByRange(globalReader interface{}, startPrefix interface{}, endPrefix interface{}) *Writer_DeleteByRange_Call { + return &Writer_DeleteByRange_Call{Call: _e.mock.On("DeleteByRange", globalReader, startPrefix, endPrefix)} +} + +func (_c *Writer_DeleteByRange_Call) Run(run func(globalReader storage.Reader, startPrefix []byte, endPrefix []byte)) *Writer_DeleteByRange_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 storage.Reader + if args[0] != nil { + arg0 = args[0].(storage.Reader) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + var arg2 []byte + if args[2] != nil { + arg2 = args[2].([]byte) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Writer_DeleteByRange_Call) Return(err error) *Writer_DeleteByRange_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Writer_DeleteByRange_Call) RunAndReturn(run func(globalReader storage.Reader, startPrefix []byte, endPrefix []byte) error) *Writer_DeleteByRange_Call { + _c.Call.Return(run) + return _c +} + +// Set provides a mock function for the type Writer +func (_mock *Writer) Set(k []byte, v []byte) error { + ret := _mock.Called(k, v) if len(ret) == 0 { panic("no return value specified for Set") } var r0 error - if rf, ok := ret.Get(0).(func([]byte, []byte) error); ok { - r0 = rf(k, v) + if returnFunc, ok := ret.Get(0).(func([]byte, []byte) error); ok { + r0 = returnFunc(k, v) } else { r0 = ret.Error(0) } - return r0 } -// NewWriter creates a new instance of Writer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewWriter(t interface { - mock.TestingT - Cleanup(func()) -}) *Writer { - mock := &Writer{} - mock.Mock.Test(t) +// Writer_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set' +type Writer_Set_Call struct { + *mock.Call +} - t.Cleanup(func() { mock.AssertExpectations(t) }) +// Set is a helper method to define mock.On call +// - k []byte +// - v []byte +func (_e *Writer_Expecter) Set(k interface{}, v interface{}) *Writer_Set_Call { + return &Writer_Set_Call{Call: _e.mock.On("Set", k, v)} +} - return mock +func (_c *Writer_Set_Call) Run(run func(k []byte, v []byte)) *Writer_Set_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 []byte + if args[0] != nil { + arg0 = args[0].([]byte) + } + var arg1 []byte + if args[1] != nil { + arg1 = args[1].([]byte) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *Writer_Set_Call) Return(err error) *Writer_Set_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Writer_Set_Call) RunAndReturn(run func(k []byte, v []byte) error) *Writer_Set_Call { + _c.Call.Return(run) + return _c } diff --git a/storage/operation/children.go b/storage/operation/children.go index 6d1f757d176..28a5ed58909 100644 --- a/storage/operation/children.go +++ b/storage/operation/children.go @@ -3,6 +3,7 @@ package operation import ( "errors" "fmt" + "slices" "github.com/jordanschalm/lockctx" @@ -63,10 +64,8 @@ func indexBlockByParent(rw storage.ReaderBatchWriter, blockID flow.Identifier, p } // check we don't add a duplicate - for _, dupID := range childrenIDs { - if blockID == dupID { - return storage.ErrAlreadyExists - } + if slices.Contains(childrenIDs, blockID) { + return storage.ErrAlreadyExists } // adding the new block to be another child of the parent diff --git a/storage/operation/codec.go b/storage/operation/codec.go index 43dc4c37f7a..258f0feb7cc 100644 --- a/storage/operation/codec.go +++ b/storage/operation/codec.go @@ -8,7 +8,7 @@ import ( ) // EncodeKeyPart encodes a value to be used as a part of a key to be stored in storage. -func EncodeKeyPart(v interface{}) []byte { +func EncodeKeyPart(v any) []byte { switch i := v.(type) { case uint8: return []byte{i} diff --git a/storage/operation/reads.go b/storage/operation/reads.go index 9bf9c60197d..aeb8cb2e730 100644 --- a/storage/operation/reads.go +++ b/storage/operation/reads.go @@ -106,8 +106,7 @@ func KeyOnlyIterateFunc(fn func(key []byte) error) IterationFunc { } // KeyExists returns true if a key exists in the database. -// When this returned function is executed (and only then), it will write into the `keyExists` whether -// the key exists. +// // No errors are expected during normal operation. func KeyExists(r storage.Reader, key []byte) (exist bool, errToReturn error) { _, closer, err := r.Get(key) @@ -127,6 +126,31 @@ func KeyExists(r storage.Reader, key []byte) (exist bool, errToReturn error) { return true, nil } +// PrefixExists returns true if at least one key with the provided prefix exists in the database. +// This is distinct from KeyExists which checks for an exact key match. +// +// No errors are expected during normal operation. +func PrefixExists(r storage.Reader, prefix []byte, opt storage.IteratorOption) (exist bool, errToReturn error) { + if len(prefix) == 0 { + return false, fmt.Errorf("prefix must not be empty") + } + + iter, err := r.NewIter(prefix, prefix, opt) + if err != nil { + return false, fmt.Errorf("can not create iterator: %w", err) + } + defer func() { + errToReturn = merr.CloseAndMergeError(iter, errToReturn) + }() + + // First returns true if it finds a valid key with the given prefix, otherwise it returns false. + if iter.First() { + return true, nil + } + + return false, nil +} + // RetrieveByKey will retrieve the binary data under the given key from the database // and decode it into the given entity. The provided entity needs to be a // pointer to an initialized entity of the correct type. diff --git a/storage/operation/reads_functors.go b/storage/operation/reads_functors.go index dace2e9ec02..3b897d8c83b 100644 --- a/storage/operation/reads_functors.go +++ b/storage/operation/reads_functors.go @@ -20,7 +20,7 @@ func Traverse(prefix []byte, iterFunc IterationFunc, opt storage.IteratorOption) } } -func Retrieve(key []byte, entity interface{}) func(storage.Reader) error { +func Retrieve(key []byte, entity any) func(storage.Reader) error { return func(r storage.Reader) error { return RetrieveByKey(r, key, entity) } @@ -37,7 +37,7 @@ func Exists(key []byte, keyExists *bool) func(storage.Reader) error { } } -func FindHighestAtOrBelow(prefix []byte, height uint64, entity interface{}) func(storage.Reader) error { +func FindHighestAtOrBelow(prefix []byte, height uint64, entity any) func(storage.Reader) error { return func(r storage.Reader) error { return FindHighestAtOrBelowByPrefix(r, prefix, height, entity) } diff --git a/storage/operation/reads_test.go b/storage/operation/reads_test.go index 78a4d51024e..506fb5c2fee 100644 --- a/storage/operation/reads_test.go +++ b/storage/operation/reads_test.go @@ -408,6 +408,42 @@ func TestFindHighestAtOrBelow(t *testing.T) { }) } +func TestPrefixExists(t *testing.T) { + dbtest.RunWithStorages(t, func(t *testing.T, r storage.Reader, withWriter dbtest.WithWriter) { + // Empty prefix should return an error. + _, err := operation.PrefixExists(r, []byte{}, storage.DefaultIteratorOptions()) + require.Error(t, err) + + prefix := []byte{0x10, 0x20} + + // No keys with the prefix exist yet. + exists, err := operation.PrefixExists(r, prefix, storage.DefaultIteratorOptions()) + require.NoError(t, err) + require.False(t, exists) + + // Insert a key with the prefix. + require.NoError(t, withWriter(func(writer storage.Writer) error { + return operation.Upsert(append(prefix, 0x03), []byte{0x00})(writer) + })) + + // The key exists for the prefix should fail + exists, err = operation.KeyExists(r, prefix) + require.NoError(t, err) + require.False(t, exists) + + // The prefix should now be found. + exists, err = operation.PrefixExists(r, prefix, storage.DefaultIteratorOptions()) + require.NoError(t, err) + require.True(t, exists) + + // A different prefix should not be found. + differentPrefix := []byte{0x10, 0x30} + exists, err = operation.PrefixExists(r, differentPrefix, storage.DefaultIteratorOptions()) + require.NoError(t, err) + require.False(t, exists) + }) +} + func TestCommonPrefix(t *testing.T) { testCases := []struct { name string diff --git a/storage/operation/stats.go b/storage/operation/stats.go index e72b35b3e22..9226cb41cf3 100644 --- a/storage/operation/stats.go +++ b/storage/operation/stats.go @@ -42,10 +42,8 @@ func SummarizeKeysByFirstByteConcurrent(log zerolog.Logger, r storage.Reader, nW defer cancel() // Start nWorker goroutines. - for i := 0; i < nWorker; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range nWorker { + wg.Go(func() { for { select { case <-ctx.Done(): @@ -67,7 +65,7 @@ func SummarizeKeysByFirstByteConcurrent(log zerolog.Logger, r storage.Reader, nW } } } - }() + }) } progress := util.LogProgress(log, @@ -77,7 +75,7 @@ func SummarizeKeysByFirstByteConcurrent(log zerolog.Logger, r storage.Reader, nW )) // Send all prefixes [0..255] to taskChan. - for p := 0; p < 256; p++ { + for p := range 256 { taskChan <- byte(p) } close(taskChan) diff --git a/storage/operation/transaction_results.go b/storage/operation/transaction_results.go index 4cfac1c7b42..1b7cbbafc91 100644 --- a/storage/operation/transaction_results.go +++ b/storage/operation/transaction_results.go @@ -226,7 +226,7 @@ func RetrieveTransactionResultErrorMessageByIndex(r storage.Reader, blockID flow // TransactionResultErrorMessagesExists checks whether tx result error messages exist in the database. // No error returns are expected during normal operations. func TransactionResultErrorMessagesExists(r storage.Reader, blockID flow.Identifier, blockExists *bool) error { - exists, err := KeyExists(r, MakePrefix(codeTransactionResultErrorMessageIndex, blockID)) + exists, err := PrefixExists(r, MakePrefix(codeTransactionResultErrorMessageIndex, blockID), storage.DefaultIteratorOptions()) if err != nil { return err } diff --git a/storage/operation/transaction_results_test.go b/storage/operation/transaction_results_test.go index c90bc219780..c022dcf0b53 100644 --- a/storage/operation/transaction_results_test.go +++ b/storage/operation/transaction_results_test.go @@ -227,3 +227,128 @@ func TestRetrieveAllTxResultsForBlock(t *testing.T) { }) }) } + +// TestInsertAndIndexTransactionResultErrorMessages verifies that error messages can be inserted, +// retrieved by transaction ID and index, and that duplicate inserts are rejected. +func TestInsertAndIndexTransactionResultErrorMessages(t *testing.T) { + t.Run("happy path", func(t *testing.T) { + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + lockManager := storage.NewTestingLockManager() + blockID := unittest.IdentifierFixture() + errorMessages := unittest.TransactionResultErrorMessagesFixture(3) + + err := unittest.WithLock(t, lockManager, storage.LockInsertTransactionResultErrMessage, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.InsertAndIndexTransactionResultErrorMessages(lctx, rw, blockID, errorMessages) + }) + }) + require.NoError(t, err) + + // Verify retrieval by transaction ID. + for _, expected := range errorMessages { + var actual flow.TransactionResultErrorMessage + err = operation.RetrieveTransactionResultErrorMessage(db.Reader(), blockID, expected.TransactionID, &actual) + require.NoError(t, err) + assert.Equal(t, expected, actual) + } + + // Verify retrieval by index. + for i, expected := range errorMessages { + var actual flow.TransactionResultErrorMessage + err = operation.RetrieveTransactionResultErrorMessageByIndex(db.Reader(), blockID, uint32(i), &actual) + require.NoError(t, err) + assert.Equal(t, expected, actual) + } + + // Verify bulk retrieval. + var retrieved []flow.TransactionResultErrorMessage + err = operation.LookupTransactionResultErrorMessagesByBlockIDUsingIndex(db.Reader(), blockID, &retrieved) + require.NoError(t, err) + assert.Equal(t, errorMessages, retrieved) + }) + }) + + t.Run("returns ErrAlreadyExists on duplicate insert", func(t *testing.T) { + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + lockManager := storage.NewTestingLockManager() + blockID := unittest.IdentifierFixture() + errorMessages := unittest.TransactionResultErrorMessagesFixture(1) + + insert := func() error { + return unittest.WithLock(t, lockManager, storage.LockInsertTransactionResultErrMessage, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.InsertAndIndexTransactionResultErrorMessages(lctx, rw, blockID, errorMessages) + }) + }) + } + + err := insert() + require.NoError(t, err) + + err = insert() + require.ErrorIs(t, err, storage.ErrAlreadyExists) + + // Verify that the original error messages are still there and unchanged + for _, expected := range errorMessages { + var actual flow.TransactionResultErrorMessage + err = operation.RetrieveTransactionResultErrorMessage(db.Reader(), blockID, expected.TransactionID, &actual) + require.NoError(t, err) + assert.Equal(t, expected, actual) + } + }) + }) +} + +// TestTransactionResultErrorMessagesExists verifies the existence check for tx result error messages. +func TestTransactionResultErrorMessagesExists(t *testing.T) { + t.Run("returns false for unknown block", func(t *testing.T) { + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + blockID := unittest.IdentifierFixture() + var exists bool + err := operation.TransactionResultErrorMessagesExists(db.Reader(), blockID, &exists) + require.NoError(t, err) + require.False(t, exists) + }) + }) + + t.Run("returns true after inserting error messages", func(t *testing.T) { + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + lockManager := storage.NewTestingLockManager() + blockID := unittest.IdentifierFixture() + errorMessages := unittest.TransactionResultErrorMessagesFixture(2) + + err := unittest.WithLock(t, lockManager, storage.LockInsertTransactionResultErrMessage, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.InsertAndIndexTransactionResultErrorMessages(lctx, rw, blockID, errorMessages) + }) + }) + require.NoError(t, err) + + var exists bool + err = operation.TransactionResultErrorMessagesExists(db.Reader(), blockID, &exists) + require.NoError(t, err) + require.True(t, exists) + }) + }) + + t.Run("returns false for a different block", func(t *testing.T) { + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + lockManager := storage.NewTestingLockManager() + blockID := unittest.IdentifierFixture() + otherBlockID := unittest.IdentifierFixture() + errorMessages := unittest.TransactionResultErrorMessagesFixture(1) + + err := unittest.WithLock(t, lockManager, storage.LockInsertTransactionResultErrMessage, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return operation.InsertAndIndexTransactionResultErrorMessages(lctx, rw, blockID, errorMessages) + }) + }) + require.NoError(t, err) + + var exists bool + err = operation.TransactionResultErrorMessagesExists(db.Reader(), otherBlockID, &exists) + require.NoError(t, err) + require.False(t, exists) + }) + }) +} diff --git a/storage/operation/writes.go b/storage/operation/writes.go index 920cc232d3d..8e87a011b08 100644 --- a/storage/operation/writes.go +++ b/storage/operation/writes.go @@ -16,7 +16,7 @@ import ( // Error returns: // - generic error in case of unexpected failure from the database layer or // encoding failure. -func UpsertByKey(w storage.Writer, key []byte, val interface{}) error { +func UpsertByKey(w storage.Writer, key []byte, val any) error { value, err := msgpack.Marshal(val) if err != nil { return irrecoverable.NewExceptionf("failed to encode value: %w", err) @@ -32,7 +32,7 @@ func UpsertByKey(w storage.Writer, key []byte, val interface{}) error { // Upserting returns a functor, whose execution will append the given key-value-pair to the provided // storage writer (typically a pending batch of database writes). -func Upserting(key []byte, val interface{}) func(storage.Writer) error { +func Upserting(key []byte, val any) func(storage.Writer) error { value, err := msgpack.Marshal(val) return func(w storage.Writer) error { if err != nil { diff --git a/storage/operation/writes_functors.go b/storage/operation/writes_functors.go index 1ee182d040b..abe0142f6ba 100644 --- a/storage/operation/writes_functors.go +++ b/storage/operation/writes_functors.go @@ -8,7 +8,7 @@ import "github.com/onflow/flow-go/storage" // Using these deprecated functions could minimize the changes during refactor and easier to review the changes. // The simplified implementation of the functions are in the writes.go file, which are encouraged to be used instead. -func Upsert(key []byte, val interface{}) func(storage.Writer) error { +func Upsert(key []byte, val any) func(storage.Writer) error { return func(w storage.Writer) error { return UpsertByKey(w, key, val) } diff --git a/storage/operations.go b/storage/operations.go index 0950bfc00aa..8bf2fcd44a3 100644 --- a/storage/operations.go +++ b/storage/operations.go @@ -1,6 +1,7 @@ package storage import ( + "bytes" "io" ) @@ -275,3 +276,37 @@ func PrefixUpperBound(prefix []byte) []byte { } return nil // no upper-bound } + +// PrefixInclusiveEnd returns the inclusive upper bound for iterating over keys with `prefix`. +// +// Consider iterating over keys with format [code][address][height][txIndex] for a specific address. +// A simple full-range scan uses [code][address] as both the lower and upper prefix bounds. +// +// Resumable iteration introduces a complication: resuming from a saved position requires a start +// key of [code][address][lastHeight][lastTxIndex+1]. The bare prefix [code][address] cannot serve +// as the end bound in this case — it is lexicographically less than the resume start key, so an +// iterator with that range would return no entries. +// +// The correct end bound is [code][address] padded with 0xff bytes to the full key length, i.e., +// [code][address][maxHeight][maxTxIndex]. This is the lexicographically largest key sharing the given +// prefix and key length, and is always greater than any valid key in the namespace. +// +// PrefixInclusiveEnd produces exactly this: a byte slice that begins with `prefix` and is +// padded with 0xff bytes to match the length of `start`. +// +// If len(prefix) > len(start), the returned prefix will be the first `len(start)` bytes of the prefix. +func PrefixInclusiveEnd(prefix, start []byte) []byte { + // if prefix is already greater than start, then no padding is needed + if bytes.Compare(start, prefix) <= 0 { + return prefix + } + + end := make([]byte, len(start)) + copy(end, prefix) + + // pad up to the length of start + for i := len(prefix); i < len(end); i++ { + end[i] = 0xff + } + return end +} diff --git a/storage/operations_test.go b/storage/operations_test.go new file mode 100644 index 00000000000..80c61ee4c79 --- /dev/null +++ b/storage/operations_test.go @@ -0,0 +1,98 @@ +package storage_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/onflow/flow-go/storage" +) + +func TestPrefixInclusiveEnd(t *testing.T) { + tests := []struct { + name string + prefix []byte + start []byte + expected []byte + }{ + { + name: "pads remaining bytes with 0xff", + prefix: []byte{0x01}, + start: []byte{0x01, 0x02, 0x03}, + expected: []byte{0x01, 0xff, 0xff}, + }, + { + name: "multi-byte prefix pads remaining bytes", + prefix: []byte{0x01, 0x02}, + start: []byte{0x01, 0x02, 0x03, 0x04}, + expected: []byte{0x01, 0x02, 0xff, 0xff}, + }, + { + name: "start same length as prefix - no padding added", + prefix: []byte{0x01, 0x02}, + start: []byte{0x01, 0x02}, + expected: []byte{0x01, 0x02}, + }, + { + name: "start bytes after prefix are replaced regardless of value", + prefix: []byte{0x01}, + start: []byte{0x01, 0x00}, + expected: []byte{0x01, 0xff}, + }, + { + // A shorter start is lexicographically less than prefix, so prefix is returned directly. + name: "start shorter than prefix - prefix returned directly", + prefix: []byte{0x01, 0x02, 0x03}, + start: []byte{0x01, 0x02}, + expected: []byte{0x01, 0x02, 0x03}, + }, + { + // start is lexicographically before prefix, so prefix is already beyond start - no padding needed. + name: "start lexicographically before prefix - prefix returned directly", + prefix: []byte{0x05}, + start: []byte{0x03, 0x04}, + expected: []byte{0x05}, + }, + { + // start content is entirely replaced by prefix + 0xff padding. + name: "start lexicographically after prefix - content ignored", + prefix: []byte{0x01}, + start: []byte{0x08, 0x09}, + expected: []byte{0x01, 0xff}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := storage.PrefixInclusiveEnd(tt.prefix, tt.start) + assert.Equal(t, tt.expected, result) + + // When start is within or past the prefix namespace, result must start with prefix + // and be padded to len(start). + if len(tt.start) >= len(tt.prefix) && string(tt.start) >= string(tt.prefix) { + assert.Len(t, result, len(tt.start)) + assert.Equal(t, tt.prefix, result[:len(tt.prefix)]) + } + }) + } +} + +// TestPrefixInclusiveEnd_GreaterThanAnyKeyWithPrefix verifies that the result is +// always >= any key of the same length that starts with basePrefix. +func TestPrefixInclusiveEnd_GreaterThanAnyKeyWithPrefix(t *testing.T) { + basePrefix := []byte{0x01, 0x02} + start := []byte{0x01, 0x02, 0x10, 0x20} // a mid-range start key + + end := storage.PrefixInclusiveEnd(basePrefix, start) + + // Any key of len(start) starting with basePrefix must sort <= end. + candidates := [][]byte{ + {0x01, 0x02, 0x00, 0x00}, + {0x01, 0x02, 0x10, 0x20}, + {0x01, 0x02, 0xff, 0xfe}, + } + for _, key := range candidates { + assert.True(t, string(key) <= string(end), + "expected key %x <= end %x", key, end) + } +} diff --git a/storage/pebble/lookup.go b/storage/pebble/lookup.go index d0059abf2c2..a8607fab1a0 100644 --- a/storage/pebble/lookup.go +++ b/storage/pebble/lookup.go @@ -27,6 +27,10 @@ type lookupKey struct { } // newLookupKey takes a height and registerID, returns the key for storing the register value in storage +// +// Lookup keys are encoded as follows: +// [codeRegister(1)] [owner] '/' [key] '/' [height(8)] +// owner and key are variable length fields func newLookupKey(height uint64, reg flow.RegisterID) *lookupKey { key := lookupKey{ // 1 byte gaps for db prefix and '/' separators @@ -64,51 +68,52 @@ func newLookupKey(height uint64, reg flow.RegisterID) *lookupKey { // lookupKeyToRegisterID takes a lookup key and decode it into height and RegisterID func lookupKeyToRegisterID(lookupKey []byte) (uint64, flow.RegisterID, error) { if len(lookupKey) < MinLookupKeyLen { - return 0, flow.RegisterID{}, fmt.Errorf("invalid lookup key format: expected >= %d bytes, got %d bytes", - MinLookupKeyLen, len(lookupKey)) + return 0, flow.RegisterID{}, + fmt.Errorf("invalid lookup key format: expected >= %d bytes, got %d bytes", MinLookupKeyLen, len(lookupKey)) } - // check and exclude db prefix + // 1. Check and exclude db prefix prefix := lookupKey[0] if prefix != codeRegister { - return 0, flow.RegisterID{}, fmt.Errorf("incorrect prefix %d for register lookup key, expected %d", - prefix, codeRegister) + return 0, flow.RegisterID{}, fmt.Errorf("invalid lookup key format: incorrect prefix %d for register lookup key, expected %d", prefix, codeRegister) } lookupKey = lookupKey[1:] - // Find the first slash to split the lookup key and decode the owner. - firstSlash := bytes.IndexByte(lookupKey, '/') - if firstSlash == -1 { - return 0, flow.RegisterID{}, fmt.Errorf("invalid lookup key format: cannot find first slash") - } - - owner := string(lookupKey[:firstSlash]) - - // Find the last slash to split encoded height. - lastSlashPos := bytes.LastIndexByte(lookupKey, '/') - if lastSlashPos == firstSlash { - return 0, flow.RegisterID{}, fmt.Errorf("invalid lookup key format: expected 2 separators, got 1 separator") - } - encodedHeightPos := lastSlashPos + 1 - if len(lookupKey)-encodedHeightPos != registers.HeightSuffixLen { + // 2. Get the height from the end of the key, and remove the trailing separator + // + // The height is always exactly HeightSuffixLen bytes at the end of the key. The separator + // before the height is therefore always at len(lookupKey) - HeightSuffixLen - 1. We compute + // it directly rather than searching for the last '/', because the one's complement height + // encoding can contain 0x2F ('/') bytes, which would cause a backward search to find the + // wrong separator. + heightPos := len(lookupKey) - registers.HeightSuffixLen + + if lookupKey[heightPos-1] != '/' { return 0, flow.RegisterID{}, - fmt.Errorf("invalid lookup key format: expected %d bytes of encoded height, got %d bytes", - registers.HeightSuffixLen, len(lookupKey)-encodedHeightPos) + fmt.Errorf("invalid lookup key format: expected '/' separator at position %d, got %x", heightPos-1, lookupKey[heightPos-1]) } - // Decode height. - heightBytes := lookupKey[encodedHeightPos:] + heightBytes := lookupKey[heightPos:] oneCompliment := binary.BigEndian.Uint64(heightBytes) height := ^oneCompliment - // Decode the remaining bytes into the key. - keyBytes := lookupKey[firstSlash+1 : lastSlashPos] - key := string(keyBytes) + lookupKey = lookupKey[:heightPos-1] // remove the trailing separator and height + + // 3. Get the owner and key + // + // we do this by getting everything before the first '/'. since the last '/' was already removed, + // all that's left is the key. + var found bool + ownerBytes, keyBytes, found := bytes.Cut(lookupKey, []byte("/")) + if !found { + return 0, flow.RegisterID{}, fmt.Errorf("invalid lookup key format: cannot find first slash") + } - regID := flow.RegisterID{Owner: owner, Key: key} + owner := string(ownerBytes) + key := string(keyBytes) - return height, regID, nil + return height, flow.RegisterID{Owner: owner, Key: key}, nil } // Bytes returns the encoded lookup key. diff --git a/storage/pebble/lookup_test.go b/storage/pebble/lookup_test.go index 383fd995490..7cb365000c7 100644 --- a/storage/pebble/lookup_test.go +++ b/storage/pebble/lookup_test.go @@ -10,99 +10,173 @@ import ( "github.com/onflow/flow-go/model/flow" ) -// Test_lookupKey_Bytes tests the lookup key encoding. +// Test_lookupKey_Bytes tests the lookup key encoding format, including the exact byte layout and +// a roundtrip decode. func Test_lookupKey_Bytes(t *testing.T) { t.Parallel() - expectedHeight := uint64(777) - key := newLookupKey(expectedHeight, flow.RegisterID{Owner: "owner", Key: "key"}) - - // Test prefix - require.Equal(t, byte(codeRegister), key.Bytes()[0]) - - // Test encoded Owner and Key - require.Equal(t, []byte("owner/key/"), key.Bytes()[1:11]) - - // Test encoded height - actualHeight := binary.BigEndian.Uint64(key.Bytes()[11:]) - require.Equal(t, math.MaxUint64-actualHeight, expectedHeight) - - // Test everything together - resultLookupKey := []byte{codeRegister} - resultLookupKey = append(resultLookupKey, []byte("owner/key/\xff\xff\xff\xff\xff\xff\xfc\xf6")...) - require.Equal(t, resultLookupKey, key.Bytes()) - - decodedHeight, decodedReg, err := lookupKeyToRegisterID(key.encoded) - require.NoError(t, err) - - require.Equal(t, expectedHeight, decodedHeight) - require.Equal(t, "owner", decodedReg.Owner) - require.Equal(t, "key", decodedReg.Key) -} - -func Test_decodeKey_Bytes(t *testing.T) { - height := uint64(10) - cases := []struct { - owner string - key string + name string + height uint64 + owner string + key string + expectedBytes []byte }{ - {owner: "owneraddress", key: "public/storage/hasslash-in-key"}, - {owner: "owneraddress", key: ""}, - {owner: "", key: "somekey"}, - {owner: "", key: ""}, + { + name: "typical register at height 777", + height: 777, + owner: "owner", + key: "key", + // [codeRegister] + "owner/key/" + ^777 as big-endian uint64 + expectedBytes: append([]byte{codeRegister}, []byte("owner/key/\xff\xff\xff\xff\xff\xff\xfc\xf6")...), + }, + { + name: "height 0 encodes as all 0xff", + height: 0, + owner: "a", + key: "b", + // ^0 = MaxUint64 = 0xFFFFFFFFFFFFFFFF + expectedBytes: append([]byte{codeRegister}, []byte("a/b/\xff\xff\xff\xff\xff\xff\xff\xff")...), + }, + { + name: "max height encodes as all 0x00", + height: math.MaxUint64, + owner: "a", + key: "b", + // ^MaxUint64 = 0 + expectedBytes: append([]byte{codeRegister}, []byte("a/b/\x00\x00\x00\x00\x00\x00\x00\x00")...), + }, + { + name: "empty owner and key", + height: 777, + owner: "", + key: "", + // [codeRegister] + "//" + ^777 as big-endian uint64 + expectedBytes: append([]byte{codeRegister}, []byte("//\xff\xff\xff\xff\xff\xff\xfc\xf6")...), + }, } for _, c := range cases { - owner, key := c.owner, c.key - - lookupKey := newLookupKey(height, flow.RegisterID{Owner: owner, Key: key}) - decodedHeight, decodedReg, err := lookupKeyToRegisterID(lookupKey.Bytes()) - require.NoError(t, err) - - require.Equal(t, height, decodedHeight) - require.Equal(t, owner, decodedReg.Owner) - require.Equal(t, key, decodedReg.Key) + t.Run(c.name, func(t *testing.T) { + reg := flow.RegisterID{Owner: c.owner, Key: c.key} + encoded := newLookupKey(c.height, reg).Bytes() + + // prefix byte + require.Equal(t, byte(codeRegister), encoded[0]) + + // height is stored as one's complement (bits flipped) to enable forward iteration + // in reverse height order: MaxUint64 - storedValue == originalHeight + storedHeight := binary.BigEndian.Uint64(encoded[len(encoded)-8:]) + require.Equal(t, math.MaxUint64-storedHeight, c.height) + + // full encoding + require.Equal(t, c.expectedBytes, encoded) + + // roundtrip + decodedHeight, decodedReg, err := lookupKeyToRegisterID(encoded) + require.NoError(t, err) + require.Equal(t, c.height, decodedHeight) + require.Equal(t, c.owner, decodedReg.Owner) + require.Equal(t, c.key, decodedReg.Key) + }) } } -func Test_decodeKey_fail(t *testing.T) { - var err error - // less than min length (10) - _, _, err = lookupKeyToRegisterID([]byte{codeRegister, 1, 2, 3, 4, 5, 6, 7, 8, 9}) - require.Contains(t, err.Error(), "bytes") - - // missing slash - _, _, err = lookupKeyToRegisterID([]byte{codeRegister, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) - require.Contains(t, err.Error(), "slash") - - // missing second slash - _, _, err = lookupKeyToRegisterID([]byte{codeRegister, 1, 2, 3, '/', 5, 6, 7, 8, 9, 10}) - require.Contains(t, err.Error(), "separator") +// Test_decodeKey_roundtrip tests that encoding then decoding a lookup key reproduces the original +// values, including edge cases where the height encoding contains the separator byte 0x2F ('/'). +func Test_decodeKey_roundtrip(t *testing.T) { + // heightWith0x2FInEncoding is a height whose one's complement encoding contains 0x2F ('/'). + // ^208 = 0xFFFFFFFFFFFFFF2F, so the last byte of the height encoding is '/'. + // This was previously misinterpreted as the separator between key and height. + const heightWith0x2FInEncoding = uint64(208) - // invalid height - _, _, err = lookupKeyToRegisterID([]byte{codeRegister, 1, 2, 3, '/', 5, 6, 7, 8, '/', 10}) - require.Contains(t, err.Error(), "height") - - // invalid height - _, _, err = lookupKeyToRegisterID([]byte{codeRegister, 1, 2, 3, '/', 5, '/', 7, 8, 9, 10}) - require.Contains(t, err.Error(), "height") - - // invalid height - _, _, err = lookupKeyToRegisterID([]byte{codeRegister, 1, 2, 3, '/', 5, '/', 7, 8, 9, 10, 11, 12, 13}) - require.Contains(t, err.Error(), "height") + cases := []struct { + name string + height uint64 + owner string + key string + }{ + {name: "key with slash", height: 10, owner: "owneraddress", key: "public/storage/hasslash-in-key"}, + {name: "empty key", height: 10, owner: "owneraddress", key: ""}, + {name: "empty owner", height: 10, owner: "", key: "somekey"}, + {name: "empty owner and key", height: 10, owner: "", key: ""}, + // Heights whose one's complement encoding contains 0x2F ('/'). These previously caused + // lookupKeyToRegisterID to misidentify the separator between key and height. + {name: "0x2F in height encoding: with owner and key", height: heightWith0x2FInEncoding, owner: "owneraddress", key: "code.Token"}, + {name: "0x2F in height encoding: empty key", height: heightWith0x2FInEncoding, owner: "owneraddress", key: ""}, + {name: "0x2F in height encoding: empty owner", height: heightWith0x2FInEncoding, owner: "", key: "code.Token"}, + } - // valid height - _, _, err = lookupKeyToRegisterID([]byte{codeRegister, 1, 2, 3, '/', 5, '/', 7, 8, 9, 10, 11, 12, 13, 14}) - require.NoError(t, err) + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + encoded := newLookupKey(c.height, flow.RegisterID{Owner: c.owner, Key: c.key}).Bytes() + decodedHeight, decodedReg, err := lookupKeyToRegisterID(encoded) + require.NoError(t, err) + require.Equal(t, c.height, decodedHeight) + require.Equal(t, c.owner, decodedReg.Owner) + require.Equal(t, c.key, decodedReg.Key) + }) + } } -func Test_prefix_error(t *testing.T) { - correctKey := newLookupKey(uint64(0), flow.RegisterID{Owner: "owner", Key: "key"}) - incorrectKey := firstHeightKey - _, _, err := lookupKeyToRegisterID(correctKey.Bytes()) - require.NoError(t, err) +// Test_decodeKey_errors tests all error paths of lookupKeyToRegisterID, and also verifies that +// valid inputs produce no error. +func Test_decodeKey_errors(t *testing.T) { + cases := []struct { + name string + key []byte + hasError bool + }{ + { + name: "too few bytes", + key: []byte{codeRegister, 1, 2, 3, 4, 5, 6, 7, 8, 9}, // 10 bytes < MinLookupKeyLen (11) + hasError: true, + }, + { + name: "incorrect prefix", + key: []byte{^codeRegister, byte('/'), byte('/'), 1, 2, 3, 4, 5, 6, 7, 8}, + hasError: true, + }, + { + // After stripping the prefix we have 10 bytes. heightPos = 10-8 = 2, lookupKey[1] ≠ '/' + name: "separator not at expected position: key too short for height", + key: []byte{codeRegister, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + hasError: true, + }, + { + // After stripping the prefix we have 13 bytes. heightPos = 13-8 = 5, lookupKey[4] ≠ '/' + name: "separator not at expected position: one byte short of valid", + key: []byte{codeRegister, 1, 2, 3, '/', 5, '/', 7, 8, 9, 10, 11, 12, 13}, + hasError: true, + }, + { + // After stripping the prefix: {1,2,3,4,5,'/',7,8,9,10,11,12,13,14} (14 bytes). + // heightPos = 6, lookupKey[5] = '/' passes the separator check. + // The owner+key part {1,2,3,4,5} has no '/', so bytes.Cut fails. + name: "no slash between owner and key", + key: []byte{codeRegister, 1, 2, 3, 4, 5, '/', 7, 8, 9, 10, 11, 12, 13, 14}, + hasError: true, + }, + { + // After stripping the prefix: {1,2,3,'/',5,'/',7,8,9,10,11,12,13,14} (14 bytes). + // heightPos = 6, lookupKey[5] = '/', owner+key = {1,2,3,'/',5} has '/'. + name: "valid raw key", + key: []byte{codeRegister, 1, 2, 3, '/', 5, '/', 7, 8, 9, 10, 11, 12, 13, 14}, + }, + { + name: "valid encoded key", + key: newLookupKey(uint64(0), flow.RegisterID{Owner: "owner", Key: "key"}).Bytes(), + }, + } - _, _, err = lookupKeyToRegisterID(incorrectKey) - require.ErrorContains(t, err, "incorrect prefix") + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, _, err := lookupKeyToRegisterID(c.key) + if c.hasError { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } } diff --git a/storage/pebble/registers.go b/storage/pebble/registers.go index aa08a19c77d..b707d677814 100644 --- a/storage/pebble/registers.go +++ b/storage/pebble/registers.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" "math" + "strings" "github.com/cockroachdb/pebble/v2" "github.com/pkg/errors" @@ -161,6 +162,152 @@ func (s *Registers) FirstHeight() uint64 { return s.calculateFirstHeight(s.LatestHeight()) } +// ByKeyPrefix returns an iterator over all registers whose key starts with keyPrefix, +// at or before height, across all owners. It uses a single pebble iterator that seeks +// monotonically forward through the address space. +// +// When keyPrefix is an exact key (e.g. "contract_names"), the iterator yields one entry +// per owner that has that key. When keyPrefix is a partial key (e.g. "code."), it yields +// one entry per unique matching (owner, key) pair. Using the "code." example, it yields +// the most recent contract code for each contract in each account as of the given height. +// +// If cursor is provided, the iterator will start from the next register key after the cursor. +// Use this to resume iteration from a previous position. This is useful when performing long running +// iterations, so you can close and reopen the iterator to avoid pausing compaction for too long. +// +// No error returns are expected during normal operation. +func (s *Registers) ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) storage.IndexIterator[flow.RegisterValue, flow.RegisterID] { + return func(yield func(storage.IteratorEntry[flow.RegisterValue, flow.RegisterID], error) bool) { + var lowerBound []byte + if cursor == nil { + lowerBound = []byte{codeRegister} + } else { + lowerBound = nextRegisterKeyStart(cursor.Owner, cursor.Key) + } + + iter, err := s.db.NewIter(&pebble.IterOptions{ + LowerBound: lowerBound, + UpperBound: []byte{codeRegister + 1}, // exclusive upper bound + }) + if err != nil { + yield(nil, err) + return + } + defer iter.Close() + + // starting from the first register for the first account, iterate over all registers with the + // provided `keyPrefix` at or before the target height across all accounts. + for ok := iter.First(); ok; { + rawKey := iter.Key() + entryHeight, reg, err := lookupKeyToRegisterID(rawKey) + if err != nil { + if !yield(nil, fmt.Errorf("invalid register key in scan: %w", err)) { + return + } + // in practice, the caller is most likely going to break from the loop if there's an error. + // continue here since that is the intuitive behavior. + ok = iter.Next() + continue + } + + if reg.Key < keyPrefix { + // Before the prefix range for this owner. Seek to the first matching key. + ok = iter.SeekGE(newLookupKey(height, flow.RegisterID{Owner: reg.Owner, Key: keyPrefix}).Bytes()) + continue + } + + if strings.HasPrefix(reg.Key, keyPrefix) { + if entryHeight > height { + // In range but newer than the target height. Seek to the right height for this key. + ok = iter.SeekGE(newLookupKey(height, reg).Bytes()) + continue + } + + // Found the most recent value at or before height. Yield it. + entry := registerEntry{id: reg, iter: iter} + if !yield(entry, nil) { + return + } + + // Choose the next seek based on whether this was an exact or prefix match. + // An exact match means no other key for this owner can match the prefix, so + // we can skip the entire owner. A prefix match may have further matches. + if reg.Key == keyPrefix { + ok = iter.SeekGE(nextOwnerStart(reg.Owner)) + } else { + ok = iter.SeekGE(nextRegisterKeyStart(reg.Owner, reg.Key)) + } + continue + } + + // Past the prefix range for this owner; no match exists. + ok = iter.SeekGE(nextOwnerStart(reg.Owner)) + } + } +} + +// nextRegisterKeyStart returns a seek key that lands on the first pebble entry of the +// register immediately following (owner, regKey), skipping all height-variants of regKey. +func nextRegisterKeyStart(owner, regKey string) []byte { + // keys are sorted descending by height. using height=0 as the first possible entry. + lastPossibleKey := newLookupKey(0, flow.RegisterID{Owner: owner, Key: regKey}).Bytes() + return storage.PrefixUpperBound(lastPossibleKey) // increment key by 1 +} + +// nextOwnerStart returns the seek key for the first register entry of the owner +// immediately following owner in lexicographic order. It is used to skip all remaining +// register entries for the current owner after processing their target key register (or +// determining they have none). +func nextOwnerStart(owner string) []byte { + // Include the '/' separator in the prefix so that PrefixUpperBound targets exactly + // the entries for this owner. Pebble keys have the form: + // + // [codeRegister] [owner] '/' [key] '/' [^height] + // + // All entries for a given owner share the prefix [codeRegister][owner]['/']. Using + // that full prefix ensures PrefixUpperBound returns the first key strictly after + // all of that owner's entries, regardless of owner length. + // + // The empty-owner case illustrates why the separator is required. Global registers + // (owner="") have keys of the form [codeRegister, '/' (0x2F), ...]. Without the + // separator, the prefix would be just [codeRegister] and PrefixUpperBound would + // return [codeRegister+1] = [0x03], which equals the iterator's upper bound, + // terminating the scan immediately and silently skipping every account whose first + // address byte is > '/' (0x2F). With the separator: + // + // PrefixUpperBound([codeRegister, '/']) = [codeRegister, 0x30] + // + // That seek target is strictly after all global-register keys ([codeRegister, 0x2F, + // ...]) and before any account whose first address byte is >= 0x30, so the scan + // correctly continues into those accounts. + ownerPrefix := make([]byte, 2+len(owner)) + ownerPrefix[0] = codeRegister + copy(ownerPrefix[1:], []byte(owner)) + ownerPrefix[1+len(owner)] = '/' + return storage.PrefixUpperBound(ownerPrefix) // increment key by 1 +} + +// registerEntry is the IteratorEntry implementation for the Registers index. +type registerEntry struct { + id flow.RegisterID + iter *pebble.Iterator +} + +func (e registerEntry) Cursor() flow.RegisterID { + return e.id +} + +func (e registerEntry) Value() (flow.RegisterValue, error) { + rawVal, err := e.iter.ValueAndErr() + if err != nil { + return nil, err + } + + val := make(flow.RegisterValue, len(rawVal)) + copy(val, rawVal) + return val, nil +} + // calculateFirstHeight calculates the first indexed height that is stored in the register index, based on the // latest height and the configured pruning threshold. If the latest height is below the pruning threshold, the // first indexed height will be the same as the initial height when the store was initialized. If the pruning diff --git a/storage/pebble/registers_test.go b/storage/pebble/registers_test.go index 58899e72084..717ff6e7021 100644 --- a/storage/pebble/registers_test.go +++ b/storage/pebble/registers_test.go @@ -373,6 +373,206 @@ func Benchmark_PayloadStorage(b *testing.B) { } } +// TestRegisters_ByKeyPrefix_ExactKey tests ByKeyPrefix with an exact key (no prefix +// matches), verifying it yields one entry per owner and uses nextOwnerStart after a match. +func TestRegisters_ByKeyPrefix_ExactKey(t *testing.T) { + t.Parallel() + + addrA := unittest.RandomAddressFixture() + addrB := unittest.RandomAddressFixture() + addrC := unittest.RandomAddressFixture() // no contracts, only other registers + addrD := unittest.RandomAddressFixture() // contract_names updated across two heights + + regA := flow.ContractNamesRegisterID(addrA) + regB := flow.ContractNamesRegisterID(addrB) + regD := flow.ContractNamesRegisterID(addrD) + + valA := []byte("namesA") + valB := []byte("namesB") + valDOld := []byte("namesDold") + valDNew := []byte("namesDnew") + + RunWithRegistersStorageAtInitialHeights(t, 1, 1, func(r *Registers) { + // height 2: A gets contract_names + require.NoError(t, r.Store(flow.RegisterEntries{{Key: regA, Value: valA}}, 2)) + // height 3: D gets its first contract_names + require.NoError(t, r.Store(flow.RegisterEntries{{Key: regD, Value: valDOld}}, 3)) + // height 4: B gets contract_names; C gets a non-contract register + require.NoError(t, r.Store(flow.RegisterEntries{ + {Key: regB, Value: valB}, + {Key: flow.RegisterID{Owner: string(addrC.Bytes()), Key: flow.AccountStatusKey}, Value: []byte("status")}, + }, 4)) + // height 5: D updates its contract_names + require.NoError(t, r.Store(flow.RegisterEntries{{Key: regD, Value: valDNew}}, 5)) + + t.Run("yields all accounts with contracts at or before query height", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.ContractNamesKey, 5, nil)) + assert.Len(t, results, 3) + assert.Equal(t, flow.RegisterValue(valA), results[regA]) + assert.Equal(t, flow.RegisterValue(valB), results[regB]) + assert.Equal(t, flow.RegisterValue(valDNew), results[regD]) + }) + + t.Run("yields older version when newest is above target height", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.ContractNamesKey, 4, nil)) + assert.Len(t, results, 3) + assert.Equal(t, flow.RegisterValue(valDOld), results[regD]) + }) + + t.Run("excludes accounts whose contracts were deployed after target height", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.ContractNamesKey, 2, nil)) + assert.Len(t, results, 1) + assert.Equal(t, flow.RegisterValue(valA), results[regA]) + }) + + t.Run("empty result when no contracts exist at or before target height", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.ContractNamesKey, 1, nil)) + assert.Empty(t, results) + }) + + t.Run("account with only non-contract registers is not yielded", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.ContractNamesKey, 5, nil)) + _, hasC := results[flow.ContractNamesRegisterID(addrC)] + assert.False(t, hasC) + }) + + t.Run("early termination stops iteration", func(t *testing.T) { + count := 0 + for _, err := range r.ByKeyPrefix(flow.ContractNamesKey, 5, nil) { + require.NoError(t, err) + count++ + break + } + assert.Equal(t, 1, count) + }) + }) +} + +// TestRegisters_ByKeyPrefix tests ByKeyPrefix, which scans pebble for all registers +// whose key starts with a given prefix using a single iterator. +func TestRegisters_ByKeyPrefix(t *testing.T) { + t.Parallel() + + addrA := unittest.RandomAddressFixture() + addrB := unittest.RandomAddressFixture() + addrC := unittest.RandomAddressFixture() // no code registers + + // addrA: two contracts, one updated across heights + regAFoo := flow.RegisterID{Owner: string(addrA.Bytes()), Key: "code.Foo"} + regABar := flow.RegisterID{Owner: string(addrA.Bytes()), Key: "code.Bar"} + // addrB: one contract + regBBaz := flow.RegisterID{Owner: string(addrB.Bytes()), Key: "code.Baz"} + // addrC: only a non-code register + regCStatus := flow.RegisterID{Owner: string(addrC.Bytes()), Key: flow.AccountStatusKey} + + valAFoo1 := []byte("foo-code-v1") + valAFoo2 := []byte("foo-code-v2") + valABar := []byte("bar-code") + valBBaz := []byte("baz-code") + + RunWithRegistersStorageAtInitialHeights(t, 1, 1, func(r *Registers) { + // height 2: addrA deploys Foo (v1); addrC gets a non-code register + require.NoError(t, r.Store(flow.RegisterEntries{ + {Key: regAFoo, Value: valAFoo1}, + {Key: regCStatus, Value: []byte("status")}, + }, 2)) + // height 3: addrA deploys Bar; addrB deploys Baz + require.NoError(t, r.Store(flow.RegisterEntries{ + {Key: regABar, Value: valABar}, + {Key: regBBaz, Value: valBBaz}, + }, 3)) + // height 4: addrA updates Foo to v2 + require.NoError(t, r.Store(flow.RegisterEntries{ + {Key: regAFoo, Value: valAFoo2}, + }, 4)) + + t.Run("yields one entry per matching register across all owners", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.CodeKeyPrefix, 4, nil)) + assert.Len(t, results, 3) // Foo, Bar, Baz + assert.Equal(t, flow.RegisterValue(valAFoo2), results[regAFoo]) + assert.Equal(t, flow.RegisterValue(valABar), results[regABar]) + assert.Equal(t, flow.RegisterValue(valBBaz), results[regBBaz]) + }) + + t.Run("yields older version when newest is above target height", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.CodeKeyPrefix, 3, nil)) + assert.Equal(t, flow.RegisterValue(valAFoo1), results[regAFoo]) + }) + + t.Run("excludes registers deployed after target height", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.CodeKeyPrefix, 2, nil)) + assert.Len(t, results, 1) + assert.Equal(t, flow.RegisterValue(valAFoo1), results[regAFoo]) + }) + + t.Run("empty result when no matching registers exist at or before target height", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.CodeKeyPrefix, 1, nil)) + assert.Empty(t, results) + }) + + t.Run("non-matching registers are not yielded", func(t *testing.T) { + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.CodeKeyPrefix, 4, nil)) + _, hasStatus := results[regCStatus] + assert.False(t, hasStatus) + }) + + t.Run("early termination stops iteration", func(t *testing.T) { + count := 0 + for _, err := range r.ByKeyPrefix(flow.CodeKeyPrefix, 4, nil) { + require.NoError(t, err) + count++ + break + } + assert.Equal(t, 1, count) + }) + }) +} + +// TestRegisters_ByKeyPrefix_GlobalRegisters verifies that ByKeyPrefix does not terminate +// early when global registers (empty owner) are present in pebble between account registers +// whose first address bytes straddle the '/' byte (0x2F). Before the fix, nextOwnerStart("") +// returned [codeRegister+1] which equals the iterator's upper bound, causing the scan to +// stop before processing any account whose first address byte is > 0x2F. +func TestRegisters_ByKeyPrefix_GlobalRegisters(t *testing.T) { + t.Parallel() + + // addrLow: first address byte 0x01 < '/' (0x2F) — pebble key sorts before global registers + addrLow := flow.BytesToAddress([]byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}) + // addrHigh: first address byte 0x30 > '/' (0x2F) — pebble key sorts after global registers + addrHigh := flow.BytesToAddress([]byte{0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}) + + regLow := flow.RegisterID{Owner: string(addrLow.Bytes()), Key: "code.Low"} + regHigh := flow.RegisterID{Owner: string(addrHigh.Bytes()), Key: "code.High"} + // global register (empty owner): pebble key [codeRegister, '/', ...] sorts between addrLow and addrHigh + regGlobal := flow.RegisterID{Owner: "", Key: flow.AddressStateKey} + + RunWithRegistersStorageAtInitialHeights(t, 1, 1, func(r *Registers) { + require.NoError(t, r.Store(flow.RegisterEntries{ + {Key: regLow, Value: []byte("low-code")}, + {Key: regHigh, Value: []byte("high-code")}, + {Key: regGlobal, Value: []byte("global-state")}, + }, 2)) + + results := collectRegistersByKey(t, r.ByKeyPrefix(flow.CodeKeyPrefix, 2, nil)) + assert.Len(t, results, 2) + assert.Equal(t, flow.RegisterValue([]byte("low-code")), results[regLow]) + assert.Equal(t, flow.RegisterValue([]byte("high-code")), results[regHigh]) + }) +} + +// collectRegistersByKey drains a ByKey iterator into a map keyed by register ID. +func collectRegistersByKey(t *testing.T, iter storage.IndexIterator[flow.RegisterValue, flow.RegisterID]) map[flow.RegisterID]flow.RegisterValue { + t.Helper() + results := make(map[flow.RegisterID]flow.RegisterValue) + for entry, err := range iter { + require.NoError(t, err) + val, err := entry.Value() + require.NoError(t, err) + results[entry.Cursor()] = val + } + return results +} + func RunWithRegistersStorageAtHeight1(tb testing.TB, f func(r *Registers)) { defaultHeight := uint64(1) RunWithRegistersStorageAtInitialHeights(tb, defaultHeight, defaultHeight, f) diff --git a/storage/receipts.go b/storage/receipts.go index 004f2af1afb..0a6aed1d9b5 100644 --- a/storage/receipts.go +++ b/storage/receipts.go @@ -24,6 +24,8 @@ type ExecutionReceipts interface { // ByBlockID retrieves all known execution receipts for the given block // (from any Execution Node). // + // Returns an empty list and no error if no receipts are found for the given block. + // // No errors are expected errors during normal operations. ByBlockID(blockID flow.Identifier) (flow.ExecutionReceiptList, error) } diff --git a/storage/registers.go b/storage/registers.go index 1eb56fcef4a..e8250d751df 100644 --- a/storage/registers.go +++ b/storage/registers.go @@ -20,6 +20,22 @@ type RegisterIndexReader interface { // FirstHeight at which we started to index. Returns the first indexed height found in the store. FirstHeight() uint64 + + // ByKeyPrefix returns an iterator over all registers whose key starts with keyPrefix, + // at or before height, across all owners. It uses a single pebble iterator that seeks + // monotonically forward through the address space. + // + // When keyPrefix is an exact key (e.g. "contract_names"), the iterator yields one entry + // per owner that has that key. When keyPrefix is a partial key (e.g. "code."), it yields + // one entry per unique matching (owner, key) pair. Using the "code." example, it yields + // the most recent contract code for each contract in each account as of the given height. + // + // If cursor is provided, the iterator will start from the next register key after the cursor. + // Use this to resume iteration from a previous position. This is useful when performing long running + // iterations, so you can close and reopen the iterator to avoid pausing compaction for too long. + // + // No error returns are expected during normal operation. + ByKeyPrefix(keyPrefix string, height uint64, cursor *flow.RegisterID) IndexIterator[flow.RegisterValue, flow.RegisterID] } // RegisterIndex defines methods for the register index. diff --git a/storage/scheduled_transactions_index.go b/storage/scheduled_transactions_index.go new file mode 100644 index 00000000000..0ea8ebe1396 --- /dev/null +++ b/storage/scheduled_transactions_index.go @@ -0,0 +1,157 @@ +package storage + +import ( + "github.com/jordanschalm/lockctx" + + accessmodel "github.com/onflow/flow-go/model/access" + "github.com/onflow/flow-go/model/flow" +) + +// ScheduledTransactionIterator is an iterator over scheduled transactions ordered by +// descending ID (highest first). +type ScheduledTransactionIterator = IndexIterator[accessmodel.ScheduledTransaction, accessmodel.ScheduledTransactionCursor] + +// ScheduledTransactionsIndexReader provides read access to the scheduled transactions index. +// +// All methods are safe for concurrent access. +type ScheduledTransactionsIndexReader interface { + // ByID returns the scheduled transaction with the given scheduler-assigned ID. + // + // Expected error returns during normal operation: + // - [ErrNotFound]: if no scheduled transaction with the given ID exists + ByID(id uint64) (accessmodel.ScheduledTransaction, error) + + // ByAddress returns an iterator over scheduled transactions for the given account, + // ordered by descending ID (highest first). + // Returns an exhausted iterator and no error if the account has no transactions. + // + // `cursor` is a pointer to an [accessmodel.ScheduledTransactionCursor]: + // - nil means start from the highest indexed ID (first page) + // - non-nil means start at the cursor position (inclusive) + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + ByAddress( + account flow.Address, + cursor *accessmodel.ScheduledTransactionCursor, + ) (ScheduledTransactionIterator, error) + + // All returns an iterator over all scheduled transactions, ordered by descending ID + // (highest first). Returns an exhausted iterator and no error if no transactions exist. + // + // `cursor` is a pointer to an [accessmodel.ScheduledTransactionCursor]: + // - nil means start from the highest indexed ID (first page) + // - non-nil means start at the cursor position (inclusive) + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + All(cursor *accessmodel.ScheduledTransactionCursor) (ScheduledTransactionIterator, error) +} + +// ScheduledTransactionsIndexRangeReader provides access to the range of indexed heights. +// +// All methods are safe for concurrent access. +type ScheduledTransactionsIndexRangeReader interface { + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + FirstIndexedHeight() uint64 + + // LatestIndexedHeight returns the latest block height that has been indexed. + LatestIndexedHeight() uint64 +} + +// ScheduledTransactionsIndexWriter provides write access to the scheduled transactions index. +// +// NOT CONCURRENCY SAFE. +type ScheduledTransactionsIndexWriter interface { + // Store indexes all new scheduled transactions from the given block and advances + // the latest indexed height to blockHeight. Must be called with consecutive heights. + // The caller must hold the [LockIndexScheduledTransactionsIndex] lock until the batch + // is committed. + // + // Expected error returns during normal operation: + // - [ErrAlreadyExists]: if blockHeight is already indexed + Store( + lctx lockctx.Proof, + rw ReaderBatchWriter, + blockHeight uint64, + scheduledTxs []accessmodel.ScheduledTransaction, + ) error + + // Executed updates the scheduled transaction's status to Executed and records the ID of the + // transaction that emitted the Executed event. + // The caller must hold the [LockIndexScheduledTransactionsIndex] lock until the batch + // is committed. + // + // Expected error returns during normal operation: + // - [ErrNotFound]: if no scheduled transaction with the given ID exists + // - [ErrInvalidStatusTransition]: if the transaction is already Executed, Cancelled, or Failed + Executed( + lctx lockctx.Proof, + rw ReaderBatchWriter, + scheduledTxID uint64, + transactionID flow.Identifier, + ) error + + // Cancelled updates the scheduled transaction's status to Cancelled and records the + // fee amounts and the ID of the transaction that emitted the Canceled event. + // The caller must hold the [LockIndexScheduledTransactionsIndex] lock until the batch + // is committed. + // + // Expected error returns during normal operation: + // - [ErrNotFound]: if no scheduled transaction with the given ID exists + // - [ErrInvalidStatusTransition]: if the transaction is already Executed, Cancelled, or Failed + Cancelled( + lctx lockctx.Proof, + rw ReaderBatchWriter, + scheduledTxID uint64, + feesReturned uint64, + feesDeducted uint64, + transactionID flow.Identifier, + ) error + + // Failed updates the transaction's status to Failed and records the ID of the executor + // transaction that attempted (and failed) to execute the scheduled transaction. + // The caller must hold the [LockIndexScheduledTransactionsIndex] lock until committed. + // + // Expected error returns during normal operation: + // - [ErrNotFound]: if no entry with the given ID exists + // - [ErrInvalidStatusTransition]: if the transaction is already Executed, Cancelled, or Failed + Failed( + lctx lockctx.Proof, + rw ReaderBatchWriter, + scheduledTxID uint64, + transactionID flow.Identifier, + ) error +} + +// ScheduledTransactionsIndex provides full read and write access to the scheduled transactions index. +type ScheduledTransactionsIndex interface { + ScheduledTransactionsIndexReader + ScheduledTransactionsIndexRangeReader + ScheduledTransactionsIndexWriter +} + +// ScheduledTransactionsIndexBootstrapper wraps [ScheduledTransactionsIndex] and performs +// just-in-time initialization of the index when the initial block is provided. +// +// All read and write methods proxy to the underlying index once initialized. +type ScheduledTransactionsIndexBootstrapper interface { + ScheduledTransactionsIndexReader + ScheduledTransactionsIndexWriter + + // FirstIndexedHeight returns the first (oldest) block height that has been indexed. + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + FirstIndexedHeight() (uint64, error) + + // LatestIndexedHeight returns the latest block height that has been indexed. + // + // Expected error returns during normal operation: + // - [ErrNotBootstrapped]: if the index has not been initialized + LatestIndexedHeight() (uint64, error) + + // UninitializedFirstHeight returns the height the index will accept as the first + // height, and a boolean indicating whether the index is initialized. + UninitializedFirstHeight() (uint64, bool) +} diff --git a/storage/store/blocks.go b/storage/store/blocks.go index f996ff177ad..738eed63f04 100644 --- a/storage/store/blocks.go +++ b/storage/store/blocks.go @@ -209,21 +209,43 @@ func (b *Blocks) ProposalByHeight(height uint64) (*flow.Proposal, error) { // - generic error in case of unexpected failure from the database layer, or failure // to decode an existing database value func (b *Blocks) ByCollectionID(collID flow.Identifier) (*flow.Block, error) { + blockID, err := b.BlockIDByCollectionID(collID) + if err != nil { + return nil, err + } + return b.ByID(blockID) +} + +// BlockIDByCollectionID returns the block ID for the finalized block which includes the guarantee for the +// given collection (the collection guarantee such that `CollectionGuarantee.CollectionID == collID`). +// This function returns the finalized _consensus_ block including the specified collection, not the cluster +// block which defines the collection. +// NOTE: This method is only available for collections included in finalized blocks. +// While consensus nodes verify that collections are not repeated within the same fork, +// each different fork can contain a recent collection once. Therefore, we must wait for +// finality. +// CAUTION: this method is not backed by a cache and therefore comparatively slow! +// +// Error returns: +// - storage.ErrNotFound if no FINALIZED block exists containing the expected collection guarantee +// - generic error in case of unexpected failure from the database layer, or failure +// to decode an existing database value +func (b *Blocks) BlockIDByCollectionID(collID flow.Identifier) (flow.Identifier, error) { guarantee, err := b.payloads.guarantees.ByCollectionID(collID) if err != nil { - return nil, fmt.Errorf("could not look up guarantee: %w", err) + return flow.ZeroID, fmt.Errorf("could not look up guarantee: %w", err) } var blockID flow.Identifier err = operation.LookupBlockContainingCollectionGuarantee(b.db.Reader(), guarantee.ID(), &blockID) if err != nil { - return nil, fmt.Errorf("could not look up block: %w", err) + return flow.ZeroID, fmt.Errorf("could not look up block: %w", err) } // CAUTION: a collection can be included in multiple *unfinalized* blocks. However, the implementation // assumes a one-to-one map from collection ID to a *single* block ID. This holds for FINALIZED BLOCKS ONLY // *and* only in the absence of byzantine collector clusters (which the mature protocol must tolerate). // Hence, this function should be treated as a temporary solution, which requires generalization // (one-to-many mapping) for soft finality and the mature protocol. - return b.ByID(blockID) + return blockID, nil } // BatchIndexBlockContainingCollectionGuarantees produces mappings from the IDs of [flow.CollectionGuarantee]s to the block ID containing these guarantees. diff --git a/storage/store/events.go b/storage/store/events.go index f4861902efb..a3e6a476ee4 100644 --- a/storage/store/events.go +++ b/storage/store/events.go @@ -2,6 +2,7 @@ package store import ( "fmt" + "sort" "github.com/jordanschalm/lockctx" @@ -23,6 +24,13 @@ func NewEvents(collector module.CacheMetrics, db storage.DB) *Events { retrieve := func(r storage.Reader, blockID flow.Identifier) ([]flow.Event, error) { var events []flow.Event err := operation.LookupEventsByBlockID(r, blockID, &events) + + // We want events sorted by [txIndex, eventIndex] (execution order). + // Events are keyed by [blockID, txID, txIndex, eventIndex], so reading by txID + // returns them in the correct order. However, reading by blockID returns events + // sorted by txID (a hash) first, which is unpredictable. We must re-sort here. + sortEventsExecutionOrder(events) + return events, err } @@ -41,6 +49,7 @@ func NewEvents(collector module.CacheMetrics, db storage.DB) *Events { // BatchStore will store events for the given block ID in a given batch // It requires the caller to hold [storage.LockInsertEvent] +// // Expected error returns: // - [storage.ErrAlreadyExists] if events for the block already exist. func (e *Events) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, blockEvents []flow.EventsList, batch storage.ReaderBatchWriter) error { @@ -73,6 +82,10 @@ func (e *Events) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, blockEv // ByBlockID returns the events for the given block ID // Note: This method will return an empty slice and no error if no entries for the blockID are found +// +// CAUTION: The returned slice and events cannot be safely modified. Make a copy first. +// +// No error returns are expected during normal operation. func (e *Events) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { val, err := e.cache.Get(e.db.Reader(), blockID) if err != nil { @@ -83,6 +96,10 @@ func (e *Events) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { // ByBlockIDTransactionID returns the events for the given block ID and transaction ID // Note: This method will return an empty slice and no error if no entries for the blockID are found +// +// CAUTION: The returned events cannot be safely modified. Make a copy first. +// +// No error returns are expected during normal operation. func (e *Events) ByBlockIDTransactionID(blockID flow.Identifier, txID flow.Identifier) ([]flow.Event, error) { events, err := e.ByBlockID(blockID) if err != nil { @@ -100,6 +117,10 @@ func (e *Events) ByBlockIDTransactionID(blockID flow.Identifier, txID flow.Ident // ByBlockIDTransactionIndex returns the events for the given block ID and transaction index // Note: This method will return an empty slice and no error if no entries for the blockID are found +// +// CAUTION: The returned events cannot be safely modified. Make a copy first. +// +// No error returns are expected during normal operation. func (e *Events) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint32) ([]flow.Event, error) { events, err := e.ByBlockID(blockID) if err != nil { @@ -117,6 +138,10 @@ func (e *Events) ByBlockIDTransactionIndex(blockID flow.Identifier, txIndex uint // ByBlockIDEventType returns the events for the given block ID and event type // Note: This method will return an empty slice and no error if no entries for the blockID are found +// +// CAUTION: The returned events cannot be safely modified. Make a copy first. +// +// No error returns are expected during normal operation. func (e *Events) ByBlockIDEventType(blockID flow.Identifier, eventType flow.EventType) ([]flow.Event, error) { events, err := e.ByBlockID(blockID) if err != nil { @@ -140,6 +165,7 @@ func (e *Events) RemoveByBlockID(blockID flow.Identifier) error { } // BatchRemoveByBlockID removes events keyed by a blockID in provided batch +// // No errors are expected during normal operation, even if no entries are matched. func (e *Events) BatchRemoveByBlockID(blockID flow.Identifier, rw storage.ReaderBatchWriter) error { return e.cache.RemoveTx(rw, blockID) @@ -154,6 +180,13 @@ func NewServiceEvents(collector module.CacheMetrics, db storage.DB) *ServiceEven retrieve := func(r storage.Reader, blockID flow.Identifier) ([]flow.Event, error) { var events []flow.Event err := operation.LookupServiceEventsByBlockID(r, blockID, &events) + + // We want events sorted by [txIndex, eventIndex] (execution order). + // Events are keyed by [blockID, txID, txIndex, eventIndex], so reading by txID + // returns them in the correct order. However, reading by blockID returns events + // sorted by txID (a hash) first, which is unpredictable. We must re-sort here. + sortEventsExecutionOrder(events) + return events, err } @@ -193,6 +226,11 @@ func (e *ServiceEvents) BatchStore(lctx lockctx.Proof, blockID flow.Identifier, } // ByBlockID returns the events for the given block ID +// Note: This method will return an empty slice and no error if no entries for the blockID are found +// +// CAUTION: The returned slice and events cannot be safely modified. Make a copy first. +// +// No error returns are expected during normal operation. func (e *ServiceEvents) ByBlockID(blockID flow.Identifier) ([]flow.Event, error) { val, err := e.cache.Get(e.db.Reader(), blockID) if err != nil { @@ -209,7 +247,18 @@ func (e *ServiceEvents) RemoveByBlockID(blockID flow.Identifier) error { } // BatchRemoveByBlockID removes service events keyed by a blockID in provided batch +// // No errors are expected during normal operation, even if no entries are matched. func (e *ServiceEvents) BatchRemoveByBlockID(blockID flow.Identifier, rw storage.ReaderBatchWriter) error { return e.cache.RemoveTx(rw, blockID) } + +// sortEventsExecutionOrder sorts events by [txIndex, eventIndex] (execution order). +func sortEventsExecutionOrder(events []flow.Event) { + sort.Slice(events, func(i, j int) bool { + if events[i].TransactionIndex == events[j].TransactionIndex { + return events[i].EventIndex < events[j].EventIndex + } + return events[i].TransactionIndex < events[j].TransactionIndex + }) +} diff --git a/storage/store/events_test.go b/storage/store/events_test.go index 4a70a895000..e591b3da883 100644 --- a/storage/store/events_test.go +++ b/storage/store/events_test.go @@ -140,6 +140,169 @@ func TestEventRetrieveWithoutStore(t *testing.T) { }) } +// TestByBlockID_SortsEventsByExecutionOrder verifies that events loaded from the +// database (cache miss path) are returned sorted by (TransactionIndex, +// EventIndex) regardless of the order imposed by the storage key, which is +// [blockID, txID, txIndex, eventIndex]. When two transactions have txIDs whose +// byte order differs from their execution order the DB iteration would return +// them in txID order; the retrieve function must re-sort them. +func TestByBlockID_SortsEventsByExecutionOrder(t *testing.T) { + lockManager := storage.NewTestingLockManager() + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + m := metrics.NewNoopCollector() + eventsStore := store.NewEvents(m, db) + + blockID := unittest.IdentifierFixture() + + // txIDLow sorts before txIDHigh in byte (DB key) order, but its + // TransactionIndex is higher, so in execution order it comes second. + var txIDLow, txIDHigh flow.Identifier + txIDLow[0] = 0x00 // first in DB key order + txIDHigh[0] = 0xFF // second in DB key order + + // execution tx 0 uses txIDHigh; execution tx 1 uses txIDLow + evtTx0 := unittest.EventFixture( + unittest.Event.WithTransactionID(txIDHigh), + unittest.Event.WithTransactionIndex(0), + unittest.Event.WithEventIndex(0), + ) + evtTx1A := unittest.EventFixture( + unittest.Event.WithTransactionID(txIDLow), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + ) + evtTx1B := unittest.EventFixture( + unittest.Event.WithTransactionID(txIDLow), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(1), + ) + + err := unittest.WithLock(t, lockManager, storage.LockInsertEvent, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return eventsStore.BatchStore(lctx, blockID, []flow.EventsList{{evtTx0}, {evtTx1A, evtTx1B}}, rw) + }) + }) + require.NoError(t, err) + + // Use a fresh store to force a DB load (bypasses the cache populated by BatchStore). + freshStore := store.NewEvents(m, db) + got, err := freshStore.ByBlockID(blockID) + require.NoError(t, err) + require.Len(t, got, 3) + + // Events must come back in execution order: txIndex 0, then 1 (eventIndex 0, 1). + require.Equal(t, uint32(0), got[0].TransactionIndex) + require.Equal(t, uint32(0), got[0].EventIndex) + require.Equal(t, uint32(1), got[1].TransactionIndex) + require.Equal(t, uint32(0), got[1].EventIndex) + require.Equal(t, uint32(1), got[2].TransactionIndex) + require.Equal(t, uint32(1), got[2].EventIndex) + }) +} + +// TestServiceEventStoreRetrieve verifies basic store and retrieval for ServiceEvents. +func TestServiceEventStoreRetrieve(t *testing.T) { + lockManager := storage.NewTestingLockManager() + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + m := metrics.NewNoopCollector() + svcEventsStore := store.NewServiceEvents(m, db) + + blockID := unittest.IdentifierFixture() + txID := unittest.IdentifierFixture() + + evt1 := unittest.EventFixture( + unittest.Event.WithTransactionID(txID), + unittest.Event.WithTransactionIndex(0), + unittest.Event.WithEventIndex(0), + ) + evt2 := unittest.EventFixture( + unittest.Event.WithTransactionID(txID), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + ) + + err := unittest.WithLock(t, lockManager, storage.LockInsertServiceEvent, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return svcEventsStore.BatchStore(lctx, blockID, []flow.Event{evt1, evt2}, rw) + }) + }) + require.NoError(t, err) + + got, err := svcEventsStore.ByBlockID(blockID) + require.NoError(t, err) + require.Len(t, got, 2) + require.Contains(t, got, evt1) + require.Contains(t, got, evt2) + + // Test loading from database (cache miss path). + freshStore := store.NewServiceEvents(m, db) + got, err = freshStore.ByBlockID(blockID) + require.NoError(t, err) + require.Len(t, got, 2) + require.Contains(t, got, evt1) + require.Contains(t, got, evt2) + }) +} + +// TestServiceEventByBlockID_SortsEventsByExecutionOrder verifies that service events +// loaded from the database (cache miss path) are returned sorted by (TransactionIndex, +// EventIndex) regardless of the DB key order, which is keyed by txID byte order. +// Before the fix, the sort was missing for ServiceEvents (unlike Events which already +// had it), causing events to be returned in DB key order on a cache miss. +func TestServiceEventByBlockID_SortsEventsByExecutionOrder(t *testing.T) { + lockManager := storage.NewTestingLockManager() + dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { + m := metrics.NewNoopCollector() + svcEventsStore := store.NewServiceEvents(m, db) + + blockID := unittest.IdentifierFixture() + + // txIDLow sorts before txIDHigh in byte (DB key) order, but its + // TransactionIndex is higher, so in execution order it comes second. + var txIDLow, txIDHigh flow.Identifier + txIDLow[0] = 0x00 // first in DB key order + txIDHigh[0] = 0xFF // second in DB key order + + // execution tx 0 uses txIDHigh; execution tx 1 uses txIDLow + evtTx0 := unittest.EventFixture( + unittest.Event.WithTransactionID(txIDHigh), + unittest.Event.WithTransactionIndex(0), + unittest.Event.WithEventIndex(0), + ) + evtTx1A := unittest.EventFixture( + unittest.Event.WithTransactionID(txIDLow), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(0), + ) + evtTx1B := unittest.EventFixture( + unittest.Event.WithTransactionID(txIDLow), + unittest.Event.WithTransactionIndex(1), + unittest.Event.WithEventIndex(1), + ) + + err := unittest.WithLock(t, lockManager, storage.LockInsertServiceEvent, func(lctx lockctx.Context) error { + return db.WithReaderBatchWriter(func(rw storage.ReaderBatchWriter) error { + return svcEventsStore.BatchStore(lctx, blockID, []flow.Event{evtTx0, evtTx1A, evtTx1B}, rw) + }) + }) + require.NoError(t, err) + + // Use a fresh store to force a DB load (bypasses the cache populated by BatchStore). + freshStore := store.NewServiceEvents(m, db) + got, err := freshStore.ByBlockID(blockID) + require.NoError(t, err) + require.Len(t, got, 3) + + // Events must come back in execution order: txIndex 0, then 1 (eventIndex 0, 1). + require.Equal(t, uint32(0), got[0].TransactionIndex) + require.Equal(t, uint32(0), got[0].EventIndex) + require.Equal(t, uint32(1), got[1].TransactionIndex) + require.Equal(t, uint32(0), got[1].EventIndex) + require.Equal(t, uint32(1), got[2].TransactionIndex) + require.Equal(t, uint32(1), got[2].EventIndex) + }) +} + func TestEventStoreAndRemove(t *testing.T) { lockManager := storage.NewTestingLockManager() dbtest.RunWithDB(t, func(t *testing.T, db storage.DB) { diff --git a/tools/test_matrix_generator/default-test-matrix-config.json b/tools/test_matrix_generator/default-test-matrix-config.json index a62ac6aec5a..4079ff2db64 100644 --- a/tools/test_matrix_generator/default-test-matrix-config.json +++ b/tools/test_matrix_generator/default-test-matrix-config.json @@ -9,7 +9,7 @@ {"name": "state"}, {"name": "storage"}, {"name": "utils"}, - {"name": "engine", "runner": "buildjet-4vcpu-ubuntu-2004" ,"subpackages": [ + {"name": "engine", "runner": "blacksmith-4vcpu-ubuntu-2404" ,"subpackages": [ {"name": "engine/access"}, {"name": "engine/collection"}, {"name": "engine/common"}, @@ -17,17 +17,17 @@ {"name": "engine/execution/computation"}, {"name": "engine/execution"}, {"name": "engine/verification"}, - {"name": "engine/execution/ingestion", "runner": "buildjet-8vcpu-ubuntu-2004"} + {"name": "engine/execution/ingestion", "runner": "blacksmith-8vcpu-ubuntu-2404"} ]}, - {"name": "module", "runner": "buildjet-4vcpu-ubuntu-2004" ,"subpackages": [{"name": "module/dkg"}]}, + {"name": "module", "runner": "blacksmith-4vcpu-ubuntu-2404" ,"subpackages": [{"name": "module/dkg"}]}, {"name": "network", "subpackages": [ {"name": "network/alsp"}, {"name": "network/p2p/connection"}, {"name": "network/p2p/scoring"}, - {"name": "network/p2p", "runner": "buildjet-16vcpu-ubuntu-2004"}, - {"name": "network/test/cohort1", "runner": "buildjet-16vcpu-ubuntu-2004"}, - {"name": "network/test/cohort2", "runner": "buildjet-4vcpu-ubuntu-2004"}, - {"name": "network/p2p/node", "runner": "buildjet-4vcpu-ubuntu-2004"} + {"name": "network/p2p", "runner": "blacksmith-16vcpu-ubuntu-2404"}, + {"name": "network/test/cohort1", "runner": "blacksmith-16vcpu-ubuntu-2404"}, + {"name": "network/test/cohort2", "runner": "blacksmith-4vcpu-ubuntu-2404"}, + {"name": "network/p2p/node", "runner": "blacksmith-4vcpu-ubuntu-2404"} ]} ] } diff --git a/tools/test_matrix_generator/insecure-module-test-matrix-config.json b/tools/test_matrix_generator/insecure-module-test-matrix-config.json index 59e7aa6ecb0..81ae96b8462 100644 --- a/tools/test_matrix_generator/insecure-module-test-matrix-config.json +++ b/tools/test_matrix_generator/insecure-module-test-matrix-config.json @@ -2,9 +2,9 @@ "packagesPath": "./insecure", "includeOthers": false, "packages": [ - {"name": "insecure", "runner": "buildjet-4vcpu-ubuntu-2004" ,"subpackages": [ - {"name": "insecure/integration/functional/test/gossipsub/rpc_inspector", "runner": "buildjet-8vcpu-ubuntu-2004"}, - {"name": "insecure/integration/functional/test/gossipsub/scoring", "runner": "buildjet-8vcpu-ubuntu-2004"} + {"name": "insecure", "runner": "blacksmith-4vcpu-ubuntu-2404" ,"subpackages": [ + {"name": "insecure/integration/functional/test/gossipsub/rpc_inspector", "runner": "blacksmith-8vcpu-ubuntu-2404"}, + {"name": "insecure/integration/functional/test/gossipsub/scoring", "runner": "blacksmith-8vcpu-ubuntu-2404"} ]} ] } diff --git a/tools/test_matrix_generator/integration-module-test-matrix-config.json b/tools/test_matrix_generator/integration-module-test-matrix-config.json index 379ee6ab64e..3daa7b82f36 100644 --- a/tools/test_matrix_generator/integration-module-test-matrix-config.json +++ b/tools/test_matrix_generator/integration-module-test-matrix-config.json @@ -3,7 +3,7 @@ "includeOthers": false, "packages": [{ "name": "integration", - "runner": "buildjet-4vcpu-ubuntu-2004", + "runner": "blacksmith-4vcpu-ubuntu-2404", "exclude": ["integration/tests"] }] } diff --git a/tools/test_matrix_generator/matrix.go b/tools/test_matrix_generator/matrix.go index 1fea6492ef5..8a1a1b1ec5b 100644 --- a/tools/test_matrix_generator/matrix.go +++ b/tools/test_matrix_generator/matrix.go @@ -27,7 +27,7 @@ var ( const ( flowPackagePrefix = "github.com/onflow/flow-go/" ciMatrixName = "dynamicMatrix" - defaultCIRunner = "ubuntu-latest" + defaultCIRunner = "blacksmith-4vcpu-ubuntu-2404" ) // flowGoPackage configuration for a package to be tested. diff --git a/tools/test_matrix_generator/matrix_test.go b/tools/test_matrix_generator/matrix_test.go index a155b541f62..ea19d65bb8e 100644 --- a/tools/test_matrix_generator/matrix_test.go +++ b/tools/test_matrix_generator/matrix_test.go @@ -42,7 +42,7 @@ func TestBuildMatrices(t *testing.T) { }) t.Run("top level package only override runner", func(t *testing.T) { name := "counter" - runner := "buildjet-4vcpu-ubuntu-2204" + runner := "blacksmith-4vcpu-ubuntu-2404" configFile := fmt.Sprintf(`{"packagesPath": ".", "packages": [{"name": "%s", "runner": "%s"}]}`, name, runner) allPackges := goPackageFixture("counter/count", "counter/print/int", "counter/log") cfg := loadPackagesConfig(configFile) @@ -59,7 +59,7 @@ func TestBuildMatrices(t *testing.T) { subPkg2 := "module/chunks" subPkg3 := "crypto/hash" subPkg4 := "model/bootstrap" - subPkg1Runner := "buildjet-4vcpu-ubuntu-2204" + subPkg1Runner := "blacksmith-4vcpu-ubuntu-2404" configFile := fmt.Sprintf(` {"packagesPath": ".", "includeOthers": true, "packages": [{"name": "%s", "subpackages": [{"name": "%s", "runner": "%s"}, {"name": "%s"}, {"name": "%s"}, {"name": "%s"}]}]}`, topLevelPkgName, subPkg1, subPkg1Runner, subPkg2, subPkg3, subPkg4) @@ -112,7 +112,7 @@ func TestBuildMatrices(t *testing.T) { t.Run("top level package with sub packages and exclude", func(t *testing.T) { topLevelPkgName := "network" subPkg1 := "network/p2p/node" - subPkg1Runner := "buildjet-4vcpu-ubuntu-2204" + subPkg1Runner := "blacksmith-4vcpu-ubuntu-2404" configFile := fmt.Sprintf(` {"packagesPath": ".", "packages": [{"name": "%s", "exclude": ["network/alsp"], "subpackages": [{"name": "%s", "runner": "%s"}]}]}`, topLevelPkgName, subPkg1, subPkg1Runner) diff --git a/utils/concurrentqueue/concurrentqueue.go b/utils/concurrentqueue/concurrentqueue.go index a5fde3a2bf1..09e30881423 100644 --- a/utils/concurrentqueue/concurrentqueue.go +++ b/utils/concurrentqueue/concurrentqueue.go @@ -19,21 +19,21 @@ func (s *ConcurrentQueue) Len() int { return s.q.Len() } -func (s *ConcurrentQueue) Push(v interface{}) { +func (s *ConcurrentQueue) Push(v any) { s.m.Lock() defer s.m.Unlock() s.q.PushBack(v) } -func (s *ConcurrentQueue) Pop() (interface{}, bool) { +func (s *ConcurrentQueue) Pop() (any, bool) { s.m.Lock() defer s.m.Unlock() return s.q.PopFront() } -func (s *ConcurrentQueue) PopBatch(batchSize int) ([]interface{}, bool) { +func (s *ConcurrentQueue) PopBatch(batchSize int) ([]any, bool) { s.m.Lock() defer s.m.Unlock() @@ -46,7 +46,7 @@ func (s *ConcurrentQueue) PopBatch(batchSize int) ([]interface{}, bool) { count = batchSize } - result := make([]interface{}, count) + result := make([]any, count) for i := 0; i < count; i++ { v, _ := s.q.PopFront() result[i] = v @@ -55,7 +55,7 @@ func (s *ConcurrentQueue) PopBatch(batchSize int) ([]interface{}, bool) { return result, true } -func (s *ConcurrentQueue) Front() (interface{}, bool) { +func (s *ConcurrentQueue) Front() (any, bool) { s.m.Lock() defer s.m.Unlock() diff --git a/utils/concurrentqueue/concurrentqueue_test.go b/utils/concurrentqueue/concurrentqueue_test.go index eac4c92e8fd..c086c8dfcc6 100644 --- a/utils/concurrentqueue/concurrentqueue_test.go +++ b/utils/concurrentqueue/concurrentqueue_test.go @@ -19,7 +19,7 @@ func TestSafeQueue(t *testing.T) { samples := 100 wg := sync.WaitGroup{} wg.Add(workers) - for i := 0; i < workers; i++ { + for i := range workers { go func(worker int) { for i := 1; i <= samples; i++ { q.Push(testEntry{ diff --git a/utils/debug/registerCache.go b/utils/debug/registerCache.go index dca04243db1..e843b393b05 100644 --- a/utils/debug/registerCache.go +++ b/utils/debug/registerCache.go @@ -56,6 +56,12 @@ func NewFileRegisterCache(filePath string) (*FileRegisterCache, error) { f, err := os.Open(filePath) if err != nil { + if os.IsNotExist(err) { + return &FileRegisterCache{ + filePath: filePath, + data: data, + }, nil + } return nil, err } defer f.Close() @@ -77,17 +83,12 @@ func NewFileRegisterCache(filePath string) (*FileRegisterCache, error) { return nil, err } - owner, err := hex.DecodeString(d.Key.Owner) - if err != nil { - return nil, err - } - keyCopy, err := hex.DecodeString(d.Key.Key) if err != nil { return nil, err } - data[newRegisterKey(string(owner), string(keyCopy))] = d + data[newRegisterKey(d.Key.Owner, string(keyCopy))] = d } } diff --git a/utils/debug/registerCache_test.go b/utils/debug/registerCache_test.go new file mode 100644 index 00000000000..2d400d6f527 --- /dev/null +++ b/utils/debug/registerCache_test.go @@ -0,0 +1,155 @@ +package debug + +import ( + "encoding/hex" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/model/flow" +) + +// testOwner returns the raw binary owner string for a given hex address string, +// matching the encoding used by AddressToRegisterOwner. +func testOwner(hexAddr string) string { + return string(flow.HexToAddress(hexAddr).Bytes()) +} + +func TestFileRegisterCache_NewEmptyCache(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + cache, err := NewFileRegisterCache(filepath.Join(dir, "cache.dat")) + require.NoError(t, err) + require.NotNil(t, cache) +} + +func TestFileRegisterCache_SetGet(t *testing.T) { + t.Parallel() + + owner := testOwner("0000000000000001") + key := "someKey" + value := []byte("someValue") + + dir := t.TempDir() + cache, err := NewFileRegisterCache(filepath.Join(dir, "cache.dat")) + require.NoError(t, err) + + _, found := cache.Get(owner, key) + assert.False(t, found) + + cache.Set(owner, key, value) + + got, found := cache.Get(owner, key) + require.True(t, found) + assert.Equal(t, value, got) +} + +func TestFileRegisterCache_SetDoesNotAliasValue(t *testing.T) { + t.Parallel() + + owner := testOwner("0000000000000001") + key := "k" + value := []byte("original") + + dir := t.TempDir() + cache, err := NewFileRegisterCache(filepath.Join(dir, "cache.dat")) + require.NoError(t, err) + + cache.Set(owner, key, value) + value[0] = 'X' // mutate original slice + + got, found := cache.Get(owner, key) + require.True(t, found) + assert.Equal(t, byte('o'), got[0], "Set should store a copy of value") +} + +func TestFileRegisterCache_PersistAndReload(t *testing.T) { + t.Parallel() + + owner := testOwner("0000000000000001") + key := "someKey" + value := []byte("someValue") + + dir := t.TempDir() + filePath := filepath.Join(dir, "cache.dat") + + cache, err := NewFileRegisterCache(filePath) + require.NoError(t, err) + cache.Set(owner, key, value) + require.NoError(t, cache.Persist()) + + loaded, err := NewFileRegisterCache(filePath) + require.NoError(t, err) + + got, found := loaded.Get(owner, key) + require.True(t, found) + assert.Equal(t, value, got) +} + +func TestFileRegisterCache_ParsedEntryKey(t *testing.T) { + t.Parallel() + + owner := testOwner("0000000000000001") + key := "someKey" + value := []byte("someValue") + + dir := t.TempDir() + filePath := filepath.Join(dir, "cache.dat") + + cache, err := NewFileRegisterCache(filePath) + require.NoError(t, err) + cache.Set(owner, key, value) + require.NoError(t, cache.Persist()) + + loaded, err := NewFileRegisterCache(filePath) + require.NoError(t, err) + + entry, found := loaded.data[newRegisterKey(owner, key)] + require.True(t, found) + + // Owner is stored as raw binary (AddressToRegisterOwner encoding). + assert.Equal(t, owner, entry.Key.Owner) + + // Key is stored as hex-encoded bytes; decode it to recover the original key. + decoded, err := hex.DecodeString(entry.Key.Key) + require.NoError(t, err) + assert.Equal(t, key, string(decoded)) +} + +func TestFileRegisterCache_MultipleEntries(t *testing.T) { + t.Parallel() + + owner1 := testOwner("0000000000000001") + owner2 := testOwner("0000000000000002") + + dir := t.TempDir() + filePath := filepath.Join(dir, "cache.dat") + + cache, err := NewFileRegisterCache(filePath) + require.NoError(t, err) + cache.Set(owner1, "k1", []byte("v1")) + cache.Set(owner1, "k2", []byte("v2")) + cache.Set(owner2, "k1", []byte("v3")) + require.NoError(t, cache.Persist()) + + loaded, err := NewFileRegisterCache(filePath) + require.NoError(t, err) + + v, found := loaded.Get(owner1, "k1") + require.True(t, found) + assert.Equal(t, []byte("v1"), v) + + v, found = loaded.Get(owner1, "k2") + require.True(t, found) + assert.Equal(t, []byte("v2"), v) + + v, found = loaded.Get(owner2, "k1") + require.True(t, found) + assert.Equal(t, []byte("v3"), v) + + _, found = loaded.Get(owner2, "k2") + assert.False(t, found) +} diff --git a/utils/debug/remoteDebugger.go b/utils/debug/remoteDebugger.go index 0b9cd25d5d2..c023176c59d 100644 --- a/utils/debug/remoteDebugger.go +++ b/utils/debug/remoteDebugger.go @@ -33,17 +33,13 @@ func NewRemoteDebugger( // no signature processor here // TODO Maybe we add fee-deduction step as well - ctx := fvm.NewContext( - append( - []fvm.Option{ - fvm.WithLogger(logger), - fvm.WithChain(chain), - fvm.WithAuthorizationChecksEnabled(false), - fvm.WithEVMEnabled(true), - }, - options..., - )..., - ) + ctx := fvm.NewContext(chain, append( + []fvm.Option{ + fvm.WithLogger(logger), + fvm.WithAuthorizationChecksEnabled(false), + }, + options..., + )...) return &RemoteDebugger{ ctx: ctx, @@ -54,15 +50,30 @@ func NewRemoteDebugger( // RunTransaction runs the transaction using the given storage snapshot. func (d *RemoteDebugger) RunTransaction( txBody *flow.TransactionBody, + isSystemTransaction bool, snapshot StorageSnapshot, blockHeader *flow.Header, ) ( Result, error, ) { + opts := []fvm.Option{ + fvm.WithBlockHeader(blockHeader), + } + + if isSystemTransaction { + opts = append( + opts, + fvm.WithAuthorizationChecksEnabled(false), + fvm.WithSequenceNumberCheckAndIncrementEnabled(false), + fvm.WithRandomSourceHistoryCallAllowed(true), + fvm.WithAccountStorageLimit(false), + ) + } + blockCtx := fvm.NewContextFromParent( d.ctx, - fvm.WithBlockHeader(blockHeader), + opts..., ) tx := fvm.Transaction(txBody, 0) @@ -112,11 +123,16 @@ func (d *RemoteDebugger) RunSDKTransaction( return d.RunTransaction( txBody, + isSystemTransaction(tx), snapshot, header, ) } +func isSystemTransaction(tx *sdk.Transaction) bool { + return tx.Payer == sdk.EmptyAddress +} + // RunScript runs the script using the given storage snapshot. func (d *RemoteDebugger) RunScript( code []byte, diff --git a/utils/dsl/dsl.go b/utils/dsl/dsl.go index 928d0e7ad9c..48bd3e7855e 100644 --- a/utils/dsl/dsl.go +++ b/utils/dsl/dsl.go @@ -66,10 +66,10 @@ type Import struct { func (i Import) ToCadence() string { if i.Address != sdk.EmptyAddress { - if len(i.Names) > 0 { - return fmt.Sprintf("import %s from 0x%s\n", strings.Join(i.Names, ", "), i.Address) + if len(i.Names) == 0 { + panic("Import must have at least one name") } - return fmt.Sprintf("import 0x%s\n", i.Address) + return fmt.Sprintf("import %s from 0x%s\n", strings.Join(i.Names, ", "), i.Address) } return "" } diff --git a/utils/helpers.go b/utils/helpers.go new file mode 100644 index 00000000000..9538a227411 --- /dev/null +++ b/utils/helpers.go @@ -0,0 +1,28 @@ +package utils + +import "reflect" + +// IsNil checks if the input is nil, and works for any type including interfaces. +// This method uses reflection. Avoid use in performance-critical code. +func IsNil(v any) bool { + if v == nil { + return true + } + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return rv.IsNil() + default: + return false + } +} + +// NotNil verifies that the input is not nil and returns it. It panics if the input is nil. +// This is useful when checking dependencies are initialized during bootstrap. +// This method uses reflection. Avoid use in performance-critical code. +func NotNil[T any](v T) T { + if IsNil(v) { + panic("value is nil") + } + return v +} diff --git a/utils/io/filelock.go b/utils/io/filelock.go new file mode 100644 index 00000000000..290b58c2915 --- /dev/null +++ b/utils/io/filelock.go @@ -0,0 +1,84 @@ +package io + +import ( + "errors" + "fmt" + "os" + "path/filepath" + + "github.com/gofrs/flock" +) + +// FileLock represents an exclusive file lock that prevents multiple processes +// from accessing the same resource. If another process tries to acquire the lock, +// it will fail and should crash. +type FileLock struct { + lockFile *flock.Flock +} + +// NewFileLock creates a new file lock at the specified path. +// The lock file will be created in the same directory as the path. +// If path is a directory, the lock file will be created inside it. +// If the directory doesn't exist yet, it assumes the path is intended to be a directory. +func NewFileLock(path string) (*FileLock, error) { + // Determine the lock file path + // Always create the lock file in the specified path (treating it as a directory) + // This ensures the lock is always in the WAL directory itself + lockPath := filepath.Join(path, ".lock") + + // Ensure the directory exists before trying to create the lock file + dir := filepath.Dir(lockPath) + if err := os.MkdirAll(dir, 0755); err != nil { + if os.IsPermission(err) { + return nil, fmt.Errorf("failed to create directory for lock file %s (permission denied): %w", lockPath, err) + } + return nil, fmt.Errorf("failed to create directory for lock file %s: %w", lockPath, err) + } + + return &FileLock{ + lockFile: flock.New(lockPath), + }, nil +} + +// Lock acquires an exclusive lock on the file. This will block until the lock +// can be acquired. If the lock cannot be acquired (e.g., another process holds it), +// it returns an error. The process should crash in this case. +func (fl *FileLock) Lock() error { + locked, err := fl.lockFile.TryLock() + if err != nil { + // Check if the error is due to permission denied + var pathErr *os.PathError + if errors.Is(err, os.ErrPermission) || (errors.As(err, &pathErr) && os.IsPermission(pathErr.Err)) { + return fmt.Errorf("failed to acquire file lock at %s (permission denied): %w", fl.lockFile.Path(), err) + } + return fmt.Errorf("failed to acquire file lock at %s: %w", fl.lockFile.Path(), err) + } + if !locked { + // Lock file exists and is held by another process + return fmt.Errorf("cannot acquire exclusive lock at %s: another process is already using this directory", fl.lockFile.Path()) + } + return nil +} + +// Unlock releases the file lock. +func (fl *FileLock) Unlock() error { + if err := fl.lockFile.Unlock(); err != nil { + return fmt.Errorf("failed to release file lock at %s: %w", fl.lockFile.Path(), err) + } + return nil +} + +// Close releases the file lock. Implements io.Closer. +func (fl *FileLock) Close() error { + return fl.lockFile.Close() +} + +// Path returns the path to the lock file. +func (fl *FileLock) Path() string { + return fl.lockFile.Path() +} + +// IsLocked returns true if this FileLock instance currently holds the lock. +func (fl *FileLock) IsLocked() bool { + return fl.lockFile.Locked() +} diff --git a/utils/io/filelock_test.go b/utils/io/filelock_test.go new file mode 100644 index 00000000000..0312be47d6d --- /dev/null +++ b/utils/io/filelock_test.go @@ -0,0 +1,499 @@ +package io + +import ( + "os" + "path/filepath" + "sync" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/onflow/flow-go/utils/unittest" +) + +// RemoveLockFile removes the lock file if it exists. +// This is only used in tests. +func RemoveLockFile(lockDir string) error { + lockPath := filepath.Join(lockDir, ".lock") + if !FileExists(lockPath) { + return nil + } + return os.Remove(lockPath) +} + +func TestFileLock(t *testing.T) { + t.Run("basic lock and unlock", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock, err := NewFileLock(dir) + require.NoError(t, err) + require.NotNil(t, lock) + + // Verify lock path + expectedPath := filepath.Join(dir, ".lock") + require.Equal(t, expectedPath, lock.Path()) + + // Acquire lock + err = lock.Lock() + require.NoError(t, err) + + // Release lock + err = lock.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("lock prevents concurrent access", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock1, err := NewFileLock(dir) + require.NoError(t, err) + lock2, err := NewFileLock(dir) + require.NoError(t, err) + + // First lock should succeed + err = lock1.Lock() + require.NoError(t, err) + + // Second lock should fail + err = lock2.Lock() + require.Error(t, err) + require.Contains(t, err.Error(), "another process is already using this directory") + + // Release first lock + err = lock1.Unlock() + require.NoError(t, err) + + // Now second lock should succeed + err = lock2.Lock() + require.NoError(t, err) + + err = lock2.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("lock can be re-acquired after unlock", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock, err := NewFileLock(dir) + require.NoError(t, err) + + // Acquire and release multiple times + for i := 0; i < 3; i++ { + err := lock.Lock() + require.NoError(t, err, "iteration %d", i) + + err = lock.Unlock() + require.NoError(t, err, "iteration %d", i) + } + }) + }) + + t.Run("concurrent goroutines competing for lock", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + const numGoroutines = 10 + var wg sync.WaitGroup + successCount := 0 + failureCount := 0 + var mu sync.Mutex + var lockHeld sync.WaitGroup + + // First, acquire the lock to hold it + mainLock, err := NewFileLock(dir) + require.NoError(t, err) + err = mainLock.Lock() + require.NoError(t, err) + + // Start multiple goroutines trying to acquire the same lock + for i := 0; i < numGoroutines; i++ { + wg.Add(1) + lockHeld.Add(1) + go func() { + defer wg.Done() + lock, err := NewFileLock(dir) + if err != nil { + mu.Lock() + failureCount++ + mu.Unlock() + lockHeld.Done() + return + } + err = lock.Lock() + mu.Lock() + if err != nil { + failureCount++ + } else { + successCount++ + } + mu.Unlock() + lockHeld.Done() + if err == nil { + _ = lock.Unlock() + } + }() + } + + // Wait a bit to ensure all goroutines have tried to acquire the lock + lockHeld.Wait() + + // Release the main lock + err = mainLock.Unlock() + require.NoError(t, err) + + // Wait for all goroutines to finish + wg.Wait() + + // All should have failed since the main lock was held + require.Equal(t, 0, successCount, "no goroutine should acquire the lock while main lock is held") + require.Equal(t, numGoroutines, failureCount, "all goroutines should fail to acquire the lock") + }) + }) + + t.Run("lock file is created in correct location", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock, err := NewFileLock(dir) + require.NoError(t, err) + lockPath := lock.Path() + + // Lock file should not exist before locking + require.False(t, FileExists(lockPath)) + + // Acquire lock + err = lock.Lock() + require.NoError(t, err) + + // Lock file should exist after locking + require.True(t, FileExists(lockPath)) + + // Verify it's in the expected location + expectedPath := filepath.Join(dir, ".lock") + require.Equal(t, expectedPath, lockPath) + + err = lock.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("multiple locks on different directories", func(t *testing.T) { + unittest.RunWithTempDirs(t, func(dir1, dir2 string) { + lock1, err := NewFileLock(dir1) + require.NoError(t, err) + lock2, err := NewFileLock(dir2) + require.NoError(t, err) + + // Both locks should succeed since they're on different directories + err = lock1.Lock() + require.NoError(t, err) + + err = lock2.Lock() + require.NoError(t, err) + + // Both should be able to unlock + err = lock1.Unlock() + require.NoError(t, err) + + err = lock2.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("lock works with non-existent directory", func(t *testing.T) { + unittest.RunWithTempDir(t, func(baseDir string) { + nonExistentDir := filepath.Join(baseDir, "non-existent", "subdir") + lock, err := NewFileLock(nonExistentDir) + require.NoError(t, err) + + // Lock should still work (the directory was created in NewFileLock) + err = lock.Lock() + require.NoError(t, err) + + // Verify lock file path is correct + expectedPath := filepath.Join(nonExistentDir, ".lock") + require.Equal(t, expectedPath, lock.Path()) + + err = lock.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("unlock without lock is safe", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock, err := NewFileLock(dir) + require.NoError(t, err) + + // Unlocking without locking should not panic + // (though it may return an error) + err = lock.Unlock() + // The error is acceptable - we just want to ensure it doesn't panic + _ = err + }) + }) + + t.Run("double unlock is safe", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock, err := NewFileLock(dir) + require.NoError(t, err) + + err = lock.Lock() + require.NoError(t, err) + + err = lock.Unlock() + require.NoError(t, err) + + // Unlocking again should be safe (may return error but shouldn't panic) + err = lock.Unlock() + _ = err // Error is acceptable + }) + }) + + t.Run("lock is released when process terminates", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + // Acquire lock in first "process" (goroutine) + lock1, err := NewFileLock(dir) + require.NoError(t, err) + err = lock1.Lock() + require.NoError(t, err) + + // Simulate process termination by unlocking + err = lock1.Unlock() + require.NoError(t, err) + + // Now a new "process" should be able to acquire the lock + lock2, err := NewFileLock(dir) + require.NoError(t, err) + err = lock2.Lock() + require.NoError(t, err) + + err = lock2.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("lock file persists after unlock", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock, err := NewFileLock(dir) + require.NoError(t, err) + lockPath := lock.Path() + + err = lock.Lock() + require.NoError(t, err) + + // Lock file should exist + require.True(t, FileExists(lockPath)) + + err = lock.Unlock() + require.NoError(t, err) + + // Lock file may or may not exist after unlock (implementation detail) + // But the important thing is that we can acquire a new lock + lock2, err := NewFileLock(dir) + require.NoError(t, err) + err = lock2.Lock() + require.NoError(t, err) + + err = lock2.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("error message contains lock path", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock1, err := NewFileLock(dir) + require.NoError(t, err) + lock2, err := NewFileLock(dir) + require.NoError(t, err) + + err = lock1.Lock() + require.NoError(t, err) + + err = lock2.Lock() + require.Error(t, err) + require.Contains(t, err.Error(), lock2.Path()) + require.Contains(t, err.Error(), "another process is already using this directory") + + err = lock1.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("lock works with absolute paths", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + absDir, err := filepath.Abs(dir) + require.NoError(t, err) + + lock, err := NewFileLock(absDir) + require.NoError(t, err) + err = lock.Lock() + require.NoError(t, err) + + // Verify lock path is also absolute + lockPath := lock.Path() + require.True(t, filepath.IsAbs(lockPath)) + + err = lock.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("lock works with relative paths", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + // Change to the temp directory + originalDir, err := os.Getwd() + require.NoError(t, err) + defer func() { + _ = os.Chdir(originalDir) + }() + + err = os.Chdir(dir) + require.NoError(t, err) + + // Use relative path + lock, err := NewFileLock(".") + require.NoError(t, err) + err = lock.Lock() + require.NoError(t, err) + + err = lock.Unlock() + require.NoError(t, err) + }) + }) + + t.Run("IsLocked detects lock state", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock1, err := NewFileLock(dir) + require.NoError(t, err) + lock2, err := NewFileLock(dir) + require.NoError(t, err) + + // Initially, lock should not be locked + require.False(t, lock1.IsLocked(), "lock should not be locked initially") + + // Acquire lock + err = lock1.Lock() + require.NoError(t, err) + + // Now lock1 should know it's locked + require.True(t, lock1.IsLocked(), "lock1 should know it holds the lock") + + // Release lock + err = lock1.Unlock() + require.NoError(t, err) + + // Now lock should not be locked + require.False(t, lock1.IsLocked(), "lock should not be locked after unlock") + _ = lock2 // lock2 unused after IsLocked behavior changed + }) + }) + + t.Run("RemoveLockFile removes lock file", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lockPath := filepath.Join(dir, ".lock") + + // Lock file shouldn't exist initially + require.False(t, FileExists(lockPath)) + + // Remove non-existent lock file should succeed + err := RemoveLockFile(dir) + require.NoError(t, err) + + // Acquire lock + lock, err := NewFileLock(dir) + require.NoError(t, err) + err = lock.Lock() + require.NoError(t, err) + + // Lock file should exist + require.True(t, FileExists(lockPath)) + + // Can't remove lock file while lock is held + // (this is expected - the file is locked) + // But we can unlock first + err = lock.Unlock() + require.NoError(t, err) + + // Now we can remove the lock file + err = RemoveLockFile(dir) + require.NoError(t, err) + require.False(t, FileExists(lockPath), "lock file should be removed") + }) + }) + + t.Run("NewFileLock error for permission denied on directory creation", func(t *testing.T) { + // This test may not work on all systems, especially Windows + // Skip if we can't create a read-only parent directory + unittest.RunWithTempDir(t, func(baseDir string) { + // Create a subdirectory that we'll make read-only + restrictedDir := filepath.Join(baseDir, "restricted") + err := os.MkdirAll(restrictedDir, 0755) + require.NoError(t, err) + + // Create a subdirectory inside that we'll try to lock + // But first make the parent read-only so we can't create subdirectories + lockTargetDir := filepath.Join(restrictedDir, "wal") + + // Make the restricted directory read-only (remove write permission) + err = os.Chmod(restrictedDir, 0555) + require.NoError(t, err) + defer func() { + // Restore permissions for cleanup + _ = os.Chmod(restrictedDir, 0755) + }() + + _, err = NewFileLock(lockTargetDir) + require.Error(t, err) + + // Verify the error message contains permission denied + require.Contains(t, err.Error(), "permission denied") + require.Contains(t, err.Error(), lockTargetDir) + }) + }) + + t.Run("lock error for permission denied on lock file creation", func(t *testing.T) { + // This test may not work on all systems, especially Windows + unittest.RunWithTempDir(t, func(baseDir string) { + // Create the WAL directory + walDir := filepath.Join(baseDir, "wal") + err := os.MkdirAll(walDir, 0755) + require.NoError(t, err) + + // Create the lock first while we have write permission + lock, err := NewFileLock(walDir) + require.NoError(t, err) + + // Make the directory read-only so we can't create the lock file + err = os.Chmod(walDir, 0555) + require.NoError(t, err) + defer func() { + // Restore permissions for cleanup + _ = os.Chmod(walDir, 0755) + }() + + err = lock.Lock() + require.Error(t, err) + + // Verify the error message contains permission denied + require.Contains(t, err.Error(), "permission denied") + require.Contains(t, err.Error(), walDir) + }) + }) + + t.Run("lock error message distinguishes permission denied from lock conflict", func(t *testing.T) { + unittest.RunWithTempDir(t, func(dir string) { + lock1, err := NewFileLock(dir) + require.NoError(t, err) + lock2, err := NewFileLock(dir) + require.NoError(t, err) + + // Acquire first lock + err = lock1.Lock() + require.NoError(t, err) + + // Try to acquire second lock - should get lock conflict, not permission denied + err = lock2.Lock() + require.Error(t, err) + require.Contains(t, err.Error(), "another process is already using this directory") + require.NotContains(t, err.Error(), "permission denied") + + err = lock1.Unlock() + require.NoError(t, err) + }) + }) +} diff --git a/utils/logging/identifier.go b/utils/logging/identifier.go index 4df1ca9af3e..864d8a2923c 100644 --- a/utils/logging/identifier.go +++ b/utils/logging/identifier.go @@ -16,7 +16,7 @@ func ID(id flow.Identifier) []byte { return id[:] } -func Type(obj interface{}) string { +func Type(obj any) string { return fmt.Sprintf("%T", obj) } diff --git a/utils/logging/json.go b/utils/logging/json.go index 3c9e50908a7..1ba2318d47a 100644 --- a/utils/logging/json.go +++ b/utils/logging/json.go @@ -5,7 +5,7 @@ import ( "fmt" ) -func AsJSON(v interface{}) []byte { +func AsJSON(v any) []byte { data, err := json.Marshal(v) if err != nil { panic(fmt.Sprintf("could not encode as JSON: %s", err)) diff --git a/utils/rand/rand.go b/utils/rand/rand.go index 929f944b391..1bb1e50e000 100644 --- a/utils/rand/rand.go +++ b/utils/rand/rand.go @@ -161,7 +161,7 @@ func Samples(n uint, m uint, swap func(i, j uint)) error { if n < m { return fmt.Errorf("sample size (%d) cannot be larger than entire population (%d)", m, n) } - for i := uint(0); i < m; i++ { + for i := range m { j, err := Uintn(n - i) if err != nil { return err diff --git a/utils/rand/rand_test.go b/utils/rand/rand_test.go index 35fe273a2e1..c5940bea3ef 100644 --- a/utils/rand/rand_test.go +++ b/utils/rand/rand_test.go @@ -127,11 +127,11 @@ func TestShuffle(t *testing.T) { t.Run("shuffle a random permutation", func(t *testing.T) { // initialize the list - for i := 0; i < listSize; i++ { + for i := range listSize { list[i] = i } // shuffle and count multiple times - for k := 0; k < sampleSize; k++ { + for range sampleSize { shuffleAndCount(t) } // if the shuffle is uniform, the test element @@ -140,8 +140,8 @@ func TestShuffle(t *testing.T) { }) t.Run("shuffle a same permutation", func(t *testing.T) { - for k := 0; k < sampleSize; k++ { - for i := 0; i < listSize; i++ { + for range sampleSize { + for i := range listSize { list[i] = i } // suffle the same permutation @@ -175,11 +175,11 @@ func TestSamples(t *testing.T) { testElement := mrand.Intn(listSize) // Slice to shuffle list := make([]int, 0, listSize) - for i := 0; i < listSize; i++ { + for i := range listSize { list = append(list, i) } - for i := 0; i < sampleSize; i++ { + for range sampleSize { err := Samples(uint(listSize), uint(samplesSize), func(i, j uint) { list[i], list[j] = list[j], list[i] }) diff --git a/utils/slices/slices.go b/utils/slices/slices.go index a8ac7982467..42d96d5ac38 100644 --- a/utils/slices/slices.go +++ b/utils/slices/slices.go @@ -1,6 +1,7 @@ package slices import ( + "slices" "sort" "golang.org/x/exp/constraints" @@ -45,13 +46,15 @@ func MakeRange[T constraints.Integer](min, max T) []T { // Fill constructs a slice of type T with length n. The slice is then filled with input "val". func Fill[T any](val T, n int) []T { arr := make([]T, n) - for i := 0; i < n; i++ { + for i := range n { arr[i] = val } return arr } // AreStringSlicesEqual returns true if the two string slices are equal. +// +// CAUTION: this function performs inplace sorts of the input slices. func AreStringSlicesEqual(a, b []string) bool { if len(a) != len(b) { return false @@ -60,7 +63,7 @@ func AreStringSlicesEqual(a, b []string) bool { sort.Strings(a) sort.Strings(b) - for i := 0; i < len(a); i++ { + for i := range a { if a[i] != b[i] { return false } @@ -71,11 +74,15 @@ func AreStringSlicesEqual(a, b []string) bool { // StringSliceContainsElement returns true if the string slice contains the element. func StringSliceContainsElement(a []string, v string) bool { - for _, x := range a { - if x == v { - return true - } - } + return slices.Contains(a, v) +} - return false +// ToMap converts a slice of any comparable type into a map where each element +// in the slice becomes a key in the map with the value set to a struct{}. +func ToMap[T comparable](values []T) map[T]struct{} { + valueMap := make(map[T]struct{}, len(values)) + for _, v := range values { + valueMap[v] = struct{}{} + } + return valueMap } diff --git a/utils/unittest/execution_state.go b/utils/unittest/execution_state.go index 53e082cf163..d7f0607fb70 100644 --- a/utils/unittest/execution_state.go +++ b/utils/unittest/execution_state.go @@ -23,7 +23,7 @@ const ServiceAccountPrivateKeySignAlgo = crypto.ECDSAP256 const ServiceAccountPrivateKeyHashAlgo = hash.SHA2_256 // Pre-calculated state commitment with root account with the above private key -const GenesisStateCommitmentHex = "dad6fda8f9745ec0e1cf9d4d2429060a9460cef513f29272a6deb973820af6aa" +const GenesisStateCommitmentHex = "3ff353652eebe7d4eaea9eb9ad063e0f3c39c1b9b4e8c98ff50ffe40a9fc661a" var GenesisStateCommitment flow.StateCommitment @@ -87,10 +87,10 @@ func genesisCommitHexByChainID(chainID flow.ChainID) string { return GenesisStateCommitmentHex } if chainID == flow.Testnet { - return "d758711a98ebb0cb16023f8b14dfd18ab6b4292af6634f115f47b2065b839f4b" + return "362ff5ad8717c00053b025e40e7eacfd3eb02cae037befe9be68c724f3fe0d2a" } if chainID == flow.Sandboxnet { - return "e1c08b17f9e5896f03fe28dd37ca396c19b26628161506924fbf785834646ea1" + return "5d0bbfdfa9d17ea16062eb8ddd4cb20e4f99977d02fe58523d5b62f41a34b18a" } - return "a3af0430b178103671b02564a1cc3477ab25acf459523449640a2b6198bd83c8" + return "527cf46e35636148a3f88e399c1321cf56c7aecfd67e0f28df52fd21166ca814" } diff --git a/utils/unittest/fixtures.go b/utils/unittest/fixtures.go index d944d454fb6..fad9543eb5c 100644 --- a/utils/unittest/fixtures.go +++ b/utils/unittest/fixtures.go @@ -118,20 +118,27 @@ func InvalidFormatSignature() flow.TransactionSignature { } } -func TransactionSignatureFixture() flow.TransactionSignature { +func SignatureFixtureForTransactions() crypto.Signature { sigLen := crypto.SignatureLenECDSAP256 + sig := SeedFixture(sigLen) + + // make sure the ECDSA signature passes the format check + sig[sigLen/2] = 0 + sig[0] = 0 + sig[sigLen/2-1] |= 1 + sig[sigLen-1] |= 1 + return sig +} + +func TransactionSignatureFixture() flow.TransactionSignature { s := flow.TransactionSignature{ Address: AddressFixture(), SignerIndex: 0, - Signature: SeedFixture(sigLen), + Signature: SignatureFixtureForTransactions(), KeyIndex: 1, ExtensionData: []byte{}, } - // make sure the ECDSA signature passes the format check - s.Signature[sigLen/2] = 0 - s.Signature[0] = 0 - s.Signature[sigLen/2-1] |= 1 - s.Signature[sigLen-1] |= 1 + return s } @@ -1616,7 +1623,7 @@ func TransactionBodyFixture(opts ...func(*flow.TransactionBody)) flow.Transactio func TransactionBodyListFixture(n int) []flow.TransactionBody { l := make([]flow.TransactionBody, n) for i := 0; i < n; i++ { - l[i] = TransactionBodyFixture() + l[i] = TransactionFixture() } return l @@ -2642,7 +2649,7 @@ func MachineAccountFixture(t *testing.T) ( ) { info := NodeMachineAccountInfoFixture() - bal, err := cadence.NewUFix64("0.5") + bal, err := cadence.NewUFix64("5.0") require.NoError(t, err) acct := &sdk.Account{ diff --git a/utils/unittest/fixtures/transaction.go b/utils/unittest/fixtures/transaction.go index 6015f2c7424..5e1697f83c9 100644 --- a/utils/unittest/fixtures/transaction.go +++ b/utils/unittest/fixtures/transaction.go @@ -86,13 +86,17 @@ func NewTransactionGenerator( // Fixture generates a [flow.TransactionBody] with random data based on the provided options. func (g *TransactionGenerator) Fixture(opts ...TransactionOption) *flow.TransactionBody { + // simplify the transaction by using the same address for the proposer, payer and authorizers + proposalKey := g.proposalKeys.Fixture() + proposalAddress := proposalKey.Address + tx := &flow.TransactionBody{ ReferenceBlockID: g.identifiers.Fixture(), Script: []byte("access(all) fun main() {}"), GasLimit: 10, - ProposalKey: g.proposalKeys.Fixture(), - Payer: g.addresses.Fixture(), - Authorizers: []flow.Address{g.addresses.Fixture()}, + ProposalKey: proposalKey, + Payer: proposalAddress, + Authorizers: []flow.Address{proposalAddress}, } for _, opt := range opts { @@ -104,6 +108,9 @@ func (g *TransactionGenerator) Fixture(opts ...TransactionOption) *flow.Transact // allowing the transaction to be properly serialized and deserialized over protobuf. // if the signature does not match the proposer, the signer index resolved during // deserialization will be incorrect. + + // this would also pass the sanity checks on the transaction signatures + // by the access TransactionValidator tx.EnvelopeSignatures = []flow.TransactionSignature{ g.transactionSigs.Fixture( TransactionSignature.WithAddress(tx.ProposalKey.Address), diff --git a/utils/unittest/mocks/matchers.go b/utils/unittest/mocks/matchers.go index ba7b60602db..11b8dbf5e3c 100644 --- a/utils/unittest/mocks/matchers.go +++ b/utils/unittest/mocks/matchers.go @@ -17,6 +17,6 @@ import ( // return nil // }). // Once() -func MatchLock(lock string) interface{} { +func MatchLock(lock string) any { return mock.MatchedBy(func(lctx lockctx.Proof) bool { return lctx.HoldsLock(lock) }) } diff --git a/utils/unittest/network/conduit.go b/utils/unittest/network/conduit.go index e4a60acc155..46908bd228c 100644 --- a/utils/unittest/network/conduit.go +++ b/utils/unittest/network/conduit.go @@ -17,7 +17,7 @@ var _ network.Conduit = (*Conduit)(nil) // Publish sends a message on this mock network, invoking any callback that has // been specified. This will panic if no callback is found. -func (c *Conduit) Publish(event interface{}, targetIDs ...flow.Identifier) error { +func (c *Conduit) Publish(event any, targetIDs ...flow.Identifier) error { if c.net.publishFunc != nil { return c.net.publishFunc(c.channel, event, targetIDs...) } diff --git a/utils/unittest/network/fixtures.go b/utils/unittest/network/fixtures.go index 9990c1c1dbd..45dbffb3861 100644 --- a/utils/unittest/network/fixtures.go +++ b/utils/unittest/network/fixtures.go @@ -39,7 +39,7 @@ func TxtIPFixture() string { func IpLookupFixture(count int) map[string]*IpLookupTestCase { tt := make(map[string]*IpLookupTestCase) - for i := 0; i < count; i++ { + for i := range count { ipTestCase := &IpLookupTestCase{ Domain: fmt.Sprintf("example%d.com", i), Result: []net.IPAddr{ // resolves each domain to 4 addresses. @@ -60,7 +60,7 @@ func IpLookupFixture(count int) map[string]*IpLookupTestCase { func TxtLookupFixture(count int) map[string]*TxtLookupTestCase { tt := make(map[string]*TxtLookupTestCase) - for i := 0; i < count; i++ { + for i := range count { ttTestCase := &TxtLookupTestCase{ Txt: fmt.Sprintf("_dnsaddr.example%d.com", i), Records: []string{ // resolves each txt to 4 addresses. @@ -80,7 +80,7 @@ func TxtLookupFixture(count int) map[string]*TxtLookupTestCase { func IpLookupListFixture(count int) []*IpLookupTestCase { tt := make([]*IpLookupTestCase, 0) - for i := 0; i < count; i++ { + for i := range count { ipTestCase := &IpLookupTestCase{ Domain: fmt.Sprintf("example%d.com", i), Result: []net.IPAddr{ // resolves each domain to 4 addresses. @@ -101,7 +101,7 @@ func IpLookupListFixture(count int) []*IpLookupTestCase { func TxtLookupListFixture(count int) []*TxtLookupTestCase { tt := make([]*TxtLookupTestCase, 0) - for i := 0; i < count; i++ { + for i := range count { ttTestCase := &TxtLookupTestCase{ Txt: fmt.Sprintf("_dnsaddr.example%d.com", i), Records: []string{ // resolves each txt to 4 addresses. diff --git a/utils/unittest/network/network.go b/utils/unittest/network/network.go index 324d3c82050..8f0d2125d2b 100644 --- a/utils/unittest/network/network.go +++ b/utils/unittest/network/network.go @@ -11,8 +11,8 @@ import ( mocknetwork "github.com/onflow/flow-go/network/mock" ) -type EngineProcessFunc func(channels.Channel, flow.Identifier, interface{}) error -type PublishFunc func(channels.Channel, interface{}, ...flow.Identifier) error +type EngineProcessFunc func(channels.Channel, flow.Identifier, any) error +type PublishFunc func(channels.Channel, any, ...flow.Identifier) error // Conduit represents a mock conduit. @@ -52,7 +52,7 @@ func (n *Network) Register(channel channels.Channel, engine network.MessageProce // Send sends a message to the engine registered to the given channel on this mock network and returns // an error if one occurs. If no engine is registered, this is a noop. -func (n *Network) Send(channel channels.Channel, originID flow.Identifier, event interface{}) error { +func (n *Network) Send(channel channels.Channel, originID flow.Identifier, event any) error { if eng, ok := n.engines[channel]; ok { return eng.Process(channel, originID, event) } @@ -81,7 +81,7 @@ func NewEngine() *Engine { // OnProcess specifies the callback that should be executed when `Process` is called on this mock engine. func (e *Engine) OnProcess(processFunc EngineProcessFunc) *Engine { e.On("Process", mock.AnythingOfType("channels.Channel"), mock.AnythingOfType("flow.Identifier"), mock.Anything). - Return((func(channels.Channel, flow.Identifier, interface{}) error)(processFunc)) + Return((func(channels.Channel, flow.Identifier, any) error)(processFunc)) return e } diff --git a/utils/visited/visited.go b/utils/visited/visited.go new file mode 100644 index 00000000000..cdba777ea96 --- /dev/null +++ b/utils/visited/visited.go @@ -0,0 +1,44 @@ +package visited + +// Visited is a simple object that tracks whether or not a particular value has been visited. +// Use this when iterating over a collection and you need to know if a value has been encountered. +// +// CAUTION: Not concurrency safe. +type Visited[T comparable] struct { + m map[T]struct{} +} + +func New[T comparable]() Visited[T] { + return Visited[T]{ + m: make(map[T]struct{}), + } +} + +// Visit returns true if the value has been visited, false otherwise. +// It also adds the value to the set of visited values. +// +// CAUTION: Not concurrency safe. +func (s *Visited[T]) Visit(key T) bool { + if _, ok := s.m[key]; ok { + return true + } + s.m[key] = struct{}{} + return false +} + +// PeekVisited returns true if the value has been visited, false otherwise. +// It does not add the value to the set of visited values. +// Use this for use cases where marking the value as visited needs to happen after processing. +// +// CAUTION: Not concurrency safe. +func (s *Visited[T]) PeekVisited(key T) bool { + _, ok := s.m[key] + return ok +} + +// Count returns the number of visited values. +// +// CAUTION: Not concurrency safe. +func (s *Visited[T]) Count() int { + return len(s.m) +} diff --git a/utils/visited/visited_test.go b/utils/visited/visited_test.go new file mode 100644 index 00000000000..8f19d630187 --- /dev/null +++ b/utils/visited/visited_test.go @@ -0,0 +1,86 @@ +package visited + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestVisited_Visit verifies that Visit returns false on first encounter and true on repeat. +func TestVisited_Visit(t *testing.T) { + t.Run("first visit returns false", func(t *testing.T) { + v := New[int]() + assert.False(t, v.Visit(1)) + }) + + t.Run("second visit returns true", func(t *testing.T) { + v := New[int]() + v.Visit(1) + assert.True(t, v.Visit(1)) + }) + + t.Run("subsequent visits all return true", func(t *testing.T) { + v := New[int]() + v.Visit(1) + assert.True(t, v.Visit(1)) + assert.True(t, v.Visit(1)) + }) + + t.Run("distinct values tracked independently", func(t *testing.T) { + v := New[string]() + assert.False(t, v.Visit("a")) + assert.False(t, v.Visit("b")) + assert.True(t, v.Visit("a")) + assert.True(t, v.Visit("b")) + }) +} + +// TestVisited_Count verifies that Count reflects the number of unique visited values. +func TestVisited_Count(t *testing.T) { + t.Run("zero on empty", func(t *testing.T) { + v := New[int]() + assert.Equal(t, 0, v.Count()) + }) + + t.Run("increments on each new value", func(t *testing.T) { + v := New[int]() + v.Visit(1) + assert.Equal(t, 1, v.Count()) + v.Visit(2) + assert.Equal(t, 2, v.Count()) + }) + + t.Run("does not increment on repeat visit", func(t *testing.T) { + v := New[int]() + v.Visit(1) + v.Visit(1) + assert.Equal(t, 1, v.Count()) + }) + + t.Run("PeekVisited does not increment count", func(t *testing.T) { + v := New[int]() + v.PeekVisited(1) + assert.Equal(t, 0, v.Count()) + }) +} + +// TestVisited_PeekVisited verifies that PeekVisited reports membership without mutating the set. +func TestVisited_PeekVisited(t *testing.T) { + t.Run("returns false for unvisited key", func(t *testing.T) { + v := New[int]() + assert.False(t, v.PeekVisited(42)) + }) + + t.Run("returns true for visited key", func(t *testing.T) { + v := New[int]() + v.Visit(42) + assert.True(t, v.PeekVisited(42)) + }) + + t.Run("does not add key to visited set", func(t *testing.T) { + v := New[int]() + v.PeekVisited(42) + // Visit should still return false — PeekVisited must not have mutated the set. + assert.False(t, v.Visit(42)) + }) +}